Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions src/labthings_fastapi/actions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
InvocationCancelledError,
invocation_logger,
)
from ..outputs.blob import BlobIOContextDep
from ..outputs.blob import BlobIOContextDep, blobdata_to_url_ctx

if TYPE_CHECKING:
# We only need these imports for type hints, so this avoids circular imports.
Expand All @@ -46,6 +46,14 @@
"""The API route used to list `.Invocation` objects."""


class NoBlobManagerError(RuntimeError):
"""Raised if an API route accesses Invocation outputs without a BlobIOContextDep.

Any access to an invocation output must have BlobIOContextDep as a dependency, as
the output may be a blob, and the blob needs this context to resolve its URL.
"""


class Invocation(Thread):
"""A Thread subclass that retains output values and tracks progress.

Expand Down Expand Up @@ -123,7 +131,23 @@

@property
def output(self) -> Any:
"""Return value of the Action. If the Action is still running, returns None."""
"""Return value of the Action. If the Action is still running, returns None.

:raise NoBlobManagerError: If this is called in a context where the blob
manager context variables are not available. This stops errors being raised
later once the blob is returned and tries to serialise. If the errors
happen during serialisation the stack-trace will not clearly identify
the route with the missing dependency.
"""
try:
blobdata_to_url_ctx.get()
except LookupError as e:
raise NoBlobManagerError(

Check warning on line 145 in src/labthings_fastapi/actions/__init__.py

View workflow job for this annotation

GitHub Actions / coverage

144-145 lines are not covered with tests
"An invocation output has been requested from a api route that "
"doesn't have a BlobIOContextDep dependency. This dependency is needed "
" for blobs to identify their url."
) from e

with self._status_lock:
return self._return_value

Expand Down Expand Up @@ -260,13 +284,13 @@
with self._status_lock:
self._status = InvocationStatus.CANCELLED
self.action.emit_changed_event(self.thing, self._status)
except Exception as e: # skipcq: PYL-W0703
logger.exception(e)
with self._status_lock:
self._status = InvocationStatus.ERROR
self._exception = e
self.action.emit_changed_event(self.thing, self._status)
raise e

Check warning on line 293 in src/labthings_fastapi/actions/__init__.py

View workflow job for this annotation

GitHub Actions / coverage

287-293 lines are not covered with tests
finally:
with self._status_lock:
self._end_time = datetime.datetime.now()
Expand Down Expand Up @@ -384,8 +408,8 @@
:param id: the unique ID of the action to retrieve.
:return: the `.Invocation` object.
"""
with self._invocations_lock:
return self._invocations[id]

Check warning on line 412 in src/labthings_fastapi/actions/__init__.py

View workflow job for this annotation

GitHub Actions / coverage

411-412 lines are not covered with tests

def list_invocations(
self,
Expand Down Expand Up @@ -506,13 +530,13 @@
with self._invocations_lock:
try:
invocation: Any = self._invocations[id]
except KeyError:
raise HTTPException(

Check warning on line 534 in src/labthings_fastapi/actions/__init__.py

View workflow job for this annotation

GitHub Actions / coverage

533-534 lines are not covered with tests
status_code=404,
detail="No action invocation found with ID {id}",
)
if not invocation.output:
raise HTTPException(

Check warning on line 539 in src/labthings_fastapi/actions/__init__.py

View workflow job for this annotation

GitHub Actions / coverage

539 line is not covered with tests
status_code=503,
detail="No result is available for this invocation",
)
Expand All @@ -520,7 +544,7 @@
invocation.output.response
):
# TODO: honour "accept" header
return invocation.output.response()

Check warning on line 547 in src/labthings_fastapi/actions/__init__.py

View workflow job for this annotation

GitHub Actions / coverage

547 line is not covered with tests
return invocation.output

@app.delete(
Expand All @@ -545,8 +569,8 @@
with self._invocations_lock:
try:
invocation: Any = self._invocations[id]
except KeyError:
raise HTTPException(

Check warning on line 573 in src/labthings_fastapi/actions/__init__.py

View workflow job for this annotation

GitHub Actions / coverage

572-573 lines are not covered with tests
status_code=404,
detail="No action invocation found with ID {id}",
)
Expand Down
4 changes: 3 additions & 1 deletion src/labthings_fastapi/descriptors/action.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,11 @@

@overload
def __get__(self, obj: Literal[None], type=None) -> ActionDescriptor: # noqa: D105
...

Check warning on line 126 in src/labthings_fastapi/descriptors/action.py

View workflow job for this annotation

GitHub Actions / coverage

126 line is not covered with tests

@overload
def __get__(self, obj: Thing, type=None) -> Callable: # noqa: D105
...

Check warning on line 130 in src/labthings_fastapi/descriptors/action.py

View workflow job for this annotation

GitHub Actions / coverage

130 line is not covered with tests

def __get__(
self, obj: Optional[Thing], type: Optional[type[Thing]] = None
Expand Down Expand Up @@ -207,8 +207,8 @@
try:
runner = get_blocking_portal(obj)
if not runner:
thing_name = obj.__class__.__name__
msg = (

Check warning on line 211 in src/labthings_fastapi/descriptors/action.py

View workflow job for this annotation

GitHub Actions / coverage

210-211 lines are not covered with tests
f"Cannot emit action changed event. Is {thing_name} connected to "
"a running server?"
)
Expand Down Expand Up @@ -339,7 +339,9 @@
),
summary=f"All invocations of {self.name}.",
)
def list_invocations(action_manager: ActionManagerContextDep):
def list_invocations(
action_manager: ActionManagerContextDep, _blob_manager: BlobIOContextDep
):
return action_manager.list_invocations(self, thing)

def action_affordance(
Expand Down
24 changes: 24 additions & 0 deletions tests/test_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,30 @@ def run(payload=None):
return run


def test_get_action_invocations():
"""Test that running "get" on an action returns a list of invocations."""
with TestClient(server.app) as client:
# When we start the action has no invocations
invocations_before = client.get("/thing/increment_counter").json()
assert invocations_before == []
# Start the action
r = client.post("/thing/increment_counter")
assert r.status_code in (200, 201)
# Now it is started, there is a list of 1 dictionary containing the
# invocation information.
invocations_after = client.get("/thing/increment_counter").json()
assert len(invocations_after) == 1
assert isinstance(invocations_after, list)
assert isinstance(invocations_after[0], dict)
assert "status" in invocations_after[0]
assert "id" in invocations_after[0]
assert "action" in invocations_after[0]
assert "href" in invocations_after[0]
assert "timeStarted" in invocations_after[0]
# Let the task finish before ending the test
poll_task(client, r.json())


def test_counter():
with TestClient(server.app) as client:
before_value = client.get("/thing/counter").json()
Expand Down