Skip to content

feat: improve Go SDK to fetch list of objects - #4683

Merged
TomChv merged 3 commits into
mainfrom
feat/go-sdk-list-of-object
Mar 20, 2023
Merged

TomChv merged 3 commits into
mainfrom
feat/go-sdk-list-of-object

Conversation

@TomChv

@TomChv TomChv commented Mar 2, 2023 •

Copy link
Copy Markdown
Member

Changes

Extends Go template capabilities.
Store scalar type private field to return it if it's set by a list execution.
Add test on list of objects.
Add Schema setter and getter to fetch global GQL
types.
Add utility functions to the Go template.
Improve query builder to also parse a list of objects.

Approach

This feature has a simple concept but is actually really hard to implement.
The purpose is to make possible to fetch list of objects.
For the whole context: See #3457.

That implies multiple constraints:

  1. How build the GQL query?

Our current way of building GQL query is simple, each method called adds a level of depth.
For instance: container.ID(ctx) will build the query { query { container { id } } }.

But it's different for array: you cannot do container.EnvVariables(ctx).Name(ctx).
For 2 reasons:

  • You may want to retrieve more than just on the property of the object at the same time so how do you chain those calls?.
  • Most important, the value returned by EnvVariable is an array so no method can be called on it.

As a workaround, the GQL query built on call to array includes all possible scalar fields in it.
For instance: container.EnvVariables(ctx) build: { query { container { envVariables { name value } } } }.


💡 See last section of this comment for a possible workaround.


  1. Each type already has public methods exposed to retrieve its values. Let's take for example EnvVariable.
// A simple key value object that represents an environment variable.
type EnvVariable struct {...}

// The environment variable name.
func (r *EnvVariable) Name(ctx context.Context) (string, error) {...}

// The environment variable value.
func (r *EnvVariable) Value(ctx context.Context) (string, error) {...}

This type is designed to be used as a single value that will directly update the GQL query and execute it.
To fix that, each type stores as privates members its scalar types.

For instance:

type EnvVariable struct {
  name string
  value string
}

And on call to array methods, those private fields will be set so they can be returned instead of executing a GQL query (see usage for more details).
Those private fields are set thanks a temporary data structure with the public field of those values, so it can be Unmarshalled by the query response.

  1. The Go Generation

This was the most challenging part, the Go generator (and probably the Typescript one too) had no way to access the whole GQL schema.

I'm not sure if it is a design problem but I created special methods so I can access any part of the GQL schema in resolvers so I can introspect a high level type from another.
For instance Container can returns EnvVariable but EnvVariable is a whole type too defined at the same level as Container so I could not access its field without going through the whole schema.

I think generators need a complete refactor, as much about Go text templates as the Go code to make that kind of feature naturally possible in the code.

Usage & Result

Test already shows an example of usage and expected result.

I think the DX is acceptable but could be better.
However, it's quite straightforward and the experience is simple:

// Setup container
alpine, err := c.
  Container().
  From("alpine:3.16.2").
  WithEnvVariable("FOO", "BAR").

// Call array method
envs, err := alpine.EnvVariables(ctx)
if err != nil { ... }

for _, env := range envs {
   name, err := env.Name(ctx) // I wish we could suppress the returns of the error + ctx usage since they are useless here
   if err != nil { ... }

   value, err := env.Value(ctx) // I wish we could suppress the returns of the error + ctx usage since they are useless here
   if err != nil { ... }

   fmt.Println(name, value)
}

Limitation

Current changes only support the fetching of Scalar types like String, Boolean, or Int.
As a consequence, it is not possible to fetch data in recursivity.

For instance, you can call project.Extensions() but each returned project will have extensions stored
in the list.

An idea that may improve the DX.

Create a special class or wrapper around arrays to still take benefits of GraphQL by allowing the fetch of only
selected fields, removing the error returns and context usage.

I'm not sure about the design for now but we shall think about it.

Resolves: #3457

@TomChv TomChv self-assigned this Mar 2, 2023
@TomChv

TomChv commented Mar 2, 2023

Copy link
Copy Markdown
Member Author

FIY: After the first check that validates the concept, I plan to add bunch of documentation in the Go Code and the templates

@helderco

helderco commented Mar 2, 2023

