Skip to content

Support interfaces in core + Go SDK modules - #6254

Merged
sipsma merged 14 commits into
dagger:mainfrom
sipsma:interfaces
Jan 4, 2024
Merged

sipsma merged 14 commits into
dagger:mainfrom
sipsma:interfaces

Conversation

@sipsma

@sipsma sipsma commented Dec 12, 2023 •

Copy link
Copy Markdown
Contributor

This adds initial support for interfaces: #6213. See that issue for a description of the problems it's solving.

The support here is very much MVP and has a lot of restrictions (mentioned below). However the PR is already borderline too big so I think we can merge with approximately the current feature set and fill in gaps as needed in follow ups.

Example

Expand

The following is what the current integ test for interface is doing (with slight trimming for brevity). It looks very similar to the example from the original issue but with one noticeable difference:

  • The Duck interface definition embeds DaggerObject, which is a new pre-defined interface that comes with the SDK and must be included in any interface used in module type signatures. It enforces that the implementation of the interface is an ID-able object in our dagger API, which is required for interfaces to work.

Mallard module (no deps):

type Mallard struct{}

func (m *Mallard) Quack() string {
	return "mallard quack"
}

Crested module (no deps):

type Crested struct{}

func (m *Crested) Quack() string {
	return "crested quack"
}

Pond module (no deps):

type Pond struct {
	Ducks []Duck
}

type Duck interface {
	DaggerObject
	Quack(context.Context) (string, error)
}

func (m Pond) WithDuck(duck Duck) *Pond {
	m.Ducks = append(m.Ducks, duck)
	return &m
}

func (m *Pond) QuackAll(ctx context.Context) (string, error) {
	var quacks []string
	for _, duck := range m.Ducks {
		quack, err := duck.Quack(ctx)
		if err != nil {
			return "", err
		}
		quacks = append(quacks, quack)
	}
	return strings.Join(quacks, "\n"), nil
}

Caller module (deps on Mallard, Crested and Pond):

type Caller struct{}

func (m * Caller) Test(ctx context.Context) (string, error) {
	return dag.Pond().
		WithDuck(dag.Mallard().AsPondDuck()).
		WithDuck(dag.Crested().AsPondDuck()).
		QuackAll(ctx)
}

GraphQL + Core API Implementation

