-
Notifications
You must be signed in to change notification settings - Fork 129
Expand file tree
/
Copy pathSessionManager.php
More file actions
86 lines (75 loc) · 2.64 KB
/
SessionManager.php
File metadata and controls
86 lines (75 loc) · 2.64 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
<?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\Exception\InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Symfony\Component\Uid\Uuid;
/**
* Default implementation of SessionManagerInterface.
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class SessionManager implements SessionManagerInterface
{
/**
* @param int $gcProbability The probability (numerator) that GC will run on any given request. Combined with $gcDivisor to calculate the actual probability. Set to 0 to disable GC. Similar to PHP's session.gc_probability.
* @param int $gcDivisor The divisor used with $gcProbability to calculate GC probability. The probability is gcProbability/gcDivisor (e.g. 1/100 = 1%). Similar to PHP's session.gc_divisor.
*/
public function __construct(
private readonly SessionStoreInterface $store,
private readonly LoggerInterface $logger = new NullLogger(),
private readonly int $gcProbability = 1,
private readonly int $gcDivisor = 100,
) {
if ($gcProbability < 0) {
throw new InvalidArgumentException('gcProbability must be greater than or equal to 0.');
}
if ($gcDivisor < 1) {
throw new InvalidArgumentException('gcDivisor must be greater than or equal to 1.');
}
}
public function create(): SessionInterface
{
return new Session($this->store, Uuid::v4());
}
public function createWithId(Uuid $id): SessionInterface
{
return new Session($this->store, $id);
}
public function exists(Uuid $id): bool
{
return $this->store->exists($id);
}
public function destroy(Uuid $id): bool
{
return $this->store->destroy($id);
}
/**
* Run garbage collection on expired sessions.
* Uses the session store's internal TTL configuration.
*/
public function gc(): void
{
if (0 === $this->gcProbability) {
return;
}
if (random_int(1, $this->gcDivisor) > $this->gcProbability) {
return;
}
$deletedSessions = $this->store->gc();
if (!empty($deletedSessions)) {
$this->logger->debug('Garbage collected expired sessions.', [
'count' => \count($deletedSessions),
'session_ids' => array_map(static fn (Uuid $id) => $id->toRfc4122(), $deletedSessions),
]);
}
}
}