-
Notifications
You must be signed in to change notification settings - Fork 246
/
experimental.go
442 lines (379 loc) · 12.8 KB
/
experimental.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
package v1
import (
"context"
"errors"
"io"
"time"
v1 "github.com/authzed/authzed-go/proto/authzed/api/v1"
grpcvalidate "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/validator"
"github.com/rs/zerolog/log"
"github.com/samber/lo"
"golang.org/x/exp/slices"
"github.com/authzed/spicedb/internal/middleware"
datastoremw "github.com/authzed/spicedb/internal/middleware/datastore"
"github.com/authzed/spicedb/internal/middleware/handwrittenvalidation"
"github.com/authzed/spicedb/internal/middleware/streamtimeout"
"github.com/authzed/spicedb/internal/middleware/usagemetrics"
"github.com/authzed/spicedb/internal/namespace"
"github.com/authzed/spicedb/internal/relationships"
"github.com/authzed/spicedb/internal/services/shared"
options "github.com/authzed/spicedb/internal/services/v1/options"
"github.com/authzed/spicedb/pkg/cursor"
"github.com/authzed/spicedb/pkg/datastore"
dsoptions "github.com/authzed/spicedb/pkg/datastore/options"
"github.com/authzed/spicedb/pkg/middleware/consistency"
core "github.com/authzed/spicedb/pkg/proto/core/v1"
dispatchv1 "github.com/authzed/spicedb/pkg/proto/dispatch/v1"
implv1 "github.com/authzed/spicedb/pkg/proto/impl/v1"
"github.com/authzed/spicedb/pkg/tuple"
)
const (
defaultExportBatchSizeFallback = 1_000
maxExportBatchSizeFallback = 1_000
streamReadTimeoutFallbackSeconds = 600
)
// NewExperimentalServer creates a ExperimentalServiceServer instance.
func NewExperimentalServer(opts ...options.ExperimentalServerOptionsOption) v1.ExperimentalServiceServer {
config := options.NewExperimentalServerOptionsWithOptionsAndDefaults(opts...)
if config.DefaultExportBatchSize == 0 {
log.
Warn().
Uint32("specified", config.DefaultExportBatchSize).
Uint32("fallback", defaultExportBatchSizeFallback).
Msg("experimental server config specified invalid DefaultExportBatchSize, setting to fallback")
config.DefaultExportBatchSize = defaultExportBatchSizeFallback
}
if config.MaxExportBatchSize == 0 {
log.
Warn().
Uint32("specified", config.MaxExportBatchSize).
Uint32("fallback", maxExportBatchSizeFallback).
Msg("experimental server config specified invalid MaxExportBatchSize, setting to fallback")
config.MaxExportBatchSize = maxExportBatchSizeFallback
}
if config.StreamReadTimeout == 0 {
log.
Warn().
Stringer("specified", config.StreamReadTimeout).
Stringer("fallback", streamReadTimeoutFallbackSeconds*time.Second).
Msg("experimental server config specified invalid StreamReadTimeout, setting to fallback")
config.StreamReadTimeout = streamReadTimeoutFallbackSeconds * time.Second
}
return &experimentalServer{
WithServiceSpecificInterceptors: shared.WithServiceSpecificInterceptors{
Unary: middleware.ChainUnaryServer(
grpcvalidate.UnaryServerInterceptor(true),
handwrittenvalidation.UnaryServerInterceptor,
usagemetrics.UnaryServerInterceptor(),
),
Stream: middleware.ChainStreamServer(
grpcvalidate.StreamServerInterceptor(true),
handwrittenvalidation.StreamServerInterceptor,
usagemetrics.StreamServerInterceptor(),
streamtimeout.MustStreamServerInterceptor(config.StreamReadTimeout),
),
},
defaultBatchSize: uint64(config.DefaultExportBatchSize),
maxBatchSize: uint64(config.MaxExportBatchSize),
}
}
type experimentalServer struct {
v1.UnimplementedExperimentalServiceServer
shared.WithServiceSpecificInterceptors
defaultBatchSize uint64
maxBatchSize uint64
}
type bulkLoadAdapter struct {
stream v1.ExperimentalService_BulkImportRelationshipsServer
referencedNamespaceMap map[string]*namespace.TypeSystem
referencedCaveatMap map[string]*core.CaveatDefinition
current core.RelationTuple
caveat core.ContextualizedCaveat
awaitingNamespaces []string
awaitingCaveats []string
currentBatch []*v1.Relationship
numSent int
err error
}
func (a *bulkLoadAdapter) Next(_ context.Context) (*core.RelationTuple, error) {
for a.err == nil && a.numSent == len(a.currentBatch) {
// Load a new batch
batch, err := a.stream.Recv()
if err != nil {
a.err = err
if errors.Is(a.err, io.EOF) {
return nil, nil
}
return nil, a.err
}
a.currentBatch = batch.Relationships
a.numSent = 0
a.awaitingNamespaces, a.awaitingCaveats = extractBatchNewReferencedNamespacesAndCaveats(
a.currentBatch,
a.referencedNamespaceMap,
a.referencedCaveatMap,
)
}
if len(a.awaitingNamespaces) > 0 || len(a.awaitingCaveats) > 0 {
// Shut down the stream to give our caller a chance to fill in this information
return nil, nil
}
a.current.Caveat = &a.caveat
tuple.CopyRelationshipToRelationTuple[
*v1.ObjectReference,
*v1.SubjectReference,
*v1.ContextualizedCaveat,
](a.currentBatch[a.numSent], &a.current)
if err := relationships.ValidateOneRelationship(
a.referencedNamespaceMap,
a.referencedCaveatMap,
&a.current,
); err != nil {
return nil, err
}
a.numSent++
return &a.current, nil
}
func extractBatchNewReferencedNamespacesAndCaveats(
batch []*v1.Relationship,
existingNamespaces map[string]*namespace.TypeSystem,
existingCaveats map[string]*core.CaveatDefinition,
) ([]string, []string) {
newNamespaces := make(map[string]struct{})
newCaveats := make(map[string]struct{})
for _, rel := range batch {
if _, ok := existingNamespaces[rel.Resource.ObjectType]; !ok {
newNamespaces[rel.Resource.ObjectType] = struct{}{}
}
if _, ok := existingNamespaces[rel.Subject.Object.ObjectType]; !ok {
newNamespaces[rel.Subject.Object.ObjectType] = struct{}{}
}
if rel.OptionalCaveat != nil {
if _, ok := existingCaveats[rel.OptionalCaveat.CaveatName]; !ok {
newCaveats[rel.OptionalCaveat.CaveatName] = struct{}{}
}
}
}
return lo.Keys(newNamespaces), lo.Keys(newCaveats)
}
func (es *experimentalServer) BulkImportRelationships(stream v1.ExperimentalService_BulkImportRelationshipsServer) error {
ds := datastoremw.MustFromContext(stream.Context())
var numWritten uint64
if _, err := ds.ReadWriteTx(stream.Context(), func(rwt datastore.ReadWriteTransaction) error {
loadedNamespaces := make(map[string]*namespace.TypeSystem)
loadedCaveats := make(map[string]*core.CaveatDefinition)
adapter := &bulkLoadAdapter{
stream: stream,
referencedNamespaceMap: loadedNamespaces,
referencedCaveatMap: loadedCaveats,
current: core.RelationTuple{
ResourceAndRelation: &core.ObjectAndRelation{},
Subject: &core.ObjectAndRelation{},
},
caveat: core.ContextualizedCaveat{},
}
var streamWritten uint64
var err error
for ; adapter.err == nil && err == nil; streamWritten, err = rwt.BulkLoad(stream.Context(), adapter) {
numWritten += streamWritten
// The stream has terminated because we're awaiting namespace and caveat information
if len(adapter.awaitingNamespaces) > 0 {
nsDefs, err := rwt.LookupNamespacesWithNames(stream.Context(), adapter.awaitingNamespaces)
if err != nil {
return err
}
for _, nsDef := range nsDefs {
nts, err := namespace.NewNamespaceTypeSystem(nsDef.Definition, namespace.ResolverForDatastoreReader(rwt))
if err != nil {
return err
}
loadedNamespaces[nsDef.Definition.Name] = nts
}
adapter.awaitingNamespaces = nil
}
if len(adapter.awaitingCaveats) > 0 {
caveats, err := rwt.LookupCaveatsWithNames(stream.Context(), adapter.awaitingCaveats)
if err != nil {
return err
}
for _, caveat := range caveats {
loadedCaveats[caveat.Definition.Name] = caveat.Definition
}
adapter.awaitingCaveats = nil
}
}
numWritten += streamWritten
return err
}, dsoptions.WithDisableRetries(true)); err != nil {
return shared.RewriteError(stream.Context(), err)
}
usagemetrics.SetInContext(stream.Context(), &dispatchv1.ResponseMeta{
// One request for the whole load
DispatchCount: 1,
})
return stream.SendAndClose(&v1.BulkImportRelationshipsResponse{
NumLoaded: numWritten,
})
}
func (es *experimentalServer) BulkExportRelationships(
req *v1.BulkExportRelationshipsRequest,
resp v1.ExperimentalService_BulkExportRelationshipsServer,
) error {
ctx := resp.Context()
ds := datastoremw.MustFromContext(ctx)
var atRevision datastore.Revision
var cur dsoptions.Cursor
if req.OptionalCursor != nil {
var err error
atRevision, cur, err = decodeCursor(ds, req.OptionalCursor)
if err != nil {
return shared.RewriteError(ctx, err)
}
} else {
var err error
atRevision, _, err = consistency.RevisionFromContext(ctx)
if err != nil {
return shared.RewriteError(ctx, err)
}
}
reader := ds.SnapshotReader(atRevision)
namespaces, err := reader.ListAllNamespaces(ctx)
if err != nil {
return shared.RewriteError(ctx, err)
}
// Make sure the namespaces are always in a stable order
slices.SortFunc(namespaces, func(
lhs datastore.RevisionedDefinition[*core.NamespaceDefinition],
rhs datastore.RevisionedDefinition[*core.NamespaceDefinition],
) bool {
return lhs.Definition.Name < rhs.Definition.Name
})
// Skip the namespaces that are already fully returned
for cur != nil && len(namespaces) > 0 && namespaces[0].Definition.Name < cur.ResourceAndRelation.Namespace {
namespaces = namespaces[1:]
}
limit := es.defaultBatchSize
if req.OptionalLimit > 0 {
limit = uint64(req.OptionalLimit)
}
if limit > es.maxBatchSize {
limit = es.maxBatchSize
}
// Pre-allocate all of the relationships that we might need in order to
// make export easier and faster for the garbage collector.
relsArray := make([]v1.Relationship, limit)
objArray := make([]v1.ObjectReference, limit)
subArray := make([]v1.SubjectReference, limit)
subObjArray := make([]v1.ObjectReference, limit)
caveatArray := make([]v1.ContextualizedCaveat, limit)
for i := range relsArray {
relsArray[i].Resource = &objArray[i]
relsArray[i].Subject = &subArray[i]
relsArray[i].Subject.Object = &subObjArray[i]
}
emptyRels := make([]*v1.Relationship, limit)
for _, ns := range namespaces {
rels := emptyRels
// We want to keep iterating as long as we're sending full batches.
// To bootstrap this loop, we enter the first time with a full rels
// slice of dummy rels that were never sent.
for uint64(len(rels)) == limit {
// Lop off any rels we've already sent
rels = rels[:0]
tplFn := func(tpl *core.RelationTuple) {
offset := len(rels)
rels = append(rels, &relsArray[offset]) // nozero
tuple.CopyRelationTupleToRelationship(tpl, &relsArray[offset], &caveatArray[offset])
}
cur, err = queryForEach(
ctx,
reader,
datastore.RelationshipsFilter{ResourceType: ns.Definition.Name},
tplFn,
dsoptions.WithLimit(&limit),
dsoptions.WithAfter(cur),
dsoptions.WithSort(dsoptions.ByResource),
)
if err != nil {
return shared.RewriteError(ctx, err)
}
if len(rels) == 0 {
continue
}
encoded, err := cursor.Encode(&implv1.DecodedCursor{
VersionOneof: &implv1.DecodedCursor_V1{
V1: &implv1.V1Cursor{
Revision: atRevision.String(),
Sections: []string{
tuple.MustString(cur),
},
},
},
})
if err != nil {
return shared.RewriteError(ctx, err)
}
if err := resp.Send(&v1.BulkExportRelationshipsResponse{
AfterResultCursor: encoded,
Relationships: rels,
}); err != nil {
return shared.RewriteError(ctx, err)
}
}
// Datastore namespace order might not be exactly the same as go namespace order
// so we shouldn't assume cursors are valid across namespaces
cur = nil
}
return nil
}
func queryForEach(
ctx context.Context,
reader datastore.Reader,
filter datastore.RelationshipsFilter,
fn func(tpl *core.RelationTuple),
opts ...dsoptions.QueryOptionsOption,
) (*core.RelationTuple, error) {
iter, err := reader.QueryRelationships(ctx, filter, opts...)
if err != nil {
return nil, err
}
defer iter.Close()
var hadTuples bool
for tpl := iter.Next(); tpl != nil; tpl = iter.Next() {
fn(tpl)
hadTuples = true
}
if iter.Err() != nil {
return nil, err
}
var cur *core.RelationTuple
if hadTuples {
cur, err = iter.Cursor()
iter.Close()
if err != nil {
return nil, err
}
}
return cur, nil
}
func decodeCursor(ds datastore.Datastore, encoded *v1.Cursor) (datastore.Revision, *core.RelationTuple, error) {
decoded, err := cursor.Decode(encoded)
if err != nil {
return datastore.NoRevision, nil, err
}
if decoded.GetV1() == nil {
return datastore.NoRevision, nil, errors.New("malformed cursor: no V1 in OneOf")
}
if len(decoded.GetV1().Sections) != 1 {
return datastore.NoRevision, nil, errors.New("malformed cursor: wrong number of components")
}
atRevision, err := ds.RevisionFromString(decoded.GetV1().Revision)
if err != nil {
return datastore.NoRevision, nil, err
}
cur := tuple.Parse(decoded.GetV1().GetSections()[0])
if cur == nil {
return datastore.NoRevision, nil, errors.New("malformed cursor: invalid encoded relation tuple")
}
return atRevision, cur, nil
}