github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/internal/services/v1/reflection.go (about) 1 package v1 2 3 import ( 4 "context" 5 6 datastoremw "github.com/authzed/spicedb/internal/middleware/datastore" 7 "github.com/authzed/spicedb/pkg/datastore" 8 "github.com/authzed/spicedb/pkg/diff" 9 "github.com/authzed/spicedb/pkg/middleware/consistency" 10 core "github.com/authzed/spicedb/pkg/proto/core/v1" 11 "github.com/authzed/spicedb/pkg/schemadsl/compiler" 12 "github.com/authzed/spicedb/pkg/schemadsl/input" 13 ) 14 15 func loadCurrentSchema(ctx context.Context) (*diff.DiffableSchema, datastore.Revision, error) { 16 ds := datastoremw.MustFromContext(ctx) 17 18 atRevision, _, err := consistency.RevisionFromContext(ctx) 19 if err != nil { 20 return nil, nil, err 21 } 22 23 reader := ds.SnapshotReader(atRevision) 24 25 namespacesAndRevs, err := reader.ListAllNamespaces(ctx) 26 if err != nil { 27 return nil, atRevision, err 28 } 29 30 caveatsAndRevs, err := reader.ListAllCaveats(ctx) 31 if err != nil { 32 return nil, atRevision, err 33 } 34 35 namespaces := make([]*core.NamespaceDefinition, 0, len(namespacesAndRevs)) 36 for _, namespaceAndRev := range namespacesAndRevs { 37 namespaces = append(namespaces, namespaceAndRev.Definition) 38 } 39 40 caveats := make([]*core.CaveatDefinition, 0, len(caveatsAndRevs)) 41 for _, caveatAndRev := range caveatsAndRevs { 42 caveats = append(caveats, caveatAndRev.Definition) 43 } 44 45 return &diff.DiffableSchema{ 46 ObjectDefinitions: namespaces, 47 CaveatDefinitions: caveats, 48 }, atRevision, nil 49 } 50 51 func schemaDiff(ctx context.Context, comparisonSchemaString string) (*diff.SchemaDiff, *diff.DiffableSchema, *diff.DiffableSchema, error) { 52 existingSchema, _, err := loadCurrentSchema(ctx) 53 if err != nil { 54 return nil, nil, nil, err 55 } 56 57 // Compile the comparison schema. 58 compiled, err := compiler.Compile(compiler.InputSchema{ 59 Source: input.Source("schema"), 60 SchemaString: comparisonSchemaString, 61 }, compiler.AllowUnprefixedObjectType()) 62 if err != nil { 63 return nil, nil, nil, err 64 } 65 66 comparisonSchema := diff.NewDiffableSchemaFromCompiledSchema(compiled) 67 68 diff, err := diff.DiffSchemas(*existingSchema, comparisonSchema) 69 if err != nil { 70 return nil, nil, nil, err 71 } 72 73 // Return the diff. 74 return diff, existingSchema, &comparisonSchema, nil 75 }