firebox 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- firebox/__init__.py +59 -0
- firebox/__main__.py +109 -0
- firebox/config.py +173 -0
- firebox/events.py +323 -0
- firebox/group.py +89 -0
- firebox/kernel.py +352 -0
- firebox/plugin.py +221 -0
- firebox/py.typed +0 -0
- firebox-0.1.0.dist-info/METADATA +174 -0
- firebox-0.1.0.dist-info/RECORD +14 -0
- firebox-0.1.0.dist-info/WHEEL +5 -0
- firebox-0.1.0.dist-info/entry_points.txt +2 -0
- firebox-0.1.0.dist-info/licenses/LICENSE +201 -0
- firebox-0.1.0.dist-info/top_level.txt +1 -0
firebox/__init__.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Firebox: a kernel for applications made of plugins.
|
|
2
|
+
|
|
3
|
+
class About(Plugin[AboutConfig]):
|
|
4
|
+
needs = (App,)
|
|
5
|
+
|
|
6
|
+
async def mount(self, ctx: Context) -> None:
|
|
7
|
+
await ctx.enter(ctx.get(App).include(router)) # taken away again at unmount
|
|
8
|
+
|
|
9
|
+
async with Kernel(plugins(load("firebox.yml"))) as kernel:
|
|
10
|
+
...
|
|
11
|
+
|
|
12
|
+
python -m firebox plan firebox.yml # what would be mounted, in which order
|
|
13
|
+
python -m firebox run firebox.yml # mount, run until a task ends, unmount
|
|
14
|
+
|
|
15
|
+
Five things, after Cordis, a plugin framework for JavaScript:
|
|
16
|
+
|
|
17
|
+
- a **service** is a thing that one plugin provides and others need, named
|
|
18
|
+
by its type;
|
|
19
|
+
- a **plugin** says what it needs and provides, has settings, and mounts;
|
|
20
|
+
- a **context** is what a plugin is handed: what it does through it is
|
|
21
|
+
undone when the plugin is unmounted;
|
|
22
|
+
- a **group** is some plugins that a plugin mounts under itself, with
|
|
23
|
+
services of their own: a plugin of a group is given a service of its
|
|
24
|
+
group, or else of the nearest group above. The kernel is the group at
|
|
25
|
+
the top, and the plugin ``group`` mounts a list of entries as one;
|
|
26
|
+
- an **event** is how the parts signal each other: a plugin listens to the
|
|
27
|
+
events of another, and whoever owns a thing fires its events, to tell,
|
|
28
|
+
to ask, or to let a listener put itself around what it does
|
|
29
|
+
(``Events``; the five ways of firing are Cordis's, and the class of an
|
|
30
|
+
event, ``Told``, ``Asked`` or ``Around``, says which are its own).
|
|
31
|
+
|
|
32
|
+
A deployment is a YAML list of entries, each a plugin with its settings,
|
|
33
|
+
with patches laid over it by id. A plugin is named by ``module:Class``,
|
|
34
|
+
or by a short name that a package gives it as an entry point of the group
|
|
35
|
+
``firebox.plugins``.
|
|
36
|
+
|
|
37
|
+
The kernel mounts when it starts and unmounts when it stops; the tasks of
|
|
38
|
+
its plugins end before any plugin is unmounted. It replaces no plugin
|
|
39
|
+
while it runs, though a group can be mounted and stopped while it does.
|
|
40
|
+
It does not keep a plugin from anything: a plugin is code of the
|
|
41
|
+
deployment's own choosing, in the same process.
|
|
42
|
+
|
|
43
|
+
Firebox knows nothing of what is built on it. ``docs/kernel.md`` has the
|
|
44
|
+
rules, the choices and the limits.
|
|
45
|
+
|
|
46
|
+
It imports Pydantic, for a plugin's settings, PyYAML, and Typer for its
|
|
47
|
+
two commands.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
from firebox.config import GROUP, BadEntry, Entry, beside, laid_over, load, member, patched, plugins, read, resolve
|
|
51
|
+
from firebox.events import Around, Asked, Events, Next, Off, Told, answered
|
|
52
|
+
from firebox.group import GroupConfig, GroupOf
|
|
53
|
+
from firebox.kernel import GRACE, Clash, Cycle, Group, Kernel, NothingToRun, NotProvided, Unmet
|
|
54
|
+
from firebox.plugin import Context, NotDeclared, Plugin, PluginConfig
|
|
55
|
+
|
|
56
|
+
__all__ = [
|
|
57
|
+
"Around", "Asked", "BadEntry", "Clash", "Context", "Cycle", "Entry", "Events", "GRACE", "GROUP", "Group", "GroupConfig", "GroupOf", "Kernel", "Next", "NotDeclared", "NotProvided", "NothingToRun", "Off", "Plugin", "PluginConfig", "Told", "Unmet",
|
|
58
|
+
"answered", "beside", "laid_over", "load", "member", "patched", "plugins", "read", "resolve",
|
|
59
|
+
]
|
firebox/__main__.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""A deployment from a shell.
|
|
2
|
+
|
|
3
|
+
python -m firebox plan firebox.yml # what would be mounted, in which order
|
|
4
|
+
python -m firebox run firebox.yml # mount, run until a task ends, unmount
|
|
5
|
+
python -m firebox run firebox.yml --patch local.yml
|
|
6
|
+
|
|
7
|
+
``run`` writes what the plugins log to the standard error, from the level
|
|
8
|
+
``--log`` up: ``info`` when none is given. The commands are Typer's.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import asyncio
|
|
14
|
+
import logging
|
|
15
|
+
import sys
|
|
16
|
+
from collections.abc import Sequence
|
|
17
|
+
from enum import StrEnum
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Annotated
|
|
20
|
+
|
|
21
|
+
import typer
|
|
22
|
+
|
|
23
|
+
from firebox.config import load, plugins
|
|
24
|
+
from firebox.group import GroupOf
|
|
25
|
+
from firebox.kernel import GRACE, Group, Kernel
|
|
26
|
+
|
|
27
|
+
PROGRAM = "python -m firebox"
|
|
28
|
+
ERRORS = (OSError, LookupError, ValueError, RuntimeError)
|
|
29
|
+
"""What a command says in one line and ends with 1 for."""
|
|
30
|
+
|
|
31
|
+
app = typer.Typer(help="Mount the plugins of a deployment file.", no_args_is_help=True, add_completion=False, pretty_exceptions_show_locals=False)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Level(StrEnum):
|
|
35
|
+
"""The level from which what the plugins log is written."""
|
|
36
|
+
|
|
37
|
+
debug = "debug"
|
|
38
|
+
info = "info"
|
|
39
|
+
warning = "warning"
|
|
40
|
+
error = "error"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
File = Annotated[Path, typer.Argument(help="The root file of the deployment, a YAML list of entries.")]
|
|
44
|
+
Patches = Annotated[list[Path] | None, typer.Option("--patch", help="A patch to lay over it; can be given more than once.")]
|
|
45
|
+
Grace = Annotated[float, typer.Option(help="Seconds that a task has to end when it is asked to, before it is cancelled.")]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def kernel_of(file: str | Path, patches: Sequence[str | Path], grace: float = GRACE) -> Kernel:
|
|
49
|
+
"""The kernel of a deployment file. A path in a plugin's settings is
|
|
50
|
+
taken from the directory of that file."""
|
|
51
|
+
return Kernel(plugins(load(file, *patches)), root=Path(file).resolve().parent, grace=grace)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def planned(group: Group) -> list[str]:
|
|
55
|
+
"""A line for each plugin of *group* in the order of mounting, with
|
|
56
|
+
what it needs and provides; under a plugin that mounts a group of
|
|
57
|
+
entries, the same for those, each by its id with the group's name."""
|
|
58
|
+
lines: list[str] = []
|
|
59
|
+
for id in group.order():
|
|
60
|
+
plugin = group.plugins[id]
|
|
61
|
+
needs = ", ".join(one.__name__ for one in plugin.needed(group.root)) or "nothing"
|
|
62
|
+
provides = ", ".join(one.__name__ for one in plugin.provides) or "nothing"
|
|
63
|
+
lines.append(f"{group.path(id)}: {type(plugin).__name__}, needs {needs}, provides {provides}")
|
|
64
|
+
if isinstance(plugin, GroupOf):
|
|
65
|
+
lines += planned(Group(plugin.plugins(group.root), root=plugin.within(group.root), above=group, name=group.path(id)))
|
|
66
|
+
return lines
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@app.command()
|
|
70
|
+
def plan(file: File, patch: Patches = None, grace: Grace = GRACE) -> None:
|
|
71
|
+
"""Print the plugins in the order of mounting, with what each needs and provides."""
|
|
72
|
+
for line in planned(kernel_of(file, patch or [], grace)):
|
|
73
|
+
print(line)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@app.command()
|
|
77
|
+
def run(
|
|
78
|
+
file: File,
|
|
79
|
+
patch: Patches = None,
|
|
80
|
+
grace: Grace = GRACE,
|
|
81
|
+
log: Annotated[Level, typer.Option(help="The level from which what the plugins log is written.")] = Level.info,
|
|
82
|
+
) -> None:
|
|
83
|
+
"""Mount the plugins, run until a task of one ends, and unmount them."""
|
|
84
|
+
kernel = kernel_of(file, patch or [], grace)
|
|
85
|
+
# Does nothing when the program that calls this has set up its logging already.
|
|
86
|
+
logging.basicConfig(level=log.value.upper(), format="%(levelname)s %(name)s: %(message)s")
|
|
87
|
+
try:
|
|
88
|
+
asyncio.run(kernel.run())
|
|
89
|
+
except KeyboardInterrupt:
|
|
90
|
+
# Stopped from the keyboard: everything was unmounted on the way out, and that is how a deployment is stopped.
|
|
91
|
+
return
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def main(arguments: Sequence[str] | None = None) -> int:
|
|
95
|
+
"""Run a command, and give the code that the shell gets: 0; 1, with
|
|
96
|
+
what was wrong in one line on the standard error; or 2, in Typer's own
|
|
97
|
+
words, for a command that is written wrong."""
|
|
98
|
+
try:
|
|
99
|
+
app(args=None if arguments is None else list(arguments), prog_name=PROGRAM)
|
|
100
|
+
except SystemExit as ended:
|
|
101
|
+
return ended.code if isinstance(ended.code, int) else int(ended.code is not None)
|
|
102
|
+
except ERRORS as error:
|
|
103
|
+
print(f"{type(error).__name__}: {error}", file=sys.stderr)
|
|
104
|
+
return 1
|
|
105
|
+
return 0
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
if __name__ == "__main__":
|
|
109
|
+
sys.exit(main())
|
firebox/config.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""A deployment as a YAML file: which plugins are mounted, and with which
|
|
2
|
+
settings.
|
|
3
|
+
|
|
4
|
+
# firebox.yml
|
|
5
|
+
- id: store
|
|
6
|
+
name: shop:Store
|
|
7
|
+
config:
|
|
8
|
+
directory: data
|
|
9
|
+
- id: app
|
|
10
|
+
name: shop:WebApp
|
|
11
|
+
- id: server
|
|
12
|
+
name: shop:Server
|
|
13
|
+
config:
|
|
14
|
+
port: 8765
|
|
15
|
+
|
|
16
|
+
The file is a list of entries. An entry has an ``id``, the ``name`` of
|
|
17
|
+
its plugin, and the plugin's ``config``. The form is Cordis's: a root
|
|
18
|
+
file, and patches over it.
|
|
19
|
+
|
|
20
|
+
A patch is a file of the same form. An entry of a patch with an id that
|
|
21
|
+
is there already changes that entry: its ``config`` is laid over the one
|
|
22
|
+
that is there, member by member. An entry with a new id is added. So a
|
|
23
|
+
deployment keeps what is its own (a port, a directory) in a patch, beside
|
|
24
|
+
a root that it shares.
|
|
25
|
+
|
|
26
|
+
No secret is written in such a file. A setting names where a secret is:
|
|
27
|
+
a file, or a variable of the environment.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import importlib
|
|
33
|
+
from collections.abc import Mapping, Sequence
|
|
34
|
+
from importlib.metadata import entry_points
|
|
35
|
+
from pathlib import Path
|
|
36
|
+
from typing import Any
|
|
37
|
+
|
|
38
|
+
import yaml
|
|
39
|
+
from pydantic import BaseModel, ConfigDict, Field, ValidationError
|
|
40
|
+
|
|
41
|
+
from firebox.plugin import Plugin
|
|
42
|
+
|
|
43
|
+
GROUP = "firebox.plugins"
|
|
44
|
+
"""The group of entry points under which a package names its plugins."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class BadEntry(ValueError):
|
|
48
|
+
"""An entry of a deployment file is not one: its form, its plugin, or
|
|
49
|
+
its settings."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Entry(BaseModel):
|
|
53
|
+
"""One plugin of a deployment. In a patch, ``name`` can be left out
|
|
54
|
+
for an id that is there already."""
|
|
55
|
+
|
|
56
|
+
model_config = ConfigDict(extra="forbid")
|
|
57
|
+
|
|
58
|
+
id: str = Field(min_length=1)
|
|
59
|
+
name: str | None = None
|
|
60
|
+
"""The plugin: the name of an entry point of the group
|
|
61
|
+
``firebox.plugins``, or ``module:Class``."""
|
|
62
|
+
config: dict[str, Any] = {}
|
|
63
|
+
disabled: bool | None = None
|
|
64
|
+
"""An entry that is disabled is not mounted."""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def read(path: str | Path) -> list[Entry]:
|
|
68
|
+
"""The entries of one file. A file with nothing in it has none."""
|
|
69
|
+
where = Path(path)
|
|
70
|
+
found = yaml.safe_load(where.read_text(encoding="utf-8"))
|
|
71
|
+
if found is None:
|
|
72
|
+
return []
|
|
73
|
+
if not isinstance(found, list):
|
|
74
|
+
raise BadEntry(f"{where} is not a list of entries")
|
|
75
|
+
try:
|
|
76
|
+
entries = [Entry.model_validate(one) for one in found]
|
|
77
|
+
except ValidationError as error:
|
|
78
|
+
raise BadEntry(f"{where}: {error}") from error
|
|
79
|
+
ids = [entry.id for entry in entries]
|
|
80
|
+
for id in ids:
|
|
81
|
+
if ids.count(id) > 1:
|
|
82
|
+
raise BadEntry(f"{where} has the id '{id}' twice")
|
|
83
|
+
return entries
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def laid_over(under: Mapping[str, Any], over: Mapping[str, Any]) -> dict[str, Any]:
|
|
87
|
+
"""*over* on *under*: an object is laid over an object member by
|
|
88
|
+
member, and anything else takes the place of what was there."""
|
|
89
|
+
merged = dict(under)
|
|
90
|
+
for name, value in over.items():
|
|
91
|
+
there = merged.get(name)
|
|
92
|
+
merged[name] = laid_over(there, value) if isinstance(there, Mapping) and isinstance(value, Mapping) else value
|
|
93
|
+
return merged
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def patched(entries: Sequence[Entry], patch: Sequence[Entry]) -> list[Entry]:
|
|
97
|
+
"""*entries* with *patch* over them, by id."""
|
|
98
|
+
by_id = {entry.id: entry for entry in entries}
|
|
99
|
+
for change in patch:
|
|
100
|
+
there = by_id.get(change.id)
|
|
101
|
+
if there is None:
|
|
102
|
+
by_id[change.id] = change
|
|
103
|
+
else:
|
|
104
|
+
by_id[change.id] = Entry(
|
|
105
|
+
id=change.id,
|
|
106
|
+
name=change.name if change.name is not None else there.name,
|
|
107
|
+
config=laid_over(there.config, change.config),
|
|
108
|
+
disabled=change.disabled if change.disabled is not None else there.disabled,
|
|
109
|
+
)
|
|
110
|
+
return list(by_id.values())
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def beside(path: Path) -> Path:
|
|
114
|
+
"""The patch that goes with a root file by its name:
|
|
115
|
+
``firebox.patch.yml`` beside ``firebox.yml``."""
|
|
116
|
+
return path.with_name(f"{path.stem}.patch{path.suffix}")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def load(path: str | Path, *patches: str | Path) -> list[Entry]:
|
|
120
|
+
"""The entries of a deployment: the root file, the patch beside it
|
|
121
|
+
when there is one, and then each of *patches*, in order."""
|
|
122
|
+
root = Path(path)
|
|
123
|
+
entries = read(root)
|
|
124
|
+
for patch in ([beside(root)] if beside(root).is_file() else []) + [Path(one) for one in patches]:
|
|
125
|
+
entries = patched(entries, read(patch))
|
|
126
|
+
return entries
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def member(name: str) -> Any:
|
|
130
|
+
"""What ``module:name`` names: a member of a module. A plugin's
|
|
131
|
+
settings name a function of the deployment's own this way."""
|
|
132
|
+
module, colon, of = name.partition(":")
|
|
133
|
+
if colon == "" or module == "" or of == "":
|
|
134
|
+
raise BadEntry(f"'{name}' is not of the form module:name")
|
|
135
|
+
try:
|
|
136
|
+
return getattr(importlib.import_module(module), of)
|
|
137
|
+
except (ImportError, AttributeError) as error:
|
|
138
|
+
raise BadEntry(f"there is no '{name}': {error}") from error
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def resolve(name: str) -> type[Plugin[Any]]:
|
|
142
|
+
"""The plugin of a name: ``module:Class``, or an entry point of the
|
|
143
|
+
group ``firebox.plugins``."""
|
|
144
|
+
if ":" in name:
|
|
145
|
+
try:
|
|
146
|
+
found = member(name)
|
|
147
|
+
except BadEntry as error:
|
|
148
|
+
raise BadEntry(f"there is no plugin '{name}': {error.__cause__ or error}") from error
|
|
149
|
+
else:
|
|
150
|
+
known = {point.name: point for point in entry_points(group=GROUP)}
|
|
151
|
+
if name not in known:
|
|
152
|
+
raise BadEntry(f"there is no plugin '{name}': the entry points of '{GROUP}' are {', '.join(sorted(known)) or 'none'}")
|
|
153
|
+
found = known[name].load()
|
|
154
|
+
if not (isinstance(found, type) and issubclass(found, Plugin)):
|
|
155
|
+
raise BadEntry(f"'{name}' is not a plugin: {found!r}")
|
|
156
|
+
return found
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def plugins(entries: Sequence[Entry]) -> dict[str, Plugin[Any]]:
|
|
160
|
+
"""The plugin of each entry that is not disabled, made with its
|
|
161
|
+
settings, under the id of its entry."""
|
|
162
|
+
made: dict[str, Plugin[Any]] = {}
|
|
163
|
+
for entry in entries:
|
|
164
|
+
if entry.disabled:
|
|
165
|
+
continue
|
|
166
|
+
if entry.name is None:
|
|
167
|
+
raise BadEntry(f"the entry '{entry.id}' names no plugin")
|
|
168
|
+
plugin = resolve(entry.name)
|
|
169
|
+
try:
|
|
170
|
+
made[entry.id] = plugin(plugin.Config.model_validate(entry.config))
|
|
171
|
+
except ValidationError as error:
|
|
172
|
+
raise BadEntry(f"the settings of '{entry.id}' ({entry.name}) do not fit: {error}") from error
|
|
173
|
+
return made
|
firebox/events.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
"""Events: how the parts of a deployment signal each other, after Cordis.
|
|
2
|
+
|
|
3
|
+
@dataclass(frozen=True)
|
|
4
|
+
class TurnParked(Told): # an event is an object; its class names it,
|
|
5
|
+
turn: str # and says how it is fired
|
|
6
|
+
|
|
7
|
+
events = Events()
|
|
8
|
+
off = events.on(TurnParked, tell) # a listener, until ``off()``
|
|
9
|
+
await events.parallel(TurnParked("R-1"))
|
|
10
|
+
|
|
11
|
+
Whoever owns a thing fires its events. The five ways of firing are
|
|
12
|
+
Cordis's, by Cordis's names, and the class of an event says which are
|
|
13
|
+
its own:
|
|
14
|
+
|
|
15
|
+
Told emit every listener, in order; nothing is awaited
|
|
16
|
+
parallel every listener; what they return is awaited together
|
|
17
|
+
Asked serial in order, each awaited, until one answers
|
|
18
|
+
bail in order, nothing awaited, until one answers
|
|
19
|
+
Around waterfall each listener is around the next, and the last is
|
|
20
|
+
around what the owner would have done
|
|
21
|
+
|
|
22
|
+
An event that is ``Told`` tells. One that is ``Asked`` asks: the first listener
|
|
23
|
+
that answers with something other than ``None`` or ``False`` is the
|
|
24
|
+
answer. ``Around`` is how a listener changes what is there: it is handed
|
|
25
|
+
``next``, and it may call it, change what it is handed or what comes back,
|
|
26
|
+
or not call it at all, and then what the owner would have done is not
|
|
27
|
+
done.
|
|
28
|
+
|
|
29
|
+
So a listener's shape follows from the class that it listens to: one
|
|
30
|
+
argument, the event, or two for an event that it is around. One of
|
|
31
|
+
another shape is refused when it is put on, and an event that is fired
|
|
32
|
+
another way than its class says is refused when it is fired.
|
|
33
|
+
|
|
34
|
+
A listener is put after the ones that are there, or with ``prepend``
|
|
35
|
+
before them: the first one hears first, and is outermost in a waterfall.
|
|
36
|
+
|
|
37
|
+
Nothing here knows the kernel. A kernel has one ``Events`` for its
|
|
38
|
+
plugins (``Context.on``, ``Context.events``), and anything else can have
|
|
39
|
+
its own.
|
|
40
|
+
|
|
41
|
+
Events can be put one above another, as the groups of a kernel are: an
|
|
42
|
+
event is then heard along its own line, by the listeners of the events
|
|
43
|
+
that fired it, of each one above, and of each one below; never across, by
|
|
44
|
+
those of another that is beside it. The ones above hear first, and are
|
|
45
|
+
outermost in a waterfall.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
from __future__ import annotations
|
|
49
|
+
|
|
50
|
+
import asyncio
|
|
51
|
+
import inspect
|
|
52
|
+
from collections.abc import Awaitable, Callable
|
|
53
|
+
from typing import Any, Protocol, overload
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class Told:
|
|
57
|
+
"""An event that tells: its listeners are called with it, and what
|
|
58
|
+
they return is nothing to whoever fired. Fired with ``emit`` or
|
|
59
|
+
``parallel``."""
|
|
60
|
+
|
|
61
|
+
__slots__ = ()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Asked[R]:
|
|
65
|
+
"""An event that asks: its listeners are called with it in order, and
|
|
66
|
+
the first that answers with something other than ``None`` or ``False``
|
|
67
|
+
has answered, with an *R*. Fired with ``serial`` or ``bail``."""
|
|
68
|
+
|
|
69
|
+
__slots__ = ()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Around[R]:
|
|
73
|
+
"""An event that a listener is around: it is called with the event and
|
|
74
|
+
``next``, and what the outermost listener returns, an *R*, is what
|
|
75
|
+
whoever fired gets in place of what it would have done. Fired with
|
|
76
|
+
``waterfall``."""
|
|
77
|
+
|
|
78
|
+
__slots__ = ()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
WAYS: dict[type, tuple[str, ...]] = {Told: ("emit", "parallel"), Asked: ("serial", "bail"), Around: ("waterfall",)}
|
|
82
|
+
"""The ways in which an event of each kind is fired."""
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class Next[E = Any](Protocol):
|
|
86
|
+
"""What a listener of a waterfall is handed: the rest of the chain.
|
|
87
|
+
With no argument the rest gets the event as it is; with one, that
|
|
88
|
+
event in its place."""
|
|
89
|
+
|
|
90
|
+
def __call__(self, event: E | None = None, /) -> Awaitable[Any]: ...
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
type Off = Callable[[], bool]
|
|
94
|
+
"""What takes a listener away again: whether it was still there."""
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def answered(value: object) -> bool:
|
|
98
|
+
"""Whether what a listener returned is an answer: anything but
|
|
99
|
+
``None`` and ``False``."""
|
|
100
|
+
return value is not None and value is not False
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def kind_of(event: type) -> type:
|
|
104
|
+
"""Which of ``Told``, ``Asked`` and ``Around`` the class *event*
|
|
105
|
+
is: an event is one of the three, and only one."""
|
|
106
|
+
found = [kind for kind in WAYS if isinstance(event, type) and issubclass(event, kind)]
|
|
107
|
+
if len(found) != 1:
|
|
108
|
+
name = event.__name__ if isinstance(event, type) else repr(event)
|
|
109
|
+
raise TypeError(f"an event is named by its class, which is Told, Asked or Around: {name} is {'none' if len(found) == 0 else 'more than one'} of them")
|
|
110
|
+
return found[0]
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def takes(listener: Callable[..., Any], count: int) -> bool:
|
|
114
|
+
"""Whether *listener* can be called with *count* arguments. One whose
|
|
115
|
+
arguments cannot be read, as some that are built in, is taken to."""
|
|
116
|
+
try:
|
|
117
|
+
parameters = inspect.signature(listener).parameters.values()
|
|
118
|
+
except (TypeError, ValueError):
|
|
119
|
+
return True
|
|
120
|
+
positional = [one for one in parameters if one.kind in (one.POSITIONAL_ONLY, one.POSITIONAL_OR_KEYWORD)]
|
|
121
|
+
needed = sum(1 for one in positional if one.default is one.empty)
|
|
122
|
+
needed_by_name = any(one.kind is one.KEYWORD_ONLY and one.default is one.empty for one in parameters)
|
|
123
|
+
any_number = any(one.kind is one.VAR_POSITIONAL for one in parameters)
|
|
124
|
+
return not needed_by_name and needed <= count and (any_number or count <= len(positional))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class Events:
|
|
128
|
+
"""The listeners of some events, and the five ways to fire one.
|
|
129
|
+
*above* are the events that these are below."""
|
|
130
|
+
|
|
131
|
+
def __init__(self, above: Events | None = None) -> None:
|
|
132
|
+
self.above: Events | None = None
|
|
133
|
+
self._below: list[Events] = []
|
|
134
|
+
self._listeners: dict[type, list[Callable[..., Any]]] = {}
|
|
135
|
+
if above is not None:
|
|
136
|
+
self.join(above)
|
|
137
|
+
|
|
138
|
+
def join(self, above: Events) -> None:
|
|
139
|
+
"""Be below *above* from now on, and below nothing else."""
|
|
140
|
+
self.leave()
|
|
141
|
+
self.above = above
|
|
142
|
+
above._below.append(self)
|
|
143
|
+
|
|
144
|
+
def leave(self) -> None:
|
|
145
|
+
"""Be below nothing any more: what is fired above is not heard
|
|
146
|
+
here, and what is fired here is not heard above."""
|
|
147
|
+
if self.above is not None and self in self.above._below:
|
|
148
|
+
self.above._below.remove(self)
|
|
149
|
+
self.above = None
|
|
150
|
+
|
|
151
|
+
# -- listening ---------------------------------------------------------------------
|
|
152
|
+
|
|
153
|
+
@overload
|
|
154
|
+
def on[E: Told | Asked[Any]](self, kind: type[E], listener: Callable[[E], object], *, prepend: bool = False) -> Off: ...
|
|
155
|
+
|
|
156
|
+
@overload
|
|
157
|
+
def on[E: Around[Any]](self, kind: type[E], listener: Callable[[E, Next[E]], object], *, prepend: bool = False) -> Off: ...
|
|
158
|
+
|
|
159
|
+
def on(self, kind: type, listener: Callable[..., Any], *, prepend: bool = False) -> Off:
|
|
160
|
+
"""Have *listener* called for each event of the class *kind*,
|
|
161
|
+
after the listeners that are there, or with *prepend* before
|
|
162
|
+
them. It takes the event, and ``next`` as well for an event that
|
|
163
|
+
it is around: one of another shape is a ``TypeError`` now, and not
|
|
164
|
+
when the event is fired. What comes back takes it away again, and
|
|
165
|
+
says whether it was still there."""
|
|
166
|
+
self._fits(kind, listener)
|
|
167
|
+
return self._put(kind, listener, prepend)
|
|
168
|
+
|
|
169
|
+
@overload
|
|
170
|
+
def once[E: Told | Asked[Any]](self, kind: type[E], listener: Callable[[E], object], *, prepend: bool = False) -> Off: ...
|
|
171
|
+
|
|
172
|
+
@overload
|
|
173
|
+
def once[E: Around[Any]](self, kind: type[E], listener: Callable[[E, Next[E]], object], *, prepend: bool = False) -> Off: ...
|
|
174
|
+
|
|
175
|
+
def once(self, kind: type, listener: Callable[..., Any], *, prepend: bool = False) -> Off:
|
|
176
|
+
"""As ``on``, for the next event of the class alone."""
|
|
177
|
+
self._fits(kind, listener)
|
|
178
|
+
|
|
179
|
+
def first(*given: Any) -> Any:
|
|
180
|
+
off()
|
|
181
|
+
return listener(*given)
|
|
182
|
+
|
|
183
|
+
off = self._put(kind, first, prepend)
|
|
184
|
+
return off
|
|
185
|
+
|
|
186
|
+
def listeners(self, kind: type) -> list[Callable[..., Any]]:
|
|
187
|
+
"""Who hears an event of *kind* that is fired here, the first to
|
|
188
|
+
hear first: the listeners above, the topmost first; then the ones
|
|
189
|
+
here; then the ones below."""
|
|
190
|
+
return [*self._up(kind), *self._own(kind), *self._down(kind)]
|
|
191
|
+
|
|
192
|
+
def _own(self, kind: type) -> list[Callable[..., Any]]:
|
|
193
|
+
return list(self._listeners.get(kind, ()))
|
|
194
|
+
|
|
195
|
+
def _up(self, kind: type) -> list[Callable[..., Any]]:
|
|
196
|
+
return [] if self.above is None else [*self.above._up(kind), *self.above._own(kind)]
|
|
197
|
+
|
|
198
|
+
def _down(self, kind: type) -> list[Callable[..., Any]]:
|
|
199
|
+
return [listener for below in self._below for listener in (*below._own(kind), *below._down(kind))]
|
|
200
|
+
|
|
201
|
+
@staticmethod
|
|
202
|
+
def _fits(kind: type, listener: Callable[..., Any]) -> None:
|
|
203
|
+
way = kind_of(kind)
|
|
204
|
+
if not callable(listener):
|
|
205
|
+
raise TypeError(f"a listener of {kind.__name__} is a function, not {listener!r}")
|
|
206
|
+
count = 2 if way is Around else 1
|
|
207
|
+
if not takes(listener, count):
|
|
208
|
+
shape = "the event and next: it is around the event" if way is Around else "the event alone"
|
|
209
|
+
raise TypeError(f"a listener of {kind.__name__} takes {shape}; {getattr(listener, '__qualname__', listener)!s} does not")
|
|
210
|
+
|
|
211
|
+
def _put(self, kind: type, listener: Callable[..., Any], prepend: bool) -> Off:
|
|
212
|
+
held = self._listeners.setdefault(kind, [])
|
|
213
|
+
if prepend:
|
|
214
|
+
held.insert(0, listener)
|
|
215
|
+
else:
|
|
216
|
+
held.append(listener)
|
|
217
|
+
|
|
218
|
+
def off() -> bool:
|
|
219
|
+
for index, one in enumerate(held):
|
|
220
|
+
if one is listener:
|
|
221
|
+
del held[index]
|
|
222
|
+
return True
|
|
223
|
+
return False
|
|
224
|
+
|
|
225
|
+
return off
|
|
226
|
+
|
|
227
|
+
@staticmethod
|
|
228
|
+
def _fired(event: object, kind: type, way: str) -> None:
|
|
229
|
+
if not isinstance(event, kind):
|
|
230
|
+
own = " or ".join(WAYS[kind_of(type(event))])
|
|
231
|
+
raise TypeError(f"{type(event).__name__} is fired with {own}, not with {way}")
|
|
232
|
+
|
|
233
|
+
# -- telling -----------------------------------------------------------------------
|
|
234
|
+
|
|
235
|
+
def emit(self, event: Told) -> None:
|
|
236
|
+
"""Tell each listener of *event*, in order. Nothing is awaited: a
|
|
237
|
+
listener that is a coroutine function is a ``TypeError``, since
|
|
238
|
+
what it returned would never run. What a listener raises is
|
|
239
|
+
raised here, and the ones after it are not told."""
|
|
240
|
+
self._fired(event, Told, "emit")
|
|
241
|
+
for listener in self.listeners(type(event)):
|
|
242
|
+
self._plain(event, listener(event), "emit")
|
|
243
|
+
|
|
244
|
+
async def parallel(self, event: Told) -> None:
|
|
245
|
+
"""Tell each listener of *event*: each is called, in order, and
|
|
246
|
+
what they return is awaited together. Every listener is told,
|
|
247
|
+
whatever another raised; then what was raised is raised as one
|
|
248
|
+
``ExceptionGroup``."""
|
|
249
|
+
self._fired(event, Told, "parallel")
|
|
250
|
+
errors: list[Exception] = []
|
|
251
|
+
waiting: list[Awaitable[Any]] = []
|
|
252
|
+
for listener in self.listeners(type(event)):
|
|
253
|
+
try:
|
|
254
|
+
given = listener(event)
|
|
255
|
+
except Exception as error:
|
|
256
|
+
errors.append(error)
|
|
257
|
+
continue
|
|
258
|
+
if inspect.isawaitable(given):
|
|
259
|
+
waiting.append(given)
|
|
260
|
+
for result in await asyncio.gather(*waiting, return_exceptions=True):
|
|
261
|
+
if isinstance(result, Exception):
|
|
262
|
+
errors.append(result)
|
|
263
|
+
elif isinstance(result, BaseException):
|
|
264
|
+
raise result
|
|
265
|
+
if errors:
|
|
266
|
+
raise ExceptionGroup(f"{len(errors)} of the listeners of {type(event).__name__} failed", errors)
|
|
267
|
+
|
|
268
|
+
# -- asking ------------------------------------------------------------------------
|
|
269
|
+
|
|
270
|
+
async def serial[R](self, event: Asked[R]) -> R | None:
|
|
271
|
+
"""Ask each listener of *event* in order, awaiting what it
|
|
272
|
+
returns, until one answers: its answer, or ``None`` when none
|
|
273
|
+
did. The listeners after it are not asked."""
|
|
274
|
+
self._fired(event, Asked, "serial")
|
|
275
|
+
for listener in self.listeners(type(event)):
|
|
276
|
+
given = listener(event)
|
|
277
|
+
if inspect.isawaitable(given):
|
|
278
|
+
given = await given
|
|
279
|
+
if answered(given):
|
|
280
|
+
return given
|
|
281
|
+
return None
|
|
282
|
+
|
|
283
|
+
def bail[R](self, event: Asked[R]) -> R | None:
|
|
284
|
+
"""As ``serial``, with nothing awaited: a listener that is a
|
|
285
|
+
coroutine function is a ``TypeError``."""
|
|
286
|
+
self._fired(event, Asked, "bail")
|
|
287
|
+
for listener in self.listeners(type(event)):
|
|
288
|
+
given = self._plain(event, listener(event), "bail")
|
|
289
|
+
if answered(given):
|
|
290
|
+
return given
|
|
291
|
+
return None
|
|
292
|
+
|
|
293
|
+
# -- changing what is there --------------------------------------------------------
|
|
294
|
+
|
|
295
|
+
async def waterfall[R](self, event: Around[R], inner: Callable[[Any], Awaitable[R] | R]) -> R:
|
|
296
|
+
"""Do *inner* with *event*, with each listener of the event around
|
|
297
|
+
it: the first listener is outermost. A listener is called with
|
|
298
|
+
the event and ``next``, and what it returns is what the one
|
|
299
|
+
around it gets from its own ``next``. With no listener this is
|
|
300
|
+
``inner(event)`` and nothing else.
|
|
301
|
+
|
|
302
|
+
A listener that does not call ``next`` keeps the rest from
|
|
303
|
+
running, *inner* too. That is what a waterfall is for, and whoever
|
|
304
|
+
writes such a listener answers for what is then not done."""
|
|
305
|
+
self._fired(event, Around, "waterfall")
|
|
306
|
+
waiting = self.listeners(type(event))
|
|
307
|
+
|
|
308
|
+
async def step(at: int, now: Any) -> Any:
|
|
309
|
+
def onward(changed: Any = None, /) -> Awaitable[Any]:
|
|
310
|
+
return step(at + 1, now if changed is None else changed)
|
|
311
|
+
|
|
312
|
+
given = inner(now) if at == len(waiting) else waiting[at](now, onward)
|
|
313
|
+
return await given if inspect.isawaitable(given) else given
|
|
314
|
+
|
|
315
|
+
return await step(0, event)
|
|
316
|
+
|
|
317
|
+
@staticmethod
|
|
318
|
+
def _plain(event: object, given: Any, way: str) -> Any:
|
|
319
|
+
if inspect.iscoroutine(given):
|
|
320
|
+
given.close()
|
|
321
|
+
if inspect.isawaitable(given):
|
|
322
|
+
raise TypeError(f"{type(event).__name__} is fired with {way}, which awaits nothing: a listener that is a coroutine function is not called that way")
|
|
323
|
+
return given
|