diff --git a/.dagger/modules/e2e/main.dang b/.dagger/modules/e2e/main.dang index 275825d..7fe41f9 100644 --- a/.dagger/modules/e2e/main.dang +++ b/.dagger/modules/e2e/main.dang @@ -2,7 +2,7 @@ End-to-end checks for the Java SDK helper module. Every check here calls the java-sdk module, which needs an engine at its floor, -v1.0.0-beta.18, or later. dagger.toml does not install this module, so +v1.0.0-beta.26, or later. dagger.toml does not install this module, so `dagger check` runs these checks only through `engine-e2e:floor-check`, on an engine built from the floor's commit. AGENTS.md has the commands that run them on the local engine. @@ -64,10 +64,10 @@ type E2e { entrypoint only. """ let entrypointManifest(name: String!): String! { - "name = \"" + name + "\"\n\n[entrypoint]\n kind = \"dang\"\n source = \"./" + dangEntrypointPath + "\"\n" + "name = \"" + name + "\"\n\n[entrypoint]\nkind = \"dang\"\nsource = \"./" + dangEntrypointPath + "\"\n" } - let floorVersion: String! = "v1.0.0-beta.18" + let floorVersion: String! = "v1.0.0-beta.26" """ Checks of a module generated with the Dang entrypoint, through the CLI. @@ -722,11 +722,11 @@ type E2e { """ engineFloorRefusalCheck(ws: Workspace!): Void @check { let refused = [ - "v1.0.0-beta.17", "v1.0.0-beta.17+0da36c8d", "v1.0.0-beta.11", "v1.0.0-beta.9", + "v1.0.0-beta.25", "v1.0.0-beta.25+a45241b2", "v1.0.0-beta.11", "v1.0.0-beta.9", "v1.0.0-alpha.20", "v0.21.9", ] let accepted = [ - "v1.0.0-beta.18", "v1.0.0-beta.18+249edbd6", "v1.0.0-beta.19", "v1.0.0-rc.1", "v1.0.0", + "v1.0.0-beta.26", "v1.0.0-beta.26+9f15293b", "v1.0.0-beta.27", "v1.0.0-rc.1", "v1.0.0", "v1.0.1", "v2.0.0-beta.1", "v0.21.1-20260529020034-dev-b2f595b50044", "v1.0.0-dev.3", "devel", "", ] refused.each { engine => diff --git a/.dagger/modules/engine-e2e/dagger-module.toml b/.dagger/modules/engine-e2e/dagger-module.toml index 7489452..e1ea6e1 100644 --- a/.dagger/modules/engine-e2e/dagger-module.toml +++ b/.dagger/modules/engine-e2e/dagger-module.toml @@ -6,10 +6,10 @@ engineVersion = "v1.0.0-0" [[dependencies]] name = "engine-dev" - source = "github.com/dagger/dagger/.dagger/modules/engine-dev@249edbd646e63c5181053c8af72623ed9bdf030d" - pin = "249edbd646e63c5181053c8af72623ed9bdf030d" + source = "github.com/dagger/dagger/.dagger/modules/engine-dev@9f15293b2d3960d9eeee567d2e50bd60dcf0df80" + pin = "9f15293b2d3960d9eeee567d2e50bd60dcf0df80" [[dependencies]] name = "below-floor-engine-dev" - source = "github.com/dagger/dagger/.dagger/modules/engine-dev@0da36c8da9cb6a682c7d27eca9bd2c125de5ed09" - pin = "0da36c8da9cb6a682c7d27eca9bd2c125de5ed09" + source = "github.com/dagger/dagger/.dagger/modules/engine-dev@a45241b20a5e07fbfc5954479ef0b61da843499c" + pin = "a45241b20a5e07fbfc5954479ef0b61da843499c" diff --git a/.dagger/modules/engine-e2e/main.dang b/.dagger/modules/engine-e2e/main.dang index f47a04c..7ca70f5 100644 --- a/.dagger/modules/engine-e2e/main.dang +++ b/.dagger/modules/engine-e2e/main.dang @@ -5,14 +5,14 @@ engine-dev dependency in dagger-module.toml. """ type EngineE2e { """ - Commit of v1.0.0-beta.18, this SDK's floor. + Commit of v1.0.0-beta.26, this SDK's floor. """ - let floorCommit: String! = "249edbd646e63c5181053c8af72623ed9bdf030d" + let floorCommit: String! = "9f15293b2d3960d9eeee567d2e50bd60dcf0df80" """ - Commit of v1.0.0-beta.17, the last release below the floor. + Commit of v1.0.0-beta.25, the last release below the floor. """ - let belowFloorCommit: String! = "0da36c8da9cb6a682c7d27eca9bd2c125de5ed09" + let belowFloorCommit: String! = "a45241b20a5e07fbfc5954479ef0b61da843499c" let modulePath: String! = ".dagger/modules/sdk-smoke" @@ -95,7 +95,7 @@ type EngineE2e { ) let refusal = initialized.stdout + initialized.stderr assert( - refusal.contains("needs Dagger engine v1.0.0-beta.18 or later"), + refusal.contains("needs Dagger engine v1.0.0-beta.26 or later"), "dagger module init on the engine below the floor did not name the floor:\n" + refusal, ) diff --git a/.dagger/modules/packager/main.dang b/.dagger/modules/packager/main.dang index 846331a..bdca17f 100644 --- a/.dagger/modules/packager/main.dang +++ b/.dagger/modules/packager/main.dang @@ -80,17 +80,23 @@ type Packager { # A module's introspection schema includes its dependencies' types, so the # schema is taken from a dependency-free module: the SDK reactor must compile # against plain core types, the way a freshly generated Java module does. - let introspectionJSON = ws - .moduleSource("/.dagger/modules/templates") - .introspectionSchemaJSON + let templates = ws.moduleSource("/.dagger/modules/templates") + let introspectionJSON = templates.introspectionSchemaJSON + # The same module at the engine's own version, whose schema spells names by + # the current rules (asJson, PER_SESSION): the SDK's tests run against it too. + let latestJSON = templates.withEngineVersion(engineVersion).introspectionSchemaJSON mvn .withoutEntrypoint .withMountedCache("/root/.m2", mavenRepo, sharing: CacheSharingMode.LOCKED) .withMountedFile("/schema.json", introspectionJSON) + .withMountedFile("/schema-latest.json", latestJSON) .withDirectory("/dagger-io", sdkSource(ws)) .withWorkdir("/dagger-io") .withExec(["mvn", "--projects", "dagger-codegen-maven-plugin", "--also-make", "install", "-T1C", "-Dmaven.test.skip=true", "-Dfmt.skip=true", "-Dproject.build.outputTimestamp=2024-01-01T00:00:00Z", "--no-transfer-progress"]) .withExec(["mvn", "-Ptests", "test", "-Ddaggerengine.schema=/schema.json", "-Ddaggerengine.version=" + engineVersion, "-Dfmt.skip=true", "--no-transfer-progress"]) + # clean: the run above generated into the same target/, and codegen + # leaves behind the classes a formatted schema renames (JSON.java, ...). + .withExec(["mvn", "-Ptests", "clean", "test", "--projects", "dagger-java-sdk,dagger-java-annotation-processor", "-Ddaggerengine.schema=/schema-latest.json", "-Ddaggerengine.version=" + engineVersion, "-Dfmt.skip=true", "--no-transfer-progress"]) # Compile the client the gate produces from the *real* schema, pinned to the # version the gate opens at. The engine has since reached it, so the run # above already generates this shape — but pinning keeps the post-gate diff --git a/AGENTS.md b/AGENTS.md index 801ad32..8973d84 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ ## Run the checks locally -The checks need an engine at this SDK's floor, v1.0.0-beta.18, or later. The +The checks need an engine at this SDK's floor, v1.0.0-beta.26, or later. The CLI runs on the engine it ships with; `--engine` or `DAGGER_ENGINE` selects another (`dagger help engine`): @@ -36,12 +36,12 @@ dagger check engine-e2e:dev-sdk-check ``` `floor-check` runs every e2e check on the floor engine, built from its commit. -`below-floor-check` checks that v1.0.0-beta.17 is refused. `dev-sdk-check` +`below-floor-check` checks that v1.0.0-beta.25 is refused. `dev-sdk-check` initializes a Java module through the CLI on the floor engine and calls it. To run e2e checks on the floor's released engine instead: ```sh -dagger check --engine=image://registry.dagger.io/engine:v1.0.0-beta.18 \ +dagger check --engine=image://registry.dagger.io/engine:v1.0.0-beta.26 \ -m .dagger/modules/e2e find-client-root-check ``` diff --git a/README.md b/README.md index cfa82dd..666b8e6 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ generated when the engine loads the module**. The module builds with a plain > until it moves to the entrypoint. > [!IMPORTANT] -> This SDK needs an engine `v1.0.0-beta.18` or later. On an older engine, +> This SDK needs an engine `v1.0.0-beta.26` or later. On an older engine, > `dagger module init` and `dagger generate` stop before they write anything, > with a message that names the floor and the engine's version. > @@ -26,7 +26,7 @@ generated when the engine loads the module**. The module builds with a plain > [`github.com/dagger/sdk-helpers`](https://github.com/dagger/sdk-helpers), the > manifest builder that > [dagger/dagger#13992](https://github.com/dagger/dagger/pull/13992) moved out of -> the engine, pinned at its `v1.0.8` tag. +> the engine, pinned at its `v1.0.12` tag. ## Install @@ -150,7 +150,7 @@ computed again. ### The engine release a module targets -A module on the entrypoint targets `v1.0.0-beta.25`: its bindings use the +A module on the entrypoint targets `v1.0.0-beta.28`: its bindings use the running engine's view of that release, its entrypoint sets `DAGGER_CLIENT_VERSION` on the process that runs a call, and generation writes `src/generated/dang/entrypoint/dang.toml` with `dang = "2.1"` and that release @@ -159,6 +159,11 @@ comments, and refuses settings it would break. Those files are listed in `src/generated/sha256sums`, so after editing one, run `dagger generate`. The `targetVersion` scope setting accepts only that release. +Generated Java names follow Java's conventions as the engine formats them: +`Json`, `Id` and `Llm` for `JSON`, `ID` and `LLM`, `asJson()` for `asJSON`, and +`PER_SESSION` for `PerSession`. A method or enum constant the engine renames +keeps its schema name as a deprecated alias; a renamed class has no alias. + ### Stale generated files A call refuses a module on the entrypoint whose generated files are stale, and @@ -396,11 +401,11 @@ On the engine the CLI runs on, this runs the SDK library's unit tests templates. The `engine-e2e` checks build engines from the dagger/dagger commits pinned in `.dagger/modules/engine-e2e`: -- `engine-e2e:floor-check` builds the floor release, `v1.0.0-beta.18`, and runs +- `engine-e2e:floor-check` builds the floor release, `v1.0.0-beta.26`, and runs every e2e check on it. - `engine-e2e:dev-sdk-check` installs this checkout as the `java` SDK on the same engine, initializes a Java module through the CLI, and calls it. -- `engine-e2e:below-floor-check` builds `v1.0.0-beta.17` and checks that +- `engine-e2e:below-floor-check` builds `v1.0.0-beta.25` and checks that generation and `dagger module init` refuse it. - `engine-e2e:cache-policy-sessions-check`, `pinned-git-client-check` and `standalone-client-check` run calls in sessions of their own on the same diff --git a/dagger-module.toml b/dagger-module.toml index 5c7aeaf..2c9fbf9 100644 --- a/dagger-module.toml +++ b/dagger-module.toml @@ -1,9 +1,9 @@ name = "java-sdk" -engineVersion = "v1.0.0-beta.18" +engineVersion = "v1.0.0-beta.26" [runtime] source = "dang" [[dependencies]] name = "sdk-helpers" - source = "github.com/dagger/sdk-helpers@v1.0.8" + source = "github.com/dagger/sdk-helpers@v1.0.12" diff --git a/dagger.json b/dagger.json index deba4d6..aba3696 100644 --- a/dagger.json +++ b/dagger.json @@ -1,13 +1,13 @@ { "name": "java-sdk", - "engineVersion": "v1.0.0-beta.18", + "engineVersion": "v1.0.0-beta.26", "sdk": { "source": "dang" }, "dependencies": [ { "name": "sdk-helpers", - "source": "github.com/dagger/sdk-helpers@v1.0.8" + "source": "github.com/dagger/sdk-helpers@v1.0.12" } ] } diff --git a/dagger.lock b/dagger.lock index 201aec2..d446eb7 100644 --- a/dagger.lock +++ b/dagger.lock @@ -4,13 +4,13 @@ [["version","2"]] ["","git-latest",["github.com/dagger/alpine"],"refs/heads/main"] ["","git-latest",["github.com/dagger/dang-sdk"],"refs/heads/main"] -["","git-latest",["github.com/dagger/sdk-helpers",["version","v1.0.8"]],"refs/tags/v1.0.8"] +["","git-latest",["github.com/dagger/sdk-helpers",["version","v1.0.12"]],"refs/tags/v1.0.12"] ["","git-sha",["github.com/containernetworking/plugins","refs/tags/v1.9.0"],"9b3772e1a7abf93cbb7c6526a28bc0d27b830e02"] ["","git-sha",["github.com/dagger/alpine","main"],"ff6a5f4c28364912d92c00e682dd0bf19f524ef9"] ["","git-sha",["github.com/dagger/alpine","refs/heads/main"],"ff6a5f4c28364912d92c00e682dd0bf19f524ef9"] ["","git-sha",["github.com/dagger/dagger","refs/tags/v1.0.0-beta.11"],"a4e1e4ff663e5e51c2b96c2c0772f3d2f00cfb94"] ["","git-sha",["github.com/dagger/dang-sdk","refs/heads/main"],"9c8e5c6f1927b9adc325846d47e66e697991797d"] -["","git-sha",["github.com/dagger/sdk-helpers","refs/tags/v1.0.8"],"31dafd0c74d9a08faa00c09dce87a5af072e7a9d"] +["","git-sha",["github.com/dagger/sdk-helpers","refs/tags/v1.0.12"],"69e2b90a3dce437cb07f5ee19ad901bf83fff097"] ["","git-sha",["github.com/libfuse/sshfs","refs/tags/sshfs-3.7.6"],"7a2d988775446ebe7af9b01c99b3b8e86bddb05a"] ["","git-sha",["github.com/opencontainers/runc","refs/tags/v1.4.2"],"c241c0bb5e60a8e8c1b2e53d4eca8d0068d8d57e"] ["","oci-latest",["docker.io/library/busybox"],"1.38.0"] diff --git a/docs/collections.md b/docs/collections.md index 1140c58..81200a0 100644 --- a/docs/collections.md +++ b/docs/collections.md @@ -1,7 +1,7 @@ # Collections A collection is an object that holds a set of items a module discovers at run -time, each with a unique key. This SDK needs an engine v1.0.0-beta.18 or later. +time, each with a unique key. This SDK needs an engine v1.0.0-beta.26 or later. The engine serves collections from v1.0.0-beta.15 ([dagger/dagger#14221](https://github.com/dagger/dagger/pull/14221)). v1.0.0-beta.17 adds the projected types that every call into a collection diff --git a/main.dang b/main.dang index 75c662e..f556678 100644 --- a/main.dang +++ b/main.dang @@ -376,12 +376,9 @@ type JavaSdk { """ The engine release a module on the entrypoint is staged at, so its bindings - are generated from the API view the engine serves the module: an entrypoint - module carries no engine version, and the engine serves it a release before - the identifier-casing cut. Pre-cut until the Java codegen is ported to the - new naming rules. + are generated from the API view its entrypoint imports. """ - let entrypointTarget: String! = "v1.0.0-beta.25" + let entrypointTarget: String! = "v1.0.0-beta.28" """ The engine release a module on the entrypoint targets, refusing a @@ -398,7 +395,7 @@ type JavaSdk { """ The first engine release this SDK runs on. """ - let engineFloor: String! = "v1.0.0-beta.18" + let engineFloor: String! = "v1.0.0-beta.26" """ Why this SDK refuses an engine of the given version, or the empty string when diff --git a/main.dang.tmpl b/main.dang.tmpl index 5e566ee..dc88e4a 100644 --- a/main.dang.tmpl +++ b/main.dang.tmpl @@ -376,12 +376,9 @@ type JavaSdk { """ The engine release a module on the entrypoint is staged at, so its bindings - are generated from the API view the engine serves the module: an entrypoint - module carries no engine version, and the engine serves it a release before - the identifier-casing cut. Pre-cut until the Java codegen is ported to the - new naming rules. + are generated from the API view its entrypoint imports. """ - let entrypointTarget: String! = "v1.0.0-beta.25" + let entrypointTarget: String! = "v1.0.0-beta.28" """ The engine release a module on the entrypoint targets, refusing a @@ -398,7 +395,7 @@ type JavaSdk { """ The first engine release this SDK runs on. """ - let engineFloor: String! = "v1.0.0-beta.18" + let engineFloor: String! = "v1.0.0-beta.26" """ Why this SDK refuses an engine of the given version, or the empty string when diff --git a/mod.dang b/mod.dang index f23a44c..2f41ac8 100644 --- a/mod.dang +++ b/mod.dang @@ -143,7 +143,7 @@ type Mod { clients.reduce(directory.withFile("core/schema.json", introspectionJSON)) { plan, client => let entry = "target-" + client.moduleName plan - .withFile(entry + "/schema.json", client.withEngineVersion(view).clientSchemaIntrospectionJSON) + .withFile(entry + "/schema.json", client.withEngineVersion(view).clientSchemaIntrospectionJson) .withNewFile(entry + "/module", client.moduleName + "\n") .withNewFile(entry + "/descriptor", clientDescriptor(client)) } @@ -421,7 +421,7 @@ type Mod { .withNewFile("dagger-module.toml", "name = \"core-schema\"\n") .asModuleSource .withEngineVersion(engineVersion) - .clientSchemaIntrospectionJSON + .clientSchemaIntrospectionJson } """ @@ -604,7 +604,7 @@ type Mod { } let modSource = ws.moduleSource(workspaceRef(rootPath)) let name = modSource.moduleName - let introspectionJSON = modSource.introspectionSchemaJSON + let introspectionJSON = modSource.introspectionSchemaJson let vendored = vendoredSdk(introspectionJSON, name) let pom = withClientsProfile(committed.file("pom.xml").contents) let stale = staleClientDirs(committed) diff --git a/prebuilt/m2/io/dagger/dagger-codegen-maven-plugin/0.21.4/dagger-codegen-maven-plugin-0.21.4.jar b/prebuilt/m2/io/dagger/dagger-codegen-maven-plugin/0.21.4/dagger-codegen-maven-plugin-0.21.4.jar index 3f59fbb..af4df30 100644 Binary files a/prebuilt/m2/io/dagger/dagger-codegen-maven-plugin/0.21.4/dagger-codegen-maven-plugin-0.21.4.jar and b/prebuilt/m2/io/dagger/dagger-codegen-maven-plugin/0.21.4/dagger-codegen-maven-plugin-0.21.4.jar differ diff --git a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/DaggerCLIUtils.java b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/DaggerCLIUtils.java index 6404f11..4ab04b8 100644 --- a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/DaggerCLIUtils.java +++ b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/DaggerCLIUtils.java @@ -44,6 +44,15 @@ public static String getBinary(String defaultCLIPath) { public static InputStream query(InputStream query, String binPath) throws IOException, InterruptedException { + return query(query, binPath, null); + } + + /** + * Runs a GraphQL query with {@code dagger query}, with its variables as JSON (or null), and + * returns the response data as JSON. + */ + public static InputStream query(InputStream query, String binPath, String variables) + throws IOException, InterruptedException { if (query == null) { throw new IOException("missing introspection query resource"); } @@ -60,7 +69,7 @@ public static InputStream query(InputStream query, String binPath) envVars.remove("OTEL_EXPORTER_OTLP_ENDPOINT"); envVars.remove("OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"); - ProcessBuilder builder = new ProcessBuilder(binPath, "query", "-s", "-M"); + ProcessBuilder builder = new ProcessBuilder(queryCommand(binPath, variables)); builder.environment().clear(); builder.environment().putAll(envVars); @@ -109,6 +118,16 @@ public static InputStream query(InputStream query, String binPath) return new ByteArrayInputStream(out.toByteArray()); } + /** The {@code dagger query} command line, passing variables (when not null) as JSON. */ + static List queryCommand(String binPath, String variables) { + List command = new ArrayList<>(List.of(binPath, "query", "-s", "-M")); + if (variables != null) { + command.add("--var-json"); + command.add(variables); + } + return command; + } + public static InputStream introspectionQuery(Class anchorClass) throws IOException { String resource = "introspection/introspection.graphql"; InputStream stream = getResource(anchorClass.getClassLoader(), resource); diff --git a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/DaggerCodegenMojo.java b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/DaggerCodegenMojo.java index 85b711d..4e3c516 100644 --- a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/DaggerCodegenMojo.java +++ b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/DaggerCodegenMojo.java @@ -1,12 +1,15 @@ package io.dagger.codegen; import io.dagger.codegen.introspection.CodegenVisitor; +import io.dagger.codegen.introspection.FormattedNames; import io.dagger.codegen.introspection.Schema; import io.dagger.codegen.introspection.SchemaVisitor; import io.dagger.codegen.introspection.Type; import io.dagger.codegen.introspection.TypeRegistry; import java.io.*; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Map; @@ -43,6 +46,13 @@ public class DaggerCodegenMojo extends AbstractMojo { @Parameter(property = "dagger.introspectionJson") protected String introspectionJson; + /** + * The names file written with the introspection JSON (see {@link FormattedNames#read}). Only read + * with {@code introspectionJson}: without it, codegen asks the engine for the names. + */ + @Parameter(property = "dagger.namesJson") + protected String namesJson; + /** * A {@link GenerationPlan} directory. When set, every package the plan names is generated in this * one invocation and {@code introspectionJson} is ignored. @@ -70,7 +80,11 @@ public void execute() throws MojoExecutionException, MojoFailureException { Path dest = outputDir.toPath(); if (plan != null && !plan.isEmpty()) { try { - new Generator(dest, Charset.forName(outputEncoding), version) + new Generator( + dest, + Charset.forName(outputEncoding), + version, + EngineQueries.fromEnvironment(System.getenv(), bin)) .generate(GenerationPlan.read(Path.of(plan))); } catch (IOException | IllegalArgumentException e) { throw new MojoFailureException(e.getMessage(), e); @@ -80,13 +94,14 @@ public void execute() throws MojoExecutionException, MojoFailureException { } return; } - try (InputStream in = getInstrospectionJson()) { - Schema schema = Schema.initialize(in, version); + try { + Schema schema = loadSchema(); SchemaVisitor codegen = new CodegenVisitor( schema, TypeRegistry.acrossPackages( - Generator.CORE_PACKAGE, Generator.RUNTIME_PACKAGE, Map.of()), + Generator.CORE_PACKAGE, Generator.RUNTIME_PACKAGE, Map.of()) + .withJavaTypeNames(schema.javaTypeNames()), dest, Charset.forName(outputEncoding)); schema.visit( @@ -134,7 +149,7 @@ public void visitIDAbles(List types) { } }); } catch (IOException | InterruptedException e) { - throw new MojoFailureException(e); + throw new MojoFailureException(e.getMessage(), e); } if (project != null) { @@ -143,25 +158,54 @@ public void visitIDAbles(List types) { } } - private InputStream getInstrospectionJson() - throws IOException, MojoFailureException, InterruptedException { + /** + * Loads the schema, with the Java names the engine formatted for it: from the names file of an + * introspection JSON file when there is one, else from the engine. A schema read through the CLI + * gets its names through the CLI too. + */ + private Schema loadSchema() throws IOException, MojoFailureException, InterruptedException { if (this.introspectionJson != null && !this.introspectionJson.isEmpty()) { File f = new File(this.introspectionJson); if (f.exists()) { - return new FileInputStream(f); + byte[] schemaJson = Files.readAllBytes(f.toPath()); + Schema schema = Schema.initialize(new ByteArrayInputStream(schemaJson), version); + schema.setFormattedNames(namesFor(schemaJson)); + return schema; } } this.bin = DaggerCLIUtils.getBinary(this.bin); - return daggerSchema(); - } - - private InputStream daggerSchema() - throws IOException, InterruptedException, MojoFailureException { String actualVersion = DaggerCLIUtils.getVersion(this.bin); getLog() .info(String.format("Querying local dagger CLI for schema (version=%s)", actualVersion)); this.version = actualVersion; - return DaggerCLIUtils.query(DaggerCLIUtils.introspectionQuery(getClass()), this.bin); + byte[] schemaJson = + DaggerCLIUtils.query(DaggerCLIUtils.introspectionQuery(getClass()), this.bin) + .readAllBytes(); + Schema schema = Schema.initialize(new ByteArrayInputStream(schemaJson), this.version); + schema.setFormattedNames( + FormattedNames.fetch( + schemaJson, + (query, variables) -> + DaggerCLIUtils.query( + new ByteArrayInputStream(query.getBytes(StandardCharsets.UTF_8)), + this.bin, + variables))); + return schema; + } + + /** The formatted names of an introspection JSON file's schema: its names file, or the engine. */ + private Map> namesFor(byte[] schemaJson) + throws IOException, InterruptedException { + if (this.namesJson != null && !this.namesJson.isEmpty()) { + File names = new File(this.namesJson); + if (names.exists()) { + try (InputStream in = new FileInputStream(names)) { + return FormattedNames.read(in); + } + } + } + getLog().info("Formatting the schema's names with the engine (Query.naming)"); + return FormattedNames.fetch(schemaJson, EngineQueries.fromEnvironment(System.getenv(), bin)); } public File getOutputDirectory() { diff --git a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/EngineQueries.java b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/EngineQueries.java new file mode 100644 index 0000000..44c07c0 --- /dev/null +++ b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/EngineQueries.java @@ -0,0 +1,142 @@ +package io.dagger.codegen; + +import io.dagger.codegen.introspection.FormattedNames; +import jakarta.json.Json; +import jakarta.json.JsonObject; +import jakarta.json.JsonReader; +import jakarta.json.JsonValue; +import jakarta.json.JsonValue.ValueType; +import jakarta.json.stream.JsonParsingException; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; +import java.net.ConnectException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Base64; +import java.util.Map; + +/** + * Where codegen asks the engine to format names (see {@link FormattedNames}). + * + *

