Merge branch '17119-virtual-folder-from-query'
[arvados.git] / lib / controller / router / response.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package router
6
7 import (
8         "encoding/json"
9         "fmt"
10         "net/http"
11         "regexp"
12         "strings"
13         "time"
14
15         "git.arvados.org/arvados.git/sdk/go/arvados"
16         "git.arvados.org/arvados.git/sdk/go/httpserver"
17 )
18
19 const rfc3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
20
21 type responseOptions struct {
22         Select []string
23         Count  string
24 }
25
26 func (rtr *router) responseOptions(opts interface{}) (responseOptions, error) {
27         var rOpts responseOptions
28         switch opts := opts.(type) {
29         case *arvados.GetOptions:
30                 rOpts.Select = opts.Select
31         case *arvados.ListOptions:
32                 rOpts.Select = opts.Select
33                 rOpts.Count = opts.Count
34         }
35         return rOpts, nil
36 }
37
38 func applySelectParam(selectParam []string, orig map[string]interface{}) map[string]interface{} {
39         if len(selectParam) == 0 {
40                 return orig
41         }
42         selected := map[string]interface{}{}
43         for _, attr := range selectParam {
44                 if v, ok := orig[attr]; ok {
45                         selected[attr] = v
46                 }
47         }
48         // Some keys are always preserved, even if not requested
49         for _, k := range []string{"etag", "kind", "writable_by"} {
50                 if v, ok := orig[k]; ok {
51                         selected[k] = v
52                 }
53         }
54         return selected
55 }
56
57 func (rtr *router) sendResponse(w http.ResponseWriter, req *http.Request, resp interface{}, opts responseOptions) {
58         var tmp map[string]interface{}
59
60         if resp, ok := resp.(http.Handler); ok {
61                 // resp knows how to write its own http response
62                 // header and body.
63                 resp.ServeHTTP(w, req)
64                 return
65         }
66
67         err := rtr.transcode(resp, &tmp)
68         if err != nil {
69                 rtr.sendError(w, err)
70                 return
71         }
72
73         respKind := kind(resp)
74         if respKind != "" {
75                 tmp["kind"] = respKind
76         }
77         if included, ok := tmp["included"]; ok && included == nil {
78                 tmp["included"] = make([]interface{}, 0)
79         }
80         defaultItemKind := ""
81         if strings.HasSuffix(respKind, "List") {
82                 defaultItemKind = strings.TrimSuffix(respKind, "List")
83         }
84
85         if _, isListResponse := tmp["items"].([]interface{}); isListResponse {
86                 items, _ := tmp["items"].([]interface{})
87                 included, _ := tmp["included"].([]interface{})
88                 for _, slice := range [][]interface{}{items, included} {
89                         for i, item := range slice {
90                                 // Fill in "kind" by inspecting UUID/PDH if
91                                 // possible; fall back on assuming each
92                                 // Items[] entry in an "arvados#fooList"
93                                 // response should have kind="arvados#foo".
94                                 item, _ := item.(map[string]interface{})
95                                 infix := ""
96                                 if uuid, _ := item["uuid"].(string); len(uuid) == 27 {
97                                         infix = uuid[6:11]
98                                 }
99                                 if k := kind(infixMap[infix]); k != "" {
100                                         item["kind"] = k
101                                 } else if pdh, _ := item["portable_data_hash"].(string); pdh != "" {
102                                         item["kind"] = "arvados#collection"
103                                 } else if defaultItemKind != "" {
104                                         item["kind"] = defaultItemKind
105                                 }
106                                 item = applySelectParam(opts.Select, item)
107                                 rtr.mungeItemFields(item)
108                                 slice[i] = item
109                         }
110                 }
111                 if opts.Count == "none" {
112                         delete(tmp, "items_available")
113                 }
114         } else {
115                 tmp = applySelectParam(opts.Select, tmp)
116                 rtr.mungeItemFields(tmp)
117         }
118
119         w.Header().Set("Content-Type", "application/json")
120         enc := json.NewEncoder(w)
121         enc.SetEscapeHTML(false)
122         enc.Encode(tmp)
123 }
124
125 func (rtr *router) sendError(w http.ResponseWriter, err error) {
126         code := http.StatusInternalServerError
127         if err, ok := err.(interface{ HTTPStatus() int }); ok {
128                 code = err.HTTPStatus()
129         }
130         httpserver.Error(w, err.Error(), code)
131 }
132
133 var infixMap = map[string]interface{}{
134         "4zz18": arvados.Collection{},
135         "xvhdp": arvados.ContainerRequest{},
136         "dz642": arvados.Container{},
137         "j7d0g": arvados.Group{},
138         "8i9sb": arvados.Job{},
139         "d1hrv": arvados.PipelineInstance{},
140         "p5p6p": arvados.PipelineTemplate{},
141         "j58dm": arvados.Specimen{},
142         "q1cn2": arvados.Trait{},
143         "7fd4e": arvados.Workflow{},
144 }
145
146 var mungeKind = regexp.MustCompile(`\..`)
147
148 func kind(resp interface{}) string {
149         t := fmt.Sprintf("%T", resp)
150         if !strings.HasPrefix(t, "arvados.") {
151                 return ""
152         }
153         return mungeKind.ReplaceAllStringFunc(t, func(s string) string {
154                 // "arvados.CollectionList" => "arvados#collectionList"
155                 return "#" + strings.ToLower(s[1:])
156         })
157 }
158
159 func (rtr *router) mungeItemFields(tmp map[string]interface{}) {
160         for k, v := range tmp {
161                 if strings.HasSuffix(k, "_at") {
162                         // Format non-nil timestamps as
163                         // rfc3339NanoFixed (otherwise they would use
164                         // the default time encoding, which omits
165                         // trailing zeroes).
166                         switch tv := v.(type) {
167                         case *time.Time:
168                                 if tv == nil || tv.IsZero() {
169                                         tmp[k] = nil
170                                 } else {
171                                         tmp[k] = tv.Format(rfc3339NanoFixed)
172                                 }
173                         case time.Time:
174                                 if tv.IsZero() {
175                                         tmp[k] = nil
176                                 } else {
177                                         tmp[k] = tv.Format(rfc3339NanoFixed)
178                                 }
179                         case string:
180                                 if tv == "" {
181                                         tmp[k] = nil
182                                 } else if t, err := time.Parse(time.RFC3339Nano, tv); err != nil {
183                                         // pass through an invalid time value (?)
184                                 } else if t.IsZero() {
185                                         tmp[k] = nil
186                                 } else {
187                                         tmp[k] = t.Format(rfc3339NanoFixed)
188                                 }
189                         }
190                 }
191                 // Arvados API spec says when these fields are empty
192                 // they appear in responses as null, rather than a
193                 // zero value.
194                 switch k {
195                 case "output_uuid", "output_name", "log_uuid", "description", "requesting_container_uuid", "container_uuid":
196                         if v == "" {
197                                 tmp[k] = nil
198                         }
199                 case "container_count_max":
200                         if v == float64(0) {
201                                 tmp[k] = nil
202                         }
203                 }
204         }
205 }