Skip to content

Commit 42e0e98

Browse files
committed
fix(codegen): defer module session lookup until requests
1 parent 198d001 commit 42e0e98

4 files changed

Lines changed: 167 additions & 74 deletions

File tree

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package gogenerator
2+
3+
import (
4+
"encoding/json"
5+
"os"
6+
"os/exec"
7+
"path/filepath"
8+
"strings"
9+
"testing"
10+
11+
"github.com/dagger/dagger/cmd/codegen/generator"
12+
"github.com/dagger/dagger/cmd/codegen/generator/go/templates"
13+
"github.com/dagger/dagger/cmd/codegen/introspection"
14+
"github.com/stretchr/testify/require"
15+
)
16+
17+
// Compile and execute both generated packages without an inherited session.
18+
// A source-only assertion would miss an eager initializer in either package,
19+
// or a global author handle that permanently remembers missing configuration.
20+
func TestGeneratedModuleSessionIsLazy(t *testing.T) {
21+
root := t.TempDir()
22+
data, err := os.ReadFile("../../introspection/testdata/schema.json")
23+
require.NoError(t, err)
24+
var schema introspection.Schema
25+
require.NoError(t, json.Unmarshal(data, &schema))
26+
generator.SetSchemaParents(&schema)
27+
previous := generator.GetSchema()
28+
generator.SetSchema(&schema)
29+
t.Cleanup(func() { generator.SetSchema(previous) })
30+
cfg := generator.Config{OutputDir: root, ModuleConfig: &generator.ModuleGeneratorConfig{ModuleName: "example", ModuleSourcePath: "."}}
31+
funcs := templates.GoTemplateFuncs(t.Context(), &schema, &schema, "v1.0.0-beta.21", cfg, nil, nil, 0)
32+
tmpls := templates.Templates(funcs)
33+
pkg := &PackageInfo{PackageName: "main", PackageImport: "example.com/importsafe"}
34+
for _, name := range []string{"internal/dagger/core/core.gen.go", "internal/dagger/dagger.gen.go"} {
35+
source, err := renderFile(root, &schema, "v1.0.0-beta.21", pkg, tmpls[name])
36+
require.NoError(t, err)
37+
require.NoError(t, os.MkdirAll(filepath.Dir(filepath.Join(root, name)), 0755))
38+
require.NoError(t, os.WriteFile(filepath.Join(root, name), source, 0600))
39+
}
40+
// Reuse the SDK's dependency pins, including its telemetry replacements.
41+
for _, name := range []string{"go.mod", "go.sum"} {
42+
data, err := os.ReadFile(filepath.Join("../../../../sdk/go", name))
43+
require.NoError(t, err)
44+
if name == "go.mod" {
45+
data = []byte(strings.Replace(string(data), "module dagger.io/dagger", "module example.com/importsafe", 1))
46+
}
47+
require.NoError(t, os.WriteFile(filepath.Join(root, name), data, 0600))
48+
}
49+
testSource, err := os.ReadFile("testdata/module-session/session_test.go")
50+
require.NoError(t, err)
51+
require.NoError(t, os.WriteFile(filepath.Join(root, "session_test.go"), testSource, 0600))
52+
cmd := exec.CommandContext(t.Context(), "go", "test", "-mod=mod", "./...")
53+
cmd.Dir = root
54+
for _, entry := range os.Environ() {
55+
if !strings.HasPrefix(entry, "DAGGER_SESSION_PORT=") && !strings.HasPrefix(entry, "DAGGER_SESSION_TOKEN=") && !strings.HasPrefix(entry, "GOWORK=") {
56+
cmd.Env = append(cmd.Env, entry)
57+
}
58+
}
59+
cmd.Env = append(cmd.Env, "GOWORK=off")
60+
out, err := cmd.CombinedOutput()
61+
require.NoError(t, err, string(out))
62+
}

‎cmd/codegen/generator/go/templates/src/_dagger.gen.go/defs.go.tmpl‎

Lines changed: 36 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -221,32 +221,53 @@ func WrapClient(c graphql.Client) graphql.Client {
221221
return errorWrappedClient{c}
222222
}
223223

224-
// dag is this package's own connection, used only by the generated
225-
// UnmarshalJSON methods above to build a query root when deserializing an
226-
// object from its ID. It lives here, self-contained, rather than reusing
227-
// the connect-layer package's dag (internal/dagger.dag), because this
228-
// package can't import that one without creating a cycle. It talks to the
229-
// same underlying engine session either way, since both read it from the
230-
// same environment variables.
231-
var dag *Query
224+
// The decoder and connect layer share a lazy transport. Importing bindings,
225+
// constructing handles, and decoding IDs must not require a Dagger session.
226+
var dag = NewQuery(ModuleGraphQLClient())
232227

