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