-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathcontext.py
More file actions
635 lines (546 loc) · 22.6 KB
/
context.py
File metadata and controls
635 lines (546 loc) · 22.6 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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
from __future__ import annotations
import hashlib
import logging
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Concatenate, Generic, ParamSpec, TypeVar
from aws_durable_execution_sdk_python.config import (
BatchedInput,
CallbackConfig,
ChildConfig,
Duration,
InvokeConfig,
MapConfig,
ParallelConfig,
StepConfig,
WaitForCallbackConfig,
)
from aws_durable_execution_sdk_python.exceptions import (
CallbackError,
SuspendExecution,
ValidationError,
)
from aws_durable_execution_sdk_python.identifier import OperationIdentifier
from aws_durable_execution_sdk_python.lambda_service import OperationSubType
from aws_durable_execution_sdk_python.logger import Logger, LogInfo
from aws_durable_execution_sdk_python.operation.callback import (
CallbackOperationExecutor,
wait_for_callback_handler,
)
from aws_durable_execution_sdk_python.operation.child import child_handler
from aws_durable_execution_sdk_python.operation.invoke import InvokeOperationExecutor
from aws_durable_execution_sdk_python.operation.map import map_handler
from aws_durable_execution_sdk_python.operation.parallel import parallel_handler
from aws_durable_execution_sdk_python.operation.step import StepOperationExecutor
from aws_durable_execution_sdk_python.operation.wait import WaitOperationExecutor
from aws_durable_execution_sdk_python.operation.wait_for_condition import (
WaitForConditionOperationExecutor,
)
from aws_durable_execution_sdk_python.serdes import (
PassThroughSerDes,
SerDes,
deserialize,
)
from aws_durable_execution_sdk_python.state import ExecutionState # noqa: TCH001
from aws_durable_execution_sdk_python.threading import OrderedCounter
from aws_durable_execution_sdk_python.types import (
BatchResult,
LoggerInterface,
StepContext,
WaitForCallbackContext,
WaitForConditionCheckContext,
)
from aws_durable_execution_sdk_python.types import Callback as CallbackProtocol
from aws_durable_execution_sdk_python.types import (
DurableContext as DurableContextProtocol,
)
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
from aws_durable_execution_sdk_python.state import CheckpointedResult
from aws_durable_execution_sdk_python.types import LambdaContext
from aws_durable_execution_sdk_python.waits import WaitForConditionConfig
P = TypeVar("P") # Payload type
R = TypeVar("R") # Result type
T = TypeVar("T")
U = TypeVar("U")
Params = ParamSpec("Params")
logger = logging.getLogger(__name__)
PASS_THROUGH_SERDES: SerDes[Any] = PassThroughSerDes()
@dataclass(frozen=True)
class ExecutionContext:
"""Readonly metadata about the current durable execution context.
This class provides immutable access to execution-level metadata.
Attributes:
durable_execution_arn: The Amazon Resource Name (ARN) of the current
durable execution.
"""
durable_execution_arn: str
def durable_step(
func: Callable[Concatenate[StepContext, Params], T],
) -> Callable[Params, Callable[[StepContext], T]]:
"""Wrap your callable into a named function that a Durable step can run."""
def wrapper(*args, **kwargs):
def function_with_arguments(context: StepContext):
return func(context, *args, **kwargs)
function_with_arguments._original_name = func.__name__ # noqa: SLF001
return function_with_arguments
return wrapper
def durable_with_child_context(
func: Callable[Concatenate[DurableContext, Params], T],
) -> Callable[Params, Callable[[DurableContext], T]]:
"""Wrap your callable into a Durable child context."""
def wrapper(*args, **kwargs):
def function_with_arguments(child_context: DurableContext):
return func(child_context, *args, **kwargs)
function_with_arguments._original_name = func.__name__ # noqa: SLF001
return function_with_arguments
return wrapper
def durable_wait_for_callback(
func: Callable[Concatenate[str, WaitForCallbackContext, Params], T],
) -> Callable[Params, Callable[[str, WaitForCallbackContext], T]]:
"""Wrap your callable into a wait_for_callback submitter function.
This decorator allows you to define a submitter function with additional
parameters that will be bound when called.
Args:
func: A callable that takes callback_id, context, and additional parameters
Returns:
A wrapper function that binds the additional parameters and returns
a submitter function compatible with wait_for_callback
Example:
@durable_wait_for_callback
def submit_to_external_system(
callback_id: str,
context: WaitForCallbackContext,
task_name: str,
priority: int
):
context.logger.info(f"Submitting {task_name} with callback {callback_id}")
external_api.submit_task(
task_name=task_name,
priority=priority,
callback_id=callback_id
)
# Usage in durable handler:
result = context.wait_for_callback(
submit_to_external_system("my_task", priority=5)
)
"""
def wrapper(*args, **kwargs):
def submitter_with_arguments(callback_id: str, context: WaitForCallbackContext):
return func(callback_id, context, *args, **kwargs)
submitter_with_arguments._original_name = func.__name__ # noqa: SLF001
return submitter_with_arguments
return wrapper
class Callback(Generic[T], CallbackProtocol[T]): # noqa: PYI059
"""A future that will block on result() until callback_id returns."""
def __init__(
self,
callback_id: str,
operation_id: str,
state: ExecutionState,
serdes: SerDes[T] | None = None,
):
self.callback_id: str = callback_id
self.operation_id: str = operation_id
self.state: ExecutionState = state
self.serdes: SerDes[T] | None = serdes
def result(self) -> T | None:
"""Return the result of the future. Will block until result is available.
This will suspend the current execution while waiting for the result to
become available. Durable Functions will replay the execution once the
result is ready, and proceed when it reaches the .result() call.
Use the callback id with the following APIs to send back the result, error or
heartbeats: SendDurableExecutionCallbackSuccess, SendDurableExecutionCallbackFailure
and SendDurableExecutionCallbackHeartbeat.
"""
checkpointed_result: CheckpointedResult = self.state.get_checkpoint_result(
self.operation_id
)
if not checkpointed_result.is_existent():
msg = "Callback operation must exist"
raise CallbackError(message=msg, callback_id=self.callback_id)
if (
checkpointed_result.is_failed()
or checkpointed_result.is_cancelled()
or checkpointed_result.is_timed_out()
or checkpointed_result.is_stopped()
):
msg = (
checkpointed_result.error.message
if checkpointed_result.error and checkpointed_result.error.message
else "Callback failed"
)
raise CallbackError(message=msg, callback_id=self.callback_id)
if checkpointed_result.is_succeeded():
if checkpointed_result.result is None:
return None # type: ignore
return deserialize(
serdes=self.serdes if self.serdes is not None else PASS_THROUGH_SERDES,
data=checkpointed_result.result,
operation_id=self.operation_id,
durable_execution_arn=self.state.durable_execution_arn,
)
# operation exists; it has not terminated (successfully or otherwise)
# therefore we should wait
msg = "Callback result not received yet. Suspending execution while waiting for result."
raise SuspendExecution(msg)
class DurableContext(DurableContextProtocol):
def __init__(
self,
state: ExecutionState,
execution_context: ExecutionContext,
lambda_context: LambdaContext | None = None,
parent_id: str | None = None,
logger: Logger | None = None,
) -> None:
self.state: ExecutionState = state
self.execution_context: ExecutionContext = execution_context
self.lambda_context = lambda_context
self._parent_id: str | None = parent_id
self._step_counter: OrderedCounter = OrderedCounter()
log_info = LogInfo(
execution_state=state,
parent_id=parent_id,
)
self._log_info = log_info
self.logger: Logger = logger or Logger.from_log_info(
logger=logging.getLogger(),
info=log_info,
)
# region factories
@staticmethod
def from_lambda_context(
state: ExecutionState,
lambda_context: LambdaContext,
):
return DurableContext(
state=state,
execution_context=ExecutionContext(
durable_execution_arn=state.durable_execution_arn
),
lambda_context=lambda_context,
parent_id=None,
)
def create_child_context(self, parent_id: str) -> DurableContext:
"""Create a child context from the given parent."""
logger.debug("Creating child context for parent %s", parent_id)
return DurableContext(
state=self.state,
execution_context=self.execution_context,
lambda_context=self.lambda_context,
parent_id=parent_id,
logger=self.logger.with_log_info(
LogInfo(
execution_state=self.state,
parent_id=parent_id,
)
),
)
# endregion factories
@staticmethod
def _resolve_step_name(name: str | None, func: Callable) -> str | None:
"""Resolve the step name.
Returns:
str | None: The provided name, and if that doesn't exist the callable function's name if it has one.
"""
# callable's name will override name if name is falsy ('' or None)
return name or getattr(func, "_original_name", None)
def set_logger(self, new_logger: LoggerInterface):
"""Set the logger for the current context."""
self.logger = Logger.from_log_info(
logger=new_logger,
info=self._log_info,
)
def _create_step_id_for_logical_step(self, step: int) -> str:
"""
Generate a step_id based on the given logical step.
This allows us to recover operation ids or even look
forward without changing the internal state of this context.
"""
step_id = f"{self._parent_id}-{step}" if self._parent_id else str(step)
return hashlib.blake2b(step_id.encode()).hexdigest()[:64]
def _create_step_id(self) -> str:
"""Generate a thread-safe step id, incrementing in order of invocation.
This method is an internal implementation detail. Do not rely the exact format of
the id generated by this method. It is subject to change without notice.
"""
new_counter: int = self._step_counter.increment()
return self._create_step_id_for_logical_step(new_counter)
# region Operations
def create_callback(
self, name: str | None = None, config: CallbackConfig | None = None
) -> Callback:
"""Create a callback.
This generates a future with a callback id. External systems can signal
your Durable Function to proceed by using this callback id with the
SendDurableExecutionCallbackSuccess, SendDurableExecutionCallbackFailure and
SendDurableExecutionCallbackHeartbeat APIs.
Args:
name (str): Optional name for the operation.
config (CallbackConfig): Configuration for the callback.
Return:
Callback future. Use result() on this future to wait for the callback resuilt.
"""
if not config:
config = CallbackConfig()
operation_id: str = self._create_step_id()
executor: CallbackOperationExecutor = CallbackOperationExecutor(
state=self.state,
operation_identifier=OperationIdentifier(
operation_id=operation_id, parent_id=self._parent_id, name=name
),
config=config,
)
callback_id: str = executor.process()
result: Callback = Callback(
callback_id=callback_id,
operation_id=operation_id,
state=self.state,
serdes=config.serdes,
)
self.state.track_replay(operation_id=operation_id)
return result
def invoke(
self,
function_name: str,
payload: P,
name: str | None = None,
config: InvokeConfig[P, R] | None = None,
) -> R:
"""Invoke another Durable Function.
Args:
function_name: Name of the function to invoke
payload: Input payload to send to the function
name: Optional name for the operation
config: Optional configuration for the invoke operation
Returns:
The result of the invoked function
"""
if not config:
config = InvokeConfig[P, R]()
operation_id = self._create_step_id()
executor: InvokeOperationExecutor[R] = InvokeOperationExecutor(
function_name=function_name,
payload=payload,
state=self.state,
operation_identifier=OperationIdentifier(
operation_id=operation_id,
parent_id=self._parent_id,
name=name,
),
config=config,
)
result: R = executor.process()
self.state.track_replay(operation_id=operation_id)
return result
def map(
self,
inputs: Sequence[U],
func: Callable[[DurableContext, U | BatchedInput[Any, U], int, Sequence[U]], T],
name: str | None = None,
config: MapConfig | None = None,
) -> BatchResult[R]:
"""Execute a callable for each item in parallel."""
map_name: str | None = self._resolve_step_name(name, func)
operation_id = self._create_step_id()
operation_identifier = OperationIdentifier(
operation_id=operation_id, parent_id=self._parent_id, name=map_name
)
map_context = self.create_child_context(parent_id=operation_id)
def map_in_child_context() -> BatchResult[R]:
# map_context is a child_context of the context upon which `.map`
# was called. We are calling it `map_context` to make it explicit
# that any operations happening from hereon are done on the context
# that owns the branches
return map_handler(
items=inputs,
func=func,
config=config,
execution_state=self.state,
map_context=map_context,
operation_identifier=operation_identifier,
)
result: BatchResult[R] = child_handler(
func=map_in_child_context,
state=self.state,
operation_identifier=operation_identifier,
config=ChildConfig(
sub_type=OperationSubType.MAP,
serdes=getattr(config, "serdes", None),
# child_handler should only know the serdes of the parent serdes,
# the item serdes will be passed when we are actually executing
# the branch within its own child_handler.
item_serdes=None,
),
)
self.state.track_replay(operation_id=operation_id)
return result
def parallel(
self,
functions: Sequence[Callable[[DurableContext], T]],
name: str | None = None,
config: ParallelConfig | None = None,
) -> BatchResult[T]:
"""Execute multiple callables in parallel."""
# _create_step_id() is thread-safe. rest of method is safe, since using local copy of parent id
operation_id = self._create_step_id()
parallel_context = self.create_child_context(parent_id=operation_id)
operation_identifier = OperationIdentifier(
operation_id=operation_id, parent_id=self._parent_id, name=name
)
def parallel_in_child_context() -> BatchResult[T]:
# parallel_context is a child_context of the context upon which `.map`
# was called. We are calling it `parallel_context` to make it explicit
# that any operations happening from hereon are done on the context
# that owns the branches
return parallel_handler(
callables=functions,
config=config,
execution_state=self.state,
parallel_context=parallel_context,
operation_identifier=operation_identifier,
)
result: BatchResult[T] = child_handler(
func=parallel_in_child_context,
state=self.state,
operation_identifier=operation_identifier,
config=ChildConfig(
sub_type=OperationSubType.PARALLEL,
serdes=getattr(config, "serdes", None),
# child_handler should only know the serdes of the parent serdes,
# the item serdes will be passed when we are actually executing
# the branch within its own child_handler.
item_serdes=None,
),
)
self.state.track_replay(operation_id=operation_id)
return result
def run_in_child_context(
self,
func: Callable[[DurableContext], T],
name: str | None = None,
config: ChildConfig | None = None,
) -> T:
"""Run the callable and pass a child context to it.
Use this to nest and group operations.
Args:
callable (Callable[[DurableContext], T]): Run this callable and pass the child context as the argument to it.
name (str | None): name for the operation.
config (ChildConfig | None = None): c
Returns:
T: The result of the callable.
"""
step_name: str | None = self._resolve_step_name(name, func)
# _create_step_id() is thread-safe. rest of method is safe, since using local copy of parent id
operation_id = self._create_step_id()
def callable_with_child_context():
return func(self.create_child_context(parent_id=operation_id))
result: T = child_handler(
func=callable_with_child_context,
state=self.state,
operation_identifier=OperationIdentifier(
operation_id=operation_id, parent_id=self._parent_id, name=step_name
),
config=config,
)
self.state.track_replay(operation_id=operation_id)
return result
def step(
self,
func: Callable[[StepContext], T],
name: str | None = None,
config: StepConfig | None = None,
) -> T:
step_name = self._resolve_step_name(name, func)
logger.debug("Step name: %s", step_name)
if not config:
config = StepConfig()
operation_id = self._create_step_id()
executor: StepOperationExecutor[T] = StepOperationExecutor(
func=func,
config=config,
state=self.state,
operation_identifier=OperationIdentifier(
operation_id=operation_id,
parent_id=self._parent_id,
name=step_name,
),
context_logger=self.logger,
)
result: T = executor.process()
self.state.track_replay(operation_id=operation_id)
return result
def wait(self, duration: Duration, name: str | None = None) -> None:
"""Wait for a specified amount of time.
Args:
duration: Duration to wait
name: Optional name for the wait step
"""
seconds = duration.to_seconds()
if seconds < 1:
msg = "duration must be at least 1 second"
raise ValidationError(msg)
operation_id = self._create_step_id()
wait_seconds = duration.seconds
executor: WaitOperationExecutor = WaitOperationExecutor(
seconds=wait_seconds,
state=self.state,
operation_identifier=OperationIdentifier(
operation_id=operation_id,
parent_id=self._parent_id,
name=name,
),
)
executor.process()
self.state.track_replay(operation_id=operation_id)
def wait_for_callback(
self,
submitter: Callable[[str, WaitForCallbackContext], None],
name: str | None = None,
config: WaitForCallbackConfig | None = None,
) -> Any:
step_name: str | None = self._resolve_step_name(name, submitter)
logger.debug("wait_for_callback name: %s", step_name)
def wait_in_child_context(context: DurableContext):
return wait_for_callback_handler(context, submitter, step_name, config)
return self.run_in_child_context(
wait_in_child_context,
step_name,
)
def wait_for_condition(
self,
check: Callable[[T, WaitForConditionCheckContext], T],
config: WaitForConditionConfig[T],
name: str | None = None,
) -> T:
"""Wait for a condition to be met by polling.
Args:
check (Callable[[T, WaitForConditionCheckContext], T]): Function that checks the condition and returns updated state
config (WaitForConditionConfig[T]): Configuration including wait strategy and initial state
name (str | None): Optional name for the operation
Returns:
The final state when condition is met.
"""
if check is None:
msg = "`check` is required for wait_for_condition"
raise ValidationError(msg)
if not config:
msg = "`config` is required for wait_for_condition"
raise ValidationError(msg)
operation_id = self._create_step_id()
executor: WaitForConditionOperationExecutor[T] = (
WaitForConditionOperationExecutor(
check=check,
config=config,
state=self.state,
operation_identifier=OperationIdentifier(
operation_id=operation_id,
parent_id=self._parent_id,
name=name,
),
context_logger=self.logger,
)
)
result: T = executor.process()
self.state.track_replay(operation_id=operation_id)
return result
# endregion Operations