Repository navigation
Conversation
84152e9 to
f52322a
Compare
This introduces a complete C# SDK implementation for Dagger with full module
development support, at parity with the current engine.
Core Features:
- Full Dagger API client with fluent chainable interface, generated from live
engine introspection (generic ID scalars, @expectedType arguments and
input fields, and Relay-style node(id:) object loading)
- Module runtime with attribute-based type registration
- Support for objects, interfaces, enums, checks, and functions
- Constructor-based dependency injection with async factory methods
- State round-trips through the engine: public properties auto-expose as
fields, object/interface values serialize as ids, enum values keep their
registered member names, renamed members keep registration and state in
sync
- W3C trace propagation so module spans join the CLI's trace
- The module runtime works against the client generated for whichever API
view the module's engine version selects (e.g. FunctionCachePolicy values
are resolved by name, whatever their casing)
Attributes:
- [Object] - Mark classes as Dagger modules
- [Interface] - Define interface types
- [Function] - Expose methods; optional overrides for properties
(Name/Description/Deprecated)
- [Constructor] - Alternative static factory constructor (one per module)
- [Check] - Mark functions as checks for `dagger check`. Like every SDK, a
check returns void/Task and fails by throwing; a container runs as a check
by awaiting Sync()
- [Generate] - Mark Changeset-returning functions as generators for
`dagger generate`
- [Up] - Mark Service-returning functions as services for `dagger up`
- [Name] - Custom parameter naming (e.g., for keyword conflicts)
- [DefaultPath] - Load contextual Directory/File/Git arguments
- [DefaultAddress] - Load an omitted Container argument from an image address
- [Ignore] - Directory ignore patterns for Directory arguments
- [Deprecated] - Deprecate functions, properties, and parameters
- [Enum]/[EnumValue] - Optional customization; plain public enums register
automatically
Module System:
- Automatic type discovery and registration
- GraphQL schema generation from C# types
- State management with JSON serialization
- Support for Dagger types (Container, Directory, File, etc.)
- Interface support end-to-end: declaration, cross-module implementation and
consumption via generated wrappers, As{Interface}() local conversions,
AsInterface<T>() for dependency objects, and query-chained dynamic proxies
Developer Experience:
- Roslyn analyzers for compile-time validation with code fixes, including
the check contract (DAGGER016/DAGGER017)
- Comprehensive examples demonstrating all features, including a standalone
client consuming the published NuGet package
- NuGet versioning tracks the targeted engine version with a -preview suffix
(engine v0.21.7 -> DaggerIO 0.21.7-preview)
- csharp-client workspace module (.dagger/modules/csharp-client-dev) with
test, lint, fmt, client-library generation, pack and publish
- Bare "csharp" SDK refs resolve to github.com/dagger/dagger/sdk/csharp at
the engine version, like java, php and elixir
Testing:
- Full integration suite (module_csharp_test.go) on the workspace/config
module flow, plus csharp participation in the cross-SDK interface, checks
(direct/blueprint/toolchain), generators, up, and contextual git-input
matrices
- TestCheckFunctions covers void/Task checks, containers run as checks via
Sync(), and the DAGGER017 rejection of Container-returning checks
Signed-off-by: pjmagee <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
f52322a to
b03ca8d
Compare
|
Thanks for picking this up again. I packed the client from this branch (b03ca8d) and ran our integration test suites against it. Some context first, because we are a client-only user and that is a case the module tests do not cover. Our use case
Results On engine v1.0.0-beta.27 all five suites pass, and our code compiled against the client without changes. Four things came up:
The trace propagation is valuable for us: with the published 0.21.7-preview.1 package, calls made from a test show up nested under that test in the Happy to test further iterations. 🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2 |
HttpClient cancels a request after 100 seconds by default. One GraphQL query can wait much longer than that, for a long exec or for a service to start, and then failed with a TaskCanceledException although the engine was still working. The client now has no request timeout; a caller bounds a call with its CancellationToken. Signed-off-by: Dominik Niebuhr <[email protected]>
- Control characters in a string argument were written into the query unescaped, which the engine rejects. They are now escaped as \uXXXX. - Integer arguments were formatted with the current culture. - An error whose path contains a list index could not be deserialized, because the path was typed as a list of strings. The original error was lost behind a JsonException. - A failed HTTP request with a body that is not JSON threw a JsonException. It now throws a DaggerException with the status code and the body. Signed-off-by: Dominik Niebuhr <[email protected]>
|
Follow-up to my comment above: I put fixes for the client-library side into a PR against this branch, pjmagee#14. Four commits that can be taken one by one:
With those commits the SDK's own test project passes on v1.0.0-beta.27 without a wrapper (73 tests). One more observation that I did not change, because it is a packaging decision: 🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2 |
The client only worked under `dagger run` or inside a Dagger container, where DAGGER_SESSION_PORT and DAGGER_SESSION_TOKEN are set. Anywhere else it threw, so `dotnet run`, `dotnet test` and the test runner of an IDE needed a wrapper. The READMEs already promised that a compatible CLI is downloaded and run automatically; this adds the code for it, following sdk/go/engineconn: 1. A provided session is used as before. A port without a token is an error instead of a reason to start a second session. 2. _EXPERIMENTAL_DAGGER_CLI_BIN names the CLI to run. 3. Otherwise the CLI release the SDK is built for (CliVersion) is downloaded from dl.dagger.io into the user's cache directory, checked against the published checksum, and CLIs of other versions are removed from the cache. 4. When that release is not published, as for a development build, `dagger` from the PATH is used with a warning. The CLI is started as `dagger session` with the SDK labels and the announced version. Like the Go SDK, the client waits up to five minutes for the session to be reported and, on dispose or process exit, up to five minutes for the CLI to end after its input is closed. Client.Dag no longer caches a failed connection attempt: the next access tries again, which matters now that connecting can involve a download and an engine start. CliVersion is pinned to the version in internal/version/VERSION and has to be bumped with it, like the version files of the other SDKs. Signed-off-by: Dominik Niebuhr <[email protected]>
An xUnit test project that starts PostgreSQL as a Dagger service from a test fixture and reaches it through Host.tunnel. The same `dotnet test` works on a developer machine, under `dagger run` and inside a Dagger container. Signed-off-by: Dominik Niebuhr <[email protected]>
dominik-niebuhr
left a comment
There was a problem hiding this comment.
I read the parts of this PR that hook into the engine and the repository tooling, and compared them with the Java, PHP and Elixir SDKs: sdk/csharp/runtime, the csharp-client-dev module, and the changes to core/sdk and dagger.toml. I use the client and am not a maintainer, so take this as a second pair of eyes before a maintainer review.
Everything is from reading the code at b03ca8d. Where I ran something, the comment says so. The suggestions are not tested unless a comment says otherwise: I could not run the dev module against a dev engine.
Looked right to me
- The registration in
core/sdkand the entries indagger.tomlfollowjava-client. For people who do not use C#, the only change I see is that the namecsharpis now reserved. - The
CodegenandModuleRuntimesignatures match what the engine calls. - The NuGet API key in
publishis passed as a secret variable and never ends up in a layer or an argument.
Most important of the inline comments
- The
testcheck runs the integration tests against the CI engine instead of the dev engine. - The entrypoint is
dotnet run, which applies launch settings and is slow per call. - The base image is a floating tag with an
apt-getstep on top. - Initialising a module can overwrite the repository's
.editorconfig.
Questions a maintainer will probably ask, not tied to a line
- The NuGet package id
DaggerIOis owned by a personal account. Who should own it once this repository publishes it? (That is also the open question in #15150.) sdk/dotnetanddotnet-client-devstill exist. Does this PR replace them, and if so, when do they go?- When a module's source is the repository root, the repository's own
Directory.Build.props,Directory.Packages.propsandglobal.jsontake part in the module build. Central package management would reject the versionedPackageReferences inDagger.SDK.props, and aglobal.jsonpinned to .NET 8 or 9 fails in the 10.0 image. Is that case meant to work?
The client-library side is covered by my earlier comment and by pjmagee#14. I am happy to send any of the points above as a PR against your branch as well.
🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2
| devContainer | ||
| .withExec(["dotnet", "restore"]) | ||
| .withExec(["dotnet", "build", "--no-restore"]) | ||
| .withExec(["dotnet", "test", "--no-build"], experimentalPrivilegedNesting: true) |
There was a problem hiding this comment.
This check does not test the dev engine. The exec gets the outer session in DAGGER_SESSION_PORT/DAGGER_SESSION_TOKEN, and the C# client uses exactly those two variables. So ClientIntegrationTests talk to the engine that runs CI, while the dev engine that installClient builds and binds is never used. The check cannot catch a mismatch between the SDK and the engine of the same commit.
engine-dev/main.go describes the trap in the comment on withoutOuterSession (the variables are set when the process starts, so they have to be unset at the process boundary), and dotnet-client-dev runs its tests through dagger run. Combined:
| .withExec(["dotnet", "test", "--no-build"], experimentalPrivilegedNesting: true) | |
| .withExec(["env", "-u", "DAGGER_SESSION_PORT", "-u", "DAGGER_SESSION_TOKEN", "dagger", "run", "dotnet", "test", "--no-build"]) |
Untested: I could not run this module against a dev engine.
🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2
| let after = before | ||
| .withFile(sourcePath + "/src/introspection.json", daggerEngine(ws: self.ws).introspectionJson) | ||
| .withFile(sourcePath + "/src/Dagger.SDK/Dagger.SDK.g.cs", generatedClient) |
There was a problem hiding this comment.
Is src/introspection.json needed in the repository? It is 1.1 MB, and I found nothing in the build that reads it: the code generator gets the schema as an argument (generatedClient above), and runtime/main.go gets it from the engine. No other SDK on main commits an introspection file. With it committed, every schema or docstring change in any PR makes this module's generated output stale.
If it can go, together with the file itself:
| let after = before | |
| .withFile(sourcePath + "/src/introspection.json", daggerEngine(ws: self.ws).introspectionJson) | |
| .withFile(sourcePath + "/src/Dagger.SDK/Dagger.SDK.g.cs", generatedClient) | |
| let after = before | |
| .withFile(sourcePath + "/src/Dagger.SDK/Dagger.SDK.g.cs", generatedClient) |
🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2
| """ | ||
| Package version | ||
| """ | ||
| version: String!, |
There was a problem hiding this comment.
publish accepts any version string. The comment in Dagger.SDK.csproj says the publish toolchain derives the -preview version from the engine version, but nothing here does: --version=0.21.9 would publish a stable package of an experimental SDK. java-client-dev takes the source tag and derives the version from it (release / releaseDryRun).
Two smaller things in the same function: dotnet nuget push has no --skip-duplicate, so a rerun after a partly successful push fails, and the dry run only lists the package files without looking inside them.
The secret handling itself looks right to me (withSecretVariable, quoted in the shell command).
🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2
| *.swp | ||
|
|
||
| # Code generated by Dagger. | ||
| /sdk/Dagger.SDK/introspection.json |
There was a problem hiding this comment.
This entry matches nothing in this layout (it looks like it came from sdk/dotnet, where the file is ignored rather than committed). If the introspection file is dropped from generate (see my comment on main.dang), this would be the matching entry:
| /sdk/Dagger.SDK/introspection.json | |
| /src/introspection.json |
🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2
| var parts []string | ||
| currentPart := "" | ||
| for _, r := range name { | ||
| if r == '-' || r == '_' || r == ' ' { |
There was a problem hiding this comment.
Names with other separators give invalid class names. Only -, _ and space split the name. A module in a directory called ci.tools becomes Ci.tools, so the template produces public class Ci.tools and Ci.tools.csproj, and the first build fails with a compiler error the user cannot relate to the name. Splitting on every character that is not a letter or digit (unicode.IsLetter / unicode.IsDigit) covers this.
Also, the doc comment on line 202 says "123test" -> "Test123", but the code below drops leading digits and returns test (lower case, because the first rune of the only part is 1). Prefixing instead of dropping would keep distinct names distinct.
🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2
| } | ||
| rest := "" | ||
| if len(part) > 1 { | ||
| rest = part[1:] |
There was a problem hiding this comment.
This cuts a multi-byte first letter in half. firstRune is the first rune, but part[1:] skips one byte. For a part that starts with a non-ASCII letter, for example my-élan, the result is é followed by the second byte of é, which is invalid UTF-8 in the class name and the file name.
| rest = part[1:] | |
| rest = string([]rune(part)[1:]) |
Line 253 has the same pattern (result[1:]), where it only works because it runs again for every leftover byte.
🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2
| } | ||
|
|
||
| // Build the module with specific project file | ||
| ctr = ctr.WithExec([]string{"dotnet", "build", projectFile, "-c", "Release"}) |
There was a problem hiding this comment.
No NuGet cache. Nothing mounts a cache for ~/.nuget/packages, so this restore, and the three restores of the code generator, analyzers and code fixes above, download their packages from nuget.org again whenever their layer is not cached, which for this line is every change to the module's source. Module loads then also depend on nuget.org being reachable.
The Java runtime mounts a Maven cache volume (sdk-java-maven-m2, locked sharing) and the PHP runtime a Composer cache. The equivalent here would be a WithMountedCache("/root/.nuget/packages", dag.CacheVolume("sdk-csharp-nuget")) on base (the image runs as root). One thing to check before doing that: the entrypoint below evaluates the project again at every function call, so the cache would have to be mounted in the runtime container too, or the module published to a directory that no longer needs the packages folder.
🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2
There was a problem hiding this comment.
I think we could certainly add cache for .nuget
|
|
||
| // Set the entrypoint to run the compiled program | ||
| ctr = ctr.WithEntrypoint([]string{ | ||
| "dotnet", "run", "--project", projectFile, "--no-build", "-c", "Release", "--", |
There was a problem hiding this comment.
dotnet run as the entrypoint. Two effects on every function call:
dotnet runapplies the module'sProperties/launchSettings.json. A profile there, which IDEs create by themselves, changes the environment of every function call in the engine.- It evaluates the project before starting the program. With a trivial app I measured about 0.4 to 0.7 s per start for
dotnet run --no-buildagainst about 0.04 s fordotnet App.dll(locally on macOS, not in the engine). Every function call is a fresh exec, so this is paid each time.
The small fix is the flag below (it exists in the SDK of this image, checked with dotnet run --help). The better one would be to publish the module to a fixed directory in ModuleRuntime and start the dll directly, as the Java runtime does with java -jar.
| "dotnet", "run", "--project", projectFile, "--no-build", "-c", "Release", "--", | |
| "dotnet", "run", "--project", projectFile, "--no-build", "--no-launch-profile", "-c", "Release", "--", |
🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2
| @@ -0,0 +1,11 @@ | |||
| { | |||
| "name": "csharp-sdk", | |||
| "engineVersion": "v0.21.7", | |||
There was a problem hiding this comment.
The Java, PHP and Elixir runtime modules are on v0.21.9 on main, and so is the new csharp-client-dev module. Is v0.21.7 here intended?
🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2
…-fixes fix(sdk/csharp): client session start, request timeout and error handling
Co-authored-by: dominik-niebuhr <[email protected]> Signed-off-by: Patrick Magee <[email protected]>
Experimental C# SDK with module support. This supersedes #11502, which was closed as stale; the branch has since been rebased onto current
mainand brought up to the v1 engine.What's in it
IDscalars,@expectedTypearguments and input fields, and Relay-stylenode(id:)object loading.[Object],[Interface],[Function],[Constructor],[Check],[Generate],[Up],[Name],[DefaultPath],[DefaultAddress],[Ignore],[Deprecated],[Enum]/[EnumValue].string? value,string value = "hello"), and async factory constructors via[Constructor](like the Python SDK'screate()).As{Interface}()conversions,AsInterface<T>()for dependency objects..editorconfig.csharp-clientworkspace module (.dagger/modules/csharp-client-dev) withtest,lint(CSharpier),fmt, client-library generation,packandpublish. BarecsharpSDK refs resolve togithub.com/dagger/dagger/sdk/csharpat the engine version, like java, php and elixir.DaggerIO) is optional for modules, since the SDK is vendored with the generated client; publishing it needs a nuget.org API key owned by the Dagger team.Checks follow the same contract as the other SDKs
A check returns
void/Taskand fails by throwing. To run a container as a check, await itsSync(); a non-zero exit throws. The SDK only registerswithCheck(), and the engine enforces the contract (check X.y must return Void). DAGGER017 reports the same rule at compile time.Testing
Run locally against a dev engine built from this branch (
./hack/build):dagger check 'csharp-client/**':test,lint,release-dry-runand theclient-librarystaleness check pass.dagger check 'markdown-lint/**' 'golangci-lint/**'pass.TestCsharp: 84 passed.TestChecks(direct/blueprint/toolchain),TestGenerators,TestUp,TestInterfaceandTestModule/TestContextGit(23 passed).dotnet,humanizer,aspnet-hello,aspnet-blazor-template,csharp-features) load and run against this branch onv1.0.0-beta.10, includingdagger check,dagger generateanddagger up.🤖 Generated with Claude Code