Codegen usually runs in a Maven exec the SDK module started, with the schema handed to it as a + * file. Such an exec joins the engine's session as a nested client ({@code DAGGER_SESSION_PORT} and + * {@code DAGGER_SESSION_TOKEN}), and a request without client metadata is served at the engine's + * own API view, which has {@code Query.naming} from v1.0.0-beta.26: codegen asks there, passing the + * generated schema's version, so the names follow that schema's dictionary. Outside a session, it + * asks through the {@code dagger} CLI. + */ +public final class EngineQueries { + + static final String SESSION_PORT = "DAGGER_SESSION_PORT"; + static final String SESSION_TOKEN = "DAGGER_SESSION_TOKEN"; + + private EngineQueries() {} + + /** + * The runner for this environment: the nested session when there is one, else the dagger CLI + * (resolved like the schema query: {@code dagger.bin}, {@code _EXPERIMENTAL_DAGGER_CLI_BIN}, else + * {@code dagger}). + */ + public static FormattedNames.QueryRunner fromEnvironment(Map env, String bin) { + FormattedNames.QueryRunner session = session(env); + if (session != null) { + return session; + } + String cli = DaggerCLIUtils.getBinary(bin); + return (query, variables) -> + DaggerCLIUtils.query( + new ByteArrayInputStream(query.getBytes(StandardCharsets.UTF_8)), cli, variables); + } + + /** The nested session's runner, or null without a session in the environment. */ + static FormattedNames.QueryRunner session(Map env) { + String port = env.get(SESSION_PORT); + String token = env.get(SESSION_TOKEN); + if (port == null || port.isBlank() || token == null) { + return null; + } + return session(URI.create("http://127.0.0.1:" + port.trim() + "/query"), token); + } + + /** + * A runner posting to a session's GraphQL endpoint, authenticated with its token. It sends no + * client metadata, so the engine serves it at its own version. + */ + static FormattedNames.QueryRunner session(URI endpoint, String token) { + HttpClient client = + HttpClient.newBuilder() + .version(HttpClient.Version.HTTP_1_1) + .connectTimeout(Duration.ofSeconds(30)) + .build(); + String auth = + "Basic " + + Base64.getEncoder().encodeToString((token + ":").getBytes(StandardCharsets.UTF_8)); + return (query, variables) -> { + String body = + Json.createObjectBuilder() + .add("query", query) + .add("variables", readObject(variables, "the query variables")) + .build() + .toString(); + HttpRequest request = + HttpRequest.newBuilder(endpoint) + .timeout(Duration.ofSeconds(60)) + .header("Content-Type", "application/json") + .header("Authorization", auth) + .POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8)) + .build(); + HttpResponse response; + try { + response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); + } catch (ConnectException e) { + throw new IOException("the Dagger session at " + endpoint + " is unreachable", e); + } + return data(endpoint, response.statusCode(), response.body()); + }; + } + + /** The data of a GraphQL response, or the failure its errors or status report. */ + static InputStream data(URI endpoint, int status, String body) throws IOException { + JsonObject response; + try { + response = readObject(body, "the response"); + } catch (IOException e) { + throw new IOException( + "the Dagger session at " + endpoint + " answered HTTP " + status + ": " + body, e); + } + JsonValue errors = response.get("errors"); + if (errors != null + && errors.getValueType() == ValueType.ARRAY + && !errors.asJsonArray().isEmpty()) { + StringBuilder messages = new StringBuilder(); + for (JsonValue error : errors.asJsonArray()) { + String message = + error.getValueType() == ValueType.OBJECT + ? error.asJsonObject().getString("message", error.toString()) + : error.toString(); + messages.append(messages.length() == 0 ? "" : "; ").append(message); + } + throw new IOException(messages.toString()); + } + JsonValue data = response.get("data"); + if (status / 100 != 2 || data == null || data.getValueType() != ValueType.OBJECT) { + throw new IOException( + "the Dagger session at " + endpoint + " answered HTTP " + status + ": " + body); + } + return new ByteArrayInputStream(data.toString().getBytes(StandardCharsets.UTF_8)); + } + + private static JsonObject readObject(String json, String what) throws IOException { + try (JsonReader reader = Json.createReader(new StringReader(json))) { + return reader.readObject(); + } catch (JsonParsingException | IllegalStateException e) { + throw new IOException(what + " is not a JSON object", e); + } + } +} diff --git a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/GenerationPlan.java b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/GenerationPlan.java index 2059c69..4a5eb88 100644 --- a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/GenerationPlan.java +++ b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/GenerationPlan.java @@ -22,6 +22,10 @@ * <plan>/target-*/descriptor where that target lives, as {@link TargetDescriptor#read} * * + *

Beside any schema, an optional {@code names.json} holds the Java names the engine formatted + * for it (see {@code FormattedNames}); without one, a schema that needs them gets them from the + * engine. + * *

The directory names carry no meaning beyond ordering the targets; a module name can hold * characters a path cannot, so it travels in a file. Targets are read in module-name order, so a * plan generates the same bytes however its caller happened to lay it out. diff --git a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/Generator.java b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/Generator.java index 2d92eda..47d2d8e 100644 --- a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/Generator.java +++ b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/Generator.java @@ -3,6 +3,7 @@ import io.dagger.codegen.introspection.ClientEntryPoint; import io.dagger.codegen.introspection.CodegenVisitor; import io.dagger.codegen.introspection.Field; +import io.dagger.codegen.introspection.FormattedNames; import io.dagger.codegen.introspection.Schema; import io.dagger.codegen.introspection.SchemaPartition; import io.dagger.codegen.introspection.TargetDescriptor; @@ -10,11 +11,13 @@ import io.dagger.codegen.introspection.TypeKind; import io.dagger.codegen.introspection.TypeRef; import io.dagger.codegen.introspection.TypeRegistry; +import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -30,11 +33,33 @@ public final class Generator { private final Path outputDirectory; private final Charset encoding; private final String engineVersion; + private final FormattedNames.QueryRunner engine; + /** + * A generator asking the engine of this environment to format names, when a schema needs them + * (see {@link EngineQueries#fromEnvironment}). + */ public Generator(Path outputDirectory, Charset encoding, String engineVersion) { + this( + outputDirectory, + encoding, + engineVersion, + EngineQueries.fromEnvironment(System.getenv(), null)); + } + + /** + * @param engine where a schema gets its names formatted, unless its plan entry carries a names + * file + */ + public Generator( + Path outputDirectory, + Charset encoding, + String engineVersion, + FormattedNames.QueryRunner engine) { this.outputDirectory = outputDirectory; this.encoding = encoding; this.engineVersion = engineVersion; + this.engine = engine; } public void generate(GenerationPlan plan) throws IOException { @@ -47,9 +72,11 @@ public void generate(GenerationPlan plan) throws IOException { Map packageByTypeName = new LinkedHashMap<>(); Map targetByTypeName = new LinkedHashMap<>(); Map clients = new LinkedHashMap<>(); + Map javaTypeNames = new HashMap<>(); for (GenerationPlan.Target target : plan.targets()) { - SchemaPartition client = - SchemaPartition.client(typeChecksAsCheck(read(target.schema())), target.module()); + Schema schema = read(target.schema()); + javaTypeNames.putAll(schema.javaTypeNames()); + SchemaPartition client = SchemaPartition.client(typeChecksAsCheck(schema), target.module()); clients.put(target.module(), client); for (String owned : client.typeNames()) { requireUnclaimed(targetByTypeName, owned, target.module()); @@ -58,11 +85,13 @@ public void generate(GenerationPlan plan) throws IOException { } Schema coreSchema = read(plan.coreSchema()); + javaTypeNames.putAll(coreSchema.javaTypeNames()); requireEveryOwnedModulePlanned(coreSchema, packages.keySet()); requireNoTargetShadowsCore(coreSchema, targetByTypeName); TypeRegistry registry = - TypeRegistry.acrossPackages(CORE_PACKAGE, RUNTIME_PACKAGE, packageByTypeName); + TypeRegistry.acrossPackages(CORE_PACKAGE, RUNTIME_PACKAGE, packageByTypeName) + .withJavaTypeNames(javaTypeNames); emit(SchemaPartition.core(coreSchema), registry, null, null); for (GenerationPlan.Target target : plan.targets()) { SchemaPartition client = clients.get(target.module()); @@ -166,9 +195,32 @@ private void emit( partition.schema(), registry, entryPoint, descriptor, outputDirectory, encoding)); } + /** + * A plan's schema, with the Java names the engine formatted for it: from the {@code names.json} + * beside it, else from the engine. + */ private Schema read(Path schemaFile) throws IOException { - try (InputStream in = Files.newInputStream(schemaFile)) { - return Schema.initialize(in, engineVersion); + byte[] schemaJson = Files.readAllBytes(schemaFile); + Schema schema = Schema.initialize(new ByteArrayInputStream(schemaJson), engineVersion); + schema.setFormattedNames(formattedNames(schemaJson, schemaFile.resolveSibling(NAMES_FILE))); + return schema; + } + + /** The names file a plan entry may carry beside its schema, as {@link FormattedNames#read}. */ + static final String NAMES_FILE = "names.json"; + + private Map> formattedNames(byte[] schemaJson, Path namesFile) + throws IOException { + if (Files.isRegularFile(namesFile)) { + try (InputStream in = Files.newInputStream(namesFile)) { + return FormattedNames.read(in); + } + } + try { + return FormattedNames.fetch(schemaJson, engine); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("interrupted while formatting names", e); } } } diff --git a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/EnumValue.java b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/EnumValue.java index 038cbcb..d8dc48d 100644 --- a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/EnumValue.java +++ b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/EnumValue.java @@ -1,6 +1,7 @@ package io.dagger.codegen.introspection; import jakarta.json.bind.annotation.JsonbProperty; +import jakarta.json.bind.annotation.JsonbTransient; public class EnumValue { @@ -12,6 +13,17 @@ public class EnumValue { private String DeprecationReason; + /** The Java constant name the engine formatted for this value, or null. */ + @JsonbTransient private String formattedName; + + public String getFormattedName() { + return formattedName; + } + + public void setFormattedName(String formattedName) { + this.formattedName = formattedName; + } + public String getName() { return name; } diff --git a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/EnumVisitor.java b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/EnumVisitor.java index 3330927..02b808a 100644 --- a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/EnumVisitor.java +++ b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/EnumVisitor.java @@ -1,8 +1,17 @@ package io.dagger.codegen.introspection; import com.palantir.javapoet.*; +import jakarta.json.bind.annotation.JsonbTypeDeserializer; +import jakarta.json.bind.annotation.JsonbTypeSerializer; import java.nio.charset.Charset; import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import javax.lang.model.SourceVersion; import javax.lang.model.element.Modifier; public class EnumVisitor extends AbstractVisitor { @@ -14,19 +23,133 @@ public EnumVisitor(Schema schema, TypeRegistry registry, Path targetDirectory, C @Override TypeSpec generateType(Type type) { TypeSpec.Builder classBuilder = - TypeSpec.enumBuilder(Helpers.formatName(type)) + TypeSpec.enumBuilder(registry().javaTypeName(type.getName())) .addJavadoc(type.getDescription() != null ? type.getDescription() : "") .addModifiers(Modifier.PUBLIC); + Helpers.addGraphQLType(classBuilder, registry(), type.getName()); + Map> constants = constants(type); + boolean namedLikeValues = + constants.entrySet().stream() + .allMatch( + e -> e.getValue().size() == 1 && e.getKey().equals(e.getValue().get(0).getName())); + if (namedLikeValues) { + // Constants go over the wire by name. + for (EnumValue enumValue : type.getEnumValues()) { + TypeSpec.Builder enumTypeBuilder = + TypeSpec.anonymousClassBuilder("").addJavadoc(enumValue.getDescription()); + if (enumValue.isDeprecated()) { + enumTypeBuilder.addAnnotation(Deprecated.class); + } + classBuilder.addEnumConstant(enumValue.getName(), enumTypeBuilder.build()); + } + return classBuilder.build(); + } + + return valueEnum(classBuilder, type, constants); + } + + /** + * The enum's constants, by name, with the schema values each stands for, in schema order: a + * value's constant is the name the engine formatted for it ({@code PER_SESSION} for {@code + * PerSession}), else its schema name. Values whose names format alike ({@code Gzip} and {@code + * GZIP}) share a constant, sent as the first one's value. + */ + private Map> constants(Type type) { + Map> constants = new LinkedHashMap<>(); for (EnumValue enumValue : type.getEnumValues()) { + String name = enumValue.getName(); + if (getSchema().formatsEnumValues() + && enumValue.getFormattedName() != null + && SourceVersion.isName(enumValue.getFormattedName())) { + name = enumValue.getFormattedName(); + } + constants.computeIfAbsent(name, k -> new ArrayList<>()).add(enumValue); + } + return constants; + } + + /** + * An enum whose constants are named apart from their schema values: each carries its values, and + * the class implements GraphQLEnum, (de)serializing through them. The schema values that used to + * be constants stay as deprecated aliases. + */ + private TypeSpec valueEnum( + TypeSpec.Builder classBuilder, Type type, Map> constants) { + ClassName enumClass = registry().forType(type.getName()); + classBuilder + .addSuperinterface(registry().runtime("GraphQLEnum")) + .addAnnotation( + AnnotationSpec.builder(JsonbTypeSerializer.class) + .addMember("value", "$T.class", registry().runtime("GraphQLEnumSerializer")) + .build()) + .addAnnotation( + AnnotationSpec.builder(JsonbTypeDeserializer.class) + .addMember("value", "$T.class", registry().runtime("GraphQLEnumDeserializer")) + .build()); + + for (Map.Entry> constant : constants.entrySet()) { + List values = constant.getValue(); + EnumValue primary = values.get(0); + CodeBlock args = + CodeBlock.join(values.stream().map(v -> CodeBlock.of("$S", v.getName())).toList(), ", "); TypeSpec.Builder enumTypeBuilder = - TypeSpec.anonymousClassBuilder("").addJavadoc(enumValue.getDescription()); - if (enumValue.isDeprecated()) { + TypeSpec.anonymousClassBuilder(args) + .addJavadoc(Helpers.escapeJavadoc(primary.getDescription())); + if (values.stream().allMatch(EnumValue::isDeprecated)) { enumTypeBuilder.addAnnotation(Deprecated.class); } - classBuilder.addEnumConstant(enumValue.getName(), enumTypeBuilder.build()); + classBuilder.addEnumConstant(constant.getKey(), enumTypeBuilder.build()); + } + + // The old constants, named like the schema values, as deprecated aliases. + Set taken = new HashSet<>(constants.keySet()); + for (Map.Entry> constant : constants.entrySet()) { + for (EnumValue value : constant.getValue()) { + String legacyName = value.getName(); + if (!SourceVersion.isName(legacyName) || !taken.add(legacyName)) { + continue; + } + classBuilder.addField( + FieldSpec.builder( + enumClass, legacyName, Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL) + .addAnnotation(Deprecated.class) + .addJavadoc("@deprecated Use {@link #$L} instead.\n", constant.getKey()) + .initializer("$L", constant.getKey()) + .build()); + } } + classBuilder.addField( + FieldSpec.builder(String[].class, "values", Modifier.PRIVATE, Modifier.FINAL).build()); + classBuilder.addMethod( + MethodSpec.constructorBuilder() + .addParameter(String[].class, "values") + .varargs() + .addStatement("this.values = values") + .build()); + classBuilder.addMethod( + MethodSpec.methodBuilder("graphQLValue") + .addAnnotation(Override.class) + .addModifiers(Modifier.PUBLIC) + .returns(String.class) + .addJavadoc("The schema value this constant is sent as.\n") + .addStatement("return values[0]") + .build()); + classBuilder.addMethod( + MethodSpec.methodBuilder("hasGraphQLValue") + .addAnnotation(Override.class) + .addModifiers(Modifier.PUBLIC) + .returns(boolean.class) + .addParameter(String.class, "value") + .addJavadoc("Whether the API may return this constant as the given value.\n") + .beginControlFlow("for (String v : values)") + .beginControlFlow("if (v.equals(value))") + .addStatement("return true") + .endControlFlow() + .endControlFlow() + .addStatement("return false") + .build()); return classBuilder.build(); } } diff --git a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/Field.java b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/Field.java index 4bb27bc..7934554 100644 --- a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/Field.java +++ b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/Field.java @@ -25,6 +25,17 @@ public class Field { private Type parentObject; + /** The Java name the engine formatted for this field's name, or null. */ + @JsonbTransient private String formattedName; + + public String getFormattedName() { + return formattedName; + } + + public void setFormattedName(String formattedName) { + this.formattedName = formattedName; + } + public String getName() { return name; } diff --git a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/FormattedNames.java b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/FormattedNames.java new file mode 100644 index 0000000..70b7edc --- /dev/null +++ b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/FormattedNames.java @@ -0,0 +1,268 @@ +package io.dagger.codegen.introspection; + +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonObject; +import jakarta.json.JsonReader; +import jakarta.json.JsonString; +import jakarta.json.JsonValue; +import jakarta.json.JsonValue.ValueType; +import jakarta.json.stream.JsonParsingException; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeSet; +import java.util.regex.Pattern; + +/** + * Schema names formatted by the engine, for Java identifiers in Java's own conventions: members, + * parameters, setters and accessors in camelCase with acronyms written like words ({@code asJson}, + * {@code withGpu}), classes in PascalCase with acronyms written like words ({@code JsonValue}, + * {@code Llm}), and enum constants in SCREAMING_SNAKE_CASE ({@code PER_SESSION}). + * + *

Codegen doesn't parse names itself: the naming rules live in the engine, which formats them + * with {@code Query.naming(version:).formatIdentifiers}. The version is the schema's own {@code + * __schemaVersion}, so the names follow the dictionary of the schema being generated whatever the + * view of the session that formats them. + * + *

A failure fails codegen rather than falling back to the schema's names, which would generate a + * different API. + */ +public final class FormattedNames { + + /** The key of the member names (methods, parameters, accessors) in a names file. */ + public static final String MEMBERS = "CAMEL:CAPITALIZED"; + + /** The key of the class names in a names file. */ + public static final String TYPES = "PASCAL:CAPITALIZED"; + + /** The key of the enum constant names in a names file. */ + public static final String ENUM_VALUES = "SCREAMING_SNAKE:UPPERCASE"; + + /** The formats Java codegen uses, keyed like a names file: {@code CASING:ACRONYMS}. */ + public static final List FORMATS = List.of(MEMBERS, TYPES, ENUM_VALUES); + + /** + * Bounds the size of the names sent per request. The names may go to {@code dagger query} as a + * command-line argument, which Linux caps at 128 KiB; the core schema's names fit in one. + */ + static final int BATCH_BYTES = 64 << 10; + + /** Formats a batch of names in every format of {@link #FORMATS}, one alias per format. */ + public static final String QUERY = query(); + + private static final Pattern HAS_ALNUM = Pattern.compile("[A-Za-z0-9]"); + + private FormattedNames() {} + + private static String query() { + StringBuilder query = + new StringBuilder( + "query FormatIdentifiers($names: [String!]!, $version: String) {" + + " naming(version: $version) {"); + for (int i = 0; i < FORMATS.size(); i++) { + String[] format = FORMATS.get(i).split(":"); + query + .append(" f") + .append(i) + .append(": formatIdentifiers(names: $names, casing: ") + .append(format[0]) + .append(", acronyms: ") + .append(format[1]) + .append(")"); + } + return query.append(" } }").toString(); + } + + /** + * Runs a GraphQL query with variables (a JSON object) against the engine and returns the + * response's data as JSON. + */ + @FunctionalInterface + public interface QueryRunner { + InputStream query(String query, String variables) throws IOException, InterruptedException; + } + + /** + * Formats the names of a schema through the engine, in batches, in every format Java codegen + * uses, passing the schema's {@code __schemaVersion} as the dictionary version. Returns the names + * keyed by format ({@link #MEMBERS}, {@link #TYPES}, {@link #ENUM_VALUES}), like a names file. + * + * @throws IOException when the names can't be formatted, with a message that says why codegen + * needs them + */ + public static Map> fetch(byte[] schemaJson, QueryRunner runner) + throws IOException, InterruptedException { + JsonObject root = read(schemaJson, "the introspection JSON"); + String version = schemaVersion(root); + Map> formatted = new HashMap<>(); + for (String format : FORMATS) { + formatted.put(format, new HashMap<>()); + } + for (List batch : batches(names(root), BATCH_BYTES)) { + var variables = Json.createObjectBuilder().add("names", Json.createArrayBuilder(batch)); + if (version == null) { + variables.addNull("version"); + } else { + variables.add("version", version); + } + JsonObject data; + try (InputStream in = runner.query(QUERY, variables.build().toString())) { + data = read(in.readAllBytes(), "the naming response"); + } catch (IOException e) { + throw failure(version, e.getMessage(), e); + } + JsonObject naming = object(data, "naming"); + for (int i = 0; i < FORMATS.size(); i++) { + JsonValue result = naming == null ? null : naming.get("f" + i); + if (result == null || result.getValueType() != ValueType.ARRAY) { + throw failure(version, "the response has no formatIdentifiers result: " + data, null); + } + JsonArray out = result.asJsonArray(); + if (out.size() != batch.size()) { + throw failure( + version, "sent " + batch.size() + " names, got " + out.size() + " back", null); + } + Map names = formatted.get(FORMATS.get(i)); + for (int j = 0; j < batch.size(); j++) { + names.put(batch.get(j), out.getString(j)); + } + } + } + return formatted; + } + + private static IOException failure(String version, String why, Throwable cause) { + return new IOException( + "the engine could not format the schema's Java names with Query.naming (schema version " + + (version == null ? "unknown" : version) + + "): " + + why, + cause); + } + + /** + * Reads the names Java codegen uses from a names file, as {@code codegen introspect --names-out} + * writes it: {@code {"CAMEL:CAPITALIZED": {"withGPU": "withGpu", ...}, "PASCAL:CAPITALIZED": + * {...}, ...}}, keyed by format. Formats Java codegen doesn't use are left out, and a format the + * file doesn't have keeps the schema's names. Returns null when the file has none of them. + */ + public static Map> read(InputStream namesJson) throws IOException { + JsonObject root = read(namesJson.readAllBytes(), "the names file"); + Map> formatted = new HashMap<>(); + for (String format : FORMATS) { + JsonValue names = root.get(format); + if (names == null || names.getValueType() != ValueType.OBJECT) { + continue; + } + Map byName = new HashMap<>(); + for (Map.Entry e : names.asJsonObject().entrySet()) { + if (e.getValue() instanceof JsonString s) { + byName.put(e.getKey(), s.getString()); + } + } + formatted.put(format, byName); + } + return formatted.isEmpty() ? null : formatted; + } + + /** The schema's {@code __schemaVersion}, or null when it has none. */ + static String schemaVersion(JsonObject root) { + JsonValue version = root.get("__schemaVersion"); + if (version instanceof JsonString s && !s.getString().isEmpty()) { + return s.getString(); + } + return null; + } + + /** + * The distinct type, field, argument, input field and enum value names in the schema, sorted, + * leaving out introspection names ("__" prefix) and names the engine can't format (non-ASCII, or + * with no letters or digits). + */ + static List names(JsonObject root) { + TreeSet names = new TreeSet<>(); + JsonObject schema = object(root, "__schema"); + if (schema == null) { + return List.of(); + } + for (JsonObject type : objects(schema, "types")) { + String typeName = type.getString("name", ""); + if (typeName.startsWith("__")) { + continue; + } + addName(names, typeName); + for (JsonObject field : objects(type, "fields")) { + addName(names, field.getString("name", "")); + for (JsonObject arg : objects(field, "args")) { + addName(names, arg.getString("name", "")); + } + } + for (JsonObject inputField : objects(type, "inputFields")) { + addName(names, inputField.getString("name", "")); + } + for (JsonObject enumValue : objects(type, "enumValues")) { + addName(names, enumValue.getString("name", "")); + } + } + return new ArrayList<>(names); + } + + /** + * Splits names into batches of at most maxBytes as a JSON array (but at least one name each). + * Schema names need no escaping, so each takes its length plus quotes and a comma. + */ + static List> batches(List names, int maxBytes) { + List> batches = new ArrayList<>(); + int start = 0; + while (start < names.size()) { + int end = start; + int size = 2; + while (end < names.size() + && (end == start || size + names.get(end).length() + 3 <= maxBytes)) { + size += names.get(end).length() + 3; + end++; + } + batches.add(names.subList(start, end)); + start = end; + } + return batches; + } + + private static void addName(TreeSet names, String name) { + if (name.startsWith("__") + || !name.chars().allMatch(c -> c < 0x80) + || !HAS_ALNUM.matcher(name).find()) { + return; + } + names.add(name); + } + + private static JsonObject object(JsonObject parent, String key) { + JsonValue value = parent.get(key); + return value != null && value.getValueType() == ValueType.OBJECT ? value.asJsonObject() : null; + } + + private static List objects(JsonObject parent, String key) { + JsonValue value = parent.get(key); + if (value == null || value.getValueType() != ValueType.ARRAY) { + return List.of(); + } + return value.asJsonArray().stream() + .filter(v -> v.getValueType() == ValueType.OBJECT) + .map(JsonValue::asJsonObject) + .toList(); + } + + private static JsonObject read(byte[] json, String what) throws IOException { + try (JsonReader reader = Json.createReader(new ByteArrayInputStream(json))) { + return reader.readObject(); + } catch (JsonParsingException | IllegalStateException e) { + throw new IOException(what + " is not a JSON object: " + e.getMessage(), e); + } + } +} diff --git a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/Helpers.java b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/Helpers.java index 8eacb26..b8239b0 100644 --- a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/Helpers.java +++ b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/Helpers.java @@ -2,11 +2,14 @@ import static org.apache.commons.lang3.StringUtils.capitalize; +import com.palantir.javapoet.AnnotationSpec; import com.palantir.javapoet.ClassName; import com.palantir.javapoet.MethodSpec; import com.palantir.javapoet.ParameterSpec; import com.palantir.javapoet.TypeName; +import com.palantir.javapoet.TypeSpec; import java.util.List; +import java.util.stream.Collectors; import javax.lang.model.element.Modifier; public class Helpers { @@ -154,27 +157,117 @@ static String formatName(String graphqlName) { } } + /** + * Marks a generated class with the GraphQL type it stands for, when engine-formatted names named + * it apart from the type: the runtime reads it wherever it sends a class's type name to the API. + */ + static void addGraphQLType(TypeSpec.Builder builder, TypeRegistry registry, String typeName) { + if (!registry.formatsTypeNames() + || "Query".equals(typeName) + || typeName.equals(registry.javaTypeName(typeName))) { + return; + } + builder.addAnnotation( + AnnotationSpec.builder(registry.runtime("GraphQLType")) + .addMember("value", "$S", typeName) + .build()); + } + + /** + * The Java spelling of a field, argument or input field name: camelCase with acronyms written + * like words ({@code asJson}, {@code withGpu}) as the engine formatted it (see {@link + * FormattedNames}), else the schema name as is. Strings sent to the API always use the schema + * name. + */ + static String javaName(String name, String formattedName) { + if (formattedName == null || formattedName.isEmpty()) { + return name; + } + return formattedName; + } + + /** The Java method name of a field. */ static String formatName(Field field) { + return escapeMethodName(field, javaName(field.getName(), field.getFormattedName())); + } + + /** + * The Java method name of a field before engine-formatted names: the schema name, escaped. When + * it differs from {@link #formatName(Field)}, it's kept as a deprecated alias. + */ + static String legacyName(Field field) { + return escapeMethodName(field, field.getName()); + } + + private static String escapeMethodName(Field field, String name) { if ("Container".equals(field.getParentObject().getName()) && "import".equals(field.getName())) { return "importTarball"; - } else if (JAVA_KEYWORDS.contains(field.getName()) - || ((JAVA_OBJECT_METHODS.contains(field.getName()) - || QUERY_BUILDER_ACCESSOR.equals(field.getName())) + } else if (JAVA_KEYWORDS.contains(name) + || ((JAVA_OBJECT_METHODS.contains(name) || QUERY_BUILDER_ACCESSOR.equals(name)) && field.getRequiredArgs().isEmpty())) { - return field.getName() + "_"; + return name + "_"; } else { - return field.getName(); + return name; } } + /** + * The class holding a field's optional arguments. It keeps the name derived from the schema name: + * like the arguments classes of entry points, it is named apart from formatted names, so code + * naming it keeps compiling. + */ + static String argumentsClassName(Field field) { + return capitalize(legacyName(field)) + "Arguments"; + } + + /** The Java variable name of an argument or input field. */ static String formatName(InputObject arg) { - if (JAVA_KEYWORDS.contains(arg.getName())) { - return "_" + arg.getName(); + return escapeVariableName(javaName(arg.getName(), arg.getFormattedName())); + } + + private static String escapeVariableName(String name) { + if (JAVA_KEYWORDS.contains(name)) { + return "_" + name; } else { - return arg.getName(); + return name; } } + /** The name of the "with" setter of an argument or input field. */ + static String withSetterName(InputObject var) { + return "with" + capitalize(javaName(var.getName(), var.getFormattedName())); + } + + /** The name of the "with" setter of an argument or input field before formatted names. */ + static String legacyWithSetterName(InputObject var) { + return "with" + capitalize(var.getName()); + } + + /** + * A deprecated method under a name the generator used before formatted names, forwarding to the + * method that replaces it. + */ + static MethodSpec deprecatedAlias(MethodSpec target, String legacyName, Modifier... modifiers) { + MethodSpec.Builder builder = + MethodSpec.methodBuilder(legacyName) + .addModifiers(Modifier.PUBLIC) + .addModifiers(modifiers) + .addTypeVariables(target.typeVariables()) + .returns(target.returnType()) + .addParameters(target.parameters()) + .addExceptions(target.exceptions()) + .addAnnotation(Deprecated.class) + .addJavadoc("@deprecated Use {@link #$L} instead.\n", target.name()); + String args = + target.parameters().stream().map(ParameterSpec::name).collect(Collectors.joining(", ")); + if (TypeName.VOID.equals(target.returnType())) { + builder.addStatement("$L($L)", target.name(), args); + } else { + builder.addStatement("return $L($L)", target.name(), args); + } + return builder.build(); + } + static MethodSpec getter(String var, TypeName type) { String prefix = (TypeName.BOOLEAN.equals(type) || ClassName.get(Boolean.class).equals(type)) ? "is" : "get"; @@ -199,7 +292,7 @@ static MethodSpec withSetter(InputObject var, TypeName type, TypeName returnType static MethodSpec withSetter(InputObject var, TypeName type, TypeName returnType, String doc) { MethodSpec.Builder builder = - MethodSpec.methodBuilder("with" + capitalize(var.getName())) + MethodSpec.methodBuilder(withSetterName(var)) .addModifiers(Modifier.PUBLIC) .addParameter(type, Helpers.formatName(var)) .returns(returnType) diff --git a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/IDAbleVisitor.java b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/IDAbleVisitor.java index ce91208..c80e5b4 100644 --- a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/IDAbleVisitor.java +++ b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/IDAbleVisitor.java @@ -18,38 +18,82 @@ public IDAbleVisitor( @Override TypeSpec generateType(List types) { + ClassName json = registry().forType("JSON"); + // Enums named apart from their schema values convert through their values; enums named like + // them, through their names (see GraphQLEnums). + boolean enumValues = getSchema().formatsEnumValues(); + ClassName graphQLEnums = registry().runtime("GraphQLEnums"); + + MethodSpec.Builder toJSON = + MethodSpec.methodBuilder("toJSON") + .addModifiers(Modifier.PUBLIC, Modifier.STATIC) + .returns(json) + .addException(Exception.class) + .addParameter(Object.class, "object") + .beginControlFlow( + "try ($T jsonb = $T.create(new $T().withPropertyVisibilityStrategy(new $T())))", + Jsonb.class, + JsonbBuilder.class, + JsonbConfig.class, + registry().runtime("FieldsStrategy")) + .beginControlFlow("if (object instanceof $T)", Enum.class); + if (enumValues) { + toJSON.addStatement( + "return $T.from(jsonb.toJson($T.value(($T) object)))", json, graphQLEnums, Enum.class); + } else { + toJSON.addStatement( + "return $T.from(jsonb.toJson((($T) object).name()))", json, Enum.class); + } + toJSON.endControlFlow(); + if (enumValues) { + // A list's elements don't go through their enum's serializer. + toJSON.addStatement("return $T.from(jsonb.toJson($T.values(object)))", json, graphQLEnums); + } else { + toJSON.addStatement("return $T.from(jsonb.toJson(object))", json); + } + toJSON.endControlFlow(); + + MethodSpec.Builder fromJSON = + MethodSpec.methodBuilder("fromJSON") + .addModifiers(Modifier.PUBLIC, Modifier.STATIC) + .addTypeVariable(TypeVariableName.get("T")) + .returns(TypeVariableName.get("T")) + .addParameter(ClassName.get(String.class), "json") + .addParameter( + ParameterizedTypeName.get(ClassName.get(Class.class), TypeVariableName.get("T")), + "clazz") + .addException(Exception.class) + .beginControlFlow( + "try ($T jsonb = $T.create(new $T().withPropertyVisibilityStrategy(new $T())))", + Jsonb.class, + JsonbBuilder.class, + JsonbConfig.class, + registry().runtime("FieldsStrategy")) + .beginControlFlow("if (clazz.isEnum())"); + if (enumValues) { + fromJSON.addStatement( + "return $T.valueOf(clazz, jsonb.fromJson(json, $T.class))", graphQLEnums, String.class); + } else { + fromJSON + .addStatement( + "$T valueOf = clazz.getMethod($S, $T.class)", Method.class, "valueOf", String.class) + .addStatement( + "return clazz.cast(valueOf.invoke(null, jsonb.fromJson(json, $T.class)))", + String.class); + } + fromJSON.endControlFlow().addStatement("return jsonb.fromJson(json, clazz)").endControlFlow(); + TypeSpec.Builder b = TypeSpec.classBuilder("JsonConverter") .addJavadoc("Convert to and from Json with the right serializers and deserializers") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) - .addMethod( - MethodSpec.methodBuilder("toJSON") - .addModifiers(Modifier.PUBLIC, Modifier.STATIC) - .returns(registry().forType("JSON")) - .addException(Exception.class) - .addParameter(Object.class, "object") - .beginControlFlow( - "try ($T jsonb = $T.create(new $T().withPropertyVisibilityStrategy(new $T())))", - Jsonb.class, - JsonbBuilder.class, - JsonbConfig.class, - registry().runtime("FieldsStrategy")) - .beginControlFlow("if (object instanceof $T)", Enum.class) - .addStatement( - "return $T.from(jsonb.toJson((($T) object).name()))", - registry().forType("JSON"), - Enum.class) - .endControlFlow() - .addStatement( - "return $T.from(jsonb.toJson(object))", registry().forType("JSON")) - .endControlFlow() - .build()) + .addMethod(toJSON.build()) .addMethod( MethodSpec.methodBuilder("fromJSON") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addTypeVariable(TypeVariableName.get("T")) .returns(TypeVariableName.get("T")) - .addParameter(registry().forType("JSON"), "json") + .addParameter(json, "json") .addParameter( ParameterizedTypeName.get( ClassName.get(Class.class), TypeVariableName.get("T")), @@ -57,36 +101,7 @@ TypeSpec generateType(List types) { .addException(Exception.class) .addStatement("return fromJSON(json.convert(), clazz)") .build()) - .addMethod( - MethodSpec.methodBuilder("fromJSON") - .addModifiers(Modifier.PUBLIC, Modifier.STATIC) - .addTypeVariable(TypeVariableName.get("T")) - .returns(TypeVariableName.get("T")) - .addParameter(ClassName.get(String.class), "json") - .addParameter( - ParameterizedTypeName.get( - ClassName.get(Class.class), TypeVariableName.get("T")), - "clazz") - .addException(Exception.class) - .beginControlFlow( - "try ($T jsonb = $T.create(new $T().withPropertyVisibilityStrategy(new $T())))", - Jsonb.class, - JsonbBuilder.class, - JsonbConfig.class, - registry().runtime("FieldsStrategy")) - .beginControlFlow("if (clazz.isEnum())") - .addStatement( - "$T valueOf = clazz.getMethod($S, $T.class)", - Method.class, - "valueOf", - String.class) - .addStatement( - "return clazz.cast(valueOf.invoke(null, jsonb.fromJson(json, $T.class)))", - String.class) - .endControlFlow() - .addStatement("return jsonb.fromJson(json, clazz)") - .endControlFlow() - .build()); + .addMethod(fromJSON.build()); return b.build(); } } diff --git a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/InputObject.java b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/InputObject.java index bc82686..1c19936 100644 --- a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/InputObject.java +++ b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/InputObject.java @@ -1,5 +1,6 @@ package io.dagger.codegen.introspection; +import jakarta.json.bind.annotation.JsonbTransient; import java.util.List; public class InputObject { @@ -10,6 +11,17 @@ public class InputObject { private TypeRef type; private List directives; + /** The Java name the engine formatted for this argument or input field's name, or null. */ + @JsonbTransient private String formattedName; + + public String getFormattedName() { + return formattedName; + } + + public void setFormattedName(String formattedName) { + this.formattedName = formattedName; + } + public String getName() { return name; } diff --git a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/InputVisitor.java b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/InputVisitor.java index 792a22c..a4b36e4 100644 --- a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/InputVisitor.java +++ b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/InputVisitor.java @@ -1,10 +1,15 @@ package io.dagger.codegen.introspection; import com.palantir.javapoet.*; +import jakarta.json.bind.annotation.JsonbProperty; import java.nio.charset.Charset; import java.nio.file.Path; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; import javax.lang.model.element.Modifier; class InputVisitor extends AbstractVisitor { @@ -16,30 +21,51 @@ public InputVisitor( @Override TypeSpec generateType(Type type) { + ClassName thisType = registry().forType(type.getName()); TypeSpec.Builder classBuilder = - TypeSpec.classBuilder(Helpers.formatName(type)) + TypeSpec.classBuilder(thisType.simpleName()) .addJavadoc(type.getDescription() != null ? type.getDescription() : "") .addModifiers(Modifier.PUBLIC) .addSuperinterface(registry().runtime("InputValue")); + Helpers.addGraphQLType(classBuilder, registry(), type.getName()); + List methods = new ArrayList<>(); + List legacyNames = new ArrayList<>(); for (InputObject inputObject : type.getInputFields()) { - - classBuilder.addField( + String fieldName = fieldName(inputObject); + FieldSpec.Builder field = FieldSpec.builder( - inputObject.getType().formatInput(registry()), - inputObject.getName(), - Modifier.PRIVATE) - .build()); - - classBuilder.addMethod( - Helpers.getter(inputObject.getName(), inputObject.getType().formatInput(registry()))); - classBuilder.addMethod( - Helpers.setter(inputObject.getName(), inputObject.getType().formatOutput(registry()))); - classBuilder.addMethod( - Helpers.withSetter( - inputObject, - inputObject.getType().formatInput(registry()), - registry().forType(type.getName()))); + inputObject.getType().formatInput(registry()), fieldName, Modifier.PRIVATE); + if (!fieldName.equals(inputObject.getName())) { + // JSON-B serializes inputs by field name: keep the schema's. + field.addAnnotation( + AnnotationSpec.builder(JsonbProperty.class) + .addMember("value", "$S", inputObject.getName()) + .build()); + } + classBuilder.addField(field.build()); + + methods.add(Helpers.getter(fieldName, inputObject.getType().formatInput(registry()))); + methods.add(Helpers.setter(fieldName, inputObject.getType().formatOutput(registry()))); + methods.add( + Helpers.withSetter(inputObject, inputObject.getType().formatInput(registry()), thisType)); + legacyNames.add( + Helpers.getter(inputObject.getName(), inputObject.getType().formatInput(registry())) + .name()); + legacyNames.add( + Helpers.setter(inputObject.getName(), inputObject.getType().formatOutput(registry())) + .name()); + legacyNames.add(Helpers.legacyWithSetterName(inputObject)); + } + Set methodNames = methods.stream().map(MethodSpec::name).collect(Collectors.toSet()); + for (int i = 0; i < methods.size(); i++) { + MethodSpec method = methods.get(i); + classBuilder.addMethod(method); + // Accessors renamed by formatted names keep their old names as deprecated aliases. + String legacyName = legacyNames.get(i); + if (!legacyName.equals(method.name()) && !methodNames.contains(legacyName)) { + classBuilder.addMethod(Helpers.deprecatedAlias(method, legacyName)); + } } MethodSpec.Builder toMapMethod = @@ -51,8 +77,10 @@ TypeSpec generateType(Type type) { "$1T map = new $1T()", ParameterizedTypeName.get(HashMap.class, String.class, Object.class)); for (InputObject inputObject : type.getInputFields()) { - toMapMethod.beginControlFlow("if (this.$1L != null)", inputObject.getName()); - toMapMethod.addStatement("map.put(\"$1L\", this.$1L)", inputObject.getName()); + // The map's keys are sent as the input's field names: keep the schema's. + toMapMethod.beginControlFlow("if (this.$L != null)", fieldName(inputObject)); + toMapMethod.addStatement( + "map.put(\"$L\", this.$L)", inputObject.getName(), fieldName(inputObject)); toMapMethod.endControlFlow(); } toMapMethod.addStatement("return map"); @@ -60,4 +88,15 @@ TypeSpec generateType(Type type) { return classBuilder.build(); } + + /** + * The Java field of an input field: its engine-formatted name when there is one, else the schema + * name as is. + */ + private static String fieldName(InputObject inputObject) { + if (inputObject.getFormattedName() == null || inputObject.getFormattedName().isEmpty()) { + return inputObject.getName(); + } + return Helpers.formatName(inputObject); + } } diff --git a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/InterfaceVisitor.java b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/InterfaceVisitor.java index df251dd..f99a7fb 100644 --- a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/InterfaceVisitor.java +++ b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/InterfaceVisitor.java @@ -6,7 +6,9 @@ import java.nio.file.Path; import java.util.List; import java.util.Optional; +import java.util.Set; import java.util.concurrent.ExecutionException; +import java.util.stream.Collectors; import javax.lang.model.element.Modifier; /** @@ -34,9 +36,10 @@ void visit(Type type) throws IOException { @Override TypeSpec generateType(Type type) { TypeSpec.Builder interfaceBuilder = - TypeSpec.interfaceBuilder(Helpers.formatName(type)) + TypeSpec.interfaceBuilder(registry().javaTypeName(type.getName())) .addJavadoc(Helpers.escapeJavadoc(type.getDescription())) .addModifiers(Modifier.PUBLIC); + Helpers.addGraphQLType(interfaceBuilder, registry(), type.getName()); // An interface exposing an id field is IDAble like any object, so a value // typed by it (a Node argument, say) serializes by ID through the same @@ -47,6 +50,8 @@ TypeSpec generateType(Type type) { } if (type.getFields() != null) { + Set methodNames = + type.getFields().stream().map(Helpers::formatName).collect(Collectors.toSet()); for (Field field : type.getFields()) { MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(Helpers.formatName(field)) @@ -92,7 +97,14 @@ TypeSpec generateType(Type type) { methodBuilder.addAnnotation(Deprecated.class); } - interfaceBuilder.addMethod(methodBuilder.build()); + MethodSpec method = methodBuilder.build(); + interfaceBuilder.addMethod(method); + // A method renamed by a formatted name keeps its old name as a deprecated default + // method, so implementations don't need to provide it. + String legacyName = Helpers.legacyName(field); + if (!legacyName.equals(method.name()) && !methodNames.contains(legacyName)) { + interfaceBuilder.addMethod(Helpers.deprecatedAlias(method, legacyName, Modifier.DEFAULT)); + } } } @@ -101,8 +113,8 @@ TypeSpec generateType(Type type) { /** Generates the FooClient class that implements the Foo interface via query building. */ TypeSpec generateClientType(Type type) { - String clientName = Helpers.formatName(type) + "Client"; ClassName interfaceName = registry().forType(type.getName()); + String clientName = registry().forInterfaceClient(type.getName()).simpleName(); TypeSpec.Builder classBuilder = TypeSpec.classBuilder(clientName) @@ -113,6 +125,7 @@ TypeSpec generateClientType(Type type) { FieldSpec.builder( registry().runtime("QueryBuilder"), "queryBuilder", Modifier.PRIVATE) .build()); + Helpers.addGraphQLType(classBuilder, registry(), type.getName()); // Constructor MethodSpec constructor = diff --git a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/ObjectVisitor.java b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/ObjectVisitor.java index 5ef9777..fed42d1 100644 --- a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/ObjectVisitor.java +++ b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/ObjectVisitor.java @@ -1,9 +1,9 @@ package io.dagger.codegen.introspection; -import static org.apache.commons.lang3.StringUtils.capitalize; import static org.apache.commons.lang3.StringUtils.uncapitalize; import com.palantir.javapoet.*; +import jakarta.json.bind.annotation.JsonbProperty; import jakarta.json.bind.annotation.JsonbTypeDeserializer; import jakarta.json.bind.annotation.JsonbTypeSerializer; import jakarta.json.bind.serializer.DeserializationContext; @@ -11,10 +11,14 @@ import jakarta.json.stream.JsonParser; import java.nio.charset.Charset; import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashSet; import java.util.List; import java.util.Optional; +import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.function.UnaryOperator; +import java.util.stream.Collectors; import javax.lang.model.element.Modifier; class ObjectVisitor extends AbstractVisitor { @@ -50,18 +54,22 @@ public ObjectVisitor( * * @param receiverType the core type the field was reached through, or null on {@code Query}, * whose receiver is the session + * @param receiverTypeName that type's GraphQL name, or null on {@code Query} */ - private record Entry(ClassName receiverType, String receiverName) { + private record Entry(ClassName receiverType, String receiverTypeName, String receiverName) { - static final Entry ON_QUERY = new Entry(null, "session"); + static final Entry ON_QUERY = new Entry(null, null, "session"); boolean onQuery() { return receiverType == null; } - /** Every entry lands in one class, so two fields of the same name need telling apart. */ + /** + * Every entry lands in one class, so two fields of the same name need telling apart. Named + * after the GraphQL type, like the arguments class itself, so formatted names don't rename it. + */ String argumentsPrefix() { - return onQuery() ? "" : receiverType.simpleName(); + return onQuery() ? "" : Helpers.formatName(receiverTypeName); } /** The chain the entry selects from: the receiver's, carrying the target to serve. */ @@ -74,13 +82,14 @@ String chainFrom() { TypeSpec generateType(Type type) { ClassName thisType = registry().forType(type.getName()); TypeSpec.Builder classBuilder = - TypeSpec.classBuilder(Helpers.formatName(type)) + TypeSpec.classBuilder(thisType.simpleName()) .addJavadoc(Helpers.escapeJavadoc(type.getDescription())) .addModifiers(Modifier.PUBLIC) .addField( FieldSpec.builder( registry().runtime("QueryBuilder"), "queryBuilder", Modifier.PRIVATE) .build()); + Helpers.addGraphQLType(classBuilder, registry(), type.getName()); // Add implements for any interfaces this object implements for (String ifaceName : type.getImplementedInterfaceNames()) { @@ -91,27 +100,7 @@ TypeSpec generateType(Type type) { buildCoreEntryPoint(classBuilder, thisType); // loadObjectFromID: load any object by its ID using node(id:) + inline fragment - classBuilder.addMethod( - MethodSpec.methodBuilder("loadObjectFromID") - .addModifiers(Modifier.PUBLIC) - .addTypeVariable(TypeVariableName.get("T")) - .returns(TypeVariableName.get("T")) - .addParameter( - ParameterizedTypeName.get(ClassName.get(Class.class), TypeVariableName.get("T")), - "clazz") - .addParameter(registry().forType("ID"), "id") - .addJavadoc("Load any object by its ID using node(id:) with an inline fragment.\n") - .beginControlFlow("try") - .addStatement( - "$T qb = this.queryBuilder.chainNode(clazz.getSimpleName(), id)", - registry().runtime("QueryBuilder")) - .addStatement( - "return clazz.getDeclaredConstructor($T.class).newInstance(qb)", - registry().runtime("QueryBuilder")) - .nextControlFlow("catch (Exception e)") - .addStatement("throw new RuntimeException(\"Failed to load object from ID\", e)") - .endControlFlow() - .build()); + classBuilder.addMethod(loadObjectFromID()); // nodeQueryBuilder: create a QueryBuilder for node(id:) + inline fragment classBuilder.addMethod( @@ -175,10 +164,19 @@ TypeSpec generateType(Type type) { for (Field scalarField : type.getFields().stream().filter(f -> f.getTypeRef().isScalar()).toList()) { - classBuilder.addField( - scalarField.getTypeRef().formatOutput(registry()), - Helpers.formatName(scalarField), - Modifier.PRIVATE); + FieldSpec.Builder cached = + FieldSpec.builder( + scalarField.getTypeRef().formatOutput(registry()), + Helpers.formatName(scalarField), + Modifier.PRIVATE); + if (!Helpers.formatName(scalarField).equals(Helpers.legacyName(scalarField))) { + // JSON-B reads a field by its Java name: keep the schema's. + cached.addAnnotation( + AnnotationSpec.builder(JsonbProperty.class) + .addMember("value", "$S", scalarField.getName()) + .build()); + } + classBuilder.addField(cached.build()); } } @@ -201,17 +199,18 @@ TypeSpec generateType(Type type) { .addStatement("return this.queryBuilder") .build()); + Set methodNames = methodNames(type); for (Field field : type.getFields()) { if (field.hasOptionalArgs()) { buildFieldArgumentsHelpers(classBuilder, field, type, null); - buildFieldMethod(classBuilder, field, true, null); + buildFieldMethod(classBuilder, field, true, null, methodNames); } - buildFieldMethod(classBuilder, field, false, null); + buildFieldMethod(classBuilder, field, false, null, methodNames); } if (entryPoint != null && entryPoint.rootTypeName().equals(type.getName())) { - buildEntryPoints(classBuilder, type); + buildEntryPoints(classBuilder, type, methodNames); } if (List.of("Container", "Directory").contains(type.getName())) { @@ -252,15 +251,16 @@ private void buildCoreEntryPoint(TypeSpec.Builder classBuilder, ClassName core) * The way into this client package: the module's {@code Query} field, and every field it * contributes to another core type. */ - private void buildEntryPoints(TypeSpec.Builder classBuilder, Type type) { + private void buildEntryPoints(TypeSpec.Builder classBuilder, Type type, Set methodNames) { classBuilder.addField(targetConstant()); - buildEntry(classBuilder, entryPoint.entryField(), type, Entry.ON_QUERY); + buildEntry(classBuilder, entryPoint.entryField(), type, Entry.ON_QUERY, methodNames); entryPoint .shims() .forEach( (typeName, fields) -> { - Entry shim = new Entry(registry().forType(typeName), uncapitalize(typeName)); - fields.forEach(field -> buildEntry(classBuilder, field, type, shim)); + Entry shim = + new Entry(registry().forType(typeName), typeName, uncapitalize(typeName)); + fields.forEach(field -> buildEntry(classBuilder, field, type, shim, methodNames)); }); } @@ -269,18 +269,93 @@ private void buildEntryPoints(TypeSpec.Builder classBuilder, Type type) { * holds. A field on any other core type reads the session off its receiver, so there is no * session left for a caller to choose. */ - private void buildEntry(TypeSpec.Builder classBuilder, Field field, Type type, Entry entry) { + private void buildEntry( + TypeSpec.Builder classBuilder, Field field, Type type, Entry entry, Set methodNames) { if (field.hasOptionalArgs()) { buildFieldArgumentsHelpers(classBuilder, field, type, entry); - MethodSpec withOptArgs = buildFieldMethod(classBuilder, field, true, entry); + MethodSpec withOptArgs = buildFieldMethod(classBuilder, field, true, entry, methodNames); if (entry.onQuery()) { - classBuilder.addMethod(ambient(withOptArgs, Helpers.escapeJavadoc(field.getDescription()))); + MethodSpec ambient = ambient(withOptArgs, Helpers.escapeJavadoc(field.getDescription())); + classBuilder.addMethod(ambient); + addLegacyAlias(classBuilder, ambient, field, methodNames, Modifier.STATIC); } } - MethodSpec method = buildFieldMethod(classBuilder, field, false, entry); + MethodSpec method = buildFieldMethod(classBuilder, field, false, entry, methodNames); if (entry.onQuery()) { - classBuilder.addMethod(ambient(method, Helpers.escapeJavadoc(field.getDescription()))); + MethodSpec ambient = ambient(method, Helpers.escapeJavadoc(field.getDescription())); + classBuilder.addMethod(ambient); + addLegacyAlias(classBuilder, ambient, field, methodNames, Modifier.STATIC); + } + } + + /** + * The names of the methods generated for a type's fields, and for the entry points it carries: an + * old name a formatted name freed is only kept as an alias when no method took it. + */ + private Set methodNames(Type type) { + Set names = new HashSet<>(); + type.getFields().forEach(field -> names.add(Helpers.formatName(field))); + if (entryPoint != null && entryPoint.rootTypeName().equals(type.getName())) { + names.add(Helpers.formatName(entryPoint.entryField())); + entryPoint + .shims() + .values() + .forEach(fields -> fields.forEach(field -> names.add(Helpers.formatName(field)))); } + return names; + } + + /** + * When a formatted name renamed a field's method, its old name as a deprecated alias, unless + * another method now has that name. + */ + private static void addLegacyAlias( + TypeSpec.Builder classBuilder, + MethodSpec method, + Field field, + Set methodNames, + Modifier... modifiers) { + String legacyName = Helpers.legacyName(field); + if (!legacyName.equals(method.name()) && !methodNames.contains(legacyName)) { + classBuilder.addMethod(Helpers.deprecatedAlias(method, legacyName, modifiers)); + } + } + + /** + * Core.loadObjectFromID: loads any object by its ID with node(id:) and an inline fragment on the + * class's GraphQL type. Classes named apart from their type carry it in {@code @GraphQLType}. + */ + private MethodSpec loadObjectFromID() { + ClassName queryBuilder = registry().runtime("QueryBuilder"); + MethodSpec.Builder builder = + MethodSpec.methodBuilder("loadObjectFromID") + .addModifiers(Modifier.PUBLIC) + .addTypeVariable(TypeVariableName.get("T")) + .returns(TypeVariableName.get("T")) + .addParameter( + ParameterizedTypeName.get(ClassName.get(Class.class), TypeVariableName.get("T")), + "clazz") + .addParameter(registry().forType("ID"), "id") + .addJavadoc("Load any object by its ID using node(id:) with an inline fragment.\n") + .beginControlFlow("try"); + if (registry().formatsTypeNames()) { + ClassName graphQLType = registry().runtime("GraphQLType"); + builder + .addStatement("$T graphQLType = clazz.getAnnotation($T.class)", graphQLType, graphQLType) + .addStatement( + "$T typeName = graphQLType != null ? graphQLType.value() : clazz.getSimpleName()", + String.class) + .addStatement("$T qb = this.queryBuilder.chainNode(typeName, id)", queryBuilder); + } else { + builder.addStatement( + "$T qb = this.queryBuilder.chainNode(clazz.getSimpleName(), id)", queryBuilder); + } + return builder + .addStatement("return clazz.getDeclaredConstructor($T.class).newInstance(qb)", queryBuilder) + .nextControlFlow("catch (Exception e)") + .addStatement("throw new RuntimeException(\"Failed to load object from ID\", e)") + .endControlFlow() + .build(); } private FieldSpec targetConstant() { @@ -336,7 +411,11 @@ private TypeName resolveReturnType(Field field) { } private MethodSpec buildFieldMethod( - TypeSpec.Builder classBuilder, Field field, boolean withOptionalArgs, Entry entry) { + TypeSpec.Builder classBuilder, + Field field, + boolean withOptionalArgs, + Entry entry, + Set methodNames) { MethodSpec.Builder fieldMethodBuilder = MethodSpec.methodBuilder(Helpers.formatName(field)).addModifiers(Modifier.PUBLIC); String chainFrom = "this.queryBuilder"; @@ -517,6 +596,11 @@ private MethodSpec buildFieldMethod( MethodSpec method = fieldMethodBuilder.build(); classBuilder.addMethod(method); + if (entry == null) { + addLegacyAlias(classBuilder, method, field, methodNames); + } else { + addLegacyAlias(classBuilder, method, field, methodNames, Modifier.STATIC); + } return method; } @@ -545,16 +629,20 @@ private void buildFieldArgumentsHelpers( .toList(); fieldArgumentsClassBuilder.addFields(optionalArgFields); - List optionalArgFieldWithMethods = - field.getOptionalArgs().stream() - .map( - arg -> - Helpers.withSetter( - arg, - resolveArgType(arg, field), - fieldArgumentsClassName, - arg.getDescription())) - .toList(); + List optionalArgFieldWithMethods = new ArrayList<>(); + Set withSetterNames = + field.getOptionalArgs().stream().map(Helpers::withSetterName).collect(Collectors.toSet()); + for (InputObject arg : field.getOptionalArgs()) { + MethodSpec withSetter = + Helpers.withSetter( + arg, resolveArgType(arg, field), fieldArgumentsClassName, arg.getDescription()); + optionalArgFieldWithMethods.add(withSetter); + // A setter renamed by a formatted name keeps its old name as a deprecated alias. + String legacyName = Helpers.legacyWithSetterName(arg); + if (!legacyName.equals(withSetter.name()) && !withSetterNames.contains(legacyName)) { + optionalArgFieldWithMethods.add(Helpers.deprecatedAlias(withSetter, legacyName)); + } + } fieldArgumentsClassBuilder.addMethods(optionalArgFieldWithMethods); List blocks = @@ -583,9 +671,13 @@ private void buildFieldArgumentsHelpers( classBuilder.addType(fieldArgumentsClassBuilder.build()); } - /** The nested class holding a field's optional arguments, as the enclosing class names it. */ + /** + * The nested class holding a field's optional arguments, as the enclosing class names it. Named + * after the schema names, so formatted names don't rename it (see {@link + * Helpers#argumentsClassName}). + */ private ClassName argumentsClass(Field field, Entry entry) { String prefix = entry == null ? "" : entry.argumentsPrefix(); - return ClassName.bestGuess(prefix + capitalize(Helpers.formatName(field)) + "Arguments"); + return ClassName.bestGuess(prefix + Helpers.argumentsClassName(field)); } } diff --git a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/ScalarVisitor.java b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/ScalarVisitor.java index 1404292..726044e 100644 --- a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/ScalarVisitor.java +++ b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/ScalarVisitor.java @@ -16,7 +16,7 @@ public ScalarVisitor( @Override TypeSpec generateType(Type type) { TypeSpec.Builder classBuilder = - TypeSpec.classBuilder(Helpers.formatName(type)) + TypeSpec.classBuilder(registry().javaTypeName(type.getName())) .addJavadoc(type.getDescription() != null ? type.getDescription() : "") .addModifiers(Modifier.PUBLIC) .superclass( @@ -30,6 +30,7 @@ TypeSpec generateType(Type type) { AnnotationSpec.builder(JsonbTypeDeserializer.class) .addMember("value", "$T.class", registry().runtime("ScalarStringDeserializer")) .build()); + Helpers.addGraphQLType(classBuilder, registry(), type.getName()); MethodSpec constructor = MethodSpec.constructorBuilder() diff --git a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/Schema.java b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/Schema.java index 0c78208..cebd3fa 100644 --- a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/Schema.java +++ b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/Schema.java @@ -7,7 +7,9 @@ import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.apache.maven.artifact.versioning.ComparableVersion; public class Schema { @@ -57,6 +59,73 @@ public static Schema initialize(InputStream in, String version) throws IOExcepti private List types; + /** The class names the engine formatted, keyed by GraphQL type name; empty when unformatted. */ + private Map javaTypeNames = Map.of(); + + /** Whether enum constants follow Java's convention, from formatted names. */ + private boolean formattedEnumValues; + + /** + * Attaches the Java names the engine formatted (see {@link FormattedNames}), keyed by format and + * then by schema name: member names to fields, arguments and input fields, class names to types, + * and constant names to enum values. A name without an entry, a format without names, or a null + * map keeps the schema name. + */ + public void setFormattedNames(Map> formats) { + if (formats == null || types == null) { + return; + } + Map members = formats.getOrDefault(FormattedNames.MEMBERS, Map.of()); + Map typeNames = formats.get(FormattedNames.TYPES); + Map enumValues = formats.get(FormattedNames.ENUM_VALUES); + for (Type type : types) { + if (type.getFields() != null) { + for (Field field : type.getFields()) { + field.setFormattedName(members.get(field.getName())); + if (field.getArgs() != null) { + field.getArgs().forEach(arg -> arg.setFormattedName(members.get(arg.getName()))); + } + } + } + if (type.getInputFields() != null) { + type.getInputFields() + .forEach(inputField -> inputField.setFormattedName(members.get(inputField.getName()))); + } + if (enumValues != null && type.getEnumValues() != null) { + for (EnumValue value : type.getEnumValues()) { + value.setFormattedName(enumValues.get(value.getName())); + } + } + } + if (typeNames != null) { + Map classes = new HashMap<>(); + for (Type type : types) { + String formatted = typeNames.get(type.getName()); + if (formatted != null && !formatted.isEmpty()) { + classes.put(type.getName(), formatted); + } + } + javaTypeNames = Map.copyOf(classes); + } + formattedEnumValues = enumValues != null; + } + + /** + * The class names the engine formatted for this schema's types, by GraphQL type name; empty when + * the schema's names aren't formatted. + */ + public Map javaTypeNames() { + return javaTypeNames; + } + + /** + * Whether enum constants follow Java's convention (SCREAMING_SNAKE_CASE, carrying their schema + * values), rather than the schema's values. + */ + public boolean formatsEnumValues() { + return formattedEnumValues; + } + public QueryType getQueryType() { return queryType; } diff --git a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/TypeRegistry.java b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/TypeRegistry.java index 9c7e78f..7c14b49 100644 --- a/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/TypeRegistry.java +++ b/sdk/dagger-codegen-maven-plugin/src/main/java/io/dagger/codegen/introspection/TypeRegistry.java @@ -1,10 +1,12 @@ package io.dagger.codegen.introspection; +import static org.apache.commons.lang3.StringUtils.capitalize; + import com.palantir.javapoet.ClassName; import java.util.Map; /** - * Where every Java class a generated package refers to lives. + * Where every Java class a generated package refers to lives, and what it is called. * *

Generated code names three kinds of class: a schema type, a hand-written runtime class ({@code * QueryBuilder}, {@code Arguments}, ...), and itself. Every visitor used to name them by simple @@ -13,6 +15,10 @@ * *

Core and the runtime are two packages, because only core is generated: the runtime is * hand-written and stays where it is however the generated packages are laid out. + * + *

A schema type's class is named after the type, or, when the schema's names are formatted by + * the engine (see {@link FormattedNames}), by the name the engine formatted for it: {@code + * JsonValue} for {@code JSONValue}. Strings sent to the API always use the GraphQL type name. */ public final class TypeRegistry { @@ -20,20 +26,23 @@ public final class TypeRegistry { private final String corePackage; private final String runtimePackage; private final Map packageByTypeName; + private final Map javaTypeNames; private TypeRegistry( String targetPackage, String corePackage, String runtimePackage, - Map packageByTypeName) { + Map packageByTypeName, + Map javaTypeNames) { this.targetPackage = targetPackage; this.corePackage = corePackage; this.runtimePackage = runtimePackage; this.packageByTypeName = packageByTypeName; + this.javaTypeNames = javaTypeNames; } public static TypeRegistry singlePackage(String pkg) { - return new TypeRegistry(pkg, pkg, pkg, Map.of()); + return new TypeRegistry(pkg, pkg, pkg, Map.of(), Map.of()); } /** @@ -46,12 +55,26 @@ public static TypeRegistry singlePackage(String pkg) { public static TypeRegistry acrossPackages( String corePackage, String runtimePackage, Map packageByTypeName) { return new TypeRegistry( - corePackage, corePackage, runtimePackage, Map.copyOf(packageByTypeName)); + corePackage, corePackage, runtimePackage, Map.copyOf(packageByTypeName), Map.of()); } /** The same resolution, writing into a different package. */ public TypeRegistry emittingInto(String pkg) { - return new TypeRegistry(pkg, corePackage, runtimePackage, packageByTypeName); + return new TypeRegistry(pkg, corePackage, runtimePackage, packageByTypeName, javaTypeNames); + } + + /** + * The same resolution, naming classes by the names the engine formatted for their types, keyed by + * GraphQL type name (see {@link Schema#javaTypeNames}). A type without one keeps its name. + */ + public TypeRegistry withJavaTypeNames(Map javaTypeNames) { + return new TypeRegistry( + targetPackage, corePackage, runtimePackage, packageByTypeName, Map.copyOf(javaTypeNames)); + } + + /** Whether classes are named by engine-formatted names. */ + public boolean formatsTypeNames() { + return !javaTypeNames.isEmpty(); } public String targetPackage() { @@ -59,9 +82,23 @@ public String targetPackage() { } /** - * The Java class generated for a GraphQL type. {@code Query} is {@code Client}, the builtin - * scalars are their {@code java.lang} counterparts, and a type a module owns is in that module's - * package. + * The simple name of the Java class generated for a GraphQL type: {@code Core} for {@code Query}, + * the name the engine formatted when there is one, else the type's name capitalized. + */ + public String javaTypeName(String graphqlName) { + if ("Query".equals(graphqlName)) { + return Helpers.formatName(graphqlName); + } + String formatted = javaTypeNames.get(graphqlName); + if (formatted == null || formatted.isEmpty()) { + return capitalize(graphqlName); + } + return formatted; + } + + /** + * The Java class generated for a GraphQL type. {@code Query} is {@code Core}, the builtin scalars + * are their {@code java.lang} counterparts, and a type a module owns is in that module's package. */ public ClassName forType(String graphqlName) { switch (graphqlName) { @@ -75,8 +112,7 @@ public ClassName forType(String graphqlName) { return ClassName.get(Float.class); default: return ClassName.get( - packageByTypeName.getOrDefault(graphqlName, corePackage), - Helpers.formatName(graphqlName)); + packageByTypeName.getOrDefault(graphqlName, corePackage), javaTypeName(graphqlName)); } } diff --git a/sdk/dagger-codegen-maven-plugin/src/test/java/io/dagger/codegen/EngineQueriesTest.java b/sdk/dagger-codegen-maven-plugin/src/test/java/io/dagger/codegen/EngineQueriesTest.java new file mode 100644 index 0000000..e247680 --- /dev/null +++ b/sdk/dagger-codegen-maven-plugin/src/test/java/io/dagger/codegen/EngineQueriesTest.java @@ -0,0 +1,127 @@ +package io.dagger.codegen; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.sun.net.httpserver.HttpServer; +import io.dagger.codegen.introspection.FormattedNames; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** Codegen formats names through the nested session it runs in, when it has one. */ +class EngineQueriesTest { + + private HttpServer server; + private final List requests = new ArrayList<>(); + private final List authorizations = new ArrayList<>(); + private final List clientMetadata = new ArrayList<>(); + + @AfterEach + void stop() { + if (server != null) { + server.stop(0); + } + } + + @Test + void postsTheQueryToTheSessionAndReturnsItsData() throws Exception { + serve(200, "{\"data\":{\"f0\":[\"withGpu\"]}}"); + + FormattedNames.QueryRunner runner = + EngineQueries.fromEnvironment(session("s3cret"), "/nonexistent/dagger"); + String data; + try (InputStream in = runner.query(FormattedNames.QUERY, "{\"names\":[\"withGPU\"]}")) { + data = new String(in.readAllBytes(), StandardCharsets.UTF_8); + } + + assertThat(data).isEqualTo("{\"f0\":[\"withGpu\"]}"); + assertThat(requests).hasSize(1); + assertThat(requests.get(0)) + .contains("\"query\":\"query FormatIdentifiers(") + .contains("\"variables\":{\"names\":[\"withGPU\"]}"); + assertThat(authorizations) + .containsExactly( + "Basic " + + Base64.getEncoder().encodeToString("s3cret:".getBytes(StandardCharsets.UTF_8))); + // No client metadata: the engine serves the request at its own version. + assertThat(clientMetadata).containsExactly((String) null); + } + + @Test + void reportsTheErrorsOfTheResponse() throws Exception { + serve( + 200, + "{\"errors\":[{\"message\":\"Cannot query field \\\"formatIdentifiers\\\" on type" + + " \\\"Query\\\".\"}],\"data\":null}"); + + FormattedNames.QueryRunner runner = EngineQueries.fromEnvironment(session("t"), null); + + assertThatThrownBy(() -> runner.query(FormattedNames.QUERY, "{\"names\":[]}")) + .isInstanceOf(IOException.class) + .hasMessageContaining("Cannot query field \"formatIdentifiers\""); + } + + @Test + void reportsAFailedResponse() throws Exception { + serve(401, "unauthorized"); + + FormattedNames.QueryRunner runner = EngineQueries.fromEnvironment(session("t"), null); + + assertThatThrownBy(() -> runner.query(FormattedNames.QUERY, "{\"names\":[]}")) + .isInstanceOf(IOException.class) + .hasMessageContaining("HTTP 401") + .hasMessageContaining("unauthorized"); + } + + @Test + void withoutASessionTheCliIsAsked() throws Exception { + FormattedNames.QueryRunner runner = + EngineQueries.fromEnvironment(Map.of(), "/nonexistent/dagger"); + + assertThatThrownBy(() -> runner.query(FormattedNames.QUERY, "{\"names\":[]}")) + .isInstanceOf(IOException.class) + .hasMessageContaining("/nonexistent/dagger"); + } + + @Test + void theCliGetsTheVariablesAsJson() { + assertThat(DaggerCLIUtils.queryCommand("dagger", "{\"names\":[\"a\"]}")) + .containsExactly("dagger", "query", "-s", "-M", "--var-json", "{\"names\":[\"a\"]}"); + assertThat(DaggerCLIUtils.queryCommand("dagger", null)) + .containsExactly("dagger", "query", "-s", "-M"); + } + + private Map session(String token) { + return Map.of( + EngineQueries.SESSION_PORT, + String.valueOf(server.getAddress().getPort()), + EngineQueries.SESSION_TOKEN, + token); + } + + private void serve(int status, String body) throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext( + "/query", + exchange -> { + requests.add( + new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8)); + authorizations.add(exchange.getRequestHeaders().getFirst("Authorization")); + clientMetadata.add(exchange.getRequestHeaders().getFirst("X-Dagger-Client-Metadata")); + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(status, bytes.length); + try (var out = exchange.getResponseBody()) { + out.write(bytes); + } + }); + server.start(); + } +} diff --git a/sdk/dagger-codegen-maven-plugin/src/test/java/io/dagger/codegen/GeneratorTest.java b/sdk/dagger-codegen-maven-plugin/src/test/java/io/dagger/codegen/GeneratorTest.java index 25a60dd..5c62c5b 100644 --- a/sdk/dagger-codegen-maven-plugin/src/test/java/io/dagger/codegen/GeneratorTest.java +++ b/sdk/dagger-codegen-maven-plugin/src/test/java/io/dagger/codegen/GeneratorTest.java @@ -3,7 +3,13 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.dagger.codegen.introspection.FormattedNames; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonObjectBuilder; +import java.io.ByteArrayInputStream; import java.io.IOException; +import java.io.StringReader; import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -250,7 +256,7 @@ void theSamePlanGeneratesTheSameBytesWhateverOrderItsEntriesAreLaidOutIn() throw Path reversed = Files.createTempDirectory("plan-reversed"); writePlanAt(reversed, CORE_WITH_TWO_TARGETS, target("beta", BETA), target("alpha", ALPHA)); Path secondOut = Files.createTempDirectory("out-reversed"); - new Generator(secondOut, StandardCharsets.UTF_8, VERSION) + new Generator(secondOut, StandardCharsets.UTF_8, VERSION, SCHEMA_NAMES) .generate(GenerationPlan.read(reversed)); assertThat(Files.readString(secondOut.resolve("io/dagger/client/modules/core/Core.java"))) @@ -407,7 +413,8 @@ void aLocalTargetOutsideTheWorkspaceRootIsRefused() throws Exception { } private void generate() throws IOException { - new Generator(out, StandardCharsets.UTF_8, VERSION).generate(GenerationPlan.read(plan)); + new Generator(out, StandardCharsets.UTF_8, VERSION, SCHEMA_NAMES) + .generate(GenerationPlan.read(plan)); } private record Entry(String module, String schema, String descriptor) {} @@ -570,6 +577,19 @@ public CharSequence getCharContent(boolean ignoreEncodingErrors) { private static final String VERSION = "v1.0.0-beta.18"; + /** Formats every name as itself, so these tests need no engine. */ + private static final FormattedNames.QueryRunner SCHEMA_NAMES = + (query, variables) -> { + JsonArray names = + Json.createReader(new StringReader(variables)).readObject().getJsonArray("names"); + JsonObjectBuilder naming = Json.createObjectBuilder(); + for (int i = 0; i < FormattedNames.FORMATS.size(); i++) { + naming.add("f" + i, names); + } + String data = Json.createObjectBuilder().add("naming", naming).build().toString(); + return new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + }; + private static String owned(String module) { return "\"directives\": [{\"name\": \"sourceMap\", \"args\": [{\"name\": \"module\"," + " \"value\": \"\\\"" diff --git a/sdk/dagger-codegen-maven-plugin/src/test/java/io/dagger/codegen/introspection/FormattedNamesCodegenTest.java b/sdk/dagger-codegen-maven-plugin/src/test/java/io/dagger/codegen/introspection/FormattedNamesCodegenTest.java new file mode 100644 index 0000000..eb208c0 --- /dev/null +++ b/sdk/dagger-codegen-maven-plugin/src/test/java/io/dagger/codegen/introspection/FormattedNamesCodegenTest.java @@ -0,0 +1,302 @@ +package io.dagger.codegen.introspection; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.dagger.codegen.GenerationPlan; +import io.dagger.codegen.Generator; +import jakarta.json.Json; +import jakarta.json.JsonArrayBuilder; +import jakarta.json.JsonObject; +import jakarta.json.JsonObjectBuilder; +import jakarta.json.JsonString; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * Java identifiers follow the names the engine formatted, while everything sent to the API keeps + * the schema's names. + */ +class FormattedNamesCodegenTest { + @TempDir Path output; + @TempDir Path plans; + + /** What the fake engine was asked: one version per request. */ + private final List versions = new ArrayList<>(); + + @Test + void namesJavaIdentifiersFromFormattedNames() throws Exception { + generate(schema(), engine()); + + // The engine was asked once, with the schema's own version. + assertThat(versions).containsExactly("v1.0.0-beta.21"); + + String container = read("Container"); + // Methods are camelCase with acronyms written like words, and select the schema's fields. + assertThat(container) + .contains("public String htmlUrl()") + .contains("this.queryBuilder.chain(\"htmlURL\")") + .contains("@JsonbProperty(\"htmlURL\")") + .contains("private String htmlUrl;") + .contains("public String asJson()") + .contains("this.queryBuilder.chain(\"asJSON\")") + .contains("public List prerequisiteShas()") + .contains("public Container withGpu(List devices)") + .contains("builder.add(\"devices\", devices)") + .contains("this.queryBuilder.chain(\"withGPU\", fieldArgs)") + .contains("public Container withMcpServer(String name)") + .contains("public Container withMcpServer(String name, WithMCPServerArguments optArgs)") + .contains("this.queryBuilder.chain(\"withMCPServer\", fieldArgs)") + .contains("public Container importTarball(String source)") + .contains("this.queryBuilder.chain(\"import\", fieldArgs)"); + // Optional arguments keep their class, and send the schema's argument names. + assertThat(container) + .contains("public static class WithMCPServerArguments") + .contains("private Boolean insecureSkipTlsVerify;") + .contains( + "public WithMCPServerArguments withInsecureSkipTlsVerify(Boolean insecureSkipTlsVerify)") + .contains("builder.add(\"insecureSkipTLSVerify\", this.insecureSkipTlsVerify)"); + // The old names stay as deprecated aliases. + assertThat(container) + .contains("public String htmlURL()") + .contains("return htmlUrl();") + .contains("public String asJSON()") + .contains("return asJson();") + .contains("public List prerequisiteSHAs()") + .contains("public Container withGPU(List devices)") + .contains("return withGpu(devices);") + .contains("public Container withMCPServer(String name)") + .contains("public Container withMCPServer(String name, WithMCPServerArguments optArgs)") + .contains("return withMcpServer(name, optArgs);") + .contains( + "public WithMCPServerArguments withInsecureSkipTLSVerify(Boolean insecureSkipTlsVerify)") + .contains("return withInsecureSkipTlsVerify(insecureSkipTlsVerify);") + .contains("@deprecated Use {@link #withMcpServer} instead.") + .doesNotContain("importTarball_"); + + // Interfaces declare the new name, and keep the old one as a default method. + assertThat(read("Node")) + .contains("String htmlUrl() throws") + .contains("default String htmlURL() throws") + .contains("return htmlUrl();"); + assertThat(read("NodeClient")) + .contains("public String htmlUrl()") + .contains("this.queryBuilder.chain(\"htmlURL\")") + .doesNotContain("String htmlURL()"); + + // Input objects send and serialize the schema's field names. + assertThat(read("BuildArg")) + .contains("@JsonbProperty(\"insecureSkipTLSVerify\")") + .contains("private Boolean insecureSkipTlsVerify;") + .contains("public Boolean isInsecureSkipTlsVerify()") + .contains("public void setInsecureSkipTlsVerify(Boolean insecureSkipTlsVerify)") + .contains("public BuildArg withInsecureSkipTlsVerify(Boolean insecureSkipTlsVerify)") + .contains("map.put(\"insecureSkipTLSVerify\", this.insecureSkipTlsVerify)") + .contains("public Boolean isInsecureSkipTLSVerify()") + .contains("public void setInsecureSkipTLSVerify(Boolean insecureSkipTlsVerify)") + .contains("public BuildArg withInsecureSkipTLSVerify(Boolean insecureSkipTlsVerify)") + .contains("private String name;") + .doesNotContain("@JsonbProperty(\"name\")") + .doesNotContain("@GraphQLType"); + + // Enum constants are SCREAMING_SNAKE_CASE, carrying the schema values they go over the wire + // as. The old constants stay as deprecated aliases. + assertThat(read("FunctionCachePolicy")) + .contains("public enum FunctionCachePolicy implements GraphQLEnum") + .contains("@JsonbTypeSerializer(GraphQLEnumSerializer.class)") + .contains("@JsonbTypeDeserializer(GraphQLEnumDeserializer.class)") + .contains("DEFAULT(\"Default\")") + .contains("PER_SESSION(\"PerSession\")") + .contains("public static final FunctionCachePolicy PerSession = PER_SESSION;") + .contains("public static final FunctionCachePolicy Default = DEFAULT;") + .contains("@deprecated Use {@link #PER_SESSION} instead.") + .contains("public String graphQLValue()") + .contains("public boolean hasGraphQLValue(String value)") + .doesNotContain("@GraphQLType"); + // A value and its alias share a constant, sent as the first value and read back as either. + assertThat(read("ImageLayerCompression")) + .contains("GZIP(\"Gzip\", \"GZIP\")") + .contains("TCP(\"TCP\")") + .contains("public static final ImageLayerCompression Gzip = GZIP;") + .doesNotContain("ImageLayerCompression GZIP =") + .doesNotContain("ImageLayerCompression TCP ="); + assertThat(container) + .contains("public ImageLayerCompression compression()") + .contains("return nextQueryBuilder.executeQuery(ImageLayerCompression.class)"); + + // Classes follow Java's convention, and name their GraphQL type when it differs. + assertThat(read("JsonValue")) + .contains("@GraphQLType(\"JSONValue\")") + .contains("public class JsonValue implements IDAble") + .contains("public Json contents()") + .contains("chainNode(\"JSONValue\", new Id(id))"); + assertThat(read("Json")) + .contains("@GraphQLType(\"JSON\")") + .contains("public class Json extends Scalar"); + assertThat(read("Id")).contains("@GraphQLType(\"ID\")").contains("public class Id extends"); + assertThat(container) + .contains("public class Container implements Node, IDAble") + .doesNotContain("@GraphQLType") + // Lists of objects instantiate the classes, but select the GraphQL type. + .contains("public List values()") + .contains("nextQueryBuilder.executeObjectListQuery(\"JSONValue\")") + .contains("new JsonValue(qb)"); + // Loading by ID reads the class's GraphQL type. + assertThat(read("Core")) + .contains("public T loadObjectFromID(Class clazz, Id id)") + .contains("GraphQLType graphQLType = clazz.getAnnotation(GraphQLType.class);") + .contains("this.queryBuilder.chainNode(typeName, id)") + .doesNotContain("@GraphQLType"); + // JSON conversions go through the enums' values. + assertThat(read("JsonConverter")) + .contains("public static Json toJSON(Object object)") + .contains("GraphQLEnums.value((Enum) object)") + .contains("GraphQLEnums.valueOf(clazz, jsonb.fromJson(json, String.class))"); + assertThat(output.resolve(corePath("JSON"))).doesNotExist(); + } + + /** A names file beside the schema stands in for the engine. */ + @Test + void readsANamesFileInsteadOfAskingTheEngine() throws Exception { + Path plan = plan(schema()); + Files.copy(resource("formatted-names.names.json"), plan.resolve("core/names.json")); + new Generator( + output, + StandardCharsets.UTF_8, + "v1.0.0-beta.28", + (query, variables) -> { + throw new AssertionError("asked the engine despite a names file"); + }) + .generate(GenerationPlan.read(plan)); + + assertThat(read("Container")).contains("public String htmlUrl()"); + assertThat(read("JsonValue")).contains("@GraphQLType(\"JSONValue\")"); + } + + /** + * An engine that can't format the names fails codegen, rather than generating the schema's names: + * that would be a different API from the one the schema names. + */ + @Test + void failsWhenTheEngineCannotFormatTheNames() throws Exception { + assertThatThrownBy( + () -> + generate( + schema(), + (query, variables) -> { + throw new IOException("Cannot query field \"naming\""); + })) + .isInstanceOf(IOException.class) + .hasMessageContaining("Query.naming") + .hasMessageContaining("v1.0.0-beta.21") + .hasMessageContaining("Cannot query field \"naming\""); + + assertThatThrownBy( + () -> + generate( + schema(), + (query, variables) -> + new ByteArrayInputStream("{\"f0\":[]}".getBytes(StandardCharsets.UTF_8)))) + .isInstanceOf(IOException.class) + .hasMessageContaining("could not format"); + assertThat(output.resolve(corePath("Container"))).doesNotExist(); + } + + @Test + void keepsSchemaNamesMissingFromTheNames() throws Exception { + Map> names = names(); + names.get(FormattedNames.MEMBERS).remove("withMCPServer"); + names.get(FormattedNames.TYPES).remove("JSONValue"); + names.get(FormattedNames.ENUM_VALUES).remove("PerSession"); + generate(schema(), engine(names)); + + // Its argument is still renamed. + assertThat(read("Container")) + .contains("public Container withMCPServer(String name)") + .contains("public static class WithMCPServerArguments") + .contains("private Boolean insecureSkipTlsVerify;") + .contains("public Container withGpu(List devices)") + .contains("public List values()") + .doesNotContain("withMcpServer"); + assertThat(read("JSONValue")).doesNotContain("GraphQLType").contains("IDAble"); + assertThat(read("FunctionCachePolicy")) + .contains("DEFAULT(\"Default\")") + .contains("PerSession(\"PerSession\")") + .doesNotContain("PER_SESSION"); + } + + private void generate(byte[] schema, FormattedNames.QueryRunner engine) throws Exception { + new Generator(output, StandardCharsets.UTF_8, "v1.0.0-beta.28", engine) + .generate(GenerationPlan.read(plan(schema))); + } + + /** A plan generating core alone from the schema. */ + private Path plan(byte[] schema) throws IOException { + Path plan = Files.createTempDirectory(plans, "plan"); + Files.createDirectories(plan.resolve("core")); + Files.write(plan.resolve("core/schema.json"), schema); + return plan; + } + + /** The fixture schema. */ + private static byte[] schema() throws IOException { + try (InputStream in = resource("formatted-names.json")) { + return in.readAllBytes(); + } + } + + private FormattedNames.QueryRunner engine() throws Exception { + return engine(names()); + } + + /** + * A fake engine answering naming's formatIdentifiers from a names file, and the name itself for a + * name the file doesn't have. + */ + private FormattedNames.QueryRunner engine(Map> names) { + return (query, variables) -> { + assertThat(query).contains("naming(version: $version)").contains("formatIdentifiers("); + JsonObject vars = Json.createReader(new StringReader(variables)).readObject(); + versions.add(vars.isNull("version") ? null : vars.getString("version")); + List requested = + vars.getJsonArray("names").stream().map(v -> ((JsonString) v).getString()).toList(); + JsonObjectBuilder data = Json.createObjectBuilder(); + for (int i = 0; i < FormattedNames.FORMATS.size(); i++) { + Map formatted = names.getOrDefault(FormattedNames.FORMATS.get(i), Map.of()); + JsonArrayBuilder out = Json.createArrayBuilder(); + requested.forEach(name -> out.add(formatted.getOrDefault(name, name))); + data.add("f" + i, out); + } + String response = Json.createObjectBuilder().add("naming", data).build().toString(); + return new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8)); + }; + } + + private static Map> names() throws Exception { + try (InputStream in = resource("formatted-names.names.json")) { + return FormattedNames.read(in); + } + } + + private String read(String className) throws Exception { + return Files.readString(output.resolve(corePath(className))); + } + + private static String corePath(String className) { + return Generator.CORE_PACKAGE.replace('.', '/') + "/" + className + ".java"; + } + + private static InputStream resource(String name) { + return FormattedNamesCodegenTest.class.getResourceAsStream("/schemas/" + name); + } +} diff --git a/sdk/dagger-codegen-maven-plugin/src/test/java/io/dagger/codegen/introspection/FormattedNamesTest.java b/sdk/dagger-codegen-maven-plugin/src/test/java/io/dagger/codegen/introspection/FormattedNamesTest.java new file mode 100644 index 0000000..7100f74 --- /dev/null +++ b/sdk/dagger-codegen-maven-plugin/src/test/java/io/dagger/codegen/introspection/FormattedNamesTest.java @@ -0,0 +1,186 @@ +package io.dagger.codegen.introspection; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import jakarta.json.Json; +import jakarta.json.JsonArrayBuilder; +import jakarta.json.JsonObject; +import jakarta.json.JsonObjectBuilder; +import jakarta.json.JsonReader; +import jakarta.json.JsonString; +import jakarta.json.JsonValue; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +class FormattedNamesTest { + + /** A request FormattedNames sent: the GraphQL document and its variables. */ + private record Request(String query, JsonObject variables) {} + + /** + * Fakes the engine: answers each formatIdentifiers alias (f0, f1, ...) under naming with each + * name prefixed by the alias, and records the requests. + */ + private static FormattedNames.QueryRunner engine(List requests) { + return (query, variables) -> { + JsonObject vars = read(variables); + requests.add(new Request(query, vars)); + JsonObjectBuilder data = Json.createObjectBuilder(); + for (int i = 0; i < FormattedNames.FORMATS.size(); i++) { + JsonArrayBuilder out = Json.createArrayBuilder(); + for (JsonValue name : vars.getJsonArray("names")) { + out.add("f" + i + "_" + ((JsonString) name).getString()); + } + data.add("f" + i, out); + } + return stream(Json.createObjectBuilder().add("naming", data).build().toString()); + }; + } + + @Test + void formatsNamesWithTheNamingOfTheSchemaVersion() throws Exception { + List requests = new ArrayList<>(); + Map> names = + FormattedNames.fetch(schema("v1.0.0-beta.28"), engine(requests)); + + assertThat(requests).hasSize(1); + Request request = requests.get(0); + // The names go as a variable, in one request formatting them in every format Java uses: + // camelCase members and PascalCase classes with acronyms written like words, and + // SCREAMING_SNAKE_CASE enum constants, all with the dictionary of the schema's version. + assertThat(request.query()) + .contains("$names: [String!]!, $version: String") + .contains("naming(version: $version) {") + .contains("f0: formatIdentifiers(names: $names, casing: CAMEL, acronyms: CAPITALIZED)") + .contains("f1: formatIdentifiers(names: $names, casing: PASCAL, acronyms: CAPITALIZED)") + .contains( + "f2: formatIdentifiers(names: $names, casing: SCREAMING_SNAKE, acronyms: UPPERCASE)"); + assertThat(request.variables().getString("version")).isEqualTo("v1.0.0-beta.28"); + assertThat(FormattedNames.FORMATS) + .containsExactly(FormattedNames.MEMBERS, FormattedNames.TYPES, FormattedNames.ENUM_VALUES); + // Type, field, argument and enum value names, sorted, leaving out introspection names and + // names with no letters or digits. + assertThat(request.variables().getJsonArray("names").getValuesAs(JsonString::getString)) + .containsExactly("Kind", "Query", "SHARED", "htmlURL"); + + // Results map back to the names in input order, keyed by format like a names file. + assertThat(names).containsOnlyKeys(FormattedNames.FORMATS); + assertThat(names.get("CAMEL:CAPITALIZED")) + .containsEntry("htmlURL", "f0_htmlURL") + .containsEntry("SHARED", "f0_SHARED") + .hasSize(4); + assertThat(names.get("PASCAL:CAPITALIZED")).containsEntry("Kind", "f1_Kind").hasSize(4); + assertThat(names.get("SCREAMING_SNAKE:UPPERCASE")) + .containsEntry("SHARED", "f2_SHARED") + .hasSize(4); + } + + /** A schema without a version leaves the dictionary to the engine. */ + @Test + void sendsANullVersionWithoutASchemaVersion() throws Exception { + List requests = new ArrayList<>(); + FormattedNames.fetch(schema(null), engine(requests)); + + assertThat(requests.get(0).variables().isNull("version")).isTrue(); + } + + @Test + void batchesNames() throws Exception { + StringBuilder fields = new StringBuilder(); + // 4000 names of 20 bytes: more than BATCH_BYTES encoded. + for (int i = 0; i < 4000; i++) { + fields.append(String.format(",{\"name\":\"field%015d\",\"args\":[]}", i)); + } + String json = + "{\"__schema\":{\"queryType\":{\"name\":\"Query\"},\"types\":[{\"kind\":\"OBJECT\"," + + "\"name\":\"Query\",\"fields\":[{\"name\":\"formatIdentifiers\",\"args\":[]}" + + fields + + "]}]}}"; + List requests = new ArrayList<>(); + Map> names = + FormattedNames.fetch(json.getBytes(StandardCharsets.UTF_8), engine(requests)); + + assertThat(requests).hasSize(2); + for (Request request : requests) { + assertThat(request.variables().getJsonArray("names").toString().length()) + .isLessThanOrEqualTo(FormattedNames.BATCH_BYTES); + } + // Query, formatIdentifiers and field0..field3999. + assertThat(names.get(FormattedNames.MEMBERS)).hasSize(4002).containsEntry("Query", "f0_Query"); + } + + @Test + void batchesAtLeastOneName() { + assertThat(FormattedNames.batches(List.of(), 10)).isEmpty(); + assertThat(FormattedNames.batches(List.of("ab", "cd", "efghijklmn", "o"), 12)) + .containsExactly(List.of("ab", "cd"), List.of("efghijklmn"), List.of("o")); + } + + @Test + void rejectsAShortAnswer() { + assertThatThrownBy( + () -> + FormattedNames.fetch( + schema("v1.0.0-beta.28"), + (query, variables) -> + stream("{\"naming\":{\"f0\":[\"x\"],\"f1\":[\"x\"],\"f2\":[\"x\"]}}"))) + .isInstanceOf(IOException.class) + .hasMessageContaining("sent 4 names, got 1 back"); + } + + @Test + void readsTheNamesFile() throws Exception { + Map> names = + FormattedNames.read( + stream( + "{\"CAMEL:CAPITALIZED\":{\"withGPU\":\"withGpu\"}," + + "\"PASCAL:CAPITALIZED\":{\"JSONValue\":\"JsonValue\"}," + + "\"SCREAMING_SNAKE:UPPERCASE\":{\"PerSession\":\"PER_SESSION\"}," + + "\"SNAKE:UPPERCASE\":{\"withGPU\":\"with_gpu\"}}")); + // The formats Java codegen uses, leaving the others out. + assertThat(names).containsOnlyKeys(FormattedNames.FORMATS); + assertThat(names.get(FormattedNames.MEMBERS)).containsExactly(Map.entry("withGPU", "withGpu")); + assertThat(names.get(FormattedNames.TYPES)) + .containsExactly(Map.entry("JSONValue", "JsonValue")); + assertThat(names.get(FormattedNames.ENUM_VALUES)) + .containsExactly(Map.entry("PerSession", "PER_SESSION")); + + // A file with only some of the formats has only those. + assertThat(FormattedNames.read(stream("{\"CAMEL:CAPITALIZED\":{\"a\":\"a\"}}"))) + .containsOnlyKeys(FormattedNames.MEMBERS); + + assertThat(FormattedNames.read(stream("{}"))).isNull(); + } + + private static byte[] schema(String version) { + String schemaVersion = version == null ? "" : "\"__schemaVersion\":\"" + version + "\","; + return ("{" + + schemaVersion + + "\"__schema\":{\"queryType\":{\"name\":\"Query\"},\"types\":[" + + "{\"kind\":\"OBJECT\",\"name\":\"Query\",\"fields\":[" + + "{\"name\":\"htmlURL\",\"args\":[]}]}," + + "{\"kind\":\"ENUM\",\"name\":\"Kind\",\"enumValues\":[{\"name\":\"SHARED\"}]}," + + "{\"kind\":\"OBJECT\",\"name\":\"__Type\",\"fields\":[{\"name\":\"possibleTypes\"}]}," + + "{\"kind\":\"SCALAR\",\"name\":\"_\"}" + + "]}}") + .getBytes(StandardCharsets.UTF_8); + } + + private static InputStream stream(String json) { + return new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)); + } + + private static JsonObject read(String json) { + try (JsonReader reader = Json.createReader(new StringReader(json))) { + return reader.readObject(); + } + } +} diff --git a/sdk/dagger-codegen-maven-plugin/src/test/resources/schemas/formatted-names.json b/sdk/dagger-codegen-maven-plugin/src/test/resources/schemas/formatted-names.json new file mode 100644 index 0000000..da18432 --- /dev/null +++ b/sdk/dagger-codegen-maven-plugin/src/test/resources/schemas/formatted-names.json @@ -0,0 +1,156 @@ +{ + "__schemaVersion": "v1.0.0-beta.21", + "__schema": { + "queryType": {"name": "Query"}, + "types": [ + { + "kind": "OBJECT", "name": "Query", "description": "The root of the API.", + "fields": [ + { + "name": "container", "description": "Creates a scratch container.", "args": [], + "type": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "OBJECT", "name": "Container", "ofType": null}}, + "isDeprecated": false, "deprecationReason": null, "directives": [] + } + ], + "interfaces": [] + }, + { + "kind": "INTERFACE", "name": "Node", "description": "An object with an ID.", + "fields": [ + { + "name": "id", "description": "The node's ID.", "args": [], + "type": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "SCALAR", "name": "ID", "ofType": null}}, + "isDeprecated": false, "deprecationReason": null, "directives": [] + }, + { + "name": "htmlURL", "description": "A web page for the node.", "args": [], + "type": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "SCALAR", "name": "String", "ofType": null}}, + "isDeprecated": false, "deprecationReason": null, "directives": [] + } + ], + "possibleTypes": [{"kind": "OBJECT", "name": "Container", "ofType": null}] + }, + { + "kind": "OBJECT", "name": "Container", "description": "A container.", + "interfaces": [{"kind": "INTERFACE", "name": "Node", "ofType": null}], + "fields": [ + { + "name": "id", "description": "The container's ID.", "args": [], + "type": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "SCALAR", "name": "ID", "ofType": null}}, + "isDeprecated": false, "deprecationReason": null, "directives": [] + }, + { + "name": "htmlURL", "description": "A web page for the container.", "args": [], + "type": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "SCALAR", "name": "String", "ofType": null}}, + "isDeprecated": false, "deprecationReason": null, "directives": [] + }, + { + "name": "asJSON", "description": "The container as JSON.", "args": [], + "type": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "SCALAR", "name": "String", "ofType": null}}, + "isDeprecated": false, "deprecationReason": null, "directives": [] + }, + { + "name": "prerequisiteSHAs", "description": "Commits the container needs.", "args": [], + "type": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "LIST", "name": null, "ofType": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "SCALAR", "name": "String", "ofType": null}}}}, + "isDeprecated": false, "deprecationReason": null, "directives": [] + }, + { + "name": "withGPU", "description": "Adds GPUs.", + "args": [ + { + "name": "devices", "description": "The GPUs.", "defaultValue": null, "directives": [], + "type": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "LIST", "name": null, "ofType": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "SCALAR", "name": "String", "ofType": null}}}} + } + ], + "type": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "OBJECT", "name": "Container", "ofType": null}}, + "isDeprecated": false, "deprecationReason": null, "directives": [] + }, + { + "name": "withMCPServer", "description": "Adds an MCP server.", + "args": [ + { + "name": "name", "description": "The server's name.", "defaultValue": null, "directives": [], + "type": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "SCALAR", "name": "String", "ofType": null}} + }, + { + "name": "insecureSkipTLSVerify", "description": "Skip TLS verification.", "defaultValue": "false", "directives": [], + "type": {"kind": "SCALAR", "name": "Boolean", "ofType": null} + } + ], + "type": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "OBJECT", "name": "Container", "ofType": null}}, + "isDeprecated": false, "deprecationReason": null, "directives": [] + }, + { + "name": "import", "description": "Imports a tarball.", + "args": [ + { + "name": "source", "description": "The tarball.", "defaultValue": null, "directives": [], + "type": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "SCALAR", "name": "String", "ofType": null}} + } + ], + "type": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "OBJECT", "name": "Container", "ofType": null}}, + "isDeprecated": false, "deprecationReason": null, "directives": [] + }, + { + "name": "values", "description": "The container's values.", "args": [], + "type": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "LIST", "name": null, "ofType": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "OBJECT", "name": "JSONValue", "ofType": null}}}}, + "isDeprecated": false, "deprecationReason": null, "directives": [] + }, + { + "name": "compression", "description": "The container's compression.", "args": [], + "type": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "ENUM", "name": "ImageLayerCompression", "ofType": null}}, + "isDeprecated": false, "deprecationReason": null, "directives": [] + } + ] + }, + { + "kind": "OBJECT", "name": "JSONValue", "description": "A JSON value.", + "interfaces": [], + "fields": [ + { + "name": "id", "description": "The value's ID.", "args": [], + "type": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "SCALAR", "name": "ID", "ofType": null}}, + "isDeprecated": false, "deprecationReason": null, "directives": [] + }, + { + "name": "contents", "description": "The value as JSON.", "args": [], + "type": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "SCALAR", "name": "JSON", "ofType": null}}, + "isDeprecated": false, "deprecationReason": null, "directives": [] + } + ] + }, + { + "kind": "INPUT_OBJECT", "name": "BuildArg", "description": "A build argument.", + "inputFields": [ + { + "name": "name", "description": "The argument's name.", "defaultValue": null, "directives": [], + "type": {"kind": "NON_NULL", "name": null, "ofType": {"kind": "SCALAR", "name": "String", "ofType": null}} + }, + { + "name": "insecureSkipTLSVerify", "description": "Skip TLS verification.", "defaultValue": null, "directives": [], + "type": {"kind": "SCALAR", "name": "Boolean", "ofType": null} + } + ] + }, + { + "kind": "ENUM", "name": "FunctionCachePolicy", "description": "A cache policy.", + "enumValues": [ + {"name": "Default", "description": "The default.", "isDeprecated": false, "deprecationReason": null}, + {"name": "PerSession", "description": "Once per session.", "isDeprecated": false, "deprecationReason": null} + ] + }, + { + "kind": "ENUM", "name": "ImageLayerCompression", "description": "A compression.", + "enumValues": [ + {"name": "Gzip", "description": "Gzip.", "isDeprecated": false, "deprecationReason": null}, + {"name": "TCP", "description": "Not a compression.", "isDeprecated": false, "deprecationReason": null}, + {"name": "GZIP", "description": "Gzip, again.", "isDeprecated": false, "deprecationReason": null} + ] + }, + {"kind": "SCALAR", "name": "ID", "description": "An ID."}, + {"kind": "SCALAR", "name": "JSON", "description": "A JSON value."}, + {"kind": "SCALAR", "name": "String", "description": "A string."}, + {"kind": "SCALAR", "name": "Boolean", "description": "A boolean."} + ] + } +} diff --git a/sdk/dagger-codegen-maven-plugin/src/test/resources/schemas/formatted-names.names.json b/sdk/dagger-codegen-maven-plugin/src/test/resources/schemas/formatted-names.names.json new file mode 100644 index 0000000..658258b --- /dev/null +++ b/sdk/dagger-codegen-maven-plugin/src/test/resources/schemas/formatted-names.names.json @@ -0,0 +1,101 @@ +{ + "CAMEL:CAPITALIZED": { + "Boolean": "boolean", + "BuildArg": "buildArg", + "Container": "container", + "Default": "default", + "FunctionCachePolicy": "functionCachePolicy", + "GZIP": "gzip", + "Gzip": "gzip", + "ID": "id", + "ImageLayerCompression": "imageLayerCompression", + "JSON": "json", + "JSONValue": "jsonValue", + "Node": "node", + "PerSession": "perSession", + "Query": "query", + "String": "string", + "TCP": "tcp", + "asJSON": "asJson", + "compression": "compression", + "container": "container", + "contents": "contents", + "devices": "devices", + "htmlURL": "htmlUrl", + "id": "id", + "import": "import", + "insecureSkipTLSVerify": "insecureSkipTlsVerify", + "name": "name", + "prerequisiteSHAs": "prerequisiteShas", + "source": "source", + "values": "values", + "withGPU": "withGpu", + "withMCPServer": "withMcpServer" + }, + "PASCAL:CAPITALIZED": { + "Boolean": "Boolean", + "BuildArg": "BuildArg", + "Container": "Container", + "Default": "Default", + "FunctionCachePolicy": "FunctionCachePolicy", + "GZIP": "Gzip", + "Gzip": "Gzip", + "ID": "Id", + "ImageLayerCompression": "ImageLayerCompression", + "JSON": "Json", + "JSONValue": "JsonValue", + "Node": "Node", + "PerSession": "PerSession", + "Query": "Query", + "String": "String", + "TCP": "Tcp", + "asJSON": "AsJson", + "compression": "Compression", + "container": "Container", + "contents": "Contents", + "devices": "Devices", + "htmlURL": "HtmlUrl", + "id": "Id", + "import": "Import", + "insecureSkipTLSVerify": "InsecureSkipTlsVerify", + "name": "Name", + "prerequisiteSHAs": "PrerequisiteShas", + "source": "Source", + "values": "Values", + "withGPU": "WithGpu", + "withMCPServer": "WithMcpServer" + }, + "SCREAMING_SNAKE:UPPERCASE": { + "Boolean": "BOOLEAN", + "BuildArg": "BUILD_ARG", + "Container": "CONTAINER", + "Default": "DEFAULT", + "FunctionCachePolicy": "FUNCTION_CACHE_POLICY", + "GZIP": "GZIP", + "Gzip": "GZIP", + "ID": "ID", + "ImageLayerCompression": "IMAGE_LAYER_COMPRESSION", + "JSON": "JSON", + "JSONValue": "JSON_VALUE", + "Node": "NODE", + "PerSession": "PER_SESSION", + "Query": "QUERY", + "String": "STRING", + "TCP": "TCP", + "asJSON": "AS_JSON", + "compression": "COMPRESSION", + "container": "CONTAINER", + "contents": "CONTENTS", + "devices": "DEVICES", + "htmlURL": "HTML_URL", + "id": "ID", + "import": "IMPORT", + "insecureSkipTLSVerify": "INSECURE_SKIP_TLS_VERIFY", + "name": "NAME", + "prerequisiteSHAs": "PREREQUISITE_SHAS", + "source": "SOURCE", + "values": "VALUES", + "withGPU": "WITH_GPU", + "withMCPServer": "WITH_MCP_SERVER" + } +} diff --git a/sdk/dagger-java-annotation-processor/src/main/java/io/dagger/annotation/processor/DaggerModuleAnnotationProcessor.java b/sdk/dagger-java-annotation-processor/src/main/java/io/dagger/annotation/processor/DaggerModuleAnnotationProcessor.java index 3cd669b..87d0f0b 100644 --- a/sdk/dagger-java-annotation-processor/src/main/java/io/dagger/annotation/processor/DaggerModuleAnnotationProcessor.java +++ b/sdk/dagger-java-annotation-processor/src/main/java/io/dagger/annotation/processor/DaggerModuleAnnotationProcessor.java @@ -19,8 +19,6 @@ import io.dagger.client.modules.core.FunctionCachePolicy; import io.dagger.client.modules.core.FunctionCall; import io.dagger.client.modules.core.FunctionCallArgValue; -import io.dagger.client.modules.core.ID; -import io.dagger.client.modules.core.JSON; import io.dagger.client.modules.core.JsonConverter; import io.dagger.client.modules.core.TypeDef; import io.dagger.client.telemetry.Telemetry; @@ -413,11 +411,13 @@ static String quoteIfString(String value, String type) { } static JavaFile generate(ModuleInfo moduleInfo) { + ClassName idClass = DaggerType.ID_CLASS; + ClassName jsonClass = DaggerType.JSON_CLASS; try { var rm = MethodSpec.methodBuilder("register") .addModifiers(Modifier.PRIVATE) - .returns(ID.class) + .returns(idClass) .addException(ExecutionException.class) .addException(DaggerQueryException.class) .addException(InterruptedException.class) @@ -506,13 +506,15 @@ static JavaFile generate(ModuleInfo moduleInfo) { var im = MethodSpec.methodBuilder("invoke") .addModifiers(Modifier.PRIVATE, Modifier.STATIC) - .returns(JSON.class) + .returns(jsonClass) .addException(Exception.class) - .addParameter(JSON.class, "parentJson") + .addParameter(jsonClass, "parentJson") .addParameter(String.class, "parentName") .addParameter(String.class, "fnName") .addParameter( - ParameterizedTypeName.get(Map.class, String.class, JSON.class), "inputArgs"); + ParameterizedTypeName.get( + ClassName.get(Map.class), ClassName.get(String.class), jsonClass), + "inputArgs"); var firstObj = true; for (var objectInfo : moduleInfo.objects()) { if (firstObj) { @@ -529,7 +531,7 @@ static JavaFile generate(ModuleInfo moduleInfo) { // The Dang entrypoint declares a constructor for the entry object, which the legacy // runtime constructs itself from its empty state. im.beginControlFlow("if (fnName.equals(\"\"))") - .addStatement("return $T.from($S)", JSON.class, "{}") + .addStatement("return $T.from($S)", jsonClass, "{}") .endControlFlow(); im.addStatement("$T clazz = Class.forName($S)", Class.class, objectInfo.qualifiedName()) .addStatement( @@ -584,9 +586,10 @@ static JavaFile generate(ModuleInfo moduleInfo) { .beginControlFlow( "if (args.length > 0 && args[0].equals($S))", "engine-call") .addStatement( - "$T.exit($T.engineCall(args, Entrypoint::invoke))", + "$T.exit($T.engineCall(args, $T::from, Entrypoint::invoke))", System.class, - ModuleDispatcher.class) + ModuleDispatcher.class, + jsonClass) .endControlFlow() .beginControlFlow( "try ($T telemetry = new $T())", Telemetry.class, Telemetry.class) @@ -606,7 +609,7 @@ static JavaFile generate(ModuleInfo moduleInfo) { .beginControlFlow("try") .addStatement("$T parentName = fnCall.parentName()", String.class) .addStatement("$T fnName = fnCall.name()", String.class) - .addStatement("$T parentJson = fnCall.parent()", JSON.class) + .addStatement("$T parentJson = fnCall.parent()", jsonClass) .addStatement( "$T fnArgs = fnCall.inputArgs()", ParameterizedTypeName.get(List.class, FunctionCallArgValue.class)) @@ -614,16 +617,16 @@ static JavaFile generate(ModuleInfo moduleInfo) { "$T<$T, $T> inputArgs = new $T<>()", Map.class, String.class, - JSON.class, + jsonClass, HashMap.class) .beginControlFlow( "for ($T fnArg : fnArgs)", FunctionCallArgValue.class) .addStatement("inputArgs.put(fnArg.name(), fnArg.value())") .endControlFlow() .addCode("\n") - .addStatement("$T result", JSON.class) + .addStatement("$T result", jsonClass) .beginControlFlow("if (parentName.isEmpty())") - .addStatement("$T modID = register()", ID.class) + .addStatement("$T modID = register()", idClass) .addStatement("result = $T.toJSON(modID)", JsonConverter.class) .nextControlFlow("else") .addStatement( @@ -766,11 +769,12 @@ private static CodeBlock functionInvoke(ObjectInfo objectInfo, FunctionInfo fnIn } else if (objectInfo.isCollection() && !isConstructor) { CodeBlock value = returnType.valueForSerialization("res"); code.addStatement( - "return $T.collectionResult(parentJson, obj, $L, $T.toJSON($L))", + "return $T.collectionResult(parentJson, obj, $L, $T.toJSON($L), $T::from)", ModuleDispatcher.class, value, JsonConverter.class, - value); + value, + DaggerType.JSON_CLASS); } else { code.addStatement( "return $T.toJSON($L)", JsonConverter.class, returnType.valueForSerialization("res")); @@ -779,6 +783,20 @@ private static CodeBlock functionInvoke(ObjectInfo objectInfo, FunctionInfo fnIn return code.build(); } + /** + * The name of a FunctionCachePolicy constant in the SDK this processor runs with: Java's + * convention ({@code PER_SESSION}) when the schema's names were formatted, else the schema's + * spelling ({@code PerSession}). Either reaches the same value. + */ + static String cachePolicy(String conventionName, String schemaName) { + try { + FunctionCachePolicy.class.getField(conventionName); + return conventionName; + } catch (NoSuchFieldException e) { + return schemaName; + } + } + public static CodeBlock withFunction( Set enums, ObjectInfo objectInfo, FunctionInfo fnInfo) throws ClassNotFoundException { boolean isConstructor = fnInfo.name().equals(""); @@ -800,14 +818,20 @@ public static CodeBlock withFunction( switch (fnInfo.cache()) { case "" -> {} case "never" -> - code.add("\n .withCachePolicy($T.Never)", FunctionCachePolicy.class); + code.add( + "\n .withCachePolicy($T.$L)", + FunctionCachePolicy.class, + cachePolicy("NEVER", "Never")); case "session" -> code.add( - "\n .withCachePolicy($T.PerSession)", FunctionCachePolicy.class); + "\n .withCachePolicy($T.$L)", + FunctionCachePolicy.class, + cachePolicy("PER_SESSION", "PerSession")); default -> code.add( - "\n .withCachePolicy($T.Default, new $T.WithCachePolicyArguments().withTimeToLive($S))", + "\n .withCachePolicy($T.$L, new $T.WithCachePolicyArguments().withTimeToLive($S))", FunctionCachePolicy.class, + cachePolicy("DEFAULT", "Default"), io.dagger.client.modules.core.Function.class, fnInfo.cache()); } @@ -837,7 +861,9 @@ public static CodeBlock withFunction( } if (hasDefaultValue) { code.add( - ".withDefaultValue($T.from($S))", JSON.class, parameterInfo.defaultValue().get()); + ".withDefaultValue($T.from($S))", + DaggerType.JSON_CLASS, + parameterInfo.defaultValue().get()); } if (hasDefaultPath) { code.add(".withDefaultPath($S)", parameterInfo.defaultPath().get()); diff --git a/sdk/dagger-java-annotation-processor/src/main/java/io/dagger/annotation/processor/DaggerType.java b/sdk/dagger-java-annotation-processor/src/main/java/io/dagger/annotation/processor/DaggerType.java index fa60240..ca0fa2a 100644 --- a/sdk/dagger-java-annotation-processor/src/main/java/io/dagger/annotation/processor/DaggerType.java +++ b/sdk/dagger-java-annotation-processor/src/main/java/io/dagger/annotation/processor/DaggerType.java @@ -3,6 +3,7 @@ import com.palantir.javapoet.ClassName; import com.palantir.javapoet.CodeBlock; import com.palantir.javapoet.ParameterizedTypeName; +import io.dagger.client.GraphQLType; import io.dagger.client.modules.core.Core; import io.dagger.client.modules.core.TypeDefKind; import io.dagger.module.info.TypeInfo; @@ -12,6 +13,46 @@ public abstract class DaggerType { protected static Set knownEnums = Set.of(); + private static final String CORE_PACKAGE = "io.dagger.client.modules.core"; + + /** + * The SDK's ID and JSON scalar classes. Their names depend on the schema the SDK was generated + * from: Java's convention ({@code Id}, {@code Json}) with engine-formatted names, the schema's + * ({@code ID}, {@code JSON}) without. + */ + static final ClassName ID_CLASS = coreClass("Id", "ID"); + + static final ClassName JSON_CLASS = coreClass("Json", "JSON"); + + private static ClassName coreClass(String conventionName, String schemaName) { + try { + Class clazz = Class.forName(CORE_PACKAGE + "." + conventionName); + GraphQLType graphQLType = clazz.getAnnotation(GraphQLType.class); + if (graphQLType != null && graphQLType.value().equals(schemaName)) { + return ClassName.get(CORE_PACKAGE, conventionName); + } + } catch (ClassNotFoundException | LinkageError e) { + // generated without formatted names + } + return ClassName.get(CORE_PACKAGE, schemaName); + } + + /** + * The GraphQL type a class stands for: the type its {@link GraphQLType} names, for SDK classes + * named by Java's convention ({@code JsonValue} for {@code JSONValue}), else its simple name. + */ + static String graphQLName(String qualifiedName, String simpleName) { + try { + GraphQLType graphQLType = Class.forName(qualifiedName).getAnnotation(GraphQLType.class); + if (graphQLType != null) { + return graphQLType.value(); + } + } catch (ClassNotFoundException | LinkageError e) { + // not an SDK class: the module's own types are named by their simple names + } + return simpleName; + } + public static void setKnownEnums(Set enums) { knownEnums = enums; } @@ -129,12 +170,13 @@ public Enum(String qualifiedName, String simpleName) { @Override CodeBlock toDaggerTypeDef() { - return CodeBlock.of("$T.core().typeDef().withEnum($S)", Core.class, simpleName); + return CodeBlock.of( + "$T.core().typeDef().withEnum($S)", Core.class, graphQLName(qualifiedName, simpleName)); } @Override String toDangTypeDef() { - return "typeDef.withEnum(" + Dang.quote(simpleName) + ")"; + return "typeDef.withEnum(" + Dang.quote(graphQLName(qualifiedName, simpleName)) + ")"; } @Override @@ -217,12 +259,13 @@ public Scalar(String qualifiedName, String simpleName) { @Override CodeBlock toDaggerTypeDef() { - return CodeBlock.of("$T.core().typeDef().withScalar($S)", Core.class, simpleName); + return CodeBlock.of( + "$T.core().typeDef().withScalar($S)", Core.class, graphQLName(qualifiedName, simpleName)); } @Override String toDangTypeDef() { - return "typeDef.withScalar(" + Dang.quote(simpleName) + ")"; + return "typeDef.withScalar(" + Dang.quote(graphQLName(qualifiedName, simpleName)) + ")"; } @Override @@ -270,12 +313,13 @@ public Object(String qualifiedName, String simpleName) { @Override CodeBlock toDaggerTypeDef() { - return CodeBlock.of("$T.core().typeDef().withObject($S)", Core.class, simpleName); + return CodeBlock.of( + "$T.core().typeDef().withObject($S)", Core.class, graphQLName(qualifiedName, simpleName)); } @Override String toDangTypeDef() { - return "typeDef.withObject(" + Dang.quote(simpleName) + ")"; + return "typeDef.withObject(" + Dang.quote(graphQLName(qualifiedName, simpleName)) + ")"; } @Override 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 a3d756b..2b3ebbd 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 @@ -192,10 +192,10 @@ private static String renderFunction(ObjectInfo object, FunctionInfo function) { } switch (function.cache()) { case "" -> {} - case "never" -> b.append("\n .withCachePolicy(FunctionCachePolicy.Never)"); - case "session" -> b.append("\n .withCachePolicy(FunctionCachePolicy.PerSession)"); + case "never" -> b.append("\n .withCachePolicy(FunctionCachePolicy.NEVER)"); + case "session" -> b.append("\n .withCachePolicy(FunctionCachePolicy.PER_SESSION)"); default -> - b.append("\n .withCachePolicy(FunctionCachePolicy.Default, timeToLive: ") + b.append("\n .withCachePolicy(FunctionCachePolicy.DEFAULT, timeToLive: ") .append(Dang.quote(function.cache())) .append(")"); } diff --git a/sdk/dagger-java-annotation-processor/src/test/java/io/dagger/annotation/processor/CollectionProcessingTest.java b/sdk/dagger-java-annotation-processor/src/test/java/io/dagger/annotation/processor/CollectionProcessingTest.java index 78fbe91..6b93ace 100644 --- a/sdk/dagger-java-annotation-processor/src/test/java/io/dagger/annotation/processor/CollectionProcessingTest.java +++ b/sdk/dagger-java-annotation-processor/src/test/java/io/dagger/annotation/processor/CollectionProcessingTest.java @@ -330,18 +330,25 @@ public Items items() { process(Map.of("Item", ITEM, "Items", items, "Main", main)); + String json = DaggerType.JSON_CLASS.simpleName(); assertThat(entrypoint()) .contains( "Item res = obj.lookup(name);\n" + " return ModuleDispatcher.collectionResult(parentJson, obj, res," - + " JsonConverter.toJSON(res));") + + " JsonConverter.toJSON(res), " + + json + + "::from);") .contains( "Items res = obj.change(names);\n" + " return ModuleDispatcher.collectionResult(parentJson, obj, res," - + " JsonConverter.toJSON(res));") + + " JsonConverter.toJSON(res), " + + json + + "::from);") .contains( "return ModuleDispatcher.collectionResult(parentJson, obj, res.orElse(null)," - + " JsonConverter.toJSON(res.orElse(null)));") + + " JsonConverter.toJSON(res.orElse(null)), " + + json + + "::from);") .contains("obj.nothing();\n return JsonConverter.toJSON(null);") .contains("Items res = obj.items();\n return JsonConverter.toJSON(res);"); } diff --git a/sdk/dagger-java-annotation-processor/src/test/java/io/dagger/annotation/processor/DaggerTypeDangTest.java b/sdk/dagger-java-annotation-processor/src/test/java/io/dagger/annotation/processor/DaggerTypeDangTest.java index 2d5838d..b5967f3 100644 --- a/sdk/dagger-java-annotation-processor/src/test/java/io/dagger/annotation/processor/DaggerTypeDangTest.java +++ b/sdk/dagger-java-annotation-processor/src/test/java/io/dagger/annotation/processor/DaggerTypeDangTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; +import io.dagger.client.GraphQLType; import io.dagger.module.info.TypeInfo; import java.util.Set; import javax.lang.model.type.TypeKind; @@ -40,7 +41,7 @@ void voidIsAnOptionalVoidKind() { void objectsScalarsAndEnumsRenderByName() { assertThat(declared("io.dagger.client.modules.core.Container").toDangTypeDef()) .isEqualTo("typeDef.withObject(\"Container\")"); - assertThat(declared("io.dagger.client.modules.core.JSON").toDangTypeDef()) + assertThat(declared(DaggerType.JSON_CLASS.canonicalName()).toDangTypeDef()) .isEqualTo("typeDef.withScalar(\"JSON\")"); DaggerType.setKnownEnums(Set.of("io.dagger.modules.demo.Severity")); @@ -48,6 +49,27 @@ void objectsScalarsAndEnumsRenderByName() { .isEqualTo("typeDef.withEnum(\"Severity\")"); } + /** A class named by Java's convention registers as the GraphQL type it stands for. */ + @GraphQLType("JSONValue") + public static class JsonValue extends io.dagger.client.Scalar { + public JsonValue(String value) { + super(value); + } + } + + @Test + void aClassNamedApartFromItsTypeRendersByItsGraphQLType() { + String name = JsonValue.class.getName(); + assertThat(declared(name).toDangTypeDef()).isEqualTo("typeDef.withScalar(\"JSONValue\")"); + assertThat(declared(name).toDaggerTypeDef().toString()).contains("withScalar(\"JSONValue\")"); + } + + @Test + void theIdAndJsonClassesAreTheGeneratedOnes() throws Exception { + assertThat(Class.forName(DaggerType.ID_CLASS.canonicalName())).isNotNull(); + assertThat(Class.forName(DaggerType.JSON_CLASS.canonicalName())).isNotNull(); + } + @Test void listsAndArraysBothRenderAsListOf() { assertThat(declared("java.util.List").toDangTypeDef()) 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 eb2bc91..e271f2c 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 @@ -58,7 +58,7 @@ void typesDescribesEveryObjectAndEnumWithoutAWorkspace() { " .withFunction(", " function(\"lint\"," + " typeDef.withKind(TypeDefKind.VOID_KIND).withOptional(true))", - " .withCachePolicy(FunctionCachePolicy.Never)", + " .withCachePolicy(FunctionCachePolicy.NEVER)", " .withCheck", " )", " .withField(\"source\", typeDef.withObject(\"Directory\"), description:" @@ -77,11 +77,11 @@ void typesDescribesEveryObjectAndEnumWithoutAWorkspace() { @Test void cachePoliciesFollowTheValuesEveryOtherSdkAccepts() { - assertThat(renderFunction("never")).contains(".withCachePolicy(FunctionCachePolicy.Never)"); + assertThat(renderFunction("never")).contains(".withCachePolicy(FunctionCachePolicy.NEVER)"); assertThat(renderFunction("session")) - .contains(".withCachePolicy(FunctionCachePolicy.PerSession)"); + .contains(".withCachePolicy(FunctionCachePolicy.PER_SESSION)"); assertThat(renderFunction("10s")) - .contains(".withCachePolicy(FunctionCachePolicy.Default, timeToLive: \"10s\")"); + .contains(".withCachePolicy(FunctionCachePolicy.DEFAULT, timeToLive: \"10s\")"); assertThat(renderFunction("")).doesNotContain("withCachePolicy"); } diff --git a/sdk/dagger-java-annotation-processor/src/test/java/io/dagger/annotation/processor/EntrypointGenerationTest.java b/sdk/dagger-java-annotation-processor/src/test/java/io/dagger/annotation/processor/EntrypointGenerationTest.java index a919b63..c72e5a0 100644 --- a/sdk/dagger-java-annotation-processor/src/test/java/io/dagger/annotation/processor/EntrypointGenerationTest.java +++ b/sdk/dagger-java-annotation-processor/src/test/java/io/dagger/annotation/processor/EntrypointGenerationTest.java @@ -15,15 +15,26 @@ class EntrypointGenerationTest { + /** The JSON scalar's class, named by the schema the SDK under test was generated from. */ + private static final String JSON = DaggerType.JSON_CLASS.simpleName(); + /** The Dang entrypoint runs the jar with engine-call, which reaches this switch directly. */ @Test void engineCallModeRunsTheStaticDispatchSwitch() { String java = generated(); assertThat(java) - .contains("private static JSON invoke(JSON parentJson, String parentName, String fnName,") + .contains( + "private static " + + JSON + + " invoke(" + + JSON + + " parentJson, String parentName, String fnName,") .contains("if (args.length > 0 && args[0].equals(\"engine-call\")) {") - .contains("System.exit(ModuleDispatcher.engineCall(args, Entrypoint::invoke));"); + .contains( + "System.exit(ModuleDispatcher.engineCall(args, " + + JSON + + "::from, Entrypoint::invoke));"); } @Test @@ -34,7 +45,7 @@ void anObjectWithoutConstructorAnswersItsConstructorWithItsEmptyState() { "\n", " if (parentName.equals(\"Hello\")) {", " if (fnName.equals(\"\")) {", - " return JSON.from(\"{}\");", + " return " + JSON + ".from(\"{}\");", " }")); } @@ -43,11 +54,31 @@ void registerDeclaresTheCachePolicy() { String java = generated(); assertThat(java) - .contains(".withCachePolicy(FunctionCachePolicy.Never)") - .contains(".withCachePolicy(FunctionCachePolicy.PerSession)") .contains( - ".withCachePolicy(FunctionCachePolicy.Default, new" - + " Function.WithCachePolicyArguments().withTimeToLive(\"1h\"))"); + ".withCachePolicy(FunctionCachePolicy." + + DaggerModuleAnnotationProcessor.cachePolicy("NEVER", "Never") + + ")") + .contains( + ".withCachePolicy(FunctionCachePolicy." + + DaggerModuleAnnotationProcessor.cachePolicy("PER_SESSION", "PerSession") + + ")") + .contains( + ".withCachePolicy(FunctionCachePolicy." + + DaggerModuleAnnotationProcessor.cachePolicy("DEFAULT", "Default") + + ", new Function.WithCachePolicyArguments().withTimeToLive(\"1h\"))"); + } + + /** The cache policy constants are the SDK's own: Java's spelling, or the schema's. */ + @Test + void theCachePolicyConstantsExist() throws Exception { + for (String[] names : + new String[][] { + {"NEVER", "Never"}, {"PER_SESSION", "PerSession"}, {"DEFAULT", "Default"} + }) { + String constant = DaggerModuleAnnotationProcessor.cachePolicy(names[0], names[1]); + assertThat(io.dagger.client.modules.core.FunctionCachePolicy.class.getField(constant)) + .isNotNull(); + } } private static String generated() { diff --git a/sdk/dagger-java-sdk/pom.xml b/sdk/dagger-java-sdk/pom.xml index c9468dc..97e4a4d 100644 --- a/sdk/dagger-java-sdk/pom.xml +++ b/sdk/dagger-java-sdk/pom.xml @@ -81,6 +81,7 @@ ${daggerengine.version} ${daggerengine.schema} + ${daggerengine.names} ${daggerengine.plan} diff --git a/sdk/dagger-java-sdk/src/main/java/io/dagger/client/Arguments.java b/sdk/dagger-java-sdk/src/main/java/io/dagger/client/Arguments.java index b3834dc..3393bce 100644 --- a/sdk/dagger-java-sdk/src/main/java/io/dagger/client/Arguments.java +++ b/sdk/dagger-java-sdk/src/main/java/io/dagger/client/Arguments.java @@ -79,6 +79,9 @@ private Object toArgumentValue(Object value) list.add(toArgumentValue(o)); } return list; + } else if (value instanceof GraphQLEnum) { + // Constants named apart from their schema values go as their values. + return ((GraphQLEnum) value).graphQLValue(); } else if (value instanceof Enum) { return ((Enum) value).toString(); } else { diff --git a/sdk/dagger-java-sdk/src/main/java/io/dagger/client/GraphQLEnum.java b/sdk/dagger-java-sdk/src/main/java/io/dagger/client/GraphQLEnum.java new file mode 100644 index 0000000..8abb812 --- /dev/null +++ b/sdk/dagger-java-sdk/src/main/java/io/dagger/client/GraphQLEnum.java @@ -0,0 +1,20 @@ +package io.dagger.client; + +/** + * A generated enum whose constants follow Java's naming convention ({@code PER_SESSION}) rather + * than the schema's values ({@code PerSession}). Each constant carries the value the API knows it + * by. Enums whose constants are named like their values don't implement it: they go over the wire + * by name. + */ +public interface GraphQLEnum { + /** The schema value this constant is sent as. */ + String graphQLValue(); + + /** + * Whether the API may return this constant as the given value: its own, or that of another schema + * value it shares a constant with ({@code GZIP} for {@code Gzip}). + */ + default boolean hasGraphQLValue(String value) { + return graphQLValue().equals(value); + } +} diff --git a/sdk/dagger-java-sdk/src/main/java/io/dagger/client/GraphQLEnumDeserializer.java b/sdk/dagger-java-sdk/src/main/java/io/dagger/client/GraphQLEnumDeserializer.java new file mode 100644 index 0000000..0b14a8b --- /dev/null +++ b/sdk/dagger-java-sdk/src/main/java/io/dagger/client/GraphQLEnumDeserializer.java @@ -0,0 +1,21 @@ +package io.dagger.client; + +import jakarta.json.bind.serializer.DeserializationContext; +import jakarta.json.bind.serializer.JsonbDeserializer; +import jakarta.json.stream.JsonParser; +import java.lang.reflect.Type; + +/** Deserializes a {@link GraphQLEnum} constant from its schema value. */ +public class GraphQLEnumDeserializer implements JsonbDeserializer { + @Override + public Object deserialize(JsonParser parser, DeserializationContext ctx, Type type) { + String value = ctx.deserialize(String.class, parser); + if (value == null) { + return null; + } + if (!(type instanceof Class enumClass)) { + throw new IllegalArgumentException("cannot deserialize an enum as " + type); + } + return GraphQLEnums.valueOf(enumClass, value); + } +} diff --git a/sdk/dagger-java-sdk/src/main/java/io/dagger/client/GraphQLEnumSerializer.java b/sdk/dagger-java-sdk/src/main/java/io/dagger/client/GraphQLEnumSerializer.java new file mode 100644 index 0000000..4b89f18 --- /dev/null +++ b/sdk/dagger-java-sdk/src/main/java/io/dagger/client/GraphQLEnumSerializer.java @@ -0,0 +1,13 @@ +package io.dagger.client; + +import jakarta.json.bind.serializer.JsonbSerializer; +import jakarta.json.bind.serializer.SerializationContext; +import jakarta.json.stream.JsonGenerator; + +/** Serializes a {@link GraphQLEnum} constant as its schema value. */ +public class GraphQLEnumSerializer implements JsonbSerializer { + @Override + public void serialize(GraphQLEnum obj, JsonGenerator generator, SerializationContext ctx) { + generator.write(obj.graphQLValue()); + } +} diff --git a/sdk/dagger-java-sdk/src/main/java/io/dagger/client/GraphQLEnums.java b/sdk/dagger-java-sdk/src/main/java/io/dagger/client/GraphQLEnums.java new file mode 100644 index 0000000..6c360d0 --- /dev/null +++ b/sdk/dagger-java-sdk/src/main/java/io/dagger/client/GraphQLEnums.java @@ -0,0 +1,66 @@ +package io.dagger.client; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** Converts enum constants to and from the values the API knows them by. */ +public final class GraphQLEnums { + private GraphQLEnums() {} + + /** + * The value an enum constant is sent as: its {@link GraphQLEnum#graphQLValue()}, or its name for + * an enum named like its values (including a module's own enums). + */ + public static String value(Enum constant) { + if (constant instanceof GraphQLEnum graphQLEnum) { + return graphQLEnum.graphQLValue(); + } + return constant.name(); + } + + /** + * An object to serialize, with every enum constant replaced by its {@link #value}: the object + * itself, or the elements of a collection or an array, at any depth. JSON-B applies an enum's + * serializer to a field, but not to an element of a list it serializes. + */ + public static Object values(Object object) { + if (object instanceof Enum constant) { + return value(constant); + } + if (object instanceof Collection collection) { + List values = new ArrayList<>(collection.size()); + collection.forEach(element -> values.add(values(element))); + return values; + } + if (object instanceof Object[] array) { + List values = new ArrayList<>(array.length); + for (Object element : array) { + values.add(values(element)); + } + return values; + } + return object; + } + + /** + * The constant of an enum class the API value stands for: the one with that {@link + * GraphQLEnum#hasGraphQLValue value}, or the one with that name. + * + * @throws IllegalArgumentException if no constant matches + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + public static T valueOf(Class enumClass, String value) { + if (!enumClass.isEnum()) { + throw new IllegalArgumentException(enumClass.getName() + " is not an enum"); + } + if (GraphQLEnum.class.isAssignableFrom(enumClass)) { + for (T constant : enumClass.getEnumConstants()) { + if (((GraphQLEnum) constant).hasGraphQLValue(value)) { + return constant; + } + } + } + return (T) Enum.valueOf((Class) enumClass, value); + } +} diff --git a/sdk/dagger-java-sdk/src/main/java/io/dagger/client/GraphQLType.java b/sdk/dagger-java-sdk/src/main/java/io/dagger/client/GraphQLType.java new file mode 100644 index 0000000..78133b1 --- /dev/null +++ b/sdk/dagger-java-sdk/src/main/java/io/dagger/client/GraphQLType.java @@ -0,0 +1,21 @@ +package io.dagger.client; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * The GraphQL type a generated class stands for, when the class name follows Java's naming + * convention rather than the schema's ({@code JsonValue} for {@code JSONValue}, {@code Llm} for + * {@code LLM}). Everything that sends a type name to the API reads it: loading objects by ID and + * registering module types. A class without it is named like its GraphQL type. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface GraphQLType { + /** The GraphQL type name. */ + String value(); +} 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 7f0f86e..694cf2c 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,7 +1,6 @@ package io.dagger.client; import io.dagger.client.engineconn.Connection; -import io.dagger.client.modules.core.JSON; import io.dagger.client.telemetry.Telemetry; import jakarta.json.Json; import jakarta.json.JsonException; @@ -20,13 +19,16 @@ import java.nio.file.Path; import java.util.HashMap; import java.util.Map; +import java.util.function.Function; /** * Answers one call of a module's Dang entrypoint: the request on standard input, the result in a * file, and a failure reported on standard error. * - *

This class is in {@code io.dagger.client} because it writes a {@link JSON} scalar's raw value, - * which only this package can read. + *

Values travel as the core JSON scalar, whose generated class is named after the schema the SDK + * was generated from ({@code JSON}, or {@code Json} under engine-formatted names). This + * hand-written class can't name it, so it takes the class as a type parameter and its {@code from} + * factory from the generated entrypoint. */ public final class ModuleDispatcher { @@ -44,22 +46,25 @@ public final class ModuleDispatcher { private ModuleDispatcher() {} - /** The generated entrypoint's dispatch switch. */ + /** The generated entrypoint's dispatch switch, over the core JSON scalar class {@code J}. */ @FunctionalInterface - public interface Dispatch { - JSON call(JSON parentJson, String parentName, String fnName, Map inputArgs) + public interface Dispatch> { + J call(J parentJson, String parentName, String fnName, Map inputArgs) throws Exception; } /** * Run the {@code engine-call} mode: {@code engine-call [--output PATH]}. Returns the process exit * code. + * + * @param json the JSON scalar's factory, {@code JSON::from} */ - public static int engineCall(String[] args, Dispatch dispatch) { + public static > int engineCall( + String[] args, Function json, Dispatch dispatch) { Connection.markModule(); try (Telemetry telemetry = new Telemetry()) { Path output = outputPath(args); - String result = dispatch(System.in, dispatch); + String result = dispatch(System.in, json, dispatch); if (output == null) { System.out.println(result); } else { @@ -75,20 +80,21 @@ public static int engineCall(String[] args, Dispatch dispatch) { } } - static String dispatch(InputStream in, Dispatch dispatch) throws Exception { + static > String dispatch( + InputStream in, Function json, Dispatch dispatch) throws Exception { JsonObject request = readRequest(in); String parentName = requiredString(request, "receiverType"); String fnName = requiredString(request, "fnName"); - JSON parentJson = JSON.from(jsonText(request, "receiverValue")); + J parentJson = json.apply(jsonText(request, "receiverValue")); JsonValue args = parse(jsonText(request, "fnArgs"), "fnArgs"); if (args.getValueType() != JsonValue.ValueType.OBJECT) { throw new IllegalArgumentException("call request field fnArgs is not a JSON object"); } - Map inputArgs = new HashMap<>(); + Map inputArgs = new HashMap<>(); for (Map.Entry arg : args.asJsonObject().entrySet()) { - inputArgs.put(arg.getKey(), JSON.from(arg.getValue().toString())); + inputArgs.put(arg.getKey(), json.apply(arg.getValue().toString())); } - JSON value = dispatch.call(parentJson, parentName, fnName, inputArgs); + J value = dispatch.call(parentJson, parentName, fnName, inputArgs); return value == null ? "null" : value.convert(); } @@ -96,9 +102,11 @@ static String dispatch(InputStream in, Dispatch dispatch) throws Exception { * The JSON of what a function of a collection returned. When the function returned its receiver, * the receiver's base goes with it, so the engine computes the delta against the collection the * module first returned. Any other result, a new instance included, starts a base of its own. + * + * @param json the JSON scalar's factory, {@code JSON::from} */ - public static JSON collectionResult( - JSON receiverJson, Object receiver, Object result, JSON resultJson) { + public static > J collectionResult( + J receiverJson, Object receiver, Object result, J resultJson, Function json) { if (result != receiver) { return resultJson; } @@ -110,14 +118,14 @@ public static JSON collectionResult( if (base == null) { return resultJson; } - return JSON.from( + return json.apply( Json.createObjectBuilder(read(resultJson).asJsonObject()) .add(COLLECTION_BASE_FIELD, base) .build() .toString()); } - private static JsonValue read(JSON json) { + private static JsonValue read(Scalar json) { try (JsonReader reader = Json.createReader(new StringReader(json.convert()))) { return reader.readValue(); } diff --git a/sdk/dagger-java-sdk/src/main/java/io/dagger/client/QueryBuilder.java b/sdk/dagger-java-sdk/src/main/java/io/dagger/client/QueryBuilder.java index ef8a39d..1e75196 100644 --- a/sdk/dagger-java-sdk/src/main/java/io/dagger/client/QueryBuilder.java +++ b/sdk/dagger-java-sdk/src/main/java/io/dagger/client/QueryBuilder.java @@ -248,6 +248,12 @@ public T executeQuery(Class klass) if (klass == String.class && value instanceof JsonString js) { return klass.cast(js.getString()); } + if (klass.isEnum() + && GraphQLEnum.class.isAssignableFrom(klass) + && value instanceof JsonString js) { + // Constants named apart from their schema values are looked up by value. + return GraphQLEnums.valueOf(klass, js.getString()); + } JsonbConfig config = new JsonbConfig().withPropertyVisibilityStrategy(new PrivateVisibilityStrategy()); Jsonb jsonb = JsonbBuilder.newBuilder().withConfig(config).build(); diff --git a/sdk/dagger-java-sdk/src/test/java/io/dagger/client/GraphQLEnumsTest.java b/sdk/dagger-java-sdk/src/test/java/io/dagger/client/GraphQLEnumsTest.java new file mode 100644 index 0000000..43f940f --- /dev/null +++ b/sdk/dagger-java-sdk/src/test/java/io/dagger/client/GraphQLEnumsTest.java @@ -0,0 +1,91 @@ +package io.dagger.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import jakarta.json.bind.Jsonb; +import jakarta.json.bind.JsonbBuilder; +import jakarta.json.bind.annotation.JsonbTypeDeserializer; +import jakarta.json.bind.annotation.JsonbTypeSerializer; +import java.util.List; +import org.junit.jupiter.api.Test; + +/** Enums whose constants are named apart from their schema values go by those values. */ +class GraphQLEnumsTest { + + /** Shaped like a generated enum under engine-formatted names. */ + @JsonbTypeSerializer(GraphQLEnumSerializer.class) + @JsonbTypeDeserializer(GraphQLEnumDeserializer.class) + public enum Policy implements GraphQLEnum { + DEFAULT("Default"), + PER_SESSION("PerSession", "PER_SESSION"); + + @Deprecated public static final Policy PerSession = PER_SESSION; + + private final String[] values; + + Policy(String... values) { + this.values = values; + } + + @Override + public String graphQLValue() { + return values[0]; + } + + @Override + public boolean hasGraphQLValue(String value) { + return List.of(values).contains(value); + } + } + + /** A module's own enum, named like its values. */ + public enum Level { + LOW + } + + public static class Holder { + public Policy policy = Policy.PER_SESSION; + } + + @Test + void anArgumentGoesAsItsSchemaValue() throws Exception { + assertThat(Arguments.newBuilder().add("policy", Policy.PER_SESSION).build().toGraphQL()) + .isEqualTo("policy:\"PerSession\""); + assertThat(Arguments.newBuilder().add("policy", Policy.PerSession).build().toGraphQL()) + .isEqualTo("policy:\"PerSession\""); + assertThat( + Arguments.newBuilder() + .add("policies", List.of(Policy.DEFAULT, Policy.PER_SESSION)) + .build() + .toGraphQL()) + .isEqualTo("policies:[\"Default\",\"PerSession\"]"); + assertThat(Arguments.newBuilder().add("level", Level.LOW).build().toGraphQL()) + .isEqualTo("level:\"LOW\""); + } + + @Test + void aValueReadsBackAsItsConstant() { + assertThat(GraphQLEnums.valueOf(Policy.class, "PerSession")).isEqualTo(Policy.PER_SESSION); + assertThat(GraphQLEnums.valueOf(Policy.class, "PER_SESSION")).isEqualTo(Policy.PER_SESSION); + assertThat(GraphQLEnums.valueOf(Level.class, "LOW")).isEqualTo(Level.LOW); + assertThatThrownBy(() -> GraphQLEnums.valueOf(Policy.class, "Never")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void jsonCarriesTheSchemaValuesInAListToo() throws Exception { + try (Jsonb jsonb = JsonbBuilder.create()) { + assertThat(jsonb.toJson(new Holder())).isEqualTo("{\"policy\":\"PerSession\"}"); + assertThat(jsonb.toJson(GraphQLEnums.values(Policy.PER_SESSION))).isEqualTo("\"PerSession\""); + assertThat(jsonb.toJson(GraphQLEnums.values(List.of(Policy.PER_SESSION, Policy.DEFAULT)))) + .isEqualTo("[\"PerSession\",\"Default\"]"); + assertThat(jsonb.toJson(GraphQLEnums.values(new Policy[] {Policy.DEFAULT}))) + .isEqualTo("[\"Default\"]"); + assertThat(jsonb.toJson(GraphQLEnums.values(List.of(List.of(Level.LOW))))) + .isEqualTo("[[\"LOW\"]]"); + assertThat(jsonb.fromJson("{\"policy\":\"PerSession\"}", Holder.class).policy) + .isEqualTo(Policy.PER_SESSION); + } + } +} 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 da97da1..9870a68 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,7 +4,6 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.dagger.client.engineconn.TestConnections; -import io.dagger.client.modules.core.JSON; import io.dagger.client.modules.core.JsonConverter; import jakarta.json.Json; import java.io.ByteArrayInputStream; @@ -23,14 +22,28 @@ class ModuleDispatcherTest { + /** + * A stand-in for the generated JSON scalar, whose class name depends on the schema the SDK was + * generated from: the dispatcher takes any. + */ + static final class TestJson extends Scalar { + TestJson(String value) { + super(value); + } + + static TestJson from(String value) { + return new TestJson(value); + } + } + @Test void theRequestReachesTheSwitchVerbatim() throws Exception { var seen = new Object() { - Map args; + Map args; String parentName; String fnName; - JSON parentJson; + TestJson parentJson; }; String result = @@ -44,7 +57,7 @@ void theRequestReachesTheSwitchVerbatim() throws Exception { seen.parentName = parentName; seen.fnName = fnName; seen.args = inputArgs; - return JSON.from("\"Hi, World\""); + return TestJson.from("\"Hi, World\""); }); assertThat(seen.parentName).isEqualTo("Hello"); @@ -83,7 +96,7 @@ void aConstructorCallCarriesItsTypeAndAnEmptyFunctionName() throws Exception { seen[0] = parentName; seen[1] = fnName; seen[2] = parentJson.convert(); - return JSON.from("{}"); + return TestJson.from("{}"); }); assertThat(seen).containsExactly("Hello", "", "null"); @@ -97,8 +110,8 @@ void aVoidResultIsJsonNull() throws Exception { @Test void malformedRequestsAreRejected() { - ModuleDispatcher.Dispatch never = - (parentJson, parentName, fnName, inputArgs) -> JSON.from("null"); + ModuleDispatcher.Dispatch never = + (parentJson, parentName, fnName, inputArgs) -> TestJson.from("null"); assertThatThrownBy(() -> dispatch("{\"fnName\":\"greet\",\"fnArgs\":\"{}\"}", never)) .hasMessageContaining("receiverType"); @@ -122,9 +135,10 @@ void theResultIsWrittenToTheOutputFile(@TempDir Path dir) throws Exception { () -> ModuleDispatcher.engineCall( new String[] {"engine-call", "--output", output.toString()}, + TestJson::from, (parentJson, parentName, fnName, inputArgs) -> { System.out.println("a log line of the module"); - return JSON.from("[\"a\",\"b\"]"); + return TestJson.from("[\"a\",\"b\"]"); })); assertThat(code).isZero(); @@ -138,6 +152,7 @@ void anEngineCallMarksTheProcessAsAModule(@TempDir Path dir) throws Exception { () -> ModuleDispatcher.engineCall( new String[] {"engine-call", "--output", dir.resolve("result.json").toString()}, + TestJson::from, (parentJson, parentName, fnName, inputArgs) -> null)); assertThat(TestConnections.markedModule()).isTrue(); @@ -185,14 +200,14 @@ void aLongMessageIsCutToFitTheStderrTheEngineKeeps() { @Test void aCollectionThatReturnsItselfKeepsItsReceiversBase() throws Exception { - JSON receiverJson = - JSON.from("{\"names\":[\"b\",\"a\"],\"__daggerCollectionBase\":\"base-id\"}"); - Items receiver = JsonConverter.fromJSON(receiverJson, Items.class); + TestJson receiverJson = + TestJson.from("{\"names\":[\"b\",\"a\"],\"__daggerCollectionBase\":\"base-id\"}"); + Items receiver = JsonConverter.fromJSON(receiverJson.convert(), Items.class); receiver.names = List.of("c"); - JSON result = + TestJson result = ModuleDispatcher.collectionResult( - receiverJson, receiver, receiver, JsonConverter.toJSON(receiver)); + receiverJson, receiver, receiver, toJson(receiver), TestJson::from); assertThat(result.convert()) .isEqualTo("{\"names\":[\"c\"],\"__daggerCollectionBase\":\"base-id\"}"); @@ -201,29 +216,35 @@ void aCollectionThatReturnsItselfKeepsItsReceiversBase() throws Exception { /** Without the base, the engine makes the new instance its own base, so its delta is empty. */ @Test void aNewCollectionDoesNotInheritTheReceiversBase() throws Exception { - JSON receiverJson = - JSON.from("{\"names\":[\"b\",\"a\"],\"__daggerCollectionBase\":\"base-id\"}"); - Items receiver = JsonConverter.fromJSON(receiverJson, Items.class); + TestJson receiverJson = + TestJson.from("{\"names\":[\"b\",\"a\"],\"__daggerCollectionBase\":\"base-id\"}"); + Items receiver = JsonConverter.fromJSON(receiverJson.convert(), Items.class); Items fresh = new Items(); fresh.names = List.of("b", "a"); - JSON result = + TestJson result = ModuleDispatcher.collectionResult( - receiverJson, receiver, fresh, JsonConverter.toJSON(fresh)); + receiverJson, receiver, fresh, toJson(fresh), TestJson::from); assertThat(result.convert()).isEqualTo("{\"names\":[\"b\",\"a\"]}"); } @Test void aReceiverWithoutBaseLeavesTheResultAsItIs() throws Exception { - JSON receiverJson = JSON.from("{\"names\":[\"a\"]}"); - Items receiver = JsonConverter.fromJSON(receiverJson, Items.class); - JSON resultJson = JsonConverter.toJSON(receiver); + TestJson receiverJson = TestJson.from("{\"names\":[\"a\"]}"); + Items receiver = JsonConverter.fromJSON(receiverJson.convert(), Items.class); + TestJson resultJson = toJson(receiver); - assertThat(ModuleDispatcher.collectionResult(receiverJson, receiver, receiver, resultJson)) + assertThat( + ModuleDispatcher.collectionResult( + receiverJson, receiver, receiver, resultJson, TestJson::from)) .isSameAs(resultJson); } + private static TestJson toJson(Object value) throws Exception { + return TestJson.from(JsonConverter.toJSON(value).convert()); + } + public static class Items { private List names; @@ -240,10 +261,12 @@ private static String request(String fnArgs) { + "}"; } - private static String dispatch(String request, ModuleDispatcher.Dispatch dispatch) + private static String dispatch(String request, ModuleDispatcher.Dispatch dispatch) throws Exception { return ModuleDispatcher.dispatch( - new ByteArrayInputStream(request.getBytes(StandardCharsets.UTF_8)), dispatch); + new ByteArrayInputStream(request.getBytes(StandardCharsets.UTF_8)), + TestJson::from, + dispatch); } private static String failWith(Throwable failure, String log) { @@ -257,6 +280,7 @@ private static String failWith(Throwable failure, String log) { () -> ModuleDispatcher.engineCall( new String[] {"engine-call"}, + TestJson::from, (parentJson, parentName, fnName, inputArgs) -> { System.err.println(log); if (failure instanceof Exception e) {