Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate to Flywheel #154

Draft
wants to merge 24 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .mina/core.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ dependencies = [
"graia-amnesia",
"loguru",
"launart",
"creart"
"creart",
"elaina-flywheel"
]
description = ""
license = {text = "MIT"}
Expand Down
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,5 @@
"python.analysis.extraPaths": [
"__pypackages__/3.10/lib"
],
"python.languageServer": "None",
}
13 changes: 11 additions & 2 deletions avilla/console/backend.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from __future__ import annotations

from functools import cached_property
import sys
from contextlib import suppress
from typing import TYPE_CHECKING

from flywheel import InstanceContext
from loguru import logger
from nonechat import Backend, Frontend
from nonechat.info import Event
Expand Down Expand Up @@ -71,9 +73,16 @@ def on_console_unmount(self):
logger.success("Console exit.")
logger.warning("Press Ctrl-C for Application exit")

@cached_property
def event_instance_ctx(self):
res = InstanceContext()
res.instances[type(self.account)] = self.account
res.instances[type(self._service.protocol)] = self._service.protocol
return res

async def post_event(self, event: Event):
with suppress(NotImplementedError):
res = await ConsoleCapability(self.account.staff).event_callback(event)
with self.event_instance_ctx.scope(), suppress(NotImplementedError):
res = await ConsoleCapability.event_callback(event)
self._service.protocol.post_event(res)
return

Expand Down
11 changes: 11 additions & 0 deletions avilla/console/bases.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from __future__ import annotations

from flywheel import InstanceOf
from .protocol import ConsoleProtocol
from .account import ConsoleAccount

class InstanceOfProtocol:
protocol = InstanceOf(ConsoleProtocol)

class InstanceOfAccount(InstanceOfProtocol):
account = InstanceOf(ConsoleAccount)
65 changes: 49 additions & 16 deletions avilla/console/capability.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,62 @@
from __future__ import annotations

from typing import Any, TypeVar
from typing import Protocol, TypeVar

from graia.amnesia.message import Element as GraiaElement
from nonechat.info import Event as ConsoleEvent
from nonechat.message import Element as ConsoleElement

from avilla.core.event import AvillaEvent
from avilla.core.ryanvk.collector.application import ApplicationCollector
from graia.ryanvk import Fn, TypeOverload
from flywheel import TypeOverload, Fn, FnCompose, FnRecord, OverloadRecorder

CE = TypeVar("CE", bound=ConsoleElement)
GE = TypeVar("GE", bound=GraiaElement)
CV = TypeVar("CV", bound=ConsoleEvent)
CE = TypeVar("CE", bound=ConsoleElement, contravariant=True)
GE = TypeVar("GE", bound=GraiaElement, contravariant=True)
CV = TypeVar("CV", bound=ConsoleEvent, contravariant=True)


class ConsoleCapability((m := ApplicationCollector())._):
@Fn.complex({TypeOverload(): ["event"]})
async def event_callback(self, event: Any) -> AvillaEvent:
...
# NOTE: 全使用 global_collect 或是 scoped_collect.globals() 最好。

@Fn.complex({TypeOverload(): ["element"]})
async def deserialize_element(self, element: Any) -> GraiaElement:
...
class ConsoleCapability:
@Fn.declare
class event_callback(FnCompose):
type = TypeOverload("type")

@Fn.complex({TypeOverload(): ["element"]})
async def serialize_element(self, element: Any) -> ConsoleElement:
...
async def call(self, record: FnRecord, event: ConsoleEvent):
from loguru import logger
logger.info(event)
entities = self.load(self.type.dig(record, event))
return await entities.first(event=event)

class shapecall(Protocol[CV]):
async def __call__(self, event: CV) -> AvillaEvent: ...

def collect(self, recorder: OverloadRecorder[shapecall[CV]], event: type[CV]):
recorder.use(self.type, event)