233-
func init() {
234-
dag = NewQuery(getClientParams())
228+
var defaultModuleClient moduleClient
229+
230+
// ModuleGraphQLClient returns the module session's shared transport. Session
231+
// configuration is read on the first request, not during package initialization.
232+
func ModuleGraphQLClient() graphql.Client {
233+
return &defaultModuleClient
234+
}
235+
236+
type moduleClient struct {
237+
mu sync.Mutex
238+
client graphql.Client
239+
}
240+
241+
func (c *moduleClient) MakeRequest(ctx context.Context, req *graphql.Request, resp *graphql.Response) error {
242+
c.mu.Lock()
243+
client := c.client
244+
if client == nil {
245+
var err error
246+
client, err = getClientParams()
247+
if err != nil {
248+
c.mu.Unlock()
249+
// Do not cache missing configuration: a session may be attached later.
250+
return err
251+
}
252+
c.client = client
253+
}
254+
c.mu.Unlock()
255+
return client.MakeRequest(ctx, req, resp)
235256
}
236257

237-
func getClientParams() graphql.Client {
258+
func getClientParams() (graphql.Client, error) {
238259
portStr, ok := os.LookupEnv("DAGGER_SESSION_PORT")
239260
if !ok {
240-
panic("DAGGER_SESSION_PORT is not set")
261+
return nil, fmt.Errorf("DAGGER_SESSION_PORT is not set; run this call in a Dagger session")
241262
}
242263
port, err := strconv.Atoi(portStr)
243264
if err != nil {
244-
panic(fmt.Errorf("DAGGER_SESSION_PORT %q is invalid: %w", portStr, err))
265+
return nil, fmt.Errorf("DAGGER_SESSION_PORT %q is invalid: %w", portStr, err)
245266
}
246267

247268
sessionToken := os.Getenv("DAGGER_SESSION_TOKEN")
248269
if sessionToken == "" {
249-
panic("DAGGER_SESSION_TOKEN is not set")
270+
return nil, fmt.Errorf("DAGGER_SESSION_TOKEN is not set; run this call in a Dagger session")
250271
}
251272

252273
host := fmt.Sprintf("127.0.0.1:%d", port)
@@ -269,7 +290,7 @@ func getClientParams() graphql.Client {
269290
return dialTransport.RoundTrip(r)
270291
}),
271292
}
272-
return graphql.NewClient(fmt.Sprintf("http://%s/query", host), httpClient)
293+
return graphql.NewClient(fmt.Sprintf("http://%s/query", host), httpClient), nil
273294
}
274295

