Lines 100.00% 11 / 11
Functions and Methods 100.00% 1 / 1
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
AmpExternalCommandRunner 100.00% 11 / 11 100.00% 1 / 1 4 100.00% 1 / 1
 runCommand 100.00% 11 / 11 100.00% 1 / 1 4
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Broker\Deploy;
6
7use Amp\Cancellation;
8use Amp\CancelledException;
9use Amp\CompositeCancellation;
10use Amp\Future;
11use Amp\Process\Process;
12use Amp\TimeoutCancellation;
13use Stewart\Contracts\Time\Duration;
14use Stewart\Runtime\Exception\DeployError;
15use Stewart\Runtime\Exception\DeployException;
16
17use function Amp\async;
18use function Amp\ByteStream\buffer;
19
20final readonly class AmpExternalCommandRunner implements ExternalCommandRunner
21{
22    public function runCommand(array $command, Duration $timeout, Cancellation $cancellation, array $environmentOverrides = []): ExternalCommandResult
23    {
24        // A non-empty environment replaces the inherited one, so the overrides go on top of it.
25        $process = Process::start($command, environment: $environmentOverrides === [] ? [] : [...getenv(), ...$environmentOverrides]);
26        $process->getStdin()->close();
27        // Both pipes drain while the command runs, so a chatty composer install cannot fill one and stall.
28        /** @var Future<string> $output */
29        $output = async(static fn(): string => buffer($process->getStdout()));
30        /** @var Future<string> $errorOutput */
31        $errorOutput = async(static fn(): string => buffer($process->getStderr()));
32
33        try {
34            $exitCode = $process->join(new CompositeCancellation($cancellation, new TimeoutCancellation($timeout->toSeconds())));
35        } catch (CancelledException $e) {
36            $process->kill();
37
38            if ($cancellation->isRequested()) {
39                throw $e;
40            }
41
42            throw DeployException::createForReason(DeployError::CommandTimedOut, $e, command: implode(' ', $command), timeout: (string) $timeout);
43        }
44
45        return new ExternalCommandResult($exitCode, $output->await(), $errorOutput->await());
46    }
47}