Expand
  1. Interfaces are defined on Modules similar to how Objects are defined today. The primary difference is that interfaces only define Functions rather than both those and Fields like Objects do.
    • This is because interfaces wrap the APIs of other objects, and once objects are being queried, fields and functions are the same from the consumers perspective.
  2. A Module that defines one or more interfaces will result in a graphql schema being loaded that has graphql objects corresponding to those interface. For example, a Duck interface from the Pond module will result in the creation of a graphql object called PondDuck.
    • These objects look mostly the same as other objects in that they get their own scalar ID type, a corresponding load*FromID field under query, etc.
    • However the load*FromID query field is special in that it accepts any object ID as an input (accepts type string). If the object corresponding to that ID does not match the interface, then load*FromID will error out. Otherwise it allows the id to be loaded as that object and used.
  3. The id field on an interface is also special in that it will return the ID of the underlying object rather than any ID value specialized to the interface. If an object Mallard is implementing an interface Duck, then the id field on Duck will have graphql type of DuckID but the value returned will be the same as if you called id on Mallard.
    • This keeps the id constant and representative of the object itself, which makes conversion of an object between its "concrete" value and various interfaces it implements simple.
      • It may also be beneficial to caching long term (don't want to invalidate cache just because a given object is "dressed up" as a different interface or something like that), especially in the context of ids v2.
    • To implement this, we now include the digest of the module an object originates in its ID value, alongside the existing pattern of including the type name and encoded value
  4. To tie this all together, the graphql server now looks at schemas being loaded, finds all the interfaces an object in the schema implements and automatically adds as* fields to the object that allow converting the object to the interface
    • For example, a schema that has both PondDuck and Mallard in the dependencies will see that Mallard implements PondDuck and thus Mallard will automatically get a asPondDuck: PondDuck! field added to it.
    • See this comment for more background on the benefits of this specific approach

Alternatives Considered

The previous implementation of all this actually used graphql interfaces, creating those for each interface typedef.

This almost worked, but ended up only being possible if we were willing to stray from the graphql spec a little bit, which wasn't worth the cost.

The main problem has to do with the ID fields on objects. The interface needs its own ID scalar type, but it also needs to be implementable by other objects, which all have their own id fields of their own scalar types.

According to the graphql spec, the fact that the objects have id of one scalar type and the interface has it as another means the object can't implement the interface.

There's definitely at least a few ways of working around this, but they all were quite complicated and not worth the effort.

  • For example, we could change all the id fields on everything to just use a single scalar type, but then SDK codegen would need a whole different way of knowing what objects to expect when an ID is used as an arg. There's ways of doing that via directives, but it explodes in complexity for not that much benefit

The only thing we miss out on in the short term in the ability to spread a query on which concrete object is being used to implement a given interface

  • However, we can pretty easily get this ability if ever needed by just adding as* fields to the interface for converting to concrete objects (in addition to the as* fields we add to the concrete objects for converting to the interfaces right now)
  • For example, we could also add a asMallard: Mallard field to PondDuck on schema load.
  • This should theoretically allow you to spread queries on concrete implementations in the same way real graphql interfaces allow you to.

SDK Support - Client Codegen

An SDK depending on a schema that contains interfaces needs to handle them now when running codegen.

The goal is to make this is painless as possible in both the short and long term for SDKs to support

Expand

I'll start by describing the utterly bare minimum an SDK needs to do to handle these, followed by descriptions of the sugar they can progressively layer on top to make them more useful. The ultimate level an SDK gets to will partially be a function of how powerful the type system is in that language (besides just whether the work has been done yet).

NOTE I'll hedge that I'm mostly speaking theoretically here; I sort of went through some semblance of this process w/ the Go SDK but we'll verify it all works out the same for the rest of the SDKs as we work on them (and can make adjustments as needed).

Level 0 (no effort required) - Explicit user conversions of objects to interfaces

As described above, each object typedef that implements a given interface typedef gets a field for converting to that interface. So Mallard automatically gets a asPondDuck: PondDuck! field on schema load because the server sees that the Mallard object typedef matches the PondDuck interface typedef.

As a result, all SDK codegen automatically picks up support for converting objects to interfaces they implement for free.

SDKs in languages that have no notion of duck typing or equivalent concepts will probably max out around here.

Even SDKs in languages that do have some level of duck typing may want to optionally add support similar to this. This is because many type systems, including Go's, don't handle the full possibilities of type matching (mentioned more below).

NOTE: This is approximately where the Go SDK currently is. In a previous iteration I had updated the client codegen to generate actual Go interfaces for interface typedefs, but I very quickly ran into fundamental limitations in Go's type matching that meant the value was pretty limited. Fortunately, this as* approach works around it entirely.

Level 1 - Basic language-native duck typing

In languages that support some notion of duck typing, an actual interface (or whatever it's called) can be generated for the graphql interface definition and used in place of a concrete struct when accepting arg inputs or returning values.

The implementation will most likely still need to generate a private concrete struct exactly as done in the previous levels, but that concrete struct will just be used internally to implement the interface when loading arbitrary (i.e. unknown) objects from an id.

This results in a much more seamless DX for users and compile-time checking, at the potential expense of extra work on the SDK developer and internal complexity.

Level 2 - Advanced language-native duck typing

If the SDK's language supports it, there are certain complex type matching patterns that would be nice to support.

For example, Go doesn't have covariance support, so an object like this:

func (o *Obj) WithFoo(foo string) *Obj { ... }
func (o *Obj) Bar() string { ... }

can't match an interface like this:

type MyIface interface {
  WithFoo(foo string) MyIface
  Bar() string
}

So while it's great if SDKs can support advanced interface matching like this, it's also fine if languages can't; as said earlier the Level 0 support inherently covers explicit object->interface conversions, so level 1+2 are ultimately just some optional sugar on top.

SDK Support - Modules

SDKs can also support use of interfaces when defining modules. Note that that this is technically optional; if an SDK doesn't support it everything would still work, there will just be a feature gap in that users can't accept/return interface types in their module.

Expand

Defining an interface

Interfaces are a just a TypeDef kind. They are registered on modules (very similarly to objects) via a WithInterface api. Functions an interface defines are the same Function type def that can be registered on object type defs.

ID Input+Output

As mentioned in the "GraphQL + Core API Implementation" section above, interfaces are id-able, with the ID being the same value as the ID of the underlying object implementing the interface.

When accepting an interface as an input, the engine will always provide the interface value as an ID. The SDK is expected to use the ID w/ the interface's graphql load%sFromID query to make API calls on the interface.

Similarly, when returning an interface, the SDK should return the ID of the interface (rather than direct json serialization of the object). The ID of the interface is obtained by just querying the id field on the interface in the graphql API.

Note that as of a prereq PR to this one, we now serve a module's own API to itself when it's running (in addition to the APIs of its dependencies), which is why it's possible to make these load%sFromID queries for interfaces defined in the module itself.

Implementation - Self Bindings

Obviously the details of the implementation are up to the SDK, but there's some general considerations worth discussing here.

The implementation of interfaces in a module has a ton of overlap with the implementation of interfaces for client-side codegen. Namely, in both cases an SDK most likely needs to generate a concrete struct representing the interface that handles loading the interface IDs via load%sFromID and chaining queries from the return value of that call.

  • Whether that concrete struct is directly exposed to users or is hidden away depends on the SDK, as discussed in the "SDK Support - Client Codegen" section

This has an interesting implication. Previously, the codegen step for modules only generated bindings to call the module's dependencies. Now, interface support implies that to at least some extent there will also be code generation for bindings to parts of the module's own API too. Namely, the bindings to use objects implementing the interface defined in the module itself.

In the long term, this is not a problem at all. We've intended to support bindings from a module to itself for a while now, so this is just that issue coming to a head for the first time.

In the shorter term, it is a bit of a potential wrench, depending on the SDK.

At the moment, the SDK has to handle all this itself: it needs to see that it's defining an interface and then trigger the codegen for that interface all in the same step.

It's also possible, either in this PR or more likely a follow up, to have the engine help out the SDKs a bit more here. Namely, the engine could either:

  1. Give the SDKs a way of triggering the codegen in two steps such they first generate the module typedefs and then can query the introspection schema again to run the full codegen of both their dependencies and themselves
  2. Give SDKs a way of getting the introspection schema of their module typedefs while still running codegen and then use that to generate self bindings. Basically, keep codegen all as a single step.

And in general there's many more possibilities. I'm curious what @helderco and @TomChv think about all this and whether this requirement is that hard to deal with in Python/Node SDKs. We can figure out the best long-term approach from there.

Go SDK Implementation details

The module-specific codegen part of the Go SDK needed to deal with the above mentioned wrench about self-bindings. There weren't any great short-term options since we haven't added generalized support for self-bindings yet.

So what I went with for now was to only do the self-binding codegen for interfaces specifically. And rather than jump through a ton of hoops to try to trigger the existing client codegen based purely off of typedefs parsed by the Go SDK module code, I just added a step to the module codegen that creates similar looking bindings, but using jennifer rather than templates or anything.

This worked out reasonably well, but does create some duplication between the module-specific codegen and the general client codegen.

As mentioned above, in the long term we were going to need to deal with this issue anyways as part of generalized support for self-bindings, so it's probably best that were being forced to figure this out.

I will wait to see what the other SDK devs think about the whole self-binding issue and figure out our generalized approach there. Based on that we can decide what approach to take w/ the Go SDK in the long term.

TODOs

Current Restrictions

  1. Core types can't implement interfaces yet
    • I just didn't update the implementation to handle loading core IDs; the best approach is to probably unify the loading logic with those of user module object IDs.
    • This is straightforward enough that I may end up including it in this PR, but otherwise it's an easy follow up
  2. In Go, objects from a user's own module can't yet be used to implement an interface
    • This relates to the self-bindings issue described above. Interfaces require an id-able object but in our current implementation objects defined in a module are not id-able from the perspective of that module (they are special cased to always just use direct json serialization rather than serialization to ID)
    • This will be addressed by generalized support for self-bindings

TODO Before Merge

  • More integ tests (basic ones exist and pass though already)
  • Make sure that Python + NodeJS have at least "Level 0" handling of interfaces in client codegen (as mentioned in the "SDK Support - Client Codegen")
    • This is invalidated now with the new approach described in this comment. All SDKs can consume modules that use interfaces at Level 1 inherently now
  • In Go, figure out way of making it possible for an API that has non-required args to match an interface definition (need to deal with the concrete struct that's generated for opts, one way or another)
    • This is also invalidated as part of the new approach, not an issue anymore
  • Merge the graphql repo PR this one is depending on, fix the go.mod in this PR
  • Handle interfaces as outputs in Go SDK, verify the server-side handling works
  • Handle more than just scalars in the interface self bindings created by the go module codegen
  • Smaller cleanup TODOs noted in comments in the code

TODO as Follow-ups (will split into issues on merge)

  • Support core types implementing interfaces (requires consolidating user module IDs and core IDs to be encode-able and decode-able from a common func)
  • Support objects from a users module being passed as interface values (requires generalized self-binding support)
  • Python + NodeJS support for interfaces when authoring modules
  • Fallback option when the As* fields conflict with existing user-defined fields
    • This is obscure enough that it's okay to merge without it, but not obscure enough to ignore indefinitely...

@sipsma
sipsma requested review from helderco, jedevc and vito December 12, 2023 05:23
@TomChv

TomChv commented Dec 14, 2023 •

Copy link
Copy Markdown
Member

What a great job and explanation 🚀 Thank you for these helpful comments!

Give the SDKs a way of triggering the codegen in two steps such they first generate the module typedefs and then can query the introspection schema again to run the full codegen of both their dependencies and themselves

Give SDKs a way of getting the introspection schema of their module typedefs while still running codegen and then use that to generate self bindings. Basically, keep codegen all as a single step.

And in general there's many more possibilities. I'm curious what @helderco and @TomChv think about all this and whether this requirement is that hard to deal with in Python/Node SDKs. We can figure out the best long-term approach from there.

Typescript has a support for interface, it should not be too hard on that side
For example:

interface IFoo {
    hello(): string
    sayHi(msg: string): string
}

class A {
    hello(i: IFoo): string {
        return i.hello()
    }
}

The small issue is that an interface in Typescript can have both field or function, for example this is possible:

interface IFoo {
  msg: string
  hello(): string
}

I think the easiest way to declare an interface from Typescript code would be to add a @interface decorator BUT, it is not possible to set a decorator on an interface so we can use an abstract class instead with some constraint.
For example:

@interface
abstract class IFoo {
   @func
    abstract hello(): string
}

@object
class Module {
    @func
    hello(a: IFoo): string {
        return a.hello()
    }
}

// Add `implements` keyword is optional
@object
class Test  {
    @func
    hello(): string {
        return "hey"
    }
}

const t = new Test()
const m = new Module()

console.log(m.hello(t)) // "hey"

Since an abstract class can have both implemented and abstract methods (and/or fields), we should throw errors in the introspection if the function isn't abstract (or we could just ignore them but I think it's better to notice the user).
That's quite nice because that means actual interface keyword can be reserved for struct argument.

On a generation perspective, it can be tricky if we import multiple modules that both use the abstract class because we should generate it only one time on the final module.
I don't know if this logic is already supported by our generators/modules and it's more or less related to the generation in two steps that you mentioned if I understood well.

I think it's possible in Typescript though, the language is pretty flexible and type system not to constraining (compared to Go). I got some ideas to make it works.
The only part I'm confused about is the generation, I could generate abstract class for GQL interface and this should do the trick but I'm not sure.

@helderco

Copy link
Copy Markdown
Contributor

I'm also leaning towards an abstract class in Python, probably with a @interface decorator (for withInterface), in line with the rest. I'm pretty sure we can do Level 3, I'll prep a short demo to confirm what you mean.

For the generation part, the easiest is to do it in two phases. However, I'm not sure if the self-bindings are really needed in Python. Rather than using a generated copy/duplicate of a local object, I'd want to use the object directly. It's the same idea I've had since the beginning for invoking functions from the same module via the API. To be clear, I've not thought about it too deeply so it's quite possible that I'm not aware of the limitations.

The basic idea is this:

from dagger import function

@function
def foo() -> str:
    return "foo"

@function
def direct() -> str:
    return foo()  # direct call in same interpreter

@function
async def via_api() -> str:
    return await foo.call()  # sends `query { foo { foo } }`

In other words, any function decorated with @function would have itself a function named .call (bikeshed) for making a query to said function. Yeah, python functions are objects and you can attach attributes to them, even other functions.

It feels like there's enough information to be able to trace the data that I need to make that query but I haven't spent enough time flushing it out. Basically use the query builder to produce the query internally that's now possible to do manually. I believe that interfaces would follow the same logic.

@sipsma
sipsma force-pushed the interfaces branch 2 times, most recently from 2665efd to 0d1cc01 Compare December 21, 2023 03:47
@sipsma

sipsma commented Dec 21, 2023 •

Copy link
Copy Markdown
Contributor Author

Just to update: been slowly chipping away at the TODOs (just pushed coverage for more input/output types on interfaces and a bit more test coverage) here. It's not the highest priority thing I'm working on atm but want to keep it moving forward so we can unblock the use cases that need it relatively soon.


I also just had a realization about a pretty nice tweak that could both solve quite a few problems at once and make client-side SDK support even easier than before.

The background is that this current PR relies on a patch to our graphql server to allow assertions on graphql objects implementing graphql interfaces to be done at runtime during query execution.

  • In raw graphql you are supposed to declare that a type implements an interface in the schema and only then can it be used as the object underlying that interface. If you don't declare that it implements the interface, it can't be used, even if the types match

So the options available to us were:

  1. Require that users in their code (across all languages) declare that a given object implements an interface
    • Ruled out cause bad DX and just generally limiting in that we want to support cases where objects implement interfaces that the module authors don't even know about necessarily
  2. When a schema is loaded, determine all the interfaces a given object implements and include those declarations in the final graphql schema
    • Not bad in DX (it's all done on the users behalf, they don't need to do anything), but a decent chunk of extra work
  3. What I went with: assert on the types matching the interface at runtime
    • Easy because we could still just re-use existing utilities in the graphql server code for these assertions.

3 seemed like the most reasonable option at the time, but it turns out that 2 is actually much preferable for a few reasons.

The first reason was pointed out by @vito during a separate chat: not declaring the interfaces an object implements in the schema brings us out of spec w/ graphql and most likely breaks some features in raw graphql clients like e.g. the playground.

That was reason enough to switch but as I was just trying to write some more example code that used interfaces I realized there's also some extremely compelling usability benefits that become possible if we go with 2.

Namely, if we know which interfaces a given object implements, the graphql server can also add fields to the object for explicitly converting to that interface.

  • So e.g. in the example in the PR description, when the Caller module schema is loaded, the graphql server knows that the schema contains the PondDuck interface and that Mallard and Crested both implement it
  • The server can thus add fields to both Mallard and Crested like asPondDuck: PondDuck

The reason this solves a bunch of problems is:

  1. It gets every SDK "Level 1" support for interfaces (as described in the "SDK Support - Client Codegen" section in the PR description) for essentially free.
    • No changes to the SDKs would be necessary beyond just treating graphql interfaces the same as objects in their codegen, which is trivial
    • Support for the levels beyond that would be nice-to-have still, but ultimately only save users a single call to e.g. Mallard.AsPondDuck()
    • It also does this without compromising on type safety. Essentially, our graphql server does the type checking and then only generates the As* fields if the object implements the interface. We don't need to resort to any in Go and even languages with no duck typing at all would still benefit from this checking.
  2. This solves multiple usability problems in Go
    • The problem around the use of concrete structs for optional args in the Go SDK should be dealable with now; the graphql server knows how to check optional args as part of the matching of object to interface.
    • The limitations mentioned in the PR description around Go's lack of covariant type matching (which I've already hit in the more real world examples I was trying to write) are completely avoided, again because the graphql server's type checking can do that

I think this approach is beneficial enough that I'll actually switch to it for this PR rather than a follow up. Besides the fact that Python+Typescript become even easier to support on the client-side, another nice thing is that this approach should actually allow quite a bit of code to be deleted from the Go client codegen changes, so it should be close to a wash in terms of PR bloat.

@sipsma
sipsma force-pushed the interfaces branch 3 times, most recently from d50de88 to c41e59d Compare December 28, 2023 03:18
@sipsma
sipsma force-pushed the interfaces branch 2 times, most recently from bc9fc77 to 4b71c99 Compare January 2, 2024 20:02
@sipsma
sipsma marked this pull request as ready for review January 3, 2024 04:02
@sipsma
sipsma requested review from a team as code owners January 3, 2024 04:02
@sipsma

sipsma commented Jan 3, 2024

Copy link
Copy Markdown
Contributor Author

@vito @jedevc @helderco this is good to review now. I updated the PR description with the modified approach I switched to since the first draft and the follow-ups I'll create issues for once merged.

@vito vito 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.

lgtm!

Being pretty aggressive with my approval here - it'll probably be a painful rebase for #6297, so I'm incentivized to just rip off the band-aid and start on that now. I trust our tests, and the added tests seem pretty exhaustive. I did a review of the non-boilerplate parts and they make sense to me, at least with today's architecture.

edit: also if there are any particular areas you'd like me to take a deeper look at, let me know!

Comment thread core/schema/coremod.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.

(just planting a flag on this TODO since the referenced PR is now merged)

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.

Good catch, went to fix it and then immediately realized it's more complicated than it's worth right now, so just leaving as is and updating the comment. We only need to include the actual functions in the typedef once we want to support core objects matching interface definitions, but that's a follow up TODO anyways.

Comment thread core/typedef.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.

Could probably also compare args without worrying about order, right? Since only the name should matter?

Not sure if that's worth doing now, the only scenario I see it coming up is if an SDK somehow messes up arg order, but for DX reasons we should make sure SDKs are preserving it anyway, and using a different arg order from the interface definition seems like a weird thing for anyone to do intentionally.

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.

True, that's another option. I guess it comes down to whether we want to support matches like this:

  • Object - fn(arg1 string, arg2 int)
  • Interface - fn(arg2 int, arg1 string)

Or matches like this:

  • Object - fn(arg1 string, arg2 int)
  • Interface - fn(blah1 string, blah2 int)

I think it would be an exclusive choice between those; I'm not immediately seeing how we could support both arbitrary name and arbitrary order.

If I was forced to choose now, I'd probably go with order mattering but not name. Can't really justify why fully, I guess it just feels more likely to choose a slightly different name for an arg but still wanting to match than it does to choose a different order of args. But atm it's just not supported so we can decide on that if/when it arises in practice.

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.

This is an interesting pattern - is this relying on the Go SDK runtime container having go installed? Which is a reasonable assumption, just checking since I don't think I've seen this approach before in our module tests.

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.

Yeah the thought process here was that I needed to write a lot of tests, the tests for interfaces inherently required multiple dependencies be loaded at the same time, and that trying to write all of it as raw graphql queries sounded like a nightmare.

Which ended up bringing me to this pattern. I kind of like it? The progress output ends up working out nicely since it's all a nested session (due to how modules work) so you just see essentially the same go test output seen when running any of the other tests.

It also hints at the idea that's been brought up previously of having first-class support for writing module test code; I guess you can think of this as doing "by-hand" what that first-class support would do in the background.

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.

Neat - thought it might be something like that!

@sipsma
sipsma force-pushed the interfaces branch 2 times, most recently from 78125aa to f9c5142 Compare January 4, 2024 02:12
Comment thread core/typedef.go Outdated
Comment on lines 102 to 104

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.

Should default values also apply here? Unsure, but it feels similar to optional - I think it makes sense to tighten it for this, and then as noted above, we can relax over time as we have more use cases.

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.

My thinking on defaults in terms of the permutations of "whether obj arg sets default" + "whether iface arg sets default" is:

  1. Neither sets - doesn't matter
  2. Both sets defaults of different values - just prefer the interface default since that's what it's "dressed up as" now anyways.
  3. Only one or the other sets the default - just use that default

It's extremely subjective and a definite grey area, but that felt most intuitive to me.

The thing about defaults is that they don't actually have to matter for type checking. This is different than optional where it's actually important since an object arg that's non-optional can't be matched with an interface arg that's optional.

Comment thread core/schema/coremod.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: this doesn't seem to be used anywhere currently

Comment thread core/schema/usermod.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.

Potential discussion topic:

I can't remember where I suggested this, but as a possible solution to the conflicts this could cause: could we have all "automagic" fields, like "id", "as*", "load*FromID", etc, use a "" prefix? Then we could enforce that no module may declare it's own "" prefixed fields. (additionally, this works as a nice way to distinguish between internal/non-internal fields, for help methods)

SDKs could remove this prefix on codegen, and in the case of a conflict - would perform some language-specific transformation to remain consistent (e.g. similar to how we handle "from" in python).

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.

Something along those lines is possible for sure.

But I'd really love it if we can find a way of addressing this that's just entirely server-side and results in SDKs being entirely agnostic.

Something like by default, if there's a conflict on AsPondDuck, the graphql server sets a more verbose + obscure name instead like AsPondDuckInterface

  • Obviously kind of meh but this situation is already obscure, so not a huge deal

If there's somehow still a conflict after something like that, then we can either fallback to dumber things like AsPondDuckInterface2 or similar. But an actual case where both AsPondDuck and AsPondDuckInterface are legitimately already taken (and the user isn't just trolling us) feels so obscure that it's on the border of whether we should even care or not probably.

