Skip to content

Codegen: Support chainable utils via With(...) #3885

Closed

Description

@sipsma

A current pain point of our SDKs is that any time you want to write your own util that's not in our API, it has to "break the chain".

e.g.

func AddAFewMounts(c *dagger.Container) *dagger.Container {
  return c.
    WithMountedDirectory("/foo", c.Host().Directory("foo").
    WithMountedDirectory("/bar", c.Host().Directory("bar")
}

func main() {
 ctr := Container().
    From("alpine").
    WithWorkdir("/foo")
ctr = AddAFewMounts(ctr) // The chain is broken!!!!!!
output, err := ctr.Exec("blah").Stdout().Contents()
...
}

This isn't a huge deal but can get more annoying the more modular utils you want to write.

Instead, we could have our codegen clients include a .With(...) method on chainable objects that could be used like this:

func AddAFewMounts(c *dagger.Container) *dagger.Container {
  return c.
    WithMountedDirectory("/foo", c.Host().Directory("foo").
    WithMountedDirectory("/bar", c.Host().Directory("bar")
}

func main() {
 output, err := Container().
    From("alpine").
    WithWorkdir("/foo").
    With(AddAFewMounts).
    Exec("blah").Stdout().Contents()
...
}

In Go, With could have signatures like:

func (c *Container) With(f func(*Container)) *Container {
  return f(c)
}
...
func (d *Directory) With(f func(*Directory)) *Directory {
  return f(d)
}

I imagine similar signatures could be generated for our other SDKs (?)

I think this would be a small-to-medium size improvement to DX and may be an interesting place for future extensions to integrate (maybe).

### Todos
- [x] https://github.com/dagger/dagger/pull/4332
- [x] https://github.com/dagger/dagger/pull/4898
- [x] https://github.com/dagger/dagger/pull/4922
- [ ] Apply to a subset of types [selectively](https://github.com/dagger/dagger/issues/3885#issuecomment-1502081027)
- [ ] Standardize *docstrings*
- [ ] Maybe standardize tests
- [ ] https://github.com/dagger/dagger/issues/5236

Activity

  1. dolanor commented on Nov 17, 2022

    @dolanor
    Contributor

    I think I like this proposal!

  2. helderco commented on Nov 17, 2022

    @helderco
    Contributor

    I like that. I want to experiment with that pattern.

  3. aluzzardi commented on Nov 17, 2022

    @aluzzardi
    Contributor

    I like it!

    Maybe it's too complex, but a more powerful thing would be to follow the http.Handler middleware pattern and return a callback. This would allow to parameterize the With() statement:

    func InstallAFewPackages(pkg ...string) WithContainerFunc {
      return func(c *dagger.Container) *dagger.Container {
        for _, p := range pkg {
          c = c.Exec("apk", "add", p)
        }
        return c
      }
    }
    
    func main() {
     output, err := Container().
        From("alpine").
        WithWorkdir("/foo").
        With(InstallAFewPackages("bash", "curl", "jq")).
        Exec("blah").Stdout().Contents()
    ...
    }

    NOTE: This is just a pattern, doesn't require any changes from original proposal

  4. added and removed on Dec 21, 2022
  5. helderco commented on Jan 5, 2023

    @helderco
    Contributor

    Just saw #4173 and immediately thought of this.

    Before

    	memcached := client.Container().
     		From("alpine:3.17").
     		WithExec([]string{"addgroup", "-g", "11211", "memcache"}).
     		WithExec([]string{"adduser", "-D", "-u", "1121", "-G", "memcache", "memcache"}).
     		WithExec([]string{"apk", "add", "--no-cache", "libsasl"}).
     		WithEnvVariable("MEMCACHED_VERSION", "1.6.17").
     		WithEnvVariable("MEMCACHED_SHA1", "e25639473e15f1bd9516b915fb7e03ab8209030f")
    
     	// add dependencies to the container
     	memcached = setDependencies(memcached)
    
     	// add source code to the container
     	memcached = downloadMemcached(memcached)
    
     	// build the application
     	memcached = buildMemcached(memcached)
    
     	// set the container entrypoint
     	entrypoint := client.Host().Directory(".").File("docker-entrypoint.sh")
     	memcached = memcached.
     		WithFile("/usr/local/bin/docker-entrypoint.sh", entrypoint).
     		WithExec([]string{"ln", "-s", "usr/local/bin/docker-entrypoint.sh", "/entrypoint.sh"}).
     		WithEntrypoint([]string{"docker-entrypoint.sh"}).
     		WithUser("memcache")
    
     	// publish the container image
     	addr, err := memcached.Publish(ctx, publishAddr)

    After

     	entrypoint := client.Host().Directory(".").File("docker-entrypoint.sh")
    
    	memcached := client.Container().
     		From("alpine:3.17").
     		WithExec([]string{"addgroup", "-g", "11211", "memcache"}).
     		WithExec([]string{"adduser", "-D", "-u", "1121", "-G", "memcache", "memcache"}).
     		WithExec([]string{"apk", "add", "--no-cache", "libsasl"}).
     		WithEnvVariable("MEMCACHED_VERSION", "1.6.17").
     		WithEnvVariable("MEMCACHED_SHA1", "e25639473e15f1bd9516b915fb7e03ab8209030f").
     		With(setDependencies).
     		With(downloadMemcached).
     		With(buildMemcached).
     		WithFile("/usr/local/bin/docker-entrypoint.sh", entrypoint).
     		WithExec([]string{"ln", "-s", "usr/local/bin/docker-entrypoint.sh", "/entrypoint.sh"}).
     		WithEntrypoint([]string{"docker-entrypoint.sh"}).
     		WithUser("memcache")
    
     	// publish the container image
     	addr, err := memcached.Publish(ctx, publishAddr)
  6. slumbering commented on Jan 6, 2023

    @slumbering
    Contributor

    Is the With() implemented in Python @helderco ?

  7. helderco commented on Jan 6, 2023

    @helderco
    Contributor

    No, but I want to 😍

  8. slumbering commented on Jan 6, 2023

    @slumbering
    Contributor

    Yes me too 😍

  9. slumbering commented on Jan 9, 2023

    @slumbering
    Contributor
  10. helderco commented on Feb 13, 2023

    @helderco
    Contributor

    Looking at this and I see two changes.

    Need to pass the client

    When you call c.Host()..., you mean to call this on the client (i.e., root Query), not Container. So I think these functions need 2 arguments: the current instance and the client.

    func AddAFewMounts(ctr *dagger.Container, client *dagger.Client) *dagger.Container {
      return ctr.
        WithMountedDirectory("/foo", client.Host().Directory("foo").
        WithMountedDirectory("/bar", client.Host().Directory("bar")
    }

    Why not return other types?

    Instead of only returning the same type, why not allow any type to be returned? For example, Container.Directory returns a dagger.Directory, this would allow more flexibility.

    This can be solved with generics. Here's Python's implementation, doesn't even have to be codegen'ed:

    class Type(Object):
        def with_(self, cb: Callable[[Self, Root], T]) -> T:
            return cb(self, self._ctx.root)

    EDIT: disregard this question. The concept of With methods mean it's expected to return the same type, just with some additions.

  11. 11 remaining items

  12. sipsma commented on Apr 6, 2023

    @sipsma
    ContributorAuthor

    is there an option 3 where my util could in the future be mapped to its own graphql resolver, and added to the GraphQL schema as a full-blown step - from which codegen could then generate native chain steps?

    Depends on exactly what you mean, especially in terms of "generate native chain steps".

    If you just mean being able to generate an SDK that has the util baked in like ctr.AddAFewMounts(), then yes that would be totally possible. This would actually solve an open question with the current extension implementation where support for extending types from core or other extensions isn't possible, you can only define your own types+methods (due to restrictions in the type systems of languages like Go). Our solution to supporting With utils here would be our solution to that problem too.

    If by "generate native chain steps", you mean that we'd be able to convert the actual implementation of a util func from one language to another, then no I don't think that's feasible in general. If we arbitrarily limited the utils to be very simple chains of method calls, then maybe, but that would rule out using loops, conditionals, libraries, etc. That would feel like a big restriction without much benefit.

  13. shykes commented on Apr 6, 2023

    @shykes
    Contributor

    is there an option 3 where my util could in the future be mapped to its own graphql resolver, and added to the GraphQL schema as a full-blown step - from which codegen could then generate native chain steps?

    Depends on exactly what you mean, especially in terms of "generate native chain steps".

    If you just mean being able to generate an SDK that has the util baked in like ctr.AddAFewMounts(), then yes that would be totally possible.

    Yes I meant that one :)

    If by "generate native chain steps", you mean that we'd be able to convert the actual implementation of a util func from one language to another, then no I don't think that's feasible in general. If we arbitrarily limited the utils to be very simple chains of method calls, then maybe, but that would rule out using loops, conditionals, libraries, etc. That would feel like a big restriction without much benefit.

    Yup, I agree - that's a non-goal.

  14. TomChv commented on Apr 6, 2023

    @TomChv
    Member

    NodeJS needs to update the examples to use the pattern in option 1 instead of getting client via new Client() as shown in #4835 (comment)

    I'm not sure I understand what you mean. I added additional patterns in #4907 to verify it works according to #4898 tests.

  15. helderco commented on Apr 6, 2023

    @helderco
    Contributor

    NodeJS needs to update the examples to use the pattern in option 1 instead of getting client via new Client() as shown in #4835 (comment)

    I'm not sure I understand what you mean. I added additional patterns in #4907 to verify it works according to #4898 tests.

    I mean this:

    * function AddAFewMounts(c) {
    * return c
    * .withMountedDirectory("/foo", new Client().host().directory("/Users/slumbering/forks/dagger"))
    * .withMountedDirectory("/bar", new Client().host().directory("/Users/slumbering/forks/dagger/sdk/nodejs"))
    * }

    I suggest two examples: a simple one without any external dependencies, and a second one with the example above but using a factory function.

    There's also the following test:

    function AddAFewMounts(c: Container): Container {
    return c
    .withMountedDirectory("/foo", new Client().host().directory("foo"))
    .withMountedDirectory("/bar", new Client().host().directory("bar"))
    }

  16. self-assigned this
    on Apr 10, 2023
  17. helderco commented on Apr 10, 2023

    @helderco
    Contributor

    NodeJS has an implementation and Go implementation has been submitted, so I'm going to make a quick Python implementation as well.

    Self-assigning to push this forward and syncing between SDKs.

  18. helderco commented on Apr 10, 2023

    @helderco
    Contributor

    SDK implementations

    Drift: apply to which objects?

    NodeJS first implemented using codegen, on all object types. However, in the Go implementation, @jlongtine is applying only to Container and Directory. He raised the question "What do you imagine doing with func (c *CacheVolume).With(...) *CacheVolume? He has a point 🤔

    However, I prefer either applying to all types or finding some rule to be more selective, but I'd rather not manually hardcode which ones to select. Otherwise, if a new type comes along where this could be useful, someone has to remember to add that type to the list.

    I submitted a proposal to return simple objects in codegen. That requires codegen to tell the difference between a plain object (e.g., EnvVariable, Port, Label) and a normal object type like Container and Directory. If in addition we exclude ID() and deprecated fields, selecting only the non-empty objects that are left, already excludes EnvVariable, Port, Label, CacheVolume, Socket, etc.

    So the Python implementation is not using codegen (for now), but has a general implementation in the base type. If the return simple objects proposal gets accepted, that implementation will automatically change the base class for these objects, thus not including with_() in these cases.

    In the meantime, we can also do a follow up to implement this detection in all SDKs, fixing this drift, while also solving the first step of that proposal. I don’t think it’s necessary to hold on merging the current PRs waiting for this though.

  19. helderco commented on Apr 12, 2023

    @helderco
    Contributor

    All SDKs have an implementation, but there’s a slight drift:

    • Apply to a subset of types selectively
    • Standardize docstrings
    • Maybe standardize tests

    After these tasks, this issue can be closed.

  20. helderco commented on Jul 11, 2023

    @helderco
    Contributor

    I found a better rule for selectively choosing which types to add this method: object types that have at least one field that returns the current type. I'll submit a PR soon that'll close this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

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