| 1: | <?php |
| 2: | |
| 3: | declare(strict_types=1); |
| 4: | |
| 5: | |
| 6: | |
| 7: | |
| 8: | |
| 9: | |
| 10: | |
| 11: | |
| 12: | |
| 13: | |
| 14: | namespace Nexus\Mcp\Client\Transport; |
| 15: | |
| 16: | use Nexus\Assert\Assert; |
| 17: | use Nexus\Mcp\Core\Exception\SupervisionExhaustedException; |
| 18: | use Nexus\Mcp\Core\Exception\TransportAlreadyClosedException; |
| 19: | use Nexus\Mcp\Core\Exception\TransportAlreadyStartedException; |
| 20: | use Nexus\Mcp\Core\Exception\TransportNotStartedException; |
| 21: | use Nexus\Mcp\Core\Schema\JsonRpc\JsonRpcMessage; |
| 22: | use Nexus\Mcp\Core\Transport\ReconnectingTransportInterface; |
| 23: | use Nexus\Mcp\Core\Transport\SendContext; |
| 24: | use Nexus\Mcp\Core\Transport\Subscription; |
| 25: | use Nexus\Mcp\Core\Transport\SubscriptionInterface; |
| 26: | use Nexus\Mcp\Core\Transport\SupervisableTransportInterface; |
| 27: | use Nexus\Mcp\Core\Transport\TransportEvents; |
| 28: | use Nexus\Mcp\Core\Transport\TransportState; |
| 29: | use Psr\Log\LoggerInterface; |
| 30: | use Psr\Log\NullLogger; |
| 31: | use Revolt\EventLoop; |
| 32: | |
| 33: | |
| 34: | |
| 35: | |
| 36: | |
| 37: | |
| 38: | |
| 39: | final class SupervisedTransport implements ReconnectingTransportInterface |
| 40: | { |
| 41: | |
| 42: | |
| 43: | |
| 44: | public const float DEFAULT_RESTART_WINDOW = 60.0; |
| 45: | |
| 46: | private const string LABEL = 'Supervised client'; |
| 47: | |
| 48: | private readonly TransportEvents $events; |
| 49: | private readonly LoggerInterface $logger; |
| 50: | |
| 51: | |
| 52: | |
| 53: | |
| 54: | private readonly \Closure $clock; |
| 55: | |
| 56: | private TransportState $state = TransportState::Idle; |
| 57: | private ?SupervisableTransportInterface $inner = null; |
| 58: | |
| 59: | |
| 60: | |
| 61: | |
| 62: | private bool $connectionEnded = true; |
| 63: | |
| 64: | |
| 65: | |
| 66: | |
| 67: | private int $restarts = 0; |
| 68: | |
| 69: | |
| 70: | |
| 71: | |
| 72: | private float $windowStartedAt = 0.0; |
| 73: | |
| 74: | |
| 75: | |
| 76: | |
| 77: | private array $subscriptions = []; |
| 78: | |
| 79: | |
| 80: | |
| 81: | |
| 82: | private array $reconnectListeners = []; |
| 83: | |
| 84: | private ?string $respawnWatcher = null; |
| 85: | |
| 86: | |
| 87: | |
| 88: | |
| 89: | |
| 90: | private bool $respawning = false; |
| 91: | |
| 92: | |
| 93: | |
| 94: | |
| 95: | |
| 96: | |
| 97: | |
| 98: | |
| 99: | public function __construct( |
| 100: | private readonly \Closure $factory, |
| 101: | private readonly int $maxRestarts = 3, |
| 102: | private readonly float $restartDelay = 0.1, |
| 103: | LoggerInterface $logger = new NullLogger(), |
| 104: | private readonly float $restartWindow = self::DEFAULT_RESTART_WINDOW, |
| 105: | ?\Closure $clock = null, |
| 106: | ) { |
| 107: | Assert::that($maxRestarts)->isPositiveInt('maxRestarts must be a positive integer, {value} given.'); |
| 108: | Assert::that($restartDelay)->isBetween(0.0, \PHP_FLOAT_MAX, message: 'restartDelay must not be negative, {value} given.'); |
| 109: | Assert::that($restartWindow)->isBetween(\PHP_FLOAT_EPSILON, \PHP_FLOAT_MAX, message: 'restartWindow must be positive, {value} given.'); |
| 110: | |
| 111: | $this->logger = $logger; |
| 112: | $this->clock = $clock ?? static fn(): float => microtime(true); |
| 113: | $this->events = new TransportEvents(); |
| 114: | } |
| 115: | |
| 116: | #[\Override] |
| 117: | public function start(): void |
| 118: | { |
| 119: | match ($this->state) { |
| 120: | TransportState::Running => throw new TransportAlreadyStartedException(transport: self::class), |
| 121: | TransportState::Closed => throw new TransportAlreadyClosedException(operation: 'start'), |
| 122: | TransportState::Idle => null, |
| 123: | }; |
| 124: | |
| 125: | |
| 126: | |
| 127: | $this->spawn(); |
| 128: | $this->state = TransportState::Running; |
| 129: | } |
| 130: | |
| 131: | #[\Override] |
| 132: | public function send(JsonRpcMessage $message, ?SendContext $context = null): void |
| 133: | { |
| 134: | if (TransportState::Idle === $this->state) { |
| 135: | throw new TransportNotStartedException(operation: 'send'); |
| 136: | } |
| 137: | |
| 138: | |
| 139: | |
| 140: | if (null === $this->inner) { |
| 141: | throw new TransportAlreadyClosedException(operation: 'send'); |
| 142: | } |
| 143: | |
| 144: | $this->inner->send($message, $context); |
| 145: | } |
| 146: | |
| 147: | #[\Override] |
| 148: | public function close(): void |
| 149: | { |
| 150: | |
| 151: | $this->state = TransportState::Closed; |
| 152: | |
| 153: | |
| 154: | |
| 155: | |
| 156: | |
| 157: | $abandonsAReplacement = $this->respawning && $this->connectionEnded; |
| 158: | $this->respawning = false; |
| 159: | |
| 160: | if (null !== $this->respawnWatcher) { |
| 161: | EventLoop::cancel($this->respawnWatcher); |
| 162: | $this->respawnWatcher = null; |
| 163: | } |
| 164: | |
| 165: | try { |
| 166: | |
| 167: | $this->endConnection(); |
| 168: | |
| 169: | if ($abandonsAReplacement) { |
| 170: | try { |
| 171: | $this->events->emitClose(); |
| 172: | } catch (\Throwable $e) { |
| 173: | |
| 174: | |
| 175: | $this->events->emitError($e); |
| 176: | } |
| 177: | } |
| 178: | } finally { |
| 179: | $this->retireConnection(); |
| 180: | } |
| 181: | } |
| 182: | |
| 183: | #[\Override] |
| 184: | public function onMessage(\Closure $listener): SubscriptionInterface |
| 185: | { |
| 186: | return $this->events->onMessage($listener); |
| 187: | } |
| 188: | |
| 189: | #[\Override] |
| 190: | public function onError(\Closure $listener): SubscriptionInterface |
| 191: | { |
| 192: | return $this->events->onError($listener); |
| 193: | } |
| 194: | |
| 195: | #[\Override] |
| 196: | public function onDrain(\Closure $listener): SubscriptionInterface |
| 197: | { |
| 198: | return $this->events->onDrain($listener); |
| 199: | } |
| 200: | |
| 201: | #[\Override] |
| 202: | public function onClose(\Closure $listener): SubscriptionInterface |
| 203: | { |
| 204: | return $this->events->onClose($listener); |
| 205: | } |
| 206: | |
| 207: | #[\Override] |
| 208: | public function isReconnecting(): bool |
| 209: | { |
| 210: | return $this->respawning; |
| 211: | } |
| 212: | |
| 213: | #[\Override] |
| 214: | public function onReconnect(\Closure $listener): SubscriptionInterface |
| 215: | { |
| 216: | $id = spl_object_id($listener); |
| 217: | $this->reconnectListeners[$id] = $listener; |
| 218: | |
| 219: | return new Subscription(function () use ($id): void { |
| 220: | unset($this->reconnectListeners[$id]); |
| 221: | }); |
| 222: | } |
| 223: | |
| 224: | |
| 225: | |
| 226: | |
| 227: | |
| 228: | |
| 229: | |
| 230: | private function spawn(): void |
| 231: | { |
| 232: | $inner = ($this->factory)(); |
| 233: | $this->inner = $inner; |
| 234: | |
| 235: | |
| 236: | $this->connectionEnded = false; |
| 237: | |
| 238: | $this->subscriptions = [ |
| 239: | $inner->onMessage($this->events->emitMessage(...)), |
| 240: | $inner->onError($this->events->emitError(...)), |
| 241: | $inner->onDrain($this->events->emitDrain(...)), |
| 242: | $inner->onClose($this->endConnection(...)), |
| 243: | $inner->onUnexpectedExit(function (?int $exitCode): void { |
| 244: | try { |
| 245: | $this->endConnection(); |
| 246: | } finally { |
| 247: | |
| 248: | $this->scheduleRespawn($exitCode); |
| 249: | } |
| 250: | }), |
| 251: | ]; |
| 252: | |
| 253: | try { |
| 254: | $inner->start(); |
| 255: | } catch (\Throwable $e) { |
| 256: | |
| 257: | |
| 258: | $this->connectionEnded = true; |
| 259: | $this->releaseConnection(); |
| 260: | |
| 261: | throw $e; |
| 262: | } |
| 263: | } |
| 264: | |
| 265: | |
| 266: | |
| 267: | |
| 268: | |
| 269: | private function endConnection(): void |
| 270: | { |
| 271: | if ($this->connectionEnded) { |
| 272: | return; |
| 273: | } |
| 274: | |
| 275: | $this->connectionEnded = true; |
| 276: | $this->events->emitClose(); |
| 277: | } |
| 278: | |
| 279: | private function scheduleRespawn(?int $exitCode): void |
| 280: | { |
| 281: | if (TransportState::Running !== $this->state) { |
| 282: | return; |
| 283: | } |
| 284: | |
| 285: | $now = ($this->clock)(); |
| 286: | |
| 287: | |
| 288: | |
| 289: | |
| 290: | |
| 291: | |
| 292: | if (0 === $this->restarts || $this->restartWindow < $now - $this->windowStartedAt) { |
| 293: | $this->restarts = 0; |
| 294: | $this->windowStartedAt = $now; |
| 295: | } |
| 296: | |
| 297: | ++$this->restarts; |
| 298: | |
| 299: | if ($this->restarts > $this->maxRestarts) { |
| 300: | $this->logger->error( |
| 301: | '{label} transport exhausted its restart budget of {budget}.', |
| 302: | ['label' => self::LABEL, 'budget' => $this->maxRestarts], |
| 303: | ); |
| 304: | |
| 305: | try { |
| 306: | $this->events->emitError(new SupervisionExhaustedException($this->maxRestarts)); |
| 307: | } finally { |
| 308: | $this->close(); |
| 309: | } |
| 310: | |
| 311: | return; |
| 312: | } |
| 313: | |
| 314: | $this->logger->warning( |
| 315: | '{label} transport respawning the peer after an unexpected exit (code {exitCode}), attempt {attempt} of {budget}.', |
| 316: | ['label' => self::LABEL, 'exitCode' => $exitCode ?? 'unknown', 'attempt' => $this->restarts, 'budget' => $this->maxRestarts], |
| 317: | ); |
| 318: | |
| 319: | |
| 320: | |
| 321: | $this->respawning = true; |
| 322: | |
| 323: | $this->retireConnection(); |
| 324: | |
| 325: | |
| 326: | |
| 327: | |
| 328: | if (TransportState::Running !== $this->state) { |
| 329: | return; |
| 330: | } |
| 331: | |
| 332: | |
| 333: | $this->respawnWatcher = EventLoop::delay($this->restartDelay, function (): void { |
| 334: | $this->respawnWatcher = null; |
| 335: | |
| 336: | try { |
| 337: | $this->spawn(); |
| 338: | } catch (\Throwable $e) { |
| 339: | |
| 340: | |
| 341: | $this->events->emitError($e); |
| 342: | $this->scheduleRespawn(null); |
| 343: | |
| 344: | return; |
| 345: | } |
| 346: | |
| 347: | |
| 348: | |
| 349: | if (TransportState::Running !== $this->state) { |
| 350: | |
| 351: | |
| 352: | return; |
| 353: | } |
| 354: | |
| 355: | $this->respawning = false; |
| 356: | |
| 357: | |
| 358: | |
| 359: | foreach ($this->reconnectListeners as $listener) { |
| 360: | try { |
| 361: | $listener(); |
| 362: | } catch (\Throwable $e) { |
| 363: | |
| 364: | |
| 365: | $this->events->emitError($e); |
| 366: | } |
| 367: | } |
| 368: | }); |
| 369: | } |
| 370: | |
| 371: | |
| 372: | |
| 373: | |
| 374: | private function retireConnection(): void |
| 375: | { |
| 376: | $inner = $this->inner; |
| 377: | |
| 378: | try { |
| 379: | |
| 380: | |
| 381: | $inner?->close(); |
| 382: | } finally { |
| 383: | $this->releaseConnection(); |
| 384: | } |
| 385: | } |
| 386: | |
| 387: | |
| 388: | |
| 389: | |
| 390: | private function releaseConnection(): void |
| 391: | { |
| 392: | foreach ($this->subscriptions as $subscription) { |
| 393: | $subscription->dispose(); |
| 394: | } |
| 395: | |
| 396: | $this->subscriptions = []; |
| 397: | $this->inner = null; |
| 398: | } |
| 399: | } |
| 400: | |