Comment thread core/schema/modifaces.go Outdated
Comment on lines 99 to 100

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: unnecessary case

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.

Just for my understanding: this is so that we can do covariance right? We need to take a concrete struct type and lift it to an interface type. But we also need to do this for slices of concrete to slices of interfaces?

A few comments in this function (or more examples in the docstring) could be helpful here. As an aside - if you know of a "formal" term for what I've just coined "access patterns" then that would be wonderful 😄

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.

We need to take a concrete struct type and lift it to an interface type. But we also need to do this for slices of concrete to slices of interfaces?

Yeah exactly, here's an example chunk of code created by this if it's helpful:

case "WithIfaceList":
  var parent Test
  err = json.Unmarshal(parentJSON, &parent)
  if err != nil {
  	fmt.Println(err.Error())
  	os.Exit(2)
  }
  var ifaces []*customIfaceImpl
  if inputArgs["ifaces"] != nil {
  	err = json.Unmarshal([]byte(inputArgs["ifaces"]), &ifaces)
  	if err != nil {
  		fmt.Println(err.Error())
  		os.Exit(2)
  	}
  }
  return (*Test).WithIfaceList(&parent, convertSlice(ifaces, (*customIfaceImpl).toIface)), nil

Trying to get everything to work just right with Go's json ser/deser while also avoiding things like typed nils was a real headache and the reason why I added what might seem like an excessive number of test cases 😅

