2a7bd9e6745ba9eecda72498e7463e77c17cd887
[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 == "arvados#sharedGroupList" {
75                 tmp["kind"] = "arvados#groupList"
76         } else if respKind != "" {
77                 tmp["kind"] = respKind
78         }
79         defaultItemKind := ""
80         if strings.HasSuffix(respKind, "List") {
81                 defaultItemKind = strings.TrimSuffix(respKind, "List")
82         }
83
84         if items, ok := tmp["items"].([]interface{}); ok {
85                 for i, item := range items {
86                         // Fill in "kind" by inspecting UUID/PDH if
87                         // possible; fall back on assuming each
88                         // Items[] entry in an "arvados#fooList"
89                         // response should have kind="arvados#foo".
90                         item, _ := item.(map[string]interface{})
91                         infix := ""
92                         if uuid, _ := item["uuid"].(string); len(uuid) == 27 {
93                                 infix = uuid[6:11]
94                         }
95                         if k := kind(infixMap[infix]); k != "" {
96                                 item["kind"] = k
97                         } else if pdh, _ := item["portable_data_hash"].(string); pdh != "" {
98                                 item["kind"] = "arvados#collection"
99                         } else if defaultItemKind != "" {
100                                 item["kind"] = defaultItemKind
101                         }
102                         item = applySelectParam(opts.Select, item)
103                         rtr.mungeItemFields(item)
104                         items[i] = item
105                 }
106                 if opts.Count == "none" {
107                         delete(tmp, "items_available")
108                 }
109         } else {
110                 tmp = applySelectParam(opts.Select, tmp)
111                 rtr.mungeItemFields(tmp)
112         }
113
114         w.Header().Set("Content-Type", "application/json")
115         enc := json.NewEncoder(w)
116         enc.SetEscapeHTML(false)
117         enc.Encode(tmp)
118 }
119
120 func (rtr *router) sendError(w http.ResponseWriter, err error) {
121         code := http.StatusInternalServerError
122         if err, ok := err.(interface{ HTTPStatus() int }); ok {
123                 code = err.HTTPStatus()
124         }
125         httpserver.Error(w, err.Error(), code)
126 }
127
128 var infixMap = map[string]interface{}{
129         "4zz18": arvados.Collection{},
130         "xvhdp": arvados.ContainerRequest{},
131         "dz642": arvados.Container{},
132         "j7d0g": arvados.Group{},
133         "8i9sb": arvados.Job{},
134         "d1hrv": arvados.PipelineInstance{},
135         "p5p6p": arvados.PipelineTemplate{},
136         "j58dm": arvados.Specimen{},
137         "q1cn2": arvados.Trait{},
138         "7fd4e": arvados.Workflow{},
139 }
140
141 var mungeKind = regexp.MustCompile(`\..`)
142
143 func kind(resp interface{}) string {
144         t := fmt.Sprintf("%T", resp)
145         if !strings.HasPrefix(t, "arvados.") {
146                 return ""
147         }
148         return mungeKind.ReplaceAllStringFunc(t, func(s string) string {
149                 // "arvados.CollectionList" => "arvados#collectionList"
150                 return "#" + strings.ToLower(s[1:])
151         })
152 }
153
154 func (rtr *router) mungeItemFields(tmp map[string]interface{}) {
155         for k, v := range tmp {
156                 if strings.HasSuffix(k, "_at") {
157                         // Format non-nil timestamps as
158                         // rfc3339NanoFixed (otherwise they would use
159                         // the default time encoding, which omits
160                         // trailing zeroes).
161                         switch tv := v.(type) {
162                         case *time.Time:
163                                 if tv == nil || tv.IsZero() {
164                                         tmp[k] = nil
165                                 } else {
166                                         tmp[k] = tv.Format(rfc3339NanoFixed)
167                                 }
168                         case time.Time:
169                                 if tv.IsZero() {
170                                         tmp[k] = nil
171                                 } else {
172                                         tmp[k] = tv.Format(rfc3339NanoFixed)
173                                 }
174                         case string:
175                                 if tv == "" {
176                                         tmp[k] = nil
177                                 } else if t, err := time.Parse(time.RFC3339Nano, tv); err != nil {
178                                         // pass through an invalid time value (?)
179                                 } else if t.IsZero() {
180                                         tmp[k] = nil
181                                 } else {
182                                         tmp[k] = t.Format(rfc3339NanoFixed)
183                                 }
184                         }
185                 }
186                 // Arvados API spec says when these fields are empty
187                 // they appear in responses as null, rather than a
188                 // zero value.
189                 switch k {
190                 case "output_uuid", "output_name", "log_uuid", "description", "requesting_container_uuid", "container_uuid":
191                         if v == "" {
192                                 tmp[k] = nil
193                         }
194                 case "container_count_max":
195                         if v == float64(0) {
196                                 tmp[k] = nil
197                         }
198                 }
199         }
200 }