-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathWorkflowContext.php
More file actions
814 lines (695 loc) · 28.4 KB
/
WorkflowContext.php
File metadata and controls
814 lines (695 loc) · 28.4 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
<?php
/**
* This file is part of Temporal package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Temporal\Internal\Workflow;
use Internal\Destroy\Destroyable;
use Psr\Log\LoggerInterface;
use Ramsey\Uuid\UuidInterface;
use React\Promise\Deferred;
use React\Promise\PromiseInterface;
use Temporal\Activity\ActivityOptions;
use Temporal\Activity\ActivityOptionsInterface;
use Temporal\Activity\LocalActivityOptions;
use Temporal\Api\Sdk\V1\EnhancedStackTrace;
use Temporal\Common\SearchAttributes\SearchAttributeKey;
use Temporal\Common\SearchAttributes\SearchAttributeUpdate;
use Temporal\Common\SideEffectOptions;
use Temporal\Common\Uuid;
use Temporal\DataConverter\EncodedValues;
use Temporal\DataConverter\Type;
use Temporal\DataConverter\ValuesInterface;
use Temporal\Interceptor\HeaderInterface;
use Temporal\Interceptor\WorkflowOutboundCalls\AwaitInput;
use Temporal\Interceptor\WorkflowOutboundCalls\AwaitWithTimeoutInput;
use Temporal\Interceptor\WorkflowOutboundCalls\CompleteInput;
use Temporal\Interceptor\WorkflowOutboundCalls\ContinueAsNewInput;
use Temporal\Interceptor\WorkflowOutboundCalls\ExecuteActivityInput;
use Temporal\Interceptor\WorkflowOutboundCalls\ExecuteChildWorkflowInput;
use Temporal\Interceptor\WorkflowOutboundCalls\ExecuteLocalActivityInput;
use Temporal\Interceptor\WorkflowOutboundCalls\GetVersionInput;
use Temporal\Interceptor\WorkflowOutboundCalls\PanicInput;
use Temporal\Interceptor\WorkflowOutboundCalls\SideEffectInput;
use Temporal\Interceptor\WorkflowOutboundCalls\TimerInput;
use Temporal\Interceptor\WorkflowOutboundCalls\UpsertMemoInput;
use Temporal\Interceptor\WorkflowOutboundCalls\UpsertSearchAttributesInput;
use Temporal\Interceptor\WorkflowOutboundCalls\UpsertTypedSearchAttributesInput;
use Temporal\Interceptor\WorkflowOutboundCallsInterceptor;
use Temporal\Interceptor\WorkflowOutboundRequestInterceptor;
use Temporal\Internal\Declaration\EntityNameValidator;
use Temporal\Internal\Declaration\WorkflowInstance\QueryDispatcher;
use Temporal\Internal\Declaration\WorkflowInstance\SignalDispatcher;
use Temporal\Internal\Declaration\WorkflowInstance\UpdateDispatcher;
use Temporal\Internal\Declaration\WorkflowInstanceInterface;
use Temporal\Internal\Interceptor\HeaderCarrier;
use Temporal\Internal\Interceptor\Pipeline;
use Temporal\Internal\ServiceContainer;
use Temporal\Internal\Support\DateInterval;
use Temporal\Internal\Support\StackRenderer;
use Temporal\Internal\Transport\ClientInterface;
use Temporal\Internal\Transport\CompletableResultInterface;
use Temporal\Internal\Transport\Request\Cancel;
use Temporal\Internal\Transport\Request\CompleteWorkflow;
use Temporal\Internal\Transport\Request\ContinueAsNew;
use Temporal\Internal\Transport\Request\GetVersion;
use Temporal\Internal\Transport\Request\NewTimer;
use Temporal\Internal\Transport\Request\Panic;
use Temporal\Internal\Transport\Request\SideEffect;
use Temporal\Internal\Transport\Request\UpsertMemo;
use Temporal\Internal\Transport\Request\UpsertSearchAttributes;
use Temporal\Internal\Transport\Request\UpsertTypedSearchAttributes;
use Temporal\Internal\Workflow\Process\HandlerState;
use Temporal\Promise;
use Temporal\Worker\Transport\Command\RequestInterface;
use Temporal\Workflow\ActivityStubInterface;
use Temporal\Workflow\ChildWorkflowOptions;
use Temporal\Workflow\ChildWorkflowStubInterface;
use Temporal\Workflow\ContinueAsNewOptions;
use Temporal\Workflow\ExternalWorkflowStubInterface;
use Temporal\Workflow\Mutex;
use Temporal\Workflow\TimerOptions;
use Temporal\Workflow\WorkflowContextInterface;
use Temporal\Workflow\WorkflowExecution;
use Temporal\Workflow\WorkflowInfo;
use function React\Promise\reject;
use function React\Promise\resolve;
/**
* Root, the most top level WorkflowContext that unites all relevant contexts, handlers, options,
* states, etc.
*
* @internal
*/
class WorkflowContext implements WorkflowContextInterface, HeaderCarrier, Destroyable
{
/**
* Contains conditional groups that contains tuple of a condition callable and its promise
* @var array<non-empty-string, array<int<0, max>, array{callable, Deferred}>>
*/
protected array $awaits = [];
protected array $trace = [];
protected bool $continueAsNew = false;
protected bool $readonly = true;
protected ?string $currentDetails = null;
/** @var Pipeline<WorkflowOutboundRequestInterceptor, PromiseInterface> */
private Pipeline $requestInterceptor;
/** @var Pipeline<WorkflowOutboundCallsInterceptor, PromiseInterface> */
private Pipeline $callsInterceptor;
private readonly QueryDispatcher $queryDispatcher;
private readonly SignalDispatcher $signalDispatcher;
private readonly UpdateDispatcher $updateDispatcher;
/**
* @param HandlerState $handlers Counter of active Update and Signal handlers
*/
public function __construct(
protected ServiceContainer $services,
protected ClientInterface $client,
protected WorkflowInstanceInterface&Destroyable $workflowInstance,
public Input $input,
protected ?ValuesInterface $lastCompletionResult = null,
protected HandlerState $handlers = new HandlerState(),
) {
$this->queryDispatcher = $this->workflowInstance->getQueryDispatcher();
$this->signalDispatcher = $this->workflowInstance->getSignalDispatcher();
$this->updateDispatcher = $this->workflowInstance->getUpdateDispatcher();
$this->requestInterceptor = $services->interceptorProvider
->getPipeline(WorkflowOutboundRequestInterceptor::class);
$this->callsInterceptor = $services->interceptorProvider
->getPipeline(WorkflowOutboundCallsInterceptor::class);
}
public function getWorkflowInstance(): WorkflowInstanceInterface
{
return $this->workflowInstance;
}
public function getInstance(): object
{
return $this->workflowInstance->getContext();
}
public function now(): \DateTimeInterface
{
return $this->services->env->now();
}
public function getRunId(): string
{
return $this->input->info->execution->getRunID();
}
public function getInfo(): WorkflowInfo
{
return $this->input->info;
}
public function getHeader(): HeaderInterface
{
return $this->input->header;
}
public function getInput(): ValuesInterface
{
return $this->input->input;
}
public function setReadonly(bool $value = true): static
{
$this->readonly = $value;
return $this;
}
public function withInput(Input $input): static
{
$clone = clone $this;
$clone->awaits = &$this->awaits;
$clone->trace = &$this->trace;
$clone->input = $input;
return $clone;
}
public function getLastCompletionResultValues(): ?ValuesInterface
{
return $this->lastCompletionResult;
}
public function getLastCompletionResult(mixed $type = null): mixed
{
return $this->lastCompletionResult?->getValue(0, $type);
}
public function getClient(): ClientInterface
{
return $this->client;
}
public function registerQuery(string $queryType, callable $handler, string $description): WorkflowContextInterface
{
EntityNameValidator::validateQueryMethod($queryType);
$this->queryDispatcher->addQueryHandler($queryType, $handler, $description);
return $this;
}
public function registerSignal(string $queryType, callable $handler, string $description): WorkflowContextInterface
{
EntityNameValidator::validateSignalMethod($queryType);
$this->signalDispatcher->addSignalHandler($queryType, $handler, $description);
return $this;
}
public function registerDynamicSignal(callable $handler): WorkflowContextInterface
{
$this->signalDispatcher->setDynamicSignalHandler($handler);
return $this;
}
public function registerDynamicQuery(callable $handler): WorkflowContextInterface
{
$this->queryDispatcher->setDynamicQueryHandler($handler);
return $this;
}
public function registerDynamicUpdate(callable $handler, ?callable $validator = null): WorkflowContextInterface
{
$this->updateDispatcher->setDynamicUpdateHandler($handler, $validator);
return $this;
}
public function registerUpdate(string $name, callable $handler, ?callable $validator, string $description): static
{
EntityNameValidator::validateUpdateMethod($name);
$this->updateDispatcher->addUpdateHandler($name, $handler, $validator, $description);
return $this;
}
public function getVersion(string $changeId, int $minSupported, int $maxSupported): PromiseInterface
{
return $this->callsInterceptor->with(
fn(GetVersionInput $input): PromiseInterface => EncodedValues::decodePromise(
$this->request(new GetVersion($input->changeId, $input->minSupported, $input->maxSupported)),
Type::TYPE_ANY,
),
/** @see WorkflowOutboundCallsInterceptor::getVersion() */
'getVersion',
)(new GetVersionInput($changeId, $minSupported, $maxSupported));
}
public function sideEffect(callable $context, ?SideEffectOptions $options = null): PromiseInterface
{
$value = null;
$closure = $context(...);
try {
if (!$this->isReplaying()) {
$value = $this->callsInterceptor->with(
$closure,
/** @see WorkflowOutboundCallsInterceptor::sideEffect() */
'sideEffect',
)(new SideEffectInput($closure, $options));
}
} catch (\Throwable $e) {
return reject($e);
}
$returnType = null;
try {
$reflection = new \ReflectionFunction($closure);
$returnType = $reflection->getReturnType();
} catch (\Throwable) {
}
$last = fn(): PromiseInterface => EncodedValues::decodePromise(
$this->request(new SideEffect(
EncodedValues::fromValues([$value]),
$options === null ? [] : $this->services->marshaller->marshal($options),
)),
$returnType,
);
return $last();
}
public function isReplaying(): bool
{
return $this->services->env->isReplaying();
}
public function complete(?array $result = null, ?\Throwable $failure = null): PromiseInterface
{
if ($failure !== null) {
$this->signalDispatcher->clearSignalQueue();
}
return $this->callsInterceptor->with(
function (CompleteInput $input): PromiseInterface {
$values = $input->result !== null
? EncodedValues::fromValues($input->result)
: EncodedValues::empty();
return $this->request(new CompleteWorkflow($values, $input->failure), false);
},
/** @see WorkflowOutboundCallsInterceptor::complete() */
'complete',
)(new CompleteInput($result, $failure));
}
public function panic(?\Throwable $failure = null): PromiseInterface
{
return $this->callsInterceptor->with(
fn(PanicInput $failure): PromiseInterface => $this->request(new Panic($failure->failure), false),
/** @see WorkflowOutboundCallsInterceptor::panic() */
'panic',
)(new PanicInput($failure));
}
public function continueAsNew(
string $type,
array $args = [],
?ContinueAsNewOptions $options = null,
): PromiseInterface {
return $this->callsInterceptor->with(
function (ContinueAsNewInput $input): PromiseInterface {
$this->continueAsNew = true;
$request = new ContinueAsNew(
$input->type,
EncodedValues::fromValues($input->args),
$this->services->marshaller->marshal($input->options ?? new ContinueAsNewOptions()),
$this->getHeader(),
);
// must not be captured
return $this->request($request, false);
},
/** @see WorkflowOutboundCallsInterceptor::continueAsNew() */
'continueAsNew',
)(new ContinueAsNewInput($type, $args, $options));
}
public function newContinueAsNewStub(string $class, ?ContinueAsNewOptions $options = null): object
{
$options ??= new ContinueAsNewOptions();
$workflow = $this->services->workflowsReader->fromClass($class);
return new ContinueAsNewProxy($class, $workflow, $options, $this);
}
public function isContinuedAsNew(): bool
{
return $this->continueAsNew;
}
public function executeChildWorkflow(
string $type,
array $args = [],
?ChildWorkflowOptions $options = null,
mixed $returnType = null,
): PromiseInterface {
return $this->callsInterceptor->with(
fn(ExecuteChildWorkflowInput $input): PromiseInterface => $this
->newUntypedChildWorkflowStub($input->type, $input->options)
->execute($input->args, $input->returnType),
/** @see WorkflowOutboundCallsInterceptor::executeChildWorkflow() */
'executeChildWorkflow',
)(new ExecuteChildWorkflowInput($type, $args, $options, $returnType));
}
public function newUntypedChildWorkflowStub(
string $type,
?ChildWorkflowOptions $options = null,
): ChildWorkflowStubInterface {
$options ??= new ChildWorkflowOptions();
return new ChildWorkflowStub($this->services->marshaller, $type, $options, $this->getHeader());
}
public function newChildWorkflowStub(
string $class,
?ChildWorkflowOptions $options = null,
): object {
$workflow = $this->services->workflowsReader->fromClass($class);
$options = $options ?? (new ChildWorkflowOptions())
->withNamespace($this->getInfo()->namespace);
return new ChildWorkflowProxy(
$class,
$workflow,
$options,
$this,
);
}
public function newExternalWorkflowStub(string $class, WorkflowExecution $execution): object
{
$workflow = $this->services->workflowsReader->fromClass($class);
$stub = $this->newUntypedExternalWorkflowStub($execution);
return new ExternalWorkflowProxy($class, $workflow, $stub);
}
public function newUntypedExternalWorkflowStub(WorkflowExecution $execution): ExternalWorkflowStubInterface
{
return new ExternalWorkflowStub($execution, $this->callsInterceptor);
}
public function executeActivity(
string $type,
array $args = [],
?ActivityOptionsInterface $options = null,
Type|string|\ReflectionClass|\ReflectionType|null $returnType = null,
): PromiseInterface {
$isLocal = $options instanceof LocalActivityOptions;
return $isLocal
? $this->callsInterceptor->with(
fn(ExecuteLocalActivityInput $input): PromiseInterface => $this
->newUntypedActivityStub($input->options)
->execute($input->type, $input->args, $input->returnType, true),
/** @see WorkflowOutboundCallsInterceptor::executeLocalActivity() */
'executeLocalActivity',
)(new ExecuteLocalActivityInput($type, $args, $options, $returnType))
: $this->callsInterceptor->with(
fn(ExecuteActivityInput $input): PromiseInterface => $this
->newUntypedActivityStub($input->options)
->execute($input->type, $input->args, $input->returnType),
/** @see WorkflowOutboundCallsInterceptor::executeActivity() */
'executeActivity',
)(new ExecuteActivityInput($type, $args, $options, $returnType));
}
public function newUntypedActivityStub(
?ActivityOptionsInterface $options = null,
): ActivityStubInterface {
$options ??= new ActivityOptions();
return new ActivityStub($this->services->marshaller, $options, $this->getHeader());
}
public function newActivityStub(
string $class,
?ActivityOptionsInterface $options = null,
): ActivityProxy {
$activities = $this->services->activitiesReader->fromClass($class);
if (isset($activities[0]) && $activities[0]->isLocalActivity() && !$options instanceof LocalActivityOptions) {
throw new \RuntimeException("Local activity can be used only with LocalActivityOptions");
}
return new ActivityProxy(
$class,
$activities,
$options ?? ActivityOptions::new(),
$this,
$this->callsInterceptor,
);
}
public function timer($interval, ?TimerOptions $options = null): PromiseInterface
{
$dateInterval = DateInterval::parse($interval, DateInterval::FORMAT_SECONDS);
return $this->callsInterceptor->with(
fn(TimerInput $input): PromiseInterface => $this->request(
new NewTimer(new AwaitOptions($input->interval, $options)),
),
/** @see WorkflowOutboundCallsInterceptor::timer() */
'timer',
)(new TimerInput($dateInterval, $options));
}
public function request(
RequestInterface $request,
bool $cancellable = true,
bool $waitResponse = true,
): PromiseInterface {
$this->readonly and throw new \RuntimeException('Workflow is not initialized.');
$this->recordTrace();
// Intercept workflow outbound calls
return $this->requestInterceptor->with(
function (RequestInterface $request) use ($waitResponse): PromiseInterface {
if (!$waitResponse) {
$this->client->send($request);
return Promise::resolve();
}
return $this->client->request($request, $this);
},
/** @see WorkflowOutboundRequestInterceptor::handleOutboundRequest() */
'handleOutboundRequest',
)($request);
}
public function getStackTrace(): string
{
return StackRenderer::renderString($this->trace);
}
public function getEnhancedStackTrace(): EnhancedStackTrace
{
return StackRenderer::renderProto($this->trace);
}
public function allHandlersFinished(): bool
{
return !$this->handlers->hasRunningHandlers();
}
public function upsertMemo(array $values): void
{
$this->callsInterceptor->with(
function (UpsertMemoInput $input): PromiseInterface {
if ($input->memo === []) {
return resolve(null);
}
$result = $this->request(new UpsertMemo($input->memo), false, false);
/** @psalm-suppress UnsupportedPropertyReferenceUsage $memo */
$memo = &$this->input->info->memo;
$memo ??= [];
foreach ($input->memo as $name => $value) {
if ($value === null) {
unset($memo[$name]);
continue;
}
$memo[$name] = $value;
}
return $result;
},
/** @see WorkflowOutboundCallsInterceptor::upsertMemo() */
'upsertMemo',
)(new UpsertMemoInput($values));
}
public function upsertSearchAttributes(array $searchAttributes): void
{
$this->callsInterceptor->with(
function (UpsertSearchAttributesInput $input): PromiseInterface {
if ($input->searchAttributes === []) {
return resolve(null);
}
$result = $this->request(new UpsertSearchAttributes($input->searchAttributes), false, false);
/** @psalm-suppress UnsupportedPropertyReferenceUsage $sa */
$sa = &$this->input->info->searchAttributes;
foreach ($input->searchAttributes as $name => $value) {
if ($value === null) {
unset($sa[$name]);
continue;
}
$sa[$name] = $value;
}
return $result;
},
/** @see WorkflowOutboundCallsInterceptor::upsertSearchAttributes() */
'upsertSearchAttributes',
)(new UpsertSearchAttributesInput($searchAttributes));
}
public function upsertTypedSearchAttributes(SearchAttributeUpdate ...$updates): void
{
$this->callsInterceptor->with(
function (UpsertTypedSearchAttributesInput $input): PromiseInterface {
if ($input->updates === []) {
return resolve(null);
}
$result = $this->request(new UpsertTypedSearchAttributes($input->updates), false, false);
// Merge changes
$tsa = $this->input->info->typedSearchAttributes;
foreach ($input->updates as $update) {
if ($update instanceof SearchAttributeUpdate\ValueUnset) {
$tsa = $tsa->withoutValue($update->name);
continue;
}
if ($update instanceof SearchAttributeUpdate\ValueSet) {
$tsa = $tsa->withValue(
SearchAttributeKey::for($update->type, $update->name),
$update->value,
);
}
}
$this->input->info->typedSearchAttributes = $tsa;
return $result;
},
/** @see WorkflowOutboundCallsInterceptor::upsertTypedSearchAttributes() */
'upsertTypedSearchAttributes',
)(new UpsertTypedSearchAttributesInput($updates));
}
public function await(callable|Mutex|PromiseInterface ...$conditions): PromiseInterface
{
return $this->callsInterceptor->with(
fn(AwaitInput $input): PromiseInterface => $this->awaitRequest(...$input->conditions),
/** @see WorkflowOutboundCallsInterceptor::await() */
'await',
)(new AwaitInput($conditions));
}
public function awaitWithTimeout($interval, callable|Mutex|PromiseInterface ...$conditions): PromiseInterface
{
$intervalObject = DateInterval::parse($interval, DateInterval::FORMAT_SECONDS);
return $this->callsInterceptor->with(
function (AwaitWithTimeoutInput $input): PromiseInterface {
/** Bypassing {@see timer()} to acquire a timer request ID */
$request = new NewTimer(new AwaitOptions($input->interval, null));
$requestId = $request->getID();
$timer = $this->request($request);
\assert($timer instanceof CompletableResultInterface);
return $this->awaitRequest($timer, ...$input->conditions)
->then(function () use ($timer, $requestId): bool {
$isCompleted = $timer->isComplete();
if (!$isCompleted) {
// If internal timer was not completed then cancel it
$this->request(new Cancel($requestId));
}
return !$isCompleted;
});
},
/** @see WorkflowOutboundCallsInterceptor::awaitWithTimeout() */
'awaitWithTimeout',
)(new AwaitWithTimeoutInput($intervalObject, $conditions));
}
/**
* Calculate unblocked conditions.
*/
public function resolveConditions(): void
{
foreach ($this->awaits as $awaitsGroupId => $awaitsGroup) {
foreach ($awaitsGroup as $i => [$condition, $deferred]) {
if ($condition()) {
unset($this->awaits[$awaitsGroupId][$i]);
$deferred->resolve(null);
$this->resolveConditionGroup($awaitsGroupId);
}
}
}
}
public function resolveConditionGroup(string $conditionGroupId): void
{
unset($this->awaits[$conditionGroupId]);
}
public function rejectConditionGroup(string $conditionGroupId): void
{
unset($this->awaits[$conditionGroupId]);
}
public function uuid(): PromiseInterface
{
return $this->sideEffect(static fn(): UuidInterface => \Ramsey\Uuid\Uuid::uuid4());
}
public function uuid4(): PromiseInterface
{
return $this->sideEffect(static fn(): UuidInterface => \Ramsey\Uuid\Uuid::uuid4());
}
public function uuid7(?\DateTimeInterface $dateTime = null): PromiseInterface
{
return $this->sideEffect(static fn(): UuidInterface => \Ramsey\Uuid\Uuid::uuid7($dateTime));
}
public function getLogger(): LoggerInterface
{
return $this->services->logger;
}
/**
* @internal
*/
public function getHandlerState(): HandlerState
{
return $this->handlers;
}
/**
* @internal
*/
#[\Override]
public function destroy(): void
{
$this->awaits = [];
$this->client->destroy();
$this->queryDispatcher->destroy();
$this->signalDispatcher->destroy();
$this->updateDispatcher->destroy();
$this->workflowInstance->destroy();
unset($this->workflowInstance, $this->client);
}
public function getQueryDispatcher(): QueryDispatcher
{
return $this->queryDispatcher;
}
public function getSignalDispatcher(): SignalDispatcher
{
return $this->signalDispatcher;
}
public function getUpdateDispatcher(): UpdateDispatcher
{
return $this->updateDispatcher;
}
/**
* Get the current details of the workflow execution.
*/
public function getCurrentDetails(): ?string
{
return $this->currentDetails;
}
/**
* Set the current details of the workflow execution.
*/
public function setCurrentDetails(?string $details): void
{
$this->currentDetails = $details;
}
protected function awaitRequest(callable|Mutex|PromiseInterface ...$conditions): PromiseInterface
{
$result = [];
$conditionGroupId = Uuid::v4();
$this->recordTrace();
foreach ($conditions as $condition) {
// Wrap Mutex into callable
$condition instanceof Mutex and $condition = static fn(): bool => !$condition->isLocked();
if ($condition instanceof \Closure) {
$callableResult = $condition($conditionGroupId);
if ($callableResult === true) {
$this->resolveConditionGroup($conditionGroupId);
return resolve(true);
}
$result[] = $this->addCondition($conditionGroupId, $condition);
continue;
}
if ($condition instanceof PromiseInterface) {
$result[] = $condition;
}
}
if (\count($result) === 1) {
return $result[0];
}
return Promise::any($result)->then(
function (mixed $result) use ($conditionGroupId): mixed {
$this->resolveConditionGroup($conditionGroupId);
return $result;
},
function (\Throwable $reason) use ($conditionGroupId): void {
$this->rejectConditionGroup($conditionGroupId);
// Throw the first reason
// It need to avoid memory leak when the related workflow is destroyed
if (\is_iterable($reason)) {
foreach ($reason as $exception) {
if ($exception instanceof \Throwable) {
throw $exception;
}
}
}
},
);
}
/**
* @param non-empty-string $conditionGroupId
*/
protected function addCondition(string $conditionGroupId, callable $condition): PromiseInterface
{
$deferred = new Deferred();
$this->awaits[$conditionGroupId][] = [$condition, $deferred];
return $deferred->promise();
}
/**
* Record last stack trace of the call.
*/
protected function recordTrace(): void
{
$this->readonly or $this->trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS);
}
}