-
Notifications
You must be signed in to change notification settings - Fork 129
Expand file tree
/
Copy pathInMemorySessionStore.php
More file actions
88 lines (70 loc) · 2.15 KB
/
InMemorySessionStore.php
File metadata and controls
88 lines (70 loc) · 2.15 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
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Server\Session;
use Mcp\Server\NativeClock;
use Psr\Clock\ClockInterface;
use Symfony\Component\Uid\Uuid;
class InMemorySessionStore implements SessionStoreInterface
{
/**
* @var array<string, array{ data: string, timestamp: int }>
*/
protected array $store = [];
public function __construct(
protected readonly int $ttl = 3600,
protected readonly ClockInterface $clock = new NativeClock(),
) {
}
public function exists(Uuid $id): bool
{
return isset($this->store[$id->toRfc4122()]);
}
public function read(Uuid $id): string|false
{
$session = $this->store[$id->toRfc4122()] ?? '';
if ('' === $session) {
return false;
}
$currentTimestamp = $this->clock->now()->getTimestamp();
if ($currentTimestamp - $session['timestamp'] > $this->ttl) {
unset($this->store[$id->toRfc4122()]);
return false;
}
return $session['data'];
}
public function write(Uuid $id, string $data): bool
{
$this->store[$id->toRfc4122()] = [
'data' => $data,
'timestamp' => $this->clock->now()->getTimestamp(),
];
return true;
}
public function destroy(Uuid $id): bool
{
if (isset($this->store[$id->toRfc4122()])) {
unset($this->store[$id->toRfc4122()]);
}
return true;
}
public function gc(): array
{
$currentTimestamp = $this->clock->now()->getTimestamp();
$deletedSessions = [];
foreach ($this->store as $sessionId => $session) {
$sessionId = Uuid::fromString($sessionId);
if ($currentTimestamp - $session['timestamp'] > $this->ttl) {
unset($this->store[$sessionId->toRfc4122()]);
$deletedSessions[] = $sessionId;
}
}
return $deletedSessions;
}
}