diff --git a/dagger-module.toml b/dagger-module.toml index 39b9c94..8ca3eb8 100644 --- a/dagger-module.toml +++ b/dagger-module.toml @@ -6,4 +6,4 @@ engineVersion = "v1.0.0-beta.27" [[dependencies]] name = "sdk-helpers" - source = "github.com/dagger/sdk-helpers@v1.0.9" + source = "github.com/dagger/sdk-helpers@v1.0.11" diff --git a/dagger.lock b/dagger.lock index be7c05d..1a38990 100644 --- a/dagger.lock +++ b/dagger.lock @@ -1,5 +1,5 @@ [["version","2"]] -["","git-latest",["github.com/dagger/sdk-helpers",["version","v1.0.9"]],"refs/tags/v1.0.9"] -["","git-sha",["github.com/dagger/sdk-helpers","refs/tags/v1.0.9"],"daffbc01a1b3f3df7b1c417a7d2c83cd06d1bd33"] +["","git-latest",["github.com/dagger/sdk-helpers",["version","v1.0.11"]],"refs/tags/v1.0.11"] +["","git-sha",["github.com/dagger/sdk-helpers","refs/tags/v1.0.11"],"3be7456c40d9206b648ac44e418f30aa79bc6190"] ["","git-sha",["https://github.com/dagger/dagger","refs/tags/v1.0.0-beta.11"],"a4e1e4ff663e5e51c2b96c2c0772f3d2f00cfb94"] ["","oci-sha",["docker.io/library/golang:1.25-alpine"],"sha256:1ae0735f00daffa3aaf1363a5184c0d2dc55c78e3db4ec70241cdac97bf84b59"] \ No newline at end of file diff --git a/sdk/bin/dagger-module b/sdk/bin/dagger-module index c86f3d3..a35d44d 100755 --- a/sdk/bin/dagger-module +++ b/sdk/bin/dagger-module @@ -5,6 +5,7 @@ use Dagger\Dagger; use Dagger\Module\CallDispatcher; use Dagger\Module\DangEntrypointRenderer; use Dagger\Module\Description; +use Dagger\Module\FunctionError; use Dagger\Module\InterfaceClients; use Dagger\Module\ValueCodec; use GraphQL\Exception\QueryError; @@ -46,6 +47,16 @@ require $autoload; $mode = $argv[1] ?? ''; $options = options(array_slice($argv, 2)); +// Made before the function runs, which may change the working directory. +$functionError = FunctionError::forModule(dirname(__DIR__), (string) getcwd()); +$functionErrorPath = getenv(FunctionError::PATH_ENV); +$functionErrorPath = $functionErrorPath === false ? null : $functionErrorPath; +if ($mode === 'call') { + // A fatal error, such as exhausted memory or a class that can't be + // declared, ends the script with no Throwable to catch below. + $functionError->reportFatalErrors($functionErrorPath, STDERR); +} + try { switch ($mode) { case 'generate': @@ -72,12 +83,19 @@ try { default: fail(USAGE, 2); } -} catch (QueryError $e) { - $extensions = $e->getErrorDetails()['extensions'] ?? []; +} catch (Throwable $t) { + if ($mode === 'call') { + // A failed call exits 2, so that its exec isn't cached, and reports + // the function's error to the engine; see FunctionError. + $functionError->report($t, $functionErrorPath, STDERR, STDOUT); + exit(2); + } + if (!$t instanceof QueryError) { + fwrite(STDERR, sprintf("dagger-module: %s: %s\n%s\n", $t::class, $t->getMessage(), $t->getTraceAsString())); + exit(1); + } + $extensions = $t->getErrorDetails()['extensions'] ?? []; fwrite(STDOUT, $extensions['stdout'] ?? ''); - fwrite(STDERR, $e->getMessage() . "\n" . ($extensions['stderr'] ?? '')); + fwrite(STDERR, $t->getMessage() . "\n" . ($extensions['stderr'] ?? '')); exit($extensions['exitCode'] ?? 1); -} catch (Throwable $t) { - fwrite(STDERR, sprintf("dagger-module: %s: %s\n%s\n", $t::class, $t->getMessage(), $t->getTraceAsString())); - exit(1); } diff --git a/sdk/src/Module/DangEntrypointRenderer.php b/sdk/src/Module/DangEntrypointRenderer.php index 67a9448..be0bfd2 100644 --- a/sdk/src/Module/DangEntrypointRenderer.php +++ b/sdk/src/Module/DangEntrypointRenderer.php @@ -289,6 +289,13 @@ private static function wrap(string $call, array $body): array ModuleTypes().all } + # The module with its Composer dependencies installed, which every call + # runs: the engine builds it ahead of a call, as the module's build, so + # a failed install shows as the build's, with Composer's output. + pub prebuild: File! { + runtime.file("vendor/autoload.php") + } + pub call( receiverType: String!, receiverValue: JSON, @@ -302,7 +309,13 @@ private static function wrap(string $call, array $body): array fnName: fnName, fnArgs: fnArgs, }}) - let result = runtime + # A failed install stays out of the rescue below, so it fails the call + # with its own error. An engine that builds prebuild first fails the + # call before it gets here. + let installed = runtime.sync rescue { + err: GraphQLError => raiseWithStderr(err) + } + let result = installed .withEnvVariable("DAGGER_CLIENT_VERSION", %clientVersion%) # The exec is cached on its own recipe, which holds neither the call's # arguments nor its cache policy; the engine's digest of the call does @@ -311,17 +324,48 @@ private static function wrap(string $call, array $body): array .withExec(["php", "sdk/bin/dagger-module", "call", "--output", "/dagger/result.json"], stdin: request, experimentalPrivilegedNesting: true) .file("/dagger/result.json") .contents rescue { - # From v1.0.0-beta.27 an exec error's message carries only the exit code. - # Its extensions hold the stderr, capped by the engine at 100 KiB. - err: GraphQLError => { - let stderr = (JSON.decode(err.extensions) :: {{stderr: String}}).stderr ?? "" - if (stderr == "") { raise err } - raise stderr - } + err: GraphQLError => raiseFunctionError(err) } (result :: JSON!) } + # An engine that gives the dispatcher a file for the function's error + # (DAGGER_FUNCTION_ERROR_PATH) puts the error the dispatcher wrote there + # in its exec's error, and fails the call with it, values and all: the + # exec's error is raised as it is. Otherwise, as with an older engine or + # a file the dispatcher couldn't write, the exec error carries the end of + # the dispatcher's stderr, where its last marker line holds the + # function's error; without one, the exec failed before the function + # returned, as when it exited by itself, and its own error is raised + # again, or, on an engine that marks no module process, its stderr. + let raiseFunctionError(err: GraphQLError!): String! { + let reported = ((JSON.decode(err.extensions) :: {{functionError: {{message: String, id: String}}}}).functionError != null) rescue false + if (reported) { + raise err + } + let marker = "::dagger-function-error::" + let stderr = ((JSON.decode(err.extensions) :: {{stderr: String}}).stderr ?? "") rescue "" + let lines = stderr.split("\n").filter { line => line.hasPrefix(marker) } + if (lines.isEmpty) { + raiseWithStderr(err) + } + raise ((JSON.decode(lines.takeLast(1).join("").trimPrefix(marker)) :: String!) rescue err.message) + } + + # Raise a failed exec's error. An engine that marks the module process + # (the moduleProcess extension) shows an exec's logs with its error, so + # the error is raised as it is; an older engine shows only the exit + # code, so the end of the exec's stderr, which the engine caps at + # 100 KiB, is raised instead. + let raiseWithStderr(err: GraphQLError!): Container! { + let marked = ((JSON.decode(err.extensions) :: {{moduleProcess: Boolean}}).moduleProcess ?? false) rescue false + let stderr = ((JSON.decode(err.extensions) :: {{stderr: String}}).stderr ?? "") rescue "" + if (marked or stderr == "") { + raise err + } + raise stderr + } + let runtime: Container! { PhpModuleBuild(contextDir: currentModule.contextDirectory, subPath: currentModule.sourceSubpath).installed } diff --git a/sdk/src/Module/FunctionError.php b/sdk/src/Module/FunctionError.php new file mode 100644 index 0000000..7494e92 --- /dev/null +++ b/sdk/src/Module/FunctionError.php @@ -0,0 +1,352 @@ + $frameworkPaths the directories whose code isn't the + * module's own: the SDK's and the installed dependencies', each ending in / + */ + public function __construct(private array $frameworkPaths) + { + } + + /** + * The module's code is everything but the SDK, its generated clients + * included, and what Composer installed into vendor/. A library the + * module installs from a path of its own resolves to that path, so its + * frames stay. + */ + public static function forModule(string $sdkRoot, string $moduleRoot): self + { + $paths = []; + foreach ([$sdkRoot, "$moduleRoot/vendor"] as $path) { + $paths[] = rtrim($path, '/') . '/'; + $real = realpath($path); + if ($real !== false) { + $paths[] = rtrim($real, '/') . '/'; + } + } + + return new self(array_values(array_unique($paths))); + } + + /** + * Report $error: in the file at $path when there is one and it can be + * written, else with the marker. Diagnostics go to $stderr. Without the + * file, the output of a failed exec the error is or wraps goes to $stdout + * and $stderr first, as an engine that reads no file shows no exec's + * logs with its error. + * + * @param resource $stderr + * @param ?resource $stdout + */ + public function report(Throwable $error, ?string $path, $stderr, $stdout = null): void + { + if ($path !== null && $path !== '' && self::writeFile($path, $error)) { + if (!self::hasOrigin($error)) { + fwrite($stderr, $this->shortTrace($error)); + } + return; + } + + $values = self::values($error); + if ($stdout !== null && is_string($values['stdout'] ?? null)) { + fwrite($stdout, $values['stdout']); + } + fwrite($stderr, sprintf("dagger-module: %s\n", $error)); + if (is_string($values['stderr'] ?? null) && $values['stderr'] !== '') { + fwrite($stderr, rtrim($values['stderr'], "\n") . "\n"); + } + self::writeMarker($stderr, self::messageOf($error)); + } + + /** + * Report a fatal error, which ends the script without a Throwable to + * catch, as error_get_last() returns it, from a shutdown function. PHP + * has shown it already, so it is only reported, in the file at $path or + * else with the marker. Anything other than a fatal error is ignored. + * + * @param ?array{type: int, message: string, file: string, line: int} $error + * @param resource $stderr + */ + public function reportFatal(?array $error, ?string $path, $stderr): void + { + if ($error === null || ($error['type'] & self::FATAL_ERRORS) === 0) { + return; + } + $fatal = new ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line']); + if ($path !== null && $path !== '' && self::writeFile($path, $fatal)) { + return; + } + self::writeMarker($stderr, self::messageOf($fatal)); + } + + /** + * Report the fatal error that ends this script, if one does, from a + * shutdown function (see reportFatal). The memory it reserves is freed + * first, so that a script that exhausted its memory can still report it. + * + * @param resource $stderr + */ + public function reportFatalErrors(?string $path, $stderr): void + { + $reserved = str_repeat("\0", self::FATAL_RESERVE); + register_shutdown_function(function () use (&$reserved, $path, $stderr): void { + $reserved = null; + $this->reportFatal(error_get_last(), $path, $stderr); + }); + } + + /** @param resource $stderr */ + private static function writeMarker($stderr, string $message): void + { + fwrite($stderr, self::MARKER . json_encode(self::truncate($message), self::JSON_FLAGS) . "\n"); + } + + /** + * Whether the error is an API error that names its origin, the call that + * failed, which the engine shows with its own logs. An error of the + * module's own, even one that wraps such an API error, is the module's + * to show. + */ + public static function hasOrigin(Throwable $error): bool + { + return $error instanceof QueryError && preg_match(self::ORIGIN, $error->getMessage()) === 1; + } + + /** + * The report the engine reads: `{"message": ..., "values": {...}}`, the + * error's message in full, with any origin it names, and the extensions + * of the GraphQL error it is or wraps, as they are, such as a failed + * exec's exit code and output. Only a report over what the engine reads + * is shortened: long strings keep their end, where output usually says + * what failed, and the message its start and the origins it names; then + * the values go. + */ + public static function fileReport(Throwable $error): string + { + $message = self::messageOf($error); + $values = self::values($error); + $report = self::encodeReport($message, $values); + if (strlen($report) <= self::FILE_LIMIT) { + return $report; + } + + if (strlen($message) > self::SHORTENED_LENGTH) { + preg_match_all(self::ORIGIN, substr($message, self::SHORTENED_LENGTH), $origins); + $message = mb_strcut($message, 0, self::SHORTENED_LENGTH) . '...' . implode('', $origins[0]); + } + $report = self::encodeReport($message, (array) self::shortened($values)); + if (strlen($report) <= self::FILE_LIMIT) { + return $report; + } + + return self::encodeReport($message, []); + } + + /** + * The error as PHP prints an uncaught one, through the module's own + * frames only, previous errors first, and without the origins the + * messages name. A file that doesn't parse reads as PHP reports it. + */ + public function shortTrace(Throwable $error): string + { + $chain = []; + for ($e = $error; $e !== null && !in_array($e, $chain, true); $e = $e->getPrevious()) { + $chain[] = $e; + } + + $parts = []; + foreach (array_reverse($chain) as $e) { + $parts[] = $this->describe($e); + } + + return implode("\nNext ", $parts); + } + + private function describe(Throwable $e): string + { + $message = self::withoutOrigins($e->getMessage()); + if ($e instanceof CompileError && $this->isModuleFile($e->getFile())) { + $kind = $e instanceof ParseError ? 'Parse error' : 'Fatal error'; + return sprintf("PHP %s: %s in %s on line %d\n", $kind, $message, $e->getFile(), $e->getLine()); + } + + $text = $e::class . ($message === '' ? '' : ": $message"); + if ($this->isModuleFile($e->getFile())) { + $text .= sprintf(' in %s:%d', $e->getFile(), $e->getLine()); + } + $text .= "\n"; + + $frames = []; + foreach ($e->getTrace() as $frame) { + $file = $frame['file'] ?? null; + if ($file === null || !$this->isModuleFile($file)) { + continue; + } + $function = isset($frame['class']) + ? $frame['class'] . ($frame['type'] ?? '::') . $frame['function'] + : $frame['function']; + $frames[] = sprintf('#%d %s(%d): %s()', count($frames), $file, $frame['line'] ?? 0, $function); + } + if ($frames !== []) { + $text .= "Stack trace:\n" . implode("\n", $frames) . "\n"; + } + + return $text; + } + + private function isModuleFile(string $file): bool + { + if ($file === '' || !str_starts_with($file, '/')) { + return false; + } + foreach ($this->frameworkPaths as $path) { + if (str_starts_with($file, $path)) { + return false; + } + } + + return true; + } + + private static function writeFile(string $path, Throwable $error): bool + { + try { + $report = self::fileReport($error); + } catch (JsonException) { + return false; + } + + return @file_put_contents($path, $report) === strlen($report); + } + + /** + * The error's message, or its class when it has none: the engine reads + * only a JSON report with a message, and rejects one with an empty + * message as invalid. + */ + private static function messageOf(Throwable $error): string + { + $message = $error->getMessage(); + + return trim($message) === '' ? $error::class : $message; + } + + /** + * The extensions of the GraphQL error that the error is or wraps, or none. + * + * @return array + */ + private static function values(Throwable $error): array + { + $seen = []; + for ($e = $error; $e !== null && !in_array($e, $seen, true); $e = $e->getPrevious()) { + $seen[] = $e; + if ($e instanceof QueryError) { + $extensions = $e->getErrorDetails()['extensions'] ?? []; + return is_array($extensions) ? $extensions : []; + } + } + + return []; + } + + /** @param array $values */ + private static function encodeReport(string $message, array $values): string + { + return json_encode( + ['message' => $message, 'values' => $values === [] ? new stdClass() : $values], + self::JSON_FLAGS, + ); + } + + /** + * The value with each string longer than SHORTENED_LENGTH, at any depth, + * cut to its end. + */ + private static function shortened(mixed $value): mixed + { + if (is_string($value) && strlen($value) > self::SHORTENED_LENGTH) { + $start = strlen($value) - self::SHORTENED_LENGTH; + // Not in the middle of a UTF-8 sequence. + while ($start < strlen($value) && (ord($value[$start]) & 0xC0) === 0x80) { + $start++; + } + return '...' . substr($value, $start); + } + if (is_array($value)) { + return array_map(self::shortened(...), $value); + } + + return $value; + } + + private static function truncate(string $message): string + { + return strlen($message) <= self::MARKER_LIMIT ? $message : mb_strcut($message, 0, self::MARKER_LIMIT) . '...'; + } + + private static function withoutOrigins(string $message): string + { + return (string) preg_replace(self::ORIGIN, '', $message); + } +} diff --git a/sdk/tests/Unit/Module/DangEntrypointRendererTest.php b/sdk/tests/Unit/Module/DangEntrypointRendererTest.php index bee440e..0e5d490 100644 --- a/sdk/tests/Unit/Module/DangEntrypointRendererTest.php +++ b/sdk/tests/Unit/Module/DangEntrypointRendererTest.php @@ -6,6 +6,7 @@ use Dagger\Module\DangEntrypointRenderer; use Dagger\Module\Description; +use Dagger\Module\FunctionError; use Dagger\ModuleNaming; use Dagger\ValueObject\DaggerEnum; use Dagger\ValueObject\DaggerEnumCase; @@ -247,15 +248,59 @@ public function itRendersTheCallContract(): void self::assertStringContainsString('experimentalPrivilegedNesting: true)', $main); self::assertStringContainsString('.file("/dagger/result.json")', $main); self::assertStringContainsString('.contents rescue {', $main); - self::assertStringContainsString('err: GraphQLError =>', $main); - self::assertStringContainsString('{ raise err }', $main); - self::assertStringContainsString('raise stderr', $main); + self::assertStringContainsString('err: GraphQLError => raiseFunctionError(err)', $main); + self::assertStringContainsString( + " let installed = runtime.sync rescue {\n" + . " err: GraphQLError => raiseWithStderr(err)\n" + . " }\n" + . " let result = installed\n", + $main, + 'a failed install stays out of the function error rescue', + ); + self::assertStringContainsString( + "pub prebuild: File! {\n runtime.file(\"vendor/autoload.php\")\n }", + $main, + ); self::assertStringContainsString( 'PhpModuleBuild(contextDir: currentModule.contextDirectory, subPath: currentModule.sourceSubpath).installed', $main, ); } + /** + * The exec error is raised as it is when the engine read the function's + * error from its file; otherwise the marker line, then the exec error. + */ + #[Test] + public function itRaisesTheFunctionError(): void + { + $main = DangEntrypointRenderer::renderMain('v1.0.0-beta.21'); + + self::assertStringContainsString( + "let reported = ((JSON.decode(err.extensions) :: {{functionError: {{message: String, id: String}}}}).functionError != null) rescue false\n" + . " if (reported) {\n" + . " raise err\n" + . " }\n" + . ' let marker = "' . FunctionError::MARKER . "\"\n", + $main, + ); + self::assertStringContainsString( + " if (lines.isEmpty) {\n raiseWithStderr(err)\n }\n" + . ' raise ((JSON.decode(lines.takeLast(1).join("").trimPrefix(marker)) :: String!) rescue err.message)', + $main, + ); + self::assertStringContainsString( + "let marked = ((JSON.decode(err.extensions) :: {{moduleProcess: Boolean}}).moduleProcess ?? false) rescue false\n" + . " let stderr = ((JSON.decode(err.extensions) :: {{stderr: String}}).stderr ?? \"\") rescue \"\"\n" + . " if (marked or stderr == \"\") {\n" + . " raise err\n" + . " }\n" + . " raise stderr\n", + $main, + 'an engine that marks no module process gets the exec stderr, as before', + ); + } + #[Test] public function itWritesTheSameFilesTwice(): void { diff --git a/sdk/tests/Unit/Module/FunctionErrorTest.php b/sdk/tests/Unit/Module/FunctionErrorTest.php new file mode 100644 index 0000000..ec2c2a3 --- /dev/null +++ b/sdk/tests/Unit/Module/FunctionErrorTest.php @@ -0,0 +1,396 @@ + 'EXEC_ERROR', + 'cmd' => ['sh', '-c', 'exit 1'], + 'exitCode' => 1, + 'stdout' => "exec stdout\n", + 'stderr' => "exec stderr\n", + ]; + + /** @var list */ + private array $files = []; + + protected function tearDown(): void + { + foreach ($this->files as $file) { + @unlink($file); + } + } + + /** + * The SDK, PHPUnit among the installed dependencies, is the framework; + * this file stands for the module's code. + */ + private function functionError(): FunctionError + { + $sdk = dirname(__DIR__, 3); + + return FunctionError::forModule("$sdk/src", $sdk); + } + + /** @param array $extensions */ + private static function queryError(string $message, array $extensions = []): QueryError + { + $error = ['message' => $message, 'path' => ['container', 'stdout']]; + if ($extensions !== []) { + $error['extensions'] = $extensions; + } + + return new QueryError(['errors' => [$error], 'data' => null]); + } + + private static function failNatively(): never + { + throw new RuntimeException('function failed natively'); + } + + private static function caught(callable $fail): Throwable + { + try { + $fail(); + } catch (Throwable $error) { + return $error; + } + self::fail('nothing was thrown'); + } + + private function tempFile(): string + { + $file = (string) tempnam(sys_get_temp_dir(), 'function-error-'); + $this->files[] = $file; + + return $file; + } + + /** @return array{string, string} what report wrote to the file and to stderr */ + private function report(Throwable $error, ?string $path): array + { + $stderr = fopen('php://memory', 'w+'); + self::assertNotFalse($stderr); + $this->functionError()->report($error, $path, $stderr); + rewind($stderr); + $logs = (string) stream_get_contents($stderr); + fclose($stderr); + + return [$path === null || !is_file($path) ? '' : (string) file_get_contents($path), $logs]; + } + + #[Test] + public function itReportsAnApiErrorWithItsExtensions(): void + { + $report = json_decode( + FunctionError::fileReport(self::queryError('exit code: 1' . self::ORIGIN, self::EXEC_ERROR)), + true, + flags: JSON_THROW_ON_ERROR, + ); + + self::assertSame(['message' => 'exit code: 1' . self::ORIGIN, 'values' => self::EXEC_ERROR], $report); + } + + #[Test] + public function itReportsTheExtensionsOfAWrappedApiError(): void + { + $inner = self::queryError('exit code: 1' . self::ORIGIN, self::EXEC_ERROR); + $error = new RuntimeException('ran a failing command: ' . $inner->getMessage(), previous: $inner); + + $report = json_decode(FunctionError::fileReport($error), true, flags: JSON_THROW_ON_ERROR); + + self::assertSame('ran a failing command: exit code: 1' . self::ORIGIN, $report['message']); + self::assertSame(self::EXEC_ERROR, $report['values']); + } + + #[Test] + public function itReportsValuesAsAnObject(): void + { + self::assertSame( + '{"message":"function failed","values":{}}', + FunctionError::fileReport(new RuntimeException('function failed')), + ); + } + + #[Test] + public function itNamesTheClassOfAnErrorWithoutAMessage(): void + { + self::assertSame( + '{"message":"RuntimeException","values":{}}', + FunctionError::fileReport(new RuntimeException(' ')), + ); + } + + #[Test] + public function itShortensAReportTheEngineWouldNotRead(): void + { + $long = str_repeat('x', FunctionError::FILE_LIMIT); + $error = self::queryError($long . self::ORIGIN, ['stdout' => $long . 'end', 'exitCode' => 1]); + + $file = FunctionError::fileReport($error); + $report = json_decode($file, true, flags: JSON_THROW_ON_ERROR); + + self::assertLessThanOrEqual(FunctionError::FILE_LIMIT, strlen($file)); + self::assertStringEndsWith('...' . self::ORIGIN, $report['message']); + self::assertSame(FunctionError::SHORTENED_LENGTH + 3 + strlen(self::ORIGIN), strlen($report['message'])); + self::assertSame(1, $report['values']['exitCode']); + self::assertStringEndsWith('xend', $report['values']['stdout']); + self::assertSame(FunctionError::SHORTENED_LENGTH + 3, strlen($report['values']['stdout'])); + } + + #[Test] + public function itDropsTheValuesWhenShorteningIsNotEnough(): void + { + $values = array_fill(0, 32, str_repeat('x', FunctionError::SHORTENED_LENGTH)); + $error = self::queryError('failed', ['many' => $values]); + + self::assertSame('{"message":"failed","values":{}}', FunctionError::fileReport($error)); + } + + #[Test] + public function itWritesTheFileAndAShortTraceOfTheModulesFrames(): void + { + $error = self::caught(self::failNatively(...)); + $path = $this->tempFile(); + + [$file, $logs] = $this->report($error, $path); + + self::assertSame('{"message":"function failed natively","values":{}}', $file); + $trace = $error->getTrace(); + self::assertSame( + sprintf( + "RuntimeException: function failed natively in %s:%d\nStack trace:\n" + . "#0 %s(%d): %s::failNatively()\n#1 %s(%d): %s::caught()\n", + __FILE__, + $error->getLine(), + __FILE__, + $trace[0]['line'] ?? 0, + self::class, + __FILE__, + $trace[1]['line'] ?? 0, + self::class, + ), + $logs, + ); + self::assertStringNotContainsString('phpunit', $logs); + self::assertStringNotContainsString(FunctionError::MARKER, $logs); + } + + #[Test] + public function itLogsNothingForAnApiErrorWhoseOriginTheEngineShows(): void + { + $path = $this->tempFile(); + + [$file, $logs] = $this->report(self::queryError('exit code: 1' . self::ORIGIN, self::EXEC_ERROR), $path); + + self::assertStringStartsWith('{"message":"exit code: 1' . self::ORIGIN . '"', $file); + self::assertSame('', $logs); + } + + #[Test] + public function itLogsAnApiErrorWithoutAnOrigin(): void + { + $path = $this->tempFile(); + + $error = self::queryError('invalid ID'); + $line = __LINE__ - 1; + + [, $logs] = $this->report($error, $path); + + self::assertSame( + "GraphQL\\Exception\\QueryError: invalid ID in " . __FILE__ . ':' . $error->getLine() . "\n" + . "Stack trace:\n#0 " . __FILE__ . "($line): " . self::class . "::queryError()\n", + $logs, + ); + } + + #[Test] + public function itLogsAWrappedErrorAfterWhatItWraps(): void + { + $inner = self::queryError('exit code: 1' . self::ORIGIN, self::EXEC_ERROR); + $error = new RuntimeException('ran a failing command: ' . $inner->getMessage(), previous: $inner); + $line = __LINE__ - 1; + + $logs = $this->functionError()->shortTrace($error); + + self::assertSame( + "GraphQL\\Exception\\QueryError: exit code: 1 in " . __FILE__ . ':' . $inner->getLine() . "\n" + . "Stack trace:\n#0 " . __FILE__ . '(' . ($line - 1) . '): ' . self::class . "::queryError()\n" + . "\nNext RuntimeException: ran a failing command: exit code: 1 in " . __FILE__ . ":$line\n", + $logs, + ); + } + + #[Test] + public function itLogsAParseErrorAsPhpDoes(): void + { + $source = $this->tempFile(); + file_put_contents($source, "functionError()->shortTrace($error), + ); + } + + #[Test] + public function itFallsBackToTheMarker(): void + { + [, $logs] = $this->report(new RuntimeException("two\nlines" . self::ORIGIN), null); + + $lines = explode("\n", rtrim($logs, "\n")); + self::assertStringStartsWith('dagger-module: RuntimeException: two', $logs); + self::assertSame(FunctionError::MARKER . '"two\nlines' . self::ORIGIN . '"', end($lines)); + } + + /** + * An engine that reads no file shows no exec's logs with its error, so + * the output of the failed exec goes to the dispatcher's own streams, as + * before the file. + */ + #[Test] + public function itFallsBackWithTheOutputOfAFailedExec(): void + { + $inner = self::queryError('exit code: 1' . self::ORIGIN, self::EXEC_ERROR); + $error = new RuntimeException('ran a failing command: ' . $inner->getMessage(), previous: $inner); + $stdout = fopen('php://memory', 'w+'); + $stderr = fopen('php://memory', 'w+'); + self::assertNotFalse($stdout); + self::assertNotFalse($stderr); + + $this->functionError()->report($error, null, $stderr, $stdout); + + rewind($stdout); + rewind($stderr); + self::assertSame("exec stdout\n", stream_get_contents($stdout)); + self::assertStringEndsWith( + "exec stderr\n" . FunctionError::MARKER . '"ran a failing command: exit code: 1' . self::ORIGIN . "\"\n", + (string) stream_get_contents($stderr), + ); + } + + #[Test] + public function itReportsAFatalError(): void + { + $path = $this->tempFile(); + $stderr = fopen('php://memory', 'w+'); + self::assertNotFalse($stderr); + $fatal = ['type' => E_ERROR, 'message' => 'Allowed memory size exhausted', 'file' => __FILE__, 'line' => 1]; + + $this->functionError()->reportFatal($fatal, $path, $stderr); + + self::assertSame('{"message":"Allowed memory size exhausted","values":{}}', file_get_contents($path)); + rewind($stderr); + self::assertSame('', stream_get_contents($stderr), 'PHP shows a fatal error itself'); + } + + #[Test] + public function itReportsAFatalErrorWithTheMarker(): void + { + $stderr = fopen('php://memory', 'w+'); + self::assertNotFalse($stderr); + $fatal = ['type' => E_COMPILE_ERROR, 'message' => 'Cannot redeclare f()', 'file' => __FILE__, 'line' => 1]; + + $this->functionError()->reportFatal($fatal, null, $stderr); + + rewind($stderr); + self::assertSame(FunctionError::MARKER . "\"Cannot redeclare f()\"\n", stream_get_contents($stderr)); + } + + /** @return array */ + public static function memoryExhaustions(): array + { + return [ + 'by a growing array' => ['$kept = []; while (true) { $kept[] = new stdClass(); }'], + // Leaves the shutdown function no memory of its own but what + // reportFatalErrors reserved: without it, nothing is reported. + 'by deep recursion' => [ + 'function r($n) { $a = [$n, new stdClass()]; return r($n + 1) + count($a); } r(0);', + ], + ]; + } + + /** + * The commonest fatal error, exhausted memory, is reported too. + */ + #[Test] + #[DataProvider('memoryExhaustions')] + public function itReportsExhaustedMemory(string $workload): void + { + $path = $this->tempFile(); + $sdk = dirname(__DIR__, 3); + $script = sprintf( + 'require %s; Dagger\Module\FunctionError::forModule(%s, %s)->reportFatalErrors(%s, STDERR); %s', + var_export("$sdk/vendor/autoload.php", true), + var_export("$sdk/src", true), + var_export($sdk, true), + var_export($path, true), + $workload, + ); + $process = proc_open( + [PHP_BINARY, '-d', 'memory_limit=32M', '-d', 'display_errors=0', '-d', 'log_errors=0', '-r', $script], + [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], + $pipes, + ); + self::assertIsResource($process); + $output = stream_get_contents($pipes[1]) . stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + + self::assertSame(255, proc_close($process), $output); + self::assertStringStartsWith( + '{"message":"Allowed memory size of 33554432 bytes exhausted', + (string) file_get_contents($path), + $output, + ); + } + + #[Test] + public function itIgnoresAnErrorThatIsNotFatal(): void + { + $path = $this->tempFile(); + $stderr = fopen('php://memory', 'w+'); + self::assertNotFalse($stderr); + + $this->functionError()->reportFatal(null, $path, $stderr); + $this->functionError()->reportFatal( + ['type' => E_WARNING, 'message' => 'mkdir(): File exists', 'file' => __FILE__, 'line' => 1], + $path, + $stderr, + ); + + self::assertSame('', file_get_contents($path)); + rewind($stderr); + self::assertSame('', stream_get_contents($stderr)); + } + + #[Test] + public function itFallsBackToTheMarkerWhenTheFileCannotBeWritten(): void + { + [, $logs] = $this->report(new RuntimeException('failed'), '/nonexistent/dir/error.json'); + + self::assertStringEndsWith(FunctionError::MARKER . "\"failed\"\n", $logs); + } +}