-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrunner.py
More file actions
489 lines (411 loc) · 17.5 KB
/
runner.py
File metadata and controls
489 lines (411 loc) · 17.5 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
from __future__ import annotations
import json
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Concatenate, ParamSpec, Protocol, TypeVar, cast
from aws_durable_execution_sdk_python.execution import (
InvocationStatus,
durable_handler,
)
from aws_durable_execution_sdk_python.lambda_service import (
ErrorObject,
OperationStatus,
OperationSubType,
OperationType,
)
from aws_durable_execution_sdk_python.lambda_service import Operation as SvcOperation
from aws_durable_execution_sdk_python_testing.checkpoint.processor import (
CheckpointProcessor,
)
from aws_durable_execution_sdk_python_testing.client import InMemoryServiceClient
from aws_durable_execution_sdk_python_testing.exceptions import (
DurableFunctionsTestError,
)
from aws_durable_execution_sdk_python_testing.executor import Executor
from aws_durable_execution_sdk_python_testing.invoker import InProcessInvoker
from aws_durable_execution_sdk_python_testing.model import (
StartDurableExecutionInput,
StartDurableExecutionOutput,
)
from aws_durable_execution_sdk_python_testing.scheduler import Scheduler
from aws_durable_execution_sdk_python_testing.store import InMemoryExecutionStore
if TYPE_CHECKING:
import datetime
from collections.abc import Callable, MutableMapping
from aws_durable_execution_sdk_python.context import DurableContext
from aws_durable_execution_sdk_python.execution import InvocationStatus
from aws_durable_execution_sdk_python_testing.execution import Execution
@dataclass(frozen=True)
class Operation:
operation_id: str
operation_type: OperationType
status: OperationStatus
parent_id: str | None = field(default=None, kw_only=True)
name: str | None = field(default=None, kw_only=True)
sub_type: OperationSubType | None = field(default=None, kw_only=True)
start_timestamp: datetime.datetime | None = field(default=None, kw_only=True)
end_timestamp: datetime.datetime | None = field(default=None, kw_only=True)
T = TypeVar("T", bound=Operation)
P = ParamSpec("P")
class OperationFactory(Protocol):
@staticmethod
def from_svc_operation(
operation: SvcOperation, all_operations: list[SvcOperation] | None = None
) -> Operation: ...
@dataclass(frozen=True)
class ExecutionOperation(Operation):
input_payload: str | None = None
@staticmethod
def from_svc_operation(
operation: SvcOperation,
all_operations: list[SvcOperation] | None = None, # noqa: ARG004
) -> ExecutionOperation:
if operation.operation_type != OperationType.EXECUTION:
msg: str = f"Expected EXECUTION operation, got {operation.operation_type}"
raise ValueError(msg)
return ExecutionOperation(
operation_id=operation.operation_id,
operation_type=operation.operation_type,
status=operation.status,
parent_id=operation.parent_id,
name=operation.name,
sub_type=operation.sub_type,
start_timestamp=operation.start_timestamp,
end_timestamp=operation.end_timestamp,
input_payload=(
operation.execution_details.input_payload
if operation.execution_details
else None
),
)
@dataclass(frozen=True)
class ContextOperation(Operation):
child_operations: list[Operation]
result: Any = None
error: ErrorObject | None = None
@staticmethod
def from_svc_operation(
operation: SvcOperation, all_operations: list[SvcOperation] | None = None
) -> ContextOperation:
if operation.operation_type != OperationType.CONTEXT:
msg: str = f"Expected CONTEXT operation, got {operation.operation_type}"
raise ValueError(msg)
child_operations = []
if all_operations:
child_operations = [
create_operation(op, all_operations)
for op in all_operations
if op.parent_id == operation.operation_id
]
return ContextOperation(
operation_id=operation.operation_id,
operation_type=operation.operation_type,
status=operation.status,
parent_id=operation.parent_id,
name=operation.name,
sub_type=operation.sub_type,
start_timestamp=operation.start_timestamp,
end_timestamp=operation.end_timestamp,
child_operations=child_operations,
result=(
json.loads(operation.context_details.result)
if operation.context_details and operation.context_details.result
else None
),
error=operation.context_details.error
if operation.context_details
else None,
)
def get_operation_by_name(self, name: str) -> Operation:
for operation in self.child_operations:
if operation.name == name:
return operation
msg: str = f"Child Operation with name '{name}' not found"
raise DurableFunctionsTestError(msg)
def get_step(self, name: str) -> StepOperation:
return cast(StepOperation, self.get_operation_by_name(name))
def get_wait(self, name: str) -> WaitOperation:
return cast(WaitOperation, self.get_operation_by_name(name))
def get_context(self, name: str) -> ContextOperation:
return cast(ContextOperation, self.get_operation_by_name(name))
def get_callback(self, name: str) -> CallbackOperation:
return cast(CallbackOperation, self.get_operation_by_name(name))
def get_invoke(self, name: str) -> InvokeOperation:
return cast(InvokeOperation, self.get_operation_by_name(name))
def get_execution(self, name: str) -> ExecutionOperation:
return cast(ExecutionOperation, self.get_operation_by_name(name))
@dataclass(frozen=True)
class StepOperation(ContextOperation):
attempt: int = 0
next_attempt_timestamp: str | None = None
result: Any = None
error: ErrorObject | None = None
@staticmethod
def from_svc_operation(
operation: SvcOperation, all_operations: list[SvcOperation] | None = None
) -> StepOperation:
if operation.operation_type != OperationType.STEP:
msg: str = f"Expected STEP operation, got {operation.operation_type}"
raise ValueError(msg)
child_operations = []
if all_operations:
child_operations = [
create_operation(op, all_operations)
for op in all_operations
if op.parent_id == operation.operation_id
]
return StepOperation(
operation_id=operation.operation_id,
operation_type=operation.operation_type,
status=operation.status,
parent_id=operation.parent_id,
name=operation.name,
sub_type=operation.sub_type,
start_timestamp=operation.start_timestamp,
end_timestamp=operation.end_timestamp,
child_operations=child_operations,
attempt=operation.step_details.attempt if operation.step_details else 0,
next_attempt_timestamp=(
operation.step_details.next_attempt_timestamp
if operation.step_details
else None
),
result=(
json.loads(operation.step_details.result)
if operation.step_details and operation.step_details.result
else None
),
error=operation.step_details.error if operation.step_details else None,
)
@dataclass(frozen=True)
class WaitOperation(Operation):
scheduled_timestamp: datetime.datetime | None = None
@staticmethod
def from_svc_operation(
operation: SvcOperation,
all_operations: list[SvcOperation] | None = None, # noqa: ARG004
) -> WaitOperation:
if operation.operation_type != OperationType.WAIT:
msg: str = f"Expected WAIT operation, got {operation.operation_type}"
raise ValueError(msg)
return WaitOperation(
operation_id=operation.operation_id,
operation_type=operation.operation_type,
status=operation.status,
parent_id=operation.parent_id,
name=operation.name,
sub_type=operation.sub_type,
start_timestamp=operation.start_timestamp,
end_timestamp=operation.end_timestamp,
scheduled_timestamp=(
operation.wait_details.scheduled_timestamp
if operation.wait_details
else None
),
)
@dataclass(frozen=True)
class CallbackOperation(ContextOperation):
callback_id: str | None = None
result: Any = None
error: ErrorObject | None = None
@staticmethod
def from_svc_operation(
operation: SvcOperation, all_operations: list[SvcOperation] | None = None
) -> CallbackOperation:
if operation.operation_type != OperationType.CALLBACK:
msg: str = f"Expected CALLBACK operation, got {operation.operation_type}"
raise ValueError(msg)
child_operations = []
if all_operations:
child_operations = [
create_operation(op, all_operations)
for op in all_operations
if op.parent_id == operation.operation_id
]
return CallbackOperation(
operation_id=operation.operation_id,
operation_type=operation.operation_type,
status=operation.status,
parent_id=operation.parent_id,
name=operation.name,
sub_type=operation.sub_type,
start_timestamp=operation.start_timestamp,
end_timestamp=operation.end_timestamp,
child_operations=child_operations,
callback_id=(
operation.callback_details.callback_id
if operation.callback_details
else None
),
result=(
json.loads(operation.callback_details.result)
if operation.callback_details and operation.callback_details.result
else None
),
error=operation.callback_details.error
if operation.callback_details
else None,
)
@dataclass(frozen=True)
class InvokeOperation(Operation):
durable_execution_arn: str | None = None
result: Any = None
error: ErrorObject | None = None
@staticmethod
def from_svc_operation(
operation: SvcOperation,
all_operations: list[SvcOperation] | None = None, # noqa: ARG004
) -> InvokeOperation:
if operation.operation_type != OperationType.INVOKE:
msg: str = f"Expected INVOKE operation, got {operation.operation_type}"
raise ValueError(msg)
return InvokeOperation(
operation_id=operation.operation_id,
operation_type=operation.operation_type,
status=operation.status,
parent_id=operation.parent_id,
name=operation.name,
sub_type=operation.sub_type,
start_timestamp=operation.start_timestamp,
end_timestamp=operation.end_timestamp,
durable_execution_arn=(
operation.invoke_details.durable_execution_arn
if operation.invoke_details
else None
),
result=(
json.loads(operation.invoke_details.result)
if operation.invoke_details and operation.invoke_details.result
else None
),
error=operation.invoke_details.error if operation.invoke_details else None,
)
OPERATION_FACTORIES: MutableMapping[OperationType, type[OperationFactory]] = {
OperationType.EXECUTION: ExecutionOperation,
OperationType.CONTEXT: ContextOperation,
OperationType.STEP: StepOperation,
OperationType.WAIT: WaitOperation,
OperationType.INVOKE: InvokeOperation,
OperationType.CALLBACK: CallbackOperation,
}
def create_operation(
svc_operation: SvcOperation, all_operations: list[SvcOperation] | None = None
) -> Operation:
operation_class: type[OperationFactory] | None = OPERATION_FACTORIES.get(
svc_operation.operation_type
)
if not operation_class:
msg: str = f"Unknown operation type: {svc_operation.operation_type}"
raise DurableFunctionsTestError(msg)
return operation_class.from_svc_operation(svc_operation, all_operations)
@dataclass(frozen=True)
class DurableFunctionTestResult:
status: InvocationStatus
operations: list[Operation]
result: Any = None
error: ErrorObject | None = None
@classmethod
def create(cls, execution: Execution) -> DurableFunctionTestResult:
operations = []
for operation in execution.operations:
if operation.operation_type is OperationType.EXECUTION:
# don't want the EXECUTION operations in the list test code asserts against
continue
if operation.parent_id is None:
operations.append(create_operation(operation, execution.operations))
if execution.result is None:
msg: str = "Execution result must exist to create test result."
raise DurableFunctionsTestError(msg)
deserialized_result = (
json.loads(execution.result.result) if execution.result.result else None
)
return cls(
status=execution.result.status,
operations=operations,
result=deserialized_result,
error=execution.result.error,
)
def get_operation_by_name(self, name: str) -> Operation:
for operation in self.operations:
if operation.name == name:
return operation
msg: str = f"Operation with name '{name}' not found"
raise DurableFunctionsTestError(msg)
def get_step(self, name: str) -> StepOperation:
return cast(StepOperation, self.get_operation_by_name(name))
def get_wait(self, name: str) -> WaitOperation:
return cast(WaitOperation, self.get_operation_by_name(name))
def get_context(self, name: str) -> ContextOperation:
return cast(ContextOperation, self.get_operation_by_name(name))
def get_callback(self, name: str) -> CallbackOperation:
return cast(CallbackOperation, self.get_operation_by_name(name))
def get_invoke(self, name: str) -> InvokeOperation:
return cast(InvokeOperation, self.get_operation_by_name(name))
def get_execution(self, name: str) -> ExecutionOperation:
return cast(ExecutionOperation, self.get_operation_by_name(name))
class DurableFunctionTestRunner:
def __init__(self, handler: Callable):
self._scheduler: Scheduler = Scheduler()
self._scheduler.start()
self._store = InMemoryExecutionStore()
self._checkpoint_processor = CheckpointProcessor(
store=self._store, scheduler=self._scheduler
)
self._service_client = InMemoryServiceClient(self._checkpoint_processor)
self._invoker = InProcessInvoker(handler, self._service_client)
self._executor = Executor(
store=self._store, scheduler=self._scheduler, invoker=self._invoker
)
# Wire up observer pattern - CheckpointProcessor uses this to notify executor of state changes
self._checkpoint_processor.add_execution_observer(self._executor)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def close(self):
self._scheduler.stop()
def run(
self,
input: str | None = None, # noqa: A002
timeout: int = 900,
function_name: str = "test-function",
execution_name: str = "execution-name",
account_id: str = "123456789012",
) -> DurableFunctionTestResult:
start_input = StartDurableExecutionInput(
account_id=account_id,
function_name=function_name,
function_qualifier="$LATEST",
execution_name=execution_name,
execution_timeout_seconds=timeout,
execution_retention_period_days=7,
invocation_id="inv-12345678-1234-1234-1234-123456789012",
trace_fields={"trace_id": "abc123", "span_id": "def456"},
tenant_id="tenant-001",
input=input,
)
output: StartDurableExecutionOutput = self._executor.start_execution(
start_input
)
if output.execution_arn is None:
msg_arn: str = "Execution ARN must exist to run test."
raise DurableFunctionsTestError(msg_arn)
# Block until completion
completed = self._executor.wait_until_complete(output.execution_arn, timeout)
if not completed:
msg_timeout: str = "Execution did not complete within timeout"
raise TimeoutError(msg_timeout)
execution: Execution = self._store.load(output.execution_arn)
return DurableFunctionTestResult.create(execution=execution)
class DurableChildContextTestRunner(DurableFunctionTestRunner):
"""Test a durable block, annotated with @durable_with_child_context, in isolation."""
def __init__(
self,
context_function: Callable[Concatenate[DurableContext, P], Any],
*args,
**kwargs,
):
# wrap the durable context around a durable handler as a convenience to run directly
@durable_handler
def handler(event: Any, context: DurableContext): # noqa: ARG001
return context_function(*args, **kwargs)(context)
super().__init__(handler)