diff --git a/docs/guide/en/console-commands.md b/docs/guide/en/console-commands.md
index a8383f5a..447192e0 100644
--- a/docs/guide/en/console-commands.md
+++ b/docs/guide/en/console-commands.md
@@ -57,3 +57,41 @@ 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)
+
+`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
new file mode 100644
index 00000000..cc385250
--- /dev/null
+++ b/src/Cli/TerminalStatusReporter.php
@@ -0,0 +1,49 @@
+getErrorOutput();
+ }
+
+ $stream = $output instanceof StreamOutput ? $output->getStream() : null;
+ $setting = getenv('YII_TERMINAL_STATUS');
+ $enabled = !in_array(strtolower(trim($setting === false ? '' : $setting)), ['off', '0', 'no', 'false'], true)
+ && $output->isDecorated()
+ && !$output->isQuiet()
+ && is_resource($stream)
+ && stream_isatty($stream);
+
+ $id = 'queue/disabled';
+ if ($enabled) {
+ try {
+ $id = 'queue/' . bin2hex(random_bytes(8));
+ } catch (Exception) {
+ $enabled = false;
+ }
+ }
+
+ 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 70e09913..c00e47ff 100644
--- a/src/Command/ConsumeCommand.php
+++ b/src/Command/ConsumeCommand.php
@@ -10,12 +10,19 @@
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;
+use Yiisoft\Queue\Cli\TerminalStatusWriter;
+use Yiisoft\Queue\Cli\SignalLoop;
use Yiisoft\Queue\DefaultQueue;
use Yiisoft\Queue\Provider\QueueConsumerProviderInterface;
use function count;
+use function array_unique;
+use function array_values;
+use function sprintf;
#[AsCommand('queue:consume', 'Consumes queued messages. Listens continuously unless --once is passed.')]
final class ConsumeCommand extends Command
@@ -23,6 +30,7 @@ final class ConsumeCommand extends Command
public function __construct(
private readonly QueueConsumerProviderInterface $queueProvider,
private readonly LoopInterface $loop,
+ private readonly ?TerminalStatusWriter $statusReporter = null,
) {
parent::__construct();
}
@@ -87,74 +95,138 @@ protected function execute(InputInterface $input, OutputInterface $output): int
return Command::INVALID;
}
- 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;
- }
-
- $this->queueProvider->getConsumer($queueNames[0] ?? DefaultQueue::NAME)->listen();
-
- return Command::SUCCESS;
- }
-
- if ($queueNames === []) {
- $queueNames = $this->queueProvider->getConsumerQueueNames();
+ return Command::INVALID;
}
- $consumers = [];
- foreach ($queueNames as $queueName) {
- $consumers[$queueName] = $this->queueProvider->getConsumer($queueName);
- }
+ $statusReporter = $this->statusReporter ?? TerminalStatusReporter::forOutput($output);
+ $activeId = null;
+ $statusReporter->emit('working', 'Preparing queue consumers');
- if ($consumers === []) {
- $output->writeln('No consumers are configured.');
+ 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;
+ }
- return Command::SUCCESS;
- }
+ if ($queueNames === []) {
+ $queueNames = $this->queueProvider->getConsumerQueueNames();
+ }
+ $queueNames = array_values(array_unique($queueNames));
+ $statusReporter->emit('working', self::rootMessage($queueNames, $once));
- $limit = (int) $limit;
- $pauseSeconds = (int) ($pauseSeconds ?? 1);
- if ($pauseSeconds < 0) {
- $pauseSeconds = 1;
- }
+ // Use list positions for record ids; queue names can contain arbitrary characters or numeric strings.
+ $consumers = [];
+ foreach ($queueNames as $queueName) {
+ $consumers[] = $this->queueProvider->getConsumer($queueName);
+ }
- if ($this->loop instanceof ScopedLoopInterface) {
- $this->loop->start();
- }
+ if ($consumers === []) {
+ $output->writeln('No consumers are configured.');
+ $statusReporter->emit('done', 'No consumers are configured.');
- try {
- while ($once || $this->loop->canContinue()) {
- $hasMessages = false;
- foreach ($consumers as $queueName => $consumer) {
- if ($once) {
- $output->write("Processing queue $queueName... ");
- }
+ return Command::SUCCESS;
+ }
- $count = $consumer->run($limit);
- $hasMessages = $count > 0 || $hasMessages;
+ $limit = (int) $limit;
+ $pauseSeconds = (int) ($pauseSeconds ?? 1);
+ if ($pauseSeconds < 0) {
+ $pauseSeconds = 1;
+ }
+ $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.");
+ }
+ }
if ($once) {
- $output->writeln("Messages processed: $count.");
+ break;
+ }
+ if (!$hasMessages && $this->loop->canContinue()) {
+ /** @psalm-var 0|positive-int $pauseSeconds */
+ sleep($pauseSeconds);
}
}
-
- if ($once) {
- break;
+ } 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;
+ }
+ }
}
+ }
- if (!$hasMessages && $this->loop->canContinue()) {
- /** @psalm-var 0|positive-int $pauseSeconds */
- sleep($pauseSeconds);
- }
+ 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));
}
- } finally {
- if ($this->loop instanceof ScopedLoopInterface) {
- $this->loop->finish();
+
+ return Command::SUCCESS;
+ } catch (Throwable $exception) {
+ if ($activeId !== null) {
+ $statusReporter->emit('error', 'Queue consumption failed', $activeId);
}
+ $statusReporter->emit('error', 'Consume failed');
+ throw $exception;
}
+ }
+
+ /** @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 Command::SUCCESS;
+ return $once
+ ? sprintf('Consuming %s in one pass', $description)
+ : sprintf('Polling %s', $description);
}
}
diff --git a/src/Provider/PredefinedQueueProvider.php b/src/Provider/PredefinedQueueProvider.php
index 7b3d6df2..d225a011 100644
--- a/src/Provider/PredefinedQueueProvider.php
+++ b/src/Provider/PredefinedQueueProvider.php
@@ -21,17 +21,19 @@
/** 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 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 5957815a..55d4149e 100644
--- a/src/Provider/QueueFactoryProvider.php
+++ b/src/Provider/QueueFactoryProvider.php
@@ -24,25 +24,27 @@
/** 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 stores numeric string keys as integers; the advertised names must remain strings.
+ $queueName = (string) $queueName;
if (array_key_exists('producer', $roles)) {
$this->producerQueueNames[] = $queueName;
}
@@ -138,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/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
new file mode 100644
index 00000000..0b99654a
--- /dev/null
+++ b/tests/Unit/Cli/TerminalStatusReporterTest.php
@@ -0,0 +1,105 @@
+ */
+ private array $environment = [];
+
+ protected function setUp(): void
+ {
+ foreach (['YII_TERMINAL_STATUS'] as $name) {
+ $this->environment[$name] = getenv($name);
+ putenv($name);
+ }
+ }
+
+ protected function tearDown(): void
+ {
+ foreach ($this->environment as $name => $value) {
+ putenv($value === false ? $name : $name . '=' . $value);
+ }
+ }
+
+ public function testForcedDecorationAndEnvironmentOnDoNotEnableRedirectedOutput(): void
+ {
+ putenv('YII_TERMINAL_STATUS=on');
+ $stream = fopen('php://memory', 'w+');
+ $writer = TerminalStatusReporter::forOutput(new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true));
+ $writer->emit('working', 'Processing');
+
+ self::assertFalse($writer->isEnabled());
+ rewind($stream);
+ self::assertSame('', stream_get_contents($stream));
+ }
+
+ public function testCustomBufferedOutputIsDisabled(): void
+ {
+ self::assertFalse(TerminalStatusReporter::forOutput(new BufferedOutput(decorated: true))->isEnabled());
+ }
+
+ public function testActualTerminalStderrIsSelectedAndInvocationsHaveDifferentRecords(): void
+ {
+ $stream = $this->terminal();
+ $output = new ConsoleOutput();
+ $output->setErrorOutput(new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true));
+ $first = TerminalStatusReporter::forOutput($output);
+ $second = TerminalStatusReporter::forOutput($output);
+
+ 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 testRedirectedStderrIsNotReplacedWithTerminalStdout(): void
+ {
+ $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 testQuietAndUndecoratedTerminalsAreDisabled(): void
+ {
+ $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 testFamilyEnvironmentDisablesTerminalOutput(): void
+ {
+ $stream = $this->terminal();
+ $output = new StreamOutput($stream, OutputInterface::VERBOSITY_NORMAL, true);
+ foreach (['off', '0', 'no', ' FALSE '] as $value) {
+ putenv('YII_TERMINAL_STATUS=' . $value);
+ self::assertFalse(TerminalStatusReporter::forOutput($output)->isEnabled());
+ }
+ fclose($stream);
+ }
+
+ /** @return resource */
+ private function terminal()
+ {
+ 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
new file mode 100644
index 00000000..99d94527
--- /dev/null
+++ b/tests/Unit/Command/ConsumeCommandStatusTest.php
@@ -0,0 +1,278 @@
+createMock(QueueConsumerInterface::class);
+ $consumer->expects($this->once())->method('listen');
+ $command = new ConsumeCommand(
+ new PredefinedQueueProvider(['mail' => ['consumer' => $consumer]]),
+ new StubLoop(),
+ );
+ $stream = fopen('php://memory', 'w+');
+ $output = new StreamOutput($stream, decorated: true);
+ fclose($stream);
+ $setting = getenv('YII_TERMINAL_STATUS');
+ putenv('YII_TERMINAL_STATUS=on');
+
+ try {
+ self::assertSame(0, $command->run(new StringInput('mail'), $output));
+ } finally {
+ putenv($setting === false ? 'YII_TERMINAL_STATUS' : 'YII_TERMINAL_STATUS=' . $setting);
+ }
+ }
+
+ public function testNumericQueueStillConsumesWhenReportingIsDisabled(): void
+ {
+ $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 testDistinctQueuesCannotCollideAndDuplicateNamesAreConsumedOnce(): void
+ {
+ $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']);
+ }
+ }
+
+ public function testConfiguredNumericNameIsDiscoveredFromPredefinedProvider(): void
+ {
+ $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::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 testConfiguredNumericNameIsDiscoveredFromFactoryProvider(): void
+ {
+ $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::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 testUserQueueNameHasSingleLineDecodedStatusMessages(): void
+ {
+ $name = "mail\u{2028}news\u{2029}jobs";
+ [$command, $stream] = $this->command(new PredefinedQueueProvider([$name => ['consumer' => $this->consumer(1)]]));
+
+ 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 testFailingChildReportsErrorBeforeItsInvocation(): void
+ {
+ $consumer = $this->createMock(QueueConsumerInterface::class);
+ $consumer->method('run')->willThrowException(new RuntimeException('handler'));
+ [$command, $stream] = $this->command(new PredefinedQueueProvider(['mail' => ['consumer' => $consumer]]));
+ try {
+ $command->run(new StringInput('--once mail'), new BufferedOutput());
+ self::fail('Expected the handler failure.');
+ } catch (RuntimeException $exception) {
+ self::assertSame('handler', $exception->getMessage());
+ }
+ $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 testEnumerationFailureReportsInvocationError(): void
+ {
+ $provider = $this->createMock(QueueConsumerProviderInterface::class);
+ $provider->method('getConsumerQueueNames')->willThrowException(new RuntimeException('enumeration'));
+ [$command, $stream] = $this->command($provider);
+ try {
+ $command->run(new StringInput('--once'), new BufferedOutput());
+ self::fail('Expected enumeration failure.');
+ } catch (RuntimeException $exception) {
+ self::assertSame('enumeration', $exception->getMessage());
+ }
+ self::assertSame(['working', 'error'], array_column($this->records($stream), 'state'));
+ }
+
+ public function testLoopStartupFailureReportsError(): void
+ {
+ $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 mail'), new BufferedOutput());
+ self::fail('Expected startup failure.');
+ } catch (RuntimeException $exception) {
+ self::assertSame('start', $exception->getMessage());
+ }
+ self::assertSame('error', array_slice($this->records($stream), -1)[0]['state']);
+ }
+
+ public function testLoopCleanupFailurePreventsFinalSuccess(): void
+ {
+ $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 mail'), new BufferedOutput());
+ self::fail('Expected cleanup failure.');
+ } catch (RuntimeException $exception) {
+ self::assertSame('finish', $exception->getMessage());
+ }
+ $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 testCleanupDoesNotReplaceTheOriginalFailure(): void
+ {
+ $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());
+ }
+
+ public function testEmptyPersistentPollWaitsAsWorkingAndStopsAsIdle(): void
+ {
+ $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'));
+ }
+
+ public function testSynchronousConsumerDoesNotClaimToListen(): void
+ {
+ $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')));
+ }
+
+ 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']);
+ }
+
+ private function consumer(int $count): QueueConsumerInterface
+ {
+ $consumer = $this->createMock(QueueConsumerInterface::class);
+ $consumer->method('run')->willReturn($count);
+ return $consumer;
+ }
+
+ /** @return array{ConsumeCommand, resource} */
+ private function command(QueueConsumerProviderInterface $provider, ?LoopInterface $loop = null): array
+ {
+ $stream = fopen('php://memory', 'w+');
+ return [new ConsumeCommand($provider, $loop ?? new StubLoop(), new TerminalStatusWriter($stream, true, 'queue/test')), $stream];
+ }
+
+ /**
+ * @param resource $stream
+ * @return list>
+ */
+ private function records($stream): array
+ {
+ 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;
+ }
+ $records[] = $record;
+ }
+ return $records;
+ }
+}