Merge branch '21642-io-panel-collection-tab-bug' into main. Closes #21642
[arvados.git] / sdk / go / arvados / collection.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package arvados
6
7 import (
8         "bytes"
9         "crypto/md5"
10         "fmt"
11         "regexp"
12         "strings"
13         "time"
14
15         "git.arvados.org/arvados.git/sdk/go/blockdigest"
16 )
17
18 var (
19         UUIDMatch = regexp.MustCompile(`^[a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}$`).MatchString
20         PDHMatch  = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`).MatchString
21 )
22
23 // Collection is an arvados#collection resource.
24 type Collection struct {
25         UUID                      string                 `json:"uuid"`
26         Etag                      string                 `json:"etag"`
27         OwnerUUID                 string                 `json:"owner_uuid"`
28         TrashAt                   *time.Time             `json:"trash_at"`
29         ManifestText              string                 `json:"manifest_text"`
30         UnsignedManifestText      string                 `json:"unsigned_manifest_text"`
31         Name                      string                 `json:"name"`
32         CreatedAt                 time.Time              `json:"created_at"`
33         ModifiedAt                time.Time              `json:"modified_at"`
34         ModifiedByClientUUID      string                 `json:"modified_by_client_uuid"`
35         ModifiedByUserUUID        string                 `json:"modified_by_user_uuid"`
36         PortableDataHash          string                 `json:"portable_data_hash"`
37         ReplicationConfirmed      *int                   `json:"replication_confirmed"`
38         ReplicationConfirmedAt    *time.Time             `json:"replication_confirmed_at"`
39         ReplicationDesired        *int                   `json:"replication_desired"`
40         StorageClassesDesired     []string               `json:"storage_classes_desired"`
41         StorageClassesConfirmed   []string               `json:"storage_classes_confirmed"`
42         StorageClassesConfirmedAt *time.Time             `json:"storage_classes_confirmed_at"`
43         DeleteAt                  *time.Time             `json:"delete_at"`
44         IsTrashed                 bool                   `json:"is_trashed"`
45         Properties                map[string]interface{} `json:"properties"`
46         WritableBy                []string               `json:"writable_by,omitempty"`
47         FileCount                 int                    `json:"file_count"`
48         FileSizeTotal             int64                  `json:"file_size_total"`
49         Version                   int                    `json:"version"`
50         PreserveVersion           bool                   `json:"preserve_version"`
51         CurrentVersionUUID        string                 `json:"current_version_uuid"`
52         Description               string                 `json:"description"`
53 }
54
55 func (c Collection) resourceName() string {
56         return "collection"
57 }
58
59 // SizedDigests returns the hash+size part of each data block
60 // referenced by the collection.
61 //
62 // Zero-length blocks are not included.
63 func (c *Collection) SizedDigests() ([]SizedDigest, error) {
64         manifestText := []byte(c.ManifestText)
65         if len(manifestText) == 0 {
66                 manifestText = []byte(c.UnsignedManifestText)
67         }
68         if len(manifestText) == 0 && c.PortableDataHash != "d41d8cd98f00b204e9800998ecf8427e+0" {
69                 // TODO: Check more subtle forms of corruption, too
70                 return nil, fmt.Errorf("manifest is missing")
71         }
72         sds := make([]SizedDigest, 0, len(manifestText)/40)
73         for _, line := range bytes.Split(manifestText, []byte{'\n'}) {
74                 if len(line) == 0 {
75                         continue
76                 }
77                 tokens := bytes.Split(line, []byte{' '})
78                 if len(tokens) < 3 {
79                         return nil, fmt.Errorf("Invalid stream (<3 tokens): %q", line)
80                 }
81                 for _, token := range tokens[1:] {
82                         if !blockdigest.LocatorPattern.Match(token) {
83                                 // FIXME: ensure it's a file token
84                                 break
85                         }
86                         if bytes.HasPrefix(token, []byte("d41d8cd98f00b204e9800998ecf8427e+0")) {
87                                 // Exclude "empty block" placeholder
88                                 continue
89                         }
90                         // FIXME: shouldn't assume 32 char hash
91                         if i := bytes.IndexRune(token[33:], '+'); i >= 0 {
92                                 token = token[:33+i]
93                         }
94                         sds = append(sds, SizedDigest(string(token)))
95                 }
96         }
97         return sds, nil
98 }
99
100 type CollectionList struct {
101         Items          []Collection `json:"items"`
102         ItemsAvailable int          `json:"items_available"`
103         Offset         int          `json:"offset"`
104         Limit          int          `json:"limit"`
105 }
106
107 // PortableDataHash computes the portable data hash of the given
108 // manifest.
109 func PortableDataHash(mt string) string {
110         // To calculate the PDH, we write the manifest to an md5 hash
111         // func, except we skip the "extra" part of block tokens that
112         // look like "abcdef0123456789abcdef0123456789+12345+extra".
113         //
114         // This code is simplified by the facts that (A) all block
115         // tokens -- even the first and last in a stream -- are
116         // preceded and followed by a space character; and (B) all
117         // non-block tokens either start with '.'  or contain ':'.
118         //
119         // A regexp-based approach (like the one this replaced) would
120         // be more readable, but very slow.
121         h := md5.New()
122         size := 0
123         todo := []byte(mt)
124         for len(todo) > 0 {
125                 // sp is the end of the current token (note that if
126                 // the current token is the last file token in a
127                 // stream, we'll also include the \n and the dirname
128                 // token on the next line, which is perfectly fine for
129                 // our purposes).
130                 sp := bytes.IndexByte(todo, ' ')
131                 if sp < 0 {
132                         // Last token of the manifest, which is never
133                         // a block token.
134                         n, _ := h.Write(todo)
135                         size += n
136                         break
137                 }
138                 if sp >= 34 && todo[32] == '+' && bytes.IndexByte(todo[:32], ':') == -1 && todo[0] != '.' {
139                         // todo[:sp] is a block token.
140                         sizeend := bytes.IndexByte(todo[33:sp], '+')
141                         if sizeend < 0 {
142                                 // "hash+size"
143                                 sizeend = sp
144                         } else {
145                                 // "hash+size+extra"
146                                 sizeend += 33
147                         }
148                         n, _ := h.Write(todo[:sizeend])
149                         h.Write([]byte{' '})
150                         size += n + 1
151                 } else {
152                         // todo[:sp] is not a block token.
153                         n, _ := h.Write(todo[:sp+1])
154                         size += n
155                 }
156                 todo = todo[sp+1:]
157         }
158         return fmt.Sprintf("%x+%d", h.Sum(nil), size)
159 }
160
161 // CollectionIDFromDNSName returns a UUID or PDH if s begins with a
162 // UUID or URL-encoded PDH; otherwise "".
163 func CollectionIDFromDNSName(s string) string {
164         // Strip domain.
165         if i := strings.IndexRune(s, '.'); i >= 0 {
166                 s = s[:i]
167         }
168         // Names like {uuid}--collections.example.com serve the same
169         // purpose as {uuid}.collections.example.com but can reduce
170         // cost/effort of using [additional] wildcard certificates.
171         if i := strings.Index(s, "--"); i >= 0 {
172                 s = s[:i]
173         }
174         if UUIDMatch(s) {
175                 return s
176         }
177         if pdh := strings.Replace(s, "-", "+", 1); PDHMatch(pdh) {
178                 return pdh
179         }
180         return ""
181 }