275296
func fallbackSpanContext(ctx context.Context) context.Context {

‎cmd/codegen/generator/go/templates/src/internal/dagger/dagger.gen.go.tmpl‎

Lines changed: 1 addition & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,9 @@ package dagger
55

66
import (
77
"context"
8-
"fmt"
9-
"net"
10-
"net/http"
11-
"os"
12-
"strconv"
138

149
"github.com/Khan/genqlient/graphql"
15-
"go.opentelemetry.io/otel/propagation"
1610
"go.opentelemetry.io/otel/trace"
17-
telemetry "github.com/dagger/otel-go"
1811

1912
"github.com/dagger/querybuilder"
2013

@@ -104,7 +97,7 @@ type Client struct {
10497
var dag *Client
10598

10699
func init() {
107-
gqlClient := getClientParams()
100+
gqlClient := core.ModuleGraphQLClient()
108101
dag = &Client{
109102
Query: core.NewQuery(gqlClient),
110103
client: core.WrapClient(gqlClient),
@@ -125,55 +118,4 @@ func (c *Client) QueryBuilder() *querybuilder.Selection {
125118
return c.Query.QueryBuilder()
126119
}
127120

128-
func getClientParams() graphql.Client {
129-
portStr, ok := os.LookupEnv("DAGGER_SESSION_PORT")
130-
if !ok {
131-
panic("DAGGER_SESSION_PORT is not set")
132-
}
133-
port, err := strconv.Atoi(portStr)
134-
if err != nil {
135-
panic(fmt.Errorf("DAGGER_SESSION_PORT %q is invalid: %w", portStr, err))
136-
}
137-
138-
sessionToken := os.Getenv("DAGGER_SESSION_TOKEN")
139-
if sessionToken == "" {
140-
panic("DAGGER_SESSION_TOKEN is not set")
141-
}
142-
143-
host := fmt.Sprintf("127.0.0.1:%d", port)
144-
145-
dialTransport := &http.Transport{
146-
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
147-
return net.Dial("tcp", host)
148-
},
149-
}
150-
httpClient := &http.Client{
151-
Transport: roundTripperFunc(func(r *http.Request) (*http.Response, error) {
152-
r.SetBasicAuth(sessionToken, "")
153-
154-
// detect $TRACEPARENT set by 'dagger run'
155-
r = r.WithContext(fallbackSpanContext(r.Context()))
156-
157-
// propagate span context via headers (i.e. for Dagger-in-Dagger)
158-
telemetry.Propagator.Inject(r.Context(), propagation.HeaderCarrier(r.Header))
159-
160-
return dialTransport.RoundTrip(r)
161-
}),
162-
}
163-
return graphql.NewClient(fmt.Sprintf("http://%s/query", host), httpClient)
164-
}
165-
166-
func fallbackSpanContext(ctx context.Context) context.Context {
167-
if trace.SpanContextFromContext(ctx).IsValid() {
168-
return ctx
169-
}
170-
return telemetry.Propagator.Extract(ctx, telemetry.NewEnvCarrier(true))
171-
}
172-
173-
// TODO: pollutes namespace, move to non internal package in dagger.io/dagger
174-
type roundTripperFunc func(*http.Request) (*http.Response, error)
175-
176-
func (fn roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
177-
return fn(req)
178-
}
179121
{{ end }}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"encoding/json"
6+
"fmt"
7+
"net/http"
8+
"net/http/httptest"
9+
"strings"
10+
"sync"
11+
"testing"
12+
13+
"example.com/importsafe/internal/dagger"
14+
)
15+
16+
// Match author code that constructs the client and query during initialization.
17+
var client = dagger.Connect()
18+
var container = client.Container()
19+
20+
func TestSession(t *testing.T) {
21+
ctx := context.Background()
22+
if _, err := container.Platform(ctx); err == nil || !strings.Contains(err.Error(), "DAGGER_SESSION_PORT is not set") {
23+
t.Fatalf("request without a session: %v", err)
24+
}
25+
var decoded dagger.Container
26+
if err := json.Unmarshal([]byte("\"decoded-id\""), &decoded); err != nil {
27+
t.Fatal(err)
28+
}
29+
for _, tc := range []struct{ port, token, want string }{
30+
{"", "", "DAGGER_SESSION_PORT"},
31+
{"invalid", "token", "DAGGER_SESSION_PORT"},
32+
{"12345", "", "DAGGER_SESSION_TOKEN"},
33+
} {
34+
t.Setenv("DAGGER_SESSION_PORT", tc.port)
35+
t.Setenv("DAGGER_SESSION_TOKEN", tc.token)
36+
if _, err := container.Platform(ctx); err == nil || !strings.Contains(err.Error(), tc.want) {
37+
t.Fatalf("missing/invalid session: %v", err)
38+
}
39+
}
40+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
41+
user, pass, ok := r.BasicAuth()
42+
if !ok || user != "secret" || pass != "" {
43+
t.Errorf("incorrect session authentication")
44+
}
45+
w.Header().Set("Content-Type", "application/json")
46+
fmt.Fprint(w, "{\"data\":{\"container\":{\"platform\":\"linux/amd64\"},\"node\":{\"platform\":\"linux/amd64\"}}}")
47+
}))
48+
defer server.Close()
49+
t.Setenv("DAGGER_SESSION_PORT", strings.TrimPrefix(server.URL, "http://127.0.0.1:"))
50+
t.Setenv("DAGGER_SESSION_TOKEN", "secret")
51+
var wg sync.WaitGroup
52+
for range 16 {
53+
wg.Add(1)
54+
go func() {
55+
defer wg.Done()
56+
platform, err := container.Platform(ctx)
57+
if err != nil || platform != "linux/amd64" {
58+
t.Errorf("pre-session handle: %q, %v", platform, err)
59+
}
60+
}()
61+
}
62+
wg.Wait()
63+
// UnmarshalJSON uses the core package's query root, not Connect's root.
64+
platform, err := decoded.Platform(ctx)
65+
if err != nil || platform != "linux/amd64" {
66+
t.Fatalf("decoded handle: %q, %v", platform, err)
67+
}
68+
}

0 commit comments

Comments
 (0)