Skip to content

Go SDK: Query Builder - #3125

Merged
aluzzardi merged 15 commits into
dagger:cloakfrom
aluzzardi:query-builder-test
Oct 12, 2022
Merged

aluzzardi merged 15 commits into
dagger:cloakfrom
aluzzardi:query-builder-test

Conversation

@aluzzardi

@aluzzardi aluzzardi commented Sep 16, 2022 •

Copy link
Copy Markdown
Contributor

Go SDK: Query Builder based Code Generation

  • Add support for "operation-less" code generation
    • Purely based on schema introspection, doesn't rely on a operations.graphql file
  • Builder Pattern
    • e.g. core.Container().From("alpine").Exec([]string{"echo", "hello world"}).Stdout().Contents(ctx)
    • Queries are built on the fly and sent in "batches", rather than bit by bit
    • Much closer experience to manually crafted GraphQL queries, without actually writing GraphQL
  • Architectured for multi-language
    • So far only includes the "Go" generator
    • ... however adding a language is still a non-trivial amount of work
      • The underlying "query builder" library was built in-house for Go
      • Other languages may or may not have a 3rd party query builder library available

Example

core := api.New(ctx.Client)

dir := core.Directory().WithNewFile("/test.txt", api.WithDirectoryWithNewFileContents("hello world"))

contents, err := dir.File("/test.txt").Contents(ctx)
if err != nil {
	return err
}
fmt.Println(contents)

alpine := core.Container().From("alpine")
for _, pkg := range []string{"bash", "jq", "curl"} {
	alpine = alpine.Exec([]string{"apk", "add", "--no-cache", "-U", pkg})
}

cmd := alpine.Exec([]string{"bash", "-c", "echo hello world!"})

output, err := cmd.Stdout().Contents(ctx)
if err != nil {
	return err
}
fmt.Println(output)

@netlify

netlify Bot commented Sep 28, 2022 •

Copy link
Copy Markdown

✅ Deploy Preview for cloak-docs ready!

Name Link
🔨 Latest commit 3cf0ca6
🔍 Latest deploy log https://app.netlify.com/sites/cloak-docs/deploys/6347214280c980000811c759
😎 Deploy Preview https://deploy-preview-3125--cloak-docs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site settings.

@aluzzardi
aluzzardi force-pushed the query-builder-test branch 5 times, most recently from d182c55 to d1b0c12 Compare October 5, 2022 02:31
@aluzzardi

Copy link
Copy Markdown
Contributor Author

Open Question: Argument Passing

This is a Go-specific issue since it doesn't support optional arguments (in contrast to TypeScript / Python, which do have optional arguments).

These are the typical Go approaches to this problem:

  1. LLB-style
dir.WithNewFile("/foo")
dir.WithNewFile("/foo", dagger.WithDirectoryWithNewFileContents("blah"))
  • Pros: Nicest DX (according to a poll between @shykes, @sipsma, @vito and myself -- highly subjective though)
  • Cons: Discoverability (mitigated by LSP), long function names because of name clashing
  • Mitigations:
    • @dolanor suggested we could use sub-packages
      • I like this idea, need more exploration.
      • Basically it would allow to remove one part of the name marshaling by name spacing by package
      • Example: dir.WithNewFile("/foo", directory.WithNewFileContents("blah"))
    • @vito suggested shortening the With mangling
      • However we realized there's many scenarios in which it will clash
      • Example: WithID() could either be a ContainerID, DirectoryID, etc
        • WithID() is for illustration purposes: the meaning behind the example is NO two arguments of ANY field in the ENTIRE API can have a conflicting type
        • Another problem is discoverability / completion / validation:
          • LSP currently suggests WithDirectoryWithNewFileContents automatically because it's a unique option to WithNewFileContents
          • Trying to pass an incompatible type of option will result in a compile error (and red highlighting in vscode)
          • Generic options won't have this property
            • e.g. dir.WithNewFile("/foo", dagger.WithID("xxx")) will compile just fine even though it's a wrong call, fail at runtime
      • All those problems however COULD potentially be mitigated with some clever interface usage, generics, etc
        • Needs investigation
  1. Mandatory positional, optional struct with non-zero values
dir.WithNewFile("/foo", nil)
dir.WithNewFile("/foo", &dagger.DirectoryWithNewFileOpts{Contents: "blah"})
  • Pros: Less magic
  • Cons
    • Must pass nil around pretty often when NOT providing args
    • Non-zero values are a bit sketchy: setting an optional string to "" won't be possible for instance since there's no way to distinguish a zero-value from an option-value-not-being-provided
      • In reality I don't think this is a big issue
  • Mitigations: N/A
  1. Everything in struct (pointer for optionals)