@Fn.declare
class deserialize_element(FnCompose):
type = TypeOverload("type")

async def call(self, record: FnRecord, element: ConsoleElement):
entities = self.load(self.type.dig(record, element))
return await entities.first(element=element)

class shapecall(Protocol[CE]):
async def __call__(self, element: CE) -> GraiaElement: ...

def collect(self, recorder: OverloadRecorder[shapecall[CE]], element: type[CE]):
recorder.use(self.type, element)

@Fn.declare
class serialize_element(FnCompose):
type = TypeOverload("type")

async def call(self, record: FnRecord, element: GraiaElement):
entities = self.load(self.type.dig(record, element))
return await entities.first(element=element)

class shapecall(Protocol[GE]):
async def __call__(self, element: GE) -> ConsoleElement: ...

def collect(self, recorder: OverloadRecorder[shapecall[GE]], element: type[GE]):
recorder.use(self.type, element)
11 changes: 5 additions & 6 deletions avilla/console/perform/action/activity.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,17 @@

from typing import TYPE_CHECKING

from avilla.core.ryanvk.collector.account import AccountCollector
from avilla.core.selector import Selector
from avilla.standard.core.activity import ActivityTrigger
from avilla.standard.core.activity import start_activity
from flywheel import scoped_collect
from avilla.console.bases import InstanceOfAccount

if TYPE_CHECKING:
from avilla.console.account import ConsoleAccount # noqa
from avilla.console.protocol import ConsoleProtocol # noqa


class ConsoleActivityActionPerform((m := AccountCollector["ConsoleProtocol", "ConsoleAccount"]())._):
m.namespace = "avilla.protocol/console::action/activity"

@m.entity(ActivityTrigger.trigger, target="land.user.activity(bell)")
class ConsoleActivityActionPerform(m := scoped_collect.env().target, InstanceOfAccount, static=True):
@m.impl(start_activity, target="land.user.activity(bell)")
async def bell(self, target: Selector | None = None):
await self.account.client.call("bell", {})
15 changes: 6 additions & 9 deletions avilla/console/perform/action/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,30 +12,27 @@
from avilla.console.capability import ConsoleCapability
from avilla.core.context import Context
from avilla.core.message import Message
from avilla.core.ryanvk.collector.account import AccountCollector
from avilla.console.bases import InstanceOfAccount
from avilla.core.selector import Selector
from avilla.standard.core.message import MessageSend, MessageSent
from avilla.standard.core.message import MessageSent, send_message
from flywheel import scoped_collect

if TYPE_CHECKING:
from avilla.console.account import ConsoleAccount # noqa
from avilla.console.protocol import ConsoleProtocol # noqa


class ConsoleMessageActionPerform((m := AccountCollector["ConsoleProtocol", "ConsoleAccount"]())._):
m.namespace = "avilla.protocol/console::action/message"

@m.entity(MessageSend.send, target="land.user")
class ConsoleMessageActionPerform(m := scoped_collect.env().target, InstanceOfAccount, static=True):
@m.impl(send_message, target="land.user")
async def send_console_message(
self,
target: Selector,
message: MessageChain,
*,
reply: Selector | None = None,
) -> Selector:
if TYPE_CHECKING:
assert isinstance(self.protocol, ConsoleProtocol)
serialized_msg = ConsoleMessage(
[await ConsoleCapability(self.account.staff).serialize_element(i) for i in message]
[await ConsoleCapability.serialize_element(i) for i in message]
)

