14812: Migrate UserProfileFormFields
[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, resp interface{}, opts responseOptions) {
56         var tmp map[string]interface{}
57
58         err := rtr.transcode(resp, &tmp)
59         if err != nil {
60                 rtr.sendError(w, err)
61                 return
62         }
63
64         respKind := kind(resp)
65         if respKind != "" {
66                 tmp["kind"] = respKind
67         }
68         defaultItemKind := ""
69         if strings.HasSuffix(respKind, "List") {
70                 defaultItemKind = strings.TrimSuffix(respKind, "List")
71         }
72
73         if items, ok := tmp["items"].([]interface{}); ok {
74                 for i, item := range items {
75                         // Fill in "kind" by inspecting UUID/PDH if
76                         // possible; fall back on assuming each
77                         // Items[] entry in an "arvados#fooList"
78                         // response should have kind="arvados#foo".
79                         item, _ := item.(map[string]interface{})
80                         infix := ""
81                         if uuid, _ := item["uuid"].(string); len(uuid) == 27 {
82                                 infix = uuid[6:11]
83                         }
84                         if k := kind(infixMap[infix]); k != "" {
85                                 item["kind"] = k
86                         } else if pdh, _ := item["portable_data_hash"].(string); pdh != "" {
87                                 item["kind"] = "arvados#collection"
88                         } else if defaultItemKind != "" {
89                                 item["kind"] = defaultItemKind
90                         }
91                         items[i] = applySelectParam(opts.Select, item)
92                 }
93                 if opts.Count == "none" {
94                         delete(tmp, "items_available")
95                 }
96         } else {
97                 tmp = applySelectParam(opts.Select, tmp)
98         }
99
100         // Format non-nil timestamps as rfc3339NanoFixed (by default
101         // they will have been encoded to time.RFC3339Nano, which
102         // omits trailing zeroes).
103         for k, v := range tmp {
104                 if !strings.HasSuffix(k, "_at") {
105                         continue
106                 }
107                 switch tv := v.(type) {
108                 case *time.Time:
109                         if tv == nil {
110                                 break
111                         }
112                         tmp[k] = tv.Format(rfc3339NanoFixed)
113                 case time.Time:
114                         tmp[k] = tv.Format(rfc3339NanoFixed)
115                 case string:
116                         t, err := time.Parse(time.RFC3339Nano, tv)
117                         if err != nil {
118                                 break
119                         }
120                         tmp[k] = t.Format(rfc3339NanoFixed)
121                 }
122         }
123         w.Header().Set("Content-Type", "application/json")
124         json.NewEncoder(w).Encode(tmp)
125 }
126
127 func (rtr *router) sendError(w http.ResponseWriter, err error) {
128         code := http.StatusInternalServerError
129         if err, ok := err.(interface{ HTTPStatus() int }); ok {
130                 code = err.HTTPStatus()
131         }
132         httpserver.Error(w, err.Error(), code)
133 }
134
135 var infixMap = map[string]interface{}{
136         "4zz18": arvados.Collection{},
137         "j7d0g": arvados.Group{},
138 }
139
140 var mungeKind = regexp.MustCompile(`\..`)
141
142 func kind(resp interface{}) string {
143         t := fmt.Sprintf("%T", resp)
144         if !strings.HasPrefix(t, "arvados.") {
145                 return ""
146         }
147         return mungeKind.ReplaceAllStringFunc(t, func(s string) string {
148                 // "arvados.CollectionList" => "arvados#collectionList"
149                 return "#" + strings.ToLower(s[1:])
150         })
151 }