forked from microsoft/durabletask-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathin_memory_backend.py
More file actions
1681 lines (1429 loc) · 74.3 KB
/
in_memory_backend.py
File metadata and controls
1681 lines (1429 loc) · 74.3 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
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""
In-memory backend for durable orchestrations suitable for testing.
This backend stores all orchestration state in memory and processes
work items synchronously within the same process. It is designed for
unit testing and integration testing scenarios where a sidecar process
or external storage is not desired.
"""
import logging
import threading
import time
import uuid
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Callable, Optional
import grpc
from concurrent import futures
from google.protobuf import empty_pb2, timestamp_pb2, wrappers_pb2
import durabletask.internal.orchestrator_service_pb2 as pb
import durabletask.internal.orchestrator_service_pb2_grpc as stubs
import durabletask.internal.helpers as helpers
from durabletask.entities.entity_instance_id import EntityInstanceId
@dataclass
class OrchestrationInstance:
"""Internal orchestration instance state stored by the in-memory backend."""
instance_id: str
name: str
status: pb.OrchestrationStatus
version: Optional[str] = None
input: Optional[str] = None
output: Optional[str] = None
custom_status: Optional[str] = None
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
last_updated_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
failure_details: Optional[pb.TaskFailureDetails] = None
history: list[pb.HistoryEvent] = field(default_factory=list)
pending_events: list[pb.HistoryEvent] = field(default_factory=list)
dispatched_events: list[pb.HistoryEvent] = field(default_factory=list)
completion_token: int = 0
tags: Optional[dict[str, str]] = None
@dataclass
class ActivityWorkItem:
"""Activity work item that needs to be executed."""
instance_id: str
name: str
task_id: int
input: Optional[str]
completion_token: int
@dataclass
class EntityState:
"""Internal entity state stored by the in-memory backend."""
instance_id: str
serialized_state: Optional[str] = None
last_modified_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
locked_by: Optional[str] = None
pending_operations: list[pb.HistoryEvent] = field(default_factory=list)
dispatched_operations: list[pb.HistoryEvent] = field(default_factory=list)
completion_token: int = 0
@dataclass
class PendingLockRequest:
"""Pending lock request from an orchestration."""
critical_section_id: str
parent_instance_id: str
lock_set: list[str]
@dataclass
class EntityWorkItem:
"""Entity work item that needs to be executed."""
instance_id: str
entity_state: Optional[str]
operations: list[pb.HistoryEvent]
completion_token: int
@dataclass
class StateWaiter:
"""Promise resolver for waiting on orchestration state changes."""
predicate: Callable[[OrchestrationInstance], bool]
event: threading.Event = field(default_factory=threading.Event)
result: Optional[OrchestrationInstance] = None
class InMemoryOrchestrationBackend(stubs.TaskHubSidecarServiceServicer):
"""
In-memory backend for durable orchestrations suitable for testing.
This backend stores all orchestration state in memory and processes
work items synchronously within the same process. It is designed for
unit testing and integration testing scenarios where a sidecar process
or external storage is not desired.
Thread-safety: All state mutations are performed with locks to ensure
thread-safe operations. The backend uses queues to manage work items
for orchestrations and activities.
"""
def __init__(self, max_history_size: int = 10000, port: int = 50051):
"""
Creates a new in-memory backend.
Args:
max_history_size: Maximum number of history events per orchestration (default 10000)
port: Port to listen on for gRPC connections (default 50051)
"""
self._lock = threading.RLock()
self._instances: dict[str, OrchestrationInstance] = {}
self._orchestration_queue: deque[str] = deque()
self._orchestration_queue_set: set[str] = set()
self._activity_queue: deque[ActivityWorkItem] = deque()
self._entities: dict[str, EntityState] = {}
self._entity_queue: deque[str] = deque()
self._entity_queue_set: set[str] = set()
self._entity_in_flight: set[str] = set()
self._pending_lock_requests: list[PendingLockRequest] = []
self._orchestration_in_flight: set[str] = set()
self._state_waiters: dict[str, list[StateWaiter]] = {}
self._next_completion_token: int = 1
self._max_history_size = max_history_size
self._port = port
self._server: Optional[grpc.Server] = None
self._logger = logging.getLogger(__name__)
self._shutdown_event = threading.Event()
self._work_available = threading.Event()
def start(self) -> str:
"""
Starts the gRPC server on the configured port.
Returns:
The address the server is listening on (e.g., "localhost:50051")
"""
self._shutdown_event.clear()
self._server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
stubs.add_TaskHubSidecarServiceServicer_to_server(self, self._server)
self._server.add_insecure_port(f'[::]:{self._port}')
self._server.start()
self._logger.info(f"In-memory backend started on port {self._port}")
return f"localhost:{self._port}"
def stop(self, grace: Optional[float] = None):
"""
Stops the gRPC server.
Args:
grace: Grace period in seconds for graceful shutdown
"""
self._shutdown_event.set()
self._work_available.set() # Unblock GetWorkItems loops
if self._server:
stop_future = self._server.stop(grace)
stop_future.wait()
self._server = None
self._logger.info("In-memory backend stopped")
def reset(self):
"""Resets the backend, clearing all state."""
with self._lock:
self._instances.clear()
self._orchestration_queue.clear()
self._orchestration_queue_set.clear()
self._activity_queue.clear()
self._entities.clear()
self._entity_queue.clear()
self._entity_queue_set.clear()
self._entity_in_flight.clear()
self._pending_lock_requests.clear()
self._orchestration_in_flight.clear()
for waiters in self._state_waiters.values():
for waiter in waiters:
waiter.event.set()
self._state_waiters.clear()
self._shutdown_event.clear()
self._work_available.clear()
# gRPC Service Methods
def Hello(self, request, context):
"""Sends a hello request to the sidecar service."""
return empty_pb2.Empty()
def StartInstance(self, request: pb.CreateInstanceRequest, context):
"""Starts a new orchestration instance."""
instance_id = request.instanceId if request.instanceId else uuid.uuid4().hex
with self._lock:
if instance_id in self._instances:
existing = self._instances[instance_id]
policy = request.orchestrationIdReusePolicy
replaceable = list(policy.replaceableStatus) if policy else []
if replaceable:
# If the existing status is in the replaceable list,
# we can replace the instance
if existing.status in replaceable:
# Remove existing to allow re-creation
del self._instances[instance_id]
self._orchestration_queue_set.discard(instance_id)
else:
# Status not replaceable - reject
context.abort(
grpc.StatusCode.ALREADY_EXISTS,
f"Orchestration instance '{instance_id}' already exists "
f"with non-replaceable status")
return pb.CreateInstanceResponse(instanceId=instance_id)
else:
context.abort(
grpc.StatusCode.ALREADY_EXISTS,
f"Orchestration instance '{instance_id}' already exists")
return pb.CreateInstanceResponse(instanceId=instance_id)
now = datetime.now(timezone.utc)
start_time = request.scheduledStartTimestamp.ToDatetime(tzinfo=timezone.utc) \
if request.HasField("scheduledStartTimestamp") else now
version = request.version.value if request.HasField("version") else None
instance = OrchestrationInstance(
instance_id=instance_id,
name=request.name,
status=pb.ORCHESTRATION_STATUS_PENDING,
version=version,
input=request.input.value if request.input else None,
created_at=now,
last_updated_at=now,
completion_token=self._next_completion_token,
tags=dict(request.tags) if request.tags else None,
)
self._next_completion_token += 1
# Add initial events to start the orchestration
orchestrator_started = helpers.new_orchestrator_started_event(start_time)
execution_started = helpers.new_execution_started_event(
request.name, instance_id,
request.input.value if request.input else None,
dict(request.tags) if request.tags else None,
version=version,
)
instance.pending_events.append(orchestrator_started)
instance.pending_events.append(execution_started)
self._instances[instance_id] = instance
self._enqueue_orchestration(instance_id)
self._logger.info(f"Created orchestration instance '{instance_id}' for '{request.name}'")
return pb.CreateInstanceResponse(instanceId=instance_id)
def GetInstance(self, request: pb.GetInstanceRequest, context):
"""Gets the status of an existing orchestration instance."""
with self._lock:
instance = self._instances.get(request.instanceId)
if not instance:
return pb.GetInstanceResponse(exists=False)
return self._build_instance_response(instance, request.getInputsAndOutputs)
def WaitForInstanceStart(self, request: pb.GetInstanceRequest, context):
"""Waits for an orchestration instance to reach a running or completion state."""
def predicate(inst: OrchestrationInstance) -> bool:
return inst.status != pb.ORCHESTRATION_STATUS_PENDING
instance = self._wait_for_state(request.instanceId, predicate, timeout=context.time_remaining())
if not instance:
return pb.GetInstanceResponse(exists=False)
return self._build_instance_response(instance, request.getInputsAndOutputs)
def WaitForInstanceCompletion(self, request: pb.GetInstanceRequest, context):
"""Waits for an orchestration instance to reach a completion state."""
instance = self._wait_for_state(
request.instanceId,
self._is_terminal_status_check,
timeout=context.time_remaining()
)
if not instance:
return pb.GetInstanceResponse(exists=False)
return self._build_instance_response(instance, request.getInputsAndOutputs)
def RaiseEvent(self, request: pb.RaiseEventRequest, context):
"""Raises an event to a running orchestration instance."""
with self._lock:
instance = self._instances.get(request.instanceId)
if not instance:
context.abort(grpc.StatusCode.NOT_FOUND,
f"Orchestration instance '{request.instanceId}' not found")
return pb.RaiseEventResponse()
event = helpers.new_event_raised_event(
request.name,
request.input.value if request.input else None
)
instance.pending_events.append(event)
instance.last_updated_at = datetime.now(timezone.utc)
self._enqueue_orchestration(instance.instance_id)
self._logger.info(f"Raised event '{request.name}' for instance '{request.instanceId}'")
return pb.RaiseEventResponse()
def TerminateInstance(self, request: pb.TerminateRequest, context):
"""Terminates a running orchestration instance."""
with self._lock:
self._terminate_instance_internal(
request.instanceId,
request.output.value if request.output else None,
request.recursive
)
return pb.TerminateResponse()
def SuspendInstance(self, request: pb.SuspendRequest, context):
"""Suspends a running orchestration instance."""
with self._lock:
instance = self._instances.get(request.instanceId)
if not instance:
context.abort(grpc.StatusCode.NOT_FOUND,
f"Orchestration instance '{request.instanceId}' not found")
return pb.SuspendResponse()
if instance.status == pb.ORCHESTRATION_STATUS_SUSPENDED:
return pb.SuspendResponse()
event = helpers.new_suspend_event()
instance.pending_events.append(event)
instance.last_updated_at = datetime.now(timezone.utc)
self._enqueue_orchestration(instance.instance_id)
self._logger.info(f"Suspended instance '{request.instanceId}'")
return pb.SuspendResponse()
def ResumeInstance(self, request: pb.ResumeRequest, context):
"""Resumes a suspended orchestration instance."""
with self._lock:
instance = self._instances.get(request.instanceId)
if not instance:
context.abort(grpc.StatusCode.NOT_FOUND,
f"Orchestration instance '{request.instanceId}' not found")
return pb.ResumeResponse()
event = helpers.new_resume_event()
instance.pending_events.append(event)
instance.last_updated_at = datetime.now(timezone.utc)
self._enqueue_orchestration(instance.instance_id)
self._logger.info(f"Resumed instance '{request.instanceId}'")
return pb.ResumeResponse()
def PurgeInstances(self, request: pb.PurgeInstancesRequest, context):
"""Purges orchestration instances from the store."""
purged_count = 0
with self._lock:
instance_id = request.instanceId
if instance_id:
# Single instance purge
instance = self._instances.get(instance_id)
if instance and self._is_terminal_status(instance.status):
del self._instances[instance_id]
self._state_waiters.pop(instance_id, None)
purged_count = 1
elif request.HasField("purgeInstanceFilter"):
# Filter-based purge
pf = request.purgeInstanceFilter
to_purge = []
for iid, inst in self._instances.items():
if not self._is_terminal_status(inst.status):
continue
if pf.runtimeStatus and inst.status not in pf.runtimeStatus:
continue
if pf.HasField("createdTimeFrom") and inst.created_at < pf.createdTimeFrom.ToDatetime(timezone.utc):
continue
if pf.HasField("createdTimeTo") and inst.created_at >= pf.createdTimeTo.ToDatetime(timezone.utc):
continue
to_purge.append(iid)
for iid in to_purge:
del self._instances[iid]
self._state_waiters.pop(iid, None)
purged_count = len(to_purge)
self._logger.info(f"Purged {purged_count} instance(s)")
return pb.PurgeInstancesResponse(
deletedInstanceCount=purged_count,
isComplete=wrappers_pb2.BoolValue(value=True),
)
def RestartInstance(self, request: pb.RestartInstanceRequest, context):
"""Restarts a completed orchestration instance."""
with self._lock:
instance = self._instances.get(request.instanceId)
if not instance:
context.abort(
grpc.StatusCode.NOT_FOUND,
f"Orchestration instance '{request.instanceId}' not found")
return pb.RestartInstanceResponse()
if not self._is_terminal_status(instance.status):
context.abort(
grpc.StatusCode.FAILED_PRECONDITION,
f"Orchestration instance '{request.instanceId}' is not in a terminal state")
return pb.RestartInstanceResponse()
name = instance.name
original_input = instance.input
version = instance.version
if request.restartWithNewInstanceId:
new_instance_id = uuid.uuid4().hex
else:
new_instance_id = request.instanceId
# Remove the old instance so we can recreate it
del self._instances[request.instanceId]
self._orchestration_queue_set.discard(request.instanceId)
self._state_waiters.pop(request.instanceId, None)
self._create_instance_internal(
new_instance_id, name, original_input, version=version)
self._logger.info(
f"Restarted instance '{request.instanceId}' as '{new_instance_id}'")
return pb.RestartInstanceResponse(instanceId=new_instance_id)
@staticmethod
def _parse_work_item_filters(request: pb.GetWorkItemsRequest):
"""Extract filter name sets from the request, or None if unfiltered."""
if not request.HasField("workItemFilters"):
return None, None, None
wf = request.workItemFilters
orch_names = {f.name for f in wf.orchestrations} if wf.orchestrations else None
activity_names = {f.name for f in wf.activities} if wf.activities else None
entity_names = {f.name for f in wf.entities} if wf.entities else None
return orch_names, activity_names, entity_names
def GetWorkItems(self, request: pb.GetWorkItemsRequest, context):
"""Streams work items to the worker (orchestration and activity work items)."""
self._logger.info("Worker connected and requesting work items")
orch_filter, activity_filter, entity_filter = self._parse_work_item_filters(request)
try:
while context.is_active() and not self._shutdown_event.is_set():
work_item = None
with self._lock:
# Check for orchestration work
skipped_orchs: list[str] = []
while self._orchestration_queue:
instance_id = self._orchestration_queue.popleft()
self._orchestration_queue_set.discard(instance_id)
instance = self._instances.get(instance_id)
if not instance or not instance.pending_events:
continue
# Skip if orchestration name doesn't match filters
if orch_filter is not None and instance.name not in orch_filter:
skipped_orchs.append(instance_id)
continue
if instance_id in self._orchestration_in_flight:
# Already being processed — re-add to queue
skipped_orchs.append(instance_id)
break
# Move pending events to dispatched_events
instance.dispatched_events = list(instance.pending_events)
instance.pending_events.clear()
# Add OrchestratorStarted for re-dispatches so that
# ctx.current_utc_datetime advances correctly
if instance.history:
now = datetime.now(timezone.utc)
orch_started = helpers.new_orchestrator_started_event(now)
instance.dispatched_events.insert(0, orch_started)
self._orchestration_in_flight.add(instance_id)
# Create orchestrator work item
work_item = pb.WorkItem(
completionToken=str(instance.completion_token),
orchestratorRequest=pb.OrchestratorRequest(
instanceId=instance.instance_id,
pastEvents=list(instance.history),
newEvents=list(instance.dispatched_events),
)
)
break
# Re-queue skipped orchestrations for other workers
for s in skipped_orchs:
if s not in self._orchestration_queue_set:
self._orchestration_queue.append(s)
self._orchestration_queue_set.add(s)
# Check for activity work
if not work_item and self._activity_queue:
# Scan for the first matching activity
skipped: list = []
matched_activity = None
while self._activity_queue:
candidate = self._activity_queue.popleft()
if activity_filter is not None and candidate.name not in activity_filter:
skipped.append(candidate)
continue
matched_activity = candidate
break
# Put back non-matching items
for s in skipped:
self._activity_queue.append(s)
if matched_activity is not None:
work_item = pb.WorkItem(
completionToken=str(matched_activity.completion_token),
activityRequest=pb.ActivityRequest(
name=matched_activity.name,
taskId=matched_activity.task_id,
input=wrappers_pb2.StringValue(value=matched_activity.input) if matched_activity.input else None,
orchestrationInstance=pb.OrchestrationInstance(instanceId=matched_activity.instance_id)
)
)
# Check for entity work
if not work_item:
skipped_entities: list[str] = []
while self._entity_queue:
entity_id = self._entity_queue.popleft()
self._entity_queue_set.discard(entity_id)
entity = self._entities.get(entity_id)
if entity and entity.pending_operations:
# Skip if entity name doesn't match filters
if entity_filter is not None:
try:
parsed = EntityInstanceId.parse(entity_id)
if parsed.entity not in entity_filter:
skipped_entities.append(entity_id)
continue
except ValueError:
pass
# Skip if this entity is already being processed
if entity_id in self._entity_in_flight:
continue
# Mark as in-flight to prevent duplicate dispatch
self._entity_in_flight.add(entity_id)
# Drain all pending operations into a batch
operations = list(entity.pending_operations)
entity.pending_operations.clear()
entity.dispatched_operations = list(operations)
# Use V2 EntityRequest format so the worker
# can properly build operation_infos
work_item = pb.WorkItem(
completionToken=str(entity.completion_token),
entityRequestV2=pb.EntityRequest(
instanceId=entity.instance_id,
entityState=wrappers_pb2.StringValue(
value=entity.serialized_state
) if entity.serialized_state else None,
operationRequests=operations,
),
)
break
# Re-queue skipped entities for other workers
for s in skipped_entities:
if s not in self._entity_queue_set:
self._entity_queue.append(s)
self._entity_queue_set.add(s)
if work_item:
yield work_item
else:
# Wait for work to become available (with timeout for shutdown checks)
self._work_available.wait(timeout=0.1)
self._work_available.clear()
except Exception:
self._logger.exception("Error in GetWorkItems stream")
def CompleteOrchestratorTask(self, request: pb.OrchestratorResponse, context):
"""Completes an orchestration execution with the given actions."""
with self._lock:
instance = self._instances.get(request.instanceId)
if not instance:
self._logger.warning(f"Instance '{request.instanceId}' not found for completion")
self._orchestration_in_flight.discard(request.instanceId)
return pb.CompleteTaskResponse()
if str(instance.completion_token) != request.completionToken:
self._logger.warning(
f"Stale completion for instance '{request.instanceId}' - ignoring"
)
self._orchestration_in_flight.discard(request.instanceId)
return pb.CompleteTaskResponse()
# Check history size limit
projected_size = len(instance.history) + len(instance.dispatched_events)
if projected_size > self._max_history_size:
self._orchestration_in_flight.discard(request.instanceId)
context.abort(
grpc.StatusCode.RESOURCE_EXHAUSTED,
f"Orchestration '{request.instanceId}' would exceed maximum history size"
)
return pb.CompleteTaskResponse()
# Move dispatched events to history
new_events = list(instance.dispatched_events)
instance.history.extend(new_events)
instance.dispatched_events.clear()
instance.last_updated_at = datetime.now(timezone.utc)
if request.customStatus:
instance.custom_status = request.customStatus.value
# Transition to RUNNING once processed for the first time
if instance.status == pb.ORCHESTRATION_STATUS_PENDING:
instance.status = pb.ORCHESTRATION_STATUS_RUNNING
# Check for suspend/resume events and update status
for evt in new_events:
if evt.HasField("executionSuspended"):
instance.status = pb.ORCHESTRATION_STATUS_SUSPENDED
elif evt.HasField("executionResumed"):
instance.status = pb.ORCHESTRATION_STATUS_RUNNING
# Process actions — wrapped in try/except to ensure the
# orchestration is never left permanently stuck in the
# in-flight set when an action handler raises.
try:
for action in request.actions:
self._process_action(instance, action)
except Exception as e:
self._logger.error(
f"Error processing actions for instance "
f"'{request.instanceId}': {e}")
# Mark the orchestration as failed so it doesn't stay
# in a running/pending state with no way to make progress.
if not self._is_terminal_status(instance.status):
instance.status = pb.ORCHESTRATION_STATUS_FAILED
instance.failure_details = pb.TaskFailureDetails(
errorType=type(e).__name__,
errorMessage=str(e),
isNonRetriable=True,
)
# Update completion token for next execution
instance.completion_token = self._next_completion_token
self._next_completion_token += 1
# Remove from in-flight before notifying or re-enqueuing
self._orchestration_in_flight.discard(request.instanceId)
# Notify waiters
self._notify_waiters(request.instanceId)
# Re-enqueue if new events arrived while the orchestration was
# in-flight (between dispatch and completion)
not_terminal = not self._is_terminal_status(instance.status)
not_suspended = instance.status != pb.ORCHESTRATION_STATUS_SUSPENDED
if instance.pending_events and not_terminal and not_suspended:
self._enqueue_orchestration(request.instanceId)
return pb.CompleteTaskResponse()
def CompleteActivityTask(self, request: pb.ActivityResponse, context):
"""Completes an activity execution."""
with self._lock:
instance = self._instances.get(request.instanceId)
if not instance:
self._logger.warning(f"Instance '{request.instanceId}' not found for activity completion")
return pb.CompleteTaskResponse()
if request.failureDetails and request.failureDetails.errorMessage:
# Activity failed
event = pb.HistoryEvent(
eventId=-1,
timestamp=timestamp_pb2.Timestamp(),
taskFailed=pb.TaskFailedEvent(
taskScheduledId=request.taskId,
failureDetails=request.failureDetails
)
)
else:
# Activity succeeded
event = pb.HistoryEvent(
eventId=-1,
timestamp=timestamp_pb2.Timestamp(),
taskCompleted=pb.TaskCompletedEvent(
taskScheduledId=request.taskId,
result=request.result
)
)
instance.pending_events.append(event)
instance.last_updated_at = datetime.now(timezone.utc)
self._enqueue_orchestration(request.instanceId)
return pb.CompleteTaskResponse()
def CompleteEntityTask(self, request: pb.EntityBatchResult, context):
"""Completes an entity batch execution."""
with self._lock:
# Find entity by completion token
entity = None
for e in self._entities.values():
if str(e.completion_token) == request.completionToken:
entity = e
break
if not entity:
self._logger.warning(
f"No entity found for completion token '{request.completionToken}'"
)
return pb.CompleteTaskResponse()
# Update entity state
if request.entityState and request.entityState.value:
entity.serialized_state = request.entityState.value
else:
entity.serialized_state = None
entity.last_modified_at = datetime.now(timezone.utc)
entity.dispatched_operations.clear()
# Update completion token for next batch
entity.completion_token = self._next_completion_token
self._next_completion_token += 1
# Clear the in-flight flag
self._entity_in_flight.discard(entity.instance_id)
# Deliver operation results to calling orchestrations.
# Each delivery is individually guarded so that one failure
# does not prevent subsequent results from being delivered.
for i, op_info in enumerate(request.operationInfos):
try:
dest = op_info.responseDestination
if dest and dest.instanceId:
parent_instance_id = op_info.responseDestination.instanceId
parent_instance = self._instances.get(parent_instance_id)
if parent_instance:
result = request.results[i] if i < len(request.results) else None
if result and result.HasField("success"):
event = pb.HistoryEvent(
eventId=-1,
timestamp=timestamp_pb2.Timestamp(),
entityOperationCompleted=pb.EntityOperationCompletedEvent(
requestId=op_info.requestId,
output=result.success.result,
)
)
elif result and result.HasField("failure"):
event = pb.HistoryEvent(
eventId=-1,
timestamp=timestamp_pb2.Timestamp(),
entityOperationFailed=pb.EntityOperationFailedEvent(
requestId=op_info.requestId,
failureDetails=result.failure.failureDetails,
)
)
else:
continue
parent_instance.pending_events.append(event)
parent_instance.last_updated_at = datetime.now(timezone.utc)
self._enqueue_orchestration(parent_instance_id)
except Exception:
self._logger.exception(
f"Error delivering entity result for operation {i}")
# Process side-effect actions (signals to other entities, new orchestrations).
# Each action is individually guarded for the same reason.
for action in request.actions:
try:
if action.HasField("sendSignal"):
signal = action.sendSignal
self._signal_entity_internal(
signal.instanceId, signal.name,
signal.input.value if signal.input else None
)
elif action.HasField("startNewOrchestration"):
start_orch = action.startNewOrchestration
orch_input = start_orch.input.value if start_orch.input else None
orch_version = start_orch.version.value \
if start_orch.HasField("version") else None
instance_id = start_orch.instanceId or uuid.uuid4().hex
self._create_instance_internal(
instance_id, start_orch.name, orch_input,
version=orch_version,
)
except Exception:
self._logger.exception(
"Error processing entity side-effect action")
# If the entity has more pending operations, re-enqueue
if entity.pending_operations:
self._enqueue_entity(entity.instance_id)
return pb.CompleteTaskResponse()
def SignalEntity(self, request: pb.SignalEntityRequest, context):
"""Signals an entity, queueing an operation for processing."""
with self._lock:
entity_id = request.instanceId
entity = self._entities.get(entity_id)
if not entity:
entity = EntityState(
instance_id=entity_id,
completion_token=self._next_completion_token,
)
self._next_completion_token += 1
self._entities[entity_id] = entity
# Create a signaled operation event
event = pb.HistoryEvent(
eventId=-1,
timestamp=timestamp_pb2.Timestamp(),
entityOperationSignaled=pb.EntityOperationSignaledEvent(
requestId=request.requestId,
operation=request.name,
input=request.input if request.input else None,
targetInstanceId=wrappers_pb2.StringValue(value=entity_id),
)
)
entity.pending_operations.append(event)
self._enqueue_entity(entity_id)
self._logger.info(f"Signaled entity '{entity_id}' operation '{request.name}'")
return pb.SignalEntityResponse()
def GetEntity(self, request: pb.GetEntityRequest, context):
"""Gets entity state."""
with self._lock:
entity = self._entities.get(request.instanceId)
if not entity:
return pb.GetEntityResponse(exists=False)
last_modified_ts = timestamp_pb2.Timestamp()
last_modified_ts.FromDatetime(entity.last_modified_at)
metadata = pb.EntityMetadata(
instanceId=entity.instance_id,
lastModifiedTime=last_modified_ts,
backlogQueueSize=len(entity.pending_operations),
lockedBy=wrappers_pb2.StringValue(value=entity.locked_by) if entity.locked_by else None,
serializedState=wrappers_pb2.StringValue(
value=entity.serialized_state) if request.includeState and entity.serialized_state else None,
)
return pb.GetEntityResponse(exists=True, entity=metadata)
def QueryInstances(self, request: pb.QueryInstancesRequest, context):
"""Query orchestration instances with filtering support."""
with self._lock:
query = request.query
start_index = 0
if query.HasField("continuationToken") and query.continuationToken.value:
try:
start_index = int(query.continuationToken.value)
except ValueError:
start_index = 0
matching = []
for instance in self._instances.values():
# Filter by runtime status
if query.runtimeStatus and instance.status not in query.runtimeStatus:
continue
# Filter by created time range
if query.HasField("createdTimeFrom") and instance.created_at < query.createdTimeFrom.ToDatetime(timezone.utc):
continue
if query.HasField("createdTimeTo") and instance.created_at >= query.createdTimeTo.ToDatetime(timezone.utc):
continue
# Filter by instance ID prefix
if query.HasField("instanceIdPrefix") and query.instanceIdPrefix.value:
if not instance.instance_id.startswith(query.instanceIdPrefix.value):
continue
matching.append(instance)
# Sort by created time for deterministic pagination
matching.sort(key=lambda i: i.created_at)
# Apply pagination
page_size = query.maxInstanceCount if query.maxInstanceCount > 0 else len(matching)
page = matching[start_index:start_index + page_size]
states = []
for inst in page:
created_ts = timestamp_pb2.Timestamp()
created_ts.FromDatetime(inst.created_at)
updated_ts = timestamp_pb2.Timestamp()
updated_ts.FromDatetime(inst.last_updated_at)
include = query.fetchInputsAndOutputs
state = pb.OrchestrationState(
instanceId=inst.instance_id,
name=inst.name,
orchestrationStatus=inst.status,
createdTimestamp=created_ts,
lastUpdatedTimestamp=updated_ts,
input=wrappers_pb2.StringValue(value=inst.input) if include and inst.input else None,
output=wrappers_pb2.StringValue(value=inst.output) if include and inst.output else None,
customStatus=wrappers_pb2.StringValue(
value=inst.custom_status) if inst.custom_status else None,
failureDetails=inst.failure_details if inst.failure_details else None,
)
states.append(state)
# Compute continuation token
next_index = start_index + page_size
continuation_token = None
if next_index < len(matching):
continuation_token = wrappers_pb2.StringValue(value=str(next_index))
return pb.QueryInstancesResponse(
orchestrationState=states,
continuationToken=continuation_token,
)
def QueryEntities(self, request: pb.QueryEntitiesRequest, context):
"""Query entities with filtering support."""
with self._lock:
query = request.query
start_index = 0
if query.HasField("continuationToken") and query.continuationToken.value:
try:
start_index = int(query.continuationToken.value)
except ValueError:
start_index = 0
matching = []
for entity in self._entities.values():
# Filter by instance ID prefix
if query.HasField("instanceIdStartsWith") and query.instanceIdStartsWith.value:
if not entity.instance_id.startswith(query.instanceIdStartsWith.value):
continue
# Filter by last modified time range
if query.HasField("lastModifiedFrom") and entity.last_modified_at < query.lastModifiedFrom.ToDatetime(timezone.utc):
continue
if query.HasField("lastModifiedTo") and entity.last_modified_at >= query.lastModifiedTo.ToDatetime(timezone.utc):
continue
# Filter transient (entities with pending operations)
if not query.includeTransient and entity.pending_operations:
continue
matching.append(entity)
# Sort by instance_id for deterministic pagination
matching.sort(key=lambda e: e.instance_id)
# Apply pagination
page_size = query.pageSize.value if query.HasField("pageSize") and query.pageSize.value > 0 else len(matching)
page = matching[start_index:start_index + page_size]
entities = []
for ent in page:
last_modified_ts = timestamp_pb2.Timestamp()
last_modified_ts.FromDatetime(ent.last_modified_at)
metadata = pb.EntityMetadata(
instanceId=ent.instance_id,
lastModifiedTime=last_modified_ts,
backlogQueueSize=len(ent.pending_operations),
lockedBy=wrappers_pb2.StringValue(value=ent.locked_by) if ent.locked_by else None,
serializedState=wrappers_pb2.StringValue(
value=ent.serialized_state
) if query.includeState and ent.serialized_state else None,
)
entities.append(metadata)
# Compute continuation token
next_index = start_index + page_size
continuation_token = None
if next_index < len(matching):
continuation_token = wrappers_pb2.StringValue(value=str(next_index))
return pb.QueryEntitiesResponse(
entities=entities,
continuationToken=continuation_token,
)
def CleanEntityStorage(self, request: pb.CleanEntityStorageRequest, context):
"""Clean entity storage: remove empty entities and release orphaned locks."""
empty_removed = 0