Skip to content

Modules: replace root in dagger.json with source #6291

Closed

Description

@sipsma

Currently, by default the engine loads the directory tree at a module's dagger.json and nothing else. However, to support cases where there are files/dirs the module relies on that are outside that directory tree (i.e. a go.mod, package.json, another dependency module that exists relative to the module, etc.) there exists a root field in dagger.json that allows you to specify a parent directory that the engine will load instead.

This technically works but is inherently very confusing, both in behavior and terminology.

We discussed a better approach in this discord thread: https://discord.com/channels/707636530424053791/1182712578154180648

Full details are TBD as part of this issue, but the gist of the idea is to "invert control" such that rather than having a dagger.json that can point to parent dirs to load, dagger.json has the ability to point to module source that is present in child dirs.


There's a many variations on this general idea possible.

For the sake of having a concrete example, here's one possibility. The directory tree in a monorepo containing two go sdk modules that share a go.mod at the root of the repo would look like:

├── dagger.json
├── go.mod
├── go.sum
├── other-subdir
│   └── depmod
└── subdir
    └── mymod

In this case, the module at subdir/mymod is a module that depends on the module at other-subdir/depmod.

The contents of dagger.json would look something like this:

[
  {
    "name": "mymod",
    "source": "./subdir/mymod",
    "sdk": "go",
    "dependencies": ["./other-subdir/depmod"]
  },
  {
    "name": "depmod",
    "source": "./other-subdir/depmod",
    "sdk": "go",
    "dependencies": []
  },
]

This would be a slightly altered format of dagger.json that allows multiple modules to be specified rather than only one (hence the list of objects on the top level).

The resulting behavior would be that if you ran dagger call (or other module-aware cli commands) in the ./subdir/mymod directory then we'd find the parent dagger.json (or error out if one wasn't found in the current git repo) and use that to know where the source of that mymod module is and also where the source of the depmod module is.

