1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
15 "git.arvados.org/arvados.git/sdk/go/arvados"
16 "git.arvados.org/arvados.git/sdk/go/httpserver"
19 //go:generate go run generate.go
21 // CollectionList is used as a template to auto-generate List()
22 // methods for other types; see generate.go.
24 func (conn *Conn) generated_CollectionList(ctx context.Context, options arvados.ListOptions) (arvados.CollectionList, error) {
26 var merged arvados.CollectionList
27 var needSort atomic.Value
29 err := conn.splitListRequest(ctx, options, func(ctx context.Context, _ string, backend arvados.API, options arvados.ListOptions) ([]string, error) {
30 options.ForwardedFor = conn.cluster.ClusterID + "-" + options.ForwardedFor
31 cl, err := backend.CollectionList(ctx, options)
37 if len(merged.Items) == 0 {
39 } else if len(cl.Items) > 0 {
40 merged.Items = append(merged.Items, cl.Items...)
43 uuids := make([]string, 0, len(cl.Items))
44 for _, item := range cl.Items {
45 uuids = append(uuids, item.UUID)
49 if needSort.Load().(bool) {
50 // Apply the default/implied order, "modified_at desc"
51 sort.Slice(merged.Items, func(i, j int) bool {
52 mi, mj := merged.Items[i].ModifiedAt, merged.Items[j].ModifiedAt
56 if merged.Items == nil {
57 // Return empty results as [], not null
58 // (https://github.com/golang/go/issues/27589 might be
59 // a better solution in the future)
60 merged.Items = []arvados.Collection{}
65 // Call fn on one or more local/remote backends if opts indicates a
66 // federation-wide list query, i.e.:
68 // * There is at least one filter of the form
69 // ["uuid","in",[a,b,c,...]] or ["uuid","=",a]
71 // * One or more of the supplied UUIDs (a,b,c,...) has a non-local
74 // * There are no other filters
76 // (If opts doesn't indicate a federation-wide list query, fn is just
77 // called once with the local backend.)
79 // fn is called more than once only if the query meets the following
88 // * Each filter is either "uuid = ..." or "uuid in [...]".
90 // * The maximum possible response size (total number of objects that
91 // could potentially be matched by all of the specified filters)
92 // exceeds the local cluster's response page size limit.
94 // If the query involves multiple backends but doesn't meet these
95 // restrictions, an error is returned without calling fn.
97 // Thus, the caller can assume that either:
99 // * splitListRequest() returns an error, or
101 // * fn is called exactly once, or
103 // * fn is called more than once, with options that satisfy the above
106 // Each call to fn indicates a single (local or remote) backend and a
107 // corresponding options argument suitable for sending to that
109 func (conn *Conn) splitListRequest(ctx context.Context, opts arvados.ListOptions, fn func(context.Context, string, arvados.API, arvados.ListOptions) ([]string, error)) error {
111 if opts.BypassFederation || opts.ForwardedFor != "" {
112 // Client requested no federation. Pass through.
113 _, err := fn(ctx, conn.cluster.ClusterID, conn.local, opts)
118 var matchAllFilters map[string]bool
119 for _, f := range opts.Filters {
120 matchThisFilter := map[string]bool{}
121 if f.Attr != "uuid" {
125 if f.Operator == "=" {
126 if uuid, ok := f.Operand.(string); ok {
127 matchThisFilter[uuid] = true
129 return httpErrorf(http.StatusBadRequest, "invalid operand type %T for filter %q", f.Operand, f)
131 } else if f.Operator == "in" {
132 if operand, ok := f.Operand.([]interface{}); ok {
133 // skip any elements that aren't
134 // strings (thus can't match a UUID,
135 // thus can't affect the response).
136 for _, v := range operand {
137 if uuid, ok := v.(string); ok {
138 matchThisFilter[uuid] = true
141 } else if strings, ok := f.Operand.([]string); ok {
142 for _, uuid := range strings {
143 matchThisFilter[uuid] = true
146 return httpErrorf(http.StatusBadRequest, "invalid operand type %T in filter %q", f.Operand, f)
153 if matchAllFilters == nil {
154 matchAllFilters = matchThisFilter
156 // Reduce matchAllFilters to the intersection
157 // of matchAllFilters ∩ matchThisFilter.
158 for uuid := range matchAllFilters {
159 if !matchThisFilter[uuid] {
160 delete(matchAllFilters, uuid)
166 if matchAllFilters == nil {
167 // Not filtering by UUID at all; just query the local
169 _, err := fn(ctx, conn.cluster.ClusterID, conn.local, opts)
173 // Collate UUIDs in matchAllFilters by remote cluster ID --
174 // e.g., todoByRemote["aaaaa"]["aaaaa-4zz18-000000000000000"]
175 // will be true -- and count the total number of UUIDs we're
176 // filtering on, so we can compare it to our max page size
179 todoByRemote := map[string]map[string]bool{}
180 for uuid := range matchAllFilters {
182 // Cannot match anything, just drop it
184 if todoByRemote[uuid[:5]] == nil {
185 todoByRemote[uuid[:5]] = map[string]bool{}
187 todoByRemote[uuid[:5]][uuid] = true
192 if len(todoByRemote) == 0 {
195 if len(todoByRemote) == 1 && todoByRemote[conn.cluster.ClusterID] != nil {
196 // All UUIDs are local, so proxy a single request. The
197 // generic case has some limitations (see below) which
198 // we don't want to impose on local requests.
199 _, err := fn(ctx, conn.cluster.ClusterID, conn.local, opts)
203 return httpErrorf(http.StatusBadRequest, "cannot execute federated list query: each filter must be either 'uuid = ...' or 'uuid in [...]'")
205 if opts.Count != "none" {
206 return httpErrorf(http.StatusBadRequest, "cannot execute federated list query unless count==\"none\"")
208 if opts.Limit >= 0 || opts.Offset != 0 || len(opts.Order) > 0 {
209 return httpErrorf(http.StatusBadRequest, "cannot execute federated list query with limit, offset, or order parameter")
211 if max := conn.cluster.API.MaxItemsPerResponse; nUUIDs > max {
212 return httpErrorf(http.StatusBadRequest, "cannot execute federated list query because number of UUIDs (%d) exceeds page size limit %d", nUUIDs, max)
215 ctx, cancel := context.WithCancel(ctx)
217 errs := make(chan error, len(todoByRemote))
218 for clusterID, todo := range todoByRemote {
219 go func(clusterID string, todo map[string]bool) {
220 // This goroutine sends exactly one value to
222 batch := make([]string, 0, len(todo))
223 for uuid := range todo {
224 batch = append(batch, uuid)
227 var backend arvados.API
228 if clusterID == conn.cluster.ClusterID {
230 } else if backend = conn.remotes[clusterID]; backend == nil {
231 errs <- httpErrorf(http.StatusNotFound, "cannot execute federated list query: no proxy available for cluster %q", clusterID)
235 if remoteOpts.Select != nil {
236 // We always need to select UUIDs to
237 // use the response, even if our
239 remoteOpts.Select = append([]string{"uuid"}, remoteOpts.Select...)
242 if len(batch) > len(todo) {
243 // Reduce batch to just the todo's
245 for uuid := range todo {
246 batch = append(batch, uuid)
249 remoteOpts.Filters = []arvados.Filter{{"uuid", "in", batch}}
251 done, err := fn(ctx, clusterID, backend, remoteOpts)
253 errs <- httpErrorf(http.StatusBadGateway, "%s", err.Error())
257 for _, uuid := range done {
258 if _, ok := todo[uuid]; ok {
264 // Zero items == no more
265 // results exist, no need to
268 } else if !progress {
269 errs <- httpErrorf(http.StatusBadGateway, "cannot make progress in federated list query: cluster %q returned %d items but none had the requested UUIDs", clusterID, len(done))
277 // Wait for all goroutines to return, then return the first
278 // non-nil error, if any.
280 for range todoByRemote {
281 if err := <-errs; err != nil && firstErr == nil {
283 // Signal to any remaining fn() calls that
284 // further effort is futile.
291 func httpErrorf(code int, format string, args ...interface{}) error {
292 return httpserver.ErrorWithStatus(fmt.Errorf(format, args...), code)