Bump loofah from 2.2.3 to 2.3.1 in /apps/workbench
[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.curoverse.com/arvados.git/sdk/go/arvados"
16         "git.curoverse.com/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         // Preserve "kind" even if not requested
49         if v, ok := orig["kind"]; ok {
50                 selected["kind"] = v
51         }
52         return selected
53 }
54
55 func (rtr *router) sendResponse(w http.ResponseWriter, req *http.Request, resp interface{}, opts responseOptions) {
56         var tmp map[string]interface{}
57
58         if resp, ok := resp.(http.Handler); ok {
59                 // resp knows how to write its own http response
60                 // header and body.
61                 resp.ServeHTTP(w, req)
62                 return
63         }
64
65         err := rtr.transcode(resp, &tmp)
66         if err != nil {
67                 rtr.sendError(w, err)
68                 return
69         }
70
71         respKind := kind(resp)
72         if respKind != "" {
73                 tmp["kind"] = respKind
74         }
75         defaultItemKind := ""
76         if strings.HasSuffix(respKind, "List") {
77                 defaultItemKind = strings.TrimSuffix(respKind, "List")
78         }
79
80         if items, ok := tmp["items"].([]interface{}); ok {
81                 for i, item := range items {
82                         // Fill in "kind" by inspecting UUID/PDH if
83                         // possible; fall back on assuming each
84                         // Items[] entry in an "arvados#fooList"
85                         // response should have kind="arvados#foo".
86                         item, _ := item.(map[string]interface{})
87                         infix := ""
88                         if uuid, _ := item["uuid"].(string); len(uuid) == 27 {
89                                 infix = uuid[6:11]
90                         }
91                         if k := kind(infixMap[infix]); k != "" {
92                                 item["kind"] = k
93                         } else if pdh, _ := item["portable_data_hash"].(string); pdh != "" {
94                                 item["kind"] = "arvados#collection"
95                         } else if defaultItemKind != "" {
96                                 item["kind"] = defaultItemKind
97                         }
98                         items[i] = applySelectParam(opts.Select, item)
99                 }
100                 if opts.Count == "none" {
101                         delete(tmp, "items_available")
102                 }
103         } else {
104                 tmp = applySelectParam(opts.Select, tmp)
105         }
106
107         // Format non-nil timestamps as rfc3339NanoFixed (by default
108         // they will have been encoded to time.RFC3339Nano, which
109         // omits trailing zeroes).
110         for k, v := range tmp {
111                 if !strings.HasSuffix(k, "_at") {
112                         continue
113                 }
114                 switch tv := v.(type) {
115                 case *time.Time:
116                         if tv == nil {
117                                 break
118                         }
119                         tmp[k] = tv.Format(rfc3339NanoFixed)
120                 case time.Time:
121                         tmp[k] = tv.Format(rfc3339NanoFixed)
122                 case string:
123                         t, err := time.Parse(time.RFC3339Nano, tv)
124                         if err != nil {
125                                 break
126                         }
127                         tmp[k] = t.Format(rfc3339NanoFixed)
128                 }
129         }
130         w.Header().Set("Content-Type", "application/json")
131         enc := json.NewEncoder(w)
132         enc.SetEscapeHTML(false)
133         enc.Encode(tmp)
134 }
135
136 func (rtr *router) sendError(w http.ResponseWriter, err error) {
137         code := http.StatusInternalServerError
138         if err, ok := err.(interface{ HTTPStatus() int }); ok {
139                 code = err.HTTPStatus()
140         }
141         httpserver.Error(w, err.Error(), code)
142 }
143
144 var infixMap = map[string]interface{}{
145         "4zz18": arvados.Collection{},
146         "j7d0g": arvados.Group{},
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 }