From b9b8accf1813cc7230680c6c51d951c556a0767f Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 08:38:40 +0100 Subject: [PATCH] Run composer on the host, not in the sandbox Package plugins and scripts never run, so no package code does. vendor is then just another file of the solution, so DockerSandbox drops its composer handling, the composer cache volume and vendorVolumes. --- app/config.php | 7 ++- src/Listener/PrepareSolutionListener.php | 16 ++---- src/Process/Composer.php | 45 ++++++++++++++++ src/Process/DockerSandbox.php | 44 ++------------- src/ReferencePackages.php | 11 ++-- test/Listener/PrepareSolutionListenerTest.php | 10 ++-- test/Process/ComposerTest.php | 38 +++++++++++++ test/Process/DockerSandboxTest.php | 54 +++---------------- test/ReferencePackagesTest.php | 4 +- 9 files changed, 112 insertions(+), 117 deletions(-) create mode 100644 src/Process/Composer.php create mode 100644 test/Process/ComposerTest.php diff --git a/app/config.php b/app/config.php index 41e140cd..bc02fbcf 100644 --- a/app/config.php +++ b/app/config.php @@ -71,6 +71,7 @@ use PhpSchool\PhpWorkshop\Output\OutputInterface; 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; @@ -280,7 +281,7 @@ }, ReferencePackages::class => function (ContainerInterface $c) { - return new ReferencePackages($c->get(ExerciseRepository::class), $c->get(Sandbox::class)); + return new ReferencePackages($c->get(ExerciseRepository::class), new Composer()); }, //Listeners @@ -288,9 +289,7 @@ return new InitialCodeListener($c->get('currentWorkingDirectory'), $c->get(LoggerInterface::class)); }, PrepareSolutionListener::class => function (ContainerInterface $c) { - return new PrepareSolutionListener( - $c->get(Sandbox::class), - ); + return new PrepareSolutionListener(new Composer()); }, CodePatchListener::class => function (ContainerInterface $c) { return new CodePatchListener( diff --git a/src/Listener/PrepareSolutionListener.php b/src/Listener/PrepareSolutionListener.php index 90df8463..a1f0e054 100644 --- a/src/Listener/PrepareSolutionListener.php +++ b/src/Listener/PrepareSolutionListener.php @@ -7,19 +7,15 @@ use PhpSchool\PhpWorkshop\Event\ExerciseRunnerEvent; use PhpSchool\PhpWorkshop\Exercise\ProvidesSolution; use PhpSchool\PhpWorkshop\Exception\RuntimeException; -use PhpSchool\PhpWorkshop\Process\Sandbox; -use PhpSchool\PhpWorkshop\Process\ProcessInput; -use PhpSchool\PhpWorkshop\Process\SandboxExecution; +use PhpSchool\PhpWorkshop\Process\Composer; +use Symfony\Component\Process\Process; /** * Listener to install composer deps for an exercise solution, offline when ReferencePackages has warmed the cache */ class PrepareSolutionListener { - public function __construct(private Sandbox $sandbox) - { - $this->sandbox = $sandbox; - } + public function __construct(private Composer $composer) {} /** * @param ExerciseRunnerEvent $event @@ -63,10 +59,8 @@ public function __invoke(ExerciseRunnerEvent $event): void /** * @param array $env */ - private function install(ExerciseRunnerEvent $event, array $env): SandboxExecution + private function install(ExerciseRunnerEvent $event, array $env): Process { - return $this->sandbox->create( - new ProcessInput('composer', ['install', '--no-interaction'], $event->getContext()->getReferenceExecutionDirectory(), $env, []), - ); + return $this->composer->create(['install'], $event->getContext()->getReferenceExecutionDirectory(), $env); } } diff --git a/src/Process/Composer.php b/src/Process/Composer.php new file mode 100644 index 00000000..5f4a810c --- /dev/null +++ b/src/Process/Composer.php @@ -0,0 +1,45 @@ +executableFinder = $executableFinder ?? new ExecutableFinder(); + } + + /** + * @param list $args eg. ['install'] + * @param array $env eg. ['COMPOSER_DISABLE_NETWORK' => '1'] + */ + public function create(array $args, string $directory, array $env = []): Process + { + $composer = $this->executableFinder->find('composer'); + if ($composer === null) { + throw ProcessNotFoundException::fromExecutable('composer'); + } + + return new Process( + [$composer, ...$args, '--no-interaction', '--no-plugins', '--no-scripts'], + $directory, + $env, + null, + self::TIMEOUT, + ); + } +} diff --git a/src/Process/DockerSandbox.php b/src/Process/DockerSandbox.php index c4b9d9bf..8c0bff1d 100644 --- a/src/Process/DockerSandbox.php +++ b/src/Process/DockerSandbox.php @@ -15,8 +15,6 @@ final class DockerSandbox implements Sandbox { private const TIMEOUT = 30; - //a named volume, so it lives on the docker host, which may not be this machine - private const COMPOSER_CACHE_VOLUME = 'php-school-composer-cache'; private ExecutableFinder $executableFinder; private string $basePath; @@ -24,22 +22,12 @@ final class DockerSandbox implements Sandbox private string $portsNetwork; private string $portsHost; - /** - * @var array - */ - private array $vendorVolumes; - - /** - * @param array $vendorVolumes folder => volume, for runs in a folder directly inside it, so vendor - * stays on the docker host between runs, eg. ['/tmp/php-school/' => 'php-school-vendor--'] - */ public function __construct( string $basePath, string $projectName, ?ExecutableFinder $executableFinder = null, string $portsNetwork = 'bridge', string $portsHost = '127.0.0.1', - array $vendorVolumes = [], ) { $this->executableFinder = $executableFinder ?? new ExecutableFinder(); $this->basePath = $basePath; @@ -49,7 +37,6 @@ public function __construct( $this->portsNetwork = $portsNetwork; //the address ports are published on, the docker host's private address when it is remote $this->portsHost = $portsHost; - $this->vendorVolumes = $vendorVolumes; } public function getImageName(): string @@ -78,30 +65,8 @@ public function getHost(): SandboxHost public function create(ProcessInput $processInput): DockerExecution { - $isComposer = $processInput->getExecutable() === 'composer'; - - $args = $processInput->getArgs(); - $mounts = [$processInput->getWorkingDirectory() . ':/solution']; - - $vendorVolume = $this->vendorVolumes[dirname($processInput->getWorkingDirectory())] ?? null; - if ($vendorVolume !== null) { - //only composer writes to it - $mounts[] = $vendorVolume . ':/solution/vendor' . ($isComposer ? '' : ':ro'); - } - - $env = ['COMPOSER_HOME' => '/composer']; - - if ($isComposer) { - //we need to mount a volume for composer cache, and never run package plugins or scripts - $mounts[] = self::COMPOSER_CACHE_VOLUME . ':/composer'; - $args = [...$args, '--no-plugins', '--no-scripts']; - } - $network = ['--network', 'none']; - if ($isComposer) { - //composer needs to download packages - $network = ['--network', 'bridge']; - } elseif (count($processInput->getExposedPorts()) > 0) { + if (count($processInput->getExposedPorts()) > 0) { $network = ['--network', $this->portsNetwork]; foreach ($processInput->getExposedPorts() as $port) { $network[] = '-p'; @@ -110,7 +75,7 @@ public function create(ProcessInput $processInput): DockerExecution } $envArgs = []; - foreach ([...$processInput->getEnv(), ...$env] as $key => $value) { + foreach ($processInput->getEnv() as $key => $value) { $envArgs[] = '-e'; $envArgs[] = $key . '=' . $value; } @@ -142,7 +107,8 @@ public function create(ProcessInput $processInput): DockerExecution '--cpus', '1', ...$envArgs, - ...array_merge(...array_map(fn($mount) => ['-v', $mount], $mounts)), + '-v', + $processInput->getWorkingDirectory() . ':/solution', '-w', '/solution', $this->getImageName(), @@ -152,7 +118,7 @@ public function create(ProcessInput $processInput): DockerExecution 'KILL', (string) self::TIMEOUT, $processInput->getExecutable(), - ...$args, + ...$processInput->getArgs(), ], $this->basePath, null, diff --git a/src/ReferencePackages.php b/src/ReferencePackages.php index 85c0a00a..19453973 100644 --- a/src/ReferencePackages.php +++ b/src/ReferencePackages.php @@ -6,8 +6,7 @@ use PhpSchool\PhpWorkshop\Exception\RuntimeException; use PhpSchool\PhpWorkshop\Exercise\ProvidesSolution; -use PhpSchool\PhpWorkshop\Process\ProcessInput; -use PhpSchool\PhpWorkshop\Process\Sandbox; +use PhpSchool\PhpWorkshop\Process\Composer; use Symfony\Component\Filesystem\Filesystem; /** @@ -18,7 +17,7 @@ class ReferencePackages { private Filesystem $filesystem; - public function __construct(private ExerciseRepository $exerciseRepository, private Sandbox $sandbox) + public function __construct(private ExerciseRepository $exerciseRepository, private Composer $composer) { $this->filesystem = new Filesystem(); } @@ -36,12 +35,8 @@ public function warm(): void $this->filesystem->remove($directory . '/vendor'); //keeps a committed composer.lock, or writes one next to the solution. It is copied with it on each verify - $execution = $this->sandbox->create( - new ProcessInput('composer', ['install', '--no-interaction'], $directory, [], []), - ); - try { - $execution->mustRun(); + $this->composer->create(['install'], $directory)->mustRun(); } catch (\Symfony\Component\Process\Exception\RuntimeException $e) { throw new RuntimeException(sprintf('Composer packages for "%s" could not be installed', $exercise->getName()), 0, $e); } diff --git a/test/Listener/PrepareSolutionListenerTest.php b/test/Listener/PrepareSolutionListenerTest.php index ddd575b5..313a0898 100644 --- a/test/Listener/PrepareSolutionListenerTest.php +++ b/test/Listener/PrepareSolutionListenerTest.php @@ -5,7 +5,7 @@ use PhpSchool\PhpWorkshop\Event\ExerciseRunnerEvent; use PhpSchool\PhpWorkshop\ExerciseRunner\Context\TestContext; use PhpSchool\PhpWorkshop\Listener\PrepareSolutionListener; -use PhpSchool\PhpWorkshop\Process\HostSandbox; +use PhpSchool\PhpWorkshop\Process\Composer; use PhpSchool\PhpWorkshop\Process\ProcessNotFoundException; use PhpSchool\PhpWorkshop\Solution\SolutionInterface; use PhpSchool\PhpWorkshopTest\Asset\CliExerciseImpl; @@ -33,7 +33,7 @@ public function testIfSolutionRequiresComposerButComposerCannotBeLocatedExceptio $this->expectException(ProcessNotFoundException::class); $this->expectExceptionMessage('Could not find executable: "composer"'); $event = new ExerciseRunnerEvent('event', $context); - (new PrepareSolutionListener(new HostSandbox($finder)))->__invoke($event); + (new PrepareSolutionListener(new Composer($finder)))->__invoke($event); } public function testIfSolutionRequiresComposerButVendorDirExistsNothingIsDone(): void @@ -54,7 +54,7 @@ public function testIfSolutionRequiresComposerButVendorDirExistsNothingIsDone(): $exercise->setSolution($solution); $event = new ExerciseRunnerEvent('event', $context); - (new PrepareSolutionListener(new HostSandbox()))->__invoke($event); + (new PrepareSolutionListener(new Composer()))->__invoke($event); $this->assertFileExists(sprintf('%s/vendor', $context->getReferenceExecutionDirectory())); //check for non existence of lock file, composer generates this when updating if it doesn't exist @@ -84,7 +84,7 @@ public function testIfSolutionRequiresComposerComposerInstallIsExecuted(): void $exercise->setSolution($solution); $event = new ExerciseRunnerEvent('event', $context); - (new PrepareSolutionListener(new HostSandbox()))->__invoke($event); + (new PrepareSolutionListener(new Composer()))->__invoke($event); $this->assertFileExists(sprintf('%s/vendor', $context->getReferenceExecutionDirectory())); } @@ -119,7 +119,7 @@ public function testExceptionIsThrownIfDependenciesCannotBeResolved(): void ->willReturn(true); $event = new ExerciseRunnerEvent('event', $context); - (new PrepareSolutionListener(new HostSandbox()))->__invoke($event); + (new PrepareSolutionListener(new Composer()))->__invoke($event); $this->assertFileExists(sprintf('%s/vendor', $context->getReferenceExecutionDirectory())); } diff --git a/test/Process/ComposerTest.php b/test/Process/ComposerTest.php new file mode 100644 index 00000000..0b675c71 --- /dev/null +++ b/test/Process/ComposerTest.php @@ -0,0 +1,38 @@ +createMock(ExecutableFinder::class); + $finder->method('find')->with('composer')->willReturn('/usr/local/bin/composer'); + + $process = (new Composer($finder))->create(['install'], __DIR__, ['COMPOSER_DISABLE_NETWORK' => '1']); + + static::assertSame( + "'/usr/local/bin/composer' 'install' '--no-interaction' '--no-plugins' '--no-scripts'", + $process->getCommandLine(), + ); + static::assertSame(__DIR__, $process->getWorkingDirectory()); + static::assertSame(['COMPOSER_DISABLE_NETWORK' => '1'], $process->getEnv()); + } + + public function testThrowsIfComposerIsNotFound(): void + { + $finder = $this->createMock(ExecutableFinder::class); + $finder->method('find')->with('composer')->willReturn(null); + + $this->expectException(ProcessNotFoundException::class); + + (new Composer($finder))->create(['install'], __DIR__); + } +} diff --git a/test/Process/DockerSandboxTest.php b/test/Process/DockerSandboxTest.php index 399f27ab..3a523190 100644 --- a/test/Process/DockerSandboxTest.php +++ b/test/Process/DockerSandboxTest.php @@ -53,7 +53,7 @@ public function testCreateThrowsExceptionIfDockerNotFound(): void ->willReturn(null); $factory = new DockerSandbox('/docker-dir', 'php8appreciate', $finder); - $input = new ProcessInput('composer', [], __DIR__, [], []); + $input = new ProcessInput('php', [], __DIR__, [], []); $factory->create($input); } @@ -64,7 +64,7 @@ public function testCreateIsIsolatedWithNoNetwork(): void $expected = $this->expectedCommand( ['--network', 'none'], - ['-e', 'COMPOSER_HOME=/composer', '-v', __DIR__ . ':/solution'], + ['-v', __DIR__ . ':/solution'], ['php', 'one', 'two'], ); static::assertSame($expected, $process->getCommandLine()); @@ -72,55 +72,13 @@ public function testCreateIsIsolatedWithNoNetwork(): void static::assertSame(35.0, $process->getTimeout()); } - public function testComposerGetsNetworkCacheAndNoPluginsOrScripts(): void - { - $process = $this->factory()->create(new ProcessInput('composer', ['install'], __DIR__, [], []))->process; - - $expected = $this->expectedCommand( - ['--network', 'bridge'], - ['-e', 'COMPOSER_HOME=/composer', '-v', __DIR__ . ':/solution', '-v', 'php-school-composer-cache:/composer'], - ['composer', 'install', '--no-plugins', '--no-scripts'], - ); - static::assertSame($expected, $process->getCommandLine()); - } - - public function testVendorVolumeIsWritableForComposerOnly(): void - { - $sandbox = new DockerSandbox('/docker-dir', 'php8appreciate', $this->anyFinder(), vendorVolumes: ['/tmp/student' => 'vendor-student']); - - $composer = $sandbox->create(new ProcessInput('composer', ['update'], '/tmp/student/abc', [], []))->process; - static::assertStringContainsString("'-v' 'vendor-student:/solution/vendor' ", $composer->getCommandLine()); - - $php = $sandbox->create(new ProcessInput('php', ['solution.php'], '/tmp/student/def', [], []))->process; - static::assertStringContainsString("'-v' 'vendor-student:/solution/vendor:ro' ", $php->getCommandLine()); - } - - public function testFoldersOutsideTheVendorVolumesKeepTheirOwnVendor(): void - { - $sandbox = new DockerSandbox('/docker-dir', 'php8appreciate', $this->anyFinder(), vendorVolumes: ['/tmp/student' => 'vendor-student']); - - //eg. the reference solution, a sibling folder whose name starts the same, or the listed folder itself - foreach (['/tmp/reference/abc', '/tmp/student-2/abc', '/tmp/student'] as $directory) { - $process = $sandbox->create(new ProcessInput('composer', ['install'], $directory, [], []))->process; - static::assertStringNotContainsString('vendor-student', $process->getCommandLine()); - } - } - - private function anyFinder(): ExecutableFinder - { - $finder = $this->createMock(ExecutableFinder::class); - $finder->method('find')->with('docker')->willReturn('/usr/local/bin/docker'); - - return $finder; - } - public function testExposedPortsArePublishedOnLoopbackOnly(): void { $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, [], [8000]))->process; $expected = $this->expectedCommand( ['--network', 'bridge', '-p', '127.0.0.1:8000:8000'], - ['-e', 'COMPOSER_HOME=/composer', '-v', __DIR__ . ':/solution'], + ['-v', __DIR__ . ':/solution'], ['php'], ); static::assertSame($expected, $process->getCommandLine()); @@ -132,7 +90,7 @@ public function testExposedPortsUseTheGivenNetwork(): void $expected = $this->expectedCommand( ['--network', 'php-school-sandbox', '-p', '127.0.0.1:8000:8000'], - ['-e', 'COMPOSER_HOME=/composer', '-v', __DIR__ . ':/solution'], + ['-v', __DIR__ . ':/solution'], ['php'], ); static::assertSame($expected, $process->getCommandLine()); @@ -144,7 +102,7 @@ public function testExposedPortsArePublishedOnTheGivenHost(): void $expected = $this->expectedCommand( ['--network', 'bridge', '-p', '172.19.0.2:8000:8000'], - ['-e', 'COMPOSER_HOME=/composer', '-v', __DIR__ . ':/solution'], + ['-v', __DIR__ . ':/solution'], ['php'], ); static::assertSame($expected, $process->getCommandLine()); @@ -163,7 +121,7 @@ public function testCreateWithEnv(): void $expected = $this->expectedCommand( ['--network', 'none'], - ['-e', 'SOME_VAR=value', '-e', 'COMPOSER_HOME=/composer', '-v', __DIR__ . ':/solution'], + ['-e', 'SOME_VAR=value', '-v', __DIR__ . ':/solution'], ['php'], ); static::assertSame($expected, $process->getCommandLine()); diff --git a/test/ReferencePackagesTest.php b/test/ReferencePackagesTest.php index f0294ff7..059ffe43 100644 --- a/test/ReferencePackagesTest.php +++ b/test/ReferencePackagesTest.php @@ -5,7 +5,7 @@ namespace PhpSchool\PhpWorkshopTest; use PhpSchool\PhpWorkshop\ExerciseRepository; -use PhpSchool\PhpWorkshop\Process\HostSandbox; +use PhpSchool\PhpWorkshop\Process\Composer; use PhpSchool\PhpWorkshop\ReferencePackages; use PhpSchool\PhpWorkshop\Solution\DirectorySolution; use PhpSchool\PhpWorkshop\Utils\System; @@ -25,7 +25,7 @@ public function testWarmLocksEachSolutionWithPackages(): void $withPackages = new CliExerciseImpl(); $withPackages->setSolution(DirectorySolution::fromDirectory($directory)); - (new ReferencePackages(new ExerciseRepository([$withPackages]), new HostSandbox()))->warm(); + (new ReferencePackages(new ExerciseRepository([$withPackages]), new Composer()))->warm(); $this->assertFileExists($directory . '/composer.lock'); $this->assertDirectoryDoesNotExist($directory . '/vendor');