dir.WithNewFile(dagger.DirectoryWithNewFileOpts{Name: "/foo"})
contents := "blah"
dir.WithNewFile(dagger.DirectoryWithNewFileOpts{Name: "/foo", Contents: &blah})
  • Pros: Least magic
  • Cons: Sucks to pass optional arguments (e.g. in Go you can't pass &"foo", need to create a string first then pass the pointer, or use a helper function)
  • Mitations:
    • Using generics, Contents: dagger.Optional("blah"). dagger.Optional (or whatever name) returns a pointer of the passed argument

Where I'm leaning

Find a GOOD solution for 1 or switch to 2

@shykes

shykes commented Oct 6, 2022

Copy link
Copy Markdown
Contributor

Open Question: Argument Passing

  1. LLB-style
* Basically it would allow to remove one part of the name marshaling by name spacing by package
* Example: `dir.WithNewFile("/foo", directory.WithNewFileContents("blah"))`

Is this actually needed in practice? ie. is there any instance of WithNewFile meaning 2 different things in 2 different places?

  1. Mandatory positional, optional struct with non-zero values
dir.WithNewFile("/foo", nil)
dir.WithNewFile("/foo", &dagger.DirectoryWithNewFileOpts{Contents: "blah"})
  • Pros: Less magic

  • Cons

    • Must pass nil around pretty often when NOT providing args

    • Non-zero values are a bit sketchy: setting an optional string to "" won't be possible for instance since there's no way to distinguish a zero-value from an option-value-not-being-provided

      • In reality I don't think this is a big issue
  • Mitigations: N/A

  1. Everything in struct (pointer for optionals)
dir.WithNewFile(dagger.DirectoryWithNewFileOpts{Name: "/foo"})
contents := "blah"
dir.WithNewFile(dagger.DirectoryWithNewFileOpts{Name: "/foo", Contents: &blah})
  • Pros: Least magic
  • Cons:

Another Con is that you need to pass nil around a lot when passing no arguments, right?

Sucks to pass optional arguments (e.g. in Go you can't pass &"foo", need to create a string first then pass the pointer, or use a helper function)

@shykes

shykes commented Oct 6, 2022

Copy link
Copy Markdown
Contributor

Question: how does this all work with extensions? Are they supported 1) completely, 2) partially, 3) not at all?

@dolanor

dolanor commented Oct 6, 2022 •

Copy link
Copy Markdown
Contributor

for 2, you can use the ugly hack of passing variadic options. So you don't have to pass nil. But I don't think it's idiomatic for that case and makes the API less clear, I think.

I'm gonna play with generics and interface to try to find a better way.

And SUPER job btw. A way better experience already, for sure!

@aluzzardi

Copy link
Copy Markdown
Contributor Author

Question: how does this all work with extensions? Are they supported 1) completely, 2) partially, 3) not at all?

Yes, it all works with extensions, semi-completely. Currently there's a whitelist to only generate the new core API (and not the old one, not extensions, etc). Only because there's still some edge cases I'm not handling yet, but it will be gone soon.

Generation is designed so it can handle the unexpected. Basically, as long as an extension can load, it's 100% guaranteed code generation will work reliably, without name clashing, etc.

Is this actually needed in practice? ie. is there any instance of WithNewFile meaning 2 different things in 2 different places?

Yes because of the above (extensions). They could clash with core, but also among themselves.

Basically, the name mangling right now is With<Object><Field><Arg>. The reason behind this is:

the meaning behind the example is NO two arguments of ANY field in the ENTIRE API can have a conflicting type

<Object><Field><Arg> is the only reliable unique identifier for a given arg that guarantees no clashing. If we do less than that, the question is how can we mitigate conflicts (e.g. go templates? some other sort of namespacing?)

@sipsma sipsma mentioned this pull request Oct 11, 2022
12 of 19 tasks

@sipsma sipsma left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dolanor suggested we could use sub-packages

I like the way things end up looking with this, but based on past experience doing this with the older codegen it becomes annoying to have to import from a bunch of packages. The go automatic import guesser would often guess wrong and import from another nearby package that was generating similar code. Doesn't rule it out entirely but something to keep in mind.

I spent a bit and couldn't come up with anything else reasonable that felt natural. I'd probably lean towards Option 2 at this point honestly unless something else comes up. The need for nil is not that bad and it would perhaps be okay to make it optional with something like

func (r *Directory) WithNewFile(path string, options ...DirectoryWithNewFileOpts) *Directory {
  // just apply the values set in the structs in options in order provided, though most of the time users will just have 0 or 1
}

The variadic is a bit odd but it allows you to skip nil, has consistent logic behavior and retains type safety. So worth considering maybe.

