Repository navigation
Support interfaces in core + Go SDK modules - #6254
Conversation
|
What a great job and explanation 🚀 Thank you for these helpful comments!
Typescript has a support for interface, it should not be too hard on that side interface IFoo {
hello(): string
sayHi(msg: string): string
}
class A {
hello(i: IFoo): string {
return i.hello()
}
}The small issue is that an interface IFoo {
msg: string
hello(): string
}I think the easiest way to declare an interface from Typescript code would be to add a @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). 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 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. |
|
I'm also leaning towards an abstract class in Python, probably with a 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 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. |
2665efd to
0d1cc01
Compare
|
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.
So the options available to us were:
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.
The reason this solves a bunch of problems is:
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. |
d50de88 to
c41e59d
Compare
bc9fc77 to
4b71c99
Compare
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
(just planting a flag on this TODO since the referenced PR is now merged)
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Neat - thought it might be something like that!
78125aa to
f9c5142
Compare
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
My thinking on defaults in terms of the permutations of "whether obj arg sets default" + "whether iface arg sets default" is:
- Neither sets - doesn't matter
- Both sets defaults of different values - just prefer the interface default since that's what it's "dressed up as" now anyways.
- 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.
There was a problem hiding this comment.
nit: this doesn't seem to be used anywhere currently
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 😄
There was a problem hiding this comment.
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)), nilTrying 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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.)
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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:
- 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)
- 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
left a comment
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
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
}There was a problem hiding this comment.
Yep totally, once we have support for core types this should become possible!
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
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]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
|
@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. |
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:
Duckinterface definition embedsDaggerObject, 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.Mallardmodule (no deps):Crestedmodule (no deps):Pondmodule (no deps):Callermodule (deps onMallard,CrestedandPond):GraphQL + Core API Implementation
Expand
Functionsrather than both those andFieldslike Objects do.Duckinterface from thePondmodule will result in the creation of a graphql object calledPondDuck.IDtype, a correspondingload*FromIDfield under query, etc.load*FromIDquery field is special in that it accepts any object ID as an input (accepts typestring). If the object corresponding to that ID does not match the interface, thenload*FromIDwill error out. Otherwise it allows the id to be loaded as that object and used.idfield 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 objectMallardis implementing an interfaceDuck, then theidfield onDuckwill have graphql type ofDuckIDbut the value returned will be the same as if you calledidonMallard.idconstant and representative of the object itself, which makes conversion of an object between its "concrete" value and various interfaces it implements simple.as*fields to the object that allow converting the object to the interfacePondDuckandMallardin the dependencies will see thatMallardimplementsPondDuckand thusMallardwill automatically get aasPondDuck: PondDuck!field added to it.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
idfields of their own scalar types.According to the graphql spec, the fact that the objects have
idof 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.
idfields 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 benefitThe 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
as*fields to the interface for converting to concrete objects (in addition to theas*fields we add to the concrete objects for converting to the interfaces right now)asMallard: Mallardfield toPondDuckon schema load.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
Mallardautomatically gets aasPondDuck: PondDuck!field on schema load because the server sees that theMallardobject typedef matches thePondDuckinterface 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:
can't match an interface like this:
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
TypeDefkind. They are registered on modules (very similarly to objects) via aWithInterfaceapi. Functions an interface defines are the sameFunctiontype 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%sFromIDquery 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
idfield 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%sFromIDqueries 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%sFromIDand chaining queries from the return value of that call.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:
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
jenniferrather 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
TODO Before Merge
TODO as Follow-ups (will split into issues on merge)
As*fields conflict with existing user-defined fields