From c24f2c212e22fe0c7a29dec61b4a98202466ef77 Mon Sep 17 00:00:00 2001 From: Simon Ser Date: Mon, 13 Dec 2021 10:41:39 +0000 Subject: [PATCH] Only fetch log body when requested If the GraphQL query only fetches the fullURL and not the last128KiB, don't make an extra HTTP request. This allows the user to fetch logs on its own, see e.g. [1]. [1]: https://git.sr.ht/~emersion/dalligi/commit/ac5cc211e2d973a39bbdca746d6ac4af21984556 --- api/graph/resolver.go | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/api/graph/resolver.go b/api/graph/resolver.go index 53ef75d..7d88897 100644 --- a/api/graph/resolver.go +++ b/api/graph/resolver.go @@ -10,12 +10,30 @@ import ( "io/ioutil" "net/http" + "github.com/99designs/gqlgen/graphql" + "git.sr.ht/~sircmpwn/builds.sr.ht/api/graph/model" ) type Resolver struct{} func FetchLogs(ctx context.Context, url string) (*model.Log, error) { + log := &model.Log{FullURL: url} + + // If the user hasn't requested the log body, stop here + if graphql.GetFieldContext(ctx) != nil { + found := false + for _, field := range graphql.CollectFieldsCtx(ctx, nil) { + if field.Name == "last128KiB" { + found = true + break + } + } + if !found { + return log, nil + } + } + // TODO: It might be possible/desirable to set up an API with the runners // we can use to fetch logs in bulk, perhaps gzipped, and set up a loader // for it. @@ -40,14 +58,13 @@ func FetchLogs(ctx context.Context, url string) (*model.Log, error) { return nil, fmt.Errorf("Unexpected response from build runner: %s", resp.Status) } limit := io.LimitReader(resp.Body, 131072) - log, err := ioutil.ReadAll(limit) + b, err := ioutil.ReadAll(limit) if err != nil { return nil, err } - return &model.Log{ - Last128KiB: string(log), - FullURL: url, - }, nil + log.Last128KiB = string(b) + + return log, nil } // Starts a job group. Does not authenticate the user. -- 2.38.5