diff --git a/.dagger/modules/e2e/dagger.json b/.dagger/modules/e2e/dagger.json index 7444df65..ffab255d 100644 --- a/.dagger/modules/e2e/dagger.json +++ b/.dagger/modules/e2e/dagger.json @@ -1,6 +1,6 @@ { "name": "e2e", - "engineVersion": "v1.0.0-0", + "engineVersion": "v1.0.0-beta.26", "sdk": { "source": "dang" }, diff --git a/.dagger/modules/e2e/fixtures/naming/app/dagger-module.toml b/.dagger/modules/e2e/fixtures/naming/app/dagger-module.toml new file mode 100644 index 00000000..a9cd83b4 --- /dev/null +++ b/.dagger/modules/e2e/fixtures/naming/app/dagger-module.toml @@ -0,0 +1,5 @@ +name = "naming-app" + +[entrypoint] + kind = "dang" + source = "./sdk/entrypoint" diff --git a/.dagger/modules/e2e/fixtures/naming/app/pyproject.toml b/.dagger/modules/e2e/fixtures/naming/app/pyproject.toml new file mode 100644 index 00000000..6bdc5e63 --- /dev/null +++ b/.dagger/modules/e2e/fixtures/naming/app/pyproject.toml @@ -0,0 +1,16 @@ +[project] +name = "naming-app" +version = "0.1.0" +requires-python = ">=3.14" +dependencies = ["dagger-io", "dagger-clients-core"] + +[build-system] +requires = ["uv_build>=0.8.4,<0.14.0"] +build-backend = "uv_build" + +[tool.uv.workspace] +members = ["sdk", "clients/core"] + +[tool.uv.sources] +dagger-io = { workspace = true } +dagger-clients-core = { workspace = true } diff --git a/.dagger/modules/e2e/fixtures/naming/app/src/naming_app/__init__.py b/.dagger/modules/e2e/fixtures/naming/app/src/naming_app/__init__.py new file mode 100644 index 00000000..149b6630 --- /dev/null +++ b/.dagger/modules/e2e/fixtures/naming/app/src/naming_app/__init__.py @@ -0,0 +1,51 @@ +"""Declarations the engine names differently on either side of the cut. + +HttpFetcher is NamingAppHttpFetcher by the legacy strcase rules and +NamingAppHTTPFetcher by the engine's identifier naming rules, and the Arch +member Arm64 is ARM_64 by the first and ARM64 by the second. A call through +the interface selects the type by its name, so the runtime has to use the +name the engine gave it. + +The interface takes no Arch: the engine refuses an own interface whose +function takes an own enum in the module's own session, so the module would +fail to load its schema (core/interface.go, "cannot accept arg ... of +external type from dependency module"). +""" + +import enum +import typing + +import dagger +from dagger import enum_type, function, interface, object_type + + +@enum_type +class Arch(enum.Enum): + Arm64 = "arm64" + + +@interface +class HttpFetcher(typing.Protocol): + @function + async def get_url(self, path: str) -> str: ... + + +@object_type +class HttpClient: + base_url: str = dagger.field() + + @function + async def get_url(self, path: str) -> str: + return f"{self.base_url}{path}" + + +@object_type +class NamingApp: + @function + def http_client(self, base_url: str) -> HttpClient: + return HttpClient(base_url=base_url) + + @function + async def fetch(self, fetcher: HttpFetcher, path: str, arch: Arch) -> str: + """Call through the module's own interface, by the engine's names.""" + return f"{await fetcher.get_url(path)} {arch.value}" diff --git a/.dagger/modules/e2e/fixtures/naming/caller/dagger-module.toml b/.dagger/modules/e2e/fixtures/naming/caller/dagger-module.toml new file mode 100644 index 00000000..310d35dc --- /dev/null +++ b/.dagger/modules/e2e/fixtures/naming/caller/dagger-module.toml @@ -0,0 +1,5 @@ +name = "naming-caller" + +[entrypoint] + kind = "dang" + source = "./sdk/entrypoint" diff --git a/.dagger/modules/e2e/fixtures/naming/caller/pyproject.toml b/.dagger/modules/e2e/fixtures/naming/caller/pyproject.toml new file mode 100644 index 00000000..64f38b88 --- /dev/null +++ b/.dagger/modules/e2e/fixtures/naming/caller/pyproject.toml @@ -0,0 +1,16 @@ +[project] +name = "naming-caller" +version = "0.1.0" +requires-python = ">=3.14" +dependencies = ["dagger-io", "dagger-clients-core"] + +[build-system] +requires = ["uv_build>=0.8.4,<0.14.0"] +build-backend = "uv_build" + +[tool.uv.workspace] +members = ["sdk", "clients/core"] + +[tool.uv.sources] +dagger-io = { workspace = true } +dagger-clients-core = { workspace = true } diff --git a/.dagger/modules/e2e/fixtures/naming/caller/src/naming_caller/__init__.py b/.dagger/modules/e2e/fixtures/naming/caller/src/naming_caller/__init__.py new file mode 100644 index 00000000..6692b3d2 --- /dev/null +++ b/.dagger/modules/e2e/fixtures/naming/caller/src/naming_caller/__init__.py @@ -0,0 +1,22 @@ +"""Calls naming-app through its client, so its runtime calls its own interface.""" + +from dagger import check, function, object_type +from dagger_clients.naming_app import NamingAppArch, naming_app + + +@object_type +class NamingCaller: + @function + async def fetch(self) -> str: + client = naming_app().http_client(base_url="https://example.com") + # Whichever name the engine gave the member, the client has it. + (arch,) = list(NamingAppArch) + return await naming_app().fetch(fetcher=client, path="/x", arch=arch) + + @function + @check + async def fetch_check(self) -> None: + got = await self.fetch() + if got != "https://example.com/x arm64": + msg = f"naming-app's call through its interface returned {got!r}" + raise ValueError(msg) diff --git a/.dagger/modules/e2e/main.dang b/.dagger/modules/e2e/main.dang index aea28b61..3f066c28 100644 --- a/.dagger/modules/e2e/main.dang +++ b/.dagger/modules/e2e/main.dang @@ -304,6 +304,47 @@ type E2e { null } + """ + A new module's main class follows the final generated config, at the SDK's + released target and at the oldest release a pin may name. Both are past the + identifier casing cut, so http-server is HTTPServer at each. + """ + pub initNamingCheck(ws: Workspace!): Void @check { + [ + {{name: "http-server", pkg: "http_server", main: "HTTPServer"}}, + {{name: "k8s-tools", pkg: "k8s_tools", main: "K8sTools"}}, + {{name: "e2e-test", pkg: "e2e_test", main: "E2ETest"}}, + ].each { want => + ["", "v" + floorVersion].each { pin => + let target = pythonSdk.targetVersionOf(pin) + let label = want.name + " at " + target + let scope = outputRoot + "/" + want.name + let seeded = ws.withNewDirectory("/" + scope, directory) + let generated = pythonSdk(targetVersion: pin).generateScope(seeded.withWorkdir(scope), isModule: true, name: want.name, clients: []) + .withWorkdir(".") + assertContains(generated.file("/" + scope + "/src/" + want.pkg + "/__init__.py").contents, "class " + want.main + ":", label + ": the main class is not " + want.main) + assertContains(generated.file("/" + scope + "/sdk/entrypoint/dang.toml").contents, "dagger = \"" + target + "\"", label + ": config target differs") + let source = generated.moduleSource("/" + scope) + let names = source.naming.typeNames(names: [want.name]) + assert((names[0] ?? "") == want.main, label + ": served naming differs from the generated class") + let objects = source.asModule.objects.{{ asObject.{{ name }} }} + assert(objects.filter { o => o.asObject.name == want.main }.length == 1, label + ": the module does not load with its main object " + want.main) + null + } + } + + # A runtime module is named by its manifest, not a generated config. + let scope = outputRoot + "/http-server-runtime" + let generated = pythonSdk(legacyRuntime: true).generateScope(ws.withNewDirectory("/" + scope, directory).withWorkdir(scope), isModule: true, name: "http-server", clients: []) + .withWorkdir(".") + let names = generated.moduleSource("/" + scope).naming.typeNames(names: ["http-server"]) + let main = names[0] ?? "" + assert(main != "", "runtime module has no main name") + assertContains(generated.file("/" + scope + "/src/http_server/__init__.py").contents, "class " + main + ":", "runtime main class differs from the engine's name") + + null + } + """ generateScope preserves a current manifest. It migrates a pre-1.0 dagger.json to dagger-module.toml. Both cases get the scope tree, and the @@ -1576,7 +1617,7 @@ type E2e { "--use-uv=false", "--base-image", "python:3.13-slim", ]) - .withExec(["grep", "-q", "class SdkSettings:", ".dagger/modules/sdk-settings/src/sdk_settings/__init__.py"]) + .withExec(["grep", "-q", "class SDKSettings:", ".dagger/modules/sdk-settings/src/sdk_settings/__init__.py"]) .withExec(["grep", "-q", ">=3.13", ".dagger/modules/sdk-settings/pyproject.toml"]) .withExec(["grep", "-q", "use-uv = false", ".dagger/modules/sdk-settings/pyproject.toml"]) .withExec(["grep", "-q", "python:3.13-slim", ".dagger/modules/sdk-settings/pyproject.toml"]) @@ -1608,9 +1649,11 @@ type E2e { assert(generatedDirectly.cwd == ws.withWorkdir(".").cwd, "direct generation moved the workspace's directory: " + generatedDirectly.cwd) assert(dangConfigDirect(generatedDirectly).changes(generatedDirectly).isEmpty, "a second direct generation changed the module") - let owned = "dang = \"2.0\"\n\n[imports.Dagger]\ndagger = \"v1.0.0-beta.20\"\npath = \"./schema\"\n\n[imports.Lib]\npath = \"./lib\"\n\n[imports.Other]\ndagger = \"v1.0.0-beta.20\"\n" + let owned = "dang = \"2.0\"\n\n[imports.Dagger]\ndagger = \"v1.0.0-beta.20\"\npath = \"./schema\"\n\n[imports.Lib]\npath = \"./lib\"\n\n[imports.Other]\ndagger = true\n" + let olderLeaf = "[imports.Dagger]\ndagger = \"v1.0.0-beta.20\"\n\n[imports.Lib]\npath = \"./lib\"\n" + assert(pythonSdk.mod(generated.withNewFile(configPath, olderLeaf), path: root, findUp: false).naming.version == target, "naming did not read the merged dang.toml") dangConfigBoth(generated.withNewFile(configPath, owned), configPath).each { contents => - assertContainsAll(contents, ["dang = \"2.1\"", "dagger = \"" + target + "\"", "[imports.Lib]", "path = \"./lib\"", "[imports.Other]", "dagger = \"v1.0.0-beta.20\""]) + assertContainsAll(contents, ["dang = \"2.1\"", "dagger = \"" + target + "\"", "[imports.Lib]", "path = \"./lib\"", "[imports.Other]", "dagger = true"]) assertNotContains(contents, "./schema", "generation kept the Dagger import's path: " + contents) assertNotContains(contents, "dang = \"2.0\"", "generation kept another Dang version: " + contents) } @@ -1622,6 +1665,15 @@ type E2e { assertContainsAll(kept.file(configPath).contents, ["[imports.Lib]", "path = \"./lib\""]) assert(kept.file("/" + root + "/cache/keep.txt").contents == "ignored", "generation changed an unrelated ignored file") } + let disagreeing = generated.withNewFile(configPath, "[imports.Dagger]\ndagger = \"v1.0.0-beta.20\"\n\n[imports.Other]\ndagger = \"v1.0.0-beta.20\"\n") + let scopeDisagreed = dangConfigGenerate(disagreeing).cwd rescue { + err: Error => err.message + } + assertContains(scopeDisagreed, "declare different Dagger versions", "scope generation did not surface the engine's refusal: " + scopeDisagreed) + let directDisagreed = dangConfigDirect(disagreeing).cwd rescue { + err: Error => err.message + } + assertContains(directDisagreed, "declare different Dagger versions", "direct generation did not surface the engine's refusal: " + directDisagreed) let endpoint = generated.withNewFile(configPath, "[imports.Dagger]\nendpoint = \"http://example\"\n") let scopeRefused = dangConfigGenerate(endpoint).cwd rescue { err: Error => err.message @@ -1652,6 +1704,7 @@ type E2e { assert(onRuntime.file(configPath).contents == customizedLeaf, "moving onto the runtime lost the entrypoint's dang.toml") let returned = dangConfigGenerate(onRuntime.withNewFile("/" + root + "/dagger-module.toml", "name = \"toml-generate-app\"\n")) assertContainsAll(returned.file(configPath).contents, ["dagger = \"" + target + "\"", "[imports.Lib]", "path = \"./lib\""]) + assertContains(returned.file("/" + root + "/sdk/entrypoint/main.dang").contents, "let clientVersion: String! = \"" + target + "\"", "a module back from the runtime declares another version") let ownEntrypoint = customized .withNewFile("/" + root + "/dagger-module.toml", dangEntrypointManifest("toml-generate-app", "./custom")) .withNewFile("/" + root + "/custom/main.dang", "# a Dang entrypoint of the user's own\n") @@ -1729,21 +1782,17 @@ type E2e { let plain = pythonSdk.generateScope(ws.withNewDirectory("/" + plainScope, directory).withWorkdir(plainScope), isModule: false, name: "target-version-plain", clients: []).withWorkdir(".") assert(plain.file("/" + plainScope + "/" + versionFilePath).contents == versionFile, "a plain scope's library does not announce the targeted release") - # Container.publish's sourceDateEpoch is newer than the floor's view, so a - # module pinned to the floor must not see it on any engine. let newInBeta22 = "source_date_epoch" let floorPinned = pythonSdk(targetVersion: floor).generateScope(scoped, isModule: true, name: name, clients: []).withWorkdir(".") - assertNotContains(floorPinned.file("/" + scope + "/" + coreInitPath).contents, newInBeta22, "core was not read in the view of the pinned release") assertContains(floorPinned.file("/" + scope + "/sdk/entrypoint/main.dang").contents, "let clientVersion: String! = \"" + floor + "\"", "the entrypoint does not declare the pinned release") assertContains(floorPinned.file("/" + scope + "/sdk/entrypoint/dang.toml").contents, "dagger = \"" + floor + "\"", "dang.toml does not follow the targetVersion pin") - if (version.contains(target)) { - assertContains(pinned.file("/" + scope + "/" + coreInitPath).contents, newInBeta22, "core was not read in the view of the targeted release") - } + # The engine running the checks serves the targeted release's view. + assertContains(pinned.file("/" + scope + "/" + coreInitPath).contents, newInBeta22, "core was not read in the view of the targeted release") let remedy = ": set targetVersion in its dagger.toml settings to " + target + ", or remove it to generate for " + target let refusals = [ ["v9.0.0", "v9.0.0, which is later than " + target + ", the engine release this Python SDK generates for: install the SDK release built for v9.0.0, or set targetVersion in its dagger.toml settings to " + target + ", or remove it"], - ["v1.0.0-beta.17", "v1.0.0-beta.17, which is below " + floor + ", the oldest release a targetVersion pin may name" + remedy], + ["v1.0.0-beta.25", "v1.0.0-beta.25, which is below " + floor + ", the oldest release a targetVersion pin may name" + remedy], ["latest", "\"latest\", which is no engine release such as " + target + remedy], ] let plainScope = outputRoot + "/target-version-scope" @@ -1837,13 +1886,10 @@ type E2e { let assertFloorPinned(generated: Container!, configFile: String!, path: String!, args: [String!]!): Void { let command = "`dagger " + args.join(" ") + "`" let root = playgroundRoot + "/" + path + "/" - # Container.publish's sourceDateEpoch is newer than the floor's view. - let newInBeta22 = "source_date_epoch" assertContains(generated.file(playgroundRoot + "/" + configFile).contents, "targetVersion = \"v" + floorVersion + "\"", command + " dropped the recorded pin") assertContains(generated.file(root + "sdk/entrypoint/main.dang").contents, "let clientVersion: String! = \"v" + floorVersion + "\"", command + " did not generate the entrypoint for the pinned release") assertContains(generated.file(root + versionFilePath).contents, "CLI_VERSION = \"" + floorVersion + "\"", command + " did not vendor the pinned release's CLI version") assertContains(generated.file(root + "sdk/entrypoint/dang.toml").contents, "dagger = \"v" + floorVersion + "\"", command + " did not write the pinned release to dang.toml") - assertNotContains(generated.file(root + coreInitPath).contents, newInBeta22, command + " did not read core in the view of the pinned release") null } @@ -2011,11 +2057,10 @@ type E2e { let callerSecretPath: String! = "review-secret.txt" """ - The first release that loads a module's files through its entrypoint's - sources member, and the oldest one a targetVersion pin may name. Its engine - image carries its CLI, and git. + The oldest release a targetVersion pin may name, the SDK's engine floor. Its + engine image carries its CLI, and git. """ - let floorVersion: String! = "1.0.0-beta.18" + let floorVersion: String! = "1.0.0-beta.26" let floorImage: String! { "registry.dagger.io/engine:v" + floorVersion } """ @@ -2078,30 +2123,6 @@ type E2e { ctr.withExec(["dagger"] + args, experimentalPrivilegedNesting: true) } - """ - Main object names derive from module names as in the engine's builtin Python - runtime, so a module keeps loading when it moves between the two. - """ - pub runtimeNamingCheck: Void @check { - [ - ["my-module", "MyModule"], - ["my_module", "MyModule"], - ["myModule", "MyModule"], - ["MyModule", "MyModule"], - ["HTTPServer", "Httpserver"], - ["s3-bucket", "S3Bucket"], - ["app2", "App2"], - ["a.b c", "ABC"], - ].each { pair => - let name = pair[0] ?? "" - let want = pair[1] ?? "" - let got = pythonSdkRuntime.mainObjectName(name) - assert(got == want, "main object name for " + name + ": got " + got + ", want " + want) - } - - null - } - let sdkSource(ws: Workspace!): Directory! { ws .directory("/", include: ["sdk/**", "!sdk/**/.venv", "!sdk/**/__pycache__"]) @@ -2172,7 +2193,7 @@ type E2e { let core = ws.directory("/helpers/core-schema").asModuleSource sdkContainer(ws) .withFile("/core-only.py", ws.file("/helpers/core-schema/core_only.py")) - .withFile("/schema.json", core.withEngineVersion(core.engineVersion).clientSchemaIntrospectionJSON) + .withFile("/schema.json", core.withEngineVersion(core.engineVersion).clientSchemaIntrospectionJson) .withExec(["python", "/core-only.py", "/schema.json", "/core.json"]) .withExec(["uv", "run", "--frozen", "python", "-m", "codegen", "generate", "-i", "/core.json", "-o", sdkBindingsPath]) .withExec(["uv", "run", "--frozen", "ruff", "check", "--fix-only", sdkBindingsPath]) @@ -2343,53 +2364,6 @@ type E2e { null } - """ - The SDK refuses an engine release older than its floor before it generates - anything, and names the version it found and what to do: pin the SDK's last - release before the floor where that release runs, from v1.0.0-beta.14, and - only upgrade below it. Releases are compared as semver orders them, with - the build after a "+" ignored and no word such as "dev" set apart, so a - build of dagger's main passes as the release it reports. A version the - SDK cannot read passes, so an unexpected format never blocks a user. On - an engine the SDK refuses, generation itself refuses. - """ - pub engineFloorRefusalCheck(ws: Workspace!): Void @check { - let pin = "dagger module install github.com/dagger/python-sdk@v1.1.1" - let pinned = ["v1.0.0-beta.17", "v1.0.0-beta.17+0da36c8d", "v1.0.0-beta.17+dev", "v1.0.0-beta.16", "v1.0.0-beta.15", "v1.0.0-beta.14", "v1.0.0-beta.14+06660c3c"] - let upgradeOnly = ["v1.0.0-beta.13", "v1.0.0-beta.9", "v1.0.0-alpha.20", "v0.21.9", "v0.21.1-20260529020034-dev-b2f595b50044", "v1.0.0-alpha-1"] - let accepted = [ - "v1.0.0-beta.18", "v1.0.0-beta.18+249edbd6", "v1.0.0-beta.18+dev", "1.0.0-beta.18", "v1.0.0-beta.19", "v1.0.0-beta.100", - "v1.0.0-beta.1000000000000000000000", "v1.0.0-rc.1", "v1.0.0-rc-1", "v1.0.0", "v1.0.1", "v2.0.0-beta.1", "v1.0.0-dev.3", "devel", "", - ] - (pinned + upgradeOnly).each { engine => - let refusal = pythonSdk.engineRefusal(engine) - let wants = ["needs Dagger engine v" + floorVersion + " or later", "this engine is " + engine + ".", "Upgrade the engine"] - wants.each { want => - assertContains(refusal, want, "engine \"" + engine + "\": the refusal does not say \"" + want + "\": " + refusal) - } - } - pinned.each { engine => - let refusal = pythonSdk.engineRefusal(engine) - assertContains(refusal, pin, "engine \"" + engine + "\": the refusal does not offer the last release that runs on it: " + refusal) - } - upgradeOnly.each { engine => - let refusal = pythonSdk.engineRefusal(engine) - assertNotContains(refusal, "pin", "engine \"" + engine + "\": the refusal offers a release that does not run on it either: " + refusal) - } - accepted.each { engine => - let refusal = pythonSdk.engineRefusal(engine) - assert(refusal == "", "the SDK refused engine \"" + engine + "\": " + refusal) - } - let refusal = pythonSdk.engineRefusal(version) - if (refusal != "") { - let said = pythonSdk.generateScope(ws.withNewDirectory("/floor-probe", directory).withWorkdir("floor-probe"), isModule: true, name: "floor-probe", clients: []).cwd rescue { - err: Error => err.message - } - assert(said.contains(refusal), "generation on engine " + version + ", which the SDK refuses, said: " + said) - } - null - } - """ A module declares a collection, on this checkout's shared entrypoint, on the one generated into it, and on this checkout's runtime, which registers @@ -2631,8 +2605,8 @@ type E2e { sdk/entrypoint, whether the path exists or not. A module generated directly refuses what the written manifest cannot carry, a [clients] table, disableDefaultFunctionCaching or a [codegen] table, as the scope - path does, rather than dropping it. The moved module runs on - v1.0.0-beta.18 or later, and generating it needs v1.0.0-beta.26 or later. + path does, rather than dropping it. Running the moved module and generating + it both need v1.0.0-beta.26 or later. """ pub remoteEntrypointReplacedCheck(ws: Workspace!): Void @check { let manifestPath = "/" + tomlGenerateModulePath + "/dagger-module.toml" @@ -3141,4 +3115,75 @@ type E2e { ) } + let namingFixturePath: String! = fixtureRoot + "/naming" + + """ + naming-app generated as a static entrypoint module, and naming-caller + generated with a client of it, in a workspace of their own. Both use the + SDK's released target, past the identifier casing cut. With pinned, an old + leaf config is replaced before naming. + """ + let namingScope(ws: Workspace!, pinned: Boolean!): Workspace! { + let app = ws.directory("/" + namingFixturePath + "/app") + let tree = directory + .withDirectory("naming-app", app) + .withDirectory("naming-caller", ws.directory("/" + namingFixturePath + "/caller")) + let fresh = pythonSdk.generateScope(tree.asWorkspace.withWorkdir("naming-app"), isModule: true, name: "naming-app", clients: []) + .withWorkdir(".") + let withApp = if (pinned) { + let older = fresh.withNewFile("/naming-app/sdk/entrypoint/dang.toml", "[imports.Dagger]\ndagger = \"v" + floorVersion + "\"\n") + pythonSdk.generateScope(older.withWorkdir("naming-app"), isModule: true, name: "naming-app", clients: []).withWorkdir(".") + } else { fresh } + pythonSdk.generateScope(withApp.withWorkdir("naming-caller"), isModule: true, name: "naming-caller", clients: [withApp.moduleSource("/naming-app")]) + .withWorkdir(".") + } + + let pyFiles(generated: Workspace!, path: String!): String! { + let root = generated.directory("/" + path) + root.glob("**/*.py").map { file => root.file(file).contents }.join("\n") + } + + """ + The engine names a module's declarations by the version it names the module + by, and the SDK follows the config generation actually writes: + + - generation spells the Python names of every schema identifier as the + engine does (experimental_with_all_gpus in core, whatever the version); + - the client generated for naming-app names its declarations as the + engine does at the released target (NamingAppHTTPFetcher and ARM64); + - naming-app's runtime, called through that client, calls its own + interface by the names the engine gave it (the namespaced type and its + function), so the call returns. + + Its interface takes no own enum, which the engine refuses in the module's + own session. + """ + pub namingCheck(ws: Workspace!): Void @check { + [ + {{pinned: false, iface: "NamingAppHTTPFetcher", member: "ARM64"}}, + {{pinned: true, iface: "NamingAppHTTPFetcher", member: "ARM64"}}, + ].each { want => + let label = if (want.pinned) { "naming-app with an upgraded config" } else { "naming-app with a new config" } + let generated = namingScope(ws, want.pinned) + let target = pythonSdk.targetVersionOf("") + assertContains(generated.file("/naming-app/sdk/entrypoint/dang.toml").contents, "dagger = \"" + target + "\"", label + ": wrong generated config") + assert(generated.moduleSource("/naming-app").naming.version == target, label + ": naming does not match the final config") + let core = pyFiles(generated, "naming-caller/clients/core/src") + assertContains(core, "def experimental_with_all_gpus(", label + ": core's Python names are not the engine's") + let client = pyFiles(generated, "naming-caller/clients/naming-app/src") + assertContains(client, "class " + want.iface, label + ": the client does not name the interface " + want.iface) + assertContains(client, want.member + " = ", label + ": the client does not name the enum member " + want.member) + assertContains(client, "def get_url(", label + ": the client does not name get_url") + let outcomes = generated.withModule("naming-caller", name: "naming-caller") + .artifacts(include: ["naming-caller:fetch-check"]).asChecks + .{{ pass, error.{{ message }} }} + assert(outcomes.length == 1, label + ": expected the fetch check, got " + toString(outcomes.length)) + # Selected on `pass` first: reading the message of a check that passed + # raises an evaluation error of its own. + let failed = outcomes.filter { c => c.pass == false }.map { c => c.error.message } + assert(failed.length == 0, label + ": the call through its interface failed: " + failed.join("\n")) + null + } + null + } } diff --git a/README.md b/README.md index bf2ba8a1..8b015ecd 100644 --- a/README.md +++ b/README.md @@ -48,29 +48,30 @@ There are three answers, and a new module gets the first: | `[entrypoint] source = ` | a Dang entrypoint of the user's own, kept as written | | `[runtime] source = ` | a module runtime, which builds and runs the module itself | -This SDK needs an engine `v1.0.0-beta.26` or later: it reads a scope's +This SDK needs an engine `v1.0.0-beta.26` or later. It reads a scope's settings through `WorkspaceSDK.scopeSetting`, which [dagger/dagger#15084](https://github.com/dagger/dagger/pull/15084) adds in that -release. The entrypoint it generates into a module needs an engine -`v1.0.0-beta.18` or later, the first release that loads a module's files -through its entrypoint's `sources` member. An entrypoint runs a module on the -engine's own version, so an entrypoint manifest keeps no `engineVersion`. - -On an engine without that field, `dagger module init` and `dagger generate` -fail while they load the SDK, before they write anything. A -generated entrypoint fails to load on an older engine with `field "types": -missing argument "workspace" required by interface`. To stay on an engine from -v1.0.0-beta.14 to v1.0.0-beta.17, pin `v1.1.1`, the last release that runs -there: `dagger module install github.com/dagger/python-sdk@v1.1.1`, and -`dagger.io/sdk/python/entrypoint@v1.1.1` for the shared entrypoint of that -release. An engine older than v1.0.0-beta.14 runs neither release, and needs -an upgrade. +release. It also needs the first release that names identifiers by its naming +rules and answers for them: generation asks it how to spell the Python names of +the schema's identifiers, and a module asks it what it named the module's own +declarations. An entrypoint manifest keeps no `engineVersion` (see "The Dagger +version of a generated entrypoint"). The final config and manifest are staged +before naming or main-object selection, so those answers describe the module +generation actually writes. + +The SDK's modules declare `engineVersion` v1.0.0-beta.26. Engines compare +only the base version, so an engine from v1.0.0-beta.18 to v1.0.0-beta.25 does +not refuse them for it: `dagger module init` and `dagger generate` fail while +they load the SDK, before they write anything. To stay on such an engine, pin a +release from before this floor, such as `v1.8.0`: +`dagger module install github.com/dagger/python-sdk@v1.8.0`. To stay on an +engine from v1.0.0-beta.14 to v1.0.0-beta.17, pin `v1.1.1`, the last release +that runs there. An entrypoint served from elsewhere, such as the shared one this repository used to serve as `dagger.io/sdk/python/entrypoint@v1`, a pin of it or a fork, is replaced by the generated entrypoint at the module's next -`dagger generate`. A module moved this way needs an engine `v1.0.0-beta.18` or -later to run, and generating it needs `v1.0.0-beta.26` or later. +`dagger generate`. Generating a module that has a manifest already keeps the kind it names: @@ -131,7 +132,7 @@ for and announces: The scope setting `targetVersion`, under `[sdks.python.scopes."".settings]` in `dagger.toml`, pins the -release, from `v1.0.0-beta.18` to the targeted release; +release, from `v1.0.0-beta.26` to the targeted release; `dagger module init python --target-version ` writes it. Any other value stops generation before it writes anything, with a message that names the module and says why. @@ -255,9 +256,10 @@ The two declarations reach an engine in different ways: - `dang.toml`: [dagger/dagger#14902](https://github.com/dagger/dagger/pull/14902), first released in v1.0.0-beta.26, makes an engine take the module's Dagger version from the file. Engines up to v1.0.0-beta.25 do not read it. It also - refuses an entrypoint whose imports declare different Dagger versions, and - serves v1.0.0-beta.25 to an entrypoint whose `dang.toml` declares no Dagger - version. + refuses an entrypoint whose imports declare different Dagger versions, so + generation stops with that error, and serves v1.0.0-beta.25, the last release + before the identifier casing cut, to an entrypoint whose `dang.toml` declares + no Dagger version. - `DAGGER_CLIENT_VERSION`: [dagger/dagger#14881](https://github.com/dagger/dagger/pull/14881), first released in v1.0.0-beta.22, makes an engine serve that version's view to the process. Engines up to v1.0.0-beta.21 do not read it. diff --git a/dang.toml b/dang.toml new file mode 100644 index 00000000..8aac7f14 --- /dev/null +++ b/dang.toml @@ -0,0 +1,2 @@ +[imports.Dagger] +dagger = "v1.0.0-beta.26" diff --git a/docs/collections.md b/docs/collections.md index b72e3fe6..f23b8476 100644 --- a/docs/collections.md +++ b/docs/collections.md @@ -1,9 +1,8 @@ # Collections A collection is a set of objects that a module discovers at run time, each -with a unique key. Generating a module with this SDK needs an engine -v1.0.0-beta.26 or later, and the generated entrypoint runs on v1.0.0-beta.18 or -later. The engine serves collections from v1.0.0-beta.15 +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)), and v1.0.0-beta.17 adds the projected types every `dagger call` into a collection resolves ([dagger/dagger#14447](https://github.com/dagger/dagger/pull/14447)) diff --git a/helpers/pyproject/python.go b/helpers/pyproject/python.go index 926174fd..325c5f80 100644 --- a/helpers/pyproject/python.go +++ b/helpers/pyproject/python.go @@ -17,7 +17,7 @@ const pythonFloor = "3.11" // lastReleaseBelowPythonFloor is the last release of this SDK, whose floor // was lastReleasePythonFloor. A refusal offers it only to a Python that -// release runs on, as engineRefusal in python-sdk.dang does for engines. +// release runs on. const ( lastReleaseBelowPythonFloor = "v1.2.0" lastReleasePythonFloor = "3.10" diff --git a/helpers/render-template/go.mod b/helpers/render-template/go.mod index f4d77667..daef993a 100644 --- a/helpers/render-template/go.mod +++ b/helpers/render-template/go.mod @@ -1,5 +1,3 @@ module render-template go 1.25.0 - -require github.com/iancoleman/strcase v0.3.0 diff --git a/helpers/render-template/go.sum b/helpers/render-template/go.sum deleted file mode 100644 index 6261b6ac..00000000 --- a/helpers/render-template/go.sum +++ /dev/null @@ -1,2 +0,0 @@ -github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= -github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= diff --git a/helpers/render-template/main.go b/helpers/render-template/main.go index d025be46..ebf3e18f 100644 --- a/helpers/render-template/main.go +++ b/helpers/render-template/main.go @@ -8,8 +8,6 @@ import ( "regexp" "strings" "text/template" - - "github.com/iancoleman/strcase" ) func main() { @@ -28,19 +26,22 @@ func packageName(moduleName string) string { return strings.ReplaceAll(project, "-", "_") } +// run renders the template for a module. MODULE_TYPE names the main class: +// the module's type name as the engine will name the module, which the caller +// asks the engine for. func run(args []string) error { - if len(args) != 3 { - return fmt.Errorf("usage: render-template MODULE_NAME TEMPLATE_DIR OUT_DIR") + if len(args) != 4 { + return fmt.Errorf("usage: render-template MODULE_NAME MODULE_TYPE TEMPLATE_DIR OUT_DIR") } moduleName := args[0] - templateDir := args[1] - outDir := args[2] + moduleType := args[1] + templateDir := args[2] + outDir := args[3] data := map[string]string{ "ModuleName": moduleName, "ModuleProject": strings.ToLower(moduleName), - "ModuleType": strcase.ToCamel(moduleName), - "ModuleImport": "dagger/" + strcase.ToKebab(moduleName), + "ModuleType": moduleType, "ModulePackage": packageName(moduleName), } diff --git a/helpers/render-template/main_test.go b/helpers/render-template/main_test.go index c3ae38e8..03d022fd 100644 --- a/helpers/render-template/main_test.go +++ b/helpers/render-template/main_test.go @@ -22,7 +22,7 @@ func TestRenderedPackageMatchesTheRuntime(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { out := t.TempDir() - if err := run([]string{tc.name, filepath.Join("..", "..", "templates", "default"), out}); err != nil { + if err := run([]string{tc.name, "Main", filepath.Join("..", "..", "templates", "default"), out}); err != nil { t.Fatal(err) } if _, err := os.Stat(filepath.Join(out, "src", tc.pkg, "__init__.py")); err != nil { diff --git a/mod.dang b/mod.dang index c7c9920f..8fdeead2 100644 --- a/mod.dang +++ b/mod.dang @@ -129,13 +129,9 @@ type Mod { if (entrypointMode == "generated") { let outside = PyprojectHelper().outsidePaths(scoped, rootPath) checkResourcesLoad(scoped, outside) - let withEntrypoint = scoped.withDirectory("/" + rootPath + "/" + entrypointPath, entrypointDir(scoped, patterns(outside))) - let entrypointDirectory = withEntrypoint.withWorkdir(modulePath(entrypointPath)) - let configured = sdkHelpers.loadDangConfig(entrypointDirectory) - .withVersion("2.1") - .withDaggerImport(name: "Dagger", version: targetVersion) - .generate(entrypointDirectory) - entrypointManifest(configured.withWorkdir("."), entrypointPath) + let configured = namedWorkspace(scoped, entrypointPath) + configured.withDirectory("/" + rootPath + "/" + entrypointPath, + entrypointDir(configured, patterns(outside), entrypointPath)) } else if (entrypointMode == "own") { checkNoResources(PyprojectHelper().outsidePaths(scoped, rootPath)) scoped @@ -152,9 +148,9 @@ type Mod { """ Refuse a module that asks for an older Python than the SDK runs on before anything is written: uv would lock it to the SDK's Python, and the runtime - would still build it on the older one, where the install fails. Beside - checkEngine, which refuses the engine: this one reads the module, so only - generation runs it, and config set stays open to fix the module. + would still build it on the older one, where the install fails. It reads + the module, so only generation runs it, and config set stays open to fix + the module. """ let checkPython: Void { let refusal = PyprojectHelper().pythonRefusal(ws.directory("/" + rootPath, include: ["pyproject.toml", ".python-version"])) @@ -237,7 +233,9 @@ type Mod { yet. So the runtime manifest points back at the module being built. """ let staging(target: Workspace!, outside: [String!]!): Workspace! { - if (hasEntrypointManifest) { + # The final entrypoint manifest is already staged for naming, even when + # the input module originally used a runtime or had no entrypoint. + if (hasEntrypointManifest or entrypointMode == "generated") { let loaded = sdkHelpers.moduleManifest(loadToml: ws.file("/" + manifestPath)).withoutEntrypoint # A static entrypoint manifest holds no runtime, and the engine refuses a # manifest with neither. Dang, not Python: the engine loads the added @@ -261,10 +259,15 @@ type Mod { """ The entrypoint the engine loads instead of calling a runtime: the module's own container renders its types, and the container build travels with it. + The main object, the class that gets the constructor, is the one the engine + takes by its naming of the module the entrypoint serves (namedSource). """ - let entrypointDir(generated: Workspace!, outside: [String!]!): Directory! { + let entrypointDir(generated: Workspace!, outside: [String!]!, entrypointPath: String!): Directory! { pythonSdkRuntime - .moduleRuntime(modSource: staging(generated, outside).moduleSource("/" + rootPath), introspectionJson: null) + .installed( + modSource: staging(generated, outside).moduleSource("/" + rootPath), + naming: namedSource(generated, entrypointPath).naming, + ) .withExec(["python", "-m", "dagger.mod", "entrypoint", "--name", moduleName, "--client-version", targetVersion, "--output", entrypointOutput] + outside.map { pattern => "--outside=" + pattern }) .directory(entrypointOutput) @@ -272,6 +275,42 @@ type Mod { .withNewFile("workspace_reader.py", currentModule.source.file("runtime/workspace_reader.py").contents) } + """ + The engine's naming of this module as generation writes it: the source the + static entrypoint is named by (namedSource), or else the module as its + manifest has it. + """ + pub naming: ModuleNaming! { + if (entrypointMode == "generated") { + namedSource(ws, vendorDirName + "/" + entrypointDirName).naming + } else { + ws.moduleSource("/" + rootPath).naming + } + } + + """ + The module the engine names once the entrypoint is generated: the manifest + this generation writes, with the entrypoint's directory in place, since the + dang.toml governing it decides the version the module is named by. + """ + let namedSource(target: Workspace!, entrypointPath: String!): ModuleSource! { + namedWorkspace(target, entrypointPath).moduleSource("/" + rootPath) + } + + """ + The final manifest and config, before main-object selection or building the + entrypoint. Reuse this workspace in the output so naming never observes the + previous import while the generated module declares a different version. + """ + let namedWorkspace(target: Workspace!, entrypointPath: String!): Workspace! { + let dir = target.withDirectory("/" + modulePath(entrypointPath), directory).withWorkdir(modulePath(entrypointPath)) + let configured = sdkHelpers.loadDangConfig(dir) + .withVersion("2.1") + .withDaggerImport(name: "Dagger", version: targetVersion) + .generate(dir) + entrypointManifest(configured.withWorkdir("."), entrypointPath) + } + """ runtime/build.dang with its reads of this module's source inlined, so the copy in a generated entrypoint needs nothing but itself and the workspace diff --git a/python-sdk.dang b/python-sdk.dang index 0f9c4918..3bf7ee9e 100644 --- a/python-sdk.dang +++ b/python-sdk.dang @@ -32,7 +32,7 @@ type PythonSdk { pub legacyRuntime: Boolean! = false """ - The engine release to generate for, from v1.0.0-beta.18 to the release + The engine release to generate for, from v1.0.0-beta.26 to the release this SDK targets; empty generates for the targeted release. """ pub targetVersion: String! = "" @@ -161,7 +161,6 @@ type PythonSdk { entrypoint served from elsewhere is replaced by the generated one. """ pub generateScope(ws: Workspace!, isModule: Boolean!, name: String!, clients: [ModuleSource!]!): Workspace! { - checkEngine let scope = normalizePath(ws.cwd) checkTarget(if (isModule) { "module \"" + name + "\"" } else { "scope " + scope }, targetVersion) # Resolve local client paths from the workspace root. @@ -173,7 +172,7 @@ type PythonSdk { let initialized = if (hadConfig) { rooted } else { - let files = moduleTemplate(name, template, pythonVersion, useUv, baseImage) + let files = moduleTemplate(name, mainTypeName(rooted, scope, name), template, pythonVersion, useUv, baseImage) # A module directory's own .gitignore is the user's. let kept = if (scopeHasFile(ws, scope, ".gitignore")) { files.withoutFile(".gitignore") } else { files } # An additive changeset names only template paths. Merging a whole @@ -260,7 +259,7 @@ type PythonSdk { The module runs on the Dang entrypoint generated into it, or on one of the user's own in its files, and on nothing else: an entrypoint served from elsewhere, the one this repository used to share among them, is replaced - by the generated one, which needs an engine v1.0.0-beta.18 or later. + by the generated one, which needs an engine v1.0.0-beta.26 or later. The runtime this SDK used to write, `[runtime] source = "python"`, goes, and so does what only a runtime reads: engineVersion, since an entrypoint runs a module on the engine's own version. Any other runtime is one the @@ -291,7 +290,7 @@ type PythonSdk { # generator reads core in; what only a runtime can honour stays as # written. Inline at each site: sdk-helpers' type names change with its # own declared engineVersion (SdkHelpers… vs SDKHelpers… from the - # v1.0.0-beta.22 naming rules), so this module must not spell them. + # v1.0.0-beta.26 naming rules), so this module must not spell them. sdkHelpers.moduleManifest(loadToml: manifest).withoutEntrypoint .withLegacyRuntime(runtime: sdkRuntimeSource, engineVersion: sdkEngineVersion) } else if (ours) { @@ -497,10 +496,11 @@ type PythonSdk { let staticEntrypointSource: String! = "./" + staticEntrypointPath """ - The first engine release this SDK runs on: the first that loads a - module's files through its entrypoint's sources member. + The oldest release a targetVersion pin may name: the engine floor. The + generated entrypoint hands the build the engine's ModuleNaming, which the + view of an older release does not serve. """ - let engineFloor: String! = "v1.0.0-beta.18" + let targetFloor: String! = "v1.0.0-beta.26" """ The engine release this SDK release targets: the one it generates for, @@ -509,53 +509,6 @@ type PythonSdk { """ let engineTarget: String! = "v1.0.0-beta.27" - """ - The last release of this SDK that runs on an engine below engineFloor. - """ - let lastReleaseBelowFloor: String! = "v1.1.1" - - """ - The first engine release lastReleaseBelowFloor runs on, as its manifest - declares. - """ - let lastReleaseEngineFloor: String! = "v1.0.0-beta.14" - - """ - Why this SDK refuses an engine of the given version, or the empty string - when it runs on it. Only a release older than the floor is refused: a - version this cannot read passes, so an unexpected format never blocks a - user, and a build of dagger's main passes as the release it reports, - `v+`. The engine's own gate cannot do this: it treats - every prerelease of v1.0.0 as v1.0.0. The refusal offers the last release - below the floor only to an engine that release runs on. - """ - pub engineRefusal(engineVersion: String!): String! { - if (Releases().precedes(engineVersion, engineFloor) == false) { - "" - } else { - let needs = "this Python SDK needs Dagger engine " + engineFloor + " or later, and this engine is " + - engineVersion + ". " - if (Releases().precedes(engineVersion, lastReleaseEngineFloor)) { - needs + "Upgrade the engine." - } else { - needs + "Upgrade the engine, or pin the last release of this SDK that runs on it: " + - "dagger module install github.com/dagger/python-sdk@" + lastReleaseBelowFloor - } - } - } - - """ - Refuse an engine older than the floor before generation reads or writes - anything, so the user reads why instead of an unknown field later. - """ - let checkEngine: Void { - let refusal = engineRefusal(version) - if (refusal != "") { - raise refusal - } - null - } - """ The engine release a scope generates for: the targetVersion setting as a `v`-prefixed release, or the release this SDK targets when it is empty. @@ -581,8 +534,8 @@ type PythonSdk { } else if (releases.precedes(engineTarget, target)) { pins + target + ", which is later than " + engineTarget + ", the engine release this Python SDK generates for: install the SDK release built for " + target + ", or set targetVersion in its dagger.toml settings to " + engineTarget + ", or remove it" - } else if (releases.precedes(target, engineFloor)) { - pins + target + ", which is below " + engineFloor + ", the oldest release a targetVersion pin may name" + remedy + } else if (releases.precedes(target, targetFloor)) { + pins + target + ", which is below " + targetFloor + ", the oldest release a targetVersion pin may name" + remedy } else { "" } @@ -736,7 +689,6 @@ type PythonSdk { targetVersion. """ pub mod(ws: Workspace!, path: String! = ".", findUp: Boolean! = true): Mod! { - checkEngine let modPath = if (findUp) { managedModuleAtOrAbove(ws, path) } else { @@ -775,12 +727,36 @@ type PythonSdk { } } + """ + The main class name of a new module: the module's type name as the engine + will name the module, asked of the module as generation writes it, before + it has any code. The engine names a module by its version's rules, which + spell an acronym differently on either side of the identifier casing cut. + """ + let mainTypeName(ws: Workspace!, scope: String!, name: String!): String! { + let staged = Mod( + rootPath: scope, + ws: generateScopeManifest(ws, scope, name), + entrypointMode: entrypointModeOf(ws, scope), + migrating: false, + engineVersion: "", + targetVersion: targetVersionOf(targetVersion), + clients: [] :: [ModuleSource!]!, + ) + let names = staged.naming.typeNames(names: [name]) + if (names.length != 1) { + raise "the engine named " + toString(names.length) + " types for module \"" + name + "\"" + } else { + names[0] ?? "" + } + } + """ The files of a new module: the named template rendered for the module name, with the pyproject.toml settings applied. An empty template name selects the default. """ - let moduleTemplate(name: String!, template: String!, pythonVersion: String!, useUv: Boolean!, baseImage: String!): Directory! { + let moduleTemplate(name: String!, typeName: String!, template: String!, pythonVersion: String!, useUv: Boolean!, baseImage: String!): Directory! { let selectedTemplate = if (template == "") { "default" } else { template } let known = currentModule.source.directory("templates").entries.map { entry => entry.trimSuffix("/") } @@ -788,14 +764,15 @@ type PythonSdk { if (known.filter { entry => entry == selectedTemplate }.length == 0) { raise "unknown init template: " + template } else { - configuredTemplate(renderedTemplate(name, selectedTemplate), pythonVersion, useUv, baseImage) + configuredTemplate(renderedTemplate(name, typeName, selectedTemplate), pythonVersion, useUv, baseImage) } } """ - Render a Python template with the requested module name. + Render a Python template with the requested module name, its main class + named typeName. """ - let renderedTemplate(name: String!, templateName: String!): Directory! { + let renderedTemplate(name: String!, typeName: String!, templateName: String!): Directory! { container .from("golang:1.25-alpine") .withoutEntrypoint @@ -805,7 +782,7 @@ type PythonSdk { .withDirectory("/template", currentModule.source.directory("templates/" + templateName)) .withWorkdir("/helper") .withExec(["go", "build", "-o", "/usr/local/bin/render-template", "."]) - .withExec(["render-template", name, "/template", "/rendered"]) + .withExec(["render-template", name, typeName, "/template", "/rendered"]) .directory("/rendered") } diff --git a/runtime/build.dang b/runtime/build.dang index c7622dd8..f9c15246 100644 --- a/runtime/build.dang +++ b/runtime/build.dang @@ -18,10 +18,16 @@ type PythonModuleBuild { pub moduleName: String! - new(contextDir: Directory! = directory, subPath: String! = ".", moduleName: String! = "") { + """ + How the engine names the module, which says which class is its main object. + """ + pub naming: ModuleNaming + + new(contextDir: Directory! = directory, subPath: String! = ".", moduleName: String! = "", naming: ModuleNaming = null) { self.contextDir = contextDir self.subPath = subPath self.moduleName = moduleName + self.naming = naming self } @@ -90,51 +96,74 @@ type PythonModuleBuild { # Last, so the layers above are shared between modules. .withEnvVariable("DAGGER_MODULE", moduleName) .withEnvVariable("DAGGER_DEFAULT_PYTHON_PACKAGE", packageName) - .withEnvVariable("DAGGER_MAIN_OBJECT", mainObjectName(moduleName)) install(built, source, cfg) + .withEnvVariable("DAGGER_MAIN_OBJECT", mainObject) } } """ - The workspace members of a scope's pyproject.toml, read as the build does. + The class name of the module's main object: of the classes its code + decorates with @object_type, the one the engine takes. """ - pub scopeMembers(pyproject: File!): [String!]! { - pyConfig(directory.withFile(projectCfg, pyproject), ".").members + let mainObject: String! { + if (naming == null) { + raise "module \"" + moduleName + "\" is built without the engine's naming of it" + } else { + let candidates = objectTypes + let main = naming.mainObject(candidates: candidates) + if (main == null) { + raise "module \"" + moduleName + "\": the engine takes none of its object types (" + + (if (candidates.length == 0) { "there are none" } else { candidates.join(", ") }) + + ") for its main object; name a class decorated with @object_type after the module" + } else { + main + } + } } """ - The class name of a module's main object, converted like the engine's builtin - Python runtime (strcase.ToCamel) so a module loads the same on both. - """ - pub mainObjectName(name: String!): String! { - name - .trimSpace - .split("") - .reduce(CamelState(out: "", capNext: true, prevIsCap: false)) { state, c => - let isCap = c.containsMatch("^[A-Z]$") - let isLow = c.containsMatch("^[a-z]$") - let isNum = c.containsMatch("^[0-9]$") - if (isCap or isLow) { - let v = if (state.capNext and isLow) { - c.toUpper - } else if (state.capNext == false and state.prevIsCap and isCap) { - c.toLower - } else { - c - } - CamelState(out: state.out + v, capNext: false, prevIsCap: isCap) - } else if (isNum) { - CamelState(out: state.out + c, capNext: true, prevIsCap: false) - } else { - CamelState( - out: state.out, - capNext: c == "_" or c == " " or c == "-" or c == ".", - prevIsCap: false, - ) - } - } - .out + The classes the module's own code decorates with @object_type, read from + its source with Python's ast rather than by importing it, so that it reads + the same whichever SDK version the module installs. A file this Python + can't parse is skipped: the module may never import it. + """ + let objectTypes: [String!]! { + container + .from(defaultBaseImage) + .withMountedDirectory("/module", filesOf( + source, + include: ["src/**/*.py", "*.py"], + exclude: ["**/.venv", "**/__pycache__"], + )) + .withExec(["python", "-c", objectTypesScript, "/module"]) + .stdout + .split("\n") + .filter { line => line != "" } + } + + let objectTypesScript: String! = [ + "import ast, pathlib, sys", + "def name(d):", + " d = d.func if isinstance(d, ast.Call) else d", + " return getattr(d, 'attr', getattr(d, 'id', ''))", + "found = set()", + "for path in pathlib.Path(sys.argv[1]).rglob('*.py'):", + " try:", + " tree = ast.parse(path.read_bytes(), str(path))", + " except (SyntaxError, ValueError):", + " continue", + " for node in ast.walk(tree):", + " if isinstance(node, ast.ClassDef) and any(name(d) == 'object_type' for d in node.decorator_list):", + " found.add(node.name)", + "print('\\n'.join(sorted(found)))", + ].join("\n") + + """ + The workspace members of a scope's pyproject.toml, read as the build does. + """ + pub scopeMembers(pyproject: File!): [String!]! { + pyConfig(directory.withFile(projectCfg, pyproject), ".").members } let base(baseImage: String!, uvImage: String!, cfg: PyConfig!): Container! { @@ -549,19 +578,3 @@ type PyConfig { members.filter { member => member == "sdk" }.length > 0 } } - -""" -Accumulator for the CamelCase conversion of a module name. -""" -type CamelState { - pub out: String! - pub capNext: Boolean! - pub prevIsCap: Boolean! - - new(out: String! = "", capNext: Boolean! = true, prevIsCap: Boolean! = false) { - self.out = out - self.capNext = capNext - self.prevIsCap = prevIsCap - self - } -} diff --git a/runtime/dagger-module.toml b/runtime/dagger-module.toml index 341afcc5..f7ad7efd 100644 --- a/runtime/dagger-module.toml +++ b/runtime/dagger-module.toml @@ -1,5 +1,5 @@ name = "python-sdk-runtime" -engineVersion = "v1.0.0-0" +engineVersion = "v1.0.0-beta.26" [runtime] source = "dang" diff --git a/runtime/dang.toml b/runtime/dang.toml new file mode 100644 index 00000000..8aac7f14 --- /dev/null +++ b/runtime/dang.toml @@ -0,0 +1,2 @@ +[imports.Dagger] +dagger = "v1.0.0-beta.26" diff --git a/runtime/main.dang b/runtime/main.dang index 9d45fa29..11d93013 100644 --- a/runtime/main.dang +++ b/runtime/main.dang @@ -12,11 +12,7 @@ type PythonSdkRuntime { """ pub moduleRuntime(modSource: ModuleSource!, introspectionJson: File): Container! { let modName = modSource.moduleOriginalName - let build = PythonModuleBuild( - contextDir: modSource.contextDirectory, - subPath: modSource.sourceSubpath, - moduleName: modName, - ) + let build = buildOf(modSource, modSource.naming) if (modSource.configExists == false or build.source.exists("pyproject.toml") == false) { raise "module \"" + modName + "\" has no source to trust; run `dagger generate` and commit the generated files" @@ -30,6 +26,15 @@ type PythonSdkRuntime { } } + """ + The module installed, its main object the one `naming` takes. Generation + renders a module's static entrypoint in it, by the naming of the module it + generates, which another source than the one it builds from may decide. + """ + pub installed(modSource: ModuleSource!, naming: ModuleNaming!): Container! { + buildOf(modSource, naming).installed + } + """ The workspace members this runtime reads from a scope's pyproject.toml. Generation checks the file it writes with it. @@ -38,10 +43,12 @@ type PythonSdkRuntime { PythonModuleBuild().scopeMembers(pyproject) } - """ - The class name of a module's main object. - """ - pub mainObjectName(name: String!): String! { - PythonModuleBuild().mainObjectName(name) + let buildOf(modSource: ModuleSource!, naming: ModuleNaming!): PythonModuleBuild! { + PythonModuleBuild( + contextDir: modSource.contextDirectory, + subPath: modSource.sourceSubpath, + moduleName: modSource.moduleOriginalName, + naming: naming, + ) } } diff --git a/scope.dang b/scope.dang index dcbe7194..976a0eff 100644 --- a/scope.dang +++ b/scope.dang @@ -565,8 +565,16 @@ type Scope { .withDirectory("src", clientSource(member)) } + """ + A client's schema: its module as the engine names and serves it, by the + version the module itself declares, with core as the scope sees it. Not + withEngineVersion(view), which would make the module declare the scope's + version and so name its declarations by that version's rules: a client of + a module past the identifier casing cut would call names the engine does + not serve it by. + """ let clientSchema(member: ClientMember!): File! { - let schema = member.source.withEngineVersion(view).clientSchemaIntrospectionJson + let schema = member.source.clientSchemaIntrospectionJson(clientVersion: view) checkClientLoads(member, schema) schema } @@ -700,7 +708,10 @@ type Scope { """ The code generator's environment, synced once per SDK version and shared by - every scope that generates. + every scope that generates. The generator reaches the session it runs in, + as every exec can, because the engine spells the Python names of the + schema's identifiers (formatIdentifiers, see + sdk/codegen/src/codegen/naming.py). """ let codegenEnv: Container! { codegenBase.withExec(["uv", "sync", "--frozen", "--no-dev", "--package", "codegen"]) diff --git a/sdk/codegen/src/codegen/cli.py b/sdk/codegen/src/codegen/cli.py index 42b53f04..b089e05f 100644 --- a/sdk/codegen/src/codegen/cli.py +++ b/sdk/codegen/src/codegen/cli.py @@ -5,7 +5,7 @@ import graphql -from codegen import ast, generator, packages, partition +from codegen import ast, generator, naming, packages, partition def main(argv: list[str] | None = None): @@ -99,7 +99,7 @@ def main(argv: list[str] | None = None): # TODO: Add argument for module init. try: args.run(args) - except partition.ClientError as e: + except (partition.ClientError, naming.NamingError) as e: parser.error(str(e)) @@ -137,9 +137,15 @@ def read_schema(introspection: pathlib.Path) -> tuple[graphql.GraphQLSchema, str return schema, result.get("__schemaVersion", "") +def styled(schema: graphql.GraphQLSchema, version: str): + """Style the schema's identifiers as the engine names them at its version.""" + return naming.styled_by(naming.engine_names([schema], version)) + + def codegen(introspection: pathlib.Path, output: pathlib.Path | None): schema, schema_version = read_schema(introspection) - code = generator.generate(schema, schema_version=schema_version) + with styled(schema, schema_version): + code = generator.generate(schema, schema_version=schema_version) if output: output.write_text(code) @@ -150,21 +156,23 @@ def codegen(introspection: pathlib.Path, output: pathlib.Path | None): def core(introspection: pathlib.Path, output: pathlib.Path): schema, schema_version = read_schema(introspection) - files = packages.core_package(schema, schema_version) + with styled(schema, schema_version): + files = packages.core_package(schema, schema_version) root = packages.write_package(output, partition.CORE, files) sys.stdout.write(f"Core generated successfully to {root}\n") def client(args: argparse.Namespace): schema, schema_version = read_schema(args.introspection) - package, files = packages.client_package( - schema, - args.name, - args.ref, - args.pin, - core_digest=args.core_digest, - schema_version=schema_version, - ) + with styled(schema, schema_version): + package, files = packages.client_package( + schema, + args.name, + args.ref, + args.pin, + core_digest=args.core_digest, + schema_version=schema_version, + ) root = packages.write_package(args.output, package, files) sys.stdout.write(f"Client generated successfully to {root}\n") @@ -176,6 +184,7 @@ def global_client(introspections: list[pathlib.Path], output: pathlib.Path): if len(set(versions)) > 1: msg = f"the schemas have different versions: {', '.join(sorted(set(versions)))}" raise partition.ClientError(msg) - files = packages.global_package(schemas, versions[0]) + with naming.styled_by(naming.engine_names(schemas, versions[0])): + files = packages.global_package(schemas, versions[0]) root = packages.write_global(output, files) sys.stdout.write(f"Global client generated successfully to {root}\n") diff --git a/sdk/codegen/src/codegen/generator.py b/sdk/codegen/src/codegen/generator.py index abb0ee4f..b2139e1c 100644 --- a/sdk/codegen/src/codegen/generator.py +++ b/sdk/codegen/src/codegen/generator.py @@ -49,14 +49,11 @@ get_named_type, is_leaf_type, ) -from graphql.pyutils import camel_to_snake, snake_to_camel from graphql.type.schema import TypeMap +from codegen.naming import snake from codegen.partition import own_fields -ACRONYM_RE = re.compile(r"([A-Z\d]+)(?=[A-Z\d]|$)") -"""Pattern for grouping initialisms.""" - DEPRECATION_RE = re.compile(r"`([a-zA-Z\d_]+)`") """Pattern for extracting replaced references in deprecations.""" @@ -501,10 +498,13 @@ def _format_name(match: re.Match[str]) -> str: def format_name(s: str) -> str: - """Format a GraphQL field or argument name into Python.""" - # rewrite acronyms, initialisms and abbreviations - s = ACRONYM_RE.sub(lambda m: m.group(0).title(), s) - s = camel_to_snake(s) + """Format a GraphQL field or argument name into Python. + + The engine spells it in snake_case (see codegen.naming); a name that + would shadow a keyword or a builtin the bindings use gets a trailing + underscore. + """ + s = snake(s) if iskeyword(s) or s in _reserved_builtins: s += "_" return s @@ -1119,13 +1119,10 @@ def render_body(self, t: GraphQLInputObjectType) -> Iterator[str]: ) ) - # The query builder derives GraphQL names from the Python ones; record - # only those it can't. - names = { - f.name: f.graphql_name - for f in fields - if snake_to_camel(f.name, upper=False) != f.graphql_name - } + # The query builder sends a field by the GraphQL name recorded here: + # the Python name is the engine's spelling, which nothing converts + # back. + names = {f.name: f.graphql_name for f in fields} if names: yield "" yield f"_graphql_names = {tuple(names.items())!r}" diff --git a/sdk/codegen/src/codegen/naming.py b/sdk/codegen/src/codegen/naming.py new file mode 100644 index 00000000..d27c4102 --- /dev/null +++ b/sdk/codegen/src/codegen/naming.py @@ -0,0 +1,178 @@ +"""Python names for the schema's identifiers, as the engine spells them. + +Every Python identifier the generator styles from the schema (methods, +arguments, input fields) is the schema name in snake_case, and the engine is +the one that spells it: ``Query.naming(version:).formatIdentifiers(casing: +SNAKE)``, at the schema's version, so the words are cut by the engine's +naming dictionary (``withGPU`` is ``with_gpu``, ``experimentalWithAllGPUs`` +is ``experimental_with_all_gpus``) rather than by a converter of the SDK's +own. + +The generator asks once, up front, for every name in the schema, and asks +directly for a name it meets that wasn't among them. It is a nested client of +the Dagger session it runs in, which it reaches through +``DAGGER_SESSION_PORT`` and ``DAGGER_SESSION_TOKEN``. A name the engine can't +format fails the generation. +""" + +from __future__ import annotations + +import base64 +import contextlib +import json +import os +import typing +import urllib.error +import urllib.request +from collections.abc import Callable, Iterable, Iterator + +from graphql import ( + GraphQLInputObjectType, + GraphQLInterfaceType, + GraphQLObjectType, + GraphQLSchema, +) + +Format: typing.TypeAlias = Callable[[list[str]], list[str]] +"""Formats names in snake_case, in order.""" + + +class NamingError(Exception): + """The engine couldn't name an identifier.""" + + +_opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + + +class Session: + """The Dagger session the generator runs in, as a nested client.""" + + def __init__(self, port: str, token: str): + self.url = f"http://127.0.0.1:{port}/query" + self.auth = "Basic " + base64.b64encode(f"{token}:".encode()).decode() + + @classmethod + def from_env(cls) -> Session: + port = os.environ.get("DAGGER_SESSION_PORT") + token = os.environ.get("DAGGER_SESSION_TOKEN") + if not port or not token: + msg = ( + "no Dagger session to name identifiers with: DAGGER_SESSION_PORT " + "and DAGGER_SESSION_TOKEN are not set; run the generator as a " + "nested client of a Dagger session" + ) + raise NamingError(msg) + return cls(port, token) + + def query(self, query: str, variables: dict[str, typing.Any]) -> typing.Any: + body = json.dumps({"query": query, "variables": variables}).encode() + request = urllib.request.Request( # noqa: S310 - a localhost URL + self.url, + data=body, + headers={"Content-Type": "application/json", "Authorization": self.auth}, + ) + try: + # The session is local: a proxy the exec inherits must not see it. + with _opener.open(request) as response: + result = json.load(response) + except urllib.error.HTTPError as e: + try: + result = json.load(e) + except ValueError: + msg = f"the Dagger session answered HTTP {e.code}: {e.reason}" + raise NamingError(msg) from e + if errors := result.get("errors"): + msg = "; ".join(str(e.get("message", e)) for e in errors) + raise NamingError(msg) + return result["data"] + + def formatter(self, version: str) -> Format: + """Format names with formatIdentifiers at a version (empty: the caller's).""" + if version: + query = ( + "query FormatIdentifiers($names: [String!]!, $version: String!) {\n" + " naming(version: $version) {\n" + " formatIdentifiers(names: $names, casing: SNAKE)\n" + " }\n" + "}" + ) + else: + query = ( + "query FormatIdentifiers($names: [String!]!) {\n" + " naming { formatIdentifiers(names: $names, casing: SNAKE) }\n" + "}" + ) + + def fmt(names: list[str]) -> list[str]: + variables: dict[str, typing.Any] = {"names": names} + if version: + variables["version"] = version + formatted = self.query(query, variables)["naming"]["formatIdentifiers"] + if len(formatted) != len(names): + msg = f"formatIdentifiers gave {len(formatted)} of {len(names)} names" + raise NamingError(msg) + return formatted + + return fmt + + +class SnakeNames: + """Names in snake_case, formatted up front and on a miss.""" + + def __init__(self, fmt: Format): + self._fmt = fmt + self._names: dict[str, str] = {} + + def prefetch(self, names: Iterable[str]) -> None: + """Format every name not formatted yet, in one call.""" + missing = sorted({n for n in names if n not in self._names}) + if missing: + self._names.update(zip(missing, self._fmt(missing), strict=True)) + + def __call__(self, name: str) -> str: + if name not in self._names: + self.prefetch([name]) + return self._names[name] + + +def schema_names(schema: GraphQLSchema) -> Iterator[str]: + """Every name in a schema the generator may style: types, fields, args.""" + for type_name, t in schema.type_map.items(): + if type_name.startswith("__"): + continue + yield type_name + if isinstance(t, GraphQLObjectType | GraphQLInterfaceType): + for field_name, f in t.fields.items(): + yield field_name + yield from f.args + elif isinstance(t, GraphQLInputObjectType): + yield from t.fields + + +_current: SnakeNames | None = None + + +@contextlib.contextmanager +def styled_by(names: SnakeNames) -> Iterator[SnakeNames]: + """Style identifiers by these names while generating.""" + global _current # noqa: PLW0603 + previous, _current = _current, names + try: + yield names + finally: + _current = previous + + +def snake(name: str) -> str: + """A schema name in snake_case, as the engine spells it.""" + if _current is None: + msg = "no engine to name identifiers with (see codegen.naming.styled_by)" + raise NamingError(msg) + return _current(name) + + +def engine_names(schemas: Iterable[GraphQLSchema], version: str) -> SnakeNames: + """The names of the schemas, formatted by the session's engine at version.""" + names = SnakeNames(Session.from_env().formatter(version)) + names.prefetch(n for schema in schemas for n in schema_names(schema)) + return names diff --git a/sdk/src/dagger/client/_core.py b/sdk/src/dagger/client/_core.py index c5d3987b..078e32d3 100644 --- a/sdk/src/dagger/client/_core.py +++ b/sdk/src/dagger/client/_core.py @@ -43,22 +43,9 @@ INDENT = " " -_SNAKE_TO_CAMEL_RE = re.compile(r"(_)([a-z\d])") _ENUM_NAME_RE = re.compile(r"[_A-Za-z][_0-9A-Za-z]*") -def snake_to_camel(s: str, upper: bool = True) -> str: - """Convert from snake_case to CamelCase. - - If upper is set, then convert to upper CamelCase, otherwise the first - character keeps its case. - """ - s = _SNAKE_TO_CAMEL_RE.sub(lambda m: m.group(2).upper(), s) - if upper: - s = s[:1].upper() + s[1:] - return s - - class EnumName(str): """A schema enum value, for callers that have no generated enum to send.""" @@ -151,14 +138,18 @@ def _enum_literal(value: enum.Enum | EnumName) -> str: def _input_literal(obj: Input) -> str: - # The generator records only the GraphQL names snake_to_camel can't derive. + # The generator records each field's GraphQL name. names = dict(getattr(type(obj), "_graphql_names", ())) fields = [] for f in dataclasses.fields(obj): value = getattr(obj, f.name) if f.default is not MISSING and value == f.default: continue - name = names.get(f.name) or snake_to_camel(f.name, upper=False) + try: + name = names[f.name] + except KeyError: + msg = f"{type(obj).__name__} records no GraphQL name for {f.name!r}" + raise InvalidQueryError(msg) from None fields.append(f"{name}: {to_literal(value)}") return "{" + ", ".join(fields) + "}" diff --git a/sdk/src/dagger/mod/_converter.py b/sdk/src/dagger/mod/_converter.py index 470fa539..97bab392 100644 --- a/sdk/src/dagger/mod/_converter.py +++ b/sdk/src/dagger/mod/_converter.py @@ -1,10 +1,11 @@ +import enum import functools import logging import typing from cattrs.preconf.json import make_converter as make_json_converter -from dagger.client._core import Arg, Context, configure_converter_enum +from dagger.client._core import Arg, Context, EnumName, configure_converter_enum from dagger.client._guards import is_id_type, is_id_type_subclass from dagger.client.base import Interface, Scalar, Type from dagger.mod import _api @@ -16,11 +17,14 @@ is_dagger_interface_type, is_dagger_object_type, list_of, + non_null, strip_annotations, syncify, - to_camel_case, ) +if typing.TYPE_CHECKING: + from dagger.mod._module import Module + logger = logging.getLogger(__name__) @@ -81,18 +85,25 @@ def to_interface_impl(proto: type) -> type[Interface]: raise TypeError(msg) methods = { - func.original_name: make_method(name, func, proto) + func.original_name: make_method(name, func, proto, mod) for name, func in typ.functions.items() } + # The class name is the interface's schema name: it's what the client + # selects the type by (see `Type._graphql_name`). return type( - mod.main_cls.__name__ + proto.__name__, + mod.names.type_name(proto.__name__), (Interface,), {"_declaration": proto, **methods}, ) -def make_method(name: str, func: Function, proto: type) -> typing.Callable: # noqa: C901 +def make_method( # noqa: C901 + name: str, + func: Function, + proto: type, + mod: "Module", +) -> typing.Callable: """Generate method for interface client binding.""" ret_type = func.return_type _is_self = ret_type is proto @@ -100,17 +111,49 @@ def make_method(name: str, func: Function, proto: type) -> typing.Callable: # n if not _is_self and is_dagger_interface_type(ret_type): ret_type = to_interface_impl(ret_type) - # Need to convert names to GraphQL convention for query builder - gql_name = to_camel_case(name) + # The interface's field and argument names, as the engine names them. + names = mod.names + gql_name = names.field_name(name) + # Keyed by Python name, which is what the call binds. gql_arg_names = { - param.name: to_camel_case(param.name) for param in func.parameters.values() + py_name: names.field_name(param.name) + for py_name, param in func.parameters.items() } + def wire(value: typing.Any) -> typing.Any: + """A value as it goes over the wire, by the engine's names. + + A member of one of the module's own enums is sent by the name the + engine gave it (``arm64`` is ``ARM64``); the client sends anything + else as it always does, a member by its Python name. + """ + if isinstance(value, list | tuple): + return [wire(v) for v in value] + if isinstance(value, enum.Enum) and mod.is_own_enum(type(value)): + return EnumName(names.enum_member_name(value.name)) + return value + + def own_enum(t: typing.Any) -> type[enum.Enum] | None: + """The module's own enum a result is, or None.""" + t = non_null(strip_annotations(t)) + return t if mod.is_own_enum(t) else None + + def read(cls: type[enum.Enum], value: str | None) -> enum.Enum | None: + """A member of one of the module's own enums, from its engine name.""" + if value is None: + return None + members = {names.enum_member_name(m.name): m for m in cls} + try: + return members[value] + except KeyError: + msg = f"Unexpected member {value!r} of enum '{cls.__name__}'" + raise TypeError(msg) from None + # Generate query builder selection based on inputs def select(obj: Interface, *args, **kwargs): bound = func.signature.bind(obj, *args, **kwargs) args = [ - Arg(name=gql_arg_names[arg_name], value=arg_value) + Arg(name=gql_arg_names[arg_name], value=wire(arg_value)) for arg_name, arg_value in bound.arguments.items() if arg_name != "self" ] @@ -136,7 +179,13 @@ def chain_method(self, *args, **kwargs): # Anything else triggers execution (async) async def exec_method(self, *args, **kwargs): _ctx = select(self, *args, **kwargs) + # The module's own enums come back by the names the engine gave them. + if enum_cls := own_enum(ret_type): + return read(enum_cls, await _ctx.execute(str | None)) if cls := list_of(ret_type): + if enum_cls := own_enum(cls): + values = await _ctx.execute(list[str | None]) + return [read(enum_cls, v) for v in values] if cls is proto: cls = type(self) elif is_dagger_interface_type(cls): diff --git a/sdk/src/dagger/mod/_entrypoint.py b/sdk/src/dagger/mod/_entrypoint.py index 06ca546b..7a632030 100644 --- a/sdk/src/dagger/mod/_entrypoint.py +++ b/sdk/src/dagger/mod/_entrypoint.py @@ -202,6 +202,7 @@ def _indent(lines: list[str], width: int) -> list[str]: SOURCES_EXCLUDE = '["**/.git", "**/.venv", "**/__pycache__"]' MAIN_TEMPLATE = """{header} +# Needs Dagger v1.0.0-beta.26 or later; older engines report a missing "naming" field. type Entrypoint implements ModuleEntrypoint {{ let moduleName: String! = {name} let clientVersion: String! = {client_version} @@ -242,6 +243,7 @@ def _indent(lines: list[str], width: int) -> list[str]: contextDir: directory.withDirectory(".", currentModule.contextDirectory, exclude: ["**/.venv", "**/__pycache__"]), subPath: currentModule.sourceSubpath, moduleName: moduleName, + naming: currentModule.naming, ).installed }} }} diff --git a/sdk/src/dagger/mod/_module.py b/sdk/src/dagger/mod/_module.py index 24d90371..a5c4968b 100644 --- a/sdk/src/dagger/mod/_module.py +++ b/sdk/src/dagger/mod/_module.py @@ -19,7 +19,7 @@ from dagger._exceptions import QueryError from dagger.client._core import configure_converter_enum from dagger.mod import _api -from dagger.mod._converter import make_converter, typedef_from +from dagger.mod._converter import make_converter, to_interface_impl, typedef_from from dagger.mod._describe import ( ArgumentDescription, EnumDescription, @@ -35,11 +35,13 @@ FunctionError, InvalidInputError, InvalidResultError, + ModuleError, ObjectNotFoundError, RegistrationError, log_exception_only, transform_error, ) +from dagger.mod._naming import ModuleNames, module_names from dagger.mod._resolver import ( Constructor, Field, @@ -92,6 +94,7 @@ def __init__(self, main_name: str = MAIN_OBJECT): self._objects: dict[str, ObjectType] = {} self._enums: dict[str, type[enum.Enum]] = {} self._main: ObjectType | None = None + self._names: ModuleNames | None = None # Escape hatch if there's too much noise from showing stack traces # from exceptions raised in functions by default. Not documented # intentionally for now. @@ -102,6 +105,38 @@ def main_cls(self) -> type[ObjectType]: assert self._main is not None return self._main.cls + @property + def names(self) -> ModuleNames: + """The engine's names for the module's interfaces and enums. + + Calls through the module's own interfaces select them. Asked for by + ``load_names``, before anything is invoked. + """ + if self._names is None: + msg = "The module's schema names were not asked for before the call" + raise ModuleError(msg) + return self._names + + async def load_names(self) -> None: + """Ask the engine how it names the module, before anything is invoked. + + A module without interfaces makes no call by the engine's names of its + own declarations, so it asks nothing. + """ + if self._names is not None: + return + interfaces = [obj for obj in self._objects.values() if obj.interface] + if not interfaces: + self._names = ModuleNames() + return + self._names = await module_names(interfaces, self._enums.values()) + # Bindings are built with the names they have when first used. + to_interface_impl.cache_clear() + + def is_own_enum(self, cls: Any) -> bool: + """Whether a class is one of the enums this module declares.""" + return isinstance(cls, type) and self._enums.get(cls.__name__) is cls + def is_main(self, other: ObjectType) -> bool: """Check if the given object is the main object of the module.""" return self.main_cls is other.cls @@ -234,6 +269,8 @@ async def invoke(self) -> str: }, ) + await self.load_names() + result = await self.get_result( parent_name, parent_state, @@ -261,6 +298,7 @@ async def dispatch(self, request: Mapping[str, Any]) -> Any: except ValueError as e: msg = "Unable to decode the call request" raise InvalidInputError(msg, extra={"request": request}) from e + await self.load_names() return await self.get_result( request["receiverType"], parent_state or {}, diff --git a/sdk/src/dagger/mod/_naming.py b/sdk/src/dagger/mod/_naming.py new file mode 100644 index 00000000..4fd430c5 --- /dev/null +++ b/sdk/src/dagger/mod/_naming.py @@ -0,0 +1,135 @@ +"""Schema names the engine gives a module's own declarations. + +The runtime registers Python names (``get_url``, ``HttpFetcher``) and the +engine turns them into schema names (``getUrl``, ``NamingAppHTTPFetcher``) by +the naming rules of the version it names the module by. The calls the runtime +builds itself, through the module's own interfaces, have to use those schema +names: a wrong one is a fragment on a type that doesn't exist, a field the +interface doesn't have, or an unknown enum member. + +So the runtime doesn't predict them: it asks the engine, which answers for the +module it is running (``CurrentModule.naming``) by the same rules it names the +module by, legacy strcase for a module declaring a version before the +identifier casing cut. One query per call, before anything is invoked, for +every name the calls through the module's interfaces can use. +""" + +from __future__ import annotations + +import dataclasses +import typing +from collections.abc import Awaitable, Callable, Iterable + +from dagger.client._core import to_literal +from dagger.client._session import default_session +from dagger.mod._exceptions import ModuleError + +if typing.TYPE_CHECKING: + import enum + + from dagger.mod._resolver import ObjectType + +Execute: typing.TypeAlias = Callable[[str], Awaitable[typing.Any]] +"""Runs a GraphQL query against the engine and returns its data.""" + + +async def _execute(query: str) -> typing.Any: + return await default_session().execute(query) + + +@dataclasses.dataclass(frozen=True, slots=True) +class ModuleNames: + """The engine's names for the module's declarations, by declared name.""" + + types: typing.Mapping[str, str] = dataclasses.field(default_factory=dict) + """Namespaced schema names of the module's interfaces.""" + + fields: typing.Mapping[str, str] = dataclasses.field(default_factory=dict) + """Schema names of the interfaces' functions and arguments.""" + + enum_members: typing.Mapping[str, str] = dataclasses.field(default_factory=dict) + """Schema names of the members of the module's enums.""" + + def type_name(self, name: str) -> str: + """The schema name of an interface the module declares.""" + return self._get(self.types, name, "type") + + def field_name(self, name: str) -> str: + """The schema name of an interface's function or argument.""" + return self._get(self.fields, name, "function or argument") + + def enum_member_name(self, name: str) -> str: + """The schema name of a member of one of the module's enums.""" + return self._get(self.enum_members, name, "enum member") + + @staticmethod + def _get(names: typing.Mapping[str, str], name: str, what: str) -> str: + try: + return names[name] + except KeyError: + # Every name a call through an interface uses is asked about + # before anything runs; this one wasn't. + msg = f"The engine wasn't asked for the schema name of {what} {name!r}" + raise ModuleError(msg) from None + + +async def module_names( + interfaces: Iterable[ObjectType], + enums: Iterable[type[enum.Enum]], + execute: Execute = _execute, +) -> ModuleNames: + """Ask the engine how it names the module's interfaces and enums. + + One query: the interfaces' type names, their functions' and arguments' + names, and the members of the module's enums, which calls through an + interface send and receive. + """ + interfaces = list(interfaces) + types = sorted({iface.cls.__name__ for iface in interfaces}) + fields = sorted( + { + name + for iface in interfaces + for fn in iface.functions.values() + for name in (fn.name, *(p.name for p in fn.parameters.values())) + } + ) + members = sorted({member.name for cls in enums for member in cls}) + asked = { + "typeNames": types, + "fieldNames": fields, + "enumMemberNames": members, + } + selections = "\n".join( + f" {field}(names: {to_literal(names)})" + for field, names in asked.items() + if names + ) + if not selections: + return ModuleNames() + data = await execute( + "query ModuleNaming {\n" + " currentModule {\n" + " naming {\n" + f"{selections}\n" + " }\n" + " }\n" + "}" + ) + naming = (data or {}).get("currentModule", {}).get("naming", {}) + + def answers(field: str) -> dict[str, str]: + names = asked[field] + if not names: + return {} + got = naming.get(field) + if not isinstance(got, list) or len(got) != len(names): + msg = f"ModuleNaming.{field} returned {got!r} for {names!r}" + raise ModuleError(msg) + return dict(zip(names, got, strict=True)) + + return ModuleNames( + types=answers("typeNames"), + fields=answers("fieldNames"), + enum_members=answers("enumMemberNames"), + ) diff --git a/sdk/src/dagger/mod/_utils.py b/sdk/src/dagger/mod/_utils.py index 96ab2b54..0ae9c8b6 100644 --- a/sdk/src/dagger/mod/_utils.py +++ b/sdk/src/dagger/mod/_utils.py @@ -19,7 +19,6 @@ import typing_extensions from cattrs.cols import is_sequence -from dagger.client._core import snake_to_camel from dagger.client.base import Type from dagger.mod._arguments import DefaultAddress, DefaultPath, Deprecated, Ignore, Name from dagger.mod._types import ContextPath @@ -46,16 +45,6 @@ async def await_maybe(value: AwaitableOrValue[T]) -> T: return await value if inspect.iscoroutine(value) else cast(T, value) -def to_pascal_case(s: str) -> str: - """Convert a string to PascalCase.""" - return snake_to_camel(s.replace("-", "_")) - - -def to_camel_case(s: str) -> str: - """Convert a string to camelCase.""" - return snake_to_camel(s.replace("-", "_"), upper=False) - - def normalize_name(name: str) -> str: """Remove the last underscore, used to avoid conflicts with reserved words.""" if name.endswith("_") and name[-2] != "_" and not name.startswith("_"): diff --git a/sdk/tests/client/test_query_builder.py b/sdk/tests/client/test_query_builder.py index 95892c3c..e2f36a61 100644 --- a/sdk/tests/client/test_query_builder.py +++ b/sdk/tests/client/test_query_builder.py @@ -3,8 +3,8 @@ import pytest -from dagger._exceptions import ClientError -from dagger.client._core import Arg, Context, EnumName, snake_to_camel, to_literal +from dagger._exceptions import ClientError, InvalidQueryError +from dagger.client._core import Arg, Context, EnumName, to_literal from dagger.client.base import Enum, Input, Scalar, Type @@ -22,7 +22,7 @@ class Block(Input): call_id: str | None = None ssh_url: str | None = None - _graphql_names = (("ssh_url", "sshURL"),) + _graphql_names = (("kind", "kind"), ("call_id", "callId"), ("ssh_url", "sshURL")) @dataclass(slots=True) @@ -31,6 +31,8 @@ class Message(Input): text: str | None = "" errored: bool | None = False + _graphql_names = (("kind", "kind"), ("text", "text"), ("errored", "errored")) + class Container(Type): def echo(self, args: list[str]) -> "Container": @@ -187,17 +189,13 @@ def test_get_value_rejects_null_for_required(): assert ctx.get_value({"version": None}, str | None) is None -@pytest.mark.parametrize( - ("value", "expected"), - [ - ("call_id", "callId"), - ("ssh_url", "sshUrl"), - ("name", "name"), - ], -) -def test_snake_to_camel(value, expected): - assert snake_to_camel(value, upper=False) == expected - assert snake_to_camel(value) == expected[:1].upper() + expected[1:] +def test_input_field_without_a_graphql_name(): + @dataclass(slots=True) + class Bare(Input): + kind: str + + with pytest.raises(InvalidQueryError, match="no GraphQL name for 'kind'"): + to_literal(Bare(kind="x")) def test_enum_literal_before_str(): diff --git a/sdk/tests/codegen/test_generator.py b/sdk/tests/codegen/test_generator.py index 34f7fae7..094a6015 100644 --- a/sdk/tests/codegen/test_generator.py +++ b/sdk/tests/codegen/test_generator.py @@ -647,7 +647,7 @@ def test_input_object_graphql_names(): rendered = InputHandler(local_ctx).render(input_type) assert "@typecheck" not in rendered - assert "_graphql_names = (('ssh_url', 'sshURL'),)" in rendered + assert "_graphql_names = (('call_id', 'callId'), ('ssh_url', 'sshURL'))" in rendered def test_input_object_post_init_checks(): diff --git a/sdk/tests/codegen/test_naming.py b/sdk/tests/codegen/test_naming.py new file mode 100644 index 00000000..41120eab --- /dev/null +++ b/sdk/tests/codegen/test_naming.py @@ -0,0 +1,63 @@ +import pytest +from graphql import build_schema + +from codegen import naming +from codegen.naming import NamingError, Session, SnakeNames, schema_names, snake + + +def test_one_call_up_front_then_one_per_miss(): + calls: list[list[str]] = [] + + def fmt(names: list[str]) -> list[str]: + calls.append(names) + return [f"<{n}>" for n in names] + + names = SnakeNames(fmt) + names.prefetch(["b", "a", "b"]) + assert calls == [["a", "b"]] + assert names("a") == "" + assert names("c") == "" + assert names("c") == "" + assert calls == [["a", "b"], ["c"]] + + +def test_engine_errors_fail_the_generation(): + def fmt(_: list[str]) -> list[str]: + msg = 'cannot parse "ü"' + raise NamingError(msg) + + with pytest.raises(NamingError, match="cannot parse"): + SnakeNames(fmt)("ü") + + +def test_schema_names(): + schema = build_schema(""" + type Query { gitRepo(withSSH: Boolean): Repo } + type Repo { shortSHA: String! } + input Opts { userIDs: [String!] } + enum Kind { A } + """) + assert set(schema_names(schema)) >= { + "Query", + "gitRepo", + "withSSH", + "Repo", + "shortSHA", + "Opts", + "userIDs", + "Kind", + } + assert not any(n.startswith("__") for n in schema_names(schema)) + + +def test_no_session(monkeypatch: pytest.MonkeyPatch): + monkeypatch.delenv("DAGGER_SESSION_PORT", raising=False) + monkeypatch.delenv("DAGGER_SESSION_TOKEN", raising=False) + with pytest.raises(NamingError, match="nested client"): + Session.from_env() + + +def test_no_names_to_style_by(monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr(naming, "_current", None) + with pytest.raises(NamingError, match="no engine"): + snake("withExec") diff --git a/sdk/tests/conftest.py b/sdk/tests/conftest.py index 1e402f03..9cd879a9 100644 --- a/sdk/tests/conftest.py +++ b/sdk/tests/conftest.py @@ -1,4 +1,9 @@ +import re + import pytest +from graphql.pyutils import camel_to_snake + +from codegen import naming @pytest.fixture(scope="session", autouse=True) @@ -23,3 +28,33 @@ def alpine_version(): @pytest.fixture def alpine_image(alpine_version): return f"alpine:{alpine_version}" + + +_INITIALISM_RE = re.compile(r"([A-Z\d]+)(?=[A-Z\d]|$)") + + +def stand_in_snake(names: list[str]) -> list[str]: + """A stand-in for the engine's formatIdentifiers(casing: SNAKE). + + The generator's tests render made-up schemas without an engine, so + something has to spell their Python names; the e2e checks generate with + the engine. + """ + return [ + camel_to_snake(_INITIALISM_RE.sub(lambda m: m.group(0).title(), n)) + for n in names + ] + + +@pytest.fixture(autouse=True) +def engine_names(monkeypatch: pytest.MonkeyPatch): + """Style generated identifiers by the stand-in, as the CLI does too.""" + + def stand_in(schemas, _version: str) -> naming.SnakeNames: + names = naming.SnakeNames(stand_in_snake) + names.prefetch(n for schema in schemas for n in naming.schema_names(schema)) + return names + + monkeypatch.setattr(naming, "engine_names", stand_in) + with naming.styled_by(naming.SnakeNames(stand_in_snake)) as names: + yield names diff --git a/sdk/tests/mod/conftest.py b/sdk/tests/mod/conftest.py index 00970f61..9ed74143 100644 --- a/sdk/tests/mod/conftest.py +++ b/sdk/tests/mod/conftest.py @@ -1,7 +1,11 @@ import enum +import json +import re +import typing import pytest +from dagger.client._session import SharedConnection from dagger.client.base import Type @@ -29,3 +33,50 @@ def _selections(obj: Type): ] return _selections + + +_NAMING_FIELD = re.compile( + r"(typeNames|fieldNames|enumMemberNames)\(names: (\[.*?\])\)" +) + + +class FakeEngine: + """Answers CurrentModule.naming from a table of the engine's names. + + A name the table lacks fails the query, as a name the engine can't name + does. Any other query gets the canned data. It keeps what it was asked. + """ + + def __init__(self, names: typing.Mapping[str, typing.Mapping[str, str]]): + self.names = names + self.data: typing.Any = None + self.queries: list[str] = [] + + @property + def naming_queries(self) -> list[str]: + return [q for q in self.queries if q.startswith("query ModuleNaming")] + + async def execute(self, query: str): + self.queries.append(query) + if not query.startswith("query ModuleNaming"): + return self.data + naming = {} + for field, names in _NAMING_FIELD.findall(query): + table = self.names.get(field, {}) + naming[field] = [table[name] for name in json.loads(names)] + return {"currentModule": {"naming": naming}} + + +@pytest.fixture +def engine(monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest): + """A fake engine behind the default session. + + Parametrize indirectly with the naming table, or set `names` on it. + """ + fake = FakeEngine(getattr(request, "param", {})) + + async def ready(_): + return fake + + monkeypatch.setattr(SharedConnection, "_ready", ready) + return fake diff --git a/sdk/tests/mod/golden/main.dang b/sdk/tests/mod/golden/main.dang index 60fbc570..5d3c33be 100644 --- a/sdk/tests/mod/golden/main.dang +++ b/sdk/tests/mod/golden/main.dang @@ -1,5 +1,6 @@ # Code generated by dagger. DO NOT EDIT. +# Needs Dagger v1.0.0-beta.26 or later; older engines report a missing "naming" field. type Entrypoint implements ModuleEntrypoint { let moduleName: String! = "main" let clientVersion: String! = "v1.0.0-beta.27" @@ -40,6 +41,7 @@ type Entrypoint implements ModuleEntrypoint { contextDir: directory.withDirectory(".", currentModule.contextDirectory, exclude: ["**/.venv", "**/__pycache__"]), subPath: currentModule.sourceSubpath, moduleName: moduleName, + naming: currentModule.naming, ).installed } } diff --git a/sdk/tests/mod/golden/main_outside.dang b/sdk/tests/mod/golden/main_outside.dang index 4f53dc48..230304a8 100644 --- a/sdk/tests/mod/golden/main_outside.dang +++ b/sdk/tests/mod/golden/main_outside.dang @@ -1,5 +1,6 @@ # Code generated by dagger. DO NOT EDIT. +# Needs Dagger v1.0.0-beta.26 or later; older engines report a missing "naming" field. type Entrypoint implements ModuleEntrypoint { let moduleName: String! = "main" let clientVersion: String! = "v1.0.0-beta.27" @@ -42,6 +43,7 @@ type Entrypoint implements ModuleEntrypoint { contextDir: directory.withDirectory(".", currentModule.contextDirectory, exclude: ["**/.venv", "**/__pycache__"]), subPath: currentModule.sourceSubpath, moduleName: moduleName, + naming: currentModule.naming, ).installed } } diff --git a/sdk/tests/mod/test_interfaces.py b/sdk/tests/mod/test_interfaces.py index 22fb9502..d49caebf 100644 --- a/sdk/tests/mod/test_interfaces.py +++ b/sdk/tests/mod/test_interfaces.py @@ -15,6 +15,20 @@ pytest.mark.anyio, ] +# What the engine names the module's declarations. +POND_NAMES = { + "typeNames": {"Duck": "PondDuck", "Goose": "PondGoose"}, + "fieldNames": { + "speak": "speak", + "quack": "quack", + "get_self": "getSelf", + "get_mob": "getMob", + "with_origin": "withOrigin", + "from": "from", + "destination": "destination", + }, +} + @pytest.fixture def mod() -> Module: @@ -36,6 +50,13 @@ def get_self(self) -> Self: ... @m.function def get_mob(self) -> list[Self]: ... + @m.function + def with_origin( + self, + from_: str, + to: typing.Annotated[str, dagger.Name("destination")], + ) -> Self: ... + def get_private(self) -> bool: ... @m.object_type @@ -46,7 +67,9 @@ class Pond: @pytest.fixture -async def duck(mod: Module): +async def duck(mod: Module, engine): + engine.names = POND_NAMES + await mod.load_names() r, t = await mod.get_structured_result( "Pond", {"duck": "123456"}, @@ -77,3 +100,10 @@ async def test_generated_implementation(duck): async def test_interface_object_chain(duck): r, _ = duck assert type(r.get_self()) is type(r) + + +async def test_interface_call_arguments(duck): + """Arguments are bound by Python name and sent by their schema name.""" + r, _ = duck + query = r.with_origin(from_="a", to="b")._ctx.build() + assert 'withOrigin(from: "a", destination: "b")' in query diff --git a/sdk/tests/mod/test_naming.py b/sdk/tests/mod/test_naming.py new file mode 100644 index 00000000..8030b3ee --- /dev/null +++ b/sdk/tests/mod/test_naming.py @@ -0,0 +1,146 @@ +"""How the runtime gets the schema names of the module's declarations.""" + +import enum +import typing + +import pytest + +import dagger +from dagger.mod import Module +from dagger.mod._exceptions import ModuleError +from dagger.mod._naming import ModuleNames, module_names + +pytestmark = [ + pytest.mark.anyio, +] + +# CurrentModule.naming's answers for a module "naming-app" at +# v1.0.0-beta.26, as the engine's identifier naming rules name it. +NAMES = { + "typeNames": {"HttpFetcher": "NamingAppHTTPFetcher"}, + "fieldNames": { + "with_arch": "withArch", + "arch": "arch", + "also": "also", + "e2e_test": "e2eTest", + "arches": "arches", + }, + "enumMemberNames": {"arm64": "ARM64", "AMD64": "AMD64"}, +} + + +@pytest.fixture +def mod() -> Module: + m = Module("NamingApp") + + @m.enum_type + class Arch(enum.Enum): + arm64 = "arm64" + AMD64 = "amd64" + + @m.interface + class HttpFetcher(typing.Protocol): + @m.function + def with_arch(self, arch: Arch, also: list[Arch]) -> typing.Self: ... + + @m.function + async def e2e_test(self) -> str: ... + + @m.function + async def arch(self) -> Arch: ... + + @m.function + async def arches(self) -> list[Arch]: ... + + @m.object_type + class NamingApp: + fetcher: HttpFetcher = dagger.field() + + return m + + +async def fetcher(mod: Module): + r, _ = await mod.get_structured_result( + "NamingApp", + {"fetcher": "fetcher-id"}, + "fetcher", + {}, + ) + return r + + +async def test_one_query(mod: Module, engine): + engine.names = NAMES + await mod.load_names() + await mod.load_names() + assert len(engine.naming_queries) == 1 + query = engine.naming_queries[0] + assert 'typeNames(names: ["HttpFetcher"])' in query + assert ( + 'fieldNames(names: ["also", "arch", "arches", "e2e_test", "with_arch"])' + in query + ) + assert 'enumMemberNames(names: ["AMD64", "arm64"])' in query + + +async def test_no_interfaces_asks_nothing(engine): + m = Module("Plain") + + @m.object_type + class Plain: + pass + + await m.load_names() + assert engine.queries == [] + + +async def test_calls_by_the_engines_names(mod: Module, engine): + engine.names = NAMES + await mod.load_names() + r = await fetcher(mod) + arch = mod._enums["Arch"] + + assert type(r).__name__ == "NamingAppHTTPFetcher" + query = r.with_arch(arch.arm64, [arch.AMD64, arch.arm64])._ctx.build() + assert "... on NamingAppHTTPFetcher" in query + assert "withArch(arch: ARM64, also: [AMD64, ARM64])" in query + + engine.data = {"node": {"e2eTest": "ok"}} + assert await r.e2e_test() == "ok" + assert "e2eTest" in engine.queries[-1] + + +async def test_enum_results(mod: Module, engine): + engine.names = NAMES + await mod.load_names() + r = await fetcher(mod) + arch = mod._enums["Arch"] + + engine.data = {"node": {"arch": "ARM64"}} + assert await r.arch() is arch.arm64 + + engine.data = {"node": {"arches": ["AMD64", "ARM64"]}} + assert await r.arches() == [arch.AMD64, arch.arm64] + + engine.data = {"node": {"arch": "ARM_64"}} + with pytest.raises(TypeError, match="Unexpected member 'ARM_64'"): + await r.arch() + + +async def test_names_are_asked_before_a_call(mod: Module): + with pytest.raises(ModuleError, match="not asked for"): + await fetcher(mod) + + +def test_unasked_name_fails(): + with pytest.raises(ModuleError, match="'get_url'"): + ModuleNames().field_name("get_url") + + +async def test_engine_answer_mismatch(mod: Module): + async def execute(_): + return {"currentModule": {"naming": {"typeNames": []}}} + + interfaces = [o for o in mod._objects.values() if o.interface] + with pytest.raises(ModuleError, match="typeNames"): + await module_names(interfaces, (), execute)