blob: 936a79abbd2f7e8e5a46c9a4dcf61ebd80bc0b59 [file] [log] [blame]
Stephane Barbarie4a2564d2018-07-26 11:02:58 -04001package model
2
3import (
4 "fmt"
5 "github.com/golang/protobuf/proto"
6 "reflect"
7 "strings"
8)
9
10const (
11 NONE string = "none"
12)
13
14type Node struct {
15 root *Root
16 Type interface{}
17 Branches map[string]*Branch
18 Tags map[string]*Revision
19 Proxy *Proxy
20 EventBus *EventBus
21 AutoPrune bool
22}
23
24func NewNode(root *Root, initialData interface{}, autoPrune bool, txid string) *Node {
25 cn := &Node{}
26
27 cn.root = root
28 cn.Branches = make(map[string]*Branch)
29 cn.Tags = make(map[string]*Revision)
30 cn.Proxy = nil
31 cn.EventBus = nil
32 cn.AutoPrune = autoPrune
33
34 if IsProtoMessage(initialData) {
35 cn.Type = reflect.ValueOf(initialData).Interface()
36 dataCopy := proto.Clone(initialData.(proto.Message))
37 cn.initialize(dataCopy, txid)
38 } else if reflect.ValueOf(initialData).IsValid() {
39 cn.Type = reflect.ValueOf(initialData).Interface()
40 } else {
41 // not implemented error
42 fmt.Errorf("cannot process initial data - %+v", initialData)
43 }
44
45 return cn
46}
47
48func (cn *Node) makeNode(data interface{}, txid string) *Node {
49 return NewNode(cn.root, data, true, txid)
50}
51
52func (cn *Node) makeRevision(branch *Branch, data interface{}, children map[string][]*Revision) *Revision {
53 return cn.root.makeRevision(branch, data, children)
54}
55
56func (cn *Node) makeLatest(branch *Branch, revision *Revision, changeAnnouncement map[string]interface{}) {
57 if _, ok := branch.revisions[revision.Hash]; !ok {
58 branch.revisions[revision.Hash] = revision
59 }
60
61 if branch.Latest == nil || revision.Hash != branch.Latest.Hash {
62 branch.Latest = revision
63 }
64
65 if changeAnnouncement != nil && branch.Txid == "" {
66 if cn.Proxy != nil {
67 for changeType, data := range changeAnnouncement {
68 // TODO: Invoke callback
69 fmt.Printf("invoking callback - changeType: %+v, data:%+v\n", changeType, data)
70 }
71 }
72
73 for changeType, data := range changeAnnouncement {
74 // TODO: send notifications
75 fmt.Printf("sending notification - changeType: %+v, data:%+v\n", changeType, data)
76 }
77 }
78}
79
80func (cn *Node) Latest() *Revision {
81 if branch, exists := cn.Branches[NONE]; exists {
82 return branch.Latest
83 }
84 return nil
85}
86
87func (cn *Node) GetHash(hash string) *Revision {
88 return cn.Branches[NONE].revisions[hash]
89}
90
91func (cn *Node) initialize(data interface{}, txid string) {
92 var children map[string][]*Revision
93 children = make(map[string][]*Revision)
94 for fieldName, field := range ChildrenFields(cn.Type) {
95 fieldValue := GetAttributeValue(data, fieldName, 0)
96
97 if fieldValue.IsValid() {
98 if field.IsContainer {
99 if field.Key != "" {
100 var keysSeen []string
101
102 for i := 0; i < fieldValue.Len(); i++ {
103 v := fieldValue.Index(i)
104 rev := cn.makeNode(v.Interface(), txid).Latest()
105 key := GetAttributeValue(v.Interface(), field.Key, 0)
106 for _, k := range keysSeen {
107 if k == key.String() {
108 fmt.Errorf("duplicate key - %s", k)
109 }
110 }
111 children[fieldName] = append(children[fieldName], rev)
112 keysSeen = append(keysSeen, key.String())
113 }
114
115 } else {
116 for i := 0; i < fieldValue.Len(); i++ {
117 v := fieldValue.Index(i)
118 children[fieldName] = append(children[fieldName], cn.makeNode(v.Interface(), txid).Latest())
119 }
120 }
121 } else {
122 children[fieldName] = append(children[fieldName], cn.makeNode(fieldValue.Interface(), txid).Latest())
123 }
124 } else {
125 fmt.Errorf("field is invalid - %+v", fieldValue)
126 }
127 }
128 // FIXME: ClearField??? No such method in go protos. Reset?
129 //data.ClearField(field_name)
130 branch := NewBranch(cn, "", nil, cn.AutoPrune)
131 rev := cn.makeRevision(branch, data, children)
132 cn.makeLatest(branch, rev, nil)
133 cn.Branches[txid] = branch
134}
135
136func (cn *Node) makeTxBranch(txid string) *Branch {
137 branchPoint := cn.Branches[NONE].Latest
138 branch := NewBranch(cn, txid, branchPoint, true)
139 cn.Branches[txid] = branch
140 return branch
141}
142
143func (cn *Node) deleteTxBranch(txid string) {
144 delete(cn.Branches, txid)
145}
146
147type t_makeBranch func(*Node) *Branch
148
149//
150// Get operation
151//
152func (cn *Node) Get(path string, hash string, depth int, deep bool, txid string) interface{} {
153 if deep {
154 depth = -1
155 }
156
157 for strings.HasPrefix(path, "/") {
158 path = path[1:]
159 }
160
161 var branch *Branch
162 var rev *Revision
163
164 // FIXME: should empty txid be cleaned up?
165 if branch = cn.Branches[txid]; txid == "" || branch == nil {
166 branch = cn.Branches[NONE]
167 }
168
169 if hash != "" {
170 rev = branch.revisions[hash]
171 } else {
172 rev = branch.Latest
173 }
174
175 return cn.get(rev, path, depth)
176}
177
178func (cn *Node) findRevByKey(revs []*Revision, keyName string, value string) (int, *Revision) {
179 for i, rev := range revs {
180 dataValue := reflect.ValueOf(rev.Config.Data)
181 dataStruct := GetAttributeStructure(rev.Config.Data, keyName, 0)
182
183 fieldValue := dataValue.Elem().FieldByName(dataStruct.Name)
184
185 if fieldValue.Interface().(string) == value {
186 return i, rev
187 }
188 }
189
190 fmt.Errorf("key %s=%s not found", keyName, value)
191
192 return -1, nil
193}
194
195func (cn *Node) get(rev *Revision, path string, depth int) interface{} {
196 if path == "" {
197 return cn.doGet(rev, depth)
198 }
199
200 partition := strings.SplitN(path, "/", 2)
201 name := partition[0]
202 path = partition[1]
203
204 field := ChildrenFields(cn.Type)[name]
205
206 if field.IsContainer {
207 if field.Key != "" {
208 children := rev.Children[name]
209 if path != "" {
210 partition = strings.SplitN(path, "/", 2)
211 key := partition[0]
212 path = ""
213 key = field.KeyFromStr(key).(string)
214 _, childRev := cn.findRevByKey(children, field.Key, key)
215 childNode := childRev.getNode()
216 return childNode.get(childRev, path, depth)
217 } else {
218 var response []interface{}
219 for _, childRev := range children {
220 childNode := childRev.getNode()
221 value := childNode.doGet(childRev, depth)
222 response = append(response, value)
223 }
224 return response
225 }
226 } else {
227 childRev := rev.Children[name][0]
228 childNode := childRev.getNode()
229 return childNode.get(childRev, path, depth)
230 }
231 }
232 return nil
233}
234
235func (cn *Node) doGet(rev *Revision, depth int) interface{} {
236 msg := rev.Get(depth)
237
238 if cn.Proxy != nil {
239 // TODO: invoke GET callback
240 fmt.Println("invoking proxy GET Callbacks")
241 }
242 return msg
243}
244
245//
246// Update operation
247//
248func (n *Node) Update(path string, data interface{}, strict bool, txid string, makeBranch t_makeBranch) *Revision {
249 // FIXME: is this required ... a bit overkill to take out a "/"
250 for strings.HasPrefix(path, "/") {
251 path = path[1:]
252 }
253
254 var branch *Branch
255 var ok bool
256 if branch, ok = n.Branches[txid]; !ok {
257 branch = makeBranch(n)
258 }
259
260 if path == "" {
261 return n.doUpdate(branch, data, strict)
262 }
263 return &Revision{}
264}
265
266func (n *Node) doUpdate(branch *Branch, data interface{}, strict bool) *Revision {
267 if reflect.TypeOf(data) != n.Type {
268 // TODO raise error
269 fmt.Errorf("data does not match type: %+v", n.Type)
270 }
271
272 // TODO: noChildren?
273
274 if n.Proxy != nil {
275 // TODO: n.proxy.InvokeCallbacks(CallbackType.PRE_UPDATE, data)
276 fmt.Println("invoking proxy PRE_UPDATE Callbacks")
277 }
278 if branch.Latest.getData() != data {
279 if strict {
280 // TODO: checkAccessViolations(data, branch.GetLatest.data)
281 fmt.Println("checking access violations")
282 }
283 rev := branch.Latest.UpdateData(data, branch)
284 n.makeLatest(branch, rev, nil) // TODO -> changeAnnouncement needs to be a tuple (CallbackType.POST_UPDATE, rev.data)
285 return rev
286 } else {
287 return branch.Latest
288 }
289}
290
291// TODO: the python implementation has a method to check if the data has no children
292//func (n *SomeNode) noChildren(data interface{}) bool {
293// for fieldName, field := range ChildrenFields(n.Type) {
294// fieldValue := GetAttributeValue(data, fieldName)
295//
296// if fieldValue.IsValid() {
297// if field.IsContainer {
298// if len(fieldValue) > 0 {
299//
300// }
301// } else {
302//
303// }
304//
305// }
306// }
307//}
308
309//
310// Add operation
311//
312func (n *Node) Add(path string, data interface{}, txid string, makeBranch t_makeBranch) *Revision {
313 for strings.HasPrefix(path, "/") {
314 path = path[1:]
315 }
316 if path == "" {
317 // TODO raise error
318 fmt.Errorf("cannot add for non-container mode\n")
319 }
320
321 var branch *Branch
322 var ok bool
323 if branch, ok = n.Branches[txid]; !ok {
324 branch = makeBranch(n)
325 }
326
327 rev := branch.Latest
328
329 partition := strings.SplitN(path, "/", 2)
330 name := partition[0]
331 path = partition[1]
332
333 field := ChildrenFields(n.Type)[name]
334 var children []*Revision
335
336 if field.IsContainer {
337 if path == "" {
338 if field.Key != "" {
339 if n.Proxy != nil {
340 // TODO -> n.proxy.InvokeCallbacks(PRE_ADD, data)
341 fmt.Println("invoking proxy PRE_ADD Callbacks")
342 }
343
344 copy(children, rev.Children[name])
345 key := GetAttributeValue(data, field.Key, 0)
346 if _, rev := n.findRevByKey(children, field.Key, key.String()); rev != nil {
347 // TODO raise error
348 fmt.Errorf("duplicate key found: %s", key.String())
349 }
350
351 childRev := n.makeNode(data, "").Latest()
352 children = append(children, childRev)
353 rev := rev.UpdateChildren(name, children, branch)
354 n.makeLatest(branch, rev, nil) // TODO -> changeAnnouncement needs to be a tuple (CallbackType.POST_ADD, rev.data)
355 return rev
356 } else {
357 fmt.Errorf("cannot add to non-keyed container\n")
358 }
359 } else if field.Key != "" {
360 partition := strings.SplitN(path, "/", 2)
361 key := partition[0]
362 path = partition[1]
363 key = field.KeyFromStr(key).(string)
364 copy(children, rev.Children[name])
365 idx, childRev := n.findRevByKey(children, field.Key, key)
366 childNode := childRev.getNode()
367 newChildRev := childNode.Add(path, data, txid, makeBranch)
368 children[idx] = newChildRev
369 rev := rev.UpdateChildren(name, children, branch)
370 n.makeLatest(branch, rev, nil)
371 return rev
372 } else {
373 fmt.Errorf("cannot add to non-keyed container\n")
374 }
375 } else {
376 fmt.Errorf("cannot add to non-container field\n")
377 }
378 return nil
379}
380
381//
382// Remove operation
383//
384func (n *Node) Remove(path string, txid string, makeBranch t_makeBranch) *Revision {
385 for strings.HasPrefix(path, "/") {
386 path = path[1:]
387 }
388 if path == "" {
389 // TODO raise error
390 fmt.Errorf("cannot remove for non-container mode\n")
391 }
392 var branch *Branch
393 var ok bool
394 if branch, ok = n.Branches[txid]; !ok {
395 branch = makeBranch(n)
396 }
397
398 rev := branch.Latest
399
400 partition := strings.SplitN(path, "/", 2)
401 name := partition[0]
402 path = partition[1]
403
404 field := ChildrenFields(n.Type)[name]
405 var children []*Revision
406 post_anno := make(map[string]interface{})
407
408 if field.IsContainer {
409 if path == "" {
410 fmt.Errorf("cannot remove without a key\n")
411 } else if field.Key != "" {
412 partition := strings.SplitN(path, "/", 2)
413 key := partition[0]
414 path = partition[1]
415 key = field.KeyFromStr(key).(string)
416 if path != "" {
417 copy(children, rev.Children[name])
418 idx, childRev := n.findRevByKey(children, field.Key, key)
419 childNode := childRev.getNode()
420 newChildRev := childNode.Remove(path, txid, makeBranch)
421 children[idx] = newChildRev
422 rev := rev.UpdateChildren(name, children, branch)
423 n.makeLatest(branch, rev, nil)
424 return rev
425 } else {
426 copy(children, rev.Children[name])
427 idx, childRev := n.findRevByKey(children, field.Key, key)
428 if n.Proxy != nil {
429 data := childRev.getData()
430 fmt.Println("invoking proxy PRE_REMOVE Callbacks")
431 fmt.Printf("setting POST_REMOVE Callbacks : %+v\n", data)
432 } else {
433 fmt.Println("setting POST_REMOVE Callbacks")
434 }
435 children = append(children[:idx], children[idx+1:]...)
436 rev := rev.UpdateChildren(name, children, branch)
437 n.makeLatest(branch, rev, post_anno)
438 return rev
439 }
440 } else {
441 fmt.Errorf("cannot add to non-keyed container\n")
442 }
443 } else {
444 fmt.Errorf("cannot add to non-container field\n")
445 }
446
447 return nil
448}
449
450func (n *Node) LoadLatest(kvStore *Backend, hash string) {
451 branch := NewBranch(n, "", nil, n.AutoPrune)
452 pr := &PersistedRevision{}
453 rev := pr.load(branch, kvStore, n.Type, hash)
454 n.makeLatest(branch, rev.Revision, nil)
455 n.Branches[NONE] = branch
456}