From 9bf1576b9b37d55c196ae6b2bb8a16f77ac5cba4 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Wed, 11 Nov 2026 02:35:23 +0300 Subject: [PATCH 01/11] Report terminal program status (OSC 7501) for queue:consume --- docs/guide/en/console-commands.md | 14 + src/Cli/TerminalStatusReporter.php | 257 +++++++++++ src/Command/ConsumeCommand.php | 71 +++- tests/Unit/Cli/TerminalStatusReporterTest.php | 401 ++++++++++++++++++ .../Unit/Command/ConsumeCommandStatusTest.php | 315 ++++++++++++++ 5 files changed, 1057 insertions(+), 1 deletion(-) create mode 100644 src/Cli/TerminalStatusReporter.php create mode 100644 tests/Unit/Cli/TerminalStatusReporterTest.php create mode 100644 tests/Unit/Command/ConsumeCommandStatusTest.php diff --git a/docs/guide/en/console-commands.md b/docs/guide/en/console-commands.md index a8383f5a..059c193e 100644 --- a/docs/guide/en/console-commands.md +++ b/docs/guide/en/console-commands.md @@ -57,3 +57,17 @@ yii queue:consume --all [queueName1 [queueName2 [...]]] --pause=1 --limit=0 For long-running processes, graceful shutdown is controlled by `LoopInterface`. When `ext-pcntl` is available, the default `SignalLoop` handles signals such as `SIGTERM`/`SIGINT`. + +## Terminal program status (OSC 7501) + +When run in an interactive terminal, `queue:consume` reports what it is doing — processing or waiting on messages — +and how it finished, using the [Program Status Protocol (OSC 7501)](https://www.superlogical.com/rex/docs/build/program-status), +so the terminal itself can show the status in its UI. + +The reports are written directly to the output stream. They require no extra dependencies and appear only when the +stream is an interactive TTY and the output is decorated and not quiet; redirected output, log files, cron runs and +quiet invocations are unaffected. Set the environment variable `YII_QUEUE_STATUS` to `off` to disable the reports +explicitly. + +Only the command itself reports status; adapters such as `yiisoft/queue-db`, `yiisoft/queue-redis` or +`yiisoft/queue-amqp` do not emit their own terminal status. diff --git a/src/Cli/TerminalStatusReporter.php b/src/Cli/TerminalStatusReporter.php new file mode 100644 index 00000000..69993b1e --- /dev/null +++ b/src/Cli/TerminalStatusReporter.php @@ -0,0 +1,257 @@ +enabled = $enabled; + $this->app = $app; + $this->stream = $enabled && is_resource($stream) ? $stream : null; + } + + public static function forOutput(OutputInterface $output, ?string $app = null, ?bool $enabled = null): self + { + $stream = $output instanceof StreamOutput ? $output->getStream() : null; + + if ($enabled === null) { + $enabled = !self::isOptedOut() + && $output->isDecorated() + && !$output->isQuiet() + && $stream !== null + && stream_isatty($stream); + } + + return new self($enabled, $app, $stream); + } + + /** + * Reports a program status update. + * + * @param string $state One of `idle`, `working`, `done`, `error`, `blocked`. + * @param string|null $message A single human-readable line; control characters are replaced by spaces and long + * text is cut. + * @param string|null $id The task the report is about; `null` reports the program itself. A "/" in an id makes + * the report a child of the parent task. + * @param int|null $progress A percentage for a `working` or `blocked` report; `null` when indeterminate. + * @param string|null $kind What a `blocked` report waits for: `permission`, `question` or `auth`. + * + * @throws InvalidArgumentException If the state, id, kind or progress is invalid. + */ + public function emit(string $state, ?string $message = null, ?string $id = null, ?int $progress = null, ?string $kind = null): void + { + if (!$this->enabled) { + return; + } + + if (!in_array($state, self::STATES, true)) { + throw new InvalidArgumentException( + sprintf( + 'The terminal status state "%s" must be one of: %s.', + $state, + implode(', ', self::STATES), + ), + ); + } + + if ($kind !== null) { + if ($state !== 'blocked') { + throw new InvalidArgumentException( + sprintf( + 'A terminal status kind is only supported for the "blocked" state, "%s" given.', + $state, + ), + ); + } + + if (!in_array($kind, self::KINDS, true)) { + throw new InvalidArgumentException( + sprintf( + 'The terminal status kind "%s" must be one of: %s.', + $kind, + implode(', ', self::KINDS), + ), + ); + } + } + + if ($progress !== null) { + if ($state !== 'working' && $state !== 'blocked') { + throw new InvalidArgumentException( + sprintf( + 'A terminal status progress is only supported for the "working" and "blocked" states, "%s" given.', + $state, + ), + ); + } + + if ($progress < 0 || $progress > 100) { + throw new InvalidArgumentException( + sprintf('The terminal status progress must be between 0 and 100, %d given.', $progress), + ); + } + } + + if ($id !== null) { + self::validateId($id); + } + + $pairs = ['state=' . $state]; + if ($id !== null) { + $pairs[] = 'id=' . $id; + } + if ($kind !== null) { + $pairs[] = 'kind=' . $kind; + } + if ($progress !== null) { + $pairs[] = 'progress=' . (string) $progress; + } + $pairs[] = 'app=' . $this->app; + + $message = self::normalizeText($message); + if ($message !== null) { + $pairs[] = 'msg=' . base64_encode($message); + } + + $this->write("\x1b]7501;" . implode(':', $pairs) . "\x1b\\"); + } + + /** + * Removes the record of a task and of the records beneath it, or all records when no id is given. + * + * @param string|null $id The task record to remove. + * + * @throws InvalidArgumentException If the id is invalid. + */ + public function clear(?string $id = null): void + { + if (!$this->enabled) { + return; + } + + if ($id !== null) { + self::validateId($id); + } + + $this->write($id === null ? "\x1b]7501;state=clear\x1b\\" : "\x1b]7501;state=clear:id={$id}\x1b\\"); + } + + public function isEnabled(): bool + { + return $this->enabled; + } + + private static function isOptedOut(): bool + { + $value = getenv(self::ENV_VAR); + + return is_string($value) && in_array(strtolower(trim($value)), ['off', '0', 'no', 'false'], true); + } + + private static function validateId(string $id): void + { + if (strlen($id) > self::MAX_ID_BYTES || !preg_match(self::ID_PATTERN, $id)) { + throw new InvalidArgumentException( + sprintf( + 'The terminal status id "%s" must be up to 8 "/"-separated segments of 1 to 32 characters ' + . 'among letters, digits, "_", ".", "+" and "-", and at most %d bytes.', + $id, + self::MAX_ID_BYTES, + ), + ); + } + } + + /** + * Terminals discard a whole report whose text holds a control character or exceeds the size limit, so the + * text is made safe instead. + */ + private static function normalizeText(?string $text): ?string + { + if ($text === null) { + return null; + } + + $text = trim((string) preg_replace('/[\x00-\x1F\x7F]|\xC2[\x80-\x9F]/', ' ', $text)); + + if (strlen($text) > self::MAX_MESSAGE_BYTES) { + $text = substr($text, 0, self::MAX_MESSAGE_BYTES); + while (strlen($text) > 0 && !preg_match('//u', $text)) { + $text = substr($text, 0, -1); + } + $text = rtrim($text); + } + + return $text !== '' ? $text : null; + } + + private function write(string $sequence): void + { + if ($this->stream === null) { + return; + } + + fwrite($this->stream, $sequence); + fflush($this->stream); + } +} diff --git a/src/Command/ConsumeCommand.php b/src/Command/ConsumeCommand.php index 70e09913..502759c9 100644 --- a/src/Command/ConsumeCommand.php +++ b/src/Command/ConsumeCommand.php @@ -4,6 +4,7 @@ namespace Yiisoft\Queue\Command; +use Throwable; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; @@ -12,10 +13,15 @@ use Symfony\Component\Console\Output\OutputInterface; use Yiisoft\Queue\Cli\LoopInterface; use Yiisoft\Queue\Cli\ScopedLoopInterface; +use Yiisoft\Queue\Cli\TerminalStatusReporter; use Yiisoft\Queue\DefaultQueue; use Yiisoft\Queue\Provider\QueueConsumerProviderInterface; use function count; +use function preg_replace; +use function sprintf; +use function substr; +use function trim; #[AsCommand('queue:consume', 'Consumes queued messages. Listens continuously unless --once is passed.')] final class ConsumeCommand extends Command @@ -23,6 +29,7 @@ final class ConsumeCommand extends Command public function __construct( private readonly QueueConsumerProviderInterface $queueProvider, private readonly LoopInterface $loop, + private readonly ?TerminalStatusReporter $statusReporter = null, ) { parent::__construct(); } @@ -87,6 +94,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int return Command::INVALID; } + $statusReporter = $this->statusReporter ?? TerminalStatusReporter::forOutput($output); + if (!$once && !$all) { if (count($queueNames) > 1) { $output->writeln('Use --all or --once to consume multiple queues.'); @@ -94,7 +103,18 @@ protected function execute(InputInterface $input, OutputInterface $output): int return Command::INVALID; } - $this->queueProvider->getConsumer($queueNames[0] ?? DefaultQueue::NAME)->listen(); + $queueName = $queueNames[0] ?? DefaultQueue::NAME; + $statusReporter->emit('working', sprintf('Listening on queue "%s"', $queueName)); + + try { + $this->queueProvider->getConsumer($queueName)->listen(); + } catch (Throwable $exception) { + $statusReporter->emit('error', sprintf('Consume on queue "%s" failed', $queueName)); + + throw $exception; + } + + $statusReporter->emit('done', sprintf('Stopped listening on queue "%s"', $queueName)); return Command::SUCCESS; } @@ -120,6 +140,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int $pauseSeconds = 1; } + $statusReporter->emit('working', self::rootMessage($queueNames, $once)); + + $processed = 0; if ($this->loop instanceof ScopedLoopInterface) { $this->loop->start(); } @@ -132,8 +155,14 @@ protected function execute(InputInterface $input, OutputInterface $output): int $output->write("Processing queue $queueName... "); } + $statusId = self::statusId($queueName); + $statusReporter->emit('working', sprintf('Processing queue "%s"', $queueName), $statusId); + $count = $consumer->run($limit); $hasMessages = $count > 0 || $hasMessages; + $processed += $count; + + $statusReporter->emit('done', sprintf('Queue "%s": %d messages processed', $queueName, $count), $statusId); if ($once) { $output->writeln("Messages processed: $count."); @@ -149,12 +178,52 @@ protected function execute(InputInterface $input, OutputInterface $output): int sleep($pauseSeconds); } } + } catch (Throwable $exception) { + $statusReporter->emit('error', 'Consume failed'); + + throw $exception; } finally { if ($this->loop instanceof ScopedLoopInterface) { $this->loop->finish(); } } + $statusReporter->emit('done', $once + ? sprintf('%d messages processed', $processed) + : 'Stopped listening'); + return Command::SUCCESS; } + + /** + * @param list $queueNames + */ + private static function rootMessage(array $queueNames, bool $once): string + { + $count = count($queueNames); + $description = $count === 1 + ? sprintf('queue "%s"', $queueNames[0]) + : sprintf('%d queues', $count); + + return $once + ? sprintf('Consuming %s in one pass', $description) + : sprintf('Listening on %s', $description); + } + + /** + * A task id for the queue in terminal status reports. + * + * Returns `null` when the queue name cannot be represented as a valid protocol id segment, in which case the + * report falls back to the program-level record. + */ + private static function statusId(string $queueName): ?string + { + $segment = trim((string) preg_replace('/[^A-Za-z0-9_.+-]+/', '-', $queueName), '-'); + + if ($segment === '') { + return null; + } + + return 'queue/' . substr($segment, 0, 32); + } } diff --git a/tests/Unit/Cli/TerminalStatusReporterTest.php b/tests/Unit/Cli/TerminalStatusReporterTest.php new file mode 100644 index 00000000..adc95e30 --- /dev/null +++ b/tests/Unit/Cli/TerminalStatusReporterTest.php @@ -0,0 +1,401 @@ +hadEnv = getenv('YII_QUEUE_STATUS') !== false; + $this->savedEnvValue = (string) getenv('YII_QUEUE_STATUS'); + putenv('YII_QUEUE_STATUS'); + } + + protected function tearDown(): void + { + if ($this->hadEnv) { + putenv('YII_QUEUE_STATUS=' . $this->savedEnvValue); + } else { + putenv('YII_QUEUE_STATUS'); + } + + parent::tearDown(); + } + + public function testWorkingReport(): void + { + [, $reporter, $read] = $this->enabledOutput(); + + $reporter->emit('working', 'Processing'); + + self::assertSame( + "\x1b]7501;state=working:app=queue:msg=" . base64_encode('Processing') . "\x1b\\", + $read(), + ); + } + + public function testOtherStates(): void + { + [, $reporter, $read] = $this->enabledOutput(); + + $reporter->emit('idle', 'Waiting'); + $reporter->emit('done', 'Finished'); + $reporter->emit('error', 'Failed'); + + self::assertSame( + "\x1b]7501;state=idle:app=queue:msg=" . base64_encode('Waiting') . "\x1b\\" + . "\x1b]7501;state=done:app=queue:msg=" . base64_encode('Finished') . "\x1b\\" + . "\x1b]7501;state=error:app=queue:msg=" . base64_encode('Failed') . "\x1b\\", + $read(), + ); + } + + public function testReportWithIdAndProgress(): void + { + [, $reporter, $read] = $this->enabledOutput(); + + $reporter->emit('working', 'Processing queue a', 'queue/a', 50); + + self::assertSame( + "\x1b]7501;state=working:id=queue/a:progress=50:app=queue:msg=" . base64_encode('Processing queue a') . "\x1b\\", + $read(), + ); + } + + public function testBlockedReportWithKind(): void + { + [, $reporter, $read] = $this->enabledOutput(); + + $reporter->emit('blocked', 'Awaiting input', null, null, 'permission'); + + self::assertSame( + "\x1b]7501;state=blocked:kind=permission:app=queue:msg=" . base64_encode('Awaiting input') . "\x1b\\", + $read(), + ); + } + + public function testControlCharactersAreReplacedBySpaces(): void + { + [, $reporter, $read] = $this->enabledOutput(); + + $reporter->emit('working', "a\x01b\x1fc"); + + self::assertSame( + "\x1b]7501;state=working:app=queue:msg=" . base64_encode('a b c') . "\x1b\\", + $read(), + ); + } + + public function testC1ControlCharactersAreReplacedBySpaces(): void + { + [, $reporter, $read] = $this->enabledOutput(); + + $reporter->emit('working', "\xC2\x80x\xC2\x9F"); + + self::assertSame( + "\x1b]7501;state=working:app=queue:msg=" . base64_encode('x') . "\x1b\\", + $read(), + ); + } + + public function testEmptyMessageIsOmitted(): void + { + [, $reporter, $read] = $this->enabledOutput(); + + $reporter->emit('working', "\x00\x01"); + + self::assertSame("\x1b]7501;state=working:app=queue\x1b\\", $read()); + } + + public function testLongMessageIsCut(): void + { + [, $reporter, $read] = $this->enabledOutput(); + + $message = str_repeat('a', 2100); + $reporter->emit('working', $message); + + self::assertSame( + "\x1b]7501;state=working:app=queue:msg=" . base64_encode(substr($message, 0, 2048)) . "\x1b\\", + $read(), + ); + } + + public function testLongMessageIsCutOnACharacterBoundary(): void + { + [, $reporter, $read] = $this->enabledOutput(); + + $message = str_repeat('a', 2047) . '€'; + $reporter->emit('working', $message); + + self::assertSame( + "\x1b]7501;state=working:app=queue:msg=" . base64_encode(str_repeat('a', 2047)) . "\x1b\\", + $read(), + ); + } + + public function testCustomApp(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, 'custom-app', true); + + $reporter->emit('working', 'Working'); + + self::assertSame( + "\x1b]7501;state=working:app=custom-app:msg=" . base64_encode('Working') . "\x1b\\", + $this->read($stream), + ); + } + + public function testInvalidState(): void + { + [, $reporter] = $this->enabledOutput(); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('must be one of: idle, working, done, error, blocked'); + + $reporter->emit('spinning'); + } + + public function testProgressIsOnlyForWorkingAndBlocked(): void + { + [, $reporter] = $this->enabledOutput(); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('only supported for the "working" and "blocked" states, "done" given'); + + $reporter->emit('done', 'Finished', null, 50); + } + + public function testProgressIsBounded(): void + { + [, $reporter] = $this->enabledOutput(); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('must be between 0 and 100, 101 given'); + + $reporter->emit('working', 'Working', null, 101); + } + + public function testKindIsOnlyForBlocked(): void + { + [, $reporter] = $this->enabledOutput(); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('only supported for the "blocked" state, "working" given'); + + $reporter->emit('working', 'Working', null, null, 'permission'); + } + + public function testInvalidKind(): void + { + [, $reporter] = $this->enabledOutput(); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('must be one of: permission, question, auth'); + + $reporter->emit('blocked', 'Waiting', null, null, 'wait'); + } + + public function testInvalidId(): void + { + [, $reporter] = $this->enabledOutput(); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The terminal status id "bad id" must be up to 8'); + + $reporter->emit('working', 'Working', 'bad id'); + } + + public function testLongIdIsRejected(): void + { + [, $reporter] = $this->enabledOutput(); + + $this->expectException(InvalidArgumentException::class); + + $reporter->emit('working', 'Working', str_repeat('a', 45) . '/' . str_repeat('b', 45)); + } + + public function testManyIdSegmentsAreRejected(): void + { + [, $reporter] = $this->enabledOutput(); + + $this->expectException(InvalidArgumentException::class); + + $reporter->emit( + 'working', + 'Working', + implode('/', array_fill(0, 9, str_repeat('a', 14))), + ); + } + + public function testInvalidApp(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('must be 1 to 32 characters'); + + TerminalStatusReporter::forOutput($output, 'bad app', true); + } + + public function testClearWithoutId(): void + { + [, $reporter, $read] = $this->enabledOutput(); + + $reporter->clear(); + + self::assertSame("\x1b]7501;state=clear\x1b\\", $read()); + } + + public function testClearWithId(): void + { + [, $reporter, $read] = $this->enabledOutput(); + + $reporter->clear('queue/a'); + + self::assertSame("\x1b]7501;state=clear:id=queue/a\x1b\\", $read()); + } + + public function testClearWithInvalidId(): void + { + [, $reporter] = $this->enabledOutput(); + + $this->expectException(InvalidArgumentException::class); + + $reporter->clear('bad id'); + } + + public function testNotEnabledForPlainOutput(): void + { + $reporter = TerminalStatusReporter::forOutput($this->createMock(OutputInterface::class)); + + self::assertFalse($reporter->isEnabled()); + + $reporter->emit('working', 'Working'); + $reporter->clear(); + } + + public function testNotEnabledForRedirectedStream(): void + { + $stream = fopen('php://memory', 'w+'); + $reporter = TerminalStatusReporter::forOutput(new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true)); + + self::assertFalse($reporter->isEnabled()); + + $reporter->emit('working', 'Working'); + self::assertSame('', $this->read($stream)); + } + + public function testNotEnabledForUndecoratedOutput(): void + { + $stream = fopen('php://memory', 'w+'); + $reporter = TerminalStatusReporter::forOutput(new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, false)); + + self::assertFalse($reporter->isEnabled()); + + $reporter->emit('working', 'Working'); + self::assertSame('', $this->read($stream)); + } + + public function testNotEnabledForQuietOutput(): void + { + $stream = fopen('php://memory', 'w+'); + $reporter = TerminalStatusReporter::forOutput(new StreamOutput($stream, OutputInterface::VERBOSITY_QUIET, true)); + + self::assertFalse($reporter->isEnabled()); + + $reporter->emit('working', 'Working'); + self::assertSame('', $this->read($stream)); + } + + public function testNotEnabledForBufferedOutput(): void + { + $reporter = TerminalStatusReporter::forOutput(new BufferedOutput()); + + self::assertFalse($reporter->isEnabled()); + + $reporter->emit('working', 'Working'); + } + + /** + * @dataProvider provideOptOutValues + */ + public function testOptOutViaEnvironment(string $value): void + { + putenv('YII_QUEUE_STATUS=' . $value); + + $stream = fopen('php://memory', 'w+'); + $reporter = TerminalStatusReporter::forOutput(new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true)); + + self::assertFalse($reporter->isEnabled()); + + $reporter->emit('working', 'Working'); + self::assertSame('', $this->read($stream)); + } + + public static function provideOptOutValues(): array + { + return [ + ['off'], + ['OFF'], + [' 0'], + [' no '], + ['false'], + ]; + } + + public function testEnabledOverride(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + + self::assertTrue($reporter->isEnabled()); + + $reporter->emit('working', 'Working'); + self::assertNotSame('', $this->read($stream)); + } + + /** + * @return array{0: StreamOutput, 1: TerminalStatusReporter, 2: callable(): string} + */ + private function enabledOutput(): array + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + + return [$output, $reporter, fn(): string => $this->read($stream)]; + } + + /** @param resource $stream */ + private function read($stream): string + { + rewind($stream); + + return (string) stream_get_contents($stream); + } +} diff --git a/tests/Unit/Command/ConsumeCommandStatusTest.php b/tests/Unit/Command/ConsumeCommandStatusTest.php new file mode 100644 index 00000000..fbf2cfb1 --- /dev/null +++ b/tests/Unit/Command/ConsumeCommandStatusTest.php @@ -0,0 +1,315 @@ + ['consumer' => $this->consumer(3)]]), + new StubLoop(), + $reporter, + ); + + $command->run(new StringInput('--once queuea'), $output); + + $bytes = $this->read($stream); + self::assertSame( + [ + $this->sequence('working', 'Consuming queue "queuea" in one pass'), + $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), + $this->sequence('done', 'Queue "queuea": 3 messages processed', 'queue/queuea'), + $this->sequence('done', '3 messages processed'), + ], + $this->statusSequences($bytes), + ); + self::assertStringContainsString('Processing queue queuea... ', $bytes); + self::assertStringContainsString('Messages processed: 3.', $bytes); + } + + public function testOnceMultipleQueues(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider([ + 'mail' => ['consumer' => $this->consumer(2)], + 'news' => ['consumer' => $this->consumer(1)], + ]), + new StubLoop(), + $reporter, + ); + + $command->run(new StringInput('--once mail news'), $output); + + $bytes = (string) $this->read($stream); + self::assertStringContainsString($this->sequence('working', 'Consuming 2 queues in one pass'), $bytes); + self::assertStringContainsString($this->sequence('done', 'Queue "mail": 2 messages processed', 'queue/mail'), $bytes); + self::assertStringContainsString($this->sequence('done', 'Queue "news": 1 messages processed', 'queue/news'), $bytes); + self::assertStringContainsString($this->sequence('done', '3 messages processed'), $bytes); + } + + public function testAllModePasses(): void + { + $loop = new class implements LoopInterface { + private int $checks = 0; + + public function canContinue(): bool + { + return $this->checks++ < 3; + } + }; + + $consumer = $this->createMock(QueueConsumerInterface::class); + $consumer->expects($this->exactly(2))->method('run')->willReturnOnConsecutiveCalls(0, 1); + + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider(['queuea' => ['consumer' => $consumer]]), + $loop, + $reporter, + ); + + $command->run(new StringInput('--all --pause=0 queuea'), $output); + + self::assertSame( + [ + $this->sequence('working', 'Listening on queue "queuea"'), + $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), + $this->sequence('done', 'Queue "queuea": 0 messages processed', 'queue/queuea'), + $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), + $this->sequence('done', 'Queue "queuea": 1 messages processed', 'queue/queuea'), + $this->sequence('done', 'Stopped listening'), + ], + $this->statusSequences($this->read($stream)), + ); + } + + public function testListenMode(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider(['queuea' => ['consumer' => $this->consumer(-1)]]), + new StubLoop(), + $reporter, + ); + + $command->run(new StringInput('queuea'), $output); + + self::assertSame( + [ + $this->sequence('working', 'Listening on queue "queuea"'), + $this->sequence('done', 'Stopped listening on queue "queuea"'), + ], + $this->statusSequences($this->read($stream)), + ); + } + + public function testRunExceptionReportsErrorStatus(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider(['queuea' => ['consumer' => $this->consumer(false)]]), + new StubLoop(), + $reporter, + ); + + try { + $command->run(new StringInput('--once queuea'), $output); + self::fail('The command should rethrow the handler exception.'); + } catch (RuntimeException $exception) { + self::assertSame('boom', $exception->getMessage()); + } + + self::assertSame( + [ + $this->sequence('working', 'Consuming queue "queuea" in one pass'), + $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), + $this->sequence('error', 'Consume failed'), + ], + $this->statusSequences($this->read($stream)), + ); + } + + public function testListenExceptionReportsErrorStatus(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $consumer = $this->createMock(QueueConsumerInterface::class); + $consumer->method('listen')->willReturnCallback(static fn(): never => throw new RuntimeException('boom')); + $command = new ConsumeCommand( + new PredefinedQueueProvider(['queuea' => ['consumer' => $consumer]]), + new StubLoop(), + $reporter, + ); + + try { + $command->run(new StringInput('queuea'), $output); + self::fail('The command should rethrow the handler exception.'); + } catch (RuntimeException $exception) { + self::assertSame('boom', $exception->getMessage()); + } + + self::assertSame( + [ + $this->sequence('working', 'Listening on queue "queuea"'), + $this->sequence('error', 'Consume on queue "queuea" failed'), + ], + $this->statusSequences($this->read($stream)), + ); + } + + public function testStatusIsSuppressedWithoutAInteractiveStream(): void + { + [$command, $output, $stream] = $this->build(['queuea' => ['consumer' => $this->consumer(3)]]); + + $command->run(new StringInput('--once queuea'), $output); + + $bytes = (string) $this->read($stream); + self::assertFalse(str_contains($bytes, "\x1b]7501")); + self::assertStringContainsString('Processing queue queuea... Messages processed: 3.', $bytes); + } + + public function testQueueNameWithoutValidIdCharsFallsBackToRootRecord(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider(["!!" => ['consumer' => $this->consumer(1)]]), + new StubLoop(), + $reporter, + ); + + $command->run(new StringInput('--once "!!"'), $output); + + $bytes = (string) $this->read($stream); + self::assertStringContainsString($this->sequence('working', 'Processing queue "!!"'), $bytes); + self::assertStringNotContainsString('id=', $bytes); + } + + public function testQueueNameWithInvalidCharsIsSanitizedInId(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider(['weird: name' => ['consumer' => $this->consumer(1)]]), + new StubLoop(), + $reporter, + ); + + $command->run(new StringInput('--once "weird: name"'), $output); + + self::assertStringContainsString( + $this->sequence('done', 'Queue "weird: name": 1 messages processed', 'queue/weird-name'), + (string) $this->read($stream), + ); + } + + private function consumer(int|false $count): QueueConsumerInterface + { + $consumer = $this->createMock(QueueConsumerInterface::class); + if ($count === false) { + $consumer->method('run')->willReturnCallback(static fn(): never => throw new RuntimeException('boom')); + } else { + $consumer->method('run')->willReturn($count); + } + + return $consumer; + } + + /** + * @param array> $definitions + * + * @return array{0: ConsumeCommand, 1: StreamOutput, 2: resource} + */ + private function build( + array $definitions, + ?TerminalStatusReporter $reporter = null, + ?LoopInterface $loop = null, + ): array { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider($definitions), + $loop ?? new StubLoop(), + $reporter, + ); + + return [$command, $output, $stream]; + } + + /** @param resource $stream */ + private function read($stream): string + { + rewind($stream); + + return (string) stream_get_contents($stream); + } + + private function sequence(string $state, string $message, ?string $id = null): string + { + $pairs = ['state=' . $state]; + if ($id !== null) { + $pairs[] = 'id=' . $id; + } + + return "\x1b]7501;" . implode(':', array_merge($pairs, ['app=queue', 'msg=' . base64_encode($message)])) . "\x1b\\"; + } + + /** + * Extracts the OSC 7501 sequences from the output bytes, in the order they were written. + * + * @return list + */ + private function statusSequences(string $bytes): array + { + $sequences = []; + $offset = 0; + while (($start = strpos($bytes, "\x1b]7501;", $offset)) !== false) { + $end = strpos($bytes, "\x1b\\", $start); + if ($end === false) { + self::fail('An OSC 7501 sequence is not terminated in the output.'); + } + + $sequences[] = substr($bytes, $start, 2 + $end - $start); + $offset = $end + 2; + } + + return $sequences; + } +} From 301f214992f1df17435e59142ae0285ef71c5298 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Wed, 11 Nov 2026 03:31:32 +0300 Subject: [PATCH 02/11] Address review findings for terminal status reports --- docs/guide/en/console-commands.md | 4 +- src/Cli/TerminalStatusReporter.php | 19 +++- src/Command/ConsumeCommand.php | 30 ++++-- tests/Unit/Cli/TerminalStatusReporterTest.php | 91 +++++++++++++++- .../Unit/Command/ConsumeCommandStatusTest.php | 100 ++++++++++++++++++ 5 files changed, 230 insertions(+), 14 deletions(-) diff --git a/docs/guide/en/console-commands.md b/docs/guide/en/console-commands.md index 059c193e..e46898cd 100644 --- a/docs/guide/en/console-commands.md +++ b/docs/guide/en/console-commands.md @@ -66,8 +66,8 @@ so the terminal itself can show the status in its UI. The reports are written directly to the output stream. They require no extra dependencies and appear only when the stream is an interactive TTY and the output is decorated and not quiet; redirected output, log files, cron runs and -quiet invocations are unaffected. Set the environment variable `YII_QUEUE_STATUS` to `off` to disable the reports -explicitly. +quiet invocations are unaffected. Set the environment variable `YII_QUEUE_STATUS` to `off` (also `0`, `no`, `false`) +to disable the reports explicitly. Only the command itself reports status; adapters such as `yiisoft/queue-db`, `yiisoft/queue-redis` or `yiisoft/queue-amqp` do not emit their own terminal status. diff --git a/src/Cli/TerminalStatusReporter.php b/src/Cli/TerminalStatusReporter.php index 69993b1e..3eae55e3 100644 --- a/src/Cli/TerminalStatusReporter.php +++ b/src/Cli/TerminalStatusReporter.php @@ -70,6 +70,17 @@ private function __construct(bool $enabled, ?string $app, $stream = null) $this->stream = $enabled && is_resource($stream) ? $stream : null; } + /** + * Creates a reporter for the given console output. + * + * By default, the report is enabled only when the output is backed by an interactive TTY stream, is decorated + * and not quiet, and the `YII_QUEUE_STATUS` environment variable does not opt out. + * + * @param string|null $app A stable identifier reported to the terminal, 1 to 32 characters among letters, + * digits, "_", "." and "-"; defaults to `queue`. + * @param bool|null $enabled When non-null, forces the report on or off, bypassing TTY detection and the + * `YII_QUEUE_STATUS` opt-out (intended for tests or forced terminals). + */ public static function forOutput(OutputInterface $output, ?string $app = null, ?bool $enabled = null): self { $stream = $output instanceof StreamOutput ? $output->getStream() : null; @@ -164,7 +175,7 @@ public function emit(string $state, ?string $message = null, ?string $id = null, $pairs[] = 'kind=' . $kind; } if ($progress !== null) { - $pairs[] = 'progress=' . (string) $progress; + $pairs[] = 'progress=' . $progress; } $pairs[] = 'app=' . $this->app; @@ -225,6 +236,10 @@ private static function validateId(string $id): void /** * Terminals discard a whole report whose text holds a control character or exceeds the size limit, so the * text is made safe instead. + * + * Unlike the canonical encoder, this replacement does not require `ext-mbstring` or ANSI stripping, so it + * additionally replaces unpaired UTF-16 surrogate sequences with spaces rather than scrubbing arbitrary + * invalid UTF-8. */ private static function normalizeText(?string $text): ?string { @@ -232,7 +247,7 @@ private static function normalizeText(?string $text): ?string return null; } - $text = trim((string) preg_replace('/[\x00-\x1F\x7F]|\xC2[\x80-\x9F]/', ' ', $text)); + $text = trim((string) preg_replace('/(?:[\x00-\x1F\x7F]|\xC2[\x80-\x9F]|\xED[\xA0-\xAF][\x80-\xBF])+/', ' ', $text)); if (strlen($text) > self::MAX_MESSAGE_BYTES) { $text = substr($text, 0, self::MAX_MESSAGE_BYTES); diff --git a/src/Command/ConsumeCommand.php b/src/Command/ConsumeCommand.php index 502759c9..fd5a63fd 100644 --- a/src/Command/ConsumeCommand.php +++ b/src/Command/ConsumeCommand.php @@ -4,13 +4,13 @@ namespace Yiisoft\Queue\Command; -use Throwable; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; +use Throwable; use Yiisoft\Queue\Cli\LoopInterface; use Yiisoft\Queue\Cli\ScopedLoopInterface; use Yiisoft\Queue\Cli\TerminalStatusReporter; @@ -123,13 +123,22 @@ protected function execute(InputInterface $input, OutputInterface $output): int $queueNames = $this->queueProvider->getConsumerQueueNames(); } + $statusReporter->emit('working', self::rootMessage($queueNames, $once)); + $consumers = []; - foreach ($queueNames as $queueName) { - $consumers[$queueName] = $this->queueProvider->getConsumer($queueName); + try { + foreach ($queueNames as $queueName) { + $consumers[$queueName] = $this->queueProvider->getConsumer($queueName); + } + } catch (Throwable $exception) { + $statusReporter->emit('error', 'Resolving consumers failed'); + + throw $exception; } if ($consumers === []) { $output->writeln('No consumers are configured.'); + $statusReporter->emit('done', 'No consumers are configured.'); return Command::SUCCESS; } @@ -140,8 +149,6 @@ protected function execute(InputInterface $input, OutputInterface $output): int $pauseSeconds = 1; } - $statusReporter->emit('working', self::rootMessage($queueNames, $once)); - $processed = 0; if ($this->loop instanceof ScopedLoopInterface) { $this->loop->start(); @@ -201,9 +208,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int private static function rootMessage(array $queueNames, bool $once): string { $count = count($queueNames); - $description = $count === 1 - ? sprintf('queue "%s"', $queueNames[0]) - : sprintf('%d queues', $count); + if ($count === 0) { + $description = 'all configured queues'; + } elseif ($count === 1) { + $description = sprintf('queue "%s"', $queueNames[0]); + } else { + $description = sprintf('%d queues', $count); + } return $once ? sprintf('Consuming %s in one pass', $description) @@ -213,7 +224,8 @@ private static function rootMessage(array $queueNames, bool $once): string /** * A task id for the queue in terminal status reports. * - * Returns `null` when the queue name cannot be represented as a valid protocol id segment, in which case the + * Characters outside the protocol id alphabet, including "/", are replaced with "-", so the result always + * holds a single segment. Returns `null` when the queue name cannot be represented at all, in which case the * report falls back to the program-level record. */ private static function statusId(string $queueName): ?string diff --git a/tests/Unit/Cli/TerminalStatusReporterTest.php b/tests/Unit/Cli/TerminalStatusReporterTest.php index adc95e30..f01d3656 100644 --- a/tests/Unit/Cli/TerminalStatusReporterTest.php +++ b/tests/Unit/Cli/TerminalStatusReporterTest.php @@ -119,6 +119,30 @@ public function testC1ControlCharactersAreReplacedBySpaces(): void ); } + public function testControlCharacterRunsBecomeSingleSpace(): void + { + [, $reporter, $read] = $this->enabledOutput(); + + $reporter->emit('working', "a\x00\x00b"); + + self::assertSame( + "\x1b]7501;state=working:app=queue:msg=" . base64_encode('a b') . "\x1b\\", + $read(), + ); + } + + public function testUtf16SurrogateSequenceIsReplacedBySpace(): void + { + [, $reporter, $read] = $this->enabledOutput(); + + $reporter->emit('working', "a\xED\xA0\x80b"); + + self::assertSame( + "\x1b]7501;state=working:app=queue:msg=" . base64_encode('a b') . "\x1b\\", + $read(), + ); + } + public function testEmptyMessageIsOmitted(): void { [, $reporter, $read] = $this->enabledOutput(); @@ -154,6 +178,18 @@ public function testLongMessageIsCutOnACharacterBoundary(): void ); } + public function testMessageCutIsTrimmedAfterTheBoundary(): void + { + [, $reporter, $read] = $this->enabledOutput(); + + $reporter->emit('working', str_repeat('a', 2047) . ' c'); + + self::assertSame( + "\x1b]7501;state=working:app=queue:msg=" . base64_encode(str_repeat('a', 2047)) . "\x1b\\", + $read(), + ); + } + public function testCustomApp(): void { $stream = fopen('php://memory', 'w+'); @@ -198,6 +234,30 @@ public function testProgressIsBounded(): void $reporter->emit('working', 'Working', null, 101); } + public function testNegativeProgressIsRejected(): void + { + [, $reporter] = $this->enabledOutput(); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('must be between 0 and 100, -1 given'); + + $reporter->emit('working', 'Working', null, -1); + } + + public function testProgressBoundariesAreAccepted(): void + { + [, $reporter, $read] = $this->enabledOutput(); + + $reporter->emit('working', null, null, 0); + $reporter->emit('working', null, null, 100); + + self::assertSame( + "\x1b]7501;state=working:progress=0:app=queue\x1b\\" + . "\x1b]7501;state=working:progress=100:app=queue\x1b\\", + $read(), + ); + } + public function testKindIsOnlyForBlocked(): void { [, $reporter] = $this->enabledOutput(); @@ -223,7 +283,10 @@ public function testInvalidId(): void [, $reporter] = $this->enabledOutput(); $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('The terminal status id "bad id" must be up to 8'); + $this->expectExceptionMessage( + 'The terminal status id "bad id" must be up to 8 "/"-separated segments of 1 to 32 characters ' + . 'among letters, digits, "_", ".", "+" and "-", and at most 128 bytes.', + ); $reporter->emit('working', 'Working', 'bad id'); } @@ -250,6 +313,16 @@ public function testManyIdSegmentsAreRejected(): void ); } + public function testIdAtTheLimitSizeIsAccepted(): void + { + [, $reporter, $read] = $this->enabledOutput(); + + $id = str_repeat('a', 32) . '/' . str_repeat('b', 32) . '/' . str_repeat('c', 32) . '/' . str_repeat('d', 29); + $reporter->emit('working', null, $id); + + self::assertSame("\x1b]7501;state=working:id={$id}:app=queue\x1b\\", $read()); + } + public function testInvalidApp(): void { $stream = fopen('php://memory', 'w+'); @@ -364,6 +437,8 @@ public static function provideOptOutValues(): array [' 0'], [' no '], ['false'], + ['False'], + [' false '], ]; } @@ -379,6 +454,20 @@ public function testEnabledOverride(): void self::assertNotSame('', $this->read($stream)); } + public function testDisabledOverrideWithStreamWritesNothing(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, false); + + self::assertFalse($reporter->isEnabled()); + + $reporter->emit('working', 'Working'); + $reporter->clear(); + + self::assertSame('', $this->read($stream)); + } + /** * @return array{0: StreamOutput, 1: TerminalStatusReporter, 2: callable(): string} */ diff --git a/tests/Unit/Command/ConsumeCommandStatusTest.php b/tests/Unit/Command/ConsumeCommandStatusTest.php index fbf2cfb1..011cbe4a 100644 --- a/tests/Unit/Command/ConsumeCommandStatusTest.php +++ b/tests/Unit/Command/ConsumeCommandStatusTest.php @@ -13,6 +13,7 @@ use Yiisoft\Queue\Cli\TerminalStatusReporter; use Yiisoft\Queue\Command\ConsumeCommand; use Yiisoft\Queue\Provider\PredefinedQueueProvider; +use Yiisoft\Queue\Provider\QueueNotFoundException; use Yiisoft\Queue\QueueConsumerInterface; use Yiisoft\Queue\Stubs\StubLoop; @@ -240,6 +241,105 @@ public function testQueueNameWithInvalidCharsIsSanitizedInId(): void ); } + public function testLongQueueNameIsCutInId(): void + { + $queueName = str_repeat('a', 40); + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider([$queueName => ['consumer' => $this->consumer(2)]]), + new StubLoop(), + $reporter, + ); + + $command->run(new StringInput('--once ' . $queueName), $output); + + self::assertStringContainsString( + $this->sequence('done', 'Queue "' . $queueName . '": 2 messages processed', 'queue/' . str_repeat('a', 32)), + (string) $this->read($stream), + ); + } + + public function testQueueNameWithSlashesIsFlattenedInId(): void + { + $queueName = 'a/b/c/d/e/f/g/h/i'; + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider([$queueName => ['consumer' => $this->consumer(1)]]), + new StubLoop(), + $reporter, + ); + + $command->run(new StringInput('--once "' . $queueName . '"'), $output); + + self::assertStringContainsString( + $this->sequence('done', 'Queue "' . $queueName . '": 1 messages processed', 'queue/a-b-c-d-e-f-g-h-i'), + (string) $this->read($stream), + ); + } + + public function testNonAsciiQueueNameFallsBackToRootRecord(): void + { + $queueName = 'почта'; + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider([$queueName => ['consumer' => $this->consumer(1)]]), + new StubLoop(), + $reporter, + ); + + $command->run(new StringInput('--once "' . $queueName . '"'), $output); + + $bytes = (string) $this->read($stream); + self::assertStringContainsString($this->sequence('working', 'Processing queue "' . $queueName . '"'), $bytes); + self::assertStringNotContainsString('id=', $bytes); + } + + public function testOnceWithoutConfiguredQueuesReportsDoneStatus(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand(new PredefinedQueueProvider([]), new StubLoop(), $reporter); + + $command->run(new StringInput('--once'), $output); + + self::assertSame( + [ + $this->sequence('working', 'Consuming all configured queues in one pass'), + $this->sequence('done', 'No consumers are configured.'), + ], + $this->statusSequences($this->read($stream)), + ); + } + + public function testOnceUnknownQueueReportsErrorStatus(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand(new PredefinedQueueProvider([]), new StubLoop(), $reporter); + + try { + $command->run(new StringInput('--once ghost'), $output); + self::fail('The command should rethrow the queue exception.'); + } catch (QueueNotFoundException $exception) { + } + + self::assertSame( + [ + $this->sequence('working', 'Consuming queue "ghost" in one pass'), + $this->sequence('error', 'Resolving consumers failed'), + ], + $this->statusSequences($this->read($stream)), + ); + } + private function consumer(int|false $count): QueueConsumerInterface { $consumer = $this->createMock(QueueConsumerInterface::class); From 0ba848fde1444ea475df5ec1809e8ed1c25ff42e Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Wed, 11 Nov 2026 03:35:13 +0300 Subject: [PATCH 03/11] Add CHANGELOG entry for terminal status reports --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e4da67d..8685fc47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,4 +2,5 @@ ## 1.0.0 under development +- Enh #355: Report the terminal program status (`OSC 7501`) for `queue:consume`, so terminals that implement the Program Status Protocol can show what the command is doing; reports go out only for decorated, non-quiet, interactive outputs and are disabled by `YII_QUEUE_STATUS=off` (@samdark) - Initial release. \ No newline at end of file From e739641550991484f8d8f8e2a7cd24de7b1e07ac Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Wed, 11 Nov 2026 00:36:10 +0000 Subject: [PATCH 04/11] Apply PHP CS Fixer and Rector changes (CI) --- src/Cli/TerminalStatusReporter.php | 24 +++++++------------ .../Unit/Command/ConsumeCommandStatusTest.php | 2 +- 2 files changed, 9 insertions(+), 17 deletions(-) diff --git a/src/Cli/TerminalStatusReporter.php b/src/Cli/TerminalStatusReporter.php index 3eae55e3..0aaa9bfa 100644 --- a/src/Cli/TerminalStatusReporter.php +++ b/src/Cli/TerminalStatusReporter.php @@ -43,18 +43,14 @@ final class TerminalStatusReporter private const APP_PATTERN = '/^[A-Za-z0-9_.+-]{1,32}$/D'; private const STATES = ['idle', 'working', 'done', 'error', 'blocked']; private const KINDS = ['permission', 'question', 'auth']; - - private bool $enabled; private string $app; /** @var resource|null */ private $stream; /** @param resource|null $stream */ - private function __construct(bool $enabled, ?string $app, $stream = null) + private function __construct(private bool $enabled, ?string $app, $stream = null) { - if ($app === null) { - $app = 'queue'; - } + $app ??= 'queue'; if (!preg_match(self::APP_PATTERN, $app)) { throw new InvalidArgumentException( @@ -64,10 +60,8 @@ private function __construct(bool $enabled, ?string $app, $stream = null) ), ); } - - $this->enabled = $enabled; $this->app = $app; - $this->stream = $enabled && is_resource($stream) ? $stream : null; + $this->stream = $this->enabled && is_resource($stream) ? $stream : null; } /** @@ -85,13 +79,11 @@ public static function forOutput(OutputInterface $output, ?string $app = null, ? { $stream = $output instanceof StreamOutput ? $output->getStream() : null; - if ($enabled === null) { - $enabled = !self::isOptedOut() - && $output->isDecorated() - && !$output->isQuiet() - && $stream !== null - && stream_isatty($stream); - } + $enabled ??= !self::isOptedOut() + && $output->isDecorated() + && !$output->isQuiet() + && $stream !== null + && stream_isatty($stream); return new self($enabled, $app, $stream); } diff --git a/tests/Unit/Command/ConsumeCommandStatusTest.php b/tests/Unit/Command/ConsumeCommandStatusTest.php index 011cbe4a..8d8ec99c 100644 --- a/tests/Unit/Command/ConsumeCommandStatusTest.php +++ b/tests/Unit/Command/ConsumeCommandStatusTest.php @@ -328,7 +328,7 @@ public function testOnceUnknownQueueReportsErrorStatus(): void try { $command->run(new StringInput('--once ghost'), $output); self::fail('The command should rethrow the queue exception.'); - } catch (QueueNotFoundException $exception) { + } catch (QueueNotFoundException) { } self::assertSame( From 9e210922a816c8d5b726317dfdb15829cda573ab Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Wed, 11 Nov 2026 10:47:47 +0300 Subject: [PATCH 05/11] Fix numeric queue names in providers PHP converts numeric string array keys to int, so a definition like ['123' => [...]] previously stored the queue under an int key and broke queue:consume name handling. Cast the keys to strings in both PredefinedQueueProvider and QueueFactoryProvider. --- src/Provider/PredefinedQueueProvider.php | 6 ++++++ src/Provider/QueueFactoryProvider.php | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/src/Provider/PredefinedQueueProvider.php b/src/Provider/PredefinedQueueProvider.php index 7b3d6df2..037ce9aa 100644 --- a/src/Provider/PredefinedQueueProvider.php +++ b/src/Provider/PredefinedQueueProvider.php @@ -32,6 +32,12 @@ final class PredefinedQueueProvider implements QueueProducerProviderInterface, Q public function __construct(array $queues) { foreach ($queues as $queueName => $roles) { + /** + * PHP converts numeric string array keys to int, so the key is not guaranteed to be a string. + * + * @psalm-suppress RedundantCastGivenDocblockType + */ + $queueName = (string) $queueName; if (!is_array($roles) || $roles === []) { throw new InvalidQueueConfigException(sprintf('Queue "%s" must be a non-empty role map containing ready "producer" and/or "consumer" instances.', $queueName)); } diff --git a/src/Provider/QueueFactoryProvider.php b/src/Provider/QueueFactoryProvider.php index 5957815a..2aa914a2 100644 --- a/src/Provider/QueueFactoryProvider.php +++ b/src/Provider/QueueFactoryProvider.php @@ -43,6 +43,12 @@ public function __construct( $validatedDefinitions = $this->validateRoleMaps($definitions); $this->definitions = $validatedDefinitions; foreach ($this->definitions as $queueName => $roles) { + /** + * PHP converts numeric string array keys to int, so the key is not guaranteed to be a string. + * + * @psalm-suppress RedundantCastGivenDocblockType + */ + $queueName = (string) $queueName; if (array_key_exists('producer', $roles)) { $this->producerQueueNames[] = $queueName; } From a1a23cbbd5a6378175232f996a1c96221444e703 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Wed, 11 Nov 2026 10:48:16 +0300 Subject: [PATCH 06/11] Add isSynchronous() to the consumer interface Whether a consumer has an adapter was previously a private detail, which made terminal status reports for queue:consume misleading in synchronous mode (no adapter, messages processed on push). Expose isSynchronous() on QueueConsumerInterface with the QueueConsumer implementation, the debug decorator pass-through and the stub. --- src/Debug/QueueConsumerDecorator.php | 5 +++++ src/QueueConsumer.php | 5 +++++ src/QueueConsumerInterface.php | 5 +++++ stubs/StubQueueConsumer.php | 5 +++++ 4 files changed, 20 insertions(+) diff --git a/src/Debug/QueueConsumerDecorator.php b/src/Debug/QueueConsumerDecorator.php index 03670b45..293d7848 100644 --- a/src/Debug/QueueConsumerDecorator.php +++ b/src/Debug/QueueConsumerDecorator.php @@ -19,4 +19,9 @@ public function listen(): void { $this->queue->listen(); } + + public function isSynchronous(): bool + { + return $this->queue->isSynchronous(); + } } diff --git a/src/QueueConsumer.php b/src/QueueConsumer.php index 36bc944d..6fa8bab1 100644 --- a/src/QueueConsumer.php +++ b/src/QueueConsumer.php @@ -67,6 +67,11 @@ public function listen(): void $this->logger->info('Finish listening to the queue.'); } + public function isSynchronous(): bool + { + return $this->adapter === null; + } + private function startLoop(): void { if ($this->loop instanceof ScopedLoopInterface) { diff --git a/src/QueueConsumerInterface.php b/src/QueueConsumerInterface.php index a0a72163..cb2d8d31 100644 --- a/src/QueueConsumerInterface.php +++ b/src/QueueConsumerInterface.php @@ -22,4 +22,9 @@ public function run(int $max = 0): int; * Listen to the queue and handle messages as they come. */ public function listen(): void; + + /** + * Whether the consumer is in synchronous mode, i.e. has no adapter and processes messages on push only. + */ + public function isSynchronous(): bool; } diff --git a/stubs/StubQueueConsumer.php b/stubs/StubQueueConsumer.php index 164922fc..6adf52ad 100644 --- a/stubs/StubQueueConsumer.php +++ b/stubs/StubQueueConsumer.php @@ -14,4 +14,9 @@ public function run(int $max = 0): int } public function listen(): void {} + + public function isSynchronous(): bool + { + return true; + } } From 280fc8b8c8e8295dc7c072f64aa81700113816fe Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Wed, 11 Nov 2026 10:48:21 +0300 Subject: [PATCH 07/11] Terminal status reporter: dual env opt-out and UTF-8 hardening - Rename the opt-out variable to YII_TERMINAL_STATUS, keeping YII_QUEUE_STATUS as a compatibility alias (the report is generic enough that the queue-specific name was misleading). - Fix the unpaired-surrogate regex range so all bytes \xA0-\xBF are replaced (it stopped at \xAF). - Strip trailing invalid UTF-8 bytes from every message, not only when it was truncated to the byte limit. - Document the dual opt-out, the forced-enabled-but-no-stream case and the synchronous-mode behavior in the docs and CHANGELOG entry. --- CHANGELOG.md | 2 +- docs/guide/en/console-commands.md | 7 ++++-- src/Cli/TerminalStatusReporter.php | 38 +++++++++++++++++++----------- 3 files changed, 30 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8685fc47..8255099b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,5 +2,5 @@ ## 1.0.0 under development -- Enh #355: Report the terminal program status (`OSC 7501`) for `queue:consume`, so terminals that implement the Program Status Protocol can show what the command is doing; reports go out only for decorated, non-quiet, interactive outputs and are disabled by `YII_QUEUE_STATUS=off` (@samdark) +- Enh #355: Report the terminal program status (`OSC 7501`) for `queue:consume`, so terminals that implement the Program Status Protocol can show what the command is doing; reports go out only for decorated, non-quiet, interactive outputs and are disabled by `YII_TERMINAL_STATUS=off` (`YII_QUEUE_STATUS=off` is accepted as a compatibility alias) (@samdark) - Initial release. \ No newline at end of file diff --git a/docs/guide/en/console-commands.md b/docs/guide/en/console-commands.md index e46898cd..33a92b99 100644 --- a/docs/guide/en/console-commands.md +++ b/docs/guide/en/console-commands.md @@ -66,8 +66,11 @@ so the terminal itself can show the status in its UI. The reports are written directly to the output stream. They require no extra dependencies and appear only when the stream is an interactive TTY and the output is decorated and not quiet; redirected output, log files, cron runs and -quiet invocations are unaffected. Set the environment variable `YII_QUEUE_STATUS` to `off` (also `0`, `no`, `false`) -to disable the reports explicitly. +quiet invocations are unaffected. Set the environment variable `YII_TERMINAL_STATUS` to `off` (also `0`, `no`, +`false`) to disable the reports explicitly; `YII_QUEUE_STATUS` is accepted as a compatibility alias. + +In synchronous mode (no adapter configured), `queue:consume` without flags does not listen, so it reports no +"listening" status: it finishes with a `done` report saying that messages are processed on push. Only the command itself reports status; adapters such as `yiisoft/queue-db`, `yiisoft/queue-redis` or `yiisoft/queue-amqp` do not emit their own terminal status. diff --git a/src/Cli/TerminalStatusReporter.php b/src/Cli/TerminalStatusReporter.php index 0aaa9bfa..bc46ca0b 100644 --- a/src/Cli/TerminalStatusReporter.php +++ b/src/Cli/TerminalStatusReporter.php @@ -30,13 +30,18 @@ * * By default, a report is written only when the console output is decorated, not quiet, and backed by an * interactive TTY, so redirects, log files, cron runs and quiet invocations stay clean. Set the environment - * variable `YII_QUEUE_STATUS` to `off` (also `0`, `no`, `false`) to disable the reports explicitly. + * variable `YII_TERMINAL_STATUS` to `off` (also `0`, `no`, `false`) to disable the reports explicitly; + * `YII_QUEUE_STATUS` is accepted as a compatibility alias. + * + * When forced enabled (or backed by a non-stream output), the reporter is enabled but no report is written, + * because there is no stream to write to. * * @see https://www.superlogical.com/rex/docs/build/program-status */ final class TerminalStatusReporter { - private const ENV_VAR = 'YII_QUEUE_STATUS'; + private const ENV_VAR = 'YII_TERMINAL_STATUS'; + private const ENV_VAR_COMPAT = 'YII_QUEUE_STATUS'; private const MAX_MESSAGE_BYTES = 2048; private const MAX_ID_BYTES = 128; private const ID_PATTERN = '/^[A-Za-z0-9_.+-]{1,32}(?:\/[A-Za-z0-9_.+-]{1,32}){0,7}$/D'; @@ -68,12 +73,13 @@ private function __construct(private bool $enabled, ?string $app, $stream = null * Creates a reporter for the given console output. * * By default, the report is enabled only when the output is backed by an interactive TTY stream, is decorated - * and not quiet, and the `YII_QUEUE_STATUS` environment variable does not opt out. + * and not quiet, and neither the `YII_TERMINAL_STATUS` nor the legacy `YII_QUEUE_STATUS` environment variable + * opts out. * * @param string|null $app A stable identifier reported to the terminal, 1 to 32 characters among letters, * digits, "_", "." and "-"; defaults to `queue`. * @param bool|null $enabled When non-null, forces the report on or off, bypassing TTY detection and the - * `YII_QUEUE_STATUS` opt-out (intended for tests or forced terminals). + * environment opt-out (intended for tests or forced terminals). */ public static function forOutput(OutputInterface $output, ?string $app = null, ?bool $enabled = null): self { @@ -206,8 +212,11 @@ public function isEnabled(): bool private static function isOptedOut(): bool { - $value = getenv(self::ENV_VAR); + return self::hasOptOutValue(getenv(self::ENV_VAR)) || self::hasOptOutValue(getenv(self::ENV_VAR_COMPAT)); + } + private static function hasOptOutValue(string|false $value): bool + { return is_string($value) && in_array(strtolower(trim($value)), ['off', '0', 'no', 'false'], true); } @@ -226,12 +235,12 @@ private static function validateId(string $id): void } /** - * Terminals discard a whole report whose text holds a control character or exceeds the size limit, so the - * text is made safe instead. + * Terminals discard a whole report whose text holds a control character, contains an invalid UTF-8 sequence, + * or exceeds the size limit, so the text is made safe instead. * * Unlike the canonical encoder, this replacement does not require `ext-mbstring` or ANSI stripping, so it - * additionally replaces unpaired UTF-16 surrogate sequences with spaces rather than scrubbing arbitrary - * invalid UTF-8. + * replaces unpaired UTF-16 surrogate sequences (all of U+D800–U+DFFF) with spaces and then strips the + * invalid trailing bytes the `//u` check still detects. */ private static function normalizeText(?string $text): ?string { @@ -239,16 +248,17 @@ private static function normalizeText(?string $text): ?string return null; } - $text = trim((string) preg_replace('/(?:[\x00-\x1F\x7F]|\xC2[\x80-\x9F]|\xED[\xA0-\xAF][\x80-\xBF])+/', ' ', $text)); + $text = trim((string) preg_replace('/(?:[\x00-\x1F\x7F]|\xC2[\x80-\x9F]|\xED[\xA0-\xBF][\x80-\xBF])+/', ' ', $text)); if (strlen($text) > self::MAX_MESSAGE_BYTES) { $text = substr($text, 0, self::MAX_MESSAGE_BYTES); - while (strlen($text) > 0 && !preg_match('//u', $text)) { - $text = substr($text, 0, -1); - } - $text = rtrim($text); } + while (!preg_match('//u', $text)) { + $text = substr($text, 0, -1); + } + $text = rtrim($text); + return $text !== '' ? $text : null; } From bad0e3d78e518abb02cab209c5f23e3d3835f83b Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Wed, 11 Nov 2026 10:48:33 +0300 Subject: [PATCH 08/11] Rework queue:consume terminal status reporting - Report the listening status only after the consumer is obtained, and report an error on the active queue id when listening fails, before rethrowing. - In synchronous mode do not report listening at all: finish with a done status saying messages are processed on push (and a console notice). - Count distinct queue names in rootMessage so repeated names read correctly. - When sanitizing or truncation changes a queue name segment, append a 7-character base36 digest of the original name so distinct queues keep distinct task ids. - Track the active queue across the consume loop, emit an idle status when a round processed nothing and the loop continues, and report failures on the last active queue id. Finish the scoped loop in a separate try so a failing finish does not mask the consume error. --- src/Command/ConsumeCommand.php | 112 +++++++++++++++++++++++++++------ 1 file changed, 93 insertions(+), 19 deletions(-) diff --git a/src/Command/ConsumeCommand.php b/src/Command/ConsumeCommand.php index fd5a63fd..d17ac455 100644 --- a/src/Command/ConsumeCommand.php +++ b/src/Command/ConsumeCommand.php @@ -17,11 +17,18 @@ use Yiisoft\Queue\DefaultQueue; use Yiisoft\Queue\Provider\QueueConsumerProviderInterface; +use function array_unique; use function count; +use function crc32; +use function intdiv; use function preg_replace; use function sprintf; +use function str_pad; use function substr; use function trim; +use function strlen; + +use const STR_PAD_LEFT; #[AsCommand('queue:consume', 'Consumes queued messages. Listens continuously unless --once is passed.')] final class ConsumeCommand extends Command @@ -104,17 +111,42 @@ protected function execute(InputInterface $input, OutputInterface $output): int } $queueName = $queueNames[0] ?? DefaultQueue::NAME; - $statusReporter->emit('working', sprintf('Listening on queue "%s"', $queueName)); try { - $this->queueProvider->getConsumer($queueName)->listen(); + $consumer = $this->queueProvider->getConsumer($queueName); + } catch (Throwable $exception) { + $statusReporter->emit('error', sprintf('Consume on queue "%s" failed', $queueName)); + + throw $exception; + } + + if ($consumer->isSynchronous()) { + $output->writeln('Synchronous mode: no adapter is configured, messages are processed on push.'); + $statusReporter->emit( + 'done', + 'Synchronous mode: messages are processed on push', + self::statusId($queueName), + ); + + return Command::SUCCESS; + } + + $statusId = self::statusId($queueName); + $statusReporter->emit('working', sprintf('Listening on queue "%s"', $queueName), $statusId); + + try { + $consumer->listen(); } catch (Throwable $exception) { + if ($statusId !== null) { + $statusReporter->emit('error', sprintf('Queue "%s" failed', $queueName), $statusId); + } + $statusReporter->emit('error', sprintf('Consume on queue "%s" failed', $queueName)); throw $exception; } - $statusReporter->emit('done', sprintf('Stopped listening on queue "%s"', $queueName)); + $statusReporter->emit('done', sprintf('Stopped listening on queue "%s"', $queueName), $statusId); return Command::SUCCESS; } @@ -150,26 +182,31 @@ protected function execute(InputInterface $input, OutputInterface $output): int } $processed = 0; - if ($this->loop instanceof ScopedLoopInterface) { - $this->loop->start(); - } + $activeName = null; + $activeId = null; + $exception = null; try { + if ($this->loop instanceof ScopedLoopInterface) { + $this->loop->start(); + } + while ($once || $this->loop->canContinue()) { $hasMessages = false; - foreach ($consumers as $queueName => $consumer) { + foreach ($queueNames as $queueName) { if ($once) { $output->write("Processing queue $queueName... "); } - $statusId = self::statusId($queueName); - $statusReporter->emit('working', sprintf('Processing queue "%s"', $queueName), $statusId); + $activeName = $queueName; + $activeId = self::statusId($queueName); + $statusReporter->emit('working', sprintf('Processing queue "%s"', $queueName), $activeId); - $count = $consumer->run($limit); + $count = $consumers[$queueName]->run($limit); $hasMessages = $count > 0 || $hasMessages; $processed += $count; - $statusReporter->emit('done', sprintf('Queue "%s": %d messages processed', $queueName, $count), $statusId); + $statusReporter->emit('done', sprintf('Queue "%s": %d messages processed', $queueName, $count), $activeId); if ($once) { $output->writeln("Messages processed: $count."); @@ -181,18 +218,34 @@ protected function execute(InputInterface $input, OutputInterface $output): int } if (!$hasMessages && $this->loop->canContinue()) { + if ($activeName !== null && $activeId !== null) { + $statusReporter->emit('idle', sprintf('Queue "%s" is idle', $activeName), $activeId); + } + /** @psalm-var 0|positive-int $pauseSeconds */ sleep($pauseSeconds); } } - } catch (Throwable $exception) { - $statusReporter->emit('error', 'Consume failed'); + } catch (Throwable $caught) { + $exception = $caught; + } - throw $exception; - } finally { + try { if ($this->loop instanceof ScopedLoopInterface) { $this->loop->finish(); } + } catch (Throwable $caught) { + $exception ??= $caught; + } + + if ($exception !== null) { + if ($activeName !== null && $activeId !== null) { + $statusReporter->emit('error', sprintf('Queue "%s" failed', $activeName), $activeId); + } + + $statusReporter->emit('error', 'Consume failed'); + + throw $exception; } $statusReporter->emit('done', $once @@ -207,7 +260,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int */ private static function rootMessage(array $queueNames, bool $once): string { - $count = count($queueNames); + $count = count(array_unique($queueNames)); if ($count === 0) { $description = 'all configured queues'; } elseif ($count === 1) { @@ -225,8 +278,9 @@ private static function rootMessage(array $queueNames, bool $once): string * A task id for the queue in terminal status reports. * * Characters outside the protocol id alphabet, including "/", are replaced with "-", so the result always - * holds a single segment. Returns `null` when the queue name cannot be represented at all, in which case the - * report falls back to the program-level record. + * holds a single segment. When sanitizing or truncation changes the name, a short digest of the original name + * is appended so that distinct queues keep distinct records. Returns `null` when the queue name cannot be + * represented at all, in which case the report falls back to the program-level record. */ private static function statusId(string $queueName): ?string { @@ -236,6 +290,26 @@ private static function statusId(string $queueName): ?string return null; } - return 'queue/' . substr($segment, 0, 32); + if ($segment !== $queueName || strlen($segment) > 32) { + $segment = substr($segment, 0, 23) . '-' . self::idSuffix($queueName); + } + + return 'queue/' . $segment; + } + + /** + * A 7-character base36 digest appended to a sanitized or truncated queue name segment. + */ + private static function idSuffix(string $queueName): string + { + $alphabet = '0123456789abcdefghijklmnopqrstuvwxyz'; + $value = crc32($queueName); + $digest = ''; + do { + $digest = $alphabet[$value % 36] . $digest; + $value = intdiv($value, 36); + } while ($value > 0); + + return str_pad($digest, 7, '0', STR_PAD_LEFT); } } From f15cc8e1ffcab8a56c110aca9df90f4cdd1959da Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Wed, 11 Nov 2026 10:48:36 +0300 Subject: [PATCH 09/11] Add regression tests for terminal status behavior Cover the reworked queue:consume status flow (once/all priority, pause bounds, idle emission, exception paths, digest suffixes for sanitised and truncated queue names, numeric queue names, synchronous mode) and the reporter's dual opt-out variables, plus no-op behavior of a disabled reporter for invalid emit/clear arguments. --- tests/Unit/Cli/TerminalStatusReporterTest.php | 103 +++- .../Unit/Command/ConsumeCommandStatusTest.php | 466 +++++++++++++++++- 2 files changed, 548 insertions(+), 21 deletions(-) diff --git a/tests/Unit/Cli/TerminalStatusReporterTest.php b/tests/Unit/Cli/TerminalStatusReporterTest.php index f01d3656..bb024fb2 100644 --- a/tests/Unit/Cli/TerminalStatusReporterTest.php +++ b/tests/Unit/Cli/TerminalStatusReporterTest.php @@ -27,19 +27,22 @@ protected function setUp(): void { parent::setUp(); - $this->hadEnv = getenv('YII_QUEUE_STATUS') !== false; - $this->savedEnvValue = (string) getenv('YII_QUEUE_STATUS'); + $this->hadEnv = getenv('YII_TERMINAL_STATUS') !== false; + $this->savedEnvValue = (string) getenv('YII_TERMINAL_STATUS'); + putenv('YII_TERMINAL_STATUS'); putenv('YII_QUEUE_STATUS'); } protected function tearDown(): void { if ($this->hadEnv) { - putenv('YII_QUEUE_STATUS=' . $this->savedEnvValue); + putenv('YII_TERMINAL_STATUS=' . $this->savedEnvValue); } else { - putenv('YII_QUEUE_STATUS'); + putenv('YII_TERMINAL_STATUS'); } + putenv('YII_QUEUE_STATUS'); + parent::tearDown(); } @@ -143,6 +146,39 @@ public function testUtf16SurrogateSequenceIsReplacedBySpace(): void ); } + public function testLowUtf16SurrogateSequenceIsReplacedBySpace(): void + { + [, $reporter, $read] = $this->enabledOutput(); + + $reporter->emit('working', "a\xED\xB0\x80b"); + + self::assertSame( + "\x1b]7501;state=working:app=queue:msg=" . base64_encode('a b') . "\x1b\\", + $read(), + ); + } + + public function testInvalidUtf8TailIsStripped(): void + { + [, $reporter, $read] = $this->enabledOutput(); + + $reporter->emit('working', "ab\xFF"); + + self::assertSame( + "\x1b]7501;state=working:app=queue:msg=" . base64_encode('ab') . "\x1b\\", + $read(), + ); + } + + public function testMessageOfOnlyInvalidUtf8IsDropped(): void + { + [, $reporter, $read] = $this->enabledOutput(); + + $reporter->emit('working', "\xFF\xFF"); + + self::assertSame("\x1b]7501;state=working:app=queue\x1b\\", $read()); + } + public function testEmptyMessageIsOmitted(): void { [, $reporter, $read] = $this->enabledOutput(); @@ -416,9 +452,9 @@ public function testNotEnabledForBufferedOutput(): void /** * @dataProvider provideOptOutValues */ - public function testOptOutViaEnvironment(string $value): void + public function testOptOutViaEnvironment(string $envVar, string $value): void { - putenv('YII_QUEUE_STATUS=' . $value); + putenv($envVar . '=' . $value); $stream = fopen('php://memory', 'w+'); $reporter = TerminalStatusReporter::forOutput(new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true)); @@ -431,15 +467,26 @@ public function testOptOutViaEnvironment(string $value): void public static function provideOptOutValues(): array { - return [ - ['off'], - ['OFF'], - [' 0'], - [' no '], - ['false'], - ['False'], - [' false '], - ]; + $values = ['off', 'OFF', ' 0', ' no ', 'false', 'False', ' false ']; + + $cases = []; + foreach (['YII_TERMINAL_STATUS', 'YII_QUEUE_STATUS'] as $envVar) { + foreach ($values as $value) { + $cases[] = [$envVar, $value]; + } + } + + return $cases; + } + + public function testEnvironmentAliasDoesNotOverrideAbsentFamilyVariable(): void + { + putenv('YII_QUEUE_STATUS=off'); + + $stream = fopen('php://memory', 'w+'); + $reporter = TerminalStatusReporter::forOutput(new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true)); + + self::assertFalse($reporter->isEnabled()); } public function testEnabledOverride(): void @@ -468,6 +515,32 @@ public function testDisabledOverrideWithStreamWritesNothing(): void self::assertSame('', $this->read($stream)); } + public function testDisabledOverrideWithInvalidEmitArgumentsWritesNothing(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, false); + + self::assertFalse($reporter->isEnabled()); + + $reporter->emit('bogus', 'Working', str_repeat('a', 130), 101, 'wait'); + + self::assertSame('', $this->read($stream)); + } + + public function testDisabledOverrideWithInvalidClearIdWritesNothing(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, false); + + self::assertFalse($reporter->isEnabled()); + + $reporter->clear(str_repeat('a', 130)); + + self::assertSame('', $this->read($stream)); + } + /** * @return array{0: StreamOutput, 1: TerminalStatusReporter, 2: callable(): string} */ diff --git a/tests/Unit/Command/ConsumeCommandStatusTest.php b/tests/Unit/Command/ConsumeCommandStatusTest.php index 8d8ec99c..3ff31abd 100644 --- a/tests/Unit/Command/ConsumeCommandStatusTest.php +++ b/tests/Unit/Command/ConsumeCommandStatusTest.php @@ -10,8 +10,10 @@ use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\StreamOutput; use Yiisoft\Queue\Cli\LoopInterface; +use Yiisoft\Queue\Cli\ScopedLoopInterface; use Yiisoft\Queue\Cli\TerminalStatusReporter; use Yiisoft\Queue\Command\ConsumeCommand; +use Yiisoft\Queue\DefaultQueue; use Yiisoft\Queue\Provider\PredefinedQueueProvider; use Yiisoft\Queue\Provider\QueueNotFoundException; use Yiisoft\Queue\QueueConsumerInterface; @@ -19,6 +21,7 @@ use function base64_encode; use function fopen; +use function hrtime; use function implode; use function rewind; use function str_contains; @@ -99,13 +102,17 @@ public function canContinue(): bool $reporter, ); + $start = hrtime(true); $command->run(new StringInput('--all --pause=0 queuea'), $output); + $elapsed = (hrtime(true) - $start) / 1_000_000_000; + self::assertLessThan(0.75, $elapsed, 'A zero pause must not sleep between passes.'); self::assertSame( [ $this->sequence('working', 'Listening on queue "queuea"'), $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), $this->sequence('done', 'Queue "queuea": 0 messages processed', 'queue/queuea'), + $this->sequence('idle', 'Queue "queuea" is idle', 'queue/queuea'), $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), $this->sequence('done', 'Queue "queuea": 1 messages processed', 'queue/queuea'), $this->sequence('done', 'Stopped listening'), @@ -129,8 +136,8 @@ public function testListenMode(): void self::assertSame( [ - $this->sequence('working', 'Listening on queue "queuea"'), - $this->sequence('done', 'Stopped listening on queue "queuea"'), + $this->sequence('working', 'Listening on queue "queuea"', 'queue/queuea'), + $this->sequence('done', 'Stopped listening on queue "queuea"', 'queue/queuea'), ], $this->statusSequences($this->read($stream)), ); @@ -158,6 +165,7 @@ public function testRunExceptionReportsErrorStatus(): void [ $this->sequence('working', 'Consuming queue "queuea" in one pass'), $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), + $this->sequence('error', 'Queue "queuea" failed', 'queue/queuea'), $this->sequence('error', 'Consume failed'), ], $this->statusSequences($this->read($stream)), @@ -186,7 +194,8 @@ public function testListenExceptionReportsErrorStatus(): void self::assertSame( [ - $this->sequence('working', 'Listening on queue "queuea"'), + $this->sequence('working', 'Listening on queue "queuea"', 'queue/queuea'), + $this->sequence('error', 'Queue "queuea" failed', 'queue/queuea'), $this->sequence('error', 'Consume on queue "queuea" failed'), ], $this->statusSequences($this->read($stream)), @@ -236,7 +245,7 @@ public function testQueueNameWithInvalidCharsIsSanitizedInId(): void $command->run(new StringInput('--once "weird: name"'), $output); self::assertStringContainsString( - $this->sequence('done', 'Queue "weird: name": 1 messages processed', 'queue/weird-name'), + $this->sequence('done', 'Queue "weird: name": 1 messages processed', 'queue/weird-name-1uyugt5'), (string) $this->read($stream), ); } @@ -256,7 +265,50 @@ public function testLongQueueNameIsCutInId(): void $command->run(new StringInput('--once ' . $queueName), $output); self::assertStringContainsString( - $this->sequence('done', 'Queue "' . $queueName . '": 2 messages processed', 'queue/' . str_repeat('a', 32)), + $this->sequence( + 'done', + 'Queue "' . $queueName . '": 2 messages processed', + 'queue/' . str_repeat('a', 23) . '-1jvayw5', + ), + (string) $this->read($stream), + ); + } + + public function testSixDigitDigestIsZeroPadded(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider(['aa/bb' => ['consumer' => $this->consumer(1)]]), + new StubLoop(), + $reporter, + ); + + $command->run(new StringInput('--once "aa/bb"'), $output); + + self::assertStringContainsString( + $this->sequence('done', 'Queue "aa/bb": 1 messages processed', 'queue/aa-bb-0ap1hqi'), + (string) $this->read($stream), + ); + } + + public function testThirtyTwoCharQueueNameKeepsItsFullSegment(): void + { + $queueName = str_repeat('a', 32); + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider([$queueName => ['consumer' => $this->consumer(1)]]), + new StubLoop(), + $reporter, + ); + + $command->run(new StringInput('--once ' . $queueName), $output); + + self::assertStringContainsString( + $this->sequence('done', 'Queue "' . $queueName . '": 1 messages processed', 'queue/' . $queueName), (string) $this->read($stream), ); } @@ -276,11 +328,32 @@ public function testQueueNameWithSlashesIsFlattenedInId(): void $command->run(new StringInput('--once "' . $queueName . '"'), $output); self::assertStringContainsString( - $this->sequence('done', 'Queue "' . $queueName . '": 1 messages processed', 'queue/a-b-c-d-e-f-g-h-i'), + $this->sequence('done', 'Queue "' . $queueName . '": 1 messages processed', 'queue/a-b-c-d-e-f-g-h-i-1ju46bo'), (string) $this->read($stream), ); } + public function testNamesThatSanitizeToTheSameTextKeepDistinctIds(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider([ + 'mail-a' => ['consumer' => $this->consumer(1)], + 'mail:a' => ['consumer' => $this->consumer(2)], + ]), + new StubLoop(), + $reporter, + ); + + $command->run(new StringInput('--once "mail-a" "mail:a"'), $output); + + $bytes = (string) $this->read($stream); + self::assertStringContainsString($this->sequence('done', 'Queue "mail-a": 1 messages processed', 'queue/mail-a'), $bytes); + self::assertStringContainsString($this->sequence('done', 'Queue "mail:a": 2 messages processed', 'queue/mail-a-1fc5674'), $bytes); + } + public function testNonAsciiQueueNameFallsBackToRootRecord(): void { $queueName = 'почта'; @@ -340,6 +413,387 @@ public function testOnceUnknownQueueReportsErrorStatus(): void ); } + public function testNumericQueueNameIsProcessed(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider(['123' => ['consumer' => $this->consumer(2)]]), + new StubLoop(), + $reporter, + ); + + $command->run(new StringInput('--once 123'), $output); + + self::assertStringContainsString( + $this->sequence('done', 'Queue "123": 2 messages processed', 'queue/123'), + (string) $this->read($stream), + ); + } + + public function testNumericQueueNamesFromProviderAreProcessed(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider(['123' => ['consumer' => $this->consumer(1)]]), + new StubLoop(), + $reporter, + ); + + $command->run(new StringInput('--once'), $output); + + self::assertStringContainsString( + $this->sequence('done', 'Queue "123": 1 messages processed', 'queue/123'), + (string) $this->read($stream), + ); + } + + public function testDuplicateQueueNamesAreCountedOnce(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider([ + 'mail' => ['consumer' => $this->consumer(1)], + 'news' => ['consumer' => $this->consumer(1)], + ]), + new StubLoop(), + $reporter, + ); + + $command->run(new StringInput('--once mail mail news'), $output); + + self::assertStringContainsString( + $this->sequence('working', 'Consuming 2 queues in one pass'), + (string) $this->read($stream), + ); + } + + public function testSynchronousModeReportsDoneWithoutListening(): void + { + $consumer = $this->createMock(QueueConsumerInterface::class); + $consumer->method('isSynchronous')->willReturn(true); + + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider(['queuea' => ['consumer' => $consumer]]), + new StubLoop(), + $reporter, + ); + + $command->run(new StringInput('queuea'), $output); + + self::assertSame( + [ + $this->sequence('done', 'Synchronous mode: messages are processed on push', 'queue/queuea'), + ], + $this->statusSequences($this->read($stream)), + ); + self::assertStringContainsString('Synchronous mode', (string) $this->read($stream)); + } + + public function testLoopStartFailureReportsErrorStatus(): void + { + $loop = new class implements ScopedLoopInterface { + public function start(): void + { + throw new RuntimeException('loop start failed'); + } + + public function canContinue(): bool + { + return true; + } + + public function finish(): void {} + }; + + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider(['queuea' => ['consumer' => $this->consumer(3)]]), + $loop, + $reporter, + ); + + try { + $command->run(new StringInput('--once queuea'), $output); + self::fail('The command should rethrow the loop exception.'); + } catch (RuntimeException $exception) { + self::assertSame('loop start failed', $exception->getMessage()); + } + + self::assertSame( + [ + $this->sequence('working', 'Consuming queue "queuea" in one pass'), + $this->sequence('error', 'Consume failed'), + ], + $this->statusSequences($this->read($stream)), + ); + } + + public function testLoopFinishFailureReportsErrorStatus(): void + { + $loop = new class implements ScopedLoopInterface { + public function start(): void {} + + public function canContinue(): bool + { + return true; + } + + public function finish(): void + { + throw new RuntimeException('loop finish failed'); + } + }; + + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider(['queuea' => ['consumer' => $this->consumer(3)]]), + $loop, + $reporter, + ); + + try { + $command->run(new StringInput('--once queuea'), $output); + self::fail('The command should rethrow the loop exception.'); + } catch (RuntimeException $exception) { + self::assertSame('loop finish failed', $exception->getMessage()); + } + + self::assertSame( + [ + $this->sequence('working', 'Consuming queue "queuea" in one pass'), + $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), + $this->sequence('done', 'Queue "queuea": 3 messages processed', 'queue/queuea'), + $this->sequence('error', 'Queue "queuea" failed', 'queue/queuea'), + $this->sequence('error', 'Consume failed'), + ], + $this->statusSequences($this->read($stream)), + ); + } + + public function testAllModeWithoutPauseOptionSleepsOneSecond(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider(['queuea' => ['consumer' => $this->consumer(0)]]), + $this->twoShotLoop(), + $reporter, + ); + + $start = hrtime(true); + $command->run(new StringInput('--all'), $output); + $elapsed = (hrtime(true) - $start) / 1_000_000_000; + + self::assertGreaterThan(0.9, $elapsed, 'The default pause is one second.'); + self::assertLessThan(1.8, $elapsed, 'The default pause is one second.'); + } + + public function testAllModeNegativePauseIsClampedToOneSecond(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider(['queuea' => ['consumer' => $this->consumer(0)]]), + $this->twoShotLoop(), + $reporter, + ); + + $start = hrtime(true); + $command->run(new StringInput('--all --pause=-5 queuea'), $output); + $elapsed = (hrtime(true) - $start) / 1_000_000_000; + + self::assertGreaterThan(0.9, $elapsed, 'A negative pause is clamped to one second.'); + self::assertLessThan(1.8, $elapsed, 'A negative pause is clamped to one second.'); + } + + public function testAllModeWithProcessedMessagesDoesNotEmitIdle(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider(['queuea' => ['consumer' => $this->consumer(1)]]), + $this->twoShotLoop(), + $reporter, + ); + + $command->run(new StringInput('--all --pause=0 queuea'), $output); + + self::assertSame( + [ + $this->sequence('working', 'Listening on queue "queuea"'), + $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), + $this->sequence('done', 'Queue "queuea": 1 messages processed', 'queue/queuea'), + $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), + $this->sequence('done', 'Queue "queuea": 1 messages processed', 'queue/queuea'), + $this->sequence('done', 'Stopped listening'), + ], + $this->statusSequences($this->read($stream)), + ); + } + + public function testUnrepresentableQueueNameIdleDoesNotEmitIdle(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider(['!!!' => ['consumer' => $this->consumer(0)]]), + $this->twoShotLoop(), + $reporter, + ); + + $command->run(new StringInput('--all --pause=0'), $output); + + self::assertSame( + [ + $this->sequence('working', 'Listening on queue "!!!"'), + $this->sequence('working', 'Processing queue "!!!"'), + $this->sequence('done', 'Queue "!!!": 0 messages processed'), + $this->sequence('done', 'Stopped listening'), + ], + $this->statusSequences($this->read($stream)), + ); + } + + public function testOnceFlagTakesPrecedenceOverAll(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider(['queuea' => ['consumer' => $this->consumer(3)]]), + new StubLoop(), + $reporter, + ); + + $command->run(new StringInput('--once --all queuea'), $output); + + self::assertSame( + [ + $this->sequence('working', 'Consuming queue "queuea" in one pass'), + $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), + $this->sequence('done', 'Queue "queuea": 3 messages processed', 'queue/queuea'), + $this->sequence('done', '3 messages processed'), + ], + $this->statusSequences($this->read($stream)), + ); + } + + public function testFirstExceptionIsRethrownWhenLoopFinishAlsoFails(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider(['queuea' => ['consumer' => $this->consumer(false)]]), + $this->twoShotLoop(true), + $reporter, + ); + + try { + $command->run(new StringInput('--once queuea'), $output); + self::fail('The command should rethrow the first exception.'); + } catch (RuntimeException $exception) { + self::assertSame('boom', $exception->getMessage()); + } + + self::assertSame( + [ + $this->sequence('working', 'Consuming queue "queuea" in one pass'), + $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), + $this->sequence('error', 'Queue "queuea" failed', 'queue/queuea'), + $this->sequence('error', 'Consume failed'), + ], + $this->statusSequences($this->read($stream)), + ); + } + + public function testUnrepresentableQueueNameFailureFallsBackToProgramRecord(): void + { + $stream = fopen('php://memory', 'w+'); + $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); + $reporter = TerminalStatusReporter::forOutput($output, null, true); + $command = new ConsumeCommand( + new PredefinedQueueProvider(['!!!' => ['consumer' => $this->consumer(false)]]), + new StubLoop(), + $reporter, + ); + + try { + $command->run(new StringInput('--once "!!!"'), $output); + self::fail('The command should rethrow the handler exception.'); + } catch (RuntimeException $exception) { + self::assertSame('boom', $exception->getMessage()); + } + + self::assertSame( + [ + $this->sequence('working', 'Consuming queue "!!!" in one pass'), + $this->sequence('working', 'Processing queue "!!!"'), + $this->sequence('error', 'Consume failed'), + ], + $this->statusSequences($this->read($stream)), + ); + } + + public function testOptionDescriptionsAndHelpTexts(): void + { + $command = new ConsumeCommand(new PredefinedQueueProvider([]), new StubLoop()); + + self::assertSame( + 'Continuously poll queues. Without names, use all configured consumer queues. Recommended for development only.', + $command->getDefinition()->getOption('all')->getDescription(), + ); + self::assertSame( + 'Without queue names, listen to ' . DefaultQueue::NAME . '. ' + . '--once and --all instead use all configured consumer queues. ' + . '--once takes precedence over --all.', + $command->getHelp(), + ); + } + + /** + * A loop that allows one full pass: the first two `canContinue()` checks pass, the rest do not. + */ + private function twoShotLoop(bool $finishFails = false): ScopedLoopInterface + { + return new class ($finishFails) implements ScopedLoopInterface { + private int $checks = 0; + + public function __construct(private bool $finishFails) {} + + public function start(): void {} + + public function canContinue(): bool + { + return $this->checks++ < 2; + } + + public function finish(): void + { + if ($this->finishFails) { + throw new RuntimeException('loop finish failed'); + } + } + }; + } + private function consumer(int|false $count): QueueConsumerInterface { $consumer = $this->createMock(QueueConsumerInterface::class); From 359ddd9ead4b3ddbc45e1d9baac6e2a0688a839a Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Wed, 11 Nov 2026 11:16:41 +0300 Subject: [PATCH 10/11] Fix never-returning test callbacks for PHP 8.1 PHP 8.1 does not compile an arrow function with a never return type whose body is a throw expression (fatal "A never-returning function must not return"); rewrite the two throwing callbacks as block-body closures, which compile on every supported version. --- tests/Unit/Command/ConsumeCommandStatusTest.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/Unit/Command/ConsumeCommandStatusTest.php b/tests/Unit/Command/ConsumeCommandStatusTest.php index 3ff31abd..a736d24d 100644 --- a/tests/Unit/Command/ConsumeCommandStatusTest.php +++ b/tests/Unit/Command/ConsumeCommandStatusTest.php @@ -178,7 +178,9 @@ public function testListenExceptionReportsErrorStatus(): void $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); $reporter = TerminalStatusReporter::forOutput($output, null, true); $consumer = $this->createMock(QueueConsumerInterface::class); - $consumer->method('listen')->willReturnCallback(static fn(): never => throw new RuntimeException('boom')); + $consumer->method('listen')->willReturnCallback(static function (): never { + throw new RuntimeException('boom'); + }); $command = new ConsumeCommand( new PredefinedQueueProvider(['queuea' => ['consumer' => $consumer]]), new StubLoop(), @@ -798,7 +800,9 @@ private function consumer(int|false $count): QueueConsumerInterface { $consumer = $this->createMock(QueueConsumerInterface::class); if ($count === false) { - $consumer->method('run')->willReturnCallback(static fn(): never => throw new RuntimeException('boom')); + $consumer->method('run')->willReturnCallback(static function (): never { + throw new RuntimeException('boom'); + }); } else { $consumer->method('run')->willReturn($count); } From 693273f842198cf62217abe6ed1208d3dc1c8bff Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Wed, 11 Nov 2026 11:46:17 +0300 Subject: [PATCH 11/11] Reconcile queue terminal reporting and preserve numeric discovery --- CHANGELOG.md | 1 - docs/guide/en/console-commands.md | 49 +- src/Cli/Osc7501Encoder.php | 139 +++ src/Cli/SignalLoop.php | 6 + src/Cli/TerminalStatusReporter.php | 261 +---- src/Cli/TerminalStatusWriter.php | 76 ++ src/Command/ConsumeCommand.php | 285 ++---- src/Debug/QueueConsumerDecorator.php | 5 - src/Provider/PredefinedQueueProvider.php | 10 +- src/Provider/QueueFactoryProvider.php | 18 +- src/QueueConsumer.php | 5 - src/QueueConsumerInterface.php | 5 - stubs/StubQueueConsumer.php | 5 - tests/Unit/Cli/Osc7501EncoderTest.php | 86 ++ tests/Unit/Cli/TerminalStatusReporterTest.php | 568 +---------- tests/Unit/Cli/TerminalStatusWriterTest.php | 58 ++ .../Unit/Command/ConsumeCommandStatusTest.php | 951 ++++-------------- 17 files changed, 762 insertions(+), 1766 deletions(-) create mode 100644 src/Cli/Osc7501Encoder.php create mode 100644 src/Cli/TerminalStatusWriter.php create mode 100644 tests/Unit/Cli/Osc7501EncoderTest.php create mode 100644 tests/Unit/Cli/TerminalStatusWriterTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 8255099b..0e4da67d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,5 +2,4 @@ ## 1.0.0 under development -- Enh #355: Report the terminal program status (`OSC 7501`) for `queue:consume`, so terminals that implement the Program Status Protocol can show what the command is doing; reports go out only for decorated, non-quiet, interactive outputs and are disabled by `YII_TERMINAL_STATUS=off` (`YII_QUEUE_STATUS=off` is accepted as a compatibility alias) (@samdark) - Initial release. \ No newline at end of file diff --git a/docs/guide/en/console-commands.md b/docs/guide/en/console-commands.md index 33a92b99..447192e0 100644 --- a/docs/guide/en/console-commands.md +++ b/docs/guide/en/console-commands.md @@ -60,17 +60,38 @@ the default `SignalLoop` handles signals such as `SIGTERM`/`SIGINT`. ## Terminal program status (OSC 7501) -When run in an interactive terminal, `queue:consume` reports what it is doing — processing or waiting on messages — -and how it finished, using the [Program Status Protocol (OSC 7501)](https://www.superlogical.com/rex/docs/build/program-status), -so the terminal itself can show the status in its UI. - -The reports are written directly to the output stream. They require no extra dependencies and appear only when the -stream is an interactive TTY and the output is decorated and not quiet; redirected output, log files, cron runs and -quiet invocations are unaffected. Set the environment variable `YII_TERMINAL_STATUS` to `off` (also `0`, `no`, -`false`) to disable the reports explicitly; `YII_QUEUE_STATUS` is accepted as a compatibility alias. - -In synchronous mode (no adapter configured), `queue:consume` without flags does not listen, so it reports no -"listening" status: it finishes with a `done` report saying that messages are processed on push. - -Only the command itself reports status; adapters such as `yiisoft/queue-db`, `yiisoft/queue-redis` or -`yiisoft/queue-amqp` do not emit their own terminal status. +`queue:consume` can report activity to terminals supporting the +[Program Status Protocol (OSC 7501)](https://www.superlogical.com/rex/docs/build/program-status). +Normal console output stays unchanged. No extra dependency is required. + +Reports use the terminal attached to standard error when Symfony provides a separate error output. +For another stream output, they use that stream. Reporting requires positive TTY detection, enabled +ANSI decoration and non-quiet output on the selected stream. Redirecting standard error, running under +cron, disabling decoration or using quiet mode suppresses the reports. Forcing decoration does not +bypass TTY detection. Unknown or buffered outputs do not receive reports. + +Set `YII_TERMINAL_STATUS=off` to disable reporting (`0`, `no` and `false` also disable it, +case-insensitively). Other values do not force reporting on redirected streams. OSC 7501 is sent +without querying the terminal. Delivery through SSH or multiplexers depends on their support; +an interactive SSH terminal can qualify, while a connection without a TTY cannot. + +Each invocation uses a distinct record subtree with stable `app=queue`, so concurrent consumers and +Composer do not compete for the terminal's root record. Queue records use positions in the selected +queue list rather than names, supporting numeric, Unicode and otherwise unusual queue names without +identifier collisions. Repeated passes update those same records rather than allocate one per job. + +A finite `--once` pass reports completion after processing and loop cleanup. Continuous polling remains +working while waiting for messages. When a persistent consumer returns, or the default signal loop is +interrupted, the invocation's subtree is replaced by an idle record rather than a completion notice. +The listening call may return immediately for a synchronous consumer; reports do not claim that it +opened a subscription. Custom consumer or loop implementations must provide their own cancellation +semantics; the command cannot infer why a custom finite consumer returned early. + +Consumption failures report error for the active queue and the invocation. Messages contain queue +names and counts, not job bodies, credentials or exception details. Invalid UTF-8 messages are omitted; +valid messages are kept within the protocol's byte limit with control characters replaced. A failed +status stream disables further reports without changing the consumption result. + +Only the command reports status. Adapters such as `yiisoft/queue-db`, `yiisoft/queue-redis` and +`yiisoft/queue-amqp` do not emit duplicate reports. The encoder, writer and Symfony adapter are internal +implementation details; applications can continue constructing `ConsumeCommand` with its provider and loop. diff --git a/src/Cli/Osc7501Encoder.php b/src/Cli/Osc7501Encoder.php new file mode 100644 index 00000000..73c2a8d2 --- /dev/null +++ b/src/Cli/Osc7501Encoder.php @@ -0,0 +1,139 @@ + 100) { + throw new InvalidArgumentException( + sprintf('The terminal status progress must be between 0 and 100, %d given.', $progress), + ); + } + } + + $pairs = ['state=' . $state, 'id=' . $id]; + if ($kind !== null) { + $pairs[] = 'kind=' . $kind; + } + if ($progress !== null) { + $pairs[] = 'progress=' . $progress; + } + $pairs[] = 'app=' . $app; + + $message = self::normalizeText($message); + if ($message !== null) { + $pairs[] = 'msg=' . base64_encode($message); + } + + return "\x1b]7501;" . implode(':', $pairs) . "\x1b\\"; + } + + private static function validateId(string $id): void + { + if (strlen($id) > self::MAX_ID_BYTES || !preg_match(self::ID_PATTERN, $id)) { + throw new InvalidArgumentException( + sprintf( + 'The terminal status id "%s" must be up to 8 "/"-separated segments of 1 to 32 characters ' + . 'among letters, digits, "_", ".", "+" and "-", and at most %d bytes.', + $id, + self::MAX_ID_BYTES, + ), + ); + } + } + + private static function normalizeText(?string $text): ?string + { + if ($text === null || !preg_match('//u', $text)) { + return null; + } + + // Bound work before sanitizing. Remove at most three bytes from a split UTF-8 character. + $text = substr($text, 0, self::MAX_MESSAGE_BYTES); + while ($text !== '' && !preg_match('//u', $text)) { + $text = substr($text, 0, -1); + } + $text = trim((string) preg_replace('/[\x00-\x1F\x7F\x{80}-\x{9F}\x{2028}\x{2029}]+/u', ' ', $text)); + + return $text !== '' ? $text : null; + } +} diff --git a/src/Cli/SignalLoop.php b/src/Cli/SignalLoop.php index e3bc9911..fbad0e26 100644 --- a/src/Cli/SignalLoop.php +++ b/src/Cli/SignalLoop.php @@ -79,6 +79,12 @@ public function canContinue(): bool return $this->dispatchSignals(); } + /** Whether this loop has received a termination signal, including during scope cleanup. */ + public function isInterrupted(): bool + { + return $this->exit; + } + protected function dispatchSignals(): bool { if ($this->previousHandlers === null) { diff --git a/src/Cli/TerminalStatusReporter.php b/src/Cli/TerminalStatusReporter.php index bc46ca0b..cc385250 100644 --- a/src/Cli/TerminalStatusReporter.php +++ b/src/Cli/TerminalStatusReporter.php @@ -4,271 +4,46 @@ namespace Yiisoft\Queue\Cli; -use InvalidArgumentException; +use Exception; +use Symfony\Component\Console\Output\ConsoleOutputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\StreamOutput; -use function base64_encode; -use function fflush; -use function fwrite; +use function bin2hex; use function getenv; -use function implode; use function in_array; use function is_resource; -use function is_string; -use function preg_match; -use function preg_replace; -use function sprintf; +use function random_bytes; use function stream_isatty; -use function strlen; use function strtolower; -use function substr; use function trim; -/** - * Reports the current program status to the terminal using the Program Status Protocol (OSC 7501). - * - * By default, a report is written only when the console output is decorated, not quiet, and backed by an - * interactive TTY, so redirects, log files, cron runs and quiet invocations stay clean. Set the environment - * variable `YII_TERMINAL_STATUS` to `off` (also `0`, `no`, `false`) to disable the reports explicitly; - * `YII_QUEUE_STATUS` is accepted as a compatibility alias. - * - * When forced enabled (or backed by a non-stream output), the reporter is enabled but no report is written, - * because there is no stream to write to. - * - * @see https://www.superlogical.com/rex/docs/build/program-status - */ +/** @internal Selects a positively verified terminal output for queue status reports. */ final class TerminalStatusReporter { - private const ENV_VAR = 'YII_TERMINAL_STATUS'; - private const ENV_VAR_COMPAT = 'YII_QUEUE_STATUS'; - private const MAX_MESSAGE_BYTES = 2048; - private const MAX_ID_BYTES = 128; - private const ID_PATTERN = '/^[A-Za-z0-9_.+-]{1,32}(?:\/[A-Za-z0-9_.+-]{1,32}){0,7}$/D'; - private const APP_PATTERN = '/^[A-Za-z0-9_.+-]{1,32}$/D'; - private const STATES = ['idle', 'working', 'done', 'error', 'blocked']; - private const KINDS = ['permission', 'question', 'auth']; - private string $app; - /** @var resource|null */ - private $stream; - - /** @param resource|null $stream */ - private function __construct(private bool $enabled, ?string $app, $stream = null) + public static function forOutput(OutputInterface $output): TerminalStatusWriter { - $app ??= 'queue'; - - if (!preg_match(self::APP_PATTERN, $app)) { - throw new InvalidArgumentException( - sprintf( - 'The terminal status app "%s" must be 1 to 32 characters among letters, digits, "_", ".", "+" and "-".', - $app, - ), - ); + if ($output instanceof ConsoleOutputInterface) { + $output = $output->getErrorOutput(); } - $this->app = $app; - $this->stream = $this->enabled && is_resource($stream) ? $stream : null; - } - /** - * Creates a reporter for the given console output. - * - * By default, the report is enabled only when the output is backed by an interactive TTY stream, is decorated - * and not quiet, and neither the `YII_TERMINAL_STATUS` nor the legacy `YII_QUEUE_STATUS` environment variable - * opts out. - * - * @param string|null $app A stable identifier reported to the terminal, 1 to 32 characters among letters, - * digits, "_", "." and "-"; defaults to `queue`. - * @param bool|null $enabled When non-null, forces the report on or off, bypassing TTY detection and the - * environment opt-out (intended for tests or forced terminals). - */ - public static function forOutput(OutputInterface $output, ?string $app = null, ?bool $enabled = null): self - { $stream = $output instanceof StreamOutput ? $output->getStream() : null; - - $enabled ??= !self::isOptedOut() + $setting = getenv('YII_TERMINAL_STATUS'); + $enabled = !in_array(strtolower(trim($setting === false ? '' : $setting)), ['off', '0', 'no', 'false'], true) && $output->isDecorated() && !$output->isQuiet() - && $stream !== null + && is_resource($stream) && stream_isatty($stream); - return new self($enabled, $app, $stream); - } - - /** - * Reports a program status update. - * - * @param string $state One of `idle`, `working`, `done`, `error`, `blocked`. - * @param string|null $message A single human-readable line; control characters are replaced by spaces and long - * text is cut. - * @param string|null $id The task the report is about; `null` reports the program itself. A "/" in an id makes - * the report a child of the parent task. - * @param int|null $progress A percentage for a `working` or `blocked` report; `null` when indeterminate. - * @param string|null $kind What a `blocked` report waits for: `permission`, `question` or `auth`. - * - * @throws InvalidArgumentException If the state, id, kind or progress is invalid. - */ - public function emit(string $state, ?string $message = null, ?string $id = null, ?int $progress = null, ?string $kind = null): void - { - if (!$this->enabled) { - return; - } - - if (!in_array($state, self::STATES, true)) { - throw new InvalidArgumentException( - sprintf( - 'The terminal status state "%s" must be one of: %s.', - $state, - implode(', ', self::STATES), - ), - ); - } - - if ($kind !== null) { - if ($state !== 'blocked') { - throw new InvalidArgumentException( - sprintf( - 'A terminal status kind is only supported for the "blocked" state, "%s" given.', - $state, - ), - ); + $id = 'queue/disabled'; + if ($enabled) { + try { + $id = 'queue/' . bin2hex(random_bytes(8)); + } catch (Exception) { + $enabled = false; } - - if (!in_array($kind, self::KINDS, true)) { - throw new InvalidArgumentException( - sprintf( - 'The terminal status kind "%s" must be one of: %s.', - $kind, - implode(', ', self::KINDS), - ), - ); - } - } - - if ($progress !== null) { - if ($state !== 'working' && $state !== 'blocked') { - throw new InvalidArgumentException( - sprintf( - 'A terminal status progress is only supported for the "working" and "blocked" states, "%s" given.', - $state, - ), - ); - } - - if ($progress < 0 || $progress > 100) { - throw new InvalidArgumentException( - sprintf('The terminal status progress must be between 0 and 100, %d given.', $progress), - ); - } - } - - if ($id !== null) { - self::validateId($id); - } - - $pairs = ['state=' . $state]; - if ($id !== null) { - $pairs[] = 'id=' . $id; - } - if ($kind !== null) { - $pairs[] = 'kind=' . $kind; - } - if ($progress !== null) { - $pairs[] = 'progress=' . $progress; - } - $pairs[] = 'app=' . $this->app; - - $message = self::normalizeText($message); - if ($message !== null) { - $pairs[] = 'msg=' . base64_encode($message); - } - - $this->write("\x1b]7501;" . implode(':', $pairs) . "\x1b\\"); - } - - /** - * Removes the record of a task and of the records beneath it, or all records when no id is given. - * - * @param string|null $id The task record to remove. - * - * @throws InvalidArgumentException If the id is invalid. - */ - public function clear(?string $id = null): void - { - if (!$this->enabled) { - return; - } - - if ($id !== null) { - self::validateId($id); - } - - $this->write($id === null ? "\x1b]7501;state=clear\x1b\\" : "\x1b]7501;state=clear:id={$id}\x1b\\"); - } - - public function isEnabled(): bool - { - return $this->enabled; - } - - private static function isOptedOut(): bool - { - return self::hasOptOutValue(getenv(self::ENV_VAR)) || self::hasOptOutValue(getenv(self::ENV_VAR_COMPAT)); - } - - private static function hasOptOutValue(string|false $value): bool - { - return is_string($value) && in_array(strtolower(trim($value)), ['off', '0', 'no', 'false'], true); - } - - private static function validateId(string $id): void - { - if (strlen($id) > self::MAX_ID_BYTES || !preg_match(self::ID_PATTERN, $id)) { - throw new InvalidArgumentException( - sprintf( - 'The terminal status id "%s" must be up to 8 "/"-separated segments of 1 to 32 characters ' - . 'among letters, digits, "_", ".", "+" and "-", and at most %d bytes.', - $id, - self::MAX_ID_BYTES, - ), - ); - } - } - - /** - * Terminals discard a whole report whose text holds a control character, contains an invalid UTF-8 sequence, - * or exceeds the size limit, so the text is made safe instead. - * - * Unlike the canonical encoder, this replacement does not require `ext-mbstring` or ANSI stripping, so it - * replaces unpaired UTF-16 surrogate sequences (all of U+D800–U+DFFF) with spaces and then strips the - * invalid trailing bytes the `//u` check still detects. - */ - private static function normalizeText(?string $text): ?string - { - if ($text === null) { - return null; - } - - $text = trim((string) preg_replace('/(?:[\x00-\x1F\x7F]|\xC2[\x80-\x9F]|\xED[\xA0-\xBF][\x80-\xBF])+/', ' ', $text)); - - if (strlen($text) > self::MAX_MESSAGE_BYTES) { - $text = substr($text, 0, self::MAX_MESSAGE_BYTES); - } - - while (!preg_match('//u', $text)) { - $text = substr($text, 0, -1); - } - $text = rtrim($text); - - return $text !== '' ? $text : null; - } - - private function write(string $sequence): void - { - if ($this->stream === null) { - return; } - fwrite($this->stream, $sequence); - fflush($this->stream); + return new TerminalStatusWriter($stream, $enabled, $id); } } diff --git a/src/Cli/TerminalStatusWriter.php b/src/Cli/TerminalStatusWriter.php new file mode 100644 index 00000000..167a4ba3 --- /dev/null +++ b/src/Cli/TerminalStatusWriter.php @@ -0,0 +1,76 @@ +enabled = $enabled && is_resource($stream); + } + + public function emit( + string $state, + ?string $message = null, + ?string $id = null, + ?int $progress = null, + ?string $kind = null, + ): void { + if (!$this->isEnabled()) { + return; + } + + $this->write(Osc7501Encoder::encode( + $state, + $id === null ? $this->id : $this->id . '/' . $id, + $this->app, + $message, + $progress, + $kind, + )); + } + + /** Clears only this invocation's subtree, or a child beneath it. Never clears the terminal root. */ + public function clear(?string $id = null): void + { + $this->emit('clear', id: $id); + } + + public function isEnabled(): bool + { + return $this->enabled && is_resource($this->stream); + } + + private function write(string $sequence): void + { + $stream = $this->stream; + if (!is_resource($stream)) { + return; + } + + try { + // Terminal status is optional. A closed or failed sink must not change the work's outcome. + if (@fwrite($stream, $sequence) !== strlen($sequence) || !@fflush($stream)) { + $this->enabled = false; + } + } catch (Throwable) { + $this->enabled = false; + } + } +} diff --git a/src/Command/ConsumeCommand.php b/src/Command/ConsumeCommand.php index d17ac455..c00e47ff 100644 --- a/src/Command/ConsumeCommand.php +++ b/src/Command/ConsumeCommand.php @@ -14,21 +14,15 @@ use Yiisoft\Queue\Cli\LoopInterface; use Yiisoft\Queue\Cli\ScopedLoopInterface; use Yiisoft\Queue\Cli\TerminalStatusReporter; +use Yiisoft\Queue\Cli\TerminalStatusWriter; +use Yiisoft\Queue\Cli\SignalLoop; use Yiisoft\Queue\DefaultQueue; use Yiisoft\Queue\Provider\QueueConsumerProviderInterface; -use function array_unique; use function count; -use function crc32; -use function intdiv; -use function preg_replace; +use function array_unique; +use function array_values; use function sprintf; -use function str_pad; -use function substr; -use function trim; -use function strlen; - -use const STR_PAD_LEFT; #[AsCommand('queue:consume', 'Consumes queued messages. Listens continuously unless --once is passed.')] final class ConsumeCommand extends Command @@ -36,7 +30,7 @@ final class ConsumeCommand extends Command public function __construct( private readonly QueueConsumerProviderInterface $queueProvider, private readonly LoopInterface $loop, - private readonly ?TerminalStatusReporter $statusReporter = null, + private readonly ?TerminalStatusWriter $statusReporter = null, ) { parent::__construct(); } @@ -101,215 +95,138 @@ protected function execute(InputInterface $input, OutputInterface $output): int return Command::INVALID; } - $statusReporter = $this->statusReporter ?? TerminalStatusReporter::forOutput($output); - - if (!$once && !$all) { - if (count($queueNames) > 1) { - $output->writeln('Use --all or --once to consume multiple queues.'); + if (!$once && !$all && count($queueNames) > 1) { + $output->writeln('Use --all or --once to consume multiple queues.'); - return Command::INVALID; - } - - $queueName = $queueNames[0] ?? DefaultQueue::NAME; - - try { - $consumer = $this->queueProvider->getConsumer($queueName); - } catch (Throwable $exception) { - $statusReporter->emit('error', sprintf('Consume on queue "%s" failed', $queueName)); + return Command::INVALID; + } - throw $exception; - } + $statusReporter = $this->statusReporter ?? TerminalStatusReporter::forOutput($output); + $activeId = null; + $statusReporter->emit('working', 'Preparing queue consumers'); - if ($consumer->isSynchronous()) { - $output->writeln('Synchronous mode: no adapter is configured, messages are processed on push.'); - $statusReporter->emit( - 'done', - 'Synchronous mode: messages are processed on push', - self::statusId($queueName), - ); + try { + if (!$once && !$all) { + $queueName = $queueNames[0] ?? DefaultQueue::NAME; + $activeId = 'queue-1'; + $statusReporter->emit('working', sprintf('Consuming queue "%s"', $queueName), $activeId); + $this->queueProvider->getConsumer($queueName)->listen(); + $statusReporter->clear(); + $statusReporter->emit('idle', 'Queue consumer returned'); return Command::SUCCESS; } - $statusId = self::statusId($queueName); - $statusReporter->emit('working', sprintf('Listening on queue "%s"', $queueName), $statusId); - - try { - $consumer->listen(); - } catch (Throwable $exception) { - if ($statusId !== null) { - $statusReporter->emit('error', sprintf('Queue "%s" failed', $queueName), $statusId); - } - - $statusReporter->emit('error', sprintf('Consume on queue "%s" failed', $queueName)); - - throw $exception; + if ($queueNames === []) { + $queueNames = $this->queueProvider->getConsumerQueueNames(); } + $queueNames = array_values(array_unique($queueNames)); + $statusReporter->emit('working', self::rootMessage($queueNames, $once)); - $statusReporter->emit('done', sprintf('Stopped listening on queue "%s"', $queueName), $statusId); - - return Command::SUCCESS; - } - - if ($queueNames === []) { - $queueNames = $this->queueProvider->getConsumerQueueNames(); - } - - $statusReporter->emit('working', self::rootMessage($queueNames, $once)); - - $consumers = []; - try { + // Use list positions for record ids; queue names can contain arbitrary characters or numeric strings. + $consumers = []; foreach ($queueNames as $queueName) { - $consumers[$queueName] = $this->queueProvider->getConsumer($queueName); + $consumers[] = $this->queueProvider->getConsumer($queueName); } - } catch (Throwable $exception) { - $statusReporter->emit('error', 'Resolving consumers failed'); - - throw $exception; - } - if ($consumers === []) { - $output->writeln('No consumers are configured.'); - $statusReporter->emit('done', 'No consumers are configured.'); - - return Command::SUCCESS; - } - - $limit = (int) $limit; - $pauseSeconds = (int) ($pauseSeconds ?? 1); - if ($pauseSeconds < 0) { - $pauseSeconds = 1; - } + if ($consumers === []) { + $output->writeln('No consumers are configured.'); + $statusReporter->emit('done', 'No consumers are configured.'); - $processed = 0; - $activeName = null; - $activeId = null; - $exception = null; + return Command::SUCCESS; + } - try { - if ($this->loop instanceof ScopedLoopInterface) { - $this->loop->start(); + $limit = (int) $limit; + $pauseSeconds = (int) ($pauseSeconds ?? 1); + if ($pauseSeconds < 0) { + $pauseSeconds = 1; } - while ($once || $this->loop->canContinue()) { - $hasMessages = false; - foreach ($queueNames as $queueName) { - if ($once) { - $output->write("Processing queue $queueName... "); + $processed = 0; + $failure = null; + try { + if ($this->loop instanceof ScopedLoopInterface) { + $this->loop->start(); + } + while ($once || $this->loop->canContinue()) { + $hasMessages = false; + foreach ($consumers as $index => $consumer) { + $queueName = $queueNames[$index]; + if ($once) { + $output->write("Processing queue $queueName... "); + } + + $activeId = 'queue-' . ($index + 1); + $statusReporter->emit('working', sprintf('Processing queue "%s"', $queueName), $activeId); + $count = $consumer->run($limit); + $hasMessages = $count > 0 || $hasMessages; + $processed += $count; + if ($this->loop instanceof SignalLoop && $this->loop->isInterrupted()) { + break 2; + } + + $statusReporter->emit( + $once ? 'done' : 'working', + $once + ? sprintf('Queue "%s": %d messages processed', $queueName, $count) + : sprintf('Waiting for messages on queue "%s"', $queueName), + $activeId, + ); + $activeId = null; + + if ($once) { + $output->writeln("Messages processed: $count."); + } } - - $activeName = $queueName; - $activeId = self::statusId($queueName); - $statusReporter->emit('working', sprintf('Processing queue "%s"', $queueName), $activeId); - - $count = $consumers[$queueName]->run($limit); - $hasMessages = $count > 0 || $hasMessages; - $processed += $count; - - $statusReporter->emit('done', sprintf('Queue "%s": %d messages processed', $queueName, $count), $activeId); - if ($once) { - $output->writeln("Messages processed: $count."); + break; + } + if (!$hasMessages && $this->loop->canContinue()) { + /** @psalm-var 0|positive-int $pauseSeconds */ + sleep($pauseSeconds); } } - - if ($once) { - break; - } - - if (!$hasMessages && $this->loop->canContinue()) { - if ($activeName !== null && $activeId !== null) { - $statusReporter->emit('idle', sprintf('Queue "%s" is idle', $activeName), $activeId); + } catch (Throwable $exception) { + $failure = $exception; + throw $exception; + } finally { + if ($this->loop instanceof ScopedLoopInterface) { + try { + $this->loop->finish(); + } catch (Throwable $exception) { + // Preserve an original processing error if restoring the loop also fails. + if ($failure === null) { + throw $exception; + } } - - /** @psalm-var 0|positive-int $pauseSeconds */ - sleep($pauseSeconds); } } - } catch (Throwable $caught) { - $exception = $caught; - } - try { - if ($this->loop instanceof ScopedLoopInterface) { - $this->loop->finish(); + if (!$once || ($this->loop instanceof SignalLoop && $this->loop->isInterrupted())) { + $statusReporter->clear(); + $statusReporter->emit('idle', 'Queue consumption stopped'); + } else { + $statusReporter->emit('done', sprintf('%d messages processed', $processed)); } - } catch (Throwable $caught) { - $exception ??= $caught; - } - if ($exception !== null) { - if ($activeName !== null && $activeId !== null) { - $statusReporter->emit('error', sprintf('Queue "%s" failed', $activeName), $activeId); + return Command::SUCCESS; + } catch (Throwable $exception) { + if ($activeId !== null) { + $statusReporter->emit('error', 'Queue consumption failed', $activeId); } - $statusReporter->emit('error', 'Consume failed'); - throw $exception; } - - $statusReporter->emit('done', $once - ? sprintf('%d messages processed', $processed) - : 'Stopped listening'); - - return Command::SUCCESS; } - /** - * @param list $queueNames - */ + /** @param list $queueNames */ private static function rootMessage(array $queueNames, bool $once): string { - $count = count(array_unique($queueNames)); - if ($count === 0) { - $description = 'all configured queues'; - } elseif ($count === 1) { - $description = sprintf('queue "%s"', $queueNames[0]); - } else { - $description = sprintf('%d queues', $count); - } + $count = count($queueNames); + $description = $count === 1 ? sprintf('queue "%s"', $queueNames[0]) : sprintf('%d queues', $count); return $once ? sprintf('Consuming %s in one pass', $description) - : sprintf('Listening on %s', $description); - } - - /** - * A task id for the queue in terminal status reports. - * - * Characters outside the protocol id alphabet, including "/", are replaced with "-", so the result always - * holds a single segment. When sanitizing or truncation changes the name, a short digest of the original name - * is appended so that distinct queues keep distinct records. Returns `null` when the queue name cannot be - * represented at all, in which case the report falls back to the program-level record. - */ - private static function statusId(string $queueName): ?string - { - $segment = trim((string) preg_replace('/[^A-Za-z0-9_.+-]+/', '-', $queueName), '-'); - - if ($segment === '') { - return null; - } - - if ($segment !== $queueName || strlen($segment) > 32) { - $segment = substr($segment, 0, 23) . '-' . self::idSuffix($queueName); - } - - return 'queue/' . $segment; - } - - /** - * A 7-character base36 digest appended to a sanitized or truncated queue name segment. - */ - private static function idSuffix(string $queueName): string - { - $alphabet = '0123456789abcdefghijklmnopqrstuvwxyz'; - $value = crc32($queueName); - $digest = ''; - do { - $digest = $alphabet[$value % 36] . $digest; - $value = intdiv($value, 36); - } while ($value > 0); - - return str_pad($digest, 7, '0', STR_PAD_LEFT); + : sprintf('Polling %s', $description); } } diff --git a/src/Debug/QueueConsumerDecorator.php b/src/Debug/QueueConsumerDecorator.php index 293d7848..03670b45 100644 --- a/src/Debug/QueueConsumerDecorator.php +++ b/src/Debug/QueueConsumerDecorator.php @@ -19,9 +19,4 @@ public function listen(): void { $this->queue->listen(); } - - public function isSynchronous(): bool - { - return $this->queue->isSynchronous(); - } } diff --git a/src/Provider/PredefinedQueueProvider.php b/src/Provider/PredefinedQueueProvider.php index 037ce9aa..d225a011 100644 --- a/src/Provider/PredefinedQueueProvider.php +++ b/src/Provider/PredefinedQueueProvider.php @@ -21,22 +21,18 @@ /** Provides already-created producer and consumer instances from strict role maps. */ final class PredefinedQueueProvider implements QueueProducerProviderInterface, QueueConsumerProviderInterface { - /** @var array> */ + /** @var array> */ private array $queues = []; /** @var list */ private array $producerQueueNames = []; /** @var list */ private array $consumerQueueNames = []; - /** @param array $queues */ + /** @param array $queues */ public function __construct(array $queues) { foreach ($queues as $queueName => $roles) { - /** - * PHP converts numeric string array keys to int, so the key is not guaranteed to be a string. - * - * @psalm-suppress RedundantCastGivenDocblockType - */ + // PHP stores numeric string keys as integers; the advertised names must remain strings. $queueName = (string) $queueName; if (!is_array($roles) || $roles === []) { throw new InvalidQueueConfigException(sprintf('Queue "%s" must be a non-empty role map containing ready "producer" and/or "consumer" instances.', $queueName)); diff --git a/src/Provider/QueueFactoryProvider.php b/src/Provider/QueueFactoryProvider.php index 2aa914a2..55d4149e 100644 --- a/src/Provider/QueueFactoryProvider.php +++ b/src/Provider/QueueFactoryProvider.php @@ -24,30 +24,26 @@ /** Lazily creates producer and consumer roles from strict nested role maps. */ final class QueueFactoryProvider implements QueueProducerProviderInterface, QueueConsumerProviderInterface { - /** @var array> */ + /** @var array> */ private array $definitions; - /** @var array> */ + /** @var array> */ private array $resolved = []; /** @var list */ private array $producerQueueNames = []; /** @var list */ private array $consumerQueueNames = []; - /** @param array $definitions */ + /** @param array $definitions */ public function __construct( array $definitions, private readonly ?ContainerInterface $container = null, private readonly bool $validate = true, ) { - /** @var array> $validatedDefinitions */ + /** @var array> $validatedDefinitions */ $validatedDefinitions = $this->validateRoleMaps($definitions); $this->definitions = $validatedDefinitions; foreach ($this->definitions as $queueName => $roles) { - /** - * PHP converts numeric string array keys to int, so the key is not guaranteed to be a string. - * - * @psalm-suppress RedundantCastGivenDocblockType - */ + // PHP stores numeric string keys as integers; the advertised names must remain strings. $queueName = (string) $queueName; if (array_key_exists('producer', $roles)) { $this->producerQueueNames[] = $queueName; @@ -144,10 +140,10 @@ private function get(string|BackedEnum $queueName, string $role, string $expecte } } - /** @param array $definitions @return array> */ + /** @param array $definitions @return array> */ private function validateRoleMaps(array $definitions): array { - /** @var array> $result */ + /** @var array> $result */ $result = []; foreach ($definitions as $queueName => $roles) { if (!is_array($roles)) { diff --git a/src/QueueConsumer.php b/src/QueueConsumer.php index 6fa8bab1..36bc944d 100644 --- a/src/QueueConsumer.php +++ b/src/QueueConsumer.php @@ -67,11 +67,6 @@ public function listen(): void $this->logger->info('Finish listening to the queue.'); } - public function isSynchronous(): bool - { - return $this->adapter === null; - } - private function startLoop(): void { if ($this->loop instanceof ScopedLoopInterface) { diff --git a/src/QueueConsumerInterface.php b/src/QueueConsumerInterface.php index cb2d8d31..a0a72163 100644 --- a/src/QueueConsumerInterface.php +++ b/src/QueueConsumerInterface.php @@ -22,9 +22,4 @@ public function run(int $max = 0): int; * Listen to the queue and handle messages as they come. */ public function listen(): void; - - /** - * Whether the consumer is in synchronous mode, i.e. has no adapter and processes messages on push only. - */ - public function isSynchronous(): bool; } diff --git a/stubs/StubQueueConsumer.php b/stubs/StubQueueConsumer.php index 6adf52ad..164922fc 100644 --- a/stubs/StubQueueConsumer.php +++ b/stubs/StubQueueConsumer.php @@ -14,9 +14,4 @@ public function run(int $max = 0): int } public function listen(): void {} - - public function isSynchronous(): bool - { - return true; - } } diff --git a/tests/Unit/Cli/Osc7501EncoderTest.php b/tests/Unit/Cli/Osc7501EncoderTest.php new file mode 100644 index 00000000..266383b7 --- /dev/null +++ b/tests/Unit/Cli/Osc7501EncoderTest.php @@ -0,0 +1,86 @@ +expectException(InvalidArgumentException::class); + Osc7501Encoder::encode($state, $id, $app, progress: $progress, kind: $kind); + } + + public static function invalidFields(): array + { + return [ + ['unknown', 'queue/run', 'queue', null, null], + ['done', 'queue/run', 'queue', 20, null], + ['working', 'queue/run', 'queue', -1, null], + ['working', 'queue/run', 'queue', 101, null], + ['working', 'queue/run', 'queue', null, 'auth'], + ['blocked', 'queue/run', 'queue', null, 'unknown'], + ['working', '', 'queue', null, null], + ['working', 'a//b', 'queue', null, null], + ['working', 'a:b', 'queue', null, null], + ['working', str_repeat('a', 33), 'queue', null, null], + ['working', implode('/', array_fill(0, 9, 'a')), 'queue', null, null], + ['working', implode('/', array_fill(0, 5, str_repeat('a', 32))), 'queue', null, null], + ['working', 'queue/run', 'bad:app', null, null], + ]; + } + + public function testClearIsScopedToAnExplicitId(): void + { + self::assertSame("\x1b]7501;state=clear:id=queue/run\x1b\\", Osc7501Encoder::encode('clear', 'queue/run', 'queue')); + } +} diff --git a/tests/Unit/Cli/TerminalStatusReporterTest.php b/tests/Unit/Cli/TerminalStatusReporterTest.php index bb024fb2..0b99654a 100644 --- a/tests/Unit/Cli/TerminalStatusReporterTest.php +++ b/tests/Unit/Cli/TerminalStatusReporterTest.php @@ -4,560 +4,102 @@ namespace Yiisoft\Queue\Tests\Unit\Cli; -use InvalidArgumentException; use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Output\BufferedOutput; +use Symfony\Component\Console\Output\ConsoleOutput; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\StreamOutput; use Yiisoft\Queue\Cli\TerminalStatusReporter; -use function base64_encode; -use function fopen; -use function getenv; -use function putenv; -use function rewind; -use function stream_get_contents; - final class TerminalStatusReporterTest extends TestCase { - private bool $hadEnv = false; - private string $savedEnvValue = ''; + /** @var array */ + private array $environment = []; protected function setUp(): void { - parent::setUp(); - - $this->hadEnv = getenv('YII_TERMINAL_STATUS') !== false; - $this->savedEnvValue = (string) getenv('YII_TERMINAL_STATUS'); - putenv('YII_TERMINAL_STATUS'); - putenv('YII_QUEUE_STATUS'); + foreach (['YII_TERMINAL_STATUS'] as $name) { + $this->environment[$name] = getenv($name); + putenv($name); + } } protected function tearDown(): void { - if ($this->hadEnv) { - putenv('YII_TERMINAL_STATUS=' . $this->savedEnvValue); - } else { - putenv('YII_TERMINAL_STATUS'); + foreach ($this->environment as $name => $value) { + putenv($value === false ? $name : $name . '=' . $value); } - - putenv('YII_QUEUE_STATUS'); - - parent::tearDown(); - } - - public function testWorkingReport(): void - { - [, $reporter, $read] = $this->enabledOutput(); - - $reporter->emit('working', 'Processing'); - - self::assertSame( - "\x1b]7501;state=working:app=queue:msg=" . base64_encode('Processing') . "\x1b\\", - $read(), - ); - } - - public function testOtherStates(): void - { - [, $reporter, $read] = $this->enabledOutput(); - - $reporter->emit('idle', 'Waiting'); - $reporter->emit('done', 'Finished'); - $reporter->emit('error', 'Failed'); - - self::assertSame( - "\x1b]7501;state=idle:app=queue:msg=" . base64_encode('Waiting') . "\x1b\\" - . "\x1b]7501;state=done:app=queue:msg=" . base64_encode('Finished') . "\x1b\\" - . "\x1b]7501;state=error:app=queue:msg=" . base64_encode('Failed') . "\x1b\\", - $read(), - ); - } - - public function testReportWithIdAndProgress(): void - { - [, $reporter, $read] = $this->enabledOutput(); - - $reporter->emit('working', 'Processing queue a', 'queue/a', 50); - - self::assertSame( - "\x1b]7501;state=working:id=queue/a:progress=50:app=queue:msg=" . base64_encode('Processing queue a') . "\x1b\\", - $read(), - ); - } - - public function testBlockedReportWithKind(): void - { - [, $reporter, $read] = $this->enabledOutput(); - - $reporter->emit('blocked', 'Awaiting input', null, null, 'permission'); - - self::assertSame( - "\x1b]7501;state=blocked:kind=permission:app=queue:msg=" . base64_encode('Awaiting input') . "\x1b\\", - $read(), - ); - } - - public function testControlCharactersAreReplacedBySpaces(): void - { - [, $reporter, $read] = $this->enabledOutput(); - - $reporter->emit('working', "a\x01b\x1fc"); - - self::assertSame( - "\x1b]7501;state=working:app=queue:msg=" . base64_encode('a b c') . "\x1b\\", - $read(), - ); - } - - public function testC1ControlCharactersAreReplacedBySpaces(): void - { - [, $reporter, $read] = $this->enabledOutput(); - - $reporter->emit('working', "\xC2\x80x\xC2\x9F"); - - self::assertSame( - "\x1b]7501;state=working:app=queue:msg=" . base64_encode('x') . "\x1b\\", - $read(), - ); } - public function testControlCharacterRunsBecomeSingleSpace(): void - { - [, $reporter, $read] = $this->enabledOutput(); - - $reporter->emit('working', "a\x00\x00b"); - - self::assertSame( - "\x1b]7501;state=working:app=queue:msg=" . base64_encode('a b') . "\x1b\\", - $read(), - ); - } - - public function testUtf16SurrogateSequenceIsReplacedBySpace(): void - { - [, $reporter, $read] = $this->enabledOutput(); - - $reporter->emit('working', "a\xED\xA0\x80b"); - - self::assertSame( - "\x1b]7501;state=working:app=queue:msg=" . base64_encode('a b') . "\x1b\\", - $read(), - ); - } - - public function testLowUtf16SurrogateSequenceIsReplacedBySpace(): void - { - [, $reporter, $read] = $this->enabledOutput(); - - $reporter->emit('working', "a\xED\xB0\x80b"); - - self::assertSame( - "\x1b]7501;state=working:app=queue:msg=" . base64_encode('a b') . "\x1b\\", - $read(), - ); - } - - public function testInvalidUtf8TailIsStripped(): void - { - [, $reporter, $read] = $this->enabledOutput(); - - $reporter->emit('working', "ab\xFF"); - - self::assertSame( - "\x1b]7501;state=working:app=queue:msg=" . base64_encode('ab') . "\x1b\\", - $read(), - ); - } - - public function testMessageOfOnlyInvalidUtf8IsDropped(): void - { - [, $reporter, $read] = $this->enabledOutput(); - - $reporter->emit('working', "\xFF\xFF"); - - self::assertSame("\x1b]7501;state=working:app=queue\x1b\\", $read()); - } - - public function testEmptyMessageIsOmitted(): void - { - [, $reporter, $read] = $this->enabledOutput(); - - $reporter->emit('working', "\x00\x01"); - - self::assertSame("\x1b]7501;state=working:app=queue\x1b\\", $read()); - } - - public function testLongMessageIsCut(): void - { - [, $reporter, $read] = $this->enabledOutput(); - - $message = str_repeat('a', 2100); - $reporter->emit('working', $message); - - self::assertSame( - "\x1b]7501;state=working:app=queue:msg=" . base64_encode(substr($message, 0, 2048)) . "\x1b\\", - $read(), - ); - } - - public function testLongMessageIsCutOnACharacterBoundary(): void - { - [, $reporter, $read] = $this->enabledOutput(); - - $message = str_repeat('a', 2047) . '€'; - $reporter->emit('working', $message); - - self::assertSame( - "\x1b]7501;state=working:app=queue:msg=" . base64_encode(str_repeat('a', 2047)) . "\x1b\\", - $read(), - ); - } - - public function testMessageCutIsTrimmedAfterTheBoundary(): void - { - [, $reporter, $read] = $this->enabledOutput(); - - $reporter->emit('working', str_repeat('a', 2047) . ' c'); - - self::assertSame( - "\x1b]7501;state=working:app=queue:msg=" . base64_encode(str_repeat('a', 2047)) . "\x1b\\", - $read(), - ); - } - - public function testCustomApp(): void + public function testForcedDecorationAndEnvironmentOnDoNotEnableRedirectedOutput(): void { + putenv('YII_TERMINAL_STATUS=on'); $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, 'custom-app', true); - - $reporter->emit('working', 'Working'); - - self::assertSame( - "\x1b]7501;state=working:app=custom-app:msg=" . base64_encode('Working') . "\x1b\\", - $this->read($stream), - ); - } - - public function testInvalidState(): void - { - [, $reporter] = $this->enabledOutput(); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('must be one of: idle, working, done, error, blocked'); - - $reporter->emit('spinning'); - } - - public function testProgressIsOnlyForWorkingAndBlocked(): void - { - [, $reporter] = $this->enabledOutput(); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('only supported for the "working" and "blocked" states, "done" given'); - - $reporter->emit('done', 'Finished', null, 50); - } - - public function testProgressIsBounded(): void - { - [, $reporter] = $this->enabledOutput(); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('must be between 0 and 100, 101 given'); - - $reporter->emit('working', 'Working', null, 101); - } - - public function testNegativeProgressIsRejected(): void - { - [, $reporter] = $this->enabledOutput(); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('must be between 0 and 100, -1 given'); - - $reporter->emit('working', 'Working', null, -1); - } - - public function testProgressBoundariesAreAccepted(): void - { - [, $reporter, $read] = $this->enabledOutput(); - - $reporter->emit('working', null, null, 0); - $reporter->emit('working', null, null, 100); - - self::assertSame( - "\x1b]7501;state=working:progress=0:app=queue\x1b\\" - . "\x1b]7501;state=working:progress=100:app=queue\x1b\\", - $read(), - ); - } - - public function testKindIsOnlyForBlocked(): void - { - [, $reporter] = $this->enabledOutput(); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('only supported for the "blocked" state, "working" given'); - - $reporter->emit('working', 'Working', null, null, 'permission'); - } - - public function testInvalidKind(): void - { - [, $reporter] = $this->enabledOutput(); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('must be one of: permission, question, auth'); + $writer = TerminalStatusReporter::forOutput(new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true)); + $writer->emit('working', 'Processing'); - $reporter->emit('blocked', 'Waiting', null, null, 'wait'); + self::assertFalse($writer->isEnabled()); + rewind($stream); + self::assertSame('', stream_get_contents($stream)); } - public function testInvalidId(): void + public function testCustomBufferedOutputIsDisabled(): void { - [, $reporter] = $this->enabledOutput(); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage( - 'The terminal status id "bad id" must be up to 8 "/"-separated segments of 1 to 32 characters ' - . 'among letters, digits, "_", ".", "+" and "-", and at most 128 bytes.', - ); - - $reporter->emit('working', 'Working', 'bad id'); + self::assertFalse(TerminalStatusReporter::forOutput(new BufferedOutput(decorated: true))->isEnabled()); } - public function testLongIdIsRejected(): void + public function testActualTerminalStderrIsSelectedAndInvocationsHaveDifferentRecords(): void { - [, $reporter] = $this->enabledOutput(); - - $this->expectException(InvalidArgumentException::class); + $stream = $this->terminal(); + $output = new ConsoleOutput(); + $output->setErrorOutput(new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true)); + $first = TerminalStatusReporter::forOutput($output); + $second = TerminalStatusReporter::forOutput($output); - $reporter->emit('working', 'Working', str_repeat('a', 45) . '/' . str_repeat('b', 45)); + self::assertTrue($first->isEnabled()); + self::assertTrue($second->isEnabled()); + // The master PTY provides a real TTY; encoding and per-invocation isolation are also covered by writer tests. + self::assertNotEquals($first, $second); + fclose($stream); } - public function testManyIdSegmentsAreRejected(): void + public function testRedirectedStderrIsNotReplacedWithTerminalStdout(): void { - [, $reporter] = $this->enabledOutput(); - - $this->expectException(InvalidArgumentException::class); - - $reporter->emit( - 'working', - 'Working', - implode('/', array_fill(0, 9, str_repeat('a', 14))), - ); + $output = new ConsoleOutput(decorated: true); + $output->setErrorOutput(new StreamOutput(fopen('php://memory', 'w+'), OutputInterface::VERBOSITY_NORMAL, true)); + self::assertFalse(TerminalStatusReporter::forOutput($output)->isEnabled()); } - public function testIdAtTheLimitSizeIsAccepted(): void + public function testQuietAndUndecoratedTerminalsAreDisabled(): void { - [, $reporter, $read] = $this->enabledOutput(); - - $id = str_repeat('a', 32) . '/' . str_repeat('b', 32) . '/' . str_repeat('c', 32) . '/' . str_repeat('d', 29); - $reporter->emit('working', null, $id); - - self::assertSame("\x1b]7501;state=working:id={$id}:app=queue\x1b\\", $read()); + $stream = $this->terminal(); + self::assertFalse(TerminalStatusReporter::forOutput(new StreamOutput($stream, OutputInterface::VERBOSITY_QUIET, true))->isEnabled()); + self::assertFalse(TerminalStatusReporter::forOutput(new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, false))->isEnabled()); + fclose($stream); } - public function testInvalidApp(): void + public function testFamilyEnvironmentDisablesTerminalOutput(): void { - $stream = fopen('php://memory', 'w+'); + $stream = $this->terminal(); $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('must be 1 to 32 characters'); - - TerminalStatusReporter::forOutput($output, 'bad app', true); - } - - public function testClearWithoutId(): void - { - [, $reporter, $read] = $this->enabledOutput(); - - $reporter->clear(); - - self::assertSame("\x1b]7501;state=clear\x1b\\", $read()); - } - - public function testClearWithId(): void - { - [, $reporter, $read] = $this->enabledOutput(); - - $reporter->clear('queue/a'); - - self::assertSame("\x1b]7501;state=clear:id=queue/a\x1b\\", $read()); - } - - public function testClearWithInvalidId(): void - { - [, $reporter] = $this->enabledOutput(); - - $this->expectException(InvalidArgumentException::class); - - $reporter->clear('bad id'); - } - - public function testNotEnabledForPlainOutput(): void - { - $reporter = TerminalStatusReporter::forOutput($this->createMock(OutputInterface::class)); - - self::assertFalse($reporter->isEnabled()); - - $reporter->emit('working', 'Working'); - $reporter->clear(); - } - - public function testNotEnabledForRedirectedStream(): void - { - $stream = fopen('php://memory', 'w+'); - $reporter = TerminalStatusReporter::forOutput(new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true)); - - self::assertFalse($reporter->isEnabled()); - - $reporter->emit('working', 'Working'); - self::assertSame('', $this->read($stream)); - } - - public function testNotEnabledForUndecoratedOutput(): void - { - $stream = fopen('php://memory', 'w+'); - $reporter = TerminalStatusReporter::forOutput(new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, false)); - - self::assertFalse($reporter->isEnabled()); - - $reporter->emit('working', 'Working'); - self::assertSame('', $this->read($stream)); - } - - public function testNotEnabledForQuietOutput(): void - { - $stream = fopen('php://memory', 'w+'); - $reporter = TerminalStatusReporter::forOutput(new StreamOutput($stream, OutputInterface::VERBOSITY_QUIET, true)); - - self::assertFalse($reporter->isEnabled()); - - $reporter->emit('working', 'Working'); - self::assertSame('', $this->read($stream)); - } - - public function testNotEnabledForBufferedOutput(): void - { - $reporter = TerminalStatusReporter::forOutput(new BufferedOutput()); - - self::assertFalse($reporter->isEnabled()); - - $reporter->emit('working', 'Working'); - } - - /** - * @dataProvider provideOptOutValues - */ - public function testOptOutViaEnvironment(string $envVar, string $value): void - { - putenv($envVar . '=' . $value); - - $stream = fopen('php://memory', 'w+'); - $reporter = TerminalStatusReporter::forOutput(new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true)); - - self::assertFalse($reporter->isEnabled()); - - $reporter->emit('working', 'Working'); - self::assertSame('', $this->read($stream)); - } - - public static function provideOptOutValues(): array - { - $values = ['off', 'OFF', ' 0', ' no ', 'false', 'False', ' false ']; - - $cases = []; - foreach (['YII_TERMINAL_STATUS', 'YII_QUEUE_STATUS'] as $envVar) { - foreach ($values as $value) { - $cases[] = [$envVar, $value]; - } + foreach (['off', '0', 'no', ' FALSE '] as $value) { + putenv('YII_TERMINAL_STATUS=' . $value); + self::assertFalse(TerminalStatusReporter::forOutput($output)->isEnabled()); } - - return $cases; + fclose($stream); } - public function testEnvironmentAliasDoesNotOverrideAbsentFamilyVariable(): void + /** @return resource */ + private function terminal() { - putenv('YII_QUEUE_STATUS=off'); - - $stream = fopen('php://memory', 'w+'); - $reporter = TerminalStatusReporter::forOutput(new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true)); - - self::assertFalse($reporter->isEnabled()); - } - - public function testEnabledOverride(): void - { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - - self::assertTrue($reporter->isEnabled()); - - $reporter->emit('working', 'Working'); - self::assertNotSame('', $this->read($stream)); - } - - public function testDisabledOverrideWithStreamWritesNothing(): void - { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, false); - - self::assertFalse($reporter->isEnabled()); - - $reporter->emit('working', 'Working'); - $reporter->clear(); - - self::assertSame('', $this->read($stream)); - } - - public function testDisabledOverrideWithInvalidEmitArgumentsWritesNothing(): void - { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, false); - - self::assertFalse($reporter->isEnabled()); - - $reporter->emit('bogus', 'Working', str_repeat('a', 130), 101, 'wait'); - - self::assertSame('', $this->read($stream)); - } - - public function testDisabledOverrideWithInvalidClearIdWritesNothing(): void - { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, false); - - self::assertFalse($reporter->isEnabled()); - - $reporter->clear(str_repeat('a', 130)); - - self::assertSame('', $this->read($stream)); - } - - /** - * @return array{0: StreamOutput, 1: TerminalStatusReporter, 2: callable(): string} - */ - private function enabledOutput(): array - { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - - return [$output, $reporter, fn(): string => $this->read($stream)]; - } - - /** @param resource $stream */ - private function read($stream): string - { - rewind($stream); - - return (string) stream_get_contents($stream); + if (!file_exists('/dev/ptmx')) { + self::markTestSkipped('A Unix PTY is required for positive TTY checks.'); + } + $stream = fopen('/dev/ptmx', 'r+'); + if (!stream_isatty($stream)) { + fclose($stream); + self::markTestSkipped('The PTY is not exposed as a TTY.'); + } + return $stream; } } diff --git a/tests/Unit/Cli/TerminalStatusWriterTest.php b/tests/Unit/Cli/TerminalStatusWriterTest.php new file mode 100644 index 00000000..2e59889f --- /dev/null +++ b/tests/Unit/Cli/TerminalStatusWriterTest.php @@ -0,0 +1,58 @@ +emit('working', 'First', 'queue-1'); + $second->emit('working', 'Second', 'queue-1'); + $first->clear(); + rewind($stream); + $bytes = stream_get_contents($stream); + self::assertStringContainsString('id=queue/first/queue-1:', $bytes); + self::assertStringContainsString('id=queue/second/queue-1:', $bytes); + self::assertStringContainsString("state=clear:id=queue/first\x1b\\", $bytes); + self::assertStringNotContainsString("state=clear\x1b\\", $bytes); + self::assertTrue(is_resource($stream)); + } + + public function testClosedStreamDoesNotInterruptWork(): void + { + $stream = fopen('php://memory', 'w+'); + $writer = new TerminalStatusWriter($stream, true, 'queue/run'); + fclose($stream); + $writer->emit('working', 'Processing'); + self::assertFalse($writer->isEnabled()); + } + + public function testWriteFailureDisablesReporting(): void + { + $stream = fopen(__FILE__, 'r'); + $writer = new TerminalStatusWriter($stream, true, 'queue/run'); + $writer->emit('working', 'Processing'); + self::assertFalse($writer->isEnabled()); + fclose($stream); + } + + public function testDisabledWriterDoesNotWrite(): void + { + $stream = fopen('php://memory', 'w+'); + $writer = new TerminalStatusWriter($stream, false, 'queue/run'); + $writer->emit('working', 'Processing'); + $writer->clear(); + rewind($stream); + self::assertSame('', stream_get_contents($stream)); + } +} diff --git a/tests/Unit/Command/ConsumeCommandStatusTest.php b/tests/Unit/Command/ConsumeCommandStatusTest.php index a736d24d..99d94527 100644 --- a/tests/Unit/Command/ConsumeCommandStatusTest.php +++ b/tests/Unit/Command/ConsumeCommandStatusTest.php @@ -5,869 +5,274 @@ namespace Yiisoft\Queue\Tests\Unit\Command; use PHPUnit\Framework\TestCase; +use Psr\Log\NullLogger; use RuntimeException; use Symfony\Component\Console\Input\StringInput; -use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Output\BufferedOutput; use Symfony\Component\Console\Output\StreamOutput; use Yiisoft\Queue\Cli\LoopInterface; use Yiisoft\Queue\Cli\ScopedLoopInterface; -use Yiisoft\Queue\Cli\TerminalStatusReporter; +use Yiisoft\Queue\Cli\SignalLoop; +use Yiisoft\Queue\Cli\TerminalStatusWriter; use Yiisoft\Queue\Command\ConsumeCommand; -use Yiisoft\Queue\DefaultQueue; use Yiisoft\Queue\Provider\PredefinedQueueProvider; -use Yiisoft\Queue\Provider\QueueNotFoundException; +use Yiisoft\Queue\Provider\QueueConsumerProviderInterface; +use Yiisoft\Queue\Provider\QueueFactoryProvider; +use Yiisoft\Queue\QueueConsumer; use Yiisoft\Queue\QueueConsumerInterface; use Yiisoft\Queue\Stubs\StubLoop; +use Yiisoft\Queue\Worker\WorkerInterface; -use function base64_encode; +use function array_slice; +use function function_exists; +use function fclose; use function fopen; -use function hrtime; -use function implode; -use function rewind; -use function str_contains; -use function stream_get_contents; +use function getenv; +use function putenv; + +use const SIGINT; final class ConsumeCommandStatusTest extends TestCase { - public function testOnceSingleQueue(): void - { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider(['queuea' => ['consumer' => $this->consumer(3)]]), - new StubLoop(), - $reporter, - ); - - $command->run(new StringInput('--once queuea'), $output); - - $bytes = $this->read($stream); - self::assertSame( - [ - $this->sequence('working', 'Consuming queue "queuea" in one pass'), - $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), - $this->sequence('done', 'Queue "queuea": 3 messages processed', 'queue/queuea'), - $this->sequence('done', '3 messages processed'), - ], - $this->statusSequences($bytes), - ); - self::assertStringContainsString('Processing queue queuea... ', $bytes); - self::assertStringContainsString('Messages processed: 3.', $bytes); - } - - public function testOnceMultipleQueues(): void - { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider([ - 'mail' => ['consumer' => $this->consumer(2)], - 'news' => ['consumer' => $this->consumer(1)], - ]), - new StubLoop(), - $reporter, - ); - - $command->run(new StringInput('--once mail news'), $output); - - $bytes = (string) $this->read($stream); - self::assertStringContainsString($this->sequence('working', 'Consuming 2 queues in one pass'), $bytes); - self::assertStringContainsString($this->sequence('done', 'Queue "mail": 2 messages processed', 'queue/mail'), $bytes); - self::assertStringContainsString($this->sequence('done', 'Queue "news": 1 messages processed', 'queue/news'), $bytes); - self::assertStringContainsString($this->sequence('done', '3 messages processed'), $bytes); - } - - public function testAllModePasses(): void + public function testClosedOutputStreamDoesNotPreventListening(): void { - $loop = new class implements LoopInterface { - private int $checks = 0; - - public function canContinue(): bool - { - return $this->checks++ < 3; - } - }; - $consumer = $this->createMock(QueueConsumerInterface::class); - $consumer->expects($this->exactly(2))->method('run')->willReturnOnConsecutiveCalls(0, 1); - - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); + $consumer->expects($this->once())->method('listen'); $command = new ConsumeCommand( - new PredefinedQueueProvider(['queuea' => ['consumer' => $consumer]]), - $loop, - $reporter, - ); - - $start = hrtime(true); - $command->run(new StringInput('--all --pause=0 queuea'), $output); - $elapsed = (hrtime(true) - $start) / 1_000_000_000; - - self::assertLessThan(0.75, $elapsed, 'A zero pause must not sleep between passes.'); - self::assertSame( - [ - $this->sequence('working', 'Listening on queue "queuea"'), - $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), - $this->sequence('done', 'Queue "queuea": 0 messages processed', 'queue/queuea'), - $this->sequence('idle', 'Queue "queuea" is idle', 'queue/queuea'), - $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), - $this->sequence('done', 'Queue "queuea": 1 messages processed', 'queue/queuea'), - $this->sequence('done', 'Stopped listening'), - ], - $this->statusSequences($this->read($stream)), - ); - } - - public function testListenMode(): void - { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider(['queuea' => ['consumer' => $this->consumer(-1)]]), + new PredefinedQueueProvider(['mail' => ['consumer' => $consumer]]), new StubLoop(), - $reporter, ); - - $command->run(new StringInput('queuea'), $output); - - self::assertSame( - [ - $this->sequence('working', 'Listening on queue "queuea"', 'queue/queuea'), - $this->sequence('done', 'Stopped listening on queue "queuea"', 'queue/queuea'), - ], - $this->statusSequences($this->read($stream)), - ); - } - - public function testRunExceptionReportsErrorStatus(): void - { $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider(['queuea' => ['consumer' => $this->consumer(false)]]), - new StubLoop(), - $reporter, - ); + $output = new StreamOutput($stream, decorated: true); + fclose($stream); + $setting = getenv('YII_TERMINAL_STATUS'); + putenv('YII_TERMINAL_STATUS=on'); try { - $command->run(new StringInput('--once queuea'), $output); - self::fail('The command should rethrow the handler exception.'); - } catch (RuntimeException $exception) { - self::assertSame('boom', $exception->getMessage()); + self::assertSame(0, $command->run(new StringInput('mail'), $output)); + } finally { + putenv($setting === false ? 'YII_TERMINAL_STATUS' : 'YII_TERMINAL_STATUS=' . $setting); } - - self::assertSame( - [ - $this->sequence('working', 'Consuming queue "queuea" in one pass'), - $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), - $this->sequence('error', 'Queue "queuea" failed', 'queue/queuea'), - $this->sequence('error', 'Consume failed'), - ], - $this->statusSequences($this->read($stream)), - ); - } - - public function testListenExceptionReportsErrorStatus(): void - { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $consumer = $this->createMock(QueueConsumerInterface::class); - $consumer->method('listen')->willReturnCallback(static function (): never { - throw new RuntimeException('boom'); - }); - $command = new ConsumeCommand( - new PredefinedQueueProvider(['queuea' => ['consumer' => $consumer]]), - new StubLoop(), - $reporter, - ); - - try { - $command->run(new StringInput('queuea'), $output); - self::fail('The command should rethrow the handler exception.'); - } catch (RuntimeException $exception) { - self::assertSame('boom', $exception->getMessage()); - } - - self::assertSame( - [ - $this->sequence('working', 'Listening on queue "queuea"', 'queue/queuea'), - $this->sequence('error', 'Queue "queuea" failed', 'queue/queuea'), - $this->sequence('error', 'Consume on queue "queuea" failed'), - ], - $this->statusSequences($this->read($stream)), - ); - } - - public function testStatusIsSuppressedWithoutAInteractiveStream(): void - { - [$command, $output, $stream] = $this->build(['queuea' => ['consumer' => $this->consumer(3)]]); - - $command->run(new StringInput('--once queuea'), $output); - - $bytes = (string) $this->read($stream); - self::assertFalse(str_contains($bytes, "\x1b]7501")); - self::assertStringContainsString('Processing queue queuea... Messages processed: 3.', $bytes); - } - - public function testQueueNameWithoutValidIdCharsFallsBackToRootRecord(): void - { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider(["!!" => ['consumer' => $this->consumer(1)]]), - new StubLoop(), - $reporter, - ); - - $command->run(new StringInput('--once "!!"'), $output); - - $bytes = (string) $this->read($stream); - self::assertStringContainsString($this->sequence('working', 'Processing queue "!!"'), $bytes); - self::assertStringNotContainsString('id=', $bytes); } - public function testQueueNameWithInvalidCharsIsSanitizedInId(): void + public function testNumericQueueStillConsumesWhenReportingIsDisabled(): void { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider(['weird: name' => ['consumer' => $this->consumer(1)]]), - new StubLoop(), - $reporter, - ); - - $command->run(new StringInput('--once "weird: name"'), $output); - - self::assertStringContainsString( - $this->sequence('done', 'Queue "weird: name": 1 messages processed', 'queue/weird-name-1uyugt5'), - (string) $this->read($stream), - ); - } - - public function testLongQueueNameIsCutInId(): void - { - $queueName = str_repeat('a', 40); - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider([$queueName => ['consumer' => $this->consumer(2)]]), - new StubLoop(), - $reporter, - ); - - $command->run(new StringInput('--once ' . $queueName), $output); - - self::assertStringContainsString( - $this->sequence( - 'done', - 'Queue "' . $queueName . '": 2 messages processed', - 'queue/' . str_repeat('a', 23) . '-1jvayw5', - ), - (string) $this->read($stream), - ); - } - - public function testSixDigitDigestIsZeroPadded(): void - { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider(['aa/bb' => ['consumer' => $this->consumer(1)]]), - new StubLoop(), - $reporter, - ); - - $command->run(new StringInput('--once "aa/bb"'), $output); - - self::assertStringContainsString( - $this->sequence('done', 'Queue "aa/bb": 1 messages processed', 'queue/aa-bb-0ap1hqi'), - (string) $this->read($stream), - ); + $consumer = $this->consumer(1); + $consumer->expects($this->once())->method('run')->willReturn(1); + $output = new BufferedOutput(); + $command = new ConsumeCommand(new PredefinedQueueProvider(['123' => ['consumer' => $consumer]]), new StubLoop()); + self::assertSame(0, $command->run(new StringInput('--once 123'), $output)); + self::assertStringContainsString('Messages processed: 1.', $output->fetch()); } - public function testThirtyTwoCharQueueNameKeepsItsFullSegment(): void + public function testDistinctQueuesCannotCollideAndDuplicateNamesAreConsumedOnce(): void { - $queueName = str_repeat('a', 32); - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider([$queueName => ['consumer' => $this->consumer(1)]]), - new StubLoop(), - $reporter, - ); - - $command->run(new StringInput('--once ' . $queueName), $output); - - self::assertStringContainsString( - $this->sequence('done', 'Queue "' . $queueName . '": 1 messages processed', 'queue/' . $queueName), - (string) $this->read($stream), - ); - } - - public function testQueueNameWithSlashesIsFlattenedInId(): void - { - $queueName = 'a/b/c/d/e/f/g/h/i'; - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider([$queueName => ['consumer' => $this->consumer(1)]]), - new StubLoop(), - $reporter, - ); - - $command->run(new StringInput('--once "' . $queueName . '"'), $output); - - self::assertStringContainsString( - $this->sequence('done', 'Queue "' . $queueName . '": 1 messages processed', 'queue/a-b-c-d-e-f-g-h-i-1ju46bo'), - (string) $this->read($stream), - ); - } - - public function testNamesThatSanitizeToTheSameTextKeepDistinctIds(): void - { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider([ - 'mail-a' => ['consumer' => $this->consumer(1)], - 'mail:a' => ['consumer' => $this->consumer(2)], - ]), - new StubLoop(), - $reporter, - ); - - $command->run(new StringInput('--once "mail-a" "mail:a"'), $output); - - $bytes = (string) $this->read($stream); - self::assertStringContainsString($this->sequence('done', 'Queue "mail-a": 1 messages processed', 'queue/mail-a'), $bytes); - self::assertStringContainsString($this->sequence('done', 'Queue "mail:a": 2 messages processed', 'queue/mail-a-1fc5674'), $bytes); - } - - public function testNonAsciiQueueNameFallsBackToRootRecord(): void - { - $queueName = 'почта'; - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider([$queueName => ['consumer' => $this->consumer(1)]]), - new StubLoop(), - $reporter, - ); - - $command->run(new StringInput('--once "' . $queueName . '"'), $output); - - $bytes = (string) $this->read($stream); - self::assertStringContainsString($this->sequence('working', 'Processing queue "' . $queueName . '"'), $bytes); - self::assertStringNotContainsString('id=', $bytes); - } - - public function testOnceWithoutConfiguredQueuesReportsDoneStatus(): void - { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand(new PredefinedQueueProvider([]), new StubLoop(), $reporter); - - $command->run(new StringInput('--once'), $output); - - self::assertSame( - [ - $this->sequence('working', 'Consuming all configured queues in one pass'), - $this->sequence('done', 'No consumers are configured.'), - ], - $this->statusSequences($this->read($stream)), - ); - } - - public function testOnceUnknownQueueReportsErrorStatus(): void - { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand(new PredefinedQueueProvider([]), new StubLoop(), $reporter); - - try { - $command->run(new StringInput('--once ghost'), $output); - self::fail('The command should rethrow the queue exception.'); - } catch (QueueNotFoundException) { + $names = ['mail:a', 'mail-a', 'mail-a-1fc5674', 'почта', '!!', str_repeat('a', 40), str_repeat('a', 41), '123']; + $definitions = []; + foreach ($names as $name) { + $consumer = $this->createMock(QueueConsumerInterface::class); + $consumer->expects($this->once())->method('run')->willReturn(1); + $definitions[$name] = ['consumer' => $consumer]; + } + [$command, $stream] = $this->command(new PredefinedQueueProvider($definitions)); + $input = '--once ' . implode(' ', $names) . ' mail-a'; + $output = new BufferedOutput(); + self::assertSame(0, $command->run(new StringInput($input), $output)); + $records = $this->records($stream); + self::assertSame('Consuming 8 queues in one pass', $records[1]['msg']); + $completed = array_values(array_filter($records, static fn(array $record): bool => $record['state'] === 'done')); + self::assertCount(9, $completed); + self::assertCount(9, array_unique(array_column($completed, 'id'))); + self::assertSame('8 messages processed', $completed[8]['msg']); + foreach ($records as $record) { + self::assertStringStartsWith('queue/test', $record['id']); } - - self::assertSame( - [ - $this->sequence('working', 'Consuming queue "ghost" in one pass'), - $this->sequence('error', 'Resolving consumers failed'), - ], - $this->statusSequences($this->read($stream)), - ); } - public function testNumericQueueNameIsProcessed(): void + public function testConfiguredNumericNameIsDiscoveredFromPredefinedProvider(): void { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider(['123' => ['consumer' => $this->consumer(2)]]), - new StubLoop(), - $reporter, - ); - - $command->run(new StringInput('--once 123'), $output); + $consumer = $this->createMock(QueueConsumerInterface::class); + $consumer->expects($this->once())->method('run')->willReturn(2); + $provider = new PredefinedQueueProvider(['123' => ['consumer' => $consumer]]); + [$command, $stream] = $this->command($provider); - self::assertStringContainsString( - $this->sequence('done', 'Queue "123": 2 messages processed', 'queue/123'), - (string) $this->read($stream), - ); + self::assertSame(0, $command->run(new StringInput('--once'), new BufferedOutput())); + self::assertSame(['123'], $provider->getConsumerQueueNames()); + self::assertSame('2 messages processed', array_slice($this->records($stream), -1)[0]['msg']); } - public function testNumericQueueNamesFromProviderAreProcessed(): void + public function testConfiguredNumericNameIsDiscoveredFromFactoryProvider(): void { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider(['123' => ['consumer' => $this->consumer(1)]]), - new StubLoop(), - $reporter, - ); - - $command->run(new StringInput('--once'), $output); + $consumer = $this->createMock(QueueConsumerInterface::class); + $consumer->expects($this->once())->method('run')->willReturn(3); + $provider = new QueueFactoryProvider(['123' => ['consumer' => static fn(): QueueConsumerInterface => $consumer]]); + [$command, $stream] = $this->command($provider); - self::assertStringContainsString( - $this->sequence('done', 'Queue "123": 1 messages processed', 'queue/123'), - (string) $this->read($stream), - ); + self::assertSame(0, $command->run(new StringInput('--once'), new BufferedOutput())); + self::assertSame(['123'], $provider->getConsumerQueueNames()); + self::assertSame('3 messages processed', array_slice($this->records($stream), -1)[0]['msg']); } - public function testDuplicateQueueNamesAreCountedOnce(): void + public function testUserQueueNameHasSingleLineDecodedStatusMessages(): void { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider([ - 'mail' => ['consumer' => $this->consumer(1)], - 'news' => ['consumer' => $this->consumer(1)], - ]), - new StubLoop(), - $reporter, - ); - - $command->run(new StringInput('--once mail mail news'), $output); + $name = "mail\u{2028}news\u{2029}jobs"; + [$command, $stream] = $this->command(new PredefinedQueueProvider([$name => ['consumer' => $this->consumer(1)]])); - self::assertStringContainsString( - $this->sequence('working', 'Consuming 2 queues in one pass'), - (string) $this->read($stream), - ); + self::assertSame(0, $command->run(new StringInput('--once "' . $name . '"'), new BufferedOutput())); + $messages = array_column($this->records($stream), 'msg'); + self::assertContains('Processing queue "mail news jobs"', $messages); + self::assertContains('Queue "mail news jobs": 1 messages processed', $messages); } - public function testSynchronousModeReportsDoneWithoutListening(): void + public function testFailingChildReportsErrorBeforeItsInvocation(): void { $consumer = $this->createMock(QueueConsumerInterface::class); - $consumer->method('isSynchronous')->willReturn(true); - - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider(['queuea' => ['consumer' => $consumer]]), - new StubLoop(), - $reporter, - ); - - $command->run(new StringInput('queuea'), $output); - - self::assertSame( - [ - $this->sequence('done', 'Synchronous mode: messages are processed on push', 'queue/queuea'), - ], - $this->statusSequences($this->read($stream)), - ); - self::assertStringContainsString('Synchronous mode', (string) $this->read($stream)); - } - - public function testLoopStartFailureReportsErrorStatus(): void - { - $loop = new class implements ScopedLoopInterface { - public function start(): void - { - throw new RuntimeException('loop start failed'); - } - - public function canContinue(): bool - { - return true; - } - - public function finish(): void {} - }; - - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider(['queuea' => ['consumer' => $this->consumer(3)]]), - $loop, - $reporter, - ); - + $consumer->method('run')->willThrowException(new RuntimeException('handler')); + [$command, $stream] = $this->command(new PredefinedQueueProvider(['mail' => ['consumer' => $consumer]])); try { - $command->run(new StringInput('--once queuea'), $output); - self::fail('The command should rethrow the loop exception.'); + $command->run(new StringInput('--once mail'), new BufferedOutput()); + self::fail('Expected the handler failure.'); } catch (RuntimeException $exception) { - self::assertSame('loop start failed', $exception->getMessage()); + self::assertSame('handler', $exception->getMessage()); } - - self::assertSame( - [ - $this->sequence('working', 'Consuming queue "queuea" in one pass'), - $this->sequence('error', 'Consume failed'), - ], - $this->statusSequences($this->read($stream)), - ); + $records = $this->records($stream); + self::assertSame(['error', 'error'], array_column(array_slice($records, -2), 'state')); + self::assertSame(['queue/test/queue-1', 'queue/test'], array_column(array_slice($records, -2), 'id')); } - public function testLoopFinishFailureReportsErrorStatus(): void + public function testEnumerationFailureReportsInvocationError(): void { - $loop = new class implements ScopedLoopInterface { - public function start(): void {} - - public function canContinue(): bool - { - return true; - } - - public function finish(): void - { - throw new RuntimeException('loop finish failed'); - } - }; - - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider(['queuea' => ['consumer' => $this->consumer(3)]]), - $loop, - $reporter, - ); - + $provider = $this->createMock(QueueConsumerProviderInterface::class); + $provider->method('getConsumerQueueNames')->willThrowException(new RuntimeException('enumeration')); + [$command, $stream] = $this->command($provider); try { - $command->run(new StringInput('--once queuea'), $output); - self::fail('The command should rethrow the loop exception.'); + $command->run(new StringInput('--once'), new BufferedOutput()); + self::fail('Expected enumeration failure.'); } catch (RuntimeException $exception) { - self::assertSame('loop finish failed', $exception->getMessage()); + self::assertSame('enumeration', $exception->getMessage()); } - - self::assertSame( - [ - $this->sequence('working', 'Consuming queue "queuea" in one pass'), - $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), - $this->sequence('done', 'Queue "queuea": 3 messages processed', 'queue/queuea'), - $this->sequence('error', 'Queue "queuea" failed', 'queue/queuea'), - $this->sequence('error', 'Consume failed'), - ], - $this->statusSequences($this->read($stream)), - ); + self::assertSame(['working', 'error'], array_column($this->records($stream), 'state')); } - public function testAllModeWithoutPauseOptionSleepsOneSecond(): void + public function testLoopStartupFailureReportsError(): void { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider(['queuea' => ['consumer' => $this->consumer(0)]]), - $this->twoShotLoop(), - $reporter, - ); - - $start = hrtime(true); - $command->run(new StringInput('--all'), $output); - $elapsed = (hrtime(true) - $start) / 1_000_000_000; - - self::assertGreaterThan(0.9, $elapsed, 'The default pause is one second.'); - self::assertLessThan(1.8, $elapsed, 'The default pause is one second.'); - } - - public function testAllModeNegativePauseIsClampedToOneSecond(): void - { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider(['queuea' => ['consumer' => $this->consumer(0)]]), - $this->twoShotLoop(), - $reporter, - ); - - $start = hrtime(true); - $command->run(new StringInput('--all --pause=-5 queuea'), $output); - $elapsed = (hrtime(true) - $start) / 1_000_000_000; - - self::assertGreaterThan(0.9, $elapsed, 'A negative pause is clamped to one second.'); - self::assertLessThan(1.8, $elapsed, 'A negative pause is clamped to one second.'); - } - - public function testAllModeWithProcessedMessagesDoesNotEmitIdle(): void - { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider(['queuea' => ['consumer' => $this->consumer(1)]]), - $this->twoShotLoop(), - $reporter, - ); - - $command->run(new StringInput('--all --pause=0 queuea'), $output); - - self::assertSame( - [ - $this->sequence('working', 'Listening on queue "queuea"'), - $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), - $this->sequence('done', 'Queue "queuea": 1 messages processed', 'queue/queuea'), - $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), - $this->sequence('done', 'Queue "queuea": 1 messages processed', 'queue/queuea'), - $this->sequence('done', 'Stopped listening'), - ], - $this->statusSequences($this->read($stream)), - ); - } - - public function testUnrepresentableQueueNameIdleDoesNotEmitIdle(): void - { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider(['!!!' => ['consumer' => $this->consumer(0)]]), - $this->twoShotLoop(), - $reporter, - ); - - $command->run(new StringInput('--all --pause=0'), $output); - - self::assertSame( - [ - $this->sequence('working', 'Listening on queue "!!!"'), - $this->sequence('working', 'Processing queue "!!!"'), - $this->sequence('done', 'Queue "!!!": 0 messages processed'), - $this->sequence('done', 'Stopped listening'), - ], - $this->statusSequences($this->read($stream)), - ); - } - - public function testOnceFlagTakesPrecedenceOverAll(): void - { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider(['queuea' => ['consumer' => $this->consumer(3)]]), - new StubLoop(), - $reporter, - ); - - $command->run(new StringInput('--once --all queuea'), $output); - - self::assertSame( - [ - $this->sequence('working', 'Consuming queue "queuea" in one pass'), - $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), - $this->sequence('done', 'Queue "queuea": 3 messages processed', 'queue/queuea'), - $this->sequence('done', '3 messages processed'), - ], - $this->statusSequences($this->read($stream)), - ); - } - - public function testFirstExceptionIsRethrownWhenLoopFinishAlsoFails(): void - { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider(['queuea' => ['consumer' => $this->consumer(false)]]), - $this->twoShotLoop(true), - $reporter, - ); - + $loop = $this->createMock(ScopedLoopInterface::class); + $loop->method('start')->willThrowException(new RuntimeException('start')); + $loop->expects($this->once())->method('finish'); + [$command, $stream] = $this->command(new PredefinedQueueProvider(['mail' => ['consumer' => $this->consumer(1)]]), $loop); try { - $command->run(new StringInput('--once queuea'), $output); - self::fail('The command should rethrow the first exception.'); + $command->run(new StringInput('--once mail'), new BufferedOutput()); + self::fail('Expected startup failure.'); } catch (RuntimeException $exception) { - self::assertSame('boom', $exception->getMessage()); + self::assertSame('start', $exception->getMessage()); } - - self::assertSame( - [ - $this->sequence('working', 'Consuming queue "queuea" in one pass'), - $this->sequence('working', 'Processing queue "queuea"', 'queue/queuea'), - $this->sequence('error', 'Queue "queuea" failed', 'queue/queuea'), - $this->sequence('error', 'Consume failed'), - ], - $this->statusSequences($this->read($stream)), - ); + self::assertSame('error', array_slice($this->records($stream), -1)[0]['state']); } - public function testUnrepresentableQueueNameFailureFallsBackToProgramRecord(): void + public function testLoopCleanupFailurePreventsFinalSuccess(): void { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $reporter = TerminalStatusReporter::forOutput($output, null, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider(['!!!' => ['consumer' => $this->consumer(false)]]), - new StubLoop(), - $reporter, - ); - + $loop = $this->createMock(ScopedLoopInterface::class); + $loop->method('finish')->willThrowException(new RuntimeException('finish')); + [$command, $stream] = $this->command(new PredefinedQueueProvider(['mail' => ['consumer' => $this->consumer(1)]]), $loop); try { - $command->run(new StringInput('--once "!!!"'), $output); - self::fail('The command should rethrow the handler exception.'); + $command->run(new StringInput('--once mail'), new BufferedOutput()); + self::fail('Expected cleanup failure.'); } catch (RuntimeException $exception) { - self::assertSame('boom', $exception->getMessage()); + self::assertSame('finish', $exception->getMessage()); } - - self::assertSame( - [ - $this->sequence('working', 'Consuming queue "!!!" in one pass'), - $this->sequence('working', 'Processing queue "!!!"'), - $this->sequence('error', 'Consume failed'), - ], - $this->statusSequences($this->read($stream)), - ); + $records = $this->records($stream); + self::assertSame('error', array_slice($records, -1)[0]['state']); + $errors = array_values(array_filter($records, static fn(array $record): bool => $record['state'] === 'error')); + self::assertSame(['queue/test'], array_column($errors, 'id')); + self::assertNotContains('1 messages processed', array_column($records, 'msg')); } - public function testOptionDescriptionsAndHelpTexts(): void + public function testCleanupDoesNotReplaceTheOriginalFailure(): void { - $command = new ConsumeCommand(new PredefinedQueueProvider([]), new StubLoop()); - - self::assertSame( - 'Continuously poll queues. Without names, use all configured consumer queues. Recommended for development only.', - $command->getDefinition()->getOption('all')->getDescription(), - ); - self::assertSame( - 'Without queue names, listen to ' . DefaultQueue::NAME . '. ' - . '--once and --all instead use all configured consumer queues. ' - . '--once takes precedence over --all.', - $command->getHelp(), - ); + $loop = $this->createMock(ScopedLoopInterface::class); + $loop->method('finish')->willThrowException(new RuntimeException('cleanup')); + $consumer = $this->createMock(QueueConsumerInterface::class); + $consumer->method('run')->willThrowException(new RuntimeException('handler')); + [$command] = $this->command(new PredefinedQueueProvider(['mail' => ['consumer' => $consumer]]), $loop); + $this->expectExceptionMessage('handler'); + $command->run(new StringInput('--once mail'), new BufferedOutput()); } - /** - * A loop that allows one full pass: the first two `canContinue()` checks pass, the rest do not. - */ - private function twoShotLoop(bool $finishFails = false): ScopedLoopInterface + public function testEmptyPersistentPollWaitsAsWorkingAndStopsAsIdle(): void { - return new class ($finishFails) implements ScopedLoopInterface { - private int $checks = 0; - - public function __construct(private bool $finishFails) {} - - public function start(): void {} - - public function canContinue(): bool - { - return $this->checks++ < 2; - } - - public function finish(): void - { - if ($this->finishFails) { - throw new RuntimeException('loop finish failed'); - } - } - }; + $loop = $this->createMock(LoopInterface::class); + $loop->method('canContinue')->willReturnOnConsecutiveCalls(true, false, false); + [$command, $stream] = $this->command(new PredefinedQueueProvider(['mail' => ['consumer' => $this->consumer(0)]]), $loop); + $command->run(new StringInput('--all --pause=0 mail'), new BufferedOutput()); + $records = $this->records($stream); + self::assertNotContains('done', array_column($records, 'state')); + self::assertNotContains('blocked', array_column($records, 'state')); + self::assertSame('Waiting for messages on queue "mail"', $records[3]['msg']); + self::assertSame('working', $records[3]['state']); + self::assertSame(['clear', 'idle'], array_column(array_slice($records, -2), 'state')); } - private function consumer(int|false $count): QueueConsumerInterface + public function testSynchronousConsumerDoesNotClaimToListen(): void { - $consumer = $this->createMock(QueueConsumerInterface::class); - if ($count === false) { - $consumer->method('run')->willReturnCallback(static function (): never { - throw new RuntimeException('boom'); - }); - } else { - $consumer->method('run')->willReturn($count); - } - - return $consumer; + $consumer = new QueueConsumer($this->createMock(WorkerInterface::class), new StubLoop(), new NullLogger()); + [$command, $stream] = $this->command(new PredefinedQueueProvider(['mail' => ['consumer' => $consumer]])); + $command->run(new StringInput('mail'), new BufferedOutput()); + $records = $this->records($stream); + self::assertSame('Consuming queue "mail"', $records[1]['msg']); + self::assertSame('idle', array_slice($records, -1)[0]['state']); + self::assertStringNotContainsString('listening', implode(' ', array_column($records, 'msg'))); } - /** - * @param array> $definitions - * - * @return array{0: ConsumeCommand, 1: StreamOutput, 2: resource} - */ - private function build( - array $definitions, - ?TerminalStatusReporter $reporter = null, - ?LoopInterface $loop = null, - ): array { - $stream = fopen('php://memory', 'w+'); - $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true); - $command = new ConsumeCommand( - new PredefinedQueueProvider($definitions), - $loop ?? new StubLoop(), - $reporter, - ); - - return [$command, $output, $stream]; + public function testInterruptedFinitePassIsNotReportedAsCompleted(): void + { + if (!function_exists('pcntl_signal') || !function_exists('posix_kill')) { + self::markTestSkipped('Process signals are required.'); + } + $loop = new SignalLoop(); + $consumer = $this->createMock(QueueConsumerInterface::class); + $consumer->method('run')->willReturnCallback(static function (): int { + posix_kill(getmypid(), SIGINT); + pcntl_signal_dispatch(); + return 0; + }); + [$command, $stream] = $this->command(new PredefinedQueueProvider(['mail' => ['consumer' => $consumer]]), $loop); + $command->run(new StringInput('--once mail'), new BufferedOutput()); + $records = $this->records($stream); + self::assertNotContains('done', array_column($records, 'state')); + self::assertSame('idle', array_slice($records, -1)[0]['state']); } - /** @param resource $stream */ - private function read($stream): string + private function consumer(int $count): QueueConsumerInterface { - rewind($stream); - - return (string) stream_get_contents($stream); + $consumer = $this->createMock(QueueConsumerInterface::class); + $consumer->method('run')->willReturn($count); + return $consumer; } - private function sequence(string $state, string $message, ?string $id = null): string + /** @return array{ConsumeCommand, resource} */ + private function command(QueueConsumerProviderInterface $provider, ?LoopInterface $loop = null): array { - $pairs = ['state=' . $state]; - if ($id !== null) { - $pairs[] = 'id=' . $id; - } - - return "\x1b]7501;" . implode(':', array_merge($pairs, ['app=queue', 'msg=' . base64_encode($message)])) . "\x1b\\"; + $stream = fopen('php://memory', 'w+'); + return [new ConsumeCommand($provider, $loop ?? new StubLoop(), new TerminalStatusWriter($stream, true, 'queue/test')), $stream]; } /** - * Extracts the OSC 7501 sequences from the output bytes, in the order they were written. - * - * @return list + * @param resource $stream + * @return list> */ - private function statusSequences(string $bytes): array + private function records($stream): array { - $sequences = []; - $offset = 0; - while (($start = strpos($bytes, "\x1b]7501;", $offset)) !== false) { - $end = strpos($bytes, "\x1b\\", $start); - if ($end === false) { - self::fail('An OSC 7501 sequence is not terminated in the output.'); + rewind($stream); + preg_match_all('/\x1b\]7501;([^\x1b]*)\x1b\\\\/', stream_get_contents($stream), $matches); + $records = []; + foreach ($matches[1] as $payload) { + $record = []; + foreach (explode(':', $payload) as $pair) { + [$name, $value] = explode('=', $pair, 2); + $record[$name] = $name === 'msg' ? base64_decode($value) : $value; } - - $sequences[] = substr($bytes, $start, 2 + $end - $start); - $offset = $end + 2; + $records[] = $record; } - - return $sequences; + return $records; } }