diff --git a/.dagger/modules/e2e/entrypoint.dang b/.dagger/modules/e2e/entrypoint.dang index 684157a..02aefbb 100644 --- a/.dagger/modules/e2e/entrypoint.dang +++ b/.dagger/modules/e2e/entrypoint.dang @@ -105,13 +105,15 @@ type EntrypointChecks { """ A failing function's error reaches the caller with its text, not as the exit - code of the process that ran it. + code of the process that ran it. An engine that gives the process an error + file reports the error as the function's own; an older one prefixes it with + "call module entrypoint: ". """ pub errorCheck(ws: Workspace!): Void @check { let failed = cli(playground(app(ws)), ["-m", "app", "call", "fail"]) let said = failed.stdout + failed.stderr assert( - failed.exitCode != 0 and said.contains("call module entrypoint: entry-app failed: boom"), + failed.exitCode != 0 and said.contains("entry-app failed: boom"), "the function's error lost its text:\n" + said, ) null diff --git a/entrypoint/build.dang.tmpl b/entrypoint/build.dang.tmpl index 683fc12..0e10f2a 100644 --- a/entrypoint/build.dang.tmpl +++ b/entrypoint/build.dang.tmpl @@ -6,12 +6,25 @@ github.com/dagger/java-sdk/runtime does, and refuses a module whose generated files are stale. """ type JavaModuleBuild { + """ + The platform the jar is built on: the engine's when unset. The jar runs on + any, but its build is cached per platform. + """ + pub platform: Platform + """ Maven build output, never an input: a class file an IDE left there is newer than its source, so the compiler skips the source and packages the stale class. """ let buildOutputExclude: [String!]! = ["**/target/**"] + """ + The jar of the SDK that vendorSdkJar commits into the module. It has no + annotation processor, so a module that has it is packaged with its committed + entrypoint and compared with nothing. + """ + let vendoredSdkJar: String! = "sdk/repo/io/dagger/dagger-java-sdk/0.21.4/dagger-java-sdk-0.21.4.jar" + """ The module's shaded jar, packaged with the entrypoint the annotation processor generates from the module's code at call time. It is refused when a generated @@ -19,7 +32,7 @@ type JavaModuleBuild { from the committed one. """ pub jar: File! { - let module = withoutSVE(container.from("")) + let module = withoutSVE(container(platform: platform ?? defaultPlatform).from("")) .withoutEntrypoint .withMountedCache("/root/.m2", cacheVolume("sdk-java-maven-m2"), sharing: CacheSharingMode.LOCKED) .withDirectory("/src", currentModule.contextDirectory, exclude: buildOutputExclude) @@ -28,20 +41,39 @@ type JavaModuleBuild { module.withExec(["sh", "-c", editedScript]).stdout, "these generated files changed since dagger generate wrote them", ) - let built = module + let named = module .withEnvVariable("_DAGGER_JAVA_SDK_MODULE_NAME", "") .withEnvVariable("_DAGGER_JAVA_SDK_CLIENT_VERSION", "") - .withExec(["sh", "-c", buildScript]) - refuseStale( - built.file("/tmp/stale").contents, - "the module's code no longer generates these committed files", - ) + let vendored = currentModule.contextDirectory.directory(currentModule.sourceSubpath).exists(vendoredSdkJar) + let built = if (vendored) { + named.withExec(["mvn", "package"] + mavenFlags) + } else { + # The processor writes the entrypoint again, under target/, and the + # committed one is compared with it. + let packaged = named + .withoutDirectory("src/generated/java") + .withExec(["mvn", "package", "-Ddagger.proc=full"] + mavenFlags) + refuseStale( + packaged + .withDirectory("/tmp/committed/java", module.directory("src/generated/java")) + .withExec(["sh", "-c", staleScript]) + .stdout, + "the module's code no longer generates these committed files", + ) + packaged + } # The shade plugin leaves the unshaded artifact beside the shaded one. built .withExec(["sh", "-c", "set -e; jar=$(ls -1 target/*.jar 2>/dev/null | grep -v '/original-' | head -n1); test -n \"$jar\" || { echo \"no packaged jar found in $(pwd)/target\" >&2; exit 1; }; cp \"$jar\" /tmp/module.jar"]) .file("/tmp/module.jar") } + """ + Maven's flags for the package: quiet, so a failed build logs its errors, such + as the compiler's, and little else. + """ + let mavenFlags: [String!]! = ["-DskipTests", "--quiet", "--threads", "1C", "--no-transfer-progress"] + """ Print each file of src/generated/sha256sums whose contents changed or that is gone, or the list itself when it is gone. @@ -54,23 +86,13 @@ type JavaModuleBuild { } """ - Package the module with its entrypoint generated again, and list in - /tmp/stale each committed entrypoint file that differs from the fresh one. - The jar vendored by vendorSdkJar has no annotation processor, so that module - is packaged with its committed entrypoint and compared with nothing. + Print each committed entrypoint file that differs from the one the processor + generated again. """ - let buildScript: String! { + let staleScript: String! { [ - "set -e", - "touch /tmp/stale", - "if [ -f sdk/repo/io/dagger/dagger-java-sdk/0.21.4/dagger-java-sdk-0.21.4.jar ]; then", - " exec mvn package -DskipTests --threads 1C --no-transfer-progress", - "fi", - "mkdir -p /tmp/committed", - "mv src/generated/java /tmp/committed/java", - "mvn package -DskipTests -Ddagger.proc=full --threads 1C --no-transfer-progress", - "diff -r /tmp/committed/java target/generated-sources/annotations >/dev/null || echo src/generated/java >> /tmp/stale", - "cmp -s src/generated/dang/entrypoint/main.dang target/classes/dagger/entrypoint/main.dang || echo src/generated/dang/entrypoint/main.dang >> /tmp/stale", + "diff -r /tmp/committed/java target/generated-sources/annotations >/dev/null || echo src/generated/java", + "cmp -s src/generated/dang/entrypoint/main.dang target/classes/dagger/entrypoint/main.dang || echo src/generated/dang/entrypoint/main.dang", ].join("\n") } diff --git a/sdk/dagger-java-annotation-processor/src/main/java/io/dagger/annotation/processor/DangEntrypointRenderer.java b/sdk/dagger-java-annotation-processor/src/main/java/io/dagger/annotation/processor/DangEntrypointRenderer.java index 2b3ebbd..d7b958a 100644 --- a/sdk/dagger-java-annotation-processor/src/main/java/io/dagger/annotation/processor/DangEntrypointRenderer.java +++ b/sdk/dagger-java-annotation-processor/src/main/java/io/dagger/annotation/processor/DangEntrypointRenderer.java @@ -64,6 +64,12 @@ static String render(ModuleInfo moduleInfo, String moduleName, String clientVers private static final String CALL = String.join( "\n", + " # The jar every call runs: the engine builds it ahead of a call, as the", + " # module's build.", + " pub prebuild(platform: Platform): File! {", + " JavaModuleBuild(platform: platform).jar", + " }", + "", " pub call(", " receiverType: String!,", " receiverValue: JSON,", @@ -98,10 +104,19 @@ static String render(ModuleInfo moduleInfo, String moduleName, String clientVers " (result :: JSON!)", " }", "", - " # The exec error carries the end of the dispatcher's stderr, whose last marker", - " # line holds the function's error. Without one, the exec failed before the", - " # function returned, and its own error is raised again.", + " # An engine that gives the dispatcher a file for the function's error 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, and its own error is raised again.", " 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 = " + Dang.quote(FUNCTION_ERROR_MARKER), " let stderr = ((JSON.decode(err.extensions) :: {{stderr: String}}).stderr ?? \"\")" + " rescue \"\"", diff --git a/sdk/dagger-java-annotation-processor/src/test/java/io/dagger/annotation/processor/DangEntrypointRendererTest.java b/sdk/dagger-java-annotation-processor/src/test/java/io/dagger/annotation/processor/DangEntrypointRendererTest.java index e271f2c..2c9a6c2 100644 --- a/sdk/dagger-java-annotation-processor/src/test/java/io/dagger/annotation/processor/DangEntrypointRendererTest.java +++ b/sdk/dagger-java-annotation-processor/src/test/java/io/dagger/annotation/processor/DangEntrypointRendererTest.java @@ -156,6 +156,34 @@ void aFailedCallRaisesTheTextAfterTheLastErrorMarker() { .contains("lines.takeLast(1)"); } + /** The engine fails the call with the error the dispatcher reported in its error file. */ + @Test + void aFailedCallWhoseErrorTheEngineReadRaisesItAsItIs() { + assertThat(DangEntrypointRenderer.render(module(), "demo", CLIENT_VERSION)) + .contains( + String.join( + "\n", + " let reported = ((JSON.decode(err.extensions) :: {{functionError: {{message:" + + " String, id: String}}}}).functionError != null) rescue false", + " if (reported) {", + " raise err", + " }", + " let marker = ")); + } + + /** The engine builds what prebuild returns before a call, which builds on the same jar. */ + @Test + void prebuildIsTheJarEveryCallRuns() { + assertThat(DangEntrypointRenderer.render(module(), "demo", CLIENT_VERSION)) + .contains( + String.join( + "\n", + " pub prebuild(platform: Platform): File! {", + " JavaModuleBuild(platform: platform).jar", + " }")) + .contains(" let build = JavaModuleBuild()\n"); + } + @Test void descriptionsAreEscapedSoTheOutputStaysParseable() { ObjectInfo object = diff --git a/sdk/dagger-java-sdk/src/main/java/io/dagger/client/ModuleDispatcher.java b/sdk/dagger-java-sdk/src/main/java/io/dagger/client/ModuleDispatcher.java index 694cf2c..1e63895 100644 --- a/sdk/dagger-java-sdk/src/main/java/io/dagger/client/ModuleDispatcher.java +++ b/sdk/dagger-java-sdk/src/main/java/io/dagger/client/ModuleDispatcher.java @@ -1,15 +1,19 @@ package io.dagger.client; import io.dagger.client.engineconn.Connection; +import io.dagger.client.exception.DaggerQueryException; import io.dagger.client.telemetry.Telemetry; import jakarta.json.Json; +import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonException; import jakarta.json.JsonObject; +import jakarta.json.JsonObjectBuilder; import jakarta.json.JsonReader; import jakarta.json.JsonString; import jakarta.json.JsonValue; import jakarta.json.stream.JsonParser; import jakarta.json.stream.JsonParsingException; +import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.StringReader; @@ -17,9 +21,15 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Collections; import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.List; import java.util.Map; +import java.util.Set; import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * Answers one call of a module's Dang entrypoint: the request on standard input, the result in a @@ -32,15 +42,56 @@ */ public final class ModuleDispatcher { - /** Starts the last line of standard error when the function fails; the entrypoint reads it. */ + /** + * Starts the last line of standard error when the function fails, for an engine that names no + * {@link #FUNCTION_ERROR_PATH_ENV file} for its error; the entrypoint reads it. + */ public static final String FUNCTION_ERROR_MARKER = "::dagger-function-error::"; + /** + * Names the file the engine gives a call's process to write its function's error to. The engine + * fails the call with the error the file reports, values and all, and shows it. + */ + public static final String FUNCTION_ERROR_PATH_ENV = "DAGGER_FUNCTION_ERROR_PATH"; + + /** The largest function error file the engine reads. */ + static final int FUNCTION_ERROR_FILE_LIMIT = 1 << 20; + + /** What a report over the limit keeps of each long string, before it drops the values. */ + static final int SHORTENED_LENGTH = 64 * 1024; + /** * The engine hands the entrypoint the last 100 KiB of a failed exec's standard error, and JSON * encodes a character in at most six bytes. */ static final int MAX_REPORTED_ERROR_LENGTH = 16 * 1024; + /** An origin an error's message names: the span of the call the engine reports it from. */ + static final Pattern ERROR_ORIGIN = + Pattern.compile("\\s*\\[traceparent:[0-9a-f]{32}-[0-9a-f]{16}\\]"); + + /** + * The packages of frames a short stack trace leaves out: the JDK's, the SDK's, the generated + * entrypoint's and clients', and those of the libraries the SDK runs on. What remains is the + * module's own code. + */ + static final List FRAMEWORK_PACKAGES = + List.of( + "java.", + "javax.", + "jdk.", + "sun.", + "com.sun.", + "io.dagger.client.", + "io.dagger.gen.", + "io.dagger.module.", + "io.dagger.annotation.", + "jakarta.", + "org.eclipse.parsson.", + "org.eclipse.yasson.", + "io.opentelemetry.", + "org.slf4j."); + /** Where the engine keeps a collection's base in the object's state, outside its schema. */ static final String COLLECTION_BASE_FIELD = "__daggerCollectionBase"; @@ -61,6 +112,20 @@ J call(J parentJson, String parentName, String fnName, Map inputArgs) */ public static > int engineCall( String[] args, Function json, Dispatch dispatch) { + String errorPath = System.getenv(FUNCTION_ERROR_PATH_ENV); + return engineCall( + args, + json, + dispatch, + errorPath == null || errorPath.isEmpty() ? null : Path.of(errorPath)); + } + + /** + * {@link #engineCall(String[], Function, Dispatch)}, reporting a failure in {@code errorFile}, + * or with the marker when it is null. + */ + static > int engineCall( + String[] args, Function json, Dispatch dispatch, Path errorFile) { Connection.markModule(); try (Telemetry telemetry = new Telemetry()) { Path output = outputPath(args); @@ -75,7 +140,8 @@ public static > int engineCall( } return 0; } catch (Throwable e) { - reportFailure(System.err, e); + // The resources are closed by now, so the function's spans are flushed. + reportFailure(System.err, e, errorFile); return 2; } } @@ -132,17 +198,178 @@ private static JsonValue read(Scalar json) { } /** - * Report the function's error last, on one marker line holding its message as a JSON string. The - * function's own output shares standard error, so the marker comes after everything else. + * Report the function's error. With an {@code errorFile}, the engine reads the error there and + * shows it, so only a short stack trace of the module's own frames is printed, and nothing for an + * API error whose origin the engine shows. Without one, or when the file can't be written, the + * error is reported last on standard error, after its full stack trace, on one marker line + * holding its message as a JSON string: the function's own output shares standard error, so the + * marker comes after everything else. */ - static void reportFailure(PrintStream err, Throwable e) { + static void reportFailure(PrintStream err, Throwable e, Path errorFile) { Throwable cause = e instanceof InvocationTargetException ite ? ite.getTargetException() : e; - String message = cause.getMessage() == null ? cause.toString() : cause.getMessage(); + String message = messageOf(cause); + if (errorFile != null && writeFunctionError(errorFile, cause, message)) { + if (!hasOrigin(cause)) { + printShortStackTrace(err, cause); + } + err.flush(); + return; + } cause.printStackTrace(err); err.println(FUNCTION_ERROR_MARKER + Json.createValue(truncate(message))); err.flush(); } + /** + * The error's message, or its type when it has none: the engine takes a report with an empty + * message for plain text. + */ + private static String messageOf(Throwable cause) { + String message = cause.getMessage(); + return message == null || message.isBlank() ? cause.getClass().getName() : message; + } + + /** + * 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. + */ + static boolean hasOrigin(Throwable cause) { + return cause instanceof DaggerQueryException + && cause.getMessage() != null + && ERROR_ORIGIN.matcher(cause.getMessage()).find(); + } + + /** + * Write {@code {"message": ..., "values": {...}}} to {@code path}: the error's message in full, + * with any origin it names, so the engine finds the call that failed, 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. Reports whether it wrote the file. + */ + static boolean writeFunctionError(Path path, Throwable cause, String message) { + JsonObject values = errorValues(cause); + String report = functionErrorReport(message, values); + if (utf8Length(report) > FUNCTION_ERROR_FILE_LIMIT) { + // 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. + String shortened = message; + if (shortened.length() > SHORTENED_LENGTH) { + StringBuilder origins = new StringBuilder(); + Matcher m = ERROR_ORIGIN.matcher(shortened.substring(cut(shortened, SHORTENED_LENGTH))); + while (m.find()) { + origins.append(m.group()); + } + shortened = shortened.substring(0, cut(shortened, SHORTENED_LENGTH)) + "..." + origins; + } + report = functionErrorReport(shortened, (JsonObject) shortenedValue(values)); + if (utf8Length(report) > FUNCTION_ERROR_FILE_LIMIT) { + report = functionErrorReport(shortened, JsonValue.EMPTY_JSON_OBJECT); + } + } + try { + Files.writeString(path, report, StandardCharsets.UTF_8); + return true; + } catch (IOException | RuntimeException e) { + return false; + } + } + + /** The extensions of the GraphQL error the cause is or wraps, or none. */ + private static JsonObject errorValues(Throwable cause) { + Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); + for (Throwable t = cause; t != null && seen.add(t); t = t.getCause()) { + if (t instanceof DaggerQueryException q && q.getError() != null) { + JsonObjectBuilder values = Json.createObjectBuilder(); + q.getError().getExtensions().forEach((name, value) -> values.add(name, jsonValue(value))); + return values.build(); + } + } + return JsonValue.EMPTY_JSON_OBJECT; + } + + /** An extension value as GraphQLError keeps it, back to JSON. */ + private static JsonValue jsonValue(Object value) { + if (value == null) { + return JsonValue.NULL; + } else if (value instanceof JsonValue json) { + return json; + } else if (value instanceof Boolean b) { + return b ? JsonValue.TRUE : JsonValue.FALSE; + } else { + return Json.createValue(value.toString()); + } + } + + private static String functionErrorReport(String message, JsonObject values) { + return Json.createObjectBuilder() + .add("message", message) + .add("values", values) + .build() + .toString(); + } + + /** The value with each string longer than SHORTENED_LENGTH, at any depth, cut to its end. */ + private static JsonValue shortenedValue(JsonValue value) { + switch (value.getValueType()) { + case STRING -> { + String s = ((JsonString) value).getString(); + if (s.length() <= SHORTENED_LENGTH) { + return value; + } + int start = s.length() - SHORTENED_LENGTH; + if (Character.isLowSurrogate(s.charAt(start))) { + start++; + } + return Json.createValue("..." + s.substring(start)); + } + case ARRAY -> { + JsonArrayBuilder shortened = Json.createArrayBuilder(); + value.asJsonArray().forEach(item -> shortened.add(shortenedValue(item))); + return shortened.build(); + } + case OBJECT -> { + JsonObjectBuilder shortened = Json.createObjectBuilder(); + value.asJsonObject().forEach((name, item) -> shortened.add(name, shortenedValue(item))); + return shortened.build(); + } + default -> { + return value; + } + } + } + + /** Where to cut s to keep at most n chars, without splitting a surrogate pair. */ + private static int cut(String s, int n) { + return Character.isHighSurrogate(s.charAt(n - 1)) ? n - 1 : n; + } + + private static int utf8Length(String s) { + return s.getBytes(StandardCharsets.UTF_8).length; + } + + /** + * Print the error's stack trace through the module's own frames only, causes included, as Java + * prints an uncaught exception, without the origins the messages name. + */ + static void printShortStackTrace(PrintStream err, Throwable cause) { + Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); + String prefix = ""; + for (Throwable t = cause; t != null && seen.add(t); t = t.getCause()) { + err.println(prefix + ERROR_ORIGIN.matcher(t.toString()).replaceAll("")); + for (StackTraceElement frame : t.getStackTrace()) { + if (isModuleFrame(frame)) { + err.println("\tat " + frame); + } + } + prefix = "Caused by: "; + } + } + + static boolean isModuleFrame(StackTraceElement frame) { + String className = frame.getClassName(); + return FRAMEWORK_PACKAGES.stream().noneMatch(className::startsWith); + } + static String truncate(String message) { if (message.length() <= MAX_REPORTED_ERROR_LENGTH) { return message; diff --git a/sdk/dagger-java-sdk/src/test/java/io/dagger/client/ModuleDispatcherTest.java b/sdk/dagger-java-sdk/src/test/java/io/dagger/client/ModuleDispatcherTest.java index 9870a68..cda1e80 100644 --- a/sdk/dagger-java-sdk/src/test/java/io/dagger/client/ModuleDispatcherTest.java +++ b/sdk/dagger-java-sdk/src/test/java/io/dagger/client/ModuleDispatcherTest.java @@ -4,8 +4,14 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.dagger.client.engineconn.TestConnections; +import io.dagger.client.exception.DaggerExecException; +import io.dagger.client.exception.DaggerQueryException; +import io.dagger.client.graphql.GraphQLErrors; import io.dagger.client.modules.core.JsonConverter; +import io.dagger.modules.demo.DemoModule; import jakarta.json.Json; +import jakarta.json.JsonObject; +import jakarta.json.JsonValue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; @@ -17,6 +23,7 @@ import java.nio.file.Path; import java.util.List; import java.util.Map; +import java.util.concurrent.Callable; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -198,6 +205,165 @@ void aLongMessageIsCutToFitTheStderrTheEngineKeeps() { .hasSizeLessThan(100 * 1024); } + private static final String ORIGIN = + "[traceparent:0123456789abcdef0123456789abcdef-0123456789abcdef]"; + + private static DaggerExecException execError() { + return new DaggerExecException( + GraphQLErrors.of( + "{\"message\":\"exit code: 1 " + + ORIGIN + + "\",\"path\":[\"container\",\"stdout\"],\"extensions\":{\"_type\":\"EXEC_ERROR\"," + + "\"cmd\":[\"sh\",\"-c\",\"exit 1\"],\"exitCode\":1,\"stdout\":\"out\"," + + "\"stderr\":\"err\",\"nested\":{\"ok\":true,\"none\":null}}}")); + } + + private static Void throwExec() throws DaggerExecException { + throw execError(); + } + + private static JsonObject readReport(Path file) throws Exception { + return Json.createReader(new StringReader(Files.readString(file))).readObject(); + } + + @Test + void aFailureIsReportedInTheErrorFileAndNotMarked(@TempDir Path dir) throws Exception { + Path file = dir.resolve("error.json"); + + String stderr = failWith(new IllegalStateException("leaf failed:\n boom"), "logged", file); + + assertThat(readReport(file)) + .isEqualTo( + Json.createObjectBuilder() + .add("message", "leaf failed:\n boom") + .add("values", JsonValue.EMPTY_JSON_OBJECT) + .build()); + assertThat(stderr).doesNotContain(ModuleDispatcher.FUNCTION_ERROR_MARKER); + assertThat(stderr).startsWith("logged\njava.lang.IllegalStateException: leaf failed:\n boom\n"); + } + + /** The engine shows an API error at its origin, with its logs, so nothing is printed. */ + @Test + void anApiErrorWithAnOriginIsReportedWithTheGraphQLErrorsExtensionsAndNotPrinted( + @TempDir Path dir) throws Exception { + Path file = dir.resolve("error.json"); + + String stderr = failWith(execError(), "logged", file); + + JsonObject report = readReport(file); + assertThat(report.getString("message")).isEqualTo("exit code: 1 " + ORIGIN); + assertThat(report.getJsonObject("values")) + .isEqualTo( + Json.createReader( + new StringReader( + "{\"_type\":\"EXEC_ERROR\",\"cmd\":[\"sh\",\"-c\",\"exit 1\"]," + + "\"exitCode\":1,\"stdout\":\"out\",\"stderr\":\"err\"," + + "\"nested\":{\"ok\":true,\"none\":null}}")) + .readObject()); + assertThat(stderr).isEqualTo("logged\n"); + } + + /** + * What {@code failing} throws, run on a thread of its own, so its stack trace holds no frames of + * the test runner's, as a module's holds none below the SDK's. + */ + private static Exception thrownBy(Callable failing) throws InterruptedException { + Exception[] thrown = new Exception[1]; + Thread thread = + new Thread( + () -> { + try { + failing.call(); + } catch (Exception e) { + thrown[0] = e; + } + }); + thread.start(); + thread.join(); + return thrown[0]; + } + + @Test + void anApiErrorWithoutAnOriginPrintsItself(@TempDir Path dir) throws Exception { + Exception failure = + thrownBy( + () -> { + throw new DaggerQueryException(GraphQLErrors.of("{\"message\":\"bad argument\"}")); + }); + + String stderr = failWith(failure, "", dir.resolve("error.json")); + + assertThat(stderr) + .isEqualTo("\nio.dagger.client.exception.DaggerQueryException: bad argument\n"); + } + + /** The module's own frames remain; the SDK's and the JDK's go. */ + @Test + void anErrorOfTheModulesOwnPrintsAShortStackTrace(@TempDir Path dir) throws Exception { + Exception failure = thrownBy(DemoModule::failNatively); + + String stderr = failWith(failure, "", dir.resolve("error.json")); + + assertThat(stderr) + .matches( + "\njava.lang.Exception: demo failed natively\n" + + "\tat io\\.dagger\\.modules\\.demo\\.DemoModule\\.failNatively" + + "\\(DemoModule\\.java:\\d+\\)\n"); + } + + /** A wrapped API error is the module's own: its chain prints, without the origins. */ + @Test + void aWrappedApiErrorPrintsItsChainWithoutOrigins(@TempDir Path dir) throws Exception { + Exception failure = thrownBy(() -> DemoModule.wrap(thrownBy(ModuleDispatcherTest::throwExec))); + Path file = dir.resolve("error.json"); + + String stderr = failWith(failure, "", file); + + assertThat(stderr) + .matches( + "\njava.lang.Exception: demo ran a failing command: exit code: 1\n" + + "\tat io\\.dagger\\.modules\\.demo\\.DemoModule\\.wrap" + + "\\(DemoModule\\.java:\\d+\\)\n" + + "Caused by: io\\.dagger\\.client\\.exception\\.DaggerExecException: exit code:" + + " 1\n"); + JsonObject report = readReport(file); + assertThat(report.getString("message")) + .isEqualTo("demo ran a failing command: exit code: 1 " + ORIGIN); + assertThat(report.getJsonObject("values").getInt("exitCode")).isEqualTo(1); + } + + /** The engine reads a report with an empty message as plain text, so the type stands in. */ + @Test + void anEmptyMessageIsReportedAsTheErrorsType(@TempDir Path dir) throws Exception { + Path file = dir.resolve("error.json"); + + failWith(new IllegalStateException(" "), "", file); + + assertThat(readReport(file).getString("message")) + .isEqualTo("java.lang.IllegalStateException"); + } + + @Test + void anUnwritableErrorFileFallsBackToTheMarker(@TempDir Path dir) { + String stderr = + failWith(new IllegalStateException("leaf failed"), "", dir.resolve("missing/error.json")); + + assertThat(decodeMarker(lastLine(stderr))).isEqualTo("leaf failed"); + } + + /** Long strings keep their ends, and the message its start and the origins it names. */ + @Test + void aReportOverTheLimitIsShortened(@TempDir Path dir) throws Exception { + Path file = dir.resolve("error.json"); + String message = "é".repeat(ModuleDispatcher.FUNCTION_ERROR_FILE_LIMIT) + " " + ORIGIN; + + failWith(new RuntimeException(message), "", file); + + assertThat(Files.size(file)).isLessThanOrEqualTo(ModuleDispatcher.FUNCTION_ERROR_FILE_LIMIT); + String reported = readReport(file).getString("message"); + assertThat(reported).startsWith("éé").endsWith("..." + " " + ORIGIN); + } + @Test void aCollectionThatReturnsItselfKeepsItsReceiversBase() throws Exception { TestJson receiverJson = @@ -270,6 +436,10 @@ private static String dispatch(String request, ModuleDispatcher.Dispatch