A few comments in this function (or more examples in the docstring) could be helpful here.

Yes for sure, will do.

As an aside - if you know of a "formal" term for what I've just coined "access patterns" then that would be wonderful 😄

Honestly I don't mind the name at all 🙂 At least, I can't think of anything better, so unless that changes I think we can stick with it.

Comment on lines 339 to 340

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.

Hm, is this required? The idea is that paramSpec should have the raw type that was actually read from the argument, so we don't need to track this separately.

Maybe it is necessary for use in concreteMethodCode, but I'm not 100% sure why this case is used, and wasn't before.

I guess the same logic applies to isPtr.

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.

Hm, is this required? The idea is that paramSpec should have the raw type that was actually read from the argument, so we don't need to track this separately.
Maybe it is necessary for use in concreteMethodCode, but I'm not 100% sure why this case is used, and wasn't before.

It's necessary now because we need to actually generate code that wraps a type in Optional whereas before all we cared about was marking something as optional in the TypeDef (which is just a bool, so it doesn't matter there whether it's optional due to being wrapped in Optional or due to an //+optional pragma).

The other possibility was to not add hasOptionalWrapper and instead just use paramType and re-run the logic of checking whether that's Optional. But it just felt simpler to have an extra field here since we already did that checking in parseParamSpecVar, may as well just re-use the work done there rather than re-run the logic a bunch of places (and handle if err != nil , etc.)

