-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathScope.php
More file actions
580 lines (489 loc) · 16.4 KB
/
Copy pathScope.php
File metadata and controls
580 lines (489 loc) · 16.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
<?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\Process;
use Internal\Destroy\Destroyable;
use React\Promise\Deferred;
use React\Promise\PromiseInterface;
use Temporal\DataConverter\EncodedValues;
use Temporal\DataConverter\ValuesInterface;
use Temporal\Exception\DestructMemorizedInstanceException;
use Temporal\Exception\Failure\CanceledFailure;
use Temporal\Exception\Failure\TemporalFailure;
use Temporal\Exception\InvalidArgumentException;
use Temporal\Interceptor\WorkflowInbound\UpdateInput;
use Temporal\Internal\Declaration\MethodHandler;
use Temporal\Internal\ServiceContainer;
use Temporal\Internal\Transport\Request\Cancel;
use Temporal\Internal\Workflow\ScopeContext;
use Temporal\Internal\Workflow\WorkflowContext;
use Temporal\Worker\FeatureFlags;
use Temporal\Worker\LoopInterface;
use Temporal\Worker\Transport\Command\RequestInterface;
use Temporal\Workflow;
use Temporal\Workflow\CancellationScopeInterface;
/**
* Unlike Java implementation, PHP has merged coroutine and cancellation scope into a single instance.
*
* @internal CoroutineScope is an internal library class, please do not use it in your code.
* @psalm-internal Temporal\Internal
* @implements CancellationScopeInterface<mixed>
*/
class Scope implements CancellationScopeInterface, Destroyable
{
protected ServiceContainer $services;
/**
* Workflow context.
*
* @psalm-suppress PropertyNotSetInConstructor
*/
protected WorkflowContext $context;
/**
* Coroutine scope context.
*
* @psalm-suppress PropertyNotSetInConstructor
*/
protected ScopeContext $scopeContext;
protected Deferred $deferred;
/**
* Worker handler generator that yields promises and requests that are processed in the {@see self::next()} method.
*/
protected DeferredGenerator $coroutine;
/**
* Every coroutine runs on its own loop layer.
*
* @var non-empty-string
*/
private string $layer = LoopInterface::ON_TICK;
/**
* Each onCancel receives unique ID.
*/
private int $cancelID = 0;
/**
* @var array<callable>
*/
private array $onCancel = [];
/**
* @var array<callable(mixed): mixed>
*/
private array $onClose = [];
private bool $detached = false;
private bool $cancelled = false;
private bool $closed = false;
private ?\Throwable $cancelReason = null;
public function __construct(
ServiceContainer $services,
) {
$this->services = $services;
$this->deferred = new Deferred();
}
/**
* @return non-empty-string
*/
public function getLayer(): string
{
return $this->layer;
}
public function isDetached(): bool
{
return $this->detached;
}
public function isCancelled(): bool
{
return $this->cancelled;
}
public function getContext(): WorkflowContext
{
return $this->context;
}
/**
* @param MethodHandler|\Closure(ValuesInterface): mixed $handler
*/
public function start(MethodHandler|\Closure $handler, ValuesInterface $values, bool $deferred): void
{
// Create a coroutine generator
$this->coroutine = DeferredGenerator::fromHandler($handler, $values)
->catch($this->onException(...));
$deferred
? $this->services->loop->once($this->layer, $this->next(...))
: $this->next();
}
/**
* @param callable(ValuesInterface): mixed $handler Update method handler.
* @param Deferred $resolver Update method promise resolver.
*/
public function startUpdate(callable $handler, UpdateInput $input, Deferred $resolver): void
{
// Update handler counter
$id = $this->context->getHandlerState()->addUpdate($input->updateId, $input->updateName);
$this->then(
fn() => $this->context->getHandlerState()->removeUpdate($id),
fn() => $this->context->getHandlerState()->removeUpdate($id),
);
$this->then(
$resolver->resolve(...),
function (\Throwable $error) use ($resolver): void {
$this->services->exceptionInterceptor->isRetryable($error)
? $this->scopeContext->panic($error)
: $resolver->reject($error);
},
);
// Create a coroutine generator
$this->coroutine = $this->callSignalOrUpdateHandler($handler, $input->arguments);
$this->next();
}
/**
* @param callable(ValuesInterface): mixed $handler
* @param non-empty-string $name
*/
public function startSignal(callable $handler, ValuesInterface $values, string $name): void
{
// Update handler counter
$id = $this->context->getHandlerState()->addSignal($name);
$this->then(
fn() => $this->context->getHandlerState()->removeSignal($id),
fn() => $this->context->getHandlerState()->removeSignal($id),
);
// Create a coroutine generator
$this->coroutine = $this->callSignalOrUpdateHandler($handler, $values);
$this->next();
}
/**
* @return $this
*/
public function attach(\Generator $generator): self
{
$this->coroutine = DeferredGenerator::fromGenerator($generator)
->catch($this->onException(...));
$this->next();
return $this;
}
public function onCancel(callable $then): self
{
$this->addOnCancel($then);
return $this;
}
/**
* @param callable(mixed): mixed $then An exception instance is passed in case of error.
* @return $this
*/
public function onClose(callable $then): self
{
$this->onClose[] = $then;
return $this;
}
public function cancel(?\Throwable $reason = null): void
{
if ($this->detached && !$reason instanceof DestructMemorizedInstanceException) {
// detaches scopes can be offload via memory flush
return;
}
if ($this->cancelled) {
return;
}
$this->cancelled = true;
$this->cancelReason = $reason;
foreach ($this->onCancel as $i => $handler) {
$this->makeCurrent();
unset($this->onCancel[$i]);
$handler($reason);
}
}
/**
* @param non-empty-string|null $layer
*/
public function startScope(callable $handler, bool $detached, ?string $layer = null): CancellationScopeInterface
{
$scope = $this->createScope($detached, $layer);
$scope->start($handler(...), EncodedValues::empty(), false);
return $scope;
}
public function promise(): PromiseInterface
{
return $this->deferred->promise();
}
public function then(
?callable $onFulfilled = null,
?callable $onRejected = null,
?callable $onProgress = null,
): PromiseInterface {
return $this->deferred->promise()->then($onFulfilled, $onRejected);
}
public function catch(callable $onRejected): PromiseInterface
{
return $this->deferred->promise()->catch($onRejected);
}
public function finally(callable $onFulfilledOrRejected): PromiseInterface
{
return $this->deferred->promise()->finally($onFulfilledOrRejected);
}
/**
* @deprecated use {@see catch()} instead
*/
public function otherwise(callable $onRejected): PromiseInterface
{
return $this->catch($onRejected);
}
/**
* @deprecated use {@see finally()} instead
*/
public function always(callable $onFulfilledOrRejected): PromiseInterface
{
return $this->finally($onFulfilledOrRejected);
}
/**
* Connects promise to scope context to be cancelled on promise cancel.
*/
public function onAwait(Deferred $deferred): void
{
$cancelID = $this->addOnCancel(static function (?\Throwable $e = null) use ($deferred): void {
$deferred->reject($e ?? new CanceledFailure(''));
});
// do not cancel already complete promises
$cleanup = function () use ($cancelID): void {
$this->makeCurrent();
$this->context->resolveConditions();
unset($this->onCancel[$cancelID]);
};
$deferred->promise()->then($cleanup, $cleanup);
}
public function destroy(): void
{
$this->context?->destroy();
$this->scopeContext?->destroy();
unset(
$this->coroutine,
$this->context,
$this->scopeContext,
$this->deferred,
$this->services,
$this->onCancel,
$this->onClose,
);
}
/**
* @param non-empty-string|null $layer
*/
protected function createScope(
bool $detached,
?string $layer = null,
?WorkflowContext $context = null,
?Workflow\UpdateContext $updateContext = null,
): self {
$scope = new Scope($this->services);
$scope->setContext($context ?? $this->context, $updateContext);
$scope->detached = $detached;
if ($layer !== null) {
$scope->layer = $layer;
}
$cancelID = $this->addOnCancel($scope->cancel(...));
$scope->onClose(
function () use ($cancelID): void {
unset($this->onCancel[$cancelID]);
},
);
return $scope;
}
protected function setContext(WorkflowContext $ctx, ?Workflow\UpdateContext $updateContext = null): void
{
$this->context = $ctx;
$this->scopeContext = ScopeContext::fromWorkflowContext(
$this->context,
$this,
$this->onRequest(...),
$updateContext,
);
}
/**
* Call a Signal or Update method. In this case deserialization errors are skipped.
*
* @param callable(ValuesInterface): mixed $handler
*/
protected function callSignalOrUpdateHandler(callable $handler, ValuesInterface $values): DeferredGenerator
{
return DeferredGenerator::fromHandler(static function (ValuesInterface $values) use ($handler): mixed {
try {
return $handler($values);
} catch (InvalidArgumentException) {
// Skip deserialization errors
return null;
}
}, $values)->catch($this->onException(...));
}
protected function onRequest(RequestInterface $request, PromiseInterface $promise, bool $cancellable = true): void
{
$cancelID = $this->addOnCancel(function (?\Throwable $reason = null) use ($request, $cancellable): void {
$client = $this->context->getClient();
if ($reason instanceof DestructMemorizedInstanceException) {
// memory flush
$client->reject($request, $reason);
return;
}
if ($client->isQueued($request)) {
$client->cancel($request);
return;
}
if (!$cancellable) {
// non-cancellable request
return;
}
$client->request(new Cancel($request->getID()), $this->scopeContext);
}, $cancellable);
// do not cancel already complete promises
$cleanup = function () use ($cancelID): void {
$this->makeCurrent();
$this->context->resolveConditions();
unset($this->onCancel[$cancelID]);
};
$promise->then($cleanup, $cleanup);
}
protected function makeCurrent(): void
{
Workflow::setCurrentContext($this->scopeContext);
}
protected function next(): void
{
$this->makeCurrent();
begin:
$this->context->resolveConditions();
try {
if (!$this->coroutine->valid()) {
$this->onResult($this->coroutine->getReturn());
return;
}
} catch (\Throwable) {
$this->onResult(null);
return;
}
$current = $this->coroutine->current();
$this->context->resolveConditions();
switch (true) {
case $current instanceof Workflow\Mutex:
$this->nextPromise($this->context->await($current));
break;
case $current instanceof PromiseInterface:
$this->nextPromise($current);
break;
case $current instanceof Deferred:
$this->nextPromise($current->promise());
break;
// todo ->context or ->scopeContext?
case $current instanceof RequestInterface:
$this->nextPromise($this->context->getClient()->request($current, $this->scopeContext));
break;
case $current instanceof \Generator:
$this->nextPromise($this->createScope(false)->attach($current));
break;
default:
try {
$this->coroutine->send($current);
} catch (\Throwable) {
// Ignore
}
goto begin;
}
}
private function addOnCancel(callable $handler, bool $cancellable = true): int
{
$id = ++$this->cancelID;
if (FeatureFlags::$propagateCancellationToNewScopes && $this->cancelled && $cancellable) {
$this->makeCurrent();
$handler($this->cancelReason);
return $id;
}
$this->onCancel[$id] = $handler;
return $id;
}
private function nextPromise(PromiseInterface $promise): void
{
if ($promise instanceof CancellationScopeInterface && $promise->isCancelled()) {
$reason = FeatureFlags::$propagateCancellationToNewScopes && $promise instanceof self
? $promise->cancelReason
: null;
$this->handleError($reason ?? new CanceledFailure(''));
return;
}
$onFulfilled = function (mixed $result): mixed {
$this->defer(
function () use ($result): void {
$this->makeCurrent();
try {
$this->coroutine->send($result);
$this->next();
} catch (\Throwable $e) {
$this->onException($e);
return;
}
},
);
return $result;
};
$onRejected = function (\Throwable $e): void {
$this->defer(
function () use ($e): void {
if ($e instanceof TemporalFailure && !$e->hasOriginalStackTrace()) {
$e->setOriginalStackTrace($this->context->getStackTrace());
}
$this->handleError($e);
},
);
throw $e;
};
$promise
->then($onFulfilled, $onRejected)
// Handle last error
->then(null, static fn(\Throwable $e) => null);
}
/**
* Send error into the coroutine. If the code inside handles exception
* we continue the flow. If the exception is bubbled up - the scope
* itself handles it.
*/
private function handleError(\Throwable $e): void
{
$this->makeCurrent();
try {
$this->coroutine->throw($e);
} catch (\Throwable $e) {
$this->onException($e);
return;
}
$this->next();
}
private function onException(\Throwable $e): void
{
if ($this->closed) {
return;
}
$this->closed = true;
$this->deferred->reject($e);
$this->makeCurrent();
$this->context->resolveConditions();
foreach ($this->onClose as $close) {
$close($e);
}
}
private function onResult(mixed $result): void
{
if ($this->closed) {
return;
}
$this->closed = true;
$this->deferred->resolve($result);
$this->makeCurrent();
$this->context->resolveConditions();
foreach ($this->onClose as $close) {
$close($result);
}
}
private function defer(\Closure $tick): void
{
$this->services->loop->once($this->layer, $tick);
$this->services->queue->count() === 0 and $this->services->loop->tick();
}
}