forked from infobloxopen/atlas-app-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
field_presence.go
222 lines (181 loc) · 5 KB
/
field_presence.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package gateway
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"net/http"
"reflect"
"strings"
"google.golang.org/genproto/protobuf/field_mask"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"github.com/infobloxopen/atlas-app-toolkit/util"
)
const (
fieldPresenceMetaKey = "field-paths"
pathsSeparator = "$"
bulkField = "objects"
)
// NewPresenceAnnotator will parse the JSON input and then add the paths to the
// metadata to be pulled from context later
func NewPresenceAnnotator(methods ...string) func(context.Context, *http.Request) metadata.MD {
return func(ctx context.Context, req *http.Request) metadata.MD {
if req == nil {
return nil
}
if !isValidMethod(req, methods...) {
return nil
}
// Read body of request then reset it to be read in future
body, err := ioutil.ReadAll(req.Body)
req.Body = ioutil.NopCloser(bytes.NewReader(body))
if err != nil {
return nil
}
md := make(metadata.MD)
if len(body) == 0 {
md[fieldPresenceMetaKey] = nil
return md
}
var root interface{}
if err := json.Unmarshal(body, &root); err != nil {
return nil
}
roots := getRoots(root)
for _, r := range roots {
queue := []pathItem{{node: r}}
paths := []string{}
for len(queue) > 0 {
// dequeue an item
item := queue[0]
queue = queue[1:]
if isLeaf(item) {
paths = append(paths, strings.Join(item.path, "."))
} else {
if m, ok := item.node.(map[string]interface{}); ok {
// if the item is an object, then enqueue all of its children
for k, v := range m {
newPath := extendPath(item.path, k)
queue = append(queue, pathItem{path: newPath, node: v})
}
}
}
}
entry := strings.Join(paths, pathsSeparator)
if len(entry) == 0 {
continue
}
md[fieldPresenceMetaKey] = append(md[fieldPresenceMetaKey], strings.Join(paths, pathsSeparator))
}
return md
}
}
func extendPath(parent []string, key string) []string {
newPath := make([]string, len(parent)+1)
copy(newPath, parent)
newPath[len(newPath)-1] = util.Camel(key)
return newPath
}
func isLeaf(item pathItem) bool {
if m, ok := item.node.(map[string]interface{}); ok {
if len(m) == 0 && len(item.path) > 0 {
return true
}
} else if len(item.path) > 0 {
return true
}
return false
}
func getRoots(root interface{}) []interface{} {
defaultRoot := []interface{}{root}
m, ok := root.(map[string]interface{})
if !ok {
return defaultRoot
}
bulk, ok := m[bulkField]
if !ok {
return defaultRoot
}
slice, ok := bulk.([]interface{})
if !ok {
return defaultRoot
}
return slice
}
func isValidMethod(req *http.Request, methods ...string) bool {
for _, m := range methods {
if req.Method == m {
return true
}
}
return false
}
// pathItem stores a in-progress deconstruction of a path for a fieldmask
type pathItem struct {
// the list of prior fields leading up to node
path []string
// a generic decoded json object the current item to inspect for further path extraction
node interface{}
}
type presenceInterceptorOptionsDecorator struct {
overrideFieldMask bool
}
type presenceInterceptorOption func(*presenceInterceptorOptionsDecorator)
//WithOverrideFieldMask represent an option to override field mask generated by grpc-gateway
func WithOverrideFieldMask(d *presenceInterceptorOptionsDecorator) {
d.overrideFieldMask = true
}
// PresenceClientInterceptor gets the interceptor for populating a fieldmask in a
// proto message from the fields given in the metadata/context
func PresenceClientInterceptor(options ...presenceInterceptorOption) grpc.UnaryClientInterceptor {
ops := &presenceInterceptorOptionsDecorator{}
for _, op := range options {
op(ops)
}
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) (err error) {
defer func() {
err = invoker(ctx, method, req, reply, cc, opts...)
}()
if req == nil {
return
}
paths, found := HeaderN(ctx, fieldPresenceMetaKey, -1)
if !found {
return
}
fieldMask := fieldMaskFromPaths(paths)
// If a field with type *FieldMask or []*FieldMask exists, set the paths in it
t := reflect.ValueOf(req)
if t.Kind() != reflect.Interface && t.Kind() != reflect.Ptr {
return
}
t = t.Elem()
if t.Kind() != reflect.Struct { // only Structs can have their fields enumerated
return
}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.Type() == reflect.TypeOf(fieldMask) {
if ops.overrideFieldMask || f.IsNil() {
f.Set(reflect.ValueOf(fieldMask))
}
return
}
}
return
}
}
func fieldMaskFromPaths(paths []string) interface{} {
if len(paths) == 0 {
return &field_mask.FieldMask{}
}
if len(paths) > 1 {
bulkFieldMasks := make([]*field_mask.FieldMask, len(paths))
for i, p := range paths {
bulkFieldMasks[i] = &field_mask.FieldMask{Paths: strings.Split(p, pathsSeparator)}
}
return bulkFieldMasks
}
return &field_mask.FieldMask{Paths: strings.Split(paths[0], pathsSeparator)}
}