Comment on lines 138 to 148

@jedevc jedevc Jan 4, 2024 •

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.

Ahhh, I hate being picky without specific suggestions, but...

This structure of code is not particularly easy to understand, especially some of the deeply chained jennifer call later on in this file (notably concreteMethodExecuteQueryCode). Given this code has been proven to be quite delicate in the past, I'm a bit worried of subtle bugs sneaking in at some point. The thought of debugging differences between templates and jennifer having different parts of code does worry me a bit if/when things crop up.

On the other hand, everything else in this PR is really not hard to understand, and the test suite does give me confidence that we've not broken everything 🎉 🎉 I really don't want to block this PR, but I think we should try and tidy this up sooner rather than later (I think part of which is working out whether to bring the templated code into jennifer, or jennifer into the templated code, etc).

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.

Yeah totally, I did the bare minimum cleanup of this code (it was even worse in the first iteration) and then briefly embarked on even more cleanup but just had to back out due to time. I think I see various paths to making it more readable by basically adding a lot more jennifer utils, but I quickly realized that was gonna add another day or two to implementation time, which given our current deadlines was too much.

That's also why I didn't embark on trying to unify everything to jennifer across the whole go sdk (which would be my preference relative to unifying everything to use templates). I will create a follow-up issue, but it's going to be hard to prioritize in the next month I think 😞.