I agree that it feels like there might be something really clever possible w/ generics or interfaces, but unless we can figure that out soon not worth blocking on IMO. This is just Go being Go, not worth fighting it too hard.

Comment thread cmd/dagger/main.go Resolved
Comment thread cmd/dagger/clientgen.go Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: using the ast package to get the package name is probably only a few lines of code: https://pkg.go.dev/go/parser#ParseDir

Just to handle cases where dir name doesn't match package name. There's a mode for stopping after the package clause (PackageClauseOnly), so shouldn't slow things down. If it's harder than a couple of quick lines of code it's no worries at all though, not remotely a blocker

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, done!

I've still kept the old logic in there, but it first tries to check if a package name is already set.

Most of the time (I guess?) client gen will output into its own directory (e.g. -o api/api.gen.go) so there's no other Go code to parse.

Comment thread sdk/go/dagger/querybuilder/marshal.go Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not a big deal at all right now, but I think it would probably result in simpler code in the long run if we can just use vektah/gqlparser to construct these graphql operation strings. I used Formatter.FormatSchemaDocument in the code-first stuff, I think you can use Formatter.FormatQueryDocument for this. Even though we don't need a whole document, from what I can tell briefly glancing you can use that for individual queries too.

If all the above is actually true (and it may not be), then I just suspect it will be easier to maintain and more robust relative to string construction. But if the string construction works that's all that matters for now :-)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome -- I just checked and I think it would work.

We could use it in func (s *Selection) Build() to construct the query.

MarshalGQL would still exist and be pretty similar to today (AFAIK gqlparser doesn't provide any Go->AST helper), but it would construct an ast.Value rather than a string.

Should've used it from the get go -- the reason it's this way is because I started with the graphb library, later hit a wall, and re-implemented parts of it which were using string construction.

Since we're a bit short in time, I filed #3332 so we can get this merged and get people using it, will clean up later.

@aluzzardi
aluzzardi marked this pull request as ready for review October 12, 2022 18:17
@aluzzardi aluzzardi changed the title [WIP] Go SDK: Query Builder Go SDK: Query Builder Oct 12, 2022
@aluzzardi

aluzzardi commented Oct 12, 2022 •

Copy link
Copy Markdown
Contributor Author

I like the way things end up looking with this, but based on past experience doing this with the older codegen it becomes annoying to have to import from a bunch of packages. The go automatic import guesser would often guess wrong and import from another nearby package that was generating similar code. Doesn't rule it out entirely but something to keep in mind.

Yes, and we also stopped doing that because of cross-package complications. For instance, alpine extends Query, but Query is defined in core and alpine can't dynamically add a Alpine() function to it.

It kinda worked (but gave us headaches) with an operations file since every operation was a full blown independent query, but with query building every field might be a cross-package reference.

I spent a bit and couldn't come up with anything else reasonable that felt natural. I'd probably lean towards Option 2 at this point honestly unless something else comes up. The need for nil is not that bad and it would perhaps be okay to make it optional with something like

Yep, that's where I'm at too. Basically:

dir.WithNewFile("/foo")

dir.WithNewFile("/foo", dagger.DirectoryWithNewFileOpts{
  Contents: "blah",
})

I think that's the most Go idiomatic way that completely avoids name collisions and such.

Contrast with the current implementation, for reference:

dir.WithNewFile("/foo")
dir.WithNewFile("/foo", dagger.WithDirectoryWithNewFileContents("blah"))

@aluzzardi

Copy link
Copy Markdown
Contributor Author

Implemented as a separate commit.

Used @sipsma s suggestion -- no need to pass nil, functions take a ...opt, last one where a field is set wins

e.g:

// this works, no `nil`
Exec()

// can pass the opts as a struct
Exec(dagger.ContainerExecOpts{
  Args: []string{"ls"},
  Stdin: "foo",
}

// this, although weird, also works
Exec(
    dagger.ContainerExecOpts{
        Args: []string{"ls"},
    }, dagger.ContainerExecOpts{
        Stdin: "foo",
    },
)

Signed-off-by: Andrea Luzzardi <[email protected]>

@sipsma sipsma left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎉

@vito

vito commented Oct 12, 2022

Copy link
Copy Markdown
Contributor

@aluzzardi Will this mean we need to remember to go generate ./... when making API changes? I wonder if we should add a CI check for that at some point.

@aluzzardi

Copy link
Copy Markdown
Contributor Author

@vito Yes, CI should be doing it!

I was about to add that into a Makefile then figured it's a good opportunity to dogfood, should add that into a magefile or something :)

@aluzzardi
aluzzardi merged commit c42751a into dagger:cloak Oct 12, 2022
@aluzzardi
aluzzardi deleted the query-builder-test branch October 12, 2022 21:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants