-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnotebox.go
1595 lines (1335 loc) · 50.4 KB
/
notebox.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 2017 Blues Inc. All rights reserved.
// Use of this source code is governed by licenses granted by the
// copyright holder including that found in the LICENSE file.
// A Notebox is defined to be a Notefile describing a set of
// Notefiles among endpoints that communicate and share info
// with one another. Generally, an "edge device" endpoint
// has a single Notebox whose ID is unique to that device,
// while a "central service" endpoint may manage a vast
// number of Noteboxes, one per "edge device" it shares
// info and commmunicates with. In theory, if a group of
// edge devices wanted to communicate peer-to-peer as well
// as with the service, or if a group of services wanted
// to communicate with each other, all these device and
// service endpoints would would share a common notebox.
// A NOTE ABOUT MUTEX ORDERING
// The following mutex ordering should be obeyed:
// 1. boxLock (OUTERMOST)
// 2. box.Openfile().lock (the openfile data structure)
// 3. box.Notefile().lock (the notefile pointed to by the openfile data structure)
// Package notelib notebox.go deals with the handling of the sync'ed container of a set of related notefiles
package notelib
import (
"context"
"fmt"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/blues/note-go/note"
)
// Address of the Noteboxes, indexed by storage object
var openboxes sync.Map
// This ONLY protects the list of open noteboxes
var boxLock sync.RWMutex
// Indicates whether or not we created a goroutine for checkpointing
var autoCheckpointStarted bool
var autoCheckpointStartedLock sync.Mutex
var (
AutoCheckpointSeconds = 5 * 60
AutoPurgeSeconds = 5 * 60
CheckpointSilently = false
)
// Information about files and templates
type NoteboxNotefileInfo struct {
NotefileID string
Info note.NotefileInfo
BodyTemplate string
PayloadTemplate uint32
TemplateFormat uint32
TemplatePort uint16
}
// See if a string is in a string array
func isNoteInNoteArray(val string, array []string) bool {
for i := range array {
if array[i] == val {
return true
}
}
return false
}
// compositeNoteID creates a valid Note ID from the required components
func compositeNoteID(endpoint string, notefile string) string {
return endpoint + ReservedIDDelimiter + notefile
}
// parseCompositeNoteID extracts componets from a Notebox Note ID
func parseCompositeNoteID(noteid string) (isInstance bool, endpoint string, notefile string) {
s := strings.Split(noteid, ReservedIDDelimiter)
// If this isn't a local instance NoteID, return that fact (with an invalid endpoint ID in that field)
if len(s) != 2 {
return false, ReservedIDDelimiter, noteid
}
return true, s[0], s[1]
}
// Initialize notebox storage
func initNotebox(ctx context.Context, endpointID string, boxStorage string, storage storageClass) (err error) {
// Create the notefile for the notebox
boxfile := CreateNotefile(false)
// Create the note for managing the notebox's notefile, whose ID is the endpoint itself
body := noteboxBody{}
// Removed 2017-11-27 because not only is this not needed, but it is also potentially
// a security issue if it were present and used, because the client could cause the
// service to fetch the notebox from elsewhere.
if false {
body.Notefile.Storage = boxStorage
}
note, err := note.CreateNote(noteboxBodyToJSON(body), nil)
if err == nil {
_, err = boxfile.AddNote(endpointID, compositeNoteID(endpointID, endpointID), note)
}
if err != nil {
return err
}
// Write the storage object. No lock isneeded because we just created it
err = storage.writeNotefile(ctx, boxfile, boxStorage, boxStorage)
if err != nil {
return err
}
if debugBox {
logDebug(ctx, "%s created", boxStorage)
}
// Done
return nil
}
// CreateNotebox creates a notebox on this endpoint
func CreateNotebox(ctx context.Context, endpointID string, boxStorage string) (err error) {
// Get storage from the provided storage object
storage, err := storageProvider(boxStorage)
if err != nil {
return err
}
// Create the object at an explicit storage object address
err = storage.createObject(ctx, boxStorage)
if err != nil {
return err
}
// Initialize the notebox
err = initNotebox(ctx, endpointID, boxStorage, storage)
if err != nil {
_ = storage.delete(ctx, boxStorage, boxStorage)
return err
}
// Done
return nil
}
// OpenEndpointNotebox opens - creating if necessary - a notebox in File storage for an endpoint
func OpenEndpointNotebox(ctx context.Context, localEndpointID string, boxLocalStorage string, create bool) (box *Notebox, err error) {
// Open the notebox
box, err = OpenNotebox(ctx, localEndpointID, boxLocalStorage)
// If error, assume that it doesn't exist, so create it and try again
if err != nil && create {
err = CreateNotebox(ctx, localEndpointID, boxLocalStorage)
if err != nil {
return &Notebox{}, err
}
box, err = OpenNotebox(ctx, localEndpointID, boxLocalStorage)
if err != nil {
return &Notebox{}, err
}
}
// Done
return box, err
}
// Delete deletes a closed Notebox, and releases its storage.
func Delete(ctx context.Context, boxStorage string) (err error) {
// First, checkpoint this notebox, with purge
box := &Notebox{}
boxi, present := openboxes.Load(boxStorage)
if !present {
return fmt.Errorf("notebox isn't open")
}
box.instance = boxi.(*NoteboxInstance)
box.checkpoint(ctx, true, true, false, false)
// See if it's still around
_, present = openboxes.Load(boxStorage)
if present {
return fmt.Errorf(note.ErrNotefileInUse+" cannot delete an open notebox: %s", boxStorage)
}
// Get the storage class
storage, err := storageProvider(boxStorage)
if err != nil {
return err
}
// Delete the storage object
return storage.delete(ctx, boxStorage, boxStorage)
}
// reopenNotebox reopens it if it's already open
func uReopenNotebox(ctx context.Context, localEndpointID string, boxLocalStorage string) (notebox *Notebox, err error) {
// Create a new reference to the instance
boxi, present := openboxes.Load(boxLocalStorage)
if !present {
err = fmt.Errorf("notebox isn't open")
return
}
instance := boxi.(*NoteboxInstance)
// Validate that we're opening with the same endpoint ID, because
// a notebox can only be open "on behalf of" a single endpoint ID at a time
// because we use the endpoint on subsequent notebox calls.
if localEndpointID != instance.endpointID {
return nil, fmt.Errorf("error opening notebox: notebox can only be opened on behalf of one Endpoint at a time: %s", boxLocalStorage)
}
// Increment the refcnt
iv, present := instance.openfiles.Load(boxLocalStorage)
if !present {
return nil, fmt.Errorf("error opening notebox: can't find underlying boxfile")
}
boxOpenfile := iv.(*OpenNotefile)
atomic.AddInt32(&boxOpenfile.openCount, 1)
if debugBox {
logDebug(ctx, "After openbox, %s open refcnt now %d", boxLocalStorage, boxOpenfile.openCount)
}
// Done
box := &Notebox{}
box.instance = instance
return box, nil
}
// OpenNotebox opens a local notebox into memory.
func OpenNotebox(ctx context.Context, localEndpointID string, boxLocalStorage string) (notebox *Notebox, err error) {
// Initialize debugging if we've not done so before
debugEnvInit()
// See if it's already open, and bump the refcount if so
boxLock.Lock()
_, present := openboxes.Load(boxLocalStorage)
if present {
notebox, err = uReopenNotebox(ctx, localEndpointID, boxLocalStorage)
boxLock.Unlock()
return
}
boxLock.Unlock()
// Load the notefile for this storage object
storage, err := storageProvider(boxLocalStorage)
if err != nil {
return nil, err
}
notefile, err := storage.readNotefile(ctx, boxLocalStorage, boxLocalStorage)
if err != nil {
return nil, fmt.Errorf("device not found " + note.ErrDeviceNotFound)
}
// For the notebox itself, create a new notefile data structure with a single refcnt
boxOpenfile := &OpenNotefile{}
boxOpenfile.notefile = notefile
boxOpenfile.storage = boxLocalStorage
boxOpenfile.openCount = 1
if debugBox {
logDebug(ctx, "After openbox, %s open refcnt now %d", boxLocalStorage, boxOpenfile.openCount)
}
// Create a new open notebox and add it to the global list
box := &Notebox{}
box.instance = &NoteboxInstance{}
box.instance.endpointID = localEndpointID
box.instance.storage = boxLocalStorage
box.instance.openfiles = sync.Map{}
boxOpenfile.box = box
// Now that we're ready to store it, see if someone else opened it in the interim. If
// so, bump the refcnt and discard what we've done. If not, we're the ones who opened it.
boxLock.Lock()
_, present = openboxes.Load(boxLocalStorage)
if present {
notebox, err = uReopenNotebox(ctx, localEndpointID, boxLocalStorage)
boxLock.Unlock()
return
}
box.instance.openfiles.Store(boxLocalStorage, boxOpenfile)
openboxes.Store(boxLocalStorage, box.instance)
boxLock.Unlock()
// Make sure that we've created a checkpointing task
if !autoCheckpointStarted {
autoCheckpointStartedLock.Lock()
if !autoCheckpointStarted {
autoCheckpointStarted = true
go autoCheckpoint(ctx)
go autoPurge(ctx)
}
autoCheckpointStartedLock.Unlock()
}
return box, nil
}
// Automatically checkpoint modified noteboxes
func autoCheckpoint(ctx context.Context) {
for {
time.Sleep(time.Duration(AutoCheckpointSeconds) * time.Second)
err := checkpointAllNoteboxes(ctx, false)
if err != nil {
logError(ctx, "autoCheckpoint error: %s", err)
}
}
}
// Automatically purge noteboxes/notefiles with zero refcnt that haven't been recently used
func autoPurge(ctx context.Context) {
for {
time.Sleep(time.Duration(AutoPurgeSeconds) * time.Second)
err := checkpointAllNoteboxes(ctx, true)
if err != nil {
logError(ctx, "autoPurge error: %s", err)
}
}
}
// Checkpoint all noteboxes and purge noteboxes that have been sitting unused for the autopurge interval
func Checkpoint(ctx context.Context) (err error) {
return checkpointAllNoteboxes(ctx, true)
}
// CheckpointNoteboxIfNeeded checkpoints a notebox if it's open
func CheckpointNoteboxIfNeeded(ctx context.Context, localEndpointID string, boxLocalStorage string) error {
// Initialize debugging if we've not done so before
debugEnvInit()
var err error
var notebox *Notebox
// Reopen the notebox (and bump the refcount) if it's already open
boxLock.Lock()
boxi, present := openboxes.Load(boxLocalStorage)
if present && boxi.(*NoteboxInstance).endpointID == localEndpointID {
notebox, err = uReopenNotebox(ctx, localEndpointID, boxLocalStorage)
}
boxLock.Unlock()
if notebox == nil || err != nil {
return err
}
err = notebox.Checkpoint(ctx)
_ = notebox.Close(ctx)
return err
}
// Purge checkpoints all noteboxes and force a purge of notefiles
func Purge(ctx context.Context) error {
var firstError error
// Iterate, checkpointing each open notebox.
openboxes.Range(func(boxStorage, boxi interface{}) bool {
box := &Notebox{}
box.instance = boxi.(*NoteboxInstance)
emptyBox, err := box.checkpoint(ctx, true, true, true, true)
if firstError == nil {
firstError = err
}
// If we're purging, get rid of the notefile if it wasn't in use
if emptyBox {
openboxes.Delete(boxStorage)
}
return true
})
// Done
return firstError
}
// checkpointAllNoteboxes ensures that what's on-disk is up to date
func checkpointAllNoteboxes(ctx context.Context, purge bool) error {
var firstError error
// Iterate, checkpointing each open notebox.
openboxes.Range(func(boxStorage, boxi interface{}) bool {
box := &Notebox{}
box.instance = boxi.(*NoteboxInstance)
emptyBox, err := box.checkpoint(ctx, true, purge, false, false)
if firstError == nil {
firstError = err
}
// If we're purging, get rid of the notefile if it wasn't in use
if purge && emptyBox {
openboxes.Delete(boxStorage)
if debugBox {
logDebug(ctx, "Notebox %s purged", boxStorage)
}
}
return true
})
// Done
return firstError
}
// Checkpoint a notebox
func (box *Notebox) Checkpoint(ctx context.Context) (err error) {
_, err = box.checkpoint(ctx, true, true, false, false)
return
}
// uCheckpoint checkpoints an open notebox
func (box *Notebox) checkpoint(ctx context.Context, write bool, purgeClosed bool, purgeClosedForce bool, purgeClosedDeleted bool) (emptyBox bool, err error) {
var firstError error
// Count the number of notefiles "in use", including the box itself
openfiles := 0
// Iterate, checkpointing each open notefile.
box.instance.openfiles.Range(func(fileStorage, openfilei interface{}) bool {
openfile := openfilei.(*OpenNotefile)
// Checkpoint the notefile, even if it has a 0 refcnt
var err error
if write {
err = box.checkpointNotefile(ctx, openfile)
if firstError == nil {
firstError = err
}
}
openfile.sanityCheckOpenCount()
// If it's closed, purge it in a race-free way
if openfile.openCount == 0 {
openfile.lock.Lock()
if openfile.openCount == 0 {
// If we're being asked to purge deleted files, do it
if purgeClosedDeleted && openfile.deleted {
box.instance.openfiles.Delete(fileStorage)
if debugBox {
logDebug(ctx, "%s purged (had been deleted)", fileStorage)
}
openfile.lock.Unlock()
return true
}
// Purge files that haven't been closed recently, just as an optimization that
// will keep things around in memory that are very frequently used so that we don't
// thrash flash I/O unnecessarily.
if purgeClosedForce || (purgeClosed && (time.Since(openfile.closeTime) >= time.Duration(AutoPurgeSeconds)*time.Second)) {
box.instance.openfiles.Delete(fileStorage)
if debugBox {
if openfile.deleted {
logDebug(ctx, "%s purged (had been deleted)", fileStorage)
} else {
logDebug(ctx, "%s purged", fileStorage)
}
}
openfile.lock.Unlock()
return true
}
}
openfile.lock.Unlock()
}
// Keep track of the number of notefiles that remain open
if openfile.openCount != 0 {
openfiles++
}
return true
})
// Done
return openfiles == 0, firstError
}
// Checkpoint an open notefile
func (box *Notebox) checkpointNotefile(ctx context.Context, openfile *OpenNotefile) error {
storage, err := storageProvider(openfile.storage)
if err != nil {
return err
}
// Lock this file
openfile.lock.Lock()
defer openfile.lock.Unlock()
// Only checkpoint if modified
modCount := openfile.notefile.Modified()
if modCount != openfile.modCountAfterCheckpoint {
if !CheckpointSilently {
logDebug(ctx, "CHECKPOINTED %s (%d mods, %d since first opened)", openfile.storage, modCount-openfile.modCountAfterCheckpoint, modCount)
}
// Write storage unless the underlying storage has been deleted during a Notebox merge
if !openfile.deleted {
openfile.notefile.lock.Lock()
err = storage.writeNotefile(ctx, openfile.notefile, box.instance.storage, openfile.storage)
openfile.notefile.lock.Unlock()
} else {
err = nil
}
// Set the modification count
if err == nil {
openfile.modCountAfterCheckpoint = modCount
} else {
logError(ctx, "Error checkpointing %s: %s", openfile.storage, err)
}
}
return err
}
// Notefiles gets a list of all openable notefiles in the current boxfile
func (box *Notebox) Notefiles(includeTombstones bool) (notefiles []string) {
// Enum all notes in the boxfile, looking at the global files only
allNotefiles := []string{}
boxfile := box.Notefile()
boxfile.lock.RLock()
for noteID, note := range boxfile.Notes {
isInstance, _, notefileID := parseCompositeNoteID(noteID)
if !isInstance {
if includeTombstones {
allNotefiles = append(allNotefiles, notefileID)
} else {
if !note.Deleted {
allNotefiles = append(allNotefiles, notefileID)
}
}
}
}
boxfile.lock.RUnlock()
if debugBox {
logDebug(context.Background(), "All Notefiles:\n%v", allNotefiles)
}
return allNotefiles
}
// ClearAllTrackers deletes all trackers for this endpoint in order to force a resync of all files
func (box *Notebox) ClearAllTrackers(ctx context.Context, endpointID string) {
// Clear the tracker on the notebox itself
box.Notefile().ClearTracker(endpointID)
// Get a list of all notefiles including the
allNotefileIDs := box.Notefiles(false)
// Iterate over all except the notebox itself
for i := range allNotefileIDs {
notefileID := allNotefileIDs[i]
openfile, file, err := box.OpenNotefile(ctx, notefileID)
if err == nil {
file.ClearTracker(endpointID)
openfile.Close(ctx)
}
}
}
// EndpointID gets the notebox's endpoint ID
func (box *Notebox) EndpointID() string {
return box.instance.endpointID
}
// GetChangedNotefiles determines, for a given tracker, if there are changes in any notebox and,
// if so, for which ones.
func (box *Notebox) GetChangedNotefiles(ctx context.Context, endpointID string) (changedNotefiles []string) {
// Get the names of all possible openable Notefiles
allNotefiles := box.Notefiles(true)
// Add the local endpoint, because that's explicitly not included in the list
allNotefiles = append(allNotefiles, box.instance.endpointID)
// Get the notefile info of the "source" and "destination" for the changes
sourceEndpointID := box.instance.endpointID
destinationEndpointID := endpointID
// Enum the notefiles, looking for changes
changedNotefiles = []string{}
for i := range allNotefiles {
notefileID := allNotefiles[i]
openfile, file, err := box.OpenNotefile(ctx, notefileID)
if err == nil {
info, err := box.GetNotefileInfo(notefileID)
if err != nil {
info = note.NotefileInfo{}
}
suppress := false
hubEndpointID := info.SyncHubEndpointID
if info.SyncHubEndpointID == "" {
hubEndpointID = note.DefaultHubEndpointID
}
isQueue, syncToHub, syncFromHub, _, _, _ := NotefileAttributesFromID(notefileID)
if isQueue && syncToHub {
suppress = true
}
if !syncToHub && hubEndpointID == destinationEndpointID {
suppress = true
}
if !syncFromHub && hubEndpointID == sourceEndpointID {
suppress = true
}
// If the file has never been tracked, we need to mark it as changed regardless
// of whether or not it is "push" or "pull".
if !file.IsTracker(endpointID) {
suppress = false
}
// If not suppressing, return true only if the file has been changed
if !suppress {
areFileChanges, err := file.AreChanges(endpointID)
if err == nil && areFileChanges {
changedNotefiles = append(changedNotefiles, notefileID)
}
}
openfile.Close(ctx)
}
}
// Done
return changedNotefiles
}
// Close releases a notebox, but leaves it in-memory with a 0 refcount for low-overhead re-open
func (box *Notebox) Close(ctx context.Context) (err error) {
// Exit if we're about to do something really bad
boxOpenfile := box.Openfile()
if boxOpenfile.openCount == 0 {
return fmt.Errorf("closing notebox: notebox already closed: %s", box.instance.endpointID)
}
// If we're on last refcnt, checkpoint to make sure everything is up-to-date. Otherwise,
// rely upon the periodic timer-based checkpoint to checkpoint the box.
if boxOpenfile.openCount == 1 && !autoCheckpointStarted {
_, err = box.checkpoint(ctx, true, false, false, false)
}
// Drop the refcnt on our own storage, re-reading boxOpenFile after the checkpoint.
atomic.AddInt32(&boxOpenfile.openCount, -1)
boxOpenfile.sanityCheckOpenCount()
boxOpenfile.closeTime = time.Now()
if debugBox {
logDebug(ctx, "After closebox, %s close refcnt=%d modcnt=%d", box.instance.storage, boxOpenfile.openCount, boxOpenfile.modCountAfterCheckpoint)
}
// Done
return err
}
// NotefileAttributesFromID extracts attributes implied by the notefileID
func NotefileAttributesFromID(notefileID string) (isQueue bool, syncToHub bool, syncFromHub bool, secure bool, reserved bool, err error) {
// Preset the error returns for the odd case where we are getting notefile attributes
// on a notebox, where the notefileid is an endpoint id - which obviously doesn't have an extension
isQueue = false
syncToHub = false
syncFromHub = false
secure = false
reserved = false
// See if it's a reserved filename
reserved = strings.HasPrefix(notefileID, "_")
// Look at the extension
components := strings.Split(notefileID, ".")
numComponents := len(components)
if numComponents < 2 {
err = fmt.Errorf("notefileID must end in a recognized type: %s", notefileID)
return
}
notefileType := components[numComponents-1]
extension := notefileType
// First, look for the base type
validType := false
if strings.HasPrefix(notefileType, "q") {
notefileType = strings.TrimPrefix(notefileType, "q")
isQueue = true
syncToHub = true
syncFromHub = true
validType = true
} else if strings.HasPrefix(notefileType, "db") {
notefileType = strings.TrimPrefix(notefileType, "db")
syncToHub = true
syncFromHub = true
validType = true
}
// Now, look for I/O attributes
if strings.HasPrefix(notefileType, "i") {
notefileType = strings.TrimPrefix(notefileType, "i")
syncToHub = false
} else if strings.HasPrefix(notefileType, "o") {
notefileType = strings.TrimPrefix(notefileType, "o")
syncFromHub = false
} else if strings.HasPrefix(notefileType, "x") {
notefileType = strings.TrimPrefix(notefileType, "x")
syncFromHub = false
syncToHub = false
}
// Now, look for the security attribute
if strings.HasPrefix(notefileType, "s") {
notefileType = strings.TrimPrefix(notefileType, "s")
secure = true
}
// If we haven't gotten a type or exhausted the option flags, it's unrecognized
if !validType || notefileType != "" {
err = fmt.Errorf("notefile type not recognized: %s", extension)
}
// Done
return
}
// NotefileExists returns true if notefile exists and is not deleted
func (box *Notebox) NotefileExists(notefileID string) (present bool) {
boxfile := box.Notefile()
boxfile.lock.RLock()
desc, descFound := boxfile.Notes[notefileID]
xnote, found := boxfile.Notes[compositeNoteID(box.instance.endpointID, notefileID)]
boxfile.lock.RUnlock()
if descFound && desc.Deleted {
descFound = false
}
if found && xnote.Deleted {
found = false
}
if notefileID == box.instance.endpointID {
descFound = true
}
present = descFound && found
return
}
// AddNotefile adds a new notefile to the notebox, and return "nil" if it already exists
func (box *Notebox) AddNotefile(ctx context.Context, notefileID string, notefileInfo *note.NotefileInfo) error {
// First, do an immediate check to see if it already exists. If so, short circuit everything
// and return a clean "no error", which is relied upon by callers.
if box.NotefileExists(notefileID) {
// Refresh the notefile info, which may likely have changed
if notefileInfo == nil {
notefileInfo = ¬e.NotefileInfo{}
}
return box.SetNotefileInfo(notefileID, *notefileInfo)
}
// Find out if it's a queue
isQueue, _, _, _, _, err := NotefileAttributesFromID(notefileID)
if err != nil {
return err
}
// Add the notefile
box.Openfile().lock.Lock()
boxfile := box.Notefile()
boxfile.lock.RLock()
err = box.uAddNotefile(ctx, notefileID, notefileInfo, CreateNotefile(isQueue))
boxfile.lock.RUnlock()
box.Openfile().lock.Unlock()
// Done
return err
}
// GetNotefileInfo retrieves info about a specific notefile
func (box *Notebox) GetNotefileInfo(notefileID string) (notefileInfo note.NotefileInfo, err error) {
// If this is for a boxfile, just return null info because there is no notefile info for a boxfile
if box.instance.endpointID == notefileID {
return note.NotefileInfo{}, nil
}
// Lock open files
boxfile := box.Notefile()
// Find the specified Notefile's global descriptor
xnote, err := boxfile.GetNote(notefileID)
if err != nil {
return note.NotefileInfo{}, fmt.Errorf(note.ErrNotefileNoExist+" cannot get info for notefile %s: %s", notefileID, err)
}
// Get the info from the notefile body
body := noteboxBodyFromJSON(xnote.GetBody())
if body.Notefile.Info == nil {
notefileInfo = note.NotefileInfo{}
} else {
notefileInfo = *body.Notefile.Info
}
// Done
return
}
// SetNotefileInfo sets the info about a notefile that is allowed to be changed after notefile creation
func (box *Notebox) SetNotefileInfo(notefileID string, notefileInfo note.NotefileInfo) (err error) {
// Now we're going to add things to the boxfile
boxfile := box.Notefile()
// Find the specified Notefile's global descriptor
xnote, err := boxfile.GetNote(notefileID)
if err != nil {
return fmt.Errorf(note.ErrNotefileNoExist+" cannot set info for notefile %s: %s", notefileID, err)
}
// Get the info from the notefile body
body := noteboxBodyFromJSON(xnote.GetBody())
if body.Notefile.Info == nil {
newInfo := note.NotefileInfo{}
body.Notefile.Info = &newInfo
}
// For now, all NotefileInfo fields can be changed dynamically. If anything in here is only
// allowed to be set at Notefile creation, here is where we should enforce that.
{
}
// Update the info
body.Notefile.Info = ¬efileInfo
_ = xnote.SetBody(noteboxBodyToJSON(body))
// Update the note
err = boxfile.UpdateNote(box.instance.endpointID, notefileID, xnote)
if err != nil {
return fmt.Errorf(note.ErrNotefileNoExist+" cannot set info for notefile %s: %s", notefileID, err)
}
// Update it in-memory if it's open
boxLock.Lock()
iv, present := box.instance.openfiles.Load(body.Notefile.Storage)
if present {
openfile := iv.(*OpenNotefile)
openfile.notefile.notefileInfo = notefileInfo
box.instance.openfiles.Store(body.Notefile.Storage, openfile)
}
boxLock.Unlock()
// Done
return
}
// CreateNotefile creates a new Notefile in-memory, which will ultimately be added to this Notebox
func (box *Notebox) CreateNotefile(isQueue bool) *Notefile {
return CreateNotefile(isQueue)
}
// AddNotefile adds a new notefile to the notebox.
// Note, importantly, that this does not open the notefile, and furthermore that because the supplied
// notefile is copied, it should no longer be used. If one wishes to use the new storage-associated notefile,
// one should open it via the OpenNotefile method on the Notebox.
// NOTE: the boxfile must be locked at least for READ by the caller, and the notefile must be locked for WRITE
func (box *Notebox) uAddNotefile(ctx context.Context, notefileID string, notefileInfo *note.NotefileInfo, notefile *Notefile) error {
// Reject any attempt to add a notefile whose name contains our special delimiter
if strings.Contains(notefileID, ReservedIDDelimiter) {
return fmt.Errorf(note.ErrNotefileName+" name cannot contain reserved character '%s'", ReservedIDDelimiter)
}
// Reject notefiles with invalid names
_, _, _, _, _, err := NotefileAttributesFromID(notefileID)
if err != nil {
return err
}
// Debug
if debugBox {
logDebug(ctx, "Adding: %s", notefileID)
}
// Find the specified notefile descriptor and instance
boxfile := box.Notefile()
descnote, descfound := boxfile.Notes[notefileID]
xnote, found := boxfile.Notes[compositeNoteID(box.instance.endpointID, notefileID)]
if found && !xnote.Deleted && descfound && !descnote.Deleted {
return fmt.Errorf(note.ErrNotefileExists+" adding notefile: notefile already exists: %s", notefileID)
}
// First, create the global Notefile descriptor or undelete it
if !descfound {
body := noteboxBody{}
body.Notefile.Info = notefileInfo
descnote, err = note.CreateNote(noteboxBodyToJSON(body), nil)
if err == nil {
err = boxfile.uAddNote(box.instance.endpointID, notefileID, &descnote, false)
}
if err != nil {
return err
}
} else if descfound && descnote.Deleted {
descnote.Deleted = false
body := noteboxBodyFromJSON(descnote.GetBody())
body.Notefile.Info = notefileInfo
_ = descnote.SetBody(noteboxBodyToJSON(body))
err = boxfile.uUpdateNote(box.instance.endpointID, notefileID, &descnote)
if err != nil {
return err
}
if debugBox {
logDebug(ctx, "%s info updated: %v", notefileID, notefileInfo)
}
}
// Inherit storage from the box
storage, err := storageProvider(box.instance.storage)
if err != nil {
return err
}
// If not already assigned, create a new storage object
fileStorage, err := storage.create(ctx, box.instance.storage, notefileID)
if err != nil {
return err
}
// Create the note for managing the instance.
body := noteboxBody{}
body.Notefile.Storage = fileStorage
if !found {
var inote note.Note
inote, err = note.CreateNote(noteboxBodyToJSON(body), nil)
if err == nil {
err = boxfile.uAddNote(box.instance.endpointID, compositeNoteID(box.instance.endpointID, notefileID), &inote, false)
}
} else {
_ = xnote.SetBody(noteboxBodyToJSON(body))
err = boxfile.uUpdateNote(box.instance.endpointID, compositeNoteID(box.instance.endpointID, notefileID), &xnote)
}
if err != nil {
_ = storage.delete(ctx, box.instance.storage, fileStorage)
return err
}
// Write the storage object for the new notefile. Note that if an error occurs
// from here on, we need to leave storage around because it's already described
// by the instance note above.
err = storage.writeNotefile(ctx, notefile, box.instance.storage, fileStorage)
if err != nil {
return err
}
// Write the storage object locked, for consistency
err = storage.writeNotefile(ctx, boxfile, box.instance.storage, box.instance.storage)
if err != nil {
return err
}
if debugBox {
logDebug(ctx, "%s created", fileStorage)
}
// Done
return err
}
// OpenNotefile gets the pointer to the openfile associated with the notebox
func (box *Notebox) Openfile() *OpenNotefile {
iv, present := box.instance.openfiles.Load(box.instance.storage)
if !present {
return &OpenNotefile{}
}
return iv.(*OpenNotefile)
}
// Notefile gets the pointer to the notefile associated with the notebox
func (box *Notebox) Notefile() *Notefile {
return box.Openfile().notefile
}
// ConvertToJSON serializes/marshals the in-memory Notebox into a JSON buffer
func (box *Notebox) ConvertToJSON(fIndent bool) (output []byte, err error) {
return box.Notefile().ConvertToJSON(fIndent)
}
// OpenNotefile opens a notefile, reading it from storage and bumping its refcount. As such,
// you MUST pair this with a call to CloseNotefile. Note that this function must work
// for the "" NotefileID (when opening the notebox "|" instance), so don't add a check
// that would prohibit this.
func (box *Notebox) OpenNotefile(ctx context.Context, notefileID string) (iOpenfile *OpenNotefile, notefile *Notefile, err error) {
// Purge all deleted notefiles from the notebox, because we may be opening one that was deleted
_, err = box.checkpoint(ctx, false, false, false, true)
if err != nil {