The thought of debugging differences between templates and jennifer having different parts of code does worry me a bit if/when things crop up.

Yeah I have the same concern, but my suspicion was that the alternative of trying to centralize everything to use templates would have:

  1. Been approximately as confusing + convoluted (the template related code is obviously very hard to work with) and would require subtle adjustments to the templates used for go sdk client codegen (which increases blast radius)
  2. Not given us this setup for replacing all the go template code in the client-side w/ jennifer, which I think is the best long term option

So my hope is that this approach at least serves as a bridge to a better future even if there's some semblance of duplication in the meantime

The other consolation here besides the tests I added is that this all only triggers when a Go SDK module uses an interface in its typedefs, so at least its blast radius is also more scoped in that respect too.

@helderco helderco 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.

I don’t foresee any difficulty with implementation in other SDKs. I’m glad you were able to find a solution with a good DX that is able to satisfy the SDK’s type checking while keeping the implementation quite simple due to the server doing most of the work! 🚀

These “dagger interface” object types that are created in the API may be confused with GraphQL interfaces (diff easily documented) but it’s worth it for what we can do in the SDKs.

Excited about the potential here!

Comment thread core/schema/coremod.go Outdated

@helderco helderco Jan 4, 2024 •

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.

Will we finally be able to create a function that accepts any object with a sync function?

type Syncable interface {
    DaggerObject
    Sync(ctx context.Context) Syncable
}

type Foo struct {}

func (m *Foo) SyncAll(ctx context.Context, objs []Syncable) error {
    // error group
}

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.

Yep totally, once we have support for core types this should become possible!

sipsma added 8 commits January 4, 2024 14:16
This is very old and is now more than covered as part of the massive
number of integ tests we have. It also started failing due to not
finding DaggerObject defined, which isn't worth the effort to handle in
the test.

Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
@sipsma

sipsma commented Jan 4, 2024

Copy link
Copy Markdown
Contributor Author

@jedevc I'm gonna merge this once CI is done so I can unblock @vito's efforts to rebase dagql on it asap, but I'll send out updates that add more comments+doc strings to the go sdk code as an immediate follow up PR. I just fear it may actually take a bit to write all that out so not worth blocking this one on it.

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