{{ message }}
Repository navigation
Expand file tree
/
Copy path_timeskipping.py
More file actions
372 lines (318 loc) · 14.2 KB
/
Copy path_timeskipping.py
File metadata and controls
372 lines (318 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
"""Per-workflow time-skipping API and testing helper."""
from __future__ import annotations
import uuid
from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from typing import Any
import google.protobuf.field_mask_pb2
import temporalio.api.common.v1
import temporalio.api.enums.v1.event_type_pb2 as _event_type
import temporalio.api.workflow.v1
import temporalio.api.workflowservice.v1
import temporalio.client
from temporalio.api.enums.v1.time_skipping_pb2 import FastForwardPollingResult
@dataclass(frozen=True)
class FastForwardConfig:
"""One-shot fast-forward within a :py:class:`TimeSkippingConfig`.
.. warning::
This API is experimental and unstable.
"""
id: str
"""Identifies this fast-forward for ``PollWorkflowExecutionTimeSkipping``."""
duration: timedelta
"""Advance the workflow's virtual time by this amount. Time skipping
auto-disables when the target time is reached."""
def _to_proto(self) -> temporalio.api.common.v1.FastForwardConfig:
proto = temporalio.api.common.v1.FastForwardConfig(id=self.id)
proto.duration.FromTimedelta(self.duration)
return proto
@dataclass(frozen=True)
class TimeSkippingConfig:
"""Per-workflow time skipping configuration.
.. warning::
This API is experimental and unstable.
"""
enabled: bool = True
"""Whether time skipping is enabled for the workflow."""
fast_forward_config: FastForwardConfig | None = None
"""One-shot fast-forward. ``None`` means skip unbounded until completion
(when :py:attr:`enabled` is true) or no skipping at all (when it is false)."""
disable_propagation: bool = False
"""If true, child workflows do not inherit the ``enabled`` flag. Virtual
start time inherits regardless."""
max_session_skip_count: int = 0
"""Max skips permitted within one time-skipping session (from when
skipping is enabled until it is disabled). Once reached, the server
auto-disables time skipping. Use ``0`` for server default."""
def __post_init__(self) -> None:
"""Validates that a fast-forward isn't configured with skipping off."""
if not self.enabled and self.fast_forward_config is not None:
raise ValueError("fast_forward_config cannot be set when enabled is False")
def _to_proto(self) -> temporalio.api.common.v1.TimeSkippingConfig:
proto = temporalio.api.common.v1.TimeSkippingConfig(
enabled=self.enabled,
disable_propagation=self.disable_propagation,
max_session_skip_count=self.max_session_skip_count,
)
if self.fast_forward_config is not None:
proto.fast_forward_config.CopyFrom(self.fast_forward_config._to_proto())
return proto
_TERMINAL_EVENT_TYPES = frozenset(
{
_event_type.EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED,
_event_type.EVENT_TYPE_WORKFLOW_EXECUTION_FAILED,
_event_type.EVENT_TYPE_WORKFLOW_EXECUTION_TIMED_OUT,
_event_type.EVENT_TYPE_WORKFLOW_EXECUTION_TERMINATED,
_event_type.EVENT_TYPE_WORKFLOW_EXECUTION_CANCELED,
_event_type.EVENT_TYPE_WORKFLOW_EXECUTION_CONTINUED_AS_NEW,
}
)
class TimeSkipper:
"""Client wrapper for per-workflow time skipping.
.. warning::
This API is experimental and unstable.
Wraps a client with an interceptor that stamps a ``TimeSkippingConfig``
on every workflow started through :py:attr:`client`. Use
:py:meth:`fast_forward` to advance a running workflow's virtual clock
(awaited the call to :py:meth:`fast_forward` waits for the fast-forward
to complete and the transition event to fire).
In tests, the same functionality is available via
:py:class:`WorkflowEnvironment.start_time_skipping_v2`. Use
``TimeSkipper`` directly outside test environments.
"""
def __init__(
self,
client: temporalio.client.Client,
*,
config: TimeSkippingConfig = TimeSkippingConfig(),
) -> None:
"""Create a time skipper.
Args:
client: Client to wrap. A cloned client is created; the original
is untouched.
config: Default config stamped on every workflow started via
:py:attr:`client`.
"""
self._config = config
self._ts_enabled = True
client_config = client.config()
client_config["interceptors"] = [
*client_config["interceptors"],
_TimeSkippingConfigInterceptor(self),
]
self._client = temporalio.client.Client(**client_config)
@property
def client(self) -> temporalio.client.Client:
"""Client that stamps time-skipping config on every started workflow."""
return self._client
@property
def config(self) -> TimeSkippingConfig:
"""Configuration applied to future start_workflow calls."""
return self._config
@config.setter
def config(self, value: TimeSkippingConfig) -> None:
self._config = value
async def fast_forward(
self,
handle: temporalio.client.WorkflowHandle[Any, Any],
duration: timedelta | float | None = None,
/,
) -> bool:
"""Issue a fast-forward on a workflow and wait for it to complete.
Sends an ``UpdateWorkflowExecutionOptions`` with the new
``TimeSkippingConfig``. For a bounded ``duration``, long-polls
``PollWorkflowExecutionTimeSkipping`` for completion, which
follows the workflow across multiple runs.
Args:
handle: Target workflow execution.
duration: One-shot advance by this amount (``timedelta`` or
seconds as a ``float``). If ``None``, enable unbounded
skipping and wait for the workflow to terminate.
Returns:
For a bounded ``duration``: True if the fast-forward completes,
False if the workflow chain terminates first. Raises
``RuntimeError`` if the fast-forward id is overridden by a later
fast-forward. For ``duration=None``: always False (there is no
fast-forward completion to observe; the call waits until the
workflow's terminal event).
"""
if duration is not None and not isinstance(duration, timedelta):
duration = timedelta(seconds=duration)
if duration is None:
return await self._wait_for_unbounded_fast_forward_completion(handle)
fast_forward_id = str(uuid.uuid4())
await self._update_time_skipping_config(
handle,
TimeSkippingConfig(
enabled=True,
fast_forward_config=FastForwardConfig(
id=fast_forward_id, duration=duration
),
disable_propagation=self._config.disable_propagation,
max_session_skip_count=self._config.max_session_skip_count,
),
)
return await self._poll_fast_forward_completion(handle, fast_forward_id)
async def _wait_for_unbounded_fast_forward_completion(
self,
handle: temporalio.client.WorkflowHandle[Any, Any],
) -> bool:
"""Enable unbounded time skipping and wait for the workflow to terminate.
There is no fast-forward id to poll on, so we watch history events
for a terminal event on the current run. Always returns False —
unbounded skipping has no completion event of its own; the wait
ends on the workflow's terminal event.
"""
await self._update_time_skipping_config(
handle,
TimeSkippingConfig(
enabled=True,
disable_propagation=self._config.disable_propagation,
max_session_skip_count=self._config.max_session_skip_count,
),
)
async for event in handle.fetch_history_events(wait_new_event=True):
if event.event_type in _TERMINAL_EVENT_TYPES:
return False
return False
async def _poll_fast_forward_completion(
self,
handle: temporalio.client.WorkflowHandle[Any, Any],
fast_forward_id: str,
) -> bool:
"""Long-poll for a bounded fast-forward to complete.
Passes ``run_id=""`` so the server resolves to the current run in
the chain (retry / CAN / cron) and follows the FF across the chain
boundary. Retries on server-side long-poll timeout until a
terminal poll result arrives.
"""
req = (
temporalio.api.workflowservice.v1.PollWorkflowExecutionTimeSkippingRequest(
namespace=self._client.namespace,
workflow_execution=temporalio.api.common.v1.WorkflowExecution(
workflow_id=handle.id,
run_id="",
),
fast_forward_id=fast_forward_id,
)
)
while True:
resp = await self._client.workflow_service.poll_workflow_execution_time_skipping(
req, retry=True
)
if (
resp.fast_forward_polling_result
== FastForwardPollingResult.FAST_FORWARD_POLLING_RESULT_FAST_FORWARD_COMPLETED
):
return True
if (
resp.fast_forward_polling_result
== FastForwardPollingResult.FAST_FORWARD_POLLING_RESULT_FAST_FORWARD_FAILED
):
# An ID mismatch means this fast-forward was overridden by a laster one,
# so raise in that case; otherwise, return False.
if "fast_forward_id does not match" in resp.failed_reason:
raise RuntimeError(
f"PollWorkflowExecutionTimeSkipping failed for id "
f"{fast_forward_id!r}: {resp.failed_reason}: overridden by a "
"later fast-forward."
)
return False
async def get_time_skipping_info(
self,
handle: temporalio.client.WorkflowHandle[Any, Any],
) -> temporalio.api.common.v1.TimeSkippingInfo | None:
"""Fetch a workflow's ``TimeSkippingInfo`` via ``DescribeWorkflowExecution``.
Returns ``None`` if time skipping has never been enabled on the
workflow.
"""
desc = await handle.describe()
ext = desc.raw_description.workflow_extended_info
if not ext.HasField("time_skipping_info"):
return None
return ext.time_skipping_info
async def get_current_time(
self,
handle: temporalio.client.WorkflowHandle[Any, Any],
) -> datetime:
"""Get a workflow's current virtual time.
Reads ``TimeSkippingInfo.current_time`` via
:py:meth:`get_time_skipping_info`. If time skipping has never been
enabled on the workflow, falls back to wall-clock time (the two
coincide when no skipping has ever happened).
"""
tsi = await self.get_time_skipping_info(handle)
if tsi is None:
return datetime.now(timezone.utc)
return tsi.current_time.ToDatetime().replace(tzinfo=timezone.utc)
async def _update_time_skipping_config(
self,
handle: temporalio.client.WorkflowHandle[Any, Any],
config: TimeSkippingConfig,
) -> temporalio.api.workflowservice.v1.UpdateWorkflowExecutionOptionsResponse:
"""Replace the stored time-skipping config for a running workflow.
The server accepts the whole ``TimeSkippingConfig`` field only, so
callers must send a complete config. Public callers should use
:py:meth:`fast_forward`.
"""
return await self._client.workflow_service.update_workflow_execution_options(
temporalio.api.workflowservice.v1.UpdateWorkflowExecutionOptionsRequest(
namespace=self._client.namespace,
workflow_execution=temporalio.api.common.v1.WorkflowExecution(
workflow_id=handle.id,
run_id=handle.run_id or "",
),
workflow_execution_options=temporalio.api.workflow.v1.WorkflowExecutionOptions(
time_skipping_config=config._to_proto(),
),
update_mask=google.protobuf.field_mask_pb2.FieldMask(
paths=["time_skipping_config"],
),
identity=self._client.identity,
),
retry=True,
)
@contextmanager
def with_time_skipping_disabled(self) -> Iterator[None]:
"""Suspend time-skipping config stamping on newly-started workflows within the block.
Workflows started via :py:attr:`client` inside the block do not get
their ``time_skipping_config`` set; existing workflows are unaffected.
"""
was_enabled = self._ts_enabled
self._ts_enabled = False
try:
yield None
finally:
self._ts_enabled = was_enabled
class _TimeSkippingConfigInterceptor(temporalio.client.Interceptor):
def __init__(self, skipper: TimeSkipper) -> None:
super().__init__()
self._skipper = skipper
def intercept_client(
self, next: temporalio.client.OutboundInterceptor
) -> temporalio.client.OutboundInterceptor:
return _TimeSkippingConfigOutbound(next, self._skipper)
class _TimeSkippingConfigOutbound(temporalio.client.OutboundInterceptor):
def __init__(
self,
next: temporalio.client.OutboundInterceptor,
skipper: TimeSkipper,
) -> None:
super().__init__(next)
self._skipper = skipper
async def start_workflow(
self, input: temporalio.client.StartWorkflowInput
) -> temporalio.client.WorkflowHandle[Any, Any]:
if self._skipper._ts_enabled:
input.time_skipping_config = self._skipper.config._to_proto()
return await super().start_workflow(input)
async def start_update_with_start_workflow(
self, input: temporalio.client.StartWorkflowUpdateWithStartInput
) -> temporalio.client.WorkflowUpdateHandle[Any]:
if self._skipper._ts_enabled:
input.start_workflow_input.time_skipping_config = (
self._skipper.config._to_proto()
)
return await super().start_update_with_start_workflow(input)
You can’t perform that action at this time.
