-
Notifications
You must be signed in to change notification settings - Fork 213
feat(extstore): Add support for Nexus task handling #1676
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,7 +6,7 @@ | |
| import concurrent.futures | ||
| import contextvars | ||
| import threading | ||
| from collections.abc import Callable, Mapping, Sequence | ||
| from collections.abc import Awaitable, Callable, Mapping, Sequence | ||
| from dataclasses import dataclass | ||
| from datetime import datetime, timezone | ||
| from functools import reduce | ||
|
|
@@ -30,6 +30,8 @@ | |
| import temporalio.common | ||
| import temporalio.converter | ||
| import temporalio.nexus | ||
| from temporalio.bridge._visitor import PayloadVisitor | ||
| from temporalio.bridge._visitor_functions import PayloadSequence, VisitorFunctions | ||
| from temporalio.bridge.worker import PollShutdownError | ||
| from temporalio.exceptions import ( | ||
| ApplicationError, | ||
|
|
@@ -216,6 +218,19 @@ async def _complete_task( | |
| ): | ||
| await asyncio.shield(self._bridge_worker().complete_nexus_task(completion)) | ||
|
|
||
| async def _encode_completion( | ||
|
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. I'm confused by the lack of decoding. Is that because it was already happening and just didn't do anything since it saw no claims?
Contributor
Author
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. Decoding happens in |
||
| self, completion: temporalio.bridge.proto.nexus.NexusTaskCompletion | ||
| ) -> None: | ||
| """Apply the payload codec then external storage to the completion's payloads.""" | ||
| dc = self._data_converter | ||
| await PayloadVisitor(skip_search_attributes=True, skip_headers=True).visit( | ||
| _PayloadTransformVisitor(dc._encode_payload_sequence), completion | ||
| ) | ||
| await PayloadVisitor(skip_search_attributes=True).visit( | ||
| _PayloadTransformVisitor(dc._external_store_payload_sequence), | ||
| completion, | ||
| ) | ||
|
|
||
| # TODO(nexus-preview): stack trace pruning. See sdk-typescript NexusHandler.execute | ||
| # "Any call up to this function and including this one will be trimmed out of stack traces."" | ||
|
|
||
|
|
@@ -260,6 +275,14 @@ async def _handle_cancel_operation_task( | |
| try: | ||
| try: | ||
| await self._handler.cancel_operation(ctx, request.operation_token) | ||
| completion = temporalio.bridge.proto.nexus.NexusTaskCompletion( | ||
| task_token=task_token, | ||
| completed=temporalio.api.nexus.v1.Response( | ||
| cancel_operation=temporalio.api.nexus.v1.CancelOperationResponse() | ||
| ), | ||
| ) | ||
| # No-op but keeps the cancel covered if it ever carries a payload. | ||
| await self._encode_completion(completion) | ||
| except asyncio.CancelledError: | ||
| completion = temporalio.bridge.proto.nexus.NexusTaskCompletion( | ||
| task_token=task_token, | ||
|
|
@@ -271,16 +294,12 @@ async def _handle_cancel_operation_task( | |
| completion = temporalio.bridge.proto.nexus.NexusTaskCompletion( | ||
| task_token=task_token, | ||
| ) | ||
| await self._data_converter.encode_failure( | ||
| handler_error, completion.failure | ||
| ) | ||
| else: | ||
| completion = temporalio.bridge.proto.nexus.NexusTaskCompletion( | ||
| task_token=task_token, | ||
| completed=temporalio.api.nexus.v1.Response( | ||
| cancel_operation=temporalio.api.nexus.v1.CancelOperationResponse() | ||
| ), | ||
| self._data_converter.failure_converter.to_failure( | ||
| handler_error, | ||
| self._data_converter.payload_converter, | ||
| completion.failure, | ||
| ) | ||
| await self._encode_completion(completion) | ||
|
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. Would it be possible to fold this step into
Contributor
Author
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. If I did that, then extra fault handling would have to be written. For example, if external storage faulted on the success completion, I'd have to catch that exception, create a failure, attempt to encode and store that failure, and then submit that completion. It would be duplicated exception handling code and might be convoluted to discriminate. |
||
| await self._complete_task(completion) | ||
| except Exception: | ||
| logger.exception("Failed to send Nexus task completion") | ||
|
|
@@ -315,6 +334,13 @@ async def _handle_start_operation_task( | |
| request_deadline, | ||
| endpoint, | ||
| ) | ||
| completion = temporalio.bridge.proto.nexus.NexusTaskCompletion( | ||
| task_token=task_token, | ||
| completed=temporalio.api.nexus.v1.Response( | ||
| start_operation=start_response | ||
| ), | ||
| ) | ||
| await self._encode_completion(completion) | ||
| except asyncio.CancelledError: | ||
| completion = temporalio.bridge.proto.nexus.NexusTaskCompletion( | ||
| task_token=task_token, | ||
|
|
@@ -326,19 +352,15 @@ async def _handle_start_operation_task( | |
| task_token=task_token, | ||
| ) | ||
| handler_error = _exception_to_handler_error(err) | ||
| await self._data_converter.encode_failure( | ||
| handler_error, completion.failure | ||
| self._data_converter.failure_converter.to_failure( | ||
| handler_error, | ||
| self._data_converter.payload_converter, | ||
| completion.failure, | ||
| ) | ||
|
|
||
| if isinstance(err, concurrent.futures.BrokenExecutor): | ||
| self._fail_worker_exception_queue.put_nowait(err) | ||
| else: | ||
| completion = temporalio.bridge.proto.nexus.NexusTaskCompletion( | ||
| task_token=task_token, | ||
| completed=temporalio.api.nexus.v1.Response( | ||
| start_operation=start_response | ||
| ), | ||
| ) | ||
| await self._encode_completion(completion) | ||
|
|
||
| await self._complete_task(completion) | ||
| except Exception: | ||
|
|
@@ -417,7 +439,9 @@ async def _start_operation( | |
| ) | ||
| ) | ||
| elif isinstance(result, nexusrpc.handler.StartOperationResultSync): | ||
| [payload] = await self._data_converter.encode([result.value]) | ||
| [payload] = self._data_converter.payload_converter.to_payloads( | ||
| [result.value] | ||
| ) | ||
|
VegetarianOrc marked this conversation as resolved.
|
||
| return temporalio.api.nexus.v1.StartOperationResponse( | ||
| sync_success=temporalio.api.nexus.v1.StartOperationResponse.Sync( | ||
| payload=payload, | ||
|
|
@@ -446,10 +470,41 @@ async def _start_operation( | |
| ) from err.__cause__ | ||
| except FailureError as new_err: | ||
| response = temporalio.api.nexus.v1.StartOperationResponse() | ||
| await self._data_converter.encode_failure(new_err, response.failure) | ||
| self._data_converter.failure_converter.to_failure( | ||
| new_err, | ||
| self._data_converter.payload_converter, | ||
| response.failure, | ||
| ) | ||
| return response | ||
|
|
||
|
|
||
| class _PayloadTransformVisitor(VisitorFunctions): | ||
| """Adapts a payload-sequence transform for use with :class:`PayloadVisitor`.""" | ||
|
|
||
| def __init__( | ||
| self, | ||
| f: Callable[ | ||
| [Sequence[temporalio.api.common.v1.Payload]], | ||
| Awaitable[list[temporalio.api.common.v1.Payload]], | ||
| ], | ||
| ) -> None: | ||
| self._f = f | ||
|
|
||
| async def visit_payload(self, payload: temporalio.api.common.v1.Payload) -> None: | ||
| new_payload = (await self._f([payload]))[0] | ||
| if new_payload is not payload: | ||
| payload.CopyFrom(new_payload) | ||
|
|
||
| async def visit_payloads(self, payloads: PayloadSequence) -> None: | ||
| if len(payloads) == 0: | ||
| return | ||
| new_payloads = await self._f(payloads) | ||
| if new_payloads is payloads: | ||
| return | ||
| del payloads[:] | ||
| payloads.extend(new_payloads) | ||
|
|
||
|
|
||
| @dataclass | ||
| class _DummyPayloadSerializer: | ||
| data_converter: temporalio.converter.DataConverter | ||
|
|
@@ -465,18 +520,35 @@ async def deserialize( | |
| content: nexusrpc.Content, # type:ignore[reportUnusedParameter] | ||
| as_type: type[Any] | None = None, | ||
| ) -> Any: | ||
| payload = self.payload | ||
| if self.data_converter.payload_codec: | ||
| try: | ||
| [payload] = await self.data_converter.payload_codec.decode([payload]) | ||
| except Exception as err: | ||
| raise nexusrpc.HandlerError( | ||
| "Payload codec failed to decode Nexus operation input", | ||
| type=nexusrpc.HandlerErrorType.INTERNAL, | ||
| ) from err | ||
| dc = self.data_converter | ||
| # The visitor mutates in place, so work on a copy to leave the request | ||
| # payload untouched. | ||
| payload = temporalio.api.common.v1.Payload() | ||
| payload.CopyFrom(self.payload) | ||
| try: | ||
| await PayloadVisitor(skip_search_attributes=True).visit( | ||
| _PayloadTransformVisitor(dc._external_retrieve_payload_sequence), | ||
| payload, | ||
| ) | ||
| except Exception as err: | ||
| raise nexusrpc.HandlerError( | ||
| "Failed to retrieve Nexus operation input from external storage", | ||
| type=nexusrpc.HandlerErrorType.INTERNAL, | ||
| retryable_override=True, | ||
| ) from err | ||
|
|
||
| try: | ||
| await PayloadVisitor(skip_search_attributes=True, skip_headers=True).visit( | ||
| _PayloadTransformVisitor(dc._decode_payload_sequence), payload | ||
| ) | ||
| except Exception as err: | ||
| raise nexusrpc.HandlerError( | ||
| "Payload codec failed to decode Nexus operation input", | ||
| type=nexusrpc.HandlerErrorType.INTERNAL, | ||
| ) from err | ||
|
|
||
| try: | ||
| [input] = self.data_converter.payload_converter.from_payloads( | ||
| [input] = dc.payload_converter.from_payloads( | ||
| [payload], | ||
| type_hints=[as_type] if as_type else None, | ||
| ) | ||
|
|
||
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.
The Nexus task transport drops the
external_payloadsfield. Regardless, it shouldn't be checking for this field anyway and should only rely on the metadata.