Skip to content

Commit

Permalink
Bump min alluka ver to support alluka.local (#893)
Browse files Browse the repository at this point in the history
Co-authored-by: always-on-duty[bot] <120557446+always-on-duty[bot]@users.noreply.github.com>
  • Loading branch information
FasterSpeeding and always-on-duty[bot] authored Apr 29, 2024
1 parent 1112464 commit 71216fe
Show file tree
Hide file tree
Showing 21 changed files with 196 additions and 143 deletions.
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,22 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Changed
- Bumped the minimum Alluka ver to `v0.2.0`.
- Tanjun's client will now use the "local" Alluka client returned by
[alluka.local.get][] if no client is passed and a local Alluka client is set.
- [Client.get_type_dependency][tanjun.abc.Client.get_type_dependency] will now
raise a [KeyError][] if no dependency is found and no default is passed.
This is a change imposed by Alluka.

### Fixed
- Now compatible with Alluka `v0.2.0`.

### Removed
- `tanjun.injecting.UndefinedOr`, `tanjun.injecting.UNDEFINED`,
`tanjun.injecting.Undefined`, and `tanjun.injecting.UndefinedOr` as these
no-longer exist in Alluka.

## [2.17.3] - 2024-03-31
### Fixed
- Post execution command hooks will no-longer be triggered after a base
Expand Down
2 changes: 1 addition & 1 deletion dev-requirements/constraints.in
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
alluka>=0.1.2, <1
alluka>=0.2.0, <1
hikari>=2.0.0.dev115, <3
typing-extensions>=4.5, <5
6 changes: 3 additions & 3 deletions dev-requirements/constraints.txt
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ aiohttp==3.9.5 ; python_full_version >= "3.9.0" and python_version < "3.13" \
aiosignal==1.3.1 ; python_full_version >= "3.9.0" and python_version < "3.13" \
--hash=sha256:54cd96e15e1649b75d6c87526a6ff0b6c1b0dd3459f43d9ca11d48c339b68cfc \
--hash=sha256:f8376fb07dd1e86a584e4fcdec80b36b7f81aac666ebc724e2c090300dd83b17
alluka==0.1.5 ; python_full_version >= "3.9.0" and python_version < "3.13" \
--hash=sha256:0b71687c829330dfa34aefa417a917fa9423e4e37e486c82db5a86a3031097db \
--hash=sha256:f0d8fb0bf067e5dbc75b51070fd2ea7651369e10055d6bb9bfcd4cbc28a93af5
alluka==0.2.0 ; python_full_version >= "3.9.0" and python_version < "3.13" \
--hash=sha256:8d5e45fab2dfb4cbc705bbbb9090d9d7ed79836024ff719a0fe494d89a0b0da2 \
--hash=sha256:f9c85d91d8a4964e3dea8ba719c2548230d4a1a141ec25c5daf35b16f649018c
async-timeout==4.0.3 ; python_full_version >= "3.9.0" and python_version < "3.11" \
--hash=sha256:4640d96be84d82d02ed59ea2b7105a0f7b33abe8703703cd0ab0bf87c427522f \
--hash=sha256:7405140ff1230c310e51dc27b3145b9092d659ce68ff733fb0cefe3ee42be028
Expand Down
6 changes: 3 additions & 3 deletions dev-requirements/tests.txt
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ aiohttp==3.9.5 ; python_full_version >= "3.9.0" and python_version < "3.13" \
aiosignal==1.3.1 ; python_full_version >= "3.9.0" and python_version < "3.13" \
--hash=sha256:54cd96e15e1649b75d6c87526a6ff0b6c1b0dd3459f43d9ca11d48c339b68cfc \
--hash=sha256:f8376fb07dd1e86a584e4fcdec80b36b7f81aac666ebc724e2c090300dd83b17
alluka==0.1.5 ; python_full_version >= "3.9.0" and python_version < "3.13" \
--hash=sha256:0b71687c829330dfa34aefa417a917fa9423e4e37e486c82db5a86a3031097db \
--hash=sha256:f0d8fb0bf067e5dbc75b51070fd2ea7651369e10055d6bb9bfcd4cbc28a93af5
alluka==0.2.0 ; python_full_version >= "3.9.0" and python_version < "3.13" \
--hash=sha256:8d5e45fab2dfb4cbc705bbbb9090d9d7ed79836024ff719a0fe494d89a0b0da2 \
--hash=sha256:f9c85d91d8a4964e3dea8ba719c2548230d4a1a141ec25c5daf35b16f649018c
async-timeout==4.0.3 ; python_full_version >= "3.9.0" and python_version < "3.11" \
--hash=sha256:4640d96be84d82d02ed59ea2b7105a0f7b33abe8703703cd0ab0bf87c427522f \
--hash=sha256:7405140ff1230c310e51dc27b3145b9092d659ce68ff733fb0cefe3ee42be028
Expand Down
18 changes: 9 additions & 9 deletions dev-requirements/type-checking.txt
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ aiohttp==3.9.5 ; python_full_version >= "3.9.0" and python_version < "3.13" \
aiosignal==1.3.1 ; python_full_version >= "3.9.0" and python_version < "3.13" \
--hash=sha256:54cd96e15e1649b75d6c87526a6ff0b6c1b0dd3459f43d9ca11d48c339b68cfc \
--hash=sha256:f8376fb07dd1e86a584e4fcdec80b36b7f81aac666ebc724e2c090300dd83b17
alluka==0.1.5 ; python_full_version >= "3.9.0" and python_version < "3.13" \
--hash=sha256:0b71687c829330dfa34aefa417a917fa9423e4e37e486c82db5a86a3031097db \
--hash=sha256:f0d8fb0bf067e5dbc75b51070fd2ea7651369e10055d6bb9bfcd4cbc28a93af5
alluka==0.2.0 ; python_full_version >= "3.9.0" and python_version < "3.13" \
--hash=sha256:8d5e45fab2dfb4cbc705bbbb9090d9d7ed79836024ff719a0fe494d89a0b0da2 \
--hash=sha256:f9c85d91d8a4964e3dea8ba719c2548230d4a1a141ec25c5daf35b16f649018c
annotated-types==0.6.0 ; python_full_version >= "3.9.0" and python_version < "3.13" \
--hash=sha256:0641064de18ba7a25dee8f96403ebc39113d0cb953a01429249d5c7564666a43 \
--hash=sha256:563339e807e53ffd9c267e99fc6d9ea23eb8443c08f112651963e24e22f84a5d
Expand Down Expand Up @@ -167,9 +167,9 @@ exceptiongroup==1.2.1 ; python_full_version >= "3.9.0" and python_version < "3.1
execnet==2.1.1 ; python_full_version >= "3.9.0" and python_version < "3.13" \
--hash=sha256:26dee51f1b80cebd6d0ca8e74dd8745419761d3bef34163928cbebbdc4749fdc \
--hash=sha256:5189b52c6121c24feae288166ab41b32549c7e2348652736540b9e6e7d4e72e3
filelock==3.13.4 ; python_full_version >= "3.9.0" and python_version < "3.13" \
--hash=sha256:404e5e9253aa60ad457cae1be07c0f0ca90a63931200a47d9b6a6af84fd7b45f \
--hash=sha256:d13f466618bfde72bd2c18255e269f72542c6e70e7bac83a0232d6b1cc5c8cf4
filelock==3.14.0 ; python_full_version >= "3.9.0" and python_version < "3.13" \
--hash=sha256:43339835842f110ca7ae60f1e1c160714c5a6afd15a2873419ab185334975c0f \
--hash=sha256:6ea72da3be9b8c82afd3edcf99f2fffbb5076335a5ae4d03248bb5b6c3eae78a
freezegun==1.5.0 ; python_full_version >= "3.9.0" and python_version < "3.13" \
--hash=sha256:200a64359b363aa3653d8aac289584078386c7c3da77339d257e46a01fb5c77c \
--hash=sha256:ec3f4ba030e34eb6cf7e1e257308aee2c60c3d038ff35996d7475760c9ff3719
Expand Down Expand Up @@ -586,9 +586,9 @@ tomli==2.0.1 ; python_full_version >= "3.9.0" and python_version < "3.13" \
typing-extensions==4.11.0 ; python_full_version >= "3.9.0" and python_version < "3.13" \
--hash=sha256:83f085bd5ca59c80295fc2a82ab5dac679cbe02b9f33f7d83af68e241bea51b0 \
--hash=sha256:c1f94d72897edaf4ce775bb7558d5b79d8126906a14ea5ed1635921406c0387a
virtualenv==20.26.0 ; python_full_version >= "3.9.0" and python_version < "3.13" \
--hash=sha256:0846377ea76e818daaa3e00a4365c018bc3ac9760cbb3544de542885aad61fb3 \
--hash=sha256:ec25a9671a5102c8d2657f62792a27b48f016664c6873f6beed3800008577210
virtualenv==20.26.1 ; python_full_version >= "3.9.0" and python_version < "3.13" \
--hash=sha256:604bfdceaeece392802e6ae48e69cec49168b9c5f4a44e483963f9242eb0e78b \
--hash=sha256:7aa9982a728ae5892558bff6a2839c00b9ed145523ece2274fad6f414690ae75
yarl==1.9.4 ; python_full_version >= "3.9.0" and python_version < "3.13" \
--hash=sha256:008d3e808d03ef28542372d01057fd09168419cdc8f848efe2804f894ae03e51 \
--hash=sha256:03caa9507d3d3c83bca08650678e25364e1843b484f19986a527630ca376ecce \
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ classifiers = [
"Topic :: Utilities",
"Typing :: Typed",
]
dependencies = ["alluka>=0.1.2, <1", "hikari>=2.0.0.dev115, <3", "typing-extensions>=4.5, <5"]
dependencies = ["alluka>=0.2.0, <1", "hikari>=2.0.0.dev115, <3", "typing-extensions>=4.5, <5"]
dynamic = ["description"]

[project.urls]
Expand Down
2 changes: 1 addition & 1 deletion tanjun/_internal/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ async def get_perm_channel(client: tanjun.Client, channel_id: hikari.Snowflake,
if client.cache and (channel := client.cache.get_guild_channel(channel_id)):
return channel

thread_cache = client.injector.get_type_dependency(_ThreadCacheT)
thread_cache = client.injector.get_type_dependency(_ThreadCacheT, default=None)
if thread_cache: # noqa: SIM102
# Has to be nested cause of pyright bug:
if thread := await thread_cache.get(channel_id, default=None): # noqa: SIM102
Expand Down
26 changes: 23 additions & 3 deletions tanjun/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@
_MessageCommandT = typing.TypeVar("_MessageCommandT", bound="MessageCommand[typing.Any]")
_MetaEventSigT = typing.TypeVar("_MetaEventSigT", bound="MetaEventSig")

_DefaultT = typing.TypeVar("_DefaultT")

_T = typing.TypeVar("_T")
_AppCommandContextT = typing.TypeVar("_AppCommandContextT", bound="AppCommandContext")
_AutocompleteValueT = typing.TypeVar("_AutocompleteValueT", int, str, float)
Expand Down Expand Up @@ -4896,19 +4898,37 @@ def set_type_dependency(self, type_: type[_T], value: _T, /) -> Self:
The client instance to allow chaining.
"""

@typing.overload
@abc.abstractmethod
def get_type_dependency(self, type_: type[_T], /) -> _T: ...

@typing.overload
@abc.abstractmethod
def get_type_dependency(self, type_: type[_T], /, *, default: _DefaultT) -> typing.Union[_T, _DefaultT]: ...

@abc.abstractmethod
def get_type_dependency(self, type_: type[_T], /) -> typing.Union[_T, alluka.Undefined]:
def get_type_dependency(self, type_: type[_T], /, *, default: _DefaultT = ...) -> typing.Union[_T, _DefaultT]:
"""Get the implementation for an injected type.
Parameters
----------
type_
The associated type.
default
The default value to return if the type is not implemented.
Returns
-------
_T | alluka.abc.Undefined
The resolved type if found, else [alluka.abc.UNDEFINED][].
_T | _DefaultT
The resolved type if found.
If the type isn't implemented then the value of `default`
will be returned if it is provided.
Raises
------
KeyError
If no dependency was found when no default was provided.
"""

@abc.abstractmethod
Expand Down
45 changes: 28 additions & 17 deletions tanjun/clients.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
_PrefixGetterSigT = typing.TypeVar("_PrefixGetterSigT", bound="PrefixGetterSig")
_T = typing.TypeVar("_T")
_P = typing_extensions.ParamSpec("_P")
_DefaultT = typing.TypeVar("_DefaultT")

class _AutocompleteContextMakerProto(typing.Protocol):
def __call__(
Expand Down Expand Up @@ -680,7 +681,8 @@ def __init__(
injector
The alluka client this should use for dependency injection.
If not provided then the client will initialise its own DI client.
If not provided then either the "local" Alluka client will be used or
the client will initialise its own DI client.
mention_prefix
Whether or not mention prefixes should be automatically set when this
client is first started.
Expand Down Expand Up @@ -760,11 +762,7 @@ def __init__(
self._injector = injector or alluka.Client()
self._is_closing = False
self._listeners: dict[
type[hikari.Event],
dict[
tanjun.ListenerCallbackSig[typing.Any],
alluka.abc.AsyncSelfInjecting[tanjun.ListenerCallbackSig[typing.Any]],
],
type[hikari.Event], dict[tanjun.ListenerCallbackSig[typing.Any], tanjun.ListenerCallbackSig[typing.Any]]
] = {}
self._loop: typing.Optional[asyncio.AbstractEventLoop] = None
self._make_autocomplete_context: _AutocompleteContextMakerProto = context.AutocompleteContext
Expand Down Expand Up @@ -1225,7 +1223,7 @@ def listeners(
self,
) -> collections.Mapping[type[hikari.Event], collections.Collection[tanjun.ListenerCallbackSig[typing.Any]]]:
# <<inherited docstring from tanjun.abc.Client>>.
return _internal.CastedView(self._listeners, lambda x: [callback.callback for callback in x.values()])
return _internal.CastedView(self._listeners, lambda x: list(x.values()))

@property
def is_alive(self) -> bool:
Expand Down Expand Up @@ -2078,7 +2076,7 @@ def decorator(callback: _MetaEventSigT, /) -> _MetaEventSigT:
def add_listener(self, event_type: type[_EventT], /, *callbacks: tanjun.ListenerCallbackSig[_EventT]) -> Self:
# <<inherited docstring from tanjun.abc.Client>>.
for callback in callbacks:
injected = self.injector.as_async_self_injecting(callback)
injected = self.injector.auto_inject_async(callback)
try:
if callback in self._listeners[event_type]:
continue
Expand All @@ -2090,7 +2088,7 @@ def add_listener(self, event_type: type[_EventT], /, *callbacks: tanjun.Listener
self._listeners[event_type][callback] = injected

if self._loop and self._events:
self._events.subscribe(event_type, injected.__call__)
self._events.subscribe(event_type, injected)

return self

Expand All @@ -2107,7 +2105,7 @@ def remove_listener(self, event_type: type[_EventT], callback: tanjun.ListenerCa
del self._listeners[event_type]

if self._loop and self._events:
self._events.unsubscribe(event_type, registered_callback.__call__)
self._events.unsubscribe(event_type, registered_callback)

return self

Expand Down Expand Up @@ -2330,7 +2328,7 @@ async def close(self, *, deregister_listeners: bool = True) -> None:

for event_type_, listeners in self._listeners.items():
for listener in listeners.values():
_try_unsubscribe(self._events, event_type_, listener.__call__)
_try_unsubscribe(self._events, event_type_, listener)

if deregister_listeners and self._server:
_try_deregister_listener(self._server, hikari.CommandInteraction, self.on_command_interaction_request)
Expand Down Expand Up @@ -2370,7 +2368,9 @@ async def open(self, *, register_listeners: bool = True) -> None:
if self._cache:
user = self._cache.get_me()

if not user and (user_cache := self.get_type_dependency(dependencies.SingleStoreCache[hikari.OwnUser])):
if not user and (
user_cache := self.get_type_dependency(dependencies.SingleStoreCache[hikari.OwnUser], default=None)
):
user = await user_cache.get(default=None)

if not user:
Expand Down Expand Up @@ -2403,7 +2403,7 @@ async def open(self, *, register_listeners: bool = True) -> None:

for event_type_, listeners in self._listeners.items():
for listener in listeners.values():
self._events.subscribe(event_type_, listener.__call__)
self._events.subscribe(event_type_, listener)

self._add_task(self._loop.create_task(self.dispatch_client_callback(ClientCallbackNames.STARTED)))

Expand All @@ -2419,8 +2419,8 @@ async def fetch_rest_application_id(self) -> hikari.Snowflake:
return self._cached_application_id

application_cache = self.get_type_dependency(
dependencies.SingleStoreCache[hikari.Application]
) or self.get_type_dependency(dependencies.SingleStoreCache[hikari.AuthorizationApplication])
dependencies.SingleStoreCache[hikari.Application], default=None
) or self.get_type_dependency(dependencies.SingleStoreCache[hikari.AuthorizationApplication], default=None)
if application_cache: # noqa: SIM102
# Has to be nested cause of pyright bug
if application := await application_cache.get(default=None):
Expand Down Expand Up @@ -2755,9 +2755,20 @@ def set_type_dependency(self, type_: type[_T], value: _T, /) -> Self:
self._injector.set_type_dependency(type_, value)
return self

def get_type_dependency(self, type_: type[_T], /) -> typing.Union[_T, alluka.abc.Undefined]:
@typing.overload
def get_type_dependency(self, type_: type[_T], /) -> _T: ...

@typing.overload
def get_type_dependency(self, type_: type[_T], /, *, default: _DefaultT) -> typing.Union[_T, _DefaultT]: ...

def get_type_dependency(
self, type_: type[_T], /, *, default: _DefaultT = tanjun.NO_DEFAULT
) -> typing.Union[_T, _DefaultT]:
# <<inherited docstring from tanjun.abc.Client>>.
return self._injector.get_type_dependency(type_)
if default is tanjun.NO_DEFAULT:
return self._injector.get_type_dependency(type_)

return self._injector.get_type_dependency(type_, default=default)

def remove_type_dependency(self, type_: type[typing.Any], /) -> Self:
# <<inherited docstring from tanjun.abc.Client>>.
Expand Down
10 changes: 5 additions & 5 deletions tanjun/dependencies/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@

import alluka

from .. import abc as tanjun

if typing.TYPE_CHECKING:
import contextlib
from collections import abc as collections
Expand Down Expand Up @@ -232,7 +234,7 @@ def __init__(
self._callback = callback
self._last_called: typing.Optional[float] = None
self._lock: typing.Optional[asyncio.Lock] = None
self._result: typing.Union[_T, alluka.abc.Undefined] = alluka.abc.UNDEFINED
self._result: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT
if expire_after is None:
pass
elif isinstance(expire_after, datetime.timedelta):
Expand All @@ -253,16 +255,14 @@ def _has_expired(self) -> bool:

# Positional arg(s) may be guaranteed under some contexts so we want to pass those through.
async def __call__(self, *args: typing.Any, ctx: alluka.Injected[alluka.abc.Context]) -> _T:
if self._result is not alluka.abc.UNDEFINED and not self._has_expired:
assert not isinstance(self._result, alluka.abc.Undefined)
if self._result is not tanjun.NO_DEFAULT and not self._has_expired:
return self._result

if not self._lock:
self._lock = asyncio.Lock()

async with self._lock:
if self._result is not alluka.abc.UNDEFINED and not self._has_expired:
assert not isinstance(self._result, alluka.abc.Undefined)
if self._result is not tanjun.NO_DEFAULT and not self._has_expired:
return self._result

result = await ctx.call_with_async_di(self._callback, *args)
Expand Down
6 changes: 3 additions & 3 deletions tanjun/dependencies/limiters.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,13 +447,13 @@ async def _get_ctx_target(ctx: tanjun.Context, type_: BucketResource, /) -> hika
if cached_channel := ctx.get_channel():
return cached_channel.parent_id or ctx.guild_id

channel_cache = ctx.get_type_dependency(async_cache.SfCache[hikari.PermissibleGuildChannel])
channel_cache = ctx.get_type_dependency(async_cache.SfCache[hikari.PermissibleGuildChannel], default=None)
if channel_cache: # noqa: SIM102
# Has to be nested cause of pyright bug:
if channel := await channel_cache.get(ctx.channel_id, default=None):
return channel.parent_id or ctx.guild_id

thread_cache = ctx.get_type_dependency(async_cache.SfCache[hikari.GuildThreadChannel])
thread_cache = ctx.get_type_dependency(async_cache.SfCache[hikari.GuildThreadChannel], default=None)
if thread_cache: # noqa: SIM102
# Has to be nested cause of pyright bug
if channel := await thread_cache.get(ctx.channel_id, default=None):
Expand All @@ -476,7 +476,7 @@ async def _get_ctx_target(ctx: tanjun.Context, type_: BucketResource, /) -> hika
try_rest = not roles
if try_rest: # noqa: SIM102
# Has to be nested cause of pyright bug
if role_cache := ctx.get_type_dependency(async_cache.SfCache[hikari.Role]):
if role_cache := ctx.get_type_dependency(async_cache.SfCache[hikari.Role], default=None):
try:
roles = filter(None, [await _try_get_role(role_cache, role_id) for role_id in ctx.member.role_ids])
try_rest = False
Expand Down
2 changes: 1 addition & 1 deletion tanjun/dependencies/owners.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ async def check_ownership(self, client: tanjun.Client, user: hikari.User, /) ->
if not self._fallback_to_application:
return False

application_cache = client.get_type_dependency(_ApplicationCacheT)
application_cache = client.get_type_dependency(_ApplicationCacheT, default=None)
if application_cache: # noqa: SIM102
# Has to be nested cause of pyright bug
if application := await application_cache.get(default=None):
Expand Down
Loading

0 comments on commit 71216fe

Please sign in to comment.