Copy link
Copy Markdown
Contributor

Hey @TomChv, can you update the description with the approach you're taking, expected usage and result?

@helderco

helderco commented Mar 2, 2023

Copy link
Copy Markdown
Contributor

Please correct me if I'm wrong, just checking if I understand the approach.

You're storing in a private property (to work as a cache) any value in the response that matches a field (e.g. Container.imageRef). So the usage is the same for lists (passing context, unpacking error), but in general if you make the same chained call twice, you'll get the stored value the second time instead of actually sending the same request twice. The list specific part is just doing the same for each item in any list that's in the response.

@TomChv

TomChv commented Mar 2, 2023

Copy link
Copy Markdown
Member Author

So the usage is the same for lists (passing context, unpacking error), but in general if you make the same chained call twice, you'll get the stored value the second time instead of actually sending the same request twice. The list specific part is just doing the same for each item in any list that's in the response.

Yeah, I would have preferred to directly access the property instead of passing a context and unpacking the error but it's unfortunately not possible because of the current SDK API design :/
Especially because we cannot have a public method and field with the same name.

However, I only store in cache values retrieved as a list so this will not conflict with a singular value that you may want to executes later.

For instance

// Retrieve the list
alpine, err := c.
  Container().
  From("alpine:3.16.2").
  WithEnvVariable("FOO", "BAR").

// Call to method in envs are scoped to these variables and will not conflict with other calls.
envs, err := alpine.EnvVariables(ctx)
name, err := envs[0].Name(ctx)

// Can still exec or do anything, the query will be executed properly
alpine.WithExec(...)
alpine.EnvVariable(...)

@TomChv
TomChv force-pushed the feat/go-sdk-list-of-object branch 2 times, most recently from 6ce1d60 to 2bbdf81 Compare March 8, 2023 23:49
@TomChv
TomChv force-pushed the feat/go-sdk-list-of-object branch from 2bbdf81 to 1bde492 Compare March 15, 2023 17:48

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

Nicely done!

I think it's probably for the best that we end up using the same types with the inner fields pre-populated, even though the ctx and error make it a bit verbose. I wanted to suggest introducing sibling types like type PrefetchedFoo { Field1, Field2 string } and returning that for arrays of Foo, but even that isn't very good because it prevents you from writing a generic function that deals with Foos.

I left some suggestions but free to just merge as-is, they're SUPER nitpicky. (I left them anticipating more suggestions but didn't find any.)

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:

Suggested change
data = data.(map[string]interface{})[k]
data = f[k]

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2001712

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.

same nit:

Suggested change
data = data.([]interface{})
data = f

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice catch! Fixed in 2001712

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.

super nitpick:

Suggested change
q = q.Select("{{ range $v := $field | GetArrayField }}{{ $v.Name }} {{ end }}")
q = q.Select("{{ range $i, $v := $field | GetArrayField }}{{if $i}} {{end}}{{ $v.Name }}{{ end }}")

This should end up with "foo bar" instead of "foo bar ".

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! I was looking for this haha
Fixed in 2001712

@dolanor

dolanor commented Mar 15, 2023

Copy link
Copy Markdown
Contributor

I like it too.
Reading it, it seems I'm getting some ideas to avoid the ctx + error, but I don't have it completely in my head, and I should play with it for real (to see if it is just some idealized idea in my mind or a real thing). I lack time to do that for now so I'm just 👍 this because it is already a big improvement!
Thanks so much!

TomChv added 3 commits March 20, 2023 16:10
Extends Go template capabilities.
Store scalar type private field to return it if it's
set by a list execution.
Add test on list of object.
Add Schema setter and getter to fetch global GQL
types.
Add utility functions to Go template.
Improve querybuilder to also parse list of object.

Resolves: #3457
Signed-off-by: Tom Chauveau <[email protected]>
Signed-off-by: Tom Chauveau <[email protected]>
@TomChv
TomChv force-pushed the feat/go-sdk-list-of-object branch from 1bde492 to 2001712 Compare March 20, 2023 23:24
@TomChv
TomChv merged commit af08b31 into main Mar 20, 2023
@TomChv
TomChv deleted the feat/go-sdk-list-of-object branch March 20, 2023 23:41
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.

🐞 codegen: Handling lists of objects

4 participants