From b294f40e111f3cdca45ebd5a066443bb6a772fcb Mon Sep 17 00:00:00 2001 From: Valithor Obsidion Date: Wed, 11 Nov 2026 10:38:36 -0500 Subject: [PATCH] Contain WebAPI failures and signal portable restarts --- .github/workflows/portable.yml | 6 ++ bot.php | 48 +-------- src/Civ13/Civ13.php | 19 +++- src/Civ13/HttpErrorBoundary.php | 94 ++++++++++++++++++ src/Civ13/HttpHandler.php | 2 +- tests/local/library.php | 9 +- tests/local/webapi-errors.php | 154 +++++++++++++++++++++++++++++ tests/windows/portable-restart.php | 94 ++++++++++++++++++ 8 files changed, 378 insertions(+), 48 deletions(-) create mode 100644 src/Civ13/HttpErrorBoundary.php create mode 100644 tests/local/webapi-errors.php create mode 100644 tests/windows/portable-restart.php diff --git a/.github/workflows/portable.yml b/.github/workflows/portable.yml index accbeaa9..0ec043db 100644 --- a/.github/workflows/portable.yml +++ b/.github/workflows/portable.yml @@ -46,6 +46,12 @@ jobs: - run: php tests/windows/bootstrap.php - run: php tests/windows/bootstrap.php --negative-control - run: php tests/windows/process.php + - name: Contained WebAPI errors (offline) + timeout-minutes: 2 + run: php -d allow_url_fopen=0 -d disable_functions=fsockopen,pfsockopen,stream_socket_client,stream_socket_server,stream_socket_accept,curl_exec,curl_multi_exec,socket_create,exec,shell_exec,system,passthru,proc_open,popen tests/local/webapi-errors.php + - name: Portable restart contracts (offline) + timeout-minutes: 2 + run: php -d allow_url_fopen=0 -d disable_functions=fsockopen,pfsockopen,stream_socket_client,stream_socket_server,stream_socket_accept,curl_exec,curl_multi_exec,socket_create,exec,shell_exec,system,passthru,proc_open,popen tests/windows/portable-restart.php - run: php tests/windows/shell-guard.php - run: php tests/windows/ready.php - run: php tests/windows/ready.php vendor/autoload.php --hosted diff --git a/bot.php b/bot.php index 81cd2d9e..53b6cf2b 100644 --- a/bot.php +++ b/bot.php @@ -620,7 +620,8 @@ function loadEnv(string $filePath, bool $explicit = false): array * @param ServerRequestInterface $request The HTTP request object. * @return Response The HTTP response object. */ -$webapi = new HttpServer(Loop::get(), async(function (ServerRequestInterface $request) use (&$civ13, &$logger): Response { +$httpErrors = new HttpErrorBoundary($logger, [$hidden_options['http_key']]); +$webapi = new HttpServer(Loop::get(), $httpErrors, async(function (ServerRequestInterface $request) use (&$civ13, &$logger): Response { /** @var ?Civ13 $civ13 */ if (! $civ13 || ! $civ13 instanceof Civ13) { $logger->warning('Civ13 instance not found. Please check the server settings.'); @@ -638,49 +639,8 @@ function loadEnv(string $filePath, bool $explicit = false): array return $civ13->httpServiceManager->handle($request); })); -/** - * This code snippet handles the error event of the web API. - * It logs the error message, file, line, and trace, and handles specific error cases. - * If the error message starts with 'Received request with invalid protocol version', it is ignored. - * If the error message starts with 'The response callback', it triggers a restart process. - * The restart process includes sending a message to a specific Discord channel and closing the socket connection. - * After a delay of 5 seconds, the script is restarted by calling the 'restart' function and closing the Discord connection. - * - * @param Exception $e The exception object representing the error. - * @param \Psr\Http\Message\RequestInterface|null $request The HTTP request object associated with the error, if available. - * @param object $civ13 The main object of the application. - * @param object $socket The socket object. - * @param bool $testing Flag indicating if the script is running in testing mode. - */ -$webapi->on('error', async(function (Exception $e, ?\Psr\Http\Message\RequestInterface $request = null) use (&$civ13, &$logger, &$socket) { - if ( - str_starts_with($e->getMessage(), 'Received request with invalid protocol version') - ) { - return; - } // Ignore this error, it's not important - $error = "[WEBAPI] {$e->getMessage()} [{$e->getFile()}:{$e->getLine()}] ".str_replace('\n', PHP_EOL, $e->getTraceAsString()); - $logger->error("[WEBAPI] $error"); - if ($request) { - $logger->error('[WEBAPI] Request: '.preg_replace('/(?<=key=)[^&]+/', '********', $request->getRequestTarget())); - } - if (str_starts_with($e->getMessage(), 'The response callback')) { - $logger->info('[WEBAPI] ERROR - RESTART'); - /** @var ?Civ13 $civ13 */ - if (! $civ13) { - return; - } - if (! getenv('testing') && isset($civ13->channel_ids['staff_bot']) && $channel = $civ13->discord->getChannel($civ13->channel_ids['staff_bot'])) { - $builder = Civ13::createBuilder() - ->setContent('Restarting due to error in HttpServer API...') - ->addFileFromContent('httpserver_error.txt', preg_replace('/(?<=key=)[^&]+/', '********', $error)); - $channel->sendMessage($builder); - } - $socket->close(); - if (! isset($civ13->timers['restart'])) { - $civ13->timers['restart'] = Loop::addTimer(5, fn () => $civ13->restart()); - } - } -})); +// React handles failed requests with an error response; keep the listener and bot alive. +$webapi->on('error', $httpErrors->report(...)); //$events = ['MESSAGE_UPDATE']; //$eventLogger = new \EventLogger\EventLogger($discord, $events); diff --git a/src/Civ13/Civ13.php b/src/Civ13/Civ13.php index 36997e94..ebd8457a 100644 --- a/src/Civ13/Civ13.php +++ b/src/Civ13/Civ13.php @@ -269,6 +269,7 @@ class Civ13 private string $constructed_file; private RestartPolicy $restartPolicy; + private bool $portableRestartRequested = false; private PromiseMiddleware $then; @@ -1035,8 +1036,24 @@ private function stopCalendarSync(): void public function restart(?string $file = null): PromiseInterface { if (getenv('CIVILIZATIONBOT_PROFILE')) { + if ($file !== null) { throw new \InvalidArgumentException('Portable restart cannot select an entry point'); } + if ($this->portableRestartRequested) { return resolve(null); } + $state = $this->portable_state_dir; + try { + if ($state === '' || !PortableProfile::absolute($state) || !is_dir($state)) { + throw new \RuntimeException('Portable restart state unavailable'); + } + // A launcher stop wins. Its existing timer owns shutdown and marker cleanup. + if (is_file($state.'/stop.request')) { return resolve(null); } + // Publish intent before shutdown: a failed write must leave the bot running. + // An existing reload request already supplies the same one-use intent. + if (!is_file($state.'/reload.request')) { PortableProcess::requestReload($state); } + } catch (\Throwable $error) { + return \React\Promise\reject($error); + } $this->stop(); - return \React\Promise\resolve(null); // Portable supervisor owns relaunch. + $this->portableRestartRequested = true; + return resolve(null); // Only the portable supervisor may spawn the replacement. } return $this->restartPolicy->restart($file, fn () => $this->stop(), fn (?string $entry) => OSFunctions::restart($entry ?? $this->constructed_file)); } diff --git a/src/Civ13/HttpErrorBoundary.php b/src/Civ13/HttpErrorBoundary.php new file mode 100644 index 00000000..094fb181 --- /dev/null +++ b/src/Civ13/HttpErrorBoundary.php @@ -0,0 +1,94 @@ + $secrets Known credentials that must never enter diagnostics. */ + public function __construct(private LoggerInterface $logger, private array $secrets = []) {} + + public function __invoke(ServerRequestInterface $request, callable $next): ResponseInterface|PromiseInterface + { + try { + $response = $next($request); + if ($response instanceof PromiseInterface) { + return $response->then( + fn ($value) => $this->response($value, $request), + fn (\Throwable $error) => $this->failure($error, $request) + ); + } + return $this->response($response, $request); + } catch (\Throwable $error) { + return $this->failure($error, $request); + } + } + + private function response(mixed $response, ServerRequestInterface $request): ResponseInterface + { + if (!$response instanceof ResponseInterface) { + return $this->failure(new \UnexpectedValueException('HTTP handler returned '.get_debug_type($response).' instead of ResponseInterface'), $request); + } + return $response; + } + + private function failure(\Throwable $error, ServerRequestInterface $request): ResponseInterface + { + $this->report($error, $request); + return new Response(Response::STATUS_INTERNAL_SERVER_ERROR, ['Content-Type' => 'text/plain'], 'Internal Server Error'); + } + + /** React's error event supplies only the exception, not a request. Never restart here. */ + public function report(\Throwable $error, ?ServerRequestInterface $request = null): void + { + if (str_starts_with($error->getMessage(), 'Received request with invalid protocol version')) { + return; + } + // No query, headers, body, or trace arguments: any of these may contain credentials or chat. + $message = '[WEBAPI]'; + if ($request !== null) { + $message .= ' '.$this->redact($request->getMethod().' '.$request->getUri()->getPath(), 512); + } + for ($depth = 0; $error !== null && $depth < 8; $error = $error->getPrevious(), ++$depth) { + $message .= "\n".($depth === 0 ? '' : 'Caused by: ').get_class($error).': '.$this->redact($error->getMessage(), 2048); + $message .= ' ['.$this->redact($error->getFile(), 512).':'.$error->getLine().']'; + // getTraceAsString() can include function arguments depending on PHP configuration. + foreach (array_slice($error->getTrace(), 0, 20) as $index => $frame) { + $message .= "\n#".$index.' '.$this->redact((string) ($frame['file'] ?? '[internal]'), 512).':'.($frame['line'] ?? 0); + $message .= ' '.$this->redact(($frame['class'] ?? '').($frame['type'] ?? '').($frame['function'] ?? ''), 256).'()'; + } + } + try { + $this->logger->error($message); + } catch (\Throwable) { + // A broken log sink must not turn an otherwise contained request into another rejection. + } + } + + private function redact(string $value, int $limit): string + { + foreach ($this->secrets as $secret) { + if ($secret !== '') { + $value = str_replace(array_unique([$secret, rawurlencode($secret), urlencode($secret)]), '[redacted]', $value); + } + } + // Drop entire URL/request-target queries, including nested JSON and encoded query keys. + $value = preg_replace('/\?[^\s]*/', '?[redacted]', $value) ?? '[redacted]'; + $value = preg_replace('/\b(Bearer|Bot)\s+\S+/i', '$1 [redacted]', $value) ?? '[redacted]'; + $credentials = <<<'REGEX' +/\b((?:[a-z0-9_-]*[_-])?(?:key|token|password|secret)|authorization)["']?\s*[:=]\s*(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,;]+)/i +REGEX; + $value = preg_replace($credentials, '$1=[redacted]', $value) ?? '[redacted]'; + $value = preg_replace('~(https?://)[^/\s@]+@~i', '$1[redacted]@', $value) ?? '[redacted]'; + $value = preg_replace('/[\x00-\x1f\x7f]/', ' ', $value) ?? '[redacted]'; + return strlen($value) > $limit ? substr($value, 0, $limit).' [truncated]' : $value; + } +} diff --git a/src/Civ13/HttpHandler.php b/src/Civ13/HttpHandler.php index 84877793..51f6beb5 100644 --- a/src/Civ13/HttpHandler.php +++ b/src/Civ13/HttpHandler.php @@ -166,7 +166,7 @@ public function handle(ServerRequestInterface $request): HttpResponse return $this->__processCallback($array['callback'], $request, $array['endpoint']); } catch (\Throwable $e) { - $this->logger->error("HTTP Server error: An endpoint for `$path` failed with error `{$e->getMessage()}`. Stack Trace:".PHP_EOL.str_replace('#', PHP_EOL.'#', $e->getTraceAsString())); + (new HttpErrorBoundary($this->logger, [$this->key]))->report($e, $request); return new HttpResponse(HttpResponse::STATUS_INTERNAL_SERVER_ERROR); } diff --git a/tests/local/library.php b/tests/local/library.php index 63c25069..ffe0a72c 100644 --- a/tests/local/library.php +++ b/tests/local/library.php @@ -41,13 +41,18 @@ class PortableRestartProbe extends Civ13\Civ13 { public function stop(bool $closeLoop = true): void { $this->stops++; } } $portable = (new ReflectionClass(PortableRestartProbe::class))->newInstanceWithoutConstructor(); +$state = sys_get_temp_dir().'/local-restart-'.bin2hex(random_bytes(8)); +mkdir($state); +$portable->portable_state_dir = $state; $oldProfile = getenv('CIVILIZATIONBOT_PROFILE'); putenv('CIVILIZATIONBOT_PROFILE=synthetic-local-profile'); try { // restartPolicy remains deliberately uninitialized: portable must never reach it or OS spawn. $portable->restart()->then(static fn ($result) => assertLocal($result === null)); - assertLocal($portable->stops === 1); + assertLocal($portable->stops === 1 && Civ13\PortableProcess::consumeReload($state)); } finally { + if (is_file($state.'/reload.request')) { unlink($state.'/reload.request'); } + rmdir($state); $oldProfile === false ? putenv('CIVILIZATIONBOT_PROFILE') : putenv('CIVILIZATIONBOT_PROFILE='.$oldProfile); } -echo "PASS actual merged portable restart stops without legacy/policy spawn\n"; +echo "PASS actual merged portable restart signals supervisor before stopping without legacy/policy spawn\n"; diff --git a/tests/local/webapi-errors.php b/tests/local/webapi-errors.php new file mode 100644 index 00000000..0b4d3a6d --- /dev/null +++ b/tests/local/webapi-errors.php @@ -0,0 +1,154 @@ +addPsr4('Civ13\\', __DIR__.'/../../src/Civ13', true); + +use Civ13\HttpErrorBoundary; +use Evenement\EventEmitter; +use Psr\Http\Message\ServerRequestInterface; +use Psr\Log\AbstractLogger; +use React\EventLoop\StreamSelectLoop; +use React\Http\HttpServer; +use React\Http\Message\Response; +use React\Http\Message\ServerRequest; +use React\Promise\Deferred; +use React\Socket\ConnectionInterface; +use React\Socket\ServerInterface; +use React\Stream\Util; +use React\Stream\WritableStreamInterface; +use function React\Promise\reject; +use function React\Promise\resolve; + +function check(bool $ok, string $why): void { if (!$ok) { throw new RuntimeException($why); } } +final class OfflineLogger extends AbstractLogger { + public array $messages = []; + public bool $fail = false; + public function log($level, string|Stringable $message, array $context = []): void { + if ($this->fail) { throw new RuntimeException('offline sink unavailable'); } + $this->messages[] = (string) $message; + } +} +final class OfflineSocket extends EventEmitter implements ServerInterface { + public bool $closed = false; + public function getAddress() { return 'tcp://127.0.0.1:0'; } + public function pause() {} + public function resume() {} + public function close() { $this->closed = true; $this->emit('close'); } +} +final class OfflineConnection extends EventEmitter implements ConnectionInterface { + public string $output = ''; + private bool $closed = false; + public function isReadable() { return !$this->closed; } + public function isWritable() { return !$this->closed; } + public function pause() {} + public function resume() {} + public function pipe(WritableStreamInterface $dest, array $options = []) { return Util::pipe($this, $dest, $options); } + public function write($data) { $this->output .= $data; return !$this->closed; } + public function getRemoteAddress() { return 'tcp://127.0.0.1:1234'; } + public function getLocalAddress() { return 'tcp://127.0.0.1:0'; } + public function end($data = null) { if ($data !== null) { $this->write($data); } $this->close(); } + public function close() { if (!$this->closed) { $this->closed = true; $this->emit('close'); $this->removeAllListeners(); } } +} +function send(OfflineSocket $socket, string $raw): OfflineConnection { + check(!$socket->closed, 'Listener was closed by a request error'); + $connection = new OfflineConnection(); + $socket->emit('connection', [$connection]); + $connection->emit('data', [$raw]); + return $connection; +} +function settled(mixed $value): mixed { + $result = null; + $error = null; + resolve($value)->then(function ($value) use (&$result) { $result = $value; }, function ($failure) use (&$error) { $error = $failure; }); + check($error === null, 'Request escaped as a rejected promise'); + return $result; +} +$logger = new OfflineLogger(); +$secret = 'fixture-key+/'; +$boundary = new HttpErrorBoundary($logger, [$secret]); +$request = new ServerRequest('GET', 'http://bot.invalid/webhook/test1714?key='.rawurlencode($secret).'&data=private-chat', ['Authorization' => 'Bearer header-secret'], 'private-body'); +$ok = new Response(204); +check($boundary($request, fn () => $ok) === $ok, 'Synchronous response changed'); +check(settled($boundary($request, fn () => resolve($ok))) === $ok, 'Promise response changed'); +foreach ([ + fn () => throw new Exception('plain failure'), + fn () => throw new TypeError('type failure'), + fn () => reject(new Exception('rejected failure')), + fn () => null, + fn () => resolve('invalid response'), +] as $handler) { + $response = settled($boundary($request, $handler)); + check($response->getStatusCode() === 500 && (string) $response->getBody() === 'Internal Server Error', 'Failure was not contained as a generic 500'); +} +$deferred = new Deferred(); +$pending = $boundary($request, fn () => $deferred->promise()); +$deferred->reject(new Exception('late failure')); +check(settled($pending)->getStatusCode() === 500, 'Delayed rejection escaped'); +check(str_contains(implode("\n", $logger->messages), 'GET /webhook/test1714'), 'Request context missing'); + +// Trace arguments may include secrets even when zend.exception_ignore_args is disabled. +ini_set('zend.exception_ignore_args', '0'); +function privateArgument(string $argument): Throwable { return new Exception('original failure'); } +$cause = privateArgument('trace-secret'); +$outer = new RuntimeException('wrapper /webhook/test1714?key=unknown-query-secret&data=private-chat token=plain-token '.$secret.' '.rawurlencode($secret), 0, $cause); +$boundary->report($outer, $request); +$last = end($logger->messages); +check(str_contains($last, 'RuntimeException: wrapper') && str_contains($last, 'Caused by: Exception: original failure') && str_contains($last, 'privateArgument()'), 'Exception chain or source frames missing'); +foreach (['trace-secret', 'unknown-query-secret', 'plain-token', $secret, rawurlencode($secret), 'private-chat', 'private-body', 'header-secret'] as $private) { + check(!str_contains(implode("\n", $logger->messages), $private), 'Private data entered diagnostic: '.$private); +} +$boundary->report(new Exception('payload {"token":"json-token", "password":"password with spaces", "client_secret":"json-client"} API_KEY=\'single quoted secret\' https://username:credential@service.invalid/path')); +foreach (['json-token', 'password with spaces', 'json-client', 'single quoted secret', 'username:credential'] as $private) { + check(!str_contains(end($logger->messages), $private), 'Quoted/URL credential entered diagnostic'); +} +$before = count($logger->messages); +$boundary->report(new RuntimeException('Received request with invalid protocol version')); +check(count($logger->messages) === $before, 'Ignored protocol error became noisy'); +$logger->fail = true; +check(settled($boundary($request, fn () => throw new Exception('sink failure')))->getStatusCode() === 500, 'Logging failure escaped containment'); +$logger->fail = false; + +// The router's own catch must use the same safe chain logging instead of dumping trace arguments. +$records = new Monolog\Handler\TestHandler(); +$router = (new ReflectionClass(Civ13\HttpHandler::class))->newInstanceWithoutConstructor(); +$router->logger = new Monolog\Logger('offline-router', [$records]); +(new ReflectionProperty(Civ13\HttpHandler::class, 'key'))->setValue($router, $secret); +(new ReflectionProperty(Civ13\HttpHandler::class, 'attributes'))->setValue($router, ['handlers' => [], 'whitelisted' => [], 'match_methods' => [], 'descriptions' => [], 'whitelist' => ['127.0.0.1'], 'ratelimits' => []]); +$router->offsetSet('/router-fail', static function (ServerRequestInterface $request, string $endpoint, bool $whitelisted) use ($secret): Response { + throw new RuntimeException('endpoint '.$secret, 0, new Exception('original endpoint cause')); +}); +$routerRequest = new ServerRequest('GET', 'http://offline.invalid/router-fail?key='.rawurlencode($secret), [], '', '1.1', ['REMOTE_ADDR' => '127.0.0.1']); +check($router->handle($routerRequest)->getStatusCode() === 500, 'Router exception escaped'); +$routerLog = implode("\n", array_map(static fn ($record) => $record['message'], $records->getRecords())); +check(str_contains($routerLog, 'GET /router-fail') && str_contains($routerLog, 'Caused by: Exception: original endpoint cause') && !str_contains($routerLog, $secret), 'Router lost safe context or original exception'); + +// Exercise real server integration with no network sockets. The same listener must serve the next request. +$loop = new StreamSelectLoop(); +$socket = new OfflineSocket(); +$server = new HttpServer($loop, $boundary, React\Async\async(static function (ServerRequestInterface $request): Response { + if ($request->getUri()->getPath() === '/fail') { throw new Exception('application failure'); } + return new Response(200, [], 'still alive'); +})); +$server->on('error', $boundary->report(...)); +$server->listen($socket); +$connection = send($socket, "GET /fail?key=fixture HTTP/1.1\r\nHost: offline.invalid\r\n\r\n"); +check(str_starts_with($connection->output, 'HTTP/1.1 500'), 'Real async request did not get 500'); +$connection = send($socket, "GET /ok HTTP/1.1\r\nHost: offline.invalid\r\n\r\n"); +check(str_starts_with($connection->output, 'HTTP/1.1 200') && str_contains($connection->output, 'still alive'), 'Next request failed'); + +// React's implicit body-buffer middleware precedes ours. Its failure reaches only the one-argument error event. +$before = count($logger->messages); +$connection = send($socket, "POST /bad-body HTTP/1.1\r\nHost: offline.invalid\r\nTransfer-Encoding: chunked\r\n\r\n1\r\naXX"); +check(str_starts_with($connection->output, 'HTTP/1.1 500'), 'Body-framing failure did not get an error response'); +check(count($logger->messages) === $before + 1 && str_contains(end($logger->messages), 'Caused by:'), 'React wrapper lost its underlying error'); +$connection = send($socket, "GET /ok HTTP/1.1\r\nHost: offline.invalid\r\n\r\n"); +check(str_starts_with($connection->output, 'HTTP/1.1 200') && !$socket->closed, 'Middleware rejection stopped listener'); +$socket->close(); + +// Static bootstrap assertion: never execute the credential-loading production entrypoint in tests. +$bootstrap = file_get_contents(__DIR__.'/../../bot.php'); +check(str_contains($bootstrap, 'new HttpServer(Loop::get(), $httpErrors,'), 'Bootstrap omitted the request boundary'); +check(str_contains($bootstrap, '$webapi->on(\'error\', $httpErrors->report(...));') && !str_contains($bootstrap, '[WEBAPI] ERROR - RESTART'), 'Bootstrap retained the crash-on-request-error listener'); +echo "PASS WebAPI errors: sync/async/delayed/invalid responses, cause chain, redaction, broken logger, actual React parser and next-request survival\n"; diff --git a/tests/windows/portable-restart.php b/tests/windows/portable-restart.php new file mode 100644 index 00000000..4a8ebd17 --- /dev/null +++ b/tests/windows/portable-restart.php @@ -0,0 +1,94 @@ +addPsr4('Civ13\\', __DIR__.'/../../src/Civ13/', true); +use Civ13\Civ13; +use Civ13\PortableProcess; +use React\Promise\PromiseInterface; +function checkRestart(bool $ok, string $message): void { + if (!$ok) { throw new RuntimeException($message); } +} +function settledRestart(PromiseInterface $promise, bool $reject = false): void { + $settled = false; + $promise->then( + static function ($value) use (&$settled, $reject): void { $settled = !$reject && $value === null; }, + static function (Throwable $error) use (&$settled, $reject): void { $settled = $reject && $error instanceof RuntimeException; } + ); + checkRestart($settled, 'Unexpected restart promise result'); +} +class OfflinePortableRestart extends Civ13 { + public int $stops = 0; + public bool $failStop = false; + public function stop(bool $closeLoop = true): void { + checkRestart(is_file($this->portable_state_dir.'/reload.request'), 'Shutdown happened before reload intent'); + if ($this->failStop) { throw new RuntimeException('Injected shutdown failure'); } + $this->stops++; + } + public function __destruct() {} +} +function restartProbe(string $state): OfflinePortableRestart { + // Policy and process launcher deliberately uninitialized: any legacy dispatch fails. + $bot = (new ReflectionClass(OfflinePortableRestart::class))->newInstanceWithoutConstructor(); + $bot->portable_state_dir = $state; + return $bot; +} +$dir = sys_get_temp_dir().'/portable-restart-'.bin2hex(random_bytes(8)); +mkdir($dir); +$oldProfile = getenv('CIVILIZATIONBOT_PROFILE'); +putenv('CIVILIZATIONBOT_PROFILE=offline-portable-restart'); +try { + $bot = restartProbe($dir); + settledRestart($bot->restart()); + settledRestart($bot->restart()); + checkRestart($bot->stops === 1, 'Duplicate restart stopped twice'); + checkRestart(PortableProcess::consumeReload($dir) && !PortableProcess::consumeReload($dir), 'Supervisor intent was not one-use'); + settledRestart($bot->restart()); + checkRestart($bot->stops === 1 && !is_file($dir.'/reload.request'), 'Duplicate restart recreated consumed intent'); + try { $bot->restart('arbitrary.php'); throw new LogicException('Portable entry override accepted'); } + catch (InvalidArgumentException) {} + + // A prior reloadconfig request and restart share one marker. + PortableProcess::requestReload($dir); + $existing = restartProbe($dir); + settledRestart($existing->restart()); + checkRestart($existing->stops === 1 && PortableProcess::consumeReload($dir), 'Existing intent was not reusable'); + + PortableProcess::requestStop($dir); + $stopping = restartProbe($dir); + settledRestart($stopping->restart()); + checkRestart($stopping->stops === 0 && !is_file($dir.'/reload.request') && is_file($dir.'/stop.request'), 'Pending stop lost precedence'); + // Simulate the supervisor decision for a stop arriving after restart intent. + PortableProcess::requestReload($dir); + settledRestart($stopping->restart()); + $reload = PortableProcess::consumeReload($dir) && !is_file($dir.'/stop.request'); + checkRestart(!$reload && $stopping->stops === 0, 'Stop plus reload caused relaunch'); + unlink($dir.'/stop.request'); + + foreach (['', 'relative-state', $dir.'/missing'] as $state) { + $invalid = restartProbe($state); + settledRestart($invalid->restart(), true); + checkRestart($invalid->stops === 0, 'Invalid state stopped the bot'); + } + // Deterministic Windows/POSIX write failure without changing system permissions. + mkdir($dir.'/reload.request'); + $failed = restartProbe($dir); + settledRestart($failed->restart(), true); + checkRestart($failed->stops === 0, 'Marker write failure stopped the bot'); + rmdir($dir.'/reload.request'); + settledRestart($failed->restart()); + checkRestart($failed->stops === 1 && PortableProcess::consumeReload($dir), 'Marker failure prevented retry'); + + $retry = restartProbe($dir); + $retry->failStop = true; + try { $retry->restart(); throw new LogicException('Shutdown failure swallowed'); } + catch (RuntimeException $error) { checkRestart($error->getMessage() === 'Injected shutdown failure', 'Unexpected shutdown error'); } + $retry->failStop = false; + settledRestart($retry->restart()); + checkRestart($retry->stops === 1 && PortableProcess::consumeReload($dir), 'Shutdown failure prevented retry'); + echo "PASS portable restart: intent before shutdown, one-use supervisor marker, duplicate suppression, stop precedence, no entry override/spawn, state failure and retry\n"; +} finally { + $oldProfile === false ? putenv('CIVILIZATIONBOT_PROFILE') : putenv('CIVILIZATIONBOT_PROFILE='.$oldProfile); + foreach (glob($dir.'/*') as $path) { is_dir($path) ? rmdir($path) : unlink($path); } + rmdir($dir); +}