From e06fb460d4c1b9bffb530d8e329931e86d5f02f3 Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 12:06:01 +0100 Subject: [PATCH 01/10] feat: sandbox picks the port exercises listen on --- src/Event/CliExecuteEvent.php | 13 +++++++ src/Exercise/Scenario/ExerciseScenario.php | 20 +++++------ src/ExerciseRunner/CgiRunner.php | 10 ++---- src/ExerciseRunner/CliRunner.php | 40 ++++++++++++++-------- src/Process/DockerExecution.php | 6 ++-- src/Process/DockerSandbox.php | 14 ++++---- src/Process/HostSandbox.php | 5 +++ src/Process/Sandbox.php | 5 +++ test/ExerciseRunner/CliRunnerTest.php | 27 +++++++++++++++ test/Process/DockerSandboxTest.php | 26 +++++++++----- test/Process/HostSandboxTest.php | 7 ++++ 11 files changed, 123 insertions(+), 50 deletions(-) diff --git a/src/Event/CliExecuteEvent.php b/src/Event/CliExecuteEvent.php index 2ce351c9..0f8c83bd 100644 --- a/src/Event/CliExecuteEvent.php +++ b/src/Event/CliExecuteEvent.php @@ -68,6 +68,19 @@ public function getExecution(): SandboxExecution return $execution; } + /** + * The port the program listens on, picked by the sandbox. Only when the scenario exposes a port. + */ + public function getPort(): int + { + $port = $this->getParameters()['port'] ?? null; + if (!is_int($port)) { + throw new \InvalidArgumentException('The scenario does not expose a port'); + } + + return $port; + } + /** * Get the arguments to be passed to the program. * diff --git a/src/Exercise/Scenario/ExerciseScenario.php b/src/Exercise/Scenario/ExerciseScenario.php index c0ef1caf..7cafe3bd 100644 --- a/src/Exercise/Scenario/ExerciseScenario.php +++ b/src/Exercise/Scenario/ExerciseScenario.php @@ -9,10 +9,7 @@ abstract class ExerciseScenario */ private array $files = []; - /** - * @var list - */ - private array $exposedPorts = []; + private bool $exposesPort = false; public function withFile(string $relativeFileName, string $content): static { @@ -29,18 +26,19 @@ public function getFiles(): array return $this->files; } - public function exposePort(int $port): static + /** + * The code listens on a port, eg. a server the check connects to. The sandbox picks it, listeners get it from the + * execute events with getPort(). + */ + public function exposePort(): static { - $this->exposedPorts[] = $port; + $this->exposesPort = true; return $this; } - /** - * @return list - */ - public function getExposedPorts(): array + public function exposesPort(): bool { - return $this->exposedPorts; + return $this->exposesPort; } } diff --git a/src/ExerciseRunner/CgiRunner.php b/src/ExerciseRunner/CgiRunner.php index 981a9602..2e1530e0 100644 --- a/src/ExerciseRunner/CgiRunner.php +++ b/src/ExerciseRunner/CgiRunner.php @@ -215,7 +215,7 @@ private function executePhpFile( RequestInterface $request, string $type, ): ResponseInterface { - $execution = $this->getPhpExecution($workingDirectory, $fileName, $request, $scenario->getExposedPorts()); + $execution = $this->getPhpExecution($workingDirectory, $fileName, $request); $execution->start(); $this->eventDispatcher->dispatch( @@ -237,10 +237,7 @@ private function executePhpFile( return Message::parseResponse($output); } - /** - * @param list $exposedPorts - */ - private function getPhpExecution(string $workingDirectory, string $fileName, RequestInterface $request, array $exposedPorts): SandboxExecution + private function getPhpExecution(string $workingDirectory, string $fileName, RequestInterface $request): SandboxExecution { $env = [ 'REQUEST_METHOD' => $request->getMethod(), @@ -268,7 +265,7 @@ private function getPhpExecution(string $workingDirectory, string $fileName, Req ], $workingDirectory, $env, - $exposedPorts, + [], $content, ); @@ -312,7 +309,6 @@ public function run(ExecutionContext $context, OutputInterface $output): bool $context->getStudentExecutionDirectory(), basename($context->getEntryPoint()), $event->getRequest(), - $scenario->getExposedPorts(), ); $execution->start(); diff --git a/src/ExerciseRunner/CliRunner.php b/src/ExerciseRunner/CliRunner.php index 76a3a7b6..bbfe3247 100644 --- a/src/ExerciseRunner/CliRunner.php +++ b/src/ExerciseRunner/CliRunner.php @@ -108,10 +108,14 @@ public function verify(ExecutionContext $context): ResultInterface $this->eventDispatcher->dispatch(new CliExerciseRunnerEvent('cli.verify.start', $context, $scenario)); + //one for each folder, every run in it listens on the same port + $referencePort = $this->pickPort($scenario); + $studentPort = $this->pickPort($scenario); + $result = new CliResult( array_map( - function (Collection $args) use ($context, $scenario) { - return $this->doVerify($context, $scenario, $args); + function (Collection $args) use ($context, $scenario, $referencePort, $studentPort) { + return $this->doVerify($context, $scenario, $args, $referencePort, $studentPort); }, $scenario->getExecutions(), ), @@ -125,12 +129,12 @@ function (Collection $args) use ($context, $scenario) { /** * @param Collection $args */ - private function doVerify(ExecutionContext $context, CliScenario $scenario, Collection $args): CliResultInterface + private function doVerify(ExecutionContext $context, CliScenario $scenario, Collection $args, ?int $referencePort, ?int $studentPort): CliResultInterface { try { /** @var CliExecuteEvent $event */ $event = $this->eventDispatcher->dispatch( - new CliExecuteEvent('cli.verify.reference-execute.pre', $context, $scenario, $args), + new CliExecuteEvent('cli.verify.reference-execute.pre', $context, $scenario, $args, ['port' => $referencePort]), ); $solutionOutput = $this->executePhpFile( $context, @@ -139,6 +143,7 @@ private function doVerify(ExecutionContext $context, CliScenario $scenario, Coll $this->exercise->getSolution()->getEntryPoint()->getRelativePath(), $event->getArgs(), 'reference', + $referencePort, ); } catch (CodeExecutionException $e) { $this->eventDispatcher->dispatch( @@ -156,7 +161,7 @@ private function doVerify(ExecutionContext $context, CliScenario $scenario, Coll try { /** @var CliExecuteEvent $event */ $event = $this->eventDispatcher->dispatch( - new CliExecuteEvent('cli.verify.student-execute.pre', $context, $scenario, $args), + new CliExecuteEvent('cli.verify.student-execute.pre', $context, $scenario, $args, ['port' => $studentPort]), ); $userOutput = $this->executePhpFile( $context, @@ -165,6 +170,7 @@ private function doVerify(ExecutionContext $context, CliScenario $scenario, Coll basename($context->getEntryPoint()), $event->getArgs(), 'student', + $studentPort, ); } catch (CodeExecutionException $e) { $this->eventDispatcher->dispatch( @@ -211,11 +217,13 @@ public function run(ExecutionContext $context, OutputInterface $output): bool $this->eventDispatcher->dispatch(new CliExerciseRunnerEvent('cli.run.start', $context, $scenario)); + $port = $this->pickPort($scenario); + $success = true; foreach ($scenario->getExecutions() as $i => $args) { /** @var CliExecuteEvent $event */ $event = $this->eventDispatcher->dispatch( - new CliExecuteEvent('cli.run.student-execute.pre', $context, $scenario, $args), + new CliExecuteEvent('cli.run.student-execute.pre', $context, $scenario, $args, ['port' => $port]), ); $args = $event->getArgs(); @@ -224,12 +232,12 @@ public function run(ExecutionContext $context, OutputInterface $output): bool $context->getStudentExecutionDirectory(), basename($context->getEntryPoint()), $args, - $scenario->getExposedPorts(), + $port, ); $execution->start(); $this->eventDispatcher->dispatch( - new CliExecuteEvent('cli.run.student.executing', $context, $scenario, $args, ['output' => $output, 'execution' => $execution]), + new CliExecuteEvent('cli.run.student.executing', $context, $scenario, $args, ['output' => $output, 'execution' => $execution, 'port' => $port]), ); $execution->wait(function ($outputType, $outputBuffer) use ($output) { $output->write($outputBuffer); @@ -256,13 +264,13 @@ public function run(ExecutionContext $context, OutputInterface $output): bool /** * @param Collection $args */ - private function executePhpFile(ExecutionContext $context, CliScenario $scenario, string $workingDirectory, string $fileName, Collection $args, string $type): string + private function executePhpFile(ExecutionContext $context, CliScenario $scenario, string $workingDirectory, string $fileName, Collection $args, string $type, ?int $port): string { - $execution = $this->getPhpExecution($workingDirectory, $fileName, $args, $scenario->getExposedPorts()); + $execution = $this->getPhpExecution($workingDirectory, $fileName, $args, $port); $execution->start(); $this->eventDispatcher->dispatch( - new CliExecuteEvent(sprintf('cli.verify.%s.executing', $type), $context, $scenario, $args, ['execution' => $execution]), + new CliExecuteEvent(sprintf('cli.verify.%s.executing', $type), $context, $scenario, $args, ['execution' => $execution, 'port' => $port]), ); $execution->wait(); @@ -275,12 +283,16 @@ private function executePhpFile(ExecutionContext $context, CliScenario $scenario /** * @param Collection $args - * @param list $exposedPorts */ - private function getPhpExecution(string $workingDirectory, string $fileName, Collection $args, array $exposedPorts): SandboxExecution + private function getPhpExecution(string $workingDirectory, string $fileName, Collection $args, ?int $port): SandboxExecution { return $this->sandbox->create( - new ProcessInput('php', [$fileName, ...$args->getArrayCopy()], $workingDirectory, [], $exposedPorts), + new ProcessInput('php', [$fileName, ...$args->getArrayCopy()], $workingDirectory, [], $port === null ? [] : [$port]), ); } + + private function pickPort(CliScenario $scenario): ?int + { + return $scenario->exposesPort() ? $this->sandbox->pickPort() : null; + } } diff --git a/src/Process/DockerExecution.php b/src/Process/DockerExecution.php index bee68a6c..bb8b487c 100644 --- a/src/Process/DockerExecution.php +++ b/src/Process/DockerExecution.php @@ -16,7 +16,7 @@ final class DockerExecution implements SandboxExecution * @param list $before * @param list $after * @param string $host the docker host's address that ports are published on, eg. 10.0.0.5 - * @param array $ports container port => published port on the host, eg. [54321 => 47213] + * @param list $ports published on the host with the same number, eg. [54321] */ public function __construct( public readonly Process $process, @@ -71,11 +71,11 @@ public function getErrorOutput(): string public function getAddress(int $port): string { - if (!isset($this->ports[$port])) { + if (!in_array($port, $this->ports, true)) { throw new \RuntimeException(sprintf('Port %d is not published', $port)); } - return $this->host . ':' . $this->ports[$port]; + return $this->host . ':' . $port; } private function runAfter(): void diff --git a/src/Process/DockerSandbox.php b/src/Process/DockerSandbox.php index 82a09cc3..de4f33cb 100644 --- a/src/Process/DockerSandbox.php +++ b/src/Process/DockerSandbox.php @@ -62,17 +62,19 @@ public function createBuildProcess(): Process ); } + public function pickPort(): int + { + return $this->portPicker->pick(); + } + public function create(ProcessInput $processInput): DockerExecution { $network = ['--network', 'none']; - $ports = []; if (count($processInput->getExposedPorts()) > 0) { $network = ['--network', $this->portsNetwork]; + //the same port on the docker host, pickPort() picked one free there foreach ($processInput->getExposedPorts() as $port) { - $hostPort = $this->portPicker->pick(); - $network[] = '-p'; - $network[] = $this->portsHost . ':' . $hostPort . ':' . $port; - $ports[$port] = $hostPort; + array_push($network, '-p', $this->portsHost . ':' . $port . ':' . $port); } } @@ -126,7 +128,7 @@ public function create(ProcessInput $processInput): DockerExecution null, $processInput->getInput(), self::TIMEOUT + 5, - ), [], [], $this->portsHost, $ports); + ), [], [], $this->portsHost, $processInput->getExposedPorts()); } private function findDocker(): string diff --git a/src/Process/HostSandbox.php b/src/Process/HostSandbox.php index 8351e2fa..a402799c 100644 --- a/src/Process/HostSandbox.php +++ b/src/Process/HostSandbox.php @@ -21,6 +21,11 @@ public function __construct(?ExecutableFinder $executableFinder = null) $this->executableFinder = $executableFinder ?? new ExecutableFinder(); } + public function pickPort(): int + { + return (new FreePortPicker())->pick(); + } + public function create(ProcessInput $processInput): HostExecution { $executablePath = $this->executableFinder->find($processInput->getExecutable()); diff --git a/src/Process/Sandbox.php b/src/Process/Sandbox.php index 784281f4..a3337170 100644 --- a/src/Process/Sandbox.php +++ b/src/Process/Sandbox.php @@ -7,4 +7,9 @@ interface Sandbox { public function create(ProcessInput $processInput): SandboxExecution; + + /** + * A port for code to listen on, free where this sandbox runs it. + */ + public function pickPort(): int; } diff --git a/test/ExerciseRunner/CliRunnerTest.php b/test/ExerciseRunner/CliRunnerTest.php index f3418d81..56724fb4 100644 --- a/test/ExerciseRunner/CliRunnerTest.php +++ b/test/ExerciseRunner/CliRunnerTest.php @@ -108,6 +108,28 @@ function (CliExecuteEvent $event) use (&$executions) { $this->assertContainsOnlyInstancesOf(SandboxExecution::class, $executions); } + public function testSandboxPicksOnePortForEachFolder(): void + { + $solution = SingleFileSolution::fromFile(realpath(__DIR__ . '/../res/cli/solution.php')); + $this->exercise->setSolution($solution); + $this->exercise->setScenario((new CliScenario())->exposePort()->withExecution([1, 2, 3])->withExecution([4, 5, 6])); + + $ports = []; + $this->eventDispatcher->listen( + ['cli.verify.reference-execute.pre', 'cli.verify.student-execute.pre'], + function (CliExecuteEvent $event) use (&$ports) { + $ports[$event->getName()][] = $event->getPort(); + }, + ); + + $context = TestContext::fromExerciseAndStudentSolution($this->exercise, __DIR__ . '/../res/cli/user.php'); + $this->runner->verify($context); + + //the same port for every run of a folder + $this->assertCount(1, array_unique($ports['cli.verify.reference-execute.pre'])); + $this->assertCount(1, array_unique($ports['cli.verify.student-execute.pre'])); + } + public function testSuccessWithSingleSetOfArgsForBC(): void { $solution = SingleFileSolution::fromFile(realpath(__DIR__ . '/../res/cli/solution.php')); @@ -205,6 +227,11 @@ public function create(ProcessInput $processInput): SandboxExecution return (new HostSandbox())->create($processInput); } + + public function pickPort(): int + { + return 54321; + } }; $runner = new CliRunner($this->exercise, $this->eventDispatcher, $sandbox, new EnvironmentManager(new Filesystem(), $this->eventDispatcher)); diff --git a/test/Process/DockerSandboxTest.php b/test/Process/DockerSandboxTest.php index cd42f043..fd6c64c1 100644 --- a/test/Process/DockerSandboxTest.php +++ b/test/Process/DockerSandboxTest.php @@ -85,7 +85,7 @@ public function testExposedPortsArePublishedOnLoopbackOnly(): void $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, [], [8000]))->process; $expected = $this->expectedCommand( - ['--network', 'bridge', '-p', '127.0.0.1:47213:8000'], + ['--network', 'bridge', '-p', '127.0.0.1:8000:8000'], ['-v', __DIR__ . ':/solution'], ['php'], ); @@ -97,7 +97,7 @@ public function testExposedPortsUseTheGivenNetwork(): void $process = $this->factory('php-school-sandbox')->create(new ProcessInput('php', [], __DIR__, [], [8000]))->process; $expected = $this->expectedCommand( - ['--network', 'php-school-sandbox', '-p', '127.0.0.1:47213:8000'], + ['--network', 'php-school-sandbox', '-p', '127.0.0.1:8000:8000'], ['-v', __DIR__ . ':/solution'], ['php'], ); @@ -109,21 +109,29 @@ public function testExposedPortsArePublishedOnTheGivenHost(): void $process = $this->factory('bridge', '172.19.0.2')->create(new ProcessInput('php', [], __DIR__, [], [8000]))->process; $expected = $this->expectedCommand( - ['--network', 'bridge', '-p', '172.19.0.2:47213:8000'], + ['--network', 'bridge', '-p', '172.19.0.2:8000:8000'], ['-v', __DIR__ . ':/solution'], ['php'], ); static::assertSame($expected, $process->getCommandLine()); } - public function testAddressIsThePickedPortOnTheGivenHost(): void + public function testPortsArePickedWithThePortPicker(): void { - $execution = $this->factory('bridge', '172.19.0.2')->create(new ProcessInput('php', [], __DIR__, [], [8000])); - static::assertSame('172.19.0.2:47213', $execution->getAddress(8000)); + $ports = $this->createMock(PortPicker::class); + $ports->method('pick')->willReturn(47213); - $execution = $this->factory('bridge', '[fdaa::2]')->create(new ProcessInput('php', [], __DIR__, [], [8000])); - static::assertStringContainsString("'-p' '[fdaa::2]:47213:8000'", $execution->process->getCommandLine()); - static::assertSame('[fdaa::2]:47213', $execution->getAddress(8000)); + static::assertSame(47213, (new DockerSandbox('/docker-dir', 'php8appreciate', portPicker: $ports))->pickPort()); + } + + public function testAddressIsTheSamePortOnTheGivenHost(): void + { + $execution = $this->factory('bridge', '172.19.0.2')->create(new ProcessInput('php', [], __DIR__, [], [47213])); + static::assertSame('172.19.0.2:47213', $execution->getAddress(47213)); + + $execution = $this->factory('bridge', '[fdaa::2]')->create(new ProcessInput('php', [], __DIR__, [], [47213])); + static::assertStringContainsString("'-p' '[fdaa::2]:47213:47213'", $execution->process->getCommandLine()); + static::assertSame('[fdaa::2]:47213', $execution->getAddress(47213)); } public function testCreateWithEnv(): void diff --git a/test/Process/HostSandboxTest.php b/test/Process/HostSandboxTest.php index bc0ecbc0..4315ad67 100644 --- a/test/Process/HostSandboxTest.php +++ b/test/Process/HostSandboxTest.php @@ -41,6 +41,13 @@ public function testCreate(): void static::assertSame("'/usr/local/bin/composer'", $process->getCommandLine()); } + public function testPickedPortIsFreeOnThisMachine(): void + { + $server = stream_socket_server('tcp://127.0.0.1:' . (new HostSandbox())->pickPort()); + static::assertNotFalse($server); + fclose($server); + } + public function testAddressIsThePortOnThisMachine(): void { $execution = (new HostSandbox())->create(new ProcessInput('php', [], __DIR__, [], [54321])); From a2e61508455dc68dda3ff656c05bcc00d2e00508 Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 12:17:51 +0100 Subject: [PATCH 02/10] The execution owns its port, getAddress() takes no port --- src/Event/CliExecuteEvent.php | 4 ++-- src/ExerciseRunner/CgiRunner.php | 2 +- src/ExerciseRunner/CliRunner.php | 6 +++--- src/Process/DockerExecution.php | 15 ++++++++------- src/Process/DockerSandbox.php | 10 ++++------ src/Process/HostExecution.php | 11 ++++++++--- src/Process/HostSandbox.php | 2 +- src/Process/ProcessInput.php | 11 ++++------- src/Process/SandboxExecution.php | 9 +++++++-- test/Process/DockerSandboxTest.php | 22 +++++++++++----------- test/Process/HostSandboxTest.php | 16 ++++++++-------- test/Process/ProcessInputTest.php | 4 ++-- 12 files changed, 59 insertions(+), 53 deletions(-) diff --git a/src/Event/CliExecuteEvent.php b/src/Event/CliExecuteEvent.php index 0f8c83bd..0aa22a30 100644 --- a/src/Event/CliExecuteEvent.php +++ b/src/Event/CliExecuteEvent.php @@ -58,7 +58,7 @@ public function appendArg(string $arg): void } /** - * The running program, eg. to connect to a port it listens on with getAddress(). Only on the executing events. + * The running program, eg. to connect to the port it listens on with getAddress(). Only on the executing events. */ public function getExecution(): SandboxExecution { @@ -69,7 +69,7 @@ public function getExecution(): SandboxExecution } /** - * The port the program listens on, picked by the sandbox. Only when the scenario exposes a port. + * The port the program will listen on, picked by the sandbox, eg. to pass it in the args. Only on the pre events when the scenario exposes a port, after that use getExecution(). */ public function getPort(): int { diff --git a/src/ExerciseRunner/CgiRunner.php b/src/ExerciseRunner/CgiRunner.php index 2e1530e0..d0ce43a4 100644 --- a/src/ExerciseRunner/CgiRunner.php +++ b/src/ExerciseRunner/CgiRunner.php @@ -265,7 +265,7 @@ private function getPhpExecution(string $workingDirectory, string $fileName, Req ], $workingDirectory, $env, - [], + null, $content, ); diff --git a/src/ExerciseRunner/CliRunner.php b/src/ExerciseRunner/CliRunner.php index bbfe3247..56c7bf5f 100644 --- a/src/ExerciseRunner/CliRunner.php +++ b/src/ExerciseRunner/CliRunner.php @@ -237,7 +237,7 @@ public function run(ExecutionContext $context, OutputInterface $output): bool $execution->start(); $this->eventDispatcher->dispatch( - new CliExecuteEvent('cli.run.student.executing', $context, $scenario, $args, ['output' => $output, 'execution' => $execution, 'port' => $port]), + new CliExecuteEvent('cli.run.student.executing', $context, $scenario, $args, ['output' => $output, 'execution' => $execution]), ); $execution->wait(function ($outputType, $outputBuffer) use ($output) { $output->write($outputBuffer); @@ -270,7 +270,7 @@ private function executePhpFile(ExecutionContext $context, CliScenario $scenario $execution->start(); $this->eventDispatcher->dispatch( - new CliExecuteEvent(sprintf('cli.verify.%s.executing', $type), $context, $scenario, $args, ['execution' => $execution, 'port' => $port]), + new CliExecuteEvent(sprintf('cli.verify.%s.executing', $type), $context, $scenario, $args, ['execution' => $execution]), ); $execution->wait(); @@ -287,7 +287,7 @@ private function executePhpFile(ExecutionContext $context, CliScenario $scenario private function getPhpExecution(string $workingDirectory, string $fileName, Collection $args, ?int $port): SandboxExecution { return $this->sandbox->create( - new ProcessInput('php', [$fileName, ...$args->getArrayCopy()], $workingDirectory, [], $port === null ? [] : [$port]), + new ProcessInput('php', [$fileName, ...$args->getArrayCopy()], $workingDirectory, [], $port), ); } diff --git a/src/Process/DockerExecution.php b/src/Process/DockerExecution.php index bb8b487c..215f048b 100644 --- a/src/Process/DockerExecution.php +++ b/src/Process/DockerExecution.php @@ -16,14 +16,14 @@ final class DockerExecution implements SandboxExecution * @param list $before * @param list $after * @param string $host the docker host's address that ports are published on, eg. 10.0.0.5 - * @param list $ports published on the host with the same number, eg. [54321] + * @param int|null $port published on the host with the same number, eg. 54321 */ public function __construct( public readonly Process $process, public readonly array $before = [], public readonly array $after = [], private string $host = '127.0.0.1', - private array $ports = [], + private ?int $port = null, ) {} public function start(): void @@ -69,13 +69,14 @@ public function getErrorOutput(): string return $this->process->getErrorOutput(); } - public function getAddress(int $port): string + public function getAddress(): string { - if (!in_array($port, $this->ports, true)) { - throw new \RuntimeException(sprintf('Port %d is not published', $port)); - } + return $this->host . ':' . $this->getPort(); + } - return $this->host . ':' . $port; + public function getPort(): int + { + return $this->port ?? throw new \RuntimeException('The code does not listen on a port'); } private function runAfter(): void diff --git a/src/Process/DockerSandbox.php b/src/Process/DockerSandbox.php index de4f33cb..23e7437a 100644 --- a/src/Process/DockerSandbox.php +++ b/src/Process/DockerSandbox.php @@ -70,12 +70,10 @@ public function pickPort(): int public function create(ProcessInput $processInput): DockerExecution { $network = ['--network', 'none']; - if (count($processInput->getExposedPorts()) > 0) { - $network = ['--network', $this->portsNetwork]; + $port = $processInput->getPort(); + if ($port !== null) { //the same port on the docker host, pickPort() picked one free there - foreach ($processInput->getExposedPorts() as $port) { - array_push($network, '-p', $this->portsHost . ':' . $port . ':' . $port); - } + $network = ['--network', $this->portsNetwork, '-p', $this->portsHost . ':' . $port . ':' . $port]; } $envArgs = []; @@ -128,7 +126,7 @@ public function create(ProcessInput $processInput): DockerExecution null, $processInput->getInput(), self::TIMEOUT + 5, - ), [], [], $this->portsHost, $processInput->getExposedPorts()); + ), [], [], $this->portsHost, $port); } private function findDocker(): string diff --git a/src/Process/HostExecution.php b/src/Process/HostExecution.php index 9e4b3799..69c37a08 100644 --- a/src/Process/HostExecution.php +++ b/src/Process/HostExecution.php @@ -8,7 +8,7 @@ final class HostExecution implements SandboxExecution { - public function __construct(public readonly Process $process) {} + public function __construct(public readonly Process $process, private ?int $port = null) {} public function start(): void { @@ -40,8 +40,13 @@ public function getErrorOutput(): string return $this->process->getErrorOutput(); } - public function getAddress(int $port): string + public function getAddress(): string { - return '127.0.0.1:' . $port; + return '127.0.0.1:' . $this->getPort(); + } + + public function getPort(): int + { + return $this->port ?? throw new \RuntimeException('The code does not listen on a port'); } } diff --git a/src/Process/HostSandbox.php b/src/Process/HostSandbox.php index a402799c..6b6ca585 100644 --- a/src/Process/HostSandbox.php +++ b/src/Process/HostSandbox.php @@ -40,7 +40,7 @@ public function create(ProcessInput $processInput): HostExecution array_merge($this->getDefaultEnv(), $processInput->getEnv()), $processInput->getInput(), 10, - )); + ), $processInput->getPort()); } /** diff --git a/src/Process/ProcessInput.php b/src/Process/ProcessInput.php index 731e146b..8c476154 100644 --- a/src/Process/ProcessInput.php +++ b/src/Process/ProcessInput.php @@ -7,14 +7,14 @@ class ProcessInput /** * @param list $args * @param array $env - * @param list $exposedPorts + * @param int|null $port the code listens on, eg. 54321 */ public function __construct( private string $executable, private array $args, private string $workingDirectory, private array $env, - private array $exposedPorts, + private ?int $port, private ?string $input = null, ) {} @@ -44,12 +44,9 @@ public function getEnv(): array return $this->env; } - /** - * @return list - */ - public function getExposedPorts(): array + public function getPort(): ?int { - return $this->exposedPorts; + return $this->port; } public function getInput(): ?string diff --git a/src/Process/SandboxExecution.php b/src/Process/SandboxExecution.php index cc45c046..d6d80cfe 100644 --- a/src/Process/SandboxExecution.php +++ b/src/Process/SandboxExecution.php @@ -28,9 +28,14 @@ public function getOutput(): string; public function getErrorOutput(): string; /** - * Where to connect to a port the code listens on, once it has started. + * Where to connect to the port the code listens on, once it has started. * * @return string eg. '127.0.0.1:54321' */ - public function getAddress(int $port): string; + public function getAddress(): string; + + /** + * The port the code listens on, eg. to pass it in the args. + */ + public function getPort(): int; } diff --git a/test/Process/DockerSandboxTest.php b/test/Process/DockerSandboxTest.php index fd6c64c1..195eef0b 100644 --- a/test/Process/DockerSandboxTest.php +++ b/test/Process/DockerSandboxTest.php @@ -61,14 +61,14 @@ public function testCreateThrowsExceptionIfDockerNotFound(): void ->willReturn(null); $factory = new DockerSandbox('/docker-dir', 'php8appreciate', $finder); - $input = new ProcessInput('php', [], __DIR__, [], []); + $input = new ProcessInput('php', [], __DIR__, [], null); $factory->create($input); } public function testCreateIsIsolatedWithNoNetwork(): void { - $process = $this->factory()->create(new ProcessInput('php', ['one', 'two'], __DIR__, [], []))->process; + $process = $this->factory()->create(new ProcessInput('php', ['one', 'two'], __DIR__, [], null))->process; $expected = $this->expectedCommand( ['--network', 'none'], @@ -82,7 +82,7 @@ public function testCreateIsIsolatedWithNoNetwork(): void public function testExposedPortsArePublishedOnLoopbackOnly(): void { - $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, [], [8000]))->process; + $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, [], 8000))->process; $expected = $this->expectedCommand( ['--network', 'bridge', '-p', '127.0.0.1:8000:8000'], @@ -94,7 +94,7 @@ public function testExposedPortsArePublishedOnLoopbackOnly(): void public function testExposedPortsUseTheGivenNetwork(): void { - $process = $this->factory('php-school-sandbox')->create(new ProcessInput('php', [], __DIR__, [], [8000]))->process; + $process = $this->factory('php-school-sandbox')->create(new ProcessInput('php', [], __DIR__, [], 8000))->process; $expected = $this->expectedCommand( ['--network', 'php-school-sandbox', '-p', '127.0.0.1:8000:8000'], @@ -106,7 +106,7 @@ public function testExposedPortsUseTheGivenNetwork(): void public function testExposedPortsArePublishedOnTheGivenHost(): void { - $process = $this->factory('bridge', '172.19.0.2')->create(new ProcessInput('php', [], __DIR__, [], [8000]))->process; + $process = $this->factory('bridge', '172.19.0.2')->create(new ProcessInput('php', [], __DIR__, [], 8000))->process; $expected = $this->expectedCommand( ['--network', 'bridge', '-p', '172.19.0.2:8000:8000'], @@ -126,17 +126,17 @@ public function testPortsArePickedWithThePortPicker(): void public function testAddressIsTheSamePortOnTheGivenHost(): void { - $execution = $this->factory('bridge', '172.19.0.2')->create(new ProcessInput('php', [], __DIR__, [], [47213])); - static::assertSame('172.19.0.2:47213', $execution->getAddress(47213)); + $execution = $this->factory('bridge', '172.19.0.2')->create(new ProcessInput('php', [], __DIR__, [], 47213)); + static::assertSame('172.19.0.2:47213', $execution->getAddress()); - $execution = $this->factory('bridge', '[fdaa::2]')->create(new ProcessInput('php', [], __DIR__, [], [47213])); + $execution = $this->factory('bridge', '[fdaa::2]')->create(new ProcessInput('php', [], __DIR__, [], 47213)); static::assertStringContainsString("'-p' '[fdaa::2]:47213:47213'", $execution->process->getCommandLine()); - static::assertSame('[fdaa::2]:47213', $execution->getAddress(47213)); + static::assertSame('[fdaa::2]:47213', $execution->getAddress()); } public function testCreateWithEnv(): void { - $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, ['SOME_VAR' => 'value'], []))->process; + $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, ['SOME_VAR' => 'value'], null))->process; $expected = $this->expectedCommand( ['--network', 'none'], @@ -148,7 +148,7 @@ public function testCreateWithEnv(): void public function testWithInput(): void { - $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, [], [], 'someinput'))->process; + $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, [], null, 'someinput'))->process; static::assertSame('someinput', $process->getInput()); } diff --git a/test/Process/HostSandboxTest.php b/test/Process/HostSandboxTest.php index 4315ad67..2bc11119 100644 --- a/test/Process/HostSandboxTest.php +++ b/test/Process/HostSandboxTest.php @@ -21,7 +21,7 @@ public function testCreateThrowsExceptionIfExecutableNotFound(): void ->willReturn(null); $factory = new HostSandbox($finder); - $input = new ProcessInput('composer', [], __DIR__, [], []); + $input = new ProcessInput('composer', [], __DIR__, [], null); $factory->create($input); } @@ -35,7 +35,7 @@ public function testCreate(): void ->willReturn('/usr/local/bin/composer'); $factory = new HostSandbox($finder); - $input = new ProcessInput('composer', [], __DIR__, [], []); + $input = new ProcessInput('composer', [], __DIR__, [], null); $process = $factory->create($input)->process; static::assertSame("'/usr/local/bin/composer'", $process->getCommandLine()); @@ -50,9 +50,9 @@ public function testPickedPortIsFreeOnThisMachine(): void public function testAddressIsThePortOnThisMachine(): void { - $execution = (new HostSandbox())->create(new ProcessInput('php', [], __DIR__, [], [54321])); + $execution = (new HostSandbox())->create(new ProcessInput('php', [], __DIR__, [], 54321)); - static::assertSame('127.0.0.1:54321', $execution->getAddress(54321)); + static::assertSame('127.0.0.1:54321', $execution->getAddress()); } public function testCreateWithArgs(): void @@ -64,7 +64,7 @@ public function testCreateWithArgs(): void ->willReturn('/usr/local/bin/composer'); $factory = new HostSandbox($finder); - $input = new ProcessInput('composer', ['one', 'two'], __DIR__, [], []); + $input = new ProcessInput('composer', ['one', 'two'], __DIR__, [], null); $process = $factory->create($input)->process; static::assertSame("'/usr/local/bin/composer' 'one' 'two'", $process->getCommandLine()); @@ -79,7 +79,7 @@ public function testCreateWithEnv(): void ->willReturn('/usr/local/bin/composer'); $factory = new HostSandbox($finder); - $input = new ProcessInput('composer', ['one', 'two'], __DIR__, ['SOME_VAR' => 'value'], []); + $input = new ProcessInput('composer', ['one', 'two'], __DIR__, ['SOME_VAR' => 'value'], null); $process = $factory->create($input)->process; static::assertSame('value', $process->getEnv()['SOME_VAR']); @@ -91,7 +91,7 @@ public function testInheritedEnvIsRemovedExceptAllowed(): void try { $process = (new HostSandbox())->create( - new ProcessInput('php', ['-r', 'echo json_encode([getenv("PHPSCHOOL_SECRET"), getenv("PATH") !== false]);'], __DIR__, [], []), + new ProcessInput('php', ['-r', 'echo json_encode([getenv("PHPSCHOOL_SECRET"), getenv("PATH") !== false]);'], __DIR__, [], null), ); $process->mustRun(); @@ -110,7 +110,7 @@ public function testWithInput(): void ->willReturn('/usr/local/bin/composer'); $factory = new HostSandbox($finder); - $input = new ProcessInput('composer', [], __DIR__, [], [], 'someinput'); + $input = new ProcessInput('composer', [], __DIR__, [], null, 'someinput'); $process = $factory->create($input)->process; static::assertSame('someinput', $process->getInput()); diff --git a/test/Process/ProcessInputTest.php b/test/Process/ProcessInputTest.php index 84453cae..2f68ff61 100644 --- a/test/Process/ProcessInputTest.php +++ b/test/Process/ProcessInputTest.php @@ -9,13 +9,13 @@ class ProcessInputTest extends TestCase { public function testProcessInput(): void { - $input = new ProcessInput('composer', ['one', 'two'], __DIR__, ['SOME_VAR' => 'value'], [], 'input'); + $input = new ProcessInput('composer', ['one', 'two'], __DIR__, ['SOME_VAR' => 'value'], null, 'input'); static::assertSame('composer', $input->getExecutable()); static::assertSame(['one', 'two'], $input->getArgs()); static::assertSame(__DIR__, $input->getWorkingDirectory()); static::assertSame(['SOME_VAR' => 'value'], $input->getEnv()); - static::assertSame([], $input->getExposedPorts()); + static::assertNull($input->getPort()); static::assertSame('input', $input->getInput()); } } From 1752158668ac4eeb8a00b158798cfb7f1b773429 Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 13:45:54 +0100 Subject: [PATCH 03/10] Sandbox prepares a Workspace per solution, ProcessInput drops directory and port --- src/Event/CliExecuteEvent.php | 13 +++--- src/Exercise/Scenario/ExerciseScenario.php | 2 +- src/ExerciseRunner/CgiRunner.php | 32 +++++++-------- src/ExerciseRunner/CliRunner.php | 48 ++++++++-------------- src/Process/DockerSandbox.php | 12 +++--- src/Process/HostSandbox.php | 10 ++--- src/Process/ProcessInput.php | 13 ------ src/Process/Sandbox.php | 6 +-- src/Process/Workspace.php | 16 ++++++++ test/ExerciseRunner/CliRunnerTest.php | 11 ++--- test/Process/DockerSandboxTest.php | 23 ++++++----- test/Process/HostSandboxTest.php | 28 +++++++------ test/Process/ProcessInputTest.php | 4 +- 13 files changed, 104 insertions(+), 114 deletions(-) create mode 100644 src/Process/Workspace.php diff --git a/src/Event/CliExecuteEvent.php b/src/Event/CliExecuteEvent.php index 0aa22a30..aa88cbd0 100644 --- a/src/Event/CliExecuteEvent.php +++ b/src/Event/CliExecuteEvent.php @@ -7,6 +7,7 @@ use PhpSchool\PhpWorkshop\Exercise\Scenario\CliScenario; use PhpSchool\PhpWorkshop\ExerciseRunner\Context\ExecutionContext; use PhpSchool\PhpWorkshop\Process\SandboxExecution; +use PhpSchool\PhpWorkshop\Process\Workspace; use PhpSchool\PhpWorkshop\Utils\Collection; /** @@ -69,16 +70,14 @@ public function getExecution(): SandboxExecution } /** - * The port the program will listen on, picked by the sandbox, eg. to pass it in the args. Only on the pre events when the scenario exposes a port, after that use getExecution(). + * The solution in the sandbox, eg. to pass its port in the args. Only on the pre events. */ - public function getPort(): int + public function getWorkspace(): Workspace { - $port = $this->getParameters()['port'] ?? null; - if (!is_int($port)) { - throw new \InvalidArgumentException('The scenario does not expose a port'); - } + /** @var Workspace $workspace */ + $workspace = $this->getParameter('workspace'); - return $port; + return $workspace; } /** diff --git a/src/Exercise/Scenario/ExerciseScenario.php b/src/Exercise/Scenario/ExerciseScenario.php index 7cafe3bd..dab9b2cc 100644 --- a/src/Exercise/Scenario/ExerciseScenario.php +++ b/src/Exercise/Scenario/ExerciseScenario.php @@ -28,7 +28,7 @@ public function getFiles(): array /** * The code listens on a port, eg. a server the check connects to. The sandbox picks it, listeners get it from the - * execute events with getPort(). + * pre execute events with getWorkspace(). */ public function exposePort(): static { diff --git a/src/ExerciseRunner/CgiRunner.php b/src/ExerciseRunner/CgiRunner.php index d0ce43a4..0a7dfde9 100644 --- a/src/ExerciseRunner/CgiRunner.php +++ b/src/ExerciseRunner/CgiRunner.php @@ -23,6 +23,7 @@ use PhpSchool\PhpWorkshop\Output\OutputInterface; use PhpSchool\PhpWorkshop\Process\Sandbox; use PhpSchool\PhpWorkshop\Process\ProcessInput; +use PhpSchool\PhpWorkshop\Process\Workspace; use PhpSchool\PhpWorkshop\Process\SandboxExecution; use PhpSchool\PhpWorkshop\Result\Cgi\CgiResult; use PhpSchool\PhpWorkshop\Result\Cgi\RequestFailure; @@ -109,10 +110,13 @@ public function verify(ExecutionContext $context): ResultInterface $this->eventDispatcher->dispatch(new CgiExerciseRunnerEvent('cgi.verify.start', $context, $scenario)); + $reference = $this->sandbox->prepare($context->getReferenceExecutionDirectory(), false); + $student = $this->sandbox->prepare($context->getStudentExecutionDirectory(), false); + $result = new CgiResult( array_map( - function (RequestInterface $request) use ($context, $scenario) { - return $this->doVerify($context, $scenario, $request); + function (RequestInterface $request) use ($context, $scenario, $reference, $student) { + return $this->doVerify($context, $scenario, $request, $reference, $student); }, $scenario->getExecutions(), ), @@ -122,7 +126,7 @@ function (RequestInterface $request) use ($context, $scenario) { return $result; } - private function doVerify(ExecutionContext $context, CgiScenario $scenario, RequestInterface $request): CgiResultInterface + private function doVerify(ExecutionContext $context, CgiScenario $scenario, RequestInterface $request, Workspace $reference, Workspace $student): CgiResultInterface { try { /** @var CgiExecuteEvent $event */ @@ -132,7 +136,7 @@ private function doVerify(ExecutionContext $context, CgiScenario $scenario, Requ $solutionResponse = $this->executePhpFile( $context, $scenario, - $context->getReferenceExecutionDirectory(), + $reference, $this->exercise->getSolution()->getEntryPoint()->getRelativePath(), $event->getRequest(), 'reference', @@ -158,7 +162,7 @@ private function doVerify(ExecutionContext $context, CgiScenario $scenario, Requ $userResponse = $this->executePhpFile( $context, $scenario, - $context->getStudentExecutionDirectory(), + $student, basename($context->getEntryPoint()), $event->getRequest(), 'student', @@ -210,12 +214,12 @@ private function getHeaders(ResponseInterface $response): array private function executePhpFile( ExecutionContext $context, CgiScenario $scenario, - string $workingDirectory, + Workspace $workspace, string $fileName, RequestInterface $request, string $type, ): ResponseInterface { - $execution = $this->getPhpExecution($workingDirectory, $fileName, $request); + $execution = $this->getPhpExecution($workspace, $fileName, $request); $execution->start(); $this->eventDispatcher->dispatch( @@ -237,7 +241,7 @@ private function executePhpFile( return Message::parseResponse($output); } - private function getPhpExecution(string $workingDirectory, string $fileName, RequestInterface $request): SandboxExecution + private function getPhpExecution(Workspace $workspace, string $fileName, RequestInterface $request): SandboxExecution { $env = [ 'REQUEST_METHOD' => $request->getMethod(), @@ -263,13 +267,11 @@ private function getPhpExecution(string $workingDirectory, string $fileName, Req '-dhtml_errors=0', '-dexpose_php=0', ], - $workingDirectory, $env, - null, $content, ); - return $this->sandbox->create($processInput); + return $this->sandbox->create($workspace, $processInput); } /** @@ -299,17 +301,15 @@ public function run(ExecutionContext $context, OutputInterface $output): bool $this->eventDispatcher->dispatch(new CgiExerciseRunnerEvent('cgi.run.start', $context, $scenario)); + $student = $this->sandbox->prepare($context->getStudentExecutionDirectory(), false); + $success = true; foreach ($scenario->getExecutions() as $i => $request) { /** @var CgiExecuteEvent $event */ $event = $this->eventDispatcher->dispatch( new CgiExecuteEvent('cgi.run.student-execute.pre', $context, $scenario, $request), ); - $execution = $this->getPhpExecution( - $context->getStudentExecutionDirectory(), - basename($context->getEntryPoint()), - $event->getRequest(), - ); + $execution = $this->getPhpExecution($student, basename($context->getEntryPoint()), $event->getRequest()); $execution->start(); $this->eventDispatcher->dispatch( diff --git a/src/ExerciseRunner/CliRunner.php b/src/ExerciseRunner/CliRunner.php index 56c7bf5f..bc3d5ddb 100644 --- a/src/ExerciseRunner/CliRunner.php +++ b/src/ExerciseRunner/CliRunner.php @@ -23,6 +23,7 @@ use PhpSchool\PhpWorkshop\Process\Sandbox; use PhpSchool\PhpWorkshop\Process\ProcessInput; use PhpSchool\PhpWorkshop\Process\SandboxExecution; +use PhpSchool\PhpWorkshop\Process\Workspace; use PhpSchool\PhpWorkshop\Result\Cli\RequestFailure; use PhpSchool\PhpWorkshop\Result\Cli\CliResult; use PhpSchool\PhpWorkshop\Result\Cli\GenericFailure; @@ -108,14 +109,13 @@ public function verify(ExecutionContext $context): ResultInterface $this->eventDispatcher->dispatch(new CliExerciseRunnerEvent('cli.verify.start', $context, $scenario)); - //one for each folder, every run in it listens on the same port - $referencePort = $this->pickPort($scenario); - $studentPort = $this->pickPort($scenario); + $reference = $this->sandbox->prepare($context->getReferenceExecutionDirectory(), $scenario->exposesPort()); + $student = $this->sandbox->prepare($context->getStudentExecutionDirectory(), $scenario->exposesPort()); $result = new CliResult( array_map( - function (Collection $args) use ($context, $scenario, $referencePort, $studentPort) { - return $this->doVerify($context, $scenario, $args, $referencePort, $studentPort); + function (Collection $args) use ($context, $scenario, $reference, $student) { + return $this->doVerify($context, $scenario, $args, $reference, $student); }, $scenario->getExecutions(), ), @@ -129,21 +129,20 @@ function (Collection $args) use ($context, $scenario, $referencePort, $studentPo /** * @param Collection $args */ - private function doVerify(ExecutionContext $context, CliScenario $scenario, Collection $args, ?int $referencePort, ?int $studentPort): CliResultInterface + private function doVerify(ExecutionContext $context, CliScenario $scenario, Collection $args, Workspace $reference, Workspace $student): CliResultInterface { try { /** @var CliExecuteEvent $event */ $event = $this->eventDispatcher->dispatch( - new CliExecuteEvent('cli.verify.reference-execute.pre', $context, $scenario, $args, ['port' => $referencePort]), + new CliExecuteEvent('cli.verify.reference-execute.pre', $context, $scenario, $args, ['workspace' => $reference]), ); $solutionOutput = $this->executePhpFile( $context, $scenario, - $context->getReferenceExecutionDirectory(), + $reference, $this->exercise->getSolution()->getEntryPoint()->getRelativePath(), $event->getArgs(), 'reference', - $referencePort, ); } catch (CodeExecutionException $e) { $this->eventDispatcher->dispatch( @@ -161,16 +160,15 @@ private function doVerify(ExecutionContext $context, CliScenario $scenario, Coll try { /** @var CliExecuteEvent $event */ $event = $this->eventDispatcher->dispatch( - new CliExecuteEvent('cli.verify.student-execute.pre', $context, $scenario, $args, ['port' => $studentPort]), + new CliExecuteEvent('cli.verify.student-execute.pre', $context, $scenario, $args, ['workspace' => $student]), ); $userOutput = $this->executePhpFile( $context, $scenario, - $context->getStudentExecutionDirectory(), + $student, basename($context->getEntryPoint()), $event->getArgs(), 'student', - $studentPort, ); } catch (CodeExecutionException $e) { $this->eventDispatcher->dispatch( @@ -217,23 +215,18 @@ public function run(ExecutionContext $context, OutputInterface $output): bool $this->eventDispatcher->dispatch(new CliExerciseRunnerEvent('cli.run.start', $context, $scenario)); - $port = $this->pickPort($scenario); + $student = $this->sandbox->prepare($context->getStudentExecutionDirectory(), $scenario->exposesPort()); $success = true; foreach ($scenario->getExecutions() as $i => $args) { /** @var CliExecuteEvent $event */ $event = $this->eventDispatcher->dispatch( - new CliExecuteEvent('cli.run.student-execute.pre', $context, $scenario, $args, ['port' => $port]), + new CliExecuteEvent('cli.run.student-execute.pre', $context, $scenario, $args, ['workspace' => $student]), ); $args = $event->getArgs(); - $execution = $this->getPhpExecution( - $context->getStudentExecutionDirectory(), - basename($context->getEntryPoint()), - $args, - $port, - ); + $execution = $this->getPhpExecution($student, basename($context->getEntryPoint()), $args); $execution->start(); $this->eventDispatcher->dispatch( @@ -264,9 +257,9 @@ public function run(ExecutionContext $context, OutputInterface $output): bool /** * @param Collection $args */ - private function executePhpFile(ExecutionContext $context, CliScenario $scenario, string $workingDirectory, string $fileName, Collection $args, string $type, ?int $port): string + private function executePhpFile(ExecutionContext $context, CliScenario $scenario, Workspace $workspace, string $fileName, Collection $args, string $type): string { - $execution = $this->getPhpExecution($workingDirectory, $fileName, $args, $port); + $execution = $this->getPhpExecution($workspace, $fileName, $args); $execution->start(); $this->eventDispatcher->dispatch( @@ -284,15 +277,8 @@ private function executePhpFile(ExecutionContext $context, CliScenario $scenario /** * @param Collection $args */ - private function getPhpExecution(string $workingDirectory, string $fileName, Collection $args, ?int $port): SandboxExecution - { - return $this->sandbox->create( - new ProcessInput('php', [$fileName, ...$args->getArrayCopy()], $workingDirectory, [], $port), - ); - } - - private function pickPort(CliScenario $scenario): ?int + private function getPhpExecution(Workspace $workspace, string $fileName, Collection $args): SandboxExecution { - return $scenario->exposesPort() ? $this->sandbox->pickPort() : null; + return $this->sandbox->create($workspace, new ProcessInput('php', [$fileName, ...$args->getArrayCopy()], [])); } } diff --git a/src/Process/DockerSandbox.php b/src/Process/DockerSandbox.php index 23e7437a..d7506693 100644 --- a/src/Process/DockerSandbox.php +++ b/src/Process/DockerSandbox.php @@ -62,17 +62,17 @@ public function createBuildProcess(): Process ); } - public function pickPort(): int + public function prepare(string $directory, bool $exposePort): Workspace { - return $this->portPicker->pick(); + return new Workspace($directory, $exposePort ? $this->portPicker->pick() : null); } - public function create(ProcessInput $processInput): DockerExecution + public function create(Workspace $workspace, ProcessInput $processInput): DockerExecution { $network = ['--network', 'none']; - $port = $processInput->getPort(); + $port = $workspace->port; if ($port !== null) { - //the same port on the docker host, pickPort() picked one free there + //the same port on the docker host, prepare() picked one free there $network = ['--network', $this->portsNetwork, '-p', $this->portsHost . ':' . $port . ':' . $port]; } @@ -110,7 +110,7 @@ public function create(ProcessInput $processInput): DockerExecution '1', ...$envArgs, '-v', - $processInput->getWorkingDirectory() . ':/solution', + $workspace->directory . ':/solution', '-w', '/solution', $this->getImageName(), diff --git a/src/Process/HostSandbox.php b/src/Process/HostSandbox.php index 6b6ca585..868bd780 100644 --- a/src/Process/HostSandbox.php +++ b/src/Process/HostSandbox.php @@ -21,12 +21,12 @@ public function __construct(?ExecutableFinder $executableFinder = null) $this->executableFinder = $executableFinder ?? new ExecutableFinder(); } - public function pickPort(): int + public function prepare(string $directory, bool $exposePort): Workspace { - return (new FreePortPicker())->pick(); + return new Workspace($directory, $exposePort ? (new FreePortPicker())->pick() : null); } - public function create(ProcessInput $processInput): HostExecution + public function create(Workspace $workspace, ProcessInput $processInput): HostExecution { $executablePath = $this->executableFinder->find($processInput->getExecutable()); @@ -36,11 +36,11 @@ public function create(ProcessInput $processInput): HostExecution return new HostExecution(new Process( [$executablePath, ...$processInput->getArgs()], - $processInput->getWorkingDirectory(), + $workspace->directory, array_merge($this->getDefaultEnv(), $processInput->getEnv()), $processInput->getInput(), 10, - ), $processInput->getPort()); + ), $workspace->port); } /** diff --git a/src/Process/ProcessInput.php b/src/Process/ProcessInput.php index 8c476154..605e4dfc 100644 --- a/src/Process/ProcessInput.php +++ b/src/Process/ProcessInput.php @@ -7,14 +7,11 @@ class ProcessInput /** * @param list $args * @param array $env - * @param int|null $port the code listens on, eg. 54321 */ public function __construct( private string $executable, private array $args, - private string $workingDirectory, private array $env, - private ?int $port, private ?string $input = null, ) {} @@ -31,11 +28,6 @@ public function getArgs(): array return $this->args; } - public function getWorkingDirectory(): string - { - return $this->workingDirectory; - } - /** * @return array */ @@ -44,11 +36,6 @@ public function getEnv(): array return $this->env; } - public function getPort(): ?int - { - return $this->port; - } - public function getInput(): ?string { return $this->input; diff --git a/src/Process/Sandbox.php b/src/Process/Sandbox.php index a3337170..f3774357 100644 --- a/src/Process/Sandbox.php +++ b/src/Process/Sandbox.php @@ -6,10 +6,10 @@ interface Sandbox { - public function create(ProcessInput $processInput): SandboxExecution; + public function create(Workspace $workspace, ProcessInput $processInput): SandboxExecution; /** - * A port for code to listen on, free where this sandbox runs it. + * Sets up a solution's directory before its runs, with a port free where this sandbox runs it when asked for. */ - public function pickPort(): int; + public function prepare(string $directory, bool $exposePort): Workspace; } diff --git a/src/Process/Workspace.php b/src/Process/Workspace.php new file mode 100644 index 00000000..c898d923 --- /dev/null +++ b/src/Process/Workspace.php @@ -0,0 +1,16 @@ +eventDispatcher->listen( ['cli.verify.reference-execute.pre', 'cli.verify.student-execute.pre'], function (CliExecuteEvent $event) use (&$ports) { - $ports[$event->getName()][] = $event->getPort(); + $ports[$event->getName()][] = $event->getWorkspace()->port; }, ); @@ -221,16 +222,16 @@ public function testRunPassesTheEntryPointRelativeToTheWorkingDirectory(): void /** @var array */ public array $inputs = []; - public function create(ProcessInput $processInput): SandboxExecution + public function create(Workspace $workspace, ProcessInput $processInput): SandboxExecution { $this->inputs[] = $processInput; - return (new HostSandbox())->create($processInput); + return (new HostSandbox())->create($workspace, $processInput); } - public function pickPort(): int + public function prepare(string $directory, bool $exposePort): Workspace { - return 54321; + return new Workspace($directory, $exposePort ? 54321 : null); } }; $runner = new CliRunner($this->exercise, $this->eventDispatcher, $sandbox, new EnvironmentManager(new Filesystem(), $this->eventDispatcher)); diff --git a/test/Process/DockerSandboxTest.php b/test/Process/DockerSandboxTest.php index 195eef0b..555070c3 100644 --- a/test/Process/DockerSandboxTest.php +++ b/test/Process/DockerSandboxTest.php @@ -5,6 +5,7 @@ use PhpSchool\PhpWorkshop\Process\DockerSandbox; use PhpSchool\PhpWorkshop\Process\PortPicker; use PhpSchool\PhpWorkshop\Process\ProcessInput; +use PhpSchool\PhpWorkshop\Process\Workspace; use PhpSchool\PhpWorkshop\Process\ProcessNotFoundException; use PHPUnit\Framework\TestCase; use Symfony\Component\Process\ExecutableFinder; @@ -61,14 +62,14 @@ public function testCreateThrowsExceptionIfDockerNotFound(): void ->willReturn(null); $factory = new DockerSandbox('/docker-dir', 'php8appreciate', $finder); - $input = new ProcessInput('php', [], __DIR__, [], null); + $input = new ProcessInput('php', [], []); - $factory->create($input); + $factory->create(new Workspace(__DIR__), $input); } public function testCreateIsIsolatedWithNoNetwork(): void { - $process = $this->factory()->create(new ProcessInput('php', ['one', 'two'], __DIR__, [], null))->process; + $process = $this->factory()->create(new Workspace(__DIR__), new ProcessInput('php', ['one', 'two'], []))->process; $expected = $this->expectedCommand( ['--network', 'none'], @@ -82,7 +83,7 @@ public function testCreateIsIsolatedWithNoNetwork(): void public function testExposedPortsArePublishedOnLoopbackOnly(): void { - $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, [], 8000))->process; + $process = $this->factory()->create(new Workspace(__DIR__, 8000), new ProcessInput('php', [], []))->process; $expected = $this->expectedCommand( ['--network', 'bridge', '-p', '127.0.0.1:8000:8000'], @@ -94,7 +95,7 @@ public function testExposedPortsArePublishedOnLoopbackOnly(): void public function testExposedPortsUseTheGivenNetwork(): void { - $process = $this->factory('php-school-sandbox')->create(new ProcessInput('php', [], __DIR__, [], 8000))->process; + $process = $this->factory('php-school-sandbox')->create(new Workspace(__DIR__, 8000), new ProcessInput('php', [], []))->process; $expected = $this->expectedCommand( ['--network', 'php-school-sandbox', '-p', '127.0.0.1:8000:8000'], @@ -106,7 +107,7 @@ public function testExposedPortsUseTheGivenNetwork(): void public function testExposedPortsArePublishedOnTheGivenHost(): void { - $process = $this->factory('bridge', '172.19.0.2')->create(new ProcessInput('php', [], __DIR__, [], 8000))->process; + $process = $this->factory('bridge', '172.19.0.2')->create(new Workspace(__DIR__, 8000), new ProcessInput('php', [], []))->process; $expected = $this->expectedCommand( ['--network', 'bridge', '-p', '172.19.0.2:8000:8000'], @@ -121,22 +122,22 @@ public function testPortsArePickedWithThePortPicker(): void $ports = $this->createMock(PortPicker::class); $ports->method('pick')->willReturn(47213); - static::assertSame(47213, (new DockerSandbox('/docker-dir', 'php8appreciate', portPicker: $ports))->pickPort()); + static::assertSame(47213, (new DockerSandbox('/docker-dir', 'php8appreciate', portPicker: $ports))->prepare(__DIR__, true)->port); } public function testAddressIsTheSamePortOnTheGivenHost(): void { - $execution = $this->factory('bridge', '172.19.0.2')->create(new ProcessInput('php', [], __DIR__, [], 47213)); + $execution = $this->factory('bridge', '172.19.0.2')->create(new Workspace(__DIR__, 47213), new ProcessInput('php', [], [])); static::assertSame('172.19.0.2:47213', $execution->getAddress()); - $execution = $this->factory('bridge', '[fdaa::2]')->create(new ProcessInput('php', [], __DIR__, [], 47213)); + $execution = $this->factory('bridge', '[fdaa::2]')->create(new Workspace(__DIR__, 47213), new ProcessInput('php', [], [])); static::assertStringContainsString("'-p' '[fdaa::2]:47213:47213'", $execution->process->getCommandLine()); static::assertSame('[fdaa::2]:47213', $execution->getAddress()); } public function testCreateWithEnv(): void { - $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, ['SOME_VAR' => 'value'], null))->process; + $process = $this->factory()->create(new Workspace(__DIR__), new ProcessInput('php', [], ['SOME_VAR' => 'value']))->process; $expected = $this->expectedCommand( ['--network', 'none'], @@ -148,7 +149,7 @@ public function testCreateWithEnv(): void public function testWithInput(): void { - $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, [], null, 'someinput'))->process; + $process = $this->factory()->create(new Workspace(__DIR__), new ProcessInput('php', [], [], 'someinput'))->process; static::assertSame('someinput', $process->getInput()); } diff --git a/test/Process/HostSandboxTest.php b/test/Process/HostSandboxTest.php index 2bc11119..bd81535a 100644 --- a/test/Process/HostSandboxTest.php +++ b/test/Process/HostSandboxTest.php @@ -3,6 +3,7 @@ namespace PhpSchool\PhpWorkshopTest\Process; use PhpSchool\PhpWorkshop\Process\ProcessInput; +use PhpSchool\PhpWorkshop\Process\Workspace; use PhpSchool\PhpWorkshop\Process\ProcessNotFoundException; use Symfony\Component\Process\ExecutableFinder; use PhpSchool\PhpWorkshop\Process\HostSandbox; @@ -21,9 +22,9 @@ public function testCreateThrowsExceptionIfExecutableNotFound(): void ->willReturn(null); $factory = new HostSandbox($finder); - $input = new ProcessInput('composer', [], __DIR__, [], null); + $input = new ProcessInput('composer', [], []); - $factory->create($input); + $factory->create(new Workspace(__DIR__), $input); } public function testCreate(): void @@ -35,22 +36,22 @@ public function testCreate(): void ->willReturn('/usr/local/bin/composer'); $factory = new HostSandbox($finder); - $input = new ProcessInput('composer', [], __DIR__, [], null); + $input = new ProcessInput('composer', [], []); - $process = $factory->create($input)->process; + $process = $factory->create(new Workspace(__DIR__), $input)->process; static::assertSame("'/usr/local/bin/composer'", $process->getCommandLine()); } public function testPickedPortIsFreeOnThisMachine(): void { - $server = stream_socket_server('tcp://127.0.0.1:' . (new HostSandbox())->pickPort()); + $server = stream_socket_server('tcp://127.0.0.1:' . (new HostSandbox())->prepare(__DIR__, true)->port); static::assertNotFalse($server); fclose($server); } public function testAddressIsThePortOnThisMachine(): void { - $execution = (new HostSandbox())->create(new ProcessInput('php', [], __DIR__, [], 54321)); + $execution = (new HostSandbox())->create(new Workspace(__DIR__, 54321), new ProcessInput('php', [], [])); static::assertSame('127.0.0.1:54321', $execution->getAddress()); } @@ -64,9 +65,9 @@ public function testCreateWithArgs(): void ->willReturn('/usr/local/bin/composer'); $factory = new HostSandbox($finder); - $input = new ProcessInput('composer', ['one', 'two'], __DIR__, [], null); + $input = new ProcessInput('composer', ['one', 'two'], []); - $process = $factory->create($input)->process; + $process = $factory->create(new Workspace(__DIR__), $input)->process; static::assertSame("'/usr/local/bin/composer' 'one' 'two'", $process->getCommandLine()); } @@ -79,9 +80,9 @@ public function testCreateWithEnv(): void ->willReturn('/usr/local/bin/composer'); $factory = new HostSandbox($finder); - $input = new ProcessInput('composer', ['one', 'two'], __DIR__, ['SOME_VAR' => 'value'], null); + $input = new ProcessInput('composer', ['one', 'two'], ['SOME_VAR' => 'value']); - $process = $factory->create($input)->process; + $process = $factory->create(new Workspace(__DIR__), $input)->process; static::assertSame('value', $process->getEnv()['SOME_VAR']); } @@ -91,7 +92,8 @@ public function testInheritedEnvIsRemovedExceptAllowed(): void try { $process = (new HostSandbox())->create( - new ProcessInput('php', ['-r', 'echo json_encode([getenv("PHPSCHOOL_SECRET"), getenv("PATH") !== false]);'], __DIR__, [], null), + new Workspace(__DIR__), + new ProcessInput('php', ['-r', 'echo json_encode([getenv("PHPSCHOOL_SECRET"), getenv("PATH") !== false]);'], []), ); $process->mustRun(); @@ -110,9 +112,9 @@ public function testWithInput(): void ->willReturn('/usr/local/bin/composer'); $factory = new HostSandbox($finder); - $input = new ProcessInput('composer', [], __DIR__, [], null, 'someinput'); + $input = new ProcessInput('composer', [], [], 'someinput'); - $process = $factory->create($input)->process; + $process = $factory->create(new Workspace(__DIR__), $input)->process; static::assertSame('someinput', $process->getInput()); } } diff --git a/test/Process/ProcessInputTest.php b/test/Process/ProcessInputTest.php index 2f68ff61..aa57c96f 100644 --- a/test/Process/ProcessInputTest.php +++ b/test/Process/ProcessInputTest.php @@ -9,13 +9,11 @@ class ProcessInputTest extends TestCase { public function testProcessInput(): void { - $input = new ProcessInput('composer', ['one', 'two'], __DIR__, ['SOME_VAR' => 'value'], null, 'input'); + $input = new ProcessInput('composer', ['one', 'two'], ['SOME_VAR' => 'value'], 'input'); static::assertSame('composer', $input->getExecutable()); static::assertSame(['one', 'two'], $input->getArgs()); - static::assertSame(__DIR__, $input->getWorkingDirectory()); static::assertSame(['SOME_VAR' => 'value'], $input->getEnv()); - static::assertNull($input->getPort()); static::assertSame('input', $input->getInput()); } } From 71024660f93042b37c11210412161c1c7e480404 Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 13:51:18 +0100 Subject: [PATCH 04/10] prepare() takes the scenario instead of a bool --- src/ExerciseRunner/CgiRunner.php | 6 +++--- src/ExerciseRunner/CliRunner.php | 6 +++--- src/Process/DockerSandbox.php | 5 +++-- src/Process/HostSandbox.php | 5 +++-- src/Process/Sandbox.php | 6 ++++-- test/ExerciseRunner/CliRunnerTest.php | 5 +++-- test/Process/DockerSandboxTest.php | 3 ++- test/Process/HostSandboxTest.php | 3 ++- 8 files changed, 23 insertions(+), 16 deletions(-) diff --git a/src/ExerciseRunner/CgiRunner.php b/src/ExerciseRunner/CgiRunner.php index 0a7dfde9..6663ce4b 100644 --- a/src/ExerciseRunner/CgiRunner.php +++ b/src/ExerciseRunner/CgiRunner.php @@ -110,8 +110,8 @@ public function verify(ExecutionContext $context): ResultInterface $this->eventDispatcher->dispatch(new CgiExerciseRunnerEvent('cgi.verify.start', $context, $scenario)); - $reference = $this->sandbox->prepare($context->getReferenceExecutionDirectory(), false); - $student = $this->sandbox->prepare($context->getStudentExecutionDirectory(), false); + $reference = $this->sandbox->prepare($context->getReferenceExecutionDirectory(), $scenario); + $student = $this->sandbox->prepare($context->getStudentExecutionDirectory(), $scenario); $result = new CgiResult( array_map( @@ -301,7 +301,7 @@ public function run(ExecutionContext $context, OutputInterface $output): bool $this->eventDispatcher->dispatch(new CgiExerciseRunnerEvent('cgi.run.start', $context, $scenario)); - $student = $this->sandbox->prepare($context->getStudentExecutionDirectory(), false); + $student = $this->sandbox->prepare($context->getStudentExecutionDirectory(), $scenario); $success = true; foreach ($scenario->getExecutions() as $i => $request) { diff --git a/src/ExerciseRunner/CliRunner.php b/src/ExerciseRunner/CliRunner.php index bc3d5ddb..3f159790 100644 --- a/src/ExerciseRunner/CliRunner.php +++ b/src/ExerciseRunner/CliRunner.php @@ -109,8 +109,8 @@ public function verify(ExecutionContext $context): ResultInterface $this->eventDispatcher->dispatch(new CliExerciseRunnerEvent('cli.verify.start', $context, $scenario)); - $reference = $this->sandbox->prepare($context->getReferenceExecutionDirectory(), $scenario->exposesPort()); - $student = $this->sandbox->prepare($context->getStudentExecutionDirectory(), $scenario->exposesPort()); + $reference = $this->sandbox->prepare($context->getReferenceExecutionDirectory(), $scenario); + $student = $this->sandbox->prepare($context->getStudentExecutionDirectory(), $scenario); $result = new CliResult( array_map( @@ -215,7 +215,7 @@ public function run(ExecutionContext $context, OutputInterface $output): bool $this->eventDispatcher->dispatch(new CliExerciseRunnerEvent('cli.run.start', $context, $scenario)); - $student = $this->sandbox->prepare($context->getStudentExecutionDirectory(), $scenario->exposesPort()); + $student = $this->sandbox->prepare($context->getStudentExecutionDirectory(), $scenario); $success = true; foreach ($scenario->getExecutions() as $i => $args) { diff --git a/src/Process/DockerSandbox.php b/src/Process/DockerSandbox.php index d7506693..0b7183f2 100644 --- a/src/Process/DockerSandbox.php +++ b/src/Process/DockerSandbox.php @@ -4,6 +4,7 @@ namespace PhpSchool\PhpWorkshop\Process; +use PhpSchool\PhpWorkshop\Exercise\Scenario\ExerciseScenario; use Symfony\Component\Process\ExecutableFinder; use Symfony\Component\Process\Process; @@ -62,9 +63,9 @@ public function createBuildProcess(): Process ); } - public function prepare(string $directory, bool $exposePort): Workspace + public function prepare(string $directory, ExerciseScenario $scenario): Workspace { - return new Workspace($directory, $exposePort ? $this->portPicker->pick() : null); + return new Workspace($directory, $scenario->exposesPort() ? $this->portPicker->pick() : null); } public function create(Workspace $workspace, ProcessInput $processInput): DockerExecution diff --git a/src/Process/HostSandbox.php b/src/Process/HostSandbox.php index 868bd780..a6047228 100644 --- a/src/Process/HostSandbox.php +++ b/src/Process/HostSandbox.php @@ -4,6 +4,7 @@ namespace PhpSchool\PhpWorkshop\Process; +use PhpSchool\PhpWorkshop\Exercise\Scenario\ExerciseScenario; use Symfony\Component\Process\ExecutableFinder; use Symfony\Component\Process\Process; @@ -21,9 +22,9 @@ public function __construct(?ExecutableFinder $executableFinder = null) $this->executableFinder = $executableFinder ?? new ExecutableFinder(); } - public function prepare(string $directory, bool $exposePort): Workspace + public function prepare(string $directory, ExerciseScenario $scenario): Workspace { - return new Workspace($directory, $exposePort ? (new FreePortPicker())->pick() : null); + return new Workspace($directory, $scenario->exposesPort() ? (new FreePortPicker())->pick() : null); } public function create(Workspace $workspace, ProcessInput $processInput): HostExecution diff --git a/src/Process/Sandbox.php b/src/Process/Sandbox.php index f3774357..d1973a41 100644 --- a/src/Process/Sandbox.php +++ b/src/Process/Sandbox.php @@ -4,12 +4,14 @@ namespace PhpSchool\PhpWorkshop\Process; +use PhpSchool\PhpWorkshop\Exercise\Scenario\ExerciseScenario; + interface Sandbox { public function create(Workspace $workspace, ProcessInput $processInput): SandboxExecution; /** - * Sets up a solution's directory before its runs, with a port free where this sandbox runs it when asked for. + * Sets up a solution's directory before its runs, with a port free where this sandbox runs it when the scenario exposes one. */ - public function prepare(string $directory, bool $exposePort): Workspace; + public function prepare(string $directory, ExerciseScenario $scenario): Workspace; } diff --git a/test/ExerciseRunner/CliRunnerTest.php b/test/ExerciseRunner/CliRunnerTest.php index d1a3046a..da7fefca 100644 --- a/test/ExerciseRunner/CliRunnerTest.php +++ b/test/ExerciseRunner/CliRunnerTest.php @@ -5,6 +5,7 @@ use Colors\Color; use PhpSchool\PhpWorkshop\Check\CodeExistsCheck; use PhpSchool\PhpWorkshop\Exercise\Scenario\CliScenario; +use PhpSchool\PhpWorkshop\Exercise\Scenario\ExerciseScenario; use PhpSchool\PhpWorkshop\ExerciseRunner\Context\TestContext; use PhpSchool\PhpWorkshop\ExerciseRunner\EnvironmentManager; use PhpSchool\PhpWorkshop\Listener\OutputRunInfoListener; @@ -229,9 +230,9 @@ public function create(Workspace $workspace, ProcessInput $processInput): Sandbo return (new HostSandbox())->create($workspace, $processInput); } - public function prepare(string $directory, bool $exposePort): Workspace + public function prepare(string $directory, ExerciseScenario $scenario): Workspace { - return new Workspace($directory, $exposePort ? 54321 : null); + return new Workspace($directory, $scenario->exposesPort() ? 54321 : null); } }; $runner = new CliRunner($this->exercise, $this->eventDispatcher, $sandbox, new EnvironmentManager(new Filesystem(), $this->eventDispatcher)); diff --git a/test/Process/DockerSandboxTest.php b/test/Process/DockerSandboxTest.php index 555070c3..a3865e56 100644 --- a/test/Process/DockerSandboxTest.php +++ b/test/Process/DockerSandboxTest.php @@ -4,6 +4,7 @@ use PhpSchool\PhpWorkshop\Process\DockerSandbox; use PhpSchool\PhpWorkshop\Process\PortPicker; +use PhpSchool\PhpWorkshop\Exercise\Scenario\CliScenario; use PhpSchool\PhpWorkshop\Process\ProcessInput; use PhpSchool\PhpWorkshop\Process\Workspace; use PhpSchool\PhpWorkshop\Process\ProcessNotFoundException; @@ -122,7 +123,7 @@ public function testPortsArePickedWithThePortPicker(): void $ports = $this->createMock(PortPicker::class); $ports->method('pick')->willReturn(47213); - static::assertSame(47213, (new DockerSandbox('/docker-dir', 'php8appreciate', portPicker: $ports))->prepare(__DIR__, true)->port); + static::assertSame(47213, (new DockerSandbox('/docker-dir', 'php8appreciate', portPicker: $ports))->prepare(__DIR__, (new CliScenario())->exposePort())->port); } public function testAddressIsTheSamePortOnTheGivenHost(): void diff --git a/test/Process/HostSandboxTest.php b/test/Process/HostSandboxTest.php index bd81535a..5d2bd4d6 100644 --- a/test/Process/HostSandboxTest.php +++ b/test/Process/HostSandboxTest.php @@ -2,6 +2,7 @@ namespace PhpSchool\PhpWorkshopTest\Process; +use PhpSchool\PhpWorkshop\Exercise\Scenario\CliScenario; use PhpSchool\PhpWorkshop\Process\ProcessInput; use PhpSchool\PhpWorkshop\Process\Workspace; use PhpSchool\PhpWorkshop\Process\ProcessNotFoundException; @@ -44,7 +45,7 @@ public function testCreate(): void public function testPickedPortIsFreeOnThisMachine(): void { - $server = stream_socket_server('tcp://127.0.0.1:' . (new HostSandbox())->prepare(__DIR__, true)->port); + $server = stream_socket_server('tcp://127.0.0.1:' . (new HostSandbox())->prepare(__DIR__, (new CliScenario())->exposePort())->port); static::assertNotFalse($server); fclose($server); } From 20af8d21844ec2f233c60e8b3085b2ebecf04190 Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 13:56:25 +0100 Subject: [PATCH 05/10] Move the port pickers to Process\Port --- src/Process/DockerSandbox.php | 2 ++ src/Process/HostSandbox.php | 1 + src/Process/{ => Port}/FreePortPicker.php | 2 +- src/Process/{ => Port}/LockPortPicker.php | 2 +- src/Process/{ => Port}/PortPicker.php | 2 +- test/Process/DockerSandboxTest.php | 2 +- test/Process/{ => Port}/FreePortPickerTest.php | 4 ++-- test/Process/{ => Port}/LockPortPickerTest.php | 4 ++-- 8 files changed, 11 insertions(+), 8 deletions(-) rename src/Process/{ => Port}/FreePortPicker.php (93%) rename src/Process/{ => Port}/LockPortPicker.php (95%) rename src/Process/{ => Port}/PortPicker.php (81%) rename test/Process/{ => Port}/FreePortPickerTest.php (76%) rename test/Process/{ => Port}/LockPortPickerTest.php (85%) diff --git a/src/Process/DockerSandbox.php b/src/Process/DockerSandbox.php index 0b7183f2..d0d3eda8 100644 --- a/src/Process/DockerSandbox.php +++ b/src/Process/DockerSandbox.php @@ -5,6 +5,8 @@ namespace PhpSchool\PhpWorkshop\Process; use PhpSchool\PhpWorkshop\Exercise\Scenario\ExerciseScenario; +use PhpSchool\PhpWorkshop\Process\Port\FreePortPicker; +use PhpSchool\PhpWorkshop\Process\Port\PortPicker; use Symfony\Component\Process\ExecutableFinder; use Symfony\Component\Process\Process; diff --git a/src/Process/HostSandbox.php b/src/Process/HostSandbox.php index a6047228..12511400 100644 --- a/src/Process/HostSandbox.php +++ b/src/Process/HostSandbox.php @@ -5,6 +5,7 @@ namespace PhpSchool\PhpWorkshop\Process; use PhpSchool\PhpWorkshop\Exercise\Scenario\ExerciseScenario; +use PhpSchool\PhpWorkshop\Process\Port\FreePortPicker; use Symfony\Component\Process\ExecutableFinder; use Symfony\Component\Process\Process; diff --git a/src/Process/FreePortPicker.php b/src/Process/Port/FreePortPicker.php similarity index 93% rename from src/Process/FreePortPicker.php rename to src/Process/Port/FreePortPicker.php index 1ace14f4..09d1de5e 100644 --- a/src/Process/FreePortPicker.php +++ b/src/Process/Port/FreePortPicker.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace PhpSchool\PhpWorkshop\Process; +namespace PhpSchool\PhpWorkshop\Process\Port; use PhpSchool\PhpWorkshop\Exception\RuntimeException; diff --git a/src/Process/LockPortPicker.php b/src/Process/Port/LockPortPicker.php similarity index 95% rename from src/Process/LockPortPicker.php rename to src/Process/Port/LockPortPicker.php index 018a65db..b73bf175 100644 --- a/src/Process/LockPortPicker.php +++ b/src/Process/Port/LockPortPicker.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace PhpSchool\PhpWorkshop\Process; +namespace PhpSchool\PhpWorkshop\Process\Port; use PhpSchool\PhpWorkshop\Exception\RuntimeException; use Symfony\Component\Lock\LockFactory; diff --git a/src/Process/PortPicker.php b/src/Process/Port/PortPicker.php similarity index 81% rename from src/Process/PortPicker.php rename to src/Process/Port/PortPicker.php index 97e3fb89..daf9337a 100644 --- a/src/Process/PortPicker.php +++ b/src/Process/Port/PortPicker.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace PhpSchool\PhpWorkshop\Process; +namespace PhpSchool\PhpWorkshop\Process\Port; /** * Picks a port, eg. the one an exercise's code listens on, or the one DockerSandbox publishes it on. diff --git a/test/Process/DockerSandboxTest.php b/test/Process/DockerSandboxTest.php index a3865e56..02a8373e 100644 --- a/test/Process/DockerSandboxTest.php +++ b/test/Process/DockerSandboxTest.php @@ -3,7 +3,7 @@ namespace PhpSchool\PhpWorkshopTest\Process; use PhpSchool\PhpWorkshop\Process\DockerSandbox; -use PhpSchool\PhpWorkshop\Process\PortPicker; +use PhpSchool\PhpWorkshop\Process\Port\PortPicker; use PhpSchool\PhpWorkshop\Exercise\Scenario\CliScenario; use PhpSchool\PhpWorkshop\Process\ProcessInput; use PhpSchool\PhpWorkshop\Process\Workspace; diff --git a/test/Process/FreePortPickerTest.php b/test/Process/Port/FreePortPickerTest.php similarity index 76% rename from test/Process/FreePortPickerTest.php rename to test/Process/Port/FreePortPickerTest.php index 7ead740e..f178bcb7 100644 --- a/test/Process/FreePortPickerTest.php +++ b/test/Process/Port/FreePortPickerTest.php @@ -2,9 +2,9 @@ declare(strict_types=1); -namespace PhpSchool\PhpWorkshopTest\Process; +namespace PhpSchool\PhpWorkshopTest\Process\Port; -use PhpSchool\PhpWorkshop\Process\FreePortPicker; +use PhpSchool\PhpWorkshop\Process\Port\FreePortPicker; use PHPUnit\Framework\TestCase; class FreePortPickerTest extends TestCase diff --git a/test/Process/LockPortPickerTest.php b/test/Process/Port/LockPortPickerTest.php similarity index 85% rename from test/Process/LockPortPickerTest.php rename to test/Process/Port/LockPortPickerTest.php index 3d05075e..7f88300f 100644 --- a/test/Process/LockPortPickerTest.php +++ b/test/Process/Port/LockPortPickerTest.php @@ -2,9 +2,9 @@ declare(strict_types=1); -namespace PhpSchool\PhpWorkshopTest\Process; +namespace PhpSchool\PhpWorkshopTest\Process\Port; -use PhpSchool\PhpWorkshop\Process\LockPortPicker; +use PhpSchool\PhpWorkshop\Process\Port\LockPortPicker; use PHPUnit\Framework\TestCase; use Symfony\Component\Lock\LockFactory; use Symfony\Component\Lock\Store\InMemoryStore; From a372dfd2d91206e4951895b1998ac177db4384e6 Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 14:09:21 +0100 Subject: [PATCH 06/10] SandboxFactory makes a Sandbox per solution, which makes a SandboxExecution per run --- app/config.php | 16 ++-- src/Event/CliExecuteEvent.php | 12 +-- src/Exercise/Scenario/ExerciseScenario.php | 2 +- src/ExerciseRunner/CgiRunner.php | 20 ++-- src/ExerciseRunner/CliRunner.php | 26 +++--- .../Factory/CgiRunnerFactory.php | 6 +- .../Factory/CliRunnerFactory.php | 6 +- src/Process/DockerSandbox.php | 93 +++++-------------- ...ecution.php => DockerSandboxExecution.php} | 2 +- src/Process/DockerSandboxFactory.php | 80 ++++++++++++++++ src/Process/HostSandbox.php | 30 +++--- ...Execution.php => HostSandboxExecution.php} | 2 +- src/Process/HostSandboxFactory.php | 21 +++++ src/Process/Sandbox.php | 11 ++- src/Process/SandboxFactory.php | 18 ++++ src/Process/Workspace.php | 16 ---- test/Check/DatabaseCheckTest.php | 4 +- test/ExerciseRunner/CgiRunnerTest.php | 4 +- test/ExerciseRunner/CliRunnerTest.php | 24 +++-- .../Factory/CgiRunnerFactoryTest.php | 4 +- .../Factory/CliRunnerFactoryTest.php | 4 +- ...est.php => DockerSandboxExecutionTest.php} | 8 +- test/Process/DockerSandboxTest.php | 35 ++++--- test/Process/HostSandboxTest.php | 32 +++---- 24 files changed, 266 insertions(+), 210 deletions(-) rename src/Process/{DockerExecution.php => DockerSandboxExecution.php} (97%) create mode 100644 src/Process/DockerSandboxFactory.php rename src/Process/{HostExecution.php => HostSandboxExecution.php} (94%) create mode 100644 src/Process/HostSandboxFactory.php create mode 100644 src/Process/SandboxFactory.php delete mode 100644 src/Process/Workspace.php rename test/Process/{DockerExecutionTest.php => DockerSandboxExecutionTest.php} (84%) diff --git a/app/config.php b/app/config.php index cb047456..4dae5a15 100644 --- a/app/config.php +++ b/app/config.php @@ -72,9 +72,9 @@ use PhpSchool\PhpWorkshop\Output\StdOutput; use PhpSchool\PhpWorkshop\Patch; use PhpSchool\PhpWorkshop\Process\Composer; -use PhpSchool\PhpWorkshop\Process\DockerSandbox; -use PhpSchool\PhpWorkshop\Process\HostSandbox; -use PhpSchool\PhpWorkshop\Process\Sandbox; +use PhpSchool\PhpWorkshop\Process\DockerSandboxFactory; +use PhpSchool\PhpWorkshop\Process\HostSandboxFactory; +use PhpSchool\PhpWorkshop\Process\SandboxFactory; use PhpSchool\PhpWorkshop\Result\Cgi\CgiResult; use PhpSchool\PhpWorkshop\Result\Cgi\GenericFailure as CgiGenericFailure; use PhpSchool\PhpWorkshop\Result\Cgi\RequestFailure as CgiRequestFailure; @@ -199,27 +199,27 @@ $manager = new RunnerManager(); $manager->addFactory(new CliRunnerFactory( $c->get(EventDispatcher::class), - $c->get(Sandbox::class), + $c->get(SandboxFactory::class), $c->get(EnvironmentManager::class), )); $manager->addFactory(new CgiRunnerFactory( $c->get(EventDispatcher::class), - $c->get(Sandbox::class), + $c->get(SandboxFactory::class), $c->get(EnvironmentManager::class), )); $manager->addFactory(new CustomVerifyingRunnerFactory()); return $manager; }, - Sandbox::class => function (ContainerInterface $c) { + SandboxFactory::class => function (ContainerInterface $c) { $sandbox = getenv('SANDBOX'); return match ($sandbox) { - 'docker' => new DockerSandbox( + 'docker' => new DockerSandboxFactory( $c->get('basePath'), $c->get('appName'), ), - default => new HostSandbox(), + default => new HostSandboxFactory(), }; }, diff --git a/src/Event/CliExecuteEvent.php b/src/Event/CliExecuteEvent.php index aa88cbd0..18564684 100644 --- a/src/Event/CliExecuteEvent.php +++ b/src/Event/CliExecuteEvent.php @@ -7,7 +7,7 @@ use PhpSchool\PhpWorkshop\Exercise\Scenario\CliScenario; use PhpSchool\PhpWorkshop\ExerciseRunner\Context\ExecutionContext; use PhpSchool\PhpWorkshop\Process\SandboxExecution; -use PhpSchool\PhpWorkshop\Process\Workspace; +use PhpSchool\PhpWorkshop\Process\Sandbox; use PhpSchool\PhpWorkshop\Utils\Collection; /** @@ -70,14 +70,14 @@ public function getExecution(): SandboxExecution } /** - * The solution in the sandbox, eg. to pass its port in the args. Only on the pre events. + * Where the solution runs, eg. to pass its port in the args. Only on the pre events. */ - public function getWorkspace(): Workspace + public function getSandbox(): Sandbox { - /** @var Workspace $workspace */ - $workspace = $this->getParameter('workspace'); + /** @var Sandbox $sandbox */ + $sandbox = $this->getParameter('sandbox'); - return $workspace; + return $sandbox; } /** diff --git a/src/Exercise/Scenario/ExerciseScenario.php b/src/Exercise/Scenario/ExerciseScenario.php index dab9b2cc..90c6b700 100644 --- a/src/Exercise/Scenario/ExerciseScenario.php +++ b/src/Exercise/Scenario/ExerciseScenario.php @@ -28,7 +28,7 @@ public function getFiles(): array /** * The code listens on a port, eg. a server the check connects to. The sandbox picks it, listeners get it from the - * pre execute events with getWorkspace(). + * pre execute events with getSandbox()->getPort(). */ public function exposePort(): static { diff --git a/src/ExerciseRunner/CgiRunner.php b/src/ExerciseRunner/CgiRunner.php index 6663ce4b..9978e2d0 100644 --- a/src/ExerciseRunner/CgiRunner.php +++ b/src/ExerciseRunner/CgiRunner.php @@ -22,8 +22,8 @@ use PhpSchool\PhpWorkshop\Input\Input; use PhpSchool\PhpWorkshop\Output\OutputInterface; use PhpSchool\PhpWorkshop\Process\Sandbox; +use PhpSchool\PhpWorkshop\Process\SandboxFactory; use PhpSchool\PhpWorkshop\Process\ProcessInput; -use PhpSchool\PhpWorkshop\Process\Workspace; use PhpSchool\PhpWorkshop\Process\SandboxExecution; use PhpSchool\PhpWorkshop\Result\Cgi\CgiResult; use PhpSchool\PhpWorkshop\Result\Cgi\RequestFailure; @@ -60,7 +60,7 @@ class CgiRunner implements ExerciseRunnerInterface public function __construct( private CgiExercise $exercise, private EventDispatcher $eventDispatcher, - private Sandbox $sandbox, + private SandboxFactory $sandboxFactory, private EnvironmentManager $environmentManager, ) {} @@ -110,8 +110,8 @@ public function verify(ExecutionContext $context): ResultInterface $this->eventDispatcher->dispatch(new CgiExerciseRunnerEvent('cgi.verify.start', $context, $scenario)); - $reference = $this->sandbox->prepare($context->getReferenceExecutionDirectory(), $scenario); - $student = $this->sandbox->prepare($context->getStudentExecutionDirectory(), $scenario); + $reference = $this->sandboxFactory->create($context->getReferenceExecutionDirectory(), $scenario); + $student = $this->sandboxFactory->create($context->getStudentExecutionDirectory(), $scenario); $result = new CgiResult( array_map( @@ -126,7 +126,7 @@ function (RequestInterface $request) use ($context, $scenario, $reference, $stud return $result; } - private function doVerify(ExecutionContext $context, CgiScenario $scenario, RequestInterface $request, Workspace $reference, Workspace $student): CgiResultInterface + private function doVerify(ExecutionContext $context, CgiScenario $scenario, RequestInterface $request, Sandbox $reference, Sandbox $student): CgiResultInterface { try { /** @var CgiExecuteEvent $event */ @@ -214,12 +214,12 @@ private function getHeaders(ResponseInterface $response): array private function executePhpFile( ExecutionContext $context, CgiScenario $scenario, - Workspace $workspace, + Sandbox $sandbox, string $fileName, RequestInterface $request, string $type, ): ResponseInterface { - $execution = $this->getPhpExecution($workspace, $fileName, $request); + $execution = $this->getPhpExecution($sandbox, $fileName, $request); $execution->start(); $this->eventDispatcher->dispatch( @@ -241,7 +241,7 @@ private function executePhpFile( return Message::parseResponse($output); } - private function getPhpExecution(Workspace $workspace, string $fileName, RequestInterface $request): SandboxExecution + private function getPhpExecution(Sandbox $sandbox, string $fileName, RequestInterface $request): SandboxExecution { $env = [ 'REQUEST_METHOD' => $request->getMethod(), @@ -271,7 +271,7 @@ private function getPhpExecution(Workspace $workspace, string $fileName, Request $content, ); - return $this->sandbox->create($workspace, $processInput); + return $sandbox->execute($processInput); } /** @@ -301,7 +301,7 @@ public function run(ExecutionContext $context, OutputInterface $output): bool $this->eventDispatcher->dispatch(new CgiExerciseRunnerEvent('cgi.run.start', $context, $scenario)); - $student = $this->sandbox->prepare($context->getStudentExecutionDirectory(), $scenario); + $student = $this->sandboxFactory->create($context->getStudentExecutionDirectory(), $scenario); $success = true; foreach ($scenario->getExecutions() as $i => $request) { diff --git a/src/ExerciseRunner/CliRunner.php b/src/ExerciseRunner/CliRunner.php index 3f159790..efee2849 100644 --- a/src/ExerciseRunner/CliRunner.php +++ b/src/ExerciseRunner/CliRunner.php @@ -21,9 +21,9 @@ use PhpSchool\PhpWorkshop\Input\Input; use PhpSchool\PhpWorkshop\Output\OutputInterface; use PhpSchool\PhpWorkshop\Process\Sandbox; +use PhpSchool\PhpWorkshop\Process\SandboxFactory; use PhpSchool\PhpWorkshop\Process\ProcessInput; use PhpSchool\PhpWorkshop\Process\SandboxExecution; -use PhpSchool\PhpWorkshop\Process\Workspace; use PhpSchool\PhpWorkshop\Result\Cli\RequestFailure; use PhpSchool\PhpWorkshop\Result\Cli\CliResult; use PhpSchool\PhpWorkshop\Result\Cli\GenericFailure; @@ -60,7 +60,7 @@ class CliRunner implements ExerciseRunnerInterface public function __construct( private CliExercise $exercise, private EventDispatcher $eventDispatcher, - private Sandbox $sandbox, + private SandboxFactory $sandboxFactory, private EnvironmentManager $environmentManager, ) {} @@ -109,8 +109,8 @@ public function verify(ExecutionContext $context): ResultInterface $this->eventDispatcher->dispatch(new CliExerciseRunnerEvent('cli.verify.start', $context, $scenario)); - $reference = $this->sandbox->prepare($context->getReferenceExecutionDirectory(), $scenario); - $student = $this->sandbox->prepare($context->getStudentExecutionDirectory(), $scenario); + $reference = $this->sandboxFactory->create($context->getReferenceExecutionDirectory(), $scenario); + $student = $this->sandboxFactory->create($context->getStudentExecutionDirectory(), $scenario); $result = new CliResult( array_map( @@ -129,12 +129,12 @@ function (Collection $args) use ($context, $scenario, $reference, $student) { /** * @param Collection $args */ - private function doVerify(ExecutionContext $context, CliScenario $scenario, Collection $args, Workspace $reference, Workspace $student): CliResultInterface + private function doVerify(ExecutionContext $context, CliScenario $scenario, Collection $args, Sandbox $reference, Sandbox $student): CliResultInterface { try { /** @var CliExecuteEvent $event */ $event = $this->eventDispatcher->dispatch( - new CliExecuteEvent('cli.verify.reference-execute.pre', $context, $scenario, $args, ['workspace' => $reference]), + new CliExecuteEvent('cli.verify.reference-execute.pre', $context, $scenario, $args, ['sandbox' => $reference]), ); $solutionOutput = $this->executePhpFile( $context, @@ -160,7 +160,7 @@ private function doVerify(ExecutionContext $context, CliScenario $scenario, Coll try { /** @var CliExecuteEvent $event */ $event = $this->eventDispatcher->dispatch( - new CliExecuteEvent('cli.verify.student-execute.pre', $context, $scenario, $args, ['workspace' => $student]), + new CliExecuteEvent('cli.verify.student-execute.pre', $context, $scenario, $args, ['sandbox' => $student]), ); $userOutput = $this->executePhpFile( $context, @@ -215,13 +215,13 @@ public function run(ExecutionContext $context, OutputInterface $output): bool $this->eventDispatcher->dispatch(new CliExerciseRunnerEvent('cli.run.start', $context, $scenario)); - $student = $this->sandbox->prepare($context->getStudentExecutionDirectory(), $scenario); + $student = $this->sandboxFactory->create($context->getStudentExecutionDirectory(), $scenario); $success = true; foreach ($scenario->getExecutions() as $i => $args) { /** @var CliExecuteEvent $event */ $event = $this->eventDispatcher->dispatch( - new CliExecuteEvent('cli.run.student-execute.pre', $context, $scenario, $args, ['workspace' => $student]), + new CliExecuteEvent('cli.run.student-execute.pre', $context, $scenario, $args, ['sandbox' => $student]), ); $args = $event->getArgs(); @@ -257,9 +257,9 @@ public function run(ExecutionContext $context, OutputInterface $output): bool /** * @param Collection $args */ - private function executePhpFile(ExecutionContext $context, CliScenario $scenario, Workspace $workspace, string $fileName, Collection $args, string $type): string + private function executePhpFile(ExecutionContext $context, CliScenario $scenario, Sandbox $sandbox, string $fileName, Collection $args, string $type): string { - $execution = $this->getPhpExecution($workspace, $fileName, $args); + $execution = $this->getPhpExecution($sandbox, $fileName, $args); $execution->start(); $this->eventDispatcher->dispatch( @@ -277,8 +277,8 @@ private function executePhpFile(ExecutionContext $context, CliScenario $scenario /** * @param Collection $args */ - private function getPhpExecution(Workspace $workspace, string $fileName, Collection $args): SandboxExecution + private function getPhpExecution(Sandbox $sandbox, string $fileName, Collection $args): SandboxExecution { - return $this->sandbox->create($workspace, new ProcessInput('php', [$fileName, ...$args->getArrayCopy()], [])); + return $sandbox->execute(new ProcessInput('php', [$fileName, ...$args->getArrayCopy()], [])); } } diff --git a/src/ExerciseRunner/Factory/CgiRunnerFactory.php b/src/ExerciseRunner/Factory/CgiRunnerFactory.php index 52eebeb9..84799b3f 100644 --- a/src/ExerciseRunner/Factory/CgiRunnerFactory.php +++ b/src/ExerciseRunner/Factory/CgiRunnerFactory.php @@ -13,7 +13,7 @@ use PhpSchool\PhpWorkshop\ExerciseRunner\CgiRunner; use PhpSchool\PhpWorkshop\ExerciseRunner\EnvironmentManager; use PhpSchool\PhpWorkshop\ExerciseRunner\ExerciseRunnerInterface; -use PhpSchool\PhpWorkshop\Process\Sandbox; +use PhpSchool\PhpWorkshop\Process\SandboxFactory; /** * Factory class for `CgiRunner` @@ -25,7 +25,7 @@ class CgiRunnerFactory implements ExerciseRunnerFactoryInterface */ private static string $type = ExerciseType::CGI; - public function __construct(private EventDispatcher $eventDispatcher, private Sandbox $sandbox, private EnvironmentManager $environmentManager) {} + public function __construct(private EventDispatcher $eventDispatcher, private SandboxFactory $sandboxFactory, private EnvironmentManager $environmentManager) {} /** * Whether the factory supports this exercise type. @@ -56,6 +56,6 @@ public function configureInput(CommandDefinition $commandDefinition): void */ public function create(ExerciseInterface $exercise): ExerciseRunnerInterface { - return new CgiRunner($exercise, $this->eventDispatcher, $this->sandbox, $this->environmentManager); + return new CgiRunner($exercise, $this->eventDispatcher, $this->sandboxFactory, $this->environmentManager); } } diff --git a/src/ExerciseRunner/Factory/CliRunnerFactory.php b/src/ExerciseRunner/Factory/CliRunnerFactory.php index 8a584d16..79dc9cc3 100644 --- a/src/ExerciseRunner/Factory/CliRunnerFactory.php +++ b/src/ExerciseRunner/Factory/CliRunnerFactory.php @@ -13,7 +13,7 @@ use PhpSchool\PhpWorkshop\ExerciseRunner\CliRunner; use PhpSchool\PhpWorkshop\ExerciseRunner\EnvironmentManager; use PhpSchool\PhpWorkshop\ExerciseRunner\ExerciseRunnerInterface; -use PhpSchool\PhpWorkshop\Process\Sandbox; +use PhpSchool\PhpWorkshop\Process\SandboxFactory; /** * Factory class for `CliRunner` @@ -25,7 +25,7 @@ class CliRunnerFactory implements ExerciseRunnerFactoryInterface */ private static string $type = ExerciseType::CLI; - public function __construct(private EventDispatcher $eventDispatcher, private Sandbox $sandbox, private EnvironmentManager $environmentManager) {} + public function __construct(private EventDispatcher $eventDispatcher, private SandboxFactory $sandboxFactory, private EnvironmentManager $environmentManager) {} /** * Whether the factory supports this exercise type. @@ -56,6 +56,6 @@ public function configureInput(CommandDefinition $commandDefinition): void */ public function create(ExerciseInterface $exercise): ExerciseRunnerInterface { - return new CliRunner($exercise, $this->eventDispatcher, $this->sandbox, $this->environmentManager); + return new CliRunner($exercise, $this->eventDispatcher, $this->sandboxFactory, $this->environmentManager); } } diff --git a/src/Process/DockerSandbox.php b/src/Process/DockerSandbox.php index d0d3eda8..e8fd7e86 100644 --- a/src/Process/DockerSandbox.php +++ b/src/Process/DockerSandbox.php @@ -4,14 +4,10 @@ namespace PhpSchool\PhpWorkshop\Process; -use PhpSchool\PhpWorkshop\Exercise\Scenario\ExerciseScenario; -use PhpSchool\PhpWorkshop\Process\Port\FreePortPicker; -use PhpSchool\PhpWorkshop\Process\Port\PortPicker; -use Symfony\Component\Process\ExecutableFinder; use Symfony\Component\Process\Process; /** - * Runs processes in a throwaway container built from the workshop's `.docker/runtime/Dockerfile`. + * Runs the code in a throwaway container with the solution's directory mounted. * * The workshop only supplies the image. All isolation flags are set here so a workshop cannot loosen them. */ @@ -19,64 +15,26 @@ final class DockerSandbox implements Sandbox { private const TIMEOUT = 30; - private ExecutableFinder $executableFinder; - private string $basePath; - private string $projectName; - private string $portsNetwork; - private string $portsHost; - private PortPicker $portPicker; - - public function __construct( - string $basePath, - string $projectName, - ?ExecutableFinder $executableFinder = null, - string $portsNetwork = 'bridge', - string $portsHost = '127.0.0.1', - ?PortPicker $portPicker = null, - ) { - $this->executableFinder = $executableFinder ?? new ExecutableFinder(); - $this->basePath = $basePath; - $this->projectName = $projectName; - //for exercises that expose ports, eg a server the check connects to. Pass a network without internet access - //to stop student code reaching out, the published ports still work - $this->portsNetwork = $portsNetwork; - //the address ports are published on, the docker host's private address when it is remote. IPv6 in brackets, - //eg. [fdaa::2] - $this->portsHost = $portsHost; - $this->portPicker = $portPicker ?? new FreePortPicker(); - } - - public function getImageName(): string - { - return strtolower($this->projectName) . '-runtime'; - } - /** - * The process that builds the runtime image. Run it once on install/deploy, not per request. + * @param string $portsNetwork the network when a port is published, see DockerSandboxFactory + * @param string $portsHost the address the port is published on, eg. 127.0.0.1 */ - public function createBuildProcess(): Process - { - return new Process( - [$this->findDocker(), 'build', '-t', $this->getImageName(), '.docker/runtime'], - $this->basePath, - null, - null, - 300, - ); - } - - public function prepare(string $directory, ExerciseScenario $scenario): Workspace - { - return new Workspace($directory, $scenario->exposesPort() ? $this->portPicker->pick() : null); - } + public function __construct( + private string $directory, + private ?int $port, + private string $docker, + private string $basePath, + private string $image, + private string $portsNetwork, + private string $portsHost, + ) {} - public function create(Workspace $workspace, ProcessInput $processInput): DockerExecution + public function execute(ProcessInput $processInput): DockerSandboxExecution { $network = ['--network', 'none']; - $port = $workspace->port; - if ($port !== null) { - //the same port on the docker host, prepare() picked one free there - $network = ['--network', $this->portsNetwork, '-p', $this->portsHost . ':' . $port . ':' . $port]; + if ($this->port !== null) { + //the same port on the docker host, the factory picked one free there + $network = ['--network', $this->portsNetwork, '-p', $this->portsHost . ':' . $this->port . ':' . $this->port]; } $envArgs = []; @@ -86,9 +44,9 @@ public function create(Workspace $workspace, ProcessInput $processInput): Docker } //no steps around it yet, create/cp/rm come when files are copied in instead of mounted - return new DockerExecution(new Process( + return new DockerSandboxExecution(new Process( [ - $this->findDocker(), + $this->docker, 'run', '--rm', '-i', @@ -113,10 +71,10 @@ public function create(Workspace $workspace, ProcessInput $processInput): Docker '1', ...$envArgs, '-v', - $workspace->directory . ':/solution', + $this->directory . ':/solution', '-w', '/solution', - $this->getImageName(), + $this->image, //the docker client being killed does not stop the container, so enforce the timeout inside it too 'timeout', '-s', @@ -129,16 +87,11 @@ public function create(Workspace $workspace, ProcessInput $processInput): Docker null, $processInput->getInput(), self::TIMEOUT + 5, - ), [], [], $this->portsHost, $port); + ), [], [], $this->portsHost, $this->port); } - private function findDocker(): string + public function getPort(): int { - $dockerPath = $this->executableFinder->find('docker'); - if ($dockerPath === null) { - throw ProcessNotFoundException::fromExecutable('docker'); - } - - return $dockerPath; + return $this->port ?? throw new \RuntimeException('The scenario does not expose a port'); } } diff --git a/src/Process/DockerExecution.php b/src/Process/DockerSandboxExecution.php similarity index 97% rename from src/Process/DockerExecution.php rename to src/Process/DockerSandboxExecution.php index 215f048b..d28d0be4 100644 --- a/src/Process/DockerExecution.php +++ b/src/Process/DockerSandboxExecution.php @@ -10,7 +10,7 @@ /** * The main process plus the docker steps around it, eg. `create` and `cp` before, `rm` after. */ -final class DockerExecution implements SandboxExecution +final class DockerSandboxExecution implements SandboxExecution { /** * @param list $before diff --git a/src/Process/DockerSandboxFactory.php b/src/Process/DockerSandboxFactory.php new file mode 100644 index 00000000..c1be1963 --- /dev/null +++ b/src/Process/DockerSandboxFactory.php @@ -0,0 +1,80 @@ +executableFinder = $executableFinder ?? new ExecutableFinder(); + $this->basePath = $basePath; + $this->projectName = $projectName; + //for exercises that expose ports, eg a server the check connects to. Pass a network without internet access + //to stop student code reaching out, the published ports still work + $this->portsNetwork = $portsNetwork; + //the address ports are published on, the docker host's private address when it is remote. IPv6 in brackets, + //eg. [fdaa::2] + $this->portsHost = $portsHost; + $this->portPicker = $portPicker ?? new FreePortPicker(); + } + + public function getImageName(): string + { + return strtolower($this->projectName) . '-runtime'; + } + + /** + * The process that builds the runtime image. Run it once on install/deploy, not per request. + */ + public function createBuildProcess(): Process + { + return new Process( + [$this->findDocker(), 'build', '-t', $this->getImageName(), '.docker/runtime'], + $this->basePath, + null, + null, + 300, + ); + } + + public function create(string $directory, ExerciseScenario $scenario): DockerSandbox + { + $port = $scenario->exposesPort() ? $this->portPicker->pick() : null; + + return new DockerSandbox($directory, $port, $this->findDocker(), $this->basePath, $this->getImageName(), $this->portsNetwork, $this->portsHost); + } + + private function findDocker(): string + { + $dockerPath = $this->executableFinder->find('docker'); + if ($dockerPath === null) { + throw ProcessNotFoundException::fromExecutable('docker'); + } + + return $dockerPath; + } +} diff --git a/src/Process/HostSandbox.php b/src/Process/HostSandbox.php index 12511400..634d0b4e 100644 --- a/src/Process/HostSandbox.php +++ b/src/Process/HostSandbox.php @@ -4,11 +4,12 @@ namespace PhpSchool\PhpWorkshop\Process; -use PhpSchool\PhpWorkshop\Exercise\Scenario\ExerciseScenario; -use PhpSchool\PhpWorkshop\Process\Port\FreePortPicker; use Symfony\Component\Process\ExecutableFinder; use Symfony\Component\Process\Process; +/** + * Runs the code straight on this machine, in the solution's directory. + */ final class HostSandbox implements Sandbox { /** @@ -16,19 +17,9 @@ final class HostSandbox implements Sandbox */ private const ALLOWED_ENV = ['PATH', 'HOME', 'COMPOSER_HOME']; - private ExecutableFinder $executableFinder; + public function __construct(private string $directory, private ?int $port, private ExecutableFinder $executableFinder) {} - public function __construct(?ExecutableFinder $executableFinder = null) - { - $this->executableFinder = $executableFinder ?? new ExecutableFinder(); - } - - public function prepare(string $directory, ExerciseScenario $scenario): Workspace - { - return new Workspace($directory, $scenario->exposesPort() ? (new FreePortPicker())->pick() : null); - } - - public function create(Workspace $workspace, ProcessInput $processInput): HostExecution + public function execute(ProcessInput $processInput): HostSandboxExecution { $executablePath = $this->executableFinder->find($processInput->getExecutable()); @@ -36,13 +27,18 @@ public function create(Workspace $workspace, ProcessInput $processInput): HostEx throw ProcessNotFoundException::fromExecutable($processInput->getExecutable()); } - return new HostExecution(new Process( + return new HostSandboxExecution(new Process( [$executablePath, ...$processInput->getArgs()], - $workspace->directory, + $this->directory, array_merge($this->getDefaultEnv(), $processInput->getEnv()), $processInput->getInput(), 10, - ), $workspace->port); + ), $this->port); + } + + public function getPort(): int + { + return $this->port ?? throw new \RuntimeException('The scenario does not expose a port'); } /** diff --git a/src/Process/HostExecution.php b/src/Process/HostSandboxExecution.php similarity index 94% rename from src/Process/HostExecution.php rename to src/Process/HostSandboxExecution.php index 69c37a08..aac40ced 100644 --- a/src/Process/HostExecution.php +++ b/src/Process/HostSandboxExecution.php @@ -6,7 +6,7 @@ use Symfony\Component\Process\Process; -final class HostExecution implements SandboxExecution +final class HostSandboxExecution implements SandboxExecution { public function __construct(public readonly Process $process, private ?int $port = null) {} diff --git a/src/Process/HostSandboxFactory.php b/src/Process/HostSandboxFactory.php new file mode 100644 index 00000000..5aa1bb1e --- /dev/null +++ b/src/Process/HostSandboxFactory.php @@ -0,0 +1,21 @@ +exposesPort() ? (new FreePortPicker())->pick() : null; + + return new HostSandbox($directory, $port, $this->executableFinder); + } +} diff --git a/src/Process/Sandbox.php b/src/Process/Sandbox.php index d1973a41..7edf3a6d 100644 --- a/src/Process/Sandbox.php +++ b/src/Process/Sandbox.php @@ -4,14 +4,15 @@ namespace PhpSchool\PhpWorkshop\Process; -use PhpSchool\PhpWorkshop\Exercise\Scenario\ExerciseScenario; - +/** + * Where one solution's code runs. Every execution of it happens here and listens on the same port. + */ interface Sandbox { - public function create(Workspace $workspace, ProcessInput $processInput): SandboxExecution; + public function execute(ProcessInput $processInput): SandboxExecution; /** - * Sets up a solution's directory before its runs, with a port free where this sandbox runs it when the scenario exposes one. + * The port the code listens on, eg. to pass it in the args. Only when the scenario exposes a port. */ - public function prepare(string $directory, ExerciseScenario $scenario): Workspace; + public function getPort(): int; } diff --git a/src/Process/SandboxFactory.php b/src/Process/SandboxFactory.php new file mode 100644 index 00000000..3a4e0d07 --- /dev/null +++ b/src/Process/SandboxFactory.php @@ -0,0 +1,18 @@ +getMockBuilder(CliRunner::class) - ->setConstructorArgs([$exercise, $eventDispatcher, new HostSandbox(), new EnvironmentManager(new Filesystem(), $eventDispatcher)]) + ->setConstructorArgs([$exercise, $eventDispatcher, new HostSandboxFactory(), new EnvironmentManager(new Filesystem(), $eventDispatcher)]) ->onlyMethods(['getRequiredChecks']) ->getMock(); diff --git a/test/ExerciseRunner/CgiRunnerTest.php b/test/ExerciseRunner/CgiRunnerTest.php index ff9cb020..eafa5da1 100644 --- a/test/ExerciseRunner/CgiRunnerTest.php +++ b/test/ExerciseRunner/CgiRunnerTest.php @@ -9,7 +9,7 @@ use PhpSchool\PhpWorkshop\ExerciseRunner\Context\TestContext; use PhpSchool\PhpWorkshop\ExerciseRunner\EnvironmentManager; use PhpSchool\PhpWorkshop\Listener\OutputRunInfoListener; -use PhpSchool\PhpWorkshop\Process\HostSandbox; +use PhpSchool\PhpWorkshop\Process\HostSandboxFactory; use PhpSchool\PhpWorkshopTest\Asset\CgiExerciseImpl; use PhpSchool\Terminal\Terminal; use PhpSchool\PhpWorkshop\Check\CodeParseCheck; @@ -38,7 +38,7 @@ public function setUp(): void { $this->exercise = new CgiExerciseImpl(); $this->eventDispatcher = new EventDispatcher(new ResultAggregator()); - $this->runner = new CgiRunner($this->exercise, $this->eventDispatcher, new HostSandbox(), new EnvironmentManager(new Filesystem(), $this->eventDispatcher)); + $this->runner = new CgiRunner($this->exercise, $this->eventDispatcher, new HostSandboxFactory(), new EnvironmentManager(new Filesystem(), $this->eventDispatcher)); $this->assertEquals('CGI Program Runner', $this->runner->getName()); } diff --git a/test/ExerciseRunner/CliRunnerTest.php b/test/ExerciseRunner/CliRunnerTest.php index da7fefca..4e1fc53d 100644 --- a/test/ExerciseRunner/CliRunnerTest.php +++ b/test/ExerciseRunner/CliRunnerTest.php @@ -9,12 +9,12 @@ use PhpSchool\PhpWorkshop\ExerciseRunner\Context\TestContext; use PhpSchool\PhpWorkshop\ExerciseRunner\EnvironmentManager; use PhpSchool\PhpWorkshop\Listener\OutputRunInfoListener; -use PhpSchool\PhpWorkshop\Process\HostSandbox; +use PhpSchool\PhpWorkshop\Process\HostSandboxFactory; use PhpSchool\PhpWorkshop\Process\SandboxExecution; use PhpSchool\PhpWorkshop\Output\NullOutput; use PhpSchool\PhpWorkshop\Process\ProcessInput; use PhpSchool\PhpWorkshop\Process\Sandbox; -use PhpSchool\PhpWorkshop\Process\Workspace; +use PhpSchool\PhpWorkshop\Process\SandboxFactory; use PhpSchool\PhpWorkshop\Utils\RequestRenderer; use PhpSchool\PhpWorkshopTest\Asset\CliExerciseImpl; use PhpSchool\Terminal\Terminal; @@ -44,7 +44,7 @@ public function setUp(): void { $this->exercise = new CliExerciseImpl(); $this->eventDispatcher = new EventDispatcher(new ResultAggregator()); - $this->runner = new CliRunner($this->exercise, $this->eventDispatcher, new HostSandbox(), new EnvironmentManager(new Filesystem(), $this->eventDispatcher)); + $this->runner = new CliRunner($this->exercise, $this->eventDispatcher, new HostSandboxFactory(), new EnvironmentManager(new Filesystem(), $this->eventDispatcher)); $this->assertEquals('CLI Program Runner', $this->runner->getName()); } @@ -120,7 +120,7 @@ public function testSandboxPicksOnePortForEachFolder(): void $this->eventDispatcher->listen( ['cli.verify.reference-execute.pre', 'cli.verify.student-execute.pre'], function (CliExecuteEvent $event) use (&$ports) { - $ports[$event->getName()][] = $event->getWorkspace()->port; + $ports[$event->getName()][] = $event->getSandbox()->getPort(); }, ); @@ -222,20 +222,26 @@ public function testRunPassesTheEntryPointRelativeToTheWorkingDirectory(): void $sandbox = new class implements Sandbox { /** @var array */ public array $inputs = []; + public Sandbox $host; - public function create(Workspace $workspace, ProcessInput $processInput): SandboxExecution + public function execute(ProcessInput $processInput): SandboxExecution { $this->inputs[] = $processInput; - return (new HostSandbox())->create($workspace, $processInput); + return $this->host->execute($processInput); } - public function prepare(string $directory, ExerciseScenario $scenario): Workspace + public function getPort(): int { - return new Workspace($directory, $scenario->exposesPort() ? 54321 : null); + return 54321; } }; - $runner = new CliRunner($this->exercise, $this->eventDispatcher, $sandbox, new EnvironmentManager(new Filesystem(), $this->eventDispatcher)); + $factory = $this->createMock(SandboxFactory::class); + $factory->method('create')->willReturnCallback(function (string $directory, ExerciseScenario $scenario) use ($sandbox) { + $sandbox->host = (new HostSandboxFactory())->create($directory, $scenario); + return $sandbox; + }); + $runner = new CliRunner($this->exercise, $this->eventDispatcher, $factory, new EnvironmentManager(new Filesystem(), $this->eventDispatcher)); $this->exercise->setScenario((new CliScenario())->withExecution([1, 2, 3])); diff --git a/test/ExerciseRunner/Factory/CgiRunnerFactoryTest.php b/test/ExerciseRunner/Factory/CgiRunnerFactoryTest.php index 6bf45d40..20731b37 100644 --- a/test/ExerciseRunner/Factory/CgiRunnerFactoryTest.php +++ b/test/ExerciseRunner/Factory/CgiRunnerFactoryTest.php @@ -9,7 +9,7 @@ use PhpSchool\PhpWorkshop\ExerciseRunner\CgiRunner; use PhpSchool\PhpWorkshop\ExerciseRunner\EnvironmentManager; use PhpSchool\PhpWorkshop\ExerciseRunner\Factory\CgiRunnerFactory; -use PhpSchool\PhpWorkshop\Process\HostSandbox; +use PhpSchool\PhpWorkshop\Process\HostSandboxFactory; use PhpSchool\PhpWorkshopTest\Asset\CgiExerciseImpl; use PHPUnit\Framework\TestCase; @@ -21,7 +21,7 @@ class CgiRunnerFactoryTest extends TestCase public function setUp(): void { $this->eventDispatcher = $this->createMock(EventDispatcher::class); - $this->factory = new CgiRunnerFactory($this->eventDispatcher, new HostSandbox(), $this->createMock(EnvironmentManager::class)); + $this->factory = new CgiRunnerFactory($this->eventDispatcher, new HostSandboxFactory(), $this->createMock(EnvironmentManager::class)); } public function testSupports(): void diff --git a/test/ExerciseRunner/Factory/CliRunnerFactoryTest.php b/test/ExerciseRunner/Factory/CliRunnerFactoryTest.php index c057ef8d..ad46f084 100644 --- a/test/ExerciseRunner/Factory/CliRunnerFactoryTest.php +++ b/test/ExerciseRunner/Factory/CliRunnerFactoryTest.php @@ -9,7 +9,7 @@ use PhpSchool\PhpWorkshop\ExerciseRunner\CliRunner; use PhpSchool\PhpWorkshop\ExerciseRunner\EnvironmentManager; use PhpSchool\PhpWorkshop\ExerciseRunner\Factory\CliRunnerFactory; -use PhpSchool\PhpWorkshop\Process\HostSandbox; +use PhpSchool\PhpWorkshop\Process\HostSandboxFactory; use PhpSchool\PhpWorkshopTest\Asset\CliExerciseImpl; use PHPUnit\Framework\TestCase; @@ -21,7 +21,7 @@ class CliRunnerFactoryTest extends TestCase public function setUp(): void { $this->eventDispatcher = $this->createMock(EventDispatcher::class); - $this->factory = new CliRunnerFactory($this->eventDispatcher, new HostSandbox(), $this->createMock(EnvironmentManager::class)); + $this->factory = new CliRunnerFactory($this->eventDispatcher, new HostSandboxFactory(), $this->createMock(EnvironmentManager::class)); } public function testSupports(): void diff --git a/test/Process/DockerExecutionTest.php b/test/Process/DockerSandboxExecutionTest.php similarity index 84% rename from test/Process/DockerExecutionTest.php rename to test/Process/DockerSandboxExecutionTest.php index 88444e1b..651aed1a 100644 --- a/test/Process/DockerExecutionTest.php +++ b/test/Process/DockerSandboxExecutionTest.php @@ -4,17 +4,17 @@ namespace PhpSchool\PhpWorkshopTest\Process; -use PhpSchool\PhpWorkshop\Process\DockerExecution; +use PhpSchool\PhpWorkshop\Process\DockerSandboxExecution; use PHPUnit\Framework\TestCase; use Symfony\Component\Process\Process; -class DockerExecutionTest extends TestCase +class DockerSandboxExecutionTest extends TestCase { public function testStepsRunAroundTheMainProcess(): void { $log = tempnam(sys_get_temp_dir(), 'steps'); - $execution = new DockerExecution( + $execution = new DockerSandboxExecution( Process::fromShellCommandline('echo main >> ' . $log), [Process::fromShellCommandline('echo before >> ' . $log)], [Process::fromShellCommandline('echo after >> ' . $log)], @@ -31,7 +31,7 @@ public function testAfterStepsRunWhenTheMainProcessFails(): void { $log = tempnam(sys_get_temp_dir(), 'steps'); - $execution = new DockerExecution( + $execution = new DockerSandboxExecution( Process::fromShellCommandline('exit 1'), [], [Process::fromShellCommandline('echo after >> ' . $log)], diff --git a/test/Process/DockerSandboxTest.php b/test/Process/DockerSandboxTest.php index 02a8373e..212d4665 100644 --- a/test/Process/DockerSandboxTest.php +++ b/test/Process/DockerSandboxTest.php @@ -2,18 +2,17 @@ namespace PhpSchool\PhpWorkshopTest\Process; -use PhpSchool\PhpWorkshop\Process\DockerSandbox; +use PhpSchool\PhpWorkshop\Process\DockerSandboxFactory; use PhpSchool\PhpWorkshop\Process\Port\PortPicker; use PhpSchool\PhpWorkshop\Exercise\Scenario\CliScenario; use PhpSchool\PhpWorkshop\Process\ProcessInput; -use PhpSchool\PhpWorkshop\Process\Workspace; use PhpSchool\PhpWorkshop\Process\ProcessNotFoundException; use PHPUnit\Framework\TestCase; use Symfony\Component\Process\ExecutableFinder; class DockerSandboxTest extends TestCase { - private function factory(string $portsNetwork = 'bridge', string $portsHost = '127.0.0.1'): DockerSandbox + private function factory(string $portsNetwork = 'bridge', string $portsHost = '127.0.0.1'): DockerSandboxFactory { $ports = new class implements PortPicker { public function pick(): int @@ -28,7 +27,7 @@ public function pick(): int ->with('docker') ->willReturn('/usr/local/bin/docker'); - return new DockerSandbox('/docker-dir', 'PHP8Appreciate', $finder, $portsNetwork, $portsHost, $ports); + return new DockerSandboxFactory('/docker-dir', 'PHP8Appreciate', $finder, $portsNetwork, $portsHost, $ports); } /** @@ -62,15 +61,15 @@ public function testCreateThrowsExceptionIfDockerNotFound(): void ->with('docker') ->willReturn(null); - $factory = new DockerSandbox('/docker-dir', 'php8appreciate', $finder); + $factory = new DockerSandboxFactory('/docker-dir', 'php8appreciate', $finder); $input = new ProcessInput('php', [], []); - $factory->create(new Workspace(__DIR__), $input); + $factory->create(__DIR__, new CliScenario())->execute($input); } public function testCreateIsIsolatedWithNoNetwork(): void { - $process = $this->factory()->create(new Workspace(__DIR__), new ProcessInput('php', ['one', 'two'], []))->process; + $process = $this->factory()->create(__DIR__, new CliScenario())->execute(new ProcessInput('php', ['one', 'two'], []))->process; $expected = $this->expectedCommand( ['--network', 'none'], @@ -84,10 +83,10 @@ public function testCreateIsIsolatedWithNoNetwork(): void public function testExposedPortsArePublishedOnLoopbackOnly(): void { - $process = $this->factory()->create(new Workspace(__DIR__, 8000), new ProcessInput('php', [], []))->process; + $process = $this->factory()->create(__DIR__, (new CliScenario())->exposePort())->execute(new ProcessInput('php', [], []))->process; $expected = $this->expectedCommand( - ['--network', 'bridge', '-p', '127.0.0.1:8000:8000'], + ['--network', 'bridge', '-p', '127.0.0.1:47213:47213'], ['-v', __DIR__ . ':/solution'], ['php'], ); @@ -96,10 +95,10 @@ public function testExposedPortsArePublishedOnLoopbackOnly(): void public function testExposedPortsUseTheGivenNetwork(): void { - $process = $this->factory('php-school-sandbox')->create(new Workspace(__DIR__, 8000), new ProcessInput('php', [], []))->process; + $process = $this->factory('php-school-sandbox')->create(__DIR__, (new CliScenario())->exposePort())->execute(new ProcessInput('php', [], []))->process; $expected = $this->expectedCommand( - ['--network', 'php-school-sandbox', '-p', '127.0.0.1:8000:8000'], + ['--network', 'php-school-sandbox', '-p', '127.0.0.1:47213:47213'], ['-v', __DIR__ . ':/solution'], ['php'], ); @@ -108,10 +107,10 @@ public function testExposedPortsUseTheGivenNetwork(): void public function testExposedPortsArePublishedOnTheGivenHost(): void { - $process = $this->factory('bridge', '172.19.0.2')->create(new Workspace(__DIR__, 8000), new ProcessInput('php', [], []))->process; + $process = $this->factory('bridge', '172.19.0.2')->create(__DIR__, (new CliScenario())->exposePort())->execute(new ProcessInput('php', [], []))->process; $expected = $this->expectedCommand( - ['--network', 'bridge', '-p', '172.19.0.2:8000:8000'], + ['--network', 'bridge', '-p', '172.19.0.2:47213:47213'], ['-v', __DIR__ . ':/solution'], ['php'], ); @@ -123,22 +122,22 @@ public function testPortsArePickedWithThePortPicker(): void $ports = $this->createMock(PortPicker::class); $ports->method('pick')->willReturn(47213); - static::assertSame(47213, (new DockerSandbox('/docker-dir', 'php8appreciate', portPicker: $ports))->prepare(__DIR__, (new CliScenario())->exposePort())->port); + static::assertSame(47213, (new DockerSandboxFactory('/docker-dir', 'php8appreciate', portPicker: $ports))->create(__DIR__, (new CliScenario())->exposePort())->getPort()); } public function testAddressIsTheSamePortOnTheGivenHost(): void { - $execution = $this->factory('bridge', '172.19.0.2')->create(new Workspace(__DIR__, 47213), new ProcessInput('php', [], [])); + $execution = $this->factory('bridge', '172.19.0.2')->create(__DIR__, (new CliScenario())->exposePort())->execute(new ProcessInput('php', [], [])); static::assertSame('172.19.0.2:47213', $execution->getAddress()); - $execution = $this->factory('bridge', '[fdaa::2]')->create(new Workspace(__DIR__, 47213), new ProcessInput('php', [], [])); + $execution = $this->factory('bridge', '[fdaa::2]')->create(__DIR__, (new CliScenario())->exposePort())->execute(new ProcessInput('php', [], [])); static::assertStringContainsString("'-p' '[fdaa::2]:47213:47213'", $execution->process->getCommandLine()); static::assertSame('[fdaa::2]:47213', $execution->getAddress()); } public function testCreateWithEnv(): void { - $process = $this->factory()->create(new Workspace(__DIR__), new ProcessInput('php', [], ['SOME_VAR' => 'value']))->process; + $process = $this->factory()->create(__DIR__, new CliScenario())->execute(new ProcessInput('php', [], ['SOME_VAR' => 'value']))->process; $expected = $this->expectedCommand( ['--network', 'none'], @@ -150,7 +149,7 @@ public function testCreateWithEnv(): void public function testWithInput(): void { - $process = $this->factory()->create(new Workspace(__DIR__), new ProcessInput('php', [], [], 'someinput'))->process; + $process = $this->factory()->create(__DIR__, new CliScenario())->execute(new ProcessInput('php', [], [], 'someinput'))->process; static::assertSame('someinput', $process->getInput()); } diff --git a/test/Process/HostSandboxTest.php b/test/Process/HostSandboxTest.php index 5d2bd4d6..bf7105d3 100644 --- a/test/Process/HostSandboxTest.php +++ b/test/Process/HostSandboxTest.php @@ -4,10 +4,9 @@ use PhpSchool\PhpWorkshop\Exercise\Scenario\CliScenario; use PhpSchool\PhpWorkshop\Process\ProcessInput; -use PhpSchool\PhpWorkshop\Process\Workspace; use PhpSchool\PhpWorkshop\Process\ProcessNotFoundException; use Symfony\Component\Process\ExecutableFinder; -use PhpSchool\PhpWorkshop\Process\HostSandbox; +use PhpSchool\PhpWorkshop\Process\HostSandboxFactory; use PHPUnit\Framework\TestCase; class HostSandboxTest extends TestCase @@ -22,10 +21,10 @@ public function testCreateThrowsExceptionIfExecutableNotFound(): void ->with('composer') ->willReturn(null); - $factory = new HostSandbox($finder); + $factory = new HostSandboxFactory($finder); $input = new ProcessInput('composer', [], []); - $factory->create(new Workspace(__DIR__), $input); + $factory->create(__DIR__, new CliScenario())->execute($input); } public function testCreate(): void @@ -36,25 +35,25 @@ public function testCreate(): void ->with('composer') ->willReturn('/usr/local/bin/composer'); - $factory = new HostSandbox($finder); + $factory = new HostSandboxFactory($finder); $input = new ProcessInput('composer', [], []); - $process = $factory->create(new Workspace(__DIR__), $input)->process; + $process = $factory->create(__DIR__, new CliScenario())->execute($input)->process; static::assertSame("'/usr/local/bin/composer'", $process->getCommandLine()); } public function testPickedPortIsFreeOnThisMachine(): void { - $server = stream_socket_server('tcp://127.0.0.1:' . (new HostSandbox())->prepare(__DIR__, (new CliScenario())->exposePort())->port); + $server = stream_socket_server('tcp://127.0.0.1:' . (new HostSandboxFactory())->create(__DIR__, (new CliScenario())->exposePort())->getPort()); static::assertNotFalse($server); fclose($server); } public function testAddressIsThePortOnThisMachine(): void { - $execution = (new HostSandbox())->create(new Workspace(__DIR__, 54321), new ProcessInput('php', [], [])); + $sandbox = (new HostSandboxFactory())->create(__DIR__, (new CliScenario())->exposePort()); - static::assertSame('127.0.0.1:54321', $execution->getAddress()); + static::assertSame('127.0.0.1:' . $sandbox->getPort(), $sandbox->execute(new ProcessInput('php', [], []))->getAddress()); } public function testCreateWithArgs(): void @@ -65,10 +64,10 @@ public function testCreateWithArgs(): void ->with('composer') ->willReturn('/usr/local/bin/composer'); - $factory = new HostSandbox($finder); + $factory = new HostSandboxFactory($finder); $input = new ProcessInput('composer', ['one', 'two'], []); - $process = $factory->create(new Workspace(__DIR__), $input)->process; + $process = $factory->create(__DIR__, new CliScenario())->execute($input)->process; static::assertSame("'/usr/local/bin/composer' 'one' 'two'", $process->getCommandLine()); } @@ -80,10 +79,10 @@ public function testCreateWithEnv(): void ->with('composer') ->willReturn('/usr/local/bin/composer'); - $factory = new HostSandbox($finder); + $factory = new HostSandboxFactory($finder); $input = new ProcessInput('composer', ['one', 'two'], ['SOME_VAR' => 'value']); - $process = $factory->create(new Workspace(__DIR__), $input)->process; + $process = $factory->create(__DIR__, new CliScenario())->execute($input)->process; static::assertSame('value', $process->getEnv()['SOME_VAR']); } @@ -92,8 +91,7 @@ public function testInheritedEnvIsRemovedExceptAllowed(): void putenv('PHPSCHOOL_SECRET=secret'); try { - $process = (new HostSandbox())->create( - new Workspace(__DIR__), + $process = (new HostSandboxFactory())->create(__DIR__, new CliScenario())->execute( new ProcessInput('php', ['-r', 'echo json_encode([getenv("PHPSCHOOL_SECRET"), getenv("PATH") !== false]);'], []), ); $process->mustRun(); @@ -112,10 +110,10 @@ public function testWithInput(): void ->with('composer') ->willReturn('/usr/local/bin/composer'); - $factory = new HostSandbox($finder); + $factory = new HostSandboxFactory($finder); $input = new ProcessInput('composer', [], [], 'someinput'); - $process = $factory->create(new Workspace(__DIR__), $input)->process; + $process = $factory->create(__DIR__, new CliScenario())->execute($input)->process; static::assertSame('someinput', $process->getInput()); } } From 7eb147b2a8c4905ff9c3219e7ed4c8a754fd22dc Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 14:44:47 +0100 Subject: [PATCH 07/10] Move the sandbox classes into Sandbox, Sandbox\Host and Sandbox\Docker --- app/config.php | 6 +++--- src/Event/CliExecuteEvent.php | 4 ++-- src/Exception/CodeExecutionException.php | 2 +- src/ExerciseRunner/CgiRunner.php | 8 ++++---- src/ExerciseRunner/CliRunner.php | 8 ++++---- src/ExerciseRunner/Factory/CgiRunnerFactory.php | 2 +- src/ExerciseRunner/Factory/CliRunnerFactory.php | 2 +- src/Process/{ => Sandbox/Docker}/DockerSandbox.php | 4 +++- .../{ => Sandbox/Docker}/DockerSandboxExecution.php | 3 ++- .../{ => Sandbox/Docker}/DockerSandboxFactory.php | 4 +++- src/Process/{ => Sandbox/Host}/HostSandbox.php | 5 ++++- .../{ => Sandbox/Host}/HostSandboxExecution.php | 3 ++- src/Process/{ => Sandbox/Host}/HostSandboxFactory.php | 3 ++- src/Process/{ => Sandbox}/ProcessInput.php | 2 +- src/Process/{ => Sandbox}/Sandbox.php | 2 +- src/Process/{ => Sandbox}/SandboxExecution.php | 2 +- src/Process/{ => Sandbox}/SandboxFactory.php | 2 +- test/Check/DatabaseCheckTest.php | 2 +- test/Exception/CodeExecutionExceptionTest.php | 2 +- test/ExerciseRunner/CgiRunnerTest.php | 2 +- test/ExerciseRunner/CliRunnerTest.php | 10 +++++----- test/ExerciseRunner/Factory/CgiRunnerFactoryTest.php | 2 +- test/ExerciseRunner/Factory/CliRunnerFactoryTest.php | 2 +- .../Docker}/DockerSandboxExecutionTest.php | 4 ++-- .../Process/{ => Sandbox/Docker}/DockerSandboxTest.php | 6 +++--- test/Process/{ => Sandbox/Host}/HostSandboxTest.php | 6 +++--- test/Process/{ => Sandbox}/ProcessInputTest.php | 4 ++-- 27 files changed, 56 insertions(+), 46 deletions(-) rename src/Process/{ => Sandbox/Docker}/DockerSandbox.php (94%) rename src/Process/{ => Sandbox/Docker}/DockerSandboxExecution.php (94%) rename src/Process/{ => Sandbox/Docker}/DockerSandboxFactory.php (93%) rename src/Process/{ => Sandbox/Host}/HostSandbox.php (89%) rename src/Process/{ => Sandbox/Host}/HostSandboxExecution.php (90%) rename src/Process/{ => Sandbox/Host}/HostSandboxFactory.php (84%) rename src/Process/{ => Sandbox}/ProcessInput.php (93%) rename src/Process/{ => Sandbox}/Sandbox.php (88%) rename src/Process/{ => Sandbox}/SandboxExecution.php (95%) rename src/Process/{ => Sandbox}/SandboxFactory.php (88%) rename test/Process/{ => Sandbox/Docker}/DockerSandboxExecutionTest.php (90%) rename test/Process/{ => Sandbox/Docker}/DockerSandboxTest.php (97%) rename test/Process/{ => Sandbox/Host}/HostSandboxTest.php (95%) rename test/Process/{ => Sandbox}/ProcessInputTest.php (81%) diff --git a/app/config.php b/app/config.php index 4dae5a15..5e9ab06f 100644 --- a/app/config.php +++ b/app/config.php @@ -72,9 +72,9 @@ use PhpSchool\PhpWorkshop\Output\StdOutput; use PhpSchool\PhpWorkshop\Patch; use PhpSchool\PhpWorkshop\Process\Composer; -use PhpSchool\PhpWorkshop\Process\DockerSandboxFactory; -use PhpSchool\PhpWorkshop\Process\HostSandboxFactory; -use PhpSchool\PhpWorkshop\Process\SandboxFactory; +use PhpSchool\PhpWorkshop\Process\Sandbox\Docker\DockerSandboxFactory; +use PhpSchool\PhpWorkshop\Process\Sandbox\Host\HostSandboxFactory; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxFactory; use PhpSchool\PhpWorkshop\Result\Cgi\CgiResult; use PhpSchool\PhpWorkshop\Result\Cgi\GenericFailure as CgiGenericFailure; use PhpSchool\PhpWorkshop\Result\Cgi\RequestFailure as CgiRequestFailure; diff --git a/src/Event/CliExecuteEvent.php b/src/Event/CliExecuteEvent.php index 18564684..7a745fac 100644 --- a/src/Event/CliExecuteEvent.php +++ b/src/Event/CliExecuteEvent.php @@ -6,8 +6,8 @@ use PhpSchool\PhpWorkshop\Exercise\Scenario\CliScenario; use PhpSchool\PhpWorkshop\ExerciseRunner\Context\ExecutionContext; -use PhpSchool\PhpWorkshop\Process\SandboxExecution; -use PhpSchool\PhpWorkshop\Process\Sandbox; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxExecution; +use PhpSchool\PhpWorkshop\Process\Sandbox\Sandbox; use PhpSchool\PhpWorkshop\Utils\Collection; /** diff --git a/src/Exception/CodeExecutionException.php b/src/Exception/CodeExecutionException.php index fbff58be..0f022374 100644 --- a/src/Exception/CodeExecutionException.php +++ b/src/Exception/CodeExecutionException.php @@ -5,7 +5,7 @@ namespace PhpSchool\PhpWorkshop\Exception; use RuntimeException; -use PhpSchool\PhpWorkshop\Process\SandboxExecution; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxExecution; /** * Represents the situation where some PHP code could not be executed successfully. diff --git a/src/ExerciseRunner/CgiRunner.php b/src/ExerciseRunner/CgiRunner.php index 9978e2d0..189d0d1a 100644 --- a/src/ExerciseRunner/CgiRunner.php +++ b/src/ExerciseRunner/CgiRunner.php @@ -21,10 +21,10 @@ use PhpSchool\PhpWorkshop\ExerciseRunner\Context\ExecutionContext; use PhpSchool\PhpWorkshop\Input\Input; use PhpSchool\PhpWorkshop\Output\OutputInterface; -use PhpSchool\PhpWorkshop\Process\Sandbox; -use PhpSchool\PhpWorkshop\Process\SandboxFactory; -use PhpSchool\PhpWorkshop\Process\ProcessInput; -use PhpSchool\PhpWorkshop\Process\SandboxExecution; +use PhpSchool\PhpWorkshop\Process\Sandbox\Sandbox; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxFactory; +use PhpSchool\PhpWorkshop\Process\Sandbox\ProcessInput; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxExecution; use PhpSchool\PhpWorkshop\Result\Cgi\CgiResult; use PhpSchool\PhpWorkshop\Result\Cgi\RequestFailure; use PhpSchool\PhpWorkshop\Result\Cgi\GenericFailure; diff --git a/src/ExerciseRunner/CliRunner.php b/src/ExerciseRunner/CliRunner.php index efee2849..82c953b1 100644 --- a/src/ExerciseRunner/CliRunner.php +++ b/src/ExerciseRunner/CliRunner.php @@ -20,10 +20,10 @@ use PhpSchool\PhpWorkshop\ExerciseRunner\Context\ExecutionContext; use PhpSchool\PhpWorkshop\Input\Input; use PhpSchool\PhpWorkshop\Output\OutputInterface; -use PhpSchool\PhpWorkshop\Process\Sandbox; -use PhpSchool\PhpWorkshop\Process\SandboxFactory; -use PhpSchool\PhpWorkshop\Process\ProcessInput; -use PhpSchool\PhpWorkshop\Process\SandboxExecution; +use PhpSchool\PhpWorkshop\Process\Sandbox\Sandbox; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxFactory; +use PhpSchool\PhpWorkshop\Process\Sandbox\ProcessInput; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxExecution; use PhpSchool\PhpWorkshop\Result\Cli\RequestFailure; use PhpSchool\PhpWorkshop\Result\Cli\CliResult; use PhpSchool\PhpWorkshop\Result\Cli\GenericFailure; diff --git a/src/ExerciseRunner/Factory/CgiRunnerFactory.php b/src/ExerciseRunner/Factory/CgiRunnerFactory.php index 84799b3f..374921c2 100644 --- a/src/ExerciseRunner/Factory/CgiRunnerFactory.php +++ b/src/ExerciseRunner/Factory/CgiRunnerFactory.php @@ -13,7 +13,7 @@ use PhpSchool\PhpWorkshop\ExerciseRunner\CgiRunner; use PhpSchool\PhpWorkshop\ExerciseRunner\EnvironmentManager; use PhpSchool\PhpWorkshop\ExerciseRunner\ExerciseRunnerInterface; -use PhpSchool\PhpWorkshop\Process\SandboxFactory; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxFactory; /** * Factory class for `CgiRunner` diff --git a/src/ExerciseRunner/Factory/CliRunnerFactory.php b/src/ExerciseRunner/Factory/CliRunnerFactory.php index 79dc9cc3..621ecf4d 100644 --- a/src/ExerciseRunner/Factory/CliRunnerFactory.php +++ b/src/ExerciseRunner/Factory/CliRunnerFactory.php @@ -13,7 +13,7 @@ use PhpSchool\PhpWorkshop\ExerciseRunner\CliRunner; use PhpSchool\PhpWorkshop\ExerciseRunner\EnvironmentManager; use PhpSchool\PhpWorkshop\ExerciseRunner\ExerciseRunnerInterface; -use PhpSchool\PhpWorkshop\Process\SandboxFactory; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxFactory; /** * Factory class for `CliRunner` diff --git a/src/Process/DockerSandbox.php b/src/Process/Sandbox/Docker/DockerSandbox.php similarity index 94% rename from src/Process/DockerSandbox.php rename to src/Process/Sandbox/Docker/DockerSandbox.php index e8fd7e86..a29e23ba 100644 --- a/src/Process/DockerSandbox.php +++ b/src/Process/Sandbox/Docker/DockerSandbox.php @@ -2,8 +2,10 @@ declare(strict_types=1); -namespace PhpSchool\PhpWorkshop\Process; +namespace PhpSchool\PhpWorkshop\Process\Sandbox\Docker; +use PhpSchool\PhpWorkshop\Process\Sandbox\ProcessInput; +use PhpSchool\PhpWorkshop\Process\Sandbox\Sandbox; use Symfony\Component\Process\Process; /** diff --git a/src/Process/DockerSandboxExecution.php b/src/Process/Sandbox/Docker/DockerSandboxExecution.php similarity index 94% rename from src/Process/DockerSandboxExecution.php rename to src/Process/Sandbox/Docker/DockerSandboxExecution.php index d28d0be4..c9a6d451 100644 --- a/src/Process/DockerSandboxExecution.php +++ b/src/Process/Sandbox/Docker/DockerSandboxExecution.php @@ -2,8 +2,9 @@ declare(strict_types=1); -namespace PhpSchool\PhpWorkshop\Process; +namespace PhpSchool\PhpWorkshop\Process\Sandbox\Docker; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxExecution; use Symfony\Component\Process\Exception\ProcessFailedException; use Symfony\Component\Process\Process; diff --git a/src/Process/DockerSandboxFactory.php b/src/Process/Sandbox/Docker/DockerSandboxFactory.php similarity index 93% rename from src/Process/DockerSandboxFactory.php rename to src/Process/Sandbox/Docker/DockerSandboxFactory.php index c1be1963..0d9f4b2b 100644 --- a/src/Process/DockerSandboxFactory.php +++ b/src/Process/Sandbox/Docker/DockerSandboxFactory.php @@ -2,8 +2,10 @@ declare(strict_types=1); -namespace PhpSchool\PhpWorkshop\Process; +namespace PhpSchool\PhpWorkshop\Process\Sandbox\Docker; +use PhpSchool\PhpWorkshop\Process\ProcessNotFoundException; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxFactory; use PhpSchool\PhpWorkshop\Exercise\Scenario\ExerciseScenario; use PhpSchool\PhpWorkshop\Process\Port\FreePortPicker; use PhpSchool\PhpWorkshop\Process\Port\PortPicker; diff --git a/src/Process/HostSandbox.php b/src/Process/Sandbox/Host/HostSandbox.php similarity index 89% rename from src/Process/HostSandbox.php rename to src/Process/Sandbox/Host/HostSandbox.php index 634d0b4e..3895825e 100644 --- a/src/Process/HostSandbox.php +++ b/src/Process/Sandbox/Host/HostSandbox.php @@ -2,8 +2,11 @@ declare(strict_types=1); -namespace PhpSchool\PhpWorkshop\Process; +namespace PhpSchool\PhpWorkshop\Process\Sandbox\Host; +use PhpSchool\PhpWorkshop\Process\ProcessNotFoundException; +use PhpSchool\PhpWorkshop\Process\Sandbox\ProcessInput; +use PhpSchool\PhpWorkshop\Process\Sandbox\Sandbox; use Symfony\Component\Process\ExecutableFinder; use Symfony\Component\Process\Process; diff --git a/src/Process/HostSandboxExecution.php b/src/Process/Sandbox/Host/HostSandboxExecution.php similarity index 90% rename from src/Process/HostSandboxExecution.php rename to src/Process/Sandbox/Host/HostSandboxExecution.php index aac40ced..20f350d3 100644 --- a/src/Process/HostSandboxExecution.php +++ b/src/Process/Sandbox/Host/HostSandboxExecution.php @@ -2,8 +2,9 @@ declare(strict_types=1); -namespace PhpSchool\PhpWorkshop\Process; +namespace PhpSchool\PhpWorkshop\Process\Sandbox\Host; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxExecution; use Symfony\Component\Process\Process; final class HostSandboxExecution implements SandboxExecution diff --git a/src/Process/HostSandboxFactory.php b/src/Process/Sandbox/Host/HostSandboxFactory.php similarity index 84% rename from src/Process/HostSandboxFactory.php rename to src/Process/Sandbox/Host/HostSandboxFactory.php index 5aa1bb1e..ef592fcb 100644 --- a/src/Process/HostSandboxFactory.php +++ b/src/Process/Sandbox/Host/HostSandboxFactory.php @@ -2,8 +2,9 @@ declare(strict_types=1); -namespace PhpSchool\PhpWorkshop\Process; +namespace PhpSchool\PhpWorkshop\Process\Sandbox\Host; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxFactory; use PhpSchool\PhpWorkshop\Exercise\Scenario\ExerciseScenario; use PhpSchool\PhpWorkshop\Process\Port\FreePortPicker; use Symfony\Component\Process\ExecutableFinder; diff --git a/src/Process/ProcessInput.php b/src/Process/Sandbox/ProcessInput.php similarity index 93% rename from src/Process/ProcessInput.php rename to src/Process/Sandbox/ProcessInput.php index 605e4dfc..353a8389 100644 --- a/src/Process/ProcessInput.php +++ b/src/Process/Sandbox/ProcessInput.php @@ -1,6 +1,6 @@ Date: Sun, 1 Nov 2026 14:46:48 +0100 Subject: [PATCH 08/10] Describe ProcessInput --- src/Process/Sandbox/ProcessInput.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/Process/Sandbox/ProcessInput.php b/src/Process/Sandbox/ProcessInput.php index 353a8389..beb45fae 100644 --- a/src/Process/Sandbox/ProcessInput.php +++ b/src/Process/Sandbox/ProcessInput.php @@ -2,11 +2,16 @@ namespace PhpSchool\PhpWorkshop\Process\Sandbox; +/** + * The command to run in a sandbox, eg. `php solution.php 0.0.0.0 54321`. + */ class ProcessInput { /** - * @param list $args - * @param array $env + * @param string $executable eg. php or php-cgi + * @param list $args eg. ['solution.php', '0.0.0.0', '54321'] + * @param array $env extra env vars, eg. the request for php-cgi + * @param string|null $input written to stdin, eg. the request body for php-cgi */ public function __construct( private string $executable, From 9bb98508c0874b7ced656c9b67c279c9d563fa99 Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 14:48:50 +0100 Subject: [PATCH 09/10] SandboxExecution docs: no implementation detail --- src/Process/Sandbox/SandboxExecution.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Process/Sandbox/SandboxExecution.php b/src/Process/Sandbox/SandboxExecution.php index 1a4fc95d..7a5c1690 100644 --- a/src/Process/Sandbox/SandboxExecution.php +++ b/src/Process/Sandbox/SandboxExecution.php @@ -5,7 +5,7 @@ namespace PhpSchool\PhpWorkshop\Process\Sandbox; /** - * One run of some code in a sandbox. How many commands that takes is up to the sandbox. + * One run of some code in a sandbox. */ interface SandboxExecution { From e41d0a40c8dbce2abb89e4fe73d572cd085b641c Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 14:53:08 +0100 Subject: [PATCH 10/10] One SandboxExecution class instead of an interface with host and docker versions --- src/Process/Sandbox/Docker/DockerSandbox.php | 8 +- .../Sandbox/Docker/DockerSandboxExecution.php | 90 ------------------- src/Process/Sandbox/Host/HostSandbox.php | 7 +- .../Sandbox/Host/HostSandboxExecution.php | 53 ----------- src/Process/Sandbox/SandboxExecution.php | 50 ++++++++--- test/Exception/CodeExecutionExceptionTest.php | 25 ++---- .../Docker/DockerSandboxExecutionTest.php | 47 ---------- 7 files changed, 52 insertions(+), 228 deletions(-) delete mode 100644 src/Process/Sandbox/Docker/DockerSandboxExecution.php delete mode 100644 src/Process/Sandbox/Host/HostSandboxExecution.php delete mode 100644 test/Process/Sandbox/Docker/DockerSandboxExecutionTest.php diff --git a/src/Process/Sandbox/Docker/DockerSandbox.php b/src/Process/Sandbox/Docker/DockerSandbox.php index a29e23ba..dd4a70e0 100644 --- a/src/Process/Sandbox/Docker/DockerSandbox.php +++ b/src/Process/Sandbox/Docker/DockerSandbox.php @@ -6,6 +6,7 @@ use PhpSchool\PhpWorkshop\Process\Sandbox\ProcessInput; use PhpSchool\PhpWorkshop\Process\Sandbox\Sandbox; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxExecution; use Symfony\Component\Process\Process; /** @@ -31,7 +32,7 @@ public function __construct( private string $portsHost, ) {} - public function execute(ProcessInput $processInput): DockerSandboxExecution + public function execute(ProcessInput $processInput): SandboxExecution { $network = ['--network', 'none']; if ($this->port !== null) { @@ -45,8 +46,7 @@ public function execute(ProcessInput $processInput): DockerSandboxExecution $envArgs[] = $key . '=' . $value; } - //no steps around it yet, create/cp/rm come when files are copied in instead of mounted - return new DockerSandboxExecution(new Process( + return new SandboxExecution(new Process( [ $this->docker, 'run', @@ -89,7 +89,7 @@ public function execute(ProcessInput $processInput): DockerSandboxExecution null, $processInput->getInput(), self::TIMEOUT + 5, - ), [], [], $this->portsHost, $this->port); + ), $this->portsHost, $this->port); } public function getPort(): int diff --git a/src/Process/Sandbox/Docker/DockerSandboxExecution.php b/src/Process/Sandbox/Docker/DockerSandboxExecution.php deleted file mode 100644 index c9a6d451..00000000 --- a/src/Process/Sandbox/Docker/DockerSandboxExecution.php +++ /dev/null @@ -1,90 +0,0 @@ - $before - * @param list $after - * @param string $host the docker host's address that ports are published on, eg. 10.0.0.5 - * @param int|null $port published on the host with the same number, eg. 54321 - */ - public function __construct( - public readonly Process $process, - public readonly array $before = [], - public readonly array $after = [], - private string $host = '127.0.0.1', - private ?int $port = null, - ) {} - - public function start(): void - { - foreach ($this->before as $step) { - $step->mustRun(); - } - - $this->process->start(); - } - - public function wait(?callable $callback = null): int - { - try { - return $this->process->wait($callback); - } finally { - $this->runAfter(); - } - } - - public function mustRun(): void - { - $this->start(); - $this->wait(); - - if (!$this->process->isSuccessful()) { - throw new ProcessFailedException($this->process); - } - } - - public function isSuccessful(): bool - { - return $this->process->isSuccessful(); - } - - public function getOutput(): string - { - return $this->process->getOutput(); - } - - public function getErrorOutput(): string - { - return $this->process->getErrorOutput(); - } - - public function getAddress(): string - { - return $this->host . ':' . $this->getPort(); - } - - public function getPort(): int - { - return $this->port ?? throw new \RuntimeException('The code does not listen on a port'); - } - - private function runAfter(): void - { - foreach ($this->after as $step) { - //cleanup, so keep going if one fails - $step->run(); - } - } -} diff --git a/src/Process/Sandbox/Host/HostSandbox.php b/src/Process/Sandbox/Host/HostSandbox.php index 3895825e..15cc308f 100644 --- a/src/Process/Sandbox/Host/HostSandbox.php +++ b/src/Process/Sandbox/Host/HostSandbox.php @@ -7,6 +7,7 @@ use PhpSchool\PhpWorkshop\Process\ProcessNotFoundException; use PhpSchool\PhpWorkshop\Process\Sandbox\ProcessInput; use PhpSchool\PhpWorkshop\Process\Sandbox\Sandbox; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxExecution; use Symfony\Component\Process\ExecutableFinder; use Symfony\Component\Process\Process; @@ -22,7 +23,7 @@ final class HostSandbox implements Sandbox public function __construct(private string $directory, private ?int $port, private ExecutableFinder $executableFinder) {} - public function execute(ProcessInput $processInput): HostSandboxExecution + public function execute(ProcessInput $processInput): SandboxExecution { $executablePath = $this->executableFinder->find($processInput->getExecutable()); @@ -30,13 +31,13 @@ public function execute(ProcessInput $processInput): HostSandboxExecution throw ProcessNotFoundException::fromExecutable($processInput->getExecutable()); } - return new HostSandboxExecution(new Process( + return new SandboxExecution(new Process( [$executablePath, ...$processInput->getArgs()], $this->directory, array_merge($this->getDefaultEnv(), $processInput->getEnv()), $processInput->getInput(), 10, - ), $this->port); + ), '127.0.0.1', $this->port); } public function getPort(): int diff --git a/src/Process/Sandbox/Host/HostSandboxExecution.php b/src/Process/Sandbox/Host/HostSandboxExecution.php deleted file mode 100644 index 20f350d3..00000000 --- a/src/Process/Sandbox/Host/HostSandboxExecution.php +++ /dev/null @@ -1,53 +0,0 @@ -process->start(); - } - - public function wait(?callable $callback = null): int - { - return $this->process->wait($callback); - } - - public function mustRun(): void - { - $this->process->mustRun(); - } - - public function isSuccessful(): bool - { - return $this->process->isSuccessful(); - } - - public function getOutput(): string - { - return $this->process->getOutput(); - } - - public function getErrorOutput(): string - { - return $this->process->getErrorOutput(); - } - - public function getAddress(): string - { - return '127.0.0.1:' . $this->getPort(); - } - - public function getPort(): int - { - return $this->port ?? throw new \RuntimeException('The code does not listen on a port'); - } -} diff --git a/src/Process/Sandbox/SandboxExecution.php b/src/Process/Sandbox/SandboxExecution.php index 7a5c1690..9f77a289 100644 --- a/src/Process/Sandbox/SandboxExecution.php +++ b/src/Process/Sandbox/SandboxExecution.php @@ -4,38 +4,62 @@ namespace PhpSchool\PhpWorkshop\Process\Sandbox; +use Symfony\Component\Process\Process; + /** * One run of some code in a sandbox. */ -interface SandboxExecution +final class SandboxExecution { - public function start(): void; + /** + * @param string $host where the port is reachable, eg. 127.0.0.1 or the docker host's address + * @param int|null $port the code listens on, eg. 54321 + */ + public function __construct(public readonly Process $process, private string $host = '127.0.0.1', private ?int $port = null) {} + + public function start(): void + { + $this->process->start(); + } /** * @param (callable(string, string): void)|null $callback receives the output as it comes */ - public function wait(?callable $callback = null): int; + public function wait(?callable $callback = null): int + { + return $this->process->wait($callback); + } /** * @throws \Symfony\Component\Process\Exception\ProcessFailedException if it fails */ - public function mustRun(): void; + public function mustRun(): void + { + $this->process->mustRun(); + } - public function isSuccessful(): bool; + public function isSuccessful(): bool + { + return $this->process->isSuccessful(); + } - public function getOutput(): string; + public function getOutput(): string + { + return $this->process->getOutput(); + } - public function getErrorOutput(): string; + public function getErrorOutput(): string + { + return $this->process->getErrorOutput(); + } /** * Where to connect to the port the code listens on, once it has started. * * @return string eg. '127.0.0.1:54321' */ - public function getAddress(): string; - - /** - * The port the code listens on, eg. to pass it in the args. - */ - public function getPort(): int; + public function getAddress(): string + { + return $this->host . ':' . ($this->port ?? throw new \RuntimeException('The code does not listen on a port')); + } } diff --git a/test/Exception/CodeExecutionExceptionTest.php b/test/Exception/CodeExecutionExceptionTest.php index 3f47ecaa..542a8515 100644 --- a/test/Exception/CodeExecutionExceptionTest.php +++ b/test/Exception/CodeExecutionExceptionTest.php @@ -5,6 +5,7 @@ use PhpSchool\PhpWorkshop\Exception\CodeExecutionException; use PHPUnit\Framework\TestCase; use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxExecution; +use Symfony\Component\Process\Process; class CodeExecutionExceptionTest extends TestCase { @@ -16,31 +17,19 @@ public function testException(): void public function testFromProcessUsesErrorOutputIfNotEmpty(): void { - $process = $this->createMock(SandboxExecution::class); + $execution = new SandboxExecution(Process::fromShellCommandline('echo "Std Output"; echo "Error Output" >&2')); + $execution->mustRun(); - $process - ->expects($this->once()) - ->method('getErrorOutput') - ->willReturn('Error Output'); - - $e = CodeExecutionException::fromExecution($process); + $e = CodeExecutionException::fromExecution($execution); $this->assertEquals('PHP Code failed to execute. Error: "Error Output"', $e->getMessage()); } public function testFromProcessUsesStdOutputIfErrorOutputEmpty(): void { - $process = $this->createMock(SandboxExecution::class); - $process - ->expects($this->once()) - ->method('getErrorOutput') - ->willReturn(''); - - $process - ->expects($this->once()) - ->method('getOutput') - ->willReturn('Std Output'); + $execution = new SandboxExecution(Process::fromShellCommandline('echo "Std Output"')); + $execution->mustRun(); - $e = CodeExecutionException::fromExecution($process); + $e = CodeExecutionException::fromExecution($execution); $this->assertEquals('PHP Code failed to execute. Error: "Std Output"', $e->getMessage()); } } diff --git a/test/Process/Sandbox/Docker/DockerSandboxExecutionTest.php b/test/Process/Sandbox/Docker/DockerSandboxExecutionTest.php deleted file mode 100644 index 092c4c35..00000000 --- a/test/Process/Sandbox/Docker/DockerSandboxExecutionTest.php +++ /dev/null @@ -1,47 +0,0 @@ -> ' . $log), - [Process::fromShellCommandline('echo before >> ' . $log)], - [Process::fromShellCommandline('echo after >> ' . $log)], - ); - - $execution->start(); - $execution->wait(); - - $this->assertSame("before\nmain\nafter\n", file_get_contents($log)); - unlink($log); - } - - public function testAfterStepsRunWhenTheMainProcessFails(): void - { - $log = tempnam(sys_get_temp_dir(), 'steps'); - - $execution = new DockerSandboxExecution( - Process::fromShellCommandline('exit 1'), - [], - [Process::fromShellCommandline('echo after >> ' . $log)], - ); - - $execution->start(); - $execution->wait(); - - $this->assertFalse($execution->isSuccessful()); - $this->assertSame("after\n", file_get_contents($log)); - unlink($log); - } -}