diff --git a/changelog/added/chatty-stream-otter.md b/changelog/added/chatty-stream-otter.md new file mode 100644 index 0000000000..6497333a14 --- /dev/null +++ b/changelog/added/chatty-stream-otter.md @@ -0,0 +1 @@ +Add experimental Stream calls for clients and Activities, with client interceptors for each operation. diff --git a/changelog/fixed/unchanced-alfredia.md b/changelog/fixed/unchanced-alfredia.md new file mode 100644 index 0000000000..410ceb31f4 --- /dev/null +++ b/changelog/fixed/unchanced-alfredia.md @@ -0,0 +1 @@ +Core skips Local Activities when replay ends in an unfinished Workflow Task. Local Activity heartbeats preserve the Workflow versioning behavior. diff --git a/scripts/gen_payload_visitor.py b/scripts/gen_payload_visitor.py index ba5ddc112b..7cf8816e48 100644 --- a/scripts/gen_payload_visitor.py +++ b/scripts/gen_payload_visitor.py @@ -23,21 +23,38 @@ from temporalio.converter._payload_converter import _get_transfer_type_converter -def discover_system_nexus_roots() -> list[Descriptor]: - module_path = base_dir / "temporalio" / "nexus" / "system" / "workflow_service" - spec = spec_from_file_location( - "temporalio_nexus_system_workflow_service", - module_path / "__init__.py", - submodule_search_locations=[str(module_path)], - ) - if spec is None or spec.loader is None: - raise RuntimeError(f"Cannot load generated system service from {module_path}") - module = module_from_spec(spec) - sys.modules[spec.name] = module - spec.loader.exec_module(module) +def discover_system_nexus_services() -> list[type]: + services: list[type] = [] + system_dir = base_dir / "temporalio" / "nexus" / "system" + for module_path in sorted(path.parent for path in system_dir.glob("*/services.py")): + spec = spec_from_file_location( + f"temporalio_nexus_system_{module_path.name}", + module_path / "__init__.py", + submodule_search_locations=[str(module_path)], + ) + if spec is None or spec.loader is None: + raise RuntimeError( + f"Cannot load generated system service from {module_path}" + ) + module = module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + services.extend( + value + for value in vars(module.services).values() + if isinstance(value, type) and nexusrpc.get_service_definition(value) + ) + return services + +def discover_system_nexus_roots() -> list[Descriptor]: roots: list[Descriptor] = [] - for annotation in get_type_hints(module._services.WorkflowService).values(): + annotations = [ + annotation + for service in discover_system_nexus_services() + for annotation in get_type_hints(service).values() + ] + for annotation in annotations: if get_origin(annotation) is not nexusrpc.Operation: continue for operation_type in get_args(annotation): diff --git a/temporalio/activity.py b/temporalio/activity.py index 23f7155edc..23c9aab766 100644 --- a/temporalio/activity.py +++ b/temporalio/activity.py @@ -182,7 +182,7 @@ class Info: apart. Zero if Core couldn't read it.""" _local_activity_origin: tuple[int, str] | None = None - """Workflow Task id and Activity id of the first schedule of this Local Activity. + """Command seq and Activity id of the first schedule of this Local Activity. Retries keep them, so that every attempt writes to a Stream as the same Producer.""" @property diff --git a/temporalio/api/enums/v1/stream_pb2.pyi b/temporalio/api/enums/v1/stream_pb2.pyi index 4c0f9134b9..c7d5df2d23 100644 --- a/temporalio/api/enums/v1/stream_pb2.pyi +++ b/temporalio/api/enums/v1/stream_pb2.pyi @@ -32,7 +32,7 @@ class _StreamIdConflictPolicyEnumTypeWrapper( STREAM_ID_CONFLICT_POLICY_FAIL: _StreamIdConflictPolicy.ValueType # 1 """The create fails with `ALREADY_EXISTS`.""" STREAM_ID_CONFLICT_POLICY_USE_EXISTING: _StreamIdConflictPolicy.ValueType # 2 - """The create returns the existing Stream without changing its expiry.""" + """The create returns `created` false for the existing Stream.""" class StreamIdConflictPolicy( _StreamIdConflictPolicy, metaclass=_StreamIdConflictPolicyEnumTypeWrapper @@ -45,7 +45,7 @@ STREAM_ID_CONFLICT_POLICY_UNSPECIFIED: StreamIdConflictPolicy.ValueType # 0 STREAM_ID_CONFLICT_POLICY_FAIL: StreamIdConflictPolicy.ValueType # 1 """The create fails with `ALREADY_EXISTS`.""" STREAM_ID_CONFLICT_POLICY_USE_EXISTING: StreamIdConflictPolicy.ValueType # 2 -"""The create returns the existing Stream without changing its expiry.""" +"""The create returns `created` false for the existing Stream.""" global___StreamIdConflictPolicy = StreamIdConflictPolicy class _StreamErrorReason: @@ -63,7 +63,7 @@ class _StreamErrorReasonEnumTypeWrapper( STREAM_ERROR_REASON_NOT_FOUND: _StreamErrorReason.ValueType # 1 """The Stream was never created (`NOT_FOUND`).""" STREAM_ERROR_REASON_EXPIRED: _StreamErrorReason.ValueType # 2 - """Retention has passed since create or the last append of a new batch (`NOT_FOUND`).""" + """The Store's retention policy removed the Records (`NOT_FOUND`).""" STREAM_ERROR_REASON_FENCED: _StreamErrorReason.ValueType # 3 """A later attempt of this Producer has written, and fencing is enabled (`FAILED_PRECONDITION`).""" STREAM_ERROR_REASON_FORMAT_TOO_NEW: _StreamErrorReason.ValueType # 4 @@ -96,7 +96,7 @@ STREAM_ERROR_REASON_UNSPECIFIED: StreamErrorReason.ValueType # 0 STREAM_ERROR_REASON_NOT_FOUND: StreamErrorReason.ValueType # 1 """The Stream was never created (`NOT_FOUND`).""" STREAM_ERROR_REASON_EXPIRED: StreamErrorReason.ValueType # 2 -"""Retention has passed since create or the last append of a new batch (`NOT_FOUND`).""" +"""The Store's retention policy removed the Records (`NOT_FOUND`).""" STREAM_ERROR_REASON_FENCED: StreamErrorReason.ValueType # 3 """A later attempt of this Producer has written, and fencing is enabled (`FAILED_PRECONDITION`).""" STREAM_ERROR_REASON_FORMAT_TOO_NEW: StreamErrorReason.ValueType # 4 diff --git a/temporalio/api/stream/v1/message_pb2.py b/temporalio/api/stream/v1/message_pb2.py index 9216b99620..36f7c7ee60 100644 --- a/temporalio/api/stream/v1/message_pb2.py +++ b/temporalio/api/stream/v1/message_pb2.py @@ -23,7 +23,7 @@ ) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n$temporal/api/stream/v1/message.proto\x12\x16temporal.api.stream.v1\x1a\x1fgoogle/protobuf/timestamp.proto\x1a$temporal/api/common/v1/message.proto\x1a"temporal/api/enums/v1/stream.proto"r\n\x13WorkflowTaskAttempt\x12\x18\n\x10started_event_id\x18\x01 \x01(\x03\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\x05\x12\x30\n\x0cstarted_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"b\n\x14LocalActivityAttempt\x12\x39\n\x04task\x18\x01 \x01(\x0b\x32+.temporal.api.stream.v1.WorkflowTaskAttempt\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\x05"^\n\x0f\x41\x63tivityAttempt\x12:\n\x16\x61ttempt_scheduled_time\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\x05"\xa2\x01\n\x10WorkflowProducer\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t\x12\x18\n\x10workflow_task_id\x18\x04 \x01(\x03\x12<\n\x07\x61ttempt\x18\x05 \x01(\x0b\x32+.temporal.api.stream.v1.WorkflowTaskAttempt"\xbd\x01\n\x15LocalActivityProducer\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t\x12\x18\n\x10workflow_task_id\x18\x04 \x01(\x03\x12\x13\n\x0b\x61\x63tivity_id\x18\x05 \x01(\t\x12=\n\x07\x61ttempt\x18\x06 \x01(\x0b\x32,.temporal.api.stream.v1.LocalActivityAttempt"\xbd\x01\n\x18WorkflowActivityProducer\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t\x12\x13\n\x0b\x61\x63tivity_id\x18\x04 \x01(\t\x12\x1a\n\x12scheduled_event_id\x18\x05 \x01(\x03\x12\x38\n\x07\x61ttempt\x18\x06 \x01(\x0b\x32\'.temporal.api.stream.v1.ActivityAttempt"\x8e\x01\n\x1aStandaloneActivityProducer\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t\x12\x38\n\x07\x61ttempt\x18\x04 \x01(\x0b\x32\'.temporal.api.stream.v1.ActivityAttempt"/\n\x0e\x43lientProducer\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\n\n\x02id\x18\x02 \x01(\t"\xf5\x02\n\x08Producer\x12<\n\x08workflow\x18\x01 \x01(\x0b\x32(.temporal.api.stream.v1.WorkflowProducerH\x00\x12G\n\x0elocal_activity\x18\x02 \x01(\x0b\x32-.temporal.api.stream.v1.LocalActivityProducerH\x00\x12M\n\x11workflow_activity\x18\x03 \x01(\x0b\x32\x30.temporal.api.stream.v1.WorkflowActivityProducerH\x00\x12Q\n\x13standalone_activity\x18\x04 \x01(\x0b\x32\x32.temporal.api.stream.v1.StandaloneActivityProducerH\x00\x12\x38\n\x06\x63lient\x18\x05 \x01(\x0b\x32&.temporal.api.stream.v1.ClientProducerH\x00\x42\x06\n\x04kind"=\n\x0c\x41ppendRecord\x12-\n\x04\x62ody\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"\x81\x01\n\x0cStreamRecord\x12\x32\n\x08producer\x18\x01 \x01(\x0b\x32 .temporal.api.stream.v1.Producer\x12-\n\x04\x62ody\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x0e\n\x06offset\x18\x03 \x01(\x0c"N\n\x12StreamErrorDetails\x12\x38\n\x06reason\x18\x01 \x01(\x0e\x32(.temporal.api.enums.v1.StreamErrorReasonB\x89\x01\n\x19io.temporal.api.stream.v1B\x0cMessageProtoP\x01Z#go.temporal.io/api/stream/v1;stream\xaa\x02\x18Temporalio.Api.Stream.V1\xea\x02\x1bTemporalio::Api::Stream::V1b\x06proto3' + b'\n$temporal/api/stream/v1/message.proto\x12\x16temporal.api.stream.v1\x1a\x1fgoogle/protobuf/timestamp.proto\x1a$temporal/api/common/v1/message.proto\x1a"temporal/api/enums/v1/stream.proto"r\n\x13WorkflowTaskAttempt\x12\x18\n\x10started_event_id\x18\x01 \x01(\x03\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\x05\x12\x30\n\x0cstarted_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"b\n\x14LocalActivityAttempt\x12\x39\n\x04task\x18\x01 \x01(\x0b\x32+.temporal.api.stream.v1.WorkflowTaskAttempt\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\x05"^\n\x0f\x41\x63tivityAttempt\x12:\n\x16\x61ttempt_scheduled_time\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\x05"\xa2\x01\n\x10WorkflowProducer\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t\x12\x18\n\x10workflow_task_id\x18\x04 \x01(\x03\x12<\n\x07\x61ttempt\x18\x05 \x01(\x0b\x32+.temporal.api.stream.v1.WorkflowTaskAttempt"\xb0\x01\n\x15LocalActivityProducer\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t\x12\x13\n\x0b\x61\x63tivity_id\x18\x05 \x01(\t\x12=\n\x07\x61ttempt\x18\x06 \x01(\x0b\x32,.temporal.api.stream.v1.LocalActivityAttempt\x12\x0b\n\x03seq\x18\x07 \x01(\r"\xbd\x01\n\x18WorkflowActivityProducer\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t\x12\x13\n\x0b\x61\x63tivity_id\x18\x04 \x01(\t\x12\x1a\n\x12scheduled_event_id\x18\x05 \x01(\x03\x12\x38\n\x07\x61ttempt\x18\x06 \x01(\x0b\x32\'.temporal.api.stream.v1.ActivityAttempt"\x8e\x01\n\x1aStandaloneActivityProducer\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t\x12\x38\n\x07\x61ttempt\x18\x04 \x01(\x0b\x32\'.temporal.api.stream.v1.ActivityAttempt"/\n\x0e\x43lientProducer\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\n\n\x02id\x18\x02 \x01(\t"\xf5\x02\n\x08Producer\x12<\n\x08workflow\x18\x01 \x01(\x0b\x32(.temporal.api.stream.v1.WorkflowProducerH\x00\x12G\n\x0elocal_activity\x18\x02 \x01(\x0b\x32-.temporal.api.stream.v1.LocalActivityProducerH\x00\x12M\n\x11workflow_activity\x18\x03 \x01(\x0b\x32\x30.temporal.api.stream.v1.WorkflowActivityProducerH\x00\x12Q\n\x13standalone_activity\x18\x04 \x01(\x0b\x32\x32.temporal.api.stream.v1.StandaloneActivityProducerH\x00\x12\x38\n\x06\x63lient\x18\x05 \x01(\x0b\x32&.temporal.api.stream.v1.ClientProducerH\x00\x42\x06\n\x04kind"=\n\x0c\x41ppendRecord\x12-\n\x04\x62ody\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"\x81\x01\n\x0cStreamRecord\x12\x32\n\x08producer\x18\x01 \x01(\x0b\x32 .temporal.api.stream.v1.Producer\x12-\n\x04\x62ody\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x0e\n\x06offset\x18\x03 \x01(\x0c"N\n\x12StreamErrorDetails\x12\x38\n\x06reason\x18\x01 \x01(\x0e\x32(.temporal.api.enums.v1.StreamErrorReasonB\x89\x01\n\x19io.temporal.api.stream.v1B\x0cMessageProtoP\x01Z#go.temporal.io/api/stream/v1;stream\xaa\x02\x18Temporalio.Api.Stream.V1\xea\x02\x1bTemporalio::Api::Stream::V1b\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -40,19 +40,19 @@ _WORKFLOWPRODUCER._serialized_start = 484 _WORKFLOWPRODUCER._serialized_end = 646 _LOCALACTIVITYPRODUCER._serialized_start = 649 - _LOCALACTIVITYPRODUCER._serialized_end = 838 - _WORKFLOWACTIVITYPRODUCER._serialized_start = 841 - _WORKFLOWACTIVITYPRODUCER._serialized_end = 1030 - _STANDALONEACTIVITYPRODUCER._serialized_start = 1033 - _STANDALONEACTIVITYPRODUCER._serialized_end = 1175 - _CLIENTPRODUCER._serialized_start = 1177 - _CLIENTPRODUCER._serialized_end = 1224 - _PRODUCER._serialized_start = 1227 - _PRODUCER._serialized_end = 1600 - _APPENDRECORD._serialized_start = 1602 - _APPENDRECORD._serialized_end = 1663 - _STREAMRECORD._serialized_start = 1666 - _STREAMRECORD._serialized_end = 1795 - _STREAMERRORDETAILS._serialized_start = 1797 - _STREAMERRORDETAILS._serialized_end = 1875 + _LOCALACTIVITYPRODUCER._serialized_end = 825 + _WORKFLOWACTIVITYPRODUCER._serialized_start = 828 + _WORKFLOWACTIVITYPRODUCER._serialized_end = 1017 + _STANDALONEACTIVITYPRODUCER._serialized_start = 1020 + _STANDALONEACTIVITYPRODUCER._serialized_end = 1162 + _CLIENTPRODUCER._serialized_start = 1164 + _CLIENTPRODUCER._serialized_end = 1211 + _PRODUCER._serialized_start = 1214 + _PRODUCER._serialized_end = 1587 + _APPENDRECORD._serialized_start = 1589 + _APPENDRECORD._serialized_end = 1650 + _STREAMRECORD._serialized_start = 1653 + _STREAMRECORD._serialized_end = 1782 + _STREAMERRORDETAILS._serialized_start = 1784 + _STREAMERRORDETAILS._serialized_end = 1862 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/api/stream/v1/message_pb2.pyi b/temporalio/api/stream/v1/message_pb2.pyi index 1a925bf356..a66e8f5947 100644 --- a/temporalio/api/stream/v1/message_pb2.pyi +++ b/temporalio/api/stream/v1/message_pb2.pyi @@ -197,22 +197,25 @@ class LocalActivityProducer(google.protobuf.message.Message): NAMESPACE_FIELD_NUMBER: builtins.int WORKFLOW_ID_FIELD_NUMBER: builtins.int RUN_ID_FIELD_NUMBER: builtins.int - WORKFLOW_TASK_ID_FIELD_NUMBER: builtins.int ACTIVITY_ID_FIELD_NUMBER: builtins.int ATTEMPT_FIELD_NUMBER: builtins.int + SEQ_FIELD_NUMBER: builtins.int namespace: builtins.str """Required. The namespace of the Workflow that made the call.""" workflow_id: builtins.str """Required.""" run_id: builtins.str """Required.""" - workflow_task_id: builtins.int - """Retries retain the original scheduling task's id, including after a Workflow timer. - Zero identifies a Local Activity first scheduled in the run's first Workflow Task. - """ activity_id: builtins.str - """Required. The SDK keeps this id across retries so they share one Producer. - The id must distinguish Local Activities first scheduled in the same Workflow Task. + """Required. The Activity id of the first schedule. It is part of the Producer identity, + so the SDK keeps it across retries. + """ + seq: builtins.int + """The sequence number of the command that first scheduled the Local Activity. It identifies + the Local Activity in its Workflow run. Retries retain it, including after a Workflow timer. + + (-- api-linter: core::0141::forbidden-types=disabled + aip.dev/not-precedent: Sequence numbers are never negative. --) """ @property def attempt(self) -> global___LocalActivityAttempt: @@ -224,9 +227,9 @@ class LocalActivityProducer(google.protobuf.message.Message): namespace: builtins.str = ..., workflow_id: builtins.str = ..., run_id: builtins.str = ..., - workflow_task_id: builtins.int = ..., activity_id: builtins.str = ..., attempt: global___LocalActivityAttempt | None = ..., + seq: builtins.int = ..., ) -> None: ... def HasField( self, field_name: typing.Literal["attempt", b"attempt"] @@ -242,10 +245,10 @@ class LocalActivityProducer(google.protobuf.message.Message): b"namespace", "run_id", b"run_id", + "seq", + b"seq", "workflow_id", b"workflow_id", - "workflow_task_id", - b"workflow_task_id", ], ) -> None: ... @@ -393,7 +396,8 @@ global___ClientProducer = ClientProducer class Producer(google.protobuf.message.Message): """Experimental. Might change in the future. The kind and ids identify a Producer. The attempt does not. - With fencing enabled, a write fails with `FENCED` after a later attempt of that Producer writes. + A Store can reject an older attempt with `FENCED` after a later attempt of that Producer writes. + A remembered resend still returns its original offsets. Records retain their Producer and attempt so that readers can apply their own retry policy. Attempts of different Producers have no order. A reset run cannot fence its base run. """ diff --git a/temporalio/api/streamservice/v1/request_response_pb2.pyi b/temporalio/api/streamservice/v1/request_response_pb2.pyi index 2762fcae61..3ca63ba470 100644 --- a/temporalio/api/streamservice/v1/request_response_pb2.pyi +++ b/temporalio/api/streamservice/v1/request_response_pb2.pyi @@ -24,8 +24,8 @@ class CreateStreamRequest(google.protobuf.message.Message): A retry with the original create request id returns `created` true, even with `FAIL`. Either policy returns `EXPIRED` while the Store remembers an expired Stream. - Retention is a Store setting. It starts at create and restarts when an append writes a new batch. - Reads and resends keep the existing expiry. + Retention is a Store policy. Keep Records for as long as a Workflow History can replay them, + including after a Workflow reset. (-- api-linter: core::0133=disabled aip.dev/not-precedent: The request identifies a Stream by its id. --) """ @@ -77,7 +77,7 @@ global___CreateStreamResponse = CreateStreamResponse class AppendRecordsRequest(google.protobuf.message.Message): """Experimental. Might change in the future. Retries must use the same Producer, attempt, request id and batch. A remembered request id - returns the original offsets without writing again. The Store sets its resend window per + returns the original offsets without duplicating Records. The Store sets its resend window per Producer. An empty or forgotten request id permits a second write. """ diff --git a/temporalio/bridge/Cargo.lock b/temporalio/bridge/Cargo.lock index a5548a91bc..23e9ffff37 100644 --- a/temporalio/bridge/Cargo.lock +++ b/temporalio/bridge/Cargo.lock @@ -2626,6 +2626,7 @@ dependencies = [ "temporalio-client", "temporalio-common", "temporalio-sdk-core", + "temporalio-streams", "tokio", "tokio-rustls", "tokio-stream", @@ -2798,6 +2799,7 @@ dependencies = [ "temporalio-client", "temporalio-common", "temporalio-macros", + "temporalio-streams", "thiserror", "tokio", "tokio-stream", @@ -2809,6 +2811,17 @@ dependencies = [ "zip", ] +[[package]] +name = "temporalio-streams" +version = "0.1.0" +dependencies = [ + "enum-iterator", + "futures-util", + "prost", + "temporalio-common", + "thiserror", +] + [[package]] name = "termtree" version = "0.5.1" diff --git a/temporalio/bridge/Cargo.toml b/temporalio/bridge/Cargo.toml index 3d63f69cdf..10ffc2208c 100644 --- a/temporalio/bridge/Cargo.toml +++ b/temporalio/bridge/Cargo.toml @@ -73,6 +73,7 @@ temporalio-sdk-core = { version = "0.12.0", path = "./sdk-core/crates/sdk-core", "envconfig", "prometheus", ] } +temporalio-streams = { version = "0.1.0", path = "./sdk-core/crates/streams" } tokio = "1.26" # Matches the sdk-core client crate's rustls stack; used to build the custom # server certificate verifier for TLSConfig.verification_server_name. diff --git a/temporalio/bridge/_visitor.py b/temporalio/bridge/_visitor.py index ead09a986f..06f5b43463 100644 --- a/temporalio/bridge/_visitor.py +++ b/temporalio/bridge/_visitor.py @@ -308,6 +308,12 @@ async def _visit_coresdk_workflow_activation_ResolveNexusOperation( if o.HasField("result"): await self._visit_coresdk_nexus_NexusOperationResult(fs, o.result) + async def _visit_coresdk_workflow_activation_ResolveStreamAppend( + self, fs: VisitorFunctions, o: Any + ): + if o.HasField("failed"): + await self._visit_temporal_api_failure_v1_Failure(fs, o.failed) + async def _visit_coresdk_workflow_activation_WorkflowActivationJob( self, fs: VisitorFunctions, o: Any ): @@ -353,6 +359,10 @@ async def _visit_coresdk_workflow_activation_WorkflowActivationJob( await self._visit_coresdk_workflow_activation_ResolveNexusOperation( fs, o.resolve_nexus_operation ) + elif o.HasField("resolve_stream_append"): + await self._visit_coresdk_workflow_activation_ResolveStreamAppend( + fs, o.resolve_stream_append + ) async def _visit_coresdk_workflow_activation_WorkflowActivation( self, fs: VisitorFunctions, o: Any @@ -492,6 +502,11 @@ async def _visit_coresdk_workflow_commands_ScheduleNexusOperation( if o.HasField("input"): await self._visit_nexus_operation_input_payload(fs, o.input) + async def _visit_coresdk_workflow_commands_AppendToStream( + self, fs: VisitorFunctions, o: Any + ): + await self._visit_payload_container(fs, o.bodies) + async def _visit_coresdk_workflow_commands_WorkflowCommand( self, fs: VisitorFunctions, o: Any ): @@ -551,6 +566,10 @@ async def _visit_coresdk_workflow_commands_WorkflowCommand( await self._visit_coresdk_workflow_commands_ScheduleNexusOperation( fs, o.schedule_nexus_operation ) + elif o.HasField("append_to_stream"): + await self._visit_coresdk_workflow_commands_AppendToStream( + fs, o.append_to_stream + ) async def _visit_coresdk_workflow_completion_Success( self, fs: VisitorFunctions, o: Any @@ -639,6 +658,60 @@ async def _visit_temporal_api_notificationservice_v1_OnCompleteResponse( ) -> None: pass + async def _visit_temporal_api_sdk_v1_CreateStreamRequest( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_sdk_v1_CreateStreamResponse( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_stream_v1_AppendRecord( + self, fs: VisitorFunctions, o: Any + ): + if o.HasField("body"): + await self._visit_temporal_api_common_v1_Payload(fs, o.body) + + async def _visit_temporal_api_sdk_v1_AppendRecordsRequest( + self, fs: VisitorFunctions, o: Any + ): + for v in o.records: + await self._visit_temporal_api_stream_v1_AppendRecord(fs, v) + + async def _visit_temporal_api_streamservice_v1_AppendRecordsResponse( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_sdk_v1_ReadRecordsRequest( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_stream_v1_StreamRecord( + self, fs: VisitorFunctions, o: Any + ): + if o.HasField("body"): + await self._visit_temporal_api_common_v1_Payload(fs, o.body) + + async def _visit_temporal_api_streamservice_v1_ReadRecordsResponse( + self, fs: VisitorFunctions, o: Any + ): + for v in o.records: + await self._visit_temporal_api_stream_v1_StreamRecord(fs, v) + + async def _visit_temporal_api_sdk_v1_DescribeStreamRequest( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_streamservice_v1_DescribeStreamResponse( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + async def _visit_temporal_api_common_v1_Header(self, fs: VisitorFunctions, o: Any): for v in o.fields.values(): await self._visit_temporal_api_common_v1_Payload(fs, v) diff --git a/temporalio/bridge/proto/activity_result/activity_result_pb2.py b/temporalio/bridge/proto/activity_result/activity_result_pb2.py index c7ecc2a0ed..80eeadca2a 100644 --- a/temporalio/bridge/proto/activity_result/activity_result_pb2.py +++ b/temporalio/bridge/proto/activity_result/activity_result_pb2.py @@ -25,9 +25,12 @@ from temporalio.api.failure.v1 import ( message_pb2 as temporal_dot_api_dot_failure_dot_v1_dot_message__pb2, ) +from temporalio.bridge.proto.common import ( + common_pb2 as temporal_dot_sdk_dot_core_dot_common_dot_common__pb2, +) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n7temporal/sdk/core/activity_result/activity_result.proto\x12\x17\x63oresdk.activity_result\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a$temporal/api/common/v1/message.proto\x1a(temporal/api/enums/v1/failed_cause.proto\x1a%temporal/api/failure/v1/message.proto"\x95\x02\n\x17\x41\x63tivityExecutionResult\x12\x35\n\tcompleted\x18\x01 \x01(\x0b\x32 .coresdk.activity_result.SuccessH\x00\x12\x32\n\x06\x66\x61iled\x18\x02 \x01(\x0b\x32 .coresdk.activity_result.FailureH\x00\x12:\n\tcancelled\x18\x03 \x01(\x0b\x32%.coresdk.activity_result.CancellationH\x00\x12I\n\x13will_complete_async\x18\x04 \x01(\x0b\x32*.coresdk.activity_result.WillCompleteAsyncH\x00\x42\x08\n\x06status"\xfc\x01\n\x12\x41\x63tivityResolution\x12\x35\n\tcompleted\x18\x01 \x01(\x0b\x32 .coresdk.activity_result.SuccessH\x00\x12\x32\n\x06\x66\x61iled\x18\x02 \x01(\x0b\x32 .coresdk.activity_result.FailureH\x00\x12:\n\tcancelled\x18\x03 \x01(\x0b\x32%.coresdk.activity_result.CancellationH\x00\x12\x35\n\x07\x62\x61\x63koff\x18\x04 \x01(\x0b\x32".coresdk.activity_result.DoBackoffH\x00\x42\x08\n\x06status":\n\x07Success\x12/\n\x06result\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"{\n\x07\x46\x61ilure\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12=\n\x05\x63\x61use\x18\x02 \x01(\x0e\x32..temporal.api.enums.v1.ActivityTaskFailedCause"A\n\x0c\x43\x61ncellation\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"\x13\n\x11WillCompleteAsync"\x8d\x01\n\tDoBackoff\x12\x0f\n\x07\x61ttempt\x18\x01 \x01(\r\x12\x33\n\x10\x62\x61\x63koff_duration\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration\x12:\n\x16original_schedule_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.TimestampB4\xea\x02\x31Temporalio::Internal::Bridge::Api::ActivityResultb\x06proto3' + b'\n7temporal/sdk/core/activity_result/activity_result.proto\x12\x17\x63oresdk.activity_result\x1a\x1egoogle/protobuf/duration.proto\x1a%temporal/sdk/core/common/common.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a$temporal/api/common/v1/message.proto\x1a(temporal/api/enums/v1/failed_cause.proto\x1a%temporal/api/failure/v1/message.proto"\x95\x02\n\x17\x41\x63tivityExecutionResult\x12\x35\n\tcompleted\x18\x01 \x01(\x0b\x32 .coresdk.activity_result.SuccessH\x00\x12\x32\n\x06\x66\x61iled\x18\x02 \x01(\x0b\x32 .coresdk.activity_result.FailureH\x00\x12:\n\tcancelled\x18\x03 \x01(\x0b\x32%.coresdk.activity_result.CancellationH\x00\x12I\n\x13will_complete_async\x18\x04 \x01(\x0b\x32*.coresdk.activity_result.WillCompleteAsyncH\x00\x42\x08\n\x06status"\xfc\x01\n\x12\x41\x63tivityResolution\x12\x35\n\tcompleted\x18\x01 \x01(\x0b\x32 .coresdk.activity_result.SuccessH\x00\x12\x32\n\x06\x66\x61iled\x18\x02 \x01(\x0b\x32 .coresdk.activity_result.FailureH\x00\x12:\n\tcancelled\x18\x03 \x01(\x0b\x32%.coresdk.activity_result.CancellationH\x00\x12\x35\n\x07\x62\x61\x63koff\x18\x04 \x01(\x0b\x32".coresdk.activity_result.DoBackoffH\x00\x42\x08\n\x06status":\n\x07Success\x12/\n\x06result\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"{\n\x07\x46\x61ilure\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12=\n\x05\x63\x61use\x18\x02 \x01(\x0e\x32..temporal.api.enums.v1.ActivityTaskFailedCause"A\n\x0c\x43\x61ncellation\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"\x13\n\x11WillCompleteAsync"\xd1\x01\n\tDoBackoff\x12\x0f\n\x07\x61ttempt\x18\x01 \x01(\r\x12\x33\n\x10\x62\x61\x63koff_duration\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration\x12:\n\x16original_schedule_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x42\n\x15local_activity_origin\x18\x04 \x01(\x0b\x32#.coresdk.common.LocalActivityOriginB4\xea\x02\x31Temporalio::Internal::Bridge::Api::ActivityResultb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -37,18 +40,18 @@ DESCRIPTOR._serialized_options = ( b"\352\0021Temporalio::Internal::Bridge::Api::ActivityResult" ) - _ACTIVITYEXECUTIONRESULT._serialized_start = 269 - _ACTIVITYEXECUTIONRESULT._serialized_end = 546 - _ACTIVITYRESOLUTION._serialized_start = 549 - _ACTIVITYRESOLUTION._serialized_end = 801 - _SUCCESS._serialized_start = 803 - _SUCCESS._serialized_end = 861 - _FAILURE._serialized_start = 863 - _FAILURE._serialized_end = 986 - _CANCELLATION._serialized_start = 988 - _CANCELLATION._serialized_end = 1053 - _WILLCOMPLETEASYNC._serialized_start = 1055 - _WILLCOMPLETEASYNC._serialized_end = 1074 - _DOBACKOFF._serialized_start = 1077 - _DOBACKOFF._serialized_end = 1218 + _ACTIVITYEXECUTIONRESULT._serialized_start = 308 + _ACTIVITYEXECUTIONRESULT._serialized_end = 585 + _ACTIVITYRESOLUTION._serialized_start = 588 + _ACTIVITYRESOLUTION._serialized_end = 840 + _SUCCESS._serialized_start = 842 + _SUCCESS._serialized_end = 900 + _FAILURE._serialized_start = 902 + _FAILURE._serialized_end = 1025 + _CANCELLATION._serialized_start = 1027 + _CANCELLATION._serialized_end = 1092 + _WILLCOMPLETEASYNC._serialized_start = 1094 + _WILLCOMPLETEASYNC._serialized_end = 1113 + _DOBACKOFF._serialized_start = 1116 + _DOBACKOFF._serialized_end = 1325 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/activity_result/activity_result_pb2.pyi b/temporalio/bridge/proto/activity_result/activity_result_pb2.pyi index 35647cbd3f..f1cd152bf3 100644 --- a/temporalio/bridge/proto/activity_result/activity_result_pb2.pyi +++ b/temporalio/bridge/proto/activity_result/activity_result_pb2.pyi @@ -14,6 +14,7 @@ import google.protobuf.timestamp_pb2 import temporalio.api.common.v1.message_pb2 import temporalio.api.enums.v1.failed_cause_pb2 import temporalio.api.failure.v1.message_pb2 +import temporalio.bridge.proto.common.common_pb2 DESCRIPTOR: google.protobuf.descriptor.FileDescriptor @@ -253,6 +254,7 @@ class DoBackoff(google.protobuf.message.Message): ATTEMPT_FIELD_NUMBER: builtins.int BACKOFF_DURATION_FIELD_NUMBER: builtins.int ORIGINAL_SCHEDULE_TIME_FIELD_NUMBER: builtins.int + LOCAL_ACTIVITY_ORIGIN_FIELD_NUMBER: builtins.int attempt: builtins.int """The attempt number that lang should provide when scheduling the retry. If the LA failed on attempt 4 and we told lang to back off with a timer, this number will be 5. @@ -265,18 +267,30 @@ class DoBackoff(google.protobuf.message.Message): to the retry LA. """ + @property + def local_activity_origin( + self, + ) -> temporalio.bridge.proto.common.common_pb2.LocalActivityOrigin: + """The origin of this local activity. Lang must pass it to the retry that it schedules after + the backoff, so all attempts keep the same origin. + """ + def __init__( self, *, attempt: builtins.int = ..., backoff_duration: google.protobuf.duration_pb2.Duration | None = ..., original_schedule_time: google.protobuf.timestamp_pb2.Timestamp | None = ..., + local_activity_origin: temporalio.bridge.proto.common.common_pb2.LocalActivityOrigin + | None = ..., ) -> None: ... def HasField( self, field_name: typing.Literal[ "backoff_duration", b"backoff_duration", + "local_activity_origin", + b"local_activity_origin", "original_schedule_time", b"original_schedule_time", ], @@ -288,6 +302,8 @@ class DoBackoff(google.protobuf.message.Message): b"attempt", "backoff_duration", b"backoff_duration", + "local_activity_origin", + b"local_activity_origin", "original_schedule_time", b"original_schedule_time", ], diff --git a/temporalio/bridge/proto/activity_task/activity_task_pb2.py b/temporalio/bridge/proto/activity_task/activity_task_pb2.py index 25233f5241..a00de328e0 100644 --- a/temporalio/bridge/proto/activity_task/activity_task_pb2.py +++ b/temporalio/bridge/proto/activity_task/activity_task_pb2.py @@ -27,7 +27,7 @@ ) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n3temporal/sdk/core/activity_task/activity_task.proto\x12\x15\x63oresdk.activity_task\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a$temporal/api/common/v1/message.proto\x1a#temporal/api/nexus/v1/message.proto\x1a%temporal/sdk/core/common/common.proto"\x8d\x01\n\x0c\x41\x63tivityTask\x12\x12\n\ntask_token\x18\x01 \x01(\x0c\x12-\n\x05start\x18\x03 \x01(\x0b\x32\x1c.coresdk.activity_task.StartH\x00\x12/\n\x06\x63\x61ncel\x18\x04 \x01(\x0b\x32\x1d.coresdk.activity_task.CancelH\x00\x42\t\n\x07variant"\xdb\x08\n\x05Start\x12\x1a\n\x12workflow_namespace\x18\x01 \x01(\t\x12\x15\n\rworkflow_type\x18\x02 \x01(\t\x12\x45\n\x12workflow_execution\x18\x03 \x01(\x0b\x32).temporal.api.common.v1.WorkflowExecution\x12\x13\n\x0b\x61\x63tivity_id\x18\x04 \x01(\t\x12\x15\n\ractivity_type\x18\x05 \x01(\t\x12\x45\n\rheader_fields\x18\x06 \x03(\x0b\x32..coresdk.activity_task.Start.HeaderFieldsEntry\x12.\n\x05input\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12:\n\x11heartbeat_details\x18\x08 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x32\n\x0escheduled_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x42\n\x1e\x63urrent_attempt_scheduled_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x30\n\x0cstarted_time\x18\x0b \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07\x61ttempt\x18\x0c \x01(\r\x12<\n\x19schedule_to_close_timeout\x18\r \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\x0e \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x34\n\x11heartbeat_timeout\x18\x0f \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x10 \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x32\n\x08priority\x18\x12 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12\x10\n\x08is_local\x18\x11 \x01(\x08\x12\x0e\n\x06run_id\x18\x13 \x01(\t\x12\x65\n&propagated_nexus_serialization_context\x18\x14 \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x12\x41\n\rworkflow_task\x18\x15 \x01(\x0b\x32*.coresdk.activity_task.WorkflowTaskAttempt\x1aT\n\x11HeaderFieldsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x80\x02\n\x13WorkflowTaskAttempt\x12\x18\n\x10started_event_id\x18\x01 \x01(\x03\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\r\x12\x30\n\x0cstarted_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12!\n\x19previous_started_event_id\x18\x04 \x01(\x03\x12\x14\n\x0c\x66\x61iled_tasks\x18\x05 \x03(\x03\x12\x18\n\x10previous_attempt\x18\x06 \x01(\r\x12\x39\n\x15previous_started_time\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"\x8a\x01\n\x06\x43\x61ncel\x12;\n\x06reason\x18\x01 \x01(\x0e\x32+.coresdk.activity_task.ActivityCancelReason\x12\x43\n\x07\x64\x65tails\x18\x02 \x01(\x0b\x32\x32.coresdk.activity_task.ActivityCancellationDetails"\xa0\x01\n\x1b\x41\x63tivityCancellationDetails\x12\x14\n\x0cis_not_found\x18\x01 \x01(\x08\x12\x14\n\x0cis_cancelled\x18\x02 \x01(\x08\x12\x11\n\tis_paused\x18\x03 \x01(\x08\x12\x14\n\x0cis_timed_out\x18\x04 \x01(\x08\x12\x1a\n\x12is_worker_shutdown\x18\x05 \x01(\x08\x12\x10\n\x08is_reset\x18\x06 \x01(\x08*o\n\x14\x41\x63tivityCancelReason\x12\r\n\tNOT_FOUND\x10\x00\x12\r\n\tCANCELLED\x10\x01\x12\r\n\tTIMED_OUT\x10\x02\x12\x13\n\x0fWORKER_SHUTDOWN\x10\x03\x12\n\n\x06PAUSED\x10\x04\x12\t\n\x05RESET\x10\x05\x42\x32\xea\x02/Temporalio::Internal::Bridge::Api::ActivityTaskb\x06proto3' + b'\n3temporal/sdk/core/activity_task/activity_task.proto\x12\x15\x63oresdk.activity_task\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a$temporal/api/common/v1/message.proto\x1a#temporal/api/nexus/v1/message.proto\x1a%temporal/sdk/core/common/common.proto"\x8d\x01\n\x0c\x41\x63tivityTask\x12\x12\n\ntask_token\x18\x01 \x01(\x0c\x12-\n\x05start\x18\x03 \x01(\x0b\x32\x1c.coresdk.activity_task.StartH\x00\x12/\n\x06\x63\x61ncel\x18\x04 \x01(\x0b\x32\x1d.coresdk.activity_task.CancelH\x00\x42\t\n\x07variant"\xbb\t\n\x05Start\x12\x1a\n\x12workflow_namespace\x18\x01 \x01(\t\x12\x15\n\rworkflow_type\x18\x02 \x01(\t\x12\x45\n\x12workflow_execution\x18\x03 \x01(\x0b\x32).temporal.api.common.v1.WorkflowExecution\x12\x13\n\x0b\x61\x63tivity_id\x18\x04 \x01(\t\x12\x15\n\ractivity_type\x18\x05 \x01(\t\x12\x45\n\rheader_fields\x18\x06 \x03(\x0b\x32..coresdk.activity_task.Start.HeaderFieldsEntry\x12.\n\x05input\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12:\n\x11heartbeat_details\x18\x08 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x32\n\x0escheduled_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x42\n\x1e\x63urrent_attempt_scheduled_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x30\n\x0cstarted_time\x18\x0b \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07\x61ttempt\x18\x0c \x01(\r\x12<\n\x19schedule_to_close_timeout\x18\r \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\x0e \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x34\n\x11heartbeat_timeout\x18\x0f \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x10 \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x32\n\x08priority\x18\x12 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12\x10\n\x08is_local\x18\x11 \x01(\x08\x12\x0e\n\x06run_id\x18\x13 \x01(\t\x12\x65\n&propagated_nexus_serialization_context\x18\x14 \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x12\x41\n\rworkflow_task\x18\x15 \x01(\x0b\x32*.coresdk.activity_task.WorkflowTaskAttempt\x12\x1a\n\x12scheduled_event_id\x18\x16 \x01(\x03\x12\x42\n\x15local_activity_origin\x18\x17 \x01(\x0b\x32#.coresdk.common.LocalActivityOrigin\x1aT\n\x11HeaderFieldsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x80\x02\n\x13WorkflowTaskAttempt\x12\x18\n\x10started_event_id\x18\x01 \x01(\x03\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\r\x12\x30\n\x0cstarted_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12!\n\x19previous_started_event_id\x18\x04 \x01(\x03\x12\x14\n\x0c\x66\x61iled_tasks\x18\x05 \x03(\x03\x12\x18\n\x10previous_attempt\x18\x06 \x01(\r\x12\x39\n\x15previous_started_time\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"\x8a\x01\n\x06\x43\x61ncel\x12;\n\x06reason\x18\x01 \x01(\x0e\x32+.coresdk.activity_task.ActivityCancelReason\x12\x43\n\x07\x64\x65tails\x18\x02 \x01(\x0b\x32\x32.coresdk.activity_task.ActivityCancellationDetails"\xa0\x01\n\x1b\x41\x63tivityCancellationDetails\x12\x14\n\x0cis_not_found\x18\x01 \x01(\x08\x12\x14\n\x0cis_cancelled\x18\x02 \x01(\x08\x12\x11\n\tis_paused\x18\x03 \x01(\x08\x12\x14\n\x0cis_timed_out\x18\x04 \x01(\x08\x12\x1a\n\x12is_worker_shutdown\x18\x05 \x01(\x08\x12\x10\n\x08is_reset\x18\x06 \x01(\x08*o\n\x14\x41\x63tivityCancelReason\x12\r\n\tNOT_FOUND\x10\x00\x12\r\n\tCANCELLED\x10\x01\x12\r\n\tTIMED_OUT\x10\x02\x12\x13\n\x0fWORKER_SHUTDOWN\x10\x03\x12\n\n\x06PAUSED\x10\x04\x12\t\n\x05RESET\x10\x05\x42\x32\xea\x02/Temporalio::Internal::Bridge::Api::ActivityTaskb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -39,18 +39,18 @@ ) _START_HEADERFIELDSENTRY._options = None _START_HEADERFIELDSENTRY._serialized_options = b"8\001" - _ACTIVITYCANCELREASON._serialized_start = 2082 - _ACTIVITYCANCELREASON._serialized_end = 2193 + _ACTIVITYCANCELREASON._serialized_start = 2178 + _ACTIVITYCANCELREASON._serialized_end = 2289 _ACTIVITYTASK._serialized_start = 258 _ACTIVITYTASK._serialized_end = 399 _START._serialized_start = 402 - _START._serialized_end = 1517 - _START_HEADERFIELDSENTRY._serialized_start = 1433 - _START_HEADERFIELDSENTRY._serialized_end = 1517 - _WORKFLOWTASKATTEMPT._serialized_start = 1520 - _WORKFLOWTASKATTEMPT._serialized_end = 1776 - _CANCEL._serialized_start = 1779 - _CANCEL._serialized_end = 1917 - _ACTIVITYCANCELLATIONDETAILS._serialized_start = 1920 - _ACTIVITYCANCELLATIONDETAILS._serialized_end = 2080 + _START._serialized_end = 1613 + _START_HEADERFIELDSENTRY._serialized_start = 1529 + _START_HEADERFIELDSENTRY._serialized_end = 1613 + _WORKFLOWTASKATTEMPT._serialized_start = 1616 + _WORKFLOWTASKATTEMPT._serialized_end = 1872 + _CANCEL._serialized_start = 1875 + _CANCEL._serialized_end = 2013 + _ACTIVITYCANCELLATIONDETAILS._serialized_start = 2016 + _ACTIVITYCANCELLATIONDETAILS._serialized_end = 2176 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi b/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi index 345b0a6b1e..9efccb2059 100644 --- a/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi +++ b/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi @@ -19,6 +19,7 @@ import google.protobuf.timestamp_pb2 import temporalio.api.common.v1.message_pb2 import temporalio.api.nexus.v1.message_pb2 +import temporalio.bridge.proto.common.common_pb2 if sys.version_info >= (3, 10): import typing as typing_extensions @@ -167,6 +168,8 @@ class Start(google.protobuf.message.Message): RUN_ID_FIELD_NUMBER: builtins.int PROPAGATED_NEXUS_SERIALIZATION_CONTEXT_FIELD_NUMBER: builtins.int WORKFLOW_TASK_FIELD_NUMBER: builtins.int + SCHEDULED_EVENT_ID_FIELD_NUMBER: builtins.int + LOCAL_ACTIVITY_ORIGIN_FIELD_NUMBER: builtins.int workflow_namespace: builtins.str """The namespace the workflow lives in""" workflow_type: builtins.str @@ -182,6 +185,10 @@ class Start(google.protobuf.message.Message): """ run_id: builtins.str """Run ID of this activity execution. Only set for standalone activities.""" + scheduled_event_id: builtins.int + """For an activity that a workflow scheduled, the event id of its ActivityTaskScheduled event. + 0 for a local activity, for a standalone activity, and when Core can't read it. + """ @property def workflow_execution( self, @@ -260,6 +267,14 @@ class Start(google.protobuf.message.Message): Core runs locally keep the value. Unset for other activities. """ + @property + def local_activity_origin( + self, + ) -> temporalio.bridge.proto.common.common_pb2.LocalActivityOrigin: + """For a local activity, its origin. All its attempts have the same origin, also attempts that + Lang schedules again after a timer-backed backoff. Unset for other activities. + """ + def __init__( self, *, @@ -294,6 +309,9 @@ class Start(google.protobuf.message.Message): propagated_nexus_serialization_context: temporalio.api.nexus.v1.message_pb2.PropagatedSerializationContext | None = ..., workflow_task: global___WorkflowTaskAttempt | None = ..., + scheduled_event_id: builtins.int = ..., + local_activity_origin: temporalio.bridge.proto.common.common_pb2.LocalActivityOrigin + | None = ..., ) -> None: ... def HasField( self, @@ -302,6 +320,8 @@ class Start(google.protobuf.message.Message): b"current_attempt_scheduled_time", "heartbeat_timeout", b"heartbeat_timeout", + "local_activity_origin", + b"local_activity_origin", "priority", b"priority", "propagated_nexus_serialization_context", @@ -343,6 +363,8 @@ class Start(google.protobuf.message.Message): b"input", "is_local", b"is_local", + "local_activity_origin", + b"local_activity_origin", "priority", b"priority", "propagated_nexus_serialization_context", @@ -353,6 +375,8 @@ class Start(google.protobuf.message.Message): b"run_id", "schedule_to_close_timeout", b"schedule_to_close_timeout", + "scheduled_event_id", + b"scheduled_event_id", "scheduled_time", b"scheduled_time", "start_to_close_timeout", diff --git a/temporalio/bridge/proto/common/__init__.py b/temporalio/bridge/proto/common/__init__.py index a8506090de..c7fdd2e4b8 100644 --- a/temporalio/bridge/proto/common/__init__.py +++ b/temporalio/bridge/proto/common/__init__.py @@ -1,5 +1,6 @@ from .common_pb2 import ( ExternalStorageMetrics, + LocalActivityOrigin, NamespacedWorkflowExecution, VersioningIntent, WorkerDeploymentVersion, @@ -7,6 +8,7 @@ __all__ = [ "ExternalStorageMetrics", + "LocalActivityOrigin", "NamespacedWorkflowExecution", "VersioningIntent", "WorkerDeploymentVersion", diff --git a/temporalio/bridge/proto/common/common_pb2.py b/temporalio/bridge/proto/common/common_pb2.py index 0b9a5c8169..abe2596725 100644 --- a/temporalio/bridge/proto/common/common_pb2.py +++ b/temporalio/bridge/proto/common/common_pb2.py @@ -16,7 +16,7 @@ from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n%temporal/sdk/core/common/common.proto\x12\x0e\x63oresdk.common\x1a\x1egoogle/protobuf/duration.proto"U\n\x1bNamespacedWorkflowExecution\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t"D\n\x17WorkerDeploymentVersion\x12\x17\n\x0f\x64\x65ployment_name\x18\x01 \x01(\t\x12\x10\n\x08\x62uild_id\x18\x02 \x01(\t"\x92\x01\n\x16\x45xternalStorageMetrics\x12\x15\n\rpayload_count\x18\x01 \x01(\x04\x12\x18\n\x10total_size_bytes\x18\x02 \x01(\x04\x12\x31\n\x0etotal_duration\x18\x03 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x14\n\x0c\x64river_names\x18\x04 \x03(\t*@\n\x10VersioningIntent\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nCOMPATIBLE\x10\x01\x12\x0b\n\x07\x44\x45\x46\x41ULT\x10\x02\x42,\xea\x02)Temporalio::Internal::Bridge::Api::Commonb\x06proto3' + b'\n%temporal/sdk/core/common/common.proto\x12\x0e\x63oresdk.common\x1a\x1egoogle/protobuf/duration.proto"7\n\x13LocalActivityOrigin\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t"U\n\x1bNamespacedWorkflowExecution\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t"D\n\x17WorkerDeploymentVersion\x12\x17\n\x0f\x64\x65ployment_name\x18\x01 \x01(\t\x12\x10\n\x08\x62uild_id\x18\x02 \x01(\t"\x92\x01\n\x16\x45xternalStorageMetrics\x12\x15\n\rpayload_count\x18\x01 \x01(\x04\x12\x18\n\x10total_size_bytes\x18\x02 \x01(\x04\x12\x31\n\x0etotal_duration\x18\x03 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x14\n\x0c\x64river_names\x18\x04 \x03(\t*@\n\x10VersioningIntent\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nCOMPATIBLE\x10\x01\x12\x0b\n\x07\x44\x45\x46\x41ULT\x10\x02\x42,\xea\x02)Temporalio::Internal::Bridge::Api::Commonb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -26,12 +26,14 @@ DESCRIPTOR._serialized_options = ( b"\352\002)Temporalio::Internal::Bridge::Api::Common" ) - _VERSIONINGINTENT._serialized_start = 395 - _VERSIONINGINTENT._serialized_end = 459 - _NAMESPACEDWORKFLOWEXECUTION._serialized_start = 89 - _NAMESPACEDWORKFLOWEXECUTION._serialized_end = 174 - _WORKERDEPLOYMENTVERSION._serialized_start = 176 - _WORKERDEPLOYMENTVERSION._serialized_end = 244 - _EXTERNALSTORAGEMETRICS._serialized_start = 247 - _EXTERNALSTORAGEMETRICS._serialized_end = 393 + _VERSIONINGINTENT._serialized_start = 452 + _VERSIONINGINTENT._serialized_end = 516 + _LOCALACTIVITYORIGIN._serialized_start = 89 + _LOCALACTIVITYORIGIN._serialized_end = 144 + _NAMESPACEDWORKFLOWEXECUTION._serialized_start = 146 + _NAMESPACEDWORKFLOWEXECUTION._serialized_end = 231 + _WORKERDEPLOYMENTVERSION._serialized_start = 233 + _WORKERDEPLOYMENTVERSION._serialized_end = 301 + _EXTERNALSTORAGEMETRICS._serialized_start = 304 + _EXTERNALSTORAGEMETRICS._serialized_end = 450 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/common/common_pb2.pyi b/temporalio/bridge/proto/common/common_pb2.pyi index 7c2b057024..b438df0003 100644 --- a/temporalio/bridge/proto/common/common_pb2.pyi +++ b/temporalio/bridge/proto/common/common_pb2.pyi @@ -68,6 +68,32 @@ build ID. """ global___VersioningIntent = VersioningIntent +@typing.final +class LocalActivityOrigin(google.protobuf.message.Message): + """Identifies one local activity in its workflow run, over all its attempts. A timer-backed backoff + schedules the next attempt as a new local activity, but that attempt keeps this origin. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + ACTIVITY_ID_FIELD_NUMBER: builtins.int + seq: builtins.int + """The `seq` of the command that scheduled the first attempt.""" + activity_id: builtins.str + """The activity id of the first attempt.""" + def __init__( + self, + *, + seq: builtins.int = ..., + activity_id: builtins.str = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["activity_id", b"activity_id", "seq", b"seq"] + ) -> None: ... + +global___LocalActivityOrigin = LocalActivityOrigin + @typing.final class NamespacedWorkflowExecution(google.protobuf.message.Message): """Identifying information about a particular workflow execution, including namespace""" diff --git a/temporalio/bridge/proto/external_data/__init__.py b/temporalio/bridge/proto/external_data/__init__.py index 836e97ef43..1d221dc4b8 100644 --- a/temporalio/bridge/proto/external_data/__init__.py +++ b/temporalio/bridge/proto/external_data/__init__.py @@ -1,6 +1,19 @@ -from .external_data_pb2 import LocalActivityMarkerData, PatchedMarkerData +from .external_data_pb2 import ( + LocalActivityMarkerData, + PatchedMarkerData, + StreamAppendMarkerData, + StreamAppendOffsets, + StreamAppendOrigin, + StreamAppendResult, + StreamFailure, +) __all__ = [ "LocalActivityMarkerData", "PatchedMarkerData", + "StreamAppendMarkerData", + "StreamAppendOffsets", + "StreamAppendOrigin", + "StreamAppendResult", + "StreamFailure", ] diff --git a/temporalio/bridge/proto/external_data/external_data_pb2.py b/temporalio/bridge/proto/external_data/external_data_pb2.py index 4bda6f5144..a4b6cd4f3c 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.py +++ b/temporalio/bridge/proto/external_data/external_data_pb2.py @@ -16,8 +16,12 @@ from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 +from temporalio.bridge.proto.common import ( + common_pb2 as temporal_dot_sdk_dot_core_dot_common_dot_common__pb2, +) + DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n3temporal/sdk/core/external_data/external_data.proto\x12\x15\x63oresdk.external_data\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xb2\x02\n\x17LocalActivityMarkerData\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x03 \x01(\t\x12\x15\n\ractivity_type\x18\x04 \x01(\t\x12\x31\n\rcomplete_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12*\n\x07\x62\x61\x63koff\x18\x06 \x01(\x0b\x32\x19.google.protobuf.Duration\x12:\n\x16original_schedule_time\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x1d\n\x10\x61\x63tivation_index\x18\x08 \x01(\x04H\x00\x88\x01\x01\x42\x13\n\x11_activation_index"3\n\x11PatchedMarkerData\x12\n\n\x02id\x18\x01 \x01(\t\x12\x12\n\ndeprecated\x18\x02 \x01(\x08\x42\x32\xea\x02/Temporalio::Internal::Bridge::Api::ExternalDatab\x06proto3' + b'\n3temporal/sdk/core/external_data/external_data.proto\x12\x15\x63oresdk.external_data\x1a\x1egoogle/protobuf/duration.proto\x1a%temporal/sdk/core/common/common.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xf6\x02\n\x17LocalActivityMarkerData\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x03 \x01(\t\x12\x15\n\ractivity_type\x18\x04 \x01(\t\x12\x31\n\rcomplete_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12*\n\x07\x62\x61\x63koff\x18\x06 \x01(\x0b\x32\x19.google.protobuf.Duration\x12:\n\x16original_schedule_time\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x1d\n\x10\x61\x63tivation_index\x18\x08 \x01(\x04H\x00\x88\x01\x01\x12\x42\n\x15local_activity_origin\x18\t \x01(\x0b\x32#.coresdk.common.LocalActivityOriginB\x13\n\x11_activation_index"3\n\x11PatchedMarkerData\x12\n\n\x02id\x18\x01 \x01(\t\x12\x12\n\ndeprecated\x18\x02 \x01(\x08"\x97\x01\n\x16StreamAppendMarkerData\x12:\n\x07\x61ppends\x18\x01 \x03(\x0b\x32).coresdk.external_data.StreamAppendResult\x12\x41\n\x0epending_origin\x18\x02 \x01(\x0b\x32).coresdk.external_data.StreamAppendOrigin"\x8b\x01\n\x12StreamAppendOrigin\x12\x18\n\x10workflow_task_id\x18\x01 \x01(\x03\x12\x18\n\x10started_event_id\x18\x02 \x01(\x03\x12\x0f\n\x07\x61ttempt\x18\x03 \x01(\x05\x12\x30\n\x0cstarted_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"\xe0\x01\n\x12StreamAppendResult\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x11\n\tstream_id\x18\x02 \x01(\t\x12\r\n\x05store\x18\x03 \x01(\t\x12\x18\n\x10\x61\x63tivation_index\x18\x04 \x01(\x04\x12>\n\x08\x61ppended\x18\x05 \x01(\x0b\x32*.coresdk.external_data.StreamAppendOffsetsH\x00\x12\x37\n\x07\x66\x61ilure\x18\x06 \x01(\x0b\x32$.coresdk.external_data.StreamFailureH\x00\x42\x08\n\x06result"@\n\x13StreamAppendOffsets\x12\x14\n\x0c\x66irst_offset\x18\x01 \x01(\x0c\x12\x13\n\x0blast_offset\x18\x02 \x01(\x0c"0\n\rStreamFailure\x12\x0e\n\x06reason\x18\x01 \x01(\t\x12\x0f\n\x07message\x18\x02 \x01(\tB2\xea\x02/Temporalio::Internal::Bridge::Api::ExternalDatab\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -27,8 +31,18 @@ DESCRIPTOR._serialized_options = ( b"\352\002/Temporalio::Internal::Bridge::Api::ExternalData" ) - _LOCALACTIVITYMARKERDATA._serialized_start = 144 - _LOCALACTIVITYMARKERDATA._serialized_end = 450 - _PATCHEDMARKERDATA._serialized_start = 452 - _PATCHEDMARKERDATA._serialized_end = 503 + _LOCALACTIVITYMARKERDATA._serialized_start = 183 + _LOCALACTIVITYMARKERDATA._serialized_end = 557 + _PATCHEDMARKERDATA._serialized_start = 559 + _PATCHEDMARKERDATA._serialized_end = 610 + _STREAMAPPENDMARKERDATA._serialized_start = 613 + _STREAMAPPENDMARKERDATA._serialized_end = 764 + _STREAMAPPENDORIGIN._serialized_start = 767 + _STREAMAPPENDORIGIN._serialized_end = 906 + _STREAMAPPENDRESULT._serialized_start = 909 + _STREAMAPPENDRESULT._serialized_end = 1133 + _STREAMAPPENDOFFSETS._serialized_start = 1135 + _STREAMAPPENDOFFSETS._serialized_end = 1199 + _STREAMFAILURE._serialized_start = 1201 + _STREAMFAILURE._serialized_end = 1249 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/external_data/external_data_pb2.pyi b/temporalio/bridge/proto/external_data/external_data_pb2.pyi index edcd4581a1..0ef68ee498 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.pyi +++ b/temporalio/bridge/proto/external_data/external_data_pb2.pyi @@ -4,13 +4,17 @@ isort:skip_file """ import builtins +import collections.abc import typing import google.protobuf.descriptor import google.protobuf.duration_pb2 +import google.protobuf.internal.containers import google.protobuf.message import google.protobuf.timestamp_pb2 +import temporalio.bridge.proto.common.common_pb2 + DESCRIPTOR: google.protobuf.descriptor.FileDescriptor @typing.final @@ -30,6 +34,7 @@ class LocalActivityMarkerData(google.protobuf.message.Message): BACKOFF_FIELD_NUMBER: builtins.int ORIGINAL_SCHEDULE_TIME_FIELD_NUMBER: builtins.int ACTIVATION_INDEX_FIELD_NUMBER: builtins.int + LOCAL_ACTIVITY_ORIGIN_FIELD_NUMBER: builtins.int seq: builtins.int attempt: builtins.int """The number of attempts at execution before we recorded this result. Typically starts at 1, @@ -62,6 +67,12 @@ class LocalActivityMarkerData(google.protobuf.message.Message): schedule-to-close timeouts when timer-based backoffs are used """ + @property + def local_activity_origin( + self, + ) -> temporalio.bridge.proto.common.common_pb2.LocalActivityOrigin: + """Replay of a backoff must give the retry its original scheduling identity.""" + def __init__( self, *, @@ -73,6 +84,8 @@ class LocalActivityMarkerData(google.protobuf.message.Message): backoff: google.protobuf.duration_pb2.Duration | None = ..., original_schedule_time: google.protobuf.timestamp_pb2.Timestamp | None = ..., activation_index: builtins.int | None = ..., + local_activity_origin: temporalio.bridge.proto.common.common_pb2.LocalActivityOrigin + | None = ..., ) -> None: ... def HasField( self, @@ -85,6 +98,8 @@ class LocalActivityMarkerData(google.protobuf.message.Message): b"backoff", "complete_time", b"complete_time", + "local_activity_origin", + b"local_activity_origin", "original_schedule_time", b"original_schedule_time", ], @@ -106,6 +121,8 @@ class LocalActivityMarkerData(google.protobuf.message.Message): b"backoff", "complete_time", b"complete_time", + "local_activity_origin", + b"local_activity_origin", "original_schedule_time", b"original_schedule_time", "seq", @@ -139,3 +156,212 @@ class PatchedMarkerData(google.protobuf.message.Message): ) -> None: ... global___PatchedMarkerData = PatchedMarkerData + +@typing.final +class StreamAppendMarkerData(google.protobuf.message.Message): + """The JSON data of a `core_stream_append` marker. Core records one marker for each activation + that gives Workflow code the result of an append. A replay takes the results from the marker and + gives them in the same activation. The `bytes` fields are Base64 in the JSON. + + A marker can have no result. Core records one when a Workflow Task completes while an append is + still running. See `pending_origin`. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + APPENDS_FIELD_NUMBER: builtins.int + PENDING_ORIGIN_FIELD_NUMBER: builtins.int + @property + def appends( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___StreamAppendResult + ]: + """The results that Workflow code got in the activation.""" + + @property + def pending_origin(self) -> global___StreamAppendOrigin: + """Set when the Workflow Task completed before Workflow code got the result of an append that + started in it. If another Worker takes over the run, it sends that append again with the same + Producer attempt and the same request id. The Store can then recognize a write that it + already has. + """ + + def __init__( + self, + *, + appends: collections.abc.Iterable[global___StreamAppendResult] | None = ..., + pending_origin: global___StreamAppendOrigin | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["pending_origin", b"pending_origin"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "appends", b"appends", "pending_origin", b"pending_origin" + ], + ) -> None: ... + +global___StreamAppendMarkerData = StreamAppendMarkerData + +@typing.final +class StreamAppendOrigin(google.protobuf.message.Message): + """The Workflow Task attempt in which an append started. Its fields are the task fields of the + `WorkflowProducer` that writes the append. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + WORKFLOW_TASK_ID_FIELD_NUMBER: builtins.int + STARTED_EVENT_ID_FIELD_NUMBER: builtins.int + ATTEMPT_FIELD_NUMBER: builtins.int + STARTED_TIME_FIELD_NUMBER: builtins.int + workflow_task_id: builtins.int + started_event_id: builtins.int + attempt: builtins.int + @property + def started_time(self) -> google.protobuf.timestamp_pb2.Timestamp: ... + def __init__( + self, + *, + workflow_task_id: builtins.int = ..., + started_event_id: builtins.int = ..., + attempt: builtins.int = ..., + started_time: google.protobuf.timestamp_pb2.Timestamp | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["started_time", b"started_time"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "attempt", + b"attempt", + "started_event_id", + b"started_event_id", + "started_time", + b"started_time", + "workflow_task_id", + b"workflow_task_id", + ], + ) -> None: ... + +global___StreamAppendOrigin = StreamAppendOrigin + +@typing.final +class StreamAppendResult(google.protobuf.message.Message): + """The result of one append, as Workflow code got it.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + STREAM_ID_FIELD_NUMBER: builtins.int + STORE_FIELD_NUMBER: builtins.int + ACTIVATION_INDEX_FIELD_NUMBER: builtins.int + APPENDED_FIELD_NUMBER: builtins.int + FAILURE_FIELD_NUMBER: builtins.int + seq: builtins.int + """The `seq` of the `AppendToStream` command.""" + stream_id: builtins.str + store: builtins.str + """The name of the Store that the append used. For a command with no Store name, it's the name + that Core chose (see `AppendToStream`). + """ + activation_index: builtins.int + """The activation that gave Workflow code the result. Activations count from 0 in each Workflow + Task. + """ + @property + def appended(self) -> global___StreamAppendOffsets: ... + @property + def failure(self) -> global___StreamFailure: ... + def __init__( + self, + *, + seq: builtins.int = ..., + stream_id: builtins.str = ..., + store: builtins.str = ..., + activation_index: builtins.int = ..., + appended: global___StreamAppendOffsets | None = ..., + failure: global___StreamFailure | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "appended", b"appended", "failure", b"failure", "result", b"result" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "activation_index", + b"activation_index", + "appended", + b"appended", + "failure", + b"failure", + "result", + b"result", + "seq", + b"seq", + "store", + b"store", + "stream_id", + b"stream_id", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["result", b"result"] + ) -> typing.Literal["appended", "failure"] | None: ... + +global___StreamAppendResult = StreamAppendResult + +@typing.final +class StreamAppendOffsets(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FIRST_OFFSET_FIELD_NUMBER: builtins.int + LAST_OFFSET_FIELD_NUMBER: builtins.int + first_offset: builtins.bytes + last_offset: builtins.bytes + def __init__( + self, + *, + first_offset: builtins.bytes = ..., + last_offset: builtins.bytes = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "first_offset", b"first_offset", "last_offset", b"last_offset" + ], + ) -> None: ... + +global___StreamAppendOffsets = StreamAppendOffsets + +@typing.final +class StreamFailure(google.protobuf.message.Message): + """Why a Stream call failed. Core builds the failure that Workflow code gets from these two fields.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REASON_FIELD_NUMBER: builtins.int + MESSAGE_FIELD_NUMBER: builtins.int + reason: builtins.str + """The name of a `temporalio.api.enums.v1.StreamErrorReason` value, such as + `STREAM_ERROR_REASON_FENCED`. History keeps the name, so the enum can't rename a value. + """ + message: builtins.str + """The failure message. Core cuts it to 4096 bytes.""" + def __init__( + self, + *, + reason: builtins.str = ..., + message: builtins.str = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["message", b"message", "reason", b"reason"] + ) -> None: ... + +global___StreamFailure = StreamFailure diff --git a/temporalio/bridge/proto/workflow_activation/__init__.py b/temporalio/bridge/proto/workflow_activation/__init__.py index 5c178e2185..453c0eefe8 100644 --- a/temporalio/bridge/proto/workflow_activation/__init__.py +++ b/temporalio/bridge/proto/workflow_activation/__init__.py @@ -16,7 +16,9 @@ ResolveNexusOperationStart, ResolveRequestCancelExternalWorkflow, ResolveSignalExternalWorkflow, + ResolveStreamAppend, SignalWorkflow, + StreamAppended, UpdateRandomSeed, WorkflowActivation, WorkflowActivationJob, @@ -40,7 +42,9 @@ "ResolveNexusOperationStart", "ResolveRequestCancelExternalWorkflow", "ResolveSignalExternalWorkflow", + "ResolveStreamAppend", "SignalWorkflow", + "StreamAppended", "UpdateRandomSeed", "WorkflowActivation", "WorkflowActivationJob", diff --git a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py index 589119c72b..bfae7abbde 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py @@ -49,7 +49,7 @@ ) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n?temporal/sdk/core/workflow_activation/workflow_activation.proto\x12\x1b\x63oresdk.workflow_activation\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a%temporal/api/failure/v1/message.proto\x1a#temporal/api/nexus/v1/message.proto\x1a$temporal/api/update/v1/message.proto\x1a$temporal/api/common/v1/message.proto\x1a(temporal/api/enums/v1/failed_cause.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a\x37temporal/sdk/core/activity_result/activity_result.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a%temporal/sdk/core/common/common.proto\x1a#temporal/sdk/core/nexus/nexus.proto"\xa2\x04\n\x12WorkflowActivation\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x14\n\x0cis_replaying\x18\x03 \x01(\x08\x12\x16\n\x0ehistory_length\x18\x04 \x01(\r\x12@\n\x04jobs\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.WorkflowActivationJob\x12 \n\x18\x61vailable_internal_flags\x18\x06 \x03(\r\x12\x1a\n\x12history_size_bytes\x18\x07 \x01(\x04\x12!\n\x19\x63ontinue_as_new_suggested\x18\x08 \x01(\x08\x12T\n#deployment_version_for_current_task\x18\t \x01(\x0b\x32\'.coresdk.common.WorkerDeploymentVersion\x12\x18\n\x10last_sdk_version\x18\n \x01(\t\x12Z\n\x1fsuggest_continue_as_new_reasons\x18\x0b \x03(\x0e\x32\x31.temporal.api.enums.v1.SuggestContinueAsNewReason\x12\x30\n(target_worker_deployment_version_changed\x18\x0c \x01(\x08"\xe0\n\n\x15WorkflowActivationJob\x12N\n\x13initialize_workflow\x18\x01 \x01(\x0b\x32/.coresdk.workflow_activation.InitializeWorkflowH\x00\x12<\n\nfire_timer\x18\x02 \x01(\x0b\x32&.coresdk.workflow_activation.FireTimerH\x00\x12K\n\x12update_random_seed\x18\x04 \x01(\x0b\x32-.coresdk.workflow_activation.UpdateRandomSeedH\x00\x12\x44\n\x0equery_workflow\x18\x05 \x01(\x0b\x32*.coresdk.workflow_activation.QueryWorkflowH\x00\x12\x46\n\x0f\x63\x61ncel_workflow\x18\x06 \x01(\x0b\x32+.coresdk.workflow_activation.CancelWorkflowH\x00\x12\x46\n\x0fsignal_workflow\x18\x07 \x01(\x0b\x32+.coresdk.workflow_activation.SignalWorkflowH\x00\x12H\n\x10resolve_activity\x18\x08 \x01(\x0b\x32,.coresdk.workflow_activation.ResolveActivityH\x00\x12G\n\x10notify_has_patch\x18\t \x01(\x0b\x32+.coresdk.workflow_activation.NotifyHasPatchH\x00\x12q\n&resolve_child_workflow_execution_start\x18\n \x01(\x0b\x32?.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartH\x00\x12\x66\n resolve_child_workflow_execution\x18\x0b \x01(\x0b\x32:.coresdk.workflow_activation.ResolveChildWorkflowExecutionH\x00\x12\x66\n resolve_signal_external_workflow\x18\x0c \x01(\x0b\x32:.coresdk.workflow_activation.ResolveSignalExternalWorkflowH\x00\x12u\n(resolve_request_cancel_external_workflow\x18\r \x01(\x0b\x32\x41.coresdk.workflow_activation.ResolveRequestCancelExternalWorkflowH\x00\x12:\n\tdo_update\x18\x0e \x01(\x0b\x32%.coresdk.workflow_activation.DoUpdateH\x00\x12`\n\x1dresolve_nexus_operation_start\x18\x0f \x01(\x0b\x32\x37.coresdk.workflow_activation.ResolveNexusOperationStartH\x00\x12U\n\x17resolve_nexus_operation\x18\x10 \x01(\x0b\x32\x32.coresdk.workflow_activation.ResolveNexusOperationH\x00\x12I\n\x11remove_from_cache\x18\x32 \x01(\x0b\x32,.coresdk.workflow_activation.RemoveFromCacheH\x00\x42\t\n\x07variant"\xe3\x0b\n\x12InitializeWorkflow\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x17\n\x0frandomness_seed\x18\x04 \x01(\x04\x12M\n\x07headers\x18\x05 \x03(\x0b\x32<.coresdk.workflow_activation.InitializeWorkflow.HeadersEntry\x12\x10\n\x08identity\x18\x06 \x01(\t\x12I\n\x14parent_workflow_info\x18\x07 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12=\n\x1aworkflow_execution_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\'\n\x1f\x63ontinued_from_execution_run_id\x18\x0b \x01(\t\x12J\n\x13\x63ontinued_initiator\x18\x0c \x01(\x0e\x32-.temporal.api.enums.v1.ContinueAsNewInitiator\x12;\n\x11\x63ontinued_failure\x18\r \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12@\n\x16last_completion_result\x18\x0e \x01(\x0b\x32 .temporal.api.common.v1.Payloads\x12\x1e\n\x16\x66irst_execution_run_id\x18\x0f \x01(\t\x12\x39\n\x0cretry_policy\x18\x10 \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x0f\n\x07\x61ttempt\x18\x11 \x01(\x05\x12\x15\n\rcron_schedule\x18\x12 \x01(\t\x12\x46\n"workflow_execution_expiration_time\x18\x13 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x45\n"cron_schedule_to_schedule_interval\x18\x14 \x01(\x0b\x32\x19.google.protobuf.Duration\x12*\n\x04memo\x18\x15 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo\x12\x43\n\x11search_attributes\x18\x16 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12.\n\nstart_time\x18\x17 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12@\n\rroot_workflow\x18\x18 \x01(\x0b\x32).temporal.api.common.v1.WorkflowExecution\x12\x32\n\x08priority\x18\x19 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12!\n\x19original_execution_run_id\x18\x1a \x01(\t\x12\x65\n&propagated_nexus_serialization_context\x18\x1b \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x18\n\tFireTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"m\n\x0fResolveActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.activity_result.ActivityResolution\x12\x10\n\x08is_local\x18\x03 \x01(\x08"\xd1\x02\n"ResolveChildWorkflowExecutionStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12[\n\tsucceeded\x18\x02 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartSuccessH\x00\x12X\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartFailureH\x00\x12]\n\tcancelled\x18\x04 \x01(\x0b\x32H.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartCancelledH\x00\x42\x08\n\x06status";\n)ResolveChildWorkflowExecutionStartSuccess\x12\x0e\n\x06run_id\x18\x01 \x01(\t"\xa6\x01\n)ResolveChildWorkflowExecutionStartFailure\x12\x13\n\x0bworkflow_id\x18\x01 \x01(\t\x12\x15\n\rworkflow_type\x18\x02 \x01(\t\x12M\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32>.coresdk.child_workflow.StartChildWorkflowExecutionFailedCause"`\n+ResolveChildWorkflowExecutionStartCancelled\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"i\n\x1dResolveChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.child_workflow.ChildWorkflowResult"+\n\x10UpdateRandomSeed\x12\x17\n\x0frandomness_seed\x18\x01 \x01(\x04"\x84\x02\n\rQueryWorkflow\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12\x12\n\nquery_type\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12H\n\x07headers\x18\x05 \x03(\x0b\x32\x37.coresdk.workflow_activation.QueryWorkflow.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01" \n\x0e\x43\x61ncelWorkflow\x12\x0e\n\x06reason\x18\x01 \x01(\t"\xa1\x02\n\x0eSignalWorkflow\x12\x13\n\x0bsignal_name\x18\x01 \x01(\t\x12.\n\x05input\x18\x02 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x10\n\x08identity\x18\x03 \x01(\t\x12I\n\x07headers\x18\x05 \x03(\x0b\x32\x38.coresdk.workflow_activation.SignalWorkflow.HeadersEntry\x12\x1c\n\x14originating_event_id\x18\x06 \x01(\x03\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01""\n\x0eNotifyHasPatch\x12\x10\n\x08patch_id\x18\x01 \x01(\t"\xb1\x01\n\x1dResolveSignalExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.SignalExternalWorkflowExecutionFailedCause"\xb8\x01\n$ResolveRequestCancelExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.CancelExternalWorkflowExecutionFailedCause"\xb2\x03\n\x08\x44oUpdate\x12\n\n\x02id\x18\x01 \x01(\t\x12\x1c\n\x14protocol_instance_id\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12.\n\x05input\x18\x04 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x43\n\x07headers\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.DoUpdate.HeadersEntry\x12*\n\x04meta\x18\x06 \x01(\x0b\x32\x1c.temporal.api.update.v1.Meta\x12\x15\n\rrun_validator\x18\x07 \x01(\x08\x12\x65\n&propagated_nexus_serialization_context\x18\x08 \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x9a\x01\n\x1aResolveNexusOperationStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x19\n\x0foperation_token\x18\x02 \x01(\tH\x00\x12\x16\n\x0cstarted_sync\x18\x03 \x01(\x08H\x00\x12\x32\n\x06\x66\x61iled\x18\x04 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status"Y\n\x15ResolveNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x33\n\x06result\x18\x02 \x01(\x0b\x32#.coresdk.nexus.NexusOperationResult"\xe0\x02\n\x0fRemoveFromCache\x12\x0f\n\x07message\x18\x01 \x01(\t\x12K\n\x06reason\x18\x02 \x01(\x0e\x32;.coresdk.workflow_activation.RemoveFromCache.EvictionReason"\xee\x01\n\x0e\x45victionReason\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nCACHE_FULL\x10\x01\x12\x0e\n\nCACHE_MISS\x10\x02\x12\x12\n\x0eNONDETERMINISM\x10\x03\x12\r\n\tLANG_FAIL\x10\x04\x12\x12\n\x0eLANG_REQUESTED\x10\x05\x12\x12\n\x0eTASK_NOT_FOUND\x10\x06\x12\x15\n\x11UNHANDLED_COMMAND\x10\x07\x12\t\n\x05\x46\x41TAL\x10\x08\x12\x1f\n\x1bPAGINATION_OR_HISTORY_FETCH\x10\t\x12\x1d\n\x19WORKFLOW_EXECUTION_ENDING\x10\nB8\xea\x02\x35Temporalio::Internal::Bridge::Api::WorkflowActivationb\x06proto3' + b'\n?temporal/sdk/core/workflow_activation/workflow_activation.proto\x12\x1b\x63oresdk.workflow_activation\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a%temporal/api/failure/v1/message.proto\x1a#temporal/api/nexus/v1/message.proto\x1a$temporal/api/update/v1/message.proto\x1a$temporal/api/common/v1/message.proto\x1a(temporal/api/enums/v1/failed_cause.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a\x37temporal/sdk/core/activity_result/activity_result.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a%temporal/sdk/core/common/common.proto\x1a#temporal/sdk/core/nexus/nexus.proto"\xa2\x04\n\x12WorkflowActivation\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x14\n\x0cis_replaying\x18\x03 \x01(\x08\x12\x16\n\x0ehistory_length\x18\x04 \x01(\r\x12@\n\x04jobs\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.WorkflowActivationJob\x12 \n\x18\x61vailable_internal_flags\x18\x06 \x03(\r\x12\x1a\n\x12history_size_bytes\x18\x07 \x01(\x04\x12!\n\x19\x63ontinue_as_new_suggested\x18\x08 \x01(\x08\x12T\n#deployment_version_for_current_task\x18\t \x01(\x0b\x32\'.coresdk.common.WorkerDeploymentVersion\x12\x18\n\x10last_sdk_version\x18\n \x01(\t\x12Z\n\x1fsuggest_continue_as_new_reasons\x18\x0b \x03(\x0e\x32\x31.temporal.api.enums.v1.SuggestContinueAsNewReason\x12\x30\n(target_worker_deployment_version_changed\x18\x0c \x01(\x08"\xb3\x0b\n\x15WorkflowActivationJob\x12N\n\x13initialize_workflow\x18\x01 \x01(\x0b\x32/.coresdk.workflow_activation.InitializeWorkflowH\x00\x12<\n\nfire_timer\x18\x02 \x01(\x0b\x32&.coresdk.workflow_activation.FireTimerH\x00\x12K\n\x12update_random_seed\x18\x04 \x01(\x0b\x32-.coresdk.workflow_activation.UpdateRandomSeedH\x00\x12\x44\n\x0equery_workflow\x18\x05 \x01(\x0b\x32*.coresdk.workflow_activation.QueryWorkflowH\x00\x12\x46\n\x0f\x63\x61ncel_workflow\x18\x06 \x01(\x0b\x32+.coresdk.workflow_activation.CancelWorkflowH\x00\x12\x46\n\x0fsignal_workflow\x18\x07 \x01(\x0b\x32+.coresdk.workflow_activation.SignalWorkflowH\x00\x12H\n\x10resolve_activity\x18\x08 \x01(\x0b\x32,.coresdk.workflow_activation.ResolveActivityH\x00\x12G\n\x10notify_has_patch\x18\t \x01(\x0b\x32+.coresdk.workflow_activation.NotifyHasPatchH\x00\x12q\n&resolve_child_workflow_execution_start\x18\n \x01(\x0b\x32?.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartH\x00\x12\x66\n resolve_child_workflow_execution\x18\x0b \x01(\x0b\x32:.coresdk.workflow_activation.ResolveChildWorkflowExecutionH\x00\x12\x66\n resolve_signal_external_workflow\x18\x0c \x01(\x0b\x32:.coresdk.workflow_activation.ResolveSignalExternalWorkflowH\x00\x12u\n(resolve_request_cancel_external_workflow\x18\r \x01(\x0b\x32\x41.coresdk.workflow_activation.ResolveRequestCancelExternalWorkflowH\x00\x12:\n\tdo_update\x18\x0e \x01(\x0b\x32%.coresdk.workflow_activation.DoUpdateH\x00\x12`\n\x1dresolve_nexus_operation_start\x18\x0f \x01(\x0b\x32\x37.coresdk.workflow_activation.ResolveNexusOperationStartH\x00\x12U\n\x17resolve_nexus_operation\x18\x10 \x01(\x0b\x32\x32.coresdk.workflow_activation.ResolveNexusOperationH\x00\x12Q\n\x15resolve_stream_append\x18\x11 \x01(\x0b\x32\x30.coresdk.workflow_activation.ResolveStreamAppendH\x00\x12I\n\x11remove_from_cache\x18\x32 \x01(\x0b\x32,.coresdk.workflow_activation.RemoveFromCacheH\x00\x42\t\n\x07variant"\xe3\x0b\n\x12InitializeWorkflow\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x17\n\x0frandomness_seed\x18\x04 \x01(\x04\x12M\n\x07headers\x18\x05 \x03(\x0b\x32<.coresdk.workflow_activation.InitializeWorkflow.HeadersEntry\x12\x10\n\x08identity\x18\x06 \x01(\t\x12I\n\x14parent_workflow_info\x18\x07 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12=\n\x1aworkflow_execution_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\'\n\x1f\x63ontinued_from_execution_run_id\x18\x0b \x01(\t\x12J\n\x13\x63ontinued_initiator\x18\x0c \x01(\x0e\x32-.temporal.api.enums.v1.ContinueAsNewInitiator\x12;\n\x11\x63ontinued_failure\x18\r \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12@\n\x16last_completion_result\x18\x0e \x01(\x0b\x32 .temporal.api.common.v1.Payloads\x12\x1e\n\x16\x66irst_execution_run_id\x18\x0f \x01(\t\x12\x39\n\x0cretry_policy\x18\x10 \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x0f\n\x07\x61ttempt\x18\x11 \x01(\x05\x12\x15\n\rcron_schedule\x18\x12 \x01(\t\x12\x46\n"workflow_execution_expiration_time\x18\x13 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x45\n"cron_schedule_to_schedule_interval\x18\x14 \x01(\x0b\x32\x19.google.protobuf.Duration\x12*\n\x04memo\x18\x15 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo\x12\x43\n\x11search_attributes\x18\x16 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12.\n\nstart_time\x18\x17 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12@\n\rroot_workflow\x18\x18 \x01(\x0b\x32).temporal.api.common.v1.WorkflowExecution\x12\x32\n\x08priority\x18\x19 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12!\n\x19original_execution_run_id\x18\x1a \x01(\t\x12\x65\n&propagated_nexus_serialization_context\x18\x1b \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x18\n\tFireTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"m\n\x0fResolveActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.activity_result.ActivityResolution\x12\x10\n\x08is_local\x18\x03 \x01(\x08"\xd1\x02\n"ResolveChildWorkflowExecutionStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12[\n\tsucceeded\x18\x02 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartSuccessH\x00\x12X\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartFailureH\x00\x12]\n\tcancelled\x18\x04 \x01(\x0b\x32H.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartCancelledH\x00\x42\x08\n\x06status";\n)ResolveChildWorkflowExecutionStartSuccess\x12\x0e\n\x06run_id\x18\x01 \x01(\t"\xa6\x01\n)ResolveChildWorkflowExecutionStartFailure\x12\x13\n\x0bworkflow_id\x18\x01 \x01(\t\x12\x15\n\rworkflow_type\x18\x02 \x01(\t\x12M\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32>.coresdk.child_workflow.StartChildWorkflowExecutionFailedCause"`\n+ResolveChildWorkflowExecutionStartCancelled\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"i\n\x1dResolveChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.child_workflow.ChildWorkflowResult"+\n\x10UpdateRandomSeed\x12\x17\n\x0frandomness_seed\x18\x01 \x01(\x04"\x84\x02\n\rQueryWorkflow\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12\x12\n\nquery_type\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12H\n\x07headers\x18\x05 \x03(\x0b\x32\x37.coresdk.workflow_activation.QueryWorkflow.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01" \n\x0e\x43\x61ncelWorkflow\x12\x0e\n\x06reason\x18\x01 \x01(\t"\xa1\x02\n\x0eSignalWorkflow\x12\x13\n\x0bsignal_name\x18\x01 \x01(\t\x12.\n\x05input\x18\x02 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x10\n\x08identity\x18\x03 \x01(\t\x12I\n\x07headers\x18\x05 \x03(\x0b\x32\x38.coresdk.workflow_activation.SignalWorkflow.HeadersEntry\x12\x1c\n\x14originating_event_id\x18\x06 \x01(\x03\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01""\n\x0eNotifyHasPatch\x12\x10\n\x08patch_id\x18\x01 \x01(\t"\xb1\x01\n\x1dResolveSignalExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.SignalExternalWorkflowExecutionFailedCause"\xb8\x01\n$ResolveRequestCancelExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.CancelExternalWorkflowExecutionFailedCause"\xb2\x03\n\x08\x44oUpdate\x12\n\n\x02id\x18\x01 \x01(\t\x12\x1c\n\x14protocol_instance_id\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12.\n\x05input\x18\x04 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x43\n\x07headers\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.DoUpdate.HeadersEntry\x12*\n\x04meta\x18\x06 \x01(\x0b\x32\x1c.temporal.api.update.v1.Meta\x12\x15\n\rrun_validator\x18\x07 \x01(\x08\x12\x65\n&propagated_nexus_serialization_context\x18\x08 \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x9a\x01\n\x1aResolveNexusOperationStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x19\n\x0foperation_token\x18\x02 \x01(\tH\x00\x12\x16\n\x0cstarted_sync\x18\x03 \x01(\x08H\x00\x12\x32\n\x06\x66\x61iled\x18\x04 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status"Y\n\x15ResolveNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x33\n\x06result\x18\x02 \x01(\x0b\x32#.coresdk.nexus.NexusOperationResult"\xe0\x02\n\x0fRemoveFromCache\x12\x0f\n\x07message\x18\x01 \x01(\t\x12K\n\x06reason\x18\x02 \x01(\x0e\x32;.coresdk.workflow_activation.RemoveFromCache.EvictionReason"\xee\x01\n\x0e\x45victionReason\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nCACHE_FULL\x10\x01\x12\x0e\n\nCACHE_MISS\x10\x02\x12\x12\n\x0eNONDETERMINISM\x10\x03\x12\r\n\tLANG_FAIL\x10\x04\x12\x12\n\x0eLANG_REQUESTED\x10\x05\x12\x12\n\x0eTASK_NOT_FOUND\x10\x06\x12\x15\n\x11UNHANDLED_COMMAND\x10\x07\x12\t\n\x05\x46\x41TAL\x10\x08\x12\x1f\n\x1bPAGINATION_OR_HISTORY_FETCH\x10\t\x12\x1d\n\x19WORKFLOW_EXECUTION_ENDING\x10\n"\xa1\x01\n\x13ResolveStreamAppend\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12?\n\x08\x61ppended\x18\x02 \x01(\x0b\x32+.coresdk.workflow_activation.StreamAppendedH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status";\n\x0eStreamAppended\x12\x14\n\x0c\x66irst_offset\x18\x01 \x01(\x0c\x12\x13\n\x0blast_offset\x18\x02 \x01(\x0c\x42\x38\xea\x02\x35Temporalio::Internal::Bridge::Api::WorkflowActivationb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -70,53 +70,57 @@ _WORKFLOWACTIVATION._serialized_start = 611 _WORKFLOWACTIVATION._serialized_end = 1157 _WORKFLOWACTIVATIONJOB._serialized_start = 1160 - _WORKFLOWACTIVATIONJOB._serialized_end = 2536 - _INITIALIZEWORKFLOW._serialized_start = 2539 - _INITIALIZEWORKFLOW._serialized_end = 4046 - _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_start = 3967 - _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_end = 4046 - _FIRETIMER._serialized_start = 4048 - _FIRETIMER._serialized_end = 4072 - _RESOLVEACTIVITY._serialized_start = 4074 - _RESOLVEACTIVITY._serialized_end = 4183 - _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_start = 4186 - _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_end = 4523 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_start = 4525 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_end = 4584 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_start = 4587 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_end = 4753 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_start = 4755 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_end = 4851 - _RESOLVECHILDWORKFLOWEXECUTION._serialized_start = 4853 - _RESOLVECHILDWORKFLOWEXECUTION._serialized_end = 4958 - _UPDATERANDOMSEED._serialized_start = 4960 - _UPDATERANDOMSEED._serialized_end = 5003 - _QUERYWORKFLOW._serialized_start = 5006 - _QUERYWORKFLOW._serialized_end = 5266 - _QUERYWORKFLOW_HEADERSENTRY._serialized_start = 3967 - _QUERYWORKFLOW_HEADERSENTRY._serialized_end = 4046 - _CANCELWORKFLOW._serialized_start = 5268 - _CANCELWORKFLOW._serialized_end = 5300 - _SIGNALWORKFLOW._serialized_start = 5303 - _SIGNALWORKFLOW._serialized_end = 5592 - _SIGNALWORKFLOW_HEADERSENTRY._serialized_start = 3967 - _SIGNALWORKFLOW_HEADERSENTRY._serialized_end = 4046 - _NOTIFYHASPATCH._serialized_start = 5594 - _NOTIFYHASPATCH._serialized_end = 5628 - _RESOLVESIGNALEXTERNALWORKFLOW._serialized_start = 5631 - _RESOLVESIGNALEXTERNALWORKFLOW._serialized_end = 5808 - _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_start = 5811 - _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_end = 5995 - _DOUPDATE._serialized_start = 5998 - _DOUPDATE._serialized_end = 6432 - _DOUPDATE_HEADERSENTRY._serialized_start = 3967 - _DOUPDATE_HEADERSENTRY._serialized_end = 4046 - _RESOLVENEXUSOPERATIONSTART._serialized_start = 6435 - _RESOLVENEXUSOPERATIONSTART._serialized_end = 6589 - _RESOLVENEXUSOPERATION._serialized_start = 6591 - _RESOLVENEXUSOPERATION._serialized_end = 6680 - _REMOVEFROMCACHE._serialized_start = 6683 - _REMOVEFROMCACHE._serialized_end = 7035 - _REMOVEFROMCACHE_EVICTIONREASON._serialized_start = 6797 - _REMOVEFROMCACHE_EVICTIONREASON._serialized_end = 7035 + _WORKFLOWACTIVATIONJOB._serialized_end = 2619 + _INITIALIZEWORKFLOW._serialized_start = 2622 + _INITIALIZEWORKFLOW._serialized_end = 4129 + _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_start = 4050 + _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_end = 4129 + _FIRETIMER._serialized_start = 4131 + _FIRETIMER._serialized_end = 4155 + _RESOLVEACTIVITY._serialized_start = 4157 + _RESOLVEACTIVITY._serialized_end = 4266 + _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_start = 4269 + _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_end = 4606 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_start = 4608 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_end = 4667 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_start = 4670 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_end = 4836 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_start = 4838 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_end = 4934 + _RESOLVECHILDWORKFLOWEXECUTION._serialized_start = 4936 + _RESOLVECHILDWORKFLOWEXECUTION._serialized_end = 5041 + _UPDATERANDOMSEED._serialized_start = 5043 + _UPDATERANDOMSEED._serialized_end = 5086 + _QUERYWORKFLOW._serialized_start = 5089 + _QUERYWORKFLOW._serialized_end = 5349 + _QUERYWORKFLOW_HEADERSENTRY._serialized_start = 4050 + _QUERYWORKFLOW_HEADERSENTRY._serialized_end = 4129 + _CANCELWORKFLOW._serialized_start = 5351 + _CANCELWORKFLOW._serialized_end = 5383 + _SIGNALWORKFLOW._serialized_start = 5386 + _SIGNALWORKFLOW._serialized_end = 5675 + _SIGNALWORKFLOW_HEADERSENTRY._serialized_start = 4050 + _SIGNALWORKFLOW_HEADERSENTRY._serialized_end = 4129 + _NOTIFYHASPATCH._serialized_start = 5677 + _NOTIFYHASPATCH._serialized_end = 5711 + _RESOLVESIGNALEXTERNALWORKFLOW._serialized_start = 5714 + _RESOLVESIGNALEXTERNALWORKFLOW._serialized_end = 5891 + _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_start = 5894 + _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_end = 6078 + _DOUPDATE._serialized_start = 6081 + _DOUPDATE._serialized_end = 6515 + _DOUPDATE_HEADERSENTRY._serialized_start = 4050 + _DOUPDATE_HEADERSENTRY._serialized_end = 4129 + _RESOLVENEXUSOPERATIONSTART._serialized_start = 6518 + _RESOLVENEXUSOPERATIONSTART._serialized_end = 6672 + _RESOLVENEXUSOPERATION._serialized_start = 6674 + _RESOLVENEXUSOPERATION._serialized_end = 6763 + _REMOVEFROMCACHE._serialized_start = 6766 + _REMOVEFROMCACHE._serialized_end = 7118 + _REMOVEFROMCACHE_EVICTIONREASON._serialized_start = 6880 + _REMOVEFROMCACHE_EVICTIONREASON._serialized_end = 7118 + _RESOLVESTREAMAPPEND._serialized_start = 7121 + _RESOLVESTREAMAPPEND._serialized_end = 7282 + _STREAMAPPENDED._serialized_start = 7284 + _STREAMAPPENDED._serialized_end = 7343 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi index e55917d810..07d3bd2b02 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi @@ -49,7 +49,7 @@ class WorkflowActivation(google.protobuf.message.Message): 3. random-seed-updates 4. signals/updates 5. all others - 6. local activity resolutions + 6. Stream results and local activity resolutions 7. queries 8. evictions @@ -65,6 +65,11 @@ class WorkflowActivation(google.protobuf.message.Message): in that same activation (prime example: cancelling not-wait-for-cancel activities). So, we do this to ensure the LA resolution happens after that cancel (or whatever else it may be) as it normally would have when executing. + * Stream results go in the same slot as local activity resolutions, for the same reason. Core + records both kinds in markers. A marker entry has the index of the activation that gave the + result, counted from 0 in its workflow task. When replaying a workflow task that has a Stream + marker, Core gives each result in the activation with that index. Inside one activation, + Stream results come first, in `seq` order, and local activity resolutions follow. * Queries always go last (and, in fact, always come in their own activation) * Evictions also always come in their own activation @@ -250,6 +255,7 @@ class WorkflowActivationJob(google.protobuf.message.Message): DO_UPDATE_FIELD_NUMBER: builtins.int RESOLVE_NEXUS_OPERATION_START_FIELD_NUMBER: builtins.int RESOLVE_NEXUS_OPERATION_FIELD_NUMBER: builtins.int + RESOLVE_STREAM_APPEND_FIELD_NUMBER: builtins.int REMOVE_FROM_CACHE_FIELD_NUMBER: builtins.int @property def initialize_workflow(self) -> global___InitializeWorkflow: @@ -324,6 +330,10 @@ class WorkflowActivationJob(google.protobuf.message.Message): def resolve_nexus_operation(self) -> global___ResolveNexusOperation: """A nexus operation resolved.""" + @property + def resolve_stream_append(self) -> global___ResolveStreamAppend: + """An append to a Stream finished.""" + @property def remove_from_cache(self) -> global___RemoveFromCache: """Remove the workflow identified by the [WorkflowActivation] containing this job from the @@ -353,6 +363,7 @@ class WorkflowActivationJob(google.protobuf.message.Message): do_update: global___DoUpdate | None = ..., resolve_nexus_operation_start: global___ResolveNexusOperationStart | None = ..., resolve_nexus_operation: global___ResolveNexusOperation | None = ..., + resolve_stream_append: global___ResolveStreamAppend | None = ..., remove_from_cache: global___RemoveFromCache | None = ..., ) -> None: ... def HasField( @@ -386,6 +397,8 @@ class WorkflowActivationJob(google.protobuf.message.Message): b"resolve_request_cancel_external_workflow", "resolve_signal_external_workflow", b"resolve_signal_external_workflow", + "resolve_stream_append", + b"resolve_stream_append", "signal_workflow", b"signal_workflow", "update_random_seed", @@ -425,6 +438,8 @@ class WorkflowActivationJob(google.protobuf.message.Message): b"resolve_request_cancel_external_workflow", "resolve_signal_external_workflow", b"resolve_signal_external_workflow", + "resolve_stream_append", + b"resolve_stream_append", "signal_workflow", b"signal_workflow", "update_random_seed", @@ -452,6 +467,7 @@ class WorkflowActivationJob(google.protobuf.message.Message): "do_update", "resolve_nexus_operation_start", "resolve_nexus_operation", + "resolve_stream_append", "remove_from_cache", ] | None @@ -1645,3 +1661,80 @@ class RemoveFromCache(google.protobuf.message.Message): ) -> None: ... global___RemoveFromCache = RemoveFromCache + +@typing.final +class ResolveStreamAppend(google.protobuf.message.Message): + """The result of an `AppendToStream` command.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + APPENDED_FIELD_NUMBER: builtins.int + FAILED_FIELD_NUMBER: builtins.int + seq: builtins.int + """The `seq` of the `AppendToStream` command.""" + @property + def appended(self) -> global___StreamAppended: ... + @property + def failed(self) -> temporalio.api.failure.v1.message_pb2.Failure: + """Why the append failed. It's an `ApplicationFailureInfo` with the type `stream_`, + such as `stream_fenced`, and with `non_retryable` set. Its details are one + `binary/protobuf` payload that holds a `temporalio.api.stream.v1.StreamErrorDetails`. + """ + + def __init__( + self, + *, + seq: builtins.int = ..., + appended: global___StreamAppended | None = ..., + failed: temporalio.api.failure.v1.message_pb2.Failure | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "appended", b"appended", "failed", b"failed", "status", b"status" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "appended", + b"appended", + "failed", + b"failed", + "seq", + b"seq", + "status", + b"status", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["status", b"status"] + ) -> typing.Literal["appended", "failed"] | None: ... + +global___ResolveStreamAppend = ResolveStreamAppend + +@typing.final +class StreamAppended(google.protobuf.message.Message): + """The offsets of the first and the last Record that the append wrote.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FIRST_OFFSET_FIELD_NUMBER: builtins.int + LAST_OFFSET_FIELD_NUMBER: builtins.int + first_offset: builtins.bytes + last_offset: builtins.bytes + def __init__( + self, + *, + first_offset: builtins.bytes = ..., + last_offset: builtins.bytes = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "first_offset", b"first_offset", "last_offset", b"last_offset" + ], + ) -> None: ... + +global___StreamAppended = StreamAppended diff --git a/temporalio/bridge/proto/workflow_commands/__init__.py b/temporalio/bridge/proto/workflow_commands/__init__.py index f599917afa..0b2f25566b 100644 --- a/temporalio/bridge/proto/workflow_commands/__init__.py +++ b/temporalio/bridge/proto/workflow_commands/__init__.py @@ -1,5 +1,6 @@ from .workflow_commands_pb2 import ( ActivityCancellationType, + AppendToStream, CancelChildWorkflowExecution, CancelSignalWorkflow, CancelTimer, @@ -28,6 +29,7 @@ __all__ = [ "ActivityCancellationType", + "AppendToStream", "CancelChildWorkflowExecution", "CancelSignalWorkflow", "CancelTimer", diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py index 3573f36b11..64a58bbb36 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py @@ -29,6 +29,9 @@ from temporalio.api.sdk.v1 import ( event_group_marker_pb2 as temporal_dot_api_dot_sdk_dot_v1_dot_event__group__marker__pb2, ) +from temporalio.api.sdk.v1 import ( + stream_pb2 as temporal_dot_api_dot_sdk_dot_v1_dot_stream__pb2, +) from temporalio.api.sdk.v1 import ( user_metadata_pb2 as temporal_dot_api_dot_sdk_dot_v1_dot_user__metadata__pb2, ) @@ -46,7 +49,7 @@ ) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n;temporal/sdk/core/workflow_commands/workflow_commands.proto\x12\x19\x63oresdk.workflow_commands\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a$temporal/api/common/v1/message.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a%temporal/api/failure/v1/message.proto\x1a\'temporal/api/sdk/v1/user_metadata.proto\x1a,temporal/api/sdk/v1/event_group_marker.proto\x1a&temporal/api/workflow/v1/message.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a#temporal/sdk/core/nexus/nexus.proto\x1a%temporal/sdk/core/common/common.proto"\xa9\x10\n\x0fWorkflowCommand\x12\x38\n\ruser_metadata\x18\x64 \x01(\x0b\x32!.temporal.api.sdk.v1.UserMetadata\x12\x42\n\x13\x65vent_group_markers\x18\x65 \x03(\x0b\x32%.temporal.api.sdk.v1.EventGroupMarker\x12<\n\x0bstart_timer\x18\x01 \x01(\x0b\x32%.coresdk.workflow_commands.StartTimerH\x00\x12H\n\x11schedule_activity\x18\x02 \x01(\x0b\x32+.coresdk.workflow_commands.ScheduleActivityH\x00\x12\x42\n\x10respond_to_query\x18\x03 \x01(\x0b\x32&.coresdk.workflow_commands.QueryResultH\x00\x12S\n\x17request_cancel_activity\x18\x04 \x01(\x0b\x32\x30.coresdk.workflow_commands.RequestCancelActivityH\x00\x12>\n\x0c\x63\x61ncel_timer\x18\x05 \x01(\x0b\x32&.coresdk.workflow_commands.CancelTimerH\x00\x12[\n\x1b\x63omplete_workflow_execution\x18\x06 \x01(\x0b\x32\x34.coresdk.workflow_commands.CompleteWorkflowExecutionH\x00\x12S\n\x17\x66\x61il_workflow_execution\x18\x07 \x01(\x0b\x32\x30.coresdk.workflow_commands.FailWorkflowExecutionH\x00\x12g\n"continue_as_new_workflow_execution\x18\x08 \x01(\x0b\x32\x39.coresdk.workflow_commands.ContinueAsNewWorkflowExecutionH\x00\x12W\n\x19\x63\x61ncel_workflow_execution\x18\t \x01(\x0b\x32\x32.coresdk.workflow_commands.CancelWorkflowExecutionH\x00\x12\x45\n\x10set_patch_marker\x18\n \x01(\x0b\x32).coresdk.workflow_commands.SetPatchMarkerH\x00\x12`\n\x1estart_child_workflow_execution\x18\x0b \x01(\x0b\x32\x36.coresdk.workflow_commands.StartChildWorkflowExecutionH\x00\x12\x62\n\x1f\x63\x61ncel_child_workflow_execution\x18\x0c \x01(\x0b\x32\x37.coresdk.workflow_commands.CancelChildWorkflowExecutionH\x00\x12w\n*request_cancel_external_workflow_execution\x18\r \x01(\x0b\x32\x41.coresdk.workflow_commands.RequestCancelExternalWorkflowExecutionH\x00\x12h\n"signal_external_workflow_execution\x18\x0e \x01(\x0b\x32:.coresdk.workflow_commands.SignalExternalWorkflowExecutionH\x00\x12Q\n\x16\x63\x61ncel_signal_workflow\x18\x0f \x01(\x0b\x32/.coresdk.workflow_commands.CancelSignalWorkflowH\x00\x12S\n\x17schedule_local_activity\x18\x10 \x01(\x0b\x32\x30.coresdk.workflow_commands.ScheduleLocalActivityH\x00\x12^\n\x1drequest_cancel_local_activity\x18\x11 \x01(\x0b\x32\x35.coresdk.workflow_commands.RequestCancelLocalActivityH\x00\x12\x66\n!upsert_workflow_search_attributes\x18\x12 \x01(\x0b\x32\x39.coresdk.workflow_commands.UpsertWorkflowSearchAttributesH\x00\x12Y\n\x1amodify_workflow_properties\x18\x13 \x01(\x0b\x32\x33.coresdk.workflow_commands.ModifyWorkflowPropertiesH\x00\x12\x44\n\x0fupdate_response\x18\x14 \x01(\x0b\x32).coresdk.workflow_commands.UpdateResponseH\x00\x12U\n\x18schedule_nexus_operation\x18\x15 \x01(\x0b\x32\x31.coresdk.workflow_commands.ScheduleNexusOperationH\x00\x12`\n\x1erequest_cancel_nexus_operation\x18\x16 \x01(\x0b\x32\x36.coresdk.workflow_commands.RequestCancelNexusOperationH\x00\x42\t\n\x07variant"S\n\nStartTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x38\n\x15start_to_fire_timeout\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration"\x1a\n\x0b\x43\x61ncelTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"\xb8\x06\n\x10ScheduleActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x15\n\ractivity_type\x18\x03 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12I\n\x07headers\x18\x06 \x03(\x0b\x32\x38.coresdk.workflow_commands.ScheduleActivity.HeadersEntry\x12\x32\n\targuments\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x34\n\x11heartbeat_timeout\x18\x0b \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x0c \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12N\n\x11\x63\x61ncellation_type\x18\r \x01(\x0e\x32\x33.coresdk.workflow_commands.ActivityCancellationType\x12\x1e\n\x16\x64o_not_eagerly_execute\x18\x0e \x01(\x08\x12;\n\x11versioning_intent\x18\x0f \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x10 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x93\x06\n\x15ScheduleLocalActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x15\n\ractivity_type\x18\x03 \x01(\t\x12\x0f\n\x07\x61ttempt\x18\x04 \x01(\r\x12:\n\x16original_schedule_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12N\n\x07headers\x18\x06 \x03(\x0b\x32=.coresdk.workflow_commands.ScheduleLocalActivity.HeadersEntry\x12\x32\n\targuments\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x0b \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x38\n\x15local_retry_threshold\x18\x0c \x01(\x0b\x32\x19.google.protobuf.Duration\x12N\n\x11\x63\x61ncellation_type\x18\r \x01(\x0e\x32\x33.coresdk.workflow_commands.ActivityCancellationType\x12#\n\x1binclude_arguments_in_marker\x18\x0e \x01(\x08\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"$\n\x15RequestCancelActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r")\n\x1aRequestCancelLocalActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r"\x9c\x01\n\x0bQueryResult\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12<\n\tsucceeded\x18\x02 \x01(\x0b\x32\'.coresdk.workflow_commands.QuerySuccessH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\t\n\x07variant"A\n\x0cQuerySuccess\x12\x31\n\x08response\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"L\n\x19\x43ompleteWorkflowExecution\x12/\n\x06result\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"J\n\x15\x46\x61ilWorkflowExecution\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"\x92\x07\n\x1e\x43ontinueAsNewWorkflowExecution\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x12\n\ntask_queue\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x37\n\x14workflow_run_timeout\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12Q\n\x04memo\x18\x06 \x03(\x0b\x32\x43.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.MemoEntry\x12W\n\x07headers\x18\x07 \x03(\x0b\x32\x46.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.HeadersEntry\x12\x43\n\x11search_attributes\x18\x08 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12\x39\n\x0cretry_policy\x18\t \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12;\n\x11versioning_intent\x18\n \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12[\n\x1binitial_versioning_behavior\x18\x0b \x01(\x0e\x32\x36.temporal.api.enums.v1.ContinueAsNewVersioningBehavior\x12\x39\n\x16\x62\x61\x63koff_start_interval\x18\x0c \x01(\x0b\x32\x19.google.protobuf.Duration\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"L\n\x17\x43\x61ncelWorkflowExecution\x12\x31\n\x07\x64\x65tails\x18\x01 \x01(\x0b\x32 .temporal.api.common.v1.Payloads"6\n\x0eSetPatchMarker\x12\x10\n\x08patch_id\x18\x01 \x01(\t\x12\x12\n\ndeprecated\x18\x02 \x01(\x08"\xe1\t\n\x1bStartChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x11\n\tnamespace\x18\x02 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x03 \x01(\t\x12\x15\n\rworkflow_type\x18\x04 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12.\n\x05input\x18\x06 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12=\n\x1aworkflow_execution_timeout\x18\x07 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x46\n\x13parent_close_policy\x18\n \x01(\x0e\x32).coresdk.child_workflow.ParentClosePolicy\x12N\n\x18workflow_id_reuse_policy\x18\x0c \x01(\x0e\x32,.temporal.api.enums.v1.WorkflowIdReusePolicy\x12\x39\n\x0cretry_policy\x18\r \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x15\n\rcron_schedule\x18\x0e \x01(\t\x12T\n\x07headers\x18\x0f \x03(\x0b\x32\x43.coresdk.workflow_commands.StartChildWorkflowExecution.HeadersEntry\x12N\n\x04memo\x18\x10 \x03(\x0b\x32@.coresdk.workflow_commands.StartChildWorkflowExecution.MemoEntry\x12\x43\n\x11search_attributes\x18\x11 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12P\n\x11\x63\x61ncellation_type\x18\x12 \x01(\x0e\x32\x35.coresdk.child_workflow.ChildWorkflowCancellationType\x12;\n\x11versioning_intent\x18\x13 \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x14 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12I\n\x13versioning_override\x18\x15 \x01(\x0b\x32,.temporal.api.workflow.v1.VersioningOverride\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"J\n\x1c\x43\x61ncelChildWorkflowExecution\x12\x1a\n\x12\x63hild_workflow_seq\x18\x01 \x01(\r\x12\x0e\n\x06reason\x18\x02 \x01(\t"\x8e\x01\n&RequestCancelExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12G\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12\x0e\n\x06reason\x18\x03 \x01(\t"\x8f\x03\n\x1fSignalExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12I\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecutionH\x00\x12\x1b\n\x11\x63hild_workflow_id\x18\x03 \x01(\tH\x00\x12\x13\n\x0bsignal_name\x18\x04 \x01(\t\x12-\n\x04\x61rgs\x18\x05 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12X\n\x07headers\x18\x06 \x03(\x0b\x32G.coresdk.workflow_commands.SignalExternalWorkflowExecution.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x42\x08\n\x06target"#\n\x14\x43\x61ncelSignalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r"e\n\x1eUpsertWorkflowSearchAttributes\x12\x43\n\x11search_attributes\x18\x01 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes"O\n\x18ModifyWorkflowProperties\x12\x33\n\rupserted_memo\x18\x01 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo"\xd2\x01\n\x0eUpdateResponse\x12\x1c\n\x14protocol_instance_id\x18\x01 \x01(\t\x12*\n\x08\x61\x63\x63\x65pted\x18\x02 \x01(\x0b\x32\x16.google.protobuf.EmptyH\x00\x12\x34\n\x08rejected\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x12\x34\n\tcompleted\x18\x04 \x01(\x0b\x32\x1f.temporal.api.common.v1.PayloadH\x00\x42\n\n\x08response"\x9a\x04\n\x16ScheduleNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x10\n\x08\x65ndpoint\x18\x02 \x01(\t\x12\x0f\n\x07service\x18\x03 \x01(\t\x12\x11\n\toperation\x18\x04 \x01(\t\x12.\n\x05input\x18\x05 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x06 \x01(\x0b\x32\x19.google.protobuf.Duration\x12X\n\x0cnexus_header\x18\x07 \x03(\x0b\x32\x42.coresdk.workflow_commands.ScheduleNexusOperation.NexusHeaderEntry\x12H\n\x11\x63\x61ncellation_type\x18\x08 \x01(\x0e\x32-.coresdk.nexus.NexusOperationCancellationType\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x1a\x32\n\x10NexusHeaderEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"*\n\x1bRequestCancelNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r*X\n\x18\x41\x63tivityCancellationType\x12\x0e\n\nTRY_CANCEL\x10\x00\x12\x1f\n\x1bWAIT_CANCELLATION_COMPLETED\x10\x01\x12\x0b\n\x07\x41\x42\x41NDON\x10\x02\x42\x36\xea\x02\x33Temporalio::Internal::Bridge::Api::WorkflowCommandsb\x06proto3' + b'\n;temporal/sdk/core/workflow_commands/workflow_commands.proto\x12\x19\x63oresdk.workflow_commands\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a$temporal/api/common/v1/message.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a%temporal/api/failure/v1/message.proto\x1a\'temporal/api/sdk/v1/user_metadata.proto\x1a,temporal/api/sdk/v1/event_group_marker.proto\x1a temporal/api/sdk/v1/stream.proto\x1a&temporal/api/workflow/v1/message.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a#temporal/sdk/core/nexus/nexus.proto\x1a%temporal/sdk/core/common/common.proto"\xf0\x10\n\x0fWorkflowCommand\x12\x38\n\ruser_metadata\x18\x64 \x01(\x0b\x32!.temporal.api.sdk.v1.UserMetadata\x12\x42\n\x13\x65vent_group_markers\x18\x65 \x03(\x0b\x32%.temporal.api.sdk.v1.EventGroupMarker\x12<\n\x0bstart_timer\x18\x01 \x01(\x0b\x32%.coresdk.workflow_commands.StartTimerH\x00\x12H\n\x11schedule_activity\x18\x02 \x01(\x0b\x32+.coresdk.workflow_commands.ScheduleActivityH\x00\x12\x42\n\x10respond_to_query\x18\x03 \x01(\x0b\x32&.coresdk.workflow_commands.QueryResultH\x00\x12S\n\x17request_cancel_activity\x18\x04 \x01(\x0b\x32\x30.coresdk.workflow_commands.RequestCancelActivityH\x00\x12>\n\x0c\x63\x61ncel_timer\x18\x05 \x01(\x0b\x32&.coresdk.workflow_commands.CancelTimerH\x00\x12[\n\x1b\x63omplete_workflow_execution\x18\x06 \x01(\x0b\x32\x34.coresdk.workflow_commands.CompleteWorkflowExecutionH\x00\x12S\n\x17\x66\x61il_workflow_execution\x18\x07 \x01(\x0b\x32\x30.coresdk.workflow_commands.FailWorkflowExecutionH\x00\x12g\n"continue_as_new_workflow_execution\x18\x08 \x01(\x0b\x32\x39.coresdk.workflow_commands.ContinueAsNewWorkflowExecutionH\x00\x12W\n\x19\x63\x61ncel_workflow_execution\x18\t \x01(\x0b\x32\x32.coresdk.workflow_commands.CancelWorkflowExecutionH\x00\x12\x45\n\x10set_patch_marker\x18\n \x01(\x0b\x32).coresdk.workflow_commands.SetPatchMarkerH\x00\x12`\n\x1estart_child_workflow_execution\x18\x0b \x01(\x0b\x32\x36.coresdk.workflow_commands.StartChildWorkflowExecutionH\x00\x12\x62\n\x1f\x63\x61ncel_child_workflow_execution\x18\x0c \x01(\x0b\x32\x37.coresdk.workflow_commands.CancelChildWorkflowExecutionH\x00\x12w\n*request_cancel_external_workflow_execution\x18\r \x01(\x0b\x32\x41.coresdk.workflow_commands.RequestCancelExternalWorkflowExecutionH\x00\x12h\n"signal_external_workflow_execution\x18\x0e \x01(\x0b\x32:.coresdk.workflow_commands.SignalExternalWorkflowExecutionH\x00\x12Q\n\x16\x63\x61ncel_signal_workflow\x18\x0f \x01(\x0b\x32/.coresdk.workflow_commands.CancelSignalWorkflowH\x00\x12S\n\x17schedule_local_activity\x18\x10 \x01(\x0b\x32\x30.coresdk.workflow_commands.ScheduleLocalActivityH\x00\x12^\n\x1drequest_cancel_local_activity\x18\x11 \x01(\x0b\x32\x35.coresdk.workflow_commands.RequestCancelLocalActivityH\x00\x12\x66\n!upsert_workflow_search_attributes\x18\x12 \x01(\x0b\x32\x39.coresdk.workflow_commands.UpsertWorkflowSearchAttributesH\x00\x12Y\n\x1amodify_workflow_properties\x18\x13 \x01(\x0b\x32\x33.coresdk.workflow_commands.ModifyWorkflowPropertiesH\x00\x12\x44\n\x0fupdate_response\x18\x14 \x01(\x0b\x32).coresdk.workflow_commands.UpdateResponseH\x00\x12U\n\x18schedule_nexus_operation\x18\x15 \x01(\x0b\x32\x31.coresdk.workflow_commands.ScheduleNexusOperationH\x00\x12`\n\x1erequest_cancel_nexus_operation\x18\x16 \x01(\x0b\x32\x36.coresdk.workflow_commands.RequestCancelNexusOperationH\x00\x12\x45\n\x10\x61ppend_to_stream\x18\x17 \x01(\x0b\x32).coresdk.workflow_commands.AppendToStreamH\x00\x42\t\n\x07variant"S\n\nStartTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x38\n\x15start_to_fire_timeout\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration"\x1a\n\x0b\x43\x61ncelTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"\xb8\x06\n\x10ScheduleActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x15\n\ractivity_type\x18\x03 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12I\n\x07headers\x18\x06 \x03(\x0b\x32\x38.coresdk.workflow_commands.ScheduleActivity.HeadersEntry\x12\x32\n\targuments\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x34\n\x11heartbeat_timeout\x18\x0b \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x0c \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12N\n\x11\x63\x61ncellation_type\x18\r \x01(\x0e\x32\x33.coresdk.workflow_commands.ActivityCancellationType\x12\x1e\n\x16\x64o_not_eagerly_execute\x18\x0e \x01(\x08\x12;\n\x11versioning_intent\x18\x0f \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x10 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\xd7\x06\n\x15ScheduleLocalActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x15\n\ractivity_type\x18\x03 \x01(\t\x12\x0f\n\x07\x61ttempt\x18\x04 \x01(\r\x12:\n\x16original_schedule_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12N\n\x07headers\x18\x06 \x03(\x0b\x32=.coresdk.workflow_commands.ScheduleLocalActivity.HeadersEntry\x12\x32\n\targuments\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x0b \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x38\n\x15local_retry_threshold\x18\x0c \x01(\x0b\x32\x19.google.protobuf.Duration\x12N\n\x11\x63\x61ncellation_type\x18\r \x01(\x0e\x32\x33.coresdk.workflow_commands.ActivityCancellationType\x12#\n\x1binclude_arguments_in_marker\x18\x0e \x01(\x08\x12\x42\n\x15local_activity_origin\x18\x0f \x01(\x0b\x32#.coresdk.common.LocalActivityOrigin\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"$\n\x15RequestCancelActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r")\n\x1aRequestCancelLocalActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r"\x9c\x01\n\x0bQueryResult\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12<\n\tsucceeded\x18\x02 \x01(\x0b\x32\'.coresdk.workflow_commands.QuerySuccessH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\t\n\x07variant"A\n\x0cQuerySuccess\x12\x31\n\x08response\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"L\n\x19\x43ompleteWorkflowExecution\x12/\n\x06result\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"J\n\x15\x46\x61ilWorkflowExecution\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"\x92\x07\n\x1e\x43ontinueAsNewWorkflowExecution\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x12\n\ntask_queue\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x37\n\x14workflow_run_timeout\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12Q\n\x04memo\x18\x06 \x03(\x0b\x32\x43.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.MemoEntry\x12W\n\x07headers\x18\x07 \x03(\x0b\x32\x46.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.HeadersEntry\x12\x43\n\x11search_attributes\x18\x08 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12\x39\n\x0cretry_policy\x18\t \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12;\n\x11versioning_intent\x18\n \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12[\n\x1binitial_versioning_behavior\x18\x0b \x01(\x0e\x32\x36.temporal.api.enums.v1.ContinueAsNewVersioningBehavior\x12\x39\n\x16\x62\x61\x63koff_start_interval\x18\x0c \x01(\x0b\x32\x19.google.protobuf.Duration\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"L\n\x17\x43\x61ncelWorkflowExecution\x12\x31\n\x07\x64\x65tails\x18\x01 \x01(\x0b\x32 .temporal.api.common.v1.Payloads"6\n\x0eSetPatchMarker\x12\x10\n\x08patch_id\x18\x01 \x01(\t\x12\x12\n\ndeprecated\x18\x02 \x01(\x08"\xe1\t\n\x1bStartChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x11\n\tnamespace\x18\x02 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x03 \x01(\t\x12\x15\n\rworkflow_type\x18\x04 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12.\n\x05input\x18\x06 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12=\n\x1aworkflow_execution_timeout\x18\x07 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x46\n\x13parent_close_policy\x18\n \x01(\x0e\x32).coresdk.child_workflow.ParentClosePolicy\x12N\n\x18workflow_id_reuse_policy\x18\x0c \x01(\x0e\x32,.temporal.api.enums.v1.WorkflowIdReusePolicy\x12\x39\n\x0cretry_policy\x18\r \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x15\n\rcron_schedule\x18\x0e \x01(\t\x12T\n\x07headers\x18\x0f \x03(\x0b\x32\x43.coresdk.workflow_commands.StartChildWorkflowExecution.HeadersEntry\x12N\n\x04memo\x18\x10 \x03(\x0b\x32@.coresdk.workflow_commands.StartChildWorkflowExecution.MemoEntry\x12\x43\n\x11search_attributes\x18\x11 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12P\n\x11\x63\x61ncellation_type\x18\x12 \x01(\x0e\x32\x35.coresdk.child_workflow.ChildWorkflowCancellationType\x12;\n\x11versioning_intent\x18\x13 \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x14 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12I\n\x13versioning_override\x18\x15 \x01(\x0b\x32,.temporal.api.workflow.v1.VersioningOverride\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"J\n\x1c\x43\x61ncelChildWorkflowExecution\x12\x1a\n\x12\x63hild_workflow_seq\x18\x01 \x01(\r\x12\x0e\n\x06reason\x18\x02 \x01(\t"\x8e\x01\n&RequestCancelExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12G\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12\x0e\n\x06reason\x18\x03 \x01(\t"\x8f\x03\n\x1fSignalExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12I\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecutionH\x00\x12\x1b\n\x11\x63hild_workflow_id\x18\x03 \x01(\tH\x00\x12\x13\n\x0bsignal_name\x18\x04 \x01(\t\x12-\n\x04\x61rgs\x18\x05 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12X\n\x07headers\x18\x06 \x03(\x0b\x32G.coresdk.workflow_commands.SignalExternalWorkflowExecution.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x42\x08\n\x06target"#\n\x14\x43\x61ncelSignalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r"e\n\x1eUpsertWorkflowSearchAttributes\x12\x43\n\x11search_attributes\x18\x01 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes"O\n\x18ModifyWorkflowProperties\x12\x33\n\rupserted_memo\x18\x01 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo"\xd2\x01\n\x0eUpdateResponse\x12\x1c\n\x14protocol_instance_id\x18\x01 \x01(\t\x12*\n\x08\x61\x63\x63\x65pted\x18\x02 \x01(\x0b\x32\x16.google.protobuf.EmptyH\x00\x12\x34\n\x08rejected\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x12\x34\n\tcompleted\x18\x04 \x01(\x0b\x32\x1f.temporal.api.common.v1.PayloadH\x00\x42\n\n\x08response"\x9a\x04\n\x16ScheduleNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x10\n\x08\x65ndpoint\x18\x02 \x01(\t\x12\x0f\n\x07service\x18\x03 \x01(\t\x12\x11\n\toperation\x18\x04 \x01(\t\x12.\n\x05input\x18\x05 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x06 \x01(\x0b\x32\x19.google.protobuf.Duration\x12X\n\x0cnexus_header\x18\x07 \x03(\x0b\x32\x42.coresdk.workflow_commands.ScheduleNexusOperation.NexusHeaderEntry\x12H\n\x11\x63\x61ncellation_type\x18\x08 \x01(\x0e\x32-.coresdk.nexus.NexusOperationCancellationType\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x1a\x32\n\x10NexusHeaderEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"*\n\x1bRequestCancelNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r"~\n\x0e\x41ppendToStream\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12.\n\x06stream\x18\x02 \x01(\x0b\x32\x1e.temporal.api.sdk.v1.StreamRef\x12/\n\x06\x62odies\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload*X\n\x18\x41\x63tivityCancellationType\x12\x0e\n\nTRY_CANCEL\x10\x00\x12\x1f\n\x1bWAIT_CANCELLATION_COMPLETED\x10\x01\x12\x0b\n\x07\x41\x42\x41NDON\x10\x02\x42\x36\xea\x02\x33Temporalio::Internal::Bridge::Api::WorkflowCommandsb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -72,70 +75,72 @@ _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_options = b"8\001" _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._options = None _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_options = b"8\001" - _ACTIVITYCANCELLATIONTYPE._serialized_start = 8785 - _ACTIVITYCANCELLATIONTYPE._serialized_end = 8873 - _WORKFLOWCOMMAND._serialized_start = 558 - _WORKFLOWCOMMAND._serialized_end = 2647 - _STARTTIMER._serialized_start = 2649 - _STARTTIMER._serialized_end = 2732 - _CANCELTIMER._serialized_start = 2734 - _CANCELTIMER._serialized_end = 2760 - _SCHEDULEACTIVITY._serialized_start = 2763 - _SCHEDULEACTIVITY._serialized_end = 3587 - _SCHEDULEACTIVITY_HEADERSENTRY._serialized_start = 3508 - _SCHEDULEACTIVITY_HEADERSENTRY._serialized_end = 3587 - _SCHEDULELOCALACTIVITY._serialized_start = 3590 - _SCHEDULELOCALACTIVITY._serialized_end = 4377 - _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_start = 3508 - _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_end = 3587 - _REQUESTCANCELACTIVITY._serialized_start = 4379 - _REQUESTCANCELACTIVITY._serialized_end = 4415 - _REQUESTCANCELLOCALACTIVITY._serialized_start = 4417 - _REQUESTCANCELLOCALACTIVITY._serialized_end = 4458 - _QUERYRESULT._serialized_start = 4461 - _QUERYRESULT._serialized_end = 4617 - _QUERYSUCCESS._serialized_start = 4619 - _QUERYSUCCESS._serialized_end = 4684 - _COMPLETEWORKFLOWEXECUTION._serialized_start = 4686 - _COMPLETEWORKFLOWEXECUTION._serialized_end = 4762 - _FAILWORKFLOWEXECUTION._serialized_start = 4764 - _FAILWORKFLOWEXECUTION._serialized_end = 4838 - _CONTINUEASNEWWORKFLOWEXECUTION._serialized_start = 4841 - _CONTINUEASNEWWORKFLOWEXECUTION._serialized_end = 5755 - _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5598 - _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5674 - _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3508 - _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3587 - _CANCELWORKFLOWEXECUTION._serialized_start = 5757 - _CANCELWORKFLOWEXECUTION._serialized_end = 5833 - _SETPATCHMARKER._serialized_start = 5835 - _SETPATCHMARKER._serialized_end = 5889 - _STARTCHILDWORKFLOWEXECUTION._serialized_start = 5892 - _STARTCHILDWORKFLOWEXECUTION._serialized_end = 7141 - _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3508 - _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3587 - _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5598 - _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5674 - _CANCELCHILDWORKFLOWEXECUTION._serialized_start = 7143 - _CANCELCHILDWORKFLOWEXECUTION._serialized_end = 7217 - _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_start = 7220 - _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_end = 7362 - _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_start = 7365 - _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_end = 7764 - _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3508 - _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3587 - _CANCELSIGNALWORKFLOW._serialized_start = 7766 - _CANCELSIGNALWORKFLOW._serialized_end = 7801 - _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_start = 7803 - _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_end = 7904 - _MODIFYWORKFLOWPROPERTIES._serialized_start = 7906 - _MODIFYWORKFLOWPROPERTIES._serialized_end = 7985 - _UPDATERESPONSE._serialized_start = 7988 - _UPDATERESPONSE._serialized_end = 8198 - _SCHEDULENEXUSOPERATION._serialized_start = 8201 - _SCHEDULENEXUSOPERATION._serialized_end = 8739 - _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_start = 8689 - _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_end = 8739 - _REQUESTCANCELNEXUSOPERATION._serialized_start = 8741 - _REQUESTCANCELNEXUSOPERATION._serialized_end = 8783 + _ACTIVITYCANCELLATIONTYPE._serialized_start = 9086 + _ACTIVITYCANCELLATIONTYPE._serialized_end = 9174 + _WORKFLOWCOMMAND._serialized_start = 592 + _WORKFLOWCOMMAND._serialized_end = 2752 + _STARTTIMER._serialized_start = 2754 + _STARTTIMER._serialized_end = 2837 + _CANCELTIMER._serialized_start = 2839 + _CANCELTIMER._serialized_end = 2865 + _SCHEDULEACTIVITY._serialized_start = 2868 + _SCHEDULEACTIVITY._serialized_end = 3692 + _SCHEDULEACTIVITY_HEADERSENTRY._serialized_start = 3613 + _SCHEDULEACTIVITY_HEADERSENTRY._serialized_end = 3692 + _SCHEDULELOCALACTIVITY._serialized_start = 3695 + _SCHEDULELOCALACTIVITY._serialized_end = 4550 + _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_start = 3613 + _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_end = 3692 + _REQUESTCANCELACTIVITY._serialized_start = 4552 + _REQUESTCANCELACTIVITY._serialized_end = 4588 + _REQUESTCANCELLOCALACTIVITY._serialized_start = 4590 + _REQUESTCANCELLOCALACTIVITY._serialized_end = 4631 + _QUERYRESULT._serialized_start = 4634 + _QUERYRESULT._serialized_end = 4790 + _QUERYSUCCESS._serialized_start = 4792 + _QUERYSUCCESS._serialized_end = 4857 + _COMPLETEWORKFLOWEXECUTION._serialized_start = 4859 + _COMPLETEWORKFLOWEXECUTION._serialized_end = 4935 + _FAILWORKFLOWEXECUTION._serialized_start = 4937 + _FAILWORKFLOWEXECUTION._serialized_end = 5011 + _CONTINUEASNEWWORKFLOWEXECUTION._serialized_start = 5014 + _CONTINUEASNEWWORKFLOWEXECUTION._serialized_end = 5928 + _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5771 + _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5847 + _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3613 + _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3692 + _CANCELWORKFLOWEXECUTION._serialized_start = 5930 + _CANCELWORKFLOWEXECUTION._serialized_end = 6006 + _SETPATCHMARKER._serialized_start = 6008 + _SETPATCHMARKER._serialized_end = 6062 + _STARTCHILDWORKFLOWEXECUTION._serialized_start = 6065 + _STARTCHILDWORKFLOWEXECUTION._serialized_end = 7314 + _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3613 + _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3692 + _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5771 + _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5847 + _CANCELCHILDWORKFLOWEXECUTION._serialized_start = 7316 + _CANCELCHILDWORKFLOWEXECUTION._serialized_end = 7390 + _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_start = 7393 + _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_end = 7535 + _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_start = 7538 + _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_end = 7937 + _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3613 + _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3692 + _CANCELSIGNALWORKFLOW._serialized_start = 7939 + _CANCELSIGNALWORKFLOW._serialized_end = 7974 + _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_start = 7976 + _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_end = 8077 + _MODIFYWORKFLOWPROPERTIES._serialized_start = 8079 + _MODIFYWORKFLOWPROPERTIES._serialized_end = 8158 + _UPDATERESPONSE._serialized_start = 8161 + _UPDATERESPONSE._serialized_end = 8371 + _SCHEDULENEXUSOPERATION._serialized_start = 8374 + _SCHEDULENEXUSOPERATION._serialized_end = 8912 + _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_start = 8862 + _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_end = 8912 + _REQUESTCANCELNEXUSOPERATION._serialized_start = 8914 + _REQUESTCANCELNEXUSOPERATION._serialized_end = 8956 + _APPENDTOSTREAM._serialized_start = 8958 + _APPENDTOSTREAM._serialized_end = 9084 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi index 81c47c0b03..99a25a278b 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi @@ -24,6 +24,7 @@ import temporalio.api.common.v1.message_pb2 import temporalio.api.enums.v1.workflow_pb2 import temporalio.api.failure.v1.message_pb2 import temporalio.api.sdk.v1.event_group_marker_pb2 +import temporalio.api.sdk.v1.stream_pb2 import temporalio.api.sdk.v1.user_metadata_pb2 import temporalio.api.workflow.v1.message_pb2 import temporalio.bridge.proto.child_workflow.child_workflow_pb2 @@ -105,6 +106,7 @@ class WorkflowCommand(google.protobuf.message.Message): UPDATE_RESPONSE_FIELD_NUMBER: builtins.int SCHEDULE_NEXUS_OPERATION_FIELD_NUMBER: builtins.int REQUEST_CANCEL_NEXUS_OPERATION_FIELD_NUMBER: builtins.int + APPEND_TO_STREAM_FIELD_NUMBER: builtins.int @property def user_metadata(self) -> temporalio.api.sdk.v1.user_metadata_pb2.UserMetadata: """User metadata that may or may not be persisted into history depending on the command type. @@ -181,6 +183,8 @@ class WorkflowCommand(google.protobuf.message.Message): def request_cancel_nexus_operation( self, ) -> global___RequestCancelNexusOperation: ... + @property + def append_to_stream(self) -> global___AppendToStream: ... def __init__( self, *, @@ -219,10 +223,13 @@ class WorkflowCommand(google.protobuf.message.Message): schedule_nexus_operation: global___ScheduleNexusOperation | None = ..., request_cancel_nexus_operation: global___RequestCancelNexusOperation | None = ..., + append_to_stream: global___AppendToStream | None = ..., ) -> None: ... def HasField( self, field_name: typing.Literal[ + "append_to_stream", + b"append_to_stream", "cancel_child_workflow_execution", b"cancel_child_workflow_execution", "cancel_signal_workflow", @@ -276,6 +283,8 @@ class WorkflowCommand(google.protobuf.message.Message): def ClearField( self, field_name: typing.Literal[ + "append_to_stream", + b"append_to_stream", "cancel_child_workflow_execution", b"cancel_child_workflow_execution", "cancel_signal_workflow", @@ -354,6 +363,7 @@ class WorkflowCommand(google.protobuf.message.Message): "update_response", "schedule_nexus_operation", "request_cancel_nexus_operation", + "append_to_stream", ] | None ): ... @@ -632,6 +642,7 @@ class ScheduleLocalActivity(google.protobuf.message.Message): LOCAL_RETRY_THRESHOLD_FIELD_NUMBER: builtins.int CANCELLATION_TYPE_FIELD_NUMBER: builtins.int INCLUDE_ARGUMENTS_IN_MARKER_FIELD_NUMBER: builtins.int + LOCAL_ACTIVITY_ORIGIN_FIELD_NUMBER: builtins.int seq: builtins.int """Lang's incremental sequence number, used as the operation identifier""" activity_id: builtins.str @@ -708,6 +719,14 @@ class ScheduleLocalActivity(google.protobuf.message.Message): core. Defaults to 1 minute. """ + @property + def local_activity_origin( + self, + ) -> temporalio.bridge.proto.common.common_pb2.LocalActivityOrigin: + """Pass the `local_activity_origin` from `DoBackoff` if this LA is scheduled because of a + timer-backed backoff attempt. + """ + def __init__( self, *, @@ -731,10 +750,14 @@ class ScheduleLocalActivity(google.protobuf.message.Message): local_retry_threshold: google.protobuf.duration_pb2.Duration | None = ..., cancellation_type: global___ActivityCancellationType.ValueType = ..., include_arguments_in_marker: builtins.bool = ..., + local_activity_origin: temporalio.bridge.proto.common.common_pb2.LocalActivityOrigin + | None = ..., ) -> None: ... def HasField( self, field_name: typing.Literal[ + "local_activity_origin", + b"local_activity_origin", "local_retry_threshold", b"local_retry_threshold", "original_schedule_time", @@ -766,6 +789,8 @@ class ScheduleLocalActivity(google.protobuf.message.Message): b"headers", "include_arguments_in_marker", b"include_arguments_in_marker", + "local_activity_origin", + b"local_activity_origin", "local_retry_threshold", b"local_retry_threshold", "original_schedule_time", @@ -1931,3 +1956,59 @@ class RequestCancelNexusOperation(google.protobuf.message.Message): def ClearField(self, field_name: typing.Literal["seq", b"seq"]) -> None: ... global___RequestCancelNexusOperation = RequestCancelNexusOperation + +@typing.final +class AppendToStream(google.protobuf.message.Message): + """Appends Records to a Stream. Core writes them as the Workflow Producer of the run and gives + the result in a `ResolveStreamAppend` job. + + * Order. The appends to one Stream reach the Store one at a time, in command order. + * Store. A `stream` with no Store name uses the Stream runtime that the Worker has under the + empty name. If the Worker has none, it uses the Worker's only runtime. + * Failures. An append that the Store refuses resolves with a failure. A `seq` or `stream` that + isn't valid fails the Workflow Task. So does a Worker with no runtime for the Store, and a + Store that is still unavailable at the heartbeat of the Workflow Task. + * Retries. When a Workflow Task fails or times out before History has the result of an append, + its retry sends the append again. + * Replay. Core gives the result that History has for the `seq`, and makes no Store call. A + command for another Stream than History has is a nondeterminism error. + * End of the Workflow. The command that ends the Workflow drops each append that has no result + yet. Lang must also accept a result that it no longer waits for. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + STREAM_FIELD_NUMBER: builtins.int + BODIES_FIELD_NUMBER: builtins.int + seq: builtins.int + """Lang's incremental sequence number for appends. It starts at 1.""" + @property + def stream(self) -> temporalio.api.sdk.v1.stream_pb2.StreamRef: ... + @property + def bodies( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + temporalio.api.common.v1.message_pb2.Payload + ]: + """The bodies of the Records, one Record for each body.""" + + def __init__( + self, + *, + seq: builtins.int = ..., + stream: temporalio.api.sdk.v1.stream_pb2.StreamRef | None = ..., + bodies: collections.abc.Iterable[temporalio.api.common.v1.message_pb2.Payload] + | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["stream", b"stream"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "bodies", b"bodies", "seq", b"seq", "stream", b"stream" + ], + ) -> None: ... + +global___AppendToStream = AppendToStream diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index c9a730c160..ebc220967c 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit c9a730c160cfd92686fdd6e9f54127c5e4577253 +Subproject commit ebc220967cecdb67bcbb57fdbd57ef1b84085b8c diff --git a/temporalio/bridge/worker.py b/temporalio/bridge/worker.py index 187b867143..3b441887ac 100644 --- a/temporalio/bridge/worker.py +++ b/temporalio/bridge/worker.py @@ -29,7 +29,10 @@ from temporalio.bridge.temporal_sdk_bridge import ( PollShutdownError, # type: ignore # noqa: F401 ) -from temporalio.worker._command_aware_visitor import CommandAwarePayloadVisitor +from temporalio.worker._command_aware_visitor import ( + CommandAwarePayloadVisitor, + StoragePayloadVisitor, +) @dataclass @@ -315,13 +318,13 @@ async def decode_activation( Returns: Metrics from any external storage retrieval operations that occurred. """ - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, ).visit(_Visitor(data_converter._decode_reference_payload_sequence), activation) metrics = temporalio.converter._extstore.StorageOperationMetrics() with metrics.track(): - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, concurrency_limit=storage_concurrency_limit, ).visit( @@ -362,7 +365,7 @@ async def encode_completion( if data_converter.external_storage: with metrics.track(): - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, concurrency_limit=storage_concurrency_limit, ).visit( @@ -370,7 +373,7 @@ async def encode_completion( completion, ) - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, ).visit( _Visitor(data_converter._encode_reference_payload_sequence), diff --git a/temporalio/client/_client.py b/temporalio/client/_client.py index 35b05e774c..bbaea1bd58 100644 --- a/temporalio/client/_client.py +++ b/temporalio/client/_client.py @@ -14,6 +14,7 @@ TYPE_CHECKING, Any, Concatenate, + TypeVar, cast, overload, ) @@ -28,7 +29,13 @@ import temporalio.converter import temporalio.runtime import temporalio.service +import temporalio.streams import temporalio.workflow +from temporalio.nexus.system.stream_service import StreamIdConflictPolicy, StreamRef +from temporalio.nexus.system.stream_service.client import ( + Stream, + StreamServiceClientExtension, +) from temporalio.service import ( ConnectConfig, DnsLoadBalancingConfig, @@ -114,6 +121,26 @@ from ._interceptor import Interceptor from ._plugin import Plugin +_BodyT = TypeVar("_BodyT") + + +class _StreamCalls(StreamServiceClientExtension): + """Start the Stream calls of a client. This class, not :py:class:`Client`, + inherits the generated extension, so the extension's methods stay out of the + client's API. + """ + + def __init__(self, client: Client) -> None: + self._client = client + + def create_nexus_client( + self, + service: type[NexusServiceType] | str, + endpoint: str, + ) -> NexusClient[NexusServiceType]: + """Return the Nexus client of the client.""" + return self._client.create_nexus_client(service, endpoint) + class Client: """Client for accessing Temporal. @@ -157,6 +184,7 @@ async def connect( grpc_compression: GrpcCompression = GrpcCompression.GZIP, payload_limits: PayloadLimitsConfig = PayloadLimitsConfig(), header_codec_behavior: HeaderCodecBehavior = HeaderCodecBehavior.NO_CODEC, + stream_config: temporalio.streams.StreamConfig | None = None, ) -> Self: """Connect to a Temporal server. @@ -226,6 +254,12 @@ async def connect( payload_limits: Warning thresholds for outbound payload/memo sizes. Over-threshold fields are logged but still sent. Set a threshold to 0 to disable it. header_codec_behavior: Encoding behavior for headers sent by the client. + stream_config: Stream Stores for this client and the Workers that use + it. Each Stream call goes to one of these Stores. Without it, a + Stream call raises :exc:`ValueError`. + + .. warning:: + This API is experimental and subject to change. """ connect_config = temporalio.service.ConnectConfig( target_host=target_host, @@ -263,6 +297,7 @@ def make_lambda( default_workflow_query_reject_condition=default_workflow_query_reject_condition, header_codec_behavior=header_codec_behavior, plugins=plugins, + stream_config=stream_config, ) def __init__( @@ -276,6 +311,7 @@ def __init__( default_workflow_query_reject_condition: None | (temporalio.common.QueryRejectCondition) = None, header_codec_behavior: HeaderCodecBehavior = HeaderCodecBehavior.NO_CODEC, + stream_config: temporalio.streams.StreamConfig | None = None, ): """Create a Temporal client from a service client. @@ -290,6 +326,7 @@ def __init__( interceptors=interceptors, default_workflow_query_reject_condition=default_workflow_query_reject_condition, header_codec_behavior=header_codec_behavior, + stream_config=stream_config, ) self._initial_config = config.copy() self._stream_producer_id = str(uuid.uuid4()) @@ -2882,6 +2919,118 @@ def create_nexus_client( """ return _NexusClient(client=self, service=service, endpoint=endpoint) + @overload + async def create_stream( + self, + *, + id: str, + store: str | None = None, + id_conflict_policy: StreamIdConflictPolicy | None = None, + body_type: type[_BodyT], + rpc_metadata: Mapping[str, str | bytes] | None = None, + rpc_timeout: timedelta | None = None, + ) -> Stream[_BodyT]: ... + + @overload + async def create_stream( + self, + *, + id: str, + store: str | None = None, + id_conflict_policy: StreamIdConflictPolicy | None = None, + body_type: None = None, + rpc_metadata: Mapping[str, str | bytes] | None = None, + rpc_timeout: timedelta | None = None, + ) -> Stream[object]: ... + + async def create_stream( + self, + *, + id: str, + store: str | None = None, + id_conflict_policy: StreamIdConflictPolicy | None = None, + body_type: Any = None, + rpc_metadata: Mapping[str, str | bytes] | None = None, + rpc_timeout: timedelta | None = None, + ) -> Stream[Any]: + """Create a Stream on a Store of the client's ``stream_config``. + + The ref of the returned Stream names that Store, so later calls on the + Stream go to it even if the selector would pick another. + + .. warning:: + This API is experimental and unstable. + + Args: + id: The Stream id. It must not be empty. + store: The name of the Store. If empty, the client uses its Store + selector or its only Store. + id_conflict_policy: What the create does if the Stream already exists. + Unspecified means fail. + body_type: The type of the Record bodies. ``None`` means any type. + rpc_metadata: Passed to the interceptor hooks. A Store call doesn't use + it. + rpc_timeout: How long the Store has to answer. + + Returns: + The handle of the Stream. + """ + return await _StreamCalls(self).create_stream( + id=id, + store=store, + id_conflict_policy=id_conflict_policy, + body_type=body_type, + rpc_metadata=rpc_metadata, + rpc_timeout=rpc_timeout, + ) + + @overload + def get_stream( + self, + ref: StreamRef[_BodyT], + *, + created: bool | None = None, + body_type: None = None, + ) -> Stream[_BodyT]: ... + + @overload + def get_stream( + self, + ref: StreamRef[_BodyT] | StreamRef[object], + *, + created: bool | None = None, + body_type: type[_BodyT], + ) -> Stream[_BodyT]: ... + + def get_stream( + self, + ref: StreamRef[Any], + *, + created: bool | None = None, + body_type: Any = None, + ) -> Stream[Any]: + """Return a handle for the Stream of ``ref``. It makes no Store call, so it + doesn't check that the Stream exists. + + .. warning:: + This API is experimental and unstable. + + Args: + ref: The ref of the Stream. A typed ref, such as ``StreamRef[str]``, + gives the type of the Record bodies. + created: The ``created`` value of the handle. ``None`` means unknown. + body_type: The type of the Record bodies. ``None`` means the type of a + typed ref, else ``object``. With a typed ref other than + ``StreamRef[object]``, it must be the type of the ref. + + Returns: + The handle of the Stream. + + Raises: + TypeError: ``body_type`` differs from the type of a typed ref. + """ + return _StreamCalls(self).get_stream(ref, created=created, body_type=body_type) + def list_nexus_operations( self, query: str, @@ -3039,6 +3188,7 @@ class ClientConnectConfig(TypedDict, total=False): grpc_compression: GrpcCompression payload_limits: PayloadLimitsConfig header_codec_behavior: HeaderCodecBehavior + stream_config: temporalio.streams.StreamConfig | None class ClientConfig(TypedDict, total=False): @@ -3053,3 +3203,4 @@ class ClientConfig(TypedDict, total=False): temporalio.common.QueryRejectCondition | None ] header_codec_behavior: Required[HeaderCodecBehavior] + stream_config: Required[temporalio.streams.StreamConfig | None] diff --git a/temporalio/client/_impl.py b/temporalio/client/_impl.py index 767dac3561..32da45ba4c 100644 --- a/temporalio/client/_impl.py +++ b/temporalio/client/_impl.py @@ -42,10 +42,14 @@ StorageDriverWorkflowInfo, WorkflowSerializationContext, ) +from temporalio.nexus.system.stream_service.client._system_nexus_interceptor import ( + _SystemNexusClientOutboundInterceptorTerminal, +) from temporalio.service import ( RPCError, RPCStatusCode, ) +from temporalio.types import ReturnType from ..common import HeaderCodecBehavior from ._activity import ( @@ -126,6 +130,7 @@ ScheduleUpdate, ScheduleUpdateInput, ) +from ._stream_store import _STREAM_SERVICE, _call_stream_store from ._worker_versioning import WorkerBuildIdVersionSets, WorkerTaskReachability from ._workflow import ( WorkflowExecutionAsyncIterator, @@ -142,7 +147,9 @@ from ._client import Client -class _ClientImpl(OutboundInterceptor): # pyright: ignore[reportUnusedClass] +class _ClientImpl( # pyright: ignore[reportUnusedClass] + _SystemNexusClientOutboundInterceptorTerminal, OutboundInterceptor +): def __init__(self, client: Client) -> None: # type: ignore # We are intentionally not calling the base class's __init__ here self._client = client @@ -1584,6 +1591,14 @@ async def get_worker_task_reachability( ### Nexus operation calls + async def _start_system_nexus_operation( + self, + input: StartNexusOperationInput[Any, ReturnType], + ) -> NexusOperationHandle[ReturnType]: + if input.service != _STREAM_SERVICE.name: + raise ValueError(f"unsupported System Nexus service: {input.service}") + return await _call_stream_store(self._client, input) + async def start_nexus_operation( self, input: StartNexusOperationInput ) -> NexusOperationHandle[Any]: diff --git a/temporalio/client/_interceptor.py b/temporalio/client/_interceptor.py index 840218e4e6..b17938dafb 100644 --- a/temporalio/client/_interceptor.py +++ b/temporalio/client/_interceptor.py @@ -2,13 +2,14 @@ from __future__ import annotations +import uuid from collections.abc import ( Awaitable, Callable, Mapping, Sequence, ) -from dataclasses import dataclass +from dataclasses import dataclass, field from datetime import timedelta from typing import ( TYPE_CHECKING, @@ -23,6 +24,9 @@ import temporalio.common import temporalio.nexus from temporalio.converter import DataConverter +from temporalio.nexus.system.stream_service.client._system_nexus_interceptor import ( + _SystemNexusClientOutboundInterceptorBase, +) if TYPE_CHECKING: from ._activity import ( @@ -621,6 +625,11 @@ class StartNexusOperationInput(Generic[_NexusInputT, _NexusOutputT]): rpc_metadata: Mapping[str, str | bytes] rpc_timeout: timedelta | None completion_callbacks: Sequence[temporalio.nexus.CompletionCallback[Any]] = () + # A `dataclasses.replace` copy keeps this id, so a resend has the same request id + # and the Store can skip a write that it already made. + _stream_request_id: uuid.UUID = field( + default_factory=uuid.uuid4, repr=False, compare=False, kw_only=True + ) @dataclass @@ -734,10 +743,18 @@ def intercept_client(self, next: OutboundInterceptor) -> OutboundInterceptor: return next -class OutboundInterceptor: +class OutboundInterceptor(_SystemNexusClientOutboundInterceptorBase): """OutboundInterceptor for intercepting client calls. This should be extended by any client outbound interceptors. + + Stream calls go to a Store, not to the server, so they have their own hooks: + ``start_create_stream``, ``start_append_records``, ``start_read_records`` and + ``start_describe_stream``. Each takes a typed :py:class:`StartNexusOperationInput` + and returns a :py:class:`NexusOperationHandle`. Stream calls don't reach the + generic Nexus start or result hooks. To retry a call, pass the same input or a + dataclass copy of it. Both keep the request id, so the Store can skip a write + that it already made when only its answer got lost. """ def __init__(self, next: OutboundInterceptor) -> None: @@ -749,6 +766,11 @@ def __init__(self, next: OutboundInterceptor) -> None: """ self.next = next + def _next_system_nexus_interceptor( + self, + ) -> _SystemNexusClientOutboundInterceptorBase: + return self.next + ### Workflow calls async def start_workflow( diff --git a/temporalio/client/_nexus.py b/temporalio/client/_nexus.py index 7e6526b95a..50d8ccea5b 100644 --- a/temporalio/client/_nexus.py +++ b/temporalio/client/_nexus.py @@ -17,6 +17,10 @@ import temporalio.converter._search_attributes import temporalio.exceptions import temporalio.nexus._util +import temporalio.nexus.system +from temporalio.nexus.system.stream_service.client._system_nexus_interceptor import ( + _start_system_nexus_operation, +) from temporalio.types import NexusServiceType, ReturnType from ._helpers import _decode_user_metadata @@ -28,6 +32,7 @@ StartNexusOperationInput, TerminateNexusOperationInput, ) +from ._stream_store import _STREAM_SERVICE if TYPE_CHECKING: from ._client import Client @@ -1156,27 +1161,33 @@ async def start_operation( result_type if isinstance(operation, str) else output_type ) - return await self._client._impl.start_nexus_operation( - StartNexusOperationInput( - operation=op_name, - arg=arg, - id=id, - endpoint=self._endpoint, - service=self._service_name, - result_type=final_result_type, - schedule_to_close_timeout=schedule_to_close_timeout, - schedule_to_start_timeout=schedule_to_start_timeout, - start_to_close_timeout=start_to_close_timeout, - id_reuse_policy=id_reuse_policy, - id_conflict_policy=id_conflict_policy, - search_attributes=search_attributes, - summary=summary, - headers=dict(headers) if headers else {}, - rpc_metadata=rpc_metadata, - rpc_timeout=rpc_timeout, - completion_callbacks=completion_callbacks, - ) + input = StartNexusOperationInput( + operation=op_name, + arg=arg, + id=id, + endpoint=self._endpoint, + service=self._service_name, + result_type=final_result_type, + schedule_to_close_timeout=schedule_to_close_timeout, + schedule_to_start_timeout=schedule_to_start_timeout, + start_to_close_timeout=start_to_close_timeout, + id_reuse_policy=id_reuse_policy, + id_conflict_policy=id_conflict_policy, + search_attributes=search_attributes, + summary=summary, + headers=dict(headers) if headers else {}, + rpc_metadata=rpc_metadata, + rpc_timeout=rpc_timeout, + completion_callbacks=completion_callbacks, ) + # Stream calls go to a Store, not to the server, so they take their typed hooks + # rather than the generic Nexus chain. + if ( + temporalio.nexus.system.is_system_endpoint(input.endpoint) + and input.service == _STREAM_SERVICE.name + ): + return await _start_system_nexus_operation(self._client._impl, input) + return await self._client._impl.start_nexus_operation(input) async def execute_operation( self, diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py new file mode 100644 index 0000000000..af2fe661b3 --- /dev/null +++ b/temporalio/client/_stream_store.py @@ -0,0 +1,469 @@ +"""Send the Stream calls of client and Activity code to a Store. + +The server doesn't run Stream calls. The generated Stream client starts each call +as a system Nexus operation, and the end of the client's interceptor chain sends it +here instead, to a Store of the client's ``StreamConfig``. This module checks each +request the way Core checks the calls of Workflow code, so both paths refuse the +same requests. +""" + +from __future__ import annotations + +import asyncio +from datetime import timedelta +from typing import Any + +import google.protobuf.message +import nexusrpc + +import temporalio.api.sdk.v1 as sdk + +# Worker modules import this module, so pydoctor can read it before the client package. +# A `from` import of a sibling here would then lose the package's re-exports. +import temporalio.client +import temporalio.nexus.system._support +import temporalio.streams +from temporalio.api.enums.v1 import StreamErrorReason, StreamIdConflictPolicy +from temporalio.api.stream.v1 import ( + LocalActivityProducer, + StandaloneActivityProducer, + WorkflowActivityProducer, + WorkflowProducer, + WorkflowTaskAttempt, +) +from temporalio.api.streamservice.v1 import ( + AppendRecordsRequest, + AppendRecordsResponse, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) +from temporalio.converter import PayloadCodec +from temporalio.exceptions import StreamError +from temporalio.nexus.system.stream_service import StreamService +from temporalio.types import ReturnType + +_definition = nexusrpc.get_service_definition(StreamService) +assert _definition +_STREAM_SERVICE: nexusrpc.ServiceDefinition = _definition + +_READ_ANSWER_TIME = timedelta(seconds=1) +"""How much of a client read's ``rpc_timeout`` the client keeps for the Store's +answer, so that a Store that waits the whole ``wait`` still answers in time. A +timeout under ten seconds keeps a tenth of itself.""" + + +def _request_ref(request: google.protobuf.message.Message) -> sdk.StreamRef: + if isinstance(request, sdk.CreateStreamRequest): + return request.stream_ref + assert isinstance( + request, + (sdk.AppendRecordsRequest, sdk.ReadRecordsRequest, sdk.DescribeStreamRequest), + ) + return request.ref + + +_Message = type[google.protobuf.message.Message] + +_STORE_OPERATIONS: dict[str, tuple[str, _Message, _Message]] = { + "CreateStream": ("create_stream", CreateStreamRequest, CreateStreamResponse), + "AppendRecords": ("append_records", AppendRecordsRequest, AppendRecordsResponse), + "ReadRecords": ("read_records", ReadRecordsRequest, ReadRecordsResponse), + "DescribeStream": ( + "describe_stream", + DescribeStreamRequest, + DescribeStreamResponse, + ), +} + + +def _store_operation(name: str) -> tuple[str, _Message, _Message]: + return _STORE_OPERATIONS[name] + + +def _store_request( + request: google.protobuf.message.Message, +) -> google.protobuf.message.Message: + stream_id = _request_ref(request).id + if isinstance(request, sdk.CreateStreamRequest): + return CreateStreamRequest( + stream_id=stream_id, id_conflict_policy=request.id_conflict_policy + ) + if isinstance(request, sdk.AppendRecordsRequest): + append = AppendRecordsRequest(stream_id=stream_id, records=request.records) + if request.HasField("producer"): + append.producer.CopyFrom(request.producer) + return append + if isinstance(request, sdk.ReadRecordsRequest): + read = ReadRecordsRequest( + stream_id=stream_id, + after_offset=request.after_offset, + max_records=request.max_records, + max_bytes=request.max_bytes, + ) + # A Store may take a zero wait as one with no end, such as Redis BLOCK 0. + if request.HasField("wait") and (request.wait.seconds or request.wait.nanos): + read.wait.CopyFrom(request.wait) + return read + return DescribeStreamRequest(stream_id=stream_id) + + +_MAX_STREAM_ID_BYTES = 4096 +"""Maximum length of a Stream id in bytes, as set by the Stream service API.""" + +_MAX_OFFSET_BYTES = 1024 +"""The maximum length of an offset in bytes. Offsets go into Workflow History.""" + +_MAX_NANOS = 999_999_999 +"""The maximum nanos of a ``Timestamp`` or a ``Duration``, whose whole seconds are +in a separate field.""" + +_MAX_DURATION_SECONDS = 315_576_000_000 +"""The maximum seconds of a protobuf ``Duration``.""" + +_PRODUCER_IDS: dict[str, tuple[tuple[str, str], ...]] = { + "workflow": ( + ("namespace", "namespace"), + ("workflow_id", "Workflow id"), + ("run_id", "run id"), + ("workflow_task_id", "Workflow Task id"), + ), + "local_activity": ( + ("namespace", "namespace"), + ("workflow_id", "Workflow id"), + ("run_id", "run id"), + ("activity_id", "Activity id"), + ("seq", "Local Activity seq"), + ), + "workflow_activity": ( + ("namespace", "namespace"), + ("workflow_id", "Workflow id"), + ("run_id", "run id"), + ("activity_id", "Activity id"), + ("scheduled_event_id", "scheduled event id"), + ), + "standalone_activity": ( + ("namespace", "namespace"), + ("activity_id", "Activity id"), + ("run_id", "run id"), + ), + "client": (("namespace", "namespace"), ("id", "client id")), +} +"""The ids of each kind of Producer, with the words that name each id in an error.""" + + +def _check_request( + request: google.protobuf.message.Message, limits: tuple[int, int, int] +) -> None: + """Check a Store request the way SDK Core's Stream runtime does, so that client + and Workflow code get the same error for the same request. + + ``limits`` are the ``max_record_bytes``, ``max_batch_bytes`` and + ``max_batch_records`` of a Stream config. + + Raises: + temporalio.exceptions.StreamError: The check refuses the request. + """ + if isinstance(request, CreateStreamRequest): + _check_stream_id(request.stream_id) + policy = request.id_conflict_policy + if policy not in StreamIdConflictPolicy.values(): + raise _invalid(f"The conflict policy {policy} is unknown") + elif isinstance(request, AppendRecordsRequest): + _check_append(request, *limits) + elif isinstance(request, ReadRecordsRequest): + _check_read(request) + else: + assert isinstance(request, DescribeStreamRequest) + _check_stream_id(request.stream_id) + + +def _check_append( + request: AppendRecordsRequest, + max_record_bytes: int, + max_batch_bytes: int, + max_batch_records: int, +) -> None: + _check_stream_id(request.stream_id) + _check_producer(request) + records = request.records + if not records: + raise _invalid("The batch has no Record") + for at, record in enumerate(records): + if not record.HasField("body"): + raise _invalid(f"Record {at} of the batch has no body") + if len(records) > max_batch_records: + raise _too_large( + f"The batch has {len(records)} Records, more than {max_batch_records}" + ) + # The limits count a Record in its stored form: a `StreamRecord` with no offset. + producer_bytes = _field_bytes(request.producer.ByteSize()) + total = 0 + for at, record in enumerate(records): + size = producer_bytes + _field_bytes(record.body.ByteSize()) + if size > max_record_bytes: + raise _too_large( + f"Record {at} of the batch has {size} bytes, more than " + f"{max_record_bytes}" + ) + total += size + if total > max_batch_bytes: + raise _too_large(f"The batch has {total} bytes, more than {max_batch_bytes}") + + +def _check_read(request: ReadRecordsRequest) -> None: + _check_stream_id(request.stream_id) + if len(request.after_offset) > _MAX_OFFSET_BYTES: + raise _invalid( + f"The after_offset of the read has {len(request.after_offset)} bytes, " + f"more than {_MAX_OFFSET_BYTES}" + ) + if request.max_records < 0: + raise _invalid("max_records must be 0 or more") + if request.max_bytes < 0: + raise _invalid("max_bytes must be 0 or more") + if request.HasField("wait"): + wait = request.wait + if wait.seconds < 0 or wait.nanos < 0: + raise _invalid("wait must be 0 or more") + if wait.seconds > _MAX_DURATION_SECONDS or wait.nanos > _MAX_NANOS: + raise _invalid("wait exceeds the protobuf Duration range") + + +def _check_stream_id(stream_id: str) -> None: + if not stream_id: + raise _invalid("The Stream id is empty") + size = len(stream_id.encode()) + if size > _MAX_STREAM_ID_BYTES: + raise _invalid( + f"The Stream id has {size} bytes, more than {_MAX_STREAM_ID_BYTES}" + ) + + +def _check_producer(request: AppendRecordsRequest) -> None: + """Refuse a Producer whose identity or attempt is incomplete, since a Store + keeps the retry state of each Producer and orders its attempts. + """ + if not request.HasField("producer"): + raise _invalid("The request has no Producer") + name = request.producer.WhichOneof("kind") + if name is None: + raise _missing("kind") + kind = getattr(request.producer, name) + for field_name, words in _PRODUCER_IDS[name]: + value = getattr(kind, field_name) + if value == "": + raise _missing(words) + if isinstance(value, int) and value < 0: + raise _invalid(f"The {words} is {value}, and it must be 0 or more") + if isinstance(kind, WorkflowProducer): + if not kind.HasField("attempt"): + raise _missing("Workflow Task attempt") + _check_task(kind.attempt) + elif isinstance(kind, LocalActivityProducer): + if not kind.HasField("attempt"): + raise _missing("attempt") + if not kind.attempt.HasField("task"): + raise _missing("Workflow Task that dispatched it") + _check_task(kind.attempt.task) + _check_attempt_number(kind.attempt.attempt, "Local Activity") + elif isinstance(kind, (WorkflowActivityProducer, StandaloneActivityProducer)): + if not kind.HasField("attempt"): + raise _missing("attempt") + if not kind.attempt.HasField("attempt_scheduled_time"): + raise _missing("attempt scheduled time") + scheduled = kind.attempt.attempt_scheduled_time + _check_time(scheduled.seconds, scheduled.nanos, "attempt scheduled time") + _check_attempt_number(kind.attempt.attempt, "Activity") + + +def _check_task(task: WorkflowTaskAttempt) -> None: + # Stores order tasks by their started event id first, so an attempt without one + # would sort below every real task. + if task.started_event_id <= 0: + raise _invalid("The Workflow Task attempt has no started event id") + if task.HasField("started_time"): + started = task.started_time + _check_time(started.seconds, started.nanos, "started time of the Workflow Task") + _check_attempt_number(task.attempt, "Workflow Task") + + +def _check_time(seconds: int, nanos: int, time: str) -> None: + # Stores order the attempts of a Producer by these times, and a time before 1970 + # or with a second or more of nanos would sort in the wrong place. + if seconds < 0: + raise _invalid(f"The {time} is before the Unix epoch") + if nanos < 0 or nanos > _MAX_NANOS: + raise _invalid( + f"The {time} has {nanos} nanos, and it must have 0 to {_MAX_NANOS}" + ) + + +def _check_attempt_number(number: int, of: str) -> None: + if number < 1: + raise _invalid(f"The {of} attempt number is {number}, and it must be 1 or more") + + +def _field_bytes(size: int) -> int: + """Return the encoded size of a length-delimited field whose content has + ``size`` bytes. The field number must be below 16, so that its tag is one byte. + """ + return 1 + max(1, (size.bit_length() + 6) // 7) + size + + +def _missing(field_name: str) -> StreamError: + return _invalid(f"The Producer has no {field_name}") + + +def _invalid(message: str) -> StreamError: + return StreamError( + message, reason=StreamErrorReason.STREAM_ERROR_REASON_INVALID_ARGUMENT + ) + + +def _too_large(message: str) -> StreamError: + return StreamError(message, reason=StreamErrorReason.STREAM_ERROR_REASON_TOO_LARGE) + + +async def _call_method( + store: temporalio.streams.StreamStore, + operation: str, + request: google.protobuf.message.Message, + request_id: str | None, +) -> google.protobuf.message.Message: + """Call one Store method, and turn what goes wrong into a ``StreamError``. + + An Activity's retry policy goes by the reason, so an unknown exception becomes + ``STORE_UNAVAILABLE``, which the policy retries, and a response of the wrong type + becomes ``STORE_CORRUPT``, which it doesn't. + """ + method, _, response_type = _store_operation(operation) + call = getattr(store, method) + try: + if request_id is None: + response = await call(request) + else: + response = await call(request, request_id=request_id) + except StreamError: + raise + except Exception as err: + raise StreamError( + f"The Stream Store '{store.name()}' failed the {operation} call " + f"with {type(err).__name__}: {err}", + reason=StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE, + ) from err + if not isinstance(response, response_type): + raise StreamError( + f"The Stream Store '{store.name()}' answered the {operation} call with " + f"{type(response).__name__}, not with {response_type.__name__}", + reason=StreamErrorReason.STREAM_ERROR_REASON_STORE_CORRUPT, + ) + return response + + +async def _call_store( # pyright: ignore[reportUnusedFunction] + store: temporalio.streams.StreamStore, + limits: tuple[int, int, int], + codec: PayloadCodec | None, + operation: str, + request: google.protobuf.message.Message, + request_id: str | None, + timeout: timedelta | None = None, +) -> google.protobuf.message.Message: + """Run one Stream call of client or Activity code against ``store``. + + Records have no serialization context, because any client or Workflow can read + them. The codec gets one Record body per call. + """ + store_request = _store_request(request) + if codec and isinstance(store_request, AppendRecordsRequest): + for appended in store_request.records: + # An encoded empty body would hide a Record with no body from the check. + if appended.HasField("body"): + [body] = await codec.encode([appended.body]) + appended.body.CopyFrom(body) + # SDK Core checks the appends and reads of Workflow code the same way, so each + # path refuses the same requests before its Store gets them. + _check_request(store_request, limits) + if ( + isinstance(store_request, ReadRecordsRequest) + and store_request.HasField("wait") + and timeout is not None + and timeout > timedelta(0) + ): + # A wait is only a bound, and a Store that waits all of it must still answer + # before the timeout fails the read. + longest = timeout - min(_READ_ANSWER_TIME, timeout / 10) + if store_request.wait.ToTimedelta() > longest: + store_request.wait.FromTimedelta(longest) + try: + # A timeout of zero is no timeout, as for an RPC of the client. + async with asyncio.timeout(timeout.total_seconds() if timeout else None): + response = await _call_method(store, operation, store_request, request_id) + except TimeoutError as err: + raise StreamError( + f"The Stream Store '{store.name()}' didn't answer the {operation} call " + "within its rpc_timeout", + reason=StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE, + ) from err + if codec and isinstance(response, ReadRecordsResponse): + for record in response.records: + [body] = await codec.decode([record.body]) + record.body.CopyFrom(body) + if isinstance(response, CreateStreamResponse): + # Each later call of the created Stream goes to this Store, whatever the + # selector picks then. + ref = sdk.StreamRef(id=_request_ref(request).id, store=store.name()) + return sdk.CreateStreamResponse(ref=ref, created=response.created) + return response + + +async def _call_stream_store( # pyright: ignore[reportUnusedFunction] + client: temporalio.client.Client, + input: temporalio.client.StartNexusOperationInput[Any, ReturnType], +) -> temporalio.client.NexusOperationHandle[ReturnType]: + stream_config = client._config["stream_config"] + if stream_config is None: + raise ValueError( + "Client has no stream_config, which every Stream call requires." + ) + data_converter = client.data_converter + converters = ( + data_converter.payload_converter, + data_converter.failure_converter, + ) + request = temporalio.nexus.system._support.model_to_proto(input.arg, *converters) + store = stream_config._store_for(_request_ref(request), client.namespace) + request_id = None + if isinstance(request, (sdk.CreateStreamRequest, sdk.AppendRecordsRequest)): + request_id = str(input._stream_request_id) + response = await _call_store( + store, + stream_config._limits(), + data_converter.payload_codec, + input.operation, + request, + request_id, + input.rpc_timeout, + ) + result_type = ( + input.result_type + or _STREAM_SERVICE.operation_definitions[input.operation].output_type + ) + handle: temporalio.client.NexusOperationHandle[ReturnType] = ( + temporalio.client.NexusOperationHandle( + client, + input.id, + result_type=result_type, + endpoint=input.endpoint, + service=input.service, + operation=input.operation, + ) + ) + handle._known_outcome = temporalio.nexus.system._support.model_from_proto( + response, result_type, *converters + ) + return handle diff --git a/temporalio/nexus/system/_support.py b/temporalio/nexus/system/_support.py index 654e5fc49e..025c854c23 100644 --- a/temporalio/nexus/system/_support.py +++ b/temporalio/nexus/system/_support.py @@ -143,7 +143,7 @@ def activity_producer(info: "temporalio.activity.Info") -> "Producer": raise RuntimeError( "Local Activity has no scheduling origin for its Producer" ) - workflow_task_id, activity_id = origin + seq, activity_id = origin local_attempt = models.LocalActivityAttempt( task=models.WorkflowTaskAttempt( started_event_id=task.started_event_id, @@ -160,7 +160,7 @@ def activity_producer(info: "temporalio.activity.Info") -> "Producer": namespace=info.namespace, workflow_id=workflow_id, run_id=run_id, - workflow_task_id=workflow_task_id, + seq=seq, activity_id=activity_id, attempt=local_attempt, ) diff --git a/temporalio/nexus/system/stream_service/models.py b/temporalio/nexus/system/stream_service/models.py index 989b1f6904..d99d809775 100644 --- a/temporalio/nexus/system/stream_service/models.py +++ b/temporalio/nexus/system/stream_service/models.py @@ -607,7 +607,7 @@ class LocalActivityProducer: namespace: str workflow_id: str run_id: str - workflow_task_id: int + seq: int activity_id: str attempt: LocalActivityAttempt @@ -637,7 +637,7 @@ def from_transfer_type( if not value.run_id: raise ValueError("missing required field LocalActivityProducer.run_id") run_id = value.run_id - workflow_task_id = value.workflow_task_id + seq = value.seq if not value.activity_id: raise ValueError("missing required field LocalActivityProducer.activity_id") activity_id = value.activity_id @@ -650,7 +650,7 @@ def from_transfer_type( namespace=namespace, workflow_id=workflow_id, run_id=run_id, - workflow_task_id=workflow_task_id, + seq=seq, activity_id=activity_id, attempt=attempt, ) @@ -664,7 +664,7 @@ def to_transfer_type( message.namespace = value.namespace message.workflow_id = value.workflow_id message.run_id = value.run_id - message.workflow_task_id = value.workflow_task_id + message.seq = value.seq message.activity_id = value.activity_id message.attempt.CopyFrom( _LocalActivityAttemptTransferTypeConverter().to_transfer_type(value.attempt) diff --git a/temporalio/streams.py b/temporalio/streams.py index 382b7523ab..a16be7ed3d 100644 --- a/temporalio/streams.py +++ b/temporalio/streams.py @@ -33,6 +33,7 @@ from collections.abc import Callable, Sequence from dataclasses import dataclass +import temporalio.api.sdk.v1 import temporalio.api.streamservice.v1 @@ -238,3 +239,28 @@ def __post_init__(self) -> None: "Each Store must have a unique name." ) names.add(name) + + def _store(self, name: str) -> StreamStore: + for store in self.stores: + if store.name() == name: + return store + raise ValueError(f"No Stream Store found with name '{name}'") + + def _store_for( + self, ref: temporalio.api.sdk.v1.StreamRef, namespace: str + ) -> StreamStore: + if ref.store: + return self._store(ref.store) + if self.store_selector is None: + return self.stores[0] + selected = self.store_selector( + StreamSelectContext(id=ref.id, namespace=namespace) + ) + if not any(selected is store for store in self.stores): + raise ValueError( + "Store returned by store_selector is not registered in StreamConfig.stores" + ) + return selected + + def _limits(self) -> tuple[int, int, int]: + return self.max_record_bytes, self.max_batch_bytes, self.max_batch_records diff --git a/temporalio/testing/_workflow.py b/temporalio/testing/_workflow.py index e7bd820806..432fdb3b63 100644 --- a/temporalio/testing/_workflow.py +++ b/temporalio/testing/_workflow.py @@ -25,6 +25,7 @@ import temporalio.exceptions import temporalio.runtime import temporalio.service +import temporalio.streams import temporalio.worker from temporalio.testing._timeskipping import ( SCHEDULE_FAST_FORWARD_POLL_TIMEOUT, @@ -104,6 +105,7 @@ async def start_local( dev_server_download_ttl: timedelta | None = None, dev_server_startup_timeout: timedelta | None = None, ui_port: int | None = None, + stream_config: temporalio.streams.StreamConfig | None = None, ) -> WorkflowEnvironment: """Start a full Temporal server locally, downloading if necessary. @@ -167,6 +169,8 @@ async def start_local( become ready after spawning. Defaults to 5 seconds and does not include download time. ui_port: UI port to use if UI is enabled. + stream_config: See parameter of the same name on + :py:meth:`temporalio.client.Client.connect`. Returns: The started CLI dev server workflow environment. @@ -196,6 +200,7 @@ async def start_local( dev_server_download_ttl=dev_server_download_ttl, dev_server_startup_timeout=dev_server_startup_timeout, ui_port=ui_port, + stream_config=stream_config, ) @classmethod @@ -218,6 +223,7 @@ async def start_time_skipping( test_server_extra_args: Sequence[str] = [], test_server_download_ttl: timedelta | None = None, test_server_startup_timeout: timedelta | None = None, + stream_config: temporalio.streams.StreamConfig | None = None, ) -> WorkflowEnvironment: """Start a V1 time skipping workflow environment. @@ -278,6 +284,8 @@ async def start_time_skipping( test_server_startup_timeout: Maximum time to wait for the test server to become ready after spawning. Defaults to 5 seconds and does not include download time. + stream_config: See parameter of the same name on + :py:meth:`temporalio.client.Client.connect`. Returns: The started workflow environment with time skipping. @@ -298,6 +306,7 @@ async def start_time_skipping( test_server_extra_args=test_server_extra_args, test_server_download_ttl=test_server_download_ttl, test_server_startup_timeout=test_server_startup_timeout, + stream_config=stream_config, ) @classmethod @@ -741,6 +750,7 @@ async def _bootstrap_dev_server( dev_server_download_ttl: timedelta | None = None, dev_server_startup_timeout: timedelta | None = None, ui_port: int | None = None, + stream_config: temporalio.streams.StreamConfig | None = None, ) -> tuple[ temporalio.bridge.testing.EphemeralServer, temporalio.client.Client, @@ -808,6 +818,7 @@ async def _bootstrap_dev_server( rpc_metadata=rpc_metadata, identity=identity, runtime=runtime, + stream_config=stream_config, ) except: try: @@ -878,6 +889,7 @@ async def _create( test_server_extra_args: Sequence[str], test_server_download_ttl: timedelta | None, test_server_startup_timeout: timedelta | None, + stream_config: temporalio.streams.StreamConfig | None, ) -> _V1WorkflowEnvironment: runtime = runtime or temporalio.runtime.Runtime.default() download_ttl_ms = None @@ -912,6 +924,7 @@ async def _create( rpc_metadata=rpc_metadata, identity=identity, runtime=runtime, + stream_config=stream_config, ) except: try: diff --git a/temporalio/worker/_activity.py b/temporalio/worker/_activity.py index cfd7fe0b08..fadc1a42e9 100644 --- a/temporalio/worker/_activity.py +++ b/temporalio/worker/_activity.py @@ -709,6 +709,13 @@ async def _execute_activity( ) if start.HasField("workflow_task") else None, + _local_activity_origin=( + start.local_activity_origin.seq, + start.local_activity_origin.activity_id, + ) + if start.HasField("local_activity_origin") + else None, + _scheduled_event_id=start.scheduled_event_id, ) for payload in start.header_fields.values(): diff --git a/temporalio/worker/_command_aware_visitor.py b/temporalio/worker/_command_aware_visitor.py index 888c06f298..224cb1018b 100644 --- a/temporalio/worker/_command_aware_visitor.py +++ b/temporalio/worker/_command_aware_visitor.py @@ -1,10 +1,11 @@ """Visitor that sets command context during payload traversal.""" import contextvars -from collections.abc import Iterator +from collections.abc import Iterable, Iterator from contextlib import contextmanager from dataclasses import dataclass +from temporalio.api.common.v1.message_pb2 import Payload from temporalio.api.enums.v1.command_type_pb2 import CommandType from temporalio.bridge._visitor import PayloadVisitor from temporalio.bridge._visitor_functions import VisitorFunctions @@ -16,8 +17,10 @@ ResolveNexusOperationStart, ResolveRequestCancelExternalWorkflow, ResolveSignalExternalWorkflow, + ResolveStreamAppend, ) from temporalio.bridge.proto.workflow_commands.workflow_commands_pb2 import ( + AppendToStream, CompleteWorkflowExecution, FailWorkflowExecution, ScheduleActivity, @@ -211,6 +214,40 @@ async def _visit_coresdk_workflow_activation_ResolveNexusOperation( fs, o ) + # Stream commands and activation jobs. Core builds the failure of a Stream job with no + # codec, so a codec must not decode it. + async def _visit_coresdk_workflow_commands_AppendToStream( + self, fs: VisitorFunctions, o: AppendToStream + ) -> None: + await self._visit_stream_payloads(fs, o.seq, o.bodies) + + async def _visit_coresdk_workflow_activation_ResolveStreamAppend( + self, fs: VisitorFunctions, o: ResolveStreamAppend + ) -> None: + pass + + async def _visit_stream_payloads( + self, fs: VisitorFunctions, seq: int, payloads: Iterable[Payload] + ) -> None: + # Any writer can append a Record, so the visitor doesn't treat its body as a + # system Nexus envelope. A codec gets each body alone, as in client code. + with current_command(CommandType.COMMAND_TYPE_UNSPECIFIED, seq): + for payload in payloads: + await fs.visit_payload(payload) + + +class StoragePayloadVisitor(CommandAwarePayloadVisitor): + """Payload visitor for the passes of external storage and of its references. + + These passes skip Stream bodies. A Stream body is its writer's value, and it can + look like a reference into this Worker's external storage. + """ + + async def _visit_stream_payloads( + self, fs: VisitorFunctions, seq: int, payloads: Iterable[Payload] + ) -> None: + pass + @contextmanager def current_command( @@ -220,6 +257,8 @@ def current_command( update_protocol_instance_id: str | None = None, ) -> Iterator[None]: """Context manager for setting command info.""" + # `COMMAND_TYPE_UNSPECIFIED` marks the body of a Stream Record, which gets no + # serialization context. No other command may use that type. token = current_command_info.set( CommandInfo( command_type=command_type, diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index bcca2648a8..06621aa219 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -2547,6 +2547,13 @@ def get_serialization_context( # The update's result and failure go back to the Nexus caller return self._nexus_update_contexts[command_info.update_protocol_instance_id] + if ( + command_info.command_type + == temporalio.api.enums.v1.command_type_pb2.CommandType.COMMAND_TYPE_UNSPECIFIED + ): + # The body of a Stream Record, which any code may read, so it has no context + return None + if ( command_info.command_type == temporalio.api.enums.v1.command_type_pb2.CommandType.COMMAND_TYPE_SCHEDULE_ACTIVITY_TASK @@ -3637,6 +3644,10 @@ def _apply_schedule_command( self._input.local_retry_threshold ) if local_backoff: + if local_backoff.HasField("local_activity_origin"): + command.schedule_local_activity.local_activity_origin.CopyFrom( + local_backoff.local_activity_origin + ) command.schedule_local_activity.attempt = local_backoff.attempt command.schedule_local_activity.original_schedule_time.CopyFrom( local_backoff.original_schedule_time diff --git a/tests/helpers/streams.py b/tests/helpers/streams.py index 10e43a2b66..cc94883184 100644 --- a/tests/helpers/streams.py +++ b/tests/helpers/streams.py @@ -1,13 +1,88 @@ """Helpers for the tests of Streams.""" import asyncio +import collections import selectors -from collections.abc import Coroutine, Iterator +from collections.abc import Awaitable, Callable, Coroutine, Iterator, Sequence from contextlib import contextmanager from typing import Any, TypeVar +from google.protobuf.message import Message + +import temporalio.api.common.v1 +import temporalio.api.streamservice.v1 +import temporalio.client +import temporalio.converter +import temporalio.streams +import temporalio.testing + _T = TypeVar("_T") +CodecCall = tuple[str, temporalio.converter.SerializationContext | None, int] + + +class ContextCodec( + temporalio.converter.PayloadCodec, temporalio.converter.WithSerializationContext +): + """Wraps each payload with the kind of its serialization context as a key, and + refuses to unwrap a payload with another key. ``calls`` logs the context and the + payload count of each call. + """ + + def __init__( + self, + calls: list[CodecCall] | None = None, + context: temporalio.converter.SerializationContext | None = None, + ) -> None: + self.calls: list[CodecCall] = [] if calls is None else calls + self._context = context + + def with_context( + self, context: temporalio.converter.SerializationContext + ) -> "ContextCodec": + return ContextCodec(self.calls, context) + + async def encode( + self, payloads: Sequence[temporalio.api.common.v1.Payload] + ) -> list[temporalio.api.common.v1.Payload]: + self.calls.append(("encode", self._context, len(payloads))) + return [wrapped(payload, self._context) for payload in payloads] + + async def decode( + self, payloads: Sequence[temporalio.api.common.v1.Payload] + ) -> list[temporalio.api.common.v1.Payload]: + self.calls.append(("decode", self._context, len(payloads))) + decoded: list[temporalio.api.common.v1.Payload] = [] + for payload in payloads: + if payload.metadata.get("encoding") == b"test/wrapped": + key = wrapped( + temporalio.api.common.v1.Payload(), self._context + ).metadata["context"] + assert payload.metadata["context"] == key, ( + f"{payload} isn't for {key!r}" + ) + payload = temporalio.api.common.v1.Payload.FromString(payload.data) + decoded.append(payload) + return decoded + + +def wrapped( + payload: temporalio.api.common.v1.Payload, + context: temporalio.converter.SerializationContext | None = None, +) -> temporalio.api.common.v1.Payload: + """Return ``payload`` as a :py:class:`ContextCodec` encodes it with ``context``.""" + return temporalio.api.common.v1.Payload( + metadata={ + "encoding": b"test/wrapped", + "context": type(context).__name__.encode(), + }, + data=payload.SerializeToString(), + ) + + +Fault = Callable[[Callable[[], Awaitable[Any]]], Awaitable[Any]] +"""What a :py:class:`FaultStore` does with one call. It gets the call of the memory Store.""" + @contextmanager def failure_note(note: str) -> Iterator[None]: @@ -19,6 +94,131 @@ def failure_note(note: str) -> Iterator[None]: raise +def answers(response: Message) -> Fault: + """Return a fault that answers a call with ``response``, with no Store call.""" + + async def fault(_call: Callable[[], Awaitable[Any]]) -> Any: + return response + + return fault + + +def loses_answer() -> Fault: + """Return a fault that calls the memory Store and then fails as an outage.""" + + async def fault(call: Callable[[], Awaitable[Any]]) -> Any: + await call() + raise ConnectionError("The answer of the Store was lost") + + return fault + + +class Hold: + """A fault that holds a call until :py:meth:`release`, before the memory Store.""" + + def __init__(self) -> None: + self.started = asyncio.Event() + self.cancelled = asyncio.Event() + self._released = asyncio.Event() + + def release(self) -> None: + self._released.set() + + async def __call__(self, call: Callable[[], Awaitable[Any]]) -> Any: + self.started.set() + try: + await self._released.wait() + except asyncio.CancelledError: + self.cancelled.set() + raise + return await call() + + +class FaultStore(temporalio.streams.StreamStore): + """Stream Store around a :py:class:`MemoryStreamStore`, which logs each request + and runs the next fault of its method, if one is queued. + """ + + def __init__(self, name: str = "memory", **options: Any) -> None: + self.memory = temporalio.testing.MemoryStreamStore(name=name, **options) + self.calls: list[tuple[Any, str | None]] = [] + """Each request, with its request id, which is ``None`` for a read and a + describe.""" + self.faults: dict[str, collections.deque[Fault]] = collections.defaultdict( + collections.deque + ) + + @property + def requests(self) -> list[Any]: + """Each request of :py:attr:`calls`.""" + return [request for request, _ in self.calls] + + def name(self) -> str: + return self.memory.name() + + async def create_stream( + self, + request: temporalio.api.streamservice.v1.CreateStreamRequest, + *, + request_id: str, + ) -> temporalio.api.streamservice.v1.CreateStreamResponse: + return await self._call("create_stream", request, request_id) + + async def append_records( + self, + request: temporalio.api.streamservice.v1.AppendRecordsRequest, + *, + request_id: str, + ) -> temporalio.api.streamservice.v1.AppendRecordsResponse: + return await self._call("append_records", request, request_id) + + async def read_records( + self, request: temporalio.api.streamservice.v1.ReadRecordsRequest + ) -> temporalio.api.streamservice.v1.ReadRecordsResponse: + return await self._call("read_records", request) + + async def describe_stream( + self, request: temporalio.api.streamservice.v1.DescribeStreamRequest + ) -> temporalio.api.streamservice.v1.DescribeStreamResponse: + return await self._call("describe_stream", request) + + async def _call( + self, method: str, request: Message, request_id: str | None = None + ) -> Any: + self.calls.append((request, request_id)) + + async def call() -> Any: + if request_id is None: + return await getattr(self.memory, method)(request) + return await getattr(self.memory, method)(request, request_id=request_id) + + if self.faults[method]: + return await self.faults[method].popleft()(call) + return await call() + + +def stream_client( + client: temporalio.client.Client, + *stores: temporalio.streams.StreamStore, + store_selector: Callable[ + [temporalio.streams.StreamSelectContext], temporalio.streams.StreamStore + ] + | None = None, + data_converter: temporalio.converter.DataConverter | None = None, + **limits: int, +) -> temporalio.client.Client: + """Return a client on the connection of ``client`` with the given Stream Stores + and limits. + """ + config = client.config() + config["stream_config"] = temporalio.streams.StreamConfig( + stores, store_selector=store_selector, **limits + ) + if data_converter: + config["data_converter"] = data_converter + return temporalio.client.Client(**config) + + class _JumpingSelector(selectors.DefaultSelector): """Selector that moves the clock of its loop past a wait and doesn't wait.""" diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index 04516b7b9a..70efece33e 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -1,20 +1,156 @@ """Tests of the client path of Streams, with no server.""" +import asyncio import dataclasses -from datetime import datetime, timezone +import random +from collections.abc import Awaitable, Callable +from datetime import datetime, timedelta, timezone from types import SimpleNamespace -from typing import Any, cast -from unittest.mock import patch +from typing import Any, assert_type, cast, get_args +from unittest.mock import Mock, patch import pytest +from google.protobuf.message import Message from google.protobuf.timestamp_pb2 import Timestamp import temporalio.activity +import temporalio.api.common.v1 +import temporalio.api.enums.v1 +import temporalio.api.sdk.v1 as sdk import temporalio.api.stream.v1 +import temporalio.api.stream.v1 as stream_api +import temporalio.api.streamservice.v1 as proto +import temporalio.client +import temporalio.client._stream_store import temporalio.contrib.streams import temporalio.converter +import temporalio.exceptions import temporalio.nexus.system._support +import temporalio.nexus.system.stream_service +import temporalio.nexus.system.stream_service.client +import temporalio.service +import temporalio.streams import temporalio.testing +from temporalio.types import ReturnType +from tests.helpers.streams import ( + ContextCodec, + FaultStore, + Hold, + answers, + failure_note, + loses_answer, + run_with_virtual_clock, +) + +_UNAVAILABLE = ( + temporalio.api.enums.v1.StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE +) +_INVALID_ARGUMENT = ( + temporalio.api.enums.v1.StreamErrorReason.STREAM_ERROR_REASON_INVALID_ARGUMENT +) + + +class _Interceptor(temporalio.client.Interceptor): + """Gives a client the outbound interceptor that ``outbound`` makes.""" + + def __init__( + self, + outbound: Callable[ + [temporalio.client.OutboundInterceptor], + temporalio.client.OutboundInterceptor, + ], + ) -> None: + super().__init__() + self._outbound = outbound + + def intercept_client( + self, next: temporalio.client.OutboundInterceptor + ) -> temporalio.client.OutboundInterceptor: + return self._outbound(next) + + +class _RecordingOutbound(temporalio.client.OutboundInterceptor): + """Logs the Store name of the ref of each Stream request before and after its + call. + """ + + def __init__( + self, + next: temporalio.client.OutboundInterceptor, + stores: list[tuple[str | None, str | None]], + ) -> None: + super().__init__(next) + self._stores = stores + + async def _record( + self, + input: temporalio.client.StartNexusOperationInput[Any, ReturnType], + call: Awaitable[temporalio.client.NexusOperationHandle[ReturnType]], + ) -> temporalio.client.NexusOperationHandle[ReturnType]: + ref = getattr(input.arg, "stream_ref", None) or input.arg.ref + before = ref.store + try: + return await call + finally: + self._stores.append((before, ref.store)) + + async def start_create_stream( + self, + input: temporalio.client.StartNexusOperationInput[ + temporalio.nexus.system.stream_service.models.CreateStreamRequest[Any], + temporalio.nexus.system.stream_service.models.CreateStreamResult[Any], + ], + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.models.CreateStreamResult[Any] + ]: + return await self._record(input, self.next.start_create_stream(input)) + + async def start_append_records( + self, + input: temporalio.client.StartNexusOperationInput[ + temporalio.nexus.system.stream_service.models.AppendRecordsRequest[Any], + temporalio.nexus.system.stream_service.models.AppendRecordsResponse, + ], + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.models.AppendRecordsResponse + ]: + return await self._record(input, self.next.start_append_records(input)) + + async def start_read_records( + self, + input: temporalio.client.StartNexusOperationInput[ + temporalio.nexus.system.stream_service.models.ReadRecordsRequest[Any], + temporalio.nexus.system.stream_service.models.ReadRecordsResponse[Any], + ], + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.models.ReadRecordsResponse[Any] + ]: + return await self._record(input, self.next.start_read_records(input)) + + async def start_describe_stream( + self, + input: temporalio.client.StartNexusOperationInput[ + temporalio.nexus.system.stream_service.models.DescribeStreamRequest[Any], + temporalio.nexus.system.stream_service.models.DescribeStreamResponse, + ], + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.models.DescribeStreamResponse + ]: + return await self._record(input, self.next.start_describe_stream(input)) + + async def start_nexus_operation( + self, input: temporalio.client.StartNexusOperationInput + ) -> temporalio.client.NexusOperationHandle[Any]: + raise AssertionError( + "Stream calls must bypass generic Nexus start interception" + ) + + async def get_nexus_operation_result( + self, input: temporalio.client.GetNexusOperationResultInput + ) -> Any: + raise AssertionError( + "Stream calls must bypass generic Nexus result interception" + ) def _producer_proto(producer: Any) -> temporalio.api.stream.v1.Producer: @@ -26,6 +162,938 @@ def _producer_proto(producer: Any) -> temporalio.api.stream.v1.Producer: return message +@pytest.mark.parametrize("operation", ["create", "append", "read", "describe"]) +@pytest.mark.parametrize( + "routing", ["only", "selector", "explicit", "unknown", "unregistered"] +) +@pytest.mark.parametrize("in_activity", [False, True]) +async def test_a_client_call_reaches_the_selected_store( + operation: str, routing: str, in_activity: bool +) -> None: + service_client = Mock(spec=temporalio.service.ServiceClient) + a, b = FaultStore("a"), FaultStore("b") + stores = [a] if routing == "only" else [a, b] + selected = FaultStore("other") if routing == "unregistered" else b + selects: list[temporalio.streams.StreamSelectContext] = [] + + def selector(context: temporalio.streams.StreamSelectContext) -> FaultStore: + selects.append(context) + return selected + + ref_store = {"explicit": "a", "unknown": "unknown"}.get(routing) + intercepted: list[tuple[str | None, str | None]] = [] + client = temporalio.client.Client( + service_client, + interceptors=[_Interceptor(lambda next: _RecordingOutbound(next, intercepted))], + stream_config=temporalio.streams.StreamConfig( + stores, store_selector=None if routing == "only" else selector + ), + ) + activity = temporalio.testing.ActivityEnvironment() + activity.info = dataclasses.replace( + activity.info, activity_id="activity", activity_run_id="run" + ) + producer = ( + _producer_proto(activity.run(temporalio.contrib.streams.current_producer)) + if in_activity + else temporalio.api.stream.v1.Producer( + client=temporalio.api.stream.v1.ClientProducer( + namespace="default", id=client._stream_producer_id + ) + ) + ) + for store in stores: + await store.memory.create_stream( + proto.CreateStreamRequest(stream_id="s"), request_id="setup" + ) + store.faults["read_records"].extend([answers(proto.ReadRecordsResponse())] * 2) + stream = client.get_stream( + temporalio.nexus.system.stream_service.StreamRef[int](id="s", store=ref_store) + ) + payload = temporalio.converter.PayloadConverter.default.to_payload + expected: Message + if operation == "create": + expected = proto.CreateStreamRequest( + stream_id="s", + id_conflict_policy=temporalio.api.enums.v1.StreamIdConflictPolicy.STREAM_ID_CONFLICT_POLICY_USE_EXISTING, + ) + elif operation == "append": + expected = proto.AppendRecordsRequest( + stream_id="s", + producer=producer, + records=[ + temporalio.api.stream.v1.AppendRecord(body=payload(i)) for i in (3, 5) + ], + ) + elif operation == "read": + expected = proto.ReadRecordsRequest( + stream_id="s", max_records=2, max_bytes=4096 + ) + expected.wait.FromSeconds(5) + else: + expected = proto.DescribeStreamRequest(stream_id="s") + + async def call() -> Any: + if operation == "create": + return await client.create_stream( + id="s", + store=ref_store, + body_type=int, + id_conflict_policy=temporalio.nexus.system.stream_service.StreamIdConflictPolicy.StreamIdConflictPolicyUseExisting, + ) + if operation == "append": + return await stream.append(3, 5) + if operation == "read": + return await stream.read_page( + max_records=2, max_bytes=4096, wait=timedelta(seconds=5) + ) + return await stream.describe() + + if routing in ("unknown", "unregistered"): + with pytest.raises(ValueError): + await (activity.run(call) if in_activity else call()) + assert not a.calls and not b.calls and not service_client.mock_calls + return + + for _ in range(2): + result = await (activity.run(call) if in_activity else call()) + if operation == "create": + assert result.created is False + assert result.ref == temporalio.nexus.system.stream_service.StreamRef( + id="s", store="b" if routing == "selector" else "a" + ) + chosen, other = (b, a) if routing == "selector" else (a, b) + assert chosen.requests == [expected, expected] + assert not other.calls and not service_client.mock_calls + ids = [request_id for _, request_id in chosen.calls] + if operation in ("create", "append"): + assert all(ids) and ids[0] != ids[1] + else: + assert ids == [None, None] + assert intercepted == [(ref_store, ref_store)] * 2 + assert selects == ( + [temporalio.streams.StreamSelectContext(id="s", namespace="default")] * 2 + if routing == "selector" + else [] + ) + + +async def test_a_client_without_stream_config_does_not_call_the_server() -> None: + service_client = Mock(spec=temporalio.service.ServiceClient) + with pytest.raises(ValueError): + await temporalio.client.Client(service_client).create_stream(id="s") + assert not service_client.mock_calls + + +async def test_a_stream_hook_can_change_the_request_and_response() -> None: + metadata: dict[str, str | bytes] = {"key": "value", "binary": b"value"} + timeout = timedelta(seconds=3) + received: list[tuple[str, object, object, object]] = [] + + class Edit(temporalio.client.OutboundInterceptor): + async def start_create_stream( + self, + input: temporalio.client.StartNexusOperationInput[ + temporalio.nexus.system.stream_service.models.CreateStreamRequest[Any], + temporalio.nexus.system.stream_service.models.CreateStreamResult[Any], + ], + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.models.CreateStreamResult[Any] + ]: + received.append( + ( + str(input._stream_request_id), + input.result_type, + input.rpc_metadata, + input.rpc_timeout, + ) + ) + handle = await super().start_create_stream( + dataclasses.replace( + input, + arg=dataclasses.replace( + input.arg, + stream_ref=dataclasses.replace( + input.arg.stream_ref, id="changed" + ), + ), + ), + ) + response = await handle.result() + handle._known_outcome = dataclasses.replace(response, created=False) + return handle + + store = FaultStore() + client = temporalio.client.Client( + Mock(spec=temporalio.service.ServiceClient), + stream_config=temporalio.streams.StreamConfig([store]), + interceptors=[_Interceptor(Edit)], + ) + stream = await client.create_stream( + id="original", + body_type=int, + rpc_metadata=metadata, + rpc_timeout=timeout, + ) + assert stream.ref.id == "changed" + assert stream.created is False + assert store.requests == [proto.CreateStreamRequest(stream_id="changed")] + assert received == [ + ( + store.calls[0][1], + temporalio.nexus.system.stream_service.models.CreateStreamResult[int], + metadata, + timeout, + ) + ] + + +async def test_a_stream_hook_can_return_without_calling_the_store() -> None: + class Cached(temporalio.client.OutboundInterceptor): + async def start_describe_stream( + self, + input: temporalio.client.StartNexusOperationInput[ + temporalio.nexus.system.stream_service.models.DescribeStreamRequest[ + Any + ], + temporalio.nexus.system.stream_service.models.DescribeStreamResponse, + ], + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.models.DescribeStreamResponse + ]: + handle: temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.models.DescribeStreamResponse + ] = temporalio.client.NexusOperationHandle(Mock(), input.id) + handle._known_outcome = ( + temporalio.nexus.system.stream_service.models.DescribeStreamResponse( + last_offset=b"cached" + ) + ) + return handle + + service_client = Mock(spec=temporalio.service.ServiceClient) + client = temporalio.client.Client( + service_client, interceptors=[_Interceptor(Cached)] + ) + response = await client.get_stream( + temporalio.nexus.system.stream_service.StreamRef[int](id="s") + ).describe() + assert response.last_offset == b"cached" + assert not service_client.mock_calls + + +async def test_stream_hooks_preserve_the_nexus_input_envelope() -> None: + seen: list[ + temporalio.client.StartNexusOperationInput[ + temporalio.nexus.system.stream_service.models.CreateStreamRequest[Any], + temporalio.nexus.system.stream_service.models.CreateStreamResult[Any], + ] + ] = [] + + class Inspect(temporalio.client.OutboundInterceptor): + async def start_create_stream( + self, + input: temporalio.client.StartNexusOperationInput[ + temporalio.nexus.system.stream_service.models.CreateStreamRequest[Any], + temporalio.nexus.system.stream_service.models.CreateStreamResult[Any], + ], + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.models.CreateStreamResult[Any] + ]: + seen.append(input) + return await super().start_create_stream(input) + + store = FaultStore() + service_client = Mock(spec=temporalio.service.ServiceClient) + client = temporalio.client.Client( + service_client, + stream_config=temporalio.streams.StreamConfig([store]), + interceptors=[_Interceptor(Inspect), _Interceptor(Inspect)], + ) + request = temporalio.nexus.system.stream_service.models.CreateStreamRequest( + stream_ref=temporalio.nexus.system.stream_service.StreamRef[int](id="envelope") + ) + nexus: temporalio.client.NexusClient[Any] = client.create_nexus_client( + "temporal.api.streamservice.v1.StreamService", + endpoint=temporalio.nexus.system.TEMPORAL_SYSTEM_ENDPOINT, + ) + metadata = {"key": "value"} + handle = await nexus.start_operation( + "CreateStream", + request, + id="operation-id", + result_type=temporalio.nexus.system.stream_service.models.CreateStreamResult[ + int + ], + schedule_to_close_timeout=timedelta(seconds=10), + schedule_to_start_timeout=timedelta(seconds=8), + start_to_close_timeout=timedelta(seconds=6), + headers={"header": "value"}, + summary="create a stream", + rpc_metadata=metadata, + rpc_timeout=timedelta(seconds=3), + ) + assert (await handle.result()).created is True + first, second = seen + assert first is second + assert first.arg is request + assert first.id == "operation-id" + assert ( + first.result_type + == temporalio.nexus.system.stream_service.models.CreateStreamResult[int] + ) + assert first.schedule_to_close_timeout == timedelta(seconds=10) + assert first.schedule_to_start_timeout == timedelta(seconds=8) + assert first.start_to_close_timeout == timedelta(seconds=6) + assert first.headers == {"header": "value"} + assert first.summary == "create a stream" + assert first.rpc_metadata == metadata + assert first.rpc_timeout == timedelta(seconds=3) + assert store.calls == [ + (proto.CreateStreamRequest(stream_id="envelope"), str(first._stream_request_id)) + ] + assert not service_client.mock_calls + + +async def test_unknown_stream_operation_bypasses_generic_nexus() -> None: + service_client = Mock(spec=temporalio.service.ServiceClient) + client = temporalio.client.Client(service_client) + nexus: temporalio.client.NexusClient[Any] = client.create_nexus_client( + "temporal.api.streamservice.v1.StreamService", + endpoint=temporalio.nexus.system.TEMPORAL_SYSTEM_ENDPOINT, + ) + with pytest.raises(ValueError, match="Unknown"): + _ = await nexus.start_operation("Unknown", None, id="unknown") + assert not service_client.mock_calls + + +def test_the_client_gives_the_handle_of_a_ref_with_its_body_type() -> None: + client = temporalio.client.Client( + Mock(spec=temporalio.service.ServiceClient), + stream_config=temporalio.streams.StreamConfig([FaultStore()]), + ) + typed = client.get_stream( + temporalio.nexus.system.stream_service.StreamRef[int](id="s", store="a"), + created=True, + ) + by_type = client.get_stream( + temporalio.nexus.system.stream_service.StreamRef(id="s"), body_type=str + ) + any_body = client.get_stream( + temporalio.nexus.system.stream_service.StreamRef[object](id="s"), + body_type=bytes, + ) + assert_type(typed, temporalio.nexus.system.stream_service.client.Stream[int]) + assert_type(by_type, temporalio.nexus.system.stream_service.client.Stream[str]) + assert_type(any_body, temporalio.nexus.system.stream_service.client.Stream[bytes]) + assert typed.ref == temporalio.nexus.system.stream_service.StreamRef( + id="s", store="a" + ) + for stream, body_type, created in ( + (typed, int, True), + (by_type, str, None), + (any_body, bytes, None), + ): + assert get_args(getattr(stream, "__orig_class__")) == (body_type,) + assert get_args(getattr(stream.ref, "__orig_class__")) == (body_type,) + assert stream.created is created + # The overloads refuse this call statically, so the ref is typed `Any` here. + mismatched: Any = temporalio.nexus.system.stream_service.StreamRef[int](id="s") + with pytest.raises(TypeError, match="must match the typed ref"): + client.get_stream(mismatched, body_type=str) + + +async def test_a_created_stream_keeps_its_selected_store() -> None: + a, b = FaultStore("a"), FaultStore("b") + selected = a + client = temporalio.client.Client( + Mock(spec=temporalio.service.ServiceClient), + stream_config=temporalio.streams.StreamConfig( + [a, b], store_selector=lambda _: selected + ), + ) + stream = await client.create_stream(id="s", body_type=int) + selected = b + await stream.append(1) + await stream.describe() + assert stream.ref.store == "a" + assert [type(request) for request in a.requests] == [ + proto.CreateStreamRequest, + proto.AppendRecordsRequest, + proto.DescribeStreamRequest, + ] + assert not b.calls + + +async def test_a_client_retry_recovers_a_lost_store_answer() -> None: + class Retry(temporalio.client.OutboundInterceptor): + async def _retry(self, call: Callable[[], Awaitable[ReturnType]]) -> ReturnType: + try: + return await call() + except temporalio.exceptions.StreamError as err: + if err.reason != _UNAVAILABLE: + raise + return await call() + + async def start_create_stream( + self, + input: temporalio.client.StartNexusOperationInput[ + temporalio.nexus.system.stream_service.models.CreateStreamRequest[Any], + temporalio.nexus.system.stream_service.models.CreateStreamResult[Any], + ], + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.models.CreateStreamResult[Any] + ]: + return await self._retry( + lambda: self.next.start_create_stream(dataclasses.replace(input)) + ) + + async def start_append_records( + self, + input: temporalio.client.StartNexusOperationInput[ + temporalio.nexus.system.stream_service.models.AppendRecordsRequest[Any], + temporalio.nexus.system.stream_service.models.AppendRecordsResponse, + ], + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.models.AppendRecordsResponse + ]: + return await self._retry( + lambda: self.next.start_append_records(dataclasses.replace(input)) + ) + + store = FaultStore() + store.faults["create_stream"].append(loses_answer()) + store.faults["append_records"].append(loses_answer()) + client = temporalio.client.Client( + Mock(spec=temporalio.service.ServiceClient), + stream_config=temporalio.streams.StreamConfig([store]), + interceptors=[_Interceptor(Retry)], + ) + stream = await client.create_stream(id="s", body_type=int) + assert stream.created is True + await stream.append(1) + await stream.append(2) + create, create_retry, append, append_retry, second = (key for _, key in store.calls) + assert create == create_retry + assert append == append_retry + assert len({create, append, second}) == 3 + assert [record.body for record in (await stream.read_page()).records] == [1, 2] + + +async def test_an_empty_client_append_does_not_reach_the_store() -> None: + store = FaultStore() + client = temporalio.client.Client( + Mock(spec=temporalio.service.ServiceClient), + stream_config=temporalio.streams.StreamConfig([store]), + ) + with pytest.raises(temporalio.exceptions.StreamError) as raised: + await client.get_stream( + temporalio.nexus.system.stream_service.StreamRef[int](id="s") + ).append() + assert raised.value.reason == _INVALID_ARGUMENT + assert not store.calls + + +_PRODUCER_KINDS: dict[str, dict[str, Any]] = { + "workflow": { + "namespace": "n", + "workflow_id": "w", + "run_id": "r", + "attempt": {"started_event_id": 3, "attempt": 1}, + }, + "local_activity": { + "namespace": "n", + "workflow_id": "w", + "run_id": "r", + "activity_id": "a", + "attempt": {"task": {"started_event_id": 3, "attempt": 1}, "attempt": 1}, + }, + "workflow_activity": { + "namespace": "n", + "workflow_id": "w", + "run_id": "r", + "activity_id": "a", + "attempt": {"attempt_scheduled_time": {"seconds": 1}, "attempt": 1}, + }, + "standalone_activity": { + "namespace": "n", + "activity_id": "a", + "run_id": "r", + "attempt": {"attempt_scheduled_time": {"seconds": 1}, "attempt": 1}, + }, + "client": {"namespace": "n", "id": "c"}, +} +"""The fields of a Producer of each kind that a Store takes.""" + + +def _producer_of(kind: str, **fields: Any) -> temporalio.api.stream.v1.Producer: + arguments: dict[str, Any] = {kind: {**_PRODUCER_KINDS[kind], **fields}} + return temporalio.api.stream.v1.Producer(**arguments) + + +async def test_a_bad_request_fails_before_the_store() -> None: + store = FaultStore() + limits = (1536 * 1024, 4 * 1024 * 1024, 2) + invalid, too_large = ( + _INVALID_ARGUMENT, + temporalio.api.enums.v1.StreamErrorReason.STREAM_ERROR_REASON_TOO_LARGE, + ) + ref = sdk.StreamRef(id="s") + body = temporalio.api.common.v1.Payload(data=b"x") + client = _producer_of("client") + + def create(**fields: Any) -> tuple[str, Message]: + fields = {"stream_ref": ref, **fields} + return "CreateStream", sdk.CreateStreamRequest(**fields) + + def append( + producer: temporalio.api.stream.v1.Producer | None = client, **fields: Any + ) -> tuple[str, Message]: + fields = { + "ref": ref, + "records": [temporalio.api.stream.v1.AppendRecord(body=body)] * 2, + **fields, + } + return "AppendRecords", sdk.AppendRecordsRequest(producer=producer, **fields) + + def read(**fields: Any) -> tuple[str, Message]: + fields = {"ref": ref, **fields} + return "ReadRecords", sdk.ReadRecordsRequest(**fields) + + def describe(**fields: Any) -> tuple[str, Message]: + fields = {"ref": ref, **fields} + return "DescribeStream", sdk.DescribeStreamRequest(**fields) + + activity = {"attempt_scheduled_time": {"seconds": 1}, "attempt": 1} + task = {"started_event_id": 3, "attempt": 1} + no_id = "The Stream id is empty" + # Each of the 2049 characters has two bytes in UTF-8. + long_id = sdk.StreamRef(id="é" * 2049) + long_id_message = "The Stream id has 4098 bytes, more than 4096" + cases: list[ + tuple[ + tuple[str, Message], + temporalio.api.enums.v1.StreamErrorReason.ValueType, + str, + ] + ] = [ + (create(stream_ref=sdk.StreamRef()), invalid, no_id), + (create(stream_ref=long_id), invalid, long_id_message), + (create(id_conflict_policy=99), invalid, "The conflict policy 99 is unknown"), + (append(ref=sdk.StreamRef()), invalid, no_id), + (append(None), invalid, "The request has no Producer"), + ( + append(temporalio.api.stream.v1.Producer()), + invalid, + "The Producer has no kind", + ), + ( + append(_producer_of("workflow", attempt=None)), + invalid, + "The Producer has no Workflow Task attempt", + ), + ( + append(_producer_of("workflow", workflow_task_id=-1)), + invalid, + "The Workflow Task id is -1, and it must be 0 or more", + ), + ( + append(_producer_of("workflow", attempt={"attempt": 1})), + invalid, + "The Workflow Task attempt has no started event id", + ), + ( + append(_producer_of("workflow", attempt={**task, "attempt": 0})), + invalid, + "The Workflow Task attempt number is 0, and it must be 1 or more", + ), + ( + append( + _producer_of( + "workflow", attempt={**task, "started_time": {"seconds": -1}} + ) + ), + invalid, + "The started time of the Workflow Task is before the Unix epoch", + ), + ( + append( + _producer_of( + "workflow", + attempt={**task, "started_time": {"nanos": 1_000_000_000}}, + ) + ), + invalid, + "The started time of the Workflow Task has 1000000000 nanos, and it must " + "have 0 to 999999999", + ), + ( + append(_producer_of("local_activity", attempt=None)), + invalid, + "The Producer has no attempt", + ), + ( + append(_producer_of("local_activity", attempt={"attempt": 1})), + invalid, + "The Producer has no Workflow Task that dispatched it", + ), + ( + append(_producer_of("local_activity", attempt={"task": task})), + invalid, + "The Local Activity attempt number is 0, and it must be 1 or more", + ), + ( + append(_producer_of("workflow_activity", scheduled_event_id=-1)), + invalid, + "The scheduled event id is -1, and it must be 0 or more", + ), + ( + append(_producer_of("standalone_activity", attempt=None)), + invalid, + "The Producer has no attempt", + ), + ( + append(_producer_of("standalone_activity", attempt={"attempt": 1})), + invalid, + "The Producer has no attempt scheduled time", + ), + ( + append( + _producer_of( + "workflow_activity", + attempt={**activity, "attempt_scheduled_time": {"seconds": -1}}, + ) + ), + invalid, + "The attempt scheduled time is before the Unix epoch", + ), + ( + append( + _producer_of( + "standalone_activity", + attempt={**activity, "attempt_scheduled_time": {"nanos": -1}}, + ) + ), + invalid, + "The attempt scheduled time has -1 nanos, and it must have 0 to 999999999", + ), + ( + append( + _producer_of("workflow_activity", attempt={**activity, "attempt": 0}) + ), + invalid, + "The Activity attempt number is 0, and it must be 1 or more", + ), + (append(records=[]), invalid, "The batch has no Record"), + ( + append( + records=[ + temporalio.api.stream.v1.AppendRecord(body=body), + temporalio.api.stream.v1.AppendRecord(), + ] + ), + invalid, + "Record 1 of the batch has no body", + ), + ( + append(records=[temporalio.api.stream.v1.AppendRecord(body=body)] * 3), + too_large, + "The batch has 3 Records, more than 2", + ), + (read(ref=sdk.StreamRef()), invalid, no_id), + (read(ref=long_id), invalid, long_id_message), + ( + read(after_offset=b"o" * 1025), + invalid, + "The after_offset of the read has 1025 bytes, more than 1024", + ), + (read(max_records=-1), invalid, "max_records must be 0 or more"), + (read(max_bytes=-1), invalid, "max_bytes must be 0 or more"), + (read(wait={"seconds": -1}), invalid, "wait must be 0 or more"), + (read(wait={"nanos": -1}), invalid, "wait must be 0 or more"), + ( + read(wait={"nanos": 1_000_000_000}), + invalid, + "wait exceeds the protobuf Duration range", + ), + ( + read(wait={"seconds": 315_576_000_001}), + invalid, + "wait exceeds the protobuf Duration range", + ), + (describe(ref=sdk.StreamRef()), invalid, no_id), + (describe(ref=long_id), invalid, long_id_message), + # A request that breaks two rules fails with the rule that Core checks first. + (create(stream_ref=sdk.StreamRef(), id_conflict_policy=99), invalid, no_id), + ( + append(temporalio.api.stream.v1.Producer(), ref=sdk.StreamRef()), + invalid, + no_id, + ), + (append(None, records=[]), invalid, "The request has no Producer"), + ( + append(_producer_of("workflow", workflow_id="", run_id="")), + invalid, + "The Producer has no Workflow id", + ), + ( + append(_producer_of("workflow", workflow_task_id=-1, attempt=None)), + invalid, + "The Workflow Task id is -1, and it must be 0 or more", + ), + ( + append(_producer_of("workflow", attempt={"attempt": 0})), + invalid, + "The Workflow Task attempt has no started event id", + ), + ( + append( + _producer_of( + "workflow", + attempt={**task, "started_time": {"seconds": -1, "nanos": -1}}, + ) + ), + invalid, + "The started time of the Workflow Task is before the Unix epoch", + ), + ( + append( + _producer_of( + "workflow_activity", + attempt={"attempt_scheduled_time": {"seconds": -1}, "attempt": 0}, + ) + ), + invalid, + "The attempt scheduled time is before the Unix epoch", + ), + ( + append(records=[temporalio.api.stream.v1.AppendRecord()] * 3), + invalid, + "Record 0 of the batch has no body", + ), + ( + append( + records=[ + temporalio.api.stream.v1.AppendRecord( + body=temporalio.api.common.v1.Payload(data=b"x" * limits[0]) + ) + ] + * 3 + ), + too_large, + "The batch has 3 Records, more than 2", + ), + ( + read(after_offset=b"o" * 1025, max_records=-1), + invalid, + "The after_offset of the read has 1025 bytes, more than 1024", + ), + ( + read(max_records=-1, max_bytes=-1), + invalid, + "max_records must be 0 or more", + ), + ( + read(max_bytes=-1, wait={"seconds": -1}), + invalid, + "max_bytes must be 0 or more", + ), + ( + read(wait={"seconds": -1, "nanos": 1_000_000_000}), + invalid, + "wait must be 0 or more", + ), + ] + # The words that an error uses for each text id of each kind of Producer. + words = { + "namespace": "namespace", + "workflow_id": "Workflow id", + "run_id": "run id", + "activity_id": "Activity id", + "id": "client id", + } + for kind, fields in _PRODUCER_KINDS.items(): + for name in fields.keys() & words.keys(): + missing = append(_producer_of(kind, **{name: ""})) + cases.append((missing, invalid, f"The Producer has no {words[name]}")) + for codec in (None, ContextCodec()): + for (operation, request), reason, message in cases: + with failure_note(f"{message}, with a codec: {codec is not None}"): + with pytest.raises(temporalio.exceptions.StreamError) as raised: + await temporalio.client._stream_store._call_store( + store, limits, codec, operation, request, None + ) + assert (raised.value.reason, raised.value.message) == (reason, message) + assert not store.calls + + # The largest values that the checks take. + longest_id = sdk.StreamRef(id="é" * 2048) + largest_time = {"seconds": 0, "nanos": 999_999_999} + taken = [ + create(stream_ref=longest_id), + *(append(_producer_of(kind)) for kind in _PRODUCER_KINDS), + append( + _producer_of( + "workflow", + workflow_task_id=0, + attempt={**task, "started_time": largest_time}, + ) + ), + append( + _producer_of( + "workflow_activity", + scheduled_event_id=0, + attempt={**activity, "attempt_scheduled_time": largest_time}, + ) + ), + read( + ref=longest_id, + after_offset=b"o" * 1024, + wait={"seconds": 315_576_000_000, "nanos": 999_999_999}, + ), + describe(ref=longest_id), + ] + for _, request in taken: + temporalio.client._stream_store._check_request( + temporalio.client._stream_store._store_request(request), limits + ) + + +def test_the_producer_check_has_each_id_of_each_kind_in_proto_order() -> None: + kinds = temporalio.api.stream.v1.Producer.DESCRIPTOR.oneofs_by_name["kind"].fields + assert set(temporalio.client._stream_store._PRODUCER_IDS) == { + kind.name for kind in kinds + } + for kind in kinds: + assert kind.message_type + fields = sorted(kind.message_type.fields, key=lambda field: field.number) + ids = [field.name for field in fields if field.name != "attempt"] + assert [ + name for name, _ in temporalio.client._stream_store._PRODUCER_IDS[kind.name] + ] == ids, kind.name + + +def test_the_append_check_measures_each_record_in_its_stored_size() -> None: + too_large = temporalio.api.enums.v1.StreamErrorReason.STREAM_ERROR_REASON_TOO_LARGE + rng = random.Random(0) + for case in range(200): + kind = rng.choice(list(_PRODUCER_KINDS)) + # Ids of 200 bytes or more give the Producer a longer length prefix. + ids = { + name: "i" * rng.choice([1, 2, 200, 20_000]) + for name, value in _PRODUCER_KINDS[kind].items() + if isinstance(value, str) + } + producer = _producer_of(kind, **ids) + bodies = [ + temporalio.api.common.v1.Payload( + metadata=rng.choice([{}, {"encoding": b"json/plain"}]), + data=b"x" * rng.choice([0, 1, 127, 128, 300, 20_000]), + ) + for _ in range(rng.randint(1, 3)) + ] + request = proto.AppendRecordsRequest( + stream_id="s", + producer=producer, + records=[ + temporalio.api.stream.v1.AppendRecord(body=body) for body in bodies + ], + ) + sizes = [ + stream_api.StreamRecord(producer=producer, body=body).ByteSize() + for body in bodies + ] + largest, total, count = max(sizes), sum(sizes), len(sizes) + with failure_note(f"case {case}"): + temporalio.client._stream_store._check_request( + request, (largest, total, count) + ) + over_record = ( + (largest - 1, total, count), + f"Record {sizes.index(largest)} of the batch has {largest} bytes, " + f"more than {largest - 1}", + ) + over_batch = ( + (largest, total - 1, count), + f"The batch has {total} bytes, more than {total - 1}", + ) + # The size of each Record comes before the size of the batch. + over_both = ((largest - 1, total - 1, count), over_record[1]) + for limits, message in (over_record, over_batch, over_both): + with pytest.raises(temporalio.exceptions.StreamError) as raised: + temporalio.client._stream_store._check_request(request, limits) + assert (raised.value.reason, raised.value.message) == ( + too_large, + message, + ) + + +class _FakeReads(temporalio.client.OutboundInterceptor): + def __init__(self, next: temporalio.client.OutboundInterceptor) -> None: + super().__init__(next) + self.pages = iter([(1, 2), (), (3, 4), (), (4, 5)]) + self.starts: list[int] = [] + self.waits: list[timedelta | None] = [] + + async def start_read_records( + self, + input: temporalio.client.StartNexusOperationInput[ + temporalio.nexus.system.stream_service.ReadRecordsRequest[Any], + temporalio.nexus.system.stream_service.ReadRecordsResponse[Any], + ], + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.ReadRecordsResponse[Any] + ]: + request = input.arg + self.starts.append(int.from_bytes(request.after_offset or b"", "big")) + self.waits.append(request.wait) + records = [ + temporalio.nexus.system.stream_service.StreamRecord( + body=at, offset=at.to_bytes(8, "big") + ) + for at in next(self.pages) + ] + page = temporalio.nexus.system.stream_service.ReadRecordsResponse( + records=records + ) + handle: temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.ReadRecordsResponse[Any] + ] = temporalio.client.NexusOperationHandle(Mock(), input.id) + handle._known_outcome = page + return handle + + +@pytest.mark.parametrize("wait", [None, timedelta(0), timedelta(seconds=5)]) +async def test_a_read_resumes_after_a_partial_page_and_skips_empty_pages( + wait: timedelta | None, +) -> None: + fake: list[_FakeReads] = [] + + def outbound(next: temporalio.client.OutboundInterceptor) -> _FakeReads: + fake.append(_FakeReads(next)) + return fake[0] + + client = temporalio.client.Client( + Mock(spec=temporalio.service.ServiceClient), + interceptors=[_Interceptor(outbound)], + ) + stream = client.get_stream( + temporalio.nexus.system.stream_service.StreamRef[int](id="s") + ) + [reads] = fake + got: list[int] = [] + later = temporalio.nexus.system._support.DEFAULT_READ_WAIT if wait is None else wait + for stop_at in (3, 5): + offset = got[-1].to_bytes(8, "big") if got else None + async for record in stream.read(after_offset=offset, wait=wait): + got.append(record.body) + if record.body == stop_at: + break + assert got == [1, 2, 3, 4, 5] + assert reads.starts == [0, 2, 2, 3, 3] + assert reads.waits == [wait, later, later, wait, later] + + @dataclasses.dataclass(frozen=True) class _WriterInfo: kind: str @@ -96,7 +1164,7 @@ def _expected_producer(writer: _WriterInfo) -> temporalio.api.stream.v1.Producer kind.activity_id = writer.activity_id kind.attempt.attempt = writer.attempt if writer.kind == "local_activity": - kind.workflow_task_id, kind.activity_id = writer.event_id, "original" + kind.seq, kind.activity_id = writer.event_id, "original" task = kind.attempt.task task.started_event_id, task.attempt = writer.event_id + 3, writer.attempt + 1 task.started_time.CopyFrom(time) @@ -111,7 +1179,6 @@ def _expected_producer(writer: _WriterInfo) -> temporalio.api.stream.v1.Producer ("kind", "event_id"), [ ("workflow", 7), - ("local_activity", 0), ("local_activity", 9), ("workflow_activity", 0), ("workflow_activity", 17), @@ -156,3 +1223,140 @@ def test_a_workflow_producer_preserves_the_task_id_and_attempt() -> None: task.workflow_task_id = 11 task.attempt.started_event_id, task.attempt.attempt = 37, 2 assert _producer_proto(temporalio.contrib.streams.as_producer(proto)) == proto + + +def test_a_client_uses_one_producer_for_all_its_streams() -> None: + service_client = Mock(spec=temporalio.service.ServiceClient) + config = temporalio.streams.StreamConfig(stores=[FaultStore()]) + clients = [ + temporalio.client.Client(service_client, stream_config=config) for _ in range(2) + ] + [first, second, third] = [ + _producer_proto( + temporalio.nexus.system._support.default_producer( + client.get_stream( + temporalio.nexus.system.stream_service.StreamRef(id=id) + )._nexus_client + ) + ) + for client, id in ((clients[0], "a"), (clients[0], "b"), (clients[1], "a")) + ] + assert first == second != third + assert first.client.namespace == "default" and first.client.id + + +def test_a_client_call_past_its_rpc_timeout_cancels_the_store_call() -> None: + async def script() -> None: + loop = asyncio.get_running_loop() + store, hold = FaultStore(), Hold() + store.faults["describe_stream"].append(hold) + client = temporalio.client.Client( + Mock(spec=temporalio.service.ServiceClient), + stream_config=temporalio.streams.StreamConfig([store]), + ) + stream = client.get_stream( + temporalio.nexus.system.stream_service.StreamRef[str](id="s") + ) + with pytest.raises(temporalio.exceptions.StreamError) as timed_out: + await stream.describe(rpc_timeout=timedelta(seconds=5)) + assert timed_out.value.reason == _UNAVAILABLE + assert loop.time() == 5 + assert hold.cancelled.is_set() + assert asyncio.all_tasks() == {asyncio.current_task()} + + run_with_virtual_clock(script()) + + +def test_a_client_iterator_on_an_idle_stream_waits_between_reads() -> None: + class ReadLog(temporalio.testing.MemoryStreamStore): + def __init__(self) -> None: + super().__init__() + self.reads: list[proto.ReadRecordsRequest] = [] + + async def read_records( + self, request: proto.ReadRecordsRequest + ) -> proto.ReadRecordsResponse: + self.reads.append(request) + return await super().read_records(request) + + def waits(store: ReadLog) -> list[timedelta | None]: + return [ + request.wait.ToTimedelta() if request.HasField("wait") else None + for request in store.reads + ] + + async def script() -> None: + loop = asyncio.get_running_loop() + store = ReadLog() + client = temporalio.client.Client( + Mock(spec=temporalio.service.ServiceClient), + stream_config=temporalio.streams.StreamConfig([store]), + ) + stream = await client.create_stream(id="s", body_type=int) + minute = temporalio.nexus.system._support.DEFAULT_READ_WAIT + ten, nine = timedelta(seconds=10), timedelta(seconds=9) + # With no wait, the first read returns immediately and each later one waits + # the default wait. A wait of zero means the caller chose to read in a loop. + # The Store gets no wait for it, because a Store may take a zero wait as one + # with no end. The client caps a wait below the rpc_timeout, so the Store + # answers in time. + cases: list[tuple[timedelta | None, timedelta | None, list[Any]]] = [ + (None, None, [None, minute, minute, minute, minute]), + (ten, None, [ten] * 5), + (timedelta(0), None, [None] * 5), + (None, ten, [None, nine, nine, nine, nine]), + (minute, ten, [nine] * 5), + (timedelta(seconds=5), ten, [timedelta(seconds=5)] * 5), + # Under ten seconds, the client keeps a tenth of the timeout for the + # Store's answer. A timeout of zero is no timeout. + (ten, timedelta(seconds=2), [timedelta(seconds=1.8)] * 5), + (ten, timedelta(0), [ten] * 5), + ] + for wait, rpc_timeout, expected in cases: + with failure_note(f"wait {wait}, rpc_timeout {rpc_timeout}"): + store.reads.clear() + start = loop.time() + pages = stream.read_pages(wait=wait, rpc_timeout=rpc_timeout) + for _ in expected: + assert not (await anext(pages)).records + await pages.aclose() + assert waits(store) == expected + assert loop.time() - start == pytest.approx( + sum(w.total_seconds() for w in expected if w) + ) + + # A Record that arrives during a wait ends it immediately, and the caller stops. + async def append_later() -> None: + await asyncio.sleep(90) + await stream.append(1) + + store.reads.clear() + start = loop.time() + appending = asyncio.create_task(append_later()) + async with asyncio.timeout(600): + async for record in stream.read(): + assert record.body == 1 + break + await appending + assert loop.time() - start == pytest.approx(90) + assert waits(store) == [None, minute, minute] + + run_with_virtual_clock(script()) + + +@pytest.mark.parametrize("offsets, expected", [([b"b", b"c"], b"c"), ([], b"a")]) +def test_next_read_resumes_after_the_last_returned_record( + offsets: list[bytes], expected: bytes +) -> None: + request = temporalio.nexus.system.stream_service.ReadRecordsRequest( + ref=temporalio.nexus.system.stream_service.StreamRef[int](id="s"), + after_offset=b"a", + ) + page = temporalio.nexus.system.stream_service.ReadRecordsResponse( + records=[ + temporalio.nexus.system.stream_service.StreamRecord(body=i, offset=offset) + for i, offset in enumerate(offsets) + ], + ) + next_request = temporalio.nexus.system._support.next_read_request(request, page) + assert next_request is not None and next_request.after_offset == expected diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py new file mode 100644 index 0000000000..406ecb1c86 --- /dev/null +++ b/tests/nexus/test_streams_with_worker.py @@ -0,0 +1,128 @@ +"""Tests of Streams with a Worker on the test server.""" + +from datetime import timedelta +from typing import Any + +from temporalio import activity, workflow +from temporalio.api.enums.v1 import EventType +from temporalio.client import Client +from temporalio.common import RetryPolicy +from temporalio.contrib.streams import current_producer +from temporalio.exceptions import ApplicationError +from temporalio.nexus.system.stream_service import ( + ProducerKindLocalActivity, + StreamRef, +) +from temporalio.worker import ( + Replayer, +) +from tests.helpers import new_worker +from tests.helpers.streams import ( + FaultStore, + Hold, + stream_client, +) + + +@activity.defn +async def _write_local_attempt(stream_id: str, retry: bool) -> str: + info = activity.info() + stream = activity.client().get_stream(StreamRef[str](id=stream_id)) + await stream.append(info.activity_id) + if retry and info.attempt == 1: + await activity.wait_for_worker_shutdown() + raise ApplicationError("retry after a timer") + kind = current_producer().kind + assert isinstance(kind, ProducerKindLocalActivity) + return kind.value.activity_id + + +@workflow.defn +class _LocalProducerWorkflow: + @workflow.run + async def run(self, stream_id: str) -> None: + original_id = await workflow.execute_local_activity( + _write_local_attempt, + args=[stream_id, True], + start_to_close_timeout=timedelta(seconds=10), + local_retry_threshold=timedelta(milliseconds=50), + retry_policy=RetryPolicy( + initial_interval=timedelta(milliseconds=250), maximum_attempts=2 + ), + ) + await workflow.execute_local_activity( + _write_local_attempt, + args=[stream_id, False], + activity_id=original_id, + start_to_close_timeout=timedelta(seconds=10), + ) + + +async def test_local_activity_producers_survive_timer_retries_and_worker_restart( + client: Client, +) -> None: + store, writing = FaultStore(), Hold() + client = stream_client(client, store) + stream = await client.create_stream(id="local producers", body_type=str) + store.faults["append_records"].append(writing) + async with new_worker( + client, + _LocalProducerWorkflow, + activities=[_write_local_attempt], + identity="before restart", + graceful_shutdown_timeout=timedelta(seconds=10), + ) as first: + queue = first.task_queue + handle = await client.start_workflow( + _LocalProducerWorkflow.run, + args=[stream.ref.id], + id=queue, + task_queue=queue, + ) + await writing.started.wait() + writing.release() + async with new_worker( + client, + _LocalProducerWorkflow, + activities=[_write_local_attempt], + task_queue=queue, + identity="after restart", + ): + await handle.result() + history = await handle.fetch_history() + await Replayer(workflows=[_LocalProducerWorkflow]).replay_workflow(history) + assert len(_events(history, EventType.EVENT_TYPE_TIMER_STARTED)) == 1 + starts = _events(history, EventType.EVENT_TYPE_WORKFLOW_TASK_STARTED) + workers = [ + event.workflow_task_started_event_attributes.identity for event in starts + ] + assert workers == ["before restart", "after restart"] + before, after = starts[-2].event_id, starts[-1].event_id + records = (await stream.read_page()).records + first_id, retry_id, reused_id = [record.body for record in records] + assert first_id == reused_id and first_id != retry_id + producers = [] + for record in records: + assert record.producer and isinstance( + record.producer.kind, ProducerKindLocalActivity + ) + producer = record.producer.kind.value + assert producer.attempt and producer.attempt.task + producers.append( + ( + producer.seq, + producer.activity_id, + producer.attempt.task.started_event_id, + producer.attempt.attempt, + ) + ) + # The retry is a new schedule command, so the second Local Activity has seq 3. + assert producers == [ + (1, first_id, before, 1), + (1, first_id, after, 2), + (3, first_id, after, 1), + ] + + +def _events(history: Any, event_type: EventType.ValueType) -> list[Any]: + return [event for event in history.events if event.event_type == event_type]