Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions docs/guide/en/console-commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
139 changes: 139 additions & 0 deletions src/Cli/Osc7501Encoder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Queue\Cli;

use InvalidArgumentException;

use function base64_encode;
use function implode;
use function in_array;
use function preg_match;
use function preg_replace;
use function sprintf;
use function strlen;
use function substr;
use function trim;

/** @internal Encodes OSC 7501 without depending on a console framework or output stream. */
final class Osc7501Encoder
{
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'];

public static function encode(
string $state,
string $id,
string $app,
?string $message = null,
?int $progress = null,
?string $kind = null,
): string {
self::validateId($id);
if (!preg_match(self::APP_PATTERN, $app)) {
throw new InvalidArgumentException('The terminal status app must be 1 to 32 ASCII identifier characters.');
}
if ($state === 'clear') {
return "\x1b]7501;state=clear:id={$id}\x1b\\";
}

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) {

Check warning on line 86 in src/Cli/Osc7501Encoder.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.5-ubuntu-latest

Escaped Mutant for Mutator "GreaterThan": @@ @@ ); } - if ($progress < 0 || $progress > 100) { + if ($progress < 0 || $progress >= 100) { throw new InvalidArgumentException( sprintf('The terminal status progress must be between 0 and 100, %d given.', $progress), );

Check warning on line 86 in src/Cli/Osc7501Encoder.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.5-ubuntu-latest

Escaped Mutant for Mutator "LessThan": @@ @@ ); } - if ($progress < 0 || $progress > 100) { + if ($progress <= 0 || $progress > 100) { throw new InvalidArgumentException( sprintf('The terminal status progress must be between 0 and 100, %d given.', $progress), );
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;
}
}
6 changes: 6 additions & 0 deletions src/Cli/SignalLoop.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
49 changes: 49 additions & 0 deletions src/Cli/TerminalStatusReporter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Queue\Cli;

use Exception;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\StreamOutput;

use function bin2hex;
use function getenv;
use function in_array;
use function is_resource;
use function random_bytes;
use function stream_isatty;
use function strtolower;
use function trim;

/** @internal Selects a positively verified terminal output for queue status reports. */
final class TerminalStatusReporter
{
public static function forOutput(OutputInterface $output): TerminalStatusWriter
{
if ($output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}

$stream = $output instanceof StreamOutput ? $output->getStream() : null;
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
$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);
}
}
76 changes: 76 additions & 0 deletions src/Cli/TerminalStatusWriter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Queue\Cli;

use Throwable;

use function fflush;
use function fwrite;
use function is_resource;
use function strlen;

/** @internal Writes reports within one invocation's record subtree. */
final class TerminalStatusWriter
{
/** @param resource|null $stream An explicitly selected output stream; it is never closed by this writer. */
public function __construct(
private $stream,
private bool $enabled,
private readonly string $id,
private readonly string $app = 'queue',
) {
Osc7501Encoder::encode('clear', $id, $app);
$this->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;
}
}
}
Loading
Loading