diff --git a/pyproject.toml b/pyproject.toml index 54ea30212d..5b7890ab52 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -177,11 +177,15 @@ exclude = [ # Ignore generated code 'temporalio/api', 'temporalio/bridge/proto', + 'temporalio/nexus/system/stream_service', 'temporalio/nexus/system/workflow_service', ] [[tool.mypy.overrides]] -module = "temporalio.nexus.system.workflow_service.*" +module = [ + "temporalio.nexus.system.stream_service.*", + "temporalio.nexus.system.workflow_service.*", +] ignore_errors = true [tool.pydocstyle] diff --git a/scripts/gen_nexus_system_api.py b/scripts/gen_nexus_system_api.py index a5a6381f4b..ff799b653d 100644 --- a/scripts/gen_nexus_system_api.py +++ b/scripts/gen_nexus_system_api.py @@ -24,8 +24,9 @@ wit_deps_dir = wit_input_dir / "deps" workflow_output_dir = base_dir / "temporalio" / "nexus" / "system" / "workflow_service" notification_output_dir = base_dir / "temporalio" / "nexus" / "notifications" +stream_output_dir = base_dir / "temporalio" / "nexus" / "system" / "stream_service" workflow_init_path = base_dir / "temporalio" / "workflow" / "__init__.py" -NEX_GEN_VERSION = "0.2.13" +NEX_GEN_REVISION = "5983b56b047cea94acbdb4760ca76f145f5a55d7" proto_files = [ gen_protos.api_proto_dir / "temporal" @@ -39,31 +40,40 @@ / "notificationservice" / "v1" / "request_response.proto", + gen_protos.api_proto_dir + / "temporal" + / "api" + / "streamservice" + / "v1" + / "request_response.proto", + gen_protos.api_proto_dir / "temporal" / "api" / "sdk" / "v1" / "stream.proto", ] def nex_gen_command() -> list[str]: if bin_path := os.environ.get("NEX_GEN_BIN"): return [bin_path] - if ( - shutil.which("nexgen") is None - or subprocess.check_output(["nexgen", "--version"], text=True).strip() - != f"nexgen {NEX_GEN_VERSION}" - ): + install_dir = base_dir / "build" / "nexgen" / NEX_GEN_REVISION + binary = install_dir / "bin" / ("nexgen.exe" if os.name == "nt" else "nexgen") + if not binary.is_file(): subprocess.check_call( [ "cargo", "install", "--locked", "nexgen", - "--version", - NEX_GEN_VERSION, + "--git", + "https://github.com/temporalio/nexgen.git", + "--rev", + NEX_GEN_REVISION, + "--root", + str(install_dir), "--features", "advanced", "--force", ] ) - return ["nexgen"] + return [str(binary)] def build_descriptor_set(descriptor_path: Path) -> None: @@ -85,11 +95,11 @@ def generate_package( output_dir: Path, descriptor_path: Path, *, - native_api: bool, + targets: str | None, ) -> None: args = [*command, "python", str(wit_input_dir / wit_name), str(wit_deps_dir)] - if native_api: - args.extend(["--targets", "workflow"]) + if targets: + args.extend(["--targets", targets]) subprocess.check_call( [ *args, @@ -132,17 +142,28 @@ def replace_marker_block( def generate_workflow_exports() -> None: - exports = generated_exports(workflow_output_dir / "__init__.py") - import_block = [ - "# BEGIN GENERATED NEXUS SYSTEM EXPORTS\n", - "from temporalio.nexus.system.workflow_service import (\n", - *[f" {export},\n" for export in exports], - ")\n", - "# END GENERATED NEXUS SYSTEM EXPORTS\n", + packages = [ + ( + "temporalio.nexus.system.stream_service.workflow", + stream_output_dir / "workflow" / "__init__.py", + ), + ( + "temporalio.nexus.system.workflow_service", + workflow_output_dir / "__init__.py", + ), ] + exports = [(module, generated_exports(path)) for module, path in packages] + import_block = ["# BEGIN GENERATED NEXUS SYSTEM EXPORTS\n"] + for module, names in exports: + import_block += [ + f"from {module} import (\n", + *[f" {name},\n" for name in names], + ")\n", + ] + import_block.append("# END GENERATED NEXUS SYSTEM EXPORTS\n") all_block = [ " # BEGIN GENERATED NEXUS SYSTEM __ALL__\n", - *[f' "{export}",\n' for export in exports], + *[f' "{name}",\n' for _, names in exports for name in names], " # END GENERATED NEXUS SYSTEM __ALL__\n", ] content = workflow_init_path.read_text() @@ -163,6 +184,7 @@ def generate_nexus_system_api() -> None: required_paths = [ wit_input_dir / "workflow-service.wit", wit_input_dir / "notification-service.wit", + wit_input_dir / "stream-service.wit", wit_deps_dir, *proto_files, ] @@ -173,9 +195,10 @@ def generate_nexus_system_api() -> None: descriptor_path = Path(temp_dir) / "temporal_api.bin" build_descriptor_set(descriptor_path) command = nex_gen_command() - for wit_name, output_dir, native_api in ( - ("workflow-service.wit", workflow_output_dir, True), - ("notification-service.wit", notification_output_dir, False), + for wit_name, output_dir, targets in ( + ("workflow-service.wit", workflow_output_dir, "workflow"), + ("notification-service.wit", notification_output_dir, None), + ("stream-service.wit", stream_output_dir, "workflow,client"), ): shutil.rmtree(output_dir, ignore_errors=True) output_dir.parent.mkdir(parents=True, exist_ok=True) @@ -184,13 +207,14 @@ def generate_nexus_system_api() -> None: wit_name, output_dir, descriptor_path, - native_api=native_api, + targets=targets, ) workflow_output_dir.parent.joinpath("__init__.py").touch() generate_workflow_exports() format_paths = [ str(workflow_output_dir), str(notification_output_dir), + str(stream_output_dir), str(workflow_init_path), ] subprocess.check_call( diff --git a/temporalio/_workflow_context.py b/temporalio/_workflow_context.py index 2a9041dcec..7b35f4568b 100644 --- a/temporalio/_workflow_context.py +++ b/temporalio/_workflow_context.py @@ -31,9 +31,16 @@ class _WorkflowLogicFlag(IntEnum): # Remove the explicit overrides for this flag from tests/worker/test_workflow_flags.py # when enabling it. Then remove this reminder. DECODE_DATETIME_PROXIES = 3 + USE_LAST_STREAM_RECORD_OFFSET = 4 + REPORT_EXISTING_STREAM_AS_FALSE = 5 -_DEFAULT_ENABLED_WORKFLOW_LOGIC_FLAGS: frozenset[_WorkflowLogicFlag] = frozenset() +_DEFAULT_ENABLED_WORKFLOW_LOGIC_FLAGS: frozenset[_WorkflowLogicFlag] = frozenset( + { + _WorkflowLogicFlag.USE_LAST_STREAM_RECORD_OFFSET, + _WorkflowLogicFlag.REPORT_EXISTING_STREAM_AS_FALSE, + } +) @dataclass(frozen=True) diff --git a/temporalio/activity.py b/temporalio/activity.py index b2afae0179..640450db55 100644 --- a/temporalio/activity.py +++ b/temporalio/activity.py @@ -181,6 +181,9 @@ class Info: This API is experimental and unstable. """ + _scheduled_event_id: int = 0 + """Allow Stream writes when the task token has no scheduling event ID.""" + @property def in_workflow(self) -> bool: """Was this activity started by a workflow?""" diff --git a/temporalio/api/enums/v1/__init__.py b/temporalio/api/enums/v1/__init__.py index f1e9a53005..58abe69b3e 100644 --- a/temporalio/api/enums/v1/__init__.py +++ b/temporalio/api/enums/v1/__init__.py @@ -49,6 +49,7 @@ from .query_pb2 import QueryRejectCondition, QueryResultType from .reset_pb2 import ResetReapplyExcludeType, ResetReapplyType, ResetType from .schedule_pb2 import ScheduleOverlapPolicy +from .stream_pb2 import StreamErrorReason, StreamIdConflictPolicy from .task_queue_pb2 import ( BuildIdTaskReachability, DescribeTaskQueueMode, @@ -126,6 +127,8 @@ "Severity", "SignalExternalWorkflowExecutionFailedCause", "StartChildWorkflowExecutionFailedCause", + "StreamErrorReason", + "StreamIdConflictPolicy", "SuggestContinueAsNewReason", "TaskQueueKind", "TaskQueueType", diff --git a/temporalio/api/enums/v1/stream_pb2.py b/temporalio/api/enums/v1/stream_pb2.py new file mode 100644 index 0000000000..1fd015c418 --- /dev/null +++ b/temporalio/api/enums/v1/stream_pb2.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: temporal/api/enums/v1/stream.proto +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n"temporal/api/enums/v1/stream.proto\x12\x15temporal.api.enums.v1*\x93\x01\n\x16StreamIdConflictPolicy\x12)\n%STREAM_ID_CONFLICT_POLICY_UNSPECIFIED\x10\x00\x12"\n\x1eSTREAM_ID_CONFLICT_POLICY_FAIL\x10\x01\x12*\n&STREAM_ID_CONFLICT_POLICY_USE_EXISTING\x10\x02*\xd9\x03\n\x11StreamErrorReason\x12#\n\x1fSTREAM_ERROR_REASON_UNSPECIFIED\x10\x00\x12!\n\x1dSTREAM_ERROR_REASON_NOT_FOUND\x10\x01\x12\x1f\n\x1bSTREAM_ERROR_REASON_EXPIRED\x10\x02\x12\x1e\n\x1aSTREAM_ERROR_REASON_FENCED\x10\x03\x12&\n"STREAM_ERROR_REASON_FORMAT_TOO_NEW\x10\x04\x12\'\n#STREAM_ERROR_REASON_OFFSET_TOO_HIGH\x10\x05\x12!\n\x1dSTREAM_ERROR_REASON_TOO_LARGE\x10\x06\x12(\n$STREAM_ERROR_REASON_INVALID_ARGUMENT\x10\x07\x12)\n%STREAM_ERROR_REASON_STORE_UNAVAILABLE\x10\x08\x12#\n\x1fSTREAM_ERROR_REASON_UNSUPPORTED\x10\t\x12&\n"STREAM_ERROR_REASON_ALREADY_EXISTS\x10\n\x12%\n!STREAM_ERROR_REASON_STORE_CORRUPT\x10\x0b\x42\x83\x01\n\x18io.temporal.api.enums.v1B\x0bStreamProtoP\x01Z!go.temporal.io/api/enums/v1;enums\xaa\x02\x17Temporalio.Api.Enums.V1\xea\x02\x1aTemporalio::Api::Enums::V1b\x06proto3' +) + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, __name__, globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b"\n\030io.temporal.api.enums.v1B\013StreamProtoP\001Z!go.temporal.io/api/enums/v1;enums\252\002\027Temporalio.Api.Enums.V1\352\002\032Temporalio::Api::Enums::V1" + _STREAMIDCONFLICTPOLICY._serialized_start = 62 + _STREAMIDCONFLICTPOLICY._serialized_end = 209 + _STREAMERRORREASON._serialized_start = 212 + _STREAMERRORREASON._serialized_end = 685 +# @@protoc_insertion_point(module_scope) diff --git a/temporalio/api/enums/v1/stream_pb2.pyi b/temporalio/api/enums/v1/stream_pb2.pyi new file mode 100644 index 0000000000..4c0f9134b9 --- /dev/null +++ b/temporalio/api/enums/v1/stream_pb2.pyi @@ -0,0 +1,120 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.enum_type_wrapper + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _StreamIdConflictPolicy: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _StreamIdConflictPolicyEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ + _StreamIdConflictPolicy.ValueType + ], + builtins.type, +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + 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.""" + +class StreamIdConflictPolicy( + _StreamIdConflictPolicy, metaclass=_StreamIdConflictPolicyEnumTypeWrapper +): + """Experimental. Might change in the future. + The conflict policy for an existing Stream. Unspecified means `FAIL`. + """ + +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.""" +global___StreamIdConflictPolicy = StreamIdConflictPolicy + +class _StreamErrorReason: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _StreamErrorReasonEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ + _StreamErrorReason.ValueType + ], + builtins.type, +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + 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`).""" + 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 + """The Stream has a newer format than this caller knows (`FAILED_PRECONDITION`).""" + STREAM_ERROR_REASON_OFFSET_TOO_HIGH: _StreamErrorReason.ValueType # 5 + """The offset is past the newest one, for example after a failover lost the newest Records. A + read from it works again once the Stream has Records up to that offset (`OUT_OF_RANGE`). + """ + STREAM_ERROR_REASON_TOO_LARGE: _StreamErrorReason.ValueType # 6 + """A Record or a batch is larger than the Store allows (`INVALID_ARGUMENT`).""" + STREAM_ERROR_REASON_INVALID_ARGUMENT: _StreamErrorReason.ValueType # 7 + """The request is malformed (`INVALID_ARGUMENT`).""" + STREAM_ERROR_REASON_STORE_UNAVAILABLE: _StreamErrorReason.ValueType # 8 + """The Store failed or did not respond. A retry can succeed (`UNAVAILABLE`).""" + STREAM_ERROR_REASON_UNSUPPORTED: _StreamErrorReason.ValueType # 9 + """The Store doesn't support something that the call needs (`UNIMPLEMENTED`).""" + STREAM_ERROR_REASON_ALREADY_EXISTS: _StreamErrorReason.ValueType # 10 + """A create with the `FAIL` policy found that the Stream already exists (`ALREADY_EXISTS`).""" + STREAM_ERROR_REASON_STORE_CORRUPT: _StreamErrorReason.ValueType # 11 + """Stored data is invalid. Retrying cannot repair it (`DATA_LOSS`).""" + +class StreamErrorReason( + _StreamErrorReason, metaclass=_StreamErrorReasonEnumTypeWrapper +): + """Experimental. Might change in the future. + Several reasons share a gRPC status code. Callers must check the reason to distinguish them. + """ + +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`).""" +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 +"""The Stream has a newer format than this caller knows (`FAILED_PRECONDITION`).""" +STREAM_ERROR_REASON_OFFSET_TOO_HIGH: StreamErrorReason.ValueType # 5 +"""The offset is past the newest one, for example after a failover lost the newest Records. A +read from it works again once the Stream has Records up to that offset (`OUT_OF_RANGE`). +""" +STREAM_ERROR_REASON_TOO_LARGE: StreamErrorReason.ValueType # 6 +"""A Record or a batch is larger than the Store allows (`INVALID_ARGUMENT`).""" +STREAM_ERROR_REASON_INVALID_ARGUMENT: StreamErrorReason.ValueType # 7 +"""The request is malformed (`INVALID_ARGUMENT`).""" +STREAM_ERROR_REASON_STORE_UNAVAILABLE: StreamErrorReason.ValueType # 8 +"""The Store failed or did not respond. A retry can succeed (`UNAVAILABLE`).""" +STREAM_ERROR_REASON_UNSUPPORTED: StreamErrorReason.ValueType # 9 +"""The Store doesn't support something that the call needs (`UNIMPLEMENTED`).""" +STREAM_ERROR_REASON_ALREADY_EXISTS: StreamErrorReason.ValueType # 10 +"""A create with the `FAIL` policy found that the Stream already exists (`ALREADY_EXISTS`).""" +STREAM_ERROR_REASON_STORE_CORRUPT: StreamErrorReason.ValueType # 11 +"""Stored data is invalid. Retrying cannot repair it (`DATA_LOSS`).""" +global___StreamErrorReason = StreamErrorReason diff --git a/temporalio/api/sdk/v1/__init__.py b/temporalio/api/sdk/v1/__init__.py index 4f23aac6a6..c35c2154d9 100644 --- a/temporalio/api/sdk/v1/__init__.py +++ b/temporalio/api/sdk/v1/__init__.py @@ -7,6 +7,14 @@ ) from .event_group_marker_pb2 import EventGroupMarker from .external_storage_pb2 import ExternalStorageReference +from .stream_pb2 import ( + AppendRecordsRequest, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + ReadRecordsRequest, + StreamRef, +) from .task_complete_metadata_pb2 import WorkflowTaskCompletedMetadata from .user_metadata_pb2 import UserMetadata from .worker_config_pb2 import WorkerConfig @@ -17,13 +25,19 @@ ) __all__ = [ + "AppendRecordsRequest", + "CreateStreamRequest", + "CreateStreamResponse", + "DescribeStreamRequest", "EnhancedStackTrace", "EventGroupMarker", "ExternalStorageReference", + "ReadRecordsRequest", "StackTrace", "StackTraceFileLocation", "StackTraceFileSlice", "StackTraceSDKInfo", + "StreamRef", "UserMetadata", "WorkerConfig", "WorkflowDefinition", diff --git a/temporalio/api/sdk/v1/stream_pb2.py b/temporalio/api/sdk/v1/stream_pb2.py new file mode 100644 index 0000000000..efa1175735 --- /dev/null +++ b/temporalio/api/sdk/v1/stream_pb2.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: temporal/api/sdk/v1/stream.proto +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 + +from temporalio.api.enums.v1 import ( + stream_pb2 as temporal_dot_api_dot_enums_dot_v1_dot_stream__pb2, +) +from temporalio.api.stream.v1 import ( + message_pb2 as temporal_dot_api_dot_stream_dot_v1_dot_message__pb2, +) + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n temporal/api/sdk/v1/stream.proto\x12\x13temporal.api.sdk.v1\x1a\x1egoogle/protobuf/duration.proto\x1a"temporal/api/enums/v1/stream.proto\x1a$temporal/api/stream/v1/message.proto"&\n\tStreamRef\x12\n\n\x02id\x18\x01 \x01(\t\x12\r\n\x05store\x18\x02 \x01(\t"\x94\x01\n\x13\x43reateStreamRequest\x12\x32\n\nstream_ref\x18\x01 \x01(\x0b\x32\x1e.temporal.api.sdk.v1.StreamRef\x12I\n\x12id_conflict_policy\x18\x02 \x01(\x0e\x32-.temporal.api.enums.v1.StreamIdConflictPolicy"T\n\x14\x43reateStreamResponse\x12+\n\x03ref\x18\x01 \x01(\x0b\x32\x1e.temporal.api.sdk.v1.StreamRef\x12\x0f\n\x07\x63reated\x18\x02 \x01(\x08"\xae\x01\n\x14\x41ppendRecordsRequest\x12+\n\x03ref\x18\x01 \x01(\x0b\x32\x1e.temporal.api.sdk.v1.StreamRef\x12\x32\n\x08producer\x18\x02 \x01(\x0b\x32 .temporal.api.stream.v1.Producer\x12\x35\n\x07records\x18\x03 \x03(\x0b\x32$.temporal.api.stream.v1.AppendRecord"\xa7\x01\n\x12ReadRecordsRequest\x12+\n\x03ref\x18\x01 \x01(\x0b\x32\x1e.temporal.api.sdk.v1.StreamRef\x12\x13\n\x0b\x66rom_offset\x18\x02 \x01(\x0c\x12\x13\n\x0bmax_records\x18\x03 \x01(\x05\x12\x11\n\tmax_bytes\x18\x04 \x01(\x03\x12\'\n\x04wait\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration"D\n\x15\x44\x65scribeStreamRequest\x12+\n\x03ref\x18\x01 \x01(\x0b\x32\x1e.temporal.api.sdk.v1.StreamRefBy\n\x16io.temporal.api.sdk.v1B\x0bStreamProtoP\x01Z\x1dgo.temporal.io/api/sdk/v1;sdk\xaa\x02\x15Temporalio.Api.Sdk.V1\xea\x02\x18Temporalio::Api::Sdk::V1b\x06proto3' +) + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, __name__, globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b"\n\026io.temporal.api.sdk.v1B\013StreamProtoP\001Z\035go.temporal.io/api/sdk/v1;sdk\252\002\025Temporalio.Api.Sdk.V1\352\002\030Temporalio::Api::Sdk::V1" + _STREAMREF._serialized_start = 163 + _STREAMREF._serialized_end = 201 + _CREATESTREAMREQUEST._serialized_start = 204 + _CREATESTREAMREQUEST._serialized_end = 352 + _CREATESTREAMRESPONSE._serialized_start = 354 + _CREATESTREAMRESPONSE._serialized_end = 438 + _APPENDRECORDSREQUEST._serialized_start = 441 + _APPENDRECORDSREQUEST._serialized_end = 615 + _READRECORDSREQUEST._serialized_start = 618 + _READRECORDSREQUEST._serialized_end = 785 + _DESCRIBESTREAMREQUEST._serialized_start = 787 + _DESCRIBESTREAMREQUEST._serialized_end = 855 +# @@protoc_insertion_point(module_scope) diff --git a/temporalio/api/sdk/v1/stream_pb2.pyi b/temporalio/api/sdk/v1/stream_pb2.pyi new file mode 100644 index 0000000000..3e4a146b2c --- /dev/null +++ b/temporalio/api/sdk/v1/stream_pb2.pyi @@ -0,0 +1,237 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +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 temporalio.api.enums.v1.stream_pb2 +import temporalio.api.stream.v1.message_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class StreamRef(google.protobuf.message.Message): + """Experimental. Might change in the future. + Callers treat `id` as opaque. A Store can reuse an expired id only after it forgets the Stream. + SDKs encode references with this message so that other SDKs can decode them. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ID_FIELD_NUMBER: builtins.int + STORE_FIELD_NUMBER: builtins.int + id: builtins.str + store: builtins.str + """When empty, the SDK uses its Store selector or the only registered Store. + This field is local to the SDK. Store and server requests omit it. + """ + def __init__( + self, + *, + id: builtins.str = ..., + store: builtins.str = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["id", b"id", "store", b"store"] + ) -> None: ... + +global___StreamRef = StreamRef + +@typing.final +class CreateStreamRequest(google.protobuf.message.Message): + """Experimental. Might change in the future. + Uses the Store request contract, with a `StreamRef` for SDK routing. + (-- api-linter: core::0133=disabled + aip.dev/not-precedent: The request identifies a Stream by its ref. --) + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + STREAM_REF_FIELD_NUMBER: builtins.int + ID_CONFLICT_POLICY_FIELD_NUMBER: builtins.int + id_conflict_policy: ( + temporalio.api.enums.v1.stream_pb2.StreamIdConflictPolicy.ValueType + ) + @property + def stream_ref(self) -> global___StreamRef: + """Required. The Stream to create. Its `id` must not be empty.""" + + def __init__( + self, + *, + stream_ref: global___StreamRef | None = ..., + id_conflict_policy: temporalio.api.enums.v1.stream_pb2.StreamIdConflictPolicy.ValueType = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["stream_ref", b"stream_ref"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "id_conflict_policy", b"id_conflict_policy", "stream_ref", b"stream_ref" + ], + ) -> None: ... + +global___CreateStreamRequest = CreateStreamRequest + +@typing.final +class CreateStreamResponse(google.protobuf.message.Message): + """Experimental. Might change in the future. + The reference includes the Store selected by the SDK. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REF_FIELD_NUMBER: builtins.int + CREATED_FIELD_NUMBER: builtins.int + created: builtins.bool + """False when `USE_EXISTING` returned a Stream that already existed.""" + @property + def ref(self) -> global___StreamRef: + """The SDK fills the Store name so that another caller can route the reference.""" + + def __init__( + self, + *, + ref: global___StreamRef | None = ..., + created: builtins.bool = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["ref", b"ref"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["created", b"created", "ref", b"ref"] + ) -> None: ... + +global___CreateStreamResponse = CreateStreamResponse + +@typing.final +class AppendRecordsRequest(google.protobuf.message.Message): + """Experimental. Might change in the future. + Uses the Store request contract, with a `StreamRef` for SDK routing. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REF_FIELD_NUMBER: builtins.int + PRODUCER_FIELD_NUMBER: builtins.int + RECORDS_FIELD_NUMBER: builtins.int + @property + def ref(self) -> global___StreamRef: + """Required.""" + + @property + def producer(self) -> temporalio.api.stream.v1.message_pb2.Producer: ... + @property + def records( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + temporalio.api.stream.v1.message_pb2.AppendRecord + ]: ... + def __init__( + self, + *, + ref: global___StreamRef | None = ..., + producer: temporalio.api.stream.v1.message_pb2.Producer | None = ..., + records: collections.abc.Iterable[ + temporalio.api.stream.v1.message_pb2.AppendRecord + ] + | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["producer", b"producer", "ref", b"ref"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "producer", b"producer", "records", b"records", "ref", b"ref" + ], + ) -> None: ... + +global___AppendRecordsRequest = AppendRecordsRequest + +@typing.final +class ReadRecordsRequest(google.protobuf.message.Message): + """Experimental. Might change in the future. + Uses the Store request contract, with a `StreamRef` for SDK routing. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REF_FIELD_NUMBER: builtins.int + FROM_OFFSET_FIELD_NUMBER: builtins.int + MAX_RECORDS_FIELD_NUMBER: builtins.int + MAX_BYTES_FIELD_NUMBER: builtins.int + WAIT_FIELD_NUMBER: builtins.int + from_offset: builtins.bytes + """(-- api-linter: core::0140::prepositions=disabled + aip.dev/not-precedent: "from" marks the start of a range of offsets. --) + """ + max_records: builtins.int + """Zero uses the configured default.""" + max_bytes: builtins.int + """One Record can exceed this target unless an SDK hard limit rejects it.""" + @property + def ref(self) -> global___StreamRef: + """Required.""" + + @property + def wait(self) -> google.protobuf.duration_pb2.Duration: ... + def __init__( + self, + *, + ref: global___StreamRef | None = ..., + from_offset: builtins.bytes = ..., + max_records: builtins.int = ..., + max_bytes: builtins.int = ..., + wait: google.protobuf.duration_pb2.Duration | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["ref", b"ref", "wait", b"wait"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "from_offset", + b"from_offset", + "max_bytes", + b"max_bytes", + "max_records", + b"max_records", + "ref", + b"ref", + "wait", + b"wait", + ], + ) -> None: ... + +global___ReadRecordsRequest = ReadRecordsRequest + +@typing.final +class DescribeStreamRequest(google.protobuf.message.Message): + """Experimental. Might change in the future. + Uses the Store request contract, with a `StreamRef` for SDK routing. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REF_FIELD_NUMBER: builtins.int + @property + def ref(self) -> global___StreamRef: + """Required.""" + + def __init__( + self, + *, + ref: global___StreamRef | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["ref", b"ref"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["ref", b"ref"]) -> None: ... + +global___DescribeStreamRequest = DescribeStreamRequest diff --git a/temporalio/api/stream/__init__.py b/temporalio/api/stream/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/temporalio/api/stream/v1/__init__.py b/temporalio/api/stream/v1/__init__.py new file mode 100644 index 0000000000..6e13004121 --- /dev/null +++ b/temporalio/api/stream/v1/__init__.py @@ -0,0 +1,29 @@ +from .message_pb2 import ( + ActivityAttempt, + AppendRecord, + ClientProducer, + LocalActivityAttempt, + LocalActivityProducer, + Producer, + StandaloneActivityProducer, + StreamErrorDetails, + StreamRecord, + WorkflowActivityProducer, + WorkflowProducer, + WorkflowTaskAttempt, +) + +__all__ = [ + "ActivityAttempt", + "AppendRecord", + "ClientProducer", + "LocalActivityAttempt", + "LocalActivityProducer", + "Producer", + "StandaloneActivityProducer", + "StreamErrorDetails", + "StreamRecord", + "WorkflowActivityProducer", + "WorkflowProducer", + "WorkflowTaskAttempt", +] diff --git a/temporalio/api/stream/v1/message_pb2.py b/temporalio/api/stream/v1/message_pb2.py new file mode 100644 index 0000000000..424b3f3402 --- /dev/null +++ b/temporalio/api/stream/v1/message_pb2.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: temporal/api/stream/v1/message.proto +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 + +from temporalio.api.common.v1 import ( + message_pb2 as temporal_dot_api_dot_common_dot_v1_dot_message__pb2, +) +from temporalio.api.enums.v1 import ( + stream_pb2 as temporal_dot_api_dot_enums_dot_v1_dot_stream__pb2, +) + +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"\x88\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<\n\x07\x61ttempt\x18\x04 \x01(\x0b\x32+.temporal.api.stream.v1.WorkflowTaskAttempt"\xa3\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\x04 \x01(\t\x12=\n\x07\x61ttempt\x18\x05 \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' +) + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, __name__, globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b"\n\031io.temporal.api.stream.v1B\014MessageProtoP\001Z#go.temporal.io/api/stream/v1;stream\252\002\030Temporalio.Api.Stream.V1\352\002\033Temporalio::Api::Stream::V1" + _WORKFLOWTASKATTEMPT._serialized_start = 171 + _WORKFLOWTASKATTEMPT._serialized_end = 285 + _LOCALACTIVITYATTEMPT._serialized_start = 287 + _LOCALACTIVITYATTEMPT._serialized_end = 385 + _ACTIVITYATTEMPT._serialized_start = 387 + _ACTIVITYATTEMPT._serialized_end = 481 + _WORKFLOWPRODUCER._serialized_start = 484 + _WORKFLOWPRODUCER._serialized_end = 620 + _LOCALACTIVITYPRODUCER._serialized_start = 623 + _LOCALACTIVITYPRODUCER._serialized_end = 786 + _WORKFLOWACTIVITYPRODUCER._serialized_start = 789 + _WORKFLOWACTIVITYPRODUCER._serialized_end = 978 + _STANDALONEACTIVITYPRODUCER._serialized_start = 981 + _STANDALONEACTIVITYPRODUCER._serialized_end = 1123 + _CLIENTPRODUCER._serialized_start = 1125 + _CLIENTPRODUCER._serialized_end = 1172 + _PRODUCER._serialized_start = 1175 + _PRODUCER._serialized_end = 1548 + _APPENDRECORD._serialized_start = 1550 + _APPENDRECORD._serialized_end = 1611 + _STREAMRECORD._serialized_start = 1614 + _STREAMRECORD._serialized_end = 1743 + _STREAMERRORDETAILS._serialized_start = 1745 + _STREAMERRORDETAILS._serialized_end = 1823 +# @@protoc_insertion_point(module_scope) diff --git a/temporalio/api/stream/v1/message_pb2.pyi b/temporalio/api/stream/v1/message_pb2.pyi new file mode 100644 index 0000000000..4bae4ecb18 --- /dev/null +++ b/temporalio/api/stream/v1/message_pb2.pyi @@ -0,0 +1,539 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import typing + +import google.protobuf.descriptor +import google.protobuf.message +import google.protobuf.timestamp_pb2 + +import temporalio.api.common.v1.message_pb2 +import temporalio.api.enums.v1.stream_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class WorkflowTaskAttempt(google.protobuf.message.Message): + """Experimental. Might change in the future. + Attempts of one Producer compare by `started_event_id`, then `attempt`, then `started_time`. + Attempts from different runs have no order, including reset and Continue-As-New runs. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + STARTED_EVENT_ID_FIELD_NUMBER: builtins.int + ATTEMPT_FIELD_NUMBER: builtins.int + STARTED_TIME_FIELD_NUMBER: builtins.int + started_event_id: builtins.int + """Required.""" + attempt: builtins.int + """Required. Starts at 1 for each task, so this number alone cannot order writes in a run.""" + @property + def started_time(self) -> google.protobuf.timestamp_pb2.Timestamp: + """Distinguishes tasks when the server reuses a started event id after a speculative task. + Empty when the server did not send a started time. + """ + + def __init__( + self, + *, + 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", + ], + ) -> None: ... + +global___WorkflowTaskAttempt = WorkflowTaskAttempt + +@typing.final +class LocalActivityAttempt(google.protobuf.message.Message): + """Experimental. Might change in the future. + Attempts of one Producer compare by `task`, then `attempt`. + A later Workflow Task therefore has a later attempt. Attempts from different runs have no order. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + TASK_FIELD_NUMBER: builtins.int + ATTEMPT_FIELD_NUMBER: builtins.int + attempt: builtins.int + """Required. The Local Activity's own attempt number within that Workflow Task, starting at 1.""" + @property + def task(self) -> global___WorkflowTaskAttempt: + """Required. The Workflow Task attempt that dispatched the Local Activity.""" + + def __init__( + self, + *, + task: global___WorkflowTaskAttempt | None = ..., + attempt: builtins.int = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["task", b"task"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["attempt", b"attempt", "task", b"task"] + ) -> None: ... + +global___LocalActivityAttempt = LocalActivityAttempt + +@typing.final +class ActivityAttempt(google.protobuf.message.Message): + """Experimental. Might change in the future. + One attempt of an Activity. Two attempts compare by `attempt_scheduled_time`, then `attempt`. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ATTEMPT_SCHEDULED_TIME_FIELD_NUMBER: builtins.int + ATTEMPT_FIELD_NUMBER: builtins.int + attempt: builtins.int + """Required. The attempt number, starting at 1.""" + @property + def attempt_scheduled_time(self) -> google.protobuf.timestamp_pb2.Timestamp: + """Required. A reset restarts the attempt number, so this time orders attempts across a reset.""" + + def __init__( + self, + *, + attempt_scheduled_time: google.protobuf.timestamp_pb2.Timestamp | None = ..., + attempt: builtins.int = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal["attempt_scheduled_time", b"attempt_scheduled_time"], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "attempt", b"attempt", "attempt_scheduled_time", b"attempt_scheduled_time" + ], + ) -> None: ... + +global___ActivityAttempt = ActivityAttempt + +@typing.final +class WorkflowProducer(google.protobuf.message.Message): + """Experimental. Might change in the future. + Workflow writes share one Producer per run. Local Activity writes use `LocalActivityProducer`. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAMESPACE_FIELD_NUMBER: builtins.int + WORKFLOW_ID_FIELD_NUMBER: builtins.int + RUN_ID_FIELD_NUMBER: builtins.int + ATTEMPT_FIELD_NUMBER: builtins.int + namespace: builtins.str + """Required.""" + workflow_id: builtins.str + """Required.""" + run_id: builtins.str + """Required. This run id separates the Producer from other runs in the chain.""" + @property + def attempt(self) -> global___WorkflowTaskAttempt: + """Workflow code leaves this empty so that the SDK can set the actual Workflow Task attempt.""" + + def __init__( + self, + *, + namespace: builtins.str = ..., + workflow_id: builtins.str = ..., + run_id: builtins.str = ..., + attempt: global___WorkflowTaskAttempt | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["attempt", b"attempt"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "attempt", + b"attempt", + "namespace", + b"namespace", + "run_id", + b"run_id", + "workflow_id", + b"workflow_id", + ], + ) -> None: ... + +global___WorkflowProducer = WorkflowProducer + +@typing.final +class LocalActivityProducer(google.protobuf.message.Message): + """Experimental. Might change in the future. + The Producer of one Local Activity of a Workflow run. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAMESPACE_FIELD_NUMBER: builtins.int + WORKFLOW_ID_FIELD_NUMBER: builtins.int + RUN_ID_FIELD_NUMBER: builtins.int + ACTIVITY_ID_FIELD_NUMBER: builtins.int + ATTEMPT_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.""" + activity_id: builtins.str + """Required. Local Activities have no scheduled event, so this id must be unique in the run. + The SDK assigns an id unless the caller supplies one. + """ + @property + def attempt(self) -> global___LocalActivityAttempt: + """Required.""" + + def __init__( + self, + *, + namespace: builtins.str = ..., + workflow_id: builtins.str = ..., + run_id: builtins.str = ..., + activity_id: builtins.str = ..., + attempt: global___LocalActivityAttempt | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["attempt", b"attempt"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "activity_id", + b"activity_id", + "attempt", + b"attempt", + "namespace", + b"namespace", + "run_id", + b"run_id", + "workflow_id", + b"workflow_id", + ], + ) -> None: ... + +global___LocalActivityProducer = LocalActivityProducer + +@typing.final +class WorkflowActivityProducer(google.protobuf.message.Message): + """Experimental. Might change in the future. + The Producer of one Activity that a Workflow scheduled. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAMESPACE_FIELD_NUMBER: builtins.int + WORKFLOW_ID_FIELD_NUMBER: builtins.int + RUN_ID_FIELD_NUMBER: builtins.int + ACTIVITY_ID_FIELD_NUMBER: builtins.int + SCHEDULED_EVENT_ID_FIELD_NUMBER: builtins.int + ATTEMPT_FIELD_NUMBER: builtins.int + namespace: builtins.str + """Required. The namespace of the Workflow that scheduled the Activity.""" + workflow_id: builtins.str + """Required.""" + run_id: builtins.str + """Required.""" + activity_id: builtins.str + """Required.""" + scheduled_event_id: builtins.int + """Distinguishes calls when a run reuses an Activity id after an Activity completes. + Zero when the SDK does not have the `ActivityTaskScheduled` event id. + """ + @property + def attempt(self) -> global___ActivityAttempt: + """Required.""" + + def __init__( + self, + *, + namespace: builtins.str = ..., + workflow_id: builtins.str = ..., + run_id: builtins.str = ..., + activity_id: builtins.str = ..., + scheduled_event_id: builtins.int = ..., + attempt: global___ActivityAttempt | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["attempt", b"attempt"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "activity_id", + b"activity_id", + "attempt", + b"attempt", + "namespace", + b"namespace", + "run_id", + b"run_id", + "scheduled_event_id", + b"scheduled_event_id", + "workflow_id", + b"workflow_id", + ], + ) -> None: ... + +global___WorkflowActivityProducer = WorkflowActivityProducer + +@typing.final +class StandaloneActivityProducer(google.protobuf.message.Message): + """Experimental. Might change in the future. + Standalone Activity attempts use the same order as Workflow Activity attempts. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAMESPACE_FIELD_NUMBER: builtins.int + ACTIVITY_ID_FIELD_NUMBER: builtins.int + RUN_ID_FIELD_NUMBER: builtins.int + ATTEMPT_FIELD_NUMBER: builtins.int + namespace: builtins.str + """Required.""" + activity_id: builtins.str + """Required.""" + run_id: builtins.str + """Required. The run id of the Activity itself.""" + @property + def attempt(self) -> global___ActivityAttempt: + """Required.""" + + def __init__( + self, + *, + namespace: builtins.str = ..., + activity_id: builtins.str = ..., + run_id: builtins.str = ..., + attempt: global___ActivityAttempt | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["attempt", b"attempt"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "activity_id", + b"activity_id", + "attempt", + b"attempt", + "namespace", + b"namespace", + "run_id", + b"run_id", + ], + ) -> None: ... + +global___StandaloneActivityProducer = StandaloneActivityProducer + +@typing.final +class ClientProducer(google.protobuf.message.Message): + """Experimental. Might change in the future. + Clients have no attempt, so their writes cannot be fenced or superseded by a later attempt. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAMESPACE_FIELD_NUMBER: builtins.int + ID_FIELD_NUMBER: builtins.int + namespace: builtins.str + """Required.""" + id: builtins.str + """Required. The SDK generates an id per client object unless the caller supplies one.""" + def __init__( + self, + *, + namespace: builtins.str = ..., + id: builtins.str = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["id", b"id", "namespace", b"namespace"] + ) -> None: ... + +global___ClientProducer = ClientProducer + +@typing.final +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. + 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. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + WORKFLOW_FIELD_NUMBER: builtins.int + LOCAL_ACTIVITY_FIELD_NUMBER: builtins.int + WORKFLOW_ACTIVITY_FIELD_NUMBER: builtins.int + STANDALONE_ACTIVITY_FIELD_NUMBER: builtins.int + CLIENT_FIELD_NUMBER: builtins.int + @property + def workflow(self) -> global___WorkflowProducer: ... + @property + def local_activity(self) -> global___LocalActivityProducer: ... + @property + def workflow_activity(self) -> global___WorkflowActivityProducer: ... + @property + def standalone_activity(self) -> global___StandaloneActivityProducer: ... + @property + def client(self) -> global___ClientProducer: ... + def __init__( + self, + *, + workflow: global___WorkflowProducer | None = ..., + local_activity: global___LocalActivityProducer | None = ..., + workflow_activity: global___WorkflowActivityProducer | None = ..., + standalone_activity: global___StandaloneActivityProducer | None = ..., + client: global___ClientProducer | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "client", + b"client", + "kind", + b"kind", + "local_activity", + b"local_activity", + "standalone_activity", + b"standalone_activity", + "workflow", + b"workflow", + "workflow_activity", + b"workflow_activity", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "client", + b"client", + "kind", + b"kind", + "local_activity", + b"local_activity", + "standalone_activity", + b"standalone_activity", + "workflow", + b"workflow", + "workflow_activity", + b"workflow_activity", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["kind", b"kind"] + ) -> ( + typing.Literal[ + "workflow", + "local_activity", + "workflow_activity", + "standalone_activity", + "client", + ] + | None + ): ... + +global___Producer = Producer + +@typing.final +class AppendRecord(google.protobuf.message.Message): + """Experimental. Might change in the future. + The Store adds the batch Producer and assigns an offset. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + BODY_FIELD_NUMBER: builtins.int + @property + def body(self) -> temporalio.api.common.v1.message_pb2.Payload: + """Required.""" + + def __init__( + self, + *, + body: temporalio.api.common.v1.message_pb2.Payload | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["body", b"body"] + ) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["body", b"body"]) -> None: ... + +global___AppendRecord = AppendRecord + +@typing.final +class StreamRecord(google.protobuf.message.Message): + """Experimental. Might change in the future.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PRODUCER_FIELD_NUMBER: builtins.int + BODY_FIELD_NUMBER: builtins.int + OFFSET_FIELD_NUMBER: builtins.int + offset: builtins.bytes + """Required. Record offsets are 1 to 1,024 bytes and unique within a Stream. Unsigned byte order + matches Record order. Offsets can have gaps and do not identify the Stream. + """ + @property + def producer(self) -> global___Producer: + """Stores must return the Producer that appended this Record.""" + + @property + def body(self) -> temporalio.api.common.v1.message_pb2.Payload: ... + def __init__( + self, + *, + producer: global___Producer | None = ..., + body: temporalio.api.common.v1.message_pb2.Payload | None = ..., + offset: builtins.bytes = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["body", b"body", "producer", b"producer"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "body", b"body", "offset", b"offset", "producer", b"producer" + ], + ) -> None: ... + +global___StreamRecord = StreamRecord + +@typing.final +class StreamErrorDetails(google.protobuf.message.Message): + """Experimental. Might change in the future. + Returned in gRPC status details or Nexus application failure details. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REASON_FIELD_NUMBER: builtins.int + reason: temporalio.api.enums.v1.stream_pb2.StreamErrorReason.ValueType + def __init__( + self, + *, + reason: temporalio.api.enums.v1.stream_pb2.StreamErrorReason.ValueType = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["reason", b"reason"]) -> None: ... + +global___StreamErrorDetails = StreamErrorDetails diff --git a/temporalio/api/streamservice/__init__.py b/temporalio/api/streamservice/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/temporalio/api/streamservice/v1/__init__.py b/temporalio/api/streamservice/v1/__init__.py new file mode 100644 index 0000000000..a232488de4 --- /dev/null +++ b/temporalio/api/streamservice/v1/__init__.py @@ -0,0 +1,21 @@ +from .request_response_pb2 import ( + AppendRecordsRequest, + AppendRecordsResponse, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) + +__all__ = [ + "AppendRecordsRequest", + "AppendRecordsResponse", + "CreateStreamRequest", + "CreateStreamResponse", + "DescribeStreamRequest", + "DescribeStreamResponse", + "ReadRecordsRequest", + "ReadRecordsResponse", +] diff --git a/temporalio/api/streamservice/v1/request_response_pb2.py b/temporalio/api/streamservice/v1/request_response_pb2.py new file mode 100644 index 0000000000..0b54c5bb5d --- /dev/null +++ b/temporalio/api/streamservice/v1/request_response_pb2.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: temporal/api/streamservice/v1/request_response.proto +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 + +from temporalio.api.enums.v1 import ( + stream_pb2 as temporal_dot_api_dot_enums_dot_v1_dot_stream__pb2, +) +from temporalio.api.stream.v1 import ( + message_pb2 as temporal_dot_api_dot_stream_dot_v1_dot_message__pb2, +) + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n4temporal/api/streamservice/v1/request_response.proto\x12\x1dtemporal.api.streamservice.v1\x1a\x1egoogle/protobuf/duration.proto\x1a"temporal/api/enums/v1/stream.proto\x1a$temporal/api/stream/v1/message.proto"s\n\x13\x43reateStreamRequest\x12\x11\n\tstream_id\x18\x01 \x01(\t\x12I\n\x12id_conflict_policy\x18\x02 \x01(\x0e\x32-.temporal.api.enums.v1.StreamIdConflictPolicy"\'\n\x14\x43reateStreamResponse\x12\x0f\n\x07\x63reated\x18\x01 \x01(\x08"\x94\x01\n\x14\x41ppendRecordsRequest\x12\x11\n\tstream_id\x18\x01 \x01(\t\x12\x32\n\x08producer\x18\x02 \x01(\x0b\x32 .temporal.api.stream.v1.Producer\x12\x35\n\x07records\x18\x03 \x03(\x0b\x32$.temporal.api.stream.v1.AppendRecord"B\n\x15\x41ppendRecordsResponse\x12\x14\n\x0c\x66irst_offset\x18\x01 \x01(\x0c\x12\x13\n\x0blast_offset\x18\x02 \x01(\x0c"\x8d\x01\n\x12ReadRecordsRequest\x12\x11\n\tstream_id\x18\x01 \x01(\t\x12\x13\n\x0b\x66rom_offset\x18\x02 \x01(\x0c\x12\x13\n\x0bmax_records\x18\x03 \x01(\x05\x12\x11\n\tmax_bytes\x18\x04 \x01(\x03\x12\'\n\x04wait\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration"a\n\x13ReadRecordsResponse\x12\x35\n\x07records\x18\x01 \x03(\x0b\x32$.temporal.api.stream.v1.StreamRecord\x12\x13\n\x0blast_offset\x18\x02 \x01(\x0c"*\n\x15\x44\x65scribeStreamRequest\x12\x11\n\tstream_id\x18\x01 \x01(\t"-\n\x16\x44\x65scribeStreamResponse\x12\x13\n\x0blast_offset\x18\x01 \x01(\x0c\x42\xb4\x01\n io.temporal.api.streamservice.v1B\x14RequestResponseProtoP\x01Z1go.temporal.io/api/streamservice/v1;streamservice\xaa\x02\x1fTemporalio.Api.StreamService.V1\xea\x02"Temporalio::Api::StreamService::V1b\x06proto3' +) + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, __name__, globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n io.temporal.api.streamservice.v1B\024RequestResponseProtoP\001Z1go.temporal.io/api/streamservice/v1;streamservice\252\002\037Temporalio.Api.StreamService.V1\352\002"Temporalio::Api::StreamService::V1' + _CREATESTREAMREQUEST._serialized_start = 193 + _CREATESTREAMREQUEST._serialized_end = 308 + _CREATESTREAMRESPONSE._serialized_start = 310 + _CREATESTREAMRESPONSE._serialized_end = 349 + _APPENDRECORDSREQUEST._serialized_start = 352 + _APPENDRECORDSREQUEST._serialized_end = 500 + _APPENDRECORDSRESPONSE._serialized_start = 502 + _APPENDRECORDSRESPONSE._serialized_end = 568 + _READRECORDSREQUEST._serialized_start = 571 + _READRECORDSREQUEST._serialized_end = 712 + _READRECORDSRESPONSE._serialized_start = 714 + _READRECORDSRESPONSE._serialized_end = 811 + _DESCRIBESTREAMREQUEST._serialized_start = 813 + _DESCRIBESTREAMREQUEST._serialized_end = 855 + _DESCRIBESTREAMRESPONSE._serialized_start = 857 + _DESCRIBESTREAMRESPONSE._serialized_end = 902 +# @@protoc_insertion_point(module_scope) diff --git a/temporalio/api/streamservice/v1/request_response_pb2.pyi b/temporalio/api/streamservice/v1/request_response_pb2.pyi new file mode 100644 index 0000000000..123c5607a3 --- /dev/null +++ b/temporalio/api/streamservice/v1/request_response_pb2.pyi @@ -0,0 +1,299 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +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 temporalio.api.enums.v1.stream_pb2 +import temporalio.api.stream.v1.message_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class CreateStreamRequest(google.protobuf.message.Message): + """Experimental. Might change in the future. + `FAIL` returns `ALREADY_EXISTS` for an existing Stream. `USE_EXISTING` returns `created` false. + 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. + (-- api-linter: core::0133=disabled + aip.dev/not-precedent: The request identifies a Stream by its id. --) + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + STREAM_ID_FIELD_NUMBER: builtins.int + ID_CONFLICT_POLICY_FIELD_NUMBER: builtins.int + stream_id: builtins.str + """Required. The id of the Stream to create. It must not be empty.""" + id_conflict_policy: ( + temporalio.api.enums.v1.stream_pb2.StreamIdConflictPolicy.ValueType + ) + """What the create does if the Stream already exists. Unspecified means `FAIL`.""" + def __init__( + self, + *, + stream_id: builtins.str = ..., + id_conflict_policy: temporalio.api.enums.v1.stream_pb2.StreamIdConflictPolicy.ValueType = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "id_conflict_policy", b"id_conflict_policy", "stream_id", b"stream_id" + ], + ) -> None: ... + +global___CreateStreamRequest = CreateStreamRequest + +@typing.final +class CreateStreamResponse(google.protobuf.message.Message): + """Experimental. Might change in the future.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CREATED_FIELD_NUMBER: builtins.int + created: builtins.bool + """False when `USE_EXISTING` found a Stream that already existed.""" + def __init__( + self, + *, + created: builtins.bool = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["created", b"created"]) -> None: ... + +global___CreateStreamResponse = CreateStreamResponse + +@typing.final +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 + Producer. An empty or forgotten request id permits a second write. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + STREAM_ID_FIELD_NUMBER: builtins.int + PRODUCER_FIELD_NUMBER: builtins.int + RECORDS_FIELD_NUMBER: builtins.int + stream_id: builtins.str + """Required.""" + @property + def producer(self) -> temporalio.api.stream.v1.message_pb2.Producer: + """Required. The Producer that writes the batch.""" + + @property + def records( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + temporalio.api.stream.v1.message_pb2.AppendRecord + ]: + """Required. A batch has at least one Record.""" + + def __init__( + self, + *, + stream_id: builtins.str = ..., + producer: temporalio.api.stream.v1.message_pb2.Producer | None = ..., + records: collections.abc.Iterable[ + temporalio.api.stream.v1.message_pb2.AppendRecord + ] + | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["producer", b"producer"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "producer", b"producer", "records", b"records", "stream_id", b"stream_id" + ], + ) -> None: ... + +global___AppendRecordsRequest = AppendRecordsRequest + +@typing.final +class AppendRecordsResponse(google.protobuf.message.Message): + """Experimental. Might change in the future. + The offsets of the first and the last Record of the batch. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FIRST_OFFSET_FIELD_NUMBER: builtins.int + LAST_OFFSET_FIELD_NUMBER: builtins.int + first_offset: builtins.bytes + """Required and nonempty.""" + last_offset: builtins.bytes + """Required and nonempty.""" + 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___AppendRecordsResponse = AppendRecordsResponse + +@typing.final +class ReadRecordsRequest(google.protobuf.message.Message): + """Experimental. Might change in the future. + Reads after an offset. When no Record is available, `wait` controls how long the read waits. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + STREAM_ID_FIELD_NUMBER: builtins.int + FROM_OFFSET_FIELD_NUMBER: builtins.int + MAX_RECORDS_FIELD_NUMBER: builtins.int + MAX_BYTES_FIELD_NUMBER: builtins.int + WAIT_FIELD_NUMBER: builtins.int + stream_id: builtins.str + """Required.""" + from_offset: builtins.bytes + """The read returns the Records after this offset. Empty means from the beginning. An offset + past the newest one fails with `OFFSET_TOO_HIGH`. To read only new Records, a caller gets + `last_offset` from a describe and reads after it. + (-- api-linter: core::0140::prepositions=disabled + aip.dev/not-precedent: "from" marks the start of a range of offsets. --) + """ + max_records: builtins.int + """The maximum number of Records in one page. Zero uses the Store default.""" + max_bytes: builtins.int + """The target size of a page in bytes. A larger Record is returned alone so the read can + advance. Zero uses the Store default. + """ + @property + def wait(self) -> google.protobuf.duration_pb2.Duration: + """How long the read waits for a new Record before it returns an empty page. When it's unset, + the read returns immediately. + """ + + def __init__( + self, + *, + stream_id: builtins.str = ..., + from_offset: builtins.bytes = ..., + max_records: builtins.int = ..., + max_bytes: builtins.int = ..., + wait: google.protobuf.duration_pb2.Duration | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["wait", b"wait"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "from_offset", + b"from_offset", + "max_bytes", + b"max_bytes", + "max_records", + b"max_records", + "stream_id", + b"stream_id", + "wait", + b"wait", + ], + ) -> None: ... + +global___ReadRecordsRequest = ReadRecordsRequest + +@typing.final +class ReadRecordsResponse(google.protobuf.message.Message): + """Experimental. Might change in the future.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RECORDS_FIELD_NUMBER: builtins.int + LAST_OFFSET_FIELD_NUMBER: builtins.int + last_offset: builtins.bytes + """The last position that the read covered. The next read passes it as `from_offset`. A Store + doesn't have to set it. If it's empty, that position is the offset of the last Record in + this page, or the `from_offset` of the request for an empty page. A Store can set a later + offset that skips only entries of its own that aren't Records, so the next read doesn't + scan them again. + """ + @property + def records( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + temporalio.api.stream.v1.message_pb2.StreamRecord + ]: ... + def __init__( + self, + *, + records: collections.abc.Iterable[ + temporalio.api.stream.v1.message_pb2.StreamRecord + ] + | None = ..., + last_offset: builtins.bytes = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "last_offset", b"last_offset", "records", b"records" + ], + ) -> None: ... + +global___ReadRecordsResponse = ReadRecordsResponse + +@typing.final +class DescribeStreamRequest(google.protobuf.message.Message): + """Experimental. Might change in the future.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + STREAM_ID_FIELD_NUMBER: builtins.int + stream_id: builtins.str + """Required.""" + def __init__( + self, + *, + stream_id: builtins.str = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["stream_id", b"stream_id"] + ) -> None: ... + +global___DescribeStreamRequest = DescribeStreamRequest + +@typing.final +class DescribeStreamResponse(google.protobuf.message.Message): + """Experimental. Might change in the future. + Retention is a Store setting and is not returned here. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LAST_OFFSET_FIELD_NUMBER: builtins.int + last_offset: builtins.bytes + """The offset of the newest Record, or an offset after it that skips no Record. A read from it + returns only the Records that come later. It's empty when the Stream has no Record. + """ + def __init__( + self, + *, + last_offset: builtins.bytes = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["last_offset", b"last_offset"] + ) -> None: ... + +global___DescribeStreamResponse = DescribeStreamResponse diff --git a/temporalio/api/streamservice/v1/request_response_pb2_grpc.py b/temporalio/api/streamservice/v1/request_response_pb2_grpc.py new file mode 100644 index 0000000000..bf947056a2 --- /dev/null +++ b/temporalio/api/streamservice/v1/request_response_pb2_grpc.py @@ -0,0 +1,4 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" + +import grpc diff --git a/temporalio/api/streamservice/v1/request_response_pb2_grpc.pyi b/temporalio/api/streamservice/v1/request_response_pb2_grpc.pyi new file mode 100644 index 0000000000..de236ac811 --- /dev/null +++ b/temporalio/api/streamservice/v1/request_response_pb2_grpc.pyi @@ -0,0 +1,21 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import abc +import collections.abc +import typing + +import grpc +import grpc.aio + +_T = typing.TypeVar("_T") + +class _MaybeAsyncIterator( + collections.abc.AsyncIterator[_T], + collections.abc.Iterator[_T], + metaclass=abc.ABCMeta, +): ... +class _ServicerContext(grpc.ServicerContext, grpc.aio.ServicerContext): # type: ignore[misc, type-arg] + ... diff --git a/temporalio/bridge/Cargo.lock b/temporalio/bridge/Cargo.lock index 1aaae8a89d..d0304f3887 100644 --- a/temporalio/bridge/Cargo.lock +++ b/temporalio/bridge/Cargo.lock @@ -227,9 +227,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.11.3" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" dependencies = [ "find-msvc-tools", "jobserver", @@ -311,9 +311,9 @@ dependencies = [ [[package]] name = "constant_time_eq" -version = "0.6.1" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" +checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7" dependencies = [ "rustversion", ] @@ -566,9 +566,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.15" +version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" [[package]] name = "fixedbitset" @@ -1339,6 +1339,29 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" +[[package]] +name = "nexus-rpc" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6bd72bb0b8a558f1ad4e6502a47d6db0c07b93902a11d7f806f8791b6b14f7b" +dependencies = [ + "nexus-rpc-macros", + "serde", + "thiserror", +] + +[[package]] +name = "nexus-rpc-macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be6dc5d7783ce0428a2baf74d82bd816f8e9fb30543ff07a9e0e0556e6839dd9" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "nix" version = "0.32.0" @@ -1683,6 +1706,15 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -2686,6 +2718,7 @@ dependencies = [ "derive_more", "erased-serde", "futures", + "nexus-rpc", "parking_lot", "prost", "prost-wkt-types", @@ -2716,6 +2749,7 @@ dependencies = [ "http", "pbjson", "pbjson-build", + "percent-encoding", "prost", "prost-wkt-types", "serde", @@ -2891,9 +2925,9 @@ dependencies = [ [[package]] name = "toml" -version = "1.2.2+spec-1.1.0" +version = "1.2.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5426cb1b964690d913f6c5c1a1ae0b42f428ec506bb4d452876d7a209c9bca3b" +checksum = "26b1f26e9485c1fa43ee89fe76e9f3fb9e2e52bb227f8594b4d687496b83d073" dependencies = [ "indexmap", "serde_core", @@ -2913,11 +2947,23 @@ dependencies = [ "serde_core", ] +[[package]] +name = "toml_edit" +version = "0.25.21+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88497dab46de5bf343ec66b05c251e48c6213f3e9170c70a70a823f7abe886a4" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + [[package]] name = "toml_parser" -version = "1.1.6+spec-1.1.0" +version = "1.1.7+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31" +checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" dependencies = [ "winnow", ] @@ -3607,6 +3653,9 @@ name = "winnow" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] [[package]] name = "wit-bindgen" @@ -3655,18 +3704,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.65" +version = "0.8.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32bc8a75f879cd6fe53a6bedf3c28f0e1b914c77424fc2be9e2ec85d7d25aff5" +checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.65" +version = "0.8.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8bfd2644ea1681f60cf95029ff18aa8ad1cc3f7b8fe37286f8e473bb29f816b" +checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" dependencies = [ "proc-macro2", "quote", @@ -3749,9 +3798,9 @@ dependencies = [ [[package]] name = "zip" -version = "9.8.2" +version = "9.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce" +checksum = "07db37dec4a7c468df4723fba4cadb4822d1d0f10dbea367100b6a6881b2a9c9" dependencies = [ "bzip2", "constant_time_eq", diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index 0bf830696a..cc22dcdeef 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit 0bf830696a9952bd56629983b8dda373503d4bc3 +Subproject commit cc22dcdeef9349365e2bd8be4215761db4ffb3c9 diff --git a/temporalio/client/_client.py b/temporalio/client/_client.py index efef5cb528..18c9d27a58 100644 --- a/temporalio/client/_client.py +++ b/temporalio/client/_client.py @@ -2,6 +2,7 @@ from __future__ import annotations +import uuid from collections.abc import ( Awaitable, Callable, @@ -291,6 +292,7 @@ def __init__( header_codec_behavior=header_codec_behavior, ) self._initial_config = config.copy() + self._stream_producer_id = str(uuid.uuid4()) for plugin in plugins: config = plugin.configure_client(config) diff --git a/temporalio/nexus/notifications/__init__.py b/temporalio/nexus/notifications/__init__.py index 8904171e02..29fc72fbea 100644 --- a/temporalio/nexus/notifications/__init__.py +++ b/temporalio/nexus/notifications/__init__.py @@ -1,4 +1,4 @@ -# Generated by nexgen v0.2.13. DO NOT EDIT! +# Generated by nexgen v0.2.14. DO NOT EDIT! from __future__ import annotations diff --git a/temporalio/nexus/notifications/models.py b/temporalio/nexus/notifications/models.py index 0eb97fae21..ffa44ba82a 100644 --- a/temporalio/nexus/notifications/models.py +++ b/temporalio/nexus/notifications/models.py @@ -1,4 +1,4 @@ -# Generated by nexgen v0.2.13. DO NOT EDIT! +# Generated by nexgen v0.2.14. DO NOT EDIT! from __future__ import annotations diff --git a/temporalio/nexus/system/__init__.py b/temporalio/nexus/system/__init__.py index 1f8f7c6d29..da102bd304 100644 --- a/temporalio/nexus/system/__init__.py +++ b/temporalio/nexus/system/__init__.py @@ -194,3 +194,7 @@ def _get_serialization_context( # pyright: ignore[reportUnusedFunction] "TEMPORAL_SYSTEM_ENDPOINT", "is_system_endpoint", ] + +# `temporalio.workflow` and the generated Workflow modules of a system service import each +# other. It's loaded here last, so that any of those modules can be the first import. +import temporalio.workflow # noqa: E402 # pyright: ignore[reportUnusedImport] diff --git a/temporalio/nexus/system/_support.py b/temporalio/nexus/system/_support.py index 1ff5f64c52..9f4cd52d5b 100644 --- a/temporalio/nexus/system/_support.py +++ b/temporalio/nexus/system/_support.py @@ -1,8 +1,11 @@ import collections.abc +import dataclasses import typing -from datetime import timedelta +from datetime import datetime, timedelta import google.protobuf.duration_pb2 +import google.protobuf.message +import google.protobuf.timestamp_pb2 import temporalio.api.common.v1.message_pb2 as common_pb2 import temporalio.api.enums.v1.workflow_pb2 as workflow_enums_pb2 @@ -12,6 +15,29 @@ import temporalio.common import temporalio.converter import temporalio.nexus.system +from temporalio._workflow_context import _current_workflow_flags, _WorkflowLogicFlag +from temporalio.converter._payload_converter import _get_transfer_type_converter + +if typing.TYPE_CHECKING: + import temporalio.activity + import temporalio.client + from temporalio.client import NexusClient as ClientNexusClient + from temporalio.nexus.system.stream_service.client import Stream as ClientStream + from temporalio.nexus.system.stream_service.models import ( + CreateStreamResult, + Producer, + ReadRecordsRequest, + ReadRecordsResponse, + StreamRecord, + Timestamp, + ) + from temporalio.nexus.system.stream_service.workflow._resources import ( + Stream as WorkflowStream, + ) + from temporalio.workflow import NexusClient as WorkflowNexusClient + +_BodyT = typing.TypeVar("_BodyT") +_ModelT = typing.TypeVar("_ModelT") class SignalWithStartWorkflowModelRequest(typing.Protocol): @@ -19,6 +45,229 @@ class SignalWithStartWorkflowModelRequest(typing.Protocol): id: str +def model_to_proto( + model: object, + payload_converter: temporalio.converter.PayloadConverter, + failure_converter: temporalio.converter.FailureConverter, +) -> google.protobuf.message.Message: + """Convert a system Nexus model to its proto message, with no payload in between.""" + converter = _get_transfer_type_converter(type(model)) + if converter is None: + raise TypeError(f"{type(model).__name__} is not a system Nexus model") + with temporalio.nexus.system._user_converter_context( + temporalio.nexus.system._SystemNexusUserConverters( + payload_converter, failure_converter + ) + ): + return converter.to_transfer_type(model) + + +def model_from_proto( + proto: google.protobuf.message.Message, + model_type: type[_ModelT], + payload_converter: temporalio.converter.PayloadConverter, + failure_converter: temporalio.converter.FailureConverter, +) -> _ModelT: + """Convert a proto message to the system Nexus model of ``model_type``.""" + converter = _get_transfer_type_converter(model_type) + if converter is None: + raise TypeError(f"{model_type} is not a system Nexus model") + with temporalio.nexus.system._user_converter_context( + temporalio.nexus.system._SystemNexusUserConverters( + payload_converter, failure_converter + ) + ): + return converter.from_transfer_type(proto, model_type) + + +@typing.overload +def stream_from_create( + result: "CreateStreamResult[_BodyT]", + nexus_client: "ClientNexusClient[typing.Any]", + body_type: type[_BodyT], +) -> "ClientStream[_BodyT]": ... + + +@typing.overload +def stream_from_create( + result: "CreateStreamResult[_BodyT]", + nexus_client: "WorkflowNexusClient[typing.Any]", + body_type: type[_BodyT], +) -> "WorkflowStream[_BodyT]": ... + + +def stream_from_create( + result: "CreateStreamResult[_BodyT]", + nexus_client: "ClientNexusClient[typing.Any] | WorkflowNexusClient[typing.Any]", + body_type: type[_BodyT], +) -> "ClientStream[_BodyT] | WorkflowStream[_BodyT]": + import temporalio.workflow + + if result.ref is None: + raise RuntimeError("CreateStream answered without `ref`") + created: bool | None = bool(result.created) + if isinstance(nexus_client, temporalio.workflow.NexusClient): + from temporalio.nexus.system.stream_service.workflow._resources import ( + Stream as WorkflowStream, + ) + + if not created: + flags = _current_workflow_flags.get() + # Unflagged replay must retain None, including responses from interceptors. + if flags is not None and not flags.is_flag_enabled( + _WorkflowLogicFlag.REPORT_EXISTING_STREAM_AS_FALSE + ): + created = None + return WorkflowStream[body_type]( # type: ignore[valid-type, reportInvalidTypeForm] + ref=result.ref, created=created + ) + + from temporalio.nexus.system.stream_service.client import Stream as ClientStream + + return ClientStream[body_type]( # type: ignore[valid-type, reportInvalidTypeForm] + nexus_client, ref=result.ref, created=created + ) + + +def default_producer( + nexus_client: "temporalio.client.NexusClient[typing.Any]", +) -> "Producer": + """Return the Producer of a write of Activity or client code.""" + import temporalio.activity + from temporalio.nexus.system.stream_service import models + + if temporalio.activity.in_activity(): + return activity_producer(temporalio.activity.info()) + client: temporalio.client.Client = nexus_client._client # type: ignore[attr-defined] + return models.Producer( + kind=models.ProducerKindClient( + models.ClientProducer( + namespace=client.namespace, id=client._stream_producer_id + ) + ) + ) + + +def workflow_producer() -> "Producer": + """Return the Producer of the Workflow run. It has no attempt, which Core sets.""" + from temporalio.nexus.system.stream_service import models + from temporalio.workflow import info + + return models.Producer( + kind=models.ProducerKindWorkflow( + models.WorkflowProducer( + namespace=info().namespace, + workflow_id=info().workflow_id, + run_id=info().run_id, + ) + ) + ) + + +def activity_producer(info: "temporalio.activity.Info") -> "Producer": + """Return the Producer of an attempt of an Activity, of the kind of the Activity.""" + from temporalio.nexus.system.stream_service import models + + workflow_id, run_id = info.workflow_id or "", info.workflow_run_id or "" + if info.is_local: + task = info.workflow_task + if task is None: + raise RuntimeError( + "Local Activity has no Workflow Task, which its Producer requires" + ) + local_attempt = models.LocalActivityAttempt( + task=models.WorkflowTaskAttempt( + started_event_id=task.started_event_id, + attempt=task.attempt, + started_time=_timestamp(task.started_time) + if task.started_time + else None, + ), + attempt=info.attempt, + ) + return models.Producer( + kind=models.ProducerKindLocalActivity( + models.LocalActivityProducer( + namespace=info.namespace, + workflow_id=workflow_id, + run_id=run_id, + activity_id=info.activity_id, + attempt=local_attempt, + ) + ) + ) + attempt = models.ActivityAttempt( + attempt_scheduled_time=_timestamp(info.current_attempt_scheduled_time), + attempt=info.attempt, + ) + if run_id: + # Zero is a task whose scheduled event Core couldn't read. + scheduled_event_id = info._scheduled_event_id or None # pyright: ignore[reportPrivateUsage] + return models.Producer( + kind=models.ProducerKindWorkflowActivity( + models.WorkflowActivityProducer( + namespace=info.namespace, + workflow_id=workflow_id, + run_id=run_id, + activity_id=info.activity_id, + scheduled_event_id=scheduled_event_id, + attempt=attempt, + ) + ) + ) + if not info.activity_run_id: + raise RuntimeError( + "Standalone Activity has no run id, which its Producer requires" + ) + return models.Producer( + kind=models.ProducerKindStandaloneActivity( + models.StandaloneActivityProducer( + namespace=info.namespace, + activity_id=info.activity_id, + run_id=info.activity_run_id, + attempt=attempt, + ) + ) + ) + + +def _timestamp(time: datetime) -> "Timestamp": + from temporalio.nexus.system.stream_service import models + + proto = google.protobuf.timestamp_pb2.Timestamp() + proto.FromDatetime(time) + return models.Timestamp(seconds=proto.seconds, nanos=proto.nanos) + + +DEFAULT_READ_WAIT = timedelta(minutes=1) +"""Default wait after the first page of ``read`` and ``read_pages``.""" + + +def next_read_request( + request: "ReadRecordsRequest[_BodyT]", response: "ReadRecordsResponse[_BodyT]" +) -> "ReadRecordsRequest[_BodyT] | None": + cursor = response.last_offset or request.from_offset + if not response.last_offset and response.records: + # An unflagged replay must issue its next read at the recorded request cursor. + flags = _current_workflow_flags.get() + if flags is None or flags.is_flag_enabled( + _WorkflowLogicFlag.USE_LAST_STREAM_RECORD_OFFSET + ): + cursor = response.records[-1].offset + # Empty pages don't end a Stream. The default wait avoids busy polling. + return dataclasses.replace( + request, + from_offset=cursor, + wait=DEFAULT_READ_WAIT if request.wait is None else request.wait, + ) + + +def resume_read_request( + request: "ReadRecordsRequest[_BodyT]", item: "StreamRecord[_BodyT]" +) -> "ReadRecordsRequest[_BodyT]": + return dataclasses.replace(request, from_offset=item.offset) + + def retry_policy_from_proto( proto: common_pb2.RetryPolicy, ) -> temporalio.common.RetryPolicy: diff --git a/temporalio/nexus/system/stream_service/__init__.py b/temporalio/nexus/system/stream_service/__init__.py new file mode 100644 index 0000000000..f3df0b0fb4 --- /dev/null +++ b/temporalio/nexus/system/stream_service/__init__.py @@ -0,0 +1,67 @@ +# Generated by nexgen v0.2.14. DO NOT EDIT! + +from __future__ import annotations + +from .models import ( + ActivityAttempt, + AppendRecord, + AppendRecordsRequest, + AppendRecordsResponse, + ClientProducer, + CreateStreamRequest, + CreateStreamResult, + DescribeStreamRequest, + DescribeStreamResponse, + LocalActivityAttempt, + LocalActivityProducer, + Producer, + ProducerKind, + ProducerKindClient, + ProducerKindLocalActivity, + ProducerKindStandaloneActivity, + ProducerKindWorkflow, + ProducerKindWorkflowActivity, + ReadRecordsRequest, + ReadRecordsResponse, + StandaloneActivityProducer, + StreamIdConflictPolicy, + StreamRecord, + StreamRef, + Timestamp, + WorkflowActivityProducer, + WorkflowProducer, + WorkflowTaskAttempt, +) +from .services import StreamService + +__all__ = [ + "ActivityAttempt", + "AppendRecord", + "AppendRecordsRequest", + "AppendRecordsResponse", + "ClientProducer", + "CreateStreamRequest", + "CreateStreamResult", + "DescribeStreamRequest", + "DescribeStreamResponse", + "LocalActivityAttempt", + "LocalActivityProducer", + "Producer", + "ProducerKind", + "ProducerKindWorkflow", + "ProducerKindLocalActivity", + "ProducerKindWorkflowActivity", + "ProducerKindStandaloneActivity", + "ProducerKindClient", + "ReadRecordsRequest", + "ReadRecordsResponse", + "StandaloneActivityProducer", + "StreamIdConflictPolicy", + "StreamRecord", + "StreamRef", + "Timestamp", + "WorkflowActivityProducer", + "WorkflowProducer", + "WorkflowTaskAttempt", + "StreamService", +] diff --git a/temporalio/nexus/system/stream_service/_poll.py b/temporalio/nexus/system/stream_service/_poll.py new file mode 100644 index 0000000000..0e37001d0f --- /dev/null +++ b/temporalio/nexus/system/stream_service/_poll.py @@ -0,0 +1,77 @@ +# Generated by nexgen v0.2.14. DO NOT EDIT! + +from __future__ import annotations + +import collections +import collections.abc +import typing + +_PollRequestT = typing.TypeVar("_PollRequestT") +_PollResponseT = typing.TypeVar("_PollResponseT") +_PollItemT = typing.TypeVar("_PollItemT") + + +@typing.final +class PollIterator(typing.Generic[_PollRequestT, _PollItemT]): + """Yields each item of the pages of a poll. + + ``next_request`` is the request to resume with. After an item, the resume helper gives + it. Without a resume helper, it reads the item's page again. After a page's last item, + it is the page helper's request. It is ``None`` when the page helper returns ``None``. + """ + + def __init__( + self, + request: _PollRequestT, + pages: collections.abc.AsyncIterator[_PollResponseT], + items: collections.abc.Callable[ + [_PollResponseT], collections.abc.Sequence[_PollItemT] | None + ], + next_page: collections.abc.Callable[ + [_PollRequestT, _PollResponseT], _PollRequestT | None + ], + resume: collections.abc.Callable[[_PollRequestT, _PollItemT], _PollRequestT] + | None, + ) -> None: + async def read( + page_request: _PollRequestT, + ) -> tuple[_PollRequestT | None, collections.deque[_PollItemT]]: + response = await anext(pages) + # The page iterator keeps its requests to itself, so the page helper runs here + # again. It runs before the caller gets an item, so a changed item can't change + # the next request. + return next_page(page_request, response), collections.deque( + items(response) or () + ) + + self.next_request: _PollRequestT | None = request + self._read: collections.abc.Callable[ + [_PollRequestT], + collections.abc.Awaitable[ + tuple[_PollRequestT | None, collections.deque[_PollItemT]] + ], + ] = read + self._resume: ( + collections.abc.Callable[[_PollRequestT, _PollItemT], _PollRequestT] | None + ) = resume + self._page: collections.deque[_PollItemT] = collections.deque() + self._page_request: _PollRequestT = request + self._page_next: _PollRequestT | None = None + + def __aiter__(self) -> PollIterator[_PollRequestT, _PollItemT]: + return self + + async def __anext__(self) -> _PollItemT: + while not self._page: + if self.next_request is None: + raise StopAsyncIteration + self._page_request = self.next_request + self._page_next, self._page = await self._read(self._page_request) + if not self._page: + self.next_request = self._page_next + item = self._page.popleft() + if not self._page: + self.next_request = self._page_next + elif self._resume is not None: + self.next_request = self._resume(self._page_request, item) + return item diff --git a/temporalio/nexus/system/stream_service/client/__init__.py b/temporalio/nexus/system/stream_service/client/__init__.py new file mode 100644 index 0000000000..4d358ab45a --- /dev/null +++ b/temporalio/nexus/system/stream_service/client/__init__.py @@ -0,0 +1,11 @@ +# Generated by nexgen v0.2.14. DO NOT EDIT! + +from __future__ import annotations + +from ._extensions import StreamServiceClientExtension +from ._resources.stream import Stream + +__all__ = [ + "StreamServiceClientExtension", + "Stream", +] diff --git a/temporalio/nexus/system/stream_service/client/_extensions.py b/temporalio/nexus/system/stream_service/client/_extensions.py new file mode 100644 index 0000000000..b9eb96d9ee --- /dev/null +++ b/temporalio/nexus/system/stream_service/client/_extensions.py @@ -0,0 +1,168 @@ +# Generated by nexgen v0.2.14. DO NOT EDIT! + +from __future__ import annotations + +import abc +import collections.abc +import datetime +import typing +import uuid as _uuid + +import temporalio.nexus.system + +if typing.TYPE_CHECKING: + import temporalio.client + +import temporalio.nexus.system._support as _support + +from ..models import ( + CreateStreamRequest, + CreateStreamResult, + StreamIdConflictPolicy, + StreamRef, +) +from ..services import StreamService +from ._resources.stream import Stream + +_NexusServiceT = typing.TypeVar("_NexusServiceT") +BodyT = typing.TypeVar("BodyT") + + +class StreamServiceClientExtension(abc.ABC): + """Starts the operations of ``StreamService`` from code outside a Workflow. + + A client class inherits this class and provides the SDK's ``create_nexus_client`` + method. + + .. warning:: + This API is experimental and subject to change. + """ + + @abc.abstractmethod + def create_nexus_client( + self, + service: type[_NexusServiceT] | str, + endpoint: str, + ) -> temporalio.client.NexusClient[_NexusServiceT]: + """Return the Nexus client that starts the operations of ``service``.""" + ... + + @typing.overload + def get_stream( + self, + ref: StreamRef[BodyT], + *, + created: bool | None = None, + body_type: None = None, + ) -> Stream[BodyT]: ... + @typing.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[typing.Any], + *, + created: bool | None = None, + body_type: typing.Any = None, + ) -> Stream[typing.Any]: + """Return the ``Stream`` handle for this ref.""" + arguments = typing.get_args(getattr(ref, "__orig_class__", None)) + # None means no explicit type, so use the ref's type argument, else object. + if body_type is None: + body_type = arguments[0] if arguments else object + elif arguments and arguments[0] is not object and arguments[0] != body_type: + raise TypeError("The decoding type must match the typed ref") + if arguments != (body_type,): + ref = StreamRef[body_type](id=ref.id, store=ref.store) + return Stream[body_type]( + self.create_nexus_client( + service=StreamService, + endpoint=temporalio.nexus.system.TEMPORAL_SYSTEM_ENDPOINT, + ), + ref=ref, + created=created, + ) + + async def _stream_service_create_stream( + self, + request: CreateStreamRequest[BodyT], + body_type: type[BodyT], + *, + rpc_metadata: collections.abc.Mapping[str, str | bytes] | None = None, + rpc_timeout: datetime.timedelta | None = None, + ) -> Stream[BodyT]: + nexus_client = self.create_nexus_client( + service=StreamService, + endpoint=temporalio.nexus.system.TEMPORAL_SYSTEM_ENDPOINT, + ) + handle = await nexus_client.start_operation( + operation="CreateStream", + arg=request, + id=f"{_uuid.uuid4()}", + result_type=CreateStreamResult[body_type], + rpc_metadata=rpc_metadata or {}, + rpc_timeout=rpc_timeout, + ) + result = await handle.result() + return _support.stream_from_create(result, nexus_client, body_type) + + @typing.overload + async def create_stream( + self, + *, + id: str, + store: str | None = None, + id_conflict_policy: StreamIdConflictPolicy | None = None, + body_type: type[BodyT], + rpc_metadata: collections.abc.Mapping[str, str | bytes] | None = None, + rpc_timeout: datetime.timedelta | None = None, + ) -> Stream[BodyT]: ... + + @typing.overload + async def create_stream( + self, + *, + id: str, + store: str | None = None, + id_conflict_policy: StreamIdConflictPolicy | None = None, + body_type: None = None, + rpc_metadata: collections.abc.Mapping[str, str | bytes] | None = None, + rpc_timeout: datetime.timedelta | None = None, + ) -> Stream[object]: ... + + async def create_stream( + self, + *, + id: str, + store: str | None = None, + id_conflict_policy: StreamIdConflictPolicy | None = None, + body_type: typing.Any = None, + rpc_metadata: collections.abc.Mapping[str, str | bytes] | None = None, + rpc_timeout: datetime.timedelta | None = None, + ) -> Stream[typing.Any]: + """ + Args: + id: The Stream id. It must not be empty. + store: If empty, the SDK uses its Store selector or the only registered + Store. + id_conflict_policy: What the create does if the Stream already exists. + Unspecified means fail. + """ + if body_type is None: + body_type = typing.Any + stream_ref = StreamRef( + id=id, + store=store, + ) + request = CreateStreamRequest( + stream_ref=stream_ref, + id_conflict_policy=id_conflict_policy, + ) + return await self._stream_service_create_stream( + request, body_type, rpc_metadata=rpc_metadata, rpc_timeout=rpc_timeout + ) diff --git a/temporalio/nexus/system/stream_service/client/_resources/__init__.py b/temporalio/nexus/system/stream_service/client/_resources/__init__.py new file mode 100644 index 0000000000..fd52fe93f3 --- /dev/null +++ b/temporalio/nexus/system/stream_service/client/_resources/__init__.py @@ -0,0 +1,3 @@ +# Generated by nexgen v0.2.14. DO NOT EDIT! + +from __future__ import annotations diff --git a/temporalio/nexus/system/stream_service/client/_resources/stream.py b/temporalio/nexus/system/stream_service/client/_resources/stream.py new file mode 100644 index 0000000000..09a85cd7bd --- /dev/null +++ b/temporalio/nexus/system/stream_service/client/_resources/stream.py @@ -0,0 +1,231 @@ +# Generated by nexgen v0.2.14. DO NOT EDIT! + +from __future__ import annotations + +import asyncio as _asyncio +import collections.abc +import datetime +import typing +import uuid as _uuid + +if typing.TYPE_CHECKING: + import temporalio.client + +import temporalio.nexus.system._support as _support + +from ..._poll import PollIterator +from ...models import ( + AppendRecord, + AppendRecordsRequest, + AppendRecordsResponse, + DescribeStreamRequest, + DescribeStreamResponse, + Producer, + ReadRecordsRequest, + ReadRecordsResponse, + StreamRecord, + StreamRef, +) +from ...services import StreamService + +BodyT = typing.TypeVar("BodyT") + + +class Stream(typing.Generic[BodyT]): + """One Stream. Build it from a stream-ref, or get it from a create.""" + + ref: StreamRef[BodyT] + created: bool | None + + def __init__( + self, + nexus_client: temporalio.client.NexusClient[typing.Any], + /, + *, + ref: StreamRef[BodyT], + created: bool | None, + ) -> None: + self._nexus_client: temporalio.client.NexusClient[typing.Any] = nexus_client + if type(self) is not Stream: + raise TypeError("Generic resource subclasses are not supported") + self.ref = ref + self.created = created + + @property + def body_type(self) -> type[BodyT]: + arguments = typing.get_args(getattr(self.ref, "__orig_class__", None)) + return typing.cast("type[BodyT]", arguments[0] if arguments else object) + + async def append( + self, + *records: BodyT, + producer: Producer | None = None, + rpc_metadata: collections.abc.Mapping[str, str | bytes] | None = None, + rpc_timeout: datetime.timedelta | None = None, + ) -> AppendRecordsResponse: + """Append values, and return the offsets of the batch.""" + request = AppendRecordsRequest( + ref=self.ref, + producer=( + (_support.default_producer(self._nexus_client)) + if producer is None + else producer + ), + records=[AppendRecord(body=value) for value in records], + ) + handle = await self._nexus_client.start_operation( + operation=StreamService.append_records, + arg=request, + id=f"{_uuid.uuid4()}", + rpc_metadata=rpc_metadata or {}, + rpc_timeout=rpc_timeout, + ) + return await handle.result() + + async def read_page( + self, + from_offset: bytes | None = None, + max_records: int | None = None, + wait: datetime.timedelta | None = None, + max_bytes: int | None = None, + *, + rpc_metadata: collections.abc.Mapping[str, str | bytes] | None = None, + rpc_timeout: datetime.timedelta | None = None, + ) -> ReadRecordsResponse[BodyT]: + """Read one page of Records. The poll iterator keeps reading after a page with no + Record. + """ + request = ReadRecordsRequest( + ref=self.ref, + from_offset=from_offset, + max_records=max_records, + max_bytes=max_bytes, + wait=wait, + ) + handle = await self._nexus_client.start_operation( + operation="ReadRecords", + arg=request, + id=f"{_uuid.uuid4()}", + result_type=ReadRecordsResponse[self.body_type], + rpc_metadata=rpc_metadata or {}, + rpc_timeout=rpc_timeout, + ) + return await handle.result() + + async def read_pages( + self, + from_offset: bytes | None = None, + max_records: int | None = None, + wait: datetime.timedelta | None = None, + max_bytes: int | None = None, + *, + rpc_metadata: collections.abc.Mapping[str, str | bytes] | None = None, + rpc_timeout: datetime.timedelta | None = None, + ) -> collections.abc.AsyncGenerator[ReadRecordsResponse[BodyT], None]: + """Yield each response of ``read_page`` until the poll helper returns ``None``. + + Read one page of Records. The poll iterator keeps reading after a page with no + Record. + + Args: + from_offset: Read after this offset. Empty means from the beginning. + max_records: The maximum Records per page. Zero uses the configured default. + wait: Wait per page. Unset reads immediately, then iterators use a + one-minute wait. + max_bytes: Page byte target. A larger Record can exceed it within SDK hard + limits. + """ + request = ReadRecordsRequest( + ref=self.ref, + from_offset=from_offset, + max_records=max_records, + max_bytes=max_bytes, + wait=wait, + ) + nexus_client = self._nexus_client + while True: + operation_handle = await nexus_client.start_operation( + operation="ReadRecords", + arg=request, + id=f"{_uuid.uuid4()}", + result_type=ReadRecordsResponse[self.body_type], + rpc_metadata=rpc_metadata or {}, + rpc_timeout=rpc_timeout, + ) + response = await operation_handle.result() + next_request = _support.next_read_request(request, response) + yield response + if next_request is None: + return + await _asyncio.sleep(0) + request = next_request + + def read( + self, + from_offset: bytes | None = None, + max_records: int | None = None, + wait: datetime.timedelta | None = None, + max_bytes: int | None = None, + *, + rpc_metadata: collections.abc.Mapping[str, str | bytes] | None = None, + rpc_timeout: datetime.timedelta | None = None, + ) -> PollIterator[ReadRecordsRequest[BodyT], StreamRecord[BodyT]]: + """Yield each item of ``read_pages``, page by page. + + ``next_request`` resumes after the last item that the iterator yielded. It is + ``None`` when the page helper returns ``None``. + + Read one page of Records. The poll iterator keeps reading after a page with no + Record. + + Args: + from_offset: Read after this offset. Empty means from the beginning. + max_records: The maximum Records per page. Zero uses the configured default. + wait: Wait per page. Unset reads immediately, then iterators use a + one-minute wait. + max_bytes: Page byte target. A larger Record can exceed it within SDK hard + limits. + """ + request = ReadRecordsRequest( + ref=self.ref, + from_offset=from_offset, + max_records=max_records, + max_bytes=max_bytes, + wait=wait, + ) + return PollIterator( + request, + self.read_pages( + from_offset=from_offset, + max_records=max_records, + wait=wait, + max_bytes=max_bytes, + rpc_metadata=rpc_metadata, + rpc_timeout=rpc_timeout, + ), + lambda response: response.records, + _support.next_read_request, + _support.resume_read_request, + ) + + async def describe( + self, + *, + rpc_metadata: collections.abc.Mapping[str, str | bytes] | None = None, + rpc_timeout: datetime.timedelta | None = None, + ) -> DescribeStreamResponse: + """Return the newest offset of the Stream.""" + request = DescribeStreamRequest( + ref=self.ref, + ) + handle = await self._nexus_client.start_operation( + operation=StreamService.describe_stream, + arg=request, + id=f"{_uuid.uuid4()}", + rpc_metadata=rpc_metadata or {}, + rpc_timeout=rpc_timeout, + ) + return await handle.result() + + +__all__ = ["Stream"] diff --git a/temporalio/nexus/system/stream_service/models.py b/temporalio/nexus/system/stream_service/models.py new file mode 100644 index 0000000000..ceee812dc9 --- /dev/null +++ b/temporalio/nexus/system/stream_service/models.py @@ -0,0 +1,1355 @@ +# Generated by nexgen v0.2.14. DO NOT EDIT! + +from __future__ import annotations + +import dataclasses +import datetime +import enum +import typing + +import google.protobuf.timestamp_pb2 +import typing_extensions + +import temporalio.api.enums.v1.stream_pb2 +import temporalio.api.sdk.v1.stream_pb2 +import temporalio.api.stream.v1.message_pb2 +import temporalio.api.streamservice.v1.request_response_pb2 +import temporalio.converter +import temporalio.nexus.system._support as _support + + +class StreamIdConflictPolicy(enum.IntEnum): + StreamIdConflictPolicyUnspecified = 0 + StreamIdConflictPolicyFail = 1 + StreamIdConflictPolicyUseExisting = 2 + + +BodyT = typing.TypeVar("BodyT") +_BodyT = typing_extensions.TypeVar("_BodyT", default=object) + + +@dataclasses.dataclass(slots=True) +class CreateStreamRequest(typing.Generic[BodyT]): + """Create a Stream. If it already exists, fail, or return it with use-existing.""" + + stream_ref: StreamRef[BodyT] + id_conflict_policy: StreamIdConflictPolicy | None = None + + +class _CreateStreamRequestTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + CreateStreamRequest[BodyT], temporalio.api.sdk.v1.stream_pb2.CreateStreamRequest + ] +): + transfer_type: type[temporalio.api.sdk.v1.stream_pb2.CreateStreamRequest] | None = ( + temporalio.api.sdk.v1.stream_pb2.CreateStreamRequest + ) + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.sdk.v1.stream_pb2.CreateStreamRequest, + type_hint: type[CreateStreamRequest[BodyT]], + ) -> CreateStreamRequest[BodyT]: + (body_type,) = typing.get_args(type_hint) or (typing.Any,) + if not value.HasField("stream_ref"): + raise ValueError("missing required field CreateStreamRequest.stream_ref") + stream_ref = typing.cast( + StreamRef[BodyT], + _StreamRefTransferTypeConverter().from_transfer_type( + value.stream_ref, StreamRef[body_type] + ), + ) + return CreateStreamRequest( + stream_ref=stream_ref, + id_conflict_policy=StreamIdConflictPolicy(value.id_conflict_policy) + if value.id_conflict_policy != 0 + else None, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: CreateStreamRequest[BodyT], + ) -> temporalio.api.sdk.v1.stream_pb2.CreateStreamRequest: + message = temporalio.api.sdk.v1.stream_pb2.CreateStreamRequest() + message.stream_ref.CopyFrom( + _StreamRefTransferTypeConverter().to_transfer_type(value.stream_ref) + ) + if value.id_conflict_policy is not None: + message.id_conflict_policy = ( + temporalio.api.enums.v1.stream_pb2.StreamIdConflictPolicy.ValueType( + value.id_conflict_policy + ) + ) + return message + + +temporalio.converter.transfer_type_convertible( + _CreateStreamRequestTransferTypeConverter[typing.Any] +)(CreateStreamRequest) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass +class StreamRef(typing.Generic[_BodyT]): + """A reference to one Stream. Callers treat the id as opaque.""" + + id: str + store: str | None = None + + +class _StreamRefTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + StreamRef[BodyT], temporalio.api.sdk.v1.stream_pb2.StreamRef + ] +): + transfer_type: type[temporalio.api.sdk.v1.stream_pb2.StreamRef] | None = ( + temporalio.api.sdk.v1.stream_pb2.StreamRef + ) + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.sdk.v1.stream_pb2.StreamRef, + type_hint: type[StreamRef[BodyT]], + ) -> StreamRef[BodyT]: + (_body_type,) = typing.get_args(type_hint) or (typing.Any,) + if not value.id: + raise ValueError("missing required field StreamRef.id") + id = value.id + return type_hint( + id=id, + store=value.store if bool(value.store) else None, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: StreamRef[BodyT], + ) -> temporalio.api.sdk.v1.stream_pb2.StreamRef: + message = temporalio.api.sdk.v1.stream_pb2.StreamRef() + message.id = value.id + if value.store is not None: + message.store = value.store + return message + + +temporalio.converter.transfer_type_convertible( + _StreamRefTransferTypeConverter[typing.Any] +)(StreamRef) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True) +class CreateStreamResult(typing.Generic[BodyT]): + ref: StreamRef[BodyT] | None = None + created: bool | None = None + + +class _CreateStreamResultTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + CreateStreamResult[BodyT], temporalio.api.sdk.v1.stream_pb2.CreateStreamResponse + ] +): + transfer_type: ( + type[temporalio.api.sdk.v1.stream_pb2.CreateStreamResponse] | None + ) = temporalio.api.sdk.v1.stream_pb2.CreateStreamResponse + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.sdk.v1.stream_pb2.CreateStreamResponse, + type_hint: type[CreateStreamResult[BodyT]], + ) -> CreateStreamResult[BodyT]: + (body_type,) = typing.get_args(type_hint) or (typing.Any,) + return CreateStreamResult( + ref=typing.cast( + StreamRef[BodyT], + _StreamRefTransferTypeConverter().from_transfer_type( + value.ref, StreamRef[body_type] + ), + ) + if value.HasField("ref") + else None, + created=value.created if bool(value.created) else None, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: CreateStreamResult[BodyT], + ) -> temporalio.api.sdk.v1.stream_pb2.CreateStreamResponse: + message = temporalio.api.sdk.v1.stream_pb2.CreateStreamResponse() + if value.ref is not None: + message.ref.CopyFrom( + _StreamRefTransferTypeConverter().to_transfer_type(value.ref) + ) + if value.created is not None: + message.created = value.created + return message + + +temporalio.converter.transfer_type_convertible( + _CreateStreamResultTransferTypeConverter[typing.Any] +)(CreateStreamResult) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True) +class AppendRecordsRequest(typing.Generic[BodyT]): + """Append one batch. Retries are deduplicated within the Store resend window.""" + + ref: StreamRef[BodyT] + records: list[AppendRecord[BodyT]] + producer: Producer + + +class _AppendRecordsRequestTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + AppendRecordsRequest[BodyT], + temporalio.api.sdk.v1.stream_pb2.AppendRecordsRequest, + ] +): + transfer_type: ( + type[temporalio.api.sdk.v1.stream_pb2.AppendRecordsRequest] | None + ) = temporalio.api.sdk.v1.stream_pb2.AppendRecordsRequest + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.sdk.v1.stream_pb2.AppendRecordsRequest, + type_hint: type[AppendRecordsRequest[BodyT]], + ) -> AppendRecordsRequest[BodyT]: + (body_type,) = typing.get_args(type_hint) or (typing.Any,) + if not value.HasField("ref"): + raise ValueError("missing required field AppendRecordsRequest.ref") + ref = typing.cast( + StreamRef[BodyT], + _StreamRefTransferTypeConverter().from_transfer_type( + value.ref, StreamRef[body_type] + ), + ) + records = [ + typing.cast( + AppendRecord[BodyT], + _AppendRecordTransferTypeConverter().from_transfer_type( + item, AppendRecord[body_type] + ), + ) + for item in value.records + ] + if not value.HasField("producer"): + raise ValueError("missing required field AppendRecordsRequest.producer") + producer = _ProducerTransferTypeConverter().from_transfer_type( + value.producer, Producer + ) + return AppendRecordsRequest( + ref=ref, + records=records, + producer=producer, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: AppendRecordsRequest[BodyT], + ) -> temporalio.api.sdk.v1.stream_pb2.AppendRecordsRequest: + message = temporalio.api.sdk.v1.stream_pb2.AppendRecordsRequest() + message.ref.CopyFrom( + _StreamRefTransferTypeConverter().to_transfer_type(value.ref) + ) + for element in value.records: + item = message.records.add() + item.CopyFrom( + _AppendRecordTransferTypeConverter().to_transfer_type(element) + ) + message.producer.CopyFrom( + _ProducerTransferTypeConverter().to_transfer_type(value.producer) + ) + return message + + +temporalio.converter.transfer_type_convertible( + _AppendRecordsRequestTransferTypeConverter[typing.Any] +)(AppendRecordsRequest) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True) +class AppendRecord(typing.Generic[BodyT]): + """One Record to append.""" + + body: BodyT + + +class _AppendRecordTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + AppendRecord[BodyT], temporalio.api.stream.v1.message_pb2.AppendRecord + ] +): + transfer_type: type[temporalio.api.stream.v1.message_pb2.AppendRecord] | None = ( + temporalio.api.stream.v1.message_pb2.AppendRecord + ) + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.stream.v1.message_pb2.AppendRecord, + type_hint: type[AppendRecord[BodyT]], + ) -> AppendRecord[BodyT]: + (body_type,) = typing.get_args(type_hint) or (typing.Any,) + if not value.HasField("body"): + raise ValueError("missing required field AppendRecord.body") + body = typing.cast(BodyT, _support.payload_from_proto(value.body, body_type)) + return AppendRecord( + body=body, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: AppendRecord[BodyT], + ) -> temporalio.api.stream.v1.message_pb2.AppendRecord: + message = temporalio.api.stream.v1.message_pb2.AppendRecord() + message.body.CopyFrom(_support.payload_to_proto(value.body)) + return message + + +temporalio.converter.transfer_type_convertible( + _AppendRecordTransferTypeConverter[typing.Any] +)(AppendRecord) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True) +class Producer: + """The writer of a batch. Attempts compare only within the same Producer.""" + + kind: ProducerKind | None = None + + +class _ProducerTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + Producer, temporalio.api.stream.v1.message_pb2.Producer + ] +): + transfer_type: type[temporalio.api.stream.v1.message_pb2.Producer] | None = ( + temporalio.api.stream.v1.message_pb2.Producer + ) + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.stream.v1.message_pb2.Producer, + type_hint: type[Producer], + ) -> Producer: + _oneof_kind: ( + ProducerKindWorkflow + | ProducerKindLocalActivity + | ProducerKindWorkflowActivity + | ProducerKindStandaloneActivity + | ProducerKindClient + | None + ) + match value.WhichOneof("kind"): + case "workflow": + _oneof_kind = ProducerKindWorkflow( + _WorkflowProducerTransferTypeConverter().from_transfer_type( + value.workflow, WorkflowProducer + ) + ) + case "local_activity": + _oneof_kind = ProducerKindLocalActivity( + _LocalActivityProducerTransferTypeConverter().from_transfer_type( + value.local_activity, LocalActivityProducer + ) + ) + case "workflow_activity": + _oneof_kind = ProducerKindWorkflowActivity( + _WorkflowActivityProducerTransferTypeConverter().from_transfer_type( + value.workflow_activity, WorkflowActivityProducer + ) + ) + case "standalone_activity": + _oneof_kind = ProducerKindStandaloneActivity( + _StandaloneActivityProducerTransferTypeConverter().from_transfer_type( + value.standalone_activity, StandaloneActivityProducer + ) + ) + case "client": + _oneof_kind = ProducerKindClient( + _ClientProducerTransferTypeConverter().from_transfer_type( + value.client, ClientProducer + ) + ) + case None: + _oneof_kind = None + return Producer( + kind=_oneof_kind, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: Producer, + ) -> temporalio.api.stream.v1.message_pb2.Producer: + message = temporalio.api.stream.v1.message_pb2.Producer() + if value.kind is not None: + match value.kind: + case ProducerKindWorkflow(): + message.workflow.CopyFrom( + _WorkflowProducerTransferTypeConverter().to_transfer_type( + value.kind.value + ) + ) + case ProducerKindLocalActivity(): + message.local_activity.CopyFrom( + _LocalActivityProducerTransferTypeConverter().to_transfer_type( + value.kind.value + ) + ) + case ProducerKindWorkflowActivity(): + message.workflow_activity.CopyFrom( + _WorkflowActivityProducerTransferTypeConverter().to_transfer_type( + value.kind.value + ) + ) + case ProducerKindStandaloneActivity(): + message.standalone_activity.CopyFrom( + _StandaloneActivityProducerTransferTypeConverter().to_transfer_type( + value.kind.value + ) + ) + case ProducerKindClient(): + message.client.CopyFrom( + _ClientProducerTransferTypeConverter().to_transfer_type( + value.kind.value + ) + ) + return message + + +temporalio.converter.transfer_type_convertible(_ProducerTransferTypeConverter)(Producer) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True) +class WorkflowProducer: + """The Producer of a Workflow run.""" + + namespace: str + workflow_id: str + run_id: str + attempt: WorkflowTaskAttempt | None = None + + +class _WorkflowProducerTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + WorkflowProducer, temporalio.api.stream.v1.message_pb2.WorkflowProducer + ] +): + transfer_type: ( + type[temporalio.api.stream.v1.message_pb2.WorkflowProducer] | None + ) = temporalio.api.stream.v1.message_pb2.WorkflowProducer + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.stream.v1.message_pb2.WorkflowProducer, + type_hint: type[WorkflowProducer], + ) -> WorkflowProducer: + if not value.namespace: + raise ValueError("missing required field WorkflowProducer.namespace") + namespace = value.namespace + if not value.workflow_id: + raise ValueError("missing required field WorkflowProducer.workflow_id") + workflow_id = value.workflow_id + if not value.run_id: + raise ValueError("missing required field WorkflowProducer.run_id") + run_id = value.run_id + return WorkflowProducer( + namespace=namespace, + workflow_id=workflow_id, + run_id=run_id, + attempt=_WorkflowTaskAttemptTransferTypeConverter().from_transfer_type( + value.attempt, WorkflowTaskAttempt + ) + if value.HasField("attempt") + else None, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: WorkflowProducer, + ) -> temporalio.api.stream.v1.message_pb2.WorkflowProducer: + message = temporalio.api.stream.v1.message_pb2.WorkflowProducer() + message.namespace = value.namespace + message.workflow_id = value.workflow_id + message.run_id = value.run_id + if value.attempt is not None: + message.attempt.CopyFrom( + _WorkflowTaskAttemptTransferTypeConverter().to_transfer_type( + value.attempt + ) + ) + return message + + +temporalio.converter.transfer_type_convertible(_WorkflowProducerTransferTypeConverter)( + WorkflowProducer +) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True) +class WorkflowTaskAttempt: + """One attempt of a Workflow Task.""" + + started_event_id: int + attempt: int + started_time: Timestamp | None = None + + +class _WorkflowTaskAttemptTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + WorkflowTaskAttempt, temporalio.api.stream.v1.message_pb2.WorkflowTaskAttempt + ] +): + transfer_type: ( + type[temporalio.api.stream.v1.message_pb2.WorkflowTaskAttempt] | None + ) = temporalio.api.stream.v1.message_pb2.WorkflowTaskAttempt + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.stream.v1.message_pb2.WorkflowTaskAttempt, + type_hint: type[WorkflowTaskAttempt], + ) -> WorkflowTaskAttempt: + started_event_id = value.started_event_id + attempt = value.attempt + return WorkflowTaskAttempt( + started_event_id=started_event_id, + attempt=attempt, + started_time=_TimestampTransferTypeConverter().from_transfer_type( + value.started_time, Timestamp + ) + if value.HasField("started_time") + else None, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: WorkflowTaskAttempt, + ) -> temporalio.api.stream.v1.message_pb2.WorkflowTaskAttempt: + message = temporalio.api.stream.v1.message_pb2.WorkflowTaskAttempt() + message.started_event_id = value.started_event_id + message.attempt = value.attempt + if value.started_time is not None: + message.started_time.CopyFrom( + _TimestampTransferTypeConverter().to_transfer_type(value.started_time) + ) + return message + + +temporalio.converter.transfer_type_convertible( + _WorkflowTaskAttemptTransferTypeConverter +)(WorkflowTaskAttempt) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True) +class Timestamp: + seconds: int + nanos: int + + +class _TimestampTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + Timestamp, google.protobuf.timestamp_pb2.Timestamp + ] +): + transfer_type: type[google.protobuf.timestamp_pb2.Timestamp] | None = ( + google.protobuf.timestamp_pb2.Timestamp + ) + + @typing_extensions.override + def from_transfer_type( + self, + value: google.protobuf.timestamp_pb2.Timestamp, + type_hint: type[Timestamp], + ) -> Timestamp: + seconds = value.seconds + nanos = value.nanos + return Timestamp( + seconds=seconds, + nanos=nanos, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: Timestamp, + ) -> google.protobuf.timestamp_pb2.Timestamp: + message = google.protobuf.timestamp_pb2.Timestamp() + message.seconds = value.seconds + message.nanos = value.nanos + return message + + +temporalio.converter.transfer_type_convertible(_TimestampTransferTypeConverter)( + Timestamp +) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True) +class LocalActivityProducer: + """The Producer of one Local Activity of a Workflow run.""" + + namespace: str + workflow_id: str + run_id: str + activity_id: str + attempt: LocalActivityAttempt + + +class _LocalActivityProducerTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + LocalActivityProducer, + temporalio.api.stream.v1.message_pb2.LocalActivityProducer, + ] +): + transfer_type: ( + type[temporalio.api.stream.v1.message_pb2.LocalActivityProducer] | None + ) = temporalio.api.stream.v1.message_pb2.LocalActivityProducer + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.stream.v1.message_pb2.LocalActivityProducer, + type_hint: type[LocalActivityProducer], + ) -> LocalActivityProducer: + if not value.namespace: + raise ValueError("missing required field LocalActivityProducer.namespace") + namespace = value.namespace + if not value.workflow_id: + raise ValueError("missing required field LocalActivityProducer.workflow_id") + workflow_id = value.workflow_id + if not value.run_id: + raise ValueError("missing required field LocalActivityProducer.run_id") + run_id = value.run_id + if not value.activity_id: + raise ValueError("missing required field LocalActivityProducer.activity_id") + activity_id = value.activity_id + if not value.HasField("attempt"): + raise ValueError("missing required field LocalActivityProducer.attempt") + attempt = _LocalActivityAttemptTransferTypeConverter().from_transfer_type( + value.attempt, LocalActivityAttempt + ) + return LocalActivityProducer( + namespace=namespace, + workflow_id=workflow_id, + run_id=run_id, + activity_id=activity_id, + attempt=attempt, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: LocalActivityProducer, + ) -> temporalio.api.stream.v1.message_pb2.LocalActivityProducer: + message = temporalio.api.stream.v1.message_pb2.LocalActivityProducer() + message.namespace = value.namespace + message.workflow_id = value.workflow_id + message.run_id = value.run_id + message.activity_id = value.activity_id + message.attempt.CopyFrom( + _LocalActivityAttemptTransferTypeConverter().to_transfer_type(value.attempt) + ) + return message + + +temporalio.converter.transfer_type_convertible( + _LocalActivityProducerTransferTypeConverter +)(LocalActivityProducer) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True) +class LocalActivityAttempt: + """One attempt of a Local Activity. Attempts compare by Workflow Task first.""" + + task: WorkflowTaskAttempt + attempt: int + + +class _LocalActivityAttemptTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + LocalActivityAttempt, temporalio.api.stream.v1.message_pb2.LocalActivityAttempt + ] +): + transfer_type: ( + type[temporalio.api.stream.v1.message_pb2.LocalActivityAttempt] | None + ) = temporalio.api.stream.v1.message_pb2.LocalActivityAttempt + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.stream.v1.message_pb2.LocalActivityAttempt, + type_hint: type[LocalActivityAttempt], + ) -> LocalActivityAttempt: + if not value.HasField("task"): + raise ValueError("missing required field LocalActivityAttempt.task") + task = _WorkflowTaskAttemptTransferTypeConverter().from_transfer_type( + value.task, WorkflowTaskAttempt + ) + attempt = value.attempt + return LocalActivityAttempt( + task=task, + attempt=attempt, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: LocalActivityAttempt, + ) -> temporalio.api.stream.v1.message_pb2.LocalActivityAttempt: + message = temporalio.api.stream.v1.message_pb2.LocalActivityAttempt() + message.task.CopyFrom( + _WorkflowTaskAttemptTransferTypeConverter().to_transfer_type(value.task) + ) + message.attempt = value.attempt + return message + + +temporalio.converter.transfer_type_convertible( + _LocalActivityAttemptTransferTypeConverter +)(LocalActivityAttempt) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True, kw_only=True) +class WorkflowActivityProducer: + """The Producer of one Activity that a Workflow scheduled.""" + + namespace: str + workflow_id: str + run_id: str + activity_id: str + scheduled_event_id: int | None = None + attempt: ActivityAttempt + + +class _WorkflowActivityProducerTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + WorkflowActivityProducer, + temporalio.api.stream.v1.message_pb2.WorkflowActivityProducer, + ] +): + transfer_type: ( + type[temporalio.api.stream.v1.message_pb2.WorkflowActivityProducer] | None + ) = temporalio.api.stream.v1.message_pb2.WorkflowActivityProducer + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.stream.v1.message_pb2.WorkflowActivityProducer, + type_hint: type[WorkflowActivityProducer], + ) -> WorkflowActivityProducer: + if not value.namespace: + raise ValueError( + "missing required field WorkflowActivityProducer.namespace" + ) + namespace = value.namespace + if not value.workflow_id: + raise ValueError( + "missing required field WorkflowActivityProducer.workflow_id" + ) + workflow_id = value.workflow_id + if not value.run_id: + raise ValueError("missing required field WorkflowActivityProducer.run_id") + run_id = value.run_id + if not value.activity_id: + raise ValueError( + "missing required field WorkflowActivityProducer.activity_id" + ) + activity_id = value.activity_id + if not value.HasField("attempt"): + raise ValueError("missing required field WorkflowActivityProducer.attempt") + attempt = _ActivityAttemptTransferTypeConverter().from_transfer_type( + value.attempt, ActivityAttempt + ) + return WorkflowActivityProducer( + namespace=namespace, + workflow_id=workflow_id, + run_id=run_id, + activity_id=activity_id, + scheduled_event_id=value.scheduled_event_id + if value.scheduled_event_id != 0 + else None, + attempt=attempt, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: WorkflowActivityProducer, + ) -> temporalio.api.stream.v1.message_pb2.WorkflowActivityProducer: + message = temporalio.api.stream.v1.message_pb2.WorkflowActivityProducer() + message.namespace = value.namespace + message.workflow_id = value.workflow_id + message.run_id = value.run_id + message.activity_id = value.activity_id + if value.scheduled_event_id is not None: + message.scheduled_event_id = value.scheduled_event_id + message.attempt.CopyFrom( + _ActivityAttemptTransferTypeConverter().to_transfer_type(value.attempt) + ) + return message + + +temporalio.converter.transfer_type_convertible( + _WorkflowActivityProducerTransferTypeConverter +)(WorkflowActivityProducer) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True) +class ActivityAttempt: + """One attempt of an Activity or a Standalone Activity.""" + + attempt_scheduled_time: Timestamp + attempt: int + + +class _ActivityAttemptTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + ActivityAttempt, temporalio.api.stream.v1.message_pb2.ActivityAttempt + ] +): + transfer_type: type[temporalio.api.stream.v1.message_pb2.ActivityAttempt] | None = ( + temporalio.api.stream.v1.message_pb2.ActivityAttempt + ) + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.stream.v1.message_pb2.ActivityAttempt, + type_hint: type[ActivityAttempt], + ) -> ActivityAttempt: + if not value.HasField("attempt_scheduled_time"): + raise ValueError( + "missing required field ActivityAttempt.attempt_scheduled_time" + ) + attempt_scheduled_time = _TimestampTransferTypeConverter().from_transfer_type( + value.attempt_scheduled_time, Timestamp + ) + attempt = value.attempt + return ActivityAttempt( + attempt_scheduled_time=attempt_scheduled_time, + attempt=attempt, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: ActivityAttempt, + ) -> temporalio.api.stream.v1.message_pb2.ActivityAttempt: + message = temporalio.api.stream.v1.message_pb2.ActivityAttempt() + message.attempt_scheduled_time.CopyFrom( + _TimestampTransferTypeConverter().to_transfer_type( + value.attempt_scheduled_time + ) + ) + message.attempt = value.attempt + return message + + +temporalio.converter.transfer_type_convertible(_ActivityAttemptTransferTypeConverter)( + ActivityAttempt +) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True) +class StandaloneActivityProducer: + """The Producer of a Standalone Activity.""" + + namespace: str + activity_id: str + run_id: str + attempt: ActivityAttempt + + +class _StandaloneActivityProducerTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + StandaloneActivityProducer, + temporalio.api.stream.v1.message_pb2.StandaloneActivityProducer, + ] +): + transfer_type: ( + type[temporalio.api.stream.v1.message_pb2.StandaloneActivityProducer] | None + ) = temporalio.api.stream.v1.message_pb2.StandaloneActivityProducer + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.stream.v1.message_pb2.StandaloneActivityProducer, + type_hint: type[StandaloneActivityProducer], + ) -> StandaloneActivityProducer: + if not value.namespace: + raise ValueError( + "missing required field StandaloneActivityProducer.namespace" + ) + namespace = value.namespace + if not value.activity_id: + raise ValueError( + "missing required field StandaloneActivityProducer.activity_id" + ) + activity_id = value.activity_id + if not value.run_id: + raise ValueError("missing required field StandaloneActivityProducer.run_id") + run_id = value.run_id + if not value.HasField("attempt"): + raise ValueError( + "missing required field StandaloneActivityProducer.attempt" + ) + attempt = _ActivityAttemptTransferTypeConverter().from_transfer_type( + value.attempt, ActivityAttempt + ) + return StandaloneActivityProducer( + namespace=namespace, + activity_id=activity_id, + run_id=run_id, + attempt=attempt, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: StandaloneActivityProducer, + ) -> temporalio.api.stream.v1.message_pb2.StandaloneActivityProducer: + message = temporalio.api.stream.v1.message_pb2.StandaloneActivityProducer() + message.namespace = value.namespace + message.activity_id = value.activity_id + message.run_id = value.run_id + message.attempt.CopyFrom( + _ActivityAttemptTransferTypeConverter().to_transfer_type(value.attempt) + ) + return message + + +temporalio.converter.transfer_type_convertible( + _StandaloneActivityProducerTransferTypeConverter +)(StandaloneActivityProducer) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True) +class ClientProducer: + """The Producer of a client. It has no run and no attempt.""" + + namespace: str + id: str + + +class _ClientProducerTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + ClientProducer, temporalio.api.stream.v1.message_pb2.ClientProducer + ] +): + transfer_type: type[temporalio.api.stream.v1.message_pb2.ClientProducer] | None = ( + temporalio.api.stream.v1.message_pb2.ClientProducer + ) + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.stream.v1.message_pb2.ClientProducer, + type_hint: type[ClientProducer], + ) -> ClientProducer: + if not value.namespace: + raise ValueError("missing required field ClientProducer.namespace") + namespace = value.namespace + if not value.id: + raise ValueError("missing required field ClientProducer.id") + id = value.id + return ClientProducer( + namespace=namespace, + id=id, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: ClientProducer, + ) -> temporalio.api.stream.v1.message_pb2.ClientProducer: + message = temporalio.api.stream.v1.message_pb2.ClientProducer() + message.namespace = value.namespace + message.id = value.id + return message + + +temporalio.converter.transfer_type_convertible(_ClientProducerTransferTypeConverter)( + ClientProducer +) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True) +class AppendRecordsResponse: + first_offset: bytes | None = None + last_offset: bytes | None = None + + +class _AppendRecordsResponseTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + AppendRecordsResponse, + temporalio.api.streamservice.v1.request_response_pb2.AppendRecordsResponse, + ] +): + transfer_type: ( + type[temporalio.api.streamservice.v1.request_response_pb2.AppendRecordsResponse] + | None + ) = temporalio.api.streamservice.v1.request_response_pb2.AppendRecordsResponse + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.streamservice.v1.request_response_pb2.AppendRecordsResponse, + type_hint: type[AppendRecordsResponse], + ) -> AppendRecordsResponse: + return AppendRecordsResponse( + first_offset=value.first_offset if bool(value.first_offset) else None, + last_offset=value.last_offset if bool(value.last_offset) else None, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: AppendRecordsResponse, + ) -> temporalio.api.streamservice.v1.request_response_pb2.AppendRecordsResponse: + message = ( + temporalio.api.streamservice.v1.request_response_pb2.AppendRecordsResponse() + ) + if value.first_offset is not None: + message.first_offset = value.first_offset + if value.last_offset is not None: + message.last_offset = value.last_offset + return message + + +temporalio.converter.transfer_type_convertible( + _AppendRecordsResponseTransferTypeConverter +)(AppendRecordsResponse) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True) +class ReadRecordsRequest(typing.Generic[BodyT]): + """Read Records after an offset.""" + + ref: StreamRef[BodyT] + from_offset: bytes | None = None + max_records: int | None = None + max_bytes: int | None = None + wait: datetime.timedelta | None = None + + +class _ReadRecordsRequestTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + ReadRecordsRequest[BodyT], temporalio.api.sdk.v1.stream_pb2.ReadRecordsRequest + ] +): + transfer_type: type[temporalio.api.sdk.v1.stream_pb2.ReadRecordsRequest] | None = ( + temporalio.api.sdk.v1.stream_pb2.ReadRecordsRequest + ) + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.sdk.v1.stream_pb2.ReadRecordsRequest, + type_hint: type[ReadRecordsRequest[BodyT]], + ) -> ReadRecordsRequest[BodyT]: + (body_type,) = typing.get_args(type_hint) or (typing.Any,) + if not value.HasField("ref"): + raise ValueError("missing required field ReadRecordsRequest.ref") + ref = typing.cast( + StreamRef[BodyT], + _StreamRefTransferTypeConverter().from_transfer_type( + value.ref, StreamRef[body_type] + ), + ) + return ReadRecordsRequest( + ref=ref, + from_offset=value.from_offset if bool(value.from_offset) else None, + max_records=value.max_records if value.max_records != 0 else None, + max_bytes=value.max_bytes if value.max_bytes != 0 else None, + wait=_support.duration_from_proto(value.wait) + if value.HasField("wait") + else None, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: ReadRecordsRequest[BodyT], + ) -> temporalio.api.sdk.v1.stream_pb2.ReadRecordsRequest: + message = temporalio.api.sdk.v1.stream_pb2.ReadRecordsRequest() + message.ref.CopyFrom( + _StreamRefTransferTypeConverter().to_transfer_type(value.ref) + ) + if value.from_offset is not None: + message.from_offset = value.from_offset + if value.max_records is not None: + message.max_records = value.max_records + if value.max_bytes is not None: + message.max_bytes = value.max_bytes + if value.wait is not None: + message.wait.CopyFrom(_support.duration_to_proto(value.wait)) + return message + + +temporalio.converter.transfer_type_convertible( + _ReadRecordsRequestTransferTypeConverter[typing.Any] +)(ReadRecordsRequest) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True) +class ReadRecordsResponse(typing.Generic[BodyT]): + records: list[StreamRecord[BodyT]] + last_offset: bytes | None = None + + +class _ReadRecordsResponseTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + ReadRecordsResponse[BodyT], + temporalio.api.streamservice.v1.request_response_pb2.ReadRecordsResponse, + ] +): + transfer_type: ( + type[temporalio.api.streamservice.v1.request_response_pb2.ReadRecordsResponse] + | None + ) = temporalio.api.streamservice.v1.request_response_pb2.ReadRecordsResponse + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.streamservice.v1.request_response_pb2.ReadRecordsResponse, + type_hint: type[ReadRecordsResponse[BodyT]], + ) -> ReadRecordsResponse[BodyT]: + (body_type,) = typing.get_args(type_hint) or (typing.Any,) + records = [ + typing.cast( + StreamRecord[BodyT], + _StreamRecordTransferTypeConverter().from_transfer_type( + item, StreamRecord[body_type] + ), + ) + for item in value.records + ] + return ReadRecordsResponse( + records=records, + last_offset=value.last_offset if bool(value.last_offset) else None, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: ReadRecordsResponse[BodyT], + ) -> temporalio.api.streamservice.v1.request_response_pb2.ReadRecordsResponse: + message = ( + temporalio.api.streamservice.v1.request_response_pb2.ReadRecordsResponse() + ) + for element in value.records: + item = message.records.add() + item.CopyFrom( + _StreamRecordTransferTypeConverter().to_transfer_type(element) + ) + if value.last_offset is not None: + message.last_offset = value.last_offset + return message + + +temporalio.converter.transfer_type_convertible( + _ReadRecordsResponseTransferTypeConverter[typing.Any] +)(ReadRecordsResponse) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True, kw_only=True) +class StreamRecord(typing.Generic[BodyT]): + """One Record of a Stream, as a read returns it.""" + + body: BodyT + producer: Producer | None = None + offset: bytes + + +class _StreamRecordTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + StreamRecord[BodyT], temporalio.api.stream.v1.message_pb2.StreamRecord + ] +): + transfer_type: type[temporalio.api.stream.v1.message_pb2.StreamRecord] | None = ( + temporalio.api.stream.v1.message_pb2.StreamRecord + ) + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.stream.v1.message_pb2.StreamRecord, + type_hint: type[StreamRecord[BodyT]], + ) -> StreamRecord[BodyT]: + (body_type,) = typing.get_args(type_hint) or (typing.Any,) + if not value.HasField("body"): + raise ValueError("missing required field StreamRecord.body") + body = typing.cast(BodyT, _support.payload_from_proto(value.body, body_type)) + if not value.offset: + raise ValueError("missing required field StreamRecord.offset") + offset = value.offset + return StreamRecord( + body=body, + producer=_ProducerTransferTypeConverter().from_transfer_type( + value.producer, Producer + ) + if value.HasField("producer") + else None, + offset=offset, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: StreamRecord[BodyT], + ) -> temporalio.api.stream.v1.message_pb2.StreamRecord: + message = temporalio.api.stream.v1.message_pb2.StreamRecord() + message.body.CopyFrom(_support.payload_to_proto(value.body)) + if value.producer is not None: + message.producer.CopyFrom( + _ProducerTransferTypeConverter().to_transfer_type(value.producer) + ) + message.offset = value.offset + return message + + +temporalio.converter.transfer_type_convertible( + _StreamRecordTransferTypeConverter[typing.Any] +)(StreamRecord) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True) +class DescribeStreamRequest(typing.Generic[BodyT]): + ref: StreamRef[BodyT] + + +class _DescribeStreamRequestTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + DescribeStreamRequest[BodyT], + temporalio.api.sdk.v1.stream_pb2.DescribeStreamRequest, + ] +): + transfer_type: ( + type[temporalio.api.sdk.v1.stream_pb2.DescribeStreamRequest] | None + ) = temporalio.api.sdk.v1.stream_pb2.DescribeStreamRequest + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.sdk.v1.stream_pb2.DescribeStreamRequest, + type_hint: type[DescribeStreamRequest[BodyT]], + ) -> DescribeStreamRequest[BodyT]: + (body_type,) = typing.get_args(type_hint) or (typing.Any,) + if not value.HasField("ref"): + raise ValueError("missing required field DescribeStreamRequest.ref") + ref = typing.cast( + StreamRef[BodyT], + _StreamRefTransferTypeConverter().from_transfer_type( + value.ref, StreamRef[body_type] + ), + ) + return DescribeStreamRequest( + ref=ref, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: DescribeStreamRequest[BodyT], + ) -> temporalio.api.sdk.v1.stream_pb2.DescribeStreamRequest: + message = temporalio.api.sdk.v1.stream_pb2.DescribeStreamRequest() + message.ref.CopyFrom( + _StreamRefTransferTypeConverter().to_transfer_type(value.ref) + ) + return message + + +temporalio.converter.transfer_type_convertible( + _DescribeStreamRequestTransferTypeConverter[typing.Any] +)(DescribeStreamRequest) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True) +class DescribeStreamResponse: + last_offset: bytes | None = None + + +class _DescribeStreamResponseTransferTypeConverter( + temporalio.converter.TransferTypeConverter[ + DescribeStreamResponse, + temporalio.api.streamservice.v1.request_response_pb2.DescribeStreamResponse, + ] +): + transfer_type: ( + type[ + temporalio.api.streamservice.v1.request_response_pb2.DescribeStreamResponse + ] + | None + ) = temporalio.api.streamservice.v1.request_response_pb2.DescribeStreamResponse + + @typing_extensions.override + def from_transfer_type( + self, + value: temporalio.api.streamservice.v1.request_response_pb2.DescribeStreamResponse, + type_hint: type[DescribeStreamResponse], + ) -> DescribeStreamResponse: + return DescribeStreamResponse( + last_offset=value.last_offset if bool(value.last_offset) else None, + ) + + @typing_extensions.override + def to_transfer_type( + self, + value: DescribeStreamResponse, + ) -> temporalio.api.streamservice.v1.request_response_pb2.DescribeStreamResponse: + message = temporalio.api.streamservice.v1.request_response_pb2.DescribeStreamResponse() + if value.last_offset is not None: + message.last_offset = value.last_offset + return message + + +temporalio.converter.transfer_type_convertible( + _DescribeStreamResponseTransferTypeConverter +)(DescribeStreamResponse) # pyright: ignore[reportUnusedCallResult] + + +@dataclasses.dataclass(slots=True) +class ProducerKindWorkflow: + value: WorkflowProducer + + +@dataclasses.dataclass(slots=True) +class ProducerKindLocalActivity: + value: LocalActivityProducer + + +@dataclasses.dataclass(slots=True) +class ProducerKindWorkflowActivity: + value: WorkflowActivityProducer + + +@dataclasses.dataclass(slots=True) +class ProducerKindStandaloneActivity: + value: StandaloneActivityProducer + + +@dataclasses.dataclass(slots=True) +class ProducerKindClient: + value: ClientProducer + + +ProducerKind = ( + ProducerKindWorkflow + | ProducerKindLocalActivity + | ProducerKindWorkflowActivity + | ProducerKindStandaloneActivity + | ProducerKindClient +) +"""The kind of a Producer, with its ids and its attempt.""" diff --git a/temporalio/nexus/system/stream_service/services.py b/temporalio/nexus/system/stream_service/services.py new file mode 100644 index 0000000000..d2c21e3f23 --- /dev/null +++ b/temporalio/nexus/system/stream_service/services.py @@ -0,0 +1,46 @@ +# Generated by nexgen v0.2.14. DO NOT EDIT! + +from __future__ import annotations + +import typing + +from nexusrpc import Operation, service + +from .models import ( + AppendRecordsRequest, + AppendRecordsResponse, + CreateStreamRequest, + CreateStreamResult, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) + + +@service(name="temporal.api.streamservice.v1.StreamService") +class StreamService: + """ + .. warning:: + This API is experimental and subject to change. + """ + + create_stream: Operation[ + CreateStreamRequest[typing.Any], + CreateStreamResult[typing.Any], + ] = Operation(name="CreateStream") + + append_records: Operation[ + AppendRecordsRequest[typing.Any], + AppendRecordsResponse, + ] = Operation(name="AppendRecords") + + read_records: Operation[ + ReadRecordsRequest[typing.Any], + ReadRecordsResponse[typing.Any], + ] = Operation(name="ReadRecords") + + describe_stream: Operation[ + DescribeStreamRequest[typing.Any], + DescribeStreamResponse, + ] = Operation(name="DescribeStream") diff --git a/temporalio/nexus/system/stream_service/workflow/__init__.py b/temporalio/nexus/system/stream_service/workflow/__init__.py new file mode 100644 index 0000000000..c886841f74 --- /dev/null +++ b/temporalio/nexus/system/stream_service/workflow/__init__.py @@ -0,0 +1,78 @@ +# Generated by nexgen v0.2.14. DO NOT EDIT! + +from __future__ import annotations + +import collections.abc +import typing + +import nexusrpc + +import temporalio.converter + +from .. import services as _services +from ._resources.stream import get_stream +from .operations.create_stream import create_stream + +__all__ = [ + "create_stream", + "get_stream", +] + + +_InputT = typing.TypeVar("_InputT") +_OutputT = typing.TypeVar("_OutputT") + + +_SerializationContextFactory = collections.abc.Callable[ + [_InputT], temporalio.converter.SerializationContext +] + + +_StorageTargetFactory = collections.abc.Callable[ + [_InputT], temporalio.converter.StorageDriverWorkflowInfo +] + + +class _NexusOperationInfo(typing.Generic[_InputT, _OutputT]): + def __init__( + self, + *, + operation: nexusrpc.Operation[_InputT, _OutputT], + serialization_context: _SerializationContextFactory[_InputT] | None = None, + storage_target: _StorageTargetFactory[_InputT] | None = None, + ) -> None: + self.operation: nexusrpc.Operation[_InputT, _OutputT] = operation + self.serialization_context: _SerializationContextFactory[_InputT] | None = ( + serialization_context + ) + self.storage_target: _StorageTargetFactory[_InputT] | None = storage_target + + +__nexus_operation_registry__: dict[ + tuple[str, str], _NexusOperationInfo[typing.Any, typing.Any] +] = { + ( + "temporal.api.streamservice.v1.StreamService", + "CreateStream", + ): _NexusOperationInfo( + operation=_services.StreamService.create_stream, + ), + ( + "temporal.api.streamservice.v1.StreamService", + "AppendRecords", + ): _NexusOperationInfo( + operation=_services.StreamService.append_records, + ), + ( + "temporal.api.streamservice.v1.StreamService", + "ReadRecords", + ): _NexusOperationInfo( + operation=_services.StreamService.read_records, + ), + ( + "temporal.api.streamservice.v1.StreamService", + "DescribeStream", + ): _NexusOperationInfo( + operation=_services.StreamService.describe_stream, + ), +} diff --git a/temporalio/nexus/system/stream_service/workflow/_resources/__init__.py b/temporalio/nexus/system/stream_service/workflow/_resources/__init__.py new file mode 100644 index 0000000000..501c93db22 --- /dev/null +++ b/temporalio/nexus/system/stream_service/workflow/_resources/__init__.py @@ -0,0 +1,9 @@ +# Generated by nexgen v0.2.14. DO NOT EDIT! + +from __future__ import annotations + +from .stream import Stream + +__all__ = [ + "Stream", +] diff --git a/temporalio/nexus/system/stream_service/workflow/_resources/stream.py b/temporalio/nexus/system/stream_service/workflow/_resources/stream.py new file mode 100644 index 0000000000..221f06df3c --- /dev/null +++ b/temporalio/nexus/system/stream_service/workflow/_resources/stream.py @@ -0,0 +1,252 @@ +# Generated by nexgen v0.2.14. DO NOT EDIT! + +from __future__ import annotations + +import collections.abc +import datetime +import typing + +import temporalio.nexus.system +import temporalio.nexus.system._support as _support +import temporalio.workflow + +from ..._poll import PollIterator +from ...models import ( + AppendRecord, + AppendRecordsRequest, + AppendRecordsResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, + StreamRecord, + StreamRef, +) + +BodyT = typing.TypeVar("BodyT") + + +class Stream(typing.Generic[BodyT]): + """One Stream. Build it from a stream-ref, or get it from a create.""" + + ref: StreamRef[BodyT] + created: bool | None + + def __init__( + self, + ref: StreamRef[BodyT], + created: bool | None, + ) -> None: + if type(self) is not Stream: + raise TypeError("Generic resource subclasses are not supported") + self.ref = ref + self.created = created + + @property + def body_type(self) -> type[BodyT]: + arguments = typing.get_args(getattr(self.ref, "__orig_class__", None)) + return typing.cast("type[BodyT]", arguments[0] if arguments else object) + + async def append( + self, + *records: BodyT, + ) -> AppendRecordsResponse: + """Append values, and return the offsets of the batch.""" + request = AppendRecordsRequest( + ref=self.ref, + records=[AppendRecord(body=value) for value in records], + producer=_support.workflow_producer(), + ) + handle = await _append_records(request) + return await handle + + async def read_page( + self, + from_offset: bytes | None = None, + max_records: int | None = None, + wait: datetime.timedelta | None = None, + max_bytes: int | None = None, + ) -> ReadRecordsResponse[BodyT]: + """Read one page of Records. The poll iterator keeps reading after a page with no + Record. + """ + request = ReadRecordsRequest( + ref=self.ref, + from_offset=from_offset, + max_records=max_records, + max_bytes=max_bytes, + wait=wait, + ) + handle = await _read_records(request, self.body_type) + return await handle + + async def read_pages( + self, + from_offset: bytes | None = None, + max_records: int | None = None, + wait: datetime.timedelta | None = None, + max_bytes: int | None = None, + ) -> collections.abc.AsyncGenerator[ReadRecordsResponse[BodyT], None]: + """Yield each response of ``read_page`` until the poll helper returns ``None``. + + Read one page of Records. The poll iterator keeps reading after a page with no + Record. + + Args: + from_offset: Read after this offset. Empty means from the beginning. + max_records: The maximum Records per page. Zero uses the configured default. + wait: Wait per page. Unset reads immediately, then iterators use a + one-minute wait. + max_bytes: Page byte target. A larger Record can exceed it within SDK hard + limits. + """ + request = ReadRecordsRequest( + ref=self.ref, + from_offset=from_offset, + max_records=max_records, + max_bytes=max_bytes, + wait=wait, + ) + while True: + handle = await _read_records(request, self.body_type) + response = await handle + next_request = _support.next_read_request(request, response) + yield response + if next_request is None: + return + request = next_request + + def read( + self, + from_offset: bytes | None = None, + max_records: int | None = None, + wait: datetime.timedelta | None = None, + max_bytes: int | None = None, + ) -> PollIterator[ReadRecordsRequest[BodyT], StreamRecord[BodyT]]: + """Yield each item of ``read_pages``, page by page. + + ``next_request`` resumes after the last item that the iterator yielded. It is + ``None`` when the page helper returns ``None``. + + Read one page of Records. The poll iterator keeps reading after a page with no + Record. + + Args: + from_offset: Read after this offset. Empty means from the beginning. + max_records: The maximum Records per page. Zero uses the configured default. + wait: Wait per page. Unset reads immediately, then iterators use a + one-minute wait. + max_bytes: Page byte target. A larger Record can exceed it within SDK hard + limits. + """ + request = ReadRecordsRequest( + ref=self.ref, + from_offset=from_offset, + max_records=max_records, + max_bytes=max_bytes, + wait=wait, + ) + return PollIterator( + request, + self.read_pages( + from_offset=from_offset, + max_records=max_records, + wait=wait, + max_bytes=max_bytes, + ), + lambda response: response.records, + _support.next_read_request, + _support.resume_read_request, + ) + + async def describe( + self, + ) -> DescribeStreamResponse: + """Return the newest offset of the Stream.""" + request = DescribeStreamRequest( + ref=self.ref, + ) + handle = await _describe_stream(request) + return await handle + + +@typing.overload +def get_stream( + ref: StreamRef[BodyT], + *, + created: bool | None = None, + body_type: None = None, +) -> Stream[BodyT]: ... + + +@typing.overload +def get_stream( + ref: StreamRef[BodyT] | StreamRef[object], + *, + created: bool | None = None, + body_type: type[BodyT], +) -> Stream[BodyT]: ... + + +def get_stream( + ref: StreamRef[typing.Any], + *, + created: bool | None = None, + body_type: typing.Any = None, +) -> Stream[typing.Any]: + """Return the ``Stream`` handle for this ref.""" + arguments = typing.get_args(getattr(ref, "__orig_class__", None)) + # None means no explicit type, so use the ref's type argument, else object. + if body_type is None: + body_type = arguments[0] if arguments else object + elif arguments and arguments[0] is not object and arguments[0] != body_type: + raise TypeError("The decoding type must match the typed ref") + if arguments != (body_type,): + ref = StreamRef[body_type](id=ref.id, store=ref.store) + return Stream[body_type]( + ref=ref, + created=created, + ) + + +async def _append_records( + request: AppendRecordsRequest[BodyT], +) -> temporalio.workflow.NexusOperationHandle[AppendRecordsResponse,]: + nexus_client = temporalio.workflow.create_nexus_client( + service="temporal.api.streamservice.v1.StreamService", + endpoint=temporalio.nexus.system.TEMPORAL_SYSTEM_ENDPOINT, + ) + return await nexus_client.start_operation( + operation="AppendRecords", + input=request, + output_type=AppendRecordsResponse, + ) + + +async def _read_records( + request: ReadRecordsRequest[BodyT], + body_type: type[BodyT], +) -> temporalio.workflow.NexusOperationHandle[ReadRecordsResponse[BodyT],]: + nexus_client = temporalio.workflow.create_nexus_client( + service="temporal.api.streamservice.v1.StreamService", + endpoint=temporalio.nexus.system.TEMPORAL_SYSTEM_ENDPOINT, + ) + return await nexus_client.start_operation( + operation="ReadRecords", + input=request, + output_type=ReadRecordsResponse[body_type], + ) + + +async def _describe_stream( + request: DescribeStreamRequest[BodyT], +) -> temporalio.workflow.NexusOperationHandle[DescribeStreamResponse,]: + nexus_client = temporalio.workflow.create_nexus_client( + service="temporal.api.streamservice.v1.StreamService", + endpoint=temporalio.nexus.system.TEMPORAL_SYSTEM_ENDPOINT, + ) + return await nexus_client.start_operation( + operation="DescribeStream", + input=request, + output_type=DescribeStreamResponse, + ) diff --git a/temporalio/nexus/system/stream_service/workflow/_system_nexus_interceptor.py b/temporalio/nexus/system/stream_service/workflow/_system_nexus_interceptor.py new file mode 100644 index 0000000000..11d737cede --- /dev/null +++ b/temporalio/nexus/system/stream_service/workflow/_system_nexus_interceptor.py @@ -0,0 +1,251 @@ +# Generated by nexgen v0.2.14. DO NOT EDIT! + +from __future__ import annotations + +import abc +import typing + +from .. import models + +if typing.TYPE_CHECKING: + import temporalio.workflow + from temporalio.worker._interceptor import StartNexusOperationInput + + +__all__ = [ + "_start_system_nexus_operation", + "_SystemNexusWorkflowOutboundInterceptorBase", + "_SystemNexusWorkflowOutboundInterceptorTerminal", +] + + +_InputT = typing.TypeVar("_InputT") +_OutputT = typing.TypeVar("_OutputT") + + +async def _start_system_nexus_operation( + interceptor: _SystemNexusWorkflowOutboundInterceptorBase, + input: StartNexusOperationInput[_InputT, _OutputT], +) -> temporalio.workflow.NexusOperationHandle[_OutputT]: + if ( + input.service == "temporal.api.streamservice.v1.StreamService" + and input.operation_name == "CreateStream" + ): + typed_input = typing.cast( + "StartNexusOperationInput[models.CreateStreamRequest[typing.Any], models.CreateStreamResult[typing.Any]]", + input, + ) + # The dispatch check above establishes that this operation's response type is _OutputT. + return typing.cast( + "temporalio.workflow.NexusOperationHandle[_OutputT]", + await interceptor.start_create_stream( + typed_input.input, typed_input.output_type + ), + ) + if ( + input.service == "temporal.api.streamservice.v1.StreamService" + and input.operation_name == "AppendRecords" + ): + typed_input = typing.cast( + "StartNexusOperationInput[models.AppendRecordsRequest[typing.Any], models.AppendRecordsResponse]", + input, + ) + # The dispatch check above establishes that this operation's response type is _OutputT. + return typing.cast( + "temporalio.workflow.NexusOperationHandle[_OutputT]", + await interceptor.start_append_records(typed_input.input), + ) + if ( + input.service == "temporal.api.streamservice.v1.StreamService" + and input.operation_name == "ReadRecords" + ): + typed_input = typing.cast( + "StartNexusOperationInput[models.ReadRecordsRequest[typing.Any], models.ReadRecordsResponse[typing.Any]]", + input, + ) + # The dispatch check above establishes that this operation's response type is _OutputT. + return typing.cast( + "temporalio.workflow.NexusOperationHandle[_OutputT]", + await interceptor.start_read_records( + typed_input.input, typed_input.output_type + ), + ) + if ( + input.service == "temporal.api.streamservice.v1.StreamService" + and input.operation_name == "DescribeStream" + ): + typed_input = typing.cast( + "StartNexusOperationInput[models.DescribeStreamRequest[typing.Any], models.DescribeStreamResponse]", + input, + ) + # The dispatch check above establishes that this operation's response type is _OutputT. + return typing.cast( + "temporalio.workflow.NexusOperationHandle[_OutputT]", + await interceptor.start_describe_stream(typed_input.input), + ) + raise ValueError( + f"unsupported System Nexus operation: {input.service}/{input.operation_name}" + ) + + +class _SystemNexusWorkflowOutboundInterceptorBase(abc.ABC): + @abc.abstractmethod + def _next_system_nexus_interceptor( + self, + ) -> _SystemNexusWorkflowOutboundInterceptorBase: ... + + async def start_create_stream( + self, + request: models.CreateStreamRequest[typing.Any], + output_type: type[models.CreateStreamResult[typing.Any]] | None = None, + ) -> temporalio.workflow.NexusOperationHandle[ + models.CreateStreamResult[typing.Any] + ]: + """Intercept the CreateStream operation.""" + return await self._next_system_nexus_interceptor().start_create_stream( + request, output_type + ) + + async def start_append_records( + self, request: models.AppendRecordsRequest[typing.Any] + ) -> temporalio.workflow.NexusOperationHandle[models.AppendRecordsResponse]: + """Intercept the AppendRecords operation.""" + return await self._next_system_nexus_interceptor().start_append_records(request) + + async def start_read_records( + self, + request: models.ReadRecordsRequest[typing.Any], + output_type: type[models.ReadRecordsResponse[typing.Any]] | None = None, + ) -> temporalio.workflow.NexusOperationHandle[ + models.ReadRecordsResponse[typing.Any] + ]: + """Intercept the ReadRecords operation.""" + return await self._next_system_nexus_interceptor().start_read_records( + request, output_type + ) + + async def start_describe_stream( + self, request: models.DescribeStreamRequest[typing.Any] + ) -> temporalio.workflow.NexusOperationHandle[models.DescribeStreamResponse]: + """Intercept the DescribeStream operation.""" + return await self._next_system_nexus_interceptor().start_describe_stream( + request + ) + + +class _SystemNexusWorkflowOutboundInterceptorTerminal(abc.ABC): + @abc.abstractmethod + async def _schedule_system_nexus_operation( + self, + input: StartNexusOperationInput[_InputT, _OutputT], + ) -> temporalio.workflow.NexusOperationHandle[_OutputT]: ... + + async def start_create_stream( + self, + request: models.CreateStreamRequest[typing.Any], + output_type: type[models.CreateStreamResult[typing.Any]] | None = None, + ) -> temporalio.workflow.NexusOperationHandle[ + models.CreateStreamResult[typing.Any] + ]: + from temporalio.nexus.system import TEMPORAL_SYSTEM_ENDPOINT + from temporalio.worker._interceptor import StartNexusOperationInput + from temporalio.workflow import NexusOperationCancellationType + + return await self._schedule_system_nexus_operation( + StartNexusOperationInput( + endpoint=TEMPORAL_SYSTEM_ENDPOINT, + service="temporal.api.streamservice.v1.StreamService", + operation="CreateStream", + input=request, + output_type=typing.cast( + "type[models.CreateStreamResult[typing.Any]]", + models.CreateStreamResult, + ) + if output_type is None + else output_type, + schedule_to_close_timeout=None, + schedule_to_start_timeout=None, + start_to_close_timeout=None, + cancellation_type=NexusOperationCancellationType.WAIT_COMPLETED, + headers=None, + summary=None, + ) + ) + + async def start_append_records( + self, request: models.AppendRecordsRequest[typing.Any] + ) -> temporalio.workflow.NexusOperationHandle[models.AppendRecordsResponse]: + from temporalio.nexus.system import TEMPORAL_SYSTEM_ENDPOINT + from temporalio.worker._interceptor import StartNexusOperationInput + from temporalio.workflow import NexusOperationCancellationType + + return await self._schedule_system_nexus_operation( + StartNexusOperationInput( + endpoint=TEMPORAL_SYSTEM_ENDPOINT, + service="temporal.api.streamservice.v1.StreamService", + operation="AppendRecords", + input=request, + output_type=models.AppendRecordsResponse, + schedule_to_close_timeout=None, + schedule_to_start_timeout=None, + start_to_close_timeout=None, + cancellation_type=NexusOperationCancellationType.WAIT_COMPLETED, + headers=None, + summary=None, + ) + ) + + async def start_read_records( + self, + request: models.ReadRecordsRequest[typing.Any], + output_type: type[models.ReadRecordsResponse[typing.Any]] | None = None, + ) -> temporalio.workflow.NexusOperationHandle[ + models.ReadRecordsResponse[typing.Any] + ]: + from temporalio.nexus.system import TEMPORAL_SYSTEM_ENDPOINT + from temporalio.worker._interceptor import StartNexusOperationInput + from temporalio.workflow import NexusOperationCancellationType + + return await self._schedule_system_nexus_operation( + StartNexusOperationInput( + endpoint=TEMPORAL_SYSTEM_ENDPOINT, + service="temporal.api.streamservice.v1.StreamService", + operation="ReadRecords", + input=request, + output_type=typing.cast( + "type[models.ReadRecordsResponse[typing.Any]]", + models.ReadRecordsResponse, + ) + if output_type is None + else output_type, + schedule_to_close_timeout=None, + schedule_to_start_timeout=None, + start_to_close_timeout=None, + cancellation_type=NexusOperationCancellationType.WAIT_COMPLETED, + headers=None, + summary=None, + ) + ) + + async def start_describe_stream( + self, request: models.DescribeStreamRequest[typing.Any] + ) -> temporalio.workflow.NexusOperationHandle[models.DescribeStreamResponse]: + from temporalio.nexus.system import TEMPORAL_SYSTEM_ENDPOINT + from temporalio.worker._interceptor import StartNexusOperationInput + from temporalio.workflow import NexusOperationCancellationType + + return await self._schedule_system_nexus_operation( + StartNexusOperationInput( + endpoint=TEMPORAL_SYSTEM_ENDPOINT, + service="temporal.api.streamservice.v1.StreamService", + operation="DescribeStream", + input=request, + output_type=models.DescribeStreamResponse, + schedule_to_close_timeout=None, + schedule_to_start_timeout=None, + start_to_close_timeout=None, + cancellation_type=NexusOperationCancellationType.WAIT_COMPLETED, + headers=None, + summary=None, + ) + ) diff --git a/temporalio/nexus/system/stream_service/workflow/operations/__init__.py b/temporalio/nexus/system/stream_service/workflow/operations/__init__.py new file mode 100644 index 0000000000..fd52fe93f3 --- /dev/null +++ b/temporalio/nexus/system/stream_service/workflow/operations/__init__.py @@ -0,0 +1,3 @@ +# Generated by nexgen v0.2.14. DO NOT EDIT! + +from __future__ import annotations diff --git a/temporalio/nexus/system/stream_service/workflow/operations/create_stream.py b/temporalio/nexus/system/stream_service/workflow/operations/create_stream.py new file mode 100644 index 0000000000..e800388793 --- /dev/null +++ b/temporalio/nexus/system/stream_service/workflow/operations/create_stream.py @@ -0,0 +1,83 @@ +# Generated by nexgen v0.2.14. DO NOT EDIT! + +from __future__ import annotations + +import typing + +import temporalio.nexus.system +import temporalio.nexus.system._support as _support +import temporalio.workflow + +from ...models import ( + CreateStreamRequest, + CreateStreamResult, + StreamIdConflictPolicy, + StreamRef, +) +from .._resources import Stream + +BodyT = typing.TypeVar("BodyT") + + +async def _create_stream( + request: CreateStreamRequest[BodyT], + body_type: type[BodyT], +) -> Stream[BodyT]: + nexus_client = temporalio.workflow.create_nexus_client( + service="temporal.api.streamservice.v1.StreamService", + endpoint=temporalio.nexus.system.TEMPORAL_SYSTEM_ENDPOINT, + ) + handle = await nexus_client.start_operation( + operation="CreateStream", + input=request, + output_type=CreateStreamResult[body_type], + ) + result = await handle + return _support.stream_from_create(result, nexus_client, body_type) + + +@typing.overload +async def create_stream( + *, + id: str, + store: str | None = None, + id_conflict_policy: StreamIdConflictPolicy | None = None, + body_type: type[BodyT], +) -> Stream[BodyT]: ... + + +@typing.overload +async def create_stream( + *, + id: str, + store: str | None = None, + id_conflict_policy: StreamIdConflictPolicy | None = None, + body_type: None = None, +) -> Stream[object]: ... + + +async def create_stream( + *, + id: str, + store: str | None = None, + id_conflict_policy: StreamIdConflictPolicy | None = None, + body_type: typing.Any = None, +) -> Stream[typing.Any]: + """ + Args: + id: The Stream id. It must not be empty. + store: If empty, the SDK uses its Store selector or the only registered Store. + id_conflict_policy: What the create does if the Stream already exists. + Unspecified means fail. + """ + if body_type is None: + body_type = typing.Any + stream_ref = StreamRef( + id=id, + store=store, + ) + request = CreateStreamRequest( + stream_ref=stream_ref, + id_conflict_policy=id_conflict_policy, + ) + return await _create_stream(request, body_type) diff --git a/temporalio/nexus/system/workflow_service/__init__.py b/temporalio/nexus/system/workflow_service/__init__.py index c249d52d1e..bb3cacad8b 100644 --- a/temporalio/nexus/system/workflow_service/__init__.py +++ b/temporalio/nexus/system/workflow_service/__init__.py @@ -1,4 +1,4 @@ -# Generated by nexgen v0.2.13. DO NOT EDIT! +# Generated by nexgen v0.2.14. DO NOT EDIT! from __future__ import annotations @@ -27,17 +27,24 @@ ] +_StorageTargetFactory = collections.abc.Callable[ + [_InputT], temporalio.converter.StorageDriverWorkflowInfo +] + + class _NexusOperationInfo(typing.Generic[_InputT, _OutputT]): def __init__( self, *, operation: nexusrpc.Operation[_InputT, _OutputT], serialization_context: _SerializationContextFactory[_InputT] | None = None, + storage_target: _StorageTargetFactory[_InputT] | None = None, ) -> None: self.operation: nexusrpc.Operation[_InputT, _OutputT] = operation self.serialization_context: _SerializationContextFactory[_InputT] | None = ( serialization_context ) + self.storage_target: _StorageTargetFactory[_InputT] | None = storage_target __nexus_operation_registry__: dict[ diff --git a/temporalio/nexus/system/workflow_service/_system_nexus_interceptor.py b/temporalio/nexus/system/workflow_service/_system_nexus_interceptor.py index 82b81c63a0..6a86df28f4 100644 --- a/temporalio/nexus/system/workflow_service/_system_nexus_interceptor.py +++ b/temporalio/nexus/system/workflow_service/_system_nexus_interceptor.py @@ -1,4 +1,4 @@ -# Generated by nexgen v0.2.13. DO NOT EDIT! +# Generated by nexgen v0.2.14. DO NOT EDIT! from __future__ import annotations diff --git a/temporalio/nexus/system/workflow_service/models.py b/temporalio/nexus/system/workflow_service/models.py index a17f83a296..b6472b0f65 100644 --- a/temporalio/nexus/system/workflow_service/models.py +++ b/temporalio/nexus/system/workflow_service/models.py @@ -1,4 +1,4 @@ -# Generated by nexgen v0.2.13. DO NOT EDIT! +# Generated by nexgen v0.2.14. DO NOT EDIT! from __future__ import annotations diff --git a/temporalio/nexus/system/workflow_service/operations/__init__.py b/temporalio/nexus/system/workflow_service/operations/__init__.py index c4e5635675..fd52fe93f3 100644 --- a/temporalio/nexus/system/workflow_service/operations/__init__.py +++ b/temporalio/nexus/system/workflow_service/operations/__init__.py @@ -1,3 +1,3 @@ -# Generated by nexgen v0.2.13. DO NOT EDIT! +# Generated by nexgen v0.2.14. DO NOT EDIT! from __future__ import annotations diff --git a/temporalio/nexus/system/workflow_service/operations/signal_with_start_workflow.py b/temporalio/nexus/system/workflow_service/operations/signal_with_start_workflow.py index 35f1e0934b..b697ace130 100644 --- a/temporalio/nexus/system/workflow_service/operations/signal_with_start_workflow.py +++ b/temporalio/nexus/system/workflow_service/operations/signal_with_start_workflow.py @@ -1,4 +1,4 @@ -# Generated by nexgen v0.2.13. DO NOT EDIT! +# Generated by nexgen v0.2.14. DO NOT EDIT! from __future__ import annotations diff --git a/temporalio/nexus/system/workflow_service/services.py b/temporalio/nexus/system/workflow_service/services.py index b9d6f3d943..46cdbf596a 100644 --- a/temporalio/nexus/system/workflow_service/services.py +++ b/temporalio/nexus/system/workflow_service/services.py @@ -1,4 +1,4 @@ -# Generated by nexgen v0.2.13. DO NOT EDIT! +# Generated by nexgen v0.2.14. DO NOT EDIT! from __future__ import annotations diff --git a/temporalio/workflow/__init__.py b/temporalio/workflow/__init__.py index c631fd88e8..60b02cc543 100644 --- a/temporalio/workflow/__init__.py +++ b/temporalio/workflow/__init__.py @@ -3,6 +3,10 @@ from __future__ import annotations # BEGIN GENERATED NEXUS SYSTEM EXPORTS +from temporalio.nexus.system.stream_service.workflow import ( + create_stream, + get_stream, +) from temporalio.nexus.system.workflow_service import ( signal_with_start_workflow, ) @@ -329,6 +333,8 @@ "ReturnType", "SelfType", # BEGIN GENERATED NEXUS SYSTEM __ALL__ + "create_stream", + "get_stream", "signal_with_start_workflow", # END GENERATED NEXUS SYSTEM __ALL__ ]