-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrunner.py
More file actions
1197 lines (1005 loc) · 42.7 KB
/
runner.py
File metadata and controls
1197 lines (1005 loc) · 42.7 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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import json
import logging
import os
import time
from dataclasses import dataclass, field
from typing import (
TYPE_CHECKING,
Any,
Concatenate,
ParamSpec,
Protocol,
Self,
TypeVar,
cast,
)
import aws_durable_execution_sdk_python
import boto3 # type: ignore
from botocore.exceptions import ClientError # type: ignore
from aws_durable_execution_sdk_python.execution import (
InvocationStatus,
durable_execution,
)
from aws_durable_execution_sdk_python.lambda_service import (
ErrorObject,
OperationPayload,
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.checkpoint.processors.wait import (
WaitProcessor,
)
from aws_durable_execution_sdk_python_testing.client import InMemoryServiceClient
from aws_durable_execution_sdk_python_testing.exceptions import (
DurableFunctionsLocalRunnerError,
DurableFunctionsTestError,
InvalidParameterValueException,
ResourceNotFoundException,
)
from aws_durable_execution_sdk_python_testing.executor import Executor
from aws_durable_execution_sdk_python_testing.invoker import (
InProcessInvoker,
LambdaInvoker,
)
from aws_durable_execution_sdk_python_testing.model import (
GetDurableExecutionHistoryResponse,
GetDurableExecutionResponse,
StartDurableExecutionInput,
StartDurableExecutionOutput,
events_to_operations,
)
from aws_durable_execution_sdk_python_testing.scheduler import Scheduler
from aws_durable_execution_sdk_python_testing.stores.base import (
ExecutionStore,
StoreType,
)
from aws_durable_execution_sdk_python_testing.stores.filesystem import (
FileSystemExecutionStore,
)
from aws_durable_execution_sdk_python_testing.stores.memory import (
InMemoryExecutionStore,
)
from aws_durable_execution_sdk_python_testing.stores.sqlite import SQLiteExecutionStore
from aws_durable_execution_sdk_python_testing.web.server import WebServer
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
from aws_durable_execution_sdk_python_testing.web.server import WebServiceConfig
from aws_durable_execution_sdk_python_testing.model import Event
logger = logging.getLogger(__name__)
@dataclass(frozen=True)
class WebRunnerConfig:
"""Configuration for the WebRunner using composition pattern.
This configuration class encapsulates all settings needed to run the web server
for durable functions testing, including HTTP server configuration and Lambda
service configuration.
"""
# HTTP server configuration (existing WebServiceConfig)
web_service: WebServiceConfig
# Lambda service configuration (web runner specific)
lambda_endpoint: str = "http://127.0.0.1:3001"
local_runner_endpoint: str = "http://0.0.0.0:5000"
local_runner_region: str = "us-west-2"
local_runner_mode: str = "local"
# Store configuration
store_type: StoreType = StoreType.MEMORY
store_path: str | None = None # Path for filesystem store
@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 InvalidParameterValueException(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: OperationPayload | None = 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 InvalidParameterValueException(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=operation.context_details.result
if operation.context_details
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: datetime.datetime | None = None
result: OperationPayload | None = 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 InvalidParameterValueException(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=operation.step_details.result if operation.step_details else None,
error=operation.step_details.error if operation.step_details else None,
)
@dataclass(frozen=True)
class WaitOperation(Operation):
scheduled_end_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 InvalidParameterValueException(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_end_timestamp=(
operation.wait_details.scheduled_end_timestamp
if operation.wait_details
else None
),
)
@dataclass(frozen=True)
class CallbackOperation(ContextOperation):
callback_id: str | None = None
result: OperationPayload | None = 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 InvalidParameterValueException(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=operation.callback_details.result
if operation.callback_details
else None,
error=operation.callback_details.error
if operation.callback_details
else None,
)
@dataclass(frozen=True)
class InvokeOperation(Operation):
result: OperationPayload | None = 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.CHAINED_INVOKE:
msg: str = f"Expected INVOKE operation, got {operation.operation_type}"
raise InvalidParameterValueException(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,
result=operation.chained_invoke_details.result
if operation.chained_invoke_details
else None,
error=operation.chained_invoke_details.error
if operation.chained_invoke_details
else None,
)
OPERATION_FACTORIES: MutableMapping[OperationType, type[OperationFactory]] = {
OperationType.EXECUTION: ExecutionOperation,
OperationType.CONTEXT: ContextOperation,
OperationType.STEP: StepOperation,
OperationType.WAIT: WaitOperation,
OperationType.CHAINED_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)
def _get_callback_id_from_events(
events: list[Event], name: str | None = None
) -> str | None:
"""
Get callback ID from execution history for callbacks that haven't completed.
Args:
execution_arn: The ARN of the execution to query.
name: Optional callback name to search for. If not provided, returns the latest callback.
Returns:
The callback ID string for a non-completed callback, or None if not found.
Raises:
DurableFunctionsTestError: If the named callback has already succeeded/failed/timed out.
"""
callback_started_events = [
event for event in events if event.event_type == "CallbackStarted"
]
if not callback_started_events:
return None
completed_callback_ids = {
event.event_id
for event in events
if event.event_type
in ["CallbackSucceeded", "CallbackFailed", "CallbackTimedOut"]
}
if name is not None:
for event in callback_started_events:
if event.name == name:
callback_id = event.event_id
if callback_id in completed_callback_ids:
raise DurableFunctionsTestError(
f"Callback {name} has already completed (succeeded/failed/timed out)"
)
return (
event.callback_started_details.callback_id
if event.callback_started_details
else None
)
return None
# If name is not provided, find the latest non-completed callback event
active_callbacks = [
event
for event in callback_started_events
if event.event_id not in completed_callback_ids
]
if not active_callbacks:
return None
latest_event = active_callbacks[-1]
return (
latest_event.callback_started_details.callback_id
if latest_event.callback_started_details
else None
)
@dataclass(frozen=True)
class DurableFunctionTestResult:
status: InvocationStatus
operations: list[Operation]
result: OperationPayload | None = 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)
return cls(
status=execution.result.status,
operations=operations,
result=execution.result.result,
error=execution.result.error,
)
@classmethod
def from_execution_history(
cls,
execution_response: GetDurableExecutionResponse,
history_response: GetDurableExecutionHistoryResponse,
) -> DurableFunctionTestResult:
"""Create test result from execution history responses.
Factory method for cloud runner that builds DurableFunctionTestResult
from GetDurableExecution and GetDurableExecutionHistory API responses.
"""
# Map status string to InvocationStatus enum
try:
status = InvocationStatus[execution_response.status]
except KeyError:
logger.warning(
"Unknown status: %s, defaulting to FAILED", execution_response.status
)
status = InvocationStatus.FAILED
# Convert Events to Operations - group by operation_id and merge
try:
svc_operations = events_to_operations(history_response.events)
except Exception as e:
logger.warning("Failed to convert events to operations: %s", e)
svc_operations = []
# Build operation tree (exclude EXECUTION type from top level)
operations = []
for svc_op in svc_operations:
if svc_op.operation_type == OperationType.EXECUTION:
continue
if svc_op.parent_id is None:
operations.append(create_operation(svc_op, svc_operations))
return cls(
status=status,
operations=operations,
result=execution_response.result,
error=execution_response.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))
def get_all_operations(self) -> list[Operation]:
"""Recursively get all operations including nested ones."""
all_ops = []
stack = list(self.operations)
while stack:
op = stack.pop()
all_ops.append(op)
# Add child operations to stack (if they exist)
if hasattr(op, "child_operations") and op.child_operations:
stack.extend(op.child_operations)
return all_ops
class DurableFunctionTestRunner:
def __init__(self, handler: Callable, poll_interval: float = 1.0):
self._scheduler: Scheduler = Scheduler()
self._scheduler.start()
self._store = InMemoryExecutionStore()
self.poll_interval = poll_interval
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,
checkpoint_processor=self._checkpoint_processor,
)
# 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",
skip_time: bool = False,
) -> DurableFunctionTestResult:
"""Run the durable function and wait for completion.
Args:
input: Input payload for the function
timeout: Maximum execution time in seconds
function_name: Name of the function
execution_name: Name of the execution
account_id: AWS account ID
skip_time: If True, wait operations complete immediately. If False (default),
wait operations use real time delays.
Returns:
Test result containing execution status and operations
"""
# Update time_scale in checkpoint processor for this run
time_scale = 0.0 if skip_time else 1.0
self._checkpoint_processor._transformer.processors[OperationType.WAIT] = (
WaitProcessor(time_scale=time_scale)
)
execution_arn = self.run_async(
input=input,
timeout=timeout,
function_name=function_name,
execution_name=execution_name,
account_id=account_id,
)
return self.wait_for_result(execution_arn=execution_arn, timeout=timeout)
def send_callback_success(
self, callback_id: str, result: bytes | None = None
) -> None:
self._executor.send_callback_success(callback_id=callback_id, result=result)
def send_callback_failure(
self, callback_id: str, error: ErrorObject | None = None
) -> None:
self._executor.send_callback_failure(callback_id=callback_id, error=error)
def send_callback_heartbeat(self, callback_id: str) -> None:
self._executor.send_callback_heartbeat(callback_id=callback_id)
def run_async(
self,
input: str | None = None, # noqa: A002
timeout: int = 900,
function_name: str = "test-function",
execution_name: str = "execution-name",
account_id: str = "123456789012",
) -> str:
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)
return output.execution_arn
def wait_for_result(
self, execution_arn: str, timeout: int = 60
) -> DurableFunctionTestResult:
# Block until completion
completed = self._executor.wait_until_complete(execution_arn, timeout)
if not completed:
msg_timeout: str = "Execution did not complete within timeout"
raise TimeoutError(msg_timeout)
execution: Execution = self._store.load(execution_arn)
return DurableFunctionTestResult.create(execution=execution)
def wait_for_callback(
self, execution_arn: str, name: str | None = None, timeout: int = 60
) -> str:
start_time = time.time()
while time.time() - start_time < timeout:
try:
history_response = self._executor.get_execution_history(execution_arn)
callback_id = _get_callback_id_from_events(
events=history_response.events, name=name
)
if callback_id:
return callback_id
except ResourceNotFoundException as e:
pass
except Exception as e:
msg = f"Failed to fetch execution history: {e}"
raise DurableFunctionsTestError(msg) from e
# Wait before next poll
time.sleep(self.poll_interval)
# Timeout reached
elapsed = time.time() - start_time
msg = f"Callback did not available within {timeout}s (elapsed: {elapsed:.1f}s."
raise TimeoutError(msg)
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 execution handler as a convenience to run directly
@durable_execution
def handler(event: Any, context: DurableContext): # noqa: ARG001
return context_function(*args, **kwargs)(context)
super().__init__(handler)
class WebRunner:
"""Web server runner for durable functions testing with HTTP API endpoints."""
def __init__(self, config: WebRunnerConfig) -> None:
"""Initialize WebRunner with configuration.
Args:
config: WebRunnerConfig containing server and Lambda service settings
"""
self._config = config
self._server: WebServer | None = None
self._scheduler: Scheduler | None = None
self._store: ExecutionStore | None = None
self._invoker: LambdaInvoker | None = None
self._executor: Executor | None = None
def __enter__(self) -> Self:
"""Context manager entry point.
Returns:
WebRunner: Self for use in with statement
"""
self.start()
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
"""Context manager exit point with cleanup.
Args:
exc_type: Exception type if an exception occurred
exc_val: Exception value if an exception occurred
exc_tb: Exception traceback if an exception occurred
"""
self.stop()
def start(self) -> None:
"""Start the server and initialize all dependencies.
Creates and configures all required components including scheduler,
store, invoker, executor, and web server. It does not however start
serving web requests, for that you need serve_forever.
Raises:
DurableFunctionsLocalRunnerError: If server is already started
"""
if self._server is not None:
msg = "Server is already running"
raise DurableFunctionsLocalRunnerError(msg)
# Create dependencies and server
if self._config.store_type == StoreType.SQLITE:
store_path = self._config.store_path
self._store = SQLiteExecutionStore.create_and_initialize(store_path)
elif self._config.store_type == StoreType.FILESYSTEM:
store_path = self._config.store_path or ".durable_executions"
self._store = FileSystemExecutionStore.create(store_path)
else:
self._store = InMemoryExecutionStore()
self._scheduler = Scheduler()
self._invoker = LambdaInvoker(self._create_boto3_client())
# Create shared CheckpointProcessor
checkpoint_processor = CheckpointProcessor(self._store, self._scheduler)
# Create executor with all dependencies including checkpoint processor
self._executor = Executor(
store=self._store,
scheduler=self._scheduler,
invoker=self._invoker,
checkpoint_processor=checkpoint_processor,
)
# Add executor as observer to the checkpoint processor
checkpoint_processor.add_execution_observer(self._executor)
# Start the scheduler
self._scheduler.start()
# Create web server with configuration and executor
self._server = WebServer(
config=self._config.web_service, executor=self._executor
)
def serve_forever(self) -> None:
"""Start serving HTTP requests indefinitely.
Delegates to the underlying WebServer.serve_forever() method.
This method blocks until the server is stopped.
Raises:
DurableFunctionsLocalRunnerError: If server has not been started
"""
if self._server is None:
msg = "Server not started"
raise DurableFunctionsLocalRunnerError(msg)
# This blocks until KeyboardInterrupt - let caller handle the exception
self._server.serve_forever()
def stop(self) -> None:
"""Stop the web server and cleanup resources.
Gracefully shuts down the server, scheduler, and cleans up
all allocated resources. Safe to call multiple times.
Handles cleanup exceptions gracefully to ensure all resources
are cleaned up even if some fail.
"""
if self._server is not None:
try:
self._server.server_close()
except Exception:
# Log the exception but continue cleanup
logger.exception("error closing web server")
self._server = None
if self._scheduler is not None:
try:
self._scheduler.stop()
except Exception:
logger.exception("error stopping scheduler")
self._scheduler = None
self._store = None
self._invoker = None
self._executor = None
def _create_boto3_client(self) -> Any:
"""Create boto3 client for Lambda service.
Creates a boto3 client with the local runner endpoint and region from configuration.
Returns:
Configured boto3 client for Lambda service
Raises:
Exception: If client creation fails - exceptions propagate naturally
for CLI to handle as general Exception
"""
# Create client with Lambda endpoint configuration
return boto3.client(
"lambda",
endpoint_url=self._config.lambda_endpoint,
region_name=self._config.local_runner_region,
)
class DurableFunctionCloudTestRunner:
"""Test runner that executes durable functions against actual AWS Lambda backend.
This runner invokes deployed Lambda functions and polls for execution completion,
providing the same interface as DurableFunctionTestRunner for seamless test
compatibility between local and cloud modes.
Example:
>>> runner = DurableFunctionCloudTestRunner(
... function_name="HelloWorld-Python-PR-123", region="us-west-2"
... )
>>> with runner:
... result = runner.run(input={"name": "World"}, timeout=60)
>>> assert result.current_status == InvocationStatus.SUCCEEDED
"""
def __init__(
self,
function_name: str,
region: str = "us-west-2",
lambda_endpoint: str | None = None,
poll_interval: float = 1.0,
):
"""Initialize cloud test runner."""
self.function_name = function_name
self.region = region
self.lambda_endpoint = lambda_endpoint
self.poll_interval = poll_interval
client_config = boto3.session.Config(parameter_validation=False)
self.lambda_client = boto3.client(
"lambda",
endpoint_url=lambda_endpoint,
region_name=region,
config=client_config,
)
def run(
self,
input: str | None = None, # noqa: A002
timeout: int = 60,
skip_time: bool = False, # noqa: ARG002
) -> DurableFunctionTestResult:
"""Execute function on AWS Lambda and wait for completion.
Note: skip_time parameter is ignored for cloud runner as timing is
controlled by the Lambda service.
"""
logger.info(
"Invoking Lambda function: %s (timeout: %ds)", self.function_name, timeout
)
# JSON encode input
payload = json.dumps(input)
# Invoke Lambda function
try:
response = self.lambda_client.invoke(
FunctionName=self.function_name,
InvocationType="RequestResponse",
Payload=payload,
)
except Exception as e:
msg = f"Failed to invoke Lambda function {self.function_name}: {e}"
raise DurableFunctionsTestError(msg) from e
# Check HTTP status code, 200 for RequestResponse
status_code = response.get("StatusCode")
if status_code != 200:
error_payload = response["Payload"].read().decode("utf-8")
msg = f"Lambda invocation failed with status {status_code}: {error_payload}"
raise DurableFunctionsTestError(msg)
# Check for function errors, we want to return function error for testing purpose
if "FunctionError" in response:
error_payload = response["Payload"].read().decode("utf-8")
logger.warning("Lambda function failed: %s", error_payload)
result_payload = response["Payload"].read().decode("utf-8")
logger.info(
"Lambda invocation completed, response: %s",
result_payload,
)
# Extract durable execution ARN from response headers
# The InvocationResponse includes X-Amz-Durable-Execution-Arn header
execution_arn = response.get("DurableExecutionArn")
if not execution_arn:
msg = (
f"No DurableExecutionArn in response for function {self.function_name}"
)
raise DurableFunctionsTestError(msg)
return self.wait_for_result(execution_arn=execution_arn, timeout=timeout)
def run_async(
self,
input: str | None = None, # noqa: A002
timeout: int = 60,
) -> str:
"""Execute function on AWS Lambda asynchronously"""
logger.info(
"Invoking Lambda function: %s (timeout: %ds)", self.function_name, timeout
)
payload = json.dumps(input)
try:
response = self.lambda_client.invoke(
FunctionName=self.function_name,