-
Notifications
You must be signed in to change notification settings - Fork 49
/
helpers.go
526 lines (421 loc) · 13.4 KB
/
helpers.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
/*
* EliasDB
*
* Copyright 2016 Matthias Ladkau. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package graph
import (
"bytes"
"encoding/binary"
"encoding/gob"
"fmt"
"strings"
"github.com/krotik/common/stringutil"
"github.com/krotik/eliasdb/graph/data"
"github.com/krotik/eliasdb/graph/util"
"github.com/krotik/eliasdb/hash"
"github.com/krotik/eliasdb/storage"
)
// Helper functions for GraphManager
// =================================
/*
checkPartitionName checks if a given partition name is valid.
*/
func (gm *Manager) checkPartitionName(part string) error {
if !stringutil.IsAlphaNumeric(part) {
return &util.GraphError{
Type: util.ErrInvalidData,
Detail: fmt.Sprintf("Partition name %v is not alphanumeric - can only contain [a-zA-Z0-9_]", part),
}
}
return nil
}
/*
checkNode checks if a given node can be written to the datastore.
*/
func (gm *Manager) checkNode(node data.Node) error {
return gm.checkItemGeneral(node, "Node")
}
/*
checkItemGeneral checks the general properties of a given graph item.
*/
func (gm *Manager) checkItemGeneral(node data.Node, name string) error {
if node.Key() == "" {
return &util.GraphError{Type: util.ErrInvalidData, Detail: name + " is missing a key value"}
}
if node.Kind() == "" {
return &util.GraphError{Type: util.ErrInvalidData, Detail: name + " is missing a kind value"}
}
if !stringutil.IsAlphaNumeric(node.Kind()) {
return &util.GraphError{
Type: util.ErrInvalidData,
Detail: fmt.Sprintf("%v kind %v is not alphanumeric - can only contain [a-zA-Z0-9_]", name, node.Kind()),
}
}
for attr := range node.Data() {
if attr == "" {
return &util.GraphError{Type: util.ErrInvalidData, Detail: name + " contains empty string attribute name"}
}
}
return nil
}
/*
checkEdge checks if a given edge can be written to the datastore.
*/
func (gm *Manager) checkEdge(edge data.Edge) error {
if err := gm.checkItemGeneral(edge, "Edge"); err != nil {
return err
}
if edge.End1Key() == "" {
return &util.GraphError{Type: util.ErrInvalidData, Detail: "Edge is missing a key value for end1"}
}
if edge.End1Kind() == "" {
return &util.GraphError{Type: util.ErrInvalidData, Detail: "Edge is missing a kind value for end1"}
}
if edge.End1Role() == "" {
return &util.GraphError{Type: util.ErrInvalidData, Detail: "Edge is missing a role value for end1"}
} else if !stringutil.IsAlphaNumeric(edge.End1Role()) {
return &util.GraphError{
Type: util.ErrInvalidData,
Detail: fmt.Sprintf("Edge role %v is not alphanumeric - can only contain [a-zA-Z0-9_]", edge.End1Role()),
}
}
if _, ok := edge.Attr(data.EdgeEnd1Cascading).(bool); !ok {
return &util.GraphError{Type: util.ErrInvalidData, Detail: "Edge is missing a cascading value for end1"}
}
if edge.End2Key() == "" {
return &util.GraphError{Type: util.ErrInvalidData, Detail: "Edge is missing a key value for end2"}
}
if edge.End2Kind() == "" {
return &util.GraphError{Type: util.ErrInvalidData, Detail: "Edge is missing a kind value for end2"}
}
if edge.End2Role() == "" {
return &util.GraphError{Type: util.ErrInvalidData, Detail: "Edge is missing a role value for end2"}
} else if !stringutil.IsAlphaNumeric(edge.End2Role()) {
return &util.GraphError{
Type: util.ErrInvalidData,
Detail: fmt.Sprintf("Edge role %v is not alphanumeric - can only contain [a-zA-Z0-9_]", edge.End2Role()),
}
}
if _, ok := edge.Attr(data.EdgeEnd2Cascading).(bool); !ok {
return &util.GraphError{Type: util.ErrInvalidData, Detail: "Edge is missing a cascading value for end2"}
}
return nil
}
/*
writeNodeCount writes a new node count for a specific kind to the datastore.
*/
func (gm *Manager) writeNodeCount(kind string, count uint64, flush bool) error {
numstr := make([]byte, 8)
binary.LittleEndian.PutUint64(numstr, count)
gm.gs.MainDB()[MainDBNodeCount+kind] = string(numstr)
if flush {
return gm.gs.FlushMain()
}
return nil
}
/*
writeEdgeCount writes a new edge count for a specific kind to the datastore.
*/
func (gm *Manager) writeEdgeCount(kind string, count uint64, flush bool) error {
numstr := make([]byte, 8)
binary.LittleEndian.PutUint64(numstr, count)
gm.gs.MainDB()[MainDBEdgeCount+kind] = string(numstr)
if flush {
return gm.gs.FlushMain()
}
return nil
}
/*
getNodeStorageHTree gets two HTree instances which can be used to store nodes.
This function ensures that depending entries in other datastructures do exist.
*/
func (gm *Manager) getNodeStorageHTree(part string, kind string,
create bool) (*hash.HTree, *hash.HTree, error) {
gm.storageMutex.Lock()
defer gm.storageMutex.Unlock()
// Check if the partition name is valid
if err := gm.checkPartitionName(part); err != nil {
return nil, nil, err
}
// Check if the node kind is valid
if !stringutil.IsAlphaNumeric(kind) {
return nil, nil, &util.GraphError{
Type: util.ErrInvalidData,
Detail: fmt.Sprintf("Node kind %v is not alphanumeric - can only contain [a-zA-Z0-9_]", kind),
}
}
// Make sure all required lookup maps are there
if gm.getMainDBMap(MainDBNodeKinds) == nil {
gm.storeMainDBMap(MainDBNodeKinds, make(map[string]string))
}
if gm.getMainDBMap(MainDBParts) == nil {
gm.storeMainDBMap(MainDBParts, make(map[string]string))
}
if gm.getMainDBMap(MainDBNodeAttrs+kind) == nil {
gm.storeMainDBMap(MainDBNodeAttrs+kind, make(map[string]string))
}
if gm.getMainDBMap(MainDBNodeEdges+kind) == nil {
gm.storeMainDBMap(MainDBNodeEdges+kind, make(map[string]string))
}
if _, ok := gm.gs.MainDB()[MainDBNodeCount+kind]; !ok {
gm.gs.MainDB()[MainDBNodeCount+kind] = string(make([]byte, 8, 8))
}
// Return the actual storage
gs := gm.gs.StorageManager(part+kind+StorageSuffixNodes, create)
if gs == nil {
return nil, nil, nil
}
attrTree, err := gm.getHTree(gs, RootIDNodeHTree)
if err != nil {
return nil, nil, err
}
valTree, err := gm.getHTree(gs, RootIDNodeHTreeSecond)
if err != nil {
return nil, nil, err
}
return attrTree, valTree, nil
}
/*
getEdgeStorageHTree gets a HTree which can be used to store edges. This function ensures that depending
entries in other datastructures do exist.
*/
func (gm *Manager) getEdgeStorageHTree(part string, kind string, create bool) (*hash.HTree, error) {
gm.storageMutex.Lock()
defer gm.storageMutex.Unlock()
// Check if the partition name is valid
if err := gm.checkPartitionName(part); err != nil {
return nil, err
}
// Check if the edge kind is valid
if !stringutil.IsAlphaNumeric(kind) {
return nil, &util.GraphError{
Type: util.ErrInvalidData,
Detail: fmt.Sprintf("Edge kind %v is not alphanumeric - can only contain [a-zA-Z0-9_]", kind),
}
}
// Make sure all required lookup maps are there
if gm.getMainDBMap(MainDBEdgeKinds) == nil {
gm.storeMainDBMap(MainDBEdgeKinds, make(map[string]string))
}
if gm.getMainDBMap(MainDBEdgeAttrs+kind) == nil {
gm.storeMainDBMap(MainDBEdgeAttrs+kind, make(map[string]string))
}
if _, ok := gm.gs.MainDB()[MainDBEdgeCount+kind]; !ok {
gm.gs.MainDB()[MainDBEdgeCount+kind] = string(make([]byte, 8, 8))
}
// Return the actual storage
gs := gm.gs.StorageManager(part+kind+StorageSuffixEdges, create)
if gs == nil {
return nil, nil
}
return gm.getHTree(gs, RootIDNodeHTree)
}
/*
getNodeIndexHTree gets a HTree which can be used to index nodes.
*/
func (gm *Manager) getNodeIndexHTree(part string, kind string, create bool) (*hash.HTree, error) {
return gm.getIndexHTree(part, kind, create, "Node", StorageSuffixNodesIndex)
}
/*
getEdgeIndexHTree gets a HTree which can be used to index edges.
*/
func (gm *Manager) getEdgeIndexHTree(part string, kind string, create bool) (*hash.HTree, error) {
return gm.getIndexHTree(part, kind, create, "Edge", StorageSuffixEdgesIndex)
}
/*
getIndexHTree gets a HTree which can be used to index items.
*/
func (gm *Manager) getIndexHTree(part string, kind string, create bool, name string, suffix string) (*hash.HTree, error) {
gm.storageMutex.Lock()
defer gm.storageMutex.Unlock()
// Check if the partition name is valid
if err := gm.checkPartitionName(part); err != nil {
return nil, err
}
// Check if the kind is valid
if !stringutil.IsAlphaNumeric(kind) {
return nil, &util.GraphError{
Type: util.ErrInvalidData,
Detail: fmt.Sprintf("%v kind %v is not alphanumeric - can only contain [a-zA-Z0-9_]", name, kind),
}
}
gs := gm.gs.StorageManager(part+kind+suffix, create)
if gs == nil {
return nil, nil
}
return gm.getHTree(gs, RootIDNodeHTree)
}
/*
flushNodeStorage flushes a node storage.
*/
func (gm *Manager) flushNodeStorage(part string, kind string) error {
if sm := gm.gs.StorageManager(part+kind+StorageSuffixNodes, false); sm != nil {
if err := sm.Flush(); err != nil {
return &util.GraphError{Type: util.ErrFlushing, Detail: err.Error()}
}
}
return nil
}
/*
flushNodeIndex flushes a node index.
*/
func (gm *Manager) flushNodeIndex(part string, kind string) error {
if sm := gm.gs.StorageManager(part+kind+StorageSuffixNodesIndex, false); sm != nil {
if err := sm.Flush(); err != nil {
return &util.GraphError{Type: util.ErrFlushing, Detail: err.Error()}
}
}
return nil
}
/*
flushEdgeStorage flushes an edge storage.
*/
func (gm *Manager) flushEdgeStorage(part string, kind string) error {
if sm := gm.gs.StorageManager(part+kind+StorageSuffixEdges, false); sm != nil {
if err := sm.Flush(); err != nil {
return &util.GraphError{Type: util.ErrFlushing, Detail: err.Error()}
}
}
return nil
}
/*
flushEdgeIndex flushes an edge index.
*/
func (gm *Manager) flushEdgeIndex(part string, kind string) error {
if sm := gm.gs.StorageManager(part+kind+StorageSuffixEdgesIndex, false); sm != nil {
if err := sm.Flush(); err != nil {
return &util.GraphError{Type: util.ErrFlushing, Detail: err.Error()}
}
}
return nil
}
/*
rollbackNodeStorage rollbacks a node storage.
*/
func (gm *Manager) rollbackNodeStorage(part string, kind string) error {
if sm := gm.gs.StorageManager(part+kind+StorageSuffixNodes, false); sm != nil {
if err := sm.Rollback(); err != nil {
return &util.GraphError{Type: util.ErrRollback, Detail: err.Error()}
}
}
return nil
}
/*
rollbackNodeIndex rollbacks a node index.
*/
func (gm *Manager) rollbackNodeIndex(part string, kind string) error {
if sm := gm.gs.StorageManager(part+kind+StorageSuffixNodesIndex, false); sm != nil {
if err := sm.Rollback(); err != nil {
return &util.GraphError{Type: util.ErrRollback, Detail: err.Error()}
}
}
return nil
}
/*
rollbackEdgeStorage rollbacks an edge storage.
*/
func (gm *Manager) rollbackEdgeStorage(part string, kind string) error {
if sm := gm.gs.StorageManager(part+kind+StorageSuffixEdges, false); sm != nil {
if err := sm.Rollback(); err != nil {
return &util.GraphError{Type: util.ErrRollback, Detail: err.Error()}
}
}
return nil
}
/*
rollbackEdgeIndex rollbacks an edge index.
*/
func (gm *Manager) rollbackEdgeIndex(part string, kind string) error {
if sm := gm.gs.StorageManager(part+kind+StorageSuffixEdgesIndex, false); sm != nil {
if err := sm.Rollback(); err != nil {
return &util.GraphError{Type: util.ErrRollback, Detail: err.Error()}
}
}
return nil
}
/*
getHTree creates or loads a HTree from a given StorageManager. HTrees are not cached
since the creation shouldn't have too much overhead.
*/
func (gm *Manager) getHTree(sm storage.Manager, slot int) (*hash.HTree, error) {
var htree *hash.HTree
var err error
loc := sm.Root(slot)
if loc == 0 {
// Create a new HTree and store its location
htree, err = hash.NewHTree(sm)
if err != nil {
err = &util.GraphError{Type: util.ErrAccessComponent, Detail: err.Error()}
} else {
sm.SetRoot(slot, htree.Location())
}
} else {
// Load existing HTree
htree, err = hash.LoadHTree(sm, loc)
if err != nil {
err = &util.GraphError{Type: util.ErrAccessComponent, Detail: err.Error()}
}
}
return htree, err
}
/*
getMainDBMap gets a map from the main database.
*/
func (gm *Manager) getMainDBMap(key string) map[string]string {
// First try to cache
mapval, ok := gm.mapCache[key]
if ok {
return mapval
}
// Lookup map and decode it
val, ok := gm.gs.MainDB()[key]
if ok {
mapval = stringToMap(val)
gm.mapCache[key] = mapval
}
return mapval
}
/*
storeMainDBMap stores a map in the main database. The map is stored as a gob byte slice.
Once it has been decoded it is cached for read operations.
*/
func (gm *Manager) storeMainDBMap(key string, mapval map[string]string) {
gm.mapCache[key] = mapval
gm.gs.MainDB()[key] = mapToString(mapval)
}
// Static helper functions
// =======================
/*
IsFullSpec is a function to determine if a given spec is a fully specified spec
(i.e. all spec components are specified)
*/
func IsFullSpec(spec string) bool {
sspec := strings.Split(spec, ":")
if len(sspec) != 4 || sspec[0] == "" || sspec[1] == "" || sspec[2] == "" || sspec[3] == "" {
return false
}
return true
}
/*
mapToString turns a map of strings into a single string.
*/
func mapToString(stringmap map[string]string) string {
bb := &bytes.Buffer{}
gob.NewEncoder(bb).Encode(stringmap)
return string(bb.Bytes())
}
/*
stringToMap turns a string into a map of strings.
*/
func stringToMap(mapString string) map[string]string {
var stringmap map[string]string
if err := gob.NewDecoder(bytes.NewBufferString(mapString)).Decode(&stringmap); err != nil {
panic(fmt.Sprint("Cannot decode:", mapString, err))
}
return stringmap
}