The values of atoms, kept while used.
Attributes#
| Attribute | Type | Description |
|---|---|---|
scheduler | Scheduler = ambient_run(None)[0] if scheduler is None else scheduler | |
default_idle_ttl | float | None = None if default_idle_ttl is None else to_millis(from_input_unsafe(default_idle_ttl)) | |
timeout_resolution | = float(round(self.default_idle_ttl / 2)) | |
nodes | dict[object, Node[Any]] = {} | |
preloaded_serializable | dict[str, object] = {} | |
timeout_buckets | dict[float, tuple[dict[Node[Any], None], Cancel]] = {} | |
node_timeout_bucket | dict[Node[Any], float] = {} | |
disposed | = False | |
on_node_added | Callable[[Node[Any]], None] | None = None | |
on_node_removed | Callable[[Node[Any]], None] | None = None |
Functions#
__init__#
__init__(*, initial_values=None, scheduler=None, timeout_resolution=None, default_idle_ttl=None) -> None| Parameter | Type | Description |
|---|---|---|
initial_values | Iterable[InitialValue[Any]] | None = None | |
scheduler | Scheduler | None = None | |
timeout_resolution | DurationInput | None = None | |
default_idle_ttl | DurationInput | None = None |
def __init__(
self,
*,
initial_values: Iterable[InitialValue[Any]] | None = None,
scheduler: Scheduler | None = None,
timeout_resolution: DurationInput | None = None,
default_idle_ttl: DurationInput | None = None,
) -> None:
self.scheduler: Scheduler = ambient_run(None)[0] if scheduler is None else scheduler
# milliseconds, as Effect keeps them
self.default_idle_ttl: float | None = (
None if default_idle_ttl is None else to_millis(from_input_unsafe(default_idle_ttl))
)
if timeout_resolution is None and self.default_idle_ttl is not None:
self.timeout_resolution = float(round(self.default_idle_ttl / 2))
else:
self.timeout_resolution = (
1000.0
if timeout_resolution is None
else to_millis(from_input_unsafe(timeout_resolution))
)
self.nodes: dict[object, Node[Any]] = {}
self.preloaded_serializable: dict[str, object] = {}
self.timeout_buckets: dict[float, tuple[dict[Node[Any], None], Cancel]] = {}
self.node_timeout_bucket: dict[Node[Any], float] = {}
self.disposed = False
self._current_sweep_ttl: float | None = None
self.on_node_added: Callable[[Node[Any]], None] | None = None
self.on_node_removed: Callable[[Node[Any]], None] | None = None
for entry in initial_values or ():
node = self.ensure_node(_target(entry.atom))
node.set_initial_value(entry.value, entry.skip_initial_run)check_thread#
check_thread() -> NoneRaise RegistryThreadError when another thread is running
this registry's scheduler now. Every entry point calls it.
def check_thread(self) -> None:
"""Raise ``RegistryThreadError`` when another thread is running
this registry's scheduler now. Every entry point calls it."""
scheduler = self.scheduler
if not isinstance(scheduler, Tracking):
return
driver = scheduler.driver()
if driver is not None and driver != threading.get_ident():
current = threading.current_thread().name
raise RegistryThreadError(
f"{self!r} used from thread {current!r} while its scheduler runs on thread "
f"{driver}: a registry runs on one scheduler, so use it from that thread "
"(fx.sync, not fx.blocking)"
)get_nodes#
get_nodes() -> Mapping[object, Node[Any]]The nodes by atom (or by serialization key).
Returns Mapping[object, Node[Any]]
def get_nodes(self) -> Mapping[object, Node[Any]]:
"""The nodes by atom (or by serialization key)."""
self.check_thread()
return self.nodesget#
get[A](atom) -> Aatom's value, building its node (and reading the atom) if
needed; a raise from the atom's read propagates.
Raises RegistryThreadError off the scheduler's thread and
RegistryDisposedError for a new node once disposed.
| Parameter | Type | Description |
|---|---|---|
atom | Atom[A] |
Returns A
def get[A](self, atom: Atom[A]) -> A:
"""``atom``'s value, building its node (and reading the atom) if
needed; a raise from the atom's read propagates.
Raises ``RegistryThreadError`` off the scheduler's thread and
``RegistryDisposedError`` for a new node once disposed."""
return self.ensure_node(atom).value()set#
set[W](atom, value) -> NoneWrites value through atom's write function.
Raises RegistryThreadError off the scheduler's thread and
RegistryDisposedError for a new node once disposed.
| Parameter | Type | Description |
|---|---|---|
atom | Writable[Any, W] | |
value | W |
def set[W](self, atom: Writable[Any, W], value: W) -> None:
"""Writes ``value`` through ``atom``'s write function.
Raises ``RegistryThreadError`` off the scheduler's thread and
``RegistryDisposedError`` for a new node once disposed."""
atom.write(self.ensure_node(atom).write_context, value)set_serializable#
set_serializable(key, encoded) -> NonePreload the encoded value of the serializable atom key; it is
decoded when the atom is first read.
| Parameter | Type | Description |
|---|---|---|
key | str | |
encoded | object |
def set_serializable(self, key: str, encoded: object) -> None:
"""Preload the encoded value of the serializable atom ``key``; it is
decoded when the atom is first read."""
self.check_thread()
self.preloaded_serializable[key] = encodedmodify#
modify[R, W, A](atom, f) -> ACalls f with atom's value, writes the second item it
gives and returns the first.
Raises RegistryThreadError off the scheduler's thread and
RegistryDisposedError for a new node once disposed.
| Parameter | Type | Description |
|---|---|---|
atom | Writable[R, W] | |
f | Callable[[R], tuple[A, W]] |
Returns A
def modify[R, W, A](self, atom: Writable[R, W], f: Callable[[R], tuple[A, W]]) -> A:
"""Calls ``f`` with ``atom``'s value, writes the second item it
gives and returns the first.
Raises ``RegistryThreadError`` off the scheduler's thread and
``RegistryDisposedError`` for a new node once disposed."""
node = self.ensure_node(atom)
result, next_value = f(node.value())
atom.write(node.write_context, next_value)
return resultupdate#
update[R, W](atom, f) -> NoneWrites f of atom's value.
Raises RegistryThreadError off the scheduler's thread and
RegistryDisposedError for a new node once disposed.
| Parameter | Type | Description |
|---|---|---|
atom | Writable[R, W] | |
f | Callable[[R], W] |
def update[R, W](self, atom: Writable[R, W], f: Callable[[R], W]) -> None:
"""Writes ``f`` of ``atom``'s value.
Raises ``RegistryThreadError`` off the scheduler's thread and
``RegistryDisposedError`` for a new node once disposed."""
node = self.ensure_node(atom)
atom.write(node.write_context, f(node.value()))refresh#
refresh(atom) -> NoneRuns atom's own refresh when it has one, else invalidates it
(invalidate_atom), so it is read again.
Raises RegistryThreadError off the scheduler's thread and
RegistryDisposedError for a new node once disposed.
| Parameter | Type | Description |
|---|---|---|
atom | Atom[Any] |
def refresh(self, atom: Atom[Any]) -> None:
"""Runs ``atom``'s own refresh when it has one, else invalidates it
(``invalidate_atom``), so it is read again.
Raises ``RegistryThreadError`` off the scheduler's thread and
``RegistryDisposedError`` for a new node once disposed."""
self.check_thread()
if atom.refresh is not None:
atom.refresh(self.refresh)
else:
self.invalidate_atom(atom)subscribe#
subscribe[A](atom, f, *, immediate=False) -> Callable[[], None]Call f with each new value (and the current one at once with
immediate); returns the function that unsubscribes.
| Parameter | Type | Description |
|---|---|---|
atom | Atom[A] | |
f | Callable[[A], None] | |
immediate | bool = False |
Returns Callable[[], None]
def subscribe[A](
self, atom: Atom[A], f: Callable[[A], None], *, immediate: bool = False
) -> Callable[[], None]:
"""Call ``f`` with each new value (and the current one at once with
``immediate``); returns the function that unsubscribes."""
node = self.ensure_node(atom)
if immediate:
f(node.value())
else:
# Effect 4.1.2: build the node so the listener hears its next
# change. A failed build is left for the next read to report; an
# error raised after the value is committed has no later read to
# report it, so it is re-raised.
try:
node.value()
except Exception:
if not node.state & WAITING_FOR_VALUE:
raise
remove = node.subscribe(lambda: f(node._value))
def cancel() -> None:
remove()
if node.can_be_removed:
self.schedule_node_removal(node)
return cancelmount#
mount(atom) -> Callable[[], None]Keep atom built until the returned function is called.
| Parameter | Type | Description |
|---|---|---|
atom | Atom[Any] |
Returns Callable[[], None]
def mount(self, atom: Atom[Any]) -> Callable[[], None]:
"""Keep ``atom`` built until the returned function is called."""
return self.subscribe(atom, _ignore, immediate=True)atom_has_ttl#
atom_has_ttl(atom) -> boolWhether an unused node of atom lingers for an idle TTL (the
atom's, else the registry's default) before it is removed;
False for a kept-alive atom or a zero TTL.
| Parameter | Type | Description |
|---|---|---|
atom | Atom[Any] |
Returns bool
def atom_has_ttl(self, atom: Atom[Any]) -> bool:
"""Whether an unused node of ``atom`` lingers for an idle TTL (the
atom's, else the registry's default) before it is removed;
``False`` for a kept-alive atom or a zero TTL."""
if atom.kept_alive or (atom.idle_ttl is not None and atom.idle_ttl.is_zero()):
return False
return atom.idle_ttl is not None or self.default_idle_ttl is not Noneensure_node#
ensure_node[A](atom) -> Node[A]atom's node, made (and reported to on_node_added) if
missing; a found node's idle timeout is cancelled. A preloaded
serializable value for the atom is decoded into it.
Raises RegistryThreadError off the scheduler's thread and
RegistryDisposedError for a new node once disposed.
| Parameter | Type | Description |
|---|---|---|
atom | Atom[A] |
Returns Node[A]
def ensure_node[A](self, atom: Atom[A]) -> Node[A]:
"""``atom``'s node, made (and reported to ``on_node_added``) if
missing; a found node's idle timeout is cancelled. A preloaded
serializable value for the atom is decoded into it.
Raises ``RegistryThreadError`` off the scheduler's thread and
``RegistryDisposedError`` for a new node once disposed."""
self.check_thread()
key = _key(atom)
node = self.nodes.get(key)
if node is None:
node = self.create_node(atom)
self.nodes[key] = node
if self.on_node_added is not None:
self.on_node_added(node)
elif self.atom_has_ttl(atom):
self.remove_node_timeout(node)
if isinstance(key, str) and key in self.preloaded_serializable:
self._hydrate(atom, node, self.preloaded_serializable.pop(key))
return nodecreate_node#
create_node[A](atom) -> Node[A]A new node for atom, not yet registered; unless the atom is
kept alive, a removal check is scheduled for it. Raises
RegistryDisposedError once the registry is disposed.
| Parameter | Type | Description |
|---|---|---|
atom | Atom[A] |
Returns Node[A]
def create_node[A](self, atom: Atom[A]) -> Node[A]:
"""A new node for ``atom``, not yet registered; unless the atom is
kept alive, a removal check is scheduled for it. Raises
``RegistryDisposedError`` once the registry is disposed."""
if self.disposed:
raise RegistryDisposedError(f"Cannot access Atom {atom}: registry is disposed")
if not atom.kept_alive:
self.schedule_atom_removal(atom)
return Node(self, atom)invalidate_atom#
invalidate_atom(atom) -> NoneMarks atom's node stale, releasing its current build, so the
next read rebuilds it (and runs an effect skipped for an initial
value); its dependents are invalidated too.
Raises RegistryThreadError off the scheduler's thread and
RegistryDisposedError for a new node once disposed.
| Parameter | Type | Description |
|---|---|---|
atom | Atom[Any] |
def invalidate_atom(self, atom: Atom[Any]) -> None:
"""Marks ``atom``'s node stale, releasing its current build, so the
next read rebuilds it (and runs an effect skipped for an initial
value); its dependents are invalidated too.
Raises ``RegistryThreadError`` off the scheduler's thread and
``RegistryDisposedError`` for a new node once disposed."""
node = self.ensure_node(atom)
node.skip_initial_run = False
node.invalidate()schedule_atom_removal#
schedule_atom_removal(atom) -> NoneOn the scheduler's next turn, removes atom's node
(remove_node) if nothing uses it then.
| Parameter | Type | Description |
|---|---|---|
atom | Atom[Any] |
def schedule_atom_removal(self, atom: Atom[Any]) -> None:
"""On the scheduler's next turn, removes ``atom``'s node
(``remove_node``) if nothing uses it then."""
def remove() -> None:
node = self.nodes.get(_key(atom))
if node is not None and node.can_be_removed:
self.remove_node(node)
self.scheduler.schedule(remove)schedule_node_removal#
schedule_node_removal(node) -> NoneOn the scheduler's next turn, removes node (remove_node)
if nothing uses it then.
| Parameter | Type | Description |
|---|---|---|
node | Node[Any] |
def schedule_node_removal(self, node: Node[Any]) -> None:
"""On the scheduler's next turn, removes ``node`` (``remove_node``)
if nothing uses it then."""
def remove() -> None:
if node.can_be_removed:
self.remove_node(node)
self.scheduler.schedule(remove)remove_node#
remove_node(node) -> NoneRemoves node now, running its finalizers and reporting it to
on_node_removed, or, when its atom has an idle TTL, starts its
timeout (set_node_timeout).
| Parameter | Type | Description |
|---|---|---|
node | Node[Any] |
def remove_node(self, node: Node[Any]) -> None:
"""Removes ``node`` now, running its finalizers and reporting it to
``on_node_removed``, or, when its atom has an idle TTL, starts its
timeout (``set_node_timeout``)."""
if self.atom_has_ttl(node.atom):
self.set_node_timeout(node)
else:
self._forget(node)
node.remove()
if self.on_node_removed is not None:
self.on_node_removed(node)set_node_timeout#
set_node_timeout(node) -> NoneSchedules node's removal once its idle TTL, rounded up to the
timeout resolution, has passed (nodes due together share a timer).
Nothing happens if it already has a timeout. During a sweep, the
time already waited counts, so a node due by then is removed now.
| Parameter | Type | Description |
|---|---|---|
node | Node[Any] |
def set_node_timeout(self, node: Node[Any]) -> None:
"""Schedules ``node``'s removal once its idle TTL, rounded up to the
timeout resolution, has passed (nodes due together share a timer).
Nothing happens if it already has a timeout. During a sweep, the
time already waited counts, so a node due by then is removed now."""
if node in self.node_timeout_bucket:
return
idle_ttl = self._idle_ttl_millis(node.atom)
if self._current_sweep_ttl is not None:
idle_ttl -= self._current_sweep_ttl
if idle_ttl <= 0:
self._forget(node)
node.remove()
if self.on_node_removed is not None:
self.on_node_removed(node)
return
resolution = self.timeout_resolution
ttl = math.ceil(idle_ttl / resolution) * resolution
timestamp = now_millis() + ttl
bucket = timestamp - (timestamp % resolution) + resolution
entry = self.timeout_buckets.get(bucket)
if entry is None:
delay = millis(bucket - now_millis())
nodes: dict[Node[Any], None] = {}
entry = (nodes, self.scheduler.call_later(delay, lambda: self.sweep_bucket(bucket)))
self.timeout_buckets[bucket] = entry
entry[0][node] = None
self.node_timeout_bucket[node] = bucketremove_node_timeout#
remove_node_timeout(node) -> NoneCancels node's idle timeout, if it has one, and schedules a
removal check (schedule_node_removal) in its place.
| Parameter | Type | Description |
|---|---|---|
node | Node[Any] |
def remove_node_timeout(self, node: Node[Any]) -> None:
"""Cancels ``node``'s idle timeout, if it has one, and schedules a
removal check (``schedule_node_removal``) in its place."""
bucket = self.node_timeout_bucket.pop(node, None)
if bucket is None:
return
self.schedule_node_removal(node)
nodes, cancel = self.timeout_buckets[bucket]
nodes.pop(node, None)
if not nodes:
cancel()
del self.timeout_buckets[bucket]sweep_bucket#
sweep_bucket(bucket) -> NoneRemoves the idle nodes whose timeouts end at bucket (the
timer's millisecond timestamp), each with remove_idle_node.
| Parameter | Type | Description |
|---|---|---|
bucket | float |
def sweep_bucket(self, bucket: float) -> None:
"""Removes the idle nodes whose timeouts end at ``bucket`` (the
timer's millisecond timestamp), each with ``remove_idle_node``."""
nodes = self.timeout_buckets.pop(bucket)[0]
run_all(list(nodes), self.remove_idle_node)remove_idle_node#
remove_idle_node(node) -> NoneRemoves node after its idle timeout, running its finalizers
and reporting it to on_node_removed, unless it is in use
again.
| Parameter | Type | Description |
|---|---|---|
node | Node[Any] |
def remove_idle_node(self, node: Node[Any]) -> None:
"""Removes ``node`` after its idle timeout, running its finalizers
and reporting it to ``on_node_removed``, unless it is in use
again."""
self.node_timeout_bucket.pop(node, None)
if not node.can_be_removed:
return
self._forget(node)
if self.on_node_removed is not None:
self.on_node_removed(node)
self._current_sweep_ttl = self._idle_ttl_millis(node.atom)
try:
node.remove()
finally:
self._current_sweep_ttl = Nonereset#
reset() -> NoneRemove every node, running their finalizers.
def reset(self) -> None:
"""Remove every node, running their finalizers."""
self.check_thread()
for _, cancel in self.timeout_buckets.values():
cancel()
self.timeout_buckets.clear()
self.node_timeout_bucket.clear()
nodes = list(self.nodes.values())
self.nodes.clear()
# Mark every node before removing any, so a parent cannot be
# rescheduled for removal.
for node in nodes:
node.state = REMOVED
run_all(nodes, self.destroy_node)destroy_node#
destroy_node(node) -> NoneRemoves node now, running its finalizers, and reports it to
on_node_removed (as reset does for every node).
| Parameter | Type | Description |
|---|---|---|
node | Node[Any] |
def destroy_node(self, node: Node[Any]) -> None:
"""Removes ``node`` now, running its finalizers, and reports it to
``on_node_removed`` (as ``reset`` does for every node)."""
node.remove()
if self.on_node_removed is not None:
self.on_node_removed(node)dispose#
dispose() -> Nonereset, and refuse new nodes from now on.
def dispose(self) -> None:
"""``reset``, and refuse new nodes from now on."""
self.check_thread()
self.disposed = True
self.reset()fork#
fork[A, E](effect, context) -> Fiber[A, E]Run effect with context on a fiber of this registry's
scheduler, at once, up to its first wait: what it yields runs
before this returns (Effect's runForkWith and dispatcher
flush, _dispatcher.py).
| Parameter | Type | Description |
|---|---|---|
effect | Effect[A, E, Any] | |
context | Context[Any] |
Returns Fiber[A, E]
def fork[A, E](self, effect: Effect[A, E, Any], context: Context[Any]) -> Fiber[A, E]:
"""Run ``effect`` with ``context`` on a fiber of this registry's
scheduler, at once, up to its first wait: what it yields runs
before this returns (Effect's ``runForkWith`` and dispatcher
flush, ``_dispatcher.py``)."""
require_effect(effect, "effect")
self.check_thread()
dispatcher = Dispatcher(self.scheduler)
fiber: Fiber[A, E] = new_root(self.scheduler, context, scheduler=dispatcher)
dispatcher.run_flushed(lambda: start_root(fiber, effect, now=True))
return fiberOn This Page
AttributesFunctions__init__check_threadget_nodesgetsetset_serializablemodifyupdaterefreshsubscribemountatom_has_ttlensure_nodecreate_nodeinvalidate_atomschedule_atom_removalschedule_node_removalremove_nodeset_node_timeoutremove_node_timeoutsweep_bucketremove_idle_noderesetdestroy_nodedisposefork