-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEntityContext.php
More file actions
199 lines (175 loc) · 6.26 KB
/
Copy pathEntityContext.php
File metadata and controls
199 lines (175 loc) · 6.26 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
<?php
/*
* Copyright ©2024 Robert Landers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the “Software”), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
* OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Bottledcode\DurablePhp;
use Bottledcode\DurablePhp\Events\RaiseEvent;
use Bottledcode\DurablePhp\Events\StartExecution;
use Bottledcode\DurablePhp\Events\TaskCompleted;
use Bottledcode\DurablePhp\Events\WithDelay;
use Bottledcode\DurablePhp\Events\WithEntity;
use Bottledcode\DurablePhp\Events\WithOrchestration;
use Bottledcode\DurablePhp\Exceptions\Unwind;
use Bottledcode\DurablePhp\Glue\Provenance;
use Bottledcode\DurablePhp\Proxy\SpyProxy;
use Bottledcode\DurablePhp\State\EntityHistory;
use Bottledcode\DurablePhp\State\EntityId;
use Bottledcode\DurablePhp\State\Ids\StateId;
use Bottledcode\DurablePhp\State\OrchestrationInstance;
use Closure;
use Crell\Serde\Attributes\ClassSettings;
use DateTimeImmutable;
use DateTimeInterface;
use Exception;
use Ramsey\Uuid\Uuid;
use ReflectionClass;
use ReflectionFunction;
use RuntimeException;
use Throwable;
#[ClassSettings(includeFieldsByDefault: false)]
class EntityContext implements EntityContextInterface
{
private static ?EntityContextInterface $current = null;
public function __construct(
private readonly EntityId $id,
private readonly string $operation,
private readonly mixed $input,
private mixed $state,
private readonly EntityHistory $history,
private readonly Task $eventDispatcher,
private readonly array $caller,
private readonly string $requestingId,
private readonly SpyProxy $spyProxy,
private readonly Provenance $user,
) {
self::$current = $this;
}
public static function current(): static
{
return self::$current ?? throw new RuntimeException('Not in an entity context');
}
public function delete(): never
{
$this->history->delete();
throw new Unwind('delete');
}
public function getInput(): mixed
{
return $this->input;
}
public function return(mixed $value): never
{
foreach ($this->caller as $caller) {
$this->eventDispatcher->fire(
WithOrchestration::forInstance($caller, TaskCompleted::forId($this->requestingId, $value)),
);
}
throw new Unwind('return');
}
public function setState(mixed $value): void
{
$this->history->setState($value);
$this->state = $value;
}
public function signalEntity(
EntityId $entityId,
string $operation,
array $input = [],
?DateTimeImmutable $scheduledTime = null,
): void {
$event = WithEntity::forInstance(
StateId::fromEntityId($entityId),
RaiseEvent::forOperation($operation, $input),
);
if ($scheduledTime) {
$event = WithDelay::forEvent($scheduledTime, $event);
}
$this->eventDispatcher->fire($event);
}
public function getId(): EntityId
{
return $this->id;
}
public function getOperation(): string
{
return $this->operation;
}
public function startNewOrchestration(string $orchestration, array $input = [], ?string $id = null): void
{
if ($id === null) {
$id = Uuid::uuid7()->toString();
}
$instance = StateId::fromInstance(new OrchestrationInstance($orchestration, $id));
$this->eventDispatcher->fire(
WithOrchestration::forInstance(
$instance,
StartExecution::asParent($input, []),
),
);
}
public function delay(Closure $self, DateTimeInterface $until = new DateTimeImmutable()): void
{
$classReflector = new ReflectionClass($this->history->getState());
$interfaces = $classReflector->getInterfaceNames();
if (count($interfaces) > 1) {
throw new Exception('Cannot delay an entity with more than one interface');
}
$fnReflector = new ReflectionFunction($self);
if ($fnReflector->getNumberOfParameters() > 0) {
throw new Exception('Cannot delay a function with parameters');
}
// create the spy proxy and capture the invoked operation
$spy = $this->spyProxy->define($interfaces[0]);
$operationName = null;
$arguments = null;
$class = new $spy($operationName, $arguments);
$self = $self->bindTo($class, $class);
try {
$self();
} catch (Throwable) {
// the spy always throws when an operation is invoked
}
if ($operationName === null || $arguments === null) {
throw new Exception('Did not call an operation');
}
$this->delayUntil($operationName, $arguments, $until);
}
public function getState(): mixed
{
return $this->state;
}
public function delayUntil(
string $operation,
array $args = [],
DateTimeInterface $until = new DateTimeImmutable(),
): void {
$this->eventDispatcher->fire(
WithDelay::forEvent(
$until,
WithEntity::forInstance(StateId::fromEntityId($this->id), RaiseEvent::forOperation($operation, $args)),
),
);
}
public function currentUserId(): string
{
return $this->user->userId;
}
}