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/group.py ADDED
@@ -0,0 +1,89 @@
1
+ """A group of entries, as a plugin: some plugins that are mounted together
2
+ under one entry, with services of their own.
3
+
4
+ - id: app
5
+ name: shop:WebApp
6
+ - id: acme
7
+ name: group
8
+ config:
9
+ root: tenants/acme # what a path in the settings of its entries is taken from
10
+ include: tenant.yml # a list of entries, as a deployment file is
11
+ entries: # laid over the included ones by id, as a patch is
12
+ - id: store
13
+ config: {directory: orders}
14
+
15
+ A plugin of the group is given a service of the group, or else of the
16
+ nearest group above (``Context.group``). So two such entries can each
17
+ have a store and a sign-in of their own, and share the app that is above
18
+ them both. The entries are written once, in the file that is
19
+ included, and each group says what is its own.
20
+
21
+ The plugin needs what the plugins of its group need and do not provide
22
+ themselves, so that it is mounted after whatever provides that above.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from pathlib import Path
28
+ from typing import Any
29
+
30
+ from firebox.config import Entry, patched, plugins, read
31
+ from firebox.kernel import Group
32
+ from firebox.plugin import Context, Plugin, PluginConfig
33
+
34
+
35
+ class GroupConfig(PluginConfig):
36
+ include: Path | None = None
37
+ """A file with a list of entries. A path that does not start at the
38
+ root is taken from the directory of the group above."""
39
+ entries: list[Entry] = []
40
+ """The entries of the group; with ``include``, laid over the included
41
+ ones by id, as a patch is over a root file."""
42
+ root: Path | None = None
43
+ """What a path in the settings of the group's entries is taken from.
44
+ With none, it is as for the group above."""
45
+
46
+
47
+ class GroupOf[C: GroupConfig = GroupConfig](Plugin[C]):
48
+ """Mounts its entries as a group under itself.
49
+
50
+ A subclass can change a step: ``entries`` says which entries there
51
+ are, and ``within`` what their paths are taken from. One with more
52
+ settings is written with them: ``class MountedGroup(GroupOf[MountConfig])``.
53
+ """
54
+
55
+ def __init__(self, config: C | None = None) -> None:
56
+ super().__init__(config)
57
+ self.group: Group | None = None
58
+ """The group, while this plugin is mounted."""
59
+ self._made: dict[Path, dict[str, Plugin[Any]]] = {}
60
+
61
+ def entries(self, root: Path) -> list[Entry]:
62
+ """The entries of the group: the included ones, with the entries
63
+ of the settings over them."""
64
+ included = read(root / self.config.include) if self.config.include is not None else []
65
+ return patched(included, self.config.entries)
66
+
67
+ def within(self, root: Path) -> Path:
68
+ """What a path in the settings of the group's entries is taken
69
+ from, for a group that is mounted with *root*."""
70
+ return root if self.config.root is None else root / self.config.root
71
+
72
+ def plugins(self, root: Path) -> dict[str, Plugin[Any]]:
73
+ """The plugin of each entry of the group, made once."""
74
+ if root not in self._made:
75
+ self._made[root] = plugins(self.entries(root))
76
+ return self._made[root]
77
+
78
+ def needed(self, root: Path) -> tuple[type, ...]:
79
+ inner = self.plugins(root)
80
+ own = {service for plugin in inner.values() for service in plugin.provides}
81
+ needs = [service for plugin in inner.values() for service in plugin.needed(self.within(root))]
82
+ return tuple(dict.fromkeys(service for service in needs if service not in own))
83
+
84
+ async def mount(self, ctx: Context) -> None:
85
+ self.group = await ctx.group(self.plugins(ctx.root), root=self.within(ctx.root))
86
+ ctx.defer(self._gone)
87
+
88
+ def _gone(self) -> None:
89
+ self.group = None
firebox/kernel.py ADDED
@@ -0,0 +1,352 @@
1
+ """The kernel: it mounts plugins in the order of what they need, and
2
+ unmounts them in the reverse.
3
+
4
+ async with Kernel({"store": Store(...), "app": WebApp()}) as kernel:
5
+ app = kernel.get(App)
6
+
7
+ await Kernel(plugins).run() # until a task of a plugin ends
8
+
9
+ It mounts when it starts and unmounts when it stops. No plugin is
10
+ replaced while it runs.
11
+
12
+ A plugin can mount a **group** of plugins under itself (``Context.group``).
13
+ A plugin of a group is given a service of its own group, or else of the
14
+ nearest group above. So what a group provides is its own: two groups side
15
+ by side each have theirs, and a group that provides what is also provided
16
+ above has its own in place of that one. The kernel is the group at the
17
+ top. A group that is mounted while the kernel starts is part of the
18
+ start; one that is mounted later starts at once, and is stopped without
19
+ anything else being touched.
20
+
21
+ Starting has three steps, and stopping is their reverse:
22
+
23
+ 1. each plugin is mounted;
24
+ 2. each plugin is told that every plugin is mounted (``Context.ready``);
25
+ 3. the tasks start.
26
+
27
+ When it stops, the tasks end first, the last one first, and only then is
28
+ any plugin unmounted: a task never runs on what another plugin has taken
29
+ away already.
30
+
31
+ Stopping does not wait for ever. A task that is asked to end has
32
+ ``grace`` seconds to do so, and is then cancelled; one that does not end
33
+ when it is cancelled is left after the same time, and the rest is
34
+ unmounted all the same.
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import asyncio
40
+ import inspect
41
+ import logging
42
+ from collections.abc import Callable, Coroutine, Mapping
43
+ from pathlib import Path
44
+ from types import TracebackType
45
+ from typing import Any, Self, cast
46
+
47
+ from firebox.events import Events
48
+ from firebox.plugin import Context, Plugin
49
+
50
+ GRACE = 10.0
51
+ """How long a task has to end when it is asked to, in seconds."""
52
+
53
+ logger = logging.getLogger(__name__)
54
+
55
+
56
+ class Unmet(LookupError):
57
+ """A plugin needs a service that no plugin provides."""
58
+
59
+
60
+ class Clash(ValueError):
61
+ """Two plugins provide the same service."""
62
+
63
+
64
+ class Cycle(ValueError):
65
+ """Some plugins need each other, in a circle."""
66
+
67
+
68
+ class NotProvided(LookupError):
69
+ """A plugin did not provide a service that it says it provides, or a
70
+ service was asked for that is not there."""
71
+
72
+
73
+ class NothingToRun(RuntimeError):
74
+ """No plugin has a task, so there is nothing to wait for."""
75
+
76
+
77
+ class Group:
78
+ """Some plugins that are mounted together, each under the id of its
79
+ entry: at the top, where it is the ``Kernel``, or under a plugin of
80
+ the group *above*, by ``Context.group``.
81
+
82
+ The order is found before anything of the group is mounted, from what
83
+ each plugin says it needs and provides: ``Unmet``, ``Clash`` and
84
+ ``Cycle`` are raised then. A need is met by a plugin of the group, or
85
+ else by one of a group above. A plugin whose mount fails is undone,
86
+ the ones before it are unmounted, and the error is raised.
87
+ """
88
+
89
+ def __init__(self, plugins: Mapping[str, Plugin[Any]], *, root: str | Path = ".", grace: float = GRACE, above: Group | None = None, name: str = "") -> None:
90
+ self.plugins = dict(plugins)
91
+ self.above = above
92
+ self.name = name
93
+ """The name of the group with the names of the groups above it:
94
+ ``acme``, ``acme/eu``. At the top it is empty."""
95
+ self.root = Path(root)
96
+ self.grace = grace
97
+ """How long a task has to end when it is asked to, and again when
98
+ it is cancelled."""
99
+ self.events = Events()
100
+ """The events of this group. A plugin listens through its
101
+ context, so that it stops listening when it is unmounted. An
102
+ event is heard in its group, above it and below it, for as long
103
+ as the group is mounted."""
104
+ self.started = False
105
+ """Whether the plugins of the group are mounted and told, and
106
+ their tasks begun."""
107
+ self._services: dict[type, object] = {}
108
+ self._mounted: list[Context] = []
109
+ self._ready: list[Callable[[], object]] = []
110
+ self._waiting: list[tuple[Context, Callable[[], Coroutine[Any, Any, None]], Callable[[], object] | None]] = []
111
+ self._tasks: list[tuple[str, asyncio.Task[None], Callable[[], object] | None]] = []
112
+ self._below: list[Group] = []
113
+
114
+ def path(self, id: str) -> str:
115
+ """The id of a plugin of this group with the group's name before
116
+ it: ``acme/store``."""
117
+ return f"{self.name}/{id}" if self.name else id
118
+
119
+ def groups(self) -> list[Group]:
120
+ """The groups that plugins of this group mounted, in the order of
121
+ mounting."""
122
+ return list(self._below)
123
+
124
+ # -- the order ---------------------------------------------------------------------
125
+
126
+ def order(self) -> list[str]:
127
+ """The ids in the order of mounting: each plugin after the ones of
128
+ the group that provide what it needs, and otherwise as they are
129
+ listed. What no plugin of the group provides must be provided
130
+ above."""
131
+ providers: dict[type, str] = {}
132
+ for id, plugin in self.plugins.items():
133
+ for service in plugin.provides:
134
+ if service in providers:
135
+ raise Clash(f"'{self.path(providers[service])}' and '{self.path(id)}' both provide {service.__name__}")
136
+ providers[service] = id
137
+ after: dict[str, set[str]] = {}
138
+ for id, plugin in self.plugins.items():
139
+ needs = plugin.needed(self.root)
140
+ for service in needs:
141
+ if service not in providers and not (self.above is not None and self.above.provides(service)):
142
+ where = "no plugin provides it" if self.above is None else "no plugin of its group or of a group above provides it"
143
+ raise Unmet(f"'{self.path(id)}' needs {service.__name__}, and {where}")
144
+ after[id] = {providers[service] for service in needs if service in providers} - {id}
145
+ order: list[str] = []
146
+ while len(order) < len(after):
147
+ ready = [id for id in after if id not in order and after[id] <= set(order)]
148
+ if len(ready) == 0:
149
+ left = [self.path(id) for id in after if id not in order]
150
+ raise Cycle(f"these plugins need each other in a circle: {', '.join(left)}")
151
+ order.append(ready[0])
152
+ return order
153
+
154
+ def provides(self, service: type) -> bool:
155
+ """Whether a plugin of this group or of a group above says that it
156
+ provides *service*."""
157
+ return any(service in plugin.provides for plugin in self.plugins.values()) or (self.above is not None and self.above.provides(service))
158
+
159
+ # -- starting and stopping ---------------------------------------------------------
160
+
161
+ async def start(self) -> None:
162
+ """Mount each plugin, tell each that every plugin is mounted, and
163
+ then start the tasks that they spawned; with them, the plugins of
164
+ each group that one of them mounts."""
165
+ try:
166
+ await self._mount()
167
+ await self._tell()
168
+ except BaseException:
169
+ await self.stop()
170
+ raise
171
+ self._begin()
172
+
173
+ async def _mount(self) -> None:
174
+ for id in self.order():
175
+ plugin = self.plugins[id]
176
+ ctx = Context(self, id, plugin)
177
+ self._mounted.append(ctx)
178
+ await plugin.mount(ctx)
179
+ for service in plugin.provides:
180
+ if service not in self._services:
181
+ raise NotProvided(f"'{ctx.name}' says that it provides {service.__name__}, and did not")
182
+
183
+ async def _tell(self) -> None:
184
+ while len(self._ready) > 0:
185
+ done = self._ready.pop(0)()
186
+ if inspect.isawaitable(done):
187
+ await done
188
+
189
+ def _begin(self) -> None:
190
+ for ctx, run, stop in self._waiting:
191
+ self._tasks.append((ctx.name, asyncio.create_task(run(), name=ctx.name), stop))
192
+ self._waiting.clear()
193
+ self.started = True
194
+ for below in self._below:
195
+ if not below.started:
196
+ below._begin()
197
+
198
+ async def below(self, owner: Context, plugins: Mapping[str, Plugin[Any]], name: str, root: Path) -> Group:
199
+ """Mount *plugins* as a group below this one, for the plugin of
200
+ *owner*. ``Context.group`` uses this."""
201
+ group = Group(plugins, root=root, grace=self.grace, above=self, name=self.path(name))
202
+ self._below.append(group)
203
+ group.events.join(self.events)
204
+ # Stopped with the plugin that mounted it, whatever becomes of the mounting below.
205
+ owner.at_close(group.stop)
206
+ try:
207
+ await group._mount()
208
+ if self.started:
209
+ # The group above runs already: this one is told and begins at once.
210
+ await group._tell()
211
+ group._begin()
212
+ except BaseException:
213
+ await group.stop()
214
+ raise
215
+ return group
216
+
217
+ async def stop(self) -> None:
218
+ """End each task, the last one first, and those of the groups
219
+ below before; then unmount each plugin, the last one first. A
220
+ group that is stopped is below nothing any more."""
221
+ self._ready.clear()
222
+ await self._end_tasks()
223
+ while len(self._mounted) > 0:
224
+ await self._mounted.pop().close()
225
+ self.started = False
226
+ if self.above is not None:
227
+ if self in self.above._below:
228
+ self.above._below.remove(self)
229
+ self.events.leave()
230
+
231
+ async def _end_tasks(self) -> None:
232
+ for below in reversed(self._below):
233
+ await below._end_tasks()
234
+ self._waiting.clear()
235
+ while len(self._tasks) > 0:
236
+ await self._end(*self._tasks.pop())
237
+
238
+ def tasks(self) -> list[asyncio.Task[None]]:
239
+ """The tasks of this group and of each group below that run."""
240
+ return [task for _, task, _ in self._tasks] + [task for below in self._below for task in below.tasks()]
241
+
242
+ async def __aenter__(self) -> Self:
243
+ await self.start()
244
+ return self
245
+
246
+ async def __aexit__(self, kind: type[BaseException] | None, error: BaseException | None, trace: TracebackType | None) -> None:
247
+ await self.stop()
248
+
249
+ # -- services ----------------------------------------------------------------------
250
+
251
+ def get[T](self, service: type[T]) -> T:
252
+ """The service that a mounted plugin provides: one of this group,
253
+ or else of the nearest group above."""
254
+ if service in self._services:
255
+ return cast(T, self._services[service])
256
+ if self.above is not None:
257
+ return self.above.get(service)
258
+ raise NotProvided(f"no mounted plugin provides {service.__name__}")
259
+
260
+ def own[T](self, service: type[T]) -> T:
261
+ """The service that a mounted plugin of this group itself
262
+ provides: never one from above. Whoever mounted the group asks
263
+ for what the group has of its own this way."""
264
+ if service not in self._services:
265
+ raise NotProvided(f"no mounted plugin of the group '{self.name}' provides {service.__name__}")
266
+ return cast(T, self._services[service])
267
+
268
+ def has(self, service: type) -> bool:
269
+ """Whether a mounted plugin of this group or of a group above
270
+ provides *service* now."""
271
+ return service in self._services or (self.above is not None and self.above.has(service))
272
+
273
+ def offer(self, service: type, it: object, by: str = "") -> Callable[[], None]:
274
+ """Keep *it* as the service of this group, and give what takes it
275
+ away again. ``Context.provide`` uses this. A service that a
276
+ group above has too is this group's own from now on, for its
277
+ plugins and the groups below, and that is said in the log of the
278
+ program."""
279
+ if service in self._services:
280
+ raise Clash(f"{service.__name__} is provided already")
281
+ if self.above is not None and self.above.has(service):
282
+ logger.info("'%s' provides %s for its group, in place of the one above", by or self.name, service.__name__)
283
+ self._services[service] = it
284
+
285
+ def take_away() -> None:
286
+ self._services.pop(service, None)
287
+
288
+ return take_away
289
+
290
+ def task(self, ctx: Context, run: Callable[[], Coroutine[Any, Any, None]], stop: Callable[[], object] | None) -> None:
291
+ """Keep a task to start when every plugin is mounted and told so.
292
+ ``Context.spawn`` uses this."""
293
+ self._waiting.append((ctx, run, stop))
294
+
295
+ def when_ready(self, call: Callable[[], object]) -> None:
296
+ """Keep *call* for when every plugin is mounted: of this group,
297
+ and while a group above still starts, of that one too, so that
298
+ the calls of all are made in the order of mounting.
299
+ ``Context.ready`` uses this."""
300
+ self._starting()._ready.append(call)
301
+
302
+ def _starting(self) -> Group:
303
+ """The topmost group that this one starts with: itself, under a
304
+ group that runs already or under none."""
305
+ return self if self.above is None or self.above.started else self.above._starting()
306
+
307
+ async def _end(self, id: str, task: asyncio.Task[None], stop: Callable[[], object] | None) -> None:
308
+ """End one task: ask it when it has a *stop*, and cancel it when
309
+ it has none or does not end in time."""
310
+ if stop is None:
311
+ task.cancel()
312
+ else:
313
+ await self._asked(id, task, stop)
314
+ await asyncio.wait({task}, timeout=self.grace)
315
+ if not task.done():
316
+ logger.error("the task of '%s' did not end when it was cancelled: it is left, and the rest is unmounted", id)
317
+ elif not task.cancelled():
318
+ # What the task raised is ``run``'s to report.
319
+ task.exception()
320
+
321
+ async def _asked(self, id: str, task: asyncio.Task[None], stop: Callable[[], object]) -> None:
322
+ """Ask the task to end, give it the grace, and cancel it when it
323
+ has not ended by then."""
324
+ try:
325
+ async with asyncio.timeout(self.grace):
326
+ stopped = stop()
327
+ if inspect.isawaitable(stopped):
328
+ await stopped
329
+ await asyncio.wait({task})
330
+ except TimeoutError:
331
+ logger.warning("the task of '%s' did not end within %s seconds of being asked to: it is cancelled", id, self.grace)
332
+ task.cancel()
333
+
334
+
335
+ class Kernel(Group):
336
+ """The group at the top: the plugins of a deployment. ``run`` waits
337
+ on their tasks."""
338
+
339
+ def __init__(self, plugins: Mapping[str, Plugin[Any]], *, root: str | Path = ".", grace: float = GRACE) -> None:
340
+ super().__init__(plugins, root=root, grace=grace)
341
+
342
+ async def run(self) -> None:
343
+ """Start, wait until a task of a plugin ends, and stop. An error
344
+ of that task is raised after everything is unmounted. The tasks
345
+ are the ones that there are when it has started, of each group."""
346
+ async with self:
347
+ tasks = self.tasks()
348
+ if len(tasks) == 0:
349
+ raise NothingToRun("no plugin has a task: there is nothing to run")
350
+ done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
351
+ for task in done:
352
+ task.result()
firebox/plugin.py ADDED
@@ -0,0 +1,221 @@
1
+ """A plugin, and the context that it is handed.
2
+
3
+ class WebServer(Plugin[WebServerConfig]):
4
+ needs = (App,)
5
+
6
+ async def mount(self, ctx: Context) -> None:
7
+ app = ctx.get(App)
8
+ ctx.spawn(lambda: self.serve(app), stop=self.stop)
9
+
10
+ A plugin says which services it needs and which it provides, has settings
11
+ of a type of its own, and has one step: ``mount``. Whatever it does there
12
+ goes through the context, which remembers it, so that it is all undone
13
+ when the plugin is unmounted.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import inspect
19
+ import logging
20
+ from collections.abc import Callable, Coroutine, Mapping
21
+ from contextlib import AbstractAsyncContextManager, AbstractContextManager, AsyncExitStack
22
+ from pathlib import Path
23
+ from typing import TYPE_CHECKING, Any, ClassVar, TypeVar, cast, get_args, get_origin, overload
24
+
25
+ from pydantic import BaseModel, ConfigDict
26
+
27
+ from firebox.events import Around, Asked, Events, Next, Off, Told, kind_of
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ if TYPE_CHECKING:
32
+ from firebox.kernel import Group
33
+
34
+
35
+ class NotDeclared(LookupError):
36
+ """A plugin asked for a service that it does not say it needs, or
37
+ provided one that it does not say it provides."""
38
+
39
+
40
+ class PluginConfig(BaseModel):
41
+ """The settings of a plugin. A plugin with settings has a subclass; a
42
+ member that is not known is refused."""
43
+
44
+ model_config = ConfigDict(extra="forbid")
45
+
46
+
47
+ class Plugin[C: PluginConfig = PluginConfig]:
48
+ """A unit that a kernel mounts.
49
+
50
+ ``needs`` are the services that it must be given, and ``provides`` the
51
+ ones that it gives, each named by its type. The kernel reads both
52
+ before anything is mounted, to find the order. The type of its
53
+ settings is the one that the class is written with:
54
+ ``class WebServer(Plugin[WebServerConfig])``. A base of several
55
+ plugins is written with a type parameter for it first, whose default
56
+ is the settings of the base, and a plugin with its own:
57
+ ``class AgentRole(RoleFiller[AgentConfig])``.
58
+ """
59
+
60
+ needs: ClassVar[tuple[type, ...]] = ()
61
+ provides: ClassVar[tuple[type, ...]] = ()
62
+ Config: ClassVar[type[PluginConfig]] = PluginConfig
63
+ """The type of the settings, read from the class as it is written."""
64
+
65
+ def __init_subclass__(cls, **more: Any) -> None:
66
+ super().__init_subclass__(**more)
67
+ for base in getattr(cls, "__orig_bases__", ()):
68
+ origin, given = get_origin(base), get_args(base)
69
+ # ``Plugin[Settings]``, or a base of plugins that is written with the settings of each: ``RoleFiller[Settings]``.
70
+ if not (isinstance(origin, type) and issubclass(origin, Plugin) and len(given) > 0):
71
+ continue
72
+ settings = given[0]
73
+ if isinstance(settings, TypeVar):
74
+ # The base itself, ``RoleFiller[C: RoleConfig = RoleConfig](Plugin[C])``: the default of its parameter.
75
+ settings = settings.__default__
76
+ if isinstance(settings, type):
77
+ cls.Config = settings
78
+
79
+ def __init__(self, config: C | None = None) -> None:
80
+ self.config: C = config if config is not None else cast(C, self.Config())
81
+
82
+ def needed(self, root: Path) -> tuple[type, ...]:
83
+ """The services that this plugin must be given, when it is mounted
84
+ with *root* as the directory of its paths. It is ``needs``, but
85
+ for a plugin whose needs follow from its settings: one that mounts
86
+ a group needs what the plugins of its group need from above."""
87
+ return self.needs
88
+
89
+ async def mount(self, ctx: Context) -> None:
90
+ """Take what is needed from *ctx*, and register what this plugin
91
+ adds through it."""
92
+ raise NotImplementedError(f"{type(self).__name__} has no mount")
93
+
94
+
95
+ class Context:
96
+ """What a plugin is handed when it is mounted.
97
+
98
+ Everything that a plugin adds goes through here, and is taken away in
99
+ the reverse order when the plugin is unmounted: a service that it
100
+ provided, whatever it entered, each undo that it deferred, each event
101
+ that it listened to, each group that it mounted. A task that
102
+ it spawned has ended by then: the tasks of every plugin end before any
103
+ plugin is unmounted.
104
+ """
105
+
106
+ def __init__(self, group: Group, id: str, plugin: Plugin[Any]) -> None:
107
+ self._group = group
108
+ self._plugin = plugin
109
+ self._stack = AsyncExitStack()
110
+ self.id = id
111
+ """The id of the entry that mounted this plugin."""
112
+ self.name = group.path(id)
113
+ """The id with the names of the groups that the plugin is in:
114
+ ``acme/store``. At the top it is the id."""
115
+ self.root: Path = group.root
116
+ """The directory that a path in the settings is taken from."""
117
+ self.grace: float = group.grace
118
+ """How long a task of this plugin has to end when it is asked to.
119
+ A plugin hands it on to what it runs, so that both give up
120
+ together."""
121
+
122
+ def get[T](self, service: type[T]) -> T:
123
+ """The service, which this plugin says it needs: the one of its
124
+ own group, or else of the nearest group above."""
125
+ if service not in self._plugin.needed(self.root):
126
+ raise NotDeclared(f"'{self.name}' asks for {service.__name__} and does not say that it needs it")
127
+ return self._group.get(service)
128
+
129
+ def provide[T](self, service: type[T], it: T) -> None:
130
+ """Give *it* as the service, until this plugin is unmounted."""
131
+ if service not in self._plugin.provides:
132
+ raise NotDeclared(f"'{self.name}' provides {service.__name__} and does not say that it provides it")
133
+ self._stack.callback(self._group.offer(service, it, self.name))
134
+
135
+ async def enter[T](self, managed: AbstractAsyncContextManager[T] | AbstractContextManager[T]) -> T:
136
+ """Enter *managed*, and leave it when this plugin is unmounted."""
137
+ if isinstance(managed, AbstractAsyncContextManager):
138
+ return await self._stack.enter_async_context(managed)
139
+ return self._stack.enter_context(managed)
140
+
141
+ @property
142
+ def events(self) -> Events:
143
+ """The events of this plugin's group: a plugin fires its own
144
+ here. They are heard in the group, above it and below it."""
145
+ return self._group.events
146
+
147
+ @overload
148
+ def on[E: Told | Asked[Any]](self, kind: type[E], listener: Callable[[E], object], *, prepend: bool = False) -> Off: ...
149
+
150
+ @overload
151
+ def on[E: Around[Any]](self, kind: type[E], listener: Callable[[E, Next[E]], object], *, prepend: bool = False) -> Off: ...
152
+
153
+ def on(self, kind: type, listener: Callable[..., Any], *, prepend: bool = False) -> Off:
154
+ """Have *listener* called for each event of the class *kind*,
155
+ until this plugin is unmounted: after the listeners that are
156
+ there, or with *prepend* before them. It takes the event, and
157
+ ``next`` as well for an event that it is around (``Events.on``).
158
+ What comes back takes it away sooner.
159
+
160
+ It is said in the log of the program, so that whoever starts a
161
+ deployment sees which plugin listens to what, and which is around
162
+ a thing that another part does."""
163
+ events: Any = self._group.events
164
+ off: Off = events.on(kind, listener, prepend=prepend)
165
+ does = {Told: "listens to", Asked: "answers", Around: "is around"}[kind_of(kind)]
166
+ logger.info("'%s' %s %s%s", self.name, does, kind.__name__, ", before the others" if prepend else "")
167
+ self._stack.callback(off)
168
+ return off
169
+
170
+ def defer(self, undo: Callable[[], object]) -> None:
171
+ """Call *undo* when this plugin is unmounted. It may be a
172
+ coroutine function."""
173
+
174
+ async def run() -> None:
175
+ done = undo()
176
+ if inspect.isawaitable(done):
177
+ await done
178
+
179
+ self._stack.push_async_callback(run)
180
+
181
+ def ready(self, call: Callable[[], object]) -> None:
182
+ """Call *call* when every plugin is mounted, before any task
183
+ starts. It may be a coroutine function. A plugin does here what
184
+ needs what the others registered: what was offered to it is all
185
+ there, whatever the order of the plugins. What it does through
186
+ this context then is undone at unmount like the rest, and a call
187
+ that fails is as a mount that fails: nothing starts."""
188
+ self._group.when_ready(call)
189
+
190
+ def spawn(self, run: Callable[[], Coroutine[Any, Any, None]], *, stop: Callable[[], object] | None = None) -> None:
191
+ """Run the coroutine of *run* as a task, once every plugin is
192
+ mounted and told so. When the kernel stops, *stop* is called and
193
+ the task has ``grace`` seconds to end before it is cancelled; with
194
+ no *stop*, the task is cancelled at once. That is before any
195
+ plugin is unmounted, so the task ends on what it started on."""
196
+ self._group.task(self, run, stop)
197
+
198
+ async def group(self, plugins: Mapping[str, Plugin[Any]], *, name: str | None = None, root: str | Path | None = None) -> Group:
199
+ """Mount *plugins* as a group under this plugin, now. It is
200
+ stopped when this plugin is unmounted, or sooner by its ``stop``.
201
+
202
+ A plugin of the group is given a service of the group, or else of
203
+ the nearest group above: so what the group provides is its own,
204
+ and two groups side by side can each have theirs. *name* is the
205
+ group's, under which its plugins are said in the log; with none,
206
+ the id of this plugin. *root* is what a path in the settings of
207
+ its plugins is taken from; with none, this plugin's.
208
+
209
+ While the kernel starts, the plugins of the group are told and
210
+ their tasks begin with everybody's. Under a group that runs
211
+ already, they are told and begin at once."""
212
+ return await self._group.below(self, plugins, name if name is not None else self.id, self.root if root is None else Path(root))
213
+
214
+ async def close(self) -> None:
215
+ """Undo what the plugin did through this context, last first."""
216
+ await self._stack.aclose()
217
+
218
+ def at_close(self, undo: Callable[[], Coroutine[Any, Any, None]]) -> None:
219
+ """Await *undo* when this plugin is unmounted. The kernel uses
220
+ this for a group that the plugin mounted."""
221
+ self._stack.push_async_callback(undo)
firebox/py.typed ADDED
File without changes