That can all be used to load the module as efficiently as possible (where it's from a local checkout or purely from git), as described in this and subsequent comments on a related issue.

Support for exclude/include on each module should also fit in pretty well with this sort of approach.

Activity

  1. skycaptain commented on Dec 28, 2023

    @skycaptain
    Contributor

    I think this feature is quite significant, as it would also allow the inclusion of secret files located in the user's home directory, such as ~/.gnupg mentioned in this cookbook example or ~/.netrc.

    One suggestion for the design of this feature: There could be sources that are either mandatory or optional. In the given scenario, I would prefer to permit the use of ~/.netrc files but have a fallback to environment variables within the module's code.

  2. self-assigned this
    on Jan 8, 2024
  3. shykes commented on Jan 22, 2024

    @shykes
    Contributor

    @sipsma continuing the discussion thread we started on #6386 and f2f:

    • I like your proposal and think we should do it. I am excited for this increased flexibility in configuring my Dagger modules :)
    • At this time I don't have specific changes to suggest
    • However I do have a few questions
    • My goal is to remove myself as blocker as quickly as possible

    Question 1: how do we keep it simple?

    I love the simplicity of this formula: module = directory + dagger.json. I worry about losing it. It also has cool corollaries, like "my sub-modules = my sub-directories with dagger.json".

    We don't have to keep the formula, necessarily. But we must keep the simplicity. What new formula would come with your proposed design, and is it simple enough? It now, can we make it simpler?

    Question 2: how does introspection work?

    Modules often call host().directory() for introspection. Usually it's to load data packaged with the module source.

    • In your design, what does host().directory() map to? The module's source directory, or the directory holding its dagger.json?
    • Should I always use one directory or the other for introspection? Or does it depend on the use case? What is the rule?
    • While we're at it, can we deprecate host().directory() for this purpose, and encode the answers above into an API?

    Question 3: can I use dagger.json to configure my home directory?

    The title says it all :) I have a dream of configuring Dagger in my home directory, to unlock various goodies. See #6323. Will the dagger.json from your design also be used to configure my home directory? Or do we prefer to design a different format for a different config file at the home directory?

    Random idea

    Below are new ideas coming to me as I write this. Disclaimer, I may change my mind at any time :)

    Maybe that's the answer? If dagger.json becomes a complete engine configuration, instead of module configuration, then perhaps that answers my other questions? The formula would become: configuration = dagger.json, context = directory + configuration.

    My home directory could have a dagger.json, making it a context directory for running the engine. My configuration would determine what the engine can see and do in that context: what modules to load; from where; with what default arguments 😇 ; etc.

    In this scenario, an individual module would typically not have its own dagger.json: rather it would be commonly found at the root of the repo. For example my github.com/shykes/daggerverse would have a dagger.json at its root, listing all my modules. If a module is not listed in that file, it does not exist in the daggerverse, and loading it should fail (even if there is a subdirectory at that name). This goes beyond what your current PR does, I think, by removing the role of the filesystem completely as module addressing. In the end I don't care so much about the module tree living in the filesystem, or in JSON - I just don't want it to straddle both. That's key to the simplicity, I think.

    Impact on sub-modules

    If modules don't have their own config file, but are configured by a parent configuration, then the tree of sub-modules is centralized in the engine config, instead of being decentralized in each module's directory.

    Impact on dependencies

    This would impact where the dependency tree lives. A module's dependencies would live in the module's entry in the parent configuration.

    Hopefully this section makes sense at least partially :) Thanks for reading this far.

  4. sipsma commented on Jan 22, 2024

    @sipsma
    ContributorAuthor

    @shykes

    I love the simplicity of this formula: module = directory + dagger.json. I worry about losing it. It also has cool corollaries, like "my sub-modules = my sub-directories with dagger.json".

    This is only true today (i.e. before the PR) if you aren't using root.

    If you are using root then the formula is more like module = directory + dagger.json + some parent directory. And my sub-modules = sub-directories of the directory pointed to by root that contain their own dagger.json

    This is just worth noting because the intention around all this is to simplify that case by replacing root with source, but while also leaving the very simple default case where root isn't being used today alone and as simple as it was before.

    We don't have to keep the formula, necessarily. But we must keep the simplicity. What new formula would come with your proposed design, and is it simple enough? It now, can we make it simpler?

    I'd actually say that the formula is just module = directory tree containing dagger.json + subpath.

    To explain, it might actually help to make a comparison with how golang modules work.

    Say you in your go code import a package like github.com/dagger/dagger/some/pkg:

    • The go.mod for that package may be in some/pkg or any of the parent directories, up to the root of the repo.
      • The go tooling handles doing the "findup" for you though, you just specify the git repo + subpath
    • So essentially the formula there is go module = directory tree containing go.mod + subpath

    Our behavior is essentially the same, just replace go.mod with dagger.json.

    e.g. if you run dagger functions -m github.com/shykes/daggerverse/mymod, then:

    • The dagger.json for that module may be in mymod or any of the parent directories, up to the root of the repo.
      • The dagger tooling handles doing the "findup" for you though, you just specify the git repo + subpath in your module ref

    In your design, what does host().directory() map to? The module's source directory, or the directory holding its dagger.json?

    The workdir of a module starts at the module's source directory; this is unchanged from the previous behavior.

    The directory up to dagger.json is available too, just at parent paths (also same behavior as before, except it was instead "the directory up to where root pointed to).

    There's been discussion about this a few times and while it's not 100% clear cut, each time so far we've come to the conclusion that it's probably better to have the workdir set to the source code directory since it allows you to reference paths in your module's source code that are actually relative to the source code file you are authoring.

    • e.g. in your module source code if you wrote host().directory("./some/path") then ./some/path is relative to the file you are actually authoring, no mental path arithmetic needed.

    This is similar to other tools like go test that have the same behavior of making the workdir of code being executed set to the dir containing the source file (cc @vito who made that very nice comparison).

    Should I always use one directory or the other for introspection? Or does it depend on the use case? What is the rule?

    If I understand the question, it just depends on the layout of your repo and where the files you want to load are located. That is more of a factor of the user's particular use case and the existing structure of their monorepo. The main thing is that you can reference those paths relative to the module's source code file (as described above).

    While we're at it, can we deprecate host().directory() for this purpose, and encode the answers above into an API?

    It's certainly possible, but we'd end up essentially just renaming the API, with the behavior otherwise being the same.

    I.e. assuming we rename Host->Local, then calls that introspect would look like:

    dag.Local().File("../dir/somefile.txt")
    // or
    dag.Local().Directory("./some/subdir")

    Those look pretty reasonable to me, so I'm not sure if we get much out of changing the API names more than that.

    can I use dagger.json to configure my home directory?

    I have been imagining that dagger.json is reserved for "static author-specified" configuration, and that support for "runtime caller-specified" configuration would just be a different file+mechanism.

    I see the appeal of unifying the two if feasible, trying to imagine how the details would work out though.

    If you have a dagger.json in your home directory with some module named foo specified and pointing to github.com/org/daggerverse/foo, then would you run:

    1. dagger call -m foo (with configuration to your call in ~/dagger.json applied) ?
    2. dagger call -m github.com/org/daggerverse/foo (with configuration to your call in ~/dagger.json applied)?

    What happens if you there's configuration in both a ~/dagger.json and the dagger.json in the root of a git repo for a module you execute? Are both applied? Overlayed? Etc.

    I don't have a fully formed opinion yet here, just asking more questions to clarify what you were imagining for now.

  5. shykes commented on Jan 23, 2024

    @shykes
    Contributor

    I love the simplicity of this formula: module = directory + dagger.json [...]

    This is only true today (i.e. before the PR) if you aren't using root [...]

    Yes, you're right.

    To explain, it might actually help to make a comparison with how golang modules work [...]
    Our behavior is essentially the same, just replace go.mod with dagger.json.

    • The dagger tooling handles doing the "findup" for you [...]

    Yes, I do like the "auto-findup" behavior, I agree we should do that.

    There is one notable difference though: Go has both module and package, but Dagger only has module, which sort of combines both concepts.

    The workdir of a module starts at the module's source directory; this is unchanged from the previous behavior.

    The directory up to dagger.json is available too, just at parent paths (also same behavior as before, except it was instead "the directory up to where root pointed to).

    There's been discussion about this a few times and while it's not 100% clear cut, each time so far we've come to the conclusion that it's probably better to have the workdir set to the source code directory since it allows you to reference paths in your module's source code that are actually relative to the source code file you are authoring.

    Granted I was in a noisy cafe last time I heard this discussed, and couldn't properly share my thoughts, but for the record I still strongly believe this should be changed before launch.

    • e.g. in your module source code if you wrote host().directory("./some/path") then ./some/path is relative to the file you are actually authoring, no mental path arithmetic needed.

    I propose module().source().directory("./some/path") which 1) doesn't require mental path arithmetic either, and 2) makes it clear and explicit what you are getting: the module's source directory.

    This is similar to other tools like go test that have the same behavior of making the workdir of code being executed set to the dir containing the source file (cc @vito who made that very nice comparison).

    I understand the appeal (make also comes to mind, its workdir is set to the directory containing the Makefile). But I think our situation is different than go test and make in one important way: a Dagger module has both a source directory and context directory, and the module may need to introspect both.

    it just depends on the layout of your repo and where the files you want to load are located. That is more of a factor of the user's particular use case and the existing structure of their monorepo. The main thing is that you can reference those paths relative to the module's source code file (as described above).

    I think that can be distilled into these two rules:

    1. To access your module source, for example to read a template or script used by your code, open host().directory(".")
    2. To access your module "context" (the directory containing dagger.json), open host().directory(REVERSE_MODULE_PATH), where REVERSE_MODULE_PATH is something like ../../..: the path from the module source up to the enclosing dagger.json.

    A few problems with this:

    • What the module can access, and at what relative path, depends on where its source code lives in the enclosing context dir. That feels brittle and opaque to me. It's a very common feature of artisanal build scripts, and I can't say I miss it.
    • The module source and its context directory may not always be authored by the same people (eg. team-specific modules in a multi-team monorepo). This amplifies the brittleness of accessing context directory by relative path to source.
    • If context and source directories are different, it's not intuitive that host().directory(".") would point to one vs. the other. For example if my app repo has a dagger.json configuring a module at ./ci, it would be equally reasonable IMO, to expect host().directory(".") to return the either the repo root, or ./ci.
    • host().directory(".") now mean very different things inside and outside a Dagger function; which adds a pebble in the shoe of devs porting their custom client to functions.

    While we're at it, can we deprecate host().directory() for this purpose, and encode the answers above into an API?

    It's certainly possible, but we'd end up essentially just renaming the API, with the behavior otherwise being the same.

    To clarify, I am not talking about deprecating host.directory() (poor choice of words on my part). I'm talking about not using it for the purpose of introspecting module source code. Whether we deprecate or rename that particular host API call, is orthogonal.

    can I use dagger.json to configure my home directory?

    I have been imagining that dagger.json is reserved for "static author-specified" configuration, and that support for "runtime caller-specified" configuration would just be a different file+mechanism.

    That was my assumption also, but this thread is pulling me in a different direction at the moment 😁

    I see the appeal of unifying the two if feasible, trying to imagine how the details would work out though.

    If you have a dagger.json in your home directory with some module named foo specified and pointing to github.com/org/daggerverse/foo, then would you run:

    1. dagger call -m foo (with configuration to your call in ~/dagger.json applied) ?
    2. dagger call -m github.com/org/daggerverse/foo (with configuration to your call in ~/dagger.json applied)?

    I think both would work.

    • I love that this would enable configurable short names, that would be very convenient.
    • In both cases, both ~/dagger.json and github.com/org/daggerverse/dagger.json would be applied, per the usual find-up system.

    What happens if you there's configuration in both a ~/dagger.json and the dagger.json in the root of a git repo for a module you execute? Are both applied? Overlayed? Etc.

    I think they would be overlayed, to allow 1) publishers to configure their modules, and 2) consumers to override them locally.

    I don't have a fully formed opinion yet here, just asking more questions to clarify what you were imagining for now.

    And it's very appreciated :)

  6. sipsma commented on Jan 24, 2024

    @sipsma
    ContributorAuthor

    (just getting back on one point to start)

    I propose module().source().directory("./some/path") which 1) doesn't require mental path arithmetic either, and 2) makes it clear and explicit what you are getting: the module's source directory.

    Working through what this (and the related suggestions) would look like concretely so I can be 100% sure we're on the same page (please bear with the pedantic minutia):

    ├── .git/
    └── subdir
        ├── dagger.json
        ├── go.mod
        ├── go.sum
        └── otherdir
            └── foo.txt
        └── mymod
            └── main.go
            └── modsubdir
                └── bar.txt
    

    In that case the "context dir" is subdir and the "source dir" is subdir/mymod (relative to the context dir, it is ./mymod).

    When the module executes, the container it runs in mounts the context dir to /mnt (noting so I can be maximally concrete below).

    • (technically the dir we use today is /src, but avoiding that because the name is confusing in this discussion and the name doesn't fundamentally matter, could be /fjfkdla for all we care.)

    So in the container it would look like:

    /
    └── mnt
        ├── dagger.json
        ├── go.mod
        ├── go.sum
        └── otherdir
            └── foo.txt
        └── mymod
            └── main.go
            └── modsubdir
                └── bar.txt
    

    In what you're proposing (iiuc), the process's cwd (i.e. ".") would be the context dir, so absolute path /mnt. And the module source directory would be available at ./mymod.

    Thus dag.Host() would have the following behavior

    • Context directory:
      • dag.Host().Directory(".")
    • Source directory
      • dag.Host().Directory("./mymod")
    • foo.txt
      • dag.Host().File("./otherdir/foo.txt")
    • bar.txt
      • dag.Host().File("./mymod/modsubdir/bar.txt")

    You're additionally suggesting that there would also be a dag.Module().Source() API, such that:

    • Context directory:
      • N/A
    • Source directory
      • dag.Module().Source().Directory(".")
    • foo.txt
      • N/A
    • bar.txt
      • dag.Module().Source().File("./modsubdir/bar.txt")

    Is this accurate in terms of your suggestion?


    If so, my main hesitation is that it just feels asymmetric that for the context dir you use dag.Host and the source dir you use dag.Module().Source.

    What would you think about these tweaks:

    • dag.CurrentModule().Context().Directory(".") - refer to the context directory
    • dag.CurrentModule().Source().Directory(".") - refer to the source directory

    (I switched to CurrentModule because that's an api that already exists for a module to refer to itself).

    In this scenario, .Context() and .Source() would refer to the "frozen" snapshot of the respective dirs as they were loaded into the engine.

    Given the above, I'd also be okay with the module process's current working directory changing to be the context directory since it becomes less relevant.

    The last wrinkle in all of this is the question around whether dag.Host().Directory even needs to exist at all anymore if we go with the above.

    The technical difference is that dag.Host().Directory by its nature refers not to the frozen snapshot but to the actual live filesystem in the container, including any changes that may have been made to it during module function execution.

    On one hand, it's extremely appealing to just disregard this and say that a module can never refer to files created/modified during execution. That would actually allow us to potentially just remove dag.Host() from the API presented to modules entirely and solve a bunch of problems at once.

    The counter-argument is that there are pretty compelling use cases for being able to create/modify files in function code directly and then use them in the dagger API.

    • Namely, the fact that modules allow you to just write code and use existing language-specific libraries directly, completely independent whether they call the dagger API, is one of their superpowers imo.
    • E.g. if your language has some library that expects to create files or operate on existing ones, you don't have to jump through a bunch of hoops to wrap the library up in an executable, put that in a Container and call WithExec.
      • Instead, you can just import the library and use it directly in the function. And now that functionality is magically available to any dagger CLI user or dagger module author in any other language.

    So my preference would be that:

    • dag.CurrentModule().Context() and dag.CurrentModule().Source() are the "goto" simple APIs typically needed for any of these use cases.
    • dag.Host().Directory() is still available, but only needed in more advanced cases where function really wants to refer to live changes made in the container
    • The process's current working directory can just be the context dir (though I am not strongly opinionated on this in particular, it becomes more arbitrary to me now, could even just be some scratch dir)

    I'd also not strongly object if others have a preference for ignoring the dag.Host().Directory use-case in the short term since this is one thing we can backwards-compatibly add in the future.

    I'll stop ranting here to checkpoint, let me know what you think.

  7. sipsma commented on Jan 24, 2024

    @sipsma
    ContributorAuthor

    RE: consolidating runtime+author configuration into dagger.json

    Know you have some more ideas here we're gonna sync up on, just working through the idea in detail myself ahead of time.


    (I'm gonna be adding details here for the sake of getting the point across, not fully coherent)

    Say there's a module at github.com/org/daggerverse/hugo that has functions for building static hugo-based websites based on a caller-provided directory of the website's source code.

    The layout of the github.com/org/daggerverse is:

    ├── assets
    │   └── sample-site
    ├── dagger.json
    └── hugo
        └── main.go

    Sketch of that module's code at ./hugo/main.go:

    package main
    
    func New(
    	// the source code of the website to build with hugo
    	// +optional
    	websiteSource *Directory,
    	// some api key we need for some reason
    	apiKey *Secret,
    ) Hugo {
    	if websiteSource == nil {
    		websiteSource = dag.CurrentModule().Context().Directory("./assets/sample-site")
    	}
    	return Hugo{
    		WebsiteSource: websiteSource,
    		APIKey:        apiKey,
    	}
    }
    
    type Hugo struct {
    	WebsiteSource *Directory
    	APIKey        *Secret
    }
    
    // the directory containing the built site assets
    func (m *Hugo) Built() *Directory {
    	// do things with m.WebsiteSource ...
    }
    
    // the directory containing the built site assets
    func (m *Hugo) Container() *Container {
    	// put Built into a container with a webserver or whatever
    }
    
    // etc.

    dagger.json has contents:

    {
      "modules": [
        {
          "name": "hugo",
          "sdk": "go",
          "source": "./hugo"
        }
      ]
    }

    Now let's say that I'm a caller of that module. On my local machine ~/dagger.json has contents:

    {
      "modules": [
        {
          "name": "hugo",
          "source": "github.com/org/daggerverse/hugo",
          "defaultArgs": {
            "website-source": "/home/me/my-cool-site",
            "api-key": "file:/home/me/.hugo-api-key"
          }
        }
      ]
    }

    Now I can run things like this for example:

    • dagger call -m hugo -o /tmp/site built
      • get the built site assets locally at /tmp/site
    • dagger call -m hugo container publish docker.io/me/my-site
      • build the site into a container and publish it to that registry
    • dagger call -m hugo container up
      • serve the website on my localhost

    The behavior is such that:

    • I specified -m hugo and am not locally in a module subdirectory, so the CLI defaults to ~/dagger.json and finds a module named hugo, uses the source there, etc.
    • The defaultArgs key in dagger.json applies to module constructors
    • defaultArgs has the same semantics as the CLI in terms of conveniences like providing args of type Directory as a local path, secrets as file:..., etc.

    I also like that this could probably give us a path to:

    • Support default values read from env vars for any string
      • Though we'd need to be sure that they don't allow remote modules to magically get access to caller env vars, if defaultArgs is set in the dagger.json of a module in a git module.
      • Also not entirely sure what the syntax would be here, but can save this for a separate thread, point is maybe there's a path now.
    • Configuring SDKs w/ config settings like GOPROXY, various secrets that might be needed, etc. which comes up from enterprise use-cases all the time.

    Overall I really like many aspects of this, a few places of minor concern/questions:

    defaultArgs on module dagger.json configs

    I purposely left out defaultArgs from the dagger.json of hugo in the github.com/org/daggerverse repo.

    The reason is that modules already have a way of specifying/handling default arg values in the code itself. While it certainly could be logically coherent to have defaultArgs in the dagger.json of the hugo module, I don't love that it would mean there's now multiple different ways for a module to define defaults.

    • Not a dealbreaker at all, but all else being equal it's always nice when there's only one way to do things.

    If we did support defaultArgs on the dagger.json of modules like hugo, then we'd also need to decide how to handle default values of secrets without compromising security (either don't allow it or go full blown trust model).

    Ambiguities around -m <name> and behavior in local module dirs

    There's gonna be a bunch of dumb corner cases around e.g. -m hugo and whether hugo is referring to a module at a local relative path hugo or a module named hugo the "find-up" dagger.json.

    I highly suspect we could deal with those in an intuitive way for 99.9% of cases, just something we'll need to be careful about.

    And actually now that I type this out loud, those ambiguities exist to an extent in the also dumb corner case of github.com/org/repo/module referring to a git repo or a local dir that happens to be named that. So not actually a new problem overall.

  8. helderco commented on Jan 24, 2024

    @helderco
    Contributor

    So my preference would be that:

    • dag.CurrentModule().Context() and dag.CurrentModule().Source() are the "goto" simple APIs typically needed for any of these use cases.
    • dag.Host().Directory() is still available, but only needed in more advanced cases where function really wants to refer to live changes made in the container

    That looks golden to me! 👍

    Even though you can get source from a subdir of context, you don’t have to rely on a relative path that can change. However, some times you do need to have that information, many times statically (e.g., in a go.mod), but I’d like to have a way for the API to tell me the relative path between them. Could be just .Source().Path(ctx) (or .Source().Directory().Name(ctx)).

    • The process's current working directory can just be the context dir (though I am not strongly opinionated on this in particular, it becomes more arbitrary to me now, could even just be some scratch dir)

    I prefer it to be the context dir, thinking of the times I’d want to use dag.Host() instead of the other ones. It also makes you rely more on .CurrentModule.Source() when that’s what you need.

    I'd also not strongly object if others have a preference for ignoring the dag.Host().Directory use-case in the short term since this is one thing we can backwards-compatibly add in the future.

    Rather than deprecating it only on modules, I say leave it to documentation. It may ease transition too, especially if the context is the workdir (assuming lots of usage for calling on a subdir like dagger run go run ./ci/main.go).

    The worry is that people will leave that part instead of changing, but if the docs overwhelmingly show using CurrentModule().Context(), CurrentModule().Source() and Directory as an arg, I’m hopeful that it’ll catch on.

    Of course there’s the renaming to .Local() idea that deprecates .Host() (still allowing smoother transition), but letting the user know this should be changed, so now you make a choice.

    I also like that this could probably give us a path to:

    • Support default values read from env vars for any string
      • Though we'd need to be sure that they don't allow remote modules to magically get access to caller env vars, if defaultArgs is set in the dagger.json of a module in a git module.
      • Also not entirely sure what the syntax would be here, but can save this for a separate thread, point is maybe there's a path now.
    • Configuring SDKs w/ config settings like GOPROXY, various secrets that might be needed, etc. which comes up from enterprise use-cases all the time.

    🙌

    Can also be used for global excludes, since everyone uses different tools that leave all sorts of files around.

    The global config file could also be used for engine wide configs, like passing on proxy env vars to the engine itself. They could be two different files though.

    Can be managed with dagger config. There’s lots of tools that do this. Git comes to mind (global and local configs). Hatch, which is the project manager we use on the Python SDK, also has this kind of project specific defaults in the global configuration.

    defaultArgs on module dagger.json configs

    I purposely left out defaultArgs from the dagger.json of hugo in the github.com/org/daggerverse repo.

    Yeah, whenever I talk about a config file to make the CLI calls simpler, it’s always a runtime thing, not authoring.

    However, for project specific configs I usually think about a file placed where the user most likely makes the dagger calls from (the “app", not the module), that can be committed to git for sharing, and it includes all args and flags (using viper for this). But both can work, so the CLI can use global defaults (e.g., excludes, secrets, env vars to pass to the runtime container), project specific defaults in git (e.g., default args) and still be able to override with CLI args (again, viper makes this easy, including accessing nested keys matching the call chain).

  9. shykes commented on Jan 25, 2024

    @shykes
    Contributor

    We discussed this live with @sipsma today, and made some good progress. Here is a summary below:

    • dag.Host().Directory(".") should stay, but map to a scratch directory.
    • [Follow-up note]: maybe we sandbox this to only the scratch directory, ie. / and . would both return the scratch. This avoids leaking internal details about the runtime container, which feels "dirty" to me. From there, maybe it becomes dag.Workdir().Directory(")", just saying :)
    • dag.CurrentModule().Source().Directory("."): works great. SH note: I want to bikeshed the exact API here, to make it shorter :) But that can wait
    • dag.CurrentModule().Context(): not a thing, we cut it. Rationale: there is no clear use case for a module author to introspect that directory. And it opens a backdoor to a "shadow API", if the module is loaded from a monorepo that also contains app source code, and the module relies on that as a default value, for example. No strong benefit + clear strong downsides = cut it.
    • However SDKs do need to receive the context directory where a module was configured, and the path of the source directory within that. That way, the Go SDK can honor shared go.mod, etc. This is done as proposed by Erik, using a source field etc. But only exposed to SDKs, not to functions for introspection (see previous point)
    • We discussed the idea of "codeless modules": what if you could dagger install modules without having to write code? This would add pinned dependencies in dagger.json the usual way, but the sdk and source fields would not be set. dagger call would support looking up dependencies by short name. So dagger install github.com/shykes/daggerverse/tailscale would install a pinned version of that module to the current dagger.json (which could be in my home directory or app repo), then dagger call -m tailscale would call the exact pinned version I installed. Later, if I want to add code to my module, I add the sdk field (command TBD here), and my same dependencies are codegened the usual way. This makes for a smoother learning curve.
    • In this scenario, I worry that having dependencies + modules creates confusion: there are sub-modules, and there are dependencies, they are similar but different. But maybe I am overthinking it - we ran out of time and couldn't resolve that. It feels like we're really close though
    • I also pitched an alternative to default args for fixing the "end-user convenience" problem. One design for solving auth convenience; and another for solving "implicit workdir access". I will write this down elsewhere :)

    @sipsma let me know if I missed anything

  10. sipsma commented on Jan 25, 2024

    @sipsma
    ContributorAuthor

    Yeah I'm very happy with where we landed in terms of Context dir not being a thing except to SDKs, considering that whole side of things to be closed 🙂

    • We discussed the idea of "codeless modules": what if you could dagger install modules without having to write code? This would add pinned dependencies in dagger.json the usual way, but the sdk and source fields would not be set. dagger call would support looking up dependencies by short name. So dagger install github.com/shykes/daggerverse/tailscale would install a pinned version of that module to the current dagger.json (which could be in my home directory or app repo), then dagger call -m tailscale would call the exact pinned version I installed. Later, if I want to add code to my module, I add the sdk field (command TBD here), and my same dependencies are codegened the usual way. This makes for a smoother learning curve.
    • In this scenario, I worry that having dependencies + modules creates confusion: there are sub-modules, and there are dependencies, they are similar but different. But maybe I am overthinking it - we ran out of time and couldn't resolve that. It feels like we're really close though

    Been wracking my brain over this for a while trying to get the pieces to fit together... trying out something:

    User runs dagger mod init (no args). A dagger.json is created that is empty, i.e. {}.

    User runs dagger mod install github.com/foo/bar/[email protected]. dagger.json is updated to:

    {
      "dependencies": [
        {
           "name": "tailscale",
           "source": "github.com/foo/bar/[email protected]"
        }
      ]
    }

    User can now run dagger call -m tailscale ....

    User now wants to write module code using the current dependencies in the dagger.json. They run dagger mod update --name mymod --sdk go, dagger.json now looks like:

    {
      "name": "mymod",
      "sdk": "go",
      "source": ".",
      "dependencies": [
        {
           "name": "tailscale",
           "source": "github.com/foo/bar/[email protected]"
        }
      ]
    }

    And the module source code (i.e. main.go and codegen) is placed in the same dir as the dagger.json.

    Now you can do dagger call -m mymod ... to call your own functions. dagger call -m tailscale ... still works too though.

    Now to get to a more complicated but totally valid use case, say you want to add another local module that's in a subdir and used by mymod.

    • E.g. maybe in this context you are in a local git repo checkout that you intend to push and need multiple modules in it.
    • Or e.g. maybe this dagger.json is in your home dir but you want to add a new module just on your machine and use it, etc.

    This would be done via dagger mod init -m ./some/subdir --sdk go --name othermod. dagger.json is updated to look like:

    {
      "name": "mymod",
      "sdk": "go",
      "source": ".",
      "dependencies": [
        {
           "name": "tailscale",
           "source": "github.com/foo/bar/[email protected]"
        },
        {
           "name": "othermod",
           "sdk": "go",
           "source": "./some/subdir"
        }
      ]
    }

    Now say othermod needs some other dependency, you could run dagger mod install -m othermod github.com/foo/bar/[email protected]. -m othermod indicates you are adding a dep specifically to othermod. dagger.json now looks like:

    {
      "name": "mymod",
      "sdk": "go",
      "source": ".",
      "dependencies": [
        {
           "name": "tailscale",
           "source": "github.com/foo/bar/[email protected]"
        },
        {
           "name": "othermod",
           "sdk": "go",
           "source": "./some/subdir",
           "dependencies": [
             {
                "name": "hugo",
                "source": "github.com/foo/bar/[email protected]"
             }
           ]
        }
      ]
    }

    Basically, the idea is that dependencies is the same struct "all the way down", if that makes any sense.

    The important property that's retained with this sort of approach is that each module can have its own list of dependencies. In the "monorepo of many modules" use case, I think this is important. You don't necessarily want each module to have the same set of dependencies just because they are in the same dagger.json. They might not need the same deps or may even need some overlapping set of deps but at different versions.

    There are warts remaining in this, namely:

    1. It's not clear that it would be possible to dagger call -m hugo .... Basically, dagger call -m would be limited to "top-level" modules in the dagger.json (i.e. mymod, tailscale and othermod in the example above)
      • I honestly think this is probably okay, we're reaching the point of obscurity here. If we really really wanted to figure out a syntax to support this, it's probably possible though, just dubious in terms of benefits.
    2. We want some sort of recursion limit on how deep nested dependencies could go. I can imagine how it would be implemented to arbitrary depth, but it would allow our users to get into situations that are so confusing it might be safer to just stop it early.

    Here's one alternative that I'm considering that trades the "recursive dependencies key" for separate dagger.json files.

    The idea is that you'd have local modules like othermod always get their own dagger.json separate from the "parent" one, with the parent one just pointing to the child one and relying on "find-up" behavior from there.

    So in that case, the "top-level" dagger.json would look like:

    {
      "name": "mymod",
      "sdk": "go",
      "source": ".",
      "dependencies": [
        {
           "name": "tailscale",
           "source": "github.com/foo/bar/[email protected]"
        },
        {
           "name": "othermod",
           "source": "./some/subdir"
        }
      ]
    }

    And there would also be a dagger.json in ./some/subdir that looks like:

    {
      "name": "othermod",
      "sdk": "go",
      "source": ".",
      "dependencies": [
         {
            "name": "hugo",
            "source": "github.com/foo/bar/[email protected]"
         }
       ]
    }

    The CLI+engine would handle all the complication around the "find-up" behavior, so I believe it could be hidden from users for the most part, but the tradeoff being more dagger.jsons.

    Honestly, now that I type this out, I might like this one a little bit better surprisingly? It feels a little more cohesive. The recursive dependencies is kind of a scary wart in the other approach, though the extent to which it actually complicates things in practice is not entirely clear to me yet.

    EDIT: I just remembered that this greatly complicates the case where the module in a subdir has deps on other modules in the repo... 🤦‍♂️ Essentially brings us back to root or close equivalents. So maybe not....

  11. shykes commented on Jan 26, 2024

    @shykes
    Contributor

    Honestly, now that I type this out, I might like this one a little bit better surprisingly? It feels a little more cohesive. The recursive dependencies is kind of a scary wart in the other approach, though the extent to which it actually complicates things in practice is not entirely clear to me yet.

    Yes I agree.

    EDIT: I just remembered that this greatly complicates the case where the module in a subdir has deps on other modules in the repo... 🤦‍♂️ Essentially brings us back to root or close equivalents. So maybe not....

    :( Can you elaborate on how it complicates it?

  12. shykes commented on Jan 26, 2024

    @shykes
    Contributor

    Throwing this at the wall: an example of a repo with many modules, that need to share the same go.mod for policy reasons.

    {
     "dependencies": [
      {
        "source": "./go"
        "context": "."
      },
      {
       "source": "./tailscale",
       "context": "."
      },
     ]
    }

    The point is that the parent can specify an optional context directory to be passed to each dependency's SDK, in the manner that we already discussed. This way, no path ever needs to include ... And, we no longer need a distinct modules key: everything can be under dependencies, and every module can have its own dagger.json without breaking the model.

  13. sipsma commented on Jan 26, 2024

    @sipsma
    ContributorAuthor

    :( Can you elaborate on how it complicates it?

    I'll run through concrete examples again to try to explain (and maybe see if there's a way to make it work):

    Use case here is say you are daggerizing an existing monorepo and will be adding multiple modules to it and those modules have deps

    User runs dagger mod init (no args) in the root of a repo (as checked out to their local machine). A dagger.json is created that is empty, i.e. {}.

    User runs dagger mod init -m ./somedir/modA --name=mod-a --sdk=go.

    The top-level dagger.json is updated to be:

    {
      "dependencies": [
        {
           "name": "mod-a",
           "source": "./somedir/modA"
        }
      ]
    }

    And another dagger.json is created in ./somedir/modA with:

    {
      "name": "mod-a",
      "sdk": "go",
      "source": "."
    }

    Now they do the same thing but for modB, so they run dagger mod init -m ./otherdir/modB --name=mod-b --sdk=python.

    The top-level dagger.json is updated to be:

    {
      "dependencies": [
        {
           "name": "mod-a",
           "source": "./somedir/modA"
        },
        {
           "name": "mod-b",
           "source": "./otherdir/modB"
        }
      ]
    }

    And another dagger.json is created in ./otherdir/modB with:

    {
      "name": "mod-b",
      "sdk": "python",
      "source": "."
    }

    Now let's say that the user wants modA to depend on modB. The syntax could be dagger install -m modA modB (idea being that -m modA says you are operating on modA and you specifically are installing modB).

    What caused me to hesitate is what the dagger.json updates would be. I specifically don't like the idea of ./somedir/modA/dagger.json now looking like:

    {
      "name": "mod-a",
      "sdk": "go",
      "source": ".",
      "dependencies": [
         {
           "name": "mod-b",
           "source": "../../otherdir/modB"
         }
      ]
    }

    But... I suppose it's not quite as bad as root because the path arithmetic can be entirely hidden from the end user at least 🤷‍♂️ It'd all be automated in the CLI and engine. And we can continue enforce that any paths never escape a .git root to avoid security problems of an e.g. maliciously crafted dagger.json.

    And I suppose another option would be that ./somedir/modA/dagger.json could be unchanged, and instead dagger.json in the root of the repo is instead updates like this:

    {
      "dependencies": [
        {
           "name": "mod-a",
           "source": "./somedir/modA",
           "dependencies": [
             {
               "name": "mod-b",
               "source": "./otherdir/modB"
             }
           ]
        },
        {
           "name": "mod-b",
           "source": "./otherdir/modB"
        }
      ]
    }

    That would avoid a need for any paths to ever have ../ elements.

    The implementation and behavior of that approach in particular is a bit hard to fully piece together though. My instinct would be that in order to fully determine the configuration of a given module, you need to "find-up" not just once but through multiple dagger.jsons.

    That's not awful, though there would still be corner cases, like what if I had dagger.json in my home directory and the local checkout of the repo happened to be a subdir of my homedir? I want dagger install -m modA modB to specifically update the dagger.json of the git repo checkout root, not my homedir (at least in this case).

    • Maybe we could just enforce the rule that we stop the find-up at a .git dir
    • Or you could have an explicit flag for which config dir to stop at, e.g. dagger install --config-dir . -m modA modB
  14. sipsma commented on Jan 26, 2024

    @sipsma
    ContributorAuthor

    Discussed more with @shykes, landed here (gonna use the same example as my last comment to save time):

    Use case here is say you are daggerizing an existing monorepo and will be adding multiple modules to it and those modules have deps

    User runs dagger mod init (no args) in the root of a repo (as checked out to their local machine). A dagger.json is created that is empty, i.e. {}.

    User runs dagger mod init -m ./somedir/modA --name=mod-a --sdk=go.

    The top-level dagger.json is updated to be:

    {
      "root-for": ["./somedir/modA"]
    }

    And another dagger.json is created in ./somedir/modA with:

    {
      "name": "mod-a",
      "sdk": "go",
    }

    Now they do the same thing but for modB, so they run dagger mod init -m ./otherdir/modB --name=mod-b --sdk=python.

    The top-level dagger.json is updated to be:

    {
      "root-for": ["./somedir/modA", "./otherdir/modB"]
    }

    And another dagger.json is created in ./otherdir/modB with:

    {
      "name": "mod-b",
      "sdk": "python",
    }

    Now the user runs dagger install -m modA modB. Top-level dagger.json is unchanged. ./somedir/modA/dagger.json is updated to:

    {
      "name": "mod-a",
      "sdk": "go",
      "dependencies": [
         {
           "name": "mod-b",
           "source": "../../otherdir/modB"
         }
      ]
    }

    Find-up logic in the engine is implemented such that the context dir of a module is the dagger.json that contains the root-for key for the module (or, if there is no such dagger.json, then the context dir is implicitly just the module's source dir). It also handles making sure any .. paths don't escape the context dir.

    For completeness, say you wanted the top-level module to be an actual sdk-full mod. You could do dagger mod config --sdk=go --name=top-level. Top-level dagger.json now looks like:

    {
      "name": "top-level",
      "sdk": "go",
      "root-for": ["./somedir/modA", "./otherdir/modB"]
    }

    And then if you wanted to add a dep on one of the submodules, you'd run dagger mod install -m top-level ./somedir/modA and it would be updated to look like:

    {
      "name": "top-level",
      "sdk": "go",
      "dependencies": [
         {
           "name": "mod-a",
           "source": "./somedir/modA"
         }
      ]
      "root-for": ["./somedir/modA", "./otherdir/modB"]
    }

    EDIT: fixed accidental inclusion of redundant "source": "." field in each dagger.json, which isn't needed since source is always inherently ..

  15. shykes commented on Jan 26, 2024

    @shykes
    Contributor

    Thanks for the writeup! I really like this design.

    Adding some polish bikeshedding as promised:

    • dagger init: Initialize a module
    • dagger install: Install a module
    • dagger doc: Print a module's API documentation
    • dagger call: Call one or more functions
    • dagger run: Run a script that can call functions
    • dagger sdk [go|python|ts]: install an SDK, or print the installed SDK
    • dagger develop: prepare a dev environment for developing functions. Requires installing an SDK.
    • dagger update: Update installed modules and SDK
    • dagger test: Test a module
    • dagger serve: Serve a module's HTTP API
    • dagger login
    • dagger logout
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