15720: Merge branch 'master' into 15720-fed-user-list
[arvados.git] / lib / controller / federation / list.go
index 7178d7b0aff630bc28834af3042129b4a1e9983b..26b6b254e8e9fbdbb59638ca441412ade5575abb 100644 (file)
@@ -10,6 +10,7 @@ import (
        "net/http"
        "sort"
        "sync"
+       "sync/atomic"
 
        "git.curoverse.com/arvados.git/sdk/go/arvados"
        "git.curoverse.com/arvados.git/sdk/go/httpserver"
@@ -23,6 +24,8 @@ import (
 func (conn *Conn) generated_CollectionList(ctx context.Context, options arvados.ListOptions) (arvados.CollectionList, error) {
        var mtx sync.Mutex
        var merged arvados.CollectionList
+       var needSort atomic.Value
+       needSort.Store(false)
        err := conn.splitListRequest(ctx, options, func(ctx context.Context, _ string, backend arvados.API, options arvados.ListOptions) ([]string, error) {
                cl, err := backend.CollectionList(ctx, options)
                if err != nil {
@@ -32,8 +35,9 @@ func (conn *Conn) generated_CollectionList(ctx context.Context, options arvados.
                defer mtx.Unlock()
                if len(merged.Items) == 0 {
                        merged = cl
-               } else {
+               } else if len(cl.Items) > 0 {
                        merged.Items = append(merged.Items, cl.Items...)
+                       needSort.Store(true)
                }
                uuids := make([]string, 0, len(cl.Items))
                for _, item := range cl.Items {
@@ -41,7 +45,19 @@ func (conn *Conn) generated_CollectionList(ctx context.Context, options arvados.
                }
                return uuids, nil
        })
-       sort.Slice(merged.Items, func(i, j int) bool { return merged.Items[i].UUID < merged.Items[j].UUID })
+       if needSort.Load().(bool) {
+               // Apply the default/implied order, "modified_at desc"
+               sort.Slice(merged.Items, func(i, j int) bool {
+                       mi, mj := merged.Items[i].ModifiedAt, merged.Items[j].ModifiedAt
+                       return mj.Before(mi)
+               })
+       }
+       if merged.Items == nil {
+               // Return empty results as [], not null
+               // (https://github.com/golang/go/issues/27589 might be
+               // a better solution in the future)
+               merged.Items = []arvados.Collection{}
+       }
        return merged, err
 }