/
dataset.go
1112 lines (968 loc) · 32 KB
/
dataset.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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 MIMIRO AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"bytes"
"context"
b64 "encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"reflect"
"sync"
"sync/atomic"
"time"
"github.com/dgraph-io/badger/v4"
)
type fullSyncLease struct {
ctx context.Context
cancel func()
}
type ProxyDatasetConfig struct {
RemoteURL string `json:"remoteUrl"`
UpstreamTransform string `json:"upstreamTransform"`
DownstreamTransform string `json:"downstreamTransform"`
AuthProviderName string `json:"authProviderName"`
}
// Dataset data structure
type Dataset struct {
ID string `json:"id"`
InternalID uint32 `json:"internalId"`
SubjectIdentifier string `json:"subjectIdentifier"`
store *Store
WriteLock sync.Mutex
fullSyncStarted bool
fullSyncLease *fullSyncLease
fullSyncSeen map[uint64]int
isChangeCache bool // indicates if this is a local change cache
dataChangeNotifiers []string // list of endpoints to ping after new batch committed.
cache []*Entity // cache of recently updated entities.
cacheStartOffset uint32 // log position start in cache
markedForDeletion bool
PublicNamespaces []string `json:"publicNamespaces"`
fullSyncID string
ProxyConfig *ProxyDatasetConfig `json:"proxyConfig"`
}
// NewDataset Create a new dataset from the params provided
func NewDataset(store *Store, id string, internalID uint32, subjectIdentifier string) *Dataset {
dataset := Dataset{}
dataset.store = store
dataset.ID = id
dataset.InternalID = internalID
dataset.SubjectIdentifier = subjectIdentifier
return &dataset
}
// StartFullSync Indicates that a full sync is starting
func (ds *Dataset) StartFullSync() error {
if ds.fullSyncStarted {
if ds.fullSyncLease != nil && ds.fullSyncLease.cancel != nil {
ds.fullSyncLease.cancel()
}
ds.fullSyncLease = nil
ds.fullSyncID = ""
}
ds.fullSyncStarted = true
ds.fullSyncSeen = make(map[uint64]int)
return nil
}
func (ds *Dataset) StartFullSyncWithLease(fullSyncID string) error {
if err := ds.StartFullSync(); err != nil {
return err
}
ds.fullSyncID = fullSyncID
return ds.RefreshFullSyncLease(fullSyncID)
}
func (ds *Dataset) RefreshFullSyncLease(fullSyncID string) error {
if ds.fullSyncStarted {
if fullSyncID == ds.fullSyncID {
// cancel previous lease
if ds.fullSyncLease != nil && ds.fullSyncLease.cancel != nil {
ds.fullSyncLease.cancel()
}
// start new lease
ctx, cancel := context.WithTimeout(context.Background(), ds.store.fullsyncLeaseTimeout)
ds.fullSyncLease = &fullSyncLease{
ctx,
cancel,
}
go func() {
currentFsID := ds.fullSyncID
<-ctx.Done()
endTime, ok := ctx.Deadline()
// time out was the cause
now := time.Now()
if ok && now.After(endTime) && ds.fullSyncID == currentFsID {
ds.fullSyncStarted = false
ds.fullSyncSeen = make(map[uint64]int)
ds.fullSyncID = ""
ds.fullSyncLease = nil
} // else, canceled by refresh. do nothing
}()
return nil
}
return fmt.Errorf("given fullsyncId %v does not match running fullsync id %v", fullSyncID, ds.fullSyncID)
} else if fullSyncID != "" {
return fmt.Errorf("fullsync with sync-id %v is not running", fullSyncID)
}
return nil
}
func (ds *Dataset) ReleaseFullSyncLease(fullSyncID string) error {
if ds.fullSyncLease == nil {
return errors.New("no active fullsync lease found, can't complete")
}
if ds.fullSyncLease != nil && ds.fullSyncLease.cancel != nil {
ds.fullSyncLease.cancel()
}
return nil
}
// CompleteFullSync Full sync completed - mark unseen entities as deleted
func (ds *Dataset) CompleteFullSync(ctx context.Context) error {
defer func() {
ds.fullSyncStarted = false
ds.fullSyncSeen = make(map[uint64]int) // release sync state
ds.fullSyncLease = nil // unset lease
ds.fullSyncID = "" // unset id
}()
// check all seen and mark deleted
txn := ds.store.database.NewTransaction(true)
defer txn.Discard()
deleteBatch := make([]*Entity, 0)
_, err := ds.MapEntities("", -1, func(e *Entity) error {
if ctx.Err() != nil {
return ctx.Err()
}
if !e.IsDeleted {
_, ok := ds.fullSyncSeen[e.InternalID]
if !ok {
// data no longer in source so delete it
e.IsDeleted = true
deleteBatch = append(deleteBatch, e)
}
if len(deleteBatch) == 1000 {
err := ds.StoreEntities(deleteBatch)
if err != nil {
return err
}
deleteBatch = make([]*Entity, 0)
}
}
return nil
})
if err != nil {
return err
}
// store remaining
if len(deleteBatch) > 0 {
err := ds.StoreEntities(deleteBatch)
if err != nil {
return err
}
}
return nil
}
// GetStorageKey gets storage key for storing dataset in database
func (ds *Dataset) getStorageKey() []byte {
key := make([]byte, 2+len(ds.ID))
binary.BigEndian.PutUint16(key, SysDatasetsID)
copy(key[2:], ds.ID)
return key
}
func (ds *Dataset) StoreEntities(entities []*Entity) (Error error) {
tags := []string{
"application:datahub",
fmt.Sprintf("dataset:%s", ds.ID),
}
if len(entities) == 0 {
return nil
}
ds.WriteLock.Lock()
writeLockStart := time.Now()
// release lock at end regardless
defer func() {
_ = ds.store.statsdClient.Timing("ds.writeLock.time", time.Since(writeLockStart), tags, 1)
ds.WriteLock.Unlock()
}()
// need this to ensure time moves forward in high perf environments.
time.Sleep(time.Nanosecond * 1)
txnTime := time.Now().UnixNano()
txn := ds.store.database.NewTransaction(true)
defer txn.Discard()
newitems, err := ds.StoreEntitiesWithTransaction(entities, txnTime, txn)
if err != nil {
return err
}
err = ds.store.commitIDTxn()
if err != nil {
return err
}
err = txn.Commit()
if err != nil {
return err
}
err = ds.updateDataset(newitems, entities)
if err != nil {
return err
}
return nil
}
// StoreEntities
func (ds *Dataset) StoreEntitiesWithTransaction(
entities []*Entity,
txnTime int64,
txn *badger.Txn,
) (newitems int64, Error error) {
tags := []string{
"application:datahub",
fmt.Sprintf("dataset:%s", ds.ID),
}
newitems = 0
if len(entities) == 0 {
return newitems, nil
}
_ = ds.store.statsdClient.Count("ds.added.items", int64(len(entities)), tags, 1)
// time now as uint64
/* txnTime := time.Now().UnixNano()
txn := ds.store.database.NewTransaction(true)
defer txn.Discard() */
// get dataset seq
// fixme: can be part of the dataset data structure no need to open each txn as the is a mutex protecting it
datasetSeqKey := make([]byte, 6)
binary.BigEndian.PutUint16(datasetSeqKey, SysDatasetsSequences)
binary.BigEndian.PutUint32(datasetSeqKey[2:], ds.InternalID)
logseq, _ := ds.store.database.GetSequence(datasetSeqKey, 1000)
defer func() {
err := logseq.Release()
if err != nil {
Error = err
}
}()
isnew := false
var rid uint64
idCache := make(map[string]uint64)
localLatests := make(map[uint64][]byte)
rtxn := ds.store.database.NewTransaction(false)
defer rtxn.Discard()
for batchSeqNum, e := range entities {
// entityIDBuffer buffer for lookup in main index
// index_id;rid;dataset;time => blob
// unit16;unit64;uint32;uint64
entityIDBuffer := make([]byte, 24)
uid := e.ID
var err error
rid, isnew, err = ds.store.assertIDForURI(uid, idCache)
if err != nil {
return newitems, err
}
e.InternalID = rid // set internal id on entity
e.Recorded = uint64(txnTime)
if ds.fullSyncStarted {
ds.fullSyncSeen[e.InternalID] = 1
}
jsonData, _ := json.Marshal(e)
jsonLength := len(jsonData)
_ = ds.store.statsdClient.Count("ds.processed.bytes", int64(jsonLength), tags, 1)
binary.BigEndian.PutUint16(entityIDBuffer, EntityIDToJSONIndexID)
binary.BigEndian.PutUint64(entityIDBuffer[2:], rid)
binary.BigEndian.PutUint32(entityIDBuffer[10:], ds.InternalID)
binary.BigEndian.PutUint64(entityIDBuffer[14:], uint64(txnTime))
binary.BigEndian.PutUint16(entityIDBuffer[22:], uint16(batchSeqNum))
// assume different from a previous version
isDifferent := true
isDifferentLocally := true
datasetEntitiesLatestVersionKey := make([]byte, 14)
binary.BigEndian.PutUint16(datasetEntitiesLatestVersionKey, DatasetLatestEntities)
binary.BigEndian.PutUint32(datasetEntitiesLatestVersionKey[2:], ds.InternalID)
binary.BigEndian.PutUint64(datasetEntitiesLatestVersionKey[6:], rid)
// fixme: optimise to have txntime in key and not need a value
var previousEntityIDBuffer []byte
var prevEntity *Entity
var prevJSONData []byte
if !isnew {
if previousEntityIDBufferValue, err2 := rtxn.Get(datasetEntitiesLatestVersionKey); err2 == nil {
previousEntityIDBuffer, err2 = previousEntityIDBufferValue.ValueCopy(nil)
if err2 != nil {
return newitems, err2
}
prevJSONDataValue, err2 := rtxn.Get(previousEntityIDBuffer)
if err2 != nil {
return newitems, err2
}
prevJSONData, err2 = prevJSONDataValue.ValueCopy(nil)
_ = ds.store.statsdClient.Count("ds.read.bytes", prevJSONDataValue.ValueSize(), tags, 1)
if err2 != nil {
return newitems, err2
}
prevEntity = &Entity{}
err2 = json.Unmarshal(prevJSONData, prevEntity)
if err2 != nil {
return newitems, err2
}
}
if prevEntity != nil {
if len(prevJSONData) == jsonLength &&
reflect.DeepEqual(prevEntity.References, e.References) &&
reflect.DeepEqual(prevEntity.Properties, e.Properties) {
isDifferent = false
}
}
if prevLocalJSON, found := localLatests[rid]; found {
prevLocalEntity := &Entity{}
err = json.Unmarshal(prevLocalJSON, prevLocalEntity)
prevEntity = prevLocalEntity
if err != nil {
return newitems, err
}
if len(prevLocalJSON) == jsonLength &&
reflect.DeepEqual(prevLocalEntity.References, e.References) &&
reflect.DeepEqual(prevLocalEntity.Properties, e.Properties) {
isDifferentLocally = false
}
} else {
isDifferentLocally = false
}
if prevEntity == nil {
newitems++
}
}
// not new and not different
if !isnew && !isDifferent && !isDifferentLocally {
continue
}
localLatests[rid] = jsonData
// store entity and the log entry
_ = ds.store.statsdClient.Count("ds.added.bytes", int64(jsonLength), tags, 1)
_ = ds.store.statsdClient.Gauge("ds.throughput.bytes", float64(jsonLength), tags, 1)
err = txn.Set(entityIDBuffer, jsonData)
if err != nil {
return newitems, err
}
// store change log
entityIDChangeTimeBuffer := make([]byte, 22)
nextEntitySeq, _ := logseq.Next()
binary.BigEndian.PutUint16(entityIDChangeTimeBuffer, DatasetEntityChangeLog)
binary.BigEndian.PutUint32(entityIDChangeTimeBuffer[2:], ds.InternalID)
binary.BigEndian.PutUint64(entityIDChangeTimeBuffer[6:], nextEntitySeq)
binary.BigEndian.PutUint64(entityIDChangeTimeBuffer[14:], rid)
err = txn.Set(entityIDChangeTimeBuffer, entityIDBuffer)
if err != nil {
return newitems, err
}
// dataset all latest entities
err = txn.Set(datasetEntitiesLatestVersionKey, entityIDBuffer)
if err != nil {
return newitems, err
}
// Process references
// if new then insert else get latest resource and do diff of rels from previous
if isnew {
newitems++
// iter refs and create rels
// add association to indexes
// outgoing buffer og-indexid:rid:time:predid:relatedid:deleted => nil
// 2:8:8:8:8:2
// incoming buffer ic-indexid:relatedid:rid:time:predid:deleted => nil
for k, stringOrArrayValue := range e.References {
// need to check if v is string, []interface{} or []string
var refs []string
switch v := stringOrArrayValue.(type) {
case string:
refs = []string{v}
case []string:
refs = v
case []interface{}:
refs = make([]string, len(v))
for i, v := range v {
refs[i] = v.(string)
}
case nil:
return newitems, fmt.Errorf("encountered nil ref, cannot store entity %v", e)
}
for _, ref := range refs {
outgoingBuffer := make([]byte, 40)
incomingBuffer := make([]byte, 40)
// assert uint64 id for Predicate
predid, _, err := ds.store.assertIDForURI(k, idCache)
if err != nil {
return newitems, err
}
// assert uint64 id for related entity URI
relatedid, _, err := ds.store.assertIDForURI(ref, idCache)
if err != nil {
return newitems, err
}
binary.BigEndian.PutUint16(outgoingBuffer, OutgoingRefIndex)
binary.BigEndian.PutUint64(outgoingBuffer[2:], rid)
binary.BigEndian.PutUint64(outgoingBuffer[10:], uint64(txnTime))
binary.BigEndian.PutUint64(outgoingBuffer[18:], predid)
binary.BigEndian.PutUint64(outgoingBuffer[26:], relatedid)
if e.IsDeleted {
binary.BigEndian.PutUint16(outgoingBuffer[34:], 1) // deleted.
} else {
binary.BigEndian.PutUint16(outgoingBuffer[34:], 0) // deleted.
}
binary.BigEndian.PutUint32(outgoingBuffer[36:], ds.InternalID)
err = txn.Set(outgoingBuffer, []byte(""))
if err != nil {
return newitems, err
}
binary.BigEndian.PutUint16(incomingBuffer, IncomingRefIndex)
binary.BigEndian.PutUint64(incomingBuffer[2:], relatedid)
binary.BigEndian.PutUint64(incomingBuffer[10:], rid)
binary.BigEndian.PutUint64(incomingBuffer[18:], uint64(txnTime))
binary.BigEndian.PutUint64(incomingBuffer[26:], predid)
if e.IsDeleted {
binary.BigEndian.PutUint16(incomingBuffer[34:], 1) // deleted.
} else {
binary.BigEndian.PutUint16(incomingBuffer[34:], 0) // deleted.
}
binary.BigEndian.PutUint32(incomingBuffer[36:], ds.InternalID)
err = txn.Set(incomingBuffer, []byte(""))
if err != nil {
return newitems, err
}
}
}
} else {
oldRefs := make(map[uint64][]uint64)
if prevEntity != nil {
// go through previous state
// check for no longer there rels
for k, stringOrArrayValue := range prevEntity.References {
// need to check if v is string or []string
refs, isArray := stringOrArrayValue.([]interface{})
if !isArray {
s, isSingle := stringOrArrayValue.(interface{})
if isSingle {
refs = []interface{}{s}
} else {
return newitems, fmt.Errorf("encountered nil reference, cannot store entity %v", e)
}
}
for _, ref := range refs {
// get Predicate
predid, _, err := ds.store.assertIDForURI(k, idCache)
if err != nil {
return newitems, err
}
// get related
relatedid, _, err := ds.store.assertIDForURI(ref.(string), idCache)
if err != nil {
return newitems, err
}
if refs, ok := oldRefs[predid]; ok {
refs = append(refs, relatedid)
oldRefs[predid] = refs
} else {
refs := []uint64{relatedid}
oldRefs[predid] = refs
}
}
}
}
if e.IsDeleted {
for p, referencedIds := range oldRefs {
for _, e := range referencedIds {
incomingBuffer := make([]byte, 40)
outgoingBuffer := make([]byte, 40)
binary.BigEndian.PutUint16(incomingBuffer, IncomingRefIndex)
binary.BigEndian.PutUint64(incomingBuffer[2:], e)
binary.BigEndian.PutUint64(incomingBuffer[10:], rid)
binary.BigEndian.PutUint64(incomingBuffer[18:], uint64(txnTime))
binary.BigEndian.PutUint64(incomingBuffer[26:], p)
binary.BigEndian.PutUint16(incomingBuffer[34:], 1) // is deleted
binary.BigEndian.PutUint32(incomingBuffer[36:], ds.InternalID)
err := txn.Set(incomingBuffer, []byte(""))
if err != nil {
return newitems, err
}
binary.BigEndian.PutUint16(outgoingBuffer, OutgoingRefIndex)
binary.BigEndian.PutUint64(outgoingBuffer[2:], rid)
binary.BigEndian.PutUint64(outgoingBuffer[10:], uint64(txnTime))
binary.BigEndian.PutUint64(outgoingBuffer[18:], p)
binary.BigEndian.PutUint64(outgoingBuffer[26:], e)
binary.BigEndian.PutUint16(outgoingBuffer[34:], 1) // deleted.
binary.BigEndian.PutUint32(outgoingBuffer[36:], ds.InternalID)
err = txn.Set(outgoingBuffer, []byte(""))
if err != nil {
return newitems, err
}
}
}
} else {
// go through new state
for k, stringOrArrayValue := range e.References {
// need to check if v is string, []interface{} or []string
var refs []string
switch v := stringOrArrayValue.(type) {
case string:
refs = []string{v}
case []string:
refs = v
case []interface{}:
refs = make([]string, len(v))
for i, val := range v {
refs[i] = val.(string)
}
case nil:
return newitems, fmt.Errorf("encountered nil ref, cannot store entity %v", e)
}
for _, ref := range refs {
outgoingBuffer := make([]byte, 40)
incomingBuffer := make([]byte, 40)
// assert uint64 id for Predicate
predid, _, err := ds.store.assertIDForURI(k, idCache)
if err != nil {
return newitems, err
}
// assert uint64 id for related entity URI
relatedid, _, err := ds.store.assertIDForURI(ref, idCache)
if err != nil {
return newitems, err
}
binary.BigEndian.PutUint16(outgoingBuffer, OutgoingRefIndex)
binary.BigEndian.PutUint64(outgoingBuffer[2:], rid)
binary.BigEndian.PutUint64(outgoingBuffer[10:], uint64(txnTime))
binary.BigEndian.PutUint64(outgoingBuffer[18:], predid)
binary.BigEndian.PutUint64(outgoingBuffer[26:], relatedid)
binary.BigEndian.PutUint16(outgoingBuffer[34:], 0) // deleted.
binary.BigEndian.PutUint32(outgoingBuffer[36:], ds.InternalID)
err = txn.Set(outgoingBuffer, []byte(""))
if err != nil {
return newitems, err
}
binary.BigEndian.PutUint16(incomingBuffer, IncomingRefIndex)
binary.BigEndian.PutUint64(incomingBuffer[2:], relatedid)
binary.BigEndian.PutUint64(incomingBuffer[10:], rid)
binary.BigEndian.PutUint64(incomingBuffer[18:], uint64(txnTime))
binary.BigEndian.PutUint64(incomingBuffer[26:], predid)
binary.BigEndian.PutUint16(incomingBuffer[34:], 0) // deleted.
binary.BigEndian.PutUint32(incomingBuffer[36:], ds.InternalID)
err = txn.Set(incomingBuffer, []byte(""))
if err != nil {
return newitems, err
}
/*
if this entity has been part of this batch already in a previous loop iteration,
then there is a chance that the previous version had deleted state.
If this was the case, then we potentially just added non deleted ref keys to incoming and
outgoing indexes for the same relations.
Since we are in the same batch, the txnTime is equal just as the rest of the key components apart from the deleted flag.
If only the deleted flag differentiates two keys in an ordered ref index, then the deleted version will always be seen as newer ( since 1 > 0 ).
We want our current not-deleted refs to be seen as latest for the given txnTime.
Therefore, here we remove eventual deleted ref variants from the txn.
*/
if isDifferentLocally {
prevOutgoing := make([]byte, len(outgoingBuffer))
copy(prevOutgoing, outgoingBuffer)
binary.BigEndian.PutUint16(prevOutgoing[34:], 1) // deleted.
err = txn.Delete(prevOutgoing)
if err != nil {
return newitems, err
}
prevIncoming := make([]byte, len(incomingBuffer))
copy(prevIncoming, incomingBuffer)
binary.BigEndian.PutUint16(prevIncoming[34:], 1) // deleted.
err = txn.Delete(prevIncoming)
if err != nil {
return newitems, err
}
}
if refs, ok := oldRefs[predid]; ok {
newrefs := make([]uint64, 0)
for _, refid := range refs {
if refid != relatedid {
newrefs = append(newrefs, refid)
}
}
oldRefs[predid] = newrefs
}
}
}
// iterate remaining keys of old and add them as deleted for incoming refs
for p, referencedIds := range oldRefs {
for _, e := range referencedIds {
incomingBuffer := make([]byte, 40)
outgoingBuffer := make([]byte, 40)
binary.BigEndian.PutUint16(incomingBuffer, IncomingRefIndex)
binary.BigEndian.PutUint64(incomingBuffer[2:], e)
binary.BigEndian.PutUint64(incomingBuffer[10:], rid)
binary.BigEndian.PutUint64(incomingBuffer[18:], uint64(txnTime))
binary.BigEndian.PutUint64(incomingBuffer[26:], p)
binary.BigEndian.PutUint16(incomingBuffer[34:], 1) // is deleted
binary.BigEndian.PutUint32(incomingBuffer[36:], ds.InternalID)
err := txn.Set(incomingBuffer, []byte(""))
if err != nil {
return newitems, err
}
binary.BigEndian.PutUint16(outgoingBuffer, OutgoingRefIndex)
binary.BigEndian.PutUint64(outgoingBuffer[2:], rid)
binary.BigEndian.PutUint64(outgoingBuffer[10:], uint64(txnTime))
binary.BigEndian.PutUint64(outgoingBuffer[18:], p)
binary.BigEndian.PutUint64(outgoingBuffer[26:], e)
binary.BigEndian.PutUint16(outgoingBuffer[34:], 1) // deleted.
binary.BigEndian.PutUint32(outgoingBuffer[36:], ds.InternalID)
err = txn.Set(outgoingBuffer, []byte(""))
if err != nil {
return newitems, err
}
}
}
}
}
}
/* err := ds.store.commitIdTxn()
if err != nil {
return err
}
commitTime := time.Now()
err = txn.Commit()
_ = ds.store.statsdClient.Timing("ds.commit.time", time.Since(commitTime), tags, 1)
if err != nil {
return err
}
updateDsTime := time.Now()
err = ds.updateDataset(newitems, entities)
_ = ds.store.statsdClient.Timing("ds.updateDataset.time", time.Since(updateDsTime), tags, 1)
if err != nil {
return err
} */
return newitems, nil
}
func (ds *Dataset) updateDataset(newItemCount int64, entities []*Entity) error {
if ds.ID == "core.Dataset" {
for _, dsEntity := range entities {
dsInfo, err := ds.store.NamespaceManager.GetDatasetNamespaceInfo()
if err != nil {
return err
}
newNamespaces := dsEntity.Properties[dsInfo.PublicNamespacesKey]
if newNamespaces != nil {
var newNamespacesArray []string
if strArray, ok := newNamespaces.([]string); ok {
newNamespacesArray = strArray
} else {
interfacesArray := newNamespaces.([]interface{})
newNamespacesArray = make([]string, len(interfacesArray))
for i, v := range interfacesArray {
newNamespacesArray[i] = v.(string)
}
}
dsInterface, found := ds.store.datasets.Load(dsEntity.Properties[dsInfo.NameKey])
if found {
dataset := dsInterface.(*Dataset)
dataset.PublicNamespaces = newNamespacesArray
jsonData, err := json.Marshal(dataset)
if err != nil {
return err
}
err = ds.store.storeValue(dataset.getStorageKey(), jsonData)
if err != nil {
return err
}
ds.store.datasets.Store(dataset.ID, dataset)
ds.store.datasetsByInternalID.Store(dataset.InternalID, dataset)
}
}
}
} else if newItemCount > 0 {
dsInfo, err := ds.store.NamespaceManager.GetDatasetNamespaceInfo()
if err != nil {
return err
}
// limit scope to core.Dataset, to avoid unlikely but possible
// bleeding in of properties from other datasets (partial merges)
datasets := []string{"core.Dataset"}
dsEntity, err := ds.store.GetEntity(fmt.Sprintf("%s:%s", dsInfo.DatasetPrefix, ds.ID), datasets, true)
if err != nil {
return err
}
if dsEntity != nil {
items, ok := dsEntity.Properties[dsInfo.ItemsKey]
var count int64 = 0
if ok {
// so items is stored as an int64, but comes back as a float64 because of json
if f, isFloat := items.(float64); isFloat {
existing := int64(f)
count = existing + newItemCount
} else {
ds.store.logger.Warnf("Meta entity has invalid format. expected items property to be float64: %+v", dsEntity)
}
} else {
count = newItemCount
}
dsEntity.Properties[dsInfo.ItemsKey] = count
tds, ok := ds.store.datasets.Load("core.Dataset")
if ok {
_ = tds.(*Dataset).StoreEntities([]*Entity{dsEntity})
}
}
}
return nil
}
func (ds *Dataset) GetChangesWatermark() (uint64, error) {
var waterMark uint64
err := ds.store.database.View(func(btxn *badger.Txn) error {
txn := InstrumentedTxn(btxn, ds.store)
searchBuffer := make([]byte, 7)
binary.BigEndian.PutUint16(searchBuffer, DatasetEntityChangeLog)
binary.BigEndian.PutUint32(searchBuffer[2:], ds.InternalID)
searchBuffer[6] = 0xFF
iteratorOptions := badger.DefaultIteratorOptions
iteratorOptions.Reverse = true
iteratorOptions.PrefetchValues = false
iteratorOptions.Prefix = searchBuffer
changesIterator := txn.NewIterator(iteratorOptions)
defer changesIterator.Close()
changesIterator.Rewind()
item := changesIterator.Item()
k := item.Key()
waterMark = binary.BigEndian.Uint64(k[6:14])
return nil
})
// need to add one to point to next change in searches.
return waterMark + 1, err
}
/*
func (ds *Dataset) GetAllVersionsOfEntity(uri string) []*Entity {
results := make([]*Entity, 0)
ds.store.database.View(func(txn *badger.Txn) error {
rid, ridExists := s.getIDForURI(txn, uri)
if !ridExists {
return nil
}
opts1 := badger.DefaultIteratorOptions
entityIterator := txn.NewIterator(opts1)
defer entityIterator.Close()
searchBuffer := make([]byte, 10)
binary.BigEndian.PutUint16(searchBuffer, INCOMING_REF_INDEX)
binary.BigEndian.PutUint64(searchBuffer[2:], rid)
searchBuffer = append(searchBuffer, 0xFF)
for entityIterator.Seek(searchBuffer); entityIterator.ValidForPrefix(prefixBuffer); entityIterator.Next() {
}
return nil
})
return results
} */
type EntitiesResult struct {
Context *Context
Entities []*Entity
ContinuationToken string
}
// GetEntities returns a batch of entities
func (ds *Dataset) GetEntities(from string, count int) (*EntitiesResult, error) {
result := &EntitiesResult{}
result.Context = ds.GetContext()
result.Entities = make([]*Entity, 0)
token, err := ds.MapEntities(from, count, func(entity *Entity) error {
result.Entities = append(result.Entities, entity)
return nil
})
if err != nil {
return nil, err
}
result.ContinuationToken = token
return result, nil
}
// MapEntities applies a function to all entities in the dataset
// returns the id of the last entity so that it can be used as a continuation token
func (ds *Dataset) MapEntities(from string, count int, processEntity func(entity *Entity) error) (string, error) {
continuationToken, err := ds.MapEntitiesRaw(from, count, func(entityJson []byte) error {
e := &Entity{}
err := json.Unmarshal(entityJson, e)
if err != nil {
return err
}
return processEntity(e)
})
if err != nil {
return "", err
}
// the continuation token
return continuationToken, nil
}
// MapEntities applies a function to all entities in the dataset. the entities are provided as raw json bytes
// returns the id of the last entity so that it can be used as a continuation token
func (ds *Dataset) MapEntitiesRaw(from string, count int, processEntity func(json []byte) error) (string, error) {
lastKeyAsContinuationToken := ""
err := ds.store.database.View(func(txn *badger.Txn) error {
searchBufferPrefix := make([]byte, 10)
binary.BigEndian.PutUint16(searchBufferPrefix, DatasetLatestEntities)
binary.BigEndian.PutUint32(searchBufferPrefix[2:], ds.InternalID)
var searchBuffer []byte
if from == "" {
searchBuffer = searchBufferPrefix // append(searchBufferPrefix, []byte(from)...)
} else {
searchBuffer, _ = b64.StdEncoding.DecodeString(from)
}
opts1 := badger.DefaultIteratorOptions
opts1.Prefix = searchBufferPrefix
entityIterator := txn.NewIterator(opts1)
defer entityIterator.Close()
taken := 0
entityIterator.Seek(searchBuffer)
// the from matches the id of the last object found
// so need to advanced to next
if from != "" {
lastKeyAsContinuationToken = from
entityIterator.Next()
}
for ; entityIterator.ValidForPrefix(searchBufferPrefix); entityIterator.Next() {
// store key into lastSeenKey
lastKeyAsContinuationToken = b64.StdEncoding.EncodeToString(entityIterator.Item().Key())
item := entityIterator.Item()
taken++
err := item.Value(func(val []byte) error {
entityItem, _ := txn.Get(val)
return entityItem.Value(func(entityJson []byte) error {
return processEntity(entityJson)
})
})
if err != nil {
return err
}
if taken == count {
break
}
}
return nil
})
if err != nil {
return "", err
}
// the continuation token
return lastKeyAsContinuationToken, nil
}
// Changes Object
type Changes struct {
Context *Context
Entities []*Entity
NextToken uint64
}
func NewChanges() *Changes {
changes := &Changes{}
changes.Entities = make([]*Entity, 0)
changes.NextToken = 0
return changes
}
func (ds *Dataset) GetChanges(since uint64, count int, latestOnly bool) (*Changes, error) {
changes := NewChanges()
changes.Context = ds.GetContext()
changes.Entities = make([]*Entity, 0)
var err error
changes.NextToken, err = ds.ProcessChanges(since, count, latestOnly, func(entity *Entity) {
changes.Entities = append(changes.Entities, entity)
})
if err != nil {
return nil, err
}
return changes, nil
}