summaryrefslogtreecommitdiff
path: root/tests/temporal/Workflow/CancelledWithCompensationWorkflow.php
blob: 2074aac163c0daa0ae0445155c563c3884f72541 (plain)
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
<?php

namespace Temporal\Tests\Workflow;

use Temporal\Activity\ActivityOptions;
use Temporal\Exception\Failure\CanceledFailure;
use Temporal\Tests\Activity\SimpleActivity;
use Temporal\Workflow;
use Temporal\Workflow\WorkflowMethod;

#[Workflow\WorkflowInterface]
class CancelledWithCompensationWorkflow
{
    private array $status = [];

    #[Workflow\QueryMethod(name: 'getStatus')]
    public function getStatus(): array
    {
        return $this->status;
    }

    #[WorkflowMethod(name: 'CancelledWithCompensationWorkflow')]
    public function handler()
    {
        $simple = Workflow::newActivityStub(
            SimpleActivity::class,
            ActivityOptions::new()->withStartToCloseTimeout(5)
        );

        // waits for 2 seconds
        $slow = $simple->slow('DOING SLOW ACTIVITY');

        try {
            $this->status[] = 'yield';
            $result = yield $slow;
        } catch (CanceledFailure $e) {
            $this->status[] = 'rollback';

            try {
                // must fail again
                $result = yield $slow;
            } catch (CanceledFailure $e) {
                $this->status[] = 'captured retry';
            }

            try {
                // fail since on cancelled context
                $result = yield $simple->echo('echo must fail');
            } catch (CanceledFailure $e) {
                $this->status[] = 'captured promise on cancelled';
            }

            $scope = Workflow::newDetachedCancellationScope(
                function () use ($simple) {
                    $this->status[] = 'START rollback';

                    $second = yield $simple->echo('rollback');

                    $this->status[] = sprintf("RESULT (%s)", $second);

                    if ($second !== 'ROLLBACK') {
                        $this->status[] = 'FAIL rollback';
                        return 'failed to compensate ' . $second;
                    }
                    $this->status[] = 'DONE rollback';

                    return 'OK';
                }
            );

            $this->status[] = 'WAIT ROLLBACK';
            $result = yield $scope;
            $this->status[] = 'COMPLETE rollback';
        }

        $this->status[] = 'result: ' . $result;
        return $result;
    }
}