-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
storehandler.go
364 lines (327 loc) · 7.16 KB
/
storehandler.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package store
import (
"encoding/json"
"errors"
res "github.com/jirenius/go-res"
)
// Handler is a res.Service handler that fetches resources,
// and listens for updates from a Store.
type Handler struct {
Store Store
Transformer Transformer
Default interface{}
}
var _ res.Option = Handler{}
type storeHandler struct {
s *res.Service
p res.Pattern
st Store
typ res.ResourceType
def json.RawMessage
trans Transformer
}
var errInvalidResourceType = res.InternalError(errors.New("invalid store resource type"))
// WithStore returns a new Handler value with Store set to store.
func (sh Handler) WithStore(store Store) Handler {
sh.Store = store
return sh
}
// WithTransformer returns a new Handler value with Transformer set to transformer.
func (sh Handler) WithTransformer(transformer Transformer) Handler {
sh.Transformer = transformer
return sh
}
// WithDefault returns a new Handler value with Default value set to default.
// The default value should be pre-transformed.
func (sh Handler) WithDefault(def interface{}) Handler {
sh.Default = def
return sh
}
// SetOption is to implement the res.Option interface
func (sh Handler) SetOption(h *res.Handler) {
if sh.Store == nil {
panic("no Store is set")
}
o := storeHandler{
st: sh.Store,
trans: sh.Transformer,
}
if sh.Default != nil {
raw, err := json.Marshal(sh.Default)
if err != nil {
panic("error marshaling default handler value: " + err.Error())
}
o.def = raw
}
h.Option(
res.GetResource(o.getResource),
res.OnRegister(o.onRegister),
)
o.st.OnChange(o.changeHandler)
}
func (o *storeHandler) onRegister(s *res.Service, p res.Pattern, h res.Handler) {
switch h.Type {
case res.TypeModel:
if len(o.def) > 0 && o.def[0] != '{' {
panic("Default value for TypeModel must be a json object.")
}
case res.TypeCollection:
if len(o.def) > 0 && o.def[0] != '[' {
panic("Default value for TypeModel must be a json object.")
}
case res.TypeUnset:
panic("no Type is set")
default:
panic("Type must be set to TypeModel or TypeCollection")
}
o.s = s
o.p = p
o.typ = h.Type
}
func (o *storeHandler) getResource(r res.GetRequest) {
id := r.ResourceName()
if o.trans != nil {
id = o.trans.RIDToID(id, r.PathParams())
if id == "" {
r.NotFound()
return
}
}
txn := o.st.Read(id)
defer txn.Close()
v, err := txn.Value()
if err != nil {
if errors.Is(err, ErrNotFound) && o.def != nil {
v = o.def
} else {
r.Error(err)
return
}
} else {
if o.trans != nil {
v, err = o.trans.Transform(id, v)
if err != nil {
r.Error(err)
return
}
}
}
switch o.typ {
case res.TypeModel:
r.Model(v)
case res.TypeCollection:
r.Collection(v)
default:
r.Error(errInvalidResourceType)
}
}
func (o *storeHandler) changeHandler(id string, before, after interface{}) {
var err error
rid := id
if o.trans != nil {
if before != nil {
before, err = o.trans.Transform(id, before)
if err != nil {
before = nil
}
} else if o.def != nil {
before = o.def
}
if after != nil {
after, err = o.trans.Transform(id, after)
if err != nil {
after = nil
}
} else if o.def != nil {
after = o.def
}
if after != nil {
rid = o.trans.IDToRID(id, after, o.p)
} else if before != nil {
rid = o.trans.IDToRID(id, before, o.p)
}
if rid == "" {
return
}
}
r, err := o.s.Resource(rid)
if err != nil {
o.s.Logger().Errorf("error getting resource %s: %s", rid, err)
return
}
if before == nil {
// Assert that both values are not null. Shouldn't happen.
if after == nil {
return
}
r.CreateEvent(after)
return
}
if after == nil {
r.DeleteEvent()
return
}
switch o.typ {
case res.TypeModel:
if err := modelDiff(r, before, after); err != nil {
o.s.Logger().Errorf("diff failed for model %s: %s", rid, err)
}
case res.TypeCollection:
if err := o.collectionDiff(r, before, after); err != nil {
o.s.Logger().Errorf("diff failed for collection %s: %s", rid, err)
}
default:
o.s.Logger().Errorf("invalid resource type")
}
}
// modelDiff produces change event by comparing before and after value, as they
// look when marshaled into json.
func modelDiff(r res.Resource, before, after interface{}) error {
var beforeMap, afterMap map[string]Value
var ok bool
// Convert before and after value to map[string]Value
if beforeMap, ok = before.(map[string]Value); !ok {
beforeDta, err := json.Marshal(before)
if err != nil {
return err
}
if err = json.Unmarshal(beforeDta, &beforeMap); err != nil {
return err
}
}
if afterMap, ok = after.(map[string]Value); !ok {
afterDta, err := json.Marshal(after)
if err != nil {
return err
}
if err = json.Unmarshal(afterDta, &afterMap); err != nil {
return err
}
}
// Generate change event
ch := make(map[string]interface{}, len(afterMap))
for k := range beforeMap {
if _, ok := afterMap[k]; !ok {
ch[k] = DeleteValue
}
}
for k, v := range afterMap {
ov, ok := beforeMap[k]
if !ok || !v.Equal(ov) {
ch[k] = v
}
}
r.ChangeEvent(ch)
return nil
}
// collectionDiff produces remove and add events by comparing before and after
// value, as they look when marshaled into json.
func (o *storeHandler) collectionDiff(r res.Resource, before, after interface{}) error {
var a, b []Value
var ok bool
// Convert before and after value to []Value
if a, ok = before.([]Value); !ok {
beforeDta, err := json.Marshal(before)
if err != nil {
return err
}
if err = json.Unmarshal(beforeDta, &a); err != nil {
return err
}
}
if b, ok = after.([]Value); !ok {
afterDta, err := json.Marshal(after)
if err != nil {
return err
}
if err = json.Unmarshal(afterDta, &b); err != nil {
return err
}
}
// Generate remove/add events
var i, j int
// Do a LCS matrix calculation
// https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
s := 0
m := len(a)
n := len(b)
// Trim of matches at the start and end
for s < m && s < n && a[s].Equal(b[s]) {
s++
}
if s == m && s == n {
return nil
}
for s < m && s < n && a[m-1].Equal(b[n-1]) {
m--
n--
}
var aa, bb []Value
if s > 0 || m < len(a) {
aa = a[s:m]
m = m - s
} else {
aa = a
}
if s > 0 || n < len(b) {
bb = b[s:n]
n = n - s
} else {
bb = b
}
// Create matrix and initialize it
w := m + 1
c := make([]int, w*(n+1))
for i = 0; i < m; i++ {
for j = 0; j < n; j++ {
if aa[i].Equal(bb[j]) {
c[(i+1)+w*(j+1)] = c[i+w*j] + 1
} else {
v1 := c[(i+1)+w*j]
v2 := c[i+w*(j+1)]
if v2 > v1 {
c[(i+1)+w*(j+1)] = v2
} else {
c[(i+1)+w*(j+1)] = v1
}
}
}
}
idx := m + s
i = m
j = n
rems := 0
var adds [][3]int
addCount := n - c[w*(n+1)-1]
if addCount > 0 {
adds = make([][3]int, 0, addCount)
}
Loop:
for {
m = i - 1
n = j - 1
switch {
case i > 0 && j > 0 && aa[m].Equal(bb[n]):
idx--
i--
j--
case j > 0 && (i == 0 || c[i+w*n] >= c[m+w*j]):
adds = append(adds, [3]int{n, idx, rems})
j--
case i > 0 && (j == 0 || c[i+w*n] < c[m+w*j]):
idx--
r.RemoveEvent(idx)
rems++
i--
default:
break Loop
}
}
// Do the adds
l := len(adds) - 1
for i := l; i >= 0; i-- {
add := adds[i]
r.AddEvent(bb[add[0]], add[1]-rems+add[2]+l-i)
}
return nil
}