await self.account.client.call(
Expand Down
17 changes: 9 additions & 8 deletions avilla/console/perform/action/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,25 @@

from typing import TYPE_CHECKING

from avilla.core.ryanvk.collector.account import AccountCollector
from avilla.core.selector import Selector
from avilla.standard.core.profile import Nick, Summary
from avilla.console.bases import InstanceOfAccount
from flywheel import scoped_collect

from avilla.core.builtins.capability import CoreCapability

if TYPE_CHECKING:
from avilla.console.account import ConsoleAccount # noqa
from avilla.console.protocol import ConsoleProtocol # noqa


class ConsoleProfileActionPerform((m := AccountCollector["ConsoleProtocol", "ConsoleAccount"]())._):
m.namespace = "avilla.protocol/console::action/profile"

@m.pull("lang.user", Nick)
async def get_console_nick(self, target: Selector, route: type[Nick]) -> Nick:
class ConsoleProfileActionPerform(m := scoped_collect.env().target, InstanceOfAccount, static=True):
@m.impl(CoreCapability.pull, "lang.user", Nick)
async def get_console_nick(self, target: Selector) -> Nick:
console = self.account.client.storage.current_user
return Nick(console.nickname, console.nickname, "")

@m.pull("lang.user", Summary)
async def get_summary(self, target: Selector, route: type[Summary]) -> Summary:
@m.impl(CoreCapability.pull, "lang.user", Summary)
async def get_summary(self, target: Selector) -> Summary:
console = self.account.client.storage.current_user
return Summary(console.nickname, console.nickname)
13 changes: 6 additions & 7 deletions avilla/console/perform/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,17 @@

from avilla.core.builtins.capability import CoreCapability
from avilla.core.context import Context
from avilla.core.ryanvk.collector.account import AccountCollector
from ..bases import InstanceOfAccount
from avilla.core.selector import Selector
from flywheel import scoped_collect

if TYPE_CHECKING:
from avilla.console.account import ConsoleAccount # noqa
from avilla.console.protocol import ConsoleProtocol # noqa


class ConsoleContextPerform((m := AccountCollector["ConsoleProtocol", "ConsoleAccount"]())._):
m.namespace = "avilla.protocol/console::action/get_context"

@CoreCapability.get_context.collect(m, target="land.user")
class ConsoleContextPerform(m := scoped_collect.env().target, InstanceOfAccount, static=True):
@m.impl(CoreCapability.get_context, target="land.user")
def get_context_from_channel(self, target: Selector, *, via: Selector | None = None):
return Context(
account=self.account,
Expand All @@ -25,10 +24,10 @@ def get_context_from_channel(self, target: Selector, *, via: Selector | None = N
selft=self.account.route,
)

@m.entity(CoreCapability.channel, target="land.user")
@m.impl(CoreCapability.channel, target="land.user")
def channel_from_channel(self, target: Selector):
return target["user"]

@m.entity(CoreCapability.user, target="land.user")
@m.impl(CoreCapability.user, target="land.user")
def user_from_friend(self, target: Selector):
return target["user"]
12 changes: 6 additions & 6 deletions avilla/console/perform/event/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,23 @@
from avilla.console.capability import ConsoleCapability
from avilla.core.context import Context
from avilla.core.message import Message
from avilla.core.ryanvk.collector.account import AccountCollector

from avilla.core.selector import Selector
from avilla.standard.core.message import MessageReceived
from flywheel import scoped_collect
from avilla.console.bases import InstanceOfAccount

if TYPE_CHECKING:
from avilla.console.account import ConsoleAccount # noqa
from avilla.console.protocol import ConsoleProtocol # noqa


class ConsoleEventMessagePerform((m := AccountCollector["ConsoleProtocol", "ConsoleAccount"]())._):
m.namespace = "avilla.protocol/console::event/message"

@m.entity(ConsoleCapability.event_callback, event=MessageEvent)
class ConsoleEventMessagePerform(m := scoped_collect.globals().target, InstanceOfAccount, static=True):
@m.impl(ConsoleCapability.event_callback, event=MessageEvent)
async def console_message(self, event: MessageEvent):
console = Selector().land(self.account.route["land"]).user(str(event.user.id))
message = MessageChain(
[await ConsoleCapability(self.account.staff).deserialize_element(i) for i in event.message.content]
[await ConsoleCapability.deserialize_element(i) for i in event.message.content]
)
context = Context(
account=self.account,
Expand Down
34 changes: 17 additions & 17 deletions avilla/console/perform/message/deserialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,27 +10,27 @@
from avilla.console.capability import ConsoleCapability
from avilla.console.element import Markdown, Markup
from avilla.core.elements import Face, Text
from avilla.core.ryanvk.collector.application import ApplicationCollector
from flywheel import global_collect

@global_collect
@ConsoleCapability.deserialize_element.impl(element=CslText)
async def text(element: CslText) -> Text:
return Text(element.text)

class ConsoleMessageDeserializePerform((m := ApplicationCollector())._):
m.namespace = "avilla.protocol/console::message"
m.identify = "deserialize"

# LINK: https://github.com/microsoft/pyright/issues/5409
@global_collect
@ConsoleCapability.deserialize_element.impl(element=CslEmoji)
async def emoji(element: CslEmoji) -> Face:
return Face(element.name)

@m.entity(ConsoleCapability.deserialize_element, element=CslText)
async def text(self, element: CslText) -> Text:
return Text(element.text)

@m.entity(ConsoleCapability.deserialize_element, element=CslEmoji)
async def emoji(self, element: CslEmoji) -> Face:
return Face(element.name)
@global_collect
@ConsoleCapability.deserialize_element.impl(element=CslMarkup)
async def markup(element: CslMarkup) -> Markup:
return Markup(**asdict(element))

@m.entity(ConsoleCapability.deserialize_element, element=CslMarkup)
async def markup(self, element: CslMarkup) -> Markup:
return Markup(**asdict(element))

@m.entity(ConsoleCapability.deserialize_element, element=CslMarkdown)
async def markdown(self, element: CslMarkdown) -> Markdown:
return Markdown(**asdict(element))
@global_collect
@ConsoleCapability.deserialize_element.impl(element=CslMarkdown)
async def markdown(element: CslMarkdown) -> Markdown:
return Markdown(**asdict(element))
35 changes: 18 additions & 17 deletions avilla/console/perform/message/serialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,32 @@
from avilla.console.capability import ConsoleCapability
from avilla.console.element import Markdown, Markup
from avilla.core.elements import Face, Text
from avilla.core.ryanvk.collector.account import AccountCollector
from flywheel import global_collect

if TYPE_CHECKING:
from ...account import ConsoleAccount # noqa
from ...protocol import ConsoleProtocol # noqa


class ConsoleMessageSerializePerform((m := AccountCollector["ConsoleProtocol", "ConsoleAccount"]())._):
m.namespace = "avilla.protocol/console::message"
m.identify = "serialize"
@global_collect
@ConsoleCapability.serialize_element.impl(element=Text)
async def text(element: Text):
return CslText(element.text)

# LINK: https://github.com/microsoft/pyright/issues/5409

@m.entity(ConsoleCapability.serialize_element, element=Text)
async def text(self, element: Text):
return CslText(element.text)
@global_collect
@ConsoleCapability.serialize_element.impl(element=Face)
async def emoji(element: Face):
return CslEmoji(element.id)

@m.entity(ConsoleCapability.serialize_element, element=Face)
async def emoji(self, element: Face):
return CslEmoji(element.id)

@m.entity(ConsoleCapability.serialize_element, element=Markup)
async def markup(self, element: Markup):
return CslMarkup(**asdict(element))
@global_collect
@ConsoleCapability.serialize_element.impl(element=Markup)
async def markup(element: Markup):
return CslMarkup(**asdict(element))

@m.entity(ConsoleCapability.serialize_element, element=Markdown)
async def markdown(self, element: Markdown):
return CslMarkdown(**asdict(element))

@global_collect
@ConsoleCapability.serialize_element.impl(element=Markdown)
async def markdown(element: Markdown):
return CslMarkdown(**asdict(element))
Loading