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