Repository navigation
Startup ordering #397
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rwb27
wants to merge
11
commits into
main
Choose a base branch
from
startup-ordering
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Startup ordering #397
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
5ae6f35
Add a filter by type option to `class_attributes`
rwb27 aa8fc5d
Allow thing slots to determine start-up order
rwb27 1932780
Add a test for startup ordering.
rwb27 60373f8
Rename start_first to deferred
rwb27 baae06c
Update docs with example and new argument
rwb27 cbc2952
Ignore self-dependencies
rwb27 ade0a3a
Typing fixes
rwb27 5230255
Fully cover the diff
rwb27 4501128
Fix comments and print statements from review.
rwb27 113d565
Make ordering more deterministic.
rwb27 3638c11
Change the argument name (back) to `start_before`
rwb27 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -47,7 +47,12 @@ def say_hello(self) -> str: | |||||
| from weakref import ReferenceType, WeakKeyDictionary, WeakValueDictionary, ref | ||||||
|
|
||||||
| from labthings_fastapi.base_descriptor import FieldTypedBaseDescriptor | ||||||
| from labthings_fastapi.exceptions import ThingNotConnectedError, ThingSlotError | ||||||
| from labthings_fastapi.exceptions import ( | ||||||
| ThingNotConnectedError, | ||||||
| ThingSlotCircularDependencyError, | ||||||
| ThingSlotError, | ||||||
| ) | ||||||
| from labthings_fastapi.utilities import class_attributes | ||||||
|
|
||||||
| if TYPE_CHECKING: | ||||||
| from labthings_fastapi.thing import Thing | ||||||
|
|
@@ -102,9 +107,12 @@ class Example(lt.Thing): | |||||
| """ | ||||||
|
|
||||||
| def __init__( | ||||||
| self, *, default: str | None | Iterable[str] | EllipsisType = ... | ||||||
| self, | ||||||
| *, | ||||||
| default: str | None | Iterable[str] | EllipsisType = ..., | ||||||
| start_before: bool = False, | ||||||
| ) -> None: | ||||||
| """Declare a ThingSlot. | ||||||
| r"""Declare a ThingSlot. | ||||||
|
|
||||||
| :param default: The name of the Thing(s) that will be connected by default. | ||||||
|
|
||||||
|
|
@@ -118,12 +126,24 @@ def __init__( | |||||
|
|
||||||
| If the type is a mapping of `str` to `~lt.Thing` the default should be | ||||||
| of type `Iterable[str]` (and could be an empty list). | ||||||
| :param start_before: Whether the connected Thing(s) should be started before | ||||||
| the Thing on which the slot is defined. | ||||||
|
|
||||||
| When this is `False` (the default), there's no constraint on the order | ||||||
| in which things will be started: it's assumed the slot will not be | ||||||
| accessed until all Things have started. | ||||||
|
|
||||||
| If `start_before` is set to `False` then LabThings | ||||||
| will ensure the connected Thing(s) have ``__enter__`` called before it | ||||||
| is called on this Thing, i.e. it's safe to use the slot during | ||||||
| ``__enter__``\ . | ||||||
| """ | ||||||
| super().__init__() | ||||||
| self._default = default | ||||||
| self._things: WeakKeyDictionary[ | ||||||
| "Thing", ReferenceType["Thing"] | WeakValueDictionary[str, "Thing"] | None | ||||||
| ] = WeakKeyDictionary() | ||||||
| self._start_before = start_before | ||||||
|
|
||||||
| @property | ||||||
| def thing_type(self) -> tuple[type, ...]: | ||||||
|
|
@@ -165,6 +185,11 @@ def default(self) -> str | Iterable[str] | None | EllipsisType: | |||||
| """The name of the Thing that will be connected by default, if any.""" | ||||||
| return self._default | ||||||
|
|
||||||
| @property | ||||||
| def start_before(self) -> bool: | ||||||
| """Whether the connected Things must be started before this one.""" | ||||||
|
rwb27 marked this conversation as resolved.
Resolved
|
||||||
| return self._start_before | ||||||
|
|
||||||
| def _pick_things( | ||||||
| self, | ||||||
| things: "Mapping[str, Thing]", | ||||||
|
|
@@ -338,8 +363,77 @@ def instance_get(self, obj: "Thing") -> ConnectedThings: | |||||
| return val # type: ignore[return-value] | ||||||
| # See docstring for an explanation of the type ignore directives. | ||||||
|
|
||||||
| def _connected_thing_names(self, obj: "Thing") -> set[str]: | ||||||
| """Return the names of the Thing(s) connected to this slot. | ||||||
|
|
||||||
| :param obj: the Thing instance we're considering. | ||||||
| :return: a set of Thing names that are connected. | ||||||
| """ | ||||||
| val = self.instance_get(obj) | ||||||
| if val is None: | ||||||
| return set() | ||||||
| if isinstance(val, Mapping): | ||||||
| return set(val.keys()) | ||||||
| else: | ||||||
| return {val.name} | ||||||
|
|
||||||
| def thing_slot(default: str | Iterable[str] | None | EllipsisType = ...) -> Any: | ||||||
|
|
||||||
| def _determine_startup_order(things: "Mapping[str, Thing]") -> tuple[str, ...]: | ||||||
| r"""Determine the order in which Things should be started. | ||||||
|
|
||||||
| Thing Slots may specify that connected Things must be started before the | ||||||
| thing on which the slot is defined. This function resolves those | ||||||
| dependencies and sets the order in which the Things should start. | ||||||
|
|
||||||
| "start" here refers to calling ``__enter__``\ . | ||||||
|
|
||||||
| :param things: a mapping of names to Things. | ||||||
| :return: an ordered list of Thing names. | ||||||
| :raises ThingSlotCircularDependencyError: if there is no order of starting | ||||||
| the Things that will satisfy all the constraints. | ||||||
| """ | ||||||
| dependencies: dict[str, set[str]] = {} | ||||||
| for name, thing in things.items(): | ||||||
| deps: set[str] = set() | ||||||
| for _, slot in class_attributes(thing, ThingSlot): | ||||||
| if slot.start_before: | ||||||
| deps = deps.union(slot._connected_thing_names(thing)) | ||||||
| # Having a Thing depend on itself makes no sense, so we ignore | ||||||
| # self-dependencies. | ||||||
| deps.discard(name) | ||||||
| dependencies[name] = deps | ||||||
|
|
||||||
| # We add Things to the list iteratively, when they are able to be added. | ||||||
| # Things with no dependencies will be added first, gradually working through | ||||||
| # until everything's done. | ||||||
| # If we reach an iteration where we can't add anything, we have a deadlock | ||||||
| # and we must raise an exception. | ||||||
| order: list[str] = [] | ||||||
| remaining = list(things.keys()) | ||||||
| while remaining: | ||||||
| # If a Thing's dependencies are a subset of the things that are already | ||||||
| # started, we can now add it to the order. | ||||||
| things_to_add = [n for n in remaining if dependencies[n].issubset(order)] | ||||||
| if things_to_add: | ||||||
| order += things_to_add | ||||||
| for name in things_to_add: | ||||||
| remaining.remove(name) | ||||||
| else: | ||||||
| msg = ( | ||||||
| f"There is no order in which the Things may be started.\n" | ||||||
| f"We could start {order}, but the remaining Things have cyclic " | ||||||
| f"dependencies: {remaining}.\n\n" | ||||||
| ) | ||||||
| for name in remaining: | ||||||
| msg += f"'{name}' must be started after {dependencies[name]}.\n" | ||||||
| raise ThingSlotCircularDependencyError(msg) | ||||||
| return tuple(order) | ||||||
|
|
||||||
|
|
||||||
| def thing_slot( | ||||||
| default: str | Iterable[str] | None | EllipsisType = ..., | ||||||
| start_before: bool = False, | ||||||
| ) -> Any: | ||||||
| r"""Declare a connection to another `~lt.Thing` in the same server. | ||||||
|
|
||||||
| ``lt.thing_slot`` marks a class attribute as a connection to another | ||||||
|
|
@@ -367,7 +461,7 @@ class ThingB(lt.Thing): | |||||
| The main reason to use the function is that it suppresses type errors when | ||||||
| using static type checkers such as `mypy` or `pyright` (see note below). | ||||||
|
|
||||||
| The type hint of a Thing Connection should be one of the following: | ||||||
| The type hint of a Thing Slot should be one of the following: | ||||||
|
|
||||||
| * A `~lt.Thing` subclass. An instance of this subclass will be returned when | ||||||
| the attribute is accessed. | ||||||
|
|
@@ -427,6 +521,17 @@ def show_connections(self) -> str: | |||||
| If the default is omitted or set to ``...`` the server will attempt to find | ||||||
| a matching `~lt.Thing` instance (or instances). A default value of `None` is | ||||||
| allowed if the connection is type hinted as optional. | ||||||
| :param start_before: Whether the connected Thing(s) should be started before | ||||||
| the Thing on which the slot is defined. | ||||||
|
|
||||||
| When this is `False` (the default), there's no constraint on the order | ||||||
| in which things will be started: it's assumed the slot will not be | ||||||
| accessed until all Things have started. | ||||||
|
|
||||||
| If `start_before` is set to `False` then LabThings | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
| will ensure the connected Thing(s) have ``__enter__`` called before it | ||||||
| is called on this Thing, i.e. it's safe to use the slot during | ||||||
| ``__enter__``\ . | ||||||
| :return: A `.ThingSlot` descriptor. | ||||||
|
|
||||||
| Typing notes: | ||||||
|
|
@@ -441,4 +546,4 @@ def show_connections(self) -> str: | |||||
| and it is done by established libraries such as `pydantic`\ . | ||||||
|
|
||||||
| """ | ||||||
| return ThingSlot(default=default) | ||||||
| return ThingSlot(default=default, start_before=start_before) | ||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.