-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJobManager.php
More file actions
83 lines (71 loc) · 1.97 KB
/
JobManager.php
File metadata and controls
83 lines (71 loc) · 1.97 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
<?php
declare(strict_types=1);
namespace Arcp\Runtime;
use Amp\DeferredCancellation;
use Arcp\Errors\NotFoundException;
use Arcp\Ids\JobId;
use Arcp\Ids\MessageId;
use Arcp\Ids\TraceId;
/**
* Tracks in-flight jobs and drives the state machine (RFC §10.2). Each
* job runs in its own fiber via {@see async()}; cancellation is
* cooperative through the per-job {@see DeferredCancellation}.
*/
final class JobManager
{
/** @var array<string, Job> */
private array $jobs = [];
public function __construct()
{
}
public function start(
Session $session,
MessageId $invocationId,
?TraceId $traceId,
string $tool,
): Job {
$job = new Job(
id: JobId::random(),
session: $session,
invocationId: $invocationId,
traceId: $traceId,
cancellation: new DeferredCancellation(),
tool: $tool,
);
$this->jobs[(string) $job->id] = $job;
return $job;
}
public function get(JobId $id): Job
{
return $this->jobs[(string) $id] ?? throw new NotFoundException(\sprintf('job %s not found', $id));
}
public function tryGet(JobId $id): ?Job
{
return $this->jobs[(string) $id] ?? null;
}
public function transition(Job $job, JobState $next): void
{
$job->state = $next;
if ($next->isTerminal()) {
unset($this->jobs[(string) $job->id]);
}
}
public function cancel(JobId $id, string $reason = 'user_aborted'): bool
{
$job = $this->tryGet($id);
if ($job === null || $job->state->isTerminal()) {
return false;
}
$job->cancellation->cancel(new \Amp\CancelledException(new \RuntimeException($reason)));
return true;
}
/** @return list<Job> */
public function all(): array
{
return array_values($this->jobs);
}
public function count(): int
{
return \count($this->jobs);
}
}