-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathgcp.go
More file actions
1713 lines (1518 loc) · 65.7 KB
/
Copy pathgcp.go
File metadata and controls
1713 lines (1518 loc) · 65.7 KB
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 2024 The Tessera authors. All Rights Reserved.
//
// 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 gcp contains a GCP-based storage implementation for Tessera.
//
// TODO: decide whether to rename this package.
//
// This storage implementation uses GCS for long-term storage and serving of
// entry bundles and log tiles, and Spanner for coordinating updates to GCS
// when multiple instances of a personality binary are running.
//
// A single GCS bucket is used to hold entry bundles and log internal tiles.
// The object keys for the bucket are selected so as to conform to the
// expected layout of a tile-based log.
//
// A Spanner database provides a transactional mechanism to allow multiple
// frontends to safely update the contents of the log.
package gcp
import (
"bytes"
"context"
"encoding/gob"
"errors"
"fmt"
"io"
"math"
"net/http"
"os"
"path/filepath"
"regexp"
"sync"
"time"
"cloud.google.com/go/spanner"
database "cloud.google.com/go/spanner/admin/database/apiv1"
adminpb "cloud.google.com/go/spanner/admin/database/apiv1/databasepb"
"cloud.google.com/go/spanner/apiv1/spannerpb"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"log/slog"
gcs "cloud.google.com/go/storage"
"github.com/google/go-cmp/cmp"
"github.com/transparency-dev/merkle/rfc6962"
"github.com/transparency-dev/tessera"
"github.com/transparency-dev/tessera/api"
"github.com/transparency-dev/tessera/api/layout"
"github.com/transparency-dev/tessera/internal/fetcher"
"github.com/transparency-dev/tessera/internal/migrate"
"github.com/transparency-dev/tessera/internal/otel"
"github.com/transparency-dev/tessera/internal/parse"
storage "github.com/transparency-dev/tessera/storage/internal"
"go.opentelemetry.io/otel/trace"
"golang.org/x/sync/errgroup"
"google.golang.org/api/googleapi"
"google.golang.org/api/iterator"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
// minCheckpointInterval is the shortest permitted interval between updating published checkpoints.
// GCS has a rate limit 1 update per second for individual objects, but we've observed that attempting
// to update at exactly that rate still results in the occasional refusal, so bake in a little wiggle
// room.
minCheckpointInterval = 1100 * time.Millisecond
logContType = "application/octet-stream"
ckptContType = "text/plain; charset=utf-8"
logCacheControl = "max-age=604800,immutable"
ckptCacheControl = "no-cache"
DefaultIntegrationSizeLimit = 5 * 4096
// defaultSeqTableMaxBatchByteSize is the default maximum byte size of a batch of entries to be written to the
// "V" field in the "Seq" table. This is set to just under 10 MiB, the maximum size of the Spanner
// BYTES column, with some headroom for the gob encoding.
defaultSeqTableMaxBatchByteSize = 9 << 20 // 9 MiB
// SchemaCompatibilityVersion represents the expected version (e.g. layout & serialisation) of stored data.
//
// A binary built with a given version of the Tessera library is compatible with stored data created by a different version
// of the library if and only if this value is the same as the compatibilityVersion stored in the Tessera table.
//
// NOTE: if changing this version, you need to consider whether end-users are going to update their schema instances to be
// compatible with the new format, and provide a means to do it if so.
SchemaCompatibilityVersion = 1
// defaultAssignEntriesTimeout is the default context timeout applied when assigning a batch of entries to the Spanner sequencer.
defaultAssignEntriesTimeout = 2 * time.Second
// defaultIntegrationTimeout is the default context timeout applied when undertaking an integration task.
defaultIntegrationTimeout = 10 * time.Second
// defaultGCTimeout is the default context timeout applied when undertaking a garbage collection task.
defaultGCTimeout = 30 * time.Second
)
// Storage is a GCP based storage implementation for Tessera.
type Storage struct {
cfg Config
}
// sequencer describes a type which knows how to sequence entries.
//
// TODO(al): rename this as it's really more of a coordination for the log.
type sequencer interface {
// assignEntries should durably allocate contiguous index numbers to the provided entries.
assignEntries(ctx context.Context, entries []*tessera.Entry) error
// consumeEntries should call the provided function with up to limit previously sequenced entries.
// If the call to consumeFunc returns no error, the entries should be considered to have been consumed.
// If any entries were successfully consumed, the implementation should also return true; this
// serves as a weak hint that there may be more entries to be consumed.
// If forceUpdate is true, then the consumeFunc should be called, with an empty slice of entries if
// necessary. This allows the log self-initialise in a transactionally safe manner.
consumeEntries(ctx context.Context, limit uint64, f consumeFunc, forceUpdate bool) (bool, error)
// currentTree returns the tree state of the currently integrated tree according to the IntCoord table.
currentTree(ctx context.Context) (uint64, []byte, error)
// nextIndex returns the next available index in the log.
nextIndex(ctx context.Context) (uint64, error)
// publishCheckpoint coordinates the publication of new checkpoints based on the current integrated tree.
publishCheckpoint(ctx context.Context, minStaleActive, minStaleRepub time.Duration, f func(ctx context.Context, size uint64, root []byte) error) (time.Time, error)
// garbageCollect coordinates the removal of unneeded partial tiles/entry bundles for the provided tree size, up to a maximum number of deletes per invocation.
garbageCollect(ctx context.Context, treeSize uint64, maxDeletes uint, removePrefix func(ctx context.Context, prefix string) error, entriesPath func(uint64, uint8) string) error
}
// consumeFunc is the signature of a function which can consume entries from the sequencer and integrate
// them into the log.
// Returns the new rootHash once all passed entries have been integrated.
type consumeFunc func(ctx context.Context, from uint64, entries []storage.SequencedEntry) ([]byte, error)
// Config holds GCP project and resource configuration for a storage instance.
type Config struct {
// GCSClient will be used to interact with GCS. If unset, Tessera will create one.
GCSClient *gcs.Client
// SpannerClient will be used to interact with Spanner. If unset, Tessera will create one.
SpannerClient *spanner.Client
// HTTPClient will be used for other HTTP requests. If unset, Tessera will use the net/http DefaultClient.
HTTPClient *http.Client
// Bucket is the name of the GCS bucket to use for storing log state.
Bucket string
// BucketPrefix is an optional prefix to prepend to all log resource paths.
// This can be used e.g. to store multiple logs in the same bucket.
BucketPrefix string
// Spanner is the GCP resource URI of the spanner database instance to use.
Spanner string
// SpannerTablePrefix is an optional prefix to prepend to the names of all Spanner tables.
// If set, it must start with a letter, contain only letters, digits, or underscores
// (e.g. "log1_"), and be at most 64 characters long.
// It's recommended to derive this prefix from the log's origin string, to
// make it easy to associate tables with specific logs.
//
// TODO: consider providing a mechanism to set both BucketPrefix and SpannerTablePrefix
// from a single string to avoid misconfiguration foot-guns.
SpannerTablePrefix string
}
// tablePrefixRE matches valid values for a Spanner table prefix: empty, or a leading
// letter followed by up to 63 letters, digits, or underscores.
var tablePrefixRE = regexp.MustCompile(`^([A-Za-z][A-Za-z0-9_]{0,63})?$`)
// New creates a new instance of the GCP based Storage.
func New(ctx context.Context, cfg Config) (tessera.Driver, error) {
if !tablePrefixRE.MatchString(cfg.SpannerTablePrefix) {
return nil, fmt.Errorf("invalid SpannerTablePrefix %q: must start with a letter, contain only letters, digits, or underscores, and be at most 64 characters long", cfg.SpannerTablePrefix)
}
if cfg.HTTPClient == nil {
cfg.HTTPClient = http.DefaultClient
}
return &Storage{
cfg: cfg,
}, nil
}
type LogReader struct {
lrs logResourceStore
integratedSize func(context.Context) (uint64, error)
nextIndex func(context.Context) (uint64, error)
}
func (lr *LogReader) ReadCheckpoint(ctx context.Context) ([]byte, error) {
return otel.Trace(ctx, "tessera.storage.gcp.ReadCheckpoint", tracer, func(ctx context.Context, span trace.Span) ([]byte, error) {
r, err := lr.lrs.getCheckpoint(ctx)
if err != nil {
if errors.Is(err, gcs.ErrObjectNotExist) {
return r, os.ErrNotExist
}
}
return r, err
})
}
func (lr *LogReader) ReadTile(ctx context.Context, l, i uint64, p uint8) ([]byte, error) {
return otel.Trace(ctx, "tessera.storage.gcp.ReadTile", tracer, func(ctx context.Context, span trace.Span) ([]byte, error) {
return fetcher.PartialOrFullResource(ctx, p, func(ctx context.Context, p uint8) ([]byte, error) {
return lr.lrs.getTile(ctx, l, i, p)
})
})
}
func (lr *LogReader) ReadEntryBundle(ctx context.Context, i uint64, p uint8) ([]byte, error) {
return otel.Trace(ctx, "tessera.storage.gcp.ReadEntryBundle", tracer, func(ctx context.Context, span trace.Span) ([]byte, error) {
return fetcher.PartialOrFullResource(ctx, p, func(ctx context.Context, p uint8) ([]byte, error) {
return lr.lrs.getEntryBundle(ctx, i, p)
})
})
}
func (lr *LogReader) IntegratedSize(ctx context.Context) (uint64, error) {
return otel.Trace(ctx, "tessera.storage.gcp.IntegratedSize", tracer, func(ctx context.Context, span trace.Span) (uint64, error) {
return lr.integratedSize(ctx)
})
}
func (lr *LogReader) NextIndex(ctx context.Context) (uint64, error) {
return otel.Trace(ctx, "tessera.storage.gcp.NextIndex", tracer, func(ctx context.Context, span trace.Span) (uint64, error) {
return lr.nextIndex(ctx)
})
}
// Appender creates a new tessera.Appender lifecycle object.
func (s *Storage) Appender(ctx context.Context, opts *tessera.AppendOptions) (*tessera.Appender, tessera.LogReader, error) {
if s.cfg.GCSClient == nil {
var err error
s.cfg.GCSClient, err = gcs.NewClient(ctx, gcs.WithJSONReads())
if err != nil {
return nil, nil, fmt.Errorf("failed to create GCS client: %v", err)
}
}
gs := &gcsStorage{
gcsClient: s.cfg.GCSClient,
bucket: s.cfg.Bucket,
bucketPrefix: s.cfg.BucketPrefix,
}
var err error
if s.cfg.SpannerClient == nil {
s.cfg.SpannerClient, err = spanner.NewClient(ctx, s.cfg.Spanner)
if err != nil {
return nil, nil, fmt.Errorf("failed to connect to Spanner: %v", err)
}
}
table := func(t string) string {
return s.cfg.SpannerTablePrefix + t
}
if err := initDB(ctx, s.cfg.Spanner, table); err != nil {
return nil, nil, fmt.Errorf("failed to verify/init Spanner schema: %v", err)
}
seq, err := newSpannerCoordinator(ctx, s.cfg.SpannerClient, table, uint64(opts.PushbackMaxOutstanding()))
if err != nil {
return nil, nil, fmt.Errorf("failed to create Spanner coordinator: %v", err)
}
a, lr, err := s.newAppender(ctx, gs, seq, opts)
if err != nil {
return nil, nil, err
}
return &tessera.Appender{
Add: a.Add,
}, lr, nil
}
// newAppender creates and initialises a tessera.Appender struct with the provided underlying storage implementations.
func (s *Storage) newAppender(ctx context.Context, o objStore, seq *spannerCoordinator, opts *tessera.AppendOptions) (*Appender, tessera.LogReader, error) {
if opts.CheckpointInterval() < minCheckpointInterval {
return nil, nil, fmt.Errorf("requested CheckpointInterval (%v) is less than minimum permitted %v", opts.CheckpointInterval(), minCheckpointInterval)
}
a := &Appender{
logStore: &logResourceStore{
objStore: o,
entriesPath: opts.EntriesPath(),
},
sequencer: seq,
cpUpdated: make(chan struct{}),
entriesAssigned: make(chan struct{}, 1),
}
a.queue = storage.NewQueue(ctx, opts.BatchMaxAge(), opts.BatchMaxSize(), func(ctx context.Context, entries []*tessera.Entry) error {
ctx, cancel := context.WithTimeout(ctx, defaultAssignEntriesTimeout)
defer cancel()
if err := a.sequencer.assignEntries(ctx, entries); err != nil {
return err
}
select {
case a.entriesAssigned <- struct{}{}:
default:
}
return nil
})
reader := &LogReader{
lrs: *a.logStore,
integratedSize: func(ctx context.Context) (uint64, error) {
s, _, err := a.sequencer.currentTree(ctx)
return s, err
},
nextIndex: a.sequencer.nextIndex,
}
var err error
a.newCP, err = opts.CheckpointPublisherContext(ctx, reader, s.cfg.HTTPClient)
if err != nil {
return nil, nil, fmt.Errorf("failed to create checkpoint publisher: %v", err)
}
if err := a.init(ctx); err != nil {
return nil, nil, fmt.Errorf("failed to initialise log storage: %v", err)
}
go a.integrateEntriesJob(ctx)
go a.publishCheckpointJob(ctx, opts.CheckpointInterval(), opts.CheckpointRepublishInterval(), opts.CheckpointPublicationTimeout())
if i := opts.GarbageCollectionInterval(); i > 0 {
go a.garbageCollectorJob(ctx, i)
}
return a, reader, nil
}
// Appender is an implementation of the Tessera appender lifecycle contract.
type Appender struct {
newCP func(context.Context, uint64, []byte) ([]byte, error)
sequencer sequencer
logStore *logResourceStore
queue *storage.Queue
cpUpdated chan struct{}
entriesAssigned chan struct{}
}
// Add is the entrypoint for adding entries to a sequencing log.
func (a *Appender) Add(ctx context.Context, e *tessera.Entry) tessera.IndexFuture {
ctx, span := tracer.Start(ctx, "tessera.storage.gcp.Add")
defer span.End()
// Reject entries which are too large to fit in the Seq table even as a single-entry batch.
if size := len(e.Data()); size > defaultSeqTableMaxBatchByteSize {
return func() (tessera.Index, error) {
return tessera.Index{}, fmt.Errorf("entry size %d exceeds maximum allowed %d", size, defaultSeqTableMaxBatchByteSize)
}
}
return a.queue.Add(ctx, e)
}
// integrateEntriesJob periodically append newly sequenced entries.
//
// Blocks until ctx is done.
func (a *Appender) integrateEntriesJob(ctx context.Context) {
t := time.NewTicker(1 * time.Second)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-a.entriesAssigned:
case <-t.C:
}
if err := otel.TraceErr(ctx, "tessera.storage.gcp.integrateEntriesJob", tracer, func(ctx context.Context, span trace.Span) error {
start := time.Now()
defer func() {
opsHistogram.Record(ctx, time.Since(start).Milliseconds(), metric.WithAttributes(opNameKey.String("integrateEntries")))
}()
ctx, cancel := context.WithTimeout(ctx, defaultIntegrationTimeout)
defer cancel() // Note: ok because we're in a func passed to TraceErr here!
workDone, err := a.sequencer.consumeEntries(ctx, DefaultIntegrationSizeLimit, a.integrateEntries, false)
if err != nil {
return fmt.Errorf("integrateEntriesJob: %v", err)
}
if workDone {
select {
case a.cpUpdated <- struct{}{}:
default:
}
}
return nil
}, trace.WithAttributes(otel.PeriodicKey.Bool(true))); err != nil {
slog.ErrorContext(ctx, "integrateEntriesJob failed", slog.Any("error", err))
}
}
}
// publishCheckpointJob periodically attempts to publish a new checkpoint representing the current state
// of the tree, once per interval.
//
// Blocks until ctx is done.
func (a *Appender) publishCheckpointJob(ctx context.Context, pubInterval, republishInterval, publicationTimeout time.Duration) {
t := time.NewTicker(pubInterval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-a.cpUpdated:
case <-t.C:
}
if err := otel.TraceErr(ctx, "tessera.storage.gcp.publishCheckpointJob", tracer, func(ctx context.Context, span trace.Span) error {
ctx, cancel := context.WithTimeout(ctx, publicationTimeout)
defer cancel() // Note: ok because we're in a func passed to TraceErr here!
nextPub, err := a.sequencer.publishCheckpoint(ctx, pubInterval, republishInterval, a.updateCheckpoint)
if err != nil {
return fmt.Errorf("publishCheckpoint failed: %v", err)
}
// Schedule a checkpoint update immediately, if an updated is due.
t.Reset(max(time.Millisecond, time.Until(nextPub)))
return nil
}, trace.WithAttributes(otel.PeriodicKey.Bool(true))); err != nil {
t.Reset(pubInterval)
slog.ErrorContext(ctx, "publishCheckpoint failed", slog.Any("error", err))
}
}
}
// garbageCollectorJob is a long-running function which handles the removal of obsolete partial tiles
// and entry bundles.
// Blocks until ctx is done.
func (a *Appender) garbageCollectorJob(ctx context.Context, i time.Duration) {
t := time.NewTicker(i)
defer t.Stop()
// Entirely arbitrary number.
maxBundlesPerRun := uint(100)
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
if err := otel.TraceErr(ctx, "tessera.storage.gcp.garbageCollectJob", tracer, func(ctx context.Context, span trace.Span) error {
ctx, cancel := context.WithTimeout(ctx, defaultGCTimeout)
defer cancel() // Note: ok because we're in a func passed to TraceErr here!
// Figure out the size of the latest published checkpoint - we can't be removing partial tiles implied by
// that checkpoint just because we've done an integration and know about a larger (but as yet unpublished)
// checkpoint!
cp, err := a.logStore.getCheckpoint(ctx)
if err != nil {
return fmt.Errorf("failed to get published checkpoint: %v", err)
}
_, pubSize, _, err := parse.CheckpointUnsafe(cp)
if err != nil {
return fmt.Errorf("failed to parse published checkpoint: %v", err)
}
if err := a.sequencer.garbageCollect(ctx, pubSize, maxBundlesPerRun, a.logStore.objStore.deleteObjectsWithPrefix, a.logStore.entriesPath); err != nil {
return fmt.Errorf("garbageCollect failed: %v", err)
}
return nil
}, trace.WithAttributes(otel.PeriodicKey.Bool(true))); err != nil {
slog.WarnContext(ctx, "garbageCollectTask failed", slog.Any("error", err))
}
}
}
// init ensures that the storage represents a log in a valid state.
func (a *Appender) init(ctx context.Context) error {
if _, err := a.logStore.getCheckpoint(ctx); err != nil {
if errors.Is(err, gcs.ErrObjectNotExist) {
// No checkpoint exists, do a forced (possibly empty) integration to create one in a safe
// way (setting the checkpoint directly here would not be safe as it's outside the transactional
// framework which prevents the tree from rolling backwards or otherwise forking).
ctx, c := context.WithTimeout(ctx, defaultIntegrationTimeout)
defer c()
if _, err := a.sequencer.consumeEntries(ctx, DefaultIntegrationSizeLimit, a.integrateEntries, true); err != nil {
return fmt.Errorf("forced integrate: %v", err)
}
select {
case a.cpUpdated <- struct{}{}:
default:
}
return nil
}
return fmt.Errorf("failed to read checkpoint: %v", err)
}
return nil
}
func (a *Appender) updateCheckpoint(ctx context.Context, size uint64, root []byte) error {
return otel.TraceErr(ctx, "tessera.storage.gcp.updateCheckpoint", tracer, func(ctx context.Context, span trace.Span) error {
span.SetAttributes(treeSizeKey.Int64(otel.Clamp64(size)))
cpRaw, err := a.newCP(ctx, size, root)
if err != nil {
return fmt.Errorf("newCP: %v", err)
}
if err := a.logStore.setCheckpoint(ctx, cpRaw); err != nil {
return fmt.Errorf("writeCheckpoint: %v", err)
}
slog.DebugContext(ctx, "Created and stored latest checkpoint", slog.Uint64("size", size), slog.String("root", fmt.Sprintf("%x", root)))
return nil
})
}
// objStore describes a type which can store and retrieve objects.
type objStore interface {
getObject(ctx context.Context, obj string) ([]byte, *gcs.ReaderObjectAttrs, error)
setObject(ctx context.Context, obj string, data []byte, cond *gcs.Conditions, contType string, cacheCtl string) error
deleteObjectsWithPrefix(ctx context.Context, prefix string) error
}
// logResourceStore knows how to read and write entries which represent a tiles log inside an objStore.
type logResourceStore struct {
objStore objStore
entriesPath func(uint64, uint8) string
}
func (lrs *logResourceStore) setCheckpoint(ctx context.Context, cpRaw []byte) error {
return lrs.objStore.setObject(ctx, layout.CheckpointPath, cpRaw, nil, ckptContType, ckptCacheControl)
}
func (lrs *logResourceStore) getCheckpoint(ctx context.Context) ([]byte, error) {
r, attr, err := lrs.objStore.getObject(ctx, layout.CheckpointPath)
if err != nil {
return nil, err
}
checkpointAgeHistogram.Record(ctx, time.Since(attr.LastModified).Milliseconds())
return r, err
}
// setTile idempotently stores the provided tile at the location implied by the given level, index, and treeSize.
//
// The location to which the tile is written is defined by the tile layout spec.
func (s *logResourceStore) setTile(ctx context.Context, level, index uint64, partial uint8, data []byte) error {
start := time.Now()
tPath := layout.TilePath(level, index, partial)
err := s.objStore.setObject(ctx, tPath, data, &gcs.Conditions{DoesNotExist: true}, logContType, logCacheControl)
opsHistogram.Record(ctx, time.Since(start).Milliseconds(), metric.WithAttributes(opNameKey.String("writeTile")))
return err
}
// getTile retrieves the raw tile from the provided location.
//
// The location to which the tile is written is defined by the tile layout spec.
func (s *logResourceStore) getTile(ctx context.Context, level, index uint64, partial uint8) ([]byte, error) {
start := time.Now()
tPath := layout.TilePath(level, index, partial)
d, _, err := s.objStore.getObject(ctx, tPath)
opsHistogram.Record(ctx, time.Since(start).Milliseconds(), metric.WithAttributes(opNameKey.String("readTile")))
return d, err
}
// getTiles returns the tiles with the given tile-coords for the specified log size.
//
// Tiles are returned in the same order as they're requested, nils represent tiles which were not found.
func (s *logResourceStore) getTiles(ctx context.Context, tileIDs []storage.TileID, logSize uint64) ([]*api.HashTile, error) {
return otel.Trace(ctx, "tessera.storage.gcp.getTiles", tracer, func(ctx context.Context, span trace.Span) ([]*api.HashTile, error) {
r := make([]*api.HashTile, len(tileIDs))
errG := errgroup.Group{}
for i, id := range tileIDs {
i := i
id := id
errG.Go(func() error {
objName := layout.TilePath(id.Level, id.Index, layout.PartialTileSize(id.Level, id.Index, logSize))
data, _, err := s.objStore.getObject(ctx, objName)
if err != nil {
if errors.Is(err, gcs.ErrObjectNotExist) {
// Depending on context, this may be ok.
// We'll signal to higher levels that it wasn't found by returning a nil for this tile.
return nil
}
return err
}
t := &api.HashTile{}
if err := t.UnmarshalText(data); err != nil {
return fmt.Errorf("unmarshal(%q): %v", objName, err)
}
r[i] = t
return nil
})
}
if err := errG.Wait(); err != nil {
return nil, err
}
return r, nil
})
}
// getEntryBundle returns the serialised entry bundle at the location described by the given index and partial size.
// A partial size of zero implies a full tile.
//
// Returns a wrapped os.ErrNotExist if the bundle does not exist.
func (s *logResourceStore) getEntryBundle(ctx context.Context, bundleIndex uint64, p uint8) ([]byte, error) {
objName := s.entriesPath(bundleIndex, p)
data, _, err := s.objStore.getObject(ctx, objName)
if err != nil {
if errors.Is(err, gcs.ErrObjectNotExist) {
// Return the generic NotExist error so that higher levels can differentiate
// between this and other errors.
return nil, fmt.Errorf("%v: %w", objName, os.ErrNotExist)
}
return nil, err
}
return data, nil
}
// setEntryBundle idempotently stores the serialised entry bundle at the location implied by the bundleIndex and treeSize.
func (s *logResourceStore) setEntryBundle(ctx context.Context, bundleIndex uint64, p uint8, bundleRaw []byte) error {
objName := s.entriesPath(bundleIndex, p)
// Note that setObject does an idempotent interpretation of DoesNotExist - it only
// returns an error if the named object exists _and_ contains different data to what's
// passed in here.
if err := s.objStore.setObject(ctx, objName, bundleRaw, &gcs.Conditions{DoesNotExist: true}, logContType, logCacheControl); err != nil {
return fmt.Errorf("setObject(%q): %v", objName, err)
}
return nil
}
// integrateEntries appends the provided entries into the log starting at fromSeq.
//
// Returns the new root hash of the log with the entries added.
func (a *Appender) integrateEntries(ctx context.Context, fromSeq uint64, entries []storage.SequencedEntry) ([]byte, error) {
return otel.Trace(ctx, "tessera.storage.gcp.integrateEntries", tracer, func(ctx context.Context, span trace.Span) ([]byte, error) {
var newRoot []byte
errG := errgroup.Group{}
errG.Go(func() error {
if err := a.updateEntryBundles(ctx, fromSeq, entries); err != nil {
return fmt.Errorf("updateEntryBundles: %v", err)
}
return nil
})
errG.Go(func() error {
lh := make([][]byte, len(entries))
for i, e := range entries {
lh[i] = e.LeafHash
}
r, err := integrate(ctx, fromSeq, lh, a.logStore)
if err != nil {
return fmt.Errorf("integrate: %v", err)
}
newRoot = r
return nil
})
if err := errG.Wait(); err != nil {
return nil, err
}
return newRoot, nil
})
}
// integrate adds the provided leaf hashes to the merkle tree, starting at the provided location.
func integrate(ctx context.Context, fromSeq uint64, lh [][]byte, logStore *logResourceStore) ([]byte, error) {
return otel.Trace(ctx, "tessera.storage.gcp.integrate", tracer, func(ctx context.Context, span trace.Span) ([]byte, error) {
span.SetAttributes(fromSizeKey.Int64(otel.Clamp64(fromSeq)), numEntriesKey.Int(len(lh)))
errG := errgroup.Group{}
getTiles := func(ctx context.Context, tileIDs []storage.TileID, treeSize uint64) ([]*api.HashTile, error) {
n, err := logStore.getTiles(ctx, tileIDs, treeSize)
if err != nil {
return nil, fmt.Errorf("getTiles: %w", err)
}
return n, nil
}
newSize, newRoot, tiles, err := storage.Integrate(ctx, getTiles, fromSeq, lh)
if err != nil {
return nil, fmt.Errorf("storage.Integrate: %v", err)
}
for k, v := range tiles {
func(ctx context.Context, k storage.TileID, v *api.HashTile) {
errG.Go(func() error {
data, err := v.MarshalText()
if err != nil {
return err
}
return logStore.setTile(ctx, k.Level, k.Index, layout.PartialTileSize(k.Level, k.Index, newSize), data)
})
}(ctx, k, v)
}
if err := errG.Wait(); err != nil {
return nil, err
}
slog.DebugContext(ctx, "New tree integrated", slog.Uint64("size", newSize), slog.String("root", fmt.Sprintf("%x", newRoot)))
return newRoot, nil
})
}
// updateEntryBundles adds the entries being integrated into the entry bundles.
//
// The right-most bundle will be grown, if it's partial, and/or new bundles will be created as required.
func (a *Appender) updateEntryBundles(ctx context.Context, fromSeq uint64, entries []storage.SequencedEntry) error {
return otel.TraceErr(ctx, "tessera.storage.gcp.updateEntryBundles", tracer, func(ctx context.Context, span trace.Span) error {
if len(entries) == 0 {
return nil
}
numAdded := uint64(0)
bundleIndex, entriesInBundle := fromSeq/layout.EntryBundleWidth, fromSeq%layout.EntryBundleWidth
bundleWriter := &bytes.Buffer{}
if entriesInBundle > 0 {
// If the latest bundle is partial, we need to read the data it contains in for our newer, larger, bundle.
part, err := a.logStore.getEntryBundle(ctx, uint64(bundleIndex), uint8(entriesInBundle))
if err != nil {
return err
}
if _, err := bundleWriter.Write(part); err != nil {
return fmt.Errorf("bundleWriter: %v", err)
}
}
seqErr := errgroup.Group{}
// goSetEntryBundle is a function which uses seqErr to spin off a go-routine to write out an entry bundle.
// It's used in the for loop below.
goSetEntryBundle := func(ctx context.Context, bundleIndex uint64, p uint8, bundleRaw []byte) {
seqErr.Go(func() error {
if err := a.logStore.setEntryBundle(ctx, bundleIndex, p, bundleRaw); err != nil {
return err
}
return nil
})
}
// Add new entries to the bundle
for _, e := range entries {
if _, err := bundleWriter.Write(e.BundleData); err != nil {
return fmt.Errorf("bundleWriter.Write: %v", err)
}
entriesInBundle++
fromSeq++
numAdded++
if entriesInBundle == layout.EntryBundleWidth {
// This bundle is full, so we need to write it out...
slog.DebugContext(ctx, "In-memory bundle is full, attempting write to GCS", slog.Uint64("bundleIndex", bundleIndex))
goSetEntryBundle(ctx, bundleIndex, 0, bundleWriter.Bytes())
// ... and prepare the next entry bundle for any remaining entries in the batch
bundleIndex++
entriesInBundle = 0
// Don't use Reset/Truncate here - the backing []bytes is still being used by goSetEntryBundle above.
bundleWriter = &bytes.Buffer{}
slog.DebugContext(ctx, "Starting to fill in-memory bundle", slog.Uint64("bundleIndex", bundleIndex))
}
}
// If we have a partial bundle remaining once we've added all the entries from the batch,
// this needs writing out too.
if entriesInBundle > 0 {
slog.DebugContext(ctx, "Attempting to write in-memory partial bundle to GCS", slog.Uint64("bundleIndex", bundleIndex), slog.Uint64("entriesInBundle", entriesInBundle))
goSetEntryBundle(ctx, bundleIndex, uint8(entriesInBundle), bundleWriter.Bytes())
}
return seqErr.Wait()
})
}
// spannerCoordinator uses Cloud Spanner to provide
// a durable and thread/multi-process safe sequencer.
type spannerCoordinator struct {
dbPool *spanner.Client
// table returns the provided table name with the configured table prefix, if any, prepended.
table func(string) string
maxOutstanding uint64
// seqTableMaxBatchByteSize is the maximum byte size of a batch of entries to be written to the "V" field in the "Seq" table.
seqTableMaxBatchByteSize int
}
// newSpannerCoordinator returns a new spannerSequencer struct which uses the provided
// spanner resource name for its spanner connection.
func newSpannerCoordinator(ctx context.Context, dbPool *spanner.Client, table func(string) string, maxOutstanding uint64) (*spannerCoordinator, error) {
r := &spannerCoordinator{
dbPool: dbPool,
table: table,
maxOutstanding: maxOutstanding,
seqTableMaxBatchByteSize: defaultSeqTableMaxBatchByteSize,
}
if err := r.checkDataCompatibility(ctx); err != nil {
return nil, fmt.Errorf("schema is not compatible with this version of the Tessera library: %v", err)
}
return r, nil
}
// initDB ensures that the coordination DB is initialised correctly.
//
// The database schema consists of 5 tables:
// - SeqCoord
// This table only ever contains a single row which tracks the next available
// sequence number.
// - Seq
// This table holds sequenced "batches" of entries. The batches are keyed
// by the sequence number assigned to the first entry in the batch, and
// each subsequent entry in the batch takes the numerically next sequence number.
// - IntCoord
// This table coordinates integration of the batches of entries stored in
// Seq into the committed tree state.
// - PubCoord
// This table coordinates publication of checkpoints representing the
// committed tree state.
// - GCCoord
// This table coordinates garbage collection of unneeded partial tiles
// and entry bundles.
func initDB(ctx context.Context, spannerDB string, table func(string) string) error {
return createAndPrepareTables(ctx, spannerDB,
[]string{
fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (id INT64 NOT NULL, compatibilityVersion INT64 NOT NULL) PRIMARY KEY (id)", table("Tessera")),
fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (id INT64 NOT NULL, next INT64 NOT NULL,) PRIMARY KEY (id)", table("SeqCoord")),
fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (id INT64 NOT NULL, seq INT64 NOT NULL, v BYTES(MAX),) PRIMARY KEY (id, seq)", table("Seq")),
fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (id INT64 NOT NULL, seq INT64 NOT NULL, rootHash BYTES(32)) PRIMARY KEY (id)", table("IntCoord")),
fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (id INT64 NOT NULL, publishedAt TIMESTAMP NOT NULL, size INT64) PRIMARY KEY (id)", table("PubCoord")),
fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (id INT64 NOT NULL, fromSize INT64 NOT NULL) PRIMARY KEY (id)", table("GCCoord")),
},
[]string{
fmt.Sprintf("ALTER TABLE %s ADD COLUMN IF NOT EXISTS size INT64", table("PubCoord")),
},
[][]*spanner.Mutation{
{spanner.Insert(table("Tessera"), []string{"id", "compatibilityVersion"}, []any{0, SchemaCompatibilityVersion})},
{spanner.Insert(table("SeqCoord"), []string{"id", "next"}, []any{0, 0})},
{spanner.Insert(table("IntCoord"), []string{"id", "seq", "rootHash"}, []any{0, 0, rfc6962.DefaultHasher.EmptyRoot()})},
{spanner.Insert(table("PubCoord"), []string{"id", "publishedAt", "size"}, []any{0, time.Unix(0, 0), 0})},
{spanner.Insert(table("GCCoord"), []string{"id", "fromSize"}, []any{0, 0})},
})
}
// checkDataCompatibility compares the Tessera library SchemaCompatibilityVersion with the one stored in the
// database, and returns an error if they are not identical.
func (s *spannerCoordinator) checkDataCompatibility(ctx context.Context) error {
row, err := s.dbPool.Single().ReadRow(ctx, s.table("Tessera"), spanner.Key{0}, []string{"compatibilityVersion"})
if err != nil {
return fmt.Errorf("failed to read schema compatibilityVersion: %v", err)
}
var compat int64
if err := row.Columns(&compat); err != nil {
return fmt.Errorf("failed to scan schema compatibilityVersion: %v", err)
}
if compat != SchemaCompatibilityVersion {
return fmt.Errorf("schema compatibilityVersion (%d) != library compatibilityVersion (%d)", compat, SchemaCompatibilityVersion)
}
return nil
}
// assignEntries durably assigns each of the passed-in entries an index in the log.
//
// Entries are allocated contiguous indices, in the order in which they appear in the entries parameter.
// This is achieved by storing the passed-in entries in the Seq table in Spanner, keyed by the
// index assigned to the first entry in the batch.
func (s *spannerCoordinator) assignEntries(ctx context.Context, entries []*tessera.Entry) error {
return otel.TraceErr(ctx, "tessera.storage.gcp.assignEntries", tracer, func(ctx context.Context, span trace.Span) error {
start := time.Now()
defer func() {
opsHistogram.Record(ctx, time.Since(start).Milliseconds(), metric.WithAttributes(opNameKey.String("assignEntries")))
}()
span.SetAttributes(numEntriesKey.Int(len(entries)))
span.AddEvent("Reading IntCoord:seq")
// First grab the treeSize in a non-locking read-only fashion (we don't want to block/collide with integration).
// We'll use this value to determine whether we need to apply back-pressure.
var treeSize int64
if row, err := s.dbPool.Single().ReadRowWithOptions(ctx, s.table("IntCoord"), spanner.Key{0}, []string{"seq"}, &spanner.ReadOptions{RequestTag: "tessera.op=assignEntries.treeSize"}); err != nil {
return err
} else {
if err := row.Column(0, &treeSize); err != nil {
return fmt.Errorf("failed to read integration coordination info: %v", err)
}
}
span.SetAttributes(treeSizeKey.Int64(treeSize))
var next int64 // Unfortunately, Spanner doesn't support uint64 so we'll have to cast around a bit.
span.AddEvent("Starting ReadWriteTransaction")
_, err := s.dbPool.ReadWriteTransactionWithOptions(ctx, func(ctx context.Context, txn *spanner.ReadWriteTransaction) error {
span.AddEvent("Reading SeqCoord:next")
// First we need to grab the next available sequence number from the SeqCoord table.
row, err := txn.ReadRowWithOptions(ctx, s.table("SeqCoord"), spanner.Key{0}, []string{"next"}, &spanner.ReadOptions{LockHint: spannerpb.ReadRequest_LOCK_HINT_EXCLUSIVE})
if err != nil {
return fmt.Errorf("failed to read SeqCoord: %w", err)
}
if err := row.Columns(&next); err != nil {
return fmt.Errorf("failed to parse next column: %v", err)
}
// Check whether there are too many outstanding entries and we should apply
// back-pressure.
if outstanding := next - treeSize; outstanding > int64(s.maxOutstanding) {
return tessera.ErrPushbackIntegration
}
span.AddEvent("Compiling mutations")
var mutations []*spanner.Mutation
next := uint64(next) // Shadow next with a uint64 version of the same value to save on casts.
startFrom := next
var sequencedEntries []storage.SequencedEntry
currentBatchByteSize := 0
// Assign provisional sequence numbers to entries.
// We need to do this here in order to support serialisations which include the log position.
for i, e := range entries {
sequencedEntry := storage.SequencedEntry{
BundleData: e.MarshalBundleData(startFrom + uint64(i)),
LeafHash: e.LeafHash(),
}
// If adding this entry would make the batch too big, we need to flush the original batch.
if len(sequencedEntries) > 0 && currentBatchByteSize+len(sequencedEntry.BundleData) > s.seqTableMaxBatchByteSize {
// Gob-encode the batch of entries and add it to the mutation.
m, err := s.addSeqMutation(next, sequencedEntries)
if err != nil {
return fmt.Errorf("failed to addSeqMutation: %v", err)
}
mutations = append(mutations, m)
next += uint64(len(sequencedEntries))
// Reset our batch variables, and clear the batch slice now that it's been added to the
// mutation.
sequencedEntries = nil
currentBatchByteSize = 0
}
sequencedEntries = append(sequencedEntries, sequencedEntry)
currentBatchByteSize += len(sequencedEntry.BundleData)
}
// Insert the last batch of entries if there are any.
if len(sequencedEntries) > 0 {
m, err := s.addSeqMutation(next, sequencedEntries)
if err != nil {
return fmt.Errorf("failed to addSeqMutation: %v", err)
}
mutations = append(mutations, m)
next += uint64(len(sequencedEntries))
}
// and update the next-available sequence number row in SeqCoord.
mutations = append(mutations, spanner.Update(s.table("SeqCoord"), []string{"id", "next"}, []any{0, int64(next)}))
span.AddEvent("Writing mutations")
if err := txn.BufferWrite(mutations); err != nil {
return fmt.Errorf("failed to apply TX: %v", err)
}
return nil
}, spanner.TransactionOptions{TransactionTag: "tessera.op=assignEntries"})
span.AddEvent("Finished ReadWriteTransaction")
if err != nil {
return fmt.Errorf("failed to flush batch: %w", err)
}
return nil
}, trace.WithAttributes(otel.PeriodicKey.Bool(true)))
}
// addSeqMutation returns a mutation to the Seq table for the given sequence number and entries.
//
// The entries are gob-encoded and stored in the V column.
//
// The mutation is not written to the database; it is intended to be passed to a spanner.Transaction
// which will write it to the database.
func (s *spannerCoordinator) addSeqMutation(seq uint64, entries []storage.SequencedEntry) (*spanner.Mutation, error) {
b := &bytes.Buffer{}
if err := gob.NewEncoder(b).Encode(entries); err != nil {
return nil, fmt.Errorf("failed to serialise batch: %v", err)
}
// Insert our newly sequenced batch of entries into Seq.
return spanner.Insert(s.table("Seq"), []string{"id", "seq", "v"}, []any{0, int64(seq), b.Bytes()}), nil
}
// consumeEntries calls f with previously sequenced entries.
//
// Once f returns without error, the entries it was called with are considered to have been consumed and are
// removed from the Seq table.
//
// Returns true if some entries were consumed as a weak signal that there may be further entries waiting to be consumed.
func (s *spannerCoordinator) consumeEntries(ctx context.Context, limit uint64, f consumeFunc, forceUpdate bool) (bool, error) {
if limit > math.MaxInt {
limit = math.MaxInt
}
// Read this outside of the big write transaction below; we don't want to interfere with sequencing writes.
seqLimit, err := s.nextIndex(ctx)