status
stringclasses 1
value | repo_name
stringclasses 31
values | repo_url
stringclasses 31
values | issue_id
int64 1
104k
| title
stringlengths 4
233
| body
stringlengths 0
186k
β | issue_url
stringlengths 38
56
| pull_url
stringlengths 37
54
| before_fix_sha
stringlengths 40
40
| after_fix_sha
stringlengths 40
40
| report_datetime
timestamp[us, tz=UTC] | language
stringclasses 5
values | commit_datetime
timestamp[us, tz=UTC] | updated_file
stringlengths 7
188
| chunk_content
stringlengths 1
1.03M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/integration/module_test.go | testName string
cmdCtr *DaggerCLIContainer
expectedOutput string
}
for _, tc := range []testCase{
{
testName: "dagger env/" + ctr.EnvArg,
cmdCtr: ctr.CallEnv(),
expectedOutput: "Usage:\n dagger environment [flags]\n\nAliases:\n environment, env",
},
{
testName: "dagger env init/" + ctr.EnvArg,
cmdCtr: ctr.CallEnvInit(),
expectedOutput: "Usage:\n dagger environment init",
},
{
testName: "dagger env sync/" + ctr.EnvArg,
cmdCtr: ctr.CallEnvSync(),
expectedOutput: "Usage:\n dagger environment sync",
},
{
testName: "dagger env extend/" + ctr.EnvArg,
cmdCtr: ctr.CallEnvExtend("./fake/dep"),
expectedOutput: "Usage:\n dagger environment extend",
}, |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/integration/module_test.go | {
testName: "dagger checks/" + ctr.EnvArg,
cmdCtr: ctr.CallChecks(),
expectedOutput: "Usage:\n dagger checks",
},
} {
tc := tc
t.Run(tc.testName, func(t *testing.T) {
t.Parallel()
stdout, err := tc.cmdCtr.Stdout(ctx)
require.NoError(t, err)
require.Contains(t, stdout, tc.expectedOutput)
})
}
}
}
func TestEnvCmdInit(t *testing.T) {
t.Skip("pending conversion to modules")
t.Parallel()
type testCase struct {
testName string
environmentPath string
sdk string
name string
root string
expectedErrorMessage string
}
for _, tc := range []testCase{
{
testName: "explicit environment dir/go", |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/integration/module_test.go | environmentPath: "/var/testenvironment/subdir",
sdk: "go",
name: identity.NewID(),
root: "../",
},
{
testName: "explicit environment dir/python",
environmentPath: "/var/testenvironment/subdir",
sdk: "python",
name: identity.NewID(),
root: "../..",
},
{
testName: "explicit environment file",
environmentPath: "/var/testenvironment/subdir/dagger.json",
sdk: "python",
name: identity.NewID(),
},
{
testName: "implicit environment",
sdk: "go",
name: identity.NewID(),
},
{
testName: "implicit environment with root",
environmentPath: "/var/testenvironment",
sdk: "python",
name: identity.NewID(),
root: "..",
}, |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/integration/module_test.go | {
testName: "invalid sdk",
environmentPath: "/var/testenvironment",
sdk: "c++--",
name: identity.NewID(),
expectedErrorMessage: "unsupported environment SDK",
},
{
testName: "error on git",
environmentPath: "git://github.com/dagger/dagger.git",
sdk: "go",
name: identity.NewID(),
expectedErrorMessage: "environment init is not supported for git environments",
},
} {
tc := tc
t.Run(tc.testName, func(t *testing.T) {
t.Parallel()
c, ctx := connect(t)
ctr := CLITestContainer(ctx, t, c).
WithEnvArg(tc.environmentPath).
WithSDKArg(tc.sdk).
WithNameArg(tc.name).
CallEnvInit()
if tc.expectedErrorMessage != "" {
_, err := ctr.Sync(ctx)
require.ErrorContains(t, err, tc.expectedErrorMessage)
return
}
expectedConfigPath := tc.environmentPath |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/integration/module_test.go | if !strings.HasSuffix(expectedConfigPath, "dagger.json") {
expectedConfigPath = filepath.Join(expectedConfigPath, "dagger.json")
}
_, err := ctr.File(expectedConfigPath).Contents(ctx)
require.NoError(t, err)
if tc.sdk == "go" {
codegenFile := filepath.Join(filepath.Dir(expectedConfigPath), "dagger.gen.go")
_, err := ctr.File(codegenFile).Contents(ctx)
require.NoError(t, err)
}
stderr, err := ctr.CallEnv().Stderr(ctx)
require.NoError(t, err)
require.Contains(t, stderr, fmt.Sprintf(`"name": %q`, tc.name))
require.Contains(t, stderr, fmt.Sprintf(`"sdk": %q`, tc.sdk))
})
}
t.Run("error on existing environment", func(t *testing.T) {
t.Parallel()
c, ctx := connect(t)
_, err := CLITestContainer(ctx, t, c).
WithLoadedEnv("core/integration/testdata/environments/go/basic", false).
WithSDKArg("go").
WithNameArg("foo").
CallEnvInit().
Sync(ctx)
require.ErrorContains(t, err, "environment init config path already exists")
})
}
func TestEnvChecks(t *testing.T) { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/integration/module_test.go | t.Skip("pending conversion to modules")
t.Parallel()
allChecks := []string{
"cool-static-check",
"sad-static-check",
"cool-container-check",
"sad-container-check",
"cool-composite-check",
"sad-composite-check",
"another-cool-static-check",
"another-sad-static-check",
"cool-composite-check-from-explicit-dep",
"sad-composite-check-from-explicit-dep",
"cool-composite-check-from-dynamic-dep",
"sad-composite-check-from-dynamic-dep",
"cool-check-only-return",
"cool-check-result-only-return",
"cool-string-only-return",
"cool-error-only-return",
"sad-error-only-return",
"cool-string-error-return",
"sad-string-error-return",
} |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/integration/module_test.go | compositeCheckToSubcheckNames := map[string][]string{
"cool-composite-check": {
"cool-subcheck-a",
"cool-subcheck-b",
},
"sad-composite-check": {
"sad-subcheck-a",
"sad-subcheck-b",
},
"cool-composite-check-from-explicit-dep": {
"another-cool-static-check",
"another-cool-container-check",
"another-cool-composite-check",
},
"sad-composite-check-from-explicit-dep": {
"another-sad-static-check",
"another-sad-container-check",
"another-sad-composite-check",
},
"cool-composite-check-from-dynamic-dep": {
"yet-another-cool-static-check",
"yet-another-cool-container-check",
"yet-another-cool-composite-check",
},
"sad-composite-check-from-dynamic-dep": {
"yet-another-sad-static-check",
"yet-another-sad-container-check",
"yet-another-sad-composite-check",
},
"another-cool-composite-check": { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/integration/module_test.go | "another-cool-subcheck-a",
"another-cool-subcheck-b",
},
"another-sad-composite-check": {
"another-sad-subcheck-a",
"another-sad-subcheck-b",
},
"yet-another-cool-composite-check": {
"yet-another-cool-subcheck-a",
"yet-another-cool-subcheck-b",
},
"yet-another-sad-composite-check": {
"yet-another-sad-subcheck-a",
"yet-another-sad-subcheck-b",
},
}
checkOutput := func(name string) string {
return "WE ARE RUNNING CHECK " + strcase.ToKebab(name)
}
type testCase struct {
name string
environmentPath string
selectedChecks []string
expectFailure bool
}
for _, tc := range []testCase{
{
name: "happy-path",
environmentPath: "core/integration/testdata/environments/go/basic", |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/integration/module_test.go | selectedChecks: []string{
"cool-static-check",
"cool-container-check",
"cool-composite-check",
"another-cool-static-check",
"cool-composite-check-from-explicit-dep",
"cool-composite-check-from-dynamic-dep",
"cool-check-only-return",
"cool-check-result-only-return",
"cool-string-only-return",
"cool-error-only-return",
"cool-string-error-return",
},
},
{
name: "sad-path",
expectFailure: true,
environmentPath: "core/integration/testdata/environments/go/basic",
selectedChecks: []string{
"sad-static-check",
"sad-container-check",
"sad-composite-check",
"another-sad-static-check",
"sad-composite-check-from-explicit-dep",
"sad-composite-check-from-dynamic-dep",
"sad-error-only-return",
"sad-string-error-return",
},
},
{ |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/integration/module_test.go | name: "mixed-path",
expectFailure: true,
environmentPath: "core/integration/testdata/environments/go/basic",
},
} {
tc := tc
for _, testGitEnv := range []bool{false, true} {
testGitEnv := testGitEnv
testName := tc.name
testName += "/gitenv=" + strconv.FormatBool(testGitEnv)
testName += "/" + tc.environmentPath
t.Run(testName, func(t *testing.T) {
t.Parallel()
c, ctx := connect(t)
stderr, err := CLITestContainer(ctx, t, c).
WithLoadedEnv(tc.environmentPath, testGitEnv).
CallChecks(tc.selectedChecks...).
Stderr(ctx)
if tc.expectFailure {
require.Error(t, err)
execErr := new(dagger.ExecError)
require.True(t, errors.As(err, &execErr))
stderr = execErr.Stderr
} else {
require.NoError(t, err)
}
selectedChecks := tc.selectedChecks
if len(selectedChecks) == 0 {
selectedChecks = allChecks |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/integration/module_test.go | }
curChecks := selectedChecks
for len(curChecks) > 0 {
var nextChecks []string
for _, checkName := range curChecks {
subChecks, ok := compositeCheckToSubcheckNames[checkName]
if ok {
nextChecks = append(nextChecks, subChecks...)
} else {
if checkName == "cool-error-only-return" {
continue
}
require.Contains(t, stderr, checkOutput(checkName))
}
}
curChecks = nextChecks
}
})
}
}
}
func daggerExec(args ...string) dagger.WithContainerFunc {
return func(c *dagger.Container) *dagger.Container {
return c.WithExec(append([]string{"dagger", "--debug"}, args...), dagger.ContainerWithExecOpts{
ExperimentalPrivilegedNesting: true,
})
}
}
func daggerQuery(query string) dagger.WithContainerFunc { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/integration/module_test.go | return func(c *dagger.Container) *dagger.Container {
return c.WithExec([]string{"dagger", "--debug", "query"}, dagger.ContainerWithExecOpts{
Stdin: query,
ExperimentalPrivilegedNesting: true,
})
}
}
func daggerCall(args ...string) dagger.WithContainerFunc {
return func(c *dagger.Container) *dagger.Container {
return c.WithExec(append([]string{"dagger", "--debug", "call"}, args...), dagger.ContainerWithExecOpts{
ExperimentalPrivilegedNesting: true,
})
}
}
func goGitBase(t *testing.T, c *dagger.Client) *dagger.Container {
t.Helper()
return c.Container().From(golangImage).
WithExec([]string{"apk", "add", "git"}).
WithExec([]string{"git", "config", "--global", "user.email", "dagger@example.com"}).
WithExec([]string{"git", "config", "--global", "user.name", "Dagger Tests"}).
WithMountedFile(testCLIBinPath, daggerCliFile(t, c)).
WithWorkdir("/work").
WithExec([]string{"git", "init"})
}
func logGen(ctx context.Context, t *testing.T, modSrc *dagger.Directory) { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/integration/module_test.go | t.Helper()
generated, err := modSrc.File("dagger.gen.go").Contents(ctx)
require.NoError(t, err)
t.Cleanup(func() {
t.Name()
fileName := filepath.Join(
os.TempDir(),
t.Name(),
fmt.Sprintf("dagger.gen.%d.go", time.Now().Unix()),
)
if err := os.MkdirAll(filepath.Dir(fileName), 0o755); err != nil {
t.Logf("failed to create temp dir for generated code: %v", err)
return
}
if err := os.WriteFile(fileName, []byte(generated), 0644); err != nil {
t.Logf("failed to write generated code to %s: %v", fileName, err)
} else {
t.Logf("wrote generated code to %s", fileName)
}
})
} |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | package schema
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"path/filepath"
"runtime/debug"
"strconv"
"strings"
"github.com/dagger/dagger/core"
"github.com/dagger/dagger/core/modules"
"github.com/dagger/dagger/engine"
"github.com/dagger/dagger/engine/buildkit"
"github.com/dagger/graphql"
"github.com/iancoleman/strcase"
bkgw "github.com/moby/buildkit/frontend/gateway/client"
"github.com/opencontainers/go-digest"
ocispecs "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/vektah/gqlparser/v2/ast"
"github.com/vektah/gqlparser/v2/formatter"
"golang.org/x/sync/errgroup"
)
type moduleSchema struct {
*MergedSchemas |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | moduleCache *core.CacheMap[digest.Digest, *core.Module]
dependenciesCache *core.CacheMap[digest.Digest, []*core.Module]
}
var _ ExecutableSchema = &moduleSchema{}
func (s *moduleSchema) Name() string {
return "module"
}
func (s *moduleSchema) Schema() string {
return strings.Join([]string{Module, Function, InternalSDK}, "\n")
}
func (s *moduleSchema) Dependencies() []ExecutableSchema {
return nil
}
func (s *moduleSchema) Resolvers() Resolvers {
rs := Resolvers{
"Query": ObjectResolver{
"module": ToResolver(s.module),
"currentModule": ToResolver(s.currentModule),
"function": ToResolver(s.function),
"currentFunctionCall": ToResolver(s.currentFunctionCall),
"typeDef": ToResolver(s.typeDef),
"generatedCode": ToResolver(s.generatedCode),
"moduleConfig": ToResolver(s.moduleConfig),
},
"Directory": ObjectResolver{
"asModule": ToResolver(s.directoryAsModule),
},
"FunctionCall": ObjectResolver{
"returnValue": ToVoidResolver(s.functionCallReturnValue),
"parent": ToResolver(s.functionCallParent), |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | },
}
ResolveIDable[core.Module](rs, "Module", ObjectResolver{
"dependencies": ToResolver(s.moduleDependencies),
"objects": ToResolver(s.moduleObjects),
"withObject": ToResolver(s.moduleWithObject),
"generatedCode": ToResolver(s.moduleGeneratedCode),
"serve": ToVoidResolver(s.moduleServe),
})
ResolveIDable[core.Function](rs, "Function", ObjectResolver{
"withDescription": ToResolver(s.functionWithDescription),
"withArg": ToResolver(s.functionWithArg),
})
ResolveIDable[core.FunctionArg](rs, "FunctionArg", ObjectResolver{})
ResolveIDable[core.TypeDef](rs, "TypeDef", ObjectResolver{
"kind": ToResolver(s.typeDefKind),
"withOptional": ToResolver(s.typeDefWithOptional),
"withKind": ToResolver(s.typeDefWithKind),
"withListOf": ToResolver(s.typeDefWithListOf),
"withObject": ToResolver(s.typeDefWithObject),
"withField": ToResolver(s.typeDefWithObjectField),
"withFunction": ToResolver(s.typeDefWithObjectFunction),
})
ResolveIDable[core.GeneratedCode](rs, "GeneratedCode", ObjectResolver{
"withVCSIgnoredPaths": ToResolver(s.generatedCodeWithVCSIgnoredPaths),
"withVCSGeneratedPaths": ToResolver(s.generatedCodeWithVCSGeneratedPaths),
})
return rs
}
func (s *moduleSchema) typeDef(ctx context.Context, _ *core.Query, args struct { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | ID core.TypeDefID
Kind core.TypeDefKind
}) (*core.TypeDef, error) {
if args.ID != "" {
return args.ID.Decode()
}
return &core.TypeDef{
Kind: args.Kind,
}, nil
}
func (s *moduleSchema) typeDefWithOptional(ctx context.Context, def *core.TypeDef, args struct {
Optional bool
}) (*core.TypeDef, error) {
return def.WithOptional(args.Optional), nil
}
func (s *moduleSchema) typeDefWithKind(ctx context.Context, def *core.TypeDef, args struct {
Kind core.TypeDefKind
}) (*core.TypeDef, error) {
return def.WithKind(args.Kind), nil
}
func (s *moduleSchema) typeDefWithListOf(ctx context.Context, def *core.TypeDef, args struct {
ElementType core.TypeDefID
}) (*core.TypeDef, error) {
elemType, err := args.ElementType.Decode()
if err != nil {
return nil, fmt.Errorf("failed to decode element type: %w", err)
}
return def.WithListOf(elemType), nil
}
func (s *moduleSchema) typeDefWithObject(ctx context.Context, def *core.TypeDef, args struct { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | Name string
Description string
}) (*core.TypeDef, error) {
return def.WithObject(args.Name, args.Description), nil
}
func (s *moduleSchema) typeDefWithObjectField(ctx context.Context, def *core.TypeDef, args struct {
Name string
TypeDef core.TypeDefID
Description string
}) (*core.TypeDef, error) {
fieldType, err := args.TypeDef.Decode()
if err != nil {
return nil, fmt.Errorf("failed to decode element type: %w", err)
}
return def.WithObjectField(args.Name, fieldType, args.Description)
}
func (s *moduleSchema) typeDefWithObjectFunction(ctx context.Context, def *core.TypeDef, args struct {
Function core.FunctionID
}) (*core.TypeDef, error) {
fn, err := args.Function.Decode()
if err != nil {
return nil, fmt.Errorf("failed to decode element type: %w", err)
}
return def.WithObjectFunction(fn)
}
func (s *moduleSchema) typeDefKind(ctx context.Context, def *core.TypeDef, args any) (string, error) {
return def.Kind.String(), nil
}
func (s *moduleSchema) generatedCode(ctx context.Context, _ *core.Query, args struct { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | Code core.DirectoryID
}) (*core.GeneratedCode, error) {
dir, err := args.Code.Decode()
if err != nil {
return nil, err
}
return core.NewGeneratedCode(dir), nil
}
func (s *moduleSchema) generatedCodeWithVCSIgnoredPaths(ctx context.Context, code *core.GeneratedCode, args struct {
Paths []string
}) (*core.GeneratedCode, error) {
return code.WithVCSIgnoredPaths(args.Paths), nil
}
func (s *moduleSchema) generatedCodeWithVCSGeneratedPaths(ctx context.Context, code *core.GeneratedCode, args struct {
Paths []string
}) (*core.GeneratedCode, error) {
return code.WithVCSGeneratedPaths(args.Paths), nil
}
type moduleArgs struct {
ID core.ModuleID
}
func (s *moduleSchema) module(ctx context.Context, query *core.Query, args moduleArgs) (*core.Module, error) {
if args.ID == "" {
return core.NewModule(s.platform, query.PipelinePath()), nil
}
return args.ID.Decode()
}
type moduleConfigArgs struct { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | SourceDirectory core.DirectoryID
Subpath string
}
func (s *moduleSchema) moduleConfig(ctx context.Context, query *core.Query, args moduleConfigArgs) (*modules.Config, error) {
srcDir, err := args.SourceDirectory.Decode()
if err != nil {
return nil, fmt.Errorf("failed to decode source directory: %w", err)
}
_, cfg, err := core.LoadModuleConfig(ctx, s.bk, s.services, srcDir, args.Subpath)
return cfg, err
}
func (s *moduleSchema) currentModule(ctx context.Context, _ *core.Query, _ any) (*core.Module, error) {
return s.MergedSchemas.currentModule(ctx)
}
func (s *moduleSchema) function(ctx context.Context, _ *core.Query, args struct {
Name string
ReturnType core.TypeDefID
}) (*core.Function, error) {
returnType, err := args.ReturnType.Decode()
if err != nil {
return nil, fmt.Errorf("failed to decode return type: %w", err)
}
return core.NewFunction(args.Name, returnType), nil
}
func (s *moduleSchema) currentFunctionCall(ctx context.Context, _ *core.Query, _ any) (*core.FunctionCall, error) {
return s.MergedSchemas.currentFunctionCall(ctx)
}
type asModuleArgs struct { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | SourceSubpath string
}
func (s *moduleSchema) directoryAsModule(ctx context.Context, sourceDir *core.Directory, args asModuleArgs) (_ *core.Module, rerr error) {
defer func() {
if err := recover(); err != nil {
debug.PrintStack()
rerr = fmt.Errorf("panic in directoryAsModule: %v %s", err, string(debug.Stack()))
}
}()
mod := core.NewModule(s.platform, sourceDir.Pipeline)
mod, err := mod.FromConfig(ctx, s.bk, s.services, s.progSockPath, sourceDir, args.SourceSubpath, s.runtimeForModule)
if err != nil {
return nil, fmt.Errorf("failed to create module from config: %w", err)
}
return mod, nil
}
func (s *moduleSchema) moduleGeneratedCode(ctx context.Context, mod *core.Module, _ any) (*core.GeneratedCode, error) {
sdk, err := s.sdkForModule(ctx, mod)
if err != nil {
return nil, fmt.Errorf("failed to load sdk for module %s: %w", mod.Name, err)
} |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | return sdk.Codegen(ctx, mod)
}
func (s *moduleSchema) moduleServe(ctx context.Context, mod *core.Module, args any) (rerr error) {
defer func() {
if err := recover(); err != nil {
rerr = fmt.Errorf("panic in moduleServe: %s\n%s", err, debug.Stack())
}
}()
mod, err := s.loadModuleTypes(ctx, mod)
if err != nil {
return fmt.Errorf("failed to load module types: %w", err)
}
schemaView, err := s.currentSchemaView(ctx)
if err != nil {
return err
}
err = s.serveModuleToView(ctx, mod, schemaView)
if err != nil {
return err
}
return nil
}
func (s *moduleSchema) moduleObjects(ctx context.Context, mod *core.Module, _ any) ([]*core.TypeDef, error) {
mod, err := s.loadModuleTypes(ctx, mod)
if err != nil {
return nil, fmt.Errorf("failed to load module types: %w", err)
}
return mod.Objects, nil
}
func (s *moduleSchema) moduleWithObject(ctx context.Context, module *core.Module, args struct { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | Object core.TypeDefID
}) (_ *core.Module, rerr error) {
def, err := args.Object.Decode()
if err != nil {
return nil, err
}
return module.WithObject(def)
}
func (s *moduleSchema) functionCallReturnValue(ctx context.Context, fnCall *core.FunctionCall, args struct{ Value any }) error {
valueBytes, err := json.Marshal(args.Value)
if err != nil {
return fmt.Errorf("failed to marshal function return value: %w", err)
}
return s.bk.IOReaderExport(ctx, bytes.NewReader(valueBytes), filepath.Join(core.ModMetaDirPath, core.ModMetaOutputPath), 0600)
}
func (s *moduleSchema) functionCallParent(ctx context.Context, fnCall *core.FunctionCall, _ any) (any, error) {
if fnCall.Parent == nil {
return struct{}{}, nil |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | }
return fnCall.Parent, nil
}
func (s *moduleSchema) functionWithDescription(ctx context.Context, fn *core.Function, args struct {
Description string
}) (*core.Function, error) {
return fn.WithDescription(args.Description), nil
}
func (s *moduleSchema) functionWithArg(ctx context.Context, fn *core.Function, args struct {
Name string
TypeDef core.TypeDefID
Description string
DefaultValue any
}) (*core.Function, error) {
argType, err := args.TypeDef.Decode()
if err != nil {
return nil, fmt.Errorf("failed to decode arg type: %w", err)
}
return fn.WithArg(args.Name, argType, args.Description, args.DefaultValue), nil
}
type functionCallArgs struct { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | Input []*core.CallInput
ParentOriginalName string
Parent any
Module *core.Module
Cache bool
}
func (s *moduleSchema) functionCall(ctx context.Context, fn *core.Function, args functionCallArgs) (any, error) {
mod := args.Module
if mod == nil {
return nil, fmt.Errorf("function %s has no module", fn.Name)
}
callParams := &core.FunctionCall{
Name: fn.OriginalName,
ParentName: args.ParentOriginalName,
Parent: args.Parent,
InputArgs: args.Input,
}
schemaView, moduleContextDigest, err := s.registerModuleFunctionCall(mod, callParams)
if err != nil {
return nil, fmt.Errorf("failed to handle module function call: %w", err)
}
ctr := mod.Runtime
metaDir := core.NewScratchDirectory(mod.Pipeline, mod.Platform)
ctr, err = ctr.WithMountedDirectory(ctx, s.bk, core.ModMetaDirPath, metaDir, "", false) |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | if err != nil {
return nil, fmt.Errorf("failed to mount mod metadata directory: %w", err)
}
deps, err := s.dependenciesOf(ctx, mod)
if err != nil {
return nil, fmt.Errorf("failed to get module dependencies: %w", err)
}
for _, dep := range deps {
dirMntPath := filepath.Join(core.ModMetaDirPath, core.ModMetaDepsDirPath, dep.Name, "dir")
sourceDir, err := dep.SourceDirectory.Directory(ctx, s.bk, s.services, dep.SourceDirectorySubpath)
if err != nil {
return nil, fmt.Errorf("failed to mount dep directory: %w", err)
}
ctr, err = ctr.WithMountedDirectory(ctx, s.bk, dirMntPath, sourceDir, "", true)
if err != nil {
return nil, fmt.Errorf("failed to mount dep directory: %w", err)
}
}
callParamsBytes, err := json.Marshal(callParams)
if err != nil {
return nil, fmt.Errorf("failed to marshal input: %w", err)
}
inputFileDir, err := core.NewScratchDirectory(mod.Pipeline, mod.Platform).WithNewFile(ctx, core.ModMetaInputPath, callParamsBytes, 0600, nil)
if err != nil {
return nil, fmt.Errorf("failed to create input file: %w", err)
}
inputFile, err := inputFileDir.File(ctx, s.bk, s.services, core.ModMetaInputPath) |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | if err != nil {
return nil, fmt.Errorf("failed to get input file: %w", err)
}
ctr, err = ctr.WithMountedFile(ctx, s.bk, filepath.Join(core.ModMetaDirPath, core.ModMetaInputPath), inputFile, "", true)
if err != nil {
return nil, fmt.Errorf("failed to mount input file: %w", err)
}
if !args.Cache {
clientMetadata, err := engine.ClientMetadataFromContext(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get client metadata: %w", err)
}
busterKey := base64.StdEncoding.EncodeToString([]byte(clientMetadata.ServerID))
busterTon := core.NewScratchDirectory(mod.Pipeline, mod.Platform)
ctr, err = ctr.WithMountedDirectory(ctx, s.bk, "/"+busterKey, busterTon, "", true)
if err != nil {
return nil, fmt.Errorf("failed to inject session cache key: %s", err)
}
}
ctr, err = ctr.WithExec(ctx, s.bk, s.progSockPath, mod.Platform, core.ContainerExecOpts{
ModuleContextDigest: moduleContextDigest,
ExperimentalPrivilegedNesting: true,
NestedInSameSession: true,
})
if err != nil {
return nil, fmt.Errorf("failed to exec function: %w", err) |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | }
ctrOutputDir, err := ctr.Directory(ctx, s.bk, s.services, core.ModMetaDirPath)
if err != nil {
return nil, fmt.Errorf("failed to get function output directory: %w", err)
}
result, err := ctrOutputDir.Evaluate(ctx, s.bk, s.services)
if err != nil {
return nil, fmt.Errorf("failed to evaluate function: %w", err)
}
if result == nil {
return nil, fmt.Errorf("function returned nil result")
}
/* TODO: re-add support for interpreting exit code
exitCodeStr, err := ctr.MetaFileContents(ctx, s.bk, s.progSockPath, "exitCode")
if err != nil {
return nil, fmt.Errorf("failed to read function exit code: %w", err)
}
exitCodeUint64, err := strconv.ParseUint(exitCodeStr, 10, 32)
if err != nil {
return nil, fmt.Errorf("failed to parse function exit code: %w", err)
}
exitCode := uint32(exitCodeUint64)
*/
outputBytes, err := result.Ref.ReadFile(ctx, bkgw.ReadRequest{
Filename: core.ModMetaOutputPath,
}) |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | if err != nil {
return nil, fmt.Errorf("failed to read function output file: %w", err)
}
var rawOutput any
if err := json.Unmarshal(outputBytes, &rawOutput); err != nil {
return nil, fmt.Errorf("failed to unmarshal result: %s", err)
}
if err := s.linkDependencyBlobs(ctx, result, rawOutput, fn.ReturnType, schemaView); err != nil {
return nil, fmt.Errorf("failed to link dependency blobs: %w", err)
}
return rawOutput, nil
}
func (s *moduleSchema) linkDependencyBlobs(ctx context.Context, cacheResult *buildkit.Result, value any, typeDef *core.TypeDef, schemaView *schemaView) error {
switch typeDef.Kind {
case core.TypeDefKindString, core.TypeDefKindInteger,
core.TypeDefKindBoolean, core.TypeDefKindVoid:
return nil
case core.TypeDefKindList:
listValue, ok := value.([]any)
if !ok {
return fmt.Errorf("expected list value, got %T", value)
}
for _, elem := range listValue {
if err := s.linkDependencyBlobs(ctx, cacheResult, elem, typeDef.AsList.ElementTypeDef, schemaView); err != nil {
return fmt.Errorf("failed to link dependency blobs: %w", err)
}
}
return nil
case core.TypeDefKindObject:
_, isIDable := s.idableObjectResolver(typeDef.AsObject.Name, schemaView) |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | if !isIDable {
mapValue, ok := value.(map[string]any)
if !ok {
return fmt.Errorf("expected object value for %s, got %T", typeDef.AsObject.Name, value)
}
for fieldName, fieldValue := range mapValue {
field, ok := typeDef.AsObject.FieldByName(fieldName)
if !ok {
continue
}
if err := s.linkDependencyBlobs(ctx, cacheResult, fieldValue, field.TypeDef, schemaView); err != nil {
return fmt.Errorf("failed to link dependency blobs: %w", err)
}
}
return nil
}
idStr, ok := value.(string)
if !ok {
return fmt.Errorf("expected string value for id result, got %T", value)
}
resource, err := core.ResourceFromID(idStr)
if err != nil {
return fmt.Errorf("failed to get resource from ID: %w", err)
}
pbDefinitioner, ok := resource.(core.HasPBDefinitions)
if !ok { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | return nil
}
pbDefs, err := pbDefinitioner.PBDefinitions()
if err != nil {
return fmt.Errorf("failed to get pb definitions: %w", err)
}
dependencyBlobs := map[digest.Digest]*ocispecs.Descriptor{}
for _, pbDef := range pbDefs {
dag, err := buildkit.DefToDAG(pbDef)
if err != nil {
return fmt.Errorf("failed to convert pb definition to dag: %w", err)
}
blobs, err := dag.BlobDependencies()
if err != nil {
return fmt.Errorf("failed to get blob dependencies: %w", err)
}
for k, v := range blobs {
dependencyBlobs[k] = v
}
}
if err := cacheResult.Ref.AddDependencyBlobs(ctx, dependencyBlobs); err != nil {
return fmt.Errorf("failed to add dependency blob: %w", err)
}
return nil
default:
return fmt.Errorf("unhandled type def kind %q", typeDef.Kind)
}
}
func (s *moduleSchema) idableObjectResolver(objName string, dest *schemaView) (IDableObjectResolver, bool) {
objName = gqlObjectName(objName) |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | resolver, ok := dest.resolvers()[objName]
if !ok {
return nil, false
}
idableResolver, ok := resolver.(IDableObjectResolver)
return idableResolver, ok
}
func (s *moduleSchema) serveModuleToView(ctx context.Context, mod *core.Module, schemaView *schemaView) error {
mod, err := s.loadModuleTypes(ctx, mod)
if err != nil {
return fmt.Errorf("failed to load dep module functions: %w", err)
}
cacheKey := digest.FromString(mod.Name + "." + schemaView.viewDigest.String())
_, err = s.moduleCache.GetOrInitialize(cacheKey, func() (*core.Module, error) {
executableSchema, err := s.moduleToSchemaFor(ctx, mod, schemaView)
if err != nil {
return nil, fmt.Errorf("failed to convert module to executable schema: %w", err)
}
if err := schemaView.addSchemas(executableSchema); err != nil {
return nil, fmt.Errorf("failed to install module schema: %w", err)
}
return mod, nil
})
return err
}
func (s *moduleSchema) loadModuleTypes(ctx context.Context, mod *core.Module) (*core.Module, error) {
dgst, err := mod.BaseDigest() |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | if err != nil {
return nil, fmt.Errorf("failed to get module digest: %w", err)
}
return s.moduleCache.GetOrInitialize(dgst, func() (*core.Module, error) {
schemaView, err := s.installDeps(ctx, mod)
if err != nil {
return nil, fmt.Errorf("failed to install module dependencies: %w", err)
}
getModDefFn := core.NewFunction(
"",
&core.TypeDef{
Kind: core.TypeDefKindObject,
AsObject: core.NewObjectTypeDef("Module", ""),
},
)
result, err := s.functionCall(ctx, getModDefFn, functionCallArgs{
Module: mod,
Cache: true,
})
if err != nil {
return nil, fmt.Errorf("failed to call module %q to get functions: %w", mod.Name, err)
}
idStr, ok := result.(string)
if !ok {
return nil, fmt.Errorf("expected string result, got %T", result)
}
mod, err = core.ModuleID(idStr).Decode()
if err != nil { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | return nil, fmt.Errorf("failed to decode module: %w", err)
}
for _, obj := range mod.Objects {
if err := s.validateTypeDef(obj, schemaView); err != nil {
return nil, fmt.Errorf("failed to validate type def: %w", err)
}
s.namespaceTypeDef(obj, mod, schemaView)
}
return mod, nil
})
}
func (s *moduleSchema) moduleDependencies(ctx context.Context, mod *core.Module, _ any) ([]*core.Module, error) {
return s.dependenciesOf(ctx, mod)
}
func (s *moduleSchema) dependenciesOf(ctx context.Context, mod *core.Module) ([]*core.Module, error) {
dgst, err := mod.BaseDigest()
if err != nil {
return nil, fmt.Errorf("failed to get module digest: %w", err)
}
return s.dependenciesCache.GetOrInitialize(dgst, func() ([]*core.Module, error) {
var eg errgroup.Group
deps := make([]*core.Module, len(mod.DependencyConfig))
for i, depURL := range mod.DependencyConfig {
i, depURL := i, depURL
eg.Go(func() error {
depMod, err := core.NewModule(mod.Platform, mod.Pipeline).FromRef(
ctx, s.bk, s.services, s.progSockPath,
mod.SourceDirectory,
mod.SourceDirectorySubpath, |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | depURL,
s.runtimeForModule,
)
if err != nil {
return fmt.Errorf("failed to get dependency mod from ref %q: %w", depURL, err)
}
deps[i] = depMod
return nil
})
}
if err := eg.Wait(); err != nil {
return nil, err
}
return deps, nil
})
}
func (s *moduleSchema) installDeps(ctx context.Context, module *core.Module) (*schemaView, error) {
schemaView, err := s.getModuleSchemaView(module)
if err != nil {
return nil, err
}
deps, err := s.dependenciesOf(ctx, module)
if err != nil {
return nil, fmt.Errorf("failed to get module dependencies: %w", err)
}
return schemaView, s.installDepsToSchemaView(ctx, deps, schemaView)
}
func (s *moduleSchema) installDepsToSchemaView(
ctx context.Context,
deps []*core.Module, |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | schemaView *schemaView,
) error {
var eg errgroup.Group
for _, dep := range deps {
dep := dep
eg.Go(func() error {
if err := s.serveModuleToView(ctx, dep, schemaView); err != nil {
return fmt.Errorf("failed to install dependency %q: %w", dep.Name, err)
}
return nil
})
}
return eg.Wait()
}
/* TODO: for module->schema conversion
* Need to handle IDable type as input argument (schema should accept ID as input type)
* Need to handle corner case where a single object is used as both input+output (append "Input" to name?)
* Handle case where scalar from core is returned? Might need API updates unless we hack it and say they are all strings for now...
* If an object from another non-core Module makes its way into this Module's schema, need to include the relevant schema+resolvers for that too.
*/
func (s *moduleSchema) moduleToSchemaFor(ctx context.Context, module *core.Module, dest *schemaView) (ExecutableSchema, error) {
schemaDoc := &ast.SchemaDocument{}
newResolvers := Resolvers{}
for _, def := range module.Objects {
objTypeDef := def.AsObject
objName := gqlObjectName(objTypeDef.Name)
objType, err := s.typeDefToSchema(def, false)
if err != nil {
return nil, fmt.Errorf("failed to convert module to schema: %w", err) |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | }
_, preExistingObject := dest.resolvers()[objName]
if preExistingObject {
if len(objTypeDef.Fields) > 0 || len(objTypeDef.Functions) > 0 {
return nil, fmt.Errorf("cannot attach new fields or functions to object %q from outside module", objName)
}
continue
}
astDef := &ast.Definition{
Name: objName,
Description: formatGqlDescription(objTypeDef.Description),
Kind: ast.Object,
}
newObjResolver := ObjectResolver{}
for _, field := range objTypeDef.Fields {
fieldASTType, err := s.typeDefToSchema(field.TypeDef, false)
if err != nil {
return nil, err
}
fieldName := gqlFieldName(field.Name)
astDef.Fields = append(astDef.Fields, &ast.FieldDefinition{
Name: fieldName,
Description: formatGqlDescription(field.Description),
Type: fieldASTType,
}) |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | if field.TypeDef.Kind == core.TypeDefKindObject {
newObjResolver[fieldName] = func(p graphql.ResolveParams) (any, error) {
res, err := graphql.DefaultResolveFn(p)
if err != nil {
return nil, err
}
id, ok := res.(string)
if !ok {
return nil, fmt.Errorf("expected string %sID, got %T", field.TypeDef.AsObject.Name, res)
}
return core.ResourceFromID(id)
}
} else {
_ = 1
}
}
for _, fn := range objTypeDef.Functions {
resolver, err := s.functionResolver(astDef, module, fn, dest)
if err != nil {
return nil, err
}
newObjResolver[gqlFieldName(fn.Name)] = resolver
}
if len(newObjResolver) > 0 {
newResolvers[objName] = newObjResolver
}
if len(astDef.Fields) > 0 { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | schemaDoc.Definitions = append(schemaDoc.Definitions, astDef)
}
constructorName := gqlFieldName(def.AsObject.Name)
if constructorName == gqlFieldName(module.Name) {
schemaDoc.Extensions = append(schemaDoc.Extensions, &ast.Definition{
Name: "Query",
Kind: ast.Object,
Fields: ast.FieldList{&ast.FieldDefinition{
Name: constructorName,
Type: objType,
}},
})
newResolvers["Query"] = ObjectResolver{
constructorName: PassthroughResolver,
}
}
}
buf := &bytes.Buffer{}
formatter.NewFormatter(buf).FormatSchemaDocument(schemaDoc)
schemaStr := buf.String()
return StaticSchema(StaticSchemaParams{
Name: module.Name,
Schema: schemaStr,
Resolvers: newResolvers,
}), nil
}
/* |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | This formats comments in the schema as:
"""
comment
"""
Which avoids corner cases where the comment ends in a `"`.
*/
func formatGqlDescription(desc string) string {
return "\n" + strings.TrimSpace(desc) + "\n"
}
func (s *moduleSchema) typeDefToSchema(typeDef *core.TypeDef, isInput bool) (*ast.Type, error) {
switch typeDef.Kind {
case core.TypeDefKindString:
return &ast.Type{
NamedType: "String",
NonNull: !typeDef.Optional,
}, nil
case core.TypeDefKindInteger:
return &ast.Type{
NamedType: "Int",
NonNull: !typeDef.Optional,
}, nil
case core.TypeDefKindBoolean:
return &ast.Type{
NamedType: "Boolean",
NonNull: !typeDef.Optional,
}, nil
case core.TypeDefKindVoid:
return &ast.Type{
NamedType: "Void",
NonNull: !typeDef.Optional, |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | }, nil
case core.TypeDefKindList:
if typeDef.AsList == nil {
return nil, fmt.Errorf("expected list type def, got nil")
}
astType, err := s.typeDefToSchema(typeDef.AsList.ElementTypeDef, isInput)
if err != nil {
return nil, err
}
return &ast.Type{
Elem: astType,
NonNull: !typeDef.Optional,
}, nil
case core.TypeDefKindObject:
if typeDef.AsObject == nil {
return nil, fmt.Errorf("expected object type def, got nil")
}
objTypeDef := typeDef.AsObject
objName := gqlObjectName(objTypeDef.Name)
if isInput {
return &ast.Type{NamedType: objName + "ID", NonNull: !typeDef.Optional}, nil
}
return &ast.Type{NamedType: objName, NonNull: !typeDef.Optional}, nil
default:
return nil, fmt.Errorf("unsupported type kind %q", typeDef.Kind)
}
}
func (s *moduleSchema) functionResolver(
parentObj *ast.Definition, |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | module *core.Module,
fn *core.Function,
dest *schemaView,
) (graphql.FieldResolveFn, error) {
fnName := gqlFieldName(fn.Name)
objFnName := fmt.Sprintf("%s.%s", parentObj.Name, fnName)
returnASTType, err := s.typeDefToSchema(fn.ReturnType, false)
if err != nil {
return nil, err
}
var argASTTypes ast.ArgumentDefinitionList
for _, fnArg := range fn.Args {
argASTType, err := s.typeDefToSchema(fnArg.TypeDef, true)
if err != nil {
return nil, err
}
defaultValue, err := astDefaultValue(fnArg.TypeDef, fnArg.DefaultValue)
if err != nil {
return nil, err
}
argASTTypes = append(argASTTypes, &ast.ArgumentDefinition{
Name: gqlArgName(fnArg.Name),
Description: formatGqlDescription(fnArg.Description),
Type: argASTType,
DefaultValue: defaultValue,
})
}
fieldDef := &ast.FieldDefinition{
Name: fnName,
Description: formatGqlDescription(fn.Description), |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | Type: returnASTType,
Arguments: argASTTypes,
}
parentObj.Fields = append(parentObj.Fields, fieldDef)
var returnIDableObjectResolver IDableObjectResolver
if fn.ReturnType.Kind == core.TypeDefKindObject {
returnIDableObjectResolver, _ = s.idableObjectResolver(fn.ReturnType.AsObject.Name, dest)
}
parentIDableObjectResolver, _ := s.idableObjectResolver(parentObj.Name, dest)
return ToResolver(func(ctx context.Context, parent any, args map[string]any) (_ any, rerr error) {
defer func() {
if r := recover(); r != nil {
rerr = fmt.Errorf("panic in %s: %s %s", objFnName, r, string(debug.Stack()))
}
}()
if parentIDableObjectResolver != nil {
id, err := parentIDableObjectResolver.ToID(parent)
if err != nil {
return nil, fmt.Errorf("failed to get parent ID: %w", err)
}
parent = id
}
argNames := make(map[string]string, len(fn.Args))
for _, arg := range fn.Args {
argNames[arg.Name] = arg.OriginalName
}
var callInput []*core.CallInput |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | for k, v := range args {
n, ok := argNames[k]
if !ok {
continue
}
callInput = append(callInput, &core.CallInput{
Name: n,
Value: v,
})
}
result, err := s.functionCall(ctx, fn, functionCallArgs{
Module: module,
Input: callInput,
ParentOriginalName: fn.ParentOriginalName,
Parent: parent,
})
if err != nil {
return nil, fmt.Errorf("failed to call function %q: %w", objFnName, err)
}
if returnIDableObjectResolver == nil {
return result, nil
}
id, ok := result.(string)
if !ok {
return nil, fmt.Errorf("expected string ID result for %s, got %T", objFnName, result)
}
return returnIDableObjectResolver.FromID(id)
}), nil
}
func astDefaultValue(typeDef *core.TypeDef, val any) (*ast.Value, error) { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | if val == nil {
return nil, nil
}
switch typeDef.Kind {
case core.TypeDefKindString:
strVal, ok := val.(string)
if !ok {
return nil, fmt.Errorf("expected string default value, got %T", val)
}
return &ast.Value{
Kind: ast.StringValue,
Raw: strVal,
}, nil
case core.TypeDefKindInteger:
var intVal int
switch val := val.(type) {
case int:
intVal = val
case float64:
intVal = int(val)
default:
return nil, fmt.Errorf("expected integer default value, got %T", val) |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | }
return &ast.Value{
Kind: ast.IntValue,
Raw: strconv.Itoa(intVal),
}, nil
case core.TypeDefKindBoolean:
boolVal, ok := val.(bool)
if !ok {
return nil, fmt.Errorf("expected bool default value, got %T", val)
}
return &ast.Value{
Kind: ast.BooleanValue,
Raw: strconv.FormatBool(boolVal),
}, nil
case core.TypeDefKindVoid:
if val != nil {
return nil, fmt.Errorf("expected nil value, got %T", val)
}
return &ast.Value{
Kind: ast.NullValue,
Raw: "null",
}, nil
case core.TypeDefKindList:
astVal := &ast.Value{Kind: ast.ListValue}
listVal, ok := val.([]any)
if !ok {
return nil, fmt.Errorf("expected list default value, got %T", val)
}
for _, elemVal := range listVal { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | elemASTVal, err := astDefaultValue(typeDef.AsList.ElementTypeDef, elemVal)
if err != nil {
return nil, fmt.Errorf("failed to get default value for list element: %w", err)
}
astVal.Children = append(astVal.Children, &ast.ChildValue{
Value: elemASTVal,
})
}
return astVal, nil
case core.TypeDefKindObject:
astVal := &ast.Value{Kind: ast.ObjectValue}
mapVal, ok := val.(map[string]any)
if !ok {
return nil, fmt.Errorf("expected object default value, got %T", val)
}
for name, val := range mapVal {
name = gqlFieldName(name)
field, ok := typeDef.AsObject.FieldByName(name)
if !ok {
return nil, fmt.Errorf("object field %s.%s not found", typeDef.AsObject.Name, name)
}
fieldASTVal, err := astDefaultValue(field.TypeDef, val)
if err != nil {
return nil, fmt.Errorf("failed to get default value for object field %q: %w", name, err)
}
astVal.Children = append(astVal.Children, &ast.ChildValue{
Name: name,
Value: fieldASTVal,
}) |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | }
return astVal, nil
default:
return nil, fmt.Errorf("unsupported type kind %q", typeDef.Kind)
}
}
func (s *moduleSchema) validateTypeDef(typeDef *core.TypeDef, schemaView *schemaView) error {
switch typeDef.Kind {
case core.TypeDefKindList:
return s.validateTypeDef(typeDef.AsList.ElementTypeDef, schemaView)
case core.TypeDefKindObject:
obj := typeDef.AsObject
baseObjName := gqlObjectName(obj.Name)
_, preExistingObject := schemaView.resolvers()[baseObjName]
if preExistingObject {
return nil
}
for _, field := range obj.Fields {
if gqlFieldName(field.Name) == "id" {
return fmt.Errorf("cannot define field with reserved name %q on object %q", field.Name, obj.Name)
}
if err := s.validateTypeDef(field.TypeDef, schemaView); err != nil {
return err
}
}
for _, fn := range obj.Functions {
if gqlFieldName(fn.Name) == "id" {
return fmt.Errorf("cannot define function with reserved name %q on object %q", fn.Name, obj.Name) |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | }
if err := s.validateTypeDef(fn.ReturnType, schemaView); err != nil {
return err
}
for _, arg := range fn.Args {
if gqlArgName(arg.Name) == "id" {
return fmt.Errorf("cannot define argument with reserved name %q on function %q", arg.Name, fn.Name)
}
if err := s.validateTypeDef(arg.TypeDef, schemaView); err != nil {
return err
}
}
}
}
return nil
}
func (s *moduleSchema) namespaceTypeDef(typeDef *core.TypeDef, mod *core.Module, schemaView *schemaView) {
switch typeDef.Kind {
case core.TypeDefKindList:
s.namespaceTypeDef(typeDef.AsList.ElementTypeDef, mod, schemaView)
case core.TypeDefKindObject:
obj := typeDef.AsObject
baseObjName := gqlObjectName(obj.Name)
_, preExistingObject := schemaView.resolvers()[baseObjName]
if !preExistingObject {
obj.Name = namespaceObject(obj.Name, mod.Name)
}
for _, field := range obj.Fields { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,860 | Zenith: fix Go struct field json serialization | https://github.com/dagger/dagger/pull/5757#issuecomment-1744739721
Right now if you have something like:
```go
type Foo struct {
Bar `json:"blahblah"`
}
```
The graphql schema for `Foo` will be populated with a field called `Bar`, but when we do json serialization we use `blahblah`, which means that if you try to query for the value of the `Bar` field, our gql server hits the trivial resolver codepath and looks for `bar` in the json object and doesn't find it (since it's been serialized to `blahblah`).
My first thought was that if a json struct tag is present, we should use that as the graphql field name rather than the go name. That would fix this problem I think, but it's more debatable whether it's surprising behavior (or honestly if anyone will really care about this).
---
Possibly related issue from https://github.com/dagger/dagger/pull/5757#issuecomment-1752775608
```golang
package main
import (
"context"
)
type Foo struct{}
type Test struct {
X string
Y int
}
func (t *Test) Void() {}
func (m *Foo) MyFunction(ctx context.Context) Test {
return Test{X: "hello", Y: 1337}
}
```
```bash
$ echo '{foo{myFunction{x}}}' | dagger query -m ""
...
β§ 1.17s β 22 β
20 β 2
Error: make request: input:1: foo.myFunction.x Cannot return null for non-nullable field Test.x.
```
If I modify the struct with JSON field names, the above works:
```golang
type Test struct {
X string `json:"x"`
Y int `json:"y"`
}
```
---
cc @vito @jedevc | https://github.com/dagger/dagger/issues/5860 | https://github.com/dagger/dagger/pull/6057 | 2c554b2ac26c4c6863893bac94d85108cecb48d9 | e1d69edbfd0f94c93489edac4d9d6050c36fc3b7 | 2023-10-10T22:50:32Z | go | 2023-11-14T23:56:25Z | core/schema/module.go | s.namespaceTypeDef(field.TypeDef, mod, schemaView)
}
for _, fn := range obj.Functions {
s.namespaceTypeDef(fn.ReturnType, mod, schemaView)
for _, arg := range fn.Args {
s.namespaceTypeDef(arg.TypeDef, mod, schemaView)
}
}
}
}
func gqlObjectName(name string) string {
return strcase.ToCamel(name)
}
func namespaceObject(objName, namespace string) string {
if gqlObjectName(objName) == gqlObjectName(namespace) {
return objName
}
return gqlObjectName(namespace + "_" + objName)
}
func gqlFieldName(name string) string {
return strcase.ToLowerCamel(name)
}
func gqlArgName(name string) string {
return strcase.ToLowerCamel(name)
} |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,791 | π secrets scrubbing implementation causes excessive log output latency | ### What is the issue?
# Context
We have a dagger pipeline which, at some point, [mounts secrets](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/actions/environments.py#L1053) to a container which is then runs [integration tests](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/gradle.py#L157) by with_exec'ing a task in gradle.
We are just as bad computer programmers as anyone and sometimes we introduce regressions which cause our integration tests to hang. In our particular case, the bug we introduced was that we tried to connect a jdbc driver to a nonexistent host and we'd hit some absurdly large timeout in our code.
What's unexpected, and why I'm filing an issue right now, is that dagger would be completely silent about the output of this `with_exec` step until it eventually failed.
# The problem
I eventually found that dagger's secrets scrubbing implementation is to blame. In our case, we mount about 20 secrets files, which while a lot, doesn't seem that crazy. I read dagger's code [1] and it appears that if there's a nonzero number of secrets mounted (env vars or files) the output gets piped through `replace.Chain` which chains a bunch of `Transformer` instances from go's transform module [2]. There's one instance per secret and each appears to wrap a reader with a hardcoded buffer of 4kB [3].
In our case, our gradle process was simply not chatty enough to overcome this buffering and so it seemed like it didn't do anything. We're on an old version of dagger but the problem seems still present in the `main` branch from what I can tell.
# My expectations as a user
The need to scrub secrets is not in question. However, `transform` appears to be written in a way that biases throughput over latency, when in our case exactly the opposite is desirable: when scrubbing secrets my expectation is that the output becomes visible to me _as soon as possible_. I don't want to wait for some arbitrary unconfigurable buffer to fill up and I certainly don't want that behaviour to be `O(n)` to the number of secrets mounted.
I say as soon as possible but that's not strictly speaking true, it's not like each rune has to pass through as soon as it's determined that it's not part of a prefix of one of the secrets. This being textual output, I'd be fine if it was each _line_ that gets passed through ASAP. I'm guessing this would also be undoubtedly less complicated to implement on your end and I'm also guessing that most secrets are not multiline (or if they are, it's only a handful of lines).
tl;dr: no need to go crazy here, but I'll be happy with reasonable and predictable behaviour.
# Repro
I didn't look into how dagger is tested but the desired behaviour of the return value of `NewSecretScrubReader` seems adequately unit-testable from my naive standpoint:
1. mock mounting 1, 10 and 100 secrets in each test case;
2. kick off a goroutine with an `io.Reader` which mocks a `with_exec`'ed process' `stdout`;
3. have that `io.Reader` serve a fixed number of bytes and then block on a channel, then serve a bunch more bytes, then block again;
4. concurrently, expect the `io.Reader` returned by `NewSecretScrubReader` to read an expected subset of those bytes, then unblock the channel, then read another expected subset of bytes, then unblock again.
# Notes
Dear dagger maintainers: I hope you're not finding me overprescriptive here or feel that I'm babying you. Far from it! I'm being deliberately wordy because I'm reasonably hopeful that this issue is quite cheap to fix so I'm provide as much info as I can to that aim. On our end, it sure caused a lot of head-scratching.
This is only an issue in an interactive setting: developing locally, or looking at dagger.cloud, which is probably why it went unnoticed (I didn't find any similar issue, though I only did a quick search).
# References
[1] https://github.com/dagger/dagger/blob/v0.6.4/cmd/shim/main.go#L294
[2] https://golang.org/x/text/transform
[3] https://cs.opensource.google/go/x/text/+/refs/tags/v0.13.0:transform/transform.go;l=130
### Log output
_No response_
### Steps to reproduce
_No response_
### SDK version
0.6.4
### OS version
irrelevant, I believe, but macOS and some unremarkable linux distro | https://github.com/dagger/dagger/issues/5791 | https://github.com/dagger/dagger/pull/6034 | b28daae7531cdb2ed7c2ced9da2c69fd3b080ee7 | 80180aaaed1e1e91a13dbf7df7e0411a9a54c7d3 | 2023-09-18T13:41:28Z | go | 2023-11-20T14:49:50Z | cmd/shim/secret_scrub.go | package main
import (
"fmt"
"io"
"io/fs"
"path/filepath"
"strings"
"github.com/dagger/dagger/core"
"github.com/icholy/replace"
"golang.org/x/text/transform"
)
var (
scrubString = []byte("***")
)
func NewSecretScrubReader(r io.Reader, currentDirPath string, fsys fs.FS, env []string, secretsToScrub core.SecretToScrubInfo) (io.Reader, error) { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,791 | π secrets scrubbing implementation causes excessive log output latency | ### What is the issue?
# Context
We have a dagger pipeline which, at some point, [mounts secrets](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/actions/environments.py#L1053) to a container which is then runs [integration tests](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/gradle.py#L157) by with_exec'ing a task in gradle.
We are just as bad computer programmers as anyone and sometimes we introduce regressions which cause our integration tests to hang. In our particular case, the bug we introduced was that we tried to connect a jdbc driver to a nonexistent host and we'd hit some absurdly large timeout in our code.
What's unexpected, and why I'm filing an issue right now, is that dagger would be completely silent about the output of this `with_exec` step until it eventually failed.
# The problem
I eventually found that dagger's secrets scrubbing implementation is to blame. In our case, we mount about 20 secrets files, which while a lot, doesn't seem that crazy. I read dagger's code [1] and it appears that if there's a nonzero number of secrets mounted (env vars or files) the output gets piped through `replace.Chain` which chains a bunch of `Transformer` instances from go's transform module [2]. There's one instance per secret and each appears to wrap a reader with a hardcoded buffer of 4kB [3].
In our case, our gradle process was simply not chatty enough to overcome this buffering and so it seemed like it didn't do anything. We're on an old version of dagger but the problem seems still present in the `main` branch from what I can tell.
# My expectations as a user
The need to scrub secrets is not in question. However, `transform` appears to be written in a way that biases throughput over latency, when in our case exactly the opposite is desirable: when scrubbing secrets my expectation is that the output becomes visible to me _as soon as possible_. I don't want to wait for some arbitrary unconfigurable buffer to fill up and I certainly don't want that behaviour to be `O(n)` to the number of secrets mounted.
I say as soon as possible but that's not strictly speaking true, it's not like each rune has to pass through as soon as it's determined that it's not part of a prefix of one of the secrets. This being textual output, I'd be fine if it was each _line_ that gets passed through ASAP. I'm guessing this would also be undoubtedly less complicated to implement on your end and I'm also guessing that most secrets are not multiline (or if they are, it's only a handful of lines).
tl;dr: no need to go crazy here, but I'll be happy with reasonable and predictable behaviour.
# Repro
I didn't look into how dagger is tested but the desired behaviour of the return value of `NewSecretScrubReader` seems adequately unit-testable from my naive standpoint:
1. mock mounting 1, 10 and 100 secrets in each test case;
2. kick off a goroutine with an `io.Reader` which mocks a `with_exec`'ed process' `stdout`;
3. have that `io.Reader` serve a fixed number of bytes and then block on a channel, then serve a bunch more bytes, then block again;
4. concurrently, expect the `io.Reader` returned by `NewSecretScrubReader` to read an expected subset of those bytes, then unblock the channel, then read another expected subset of bytes, then unblock again.
# Notes
Dear dagger maintainers: I hope you're not finding me overprescriptive here or feel that I'm babying you. Far from it! I'm being deliberately wordy because I'm reasonably hopeful that this issue is quite cheap to fix so I'm provide as much info as I can to that aim. On our end, it sure caused a lot of head-scratching.
This is only an issue in an interactive setting: developing locally, or looking at dagger.cloud, which is probably why it went unnoticed (I didn't find any similar issue, though I only did a quick search).
# References
[1] https://github.com/dagger/dagger/blob/v0.6.4/cmd/shim/main.go#L294
[2] https://golang.org/x/text/transform
[3] https://cs.opensource.google/go/x/text/+/refs/tags/v0.13.0:transform/transform.go;l=130
### Log output
_No response_
### Steps to reproduce
_No response_
### SDK version
0.6.4
### OS version
irrelevant, I believe, but macOS and some unremarkable linux distro | https://github.com/dagger/dagger/issues/5791 | https://github.com/dagger/dagger/pull/6034 | b28daae7531cdb2ed7c2ced9da2c69fd3b080ee7 | 80180aaaed1e1e91a13dbf7df7e0411a9a54c7d3 | 2023-09-18T13:41:28Z | go | 2023-11-20T14:49:50Z | cmd/shim/secret_scrub.go | secrets := loadSecretsToScrubFromEnv(env, secretsToScrub.Envs)
fileSecrets, err := loadSecretsToScrubFromFiles(currentDirPath, fsys, secretsToScrub.Files)
if err != nil {
return nil, fmt.Errorf("could not load secrets from file: %w", err)
}
secrets = append(secrets, fileSecrets...)
secretAsBytes := make([][]byte, 0)
for _, v := range secrets {
if len(v) == 0 {
continue
}
secretAsBytes = append(secretAsBytes, []byte(v))
}
replaceChain := make([]transform.Transformer, 0)
for _, s := range secretAsBytes {
replaceChain = append(
replaceChain,
replace.Bytes(s, scrubString),
)
}
return replace.Chain(r, replaceChain...), nil
}
func loadSecretsToScrubFromEnv(env []string, secretsToScrub []string) []string { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,791 | π secrets scrubbing implementation causes excessive log output latency | ### What is the issue?
# Context
We have a dagger pipeline which, at some point, [mounts secrets](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/actions/environments.py#L1053) to a container which is then runs [integration tests](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/gradle.py#L157) by with_exec'ing a task in gradle.
We are just as bad computer programmers as anyone and sometimes we introduce regressions which cause our integration tests to hang. In our particular case, the bug we introduced was that we tried to connect a jdbc driver to a nonexistent host and we'd hit some absurdly large timeout in our code.
What's unexpected, and why I'm filing an issue right now, is that dagger would be completely silent about the output of this `with_exec` step until it eventually failed.
# The problem
I eventually found that dagger's secrets scrubbing implementation is to blame. In our case, we mount about 20 secrets files, which while a lot, doesn't seem that crazy. I read dagger's code [1] and it appears that if there's a nonzero number of secrets mounted (env vars or files) the output gets piped through `replace.Chain` which chains a bunch of `Transformer` instances from go's transform module [2]. There's one instance per secret and each appears to wrap a reader with a hardcoded buffer of 4kB [3].
In our case, our gradle process was simply not chatty enough to overcome this buffering and so it seemed like it didn't do anything. We're on an old version of dagger but the problem seems still present in the `main` branch from what I can tell.
# My expectations as a user
The need to scrub secrets is not in question. However, `transform` appears to be written in a way that biases throughput over latency, when in our case exactly the opposite is desirable: when scrubbing secrets my expectation is that the output becomes visible to me _as soon as possible_. I don't want to wait for some arbitrary unconfigurable buffer to fill up and I certainly don't want that behaviour to be `O(n)` to the number of secrets mounted.
I say as soon as possible but that's not strictly speaking true, it's not like each rune has to pass through as soon as it's determined that it's not part of a prefix of one of the secrets. This being textual output, I'd be fine if it was each _line_ that gets passed through ASAP. I'm guessing this would also be undoubtedly less complicated to implement on your end and I'm also guessing that most secrets are not multiline (or if they are, it's only a handful of lines).
tl;dr: no need to go crazy here, but I'll be happy with reasonable and predictable behaviour.
# Repro
I didn't look into how dagger is tested but the desired behaviour of the return value of `NewSecretScrubReader` seems adequately unit-testable from my naive standpoint:
1. mock mounting 1, 10 and 100 secrets in each test case;
2. kick off a goroutine with an `io.Reader` which mocks a `with_exec`'ed process' `stdout`;
3. have that `io.Reader` serve a fixed number of bytes and then block on a channel, then serve a bunch more bytes, then block again;
4. concurrently, expect the `io.Reader` returned by `NewSecretScrubReader` to read an expected subset of those bytes, then unblock the channel, then read another expected subset of bytes, then unblock again.
# Notes
Dear dagger maintainers: I hope you're not finding me overprescriptive here or feel that I'm babying you. Far from it! I'm being deliberately wordy because I'm reasonably hopeful that this issue is quite cheap to fix so I'm provide as much info as I can to that aim. On our end, it sure caused a lot of head-scratching.
This is only an issue in an interactive setting: developing locally, or looking at dagger.cloud, which is probably why it went unnoticed (I didn't find any similar issue, though I only did a quick search).
# References
[1] https://github.com/dagger/dagger/blob/v0.6.4/cmd/shim/main.go#L294
[2] https://golang.org/x/text/transform
[3] https://cs.opensource.google/go/x/text/+/refs/tags/v0.13.0:transform/transform.go;l=130
### Log output
_No response_
### Steps to reproduce
_No response_
### SDK version
0.6.4
### OS version
irrelevant, I believe, but macOS and some unremarkable linux distro | https://github.com/dagger/dagger/issues/5791 | https://github.com/dagger/dagger/pull/6034 | b28daae7531cdb2ed7c2ced9da2c69fd3b080ee7 | 80180aaaed1e1e91a13dbf7df7e0411a9a54c7d3 | 2023-09-18T13:41:28Z | go | 2023-11-20T14:49:50Z | cmd/shim/secret_scrub.go | secrets := []string{}
for _, envKV := range env {
envName, envValue, ok := strings.Cut(envKV, "=")
if !ok {
continue
}
for _, envToScrub := range secretsToScrub {
if envName == envToScrub {
secrets = append(secrets, envValue)
}
}
}
return secrets
}
func loadSecretsToScrubFromFiles(currentDirPathAbs string, fsys fs.FS, secretFilePathsToScrub []string) ([]string, error) { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,791 | π secrets scrubbing implementation causes excessive log output latency | ### What is the issue?
# Context
We have a dagger pipeline which, at some point, [mounts secrets](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/actions/environments.py#L1053) to a container which is then runs [integration tests](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/gradle.py#L157) by with_exec'ing a task in gradle.
We are just as bad computer programmers as anyone and sometimes we introduce regressions which cause our integration tests to hang. In our particular case, the bug we introduced was that we tried to connect a jdbc driver to a nonexistent host and we'd hit some absurdly large timeout in our code.
What's unexpected, and why I'm filing an issue right now, is that dagger would be completely silent about the output of this `with_exec` step until it eventually failed.
# The problem
I eventually found that dagger's secrets scrubbing implementation is to blame. In our case, we mount about 20 secrets files, which while a lot, doesn't seem that crazy. I read dagger's code [1] and it appears that if there's a nonzero number of secrets mounted (env vars or files) the output gets piped through `replace.Chain` which chains a bunch of `Transformer` instances from go's transform module [2]. There's one instance per secret and each appears to wrap a reader with a hardcoded buffer of 4kB [3].
In our case, our gradle process was simply not chatty enough to overcome this buffering and so it seemed like it didn't do anything. We're on an old version of dagger but the problem seems still present in the `main` branch from what I can tell.
# My expectations as a user
The need to scrub secrets is not in question. However, `transform` appears to be written in a way that biases throughput over latency, when in our case exactly the opposite is desirable: when scrubbing secrets my expectation is that the output becomes visible to me _as soon as possible_. I don't want to wait for some arbitrary unconfigurable buffer to fill up and I certainly don't want that behaviour to be `O(n)` to the number of secrets mounted.
I say as soon as possible but that's not strictly speaking true, it's not like each rune has to pass through as soon as it's determined that it's not part of a prefix of one of the secrets. This being textual output, I'd be fine if it was each _line_ that gets passed through ASAP. I'm guessing this would also be undoubtedly less complicated to implement on your end and I'm also guessing that most secrets are not multiline (or if they are, it's only a handful of lines).
tl;dr: no need to go crazy here, but I'll be happy with reasonable and predictable behaviour.
# Repro
I didn't look into how dagger is tested but the desired behaviour of the return value of `NewSecretScrubReader` seems adequately unit-testable from my naive standpoint:
1. mock mounting 1, 10 and 100 secrets in each test case;
2. kick off a goroutine with an `io.Reader` which mocks a `with_exec`'ed process' `stdout`;
3. have that `io.Reader` serve a fixed number of bytes and then block on a channel, then serve a bunch more bytes, then block again;
4. concurrently, expect the `io.Reader` returned by `NewSecretScrubReader` to read an expected subset of those bytes, then unblock the channel, then read another expected subset of bytes, then unblock again.
# Notes
Dear dagger maintainers: I hope you're not finding me overprescriptive here or feel that I'm babying you. Far from it! I'm being deliberately wordy because I'm reasonably hopeful that this issue is quite cheap to fix so I'm provide as much info as I can to that aim. On our end, it sure caused a lot of head-scratching.
This is only an issue in an interactive setting: developing locally, or looking at dagger.cloud, which is probably why it went unnoticed (I didn't find any similar issue, though I only did a quick search).
# References
[1] https://github.com/dagger/dagger/blob/v0.6.4/cmd/shim/main.go#L294
[2] https://golang.org/x/text/transform
[3] https://cs.opensource.google/go/x/text/+/refs/tags/v0.13.0:transform/transform.go;l=130
### Log output
_No response_
### Steps to reproduce
_No response_
### SDK version
0.6.4
### OS version
irrelevant, I believe, but macOS and some unremarkable linux distro | https://github.com/dagger/dagger/issues/5791 | https://github.com/dagger/dagger/pull/6034 | b28daae7531cdb2ed7c2ced9da2c69fd3b080ee7 | 80180aaaed1e1e91a13dbf7df7e0411a9a54c7d3 | 2023-09-18T13:41:28Z | go | 2023-11-20T14:49:50Z | cmd/shim/secret_scrub.go | secrets := make([]string, 0, len(secretFilePathsToScrub))
for _, fileToScrub := range secretFilePathsToScrub {
absFileToScrub := fileToScrub
if !filepath.IsAbs(fileToScrub) {
absFileToScrub = filepath.Join("/", fileToScrub)
}
if strings.HasPrefix(fileToScrub, currentDirPathAbs) || strings.HasPrefix(fileToScrub, currentDirPathAbs[1:]) {
absFileToScrub = strings.TrimPrefix(fileToScrub, currentDirPathAbs)
absFileToScrub = filepath.Join("/", absFileToScrub)
}
secret, err := fs.ReadFile(fsys, absFileToScrub[1:])
if err != nil {
return nil, fmt.Errorf("secret value not available for: %w", err)
}
secrets = append(secrets, string(secret))
}
return secrets, nil
} |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,791 | π secrets scrubbing implementation causes excessive log output latency | ### What is the issue?
# Context
We have a dagger pipeline which, at some point, [mounts secrets](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/actions/environments.py#L1053) to a container which is then runs [integration tests](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/gradle.py#L157) by with_exec'ing a task in gradle.
We are just as bad computer programmers as anyone and sometimes we introduce regressions which cause our integration tests to hang. In our particular case, the bug we introduced was that we tried to connect a jdbc driver to a nonexistent host and we'd hit some absurdly large timeout in our code.
What's unexpected, and why I'm filing an issue right now, is that dagger would be completely silent about the output of this `with_exec` step until it eventually failed.
# The problem
I eventually found that dagger's secrets scrubbing implementation is to blame. In our case, we mount about 20 secrets files, which while a lot, doesn't seem that crazy. I read dagger's code [1] and it appears that if there's a nonzero number of secrets mounted (env vars or files) the output gets piped through `replace.Chain` which chains a bunch of `Transformer` instances from go's transform module [2]. There's one instance per secret and each appears to wrap a reader with a hardcoded buffer of 4kB [3].
In our case, our gradle process was simply not chatty enough to overcome this buffering and so it seemed like it didn't do anything. We're on an old version of dagger but the problem seems still present in the `main` branch from what I can tell.
# My expectations as a user
The need to scrub secrets is not in question. However, `transform` appears to be written in a way that biases throughput over latency, when in our case exactly the opposite is desirable: when scrubbing secrets my expectation is that the output becomes visible to me _as soon as possible_. I don't want to wait for some arbitrary unconfigurable buffer to fill up and I certainly don't want that behaviour to be `O(n)` to the number of secrets mounted.
I say as soon as possible but that's not strictly speaking true, it's not like each rune has to pass through as soon as it's determined that it's not part of a prefix of one of the secrets. This being textual output, I'd be fine if it was each _line_ that gets passed through ASAP. I'm guessing this would also be undoubtedly less complicated to implement on your end and I'm also guessing that most secrets are not multiline (or if they are, it's only a handful of lines).
tl;dr: no need to go crazy here, but I'll be happy with reasonable and predictable behaviour.
# Repro
I didn't look into how dagger is tested but the desired behaviour of the return value of `NewSecretScrubReader` seems adequately unit-testable from my naive standpoint:
1. mock mounting 1, 10 and 100 secrets in each test case;
2. kick off a goroutine with an `io.Reader` which mocks a `with_exec`'ed process' `stdout`;
3. have that `io.Reader` serve a fixed number of bytes and then block on a channel, then serve a bunch more bytes, then block again;
4. concurrently, expect the `io.Reader` returned by `NewSecretScrubReader` to read an expected subset of those bytes, then unblock the channel, then read another expected subset of bytes, then unblock again.
# Notes
Dear dagger maintainers: I hope you're not finding me overprescriptive here or feel that I'm babying you. Far from it! I'm being deliberately wordy because I'm reasonably hopeful that this issue is quite cheap to fix so I'm provide as much info as I can to that aim. On our end, it sure caused a lot of head-scratching.
This is only an issue in an interactive setting: developing locally, or looking at dagger.cloud, which is probably why it went unnoticed (I didn't find any similar issue, though I only did a quick search).
# References
[1] https://github.com/dagger/dagger/blob/v0.6.4/cmd/shim/main.go#L294
[2] https://golang.org/x/text/transform
[3] https://cs.opensource.google/go/x/text/+/refs/tags/v0.13.0:transform/transform.go;l=130
### Log output
_No response_
### Steps to reproduce
_No response_
### SDK version
0.6.4
### OS version
irrelevant, I believe, but macOS and some unremarkable linux distro | https://github.com/dagger/dagger/issues/5791 | https://github.com/dagger/dagger/pull/6034 | b28daae7531cdb2ed7c2ced9da2c69fd3b080ee7 | 80180aaaed1e1e91a13dbf7df7e0411a9a54c7d3 | 2023-09-18T13:41:28Z | go | 2023-11-20T14:49:50Z | cmd/shim/secret_scrub_test.go | package main
import (
"bufio"
"bytes"
_ "embed"
"fmt"
"io"
"testing"
"testing/fstest"
"github.com/dagger/dagger/core"
"github.com/stretchr/testify/require"
)
var (
sshSecretKey string
sshPublicKey string
)
func TestSecretScrubWriterWrite(t *testing.T) { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,791 | π secrets scrubbing implementation causes excessive log output latency | ### What is the issue?
# Context
We have a dagger pipeline which, at some point, [mounts secrets](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/actions/environments.py#L1053) to a container which is then runs [integration tests](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/gradle.py#L157) by with_exec'ing a task in gradle.
We are just as bad computer programmers as anyone and sometimes we introduce regressions which cause our integration tests to hang. In our particular case, the bug we introduced was that we tried to connect a jdbc driver to a nonexistent host and we'd hit some absurdly large timeout in our code.
What's unexpected, and why I'm filing an issue right now, is that dagger would be completely silent about the output of this `with_exec` step until it eventually failed.
# The problem
I eventually found that dagger's secrets scrubbing implementation is to blame. In our case, we mount about 20 secrets files, which while a lot, doesn't seem that crazy. I read dagger's code [1] and it appears that if there's a nonzero number of secrets mounted (env vars or files) the output gets piped through `replace.Chain` which chains a bunch of `Transformer` instances from go's transform module [2]. There's one instance per secret and each appears to wrap a reader with a hardcoded buffer of 4kB [3].
In our case, our gradle process was simply not chatty enough to overcome this buffering and so it seemed like it didn't do anything. We're on an old version of dagger but the problem seems still present in the `main` branch from what I can tell.
# My expectations as a user
The need to scrub secrets is not in question. However, `transform` appears to be written in a way that biases throughput over latency, when in our case exactly the opposite is desirable: when scrubbing secrets my expectation is that the output becomes visible to me _as soon as possible_. I don't want to wait for some arbitrary unconfigurable buffer to fill up and I certainly don't want that behaviour to be `O(n)` to the number of secrets mounted.
I say as soon as possible but that's not strictly speaking true, it's not like each rune has to pass through as soon as it's determined that it's not part of a prefix of one of the secrets. This being textual output, I'd be fine if it was each _line_ that gets passed through ASAP. I'm guessing this would also be undoubtedly less complicated to implement on your end and I'm also guessing that most secrets are not multiline (or if they are, it's only a handful of lines).
tl;dr: no need to go crazy here, but I'll be happy with reasonable and predictable behaviour.
# Repro
I didn't look into how dagger is tested but the desired behaviour of the return value of `NewSecretScrubReader` seems adequately unit-testable from my naive standpoint:
1. mock mounting 1, 10 and 100 secrets in each test case;
2. kick off a goroutine with an `io.Reader` which mocks a `with_exec`'ed process' `stdout`;
3. have that `io.Reader` serve a fixed number of bytes and then block on a channel, then serve a bunch more bytes, then block again;
4. concurrently, expect the `io.Reader` returned by `NewSecretScrubReader` to read an expected subset of those bytes, then unblock the channel, then read another expected subset of bytes, then unblock again.
# Notes
Dear dagger maintainers: I hope you're not finding me overprescriptive here or feel that I'm babying you. Far from it! I'm being deliberately wordy because I'm reasonably hopeful that this issue is quite cheap to fix so I'm provide as much info as I can to that aim. On our end, it sure caused a lot of head-scratching.
This is only an issue in an interactive setting: developing locally, or looking at dagger.cloud, which is probably why it went unnoticed (I didn't find any similar issue, though I only did a quick search).
# References
[1] https://github.com/dagger/dagger/blob/v0.6.4/cmd/shim/main.go#L294
[2] https://golang.org/x/text/transform
[3] https://cs.opensource.google/go/x/text/+/refs/tags/v0.13.0:transform/transform.go;l=130
### Log output
_No response_
### Steps to reproduce
_No response_
### SDK version
0.6.4
### OS version
irrelevant, I believe, but macOS and some unremarkable linux distro | https://github.com/dagger/dagger/issues/5791 | https://github.com/dagger/dagger/pull/6034 | b28daae7531cdb2ed7c2ced9da2c69fd3b080ee7 | 80180aaaed1e1e91a13dbf7df7e0411a9a54c7d3 | 2023-09-18T13:41:28Z | go | 2023-11-20T14:49:50Z | cmd/shim/secret_scrub_test.go | t.Parallel()
fsys := fstest.MapFS{
"mysecret": &fstest.MapFile{
Data: []byte("my secret file"),
},
"subdir/alsosecret": &fstest.MapFile{
Data: []byte("a subdir secret file \nwith line feed"),
},
}
env := []string{
"MY_SECRET_ID=my secret value",
}
t.Run("scrub files and env", func(t *testing.T) {
var buf bytes.Buffer
buf.WriteString("I love to share my secret value to my close ones. But I keep my secret file to myself. As well as a subdir secret file \nwith line feed.")
currentDirPath := "/"
r, err := NewSecretScrubReader(&buf, currentDirPath, fsys, env, core.SecretToScrubInfo{
Envs: []string{"MY_SECRET_ID"}, |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,791 | π secrets scrubbing implementation causes excessive log output latency | ### What is the issue?
# Context
We have a dagger pipeline which, at some point, [mounts secrets](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/actions/environments.py#L1053) to a container which is then runs [integration tests](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/gradle.py#L157) by with_exec'ing a task in gradle.
We are just as bad computer programmers as anyone and sometimes we introduce regressions which cause our integration tests to hang. In our particular case, the bug we introduced was that we tried to connect a jdbc driver to a nonexistent host and we'd hit some absurdly large timeout in our code.
What's unexpected, and why I'm filing an issue right now, is that dagger would be completely silent about the output of this `with_exec` step until it eventually failed.
# The problem
I eventually found that dagger's secrets scrubbing implementation is to blame. In our case, we mount about 20 secrets files, which while a lot, doesn't seem that crazy. I read dagger's code [1] and it appears that if there's a nonzero number of secrets mounted (env vars or files) the output gets piped through `replace.Chain` which chains a bunch of `Transformer` instances from go's transform module [2]. There's one instance per secret and each appears to wrap a reader with a hardcoded buffer of 4kB [3].
In our case, our gradle process was simply not chatty enough to overcome this buffering and so it seemed like it didn't do anything. We're on an old version of dagger but the problem seems still present in the `main` branch from what I can tell.
# My expectations as a user
The need to scrub secrets is not in question. However, `transform` appears to be written in a way that biases throughput over latency, when in our case exactly the opposite is desirable: when scrubbing secrets my expectation is that the output becomes visible to me _as soon as possible_. I don't want to wait for some arbitrary unconfigurable buffer to fill up and I certainly don't want that behaviour to be `O(n)` to the number of secrets mounted.
I say as soon as possible but that's not strictly speaking true, it's not like each rune has to pass through as soon as it's determined that it's not part of a prefix of one of the secrets. This being textual output, I'd be fine if it was each _line_ that gets passed through ASAP. I'm guessing this would also be undoubtedly less complicated to implement on your end and I'm also guessing that most secrets are not multiline (or if they are, it's only a handful of lines).
tl;dr: no need to go crazy here, but I'll be happy with reasonable and predictable behaviour.
# Repro
I didn't look into how dagger is tested but the desired behaviour of the return value of `NewSecretScrubReader` seems adequately unit-testable from my naive standpoint:
1. mock mounting 1, 10 and 100 secrets in each test case;
2. kick off a goroutine with an `io.Reader` which mocks a `with_exec`'ed process' `stdout`;
3. have that `io.Reader` serve a fixed number of bytes and then block on a channel, then serve a bunch more bytes, then block again;
4. concurrently, expect the `io.Reader` returned by `NewSecretScrubReader` to read an expected subset of those bytes, then unblock the channel, then read another expected subset of bytes, then unblock again.
# Notes
Dear dagger maintainers: I hope you're not finding me overprescriptive here or feel that I'm babying you. Far from it! I'm being deliberately wordy because I'm reasonably hopeful that this issue is quite cheap to fix so I'm provide as much info as I can to that aim. On our end, it sure caused a lot of head-scratching.
This is only an issue in an interactive setting: developing locally, or looking at dagger.cloud, which is probably why it went unnoticed (I didn't find any similar issue, though I only did a quick search).
# References
[1] https://github.com/dagger/dagger/blob/v0.6.4/cmd/shim/main.go#L294
[2] https://golang.org/x/text/transform
[3] https://cs.opensource.google/go/x/text/+/refs/tags/v0.13.0:transform/transform.go;l=130
### Log output
_No response_
### Steps to reproduce
_No response_
### SDK version
0.6.4
### OS version
irrelevant, I believe, but macOS and some unremarkable linux distro | https://github.com/dagger/dagger/issues/5791 | https://github.com/dagger/dagger/pull/6034 | b28daae7531cdb2ed7c2ced9da2c69fd3b080ee7 | 80180aaaed1e1e91a13dbf7df7e0411a9a54c7d3 | 2023-09-18T13:41:28Z | go | 2023-11-20T14:49:50Z | cmd/shim/secret_scrub_test.go | Files: []string{"/mysecret", "/subdir/alsosecret"},
})
require.NoError(t, err)
out, err := io.ReadAll(r)
require.NoError(t, err)
want := "I love to share *** to my close ones. But I keep *** to myself. As well as ***."
require.Equal(t, want, string(out))
})
t.Run("do not scrub empty env", func(t *testing.T) {
env := append(env, "EMPTY_SECRET_ID=")
currentDirPath := "/"
fsys := fstest.MapFS{
"emptysecret": &fstest.MapFile{
Data: []byte(""),
},
}
var buf bytes.Buffer
buf.WriteString("I love to share my secret value to my close ones. But I keep my secret file to myself.")
r, err := NewSecretScrubReader(&buf, currentDirPath, fsys, env, core.SecretToScrubInfo{
Envs: []string{"EMPTY_SECRET_ID"},
Files: []string{"/emptysecret"},
})
require.NoError(t, err)
out, err := io.ReadAll(r)
require.NoError(t, err)
want := "I love to share my secret value to my close ones. But I keep my secret file to myself."
require.Equal(t, want, string(out))
})
}
func TestLoadSecretsToScrubFromEnv(t *testing.T) { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,791 | π secrets scrubbing implementation causes excessive log output latency | ### What is the issue?
# Context
We have a dagger pipeline which, at some point, [mounts secrets](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/actions/environments.py#L1053) to a container which is then runs [integration tests](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/gradle.py#L157) by with_exec'ing a task in gradle.
We are just as bad computer programmers as anyone and sometimes we introduce regressions which cause our integration tests to hang. In our particular case, the bug we introduced was that we tried to connect a jdbc driver to a nonexistent host and we'd hit some absurdly large timeout in our code.
What's unexpected, and why I'm filing an issue right now, is that dagger would be completely silent about the output of this `with_exec` step until it eventually failed.
# The problem
I eventually found that dagger's secrets scrubbing implementation is to blame. In our case, we mount about 20 secrets files, which while a lot, doesn't seem that crazy. I read dagger's code [1] and it appears that if there's a nonzero number of secrets mounted (env vars or files) the output gets piped through `replace.Chain` which chains a bunch of `Transformer` instances from go's transform module [2]. There's one instance per secret and each appears to wrap a reader with a hardcoded buffer of 4kB [3].
In our case, our gradle process was simply not chatty enough to overcome this buffering and so it seemed like it didn't do anything. We're on an old version of dagger but the problem seems still present in the `main` branch from what I can tell.
# My expectations as a user
The need to scrub secrets is not in question. However, `transform` appears to be written in a way that biases throughput over latency, when in our case exactly the opposite is desirable: when scrubbing secrets my expectation is that the output becomes visible to me _as soon as possible_. I don't want to wait for some arbitrary unconfigurable buffer to fill up and I certainly don't want that behaviour to be `O(n)` to the number of secrets mounted.
I say as soon as possible but that's not strictly speaking true, it's not like each rune has to pass through as soon as it's determined that it's not part of a prefix of one of the secrets. This being textual output, I'd be fine if it was each _line_ that gets passed through ASAP. I'm guessing this would also be undoubtedly less complicated to implement on your end and I'm also guessing that most secrets are not multiline (or if they are, it's only a handful of lines).
tl;dr: no need to go crazy here, but I'll be happy with reasonable and predictable behaviour.
# Repro
I didn't look into how dagger is tested but the desired behaviour of the return value of `NewSecretScrubReader` seems adequately unit-testable from my naive standpoint:
1. mock mounting 1, 10 and 100 secrets in each test case;
2. kick off a goroutine with an `io.Reader` which mocks a `with_exec`'ed process' `stdout`;
3. have that `io.Reader` serve a fixed number of bytes and then block on a channel, then serve a bunch more bytes, then block again;
4. concurrently, expect the `io.Reader` returned by `NewSecretScrubReader` to read an expected subset of those bytes, then unblock the channel, then read another expected subset of bytes, then unblock again.
# Notes
Dear dagger maintainers: I hope you're not finding me overprescriptive here or feel that I'm babying you. Far from it! I'm being deliberately wordy because I'm reasonably hopeful that this issue is quite cheap to fix so I'm provide as much info as I can to that aim. On our end, it sure caused a lot of head-scratching.
This is only an issue in an interactive setting: developing locally, or looking at dagger.cloud, which is probably why it went unnoticed (I didn't find any similar issue, though I only did a quick search).
# References
[1] https://github.com/dagger/dagger/blob/v0.6.4/cmd/shim/main.go#L294
[2] https://golang.org/x/text/transform
[3] https://cs.opensource.google/go/x/text/+/refs/tags/v0.13.0:transform/transform.go;l=130
### Log output
_No response_
### Steps to reproduce
_No response_
### SDK version
0.6.4
### OS version
irrelevant, I believe, but macOS and some unremarkable linux distro | https://github.com/dagger/dagger/issues/5791 | https://github.com/dagger/dagger/pull/6034 | b28daae7531cdb2ed7c2ced9da2c69fd3b080ee7 | 80180aaaed1e1e91a13dbf7df7e0411a9a54c7d3 | 2023-09-18T13:41:28Z | go | 2023-11-20T14:49:50Z | cmd/shim/secret_scrub_test.go | t.Parallel()
secretValue := "my secret value"
env := []string{
fmt.Sprintf("MY_SECRET_ID=%s", secretValue),
"PUBLIC_STUFF=so public",
}
secretToScrub := core.SecretToScrubInfo{
Envs: []string{
"MY_SECRET_ID",
},
}
secrets := loadSecretsToScrubFromEnv(env, secretToScrub.Envs)
require.NotContains(t, secrets, "PUBLIC_STUFF")
require.Contains(t, secrets, secretValue)
}
func TestLoadSecretsToScrubFromFiles(t *testing.T) { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,791 | π secrets scrubbing implementation causes excessive log output latency | ### What is the issue?
# Context
We have a dagger pipeline which, at some point, [mounts secrets](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/actions/environments.py#L1053) to a container which is then runs [integration tests](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/gradle.py#L157) by with_exec'ing a task in gradle.
We are just as bad computer programmers as anyone and sometimes we introduce regressions which cause our integration tests to hang. In our particular case, the bug we introduced was that we tried to connect a jdbc driver to a nonexistent host and we'd hit some absurdly large timeout in our code.
What's unexpected, and why I'm filing an issue right now, is that dagger would be completely silent about the output of this `with_exec` step until it eventually failed.
# The problem
I eventually found that dagger's secrets scrubbing implementation is to blame. In our case, we mount about 20 secrets files, which while a lot, doesn't seem that crazy. I read dagger's code [1] and it appears that if there's a nonzero number of secrets mounted (env vars or files) the output gets piped through `replace.Chain` which chains a bunch of `Transformer` instances from go's transform module [2]. There's one instance per secret and each appears to wrap a reader with a hardcoded buffer of 4kB [3].
In our case, our gradle process was simply not chatty enough to overcome this buffering and so it seemed like it didn't do anything. We're on an old version of dagger but the problem seems still present in the `main` branch from what I can tell.
# My expectations as a user
The need to scrub secrets is not in question. However, `transform` appears to be written in a way that biases throughput over latency, when in our case exactly the opposite is desirable: when scrubbing secrets my expectation is that the output becomes visible to me _as soon as possible_. I don't want to wait for some arbitrary unconfigurable buffer to fill up and I certainly don't want that behaviour to be `O(n)` to the number of secrets mounted.
I say as soon as possible but that's not strictly speaking true, it's not like each rune has to pass through as soon as it's determined that it's not part of a prefix of one of the secrets. This being textual output, I'd be fine if it was each _line_ that gets passed through ASAP. I'm guessing this would also be undoubtedly less complicated to implement on your end and I'm also guessing that most secrets are not multiline (or if they are, it's only a handful of lines).
tl;dr: no need to go crazy here, but I'll be happy with reasonable and predictable behaviour.
# Repro
I didn't look into how dagger is tested but the desired behaviour of the return value of `NewSecretScrubReader` seems adequately unit-testable from my naive standpoint:
1. mock mounting 1, 10 and 100 secrets in each test case;
2. kick off a goroutine with an `io.Reader` which mocks a `with_exec`'ed process' `stdout`;
3. have that `io.Reader` serve a fixed number of bytes and then block on a channel, then serve a bunch more bytes, then block again;
4. concurrently, expect the `io.Reader` returned by `NewSecretScrubReader` to read an expected subset of those bytes, then unblock the channel, then read another expected subset of bytes, then unblock again.
# Notes
Dear dagger maintainers: I hope you're not finding me overprescriptive here or feel that I'm babying you. Far from it! I'm being deliberately wordy because I'm reasonably hopeful that this issue is quite cheap to fix so I'm provide as much info as I can to that aim. On our end, it sure caused a lot of head-scratching.
This is only an issue in an interactive setting: developing locally, or looking at dagger.cloud, which is probably why it went unnoticed (I didn't find any similar issue, though I only did a quick search).
# References
[1] https://github.com/dagger/dagger/blob/v0.6.4/cmd/shim/main.go#L294
[2] https://golang.org/x/text/transform
[3] https://cs.opensource.google/go/x/text/+/refs/tags/v0.13.0:transform/transform.go;l=130
### Log output
_No response_
### Steps to reproduce
_No response_
### SDK version
0.6.4
### OS version
irrelevant, I believe, but macOS and some unremarkable linux distro | https://github.com/dagger/dagger/issues/5791 | https://github.com/dagger/dagger/pull/6034 | b28daae7531cdb2ed7c2ced9da2c69fd3b080ee7 | 80180aaaed1e1e91a13dbf7df7e0411a9a54c7d3 | 2023-09-18T13:41:28Z | go | 2023-11-20T14:49:50Z | cmd/shim/secret_scrub_test.go | t.Parallel()
const currentDirPath = "/mnt"
t.Run("/mnt, fs relative, secret absolute", func(t *testing.T) {
fsys := fstest.MapFS{
"mysecret": &fstest.MapFile{
Data: []byte("my secret file"),
},
"subdir/alsosecret": &fstest.MapFile{
Data: []byte("a subdir secret file"),
},
}
secretFilePathsToScrub := []string{"/mnt/mysecret", "/mnt/subdir/alsosecret"}
secrets, err := loadSecretsToScrubFromFiles(currentDirPath, fsys, secretFilePathsToScrub)
require.NoError(t, err)
require.Contains(t, secrets, "my secret file")
require.Contains(t, secrets, "a subdir secret file")
})
t.Run("/mnt, fs relative, secret relative", func(t *testing.T) {
fsys := fstest.MapFS{ |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,791 | π secrets scrubbing implementation causes excessive log output latency | ### What is the issue?
# Context
We have a dagger pipeline which, at some point, [mounts secrets](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/actions/environments.py#L1053) to a container which is then runs [integration tests](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/gradle.py#L157) by with_exec'ing a task in gradle.
We are just as bad computer programmers as anyone and sometimes we introduce regressions which cause our integration tests to hang. In our particular case, the bug we introduced was that we tried to connect a jdbc driver to a nonexistent host and we'd hit some absurdly large timeout in our code.
What's unexpected, and why I'm filing an issue right now, is that dagger would be completely silent about the output of this `with_exec` step until it eventually failed.
# The problem
I eventually found that dagger's secrets scrubbing implementation is to blame. In our case, we mount about 20 secrets files, which while a lot, doesn't seem that crazy. I read dagger's code [1] and it appears that if there's a nonzero number of secrets mounted (env vars or files) the output gets piped through `replace.Chain` which chains a bunch of `Transformer` instances from go's transform module [2]. There's one instance per secret and each appears to wrap a reader with a hardcoded buffer of 4kB [3].
In our case, our gradle process was simply not chatty enough to overcome this buffering and so it seemed like it didn't do anything. We're on an old version of dagger but the problem seems still present in the `main` branch from what I can tell.
# My expectations as a user
The need to scrub secrets is not in question. However, `transform` appears to be written in a way that biases throughput over latency, when in our case exactly the opposite is desirable: when scrubbing secrets my expectation is that the output becomes visible to me _as soon as possible_. I don't want to wait for some arbitrary unconfigurable buffer to fill up and I certainly don't want that behaviour to be `O(n)` to the number of secrets mounted.
I say as soon as possible but that's not strictly speaking true, it's not like each rune has to pass through as soon as it's determined that it's not part of a prefix of one of the secrets. This being textual output, I'd be fine if it was each _line_ that gets passed through ASAP. I'm guessing this would also be undoubtedly less complicated to implement on your end and I'm also guessing that most secrets are not multiline (or if they are, it's only a handful of lines).
tl;dr: no need to go crazy here, but I'll be happy with reasonable and predictable behaviour.
# Repro
I didn't look into how dagger is tested but the desired behaviour of the return value of `NewSecretScrubReader` seems adequately unit-testable from my naive standpoint:
1. mock mounting 1, 10 and 100 secrets in each test case;
2. kick off a goroutine with an `io.Reader` which mocks a `with_exec`'ed process' `stdout`;
3. have that `io.Reader` serve a fixed number of bytes and then block on a channel, then serve a bunch more bytes, then block again;
4. concurrently, expect the `io.Reader` returned by `NewSecretScrubReader` to read an expected subset of those bytes, then unblock the channel, then read another expected subset of bytes, then unblock again.
# Notes
Dear dagger maintainers: I hope you're not finding me overprescriptive here or feel that I'm babying you. Far from it! I'm being deliberately wordy because I'm reasonably hopeful that this issue is quite cheap to fix so I'm provide as much info as I can to that aim. On our end, it sure caused a lot of head-scratching.
This is only an issue in an interactive setting: developing locally, or looking at dagger.cloud, which is probably why it went unnoticed (I didn't find any similar issue, though I only did a quick search).
# References
[1] https://github.com/dagger/dagger/blob/v0.6.4/cmd/shim/main.go#L294
[2] https://golang.org/x/text/transform
[3] https://cs.opensource.google/go/x/text/+/refs/tags/v0.13.0:transform/transform.go;l=130
### Log output
_No response_
### Steps to reproduce
_No response_
### SDK version
0.6.4
### OS version
irrelevant, I believe, but macOS and some unremarkable linux distro | https://github.com/dagger/dagger/issues/5791 | https://github.com/dagger/dagger/pull/6034 | b28daae7531cdb2ed7c2ced9da2c69fd3b080ee7 | 80180aaaed1e1e91a13dbf7df7e0411a9a54c7d3 | 2023-09-18T13:41:28Z | go | 2023-11-20T14:49:50Z | cmd/shim/secret_scrub_test.go | "mysecret": &fstest.MapFile{
Data: []byte("my secret file"),
},
"subdir/alsosecret": &fstest.MapFile{
Data: []byte("a subdir secret file"),
},
}
secretFilePathsToScrub := []string{"mysecret", "subdir/alsosecret"}
secrets, err := loadSecretsToScrubFromFiles(currentDirPath, fsys, secretFilePathsToScrub)
require.NoError(t, err)
require.Contains(t, secrets, "my secret file")
require.Contains(t, secrets, "a subdir secret file")
})
t.Run("/mnt, fs absolute, secret relative", func(t *testing.T) {
fsys := fstest.MapFS{
"mnt/mysecret": &fstest.MapFile{
Data: []byte("my secret file"),
},
"mnt/subdir/alsosecret": &fstest.MapFile{
Data: []byte("a subdir secret file"),
},
}
secretFilePathsToScrub := []string{"mnt/mysecret", "mnt/subdir/alsosecret"}
secrets, err := loadSecretsToScrubFromFiles(currentDirPath, fsys, secretFilePathsToScrub)
require.NoError(t, err)
require.Contains(t, secrets, "my secret file")
require.Contains(t, secrets, "a subdir secret file")
})
}
func TestScrubSecretWrite(t *testing.T) { |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,791 | π secrets scrubbing implementation causes excessive log output latency | ### What is the issue?
# Context
We have a dagger pipeline which, at some point, [mounts secrets](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/actions/environments.py#L1053) to a container which is then runs [integration tests](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/gradle.py#L157) by with_exec'ing a task in gradle.
We are just as bad computer programmers as anyone and sometimes we introduce regressions which cause our integration tests to hang. In our particular case, the bug we introduced was that we tried to connect a jdbc driver to a nonexistent host and we'd hit some absurdly large timeout in our code.
What's unexpected, and why I'm filing an issue right now, is that dagger would be completely silent about the output of this `with_exec` step until it eventually failed.
# The problem
I eventually found that dagger's secrets scrubbing implementation is to blame. In our case, we mount about 20 secrets files, which while a lot, doesn't seem that crazy. I read dagger's code [1] and it appears that if there's a nonzero number of secrets mounted (env vars or files) the output gets piped through `replace.Chain` which chains a bunch of `Transformer` instances from go's transform module [2]. There's one instance per secret and each appears to wrap a reader with a hardcoded buffer of 4kB [3].
In our case, our gradle process was simply not chatty enough to overcome this buffering and so it seemed like it didn't do anything. We're on an old version of dagger but the problem seems still present in the `main` branch from what I can tell.
# My expectations as a user
The need to scrub secrets is not in question. However, `transform` appears to be written in a way that biases throughput over latency, when in our case exactly the opposite is desirable: when scrubbing secrets my expectation is that the output becomes visible to me _as soon as possible_. I don't want to wait for some arbitrary unconfigurable buffer to fill up and I certainly don't want that behaviour to be `O(n)` to the number of secrets mounted.
I say as soon as possible but that's not strictly speaking true, it's not like each rune has to pass through as soon as it's determined that it's not part of a prefix of one of the secrets. This being textual output, I'd be fine if it was each _line_ that gets passed through ASAP. I'm guessing this would also be undoubtedly less complicated to implement on your end and I'm also guessing that most secrets are not multiline (or if they are, it's only a handful of lines).
tl;dr: no need to go crazy here, but I'll be happy with reasonable and predictable behaviour.
# Repro
I didn't look into how dagger is tested but the desired behaviour of the return value of `NewSecretScrubReader` seems adequately unit-testable from my naive standpoint:
1. mock mounting 1, 10 and 100 secrets in each test case;
2. kick off a goroutine with an `io.Reader` which mocks a `with_exec`'ed process' `stdout`;
3. have that `io.Reader` serve a fixed number of bytes and then block on a channel, then serve a bunch more bytes, then block again;
4. concurrently, expect the `io.Reader` returned by `NewSecretScrubReader` to read an expected subset of those bytes, then unblock the channel, then read another expected subset of bytes, then unblock again.
# Notes
Dear dagger maintainers: I hope you're not finding me overprescriptive here or feel that I'm babying you. Far from it! I'm being deliberately wordy because I'm reasonably hopeful that this issue is quite cheap to fix so I'm provide as much info as I can to that aim. On our end, it sure caused a lot of head-scratching.
This is only an issue in an interactive setting: developing locally, or looking at dagger.cloud, which is probably why it went unnoticed (I didn't find any similar issue, though I only did a quick search).
# References
[1] https://github.com/dagger/dagger/blob/v0.6.4/cmd/shim/main.go#L294
[2] https://golang.org/x/text/transform
[3] https://cs.opensource.google/go/x/text/+/refs/tags/v0.13.0:transform/transform.go;l=130
### Log output
_No response_
### Steps to reproduce
_No response_
### SDK version
0.6.4
### OS version
irrelevant, I believe, but macOS and some unremarkable linux distro | https://github.com/dagger/dagger/issues/5791 | https://github.com/dagger/dagger/pull/6034 | b28daae7531cdb2ed7c2ced9da2c69fd3b080ee7 | 80180aaaed1e1e91a13dbf7df7e0411a9a54c7d3 | 2023-09-18T13:41:28Z | go | 2023-11-20T14:49:50Z | cmd/shim/secret_scrub_test.go | t.Parallel()
envMap := map[string]string{
"secret1": "secret1 value",
"secret2": "secret2",
"sshSecretKey": sshSecretKey,
"sshPublicKey": sshPublicKey,
}
env := []string{}
for k, v := range envMap {
env = append(env, fmt.Sprintf("%s=%s", k, v))
}
envNames := []string{
"secret1",
"secret2",
"sshSecretKey",
"sshPublicKey",
}
secretToScrubInfo := core.SecretToScrubInfo{
Envs: envNames,
Files: []string{}, |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,791 | π secrets scrubbing implementation causes excessive log output latency | ### What is the issue?
# Context
We have a dagger pipeline which, at some point, [mounts secrets](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/actions/environments.py#L1053) to a container which is then runs [integration tests](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/gradle.py#L157) by with_exec'ing a task in gradle.
We are just as bad computer programmers as anyone and sometimes we introduce regressions which cause our integration tests to hang. In our particular case, the bug we introduced was that we tried to connect a jdbc driver to a nonexistent host and we'd hit some absurdly large timeout in our code.
What's unexpected, and why I'm filing an issue right now, is that dagger would be completely silent about the output of this `with_exec` step until it eventually failed.
# The problem
I eventually found that dagger's secrets scrubbing implementation is to blame. In our case, we mount about 20 secrets files, which while a lot, doesn't seem that crazy. I read dagger's code [1] and it appears that if there's a nonzero number of secrets mounted (env vars or files) the output gets piped through `replace.Chain` which chains a bunch of `Transformer` instances from go's transform module [2]. There's one instance per secret and each appears to wrap a reader with a hardcoded buffer of 4kB [3].
In our case, our gradle process was simply not chatty enough to overcome this buffering and so it seemed like it didn't do anything. We're on an old version of dagger but the problem seems still present in the `main` branch from what I can tell.
# My expectations as a user
The need to scrub secrets is not in question. However, `transform` appears to be written in a way that biases throughput over latency, when in our case exactly the opposite is desirable: when scrubbing secrets my expectation is that the output becomes visible to me _as soon as possible_. I don't want to wait for some arbitrary unconfigurable buffer to fill up and I certainly don't want that behaviour to be `O(n)` to the number of secrets mounted.
I say as soon as possible but that's not strictly speaking true, it's not like each rune has to pass through as soon as it's determined that it's not part of a prefix of one of the secrets. This being textual output, I'd be fine if it was each _line_ that gets passed through ASAP. I'm guessing this would also be undoubtedly less complicated to implement on your end and I'm also guessing that most secrets are not multiline (or if they are, it's only a handful of lines).
tl;dr: no need to go crazy here, but I'll be happy with reasonable and predictable behaviour.
# Repro
I didn't look into how dagger is tested but the desired behaviour of the return value of `NewSecretScrubReader` seems adequately unit-testable from my naive standpoint:
1. mock mounting 1, 10 and 100 secrets in each test case;
2. kick off a goroutine with an `io.Reader` which mocks a `with_exec`'ed process' `stdout`;
3. have that `io.Reader` serve a fixed number of bytes and then block on a channel, then serve a bunch more bytes, then block again;
4. concurrently, expect the `io.Reader` returned by `NewSecretScrubReader` to read an expected subset of those bytes, then unblock the channel, then read another expected subset of bytes, then unblock again.
# Notes
Dear dagger maintainers: I hope you're not finding me overprescriptive here or feel that I'm babying you. Far from it! I'm being deliberately wordy because I'm reasonably hopeful that this issue is quite cheap to fix so I'm provide as much info as I can to that aim. On our end, it sure caused a lot of head-scratching.
This is only an issue in an interactive setting: developing locally, or looking at dagger.cloud, which is probably why it went unnoticed (I didn't find any similar issue, though I only did a quick search).
# References
[1] https://github.com/dagger/dagger/blob/v0.6.4/cmd/shim/main.go#L294
[2] https://golang.org/x/text/transform
[3] https://cs.opensource.google/go/x/text/+/refs/tags/v0.13.0:transform/transform.go;l=130
### Log output
_No response_
### Steps to reproduce
_No response_
### SDK version
0.6.4
### OS version
irrelevant, I believe, but macOS and some unremarkable linux distro | https://github.com/dagger/dagger/issues/5791 | https://github.com/dagger/dagger/pull/6034 | b28daae7531cdb2ed7c2ced9da2c69fd3b080ee7 | 80180aaaed1e1e91a13dbf7df7e0411a9a54c7d3 | 2023-09-18T13:41:28Z | go | 2023-11-20T14:49:50Z | cmd/shim/secret_scrub_test.go | }
t.Run("multiline secret", func(t *testing.T) {
for input, expectedOutput := range map[string]string{
"aaa\n" + sshSecretKey + "\nbbb\nccc": "aaa\n***\nbbb\nccc",
"aaa" + sshSecretKey + "bbb\nccc": "aaa***bbb\nccc",
sshSecretKey: "***",
} {
var buf bytes.Buffer
r, err := NewSecretScrubReader(&buf, "/", fstest.MapFS{}, env, secretToScrubInfo)
require.NoError(t, err)
_, err = buf.WriteString(input)
require.NoError(t, err)
out, err := io.ReadAll(r)
require.NoError(t, err)
require.Equal(t, expectedOutput, string(out))
}
})
t.Run("single line secret", func(t *testing.T) {
var buf bytes.Buffer
r, err := NewSecretScrubReader(&buf, "/", fstest.MapFS{}, env, secretToScrubInfo)
require.NoError(t, err)
input := "aaa\nsecret1 value\nno secret\n"
_, err = buf.WriteString(input)
require.NoError(t, err)
out, err := io.ReadAll(r)
require.NoError(t, err)
require.Equal(t, "aaa\n***\nno secret\n", string(out))
})
t.Run("multi write", func(t *testing.T) {
var buf bytes.Buffer |
closed | dagger/dagger | https://github.com/dagger/dagger | 5,791 | π secrets scrubbing implementation causes excessive log output latency | ### What is the issue?
# Context
We have a dagger pipeline which, at some point, [mounts secrets](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/actions/environments.py#L1053) to a container which is then runs [integration tests](https://github.com/airbytehq/airbyte/blob/327d3c9ae8e14b28bf2bdf7528b22f86f510d629/airbyte-ci/connectors/pipelines/pipelines/gradle.py#L157) by with_exec'ing a task in gradle.
We are just as bad computer programmers as anyone and sometimes we introduce regressions which cause our integration tests to hang. In our particular case, the bug we introduced was that we tried to connect a jdbc driver to a nonexistent host and we'd hit some absurdly large timeout in our code.
What's unexpected, and why I'm filing an issue right now, is that dagger would be completely silent about the output of this `with_exec` step until it eventually failed.
# The problem
I eventually found that dagger's secrets scrubbing implementation is to blame. In our case, we mount about 20 secrets files, which while a lot, doesn't seem that crazy. I read dagger's code [1] and it appears that if there's a nonzero number of secrets mounted (env vars or files) the output gets piped through `replace.Chain` which chains a bunch of `Transformer` instances from go's transform module [2]. There's one instance per secret and each appears to wrap a reader with a hardcoded buffer of 4kB [3].
In our case, our gradle process was simply not chatty enough to overcome this buffering and so it seemed like it didn't do anything. We're on an old version of dagger but the problem seems still present in the `main` branch from what I can tell.
# My expectations as a user
The need to scrub secrets is not in question. However, `transform` appears to be written in a way that biases throughput over latency, when in our case exactly the opposite is desirable: when scrubbing secrets my expectation is that the output becomes visible to me _as soon as possible_. I don't want to wait for some arbitrary unconfigurable buffer to fill up and I certainly don't want that behaviour to be `O(n)` to the number of secrets mounted.
I say as soon as possible but that's not strictly speaking true, it's not like each rune has to pass through as soon as it's determined that it's not part of a prefix of one of the secrets. This being textual output, I'd be fine if it was each _line_ that gets passed through ASAP. I'm guessing this would also be undoubtedly less complicated to implement on your end and I'm also guessing that most secrets are not multiline (or if they are, it's only a handful of lines).
tl;dr: no need to go crazy here, but I'll be happy with reasonable and predictable behaviour.
# Repro
I didn't look into how dagger is tested but the desired behaviour of the return value of `NewSecretScrubReader` seems adequately unit-testable from my naive standpoint:
1. mock mounting 1, 10 and 100 secrets in each test case;
2. kick off a goroutine with an `io.Reader` which mocks a `with_exec`'ed process' `stdout`;
3. have that `io.Reader` serve a fixed number of bytes and then block on a channel, then serve a bunch more bytes, then block again;
4. concurrently, expect the `io.Reader` returned by `NewSecretScrubReader` to read an expected subset of those bytes, then unblock the channel, then read another expected subset of bytes, then unblock again.
# Notes
Dear dagger maintainers: I hope you're not finding me overprescriptive here or feel that I'm babying you. Far from it! I'm being deliberately wordy because I'm reasonably hopeful that this issue is quite cheap to fix so I'm provide as much info as I can to that aim. On our end, it sure caused a lot of head-scratching.
This is only an issue in an interactive setting: developing locally, or looking at dagger.cloud, which is probably why it went unnoticed (I didn't find any similar issue, though I only did a quick search).
# References
[1] https://github.com/dagger/dagger/blob/v0.6.4/cmd/shim/main.go#L294
[2] https://golang.org/x/text/transform
[3] https://cs.opensource.google/go/x/text/+/refs/tags/v0.13.0:transform/transform.go;l=130
### Log output
_No response_
### Steps to reproduce
_No response_
### SDK version
0.6.4
### OS version
irrelevant, I believe, but macOS and some unremarkable linux distro | https://github.com/dagger/dagger/issues/5791 | https://github.com/dagger/dagger/pull/6034 | b28daae7531cdb2ed7c2ced9da2c69fd3b080ee7 | 80180aaaed1e1e91a13dbf7df7e0411a9a54c7d3 | 2023-09-18T13:41:28Z | go | 2023-11-20T14:49:50Z | cmd/shim/secret_scrub_test.go | r, err := NewSecretScrubReader(&buf, "/", fstest.MapFS{}, env, secretToScrubInfo)
require.NoError(t, err)
inputLines := []string{
"secret1 value",
"secret2",
"nonsecret",
}
outputLines := []string{
"***",
"***",
"nonsecret",
}
for _, s := range inputLines {
buf.WriteString(s)
buf.WriteRune('\n')
}
scanner := bufio.NewScanner(r)
var i int
for scanner.Scan() {
out := scanner.Text()
expected := outputLines[i]
require.Equal(t, expected, out)
i++
}
require.Equal(t, len(outputLines), i)
})
} |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | package templates
import (
"encoding/json"
"fmt"
"go/ast"
"go/token"
"go/types"
"os"
"path/filepath"
"reflect"
"runtime/debug"
"sort"
"strings"
. "github.com/dave/jennifer/jen"
"github.com/iancoleman/strcase"
"golang.org/x/tools/go/packages"
)
const (
daggerGenFilename = "dagger.gen.go"
contextTypename = "context.Context"
constructorFuncName = "New"
)
/* |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | moduleMainSrc generates the source code of the main func for Dagger Module code using the Go SDK.
The overall idea is that users just need to create a struct with the same name as their Module and then
add methods to that struct to implement their Module. Methods on that struct become Functions.
They are also free to return custom objects from Functions, which themselves may have methods that become
Functions too. However, only the "top-level" Module struct's Functions will be directly invokable.
This is essentially just the GraphQL execution model.
The implementation works by parsing the user's code and generating a main func that reads function call inputs
from the Engine, calls the relevant function and returns the result. The generated code is mostly a giant switch/case
on the object+function name, with each case doing json deserialization of the input arguments and calling the actual
Go function.
*/
func (funcs goTemplateFuncs) moduleMainSrc() (string, error) {
defer func() {
if r := recover(); r != nil {
fmt.Fprintf(os.Stderr, "internal error during module code generation: %v\n", r)
debug.PrintStack()
panic(r)
}
}()
if funcs.modulePkg == nil {
return `func main() { panic("no code yet") }`, nil
}
ps := &parseState{
pkg: funcs.modulePkg,
fset: funcs.moduleFset, |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | methods: make(map[string][]method),
moduleName: funcs.module.Name,
}
pkgScope := funcs.modulePkg.Types.Scope()
objFunctionCases := map[string][]Code{}
createMod := Qual("dag", "CurrentModule").Call()
objs := []types.Object{}
for _, name := range pkgScope.Names() {
obj := pkgScope.Lookup(name)
if obj == nil {
continue
}
objs = append(objs, obj)
}
sort.Slice(objs, func(i, j int) bool {
return objs[i].Pos() < objs[j].Pos()
})
tps := []types.Type{}
for _, obj := range objs {
fn, isFn := obj.(*types.Func)
if isFn && fn.Name() == constructorFuncName {
ps.constructor = fn
continue
}
tps = append(tps, obj.Type())
}
added := map[string]struct{}{} |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | topLevel := true
for len(tps) != 0 {
var nextTps []types.Type
for _, tp := range tps {
named, isNamed := tp.(*types.Named)
if !isNamed {
continue
}
obj := named.Obj()
if obj.Pkg() != funcs.modulePkg.Types {
continue
}
if !obj.Exported() {
if !topLevel {
return "", fmt.Errorf("cannot code-generate unexported type %s", obj.Name())
}
continue
}
strct, isStruct := named.Underlying().(*types.Struct)
if !isStruct {
continue
} |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | if _, ok := added[obj.Name()]; ok {
continue
}
objType, extraTypes, err := ps.goStructToAPIType(strct, named)
if err != nil {
return "", err
}
if objType == nil {
continue
}
if err := ps.fillObjectFunctionCases(named, objFunctionCases); err != nil {
return "", fmt.Errorf("failed to generate function cases for %s: %w", obj.Name(), err)
}
if len(objFunctionCases[obj.Name()]) == 0 && !ps.isMainModuleObject(obj.Name()) {
if topLevel {
continue
}
if ps.isDaggerGenerated(named.Obj()) {
continue
}
}
createMod = dotLine(createMod, "WithObject").Call(Add(Line(), objType))
added[obj.Name()] = struct{}{} |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | nextTps = append(nextTps, extraTypes...)
}
tps, nextTps = nextTps, nil
topLevel = false
}
return strings.Join([]string{mainSrc, invokeSrc(objFunctionCases, createMod)}, "\n"), nil
}
func dotLine(a *Statement, id string) *Statement { |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | return a.Op(".").Line().Id(id)
}
const (
mainSrc = `func main() {
ctx := context.Background()
fnCall := dag.CurrentFunctionCall()
parentName, err := fnCall.ParentName(ctx)
if err != nil {
fmt.Println(err.Error())
os.Exit(2)
}
fnName, err := fnCall.Name(ctx)
if err != nil {
fmt.Println(err.Error())
os.Exit(2)
}
parentJson, err := fnCall.Parent(ctx)
if err != nil {
fmt.Println(err.Error())
os.Exit(2)
} |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | fnArgs, err := fnCall.InputArgs(ctx)
if err != nil {
fmt.Println(err.Error())
os.Exit(2)
}
inputArgs := map[string][]byte{}
for _, fnArg := range fnArgs {
argName, err := fnArg.Name(ctx)
if err != nil {
fmt.Println(err.Error())
os.Exit(2)
}
argValue, err := fnArg.Value(ctx)
if err != nil {
fmt.Println(err.Error())
os.Exit(2)
}
inputArgs[argName] = []byte(argValue)
}
result, err := invoke(ctx, []byte(parentJson), parentName, fnName, inputArgs)
if err != nil {
fmt.Println(err.Error())
os.Exit(2)
}
resultBytes, err := json.Marshal(result)
if err != nil {
fmt.Println(err.Error())
os.Exit(2)
}
_, err = fnCall.ReturnValue(ctx, JSON(resultBytes)) |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | if err != nil {
fmt.Println(err.Error())
os.Exit(2)
}
}
`
parentJSONVar = "parentJSON"
parentNameVar = "parentName"
fnNameVar = "fnName"
inputArgsVar = "inputArgs"
invokeFuncName = "invoke"
)
func invokeSrc(objFunctionCases map[string][]Code, createMod Code) string {
objCases := []Code{}
for objName, functionCases := range objFunctionCases {
objCases = append(objCases, Case(Lit(objName)).Block(Switch(Id(fnNameVar)).Block(functionCases...)))
}
objCases = append(objCases, Case(Lit("")).Block(
Return(createMod, Nil()),
))
objCases = append(objCases, Default().Block(
Return(Nil(), Qual("fmt", "Errorf").Call(Lit("unknown object %s"), Id(parentNameVar))),
))
objSwitch := Switch(Id(parentNameVar)).Block(objCases...)
invokeFunc := Func().Id(invokeFuncName).Params( |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | Id("ctx").Qual("context", "Context"),
Id(parentJSONVar).Index().Byte(),
Id(parentNameVar).String(),
Id(fnNameVar).String(),
Id(inputArgsVar).Map(String()).Index().Byte(),
).Params(
Id("_").Id("any"),
Id("err").Error(),
).Block(objSwitch)
return fmt.Sprintf("%#v", invokeFunc)
}
func renderNameOrStruct(t types.Type) string {
if ptr, ok := t.(*types.Pointer); ok {
return "*" + renderNameOrStruct(ptr.Elem())
}
if sl, ok := t.(*types.Slice); ok {
return "[]" + renderNameOrStruct(sl.Elem())
}
if st, ok := t.(*types.Struct); ok {
result := "struct {\n"
for i := 0; i < st.NumFields(); i++ {
if !st.Field(i).Embedded() {
result += st.Field(i).Name() + " "
} |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | result += renderNameOrStruct(st.Field(i).Type())
if tag := st.Tag(i); tag != "" {
result += " `" + tag + "`"
}
result += "\n"
}
result += "}"
return result
}
if named, ok := t.(*types.Named); ok {
base := named.Obj().Name()
if typeArgs := named.TypeArgs(); typeArgs.Len() > 0 {
base += "["
for i := 0; i < typeArgs.Len(); i++ {
if i > 0 {
base += ", "
}
base += renderNameOrStruct(typeArgs.At(i))
}
base += "]"
}
return base
} |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | return t.String()
}
var checkErrStatement = If(Err().Op("!=").Nil()).Block(
Qual("fmt", "Println").Call(Err().Dot("Error").Call()),
Qual("os", "Exit").Call(Lit(2)),
)
func (ps *parseState) fillObjectFunctionCases(type_ types.Type, cases map[string][]Code) error {
var objName string
switch x := type_.(type) {
case *types.Pointer:
return ps.fillObjectFunctionCases(x.Elem(), cases)
case *types.Named:
objName = x.Obj().Name()
default:
return nil
}
if existingCases := cases[objName]; len(existingCases) > 0 {
return nil
}
hasConstructor := ps.isMainModuleObject(objName) && ps.constructor != nil
methods := ps.methods[objName]
if len(methods) == 0 && !hasConstructor {
return nil
}
for _, method := range methods {
fnName, sig := method.fn.Name(), method.fn.Type().(*types.Signature) |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | if err := ps.fillObjectFunctionCase(objName, fnName, fnName, sig, method.paramSpecs, cases); err != nil {
return err
}
}
if hasConstructor {
sig, ok := ps.constructor.Type().(*types.Signature)
if !ok {
return fmt.Errorf("expected %s to be a function, got %T", constructorFuncName, ps.constructor.Type())
}
paramSpecs, err := ps.parseParamSpecs(ps.constructor)
if err != nil {
return fmt.Errorf("failed to parse %s function: %w", constructorFuncName, err)
}
results := sig.Results()
if results.Len() == 0 {
return fmt.Errorf("%s must return a value", constructorFuncName)
}
resultType := results.At(0).Type()
if ptrType, ok := resultType.(*types.Pointer); ok {
resultType = ptrType.Elem()
}
namedType, ok := resultType.(*types.Named)
if !ok {
return fmt.Errorf("%s must return the main module object %q", constructorFuncName, objName)
}
if namedType.Obj().Name() != objName {
return fmt.Errorf("%s must return the main module object %q", constructorFuncName, objName)
} |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | if err := ps.fillObjectFunctionCase(objName, ps.constructor.Name(), "", sig, paramSpecs, cases); err != nil {
return err
}
}
cases[objName] = append(cases[objName], Default().Block(
Return(Nil(), Qual("fmt", "Errorf").Call(Lit("unknown function %s"), Id(fnNameVar))),
))
return nil
}
func (ps *parseState) fillObjectFunctionCase(
objName string,
fnName string,
caseName string,
sig *types.Signature,
paramSpecs []paramSpec,
cases map[string][]Code,
) error {
statements := []Code{}
parentVarName := "parent"
statements = append(statements,
Var().Id(parentVarName).Id(objName),
Err().Op("=").Qual("json", "Unmarshal").Call(Id(parentJSONVar), Op("&").Id(parentVarName)),
checkErrStatement,
)
var fnCallArgs []Code
if sig.Recv() != nil {
fnCallArgs = []Code{Op("&").Id(parentVarName)}
}
vars := map[string]struct{}{} |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | for i, spec := range paramSpecs {
if i == 0 && spec.paramType.String() == contextTypename {
fnCallArgs = append(fnCallArgs, Id("ctx"))
continue
}
var varName string
var varType types.Type
var target *Statement
if spec.parent == nil {
varName = strcase.ToLowerCamel(spec.name)
varType = spec.paramType
target = Id(varName)
} else {
varName = spec.parent.name
varType = spec.parent.paramType
target = Id(spec.parent.name).Dot(spec.name)
}
if _, ok := vars[varName]; !ok {
vars[varName] = struct{}{} |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | tp, access := findOptsAccessPattern(varType, Id(varName))
statements = append(statements, Var().Id(varName).Id(renderNameOrStruct(tp)))
if spec.variadic {
fnCallArgs = append(fnCallArgs, access.Op("..."))
} else {
fnCallArgs = append(fnCallArgs, access)
}
}
statements = append(statements,
If(Id(inputArgsVar).Index(Lit(spec.graphqlName())).Op("!=").Nil()).Block(
Err().Op("=").Qual("json", "Unmarshal").Call(
Index().Byte().Parens(Id(inputArgsVar).Index(Lit(spec.graphqlName()))),
Op("&").Add(target),
),
checkErrStatement,
))
} |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | results := sig.Results()
var callStatement *Statement
if sig.Recv() != nil {
callStatement = Parens(Op("*").Id(objName)).Dot(fnName).Call(fnCallArgs...)
} else {
callStatement = Id(fnName).Call(fnCallArgs...)
}
switch results.Len() {
case 2:
if results.At(1).Type().String() != errorTypeName {
return fmt.Errorf("second return value must be error, have %s", results.At(1).Type().String())
}
statements = append(statements, Return(callStatement))
cases[objName] = append(cases[objName], Case(Lit(caseName)).Block(statements...))
if err := ps.fillObjectFunctionCases(results.At(0).Type(), cases); err != nil {
return err
}
return nil
case 1:
if results.At(0).Type().String() == errorTypeName {
statements = append(statements, Return(Nil(), callStatement))
cases[objName] = append(cases[objName], Case(Lit(caseName)).Block(statements...))
} else {
statements = append(statements, Return(callStatement, Nil()))
cases[objName] = append(cases[objName], Case(Lit(caseName)).Block(statements...))
if err := ps.fillObjectFunctionCases(results.At(0).Type(), cases); err != nil { |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | return err
}
}
return nil
case 0:
statements = append(statements,
callStatement,
Return(Nil(), Nil()))
cases[objName] = append(cases[objName], Case(Lit(caseName)).Block(statements...))
return nil
default:
return fmt.Errorf("unexpected number of results from function %s: %d", fnName, results.Len())
}
}
type parseState struct {
pkg *packages.Package
fset *token.FileSet
methods map[string][]method
moduleName string
constructor *types.Func
}
func (ps *parseState) isMainModuleObject(name string) bool {
return strcase.ToCamel(ps.moduleName) == strcase.ToCamel(name)
}
type method struct { |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | fn *types.Func
paramSpecs []paramSpec
}
func (ps *parseState) goTypeToAPIType(typ types.Type, named *types.Named) (*Statement, *types.Named, error) {
switch t := typ.(type) {
case *types.Named:
typeDef, _, err := ps.goTypeToAPIType(t.Underlying(), t)
if err != nil {
return nil, nil, fmt.Errorf("failed to convert named type: %w", err)
}
return typeDef, t, nil
case *types.Pointer:
return ps.goTypeToAPIType(t.Elem(), named)
case *types.Slice:
elemTypeDef, underlying, err := ps.goTypeToAPIType(t.Elem(), nil)
if err != nil {
return nil, nil, fmt.Errorf("failed to convert slice element type: %w", err)
}
return Qual("dag", "TypeDef").Call().Dot("WithListOf").Call(
elemTypeDef,
), underlying, nil
case *types.Basic: |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | if t.Kind() == types.Invalid {
return nil, nil, fmt.Errorf("invalid type: %+v", t)
}
var kind Code
switch t.Info() {
case types.IsString:
kind = Id("Stringkind")
case types.IsInteger:
kind = Id("Integerkind")
case types.IsBoolean:
kind = Id("Booleankind")
default:
return nil, nil, fmt.Errorf("unsupported basic type: %+v", t)
}
return Qual("dag", "TypeDef").Call().Dot("WithKind").Call(
kind,
), named, nil
case *types.Struct:
if named == nil {
return nil, nil, fmt.Errorf("struct types must be named")
}
typeName := named.Obj().Name()
if typeName == "" {
return nil, nil, fmt.Errorf("struct types must be named")
}
return Qual("dag", "TypeDef").Call().Dot("WithObject").Call(
Lit(typeName),
), named, nil
default:
return nil, nil, fmt.Errorf("unsupported type %T", t) |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | }
}
const errorTypeName = "error"
func (ps *parseState) goStructToAPIType(t *types.Struct, named *types.Named) (*Statement, []types.Type, error) {
if named == nil {
return nil, nil, fmt.Errorf("struct types must be named")
}
typeName := named.Obj().Name()
if typeName == "" {
return nil, nil, fmt.Errorf("struct types must be named")
}
objectIsDaggerGenerated := ps.isDaggerGenerated(named.Obj())
methods := []*types.Func{}
methodSet := types.NewMethodSet(types.NewPointer(named))
for i := 0; i < methodSet.Len(); i++ {
methodObj := methodSet.At(i).Obj()
if ps.isDaggerGenerated(methodObj) {
continue
}
if objectIsDaggerGenerated {
return nil, nil, fmt.Errorf("cannot define methods on objects from outside this module")
}
method, ok := methodObj.(*types.Func)
if !ok { |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | return nil, nil, fmt.Errorf("expected method to be a func, got %T", methodObj)
}
if !method.Exported() {
continue
}
methods = append(methods, method)
}
if objectIsDaggerGenerated {
return nil, nil, nil
}
sort.Slice(methods, func(i, j int) bool {
return methods[i].Pos() < methods[j].Pos()
})
withObjectArgs := []Code{
Lit(typeName),
}
withObjectOpts := []Code{}
typeSpec, err := ps.typeSpecForNamedType(named)
if err != nil {
return nil, nil, fmt.Errorf("failed to find decl for named type %s: %w", typeName, err)
}
if comment := typeSpec.Doc.Text(); comment != "" {
withObjectOpts = append(withObjectOpts, Id("Description").Op(":").Lit(strings.TrimSpace(comment)))
}
if len(withObjectOpts) > 0 {
withObjectArgs = append(withObjectArgs, Id("TypeDefWithObjectOpts").Values(withObjectOpts...))
}
typeDef := Qual("dag", "TypeDef").Call().Dot("WithObject").Call(withObjectArgs...) |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | var subTypes []types.Type
for _, method := range methods {
fnTypeDef, functionSubTypes, err := ps.goFuncToAPIFunctionDef(typeName, method)
if err != nil {
return nil, nil, fmt.Errorf("failed to convert method %s to function def: %w", method.Name(), err)
}
subTypes = append(subTypes, functionSubTypes...)
typeDef = dotLine(typeDef, "WithFunction").Call(Add(Line(), fnTypeDef))
}
astStructType, ok := typeSpec.Type.(*ast.StructType)
if !ok {
return nil, nil, fmt.Errorf("expected type spec to be a struct, got %T", typeSpec.Type)
}
astFields := unpackASTFields(astStructType.Fields)
for i := 0; i < t.NumFields(); i++ {
field := t.Field(i)
if !field.Exported() {
continue
}
fieldTypeDef, subType, err := ps.goTypeToAPIType(field.Type(), nil)
if err != nil {
return nil, nil, fmt.Errorf("failed to convert field type: %w", err)
}
if subType != nil {
subTypes = append(subTypes, subType)
}
description := astFields[i].Doc.Text()
if description == "" {
description = astFields[i].Comment.Text() |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | }
description = strings.TrimSpace(description)
name := field.Name()
tag := reflect.StructTag(t.Tag(i))
if dt := tag.Get("json"); dt != "" {
dt, _, _ = strings.Cut(dt, ",")
if dt == "-" {
continue
}
name = dt
}
withFieldArgs := []Code{
Lit(name),
fieldTypeDef,
}
if description != "" {
withFieldArgs = append(withFieldArgs,
Id("TypeDefWithFieldOpts").Values(
Id("Description").Op(":").Lit(description),
))
}
typeDef = dotLine(typeDef, "WithField").Call(withFieldArgs...)
}
if ps.isMainModuleObject(typeName) && ps.constructor != nil {
fnTypeDef, _, err := ps.goFuncToAPIFunctionDef("", ps.constructor)
if err != nil {
return nil, nil, fmt.Errorf("failed to convert constructor to function def: %w", err)
} |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | typeDef = dotLine(typeDef, "WithConstructor").Call(Add(Line(), fnTypeDef))
}
return typeDef, subTypes, nil
}
var voidDef = Qual("dag", "TypeDef").Call().
Dot("WithKind").Call(Id("Voidkind")).
Dot("WithOptional").Call(Lit(true))
func (ps *parseState) goFuncToAPIFunctionDef(receiverTypeName string, fn *types.Func) (*Statement, []types.Type, error) {
sig, ok := fn.Type().(*types.Signature)
if !ok {
return nil, nil, fmt.Errorf("expected method to be a func, got %T", fn.Type())
}
specs, err := ps.parseParamSpecs(fn)
if err != nil {
return nil, nil, err
}
if receiverTypeName != "" {
ps.methods[receiverTypeName] = append(ps.methods[receiverTypeName], method{fn: fn, paramSpecs: specs})
}
var fnReturnType *Statement
var subTypes []types.Type
results := sig.Results()
var returnSubType *types.Named
switch results.Len() {
case 0:
fnReturnType = voidDef
case 1:
result := results.At(0).Type() |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | if result.String() == errorTypeName {
fnReturnType = voidDef
} else {
fnReturnType, returnSubType, err = ps.goTypeToAPIType(result, nil)
if err != nil {
return nil, nil, fmt.Errorf("failed to convert result type: %w", err)
}
}
case 2:
result := results.At(0).Type()
subTypes = append(subTypes, result)
fnReturnType, returnSubType, err = ps.goTypeToAPIType(result, nil)
if err != nil {
return nil, nil, fmt.Errorf("failed to convert result type: %w", err)
}
default:
return nil, nil, fmt.Errorf("method %s has too many return values", fn.Name())
}
if returnSubType != nil {
subTypes = append(subTypes, returnSubType)
}
fnDef := Qual("dag", "Function").Call(Lit(fn.Name()), Add(Line(), fnReturnType))
funcDecl, err := ps.declForFunc(fn)
if err != nil {
return nil, nil, fmt.Errorf("failed to find decl for method %s: %w", fn.Name(), err)
}
if comment := funcDecl.Doc.Text(); comment != "" {
fnDef = dotLine(fnDef, "WithDescription").Call(Lit(strings.TrimSpace(comment)))
}
for i, spec := range specs { |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | if i == 0 && spec.paramType.String() == contextTypename {
continue
}
typeDef, subType, err := ps.goTypeToAPIType(spec.baseType, nil)
if err != nil {
return nil, nil, fmt.Errorf("failed to convert param type: %w", err)
}
if subType != nil {
subTypes = append(subTypes, subType)
}
if spec.optional {
typeDef = typeDef.Dot("WithOptional").Call(Lit(true))
}
args := []Code{Lit(spec.graphqlName()), typeDef}
argOpts := []Code{}
if spec.description != "" {
argOpts = append(argOpts, Id("Description").Op(":").Lit(spec.description))
}
if spec.defaultValue != "" {
var jsonEnc string
if spec.baseType.String() == "string" {
enc, err := json.Marshal(spec.defaultValue)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal default value: %w", err)
}
jsonEnc = string(enc)
} else {
jsonEnc = spec.defaultValue |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | }
argOpts = append(argOpts, Id("DefaultValue").Op(":").Id("JSON").Call(Lit(jsonEnc)))
}
if len(argOpts) > 0 {
args = append(args, Id("FunctionWithArgOpts").Values(argOpts...))
}
fnDef = dotLine(fnDef, "WithArg").Call(args...)
}
return fnDef, subTypes, nil
}
func (ps *parseState) parseParamSpecs(fn *types.Func) ([]paramSpec, error) {
sig := fn.Type().(*types.Signature)
params := sig.Params()
if params.Len() == 0 {
return nil, nil
}
specs := make([]paramSpec, 0, params.Len())
i := 0
if params.At(i).Type().String() == contextTypename {
spec, err := ps.parseParamSpecVar(params.At(i))
if err != nil {
return nil, err
}
specs = append(specs, spec)
i++
}
fnDecl, err := ps.declForFunc(fn)
if err != nil {
return nil, err
} |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | if i+1 == params.Len() {
param := params.At(i)
paramType, ok := asInlineStruct(param.Type())
if ok {
stype, ok := asInlineStructAst(fnDecl.Type.Params.List[i].Type)
if !ok {
return nil, fmt.Errorf("expected struct type for %s", param.Name())
}
parent := ¶mSpec{
name: params.At(i).Name(),
paramType: param.Type(),
baseType: param.Type(),
}
paramFields := unpackASTFields(stype.Fields)
for f := 0; f < paramType.NumFields(); f++ {
spec, err := ps.parseParamSpecVar(paramType.Field(f))
if err != nil {
return nil, err
}
spec.parent = parent
spec.description = paramFields[f].Doc.Text()
if spec.description == "" {
spec.description = paramFields[f].Comment.Text()
}
spec.description = strings.TrimSpace(spec.description)
specs = append(specs, spec)
}
return specs, nil |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | }
}
paramFields := unpackASTFields(fnDecl.Type.Params)
for ; i < params.Len(); i++ {
spec, err := ps.parseParamSpecVar(params.At(i))
if err != nil {
return nil, err
}
if sig.Variadic() && i == params.Len()-1 {
spec.variadic = true
}
if cmt, err := ps.commentForFuncField(fnDecl, paramFields, i); err == nil {
spec.description = cmt.Text()
spec.description = strings.TrimSpace(spec.description)
}
specs = append(specs, spec)
}
return specs, nil
}
func (ps *parseState) parseParamSpecVar(field *types.Var) (paramSpec, error) {
if _, ok := field.Type().(*types.Struct); ok {
return paramSpec{}, fmt.Errorf("nested structs are not supported")
}
paramType := field.Type()
baseType := paramType
for {
ptr, ok := baseType.(*types.Pointer)
if !ok { |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | break
}
baseType = ptr.Elem()
}
optional := false
if named, ok := baseType.(*types.Named); ok {
if named.Obj().Name() == "Optional" && ps.isDaggerGenerated(named.Obj()) {
typeArgs := named.TypeArgs()
if typeArgs.Len() != 1 {
return paramSpec{}, fmt.Errorf("optional type must have exactly one type argument")
}
optional = true
baseType = typeArgs.At(0)
for {
ptr, ok := baseType.(*types.Pointer)
if !ok {
break
}
baseType = ptr.Elem()
}
}
}
return paramSpec{
name: field.Name(),
paramType: paramType,
baseType: baseType,
optional: optional,
}, nil
}
type paramSpec struct { |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | name string
description string
optional bool
variadic bool
defaultValue string
paramType types.Type
baseType types.Type
parent *paramSpec
}
func (spec *paramSpec) graphqlName() string {
return strcase.ToLowerCamel(spec.name) |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | }
func (ps *parseState) typeSpecForNamedType(namedType *types.Named) (*ast.TypeSpec, error) {
tokenFile := ps.fset.File(namedType.Obj().Pos())
if tokenFile == nil {
return nil, fmt.Errorf("no file for %s", namedType.Obj().Name())
}
for _, f := range ps.pkg.Syntax {
if ps.fset.File(f.Pos()) != tokenFile {
continue
}
for _, decl := range f.Decls {
genDecl, ok := decl.(*ast.GenDecl)
if !ok {
continue
}
for _, spec := range genDecl.Specs {
typeSpec, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
if typeSpec.Name.Name == namedType.Obj().Name() {
if typeSpec.Doc == nil {
typeSpec.Doc = genDecl.Doc
}
return typeSpec, nil
}
}
}
}
return nil, fmt.Errorf("no decl for %s", namedType.Obj().Name()) |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | }
func (ps *parseState) declForFunc(fnType *types.Func) (*ast.FuncDecl, error) {
tokenFile := ps.fset.File(fnType.Pos())
if tokenFile == nil {
return nil, fmt.Errorf("no file for %s", fnType.Name())
}
for _, f := range ps.pkg.Syntax {
if ps.fset.File(f.Pos()) != tokenFile {
continue
}
for _, decl := range f.Decls {
fnDecl, ok := decl.(*ast.FuncDecl)
if ok && fnDecl.Name.Name == fnType.Name() {
return fnDecl, nil
}
}
}
return nil, fmt.Errorf("no decl for %s", fnType.Name())
}
func (ps *parseState) commentForFuncField(fnDecl *ast.FuncDecl, unpackedParams []*ast.Field, i int) (*ast.CommentGroup, error) {
pos := unpackedParams[i].Pos()
tokenFile := ps.fset.File(pos)
if tokenFile == nil {
return nil, fmt.Errorf("no file for function %s", fnDecl.Name.Name)
}
line := tokenFile.Line(pos)
allowDocComment := true
allowLineComment := true
if i == 0 {
fieldStartLine := tokenFile.Line(fnDecl.Type.Params.Pos()) |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | if fieldStartLine == line || fieldStartLine == line-1 {
allowDocComment = false
}
} else {
prevArgLine := tokenFile.Line(unpackedParams[i-1].Pos())
if prevArgLine == line || prevArgLine == line-1 {
allowDocComment = false
}
}
if i+1 < len(fnDecl.Type.Params.List) {
nextArgLine := tokenFile.Line(unpackedParams[i+1].Pos())
if nextArgLine == line {
allowLineComment = false
}
} else {
fieldEndLine := tokenFile.Line(fnDecl.Type.Params.End())
if fieldEndLine == line {
allowLineComment = false
}
}
for _, f := range ps.pkg.Syntax {
if ps.fset.File(f.Pos()) != tokenFile { |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | continue
}
if allowDocComment {
npos := tokenFile.LineStart(tokenFile.Line(pos)) - 1
for _, comment := range f.Comments {
if comment.Pos() <= npos && npos <= comment.End() {
return comment, nil
}
}
}
if allowLineComment {
npos := tokenFile.LineStart(tokenFile.Line(pos)+1) - 1
for _, comment := range f.Comments {
if comment.Pos() <= npos && npos <= comment.End() {
return comment, nil
}
}
}
}
return nil, fmt.Errorf("no comment for function %s", fnDecl.Name.Name)
}
func (ps *parseState) isDaggerGenerated(obj types.Object) bool {
tokenFile := ps.fset.File(obj.Pos())
return filepath.Base(tokenFile.Name()) == daggerGenFilename
}
func findOptsAccessPattern(t types.Type, access *Statement) (types.Type, *Statement) { |
closed | dagger/dagger | https://github.com/dagger/dagger | 6,162 | Go SDK Modules: enable general type annotation support via comments | Discord discussion: https://discord.com/channels/707636530424053791/1177373379255349248
As we need to add more support in Go for things like marking a field as private, setting default values, etc.
The most obvious option was to require use of structs (including the `Opts` struct idea, the "inline anonymous struct for args", etc.) and annotate more information via struct tags.
However, after discussion we realized a better general solution would be to not rely on struct tags but instead add support for the equivalent functionality via specially formatted comments. The reasoning being that:
1. Struct tags are essentially just glorified comments (strings that get interpreted by reflection/ast parsing), so there's not much of a practical difference in that respect
2. Comments are more general in that they can be applied equivalently not only to fields of a struct but also to function args (similar to how we support doc strings on args today), functions as a whole, structs as a whole, etc.
There's prior art for this:
1. Go's support for pragmas: https://dave.cheney.net/2018/01/08/gos-hidden-pragmas
2. K8s support for annotations: https://github.com/kubernetes-sigs/controller-tools/blob/881ffb4682cb5882f5764aca5a56fe9865bc9ed6/pkg/crd/testdata/cronjob_types.go#L105-L125
TBD the exact format of comments (i.e. use of a special prefix `//dagger: default=abc` vs something simpler like `//+default abc`).
We should use this to support at least:
1. Optional (can co-exist w/ existing `Optional` type)
2. Default values (will be limited to what can be represented as a string, but that's ok)
3. Marking object fields as private (so not included in public API but still included in serialization of object)
cc @vito @jedevc | https://github.com/dagger/dagger/issues/6162 | https://github.com/dagger/dagger/pull/6179 | e8097f5798af7f8b22f2a1be94a27c9800185053 | a499195df3de436969c4477bb1e9f074aa586eb6 | 2023-11-27T16:51:18Z | go | 2023-12-06T14:29:35Z | cmd/codegen/generator/go/templates/modules.go | switch t := t.(type) {
case *types.Pointer:
t2, val := findOptsAccessPattern(t.Elem(), access)
return t2, Id("ptr").Call(val)
default:
return t, access
}
}
func asInlineStruct(t types.Type) (*types.Struct, bool) {
switch t := t.(type) {
case *types.Pointer:
return asInlineStruct(t.Elem())
case *types.Struct:
return t, true
default:
return nil, false
}
}
func asInlineStructAst(t ast.Node) (*ast.StructType, bool) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.