Skip to content

Consider hiding the need for IDs in codegen clients  #3558

Closed

Description

@sipsma

The need to explicitly select and pass around IDs rather than objects (i.e. pass a DirectoryID rather than a Directory) is an abstraction leak; it only makes sense in the implementation details, not UX. It is inherently a bit confusing + unintuitive and it also creates more problems in that ID is a special scalar where selecting it doesn't result in evaluation (related discord thread).

This will always be the case on the raw graphql level (and it should be as that's typically how graphql APIs work), but our codegen clients could probably hide this. For example, whenever our client currently accepts a DirectoryID, we could instead accept a Directory object and just have the implementation know that it needs to internally get the ID of the Directory and use that in the raw query.

Somewhat related to this issue: #3555

Activity

  1. added this to the 0.3.0 milestone on Oct 26, 2022
  2. shykes commented on Oct 26, 2022

    @shykes
    Contributor

    +1, this would be amazing.

  3. shykes commented on Oct 27, 2022

    @shykes
    Contributor

    @aluzzardi would this be possible?

  4. jlongtine commented on Oct 27, 2022

    @jlongtine
    Contributor

    I agree that this would be awesome!

  5. sipsma commented on Oct 27, 2022

    @sipsma
    ContributorAuthor

    FWIW I'm assuming this would introduce at least a decent bit of complication to our internal code. We'd need to save these objects in the query builder and then once the final query is to be submitted call .ID() on all of the objects (in parallel for efficiency probably) before submitting the final query. All internal though, hidden from the user.

    If that is the extent of the complication (i.e. I'm not missing something even worse) then I think it'd be worth it given the UX benefits, but probably isn't utterly trivial.

  6. sipsma commented on Oct 27, 2022

    @sipsma
    ContributorAuthor

    From @jlongtine: we need the ability to force evaluations for dagger-cue.

    One possible path might be to add an optional parameter to ID like eval or sync that forces a synchronous evaluation of the ID. Technically there are other paths too (can just add separate .Eval() or Sync() methods everywhere), but this approach is appealing in that it reduces the amount of API fields we need to populate on all objects and it also makes sense in that ID is the thing being eval'd synchronously anyways.

    However, I do think we need this to be an optional param because there is still value in retrieving ID lazily, if nothing else for our internal codegen clients who can better optimize that way. Whether lazy should be default on or off is debatable, no strong feelings since ID will not be commonly used by end users anyways.

    EDIT: scratch the above, part of the point of this is that ID still needs to be accessible even if it's not commonly used anymore. So from that perspective I think it should probably default to a synchronous evaluation and then have an optional parameter to enable laziness.

    So to summarize

    1. ID() still exists for users, but is not commonly needed anymore since you can just provide objects directly.
    2. ID() by default results in a synchronous evaluation
    3. ID() also accepts an optional argument that can enable laziness. Candidate names are sync and eval which default to true but can be overridden to be false.
  7. jlongtine commented on Oct 28, 2022

    @jlongtine
    Contributor

    I don't know if this would be helpful... but seemed like it is relevant: moby/buildkit#3137

  8. aluzzardi commented on Oct 28, 2022

    @aluzzardi
    Contributor

    Totally agree here.

    Recapping / rephrasing / combining two pieces of feedback/issues:

    I think @sipsma's proposal would work great, which entails:

    • Making ID synchronous, just like the rest of functions that return an error (least surprising)
      • Follows the "rule of thumb"
    • Not having to pass IDs around anymore but the objects instead
      • Which continues to be lazy and is consistent with the rule of thumb (creating "objects" doesn't return errors)
    • Documenting said rule of thumb
    • Adding a Sync or something helper in addition, to force object evaluation?
      • Personally I think it's worth it, see example below

    Asynchronous execution with pass-by-object:

    // This is asynchronous
    file1 := c.
    	Container().
    	From("alpine:3.16.2").
    	Exec(dagger.ContainerExecOpts{[]string{"sh", "-c", "echo hello world > /file"}}).
    	File("/file")
    
    // This is asynchronous
    file2 := c.
    	Container().
    	From("alpine:3.16.2").
    	Exec(dagger.ContainerExecOpts{[]string{"sh", "-c", "echo foo bar > /file"}}).
    	File("/file")
    
    // This is asynchronous
    // NOTE: Passing `file1` and `file2` directly as object, not as ID
    result := c.
    	Container().
    	From("alpine:3.16.2").
    	WithMountedFile("/f1", file1).
    	WithMountedFile("/f2", file2).
    	Exec(dagger.ContainerExecOpts{Args: []string{"sh", "-c", "cat /f*"}}).
    	Stdout()
    
    // This will result in:
    // 1) Execution of `file1` and `file2` in parallel
    // 2) Execution of `result`
    // Follows the rule of thumb: takes context, returns an error
    _, err = result.Contents(ctx)

    With synchronous (forced) execution with pass-by-object:

    // This is SYNCHRONOUS
    // Note the chaining of `Sync()` which takes a context and returns the same object plus an error
    file1, err := c.
    	Container().
    	From("alpine:3.16.2").
    	Exec(dagger.ContainerExecOpts{[]string{"sh", "-c", "echo hello world > /file"}}).
    	File("/file").
    	Sync(ctx)
    if err != nil {
    	return err
    }
    
    
    // This is SYNCHRONOUS
    file2, err := c.
    	Container().
    	From("alpine:3.16.2").
    	Exec(dagger.ContainerExecOpts{[]string{"sh", "-c", "echo foo bar > /file"}}).
    	File("/file").
    	Sync(ctx)
    file2, err = file2.ForceEval(ctx)
    if err != nil {
    	return err
    }
    	
    // This is asynchronous
    result := c.
    	Container().
    	From("alpine:3.16.2").
    	WithMountedFile("/f1", file1).
    	WithMountedFile("/f2", file2).
    	Exec(dagger.ContainerExecOpts{Args: []string{"sh", "-c", "cat /f*"}}).
    	Stdout()
    	
    // This will result in:
    // 1) Execution of `result` -- `file1` and `file2` have already been solved
    result.Contents(ctx)

    /cc @helderco -- I agree with #3555, we should find another "rule of thumb" for Python to remove confusion

  9. modified the milestones: 0.3.0, on Oct 28, 2022
  10. shykes commented on Oct 28, 2022

    @shykes
    Contributor

    This makes me think of 2 topics that feel relevant, but may not be. Apologies in advance if I'm completely off topic, or redundant with things already said before. I just want to make sure we don't miss a potential design constraint.

    1. llb-style query generation
    2. first-class support for gql documents

    1. llb-style query generation

    Buildkit's llb API, although it has its own warts, has a very powerful "query building API" of its own: llb. One benefit of LLB over our current API, is that the "building" part is completely decoupled from the "sending" part (ie. Solve). So you can compose sub-DAGs into bigger DAGs with minimal error checking etc.

    I think this overlaps with the outcome of @aluzzardi 's current prototype, so I'm probably stating the obvious here.

    But perhaps we could take it further, and for example allowing building queries without having a client object.
    ie instead of:

    c := dagger.Connect(ctx)
    pipeline := c.Container().From("alpine")
    err := pipeline.Sync(ctx)

    We could have:

    pipeline := dagger.Container().From("alpine")
    c := dagger.Connect(ctx)
    err := c.Query(c)

    2. first-class gql documents

    This one is more blurry but feels important. GraphQL defines a first-class concept of documents. Documents exist both on the client ("operations file" convention) and on the wire: clients may send a multi-operation document, and servers are required to support that. This is considered a best practice eg. for maximizing caching in large-scale production deployments.

    I sense that this primitive of gql documents is crucial for us, and we would benefit from treating it as a first-class citizen in our SDKs. So, for example, I think our Go SDK should (somehow) expose the primitives to create not just a single query, but a document of named queries. Perhaps in the future we may even want to make this mandatory: so even if you're building and sending a one-off pipeline, in reality, you created a document with a single operation.

    I don't know if this is relevant in this discussion. If not, I will make this a separate issue :)

    To be clear this is not a request or even a proposal: just a raw dump of possibly relevant information that is swirling in my head at the moment.

  11. 3 remaining items

  12. shykes commented on Oct 31, 2022

    @shykes
    Contributor

    But perhaps we could take it further, and for example allowing building queries without having a client object.
    ie instead of:

    pipeline := dagger.Container().From("alpine")
    c := dagger.Connect(ctx)
    err := c.Query(c)

    Here it gets tricky compared to LLB because we DO return values, whereas LLB API has a single return value (a container). I don't know how to map that into a "solve-like API":

    pipeline := dagger.Container().From("alpine").Exec([]string{"ls"})
    c := dagger.Connect(ctx)
    err := c.Query(pipeline)
    
    // how do I get stdout back? maybe:
    stdout, err := c.Query(pipeline.Stdout().Contents())
    // but what type is `stdout`? does the user need to cast?
    // do users need to `c.Query()` every field they need manually?

    Open to ideas -- I did consider this in the past but got stuck.

    I'm at the same point as you. What do you think of this:

    var (
      lsStdout string
      lsCode int
    )
    pipeline := dagger.Container().
      From("alpine").
      Exec([]string{"ls"}).
      GetExitCode(&lsCode).
      GetStdout(&lsStdout).
      Exec([]string{"echo", "something", "else"})
    
    err := dagger.Connect(ctx).Query(pipeline)

    There may be problems that I'm not seeing, but it has 2 benefits that make it very compelling to me:

    1. It solves our problem above :) Arbitrary chaining, with arbitrary queries, without having to "break the chain".
    2. It's actually closer to the underlying graphql reality, where you can query any number of scalar values as you navigate the graph. For example the pipeline above could translate to the following graphql:
    query {
      container {
        from(address: "alpine") {
          exec(args: ["ls"]) {
            exitCode
            stdout
            exec(args: ["echo", "something", "else"]) {
              id // note: maybe should be called something other than id? but I digress :)
            }
          }
        }
      }
    }

    wdyt @aluzzardi @sipsma @vito ?

    EDIT: one possible variation which may or may not be a terrible idea: using callbacks instead of pointers for extra flexibility :)

    var (
      lsStdout string
      lsCode int
    )
    pipeline := dagger.Container().
      From("alpine").
      Exec([]string{"ls"}).
      GetExitCode(func(code int) error { lsStdout = code; return nil } ).
      GetStdout(func(stdout string) error { lsStdout = stdout; return nil } ).
      Exec([]string{"echo", "something", "else"})
    
    err := dagger.Connect(ctx).Query(pipeline)

    One benefit of the callback is that it gives me more flexibility to wrap my pipelines into reusable functions :)

    For example:

    // Form 1 possible: pure pipeline builder
    func lsPipeline(output *string) dagger.Pipeline {
      return dagger.Container().
        From("alpine").
        Exec([]string{"ls"}).
        GetExitCode(func(code int) error { return code == 0 } ).
        GetStdout(func(stdout string) error { if output != nil { *output = stdout }; return nil })
    }
    // Form 2 possible: synchronous execution
    func ls(ctx context.Context) (output, error) {
      var stdout string
      err := dagger.Connect(ctx).Query(lsPipeline(&stdout))
      return stdout, err
    }
  13. dolanor commented on Oct 31, 2022

    @dolanor
    Contributor
    pipeline := dagger.Container().From("alpine").Exec([]string{"ls"})
    c := dagger.Connect(ctx)
    err := c.Query(pipeline)
    
    // how do I get stdout back? maybe:
    stdout, err := c.Query(pipeline.Stdout().Contents())
    // but what type is `stdout`? does the user need to cast?
    // do users need to `c.Query()` every field they need manually?

    With a

    package dagger
    
    type StdoutRequest struct{}
    type StdoutResponse struct {
        Data []byte
    }
    
    func (c *Client) Query[Req any, Resp any](req T) (Resp, error)

    We could pass the query and determine the returning type from type parameter.

    c := dagger.Connect(ctx)
    pipeline := dagger.Container().From("alpine")
    resp, _ := c.Query[ContentResponse](pipeline.Stdout())
    
    // the type is statically typed, no casting required
    fmt.Println(string(resp.Content))
  14. dolanor commented on Oct 31, 2022

    @dolanor
    Contributor

    Actually, here is a runnable version of the idea:
    https://go.dev/play/p/5d4gFjXjN0W

    And I might have some idea on how to map the request to the response.
    Let me try.

  15. dolanor commented on Oct 31, 2022

    @dolanor
    Contributor

    Found some not completely crazy way:
    https://go.dev/play/p/MAFaGyqPeXy

    You create some mapping with a generic type alias, or use the generic RequestResponse type directly:

    type FileToContainer = RequestResponse[File, Container]
    
  16. mircubed commented on Nov 22, 2022

    @mircubed
    Contributor

    @sipsma can we close this now that the above PRs are merged?

  17. removed this from the milestone on Nov 22, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions