pycordis2 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.
pycordis/__init__.py ADDED
@@ -0,0 +1,51 @@
1
+ """Plugin and service composition from revertible effects.
2
+
3
+ pycordis composes plugins and services from revertible effects and declared
4
+ dependencies. A component declares what it needs before it loads, and disposing a
5
+ component reverts the effects it registered.
6
+
7
+ Start with `Context`: create a root context with a scheduler (`ImmediateScheduler` or
8
+ `FramePumpScheduler`), then call `Context.use` to run a component in a `Fiber`.
9
+ A `Service` and a `Key` give a component access to the services of other components.
10
+
11
+ Attributes:
12
+ __version__: The version of the installed distribution `pycordis2`, which
13
+ provides the `pycordis` package.
14
+ """
15
+
16
+ import importlib.metadata
17
+
18
+ from pycordis.context import Context
19
+ from pycordis.deferred import Deferred
20
+ from pycordis.errors import CordisError, Issue, ValidationError
21
+ from pycordis.fiber import Disposer, EffectHandle, Fiber, FiberState
22
+ from pycordis.keys import Key, Keyable
23
+ from pycordis.registry import Component, inject
24
+ from pycordis.scheduler import FramePumpScheduler, ImmediateScheduler, Scheduler
25
+ from pycordis.service import Service
26
+
27
+ # The import needs an installed distribution (`uv sync` installs it). There is no
28
+ # fallback: pyproject.toml holds the placeholder 0.0.0, so a fallback would report a
29
+ # false version. The distribution name differs from the import name.
30
+ __version__ = importlib.metadata.version("pycordis2")
31
+
32
+ __all__ = [
33
+ "Component",
34
+ "Context",
35
+ "CordisError",
36
+ "Deferred",
37
+ "Disposer",
38
+ "EffectHandle",
39
+ "Fiber",
40
+ "FiberState",
41
+ "FramePumpScheduler",
42
+ "ImmediateScheduler",
43
+ "Issue",
44
+ "Key",
45
+ "Keyable",
46
+ "Scheduler",
47
+ "Service",
48
+ "ValidationError",
49
+ "__version__",
50
+ "inject",
51
+ ]
pycordis/context.py ADDED
@@ -0,0 +1,577 @@
1
+ """Contexts.
2
+
3
+ A `Context` is the handle through which code registers effects. Derived contexts share
4
+ the fiber and the scheduler of their parent, and carry their own isolation, intercept,
5
+ and meta tables. Start with `Context(scheduler)` to create a root context.
6
+ """
7
+
8
+ from collections import ChainMap
9
+ from collections.abc import Callable, Iterable, Mapping
10
+ from types import MappingProxyType
11
+ from typing import Any, Self
12
+
13
+ from pycordis.deferred import Deferred
14
+ from pycordis.errors import CallSite
15
+ from pycordis.events import EventName, EventOptions, EventsService, Listener
16
+ from pycordis.fiber import EffectForm, EffectHandle, Fiber, resolve_config
17
+ from pycordis.keys import Keyable
18
+ from pycordis.logger import LoggerService
19
+ from pycordis.reflect import Accessor, ReflectService
20
+ from pycordis.registry import Component, RegistryService
21
+ from pycordis.scheduler import Scheduler, owner_thread
22
+ from pycordis.traceable import get_traceable
23
+
24
+
25
+ def _run_update_hooks(fiber: Fiber, config: object, next_: Callable[[], Any]) -> Any:
26
+ """Run the `internal/update` listeners of `fiber`, and then the rest of the chain.
27
+
28
+ A listener that a fiber registered belongs to that fiber, so the chain of an update
29
+ contains only the listeners of the fiber that updates. A listener that another
30
+ listener removes during the chain is skipped.
31
+ """
32
+ hooks = list(fiber.update_hooks)
33
+
34
+ def advance() -> Any:
35
+ if not hooks:
36
+ return next_()
37
+ return hooks.pop(0)(fiber, config, advance)
38
+
39
+ return advance()
40
+
41
+
42
+ class Context:
43
+ """The place from which code registers effects.
44
+
45
+ A root context owns the root fiber. `extend`, `isolate`, and `intercept` return new
46
+ contexts that point to their parent: the parent does not change, and a table
47
+ lookup reads the nearest context that has the key.
48
+
49
+ Call context methods on the owner thread of the root context, which is the thread
50
+ that created it. A call from another thread raises `CordisError("WRONG_THREAD")`.
51
+ To hand work to the owner thread, use `Scheduler.submit`.
52
+
53
+ Examples:
54
+ ```python
55
+ >>> ctx = Context(ImmediateScheduler())
56
+ >>> handle = ctx.effect(lambda: lambda: print("reverted"))
57
+ >>> handle()
58
+ reverted
59
+ ```
60
+
61
+ Attributes:
62
+ scheduler: The scheduler that runs the work of the root context.
63
+ root: The root context.
64
+ fiber: The fiber that owns the effects that this context registers.
65
+ events: The service that stores the listeners of the root context. Every
66
+ derived context shares it.
67
+ reflect: The service that stores the providers and accessors of the root
68
+ context. Every derived context shares it.
69
+ registry: The service that records the loaded components of the root context.
70
+ Every derived context shares it.
71
+ """
72
+
73
+ def __init__(self, scheduler: Scheduler) -> None:
74
+ self.scheduler = scheduler
75
+ self.root: Self = self
76
+ self._isolates: ChainMap[str, object] = ChainMap()
77
+ self._intercepts: ChainMap[str, object] = ChainMap()
78
+ self._meta: ChainMap[str, object] = ChainMap()
79
+ self._shadow: Context | None = None
80
+ self._use_site: Context | None = None
81
+ self.events = EventsService(scheduler)
82
+ self.reflect = ReflectService(scheduler)
83
+ self.registry = RegistryService(scheduler)
84
+ self.fiber = Fiber(self)
85
+ self._logger = LoggerService(self)
86
+ self.events.install(
87
+ self,
88
+ "internal/config",
89
+ lambda fiber, next_: resolve_config(fiber.runtime.config, next_()),
90
+ )
91
+ self.events.install(self, "internal/listener", self._route_update_listener)
92
+ self.events.install(self, "internal/update", _run_update_hooks, prepend=True)
93
+
94
+ def __repr__(self) -> str:
95
+ return f"Context <{self.fiber.name}>"
96
+
97
+ @property
98
+ def logger(self) -> LoggerService:
99
+ """The logging service of the root context, as this context sees it.
100
+
101
+ Call it to get a `Logger`, or log through it directly. A call from a service
102
+ method names the logger after the service. See `LoggerService`.
103
+ """
104
+ return get_traceable(self, self.root._logger)
105
+
106
+ @staticmethod
107
+ def _route_update_listener(
108
+ ctx: "Context", name: EventName, listener: Listener, options: EventOptions
109
+ ) -> EffectHandle | None:
110
+ """Keep an `internal/update` listener on the fiber that registers it."""
111
+ if name != "internal/update" or options.is_global:
112
+ return None
113
+
114
+ def setup() -> Callable[[], None]:
115
+ removed = False
116
+
117
+ def guarded(fiber: Fiber, config: object, next_: Callable[[], Any]) -> Any:
118
+ return next_() if removed else listener(fiber, config, next_)
119
+
120
+ hooks = ctx.fiber.update_hooks
121
+ remove = hooks.unshift(guarded) if options.prepend else hooks.push(guarded)
122
+
123
+ def revert() -> None:
124
+ nonlocal removed
125
+ removed = True
126
+ remove()
127
+
128
+ return revert
129
+
130
+ return ctx.fiber.effect(setup, 'ctx.on("internal/update")')
131
+
132
+ @property
133
+ def shadow(self) -> "Context | None":
134
+ """The def-site context, or `None`.
135
+
136
+ A service method runs with a context that acts for the caller (the use site) and
137
+ resolves services as the context of the service (the def site) would. This is
138
+ that def-site context. A context that is not such a context gives `None`.
139
+ """
140
+ return self._shadow
141
+
142
+ @property
143
+ def use_site(self) -> Self:
144
+ """This context without its `shadow`.
145
+
146
+ The methods that create fibers, providers, and listeners act on it, so that
147
+ nothing registered keeps a def-site link.
148
+ """
149
+ return self if self._use_site is None else self._use_site
150
+
151
+ def with_shadow(self, def_site: "Context") -> Self:
152
+ """Return a context that acts for this one and resolves services at `def_site`.
153
+
154
+ Only `ctx[key]` reads the def site. Isolation, intercept, effects, and every
155
+ other method are those of this context. A context derived from the result keeps
156
+ the def site.
157
+ """
158
+ use_site = self.use_site
159
+ shadowed = object.__new__(type(self))
160
+ shadowed.__dict__.update(use_site.__dict__)
161
+ shadowed._shadow = def_site
162
+ shadowed._use_site = use_site
163
+ return shadowed
164
+
165
+ @property
166
+ def isolates(self) -> Mapping[str, object]:
167
+ """The isolation labels by service name, as a read-only mapping."""
168
+ return MappingProxyType(self._isolates)
169
+
170
+ @property
171
+ def intercepts(self) -> Mapping[str, object]:
172
+ """The intercept configurations by service name, as a read-only mapping."""
173
+ return MappingProxyType(self._intercepts)
174
+
175
+ @property
176
+ def meta(self) -> Mapping[str, object]:
177
+ """The values that `extend` added, as a read-only mapping."""
178
+ return MappingProxyType(self._meta)
179
+
180
+ def isolated_since(self, name: str, ancestor: "Context") -> bool:
181
+ """Return whether a context between `ancestor` and this one isolates `name`.
182
+
183
+ Args:
184
+ name: The service name.
185
+ ancestor: A context that this context derives from, or this context.
186
+ """
187
+ extra = len(self._isolates.maps) - len(ancestor._isolates.maps)
188
+ return any(name in layer for layer in self._isolates.maps[:extra])
189
+
190
+ def intercept_layers(self, name: str) -> list[object]:
191
+ """Return the intercept configurations of `name`, from the outermost context in.
192
+
193
+ Each context that called `intercept` for `name` adds one entry.
194
+ """
195
+ return [
196
+ layer[name] for layer in reversed(self._intercepts.maps) if name in layer
197
+ ]
198
+
199
+ def bind_fiber(self, fiber: Fiber) -> Self:
200
+ """Return a child context whose fiber is `fiber`.
201
+
202
+ A `Fiber` calls it for the context that its component receives.
203
+ """
204
+ return self.use_site._derive(
205
+ self._isolates, self._intercepts, self._meta, fiber
206
+ )
207
+
208
+ def declare_realm(self, name: str) -> None:
209
+ """Give the service `name` a default realm in the root context if it has none.
210
+
211
+ The default realm is shared by every context that does not isolate `name`. It is
212
+ stored in the root context, so a later `isolate` call hides it.
213
+ """
214
+ self.root._isolates.setdefault(name, object())
215
+
216
+ @owner_thread("scheduler")
217
+ def extend(self, **meta: object) -> Self:
218
+ """Return a child context that adds `meta` to its `meta` mapping.
219
+
220
+ A name in `meta` hides the same name in the parent's mapping.
221
+ """
222
+ return self._derive(
223
+ self._isolates, self._intercepts, self._meta.new_child(meta)
224
+ )
225
+
226
+ @owner_thread("scheduler")
227
+ def isolate(self, name: str, label: object | None = None) -> Self:
228
+ """Return a child context whose service `name` is separate from the parent's.
229
+
230
+ Contexts with the same label share the service. The default label is a new
231
+ object, so the child context has a realm of its own.
232
+
233
+ Args:
234
+ name: The service name.
235
+ label: The identity of the realm, or `None` for a new realm.
236
+ """
237
+ realm = object() if label is None else label
238
+ return self._derive(
239
+ self._isolates.new_child({name: realm}), self._intercepts, self._meta
240
+ )
241
+
242
+ @owner_thread("scheduler")
243
+ def intercept(self, name: str, config: object) -> Self:
244
+ """Return a child context that passes `config` to the service `name`."""
245
+ return self._derive(
246
+ self._isolates, self._intercepts.new_child({name: config}), self._meta
247
+ )
248
+
249
+ @owner_thread("scheduler")
250
+ def effect(
251
+ self, execute: Callable[[], EffectForm], label: str = "anonymous"
252
+ ) -> EffectHandle:
253
+ """Run `execute` and register its inverses on this context's fiber.
254
+
255
+ The fiber reverts them when it unloads. See `Fiber.effect` for the forms that
256
+ `execute` can return.
257
+
258
+ Args:
259
+ execute: The setup function.
260
+ label: The name that `Fiber.get_effects` reports.
261
+
262
+ Returns:
263
+ The handle of the effect. Call it to revert the effect now.
264
+
265
+ Raises:
266
+ CordisError: If the fiber is disposed.
267
+ TypeError: If `execute` returns an invalid effect.
268
+ """
269
+ with self.scheduler.call():
270
+ return self.fiber.effect(execute, label, call_site=CallSite.capture(skip=1))
271
+
272
+ @owner_thread("scheduler")
273
+ def use(self, component: Component, config: object = None) -> Fiber:
274
+ """Run `component` in a new fiber that this context's fiber owns.
275
+
276
+ The fiber loads when every service in the component's `inject` has a provider,
277
+ and it ends when this context's fiber ends. Inside a task, the call returns
278
+ before the component runs; await the fiber to wait for the load.
279
+
280
+ Args:
281
+ component: A function `(ctx, config)`, a class whose constructor takes
282
+ `(ctx, config)`, or an object with an `apply(ctx, config)` method.
283
+ config: The raw config. The component's `Config` validates it.
284
+
285
+ Returns:
286
+ The new fiber. A task can `await` it.
287
+
288
+ Raises:
289
+ TypeError: If `component` is not a valid component.
290
+ CordisError: If this context's fiber is disposed.
291
+
292
+ Examples:
293
+ ```python
294
+ >>> def greet(ctx, config):
295
+ ... print("hello", config)
296
+ ... return lambda: print("bye", config)
297
+ >>> fiber = ctx.use(greet, "world")
298
+ hello world
299
+ >>> _ = fiber.dispose()
300
+ bye world
301
+ ```
302
+ """
303
+ with self.scheduler.call():
304
+ return self.registry.use(
305
+ self.use_site, component, config, CallSite.capture(skip=1)
306
+ )
307
+
308
+ @owner_thread("scheduler")
309
+ def inject(self, deps: object, callback: Callable[["Context"], Any]) -> Fiber:
310
+ """Run `callback(ctx)` in a new fiber that requires the services `deps`.
311
+
312
+ Args:
313
+ deps: Service names or keys, or a dict from a name to its intercept
314
+ configuration.
315
+ callback: The function to run. It gets the context of the new fiber and
316
+ can return an effect.
317
+
318
+ Returns:
319
+ The new fiber.
320
+ """
321
+ with self.scheduler.call():
322
+ return self.registry.inject(
323
+ self.use_site, deps, callback, CallSite.capture(skip=1)
324
+ )
325
+
326
+ def __getitem__(self, key: Keyable[Any]) -> Any:
327
+ """Return the value that the accessor or the service `key` gives.
328
+
329
+ An accessor takes precedence over a service of the same name. At the root, the
330
+ access is unchecked: it gives the value of the provider whatever the state of
331
+ the provider's fiber, or `None` when no provider is visible.
332
+
333
+ A context that belongs to a component's fiber reads only the services that the
334
+ fiber or one of its ancestors injects or provides.
335
+
336
+ Raises:
337
+ CordisError: In a component's context, if no fiber injects the service, or
338
+ if the fiber that injects it is not loaded.
339
+ TypeError: If `key` is neither a `Key` nor a `str`.
340
+ """
341
+ return self.reflect.read(self, key)
342
+
343
+ def __setitem__(self, key: Keyable[Any], value: Any) -> None:
344
+ """Set the value of the accessor or the service `key`.
345
+
346
+ Raises:
347
+ CordisError: If `key` is an accessor without a setter, or if no service
348
+ `key` is provided.
349
+ TypeError: If `key` is neither a `Key` nor a `str`.
350
+ """
351
+ self.reflect.write(self, key, value)
352
+
353
+ @owner_thread("scheduler")
354
+ def get[T](self, key: Keyable[T], strict: bool = True) -> T | None:
355
+ """Return the value of the service `key`, or `None`.
356
+
357
+ Args:
358
+ key: The service key.
359
+ strict: When true, a provider whose fiber is not `ACTIVE` gives `None`.
360
+
361
+ Returns:
362
+ The value that the provider holds. `None` when no provider is visible from
363
+ this context, or when `strict` hides the provider.
364
+ """
365
+ return self.reflect.get(self, key, strict)
366
+
367
+ @owner_thread("scheduler")
368
+ def set[T](self, key: Keyable[T], value: T) -> None:
369
+ """Replace the value of the service `key` that this context sees.
370
+
371
+ Raises:
372
+ CordisError: If no service `key` is provided.
373
+ """
374
+ self.reflect.set(self, key, value)
375
+
376
+ @owner_thread("scheduler")
377
+ def provide[T](
378
+ self,
379
+ key: Keyable[T],
380
+ value: T | None = None,
381
+ check: Callable[[T], bool] | None = None,
382
+ ) -> EffectHandle:
383
+ """Make `value` available as the service `key`.
384
+
385
+ The service belongs to this context's fiber: the fiber removes it when it
386
+ unloads. The removal waits until the fibers that depend on the service have
387
+ unloaded. A context whose realm for `key` is isolated has its own providers.
388
+
389
+ Args:
390
+ key: The service key.
391
+ value: The service value. Replace it later with `set`.
392
+ check: Called with the value, as the context of a fiber that injects
393
+ `key` sees it, when that fiber looks for its provider. The fiber does
394
+ not use this provider while the call returns a false value or raises.
395
+
396
+ Returns:
397
+ The handle of the effect. Call it to remove the service.
398
+
399
+ Raises:
400
+ CordisError: If the realm already has a provider of `key`, or if `key`
401
+ is declared as an accessor.
402
+
403
+ Examples:
404
+ ```python
405
+ >>> remove = ctx.provide("db", {"rows": 0})
406
+ >>> ctx.get("db")
407
+ {'rows': 0}
408
+ >>> remove()
409
+ ```
410
+ """
411
+ return self.reflect.provide(self.use_site, key, value, check)
412
+
413
+ @owner_thread("scheduler")
414
+ def accessor(
415
+ self,
416
+ key: Keyable[Any],
417
+ get: Callable[["Context", Any], Any],
418
+ set: Callable[["Context", Any, Any], None] | None = None,
419
+ ) -> EffectHandle:
420
+ """Compute the value of `ctx[key]` with `get`.
421
+
422
+ Args:
423
+ key: The property name.
424
+ get: Called with the context that is read and the receiver. It gives the
425
+ value. The receiver is the traceable view through which an associated
426
+ access came (see `Tracker`), or `None` for `ctx[key]`.
427
+ set: Called with the context, the new value, and the receiver on
428
+ `ctx[key] = value`. Without it, an assignment raises `CordisError`.
429
+
430
+ Returns:
431
+ The handle of the effect. Call it to remove the accessor.
432
+
433
+ Raises:
434
+ CordisError: If `key` is already declared as a service or an accessor.
435
+ """
436
+ return self.reflect.accessor(self.use_site, key, Accessor(get, set))
437
+
438
+ @owner_thread("scheduler")
439
+ def mixin(
440
+ self, source: Keyable[Any], mixins: Iterable[str] | Mapping[str, str]
441
+ ) -> EffectHandle:
442
+ """Expose attributes of the service `source` as properties of the context.
443
+
444
+ After the call, `ctx[name]` reads the attribute `name` of `ctx[source]`, and
445
+ `ctx[name] = value` sets it. A mapping gives the attribute name as the key and
446
+ the property name as the value.
447
+
448
+ Args:
449
+ source: The key of the service that has the attributes.
450
+ mixins: The attribute names, or a mapping from attribute name to property
451
+ name.
452
+
453
+ Returns:
454
+ The handle of the effect. Call it to remove the accessors.
455
+
456
+ Raises:
457
+ CordisError: If a property name is already declared.
458
+ """
459
+ return self.reflect.mixin(self.use_site, source, mixins)
460
+
461
+ @owner_thread("scheduler")
462
+ def on(
463
+ self,
464
+ name: EventName,
465
+ listener: Listener,
466
+ options: EventOptions | bool = False,
467
+ ) -> EffectHandle:
468
+ """Register `listener` for the event `name` on this context's fiber.
469
+
470
+ The fiber removes the listener when it unloads.
471
+
472
+ Args:
473
+ name: The event name.
474
+ listener: The function to call with the arguments of the event. An
475
+ argument that has a `Tracker` reaches it as its view for this
476
+ context, so its effects belong to this context's fiber.
477
+ options: The `EventOptions`, or a `bool` for `prepend`.
478
+
479
+ Returns:
480
+ The handle of the effect. Call it to remove the listener.
481
+
482
+ Raises:
483
+ CordisError: If the fiber is disposed.
484
+
485
+ Examples:
486
+ ```python
487
+ >>> remove = ctx.on("greet", lambda who: print("hello", who))
488
+ >>> ctx.emit("greet", "world")
489
+ hello world
490
+ >>> remove()
491
+ ```
492
+ """
493
+ return self.events.on(self.use_site, name, listener, options)
494
+
495
+ @owner_thread("scheduler")
496
+ def once(
497
+ self,
498
+ name: EventName,
499
+ listener: Listener,
500
+ options: EventOptions | bool = False,
501
+ ) -> EffectHandle:
502
+ """Register `listener` for the event `name`, and remove it after its first call.
503
+
504
+ The arguments and the result are those of `on`.
505
+ """
506
+ return self.events.once(self.use_site, name, listener, options)
507
+
508
+ @owner_thread("scheduler")
509
+ def emit(self, name: EventName, *args: Any, this: object = None) -> None:
510
+ """Call every listener of `name` with `args`, and ignore the results.
511
+
512
+ Args:
513
+ name: The event name.
514
+ *args: The arguments for the listeners.
515
+ this: An object with a `cordis_filter(ctx)` method that selects the
516
+ listeners by the context that registered them.
517
+ """
518
+ self.events.emit(name, *args, this=this)
519
+
520
+ @owner_thread("scheduler")
521
+ def bail(self, name: EventName, *args: Any, this: object = None) -> Any:
522
+ """Call the listeners in order, and return the first result that is not
523
+ `None` or `False`.
524
+
525
+ The arguments are those of `emit`.
526
+ """
527
+ return self.events.bail(name, *args, this=this)
528
+
529
+ @owner_thread("scheduler")
530
+ def serial(self, name: EventName, *args: Any, this: object = None) -> Deferred[Any]:
531
+ """Call the listeners one after another, and wait for each result.
532
+
533
+ The arguments are those of `emit`. The result is a `Deferred` of the first
534
+ result that is not `None` or `False`.
535
+ """
536
+ return self.events.serial(name, *args, this=this)
537
+
538
+ @owner_thread("scheduler")
539
+ def parallel(
540
+ self, name: EventName, *args: Any, this: object = None
541
+ ) -> Deferred[None]:
542
+ """Start every listener, and wait until all of them finish.
543
+
544
+ The arguments are those of `emit`. The `Deferred` rejects with an
545
+ `ExceptionGroup` when any listener fails.
546
+ """
547
+ return self.events.parallel(name, *args, this=this)
548
+
549
+ @owner_thread("scheduler")
550
+ def waterfall(self, name: EventName, *args: Any, this: object = None) -> Any:
551
+ """Run the listeners as a chain around the final function in `args[-1]`.
552
+
553
+ Each listener receives the other arguments and a `next` function that runs the
554
+ rest of the chain. See `EventsService.waterfall`.
555
+ """
556
+ return self.events.waterfall(name, *args, this=this)
557
+
558
+ def _derive(
559
+ self,
560
+ isolates: ChainMap[str, object],
561
+ intercepts: ChainMap[str, object],
562
+ meta: ChainMap[str, object],
563
+ fiber: Fiber | None = None,
564
+ ) -> Self:
565
+ child = object.__new__(type(self))
566
+ child.scheduler = self.scheduler
567
+ child.root = self.root
568
+ child.fiber = self.fiber if fiber is None else fiber
569
+ child.events = self.events
570
+ child.reflect = self.reflect
571
+ child.registry = self.registry
572
+ child._isolates = isolates
573
+ child._intercepts = intercepts
574
+ child._meta = meta
575
+ child._shadow = None
576
+ child._use_site = None
577
+ return child if self._shadow is None else child.with_shadow(self._shadow)