diff --git a/lib/Service/DecoderProcess.php b/lib/Service/DecoderProcess.php index 70b7b07..4a97901 100644 --- a/lib/Service/DecoderProcess.php +++ b/lib/Service/DecoderProcess.php @@ -24,6 +24,7 @@ final class DecoderProcess { private ?int $exitCode = null; private ?int $groupId = null; private int $outputBytes = 0; + private bool $drainedSinceLastPoll = false; private string $output = ''; /** @@ -71,6 +72,7 @@ public static function start(array $command): ?self { * listings, limit the combined bytes while only retaining stdout. */ public function drain(?int $outputLimit): ?string { + $this->drainedSinceLastPoll = false; $remaining = self::MAX_DRAIN_PER_POLL; foreach ([1, 2] as $index) { while ($remaining > 0) { @@ -82,6 +84,7 @@ public function drain(?int $outputLimit): ?string { break; } $length = strlen($chunk); + $this->drainedSinceLastPoll = true; $remaining -= $length; if ($outputLimit !== null) { if ($length > $outputLimit - $this->outputBytes) { @@ -97,6 +100,11 @@ public function drain(?int $outputLimit): ?string { return null; } + /** Whether the last drain pass consumed bytes from either process pipe. */ + public function hadOutput(): bool { + return $this->drainedSinceLastPoll; + } + public function hasExited(): bool { $status = proc_get_status($this->process); if ($this->isolated && $this->groupId === null) { diff --git a/lib/Service/ResourceLimitedProcess.php b/lib/Service/ResourceLimitedProcess.php index 443f2a5..c46bd18 100644 --- a/lib/Service/ResourceLimitedProcess.php +++ b/lib/Service/ResourceLimitedProcess.php @@ -76,7 +76,10 @@ private static function execute(array $command, int $timeoutSeconds, ?StagingBud if ($process->hasExited() && ($maxOutputBytes === null || $process->outputComplete())) { break; } - usleep(self::POLL_INTERVAL_US); + // A verbose decoder can fill the pipe much faster than a 50 ms + // polling cadence allows it to be drained. Keep reading promptly + // while data flows; retain the slower cadence when idle. + usleep($process->hadOutput() ? 1000 : self::POLL_INTERVAL_US); } } catch (\Throwable) { $reason = 'inspection'; diff --git a/tests/unit/ResourceLimitedProcessTest.php b/tests/unit/ResourceLimitedProcessTest.php index 2e588f6..f474e41 100644 --- a/tests/unit/ResourceLimitedProcessTest.php +++ b/tests/unit/ResourceLimitedProcessTest.php @@ -90,6 +90,17 @@ public function testLargeStdoutDoesNotBlockAValidDecoder(): void { self::assertSame(['success' => true, 'reason' => ''], $result); } + public function testLargeStderrDoesNotBlockAValidDecoder(): void { + $result = ResourceLimitedProcess::run( + [PHP_BINARY, '-r', 'fwrite(STDERR, str_repeat("x", 1000000));'], + $this->directory, + 100, + 10, + 3, + ); + self::assertSame(['success' => true, 'reason' => ''], $result); + } + public function testListingRejectsExcessOutput(): void { $result = ResourceLimitedProcess::capture( [PHP_BINARY, '-r', 'echo str_repeat("x", 1000000);'],