jdecool/scaleway-runtimepublic Fork
⑂ 74ba5e0
Commits
⬇ Clone ▾
git clone https://git.rickub.com/jdecool/scaleway-runtime.git
git clone ssh://git@rickub.com/jdecool/scaleway-runtime.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

feat(package)!: let Scaleway install the dependenciesUnverified

The probe showed that Scaleway runs composer install --no-dev from the
shipped composer.lock at deploy time, replacing any shipped vendor/, and
that the code dir is writable. scaleway-package now zips the sources with
composer.json and composer.lock only, and refuses a missing or stale lock
and path repositories, which Scaleway cannot resolve. The cache is built
at the first Invocation, and a read-only project only keeps var/cache as
build dir when a container was warmed there.

ADR 0008 supersedes ADR 0003.
Jérémy DECOOL committed 2026-11-14T11:57:02+01:00 Browse files
74ba5e0 parent: c711fe6
modified docs/adr/0003-ship-vendor-and-warm-cache-in-zip.md +4 -0
@@ -1,3 +1,7 @@
1+---
2+status: superseded by ADR-0008
3+---
4+
15 # The deployment zip ships vendor/ and a warmed-up cache
26
37 Scaleway can install Composer dependencies itself at deploy time, which is its documented path.
@@ -1,3 +1,7 @@
1+---
2+status: superseded by ADR-0008
3+---
4+
1 # The deployment zip ships vendor/ and a warmed-up cache5 # The deployment zip ships vendor/ and a warmed-up cache
2 6
3 Scaleway can install Composer dependencies itself at deploy time, which is its documented path.7 Scaleway can install Composer dependencies itself at deploy time, which is its documented path.
modified docs/adr/0006-default-to-the-prod-env.md +1 -1
@@ -1,6 +1,6 @@
11 # The Handler defaults APP_ENV to prod, whatever the .env files say
22
3-The zip ships `.env` as committed (ADR 0003), and the one Symfony generates says `APP_ENV=dev`.
3+The zip ships `.env` as committed (ADR 0003, then ADR 0008), and the one Symfony generates says `APP_ENV=dev`.
44 With Symfony's usual precedence, a function deployed without an `APP_ENV` variable would therefore run dev with debug on, and show stack traces to anyone; on a read-only code directory, every Invocation even answers a 500 whose body is the full trace, as the dev container cannot be built next to the prod one warmed in the zip.
55 We therefore make `ScalewayRuntime`, which only the Handler uses, set the `env` option to the `APP_ENV` of the process environment (`$_SERVER`, `$_ENV`, then `getenv()`), or to `prod` when it is unset or empty, before Dotenv runs.
66 Dotenv never overrides a variable already set, so `.env` files can no longer choose the env, and `APP_DEBUG` follows `prod`, off unless set by the environment or a `.env` file.
@@ -1,6 +1,6 @@
1 # The Handler defaults APP_ENV to prod, whatever the .env files say1 # The Handler defaults APP_ENV to prod, whatever the .env files say
2 2
3-The zip ships `.env` as committed (ADR 0003), and the one Symfony generates says `APP_ENV=dev`.3+The zip ships `.env` as committed (ADR 0003, then ADR 0008), and the one Symfony generates says `APP_ENV=dev`.
4 With Symfony's usual precedence, a function deployed without an `APP_ENV` variable would therefore run dev with debug on, and show stack traces to anyone; on a read-only code directory, every Invocation even answers a 500 whose body is the full trace, as the dev container cannot be built next to the prod one warmed in the zip.4 With Symfony's usual precedence, a function deployed without an `APP_ENV` variable would therefore run dev with debug on, and show stack traces to anyone; on a read-only code directory, every Invocation even answers a 500 whose body is the full trace, as the dev container cannot be built next to the prod one warmed in the zip.
5 We therefore make `ScalewayRuntime`, which only the Handler uses, set the `env` option to the `APP_ENV` of the process environment (`$_SERVER`, `$_ENV`, then `getenv()`), or to `prod` when it is unset or empty, before Dotenv runs.5 We therefore make `ScalewayRuntime`, which only the Handler uses, set the `env` option to the `APP_ENV` of the process environment (`$_SERVER`, `$_ENV`, then `getenv()`), or to `prod` when it is unset or empty, before Dotenv runs.
6 Dotenv never overrides a variable already set, so `.env` files can no longer choose the env, and `APP_DEBUG` follows `prod`, off unless set by the environment or a `.env` file.6 Dotenv never overrides a variable already set, so `.env` files can no longer choose the env, and `APP_DEBUG` follows `prod`, off unless set by the environment or a `.env` file.
added docs/adr/0008-let-scaleway-install-the-dependencies.md +17 -0
new file mode 100644
@@ -0,0 +1,17 @@
1+# Scaleway installs the dependencies, and the cache is built on the platform
2+
3+The probe showed that when the zip has a `composer.json` at its root, Scaleway runs `composer install --no-dev` from the shipped `composer.lock` at deploy time, Composer scripts included, and replaces any shipped `vendor/`; the code directory is writable at runtime.
4+Shipping `vendor/` and a warmed cache (ADR 0003) is therefore wasted work, and a `path` repository the build resolved locally breaks the install on the platform.
5+We therefore zip the sources with `composer.json` and `composer.lock` only, without `vendor/` nor `var/`, and let the Kernel build its cache at the first Invocation of each Warm Process, as Symfony does on any writable server.
6+
7+## Considered Options
8+
9+- Shipping `vendor/` in a subdirectory, where Scaleway does not run Composer: rejected, it moves the Kernel's project dir away from `handler.php` and fights the documented path.
10+- Warming the cache in `scaleway-package`: rejected, Scaleway's install replaces the result anyway unless the warmup runs after it, which only a Composer script can do.
11+
12+## Consequences
13+
14+- `scaleway-package` no longer needs Composer, but refuses a missing lock, a lock out of sync with `composer.json` (Composer only warns about it), and `path` repositories or dists, as Scaleway cannot resolve them and a failing install does not fail the deployment.
15+- Function environment variables are not available to Composer scripts at deploy time, and a failing script does not fail the deployment: a `post-install-cmd` running `cache:warmup --env=prod` only helps applications whose warmup needs no secret, and Symfony Flex `auto-scripts` (`cache:clear` in the `.env`'s `dev`) fail silently unless made env-explicit.
16+- The first Invocation of each Warm Process pays the container compilation when the cache was not warmed at deploy time.
17+- Every locked package must be downloadable by Scaleway: private packages would need their credentials in the zip (an `auth.json`), which the probe did not check.
new file mode 100644
@@ -0,0 +1,17 @@
1+# Scaleway installs the dependencies, and the cache is built on the platform
2+
3+The probe showed that when the zip has a `composer.json` at its root, Scaleway runs `composer install --no-dev` from the shipped `composer.lock` at deploy time, Composer scripts included, and replaces any shipped `vendor/`; the code directory is writable at runtime.
4+Shipping `vendor/` and a warmed cache (ADR 0003) is therefore wasted work, and a `path` repository the build resolved locally breaks the install on the platform.
5+We therefore zip the sources with `composer.json` and `composer.lock` only, without `vendor/` nor `var/`, and let the Kernel build its cache at the first Invocation of each Warm Process, as Symfony does on any writable server.
6+
7+## Considered Options
8+
9+- Shipping `vendor/` in a subdirectory, where Scaleway does not run Composer: rejected, it moves the Kernel's project dir away from `handler.php` and fights the documented path.
10+- Warming the cache in `scaleway-package`: rejected, Scaleway's install replaces the result anyway unless the warmup runs after it, which only a Composer script can do.
11+
12+## Consequences
13+
14+- `scaleway-package` no longer needs Composer, but refuses a missing lock, a lock out of sync with `composer.json` (Composer only warns about it), and `path` repositories or dists, as Scaleway cannot resolve them and a failing install does not fail the deployment.
15+- Function environment variables are not available to Composer scripts at deploy time, and a failing script does not fail the deployment: a `post-install-cmd` running `cache:warmup --env=prod` only helps applications whose warmup needs no secret, and Symfony Flex `auto-scripts` (`cache:clear` in the `.env`'s `dev`) fail silently unless made env-explicit.
16+- The first Invocation of each Warm Process pays the container compilation when the cache was not warmed at deploy time.
17+- Every locked package must be downloadable by Scaleway: private packages would need their credentials in the zip (an `auth.json`), which the probe did not check.
modified src/Packager.php +63 -127
@@ -5,14 +5,14 @@ declare(strict_types=1);
55 namespace JDecool\ScalewayRuntime;
66
77 /**
8- * Builds the deployment zip: a copy of the application with production dependencies
9- * and a warmed-up prod cache (ADR 0003), so Invocations never compile the container.
8+ * Builds the deployment zip: the application sources with composer.json and composer.lock, from which Scaleway
9+ * installs the dependencies at deploy time (see docs/adr/0008-let-scaleway-install-the-dependencies.md).
1010 */
1111 final readonly class Packager
1212 {
1313 /**
1414 * Patterns starting with "/" match from the application root, the others match a file or directory name anywhere.
15- * vendor/ and var/ are rebuilt from scratch, the rest is local, test or secret material.
15+ * Scaleway installs vendor/ itself and the cache is built on the platform, the rest is local, test or secret material.
1616 */
1717 public const array EXCLUDES = [
1818 '/vendor', '/var', '/tests',
@@ -41,50 +41,71 @@ final readonly class Packager
4141 if (!class_exists(\ZipArchive::class)) {
4242 throw new \RuntimeException('The zip PHP extension is required to build the deployment zip.');
4343 }
44- foreach (['handler.php' => 'run "vendor/bin/scaleway-init" first', 'composer.lock' => 'run "composer update" and commit it, builds must be reproducible'] as $file => $hint) {
44+ foreach (['handler.php' => 'run "vendor/bin/scaleway-init" first', 'composer.lock' => 'run "composer update" and commit it, Scaleway installs the dependencies from it'] as $file => $hint) {
4545 if (!is_file($this->appDir.'/'.$file)) {
4646 throw new \RuntimeException(\sprintf('"%s" is missing in "%s": %s.', $file, $this->appDir, $hint));
4747 }
4848 }
49+ self::checkLock((string) file_get_contents($this->appDir.'/composer.json'), (string) file_get_contents($this->appDir.'/composer.lock'));
4950
50- $buildDir = sys_get_temp_dir().'/scaleway-package-'.bin2hex(random_bytes(4));
51- // Private, as it holds the .env files; failing on an existing path keeps a planted directory or symlink out.
52- if (!@mkdir($buildDir, 0o700)) {
53- throw new \RuntimeException(\sprintf('Cannot create "%s".', $buildDir));
51+ $this->log('Writing '.$zipFile);
52+ [$zipSize, $codeSize] = $this->zip($zipFile, $this->relativeToApp($zipFile));
53+ $this->log(\sprintf('Done: %.1f MiB zipped, %.1f MiB unzipped before Scaleway installs the dependencies', $zipSize / 1024 ** 2, $codeSize / 1024 ** 2));
54+ if ($zipSize > self::MAX_ZIP_SIZE) {
55+ $this->log('WARNING: the zip exceeds the 100 MiB Scaleway accepts');
5456 }
55- try {
56- $this->log('Copying the application to '.$buildDir);
57- $this->copy($buildDir, $this->relativeToApp($zipFile));
58-
59- $this->log('Installing production dependencies');
60- $lock = (string) file_get_contents($buildDir.'/composer.lock');
61- $this->writeJson($buildDir.'/composer.lock', self::resolvePathRepositories($this->decodeJson($lock), $this->appDir));
62- try {
63- $this->run(['composer', 'install', '--no-dev', '--classmap-authoritative', '--no-interaction', '--no-progress'], $buildDir);
64- } finally {
65- // The zip ships the lock file exactly as committed.
66- file_put_contents($buildDir.'/composer.lock', $lock);
67- }
57+ if ($codeSize > self::MAX_CODE_SIZE) {
58+ $this->log('WARNING: the unzipped code exceeds the 500 MiB Scaleway accepts');
59+ }
60+ }
6861
69- if (is_file($buildDir.'/bin/console')) {
70- $this->log('Warming up the prod cache');
71- $this->run([\PHP_BINARY, 'bin/console', 'cache:warmup', '--no-interaction'], $buildDir);
72- } else {
73- $this->log('No bin/console found: the cache is not warmed up, the container will be compiled at the first Invocation');
74- }
62+ /**
63+ * Refuses what would make Scaleway's "composer install" fail or install something else than the lock says:
64+ * Composer only warns about a stale lock, and a failed install does not even fail the deployment.
65+ */
66+ public static function checkLock(string $composerJson, string $composerLock): void
67+ {
68+ $composer = self::decodeJson($composerJson, 'composer.json');
69+ $lock = self::decodeJson($composerLock, 'composer.lock');
7570
76- $this->log('Writing '.$zipFile);
77- [$zipSize, $codeSize] = $this->zip($buildDir, $zipFile);
78- $this->log(\sprintf('Done: %.1f MiB zipped, %.1f MiB unzipped', $zipSize / 1024 ** 2, $codeSize / 1024 ** 2));
79- if ($zipSize > self::MAX_ZIP_SIZE) {
80- $this->log('WARNING: the zip exceeds the 100 MiB Scaleway accepts');
71+ foreach (\is_array($composer['repositories'] ?? null) ? $composer['repositories'] : [] as $repository) {
72+ if (\is_array($repository) && 'path' === ($repository['type'] ?? null)) {
73+ throw new \RuntimeException(\sprintf('composer.json declares the "path" repository "%s", which Scaleway cannot resolve: remove it and run "composer update".', \is_string($repository['url'] ?? null) ? $repository['url'] : ''));
8174 }
82- if ($codeSize > self::MAX_CODE_SIZE) {
83- $this->log('WARNING: the unzipped code exceeds the 500 MiB Scaleway accepts');
75+ }
76+ foreach (['packages', 'packages-dev'] as $section) {
77+ foreach (\is_array($lock[$section] ?? null) ? $lock[$section] : [] as $package) {
78+ if (\is_array($package) && \is_array($package['dist'] ?? null) && 'path' === ($package['dist']['type'] ?? null)) {
79+ throw new \RuntimeException(\sprintf('composer.lock installs "%s" from a local path, which Scaleway cannot resolve: install it from a remote repository and run "composer update".', \is_string($package['name'] ?? null) ? $package['name'] : ''));
80+ }
81+ }
82+ }
83+ if (($lock['content-hash'] ?? null) !== self::contentHash($composer)) {
84+ throw new \RuntimeException('composer.lock is not up to date with composer.json: run "composer update --lock" and commit it.');
85+ }
86+ }
87+
88+ /**
89+ * Composer's own Locker::getContentHash(), as the application may not ship Composer's classes.
90+ *
91+ * @param array<mixed> $composer
92+ */
93+ public static function contentHash(array $composer): string
94+ {
95+ $relevant = array_intersect_key($composer, array_flip(['name', 'version', 'require', 'require-dev', 'conflict', 'replace', 'provide', 'minimum-stability', 'prefer-stable', 'repositories', 'extra']));
96+ $config = \is_array($composer['config'] ?? null) ? $composer['config'] : [];
97+ $relevantConfig = [];
98+ foreach (['platform', 'policy'] as $key) {
99+ if (isset($config[$key])) {
100+ $relevantConfig[$key] = $config[$key];
84101 }
85- } finally {
86- $this->remove($buildDir);
87102 }
103+ if ([] !== $relevantConfig) {
104+ $relevant['config'] = $relevantConfig;
105+ }
106+ ksort($relevant);
107+
108+ return md5(json_encode($relevant, \JSON_THROW_ON_ERROR));
88109 }
89110
90111 public static function isExcluded(string $relativePath): bool
@@ -100,34 +121,9 @@ final readonly class Packager
100121 }
101122
102123 /**
103- * Relative "path" repositories point outside the application, so they no longer resolve from
104- * the build dir: they are made absolute, against the application dir they are relative to.
105- *
106- * @param array<mixed> $lock
107- *
108- * @return array<mixed>
124+ * @return array{int, int} the zip size and the total size of the zipped files
109125 */
110- public static function resolvePathRepositories(array $lock, string $appDir): array
111- {
112- foreach (['packages', 'packages-dev'] as $section) {
113- $packages = \is_array($lock[$section] ?? null) ? $lock[$section] : [];
114- foreach ($packages as $i => $package) {
115- $dist = \is_array($package) ? $package['dist'] ?? null : null;
116- if (\is_array($package) && \is_array($dist) && 'path' === ($dist['type'] ?? null) && \is_string($dist['url'] ?? null) && !str_starts_with($dist['url'], '/')) {
117- $dist['url'] = $appDir.'/'.$dist['url'];
118- $package['dist'] = $dist;
119- $packages[$i] = $package;
120- }
121- }
122- if (isset($lock[$section])) {
123- $lock[$section] = $packages;
124- }
125- }
126-
127- return $lock;
128- }
129-
130- private function copy(string $buildDir, ?string $skip): void
126+ private function zip(string $zipFile, ?string $skip): array
131127 {
132128 $files = new \RecursiveIteratorIterator(
133129 new \RecursiveCallbackFilterIterator(
@@ -138,35 +134,16 @@ final readonly class Packager
138134 return $relativePath !== $skip && !self::isExcluded($relativePath);
139135 },
140136 ),
141- \RecursiveIteratorIterator::SELF_FIRST,
142137 );
143138
144- foreach ($files as $file) {
145- \assert($file instanceof \SplFileInfo);
146- $target = $buildDir.'/'.substr($file->getPathname(), \strlen($this->appDir) + 1);
147- if ($file->isDir()) {
148- $this->mkdir($target);
149- } elseif (!copy($file->getPathname(), $target) || !chmod($target, $file->getPerms() & 0o777)) {
150- throw new \RuntimeException(\sprintf('Cannot copy "%s" to "%s".', $file->getPathname(), $target));
151- }
152- }
153- }
154-
155- /**
156- * @return array{int, int} the zip size and the total size of the zipped files
157- */
158- private function zip(string $buildDir, string $zipFile): array
159- {
160139 $zip = new \ZipArchive();
161140 if (true !== $zip->open($zipFile, \ZipArchive::CREATE | \ZipArchive::OVERWRITE)) {
162141 throw new \RuntimeException(\sprintf('Cannot create "%s".', $zipFile));
163142 }
164-
165143 $codeSize = 0;
166- $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($buildDir, \FilesystemIterator::SKIP_DOTS));
167144 foreach ($files as $file) {
168145 \assert($file instanceof \SplFileInfo);
169- $name = substr($file->getPathname(), \strlen($buildDir) + 1);
146+ $name = substr($file->getPathname(), \strlen($this->appDir) + 1);
170147 $zip->addFile($file->getPathname(), $name);
171148 // Keeps the executable bits, as for bin/console.
172149 $zip->setExternalAttributesName($name, \ZipArchive::OPSYS_UNIX, ($file->getPerms() & 0o777 | 0o100000) << 16);
@@ -181,19 +158,6 @@ final readonly class Packager
181158 return [(int) filesize($zipFile), $codeSize];
182159 }
183160
184- /**
185- * @param list<string> $command
186- */
187- private function run(array $command, string $cwd): void
188- {
189- $env = ['APP_ENV' => 'prod', 'APP_DEBUG' => '0', 'COMPOSER_MIRROR_PATH_REPOS' => '1'] + getenv();
190- // Child output goes to our stderr, keeping stdout clean like the rest of the log.
191- $process = proc_open($command, [0 => ['file', '/dev/null', 'r'], 1 => $this->log, 2 => $this->log], $pipes, $cwd, $env);
192- if (false === $process || 0 !== $exitCode = proc_close($process)) {
193- throw new \RuntimeException(\sprintf('"%s" failed%s.', implode(' ', $command), isset($exitCode) ? ' with exit code '.$exitCode : ''));
194- }
195- }
196-
197161 private function relativeToApp(string $file): ?string
198162 {
199163 $dir = realpath(\dirname($file));
@@ -201,42 +165,14 @@ final readonly class Packager
201165 return false !== $dir && str_starts_with($dir.'/', $this->appDir.'/') ? ltrim(substr($dir, \strlen($this->appDir)).'/'.basename($file), '/') : null;
202166 }
203167
204- private function remove(string $dir): void
205- {
206- if (!is_dir($dir)) {
207- return;
208- }
209- $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST);
210- foreach ($files as $file) {
211- \assert($file instanceof \SplFileInfo);
212- $file->isDir() && !$file->isLink() ? rmdir($file->getPathname()) : unlink($file->getPathname());
213- }
214- rmdir($dir);
215- }
216-
217- private function mkdir(string $dir): void
218- {
219- if (!is_dir($dir) && !mkdir($dir, 0o777, true)) {
220- throw new \RuntimeException(\sprintf('Cannot create "%s".', $dir));
221- }
222- }
223-
224168 /**
225169 * @return array<mixed>
226170 */
227- private function decodeJson(string $json): array
171+ private static function decodeJson(string $json, string $file): array
228172 {
229- $data = json_decode($json, true, 512, \JSON_THROW_ON_ERROR);
230-
231- return \is_array($data) ? $data : throw new \UnexpectedValueException('composer.lock must hold a JSON object.');
232- }
173+ $data = json_decode($json, true);
233174
234- /**
235- * @param array<mixed> $data
236- */
237- private function writeJson(string $file, array $data): void
238- {
239- file_put_contents($file, json_encode($data, \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES));
175+ return \is_array($data) ? $data : throw new \UnexpectedValueException(\sprintf('%s must hold a JSON object.', $file));
240176 }
241177
242178 private function log(string $message): void
@@ -5,14 +5,14 @@ declare(strict_types=1);
5 namespace JDecool\ScalewayRuntime;5 namespace JDecool\ScalewayRuntime;
6 6
7 /**7 /**
8- * Builds the deployment zip: a copy of the application with production dependencies8+ * Builds the deployment zip: the application sources with composer.json and composer.lock, from which Scaleway
9- * and a warmed-up prod cache (ADR 0003), so Invocations never compile the container.9+ * installs the dependencies at deploy time (see docs/adr/0008-let-scaleway-install-the-dependencies.md).
10 */10 */
11 final readonly class Packager11 final readonly class Packager
12 {12 {
13 /**13 /**
14 * Patterns starting with "/" match from the application root, the others match a file or directory name anywhere.14 * Patterns starting with "/" match from the application root, the others match a file or directory name anywhere.
15- * vendor/ and var/ are rebuilt from scratch, the rest is local, test or secret material.15+ * Scaleway installs vendor/ itself and the cache is built on the platform, the rest is local, test or secret material.
16 */16 */
17 public const array EXCLUDES = [17 public const array EXCLUDES = [
18 '/vendor', '/var', '/tests',18 '/vendor', '/var', '/tests',
@@ -41,50 +41,71 @@ final readonly class Packager
41 if (!class_exists(\ZipArchive::class)) {41 if (!class_exists(\ZipArchive::class)) {
42 throw new \RuntimeException('The zip PHP extension is required to build the deployment zip.');42 throw new \RuntimeException('The zip PHP extension is required to build the deployment zip.');
43 }43 }
44- foreach (['handler.php' => 'run "vendor/bin/scaleway-init" first', 'composer.lock' => 'run "composer update" and commit it, builds must be reproducible'] as $file => $hint) {44+ foreach (['handler.php' => 'run "vendor/bin/scaleway-init" first', 'composer.lock' => 'run "composer update" and commit it, Scaleway installs the dependencies from it'] as $file => $hint) {
45 if (!is_file($this->appDir.'/'.$file)) {45 if (!is_file($this->appDir.'/'.$file)) {
46 throw new \RuntimeException(\sprintf('"%s" is missing in "%s": %s.', $file, $this->appDir, $hint));46 throw new \RuntimeException(\sprintf('"%s" is missing in "%s": %s.', $file, $this->appDir, $hint));
47 }47 }
48 }48 }
49+ self::checkLock((string) file_get_contents($this->appDir.'/composer.json'), (string) file_get_contents($this->appDir.'/composer.lock'));
49 50
50- $buildDir = sys_get_temp_dir().'/scaleway-package-'.bin2hex(random_bytes(4));51+ $this->log('Writing '.$zipFile);
51- // Private, as it holds the .env files; failing on an existing path keeps a planted directory or symlink out.52+ [$zipSize, $codeSize] = $this->zip($zipFile, $this->relativeToApp($zipFile));
52- if (!@mkdir($buildDir, 0o700)) {53+ $this->log(\sprintf('Done: %.1f MiB zipped, %.1f MiB unzipped before Scaleway installs the dependencies', $zipSize / 1024 ** 2, $codeSize / 1024 ** 2));
53- throw new \RuntimeException(\sprintf('Cannot create "%s".', $buildDir));54+ if ($zipSize > self::MAX_ZIP_SIZE) {
55+ $this->log('WARNING: the zip exceeds the 100 MiB Scaleway accepts');
54 }56 }
55- try {57+ if ($codeSize > self::MAX_CODE_SIZE) {
56- $this->log('Copying the application to '.$buildDir);58+ $this->log('WARNING: the unzipped code exceeds the 500 MiB Scaleway accepts');
57- $this->copy($buildDir, $this->relativeToApp($zipFile));59+ }
58-60+ }
59- $this->log('Installing production dependencies');
60- $lock = (string) file_get_contents($buildDir.'/composer.lock');
61- $this->writeJson($buildDir.'/composer.lock', self::resolvePathRepositories($this->decodeJson($lock), $this->appDir));
62- try {
63- $this->run(['composer', 'install', '--no-dev', '--classmap-authoritative', '--no-interaction', '--no-progress'], $buildDir);
64- } finally {
65- // The zip ships the lock file exactly as committed.
66- file_put_contents($buildDir.'/composer.lock', $lock);
67- }
68 61
69- if (is_file($buildDir.'/bin/console')) {62+ /**
70- $this->log('Warming up the prod cache');63+ * Refuses what would make Scaleway's "composer install" fail or install something else than the lock says:
71- $this->run([\PHP_BINARY, 'bin/console', 'cache:warmup', '--no-interaction'], $buildDir);64+ * Composer only warns about a stale lock, and a failed install does not even fail the deployment.
72- } else {65+ */
73- $this->log('No bin/console found: the cache is not warmed up, the container will be compiled at the first Invocation');66+ public static function checkLock(string $composerJson, string $composerLock): void
74- }67+ {
68+ $composer = self::decodeJson($composerJson, 'composer.json');
69+ $lock = self::decodeJson($composerLock, 'composer.lock');
75 70
76- $this->log('Writing '.$zipFile);71+ foreach (\is_array($composer['repositories'] ?? null) ? $composer['repositories'] : [] as $repository) {
77- [$zipSize, $codeSize] = $this->zip($buildDir, $zipFile);72+ if (\is_array($repository) && 'path' === ($repository['type'] ?? null)) {
78- $this->log(\sprintf('Done: %.1f MiB zipped, %.1f MiB unzipped', $zipSize / 1024 ** 2, $codeSize / 1024 ** 2));73+ throw new \RuntimeException(\sprintf('composer.json declares the "path" repository "%s", which Scaleway cannot resolve: remove it and run "composer update".', \is_string($repository['url'] ?? null) ? $repository['url'] : ''));
79- if ($zipSize > self::MAX_ZIP_SIZE) {
80- $this->log('WARNING: the zip exceeds the 100 MiB Scaleway accepts');
81 }74 }
82- if ($codeSize > self::MAX_CODE_SIZE) {75+ }
83- $this->log('WARNING: the unzipped code exceeds the 500 MiB Scaleway accepts');76+ foreach (['packages', 'packages-dev'] as $section) {
77+ foreach (\is_array($lock[$section] ?? null) ? $lock[$section] : [] as $package) {
78+ if (\is_array($package) && \is_array($package['dist'] ?? null) && 'path' === ($package['dist']['type'] ?? null)) {
79+ throw new \RuntimeException(\sprintf('composer.lock installs "%s" from a local path, which Scaleway cannot resolve: install it from a remote repository and run "composer update".', \is_string($package['name'] ?? null) ? $package['name'] : ''));
80+ }
81+ }
82+ }
83+ if (($lock['content-hash'] ?? null) !== self::contentHash($composer)) {
84+ throw new \RuntimeException('composer.lock is not up to date with composer.json: run "composer update --lock" and commit it.');
85+ }
86+ }
87+
88+ /**
89+ * Composer's own Locker::getContentHash(), as the application may not ship Composer's classes.
90+ *
91+ * @param array<mixed> $composer
92+ */
93+ public static function contentHash(array $composer): string
94+ {
95+ $relevant = array_intersect_key($composer, array_flip(['name', 'version', 'require', 'require-dev', 'conflict', 'replace', 'provide', 'minimum-stability', 'prefer-stable', 'repositories', 'extra']));
96+ $config = \is_array($composer['config'] ?? null) ? $composer['config'] : [];
97+ $relevantConfig = [];
98+ foreach (['platform', 'policy'] as $key) {
99+ if (isset($config[$key])) {
100+ $relevantConfig[$key] = $config[$key];
84 }101 }
85- } finally {
86- $this->remove($buildDir);
87 }102 }
103+ if ([] !== $relevantConfig) {
104+ $relevant['config'] = $relevantConfig;
105+ }
106+ ksort($relevant);
107+
108+ return md5(json_encode($relevant, \JSON_THROW_ON_ERROR));
88 }109 }
89 110
90 public static function isExcluded(string $relativePath): bool111 public static function isExcluded(string $relativePath): bool
@@ -100,34 +121,9 @@ final readonly class Packager
100 }121 }
101 122
102 /**123 /**
103- * Relative "path" repositories point outside the application, so they no longer resolve from124+ * @return array{int, int} the zip size and the total size of the zipped files
104- * the build dir: they are made absolute, against the application dir they are relative to.
105- *
106- * @param array<mixed> $lock
107- *
108- * @return array<mixed>
109 */125 */
110- public static function resolvePathRepositories(array $lock, string $appDir): array126+ private function zip(string $zipFile, ?string $skip): array
111- {
112- foreach (['packages', 'packages-dev'] as $section) {
113- $packages = \is_array($lock[$section] ?? null) ? $lock[$section] : [];
114- foreach ($packages as $i => $package) {
115- $dist = \is_array($package) ? $package['dist'] ?? null : null;
116- if (\is_array($package) && \is_array($dist) && 'path' === ($dist['type'] ?? null) && \is_string($dist['url'] ?? null) && !str_starts_with($dist['url'], '/')) {
117- $dist['url'] = $appDir.'/'.$dist['url'];
118- $package['dist'] = $dist;
119- $packages[$i] = $package;
120- }
121- }
122- if (isset($lock[$section])) {
123- $lock[$section] = $packages;
124- }
125- }
126-
127- return $lock;
128- }
129-
130- private function copy(string $buildDir, ?string $skip): void
131 {127 {
132 $files = new \RecursiveIteratorIterator(128 $files = new \RecursiveIteratorIterator(
133 new \RecursiveCallbackFilterIterator(129 new \RecursiveCallbackFilterIterator(
@@ -138,35 +134,16 @@ final readonly class Packager
138 return $relativePath !== $skip && !self::isExcluded($relativePath);134 return $relativePath !== $skip && !self::isExcluded($relativePath);
139 },135 },
140 ),136 ),
141- \RecursiveIteratorIterator::SELF_FIRST,
142 );137 );
143 138
144- foreach ($files as $file) {
145- \assert($file instanceof \SplFileInfo);
146- $target = $buildDir.'/'.substr($file->getPathname(), \strlen($this->appDir) + 1);
147- if ($file->isDir()) {
148- $this->mkdir($target);
149- } elseif (!copy($file->getPathname(), $target) || !chmod($target, $file->getPerms() & 0o777)) {
150- throw new \RuntimeException(\sprintf('Cannot copy "%s" to "%s".', $file->getPathname(), $target));
151- }
152- }
153- }
154-
155- /**
156- * @return array{int, int} the zip size and the total size of the zipped files
157- */
158- private function zip(string $buildDir, string $zipFile): array
159- {
160 $zip = new \ZipArchive();139 $zip = new \ZipArchive();
161 if (true !== $zip->open($zipFile, \ZipArchive::CREATE | \ZipArchive::OVERWRITE)) {140 if (true !== $zip->open($zipFile, \ZipArchive::CREATE | \ZipArchive::OVERWRITE)) {
162 throw new \RuntimeException(\sprintf('Cannot create "%s".', $zipFile));141 throw new \RuntimeException(\sprintf('Cannot create "%s".', $zipFile));
163 }142 }
164-
165 $codeSize = 0;143 $codeSize = 0;
166- $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($buildDir, \FilesystemIterator::SKIP_DOTS));
167 foreach ($files as $file) {144 foreach ($files as $file) {
168 \assert($file instanceof \SplFileInfo);145 \assert($file instanceof \SplFileInfo);
169- $name = substr($file->getPathname(), \strlen($buildDir) + 1);146+ $name = substr($file->getPathname(), \strlen($this->appDir) + 1);
170 $zip->addFile($file->getPathname(), $name);147 $zip->addFile($file->getPathname(), $name);
171 // Keeps the executable bits, as for bin/console.148 // Keeps the executable bits, as for bin/console.
172 $zip->setExternalAttributesName($name, \ZipArchive::OPSYS_UNIX, ($file->getPerms() & 0o777 | 0o100000) << 16);149 $zip->setExternalAttributesName($name, \ZipArchive::OPSYS_UNIX, ($file->getPerms() & 0o777 | 0o100000) << 16);
@@ -181,19 +158,6 @@ final readonly class Packager
181 return [(int) filesize($zipFile), $codeSize];158 return [(int) filesize($zipFile), $codeSize];
182 }159 }
183 160
184- /**
185- * @param list<string> $command
186- */
187- private function run(array $command, string $cwd): void
188- {
189- $env = ['APP_ENV' => 'prod', 'APP_DEBUG' => '0', 'COMPOSER_MIRROR_PATH_REPOS' => '1'] + getenv();
190- // Child output goes to our stderr, keeping stdout clean like the rest of the log.
191- $process = proc_open($command, [0 => ['file', '/dev/null', 'r'], 1 => $this->log, 2 => $this->log], $pipes, $cwd, $env);
192- if (false === $process || 0 !== $exitCode = proc_close($process)) {
193- throw new \RuntimeException(\sprintf('"%s" failed%s.', implode(' ', $command), isset($exitCode) ? ' with exit code '.$exitCode : ''));
194- }
195- }
196-
197 private function relativeToApp(string $file): ?string161 private function relativeToApp(string $file): ?string
198 {162 {
199 $dir = realpath(\dirname($file));163 $dir = realpath(\dirname($file));
@@ -201,42 +165,14 @@ final readonly class Packager
201 return false !== $dir && str_starts_with($dir.'/', $this->appDir.'/') ? ltrim(substr($dir, \strlen($this->appDir)).'/'.basename($file), '/') : null;165 return false !== $dir && str_starts_with($dir.'/', $this->appDir.'/') ? ltrim(substr($dir, \strlen($this->appDir)).'/'.basename($file), '/') : null;
202 }166 }
203 167
204- private function remove(string $dir): void
205- {
206- if (!is_dir($dir)) {
207- return;
208- }
209- $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST);
210- foreach ($files as $file) {
211- \assert($file instanceof \SplFileInfo);
212- $file->isDir() && !$file->isLink() ? rmdir($file->getPathname()) : unlink($file->getPathname());
213- }
214- rmdir($dir);
215- }
216-
217- private function mkdir(string $dir): void
218- {
219- if (!is_dir($dir) && !mkdir($dir, 0o777, true)) {
220- throw new \RuntimeException(\sprintf('Cannot create "%s".', $dir));
221- }
222- }
223-
224 /**168 /**
225 * @return array<mixed>169 * @return array<mixed>
226 */170 */
227- private function decodeJson(string $json): array171+ private static function decodeJson(string $json, string $file): array
228 {172 {
229- $data = json_decode($json, true, 512, \JSON_THROW_ON_ERROR);173+ $data = json_decode($json, true);
230-
231- return \is_array($data) ? $data : throw new \UnexpectedValueException('composer.lock must hold a JSON object.');
232- }
233 174
234- /**175+ return \is_array($data) ? $data : throw new \UnexpectedValueException(\sprintf('%s must hold a JSON object.', $file));
235- * @param array<mixed> $data
236- */
237- private function writeJson(string $file, array $data): void
238- {
239- file_put_contents($file, json_encode($data, \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES));
240 }176 }
241 177
242 private function log(string $message): void178 private function log(string $message): void
modified src/ScalewayRuntime.php +9 -5
@@ -30,9 +30,9 @@ use Symfony\Component\Runtime\SymfonyRuntime;
3030 *
3131 * Unlike SymfonyRuntime, it defaults the env to prod when the process environment sets none, whatever .env files say.
3232 *
33- * When the project's var/ directory is not writable (the deployed code may be read-only),
34- * the cache and log dirs move to the system temp dir through APP_CACHE_DIR and APP_LOG_DIR,
35- * while APP_BUILD_DIR keeps the container warmed at build time.
33+ * The cache is built at the first Invocation of each Warm Process, unless the application warmed it at deploy time.
34+ * When the project's var/ directory is not writable, the cache and log dirs move to the system temp dir through
35+ * APP_CACHE_DIR and APP_LOG_DIR, while APP_BUILD_DIR keeps a container already warmed in var/cache.
3636 *
3737 * A Front Controller closure returning a Response is called again for every Invocation, and one
3838 * taking a Request gets the Invocation's Request (see docs/adr/0004-call-response-front-controllers-per-invocation.md).
@@ -72,8 +72,12 @@ class ScalewayRuntime extends SymfonyRuntime
7272
7373 $projectDir = $this->options['project_dir'] ?? null;
7474 if (\is_string($projectDir) && !is_writable(is_dir($projectDir.'/var') ? $projectDir.'/var' : $projectDir)) {
75- // Kernels using MicroKernelTrait read these from $_SERVER only; values set by the app win.
76- $_SERVER['APP_BUILD_DIR'] ??= $projectDir.'/var/cache';
75+ // Kernels using MicroKernelTrait read these from $_SERVER only; values set by the app win. A container
76+ // warmed before the code went read-only is kept, otherwise it is built in the temp dir like the cache.
77+ $env = $this->options['env'] ?? null;
78+ if (\is_string($env) && is_dir($projectDir.'/var/cache/'.$env)) {
79+ $_SERVER['APP_BUILD_DIR'] ??= $projectDir.'/var/cache';
80+ }
7781 $_SERVER['APP_CACHE_DIR'] ??= sys_get_temp_dir().'/cache';
7882 $_SERVER['APP_LOG_DIR'] ??= sys_get_temp_dir().'/log';
7983 }
@@ -30,9 +30,9 @@ use Symfony\Component\Runtime\SymfonyRuntime;
30 *30 *
31 * Unlike SymfonyRuntime, it defaults the env to prod when the process environment sets none, whatever .env files say.31 * Unlike SymfonyRuntime, it defaults the env to prod when the process environment sets none, whatever .env files say.
32 *32 *
33- * When the project's var/ directory is not writable (the deployed code may be read-only),33+ * The cache is built at the first Invocation of each Warm Process, unless the application warmed it at deploy time.
34- * the cache and log dirs move to the system temp dir through APP_CACHE_DIR and APP_LOG_DIR,34+ * When the project's var/ directory is not writable, the cache and log dirs move to the system temp dir through
35- * while APP_BUILD_DIR keeps the container warmed at build time.35+ * APP_CACHE_DIR and APP_LOG_DIR, while APP_BUILD_DIR keeps a container already warmed in var/cache.
36 *36 *
37 * A Front Controller closure returning a Response is called again for every Invocation, and one37 * A Front Controller closure returning a Response is called again for every Invocation, and one
38 * taking a Request gets the Invocation's Request (see docs/adr/0004-call-response-front-controllers-per-invocation.md).38 * taking a Request gets the Invocation's Request (see docs/adr/0004-call-response-front-controllers-per-invocation.md).
@@ -72,8 +72,12 @@ class ScalewayRuntime extends SymfonyRuntime
72 72
73 $projectDir = $this->options['project_dir'] ?? null;73 $projectDir = $this->options['project_dir'] ?? null;
74 if (\is_string($projectDir) && !is_writable(is_dir($projectDir.'/var') ? $projectDir.'/var' : $projectDir)) {74 if (\is_string($projectDir) && !is_writable(is_dir($projectDir.'/var') ? $projectDir.'/var' : $projectDir)) {
75- // Kernels using MicroKernelTrait read these from $_SERVER only; values set by the app win.75+ // Kernels using MicroKernelTrait read these from $_SERVER only; values set by the app win. A container
76- $_SERVER['APP_BUILD_DIR'] ??= $projectDir.'/var/cache';76+ // warmed before the code went read-only is kept, otherwise it is built in the temp dir like the cache.
77+ $env = $this->options['env'] ?? null;
78+ if (\is_string($env) && is_dir($projectDir.'/var/cache/'.$env)) {
79+ $_SERVER['APP_BUILD_DIR'] ??= $projectDir.'/var/cache';
80+ }
77 $_SERVER['APP_CACHE_DIR'] ??= sys_get_temp_dir().'/cache';81 $_SERVER['APP_CACHE_DIR'] ??= sys_get_temp_dir().'/cache';
78 $_SERVER['APP_LOG_DIR'] ??= sys_get_temp_dir().'/log';82 $_SERVER['APP_LOG_DIR'] ??= sys_get_temp_dir().'/log';
79 }83 }
renamed tests/Fixtures/PackagedApp/.env +0 -0
similarity index 100%
rename from tests/Fixtures/PackagedApp/app/.env
rename to tests/Fixtures/PackagedApp/.env
similarity index 100%
rename from tests/Fixtures/PackagedApp/app/.env
rename to tests/Fixtures/PackagedApp/.env
deleted tests/Fixtures/PackagedApp/app/bin/console +0 -14
deleted file mode 100755
@@ -1,14 +0,0 @@
1-#!/usr/bin/env php
2-<?php
3-
4-// Stands in for "bin/console cache:warmup": records what the build dir looks like while the Packager runs it.
5-$buildDir = dirname(__DIR__);
6-file_put_contents((string) getenv('PACKAGER_TEST_RECORD'), json_encode([
7- 'buildDir' => $buildDir,
8- 'perms' => fileperms($buildDir) & 0o777,
9- 'argv' => array_slice($argv, 1),
10- 'appEnv' => getenv('APP_ENV'),
11- 'lock' => file_get_contents($buildDir.'/composer.lock'),
12-]));
13-
14-exit(getenv('PACKAGER_TEST_FAIL') ? 1 : 0);
deleted file mode 100755
@@ -1,14 +0,0 @@
1-#!/usr/bin/env php
2-<?php
3-
4-// Stands in for "bin/console cache:warmup": records what the build dir looks like while the Packager runs it.
5-$buildDir = dirname(__DIR__);
6-file_put_contents((string) getenv('PACKAGER_TEST_RECORD'), json_encode([
7- 'buildDir' => $buildDir,
8- 'perms' => fileperms($buildDir) & 0o777,
9- 'argv' => array_slice($argv, 1),
10- 'appEnv' => getenv('APP_ENV'),
11- 'lock' => file_get_contents($buildDir.'/composer.lock'),
12-]));
13-
14-exit(getenv('PACKAGER_TEST_FAIL') ? 1 : 0);
deleted tests/Fixtures/PackagedApp/app/composer.json +0 -16
deleted file mode 100644
@@ -1,16 +0,0 @@
1-{
2- "name": "acme/packaged-app",
3- "description": "An application packaged without any network access",
4- "type": "project",
5- "require": {
6- "acme/lib": "*@dev"
7- },
8- "require-dev": {
9- "acme/dev-tool": "*@dev"
10- },
11- "repositories": [
12- {"type": "path", "url": "../lib"},
13- {"type": "path", "url": "../dev-tool"},
14- {"packagist.org": false}
15- ]
16-}
deleted file mode 100644
@@ -1,16 +0,0 @@
1-{
2- "name": "acme/packaged-app",
3- "description": "An application packaged without any network access",
4- "type": "project",
5- "require": {
6- "acme/lib": "*@dev"
7- },
8- "require-dev": {
9- "acme/dev-tool": "*@dev"
10- },
11- "repositories": [
12- {"type": "path", "url": "../lib"},
13- {"type": "path", "url": "../dev-tool"},
14- {"packagist.org": false}
15- ]
16-}
deleted tests/Fixtures/PackagedApp/app/composer.lock +0 -51
deleted file mode 100644
@@ -1,51 +0,0 @@
1-{
2- "_readme": [
3- "This file locks the dependencies of your project to a known state",
4- "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
5- "This file is @generated automatically"
6- ],
7- "content-hash": "ef10a352ccfe70682015a26ef11e5ddd",
8- "packages": [
9- {
10- "name": "acme/lib",
11- "version": "dev-main",
12- "dist": {
13- "type": "path",
14- "url": "../lib",
15- "reference": "8b69b77cbf0c83ab7533fbbeb5f671fb065cfd3f"
16- },
17- "type": "library",
18- "description": "A production dependency installed from a relative path repository",
19- "transport-options": {
20- "relative": true
21- }
22- }
23- ],
24- "packages-dev": [
25- {
26- "name": "acme/dev-tool",
27- "version": "dev-main",
28- "dist": {
29- "type": "path",
30- "url": "../dev-tool",
31- "reference": "52d35093a9cc4d4a45e5a88e2ece54ac2b659b5a"
32- },
33- "type": "library",
34- "description": "A dev dependency the deployment zip must not ship",
35- "transport-options": {
36- "relative": true
37- }
38- }
39- ],
40- "aliases": [],
41- "minimum-stability": "stable",
42- "stability-flags": {
43- "acme/dev-tool": 20,
44- "acme/lib": 20
45- },
46- "prefer-stable": false,
47- "prefer-lowest": false,
48- "platform": {},
49- "platform-dev": {},
50- "plugin-api-version": "2.11.0"
51-}
deleted file mode 100644
@@ -1,51 +0,0 @@
1-{
2- "_readme": [
3- "This file locks the dependencies of your project to a known state",
4- "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
5- "This file is @generated automatically"
6- ],
7- "content-hash": "ef10a352ccfe70682015a26ef11e5ddd",
8- "packages": [
9- {
10- "name": "acme/lib",
11- "version": "dev-main",
12- "dist": {
13- "type": "path",
14- "url": "../lib",
15- "reference": "8b69b77cbf0c83ab7533fbbeb5f671fb065cfd3f"
16- },
17- "type": "library",
18- "description": "A production dependency installed from a relative path repository",
19- "transport-options": {
20- "relative": true
21- }
22- }
23- ],
24- "packages-dev": [
25- {
26- "name": "acme/dev-tool",
27- "version": "dev-main",
28- "dist": {
29- "type": "path",
30- "url": "../dev-tool",
31- "reference": "52d35093a9cc4d4a45e5a88e2ece54ac2b659b5a"
32- },
33- "type": "library",
34- "description": "A dev dependency the deployment zip must not ship",
35- "transport-options": {
36- "relative": true
37- }
38- }
39- ],
40- "aliases": [],
41- "minimum-stability": "stable",
42- "stability-flags": {
43- "acme/dev-tool": 20,
44- "acme/lib": 20
45- },
46- "prefer-stable": false,
47- "prefer-lowest": false,
48- "platform": {},
49- "platform-dev": {},
50- "plugin-api-version": "2.11.0"
51-}
added tests/Fixtures/PackagedApp/bin/console +4 -0
new file mode 100755
@@ -0,0 +1,4 @@
1+#!/usr/bin/env php
2+<?php
3+
4+// Only here to check that the zip keeps the executable bits.
new file mode 100755
@@ -0,0 +1,4 @@
1+#!/usr/bin/env php
2+<?php
3+
4+// Only here to check that the zip keeps the executable bits.
added tests/Fixtures/PackagedApp/composer.json +22 -0
new file mode 100644
@@ -0,0 +1,22 @@
1+{
2+ "name": "acme/packaged-app",
3+ "description": "An application packaged without any network access",
4+ "type": "project",
5+ "require": {
6+ "acme/lib": "^1.0"
7+ },
8+ "repositories": [
9+ {
10+ "type": "package",
11+ "package": {
12+ "name": "acme/lib",
13+ "version": "1.0.0",
14+ "dist": {"type": "zip", "url": "https://example.test/acme-lib-1.0.0.zip"}
15+ }
16+ },
17+ {"packagist.org": false}
18+ ],
19+ "config": {
20+ "platform": {"php": "8.4.0"}
21+ }
22+}
new file mode 100644
@@ -0,0 +1,22 @@
1+{
2+ "name": "acme/packaged-app",
3+ "description": "An application packaged without any network access",
4+ "type": "project",
5+ "require": {
6+ "acme/lib": "^1.0"
7+ },
8+ "repositories": [
9+ {
10+ "type": "package",
11+ "package": {
12+ "name": "acme/lib",
13+ "version": "1.0.0",
14+ "dist": {"type": "zip", "url": "https://example.test/acme-lib-1.0.0.zip"}
15+ }
16+ },
17+ {"packagist.org": false}
18+ ],
19+ "config": {
20+ "platform": {"php": "8.4.0"}
21+ }
22+}
added tests/Fixtures/PackagedApp/composer.lock +31 -0
new file mode 100644
@@ -0,0 +1,31 @@
1+{
2+ "_readme": [
3+ "This file locks the dependencies of your project to a known state",
4+ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
5+ "This file is @generated automatically"
6+ ],
7+ "content-hash": "1590b2de3ad8291820484cb90476045c",
8+ "packages": [
9+ {
10+ "name": "acme/lib",
11+ "version": "1.0.0",
12+ "dist": {
13+ "type": "zip",
14+ "url": "https://example.test/acme-lib-1.0.0.zip"
15+ },
16+ "type": "library"
17+ }
18+ ],
19+ "packages-dev": [],
20+ "aliases": [],
21+ "minimum-stability": "stable",
22+ "stability-flags": {},
23+ "prefer-stable": false,
24+ "prefer-lowest": false,
25+ "platform": {},
26+ "platform-dev": {},
27+ "platform-overrides": {
28+ "php": "8.4.0"
29+ },
30+ "plugin-api-version": "2.11.0"
31+}
new file mode 100644
@@ -0,0 +1,31 @@
1+{
2+ "_readme": [
3+ "This file locks the dependencies of your project to a known state",
4+ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
5+ "This file is @generated automatically"
6+ ],
7+ "content-hash": "1590b2de3ad8291820484cb90476045c",
8+ "packages": [
9+ {
10+ "name": "acme/lib",
11+ "version": "1.0.0",
12+ "dist": {
13+ "type": "zip",
14+ "url": "https://example.test/acme-lib-1.0.0.zip"
15+ },
16+ "type": "library"
17+ }
18+ ],
19+ "packages-dev": [],
20+ "aliases": [],
21+ "minimum-stability": "stable",
22+ "stability-flags": {},
23+ "prefer-stable": false,
24+ "prefer-lowest": false,
25+ "platform": {},
26+ "platform-dev": {},
27+ "platform-overrides": {
28+ "php": "8.4.0"
29+ },
30+ "plugin-api-version": "2.11.0"
31+}
deleted tests/Fixtures/PackagedApp/dev-tool/composer.json +0 -4
deleted file mode 100644
@@ -1,4 +0,0 @@
1-{
2- "name": "acme/dev-tool",
3- "description": "A dev dependency the deployment zip must not ship"
4-}
deleted file mode 100644
@@ -1,4 +0,0 @@
1-{
2- "name": "acme/dev-tool",
3- "description": "A dev dependency the deployment zip must not ship"
4-}
renamed tests/Fixtures/PackagedApp/handler.php +0 -0
similarity index 100%
rename from tests/Fixtures/PackagedApp/app/handler.php
rename to tests/Fixtures/PackagedApp/handler.php
similarity index 100%
rename from tests/Fixtures/PackagedApp/app/handler.php
rename to tests/Fixtures/PackagedApp/handler.php
deleted tests/Fixtures/PackagedApp/lib/composer.json +0 -4
deleted file mode 100644
@@ -1,4 +0,0 @@
1-{
2- "name": "acme/lib",
3- "description": "A production dependency installed from a relative path repository"
4-}
deleted file mode 100644
@@ -1,4 +0,0 @@
1-{
2- "name": "acme/lib",
3- "description": "A production dependency installed from a relative path repository"
4-}
renamed tests/Fixtures/PackagedApp/src/Service.php +0 -0
similarity index 100%
rename from tests/Fixtures/PackagedApp/app/src/Service.php
rename to tests/Fixtures/PackagedApp/src/Service.php
similarity index 100%
rename from tests/Fixtures/PackagedApp/app/src/Service.php
rename to tests/Fixtures/PackagedApp/src/Service.php
modified tests/PackagerTest.php +67 -108
@@ -14,15 +14,19 @@ final class PackagerTest extends TestCase
1414 private Filesystem $filesystem;
1515 private string $dir;
1616 private string $appDir;
17+ /** @var resource */
18+ private $log;
1719
1820 protected function setUp(): void
1921 {
2022 $this->filesystem = new Filesystem();
21- // Real paths, as bin/scaleway-package passes and as the build dir reports them (macOS /var is a symlink).
23+ // Real paths, as bin/scaleway-package passes them (macOS /var is a symlink).
2224 $this->dir = (string) realpath(sys_get_temp_dir()).'/scaleway-runtime-'.bin2hex(random_bytes(4));
23- $this->appDir = $this->dir.'/project/app';
24- $this->filesystem->mirror(__DIR__.'/Fixtures/PackagedApp', $this->dir.'/project');
25- $this->filesystem->mkdir($this->dir.'/tmp');
25+ $this->appDir = $this->dir.'/app';
26+ $this->filesystem->mirror(__DIR__.'/Fixtures/PackagedApp', $this->appDir);
27+ $log = fopen('php://memory', 'w+');
28+ self::assertNotFalse($log);
29+ $this->log = $log;
2630 }
2731
2832 protected function tearDown(): void
@@ -57,29 +61,10 @@ final class PackagerTest extends TestCase
5761 self::assertFalse(Packager::isExcluded($path));
5862 }
5963
60- public function testRelativePathRepositoriesAreResolvedAgainstTheApplication(): void
61- {
62- $lock = [
63- 'packages' => [
64- ['name' => 'acme/local', 'dist' => ['type' => 'path', 'url' => '../lib']],
65- ['name' => 'acme/absolute', 'dist' => ['type' => 'path', 'url' => '/opt/lib']],
66- ['name' => 'acme/remote', 'dist' => ['type' => 'zip', 'url' => 'https://example.test/a.zip']],
67- ],
68- 'packages-dev' => [['name' => 'acme/dev', 'dist' => ['type' => 'path', 'url' => 'packages/dev']]],
69- 'content-hash' => 'abc',
70- ];
71-
72- $expected = $lock;
73- $expected['packages'][0]['dist']['url'] = '/srv/app/../lib';
74- $expected['packages-dev'][0]['dist']['url'] = '/srv/app/packages/dev';
75-
76- self::assertSame($expected, Packager::resolvePathRepositories($lock, '/srv/app'));
77- }
78-
79- public function testZipShipsTheApplicationWithProductionDependenciesAndTheCommittedLock(): void
64+ public function testZipShipsTheSourcesAndComposerFilesWithoutVendorNorVar(): void
8065 {
8166 $this->filesystem->dumpFile($this->appDir.'/var/cache/prod/stale.php', '');
82- $this->filesystem->dumpFile($this->appDir.'/vendor/stale.php', '');
67+ $this->filesystem->dumpFile($this->appDir.'/vendor/autoload.php', '');
8368 $this->filesystem->dumpFile($this->appDir.'/tests/ServiceTest.php', '');
8469 $this->filesystem->dumpFile($this->appDir.'/.env.local', 'APP_SECRET=local');
8570 $this->filesystem->dumpFile($this->appDir.'/.git/HEAD', '');
@@ -87,126 +72,100 @@ final class PackagerTest extends TestCase
8772 $this->filesystem->dumpFile($this->appDir.'/terraform/terraform.tfstate', '{}');
8873 // A previous build, in the application like the default "function.zip": it must not end up in itself.
8974 $this->filesystem->dumpFile($this->appDir.'/function.zip', 'stale');
90- $lock = (string) file_get_contents($this->appDir.'/composer.lock');
9175
92- [$exitCode, $log] = $this->package($this->appDir.'/function.zip');
76+ new Packager($this->appDir, $this->log)->package($this->appDir.'/function.zip');
9377
94- self::assertSame(0, $exitCode, $log);
9578 $zip = new \ZipArchive();
9679 self::assertTrue($zip->open($this->appDir.'/function.zip'));
9780 $names = [];
9881 for ($i = 0; $i < $zip->numFiles; ++$i) {
9982 $names[] = (string) $zip->getNameIndex($i);
10083 }
101- $shipped = array_values(array_filter($names, static fn (string $name): bool => !str_starts_with($name, 'vendor/composer/')));
102- sort($shipped);
103- self::assertSame([
104- '.env',
105- 'bin/console',
106- 'composer.json',
107- 'composer.lock',
108- 'handler.php',
109- 'src/Service.php',
110- 'vendor/acme/lib/composer.json',
111- 'vendor/autoload.php',
112- ], $shipped);
113- // Relative "../lib" did not resolve from the build dir, yet the zip ships the lock exactly as committed.
114- self::assertSame($lock, $zip->getFromName('composer.lock'));
115- self::assertSame($lock, file_get_contents($this->appDir.'/composer.lock'));
84+ sort($names);
85+ self::assertSame(['.env', 'bin/console', 'composer.json', 'composer.lock', 'handler.php', 'src/Service.php'], $names);
86+ self::assertSame(file_get_contents($this->appDir.'/composer.lock'), $zip->getFromName('composer.lock'));
11687 self::assertTrue($zip->getExternalAttributesName('bin/console', $system, $attributes));
11788 self::assertIsInt($attributes);
11889 self::assertSame(0o755, ($attributes >> 16) & 0o777);
11990 $zip->close();
120-
121- $record = $this->record();
122- self::assertSame(['cache:warmup', '--no-interaction'], $record['argv']);
123- self::assertSame('prod', $record['appEnv']);
124- self::assertSame($lock, $record['lock']);
125- }
126-
127- public function testBuildDirIsPrivateAndRemovedAfterwards(): void
128- {
129- [$exitCode, $log] = $this->package($this->dir.'/function.zip');
130-
131- self::assertSame(0, $exitCode, $log);
132- $record = $this->record();
133- self::assertIsString($record['buildDir']);
134- self::assertStringStartsWith($this->dir.'/tmp/scaleway-package-', $record['buildDir']);
135- self::assertSame(0o700, $record['perms']);
136- self::assertSame([], $this->leftovers());
13791 }
13892
139- public function testFailedBuildLeavesNeitherBuildDirNorZip(): void
93+ public function testContentHashIsComposers(): void
14094 {
141- [$exitCode, $log] = $this->package($this->dir.'/function.zip', ['PACKAGER_TEST_FAIL' => '1']);
95+ $composer = json_decode((string) file_get_contents(__DIR__.'/Fixtures/PackagedApp/composer.json'), true);
96+ $lock = json_decode((string) file_get_contents(__DIR__.'/Fixtures/PackagedApp/composer.lock'), true);
97+ self::assertIsArray($composer);
98+ self::assertIsArray($lock);
14299
143- self::assertNotSame(0, $exitCode);
144- self::assertStringContainsString('cache:warmup --no-interaction" failed with exit code 1', $log);
145- self::assertFileDoesNotExist($this->dir.'/function.zip');
146- self::assertSame([], $this->leftovers());
100+ // The fixture lock was written by Composer itself.
101+ self::assertSame($lock['content-hash'], Packager::contentHash($composer));
147102 }
148103
149104 public function testApplicationWithoutCommittedLockIsRefused(): void
150105 {
151106 $this->filesystem->remove($this->appDir.'/composer.lock');
152- $log = fopen('php://memory', 'w');
153- \assert(false !== $log);
154107
155108 $this->expectExceptionMessage('"composer.lock" is missing');
156- new Packager($this->appDir, $log)->package($this->dir.'/function.zip');
109+ $this->package();
157110 }
158111
159- /**
160- * Runs in its own PHP process, whose sys_temp_dir is private to the test so leftovers are observable.
161- *
162- * @param array<string, string> $env
163- *
164- * @return array{int, string} the exit code and the log
165- */
166- private function package(string $zipFile, array $env = []): array
112+ public function testLockOutOfSyncWithComposerJsonIsRefused(): void
167113 {
168- $code = \sprintf('require %s; (new %s(%s, STDERR))->package(%s);', var_export(\dirname(__DIR__).'/vendor/autoload.php', true), Packager::class, var_export($this->appDir, true), var_export($zipFile, true));
169- $env += [
170- 'PACKAGER_TEST_RECORD' => $this->dir.'/record.json',
171- // Hermetic: path repositories only, and no global Composer config.
172- 'COMPOSER_HOME' => $this->dir.'/composer-home',
173- 'COMPOSER_CACHE_DIR' => $this->dir.'/composer-cache',
174- 'COMPOSER_DISABLE_NETWORK' => '1',
175- 'COMPOSER_NO_AUDIT' => '1',
176- ];
177- $process = proc_open([\PHP_BINARY, '-d', 'sys_temp_dir='.$this->dir.'/tmp', '-r', $code], [0 => ['file', '/dev/null', 'r'], 1 => ['file', '/dev/null', 'w'], 2 => ['pipe', 'w']], $pipes, null, $env + $this->inheritedEnv());
178- \assert(false !== $process);
179- $log = (string) stream_get_contents($pipes[2]);
180- fclose($pipes[2]);
181-
182- return [proc_close($process), $log];
114+ $this->editComposerJson(static fn (array $composer): array => ['require' => ['acme/lib' => '^2.0']] + $composer);
115+
116+ $this->expectExceptionMessage('composer.lock is not up to date with composer.json');
117+ $this->package();
183118 }
184119
185- /**
186- * @return array<string, string>
187- */
188- private function inheritedEnv(): array
120+ public function testPathRepositoryIsRefused(): void
189121 {
190- // Hermetic: a COMPOSER, COMPOSER_VENDOR_DIR... of the developer's shell would point the install elsewhere.
191- return array_filter(getenv(), static fn (string $name): bool => !str_starts_with($name, 'COMPOSER'), \ARRAY_FILTER_USE_KEY);
122+ // As "composer config repositories.local path .." writes it.
123+ $this->editComposerJson(static fn (array $composer): array => ['repositories' => ['local' => ['type' => 'path', 'url' => '..']]] + $composer);
124+
125+ $this->expectExceptionMessage('composer.json declares the "path" repository ".."');
126+ $this->package();
192127 }
193128
194- /**
195- * @return array<mixed>
196- */
197- private function record(): array
129+ #[TestWith(['packages'])]
130+ #[TestWith(['packages-dev'])]
131+ public function testPackageInstalledFromAPathIsRefused(string $section): void
132+ {
133+ $lock = json_decode((string) file_get_contents($this->appDir.'/composer.lock'), true);
134+ self::assertIsArray($lock);
135+ $packages = \is_array($lock[$section] ?? null) ? $lock[$section] : [];
136+ $packages[] = ['name' => 'acme/local', 'version' => 'dev-main', 'dist' => ['type' => 'path', 'url' => '../local']];
137+ $lock[$section] = $packages;
138+ $this->filesystem->dumpFile($this->appDir.'/composer.lock', (string) json_encode($lock));
139+
140+ $this->expectExceptionMessage('composer.lock installs "acme/local" from a local path');
141+ $this->package();
142+ }
143+
144+ public function testRefusedApplicationLeavesNoZip(): void
198145 {
199- $record = json_decode((string) file_get_contents($this->dir.'/record.json'), true, 512, \JSON_THROW_ON_ERROR);
200- \assert(\is_array($record));
146+ $this->filesystem->remove($this->appDir.'/handler.php');
147+
148+ try {
149+ $this->package();
150+ self::fail('The application must be refused.');
151+ } catch (\RuntimeException $e) {
152+ self::assertStringContainsString('"handler.php" is missing', $e->getMessage());
153+ }
154+ self::assertFileDoesNotExist($this->dir.'/function.zip');
155+ }
201156
202- return $record;
157+ private function package(): void
158+ {
159+ new Packager($this->appDir, $this->log)->package($this->dir.'/function.zip');
203160 }
204161
205162 /**
206- * @return list<string>
163+ * @param \Closure(array<mixed>): array<mixed> $edit
207164 */
208- private function leftovers(): array
165+ private function editComposerJson(\Closure $edit): void
209166 {
210- return array_values(array_diff(scandir($this->dir.'/tmp') ?: [], ['.', '..']));
167+ $composer = json_decode((string) file_get_contents($this->appDir.'/composer.json'), true);
168+ self::assertIsArray($composer);
169+ $this->filesystem->dumpFile($this->appDir.'/composer.json', (string) json_encode($edit($composer)));
211170 }
212171 }
@@ -14,15 +14,19 @@ final class PackagerTest extends TestCase
14 private Filesystem $filesystem;14 private Filesystem $filesystem;
15 private string $dir;15 private string $dir;
16 private string $appDir;16 private string $appDir;
17+ /** @var resource */
18+ private $log;
17 19
18 protected function setUp(): void20 protected function setUp(): void
19 {21 {
20 $this->filesystem = new Filesystem();22 $this->filesystem = new Filesystem();
21- // Real paths, as bin/scaleway-package passes and as the build dir reports them (macOS /var is a symlink).23+ // Real paths, as bin/scaleway-package passes them (macOS /var is a symlink).
22 $this->dir = (string) realpath(sys_get_temp_dir()).'/scaleway-runtime-'.bin2hex(random_bytes(4));24 $this->dir = (string) realpath(sys_get_temp_dir()).'/scaleway-runtime-'.bin2hex(random_bytes(4));
23- $this->appDir = $this->dir.'/project/app';25+ $this->appDir = $this->dir.'/app';
24- $this->filesystem->mirror(__DIR__.'/Fixtures/PackagedApp', $this->dir.'/project');26+ $this->filesystem->mirror(__DIR__.'/Fixtures/PackagedApp', $this->appDir);
25- $this->filesystem->mkdir($this->dir.'/tmp');27+ $log = fopen('php://memory', 'w+');
28+ self::assertNotFalse($log);
29+ $this->log = $log;
26 }30 }
27 31
28 protected function tearDown(): void32 protected function tearDown(): void
@@ -57,29 +61,10 @@ final class PackagerTest extends TestCase
57 self::assertFalse(Packager::isExcluded($path));61 self::assertFalse(Packager::isExcluded($path));
58 }62 }
59 63
60- public function testRelativePathRepositoriesAreResolvedAgainstTheApplication(): void64+ public function testZipShipsTheSourcesAndComposerFilesWithoutVendorNorVar(): void
61- {
62- $lock = [
63- 'packages' => [
64- ['name' => 'acme/local', 'dist' => ['type' => 'path', 'url' => '../lib']],
65- ['name' => 'acme/absolute', 'dist' => ['type' => 'path', 'url' => '/opt/lib']],
66- ['name' => 'acme/remote', 'dist' => ['type' => 'zip', 'url' => 'https://example.test/a.zip']],
67- ],
68- 'packages-dev' => [['name' => 'acme/dev', 'dist' => ['type' => 'path', 'url' => 'packages/dev']]],
69- 'content-hash' => 'abc',
70- ];
71-
72- $expected = $lock;
73- $expected['packages'][0]['dist']['url'] = '/srv/app/../lib';
74- $expected['packages-dev'][0]['dist']['url'] = '/srv/app/packages/dev';
75-
76- self::assertSame($expected, Packager::resolvePathRepositories($lock, '/srv/app'));
77- }
78-
79- public function testZipShipsTheApplicationWithProductionDependenciesAndTheCommittedLock(): void
80 {65 {
81 $this->filesystem->dumpFile($this->appDir.'/var/cache/prod/stale.php', '');66 $this->filesystem->dumpFile($this->appDir.'/var/cache/prod/stale.php', '');
82- $this->filesystem->dumpFile($this->appDir.'/vendor/stale.php', '');67+ $this->filesystem->dumpFile($this->appDir.'/vendor/autoload.php', '');
83 $this->filesystem->dumpFile($this->appDir.'/tests/ServiceTest.php', '');68 $this->filesystem->dumpFile($this->appDir.'/tests/ServiceTest.php', '');
84 $this->filesystem->dumpFile($this->appDir.'/.env.local', 'APP_SECRET=local');69 $this->filesystem->dumpFile($this->appDir.'/.env.local', 'APP_SECRET=local');
85 $this->filesystem->dumpFile($this->appDir.'/.git/HEAD', '');70 $this->filesystem->dumpFile($this->appDir.'/.git/HEAD', '');
@@ -87,126 +72,100 @@ final class PackagerTest extends TestCase
87 $this->filesystem->dumpFile($this->appDir.'/terraform/terraform.tfstate', '{}');72 $this->filesystem->dumpFile($this->appDir.'/terraform/terraform.tfstate', '{}');
88 // A previous build, in the application like the default "function.zip": it must not end up in itself.73 // A previous build, in the application like the default "function.zip": it must not end up in itself.
89 $this->filesystem->dumpFile($this->appDir.'/function.zip', 'stale');74 $this->filesystem->dumpFile($this->appDir.'/function.zip', 'stale');
90- $lock = (string) file_get_contents($this->appDir.'/composer.lock');
91 75
92- [$exitCode, $log] = $this->package($this->appDir.'/function.zip');76+ new Packager($this->appDir, $this->log)->package($this->appDir.'/function.zip');
93 77
94- self::assertSame(0, $exitCode, $log);
95 $zip = new \ZipArchive();78 $zip = new \ZipArchive();
96 self::assertTrue($zip->open($this->appDir.'/function.zip'));79 self::assertTrue($zip->open($this->appDir.'/function.zip'));
97 $names = [];80 $names = [];
98 for ($i = 0; $i < $zip->numFiles; ++$i) {81 for ($i = 0; $i < $zip->numFiles; ++$i) {
99 $names[] = (string) $zip->getNameIndex($i);82 $names[] = (string) $zip->getNameIndex($i);
100 }83 }
101- $shipped = array_values(array_filter($names, static fn (string $name): bool => !str_starts_with($name, 'vendor/composer/')));84+ sort($names);
102- sort($shipped);85+ self::assertSame(['.env', 'bin/console', 'composer.json', 'composer.lock', 'handler.php', 'src/Service.php'], $names);
103- self::assertSame([86+ self::assertSame(file_get_contents($this->appDir.'/composer.lock'), $zip->getFromName('composer.lock'));
104- '.env',
105- 'bin/console',
106- 'composer.json',
107- 'composer.lock',
108- 'handler.php',
109- 'src/Service.php',
110- 'vendor/acme/lib/composer.json',
111- 'vendor/autoload.php',
112- ], $shipped);
113- // Relative "../lib" did not resolve from the build dir, yet the zip ships the lock exactly as committed.
114- self::assertSame($lock, $zip->getFromName('composer.lock'));
115- self::assertSame($lock, file_get_contents($this->appDir.'/composer.lock'));
116 self::assertTrue($zip->getExternalAttributesName('bin/console', $system, $attributes));87 self::assertTrue($zip->getExternalAttributesName('bin/console', $system, $attributes));
117 self::assertIsInt($attributes);88 self::assertIsInt($attributes);
118 self::assertSame(0o755, ($attributes >> 16) & 0o777);89 self::assertSame(0o755, ($attributes >> 16) & 0o777);
119 $zip->close();90 $zip->close();
120-
121- $record = $this->record();
122- self::assertSame(['cache:warmup', '--no-interaction'], $record['argv']);
123- self::assertSame('prod', $record['appEnv']);
124- self::assertSame($lock, $record['lock']);
125- }
126-
127- public function testBuildDirIsPrivateAndRemovedAfterwards(): void
128- {
129- [$exitCode, $log] = $this->package($this->dir.'/function.zip');
130-
131- self::assertSame(0, $exitCode, $log);
132- $record = $this->record();
133- self::assertIsString($record['buildDir']);
134- self::assertStringStartsWith($this->dir.'/tmp/scaleway-package-', $record['buildDir']);
135- self::assertSame(0o700, $record['perms']);
136- self::assertSame([], $this->leftovers());
137 }91 }
138 92
139- public function testFailedBuildLeavesNeitherBuildDirNorZip(): void93+ public function testContentHashIsComposers(): void
140 {94 {
141- [$exitCode, $log] = $this->package($this->dir.'/function.zip', ['PACKAGER_TEST_FAIL' => '1']);95+ $composer = json_decode((string) file_get_contents(__DIR__.'/Fixtures/PackagedApp/composer.json'), true);
96+ $lock = json_decode((string) file_get_contents(__DIR__.'/Fixtures/PackagedApp/composer.lock'), true);
97+ self::assertIsArray($composer);
98+ self::assertIsArray($lock);
142 99
143- self::assertNotSame(0, $exitCode);100+ // The fixture lock was written by Composer itself.
144- self::assertStringContainsString('cache:warmup --no-interaction" failed with exit code 1', $log);101+ self::assertSame($lock['content-hash'], Packager::contentHash($composer));
145- self::assertFileDoesNotExist($this->dir.'/function.zip');
146- self::assertSame([], $this->leftovers());
147 }102 }
148 103
149 public function testApplicationWithoutCommittedLockIsRefused(): void104 public function testApplicationWithoutCommittedLockIsRefused(): void
150 {105 {
151 $this->filesystem->remove($this->appDir.'/composer.lock');106 $this->filesystem->remove($this->appDir.'/composer.lock');
152- $log = fopen('php://memory', 'w');
153- \assert(false !== $log);
154 107
155 $this->expectExceptionMessage('"composer.lock" is missing');108 $this->expectExceptionMessage('"composer.lock" is missing');
156- new Packager($this->appDir, $log)->package($this->dir.'/function.zip');109+ $this->package();
157 }110 }
158 111
159- /**112+ public function testLockOutOfSyncWithComposerJsonIsRefused(): void
160- * Runs in its own PHP process, whose sys_temp_dir is private to the test so leftovers are observable.
161- *
162- * @param array<string, string> $env
163- *
164- * @return array{int, string} the exit code and the log
165- */
166- private function package(string $zipFile, array $env = []): array
167 {113 {
168- $code = \sprintf('require %s; (new %s(%s, STDERR))->package(%s);', var_export(\dirname(__DIR__).'/vendor/autoload.php', true), Packager::class, var_export($this->appDir, true), var_export($zipFile, true));114+ $this->editComposerJson(static fn (array $composer): array => ['require' => ['acme/lib' => '^2.0']] + $composer);
169- $env += [115+
170- 'PACKAGER_TEST_RECORD' => $this->dir.'/record.json',116+ $this->expectExceptionMessage('composer.lock is not up to date with composer.json');
171- // Hermetic: path repositories only, and no global Composer config.117+ $this->package();
172- 'COMPOSER_HOME' => $this->dir.'/composer-home',
173- 'COMPOSER_CACHE_DIR' => $this->dir.'/composer-cache',
174- 'COMPOSER_DISABLE_NETWORK' => '1',
175- 'COMPOSER_NO_AUDIT' => '1',
176- ];
177- $process = proc_open([\PHP_BINARY, '-d', 'sys_temp_dir='.$this->dir.'/tmp', '-r', $code], [0 => ['file', '/dev/null', 'r'], 1 => ['file', '/dev/null', 'w'], 2 => ['pipe', 'w']], $pipes, null, $env + $this->inheritedEnv());
178- \assert(false !== $process);
179- $log = (string) stream_get_contents($pipes[2]);
180- fclose($pipes[2]);
181-
182- return [proc_close($process), $log];
183 }118 }
184 119
185- /**120+ public function testPathRepositoryIsRefused(): void
186- * @return array<string, string>
187- */
188- private function inheritedEnv(): array
189 {121 {
190- // Hermetic: a COMPOSER, COMPOSER_VENDOR_DIR... of the developer's shell would point the install elsewhere.122+ // As "composer config repositories.local path .." writes it.
191- return array_filter(getenv(), static fn (string $name): bool => !str_starts_with($name, 'COMPOSER'), \ARRAY_FILTER_USE_KEY);123+ $this->editComposerJson(static fn (array $composer): array => ['repositories' => ['local' => ['type' => 'path', 'url' => '..']]] + $composer);
124+
125+ $this->expectExceptionMessage('composer.json declares the "path" repository ".."');
126+ $this->package();
192 }127 }
193 128
194- /**129+ #[TestWith(['packages'])]
195- * @return array<mixed>130+ #[TestWith(['packages-dev'])]
196- */131+ public function testPackageInstalledFromAPathIsRefused(string $section): void
197- private function record(): array132+ {
133+ $lock = json_decode((string) file_get_contents($this->appDir.'/composer.lock'), true);
134+ self::assertIsArray($lock);
135+ $packages = \is_array($lock[$section] ?? null) ? $lock[$section] : [];
136+ $packages[] = ['name' => 'acme/local', 'version' => 'dev-main', 'dist' => ['type' => 'path', 'url' => '../local']];
137+ $lock[$section] = $packages;
138+ $this->filesystem->dumpFile($this->appDir.'/composer.lock', (string) json_encode($lock));
139+
140+ $this->expectExceptionMessage('composer.lock installs "acme/local" from a local path');
141+ $this->package();
142+ }
143+
144+ public function testRefusedApplicationLeavesNoZip(): void
198 {145 {
199- $record = json_decode((string) file_get_contents($this->dir.'/record.json'), true, 512, \JSON_THROW_ON_ERROR);146+ $this->filesystem->remove($this->appDir.'/handler.php');
200- \assert(\is_array($record));147+
148+ try {
149+ $this->package();
150+ self::fail('The application must be refused.');
151+ } catch (\RuntimeException $e) {
152+ self::assertStringContainsString('"handler.php" is missing', $e->getMessage());
153+ }
154+ self::assertFileDoesNotExist($this->dir.'/function.zip');
155+ }
201 156
202- return $record;157+ private function package(): void
158+ {
159+ new Packager($this->appDir, $this->log)->package($this->dir.'/function.zip');
203 }160 }
204 161
205 /**162 /**
206- * @return list<string>163+ * @param \Closure(array<mixed>): array<mixed> $edit
207 */164 */
208- private function leftovers(): array165+ private function editComposerJson(\Closure $edit): void
209 {166 {
210- return array_values(array_diff(scandir($this->dir.'/tmp') ?: [], ['.', '..']));167+ $composer = json_decode((string) file_get_contents($this->appDir.'/composer.json'), true);
168+ self::assertIsArray($composer);
169+ $this->filesystem->dumpFile($this->appDir.'/composer.json', (string) json_encode($edit($composer)));
211 }170 }
212 }171 }
modified tests/ScalewayRuntimeTest.php +15 -0
@@ -42,6 +42,10 @@ final class ScalewayRuntimeTest extends TestCase
4242 chmod($this->projectDir, 0o777);
4343 if (is_dir($this->projectDir.'/var')) {
4444 chmod($this->projectDir.'/var', 0o777);
45+ if (is_dir($this->projectDir.'/var/cache/prod')) {
46+ rmdir($this->projectDir.'/var/cache/prod');
47+ rmdir($this->projectDir.'/var/cache');
48+ }
4549 rmdir($this->projectDir.'/var');
4650 }
4751 unlink($this->projectDir.'/.env');
@@ -114,6 +118,7 @@ final class ScalewayRuntimeTest extends TestCase
114118
115119 public function testReadOnlyVarDirFallsBackToTempDirAndKeepsTheWarmedBuildDir(): void
116120 {
121+ mkdir($this->projectDir.'/var/cache/prod', 0o777, true);
117122 chmod($this->projectDir.'/var', 0o555);
118123
119124 $this->createRuntime();
@@ -123,6 +128,16 @@ final class ScalewayRuntimeTest extends TestCase
123128 self::assertSame(sys_get_temp_dir().'/log', $_SERVER['APP_LOG_DIR']);
124129 }
125130
131+ public function testReadOnlyVarDirWithoutWarmedCacheBuildsTheContainerInTheTempDir(): void
132+ {
133+ chmod($this->projectDir.'/var', 0o555);
134+
135+ $this->createRuntime();
136+
137+ self::assertArrayNotHasKey('APP_BUILD_DIR', $_SERVER);
138+ self::assertSame(sys_get_temp_dir().'/cache', $_SERVER['APP_CACHE_DIR']);
139+ }
140+
126141 public function testReadOnlyProjectWithoutVarDirFallsBack(): void
127142 {
128143 rmdir($this->projectDir.'/var');
@@ -42,6 +42,10 @@ final class ScalewayRuntimeTest extends TestCase
42 chmod($this->projectDir, 0o777);42 chmod($this->projectDir, 0o777);
43 if (is_dir($this->projectDir.'/var')) {43 if (is_dir($this->projectDir.'/var')) {
44 chmod($this->projectDir.'/var', 0o777);44 chmod($this->projectDir.'/var', 0o777);
45+ if (is_dir($this->projectDir.'/var/cache/prod')) {
46+ rmdir($this->projectDir.'/var/cache/prod');
47+ rmdir($this->projectDir.'/var/cache');
48+ }
45 rmdir($this->projectDir.'/var');49 rmdir($this->projectDir.'/var');
46 }50 }
47 unlink($this->projectDir.'/.env');51 unlink($this->projectDir.'/.env');
@@ -114,6 +118,7 @@ final class ScalewayRuntimeTest extends TestCase
114 118
115 public function testReadOnlyVarDirFallsBackToTempDirAndKeepsTheWarmedBuildDir(): void119 public function testReadOnlyVarDirFallsBackToTempDirAndKeepsTheWarmedBuildDir(): void
116 {120 {
121+ mkdir($this->projectDir.'/var/cache/prod', 0o777, true);
117 chmod($this->projectDir.'/var', 0o555);122 chmod($this->projectDir.'/var', 0o555);
118 123
119 $this->createRuntime();124 $this->createRuntime();
@@ -123,6 +128,16 @@ final class ScalewayRuntimeTest extends TestCase
123 self::assertSame(sys_get_temp_dir().'/log', $_SERVER['APP_LOG_DIR']);128 self::assertSame(sys_get_temp_dir().'/log', $_SERVER['APP_LOG_DIR']);
124 }129 }
125 130
131+ public function testReadOnlyVarDirWithoutWarmedCacheBuildsTheContainerInTheTempDir(): void
132+ {
133+ chmod($this->projectDir.'/var', 0o555);
134+
135+ $this->createRuntime();
136+
137+ self::assertArrayNotHasKey('APP_BUILD_DIR', $_SERVER);
138+ self::assertSame(sys_get_temp_dir().'/cache', $_SERVER['APP_CACHE_DIR']);
139+ }
140+
126 public function testReadOnlyProjectWithoutVarDirFallsBack(): void141 public function testReadOnlyProjectWithoutVarDirFallsBack(): void
127 {142 {
128 rmdir($this->projectDir.'/var');143 rmdir($this->projectDir.'/var');