forked from NETCRACKER-P2P-Streaming/krakend
/
formatter.go
306 lines (276 loc) · 6.92 KB
/
formatter.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package proxy
import (
"context"
"strings"
"github.com/devopsfaith/flatmap/tree"
"github.com/devopsfaith/krakend/config"
)
// EntityFormatter formats the response data
type EntityFormatter interface {
Format(Response) Response
}
// EntityFormatterFunc holds the formatter function
type EntityFormatterFunc func(Response) Response
// Format implements the EntityFormatter interface
func (e EntityFormatterFunc) Format(entity Response) Response { return e(entity) }
type propertyFilter func(*Response)
type entityFormatter struct {
Target string
Prefix string
PropertyFilter propertyFilter
Mapping map[string]string
}
// NewEntityFormatter creates an entity formatter with the received backend definition
func NewEntityFormatter(remote *config.Backend) EntityFormatter {
if ef := newFlatmapFormatter(remote.ExtraConfig, remote.Target, remote.Group); ef != nil {
return ef
}
var propertyFilter propertyFilter
if len(remote.Whitelist) > 0 {
propertyFilter = newWhitelistingFilter(remote.Whitelist)
} else {
propertyFilter = newBlacklistingFilter(remote.Blacklist)
}
sanitizedMappings := make(map[string]string, len(remote.Mapping))
for i, m := range remote.Mapping {
v := strings.Split(m, ".")
sanitizedMappings[i] = v[0]
}
return entityFormatter{
Target: remote.Target,
Prefix: remote.Group,
PropertyFilter: propertyFilter,
Mapping: sanitizedMappings,
}
}
// Format implements the EntityFormatter interface
func (e entityFormatter) Format(entity Response) Response {
if e.Target != "" {
extractTarget(e.Target, &entity)
}
if len(entity.Data) > 0 {
e.PropertyFilter(&entity)
}
if len(entity.Data) > 0 {
for formerKey, newKey := range e.Mapping {
if v, ok := entity.Data[formerKey]; ok {
entity.Data[newKey] = v
delete(entity.Data, formerKey)
}
}
}
if e.Prefix != "" {
entity.Data = map[string]interface{}{e.Prefix: entity.Data}
}
return entity
}
func extractTarget(target string, entity *Response) {
for _, part := range strings.Split(target, ".") {
if tmp, ok := entity.Data[part]; ok {
entity.Data, ok = tmp.(map[string]interface{})
if !ok {
entity.Data = map[string]interface{}{}
return
}
} else {
entity.Data = map[string]interface{}{}
return
}
}
}
func whitelistPrune(wlDict map[string]interface{}, inDict map[string]interface{}) bool {
canDelete := true
var deleteSibling bool
for k, v := range inDict {
deleteSibling = true
if subWl, ok := wlDict[k]; ok {
if subWlDict, okk := subWl.(map[string]interface{}); okk {
if subInDict, isDict := v.(map[string]interface{}); isDict && !whitelistPrune(subWlDict, subInDict) {
deleteSibling = false
}
} else {
// whitelist leaf, maintain this branch
deleteSibling = false
}
}
if deleteSibling {
delete(inDict, k)
} else {
canDelete = false
}
}
return canDelete
}
func newWhitelistingFilter(whitelist []string) propertyFilter {
wlDict := make(map[string]interface{})
for _, k := range whitelist {
wlFields := strings.Split(k, ".")
d := buildDictPath(wlDict, wlFields[:len(wlFields)-1])
d[wlFields[len(wlFields)-1]] = true
}
return func(entity *Response) {
if whitelistPrune(wlDict, entity.Data) {
for k := range entity.Data {
delete(entity.Data, k)
}
}
}
}
func buildDictPath(accumulator map[string]interface{}, fields []string) map[string]interface{} {
var ok bool
var c map[string]interface{}
var fIdx int
fEnd := len(fields)
p := accumulator
for fIdx = 0; fIdx < fEnd; fIdx++ {
if c, ok = p[fields[fIdx]].(map[string]interface{}); !ok {
break
}
p = c
}
for ; fIdx < fEnd; fIdx++ {
c = make(map[string]interface{})
p[fields[fIdx]] = c
p = c
}
return p
}
func newBlacklistingFilter(blacklist []string) propertyFilter {
bl := make(map[string][]string, len(blacklist))
for _, key := range blacklist {
keys := strings.Split(key, ".")
if len(keys) > 1 {
if sub, ok := bl[keys[0]]; ok {
bl[keys[0]] = append(sub, keys[1])
} else {
bl[keys[0]] = []string{keys[1]}
}
} else {
bl[keys[0]] = []string{}
}
}
return func(entity *Response) {
for k, sub := range bl {
if len(sub) == 0 {
delete(entity.Data, k)
} else {
if tmp := blacklistFilterSub(entity.Data[k], sub); len(tmp) > 0 {
entity.Data[k] = tmp
}
}
}
}
}
func blacklistFilterSub(v interface{}, blacklist []string) map[string]interface{} {
tmp, ok := v.(map[string]interface{})
if !ok {
return map[string]interface{}{}
}
for _, key := range blacklist {
delete(tmp, key)
}
return tmp
}
const flatmapKey = "flatmap_filter"
type flatmapFormatter struct {
Target string
Prefix string
Ops []flatmapOp
}
type flatmapOp struct {
Type string
Args [][]string
}
// Format implements the EntityFormatter interface
func (e flatmapFormatter) Format(entity Response) Response {
if e.Target != "" {
extractTarget(e.Target, &entity)
}
e.processOps(&entity)
if e.Prefix != "" {
entity.Data = map[string]interface{}{e.Prefix: entity.Data}
}
return entity
}
func (e flatmapFormatter) processOps(entity *Response) {
flatten, err := tree.New(entity.Data)
if err != nil {
return
}
for _, op := range e.Ops {
switch op.Type {
case "move":
flatten.Move(op.Args[0], op.Args[1])
case "append":
flatten.Append(op.Args[0], op.Args[1])
case "del":
for _, k := range op.Args {
flatten.Del(k)
}
default:
}
}
entity.Data, _ = flatten.Get([]string{}).(map[string]interface{})
}
func newFlatmapFormatter(cfg config.ExtraConfig, target, group string) EntityFormatter {
if v, ok := cfg[Namespace]; ok {
if e, ok := v.(map[string]interface{}); ok {
if vs, ok := e[flatmapKey].([]interface{}); ok {
if len(vs) == 0 {
return nil
}
ops := []flatmapOp{}
for _, v := range vs {
m, ok := v.(map[string]interface{})
if !ok {
continue
}
op := flatmapOp{}
if t, ok := m["type"].(string); ok {
op.Type = t
} else {
continue
}
if args, ok := m["args"].([]interface{}); ok {
op.Args = make([][]string, len(args))
for k, arg := range args {
if t, ok := arg.(string); ok {
op.Args[k] = strings.Split(t, ".")
}
}
}
ops = append(ops, op)
}
if len(ops) == 0 {
return nil
}
return &flatmapFormatter{
Target: target,
Prefix: group,
Ops: ops,
}
}
}
}
return nil
}
// NewFlatmapMiddleware creates a proxy middleware that enables applying flatmap operations to the proxy response
func NewFlatmapMiddleware(cfg *config.EndpointConfig) Middleware {
formatter := newFlatmapFormatter(cfg.ExtraConfig, "", "")
return func(next ...Proxy) Proxy {
if len(next) != 1 {
panic(ErrTooManyProxies)
}
if formatter == nil {
return next[0]
}
return func(ctx context.Context, request *Request) (*Response, error) {
resp, err := next[0](ctx, request)
if err != nil {
return resp, err
}
r := formatter.Format(*resp)
return &r, nil
}
}
}