-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeaseManager.php
More file actions
93 lines (80 loc) · 2.71 KB
/
LeaseManager.php
File metadata and controls
93 lines (80 loc) · 2.71 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
<?php
declare(strict_types=1);
namespace Arcp\Runtime;
use Arcp\Clock\ClockInterface;
use Arcp\Clock\SystemClock;
use Arcp\Errors\LeaseExpiredException;
use Arcp\Errors\LeaseRevokedException;
use Arcp\Errors\NotFoundException;
use Arcp\Ids\LeaseId;
use Arcp\Messages\Permissions\LeaseGranted;
use Arcp\Messages\Permissions\LeaseRevoked;
/**
* Tracks the {@see LeaseGranted} state per session (RFC §15.5). Throws
* the right typed exception for revoked / expired / unknown lookups.
*/
final class LeaseManager
{
/** @var array<string, LeaseGranted> */
private array $byId = [];
/** @var array<string, string> revoked lease id → reason */
private array $revoked = [];
public function __construct(private readonly ClockInterface $clock = new SystemClock())
{
}
public function register(LeaseGranted $lease): void
{
$this->byId[(string) $lease->leaseId] = $lease;
}
public function get(LeaseId $id): LeaseGranted
{
$key = (string) $id;
if (isset($this->revoked[$key])) {
throw new LeaseRevokedException($id, $this->revoked[$key]);
}
$lease = $this->byId[$key] ?? throw new NotFoundException(\sprintf('lease %s not found', $id));
if ($lease->expiresAt <= $this->clock->now()) {
throw new LeaseExpiredException($id, $lease->expiresAt);
}
return $lease;
}
public function ensureUsable(LeaseId $id, string $permission, string $resource, string $operation): LeaseGranted
{
$lease = $this->get($id);
if ($lease->permission !== $permission || $lease->resource !== $resource || $lease->operation !== $operation) {
throw new \Arcp\Errors\PermissionDeniedException($permission, $resource, 'lease scope mismatch');
}
return $lease;
}
public function extend(LeaseId $id, \DateTimeImmutable $newExpiresAt): LeaseGranted
{
$lease = $this->get($id);
$extended = new LeaseGranted(
$lease->leaseId,
$lease->permission,
$lease->resource,
$lease->operation,
$newExpiresAt,
);
$this->byId[(string) $id] = $extended;
return $extended;
}
public function revoke(LeaseId $id, string $reason = ''): LeaseRevoked
{
$key = (string) $id;
if (isset($this->byId[$key])) {
unset($this->byId[$key]);
}
$this->revoked[$key] = $reason;
return new LeaseRevoked($id, $reason);
}
public function isRevoked(LeaseId $id): bool
{
return isset($this->revoked[(string) $id]);
}
/** @return list<LeaseGranted> */
public function all(): array
{
return array_values($this->byId);
}
}