Repository navigation
Expand file tree
/
Copy pathProtocol.php
More file actions
1509 lines (1252 loc) · 58.1 KB
/
Copy pathProtocol.php
File metadata and controls
1509 lines (1252 loc) · 58.1 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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?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;
use Mcp\Schema\Exception\InvalidInputMessageException;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\MessageInterface;
use Mcp\Schema\JsonRpc\Notification;
use Mcp\Schema\JsonRpc\Request;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\JsonRpc\ResultInterface;
use Mcp\Schema\MessageFactory;
use Mcp\Schema\Request\InitializeRequest;
use Mcp\Schema\Request\ResourceSubscribeRequest;
use Mcp\Schema\Request\ResourceUnsubscribeRequest;
use Mcp\Schema\Request\SetLogLevelRequest;
use Mcp\Server\Authorization\AccessToken;
use Mcp\Server\Event\ClientResponseEvent;
use Mcp\Server\Event\ErrorEvent;
use Mcp\Server\Event\NotificationEvent;
use Mcp\Server\Event\RequestEvent;
use Mcp\Server\Event\ResponseEvent;
use Mcp\Server\Event\ServerRequestEvent;
use Mcp\Server\Exception\ConfigurationException;
use Mcp\Server\Exception\RuntimeException;
use Mcp\Server\Exception\SessionLockException;
use Mcp\Server\Exception\SessionLockTimeoutException;
use Mcp\Server\Exception\SessionRequiredException;
use Mcp\Server\Exception\SessionStoreException;
use Mcp\Server\Fiber\EventLoopSessionLock;
use Mcp\Server\Fiber\FiberContextInterface;
use Mcp\Server\Fiber\FiberSchedulerInterface;
use Mcp\Server\Fiber\HandlerFibers;
use Mcp\Server\Handler\Notification\NotificationHandlerInterface;
use Mcp\Server\Handler\Request\RequestHandlerInterface;
use Mcp\Server\Session\EphemeralSession;
use Mcp\Server\Session\EphemeralSessionInterface;
use Mcp\Server\Session\SessionInterface;
use Mcp\Server\Session\SessionLockInterface;
use Mcp\Server\Session\SessionManagerInterface;
use Mcp\Server\Stateless\InputContext;
use Mcp\Server\Stateless\RequestStateCodec;
use Mcp\Server\Suspension\NotificationSuspension;
use Mcp\Server\Suspension\RequestSuspension;
use Mcp\Server\Transport\StreamableHttpTransport;
use Mcp\Server\Transport\TransportInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Symfony\Component\Uid\Uuid;
/**
* @final
*
* @phpstan-import-type McpFiber from TransportInterface
* @phpstan-import-type FiberSuspend from TransportInterface
*
* @author Christopher Hertel <mail@christopher-hertel.de>
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class Protocol
{
/** Session key for pending outgoing requests */
private const SESSION_PENDING_REQUESTS = '_mcp.pending_requests';
/** Session key for incoming client responses */
private const SESSION_RESPONSES = '_mcp.responses';
/** Session key for outgoing message queue */
private const SESSION_OUTGOING_QUEUE = '_mcp.outgoing_queue';
/** Session key for active request meta */
public const SESSION_ACTIVE_REQUEST_META = '_mcp.active_request_meta';
public const SESSION_LOGGING_LEVEL = '_mcp.logging_level';
private const SESSION_NOT_FOUND_MESSAGE = 'Session not found or has expired.';
/** Session key for the fingerprint of the principal that opened the session, null when it was opened without one */
private const SESSION_PRINCIPAL = '_mcp.principal';
/** Requests whose effect has to outlast them, which a server without sessions cannot keep. */
private const SESSION_SCOPED_REQUESTS = [
ResourceSubscribeRequest::class,
ResourceUnsubscribeRequest::class,
SetLogLevelRequest::class,
];
/**
* Deliberately generic: unexpected throwables carry internal details such as file paths, class
* names and argument types, which must not be handed to the peer. The full exception is logged.
*/
private const INTERNAL_ERROR_MESSAGE = 'Internal server error.';
/** Answer to a request that could not get its session's lock in time, see {@see SessionLockInterface}. */
private const SESSION_BUSY_MESSAGE = 'Another request of this session is still being processed.';
/**
* Seconds past its timeout after which a pending client request counts as abandoned by its stream.
* Until then, the stream that sent it expires it itself and reports the timeout.
*/
private const ABANDONED_REQUEST_GRACE = 60;
/**
* The client request each suspended fiber waits on. Pending requests are stored in the session,
* which concurrent calls share, so a fiber must only be resumed with the answer to the one it sent.
*
* @var \WeakMap<McpFiber, Uuid>
*/
private \WeakMap $awaitedRequestIds;
/**
* What each transport's fiber sends the client, kept out of the session for the same reason:
* a request or notification must go out on the stream of the call that produced it.
*
* @var \WeakMap<TransportInterface<mixed>, list<array{message: string, context: array<string, mixed>}>>
*/
private \WeakMap $fiberOutgoingMessages;
/**
* Awaited requests another worker dropped as abandoned, e.g. while this one could not get the session
* lock to expire them: their fiber is still owed the timeout.
*
* @var array<string, true>
*/
private array $droppedAwaitedRequestIds = [];
private readonly ?SessionLockInterface $sessionLock;
/**
* @param array<int, RequestHandlerInterface<ResultInterface|array<string, mixed>>> $requestHandlers
* @param array<int, NotificationHandlerInterface> $notificationHandlers
* @param bool $sessionless serve each handshake-era request over Streamable HTTP
* on a session of its own, without a `Mcp-Session-Id`
*/
public function __construct(
private readonly array $requestHandlers,
private readonly array $notificationHandlers,
private readonly MessageFactory $messageFactory,
private readonly SessionManagerInterface $sessionManager,
private readonly LoggerInterface $logger = new NullLogger(),
private readonly ?EventDispatcherInterface $eventDispatcher = null,
private readonly ?InputRequiredShim $inputRequiredShim = null,
private readonly ?RequestStateCodec $requestStateCodec = null,
?SessionLockInterface $sessionLock = null,
private readonly ?FiberSchedulerInterface $fiberScheduler = null,
private readonly ?FiberContextInterface $fiberContext = null,
private readonly bool $sessionless = false,
) {
$this->sessionLock = null !== $sessionLock && null !== $fiberScheduler ? new EventLoopSessionLock($sessionLock, $fiberScheduler) : $sessionLock;
$this->awaitedRequestIds = new \WeakMap();
$this->fiberOutgoingMessages = new \WeakMap();
}
/**
* Connect this protocol to transport.
*
* The protocol takes ownership of the transport and sets up all callbacks.
*
* @param TransportInterface<mixed> $transport
*/
public function connect(TransportInterface $transport): void
{
$transport->onMessage($this->processInput(...));
if ($this->isSessionless($transport)) {
$transport->setSessionless(true);
}
$transport->onSessionEnd($this->endSession(...));
// The transport keeps these callbacks, so they reference it weakly to not keep it alive.
$transportRef = \WeakReference::create($transport);
$transport->setOutgoingMessagesProvider(fn (Uuid $sessionId): array => [
...$this->takeFiberOutgoingMessages($transportRef->get()),
...($this->isSessionless($transportRef->get()) ? [] : $this->consumeOutgoingMessages($sessionId)),
]);
$transport->setPendingRequestsProvider(fn (Uuid $sessionId, \Fiber $fiber): array => $this->getAwaitedPendingRequests($fiber, $sessionId));
$transport->setResponseFinder($this->checkResponse(...));
$transport->setFiberYieldHandler(function (mixed $yieldedValue, ?Uuid $sessionId, \Fiber $fiber) use ($transportRef): void {
$this->trackAwaitedRequest($fiber, $this->handleFiberYield($yieldedValue, $sessionId, $transportRef->get()));
});
$this->logger->info('Protocol connected to transport', ['transport' => $transport::class]);
}
/**
* Handle an incoming message from the transport.
*
* This is called by the transport whenever ANY message arrives.
*
* @param TransportInterface<mixed> $transport
* @param AccessToken|null $accessToken the token the input was authorized with, if the transport authorizes
* @param string|null $principal who the input was authenticated as, if the transport authenticates
*/
public function processInput(TransportInterface $transport, string $input, ?Uuid $sessionId, ?AccessToken $accessToken = null, ?string $principal = null): void
{
// Last line of defense: a malformed message must never escape as a PHP error and take the
// server process down.
try {
$this->doProcessInput($transport, $input, $sessionId, $accessToken, $principal);
} catch (\Throwable $e) {
$this->logger->error(\sprintf('Uncaught exception while processing input: %s', $e->getMessage()), ['exception' => $e]);
// Only a request may be answered. Replying to a notification would violate JSON-RPC,
// and the failure has already been logged.
if (null === $id = self::findResponseId($input)) {
return;
}
try {
$this->sendResponse($transport, Error::forInternalError(self::INTERNAL_ERROR_MESSAGE, $id), null, ['status_code' => 500]);
} catch (\Throwable $e) {
$this->logger->error(\sprintf('Failed to send internal error response: %s', $e->getMessage()), ['exception' => $e]);
}
}
}
/**
* Determines the id an unprocessable input has to be answered under.
*
* Returns null when the input carries no request at all, in which case it consists of
* notifications and client responses only, and JSON-RPC forbids answering it: an error
* under a response's id would read as the answer to the client's own request of that id.
*/
private static function findResponseId(string $input): string|int|null
{
try {
$data = json_decode($input, true, flags: \JSON_THROW_ON_ERROR);
} catch (\JsonException) {
return null;
}
if (!\is_array($data)) {
return null;
}
$id = $data['id'] ?? null;
return isset($data['method']) && (\is_string($id) || \is_int($id)) ? $id : null;
}
/**
* @param TransportInterface<mixed> $transport
*/
private function doProcessInput(TransportInterface $transport, string $input, ?Uuid $sessionId, ?AccessToken $accessToken, ?string $principal): void
{
$this->logger->info('Received message to process.');
$this->logger->debug('Received message payload.', ['message' => $input]);
$this->sessionManager->gc();
try {
$message = $this->messageFactory->create($input);
} catch (\JsonException $e) {
$this->logger->warning('Failed to decode json message.', ['exception' => $e]);
$error = Error::forParseError($e->getMessage());
// The status keeps a refusal from carrying the queue of a session nobody checked yet, here and below.
$this->sendResponse($transport, $error, null, ['status_code' => 400]);
return;
} catch (InvalidInputMessageException $e) {
// Answered within the session like any other message, after it was resolved.
$message = $e;
}
// Taken before the session is read and held until it is saved, so no other request of
// the session reads a state this one is about to replace. An `initialize` never reads an
// existing session and an unknown session id is refused by resolveSession(), so neither
// needs the lock. The session is looked up again under the lock, as it may have ended
// while this request waited.
$takesLock = null !== $sessionId && null !== $this->sessionLock && !$message instanceof InitializeRequest && $this->sessionManager->exists($sessionId);
if ($takesLock) {
// Who opened the session is checked before waiting for the lock too, so that another
// principal can neither tell the session is busy nor keep it busy.
try {
$session = $this->sessionManager->createWithId($sessionId);
$serves = $this->servesPrincipal($session, $principal);
} catch (SessionStoreException $e) {
$this->refuseUnavailableStore($transport, $sessionId, self::findResponseId($input), $e);
return;
}
if (!$serves) {
$this->refuseOtherPrincipal($transport, $session);
return;
}
try {
$refusal = $this->acquireSessionLock($sessionId) ? null : Error::forServerError(self::SESSION_BUSY_MESSAGE, self::findResponseId($input));
} catch (SessionLockException) {
$refusal = Error::forInternalError('Session lock is unavailable.', self::findResponseId($input));
}
if (null !== $refusal) {
$this->sendResponse($transport, $refusal, null, ['status_code' => 503]);
return;
}
}
try {
$this->handleMessage($transport, $sessionId, $message, $accessToken, $principal);
} finally {
if ($takesLock) {
$this->releaseSessionLock($sessionId);
}
}
}
/**
* @param TransportInterface<mixed> $transport
*/
private function handleMessage(TransportInterface $transport, ?Uuid $sessionId, MessageInterface|InvalidInputMessageException $message, ?AccessToken $accessToken, ?string $principal): void
{
$session = $this->resolveSession($transport, $sessionId, $message, $principal);
if (null === $session) {
return;
}
try {
if ($message instanceof InvalidInputMessageException) {
$this->handleInvalidMessage($transport, $message, $session);
} elseif ($message instanceof Request) {
$this->handleRequest($transport, $message, $session, $accessToken);
} elseif ($message instanceof Response || $message instanceof Error) {
$this->handleResponse($message, $session);
} elseif ($message instanceof Notification) {
$this->handleNotification($message, $session);
}
} catch (\Throwable $e) {
$this->logger->error(\sprintf('Uncaught exception while handling message: %s', $e->getMessage()), ['exception' => $e]);
// Only a request may be answered; a notification or a response must not produce one.
if ($message instanceof Request) {
$error = Error::forInternalError(self::INTERNAL_ERROR_MESSAGE, $message->getId());
$this->sendResponse($transport, $error, $session);
}
}
if ($session instanceof EphemeralSessionInterface) {
return;
}
try {
$session->save();
} catch (\Throwable $e) {
// The responses already reached the transport: an error for the same requests would contradict them.
$this->logger->error(\sprintf('Failed to save session: %s', $e->getMessage()), ['exception' => $e]);
}
}
/**
* Handle an invalid message from the transport.
*
* @param TransportInterface<mixed> $transport
* @param array<string, mixed> $context
*/
private function handleInvalidMessage(TransportInterface $transport, InvalidInputMessageException $exception, ?SessionInterface $session, array $context = []): void
{
$this->logger->warning('Failed to create message.', ['exception' => $exception]);
$error = $exception->isInvalidParams()
? Error::forInvalidParams($exception->getMessage(), $exception->getRequestId())
: Error::forInvalidRequest($exception->getMessage(), $exception->getRequestId());
$this->sendResponse($transport, $error, $session, $context);
}
/**
* Dispatches an event through the event dispatcher if available.
*
* @template T of object
*
* @param T $event
*
* @return T
*/
private function dispatchEvent(object $event): object
{
if (null === $this->eventDispatcher) {
return $event;
}
$dispatched = $this->eventDispatcher->dispatch($event);
// PSR-14 dispatchers return the event they were given; a dispatcher that
// swaps it for something else is not what the caller asked to dispatch.
if (!$dispatched instanceof $event) {
$this->logger->debug('Event dispatcher returned a different object than it was given; keeping the original.', [
'event' => $event::class,
'returned' => $dispatched::class,
]);
return $event;
}
return $dispatched;
}
/**
* Handle a request from the transport.
*
* @param TransportInterface<mixed> $transport
*/
private function handleRequest(TransportInterface $transport, Request $request, SessionInterface $session, ?AccessToken $accessToken): void
{
$this->logger->info('Handling request.', ['method' => $request::getMethod(), 'request_id' => $request->getId()]);
$session->set(self::SESSION_ACTIVE_REQUEST_META, $request->getMeta());
// Overwritten on every request, so a token never carries over to a later
// request of the same session; AccessToken serializes to null.
$session->set(AccessToken::class, $accessToken);
// A request starts with nothing behind it: the shim fills this in as it
// collects answers, and clearing it here is what keeps one request's
// round from being read as another's.
$session->set(InputContext::class, null);
if (null !== $this->requestStateCodec) {
$session->set(RequestStateCodec::class, $this->requestStateCodec);
}
$event = $this->dispatchEvent(new RequestEvent($request, $session));
$request = $event->getRequest();
if ($session instanceof EphemeralSessionInterface && \in_array($request::class, self::SESSION_SCOPED_REQUESTS, true)) {
$error = Error::forInternalError(\sprintf('"%s" needs a session, and this server runs without sessions.', $request::getMethod()), $request->getId());
$this->sendResponse($transport, $this->dispatchEvent(new ErrorEvent($error, $request, $session, null))->getError(), $session);
return;
}
$handlerFound = false;
foreach ($this->requestHandlers as $handler) {
if (!$handler->supports($request)) {
continue;
}
$handlerFound = true;
try {
$shim = $this->inputRequiredShim;
$codec = $this->requestStateCodec;
$dispatchResult = $this->dispatchResult(...);
$errorForThrowable = $this->errorForThrowable(...);
$saveResumedSession = $this->saveResumedSession(...);
// Weak: the fiber's state keeping this protocol alive segfaults PHP 8.1 when both are freed.
$protocol = \WeakReference::create($this);
/** @var bool $suspended set by reference once the fiber first suspended */
$suspended = false;
// One fiber for the whole exchange: with the shim, the handler
// re-enters inside it each round rather than needing a new one.
// Handled in the fiber, as the transport resumes it outside the catch below.
/** @var McpFiber $fiber */
$fiber = HandlerFibers::create(static function () use ($handler, $request, $session, $shim, $codec, $dispatchResult, $errorForThrowable, $saveResumedSession, &$suspended): Response|Error {
try {
$result = $handler->handle($request, $session);
$result = $shim?->fulfill($result, $handler, $request, $session, $codec) ?? $result;
if (HandlerFibers::isAbandoned()) {
return $result;
}
$result = $dispatchResult($result, $request, $session);
} catch (\Throwable $e) {
if (HandlerFibers::isAbandoned()) {
throw $e;
}
$result = $errorForThrowable($e, $request, $session);
}
// A fiber that never suspended is saved by doProcessInput(); after a resume nothing else saves it.
if ($suspended) {
$saveResumedSession($session);
}
return $result;
}, $this->fiberScheduler, static fn (\Throwable $e): ?Error => $protocol->get()?->errorForThrowable($e, $request, $session), $this->logger, $this->fiberContext);
$result = HandlerFibers::start($fiber);
if ($fiber->isSuspended()) {
$beforeSuspension = $session->all();
$awaitedRequestId = null;
$outgoing = null;
if ($result instanceof NotificationSuspension) {
$outgoing = $result->notification;
} elseif ($result instanceof RequestSuspension) {
if ($session instanceof EphemeralSessionInterface) {
throw new SessionRequiredException('Requests to the client need a session; configure one with Builder::setSession().');
}
$awaitedRequestId = $this->registerRequest($result->request, $result->timeout, $session);
$outgoing = $result->request->withId($awaitedRequestId->toRfc4122());
}
// The transport resumes the fiber from what the session holds: it must
// not get the fiber if the request the fiber awaits was not stored. A
// later save must not store that request either, nobody would resume it.
if (!$session instanceof EphemeralSessionInterface) {
try {
$saved = $session->save();
} catch (\Throwable $e) {
$session->hydrate($beforeSuspension);
throw $e;
}
if (!$saved) {
$session->hydrate($beforeSuspension);
throw new RuntimeException('Failed to save the session of a suspended request.');
}
}
$suspended = true;
$this->trackAwaitedRequest($fiber, $awaitedRequestId);
$transport->attachFiberToSession($fiber, $session->getId());
if (null !== $outgoing) {
$this->queueFiberOutgoing($transport, $outgoing);
}
return;
}
$this->sendResponse($transport, $fiber->getReturn(), $session);
} catch (\Throwable $e) {
$this->sendResponse($transport, $this->errorForThrowable($e, $request, $session), $session);
}
break;
}
if (!$handlerFound) {
$error = Error::forMethodNotFound(\sprintf('No handler found for method "%s".', $request::getMethod()), $request->getId());
$errorEvent = $this->dispatchEvent(new ErrorEvent($error, $request, $session, null));
$error = $errorEvent->getError();
$this->sendResponse($transport, $error, $session);
}
}
/**
* @param Response<array<string, mixed>>|Error $response
*/
private function handleResponse(Response|Error $response, SessionInterface $session): void
{
$this->logger->info('Handling response from client.', ['message_id' => $response->getId()]);
$messageId = $response->getId();
if (null === $messageId) {
$this->logger->warning('Received an id-less error response from client; cannot correlate it to a pending request.', ['response' => $response->jsonSerialize()]);
return;
}
// Request IDs are UUIDs: any other ID cannot be one the server sent.
$pending = \is_string($messageId) && Uuid::isValid($messageId) ? $session->get(self::SESSION_PENDING_REQUESTS, [])[$messageId] ?? null : null;
if (!\is_array($pending) || $this->hasTimedOut($pending)) {
$this->logger->warning('Received a client response for an unknown or timed out request ID.', ['message_id' => $messageId]);
return;
}
$this->dispatchEvent(new ClientResponseEvent($response, $session));
$session->set(self::SESSION_RESPONSES.".{$messageId}", $response->jsonSerialize());
$session->forget(self::SESSION_ACTIVE_REQUEST_META);
$this->logger->info('Client response stored in session', [
'message_id' => $messageId,
]);
}
private function handleNotification(Notification $notification, SessionInterface $session): void
{
$this->logger->info('Handling notification.', ['method' => $notification::getMethod()]);
$event = $this->dispatchEvent(new NotificationEvent($notification, $session));
$notification = $event->getNotification();
foreach ($this->notificationHandlers as $handler) {
if (!$handler->supports($notification)) {
continue;
}
try {
$handler->handle($notification, $session);
} catch (\Throwable $e) {
$this->logger->error(\sprintf('Error while handling notification: %s', $e->getMessage()), ['exception' => $e]);
}
}
}
/**
* Sends a request to the client and returns the request ID.
*/
public function sendRequest(Request $request, int $timeout, SessionInterface $session): Uuid
{
self::assertQueueable($session);
$requestId = $this->registerRequest($request, $timeout, $session);
$this->queueOutgoing($request->withId($requestId->toRfc4122()), ['type' => 'request'], $session);
return $requestId;
}
/**
* Picks the id of a request to the client and stores the request as pending in the session.
*
* The id is a UUID, not counted in the session: concurrent requests of a client load
* the session at the same time and would count up to the same id.
*/
private function registerRequest(Request $request, int $timeout, SessionInterface $session): Uuid
{
$requestId = Uuid::v4();
$id = $requestId->toRfc4122();
$this->dispatchEvent(new ServerRequestEvent($request->withId($id), $timeout, $session));
$this->logger->info('Queueing server request to client', [
'request_id' => $id,
'method' => $request::getMethod(),
]);
$this->dropAbandonedRequests($session);
// Per entry, so saving does not write back what other streams changed in the others.
$session->set(self::SESSION_PENDING_REQUESTS.".{$id}", [
'request_id' => $id,
'timeout' => $timeout,
'timestamp' => time(),
]);
return $requestId;
}
/**
* Queues a notification for later delivery.
*/
public function sendNotification(Notification $notification, SessionInterface $session): void
{
self::assertQueueable($session);
$this->logger->info('Queueing server notification to client', [
'method' => $notification::getMethod(),
]);
$this->queueOutgoing($notification, ['type' => 'notification'], $session);
}
/**
* @throws SessionRequiredException for the session of a server without sessions, which has no stream to deliver queued messages on
*/
private static function assertQueueable(SessionInterface $session): void
{
if ($session instanceof EphemeralSessionInterface) {
throw new SessionRequiredException('Messages sent outside a request need a session; configure one with Builder::setSession().');
}
}
/**
* Sends a response through the transport, on the exchange that carried its request.
*
* Responses never go through the session's outgoing queue: the session is shared by
* the concurrent requests of a client and written back whole, so a queued response
* could be overwritten by another request, or taken by it.
*
* @param TransportInterface<mixed> $transport
* @param Response<ResultInterface|array<string, mixed>>|Error $response
* @param array<string, mixed> $context
*/
private function sendResponse(TransportInterface $transport, Response|Error $response, ?SessionInterface $session, array $context = []): void
{
$this->logger->debug('Sending response', [
'response_id' => $response->getId(),
]);
try {
$encoded = json_encode($response, \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
$this->logger->error('Failed to encode response to JSON.', [
'message_id' => $response->getId(),
'exception' => $e,
]);
$fallbackError = new Error(
id: $response->getId(),
code: Error::INTERNAL_ERROR,
message: 'Response could not be encoded to JSON'
);
$encoded = json_encode($fallbackError, \JSON_THROW_ON_ERROR);
}
$context['type'] = 'response';
if (null !== $session) {
$context['session_id'] = $session->getId();
}
$transport->send($encoded, $context);
}
/**
* Helper to queue outgoing messages in session.
*
* @param array<string, mixed> $context
*/
private function queueOutgoing(Request|Notification $message, array $context, SessionInterface $session): void
{
if (null === $outgoing = $this->encodeOutgoing($message, $context)) {
return;
}
$queue = $session->get(self::SESSION_OUTGOING_QUEUE, []);
$queue[] = $outgoing;
$session->set(self::SESSION_OUTGOING_QUEUE, $queue);
}
/**
* Queues what a transport's fiber sends the client, for that transport alone.
*
* @param TransportInterface<mixed> $transport
*/
private function queueFiberOutgoing(TransportInterface $transport, Request|Notification $message): void
{
if (null === $outgoing = $this->encodeOutgoing($message, ['type' => $message instanceof Request ? 'request' : 'notification'])) {
return;
}
$queue = $this->fiberOutgoingMessages[$transport] ?? [];
$queue[] = $outgoing;
$this->fiberOutgoingMessages[$transport] = $queue;
}
/**
* @param TransportInterface<mixed>|null $transport
*
* @return list<array{message: string, context: array<string, mixed>}>
*/
private function takeFiberOutgoingMessages(?TransportInterface $transport): array
{
if (null === $transport || !isset($this->fiberOutgoingMessages[$transport])) {
return [];
}
$queue = $this->fiberOutgoingMessages[$transport];
unset($this->fiberOutgoingMessages[$transport]);
return $queue;
}
/**
* @param array<string, mixed> $context
*
* @return array{message: string, context: array<string, mixed>}|null
*/
private function encodeOutgoing(Request|Notification $message, array $context): ?array
{
try {
$encoded = json_encode($message, \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
$this->logger->error('Failed to encode message to JSON.', [
'exception' => $e,
]);
return null;
}
return [
'message' => $encoded,
'context' => $context,
];
}
/**
* Consume (get and clear) all outgoing messages for a session.
*
* @return array<int, array{message: string, context: array<string, mixed>}>
*/
public function consumeOutgoingMessages(Uuid $sessionId): array
{
if (!$this->tryAcquireSessionLockForPoll($sessionId)) {
return [];
}
try {
$session = $this->sessionManager->createWithId($sessionId);
$queue = $session->get(self::SESSION_OUTGOING_QUEUE, []);
// Saving an unchanged session would only overwrite what a concurrent request saved in the meantime.
if ([] !== $queue) {
$session->set(self::SESSION_OUTGOING_QUEUE, []);
$session->save();
}
return $queue;
} finally {
$this->releaseSessionLock($sessionId);
}
}
/**
* Check for a response to a specific request ID.
*
* When a response is found, it is removed from the session, and the
* corresponding pending request is also cleared. A request that got no
* answer within its timeout is cleared the same way and reported as an
* internal error, so its pending entry does not outlive the wait.
*
* @return Response<array<string, mixed>>|Error|null
*/
public function checkResponse(Uuid $requestId, Uuid $sessionId): Response|Error|null
{
$id = $requestId->toRfc4122();
if (isset($this->droppedAwaitedRequestIds[$id])) {
unset($this->droppedAwaitedRequestIds[$id]);
$this->settleAwaitedRequest($id);
$this->logger->warning('Client request timed out.', [
'request_id' => $id,
'session_id' => $sessionId->toRfc4122(),
]);
return Error::forInternalError('Request timed out', $id);
}
if (!$this->tryAcquireSessionLockForPoll($sessionId)) {
return null;
}
try {
$session = $this->sessionManager->createWithId($sessionId);
$responseData = $session->get(self::SESSION_RESPONSES.".{$id}");
if (null === $responseData) {
$pending = $session->get(self::SESSION_PENDING_REQUESTS, [])[$id] ?? null;
return \is_array($pending) && $this->hasTimedOut($pending) ? $this->expireRequest($requestId, $sessionId) : null;
}
$this->logger->debug('Found and consuming client response.', [
'request_id' => $id,
'session_id' => $sessionId->toRfc4122(),
]);
$session->set(self::SESSION_RESPONSES.".{$id}", null);
$session->forget(self::SESSION_PENDING_REQUESTS.".{$id}");
$session->save();
$this->settleAwaitedRequest($id);
} finally {
$this->releaseSessionLock($sessionId);
}
try {
if (isset($responseData['error'])) {
return Error::fromArray($responseData);
}
return Response::fromArray($responseData);
} catch (\Throwable $e) {
$this->logger->error('Failed to reconstruct client response from session.', [
'request_id' => $id,
'exception' => $e,
'response_data' => $responseData,
]);
return null;
}
}
/**
* Drops a timed out request from the pending ones and reports the timeout.
*
* The session is loaded again as the caller's copy may be as old as the last
* poll, and saving it back would undo what other streams stored since.
*/
private function expireRequest(Uuid $requestId, Uuid $sessionId): ?Error
{
$id = $requestId->toRfc4122();
$session = $this->sessionManager->createWithId($sessionId);
$pending = $session->get(self::SESSION_PENDING_REQUESTS, []);
// Answered or expired by another stream in the meantime: the next poll sorts it out.
if (!isset($pending[$id]) || null !== $session->get(self::SESSION_RESPONSES.".{$id}")) {
return null;
}
$this->logger->warning('Client request timed out.', [
'request_id' => $id,
'session_id' => $sessionId->toRfc4122(),
]);
$session->forget(self::SESSION_PENDING_REQUESTS.".{$id}");
$session->save();
$this->settleAwaitedRequest($id);
return Error::forInternalError('Request timed out', $id);
}
/**
* Drops the pending client requests, and their unconsumed answers, that no stream waits for anymore.
*
* Only the stream that sent a request clears it, so one whose stream is gone, through a client
* disconnect or a dead worker, would stay until the session expires.
*/
private function dropAbandonedRequests(SessionInterface $session): void
{
// A fiber of this process still waits on these, e.g. on stdio while another handler blocked the loop.
$awaited = [];
foreach ($this->awaitedRequestIds as $requestId) {
$awaited[$requestId->toRfc4122()] = true;
}
foreach ($session->get(self::SESSION_PENDING_REQUESTS, []) as $id => $pending) {
if (isset($awaited[$id]) || !\is_array($pending) || time() < (int) ($pending['timestamp'] ?? 0) + (int) ($pending['timeout'] ?? 120) + self::ABANDONED_REQUEST_GRACE) {
continue;
}
$this->logger->debug('Dropping abandoned client request.', [
'request_id' => $id,
'session_id' => $session->getId()->toRfc4122(),
]);
// Per entry, so saving does not write back what other streams changed in the others. The answer
// may have been stored after this session was loaded: set() makes forget() record its removal.
$session->forget(self::SESSION_PENDING_REQUESTS.".{$id}");
$session->set(self::SESSION_RESPONSES.".{$id}", null);
$session->forget(self::SESSION_RESPONSES.".{$id}");
}
}
/**
* @param array<mixed> $pending
*/
private function hasTimedOut(array $pending): bool
{
return time() - (int) ($pending['timestamp'] ?? 0) >= (int) ($pending['timeout'] ?? 120);
}
/**
* Get pending requests for a session.
*
* @return array<string, mixed> The pending requests
*/
public function getPendingRequests(Uuid $sessionId): array
{
$session = $this->sessionManager->createWithId($sessionId);
return $session->get(self::SESSION_PENDING_REQUESTS, []);
}
/**
* Handle values yielded by Fibers during transport-managed resumes.
*
* With the transport the fiber runs on, what it sends goes out on that transport alone;
* without one, it is queued for whichever stream of the session asks first.
*
* @param FiberSuspend|null $yieldedValue
* @param TransportInterface<mixed>|null $transport
*
* @return Uuid|null the ID of the request sent to the client, which the fiber now waits on
*/
public function handleFiberYield(mixed $yieldedValue, ?Uuid $sessionId, ?TransportInterface $transport = null): ?Uuid
{
if (!$sessionId) {
$this->logger->warning('Fiber yielded value without associated session context.');
return null;
}
if (!$yieldedValue instanceof NotificationSuspension && !$yieldedValue instanceof RequestSuspension) {
$this->logger->warning('Fiber yielded unexpected payload.', [
'payload' => $yieldedValue,
'session_id' => $sessionId->toRfc4122(),