-
Notifications
You must be signed in to change notification settings - Fork 103
/
repomgr.go
1083 lines (875 loc) · 23.8 KB
/
repomgr.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
package repomgr
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"strings"
"sync"
atproto "github.com/bluesky-social/indigo/api/atproto"
bsky "github.com/bluesky-social/indigo/api/bsky"
"github.com/bluesky-social/indigo/carstore"
lexutil "github.com/bluesky-social/indigo/lex/util"
"github.com/bluesky-social/indigo/models"
"github.com/bluesky-social/indigo/mst"
"github.com/bluesky-social/indigo/repo"
"github.com/bluesky-social/indigo/util"
blocks "github.com/ipfs/go-block-format"
"github.com/ipfs/go-cid"
"github.com/ipfs/go-datastore"
blockstore "github.com/ipfs/go-ipfs-blockstore"
ipld "github.com/ipfs/go-ipld-format"
logging "github.com/ipfs/go-log/v2"
"github.com/ipld/go-car"
cbg "github.com/whyrusleeping/cbor-gen"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"gorm.io/gorm"
)
var log = logging.Logger("repomgr")
func NewRepoManager(cs *carstore.CarStore, kmgr KeyManager) *RepoManager {
return &RepoManager{
cs: cs,
userLocks: make(map[models.Uid]*userLock),
kmgr: kmgr,
}
}
type KeyManager interface {
VerifyUserSignature(context.Context, string, []byte, []byte) error
SignForUser(context.Context, string, []byte) ([]byte, error)
}
func (rm *RepoManager) SetEventHandler(cb func(context.Context, *RepoEvent), hydrateRecords bool) {
rm.events = cb
rm.hydrateRecords = hydrateRecords
}
type RepoManager struct {
cs *carstore.CarStore
kmgr KeyManager
lklk sync.Mutex
userLocks map[models.Uid]*userLock
events func(context.Context, *RepoEvent)
hydrateRecords bool
}
type ActorInfo struct {
Did string
Handle string
DisplayName string
Type string
}
type RepoEvent struct {
User models.Uid
OldRoot *cid.Cid
NewRoot cid.Cid
Since *string
Rev string
RepoSlice []byte
PDS uint
Ops []RepoOp
}
type RepoOp struct {
Kind EventKind
Collection string
Rkey string
RecCid *cid.Cid
Record any
ActorInfo *ActorInfo
}
type EventKind string
const (
EvtKindCreateRecord = EventKind("create")
EvtKindUpdateRecord = EventKind("update")
EvtKindDeleteRecord = EventKind("delete")
)
type RepoHead struct {
gorm.Model
Usr models.Uid `gorm:"uniqueIndex"`
Root string
}
type userLock struct {
lk sync.Mutex
count int
}
func (rm *RepoManager) lockUser(ctx context.Context, user models.Uid) func() {
ctx, span := otel.Tracer("repoman").Start(ctx, "userLock")
defer span.End()
rm.lklk.Lock()
ulk, ok := rm.userLocks[user]
if !ok {
ulk = &userLock{}
rm.userLocks[user] = ulk
}
ulk.count++
rm.lklk.Unlock()
ulk.lk.Lock()
return func() {
rm.lklk.Lock()
ulk.lk.Unlock()
ulk.count--
if ulk.count == 0 {
delete(rm.userLocks, user)
}
rm.lklk.Unlock()
}
}
func (rm *RepoManager) CarStore() *carstore.CarStore {
return rm.cs
}
func (rm *RepoManager) CreateRecord(ctx context.Context, user models.Uid, collection string, rec cbg.CBORMarshaler) (string, cid.Cid, error) {
ctx, span := otel.Tracer("repoman").Start(ctx, "CreateRecord")
defer span.End()
unlock := rm.lockUser(ctx, user)
defer unlock()
rev, err := rm.cs.GetUserRepoRev(ctx, user)
if err != nil {
return "", cid.Undef, err
}
ds, err := rm.cs.NewDeltaSession(ctx, user, &rev)
if err != nil {
return "", cid.Undef, err
}
head := ds.BaseCid()
r, err := repo.OpenRepo(ctx, ds, head)
if err != nil {
return "", cid.Undef, err
}
cc, tid, err := r.CreateRecord(ctx, collection, rec)
if err != nil {
return "", cid.Undef, err
}
nroot, nrev, err := r.Commit(ctx, rm.kmgr.SignForUser)
if err != nil {
return "", cid.Undef, err
}
rslice, err := ds.CloseWithRoot(ctx, nroot, nrev)
if err != nil {
return "", cid.Undef, fmt.Errorf("close with root: %w", err)
}
var oldroot *cid.Cid
if head.Defined() {
oldroot = &head
}
if rm.events != nil {
rm.events(ctx, &RepoEvent{
User: user,
OldRoot: oldroot,
NewRoot: nroot,
Rev: nrev,
Since: &rev,
Ops: []RepoOp{{
Kind: EvtKindCreateRecord,
Collection: collection,
Rkey: tid,
Record: rec,
RecCid: &cc,
}},
RepoSlice: rslice,
})
}
return collection + "/" + tid, cc, nil
}
func (rm *RepoManager) UpdateRecord(ctx context.Context, user models.Uid, collection, rkey string, rec cbg.CBORMarshaler) (cid.Cid, error) {
ctx, span := otel.Tracer("repoman").Start(ctx, "UpdateRecord")
defer span.End()
unlock := rm.lockUser(ctx, user)
defer unlock()
rev, err := rm.cs.GetUserRepoRev(ctx, user)
if err != nil {
return cid.Undef, err
}
ds, err := rm.cs.NewDeltaSession(ctx, user, &rev)
if err != nil {
return cid.Undef, err
}
head := ds.BaseCid()
r, err := repo.OpenRepo(ctx, ds, head)
if err != nil {
return cid.Undef, err
}
rpath := collection + "/" + rkey
cc, err := r.PutRecord(ctx, rpath, rec)
if err != nil {
return cid.Undef, err
}
nroot, nrev, err := r.Commit(ctx, rm.kmgr.SignForUser)
if err != nil {
return cid.Undef, err
}
rslice, err := ds.CloseWithRoot(ctx, nroot, nrev)
if err != nil {
return cid.Undef, fmt.Errorf("close with root: %w", err)
}
var oldroot *cid.Cid
if head.Defined() {
oldroot = &head
}
if rm.events != nil {
op := RepoOp{
Kind: EvtKindUpdateRecord,
Collection: collection,
Rkey: rkey,
RecCid: &cc,
}
if rm.hydrateRecords {
op.Record = rec
}
rm.events(ctx, &RepoEvent{
User: user,
OldRoot: oldroot,
NewRoot: nroot,
Rev: nrev,
Since: &rev,
Ops: []RepoOp{op},
RepoSlice: rslice,
})
}
return cc, nil
}
func (rm *RepoManager) DeleteRecord(ctx context.Context, user models.Uid, collection, rkey string) error {
ctx, span := otel.Tracer("repoman").Start(ctx, "DeleteRecord")
defer span.End()
unlock := rm.lockUser(ctx, user)
defer unlock()
rev, err := rm.cs.GetUserRepoRev(ctx, user)
if err != nil {
return err
}
ds, err := rm.cs.NewDeltaSession(ctx, user, &rev)
if err != nil {
return err
}
head := ds.BaseCid()
r, err := repo.OpenRepo(ctx, ds, head)
if err != nil {
return err
}
rpath := collection + "/" + rkey
if err := r.DeleteRecord(ctx, rpath); err != nil {
return err
}
nroot, nrev, err := r.Commit(ctx, rm.kmgr.SignForUser)
if err != nil {
return err
}
rslice, err := ds.CloseWithRoot(ctx, nroot, nrev)
if err != nil {
return fmt.Errorf("close with root: %w", err)
}
var oldroot *cid.Cid
if head.Defined() {
oldroot = &head
}
if rm.events != nil {
rm.events(ctx, &RepoEvent{
User: user,
OldRoot: oldroot,
NewRoot: nroot,
Rev: nrev,
Since: &rev,
Ops: []RepoOp{{
Kind: EvtKindDeleteRecord,
Collection: collection,
Rkey: rkey,
}},
RepoSlice: rslice,
})
}
return nil
}
func (rm *RepoManager) InitNewActor(ctx context.Context, user models.Uid, handle, did, displayname string, declcid, actortype string) error {
unlock := rm.lockUser(ctx, user)
defer unlock()
if did == "" {
return fmt.Errorf("must specify DID for new actor")
}
if user == 0 {
return fmt.Errorf("must specify user for new actor")
}
ds, err := rm.cs.NewDeltaSession(ctx, user, nil)
if err != nil {
return fmt.Errorf("creating new delta session: %w", err)
}
r := repo.NewRepo(ctx, did, ds)
profile := &bsky.ActorProfile{
DisplayName: &displayname,
}
_, err = r.PutRecord(ctx, "app.bsky.actor.profile/self", profile)
if err != nil {
return fmt.Errorf("setting initial actor profile: %w", err)
}
root, nrev, err := r.Commit(ctx, rm.kmgr.SignForUser)
if err != nil {
return fmt.Errorf("committing repo for actor init: %w", err)
}
rslice, err := ds.CloseWithRoot(ctx, root, nrev)
if err != nil {
return fmt.Errorf("close with root: %w", err)
}
if rm.events != nil {
op := RepoOp{
Kind: EvtKindCreateRecord,
Collection: "app.bsky.actor.profile",
Rkey: "self",
}
if rm.hydrateRecords {
op.Record = profile
}
rm.events(ctx, &RepoEvent{
User: user,
NewRoot: root,
Rev: nrev,
Ops: []RepoOp{op},
RepoSlice: rslice,
})
}
return nil
}
func (rm *RepoManager) GetRepoRoot(ctx context.Context, user models.Uid) (cid.Cid, error) {
unlock := rm.lockUser(ctx, user)
defer unlock()
return rm.cs.GetUserRepoHead(ctx, user)
}
func (rm *RepoManager) GetRepoRev(ctx context.Context, user models.Uid) (string, error) {
unlock := rm.lockUser(ctx, user)
defer unlock()
return rm.cs.GetUserRepoRev(ctx, user)
}
func (rm *RepoManager) ReadRepo(ctx context.Context, user models.Uid, since string, w io.Writer) error {
return rm.cs.ReadUserCar(ctx, user, since, true, w)
}
func (rm *RepoManager) GetRecord(ctx context.Context, user models.Uid, collection string, rkey string, maybeCid cid.Cid) (cid.Cid, cbg.CBORMarshaler, error) {
bs, err := rm.cs.ReadOnlySession(user)
if err != nil {
return cid.Undef, nil, err
}
head, err := rm.cs.GetUserRepoHead(ctx, user)
if err != nil {
return cid.Undef, nil, err
}
r, err := repo.OpenRepo(ctx, bs, head)
if err != nil {
return cid.Undef, nil, err
}
ocid, val, err := r.GetRecord(ctx, collection+"/"+rkey)
if err != nil {
return cid.Undef, nil, err
}
if maybeCid.Defined() && ocid != maybeCid {
return cid.Undef, nil, fmt.Errorf("record at specified key had different CID than expected")
}
return ocid, val, nil
}
func (rm *RepoManager) GetRecordProof(ctx context.Context, user models.Uid, collection string, rkey string) (cid.Cid, []blocks.Block, error) {
robs, err := rm.cs.ReadOnlySession(user)
if err != nil {
return cid.Undef, nil, err
}
bs := util.NewLoggingBstore(robs)
head, err := rm.cs.GetUserRepoHead(ctx, user)
if err != nil {
return cid.Undef, nil, err
}
r, err := repo.OpenRepo(ctx, bs, head)
if err != nil {
return cid.Undef, nil, err
}
_, _, err = r.GetRecord(ctx, collection+"/"+rkey)
if err != nil {
return cid.Undef, nil, err
}
return head, bs.GetLoggedBlocks(), nil
}
func (rm *RepoManager) GetProfile(ctx context.Context, uid models.Uid) (*bsky.ActorProfile, error) {
bs, err := rm.cs.ReadOnlySession(uid)
if err != nil {
return nil, err
}
head, err := rm.cs.GetUserRepoHead(ctx, uid)
if err != nil {
return nil, err
}
r, err := repo.OpenRepo(ctx, bs, head)
if err != nil {
return nil, err
}
_, val, err := r.GetRecord(ctx, "app.bsky.actor.profile/self")
if err != nil {
return nil, err
}
ap, ok := val.(*bsky.ActorProfile)
if !ok {
return nil, fmt.Errorf("found wrong type in actor profile location in tree")
}
return ap, nil
}
func (rm *RepoManager) CheckRepoSig(ctx context.Context, r *repo.Repo, expdid string) error {
ctx, span := otel.Tracer("repoman").Start(ctx, "CheckRepoSig")
defer span.End()
repoDid := r.RepoDid()
if expdid != repoDid {
return fmt.Errorf("DID in repo did not match (%q != %q)", expdid, repoDid)
}
scom := r.SignedCommit()
usc := scom.Unsigned()
sb, err := usc.BytesForSigning()
if err != nil {
return fmt.Errorf("commit serialization failed: %w", err)
}
if err := rm.kmgr.VerifyUserSignature(ctx, repoDid, scom.Sig, sb); err != nil {
return fmt.Errorf("signature check failed (sig: %x) (sb: %x) : %w", scom.Sig, sb, err)
}
return nil
}
func (rm *RepoManager) HandleExternalUserEvent(ctx context.Context, pdsid uint, uid models.Uid, did string, since *string, nrev string, carslice []byte, ops []*atproto.SyncSubscribeRepos_RepoOp) error {
ctx, span := otel.Tracer("repoman").Start(ctx, "HandleExternalUserEvent")
defer span.End()
span.SetAttributes(attribute.Int64("uid", int64(uid)))
log.Debugw("HandleExternalUserEvent", "pds", pdsid, "uid", uid, "since", since, "nrev", nrev)
unlock := rm.lockUser(ctx, uid)
defer unlock()
root, ds, err := rm.cs.ImportSlice(ctx, uid, since, carslice)
if err != nil {
return fmt.Errorf("importing external carslice: %w", err)
}
r, err := repo.OpenRepo(ctx, ds, root)
if err != nil {
return fmt.Errorf("opening external user repo (%d, root=%s): %w", uid, root, err)
}
if err := rm.CheckRepoSig(ctx, r, did); err != nil {
return err
}
var skipcids map[cid.Cid]bool
if ds.BaseCid().Defined() {
oldrepo, err := repo.OpenRepo(ctx, ds, ds.BaseCid())
if err != nil {
return fmt.Errorf("failed to check data root in old repo: %w", err)
}
// if the old commit has a 'prev', CalcDiff will error out while trying
// to walk it. This is an old repo thing that is being deprecated.
// This check is a temporary workaround until all repos get migrated
// and this becomes no longer an issue
prev, _ := oldrepo.PrevCommit(ctx)
if prev != nil {
skipcids = map[cid.Cid]bool{
*prev: true,
}
}
}
if err := ds.CalcDiff(ctx, skipcids); err != nil {
return fmt.Errorf("failed while calculating mst diff (since=%v): %w", since, err)
}
var evtops []RepoOp
for _, op := range ops {
parts := strings.SplitN(op.Path, "/", 2)
if len(parts) != 2 {
return fmt.Errorf("invalid rpath in mst diff, must have collection and rkey")
}
switch EventKind(op.Action) {
case EvtKindCreateRecord:
rop := RepoOp{
Kind: EvtKindCreateRecord,
Collection: parts[0],
Rkey: parts[1],
RecCid: (*cid.Cid)(op.Cid),
}
if rm.hydrateRecords {
_, rec, err := r.GetRecord(ctx, op.Path)
if err != nil {
return fmt.Errorf("reading changed record from car slice: %w", err)
}
rop.Record = rec
}
evtops = append(evtops, rop)
case EvtKindUpdateRecord:
rop := RepoOp{
Kind: EvtKindUpdateRecord,
Collection: parts[0],
Rkey: parts[1],
RecCid: (*cid.Cid)(op.Cid),
}
if rm.hydrateRecords {
_, rec, err := r.GetRecord(ctx, op.Path)
if err != nil {
return fmt.Errorf("reading changed record from car slice: %w", err)
}
rop.Record = rec
}
evtops = append(evtops, rop)
case EvtKindDeleteRecord:
evtops = append(evtops, RepoOp{
Kind: EvtKindDeleteRecord,
Collection: parts[0],
Rkey: parts[1],
})
default:
return fmt.Errorf("unrecognized external user event kind: %q", op.Action)
}
}
rslice, err := ds.CloseWithRoot(ctx, root, nrev)
if err != nil {
return fmt.Errorf("close with root: %w", err)
}
if rm.events != nil {
rm.events(ctx, &RepoEvent{
User: uid,
//OldRoot: prev,
NewRoot: root,
Rev: nrev,
Since: since,
Ops: evtops,
RepoSlice: rslice,
PDS: pdsid,
})
}
return nil
}
func rkeyForCollection(collection string) string {
return repo.NextTID()
}
func (rm *RepoManager) BatchWrite(ctx context.Context, user models.Uid, writes []*atproto.RepoApplyWrites_Input_Writes_Elem) error {
ctx, span := otel.Tracer("repoman").Start(ctx, "BatchWrite")
defer span.End()
unlock := rm.lockUser(ctx, user)
defer unlock()
rev, err := rm.cs.GetUserRepoRev(ctx, user)
if err != nil {
return err
}
ds, err := rm.cs.NewDeltaSession(ctx, user, &rev)
if err != nil {
return err
}
head := ds.BaseCid()
r, err := repo.OpenRepo(ctx, ds, head)
if err != nil {
return err
}
var ops []RepoOp
for _, w := range writes {
switch {
case w.RepoApplyWrites_Create != nil:
c := w.RepoApplyWrites_Create
var rkey string
if c.Rkey != nil {
rkey = *c.Rkey
} else {
rkey = rkeyForCollection(c.Collection)
}
nsid := c.Collection + "/" + rkey
cc, err := r.PutRecord(ctx, nsid, c.Value.Val)
if err != nil {
return err
}
op := RepoOp{
Kind: EvtKindCreateRecord,
Collection: c.Collection,
Rkey: rkey,
RecCid: &cc,
}
if rm.hydrateRecords {
op.Record = c.Value.Val
}
ops = append(ops, op)
case w.RepoApplyWrites_Update != nil:
u := w.RepoApplyWrites_Update
cc, err := r.PutRecord(ctx, u.Collection+"/"+u.Rkey, u.Value.Val)
if err != nil {
return err
}
op := RepoOp{
Kind: EvtKindUpdateRecord,
Collection: u.Collection,
Rkey: u.Rkey,
RecCid: &cc,
}
if rm.hydrateRecords {
op.Record = u.Value.Val
}
ops = append(ops, op)
case w.RepoApplyWrites_Delete != nil:
d := w.RepoApplyWrites_Delete
if err := r.DeleteRecord(ctx, d.Collection+"/"+d.Rkey); err != nil {
return err
}
ops = append(ops, RepoOp{
Kind: EvtKindDeleteRecord,
Collection: d.Collection,
Rkey: d.Rkey,
})
default:
return fmt.Errorf("no operation set in write enum")
}
}
nroot, nrev, err := r.Commit(ctx, rm.kmgr.SignForUser)
if err != nil {
return err
}
rslice, err := ds.CloseWithRoot(ctx, nroot, nrev)
if err != nil {
return fmt.Errorf("close with root: %w", err)
}
var oldroot *cid.Cid
if head.Defined() {
oldroot = &head
}
if rm.events != nil {
rm.events(ctx, &RepoEvent{
User: user,
OldRoot: oldroot,
NewRoot: nroot,
RepoSlice: rslice,
Rev: nrev,
Since: &rev,
Ops: ops,
})
}
return nil
}
func (rm *RepoManager) ImportNewRepo(ctx context.Context, user models.Uid, repoDid string, r io.Reader, rev *string) error {
ctx, span := otel.Tracer("repoman").Start(ctx, "ImportNewRepo")
defer span.End()
unlock := rm.lockUser(ctx, user)
defer unlock()
currev, err := rm.cs.GetUserRepoRev(ctx, user)
if err != nil {
return err
}
curhead, err := rm.cs.GetUserRepoHead(ctx, user)
if err != nil {
return err
}
if rev == nil {
// if 'rev' is nil, this implies a fresh sync.
// in this case, ignore any existing blocks we have and treat this like a clean import.
curhead = cid.Undef
}
if rev != nil && *rev != currev {
// TODO: we could probably just deal with this
return fmt.Errorf("ImportNewRepo called with incorrect base")
}
err = rm.processNewRepo(ctx, user, r, rev, func(ctx context.Context, root cid.Cid, finish func(context.Context, string) ([]byte, error), bs blockstore.Blockstore) error {
r, err := repo.OpenRepo(ctx, bs, root)
if err != nil {
return fmt.Errorf("opening new repo: %w", err)
}
scom := r.SignedCommit()
usc := scom.Unsigned()
sb, err := usc.BytesForSigning()
if err != nil {
return fmt.Errorf("commit serialization failed: %w", err)
}
if err := rm.kmgr.VerifyUserSignature(ctx, repoDid, scom.Sig, sb); err != nil {
return fmt.Errorf("new user signature check failed: %w", err)
}
diffops, err := r.DiffSince(ctx, curhead)
if err != nil {
return fmt.Errorf("diff trees (curhead: %s): %w", curhead, err)
}
var ops []RepoOp
for _, op := range diffops {
repoOpsImported.Inc()
out, err := processOp(ctx, bs, op, rm.hydrateRecords)
if err != nil {
log.Errorw("failed to process repo op", "err", err, "path", op.Rpath, "repo", repoDid)
}
if out != nil {
ops = append(ops, *out)
}
}
slice, err := finish(ctx, scom.Rev)
if err != nil {
return err
}
if rm.events != nil {
rm.events(ctx, &RepoEvent{
User: user,
//OldRoot: oldroot,
NewRoot: root,
Rev: scom.Rev,
Since: &currev,
RepoSlice: slice,
Ops: ops,
})
}
return nil
})
if err != nil {
return fmt.Errorf("process new repo (current rev: %s): %w:", currev, err)
}
return nil
}
func processOp(ctx context.Context, bs blockstore.Blockstore, op *mst.DiffOp, hydrateRecords bool) (*RepoOp, error) {
parts := strings.SplitN(op.Rpath, "/", 2)
if len(parts) != 2 {
return nil, fmt.Errorf("repo mst had invalid rpath: %q", op.Rpath)
}
switch op.Op {
case "add", "mut":
kind := EvtKindCreateRecord
if op.Op == "mut" {
kind = EvtKindUpdateRecord
}
outop := &RepoOp{
Kind: kind,
Collection: parts[0],
Rkey: parts[1],
RecCid: &op.NewCid,
}
if hydrateRecords {
blk, err := bs.Get(ctx, op.NewCid)
if err != nil {
return nil, err
}
rec, err := lexutil.CborDecodeValue(blk.RawData())
if err != nil {
if !errors.Is(err, lexutil.ErrUnrecognizedType) {
return nil, err
}
log.Warnf("failed processing repo diff: %s", err)
} else {
outop.Record = rec
}
}
return outop, nil
case "del":
return &RepoOp{
Kind: EvtKindDeleteRecord,
Collection: parts[0],
Rkey: parts[1],
RecCid: nil,
}, nil
default:
return nil, fmt.Errorf("diff returned invalid op type: %q", op.Op)
}
}
func (rm *RepoManager) processNewRepo(ctx context.Context, user models.Uid, r io.Reader, rev *string, cb func(ctx context.Context, root cid.Cid, finish func(context.Context, string) ([]byte, error), bs blockstore.Blockstore) error) error {
ctx, span := otel.Tracer("repoman").Start(ctx, "processNewRepo")
defer span.End()
carr, err := car.NewCarReader(r)
if err != nil {
return err
}
if len(carr.Header.Roots) != 1 {
return fmt.Errorf("invalid car file, header must have a single root (has %d)", len(carr.Header.Roots))
}
membs := blockstore.NewBlockstore(datastore.NewMapDatastore())
for {
blk, err := carr.Next()
if err != nil {
if err == io.EOF {
break
}
return err
}
if err := membs.Put(ctx, blk); err != nil {
return err
}
}
seen := make(map[cid.Cid]bool)
root := carr.Header.Roots[0]
// TODO: if there are blocks that get convergently recreated throughout
// the repos lifecycle, this will end up erroneously not including
// them. We should compute the set of blocks needed to read any repo
// ops that happened in the commit and use that for our 'output' blocks
cids, err := walkTree(ctx, seen, root, membs, true)
if err != nil {
return fmt.Errorf("walkTree: %w", err)
}
ds, err := rm.cs.NewDeltaSession(ctx, user, rev)
if err != nil {
return fmt.Errorf("opening delta session: %w", err)
}
for _, c := range cids {
blk, err := membs.Get(ctx, c)
if err != nil {
return fmt.Errorf("copying walked cids to carstore: %w", err)
}
if err := ds.Put(ctx, blk); err != nil {
return err
}
}
finish := func(ctx context.Context, nrev string) ([]byte, error) {
return ds.CloseWithRoot(ctx, root, nrev)
}
if err := cb(ctx, root, finish, ds); err != nil {
return fmt.Errorf("cb errored root: %s, rev: %s: %w", root, stringOrNil(rev), err)
}
return nil
}
func stringOrNil(s *string) string {
if s == nil {
return "nil"
}
return *s
}
// walkTree returns all cids linked recursively by the root, skipping any cids
// in the 'skip' map, and not erroring on 'not found' if prevMissing is set
func walkTree(ctx context.Context, skip map[cid.Cid]bool, root cid.Cid, bs blockstore.Blockstore, prevMissing bool) ([]cid.Cid, error) {
// TODO: what if someone puts non-cbor links in their repo?
if root.Prefix().Codec != cid.DagCBOR {