Skip to content

Commit

Permalink
internal/services: move bulk load to experimental service
Browse files Browse the repository at this point in the history
  • Loading branch information
jakedt committed May 12, 2023
1 parent a087290 commit f61b23d
Show file tree
Hide file tree
Showing 10 changed files with 355 additions and 204 deletions.
28 changes: 14 additions & 14 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ require (
cloud.google.com/go/spanner v1.45.1
github.com/IBM/pgxpoolprometheus v1.1.1
github.com/Masterminds/squirrel v1.5.3
github.com/authzed/authzed-go v0.7.1-0.20230407200536-38340f010afc
github.com/authzed/authzed-go v0.8.1-0.20230511215435-5ca552307f34
github.com/authzed/grpcutil v0.0.0-20220104222419-f813f77722e5
github.com/aws/aws-sdk-go v1.44.110
github.com/benbjohnson/clock v1.3.0
Expand All @@ -18,13 +18,13 @@ require (
github.com/dustin/go-humanize v1.0.1
github.com/ecordell/optgen v0.0.9
github.com/emirpasic/gods v1.18.1
github.com/envoyproxy/protoc-gen-validate v0.9.1
github.com/envoyproxy/protoc-gen-validate v1.0.1
github.com/fatih/color v1.13.0
github.com/go-co-op/gocron v1.17.1
github.com/go-logr/zerologr v1.2.2
github.com/go-sql-driver/mysql v1.6.0
github.com/gogo/protobuf v1.3.2
github.com/golang/protobuf v1.5.2
github.com/golang/protobuf v1.5.3
github.com/golang/snappy v0.0.4
github.com/google/cel-go v0.12.5
github.com/google/go-cmp v0.5.9
Expand All @@ -49,7 +49,7 @@ require (
github.com/ory/dockertest/v3 v3.10.0
github.com/outcaste-io/ristretto v0.2.0
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58
github.com/planetscale/vtprotobuf v0.3.1-0.20220817155510-0ae748fd2007
github.com/planetscale/vtprotobuf v0.4.0
github.com/prometheus/client_golang v1.14.0
github.com/prometheus/client_model v0.3.0
github.com/prometheus/common v0.41.0
Expand All @@ -69,14 +69,14 @@ require (
go.opentelemetry.io/otel/trace v1.11.1
go.uber.org/goleak v1.2.0
golang.org/x/exp v0.0.0-20220823124025-807a23277127
golang.org/x/mod v0.9.0
golang.org/x/sync v0.1.0
golang.org/x/tools v0.7.0
golang.org/x/mod v0.10.0
golang.org/x/sync v0.2.0
golang.org/x/tools v0.9.1
google.golang.org/api v0.114.0
google.golang.org/genproto v0.0.0-20230320184635-7606e756e683
google.golang.org/grpc v1.54.0
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.2.0
google.golang.org/protobuf v1.29.1
google.golang.org/protobuf v1.30.0
gopkg.in/yaml.v2 v2.4.0
gopkg.in/yaml.v3 v3.0.1
mvdan.cc/gofumpt v0.4.0
Expand Down Expand Up @@ -111,7 +111,7 @@ require (
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/go-logr/logr v1.2.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/golang/glog v1.0.0 // indirect
github.com/golang/glog v1.1.1 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect
Expand All @@ -133,7 +133,7 @@ require (
github.com/klauspost/compress v1.15.10 // indirect
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
github.com/lyft/protoc-gen-star v0.6.1 // indirect
github.com/lyft/protoc-gen-star/v2 v2.0.3 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
Expand All @@ -153,7 +153,7 @@ require (
github.com/ryszard/goskiplist v0.0.0-20150312221310-2dfbae5fcf46 // indirect
github.com/shabbyrobe/gocovmerge v0.0.0-20190829150210-3e036491d500 // indirect
github.com/sirupsen/logrus v1.8.1 // indirect
github.com/spf13/afero v1.9.3 // indirect
github.com/spf13/afero v1.9.5 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/viper v1.14.0 // indirect
Expand All @@ -179,10 +179,10 @@ require (
go.uber.org/multierr v1.8.0 // indirect
golang.org/x/crypto v0.7.0 // indirect
golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 // indirect
golang.org/x/net v0.8.0 // indirect
golang.org/x/net v0.10.0 // indirect
golang.org/x/oauth2 v0.6.0 // indirect
golang.org/x/sys v0.7.0 // indirect
golang.org/x/text v0.8.0 // indirect
golang.org/x/sys v0.8.0 // indirect
golang.org/x/text v0.9.0 // indirect
golang.org/x/time v0.1.0 // indirect
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect
google.golang.org/appengine v1.6.7 // indirect
Expand Down
55 changes: 31 additions & 24 deletions go.sum

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions internal/services/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ func RegisterGrpcServices(
healthManager.RegisterReportedService(OverallServerHealthCheckKey)

v1.RegisterPermissionsServiceServer(srv, v1svc.NewPermissionsServer(dispatch, permSysConfig))
v1.RegisterExperimentalServiceServer(srv, v1svc.NewExperimentalServer())
healthManager.RegisterReportedService(v1.PermissionsService_ServiceDesc.ServiceName)

if watchServiceOption == WatchServiceEnabled {
Expand Down
208 changes: 208 additions & 0 deletions internal/services/v1/experimental.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
package v1

import (
"context"
"errors"
"io"

v1 "github.com/authzed/authzed-go/proto/authzed/api/v1"
grpcvalidate "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/validator"
"github.com/samber/lo"

"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/datastore"
dsoptions "github.com/authzed/spicedb/pkg/datastore/options"
core "github.com/authzed/spicedb/pkg/proto/core/v1"
dispatchv1 "github.com/authzed/spicedb/pkg/proto/dispatch/v1"
"github.com/authzed/spicedb/pkg/tuple"
)

// NewExperimentalServer creates a ExperimentalServiceServer instance.
func NewExperimentalServer(opts ...options.ExperimentalServerOptionsOption) v1.ExperimentalServiceServer {
config := options.NewExperimentalServerOptionsWithOptionsAndDefaults(opts...)

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.StreamReadTimeount),
),
},
}
}

type experimentalServer struct {
v1.UnimplementedExperimentalServiceServer
shared.WithServiceSpecificInterceptors
}

type bulkLoadAdapter struct {
stream v1.ExperimentalService_BulkLoadRelationshipsServer
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) BulkLoadRelationships(stream v1.ExperimentalService_BulkLoadRelationshipsServer) 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.BulkLoadRelationshipsResponse{
NumLoaded: numWritten,
})
}
11 changes: 0 additions & 11 deletions internal/services/v1/metadata_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,17 +154,6 @@ func TestAllMethodsReturnMetadata(t *testing.T) {
require.NoError(t, err)
}

return trailer
},
"BulkLoadRelationships": func(t *testing.T, client v1.PermissionsServiceClient) metadata.MD {
var trailer metadata.MD
writer, err := client.BulkLoadRelationships(ctx, grpc.Trailer(&trailer))
require.NoError(t, err)

resp, err := writer.CloseAndRecv()
require.NoError(t, err)
require.Zero(t, resp.NumLoaded)

return trailer
},
},
Expand Down
9 changes: 9 additions & 0 deletions internal/services/v1/options/options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package options

import "time"

//go:generate go run github.com/ecordell/optgen -output zz_generated.query_options.go . ExperimentalServerOptions

type ExperimentalServerOptions struct {
StreamReadTimeount time.Duration `debugmap:"visible" default:"600s"`
}
Loading

0 comments on commit f61b23d

Please sign in to comment.