Documentation
¶
Overview ¶
Package resource provides a set of types and functions for working with resources.
The complete reference for the comment annotations, struct tags, and reserved query parameters recognized by this module lives in the module's README.md (rendered on pkg.go.dev and GitHub).
Index ¶
- Constants
- Variables
- func AfterCommit(txn ReadWriteTransaction, f func(ctx context.Context)) error
- func AfterCommitOnce(txn ReadWriteTransaction, key any, f func(ctx context.Context)) error
- func AsksWarning(r *http.Request) (bool, error)
- func AuthFrom(ctx context.Context) (auth string, ok bool)
- func AwaitFirstAdministrator(ctx context.Context, perms UserPermissions, domain accesstypes.Domain) error
- func BodyLimit(limit int64) func(http.Handler) http.Handler
- func CheckAPIVersion(check APIVersionCheck) func(http.Handler) http.Handler
- func CheckWarning(method string, warning *Warning) error
- func CloneRequest(r *http.Request) (*http.Request, error)
- func ClosedDomains(ctx context.Context, perms UserPermissions) ([]accesstypes.Domain, error)
- func CommitTimestamp(_ context.Context, _ ReadWriteTransaction) (any, error)
- func CommitTimestampPtr(_ context.Context, _ ReadWriteTransaction) (any, error)
- func DeclaredLength(sqltype string) int
- func DefaultFalse(_ context.Context, _ ReadWriteTransaction) (any, error)
- func DefaultTrue(_ context.Context, _ ReadWriteTransaction) (any, error)
- func DemonstrationDescriptions() map[string]string
- func DemonstrationKeys() []string
- func DirectoryName(directory signin.Directory, namers ...DirectoryNamer) string
- func DirectoryOnlyStateHandler(client Client, rules *TenantDirectoryRules, ...) http.HandlerFunc
- func DirectoryWords(directory signin.Directory, namers ...DirectoryNamer) string
- func DiscardUpload(ctx context.Context, store FileStore, keys []string, cause error) error
- func DryRunRolledBack(err error) bool
- func FeatureFlagHandler(a FeatureApp, collection *GeneratedCollection) http.HandlerFunc
- func FeatureFlagsDDL(dbType DBType) []string
- func FeatureFlagsHandler(a FeatureApp, collection *GeneratedCollection) http.HandlerFunc
- func FeatureFlagsQueryKeys() (order, keys []accesstypes.Tag)
- func FeatureGuard(features *FeatureSet, feature Feature) func(http.HandlerFunc) http.HandlerFunc
- func FeatureNotFound(w http.ResponseWriter)
- func FeaturesHandler(features *FeatureSet) http.HandlerFunc
- func FormatByteSize(n int64) string
- func HasValueLimit(sqltype string, kind ValueKind, slice bool) bool
- func IsDryRun(r *http.Request) (bool, error)
- func ListedInSomeTenant(ctx context.Context, perms UserPermissions, resources []accesstypes.Resource) ([]accesstypes.Resource, error)
- func MigrateFeatures(ctx context.Context, db Client, declared []FeatureDeclaration) error
- func MockIterSeq2[Resource Resourcer](err error, resource ...*Resource) iter.Seq2[*Row[Resource], error]
- func NewTenantDeclarationReader(table, keyColumn string, columns *TenantDeclarationColumns) signin.DeclarationReader[*spanner.ReadWriteTransaction]
- func NewTenantDirectoryReader(columns *TenantDeclarationColumns) signin.DirectoryReader[*spanner.ReadWriteTransaction]
- func NoDryRunOrWarning() func(http.Handler) http.Handler
- func OpenNullableSecretIn[Resource Resourcer](ctx context.Context, txn ReadWriteTransaction, key KeySet, ...) (*string, error)
- func OpenSecretIn[Resource Resourcer](ctx context.Context, txn ReadWriteTransaction, key KeySet, ...) (string, error)
- func Operations(r *http.Request, pattern string, opts ...Option) iter.Seq2[*Operation, error]
- func ParseByteSize(text string) (int64, error)
- func PatchSetDiff(opts ...cmp.Option) func(a, b PatchSetComparer) string
- func PermissionDigestHandler(userPermissions func(r *http.Request) UserPermissions, opts ...DigestOption) http.HandlerFunc
- func ProcessEvent(processName string) string
- func QuerySetDiff(opts ...cmp.Option) func(a, b QuerySetComparer) string
- func Refused(err error) (int, bool)
- func ReleaseHeader(release string) func(http.Handler) http.Handler
- func RequestEnvironment() accesstypes.Environment
- func RequireFileStores(client Client, names ...StoreName) error
- func RequireSecretKeys(client Client, fields ...string) error
- func ResponseStatus(method string, result any, declared ...int) (int, error)
- func RowKey(values ...any) string
- func ServeRenderedFile(w http.ResponseWriter, r *http.Request, content *Content, ...) error
- func ServeStoredFile(ctx context.Context, w http.ResponseWriter, r *http.Request, store FileStore, ...) error
- func SessionDirectory(ctx context.Context) (signin.Directory, error)
- func SetFeatureEnabled(ctx context.Context, db Client, name Feature, enabled bool, eventSource string) error
- func SetFeatureHandler(a FeatureApp, collection *GeneratedCollection, signals Signaler) http.HandlerFunc
- func SetLocalZone(zone *time.Location)
- func SignInRoles(manager signin.UserRoleManager) signin.UserRoleManager
- func SortRows[T any](rows []*T, order []SortField, dbType DBType) error
- func TenantKeyEquals(value any, domain accesstypes.Domain) (bool, error)
- func TenantsListed(ctx context.Context, perms UserPermissions, res accesstypes.Resource, ...) ([]accesstypes.Domain, error)
- func UserDomainsHandler(userPermissions func(r *http.Request) UserPermissions, ...) http.HandlerFunc
- func UserEvent(ctx context.Context) string
- func UserProcessEvent(ctx context.Context, processName string) string
- func ValidFeatureName(name string) bool
- func ValidateFeatureDeclarations(declared []FeatureDeclaration) error
- func WarningAsked(err error) bool
- func WithAuth(ctx context.Context, auth string) context.Context
- func WithCaller(ctx context.Context, caller *Caller) context.Context
- type APIVersionCheck
- type AcrossTenantsLists
- type Answer
- type Answerer
- type AttributeData
- type AttributeType
- type BindingHop
- type Bindings
- type BodyDecoder
- type BrowserApp
- type Buffer
- type Caller
- func (c *Caller) As(perms UserPermissions) *Caller
- func (c *Caller) Check(ctx context.Context, perm accesstypes.Permission, ...) (accesstypes.Decisions, error)
- func (c *Caller) ExecuteGate(ctx context.Context, method accesstypes.Resource, request any) (*ExecuteGate, error)
- func (c *Caller) IsZero() bool
- type CallerPassword
- type Client
- type ClientOption
- type CollectionBuilder
- func (b *CollectionBuilder) AddMethodResource(scope accesstypes.PermissionScope, permission accesstypes.Permission, ...) error
- func (b *CollectionBuilder) AddResource(scope accesstypes.PermissionScope, permission accesstypes.Permission, ...) error
- func (b *CollectionBuilder) AddResourceSet(scope accesstypes.PermissionScope, res accesstypes.Resource, set SetData) error
- func (b *CollectionBuilder) Data() CollectionData
- func (b *CollectionBuilder) GeneratedCollection() *GeneratedCollection
- func (b *CollectionBuilder) SetMethodFormerName(scope accesstypes.PermissionScope, method, former accesstypes.Resource)
- func (b *CollectionBuilder) SetMethodTarget(scope accesstypes.PermissionScope, method, target accesstypes.Resource)
- func (b *CollectionBuilder) SetMethodTransition(scope accesstypes.PermissionScope, method accesstypes.Resource, ...)
- func (b *CollectionBuilder) SetResourceBindings(scope accesstypes.PermissionScope, res accesstypes.Resource, ...)
- func (b *CollectionBuilder) SetResourceComputed(scope accesstypes.PermissionScope, res accesstypes.Resource)
- func (b *CollectionBuilder) SetResourceListsAcrossTenants(res accesstypes.Resource)
- func (b *CollectionBuilder) SetResourceParent(scope accesstypes.PermissionScope, member, parent accesstypes.Resource)
- func (b *CollectionBuilder) SetResourceQueryKeys(scope accesstypes.PermissionScope, res accesstypes.Resource, ...)
- func (b *CollectionBuilder) SetResourceRequiredTags(scope accesstypes.PermissionScope, res accesstypes.Resource, ...)
- type CollectionData
- type CollectionResource
- type Columns
- type ComputedQueryDecoder
- func MustNewComputedQueryDecoder[Resource Resourcer, Request any](dbType DBType, permissions ...accesstypes.Permission) *ComputedQueryDecoder[Resource, Request]
- func NewComputedQueryDecoder[Resource Resourcer, Request any](resSet *Set[Resource], dbType DBType) (*ComputedQueryDecoder[Resource, Request], error)
- func (d *ComputedQueryDecoder[Resource, Request]) Decode(request *http.Request, userPermissions UserPermissions, ...) (*QuerySet[Resource], error)
- func (d *ComputedQueryDecoder[Resource, Request]) WithCollection(collection *GeneratedCollection) *ComputedQueryDecoder[Resource, Request]
- func (d *ComputedQueryDecoder[Resource, Request]) WithCursorKey(key *CursorKey) *ComputedQueryDecoder[Resource, Request]
- func (d *ComputedQueryDecoder[Resource, Request]) WithFeatures(features *FeatureSet) *ComputedQueryDecoder[Resource, Request]
- func (d *ComputedQueryDecoder[Resource, Request]) WithPaging(paging Paging) *ComputedQueryDecoder[Resource, Request]
- func (d *ComputedQueryDecoder[Resource, Request]) WithSubjectFacts(source SubjectFactSource) *ComputedQueryDecoder[Resource, Request]
- type Condition
- type ConditionNode
- type Config
- type Content
- type CursorKey
- type DBType
- type DataChangeEvent
- type Decoder
- func (d *Decoder[Resource, Request]) DecideOperation(ctx context.Context, txn ReadWriteTransaction, oper *Operation, ...) (*Operation, error)
- func (d *Decoder[Resource, Request]) Decode(request *http.Request, userPermissions UserPermissions, ...) (*PatchSet[Resource], error)
- func (d *Decoder[Resource, Request]) DecodeOperation(oper *Operation, userPermissions UserPermissions, scope accesstypes.Scope) (*PatchSet[Resource], error)
- func (d *Decoder[Resource, Request]) DecodeOperationWithoutPermissions(oper *Operation) (*PatchSet[Resource], error)
- func (d *Decoder[Resource, Request]) DecodeWithoutPermissions(request *http.Request) (*PatchSet[Resource], error)
- func (d *Decoder[Resource, Request]) WithFeatures(features *FeatureSet) *Decoder[Resource, Request]
- func (d *Decoder[Resource, Request]) WithValidator(v ValidatorFunc) *Decoder[Resource, Request]
- type DecoderAccessor
- type DefaultsFunc
- type Demonstration
- type DiffElem
- type DigestOption
- type DirectoryNamer
- type DirectoryOnlyState
- type DirectoryOutsider
- type DirectoryOutsiders
- type DirectoryPeople
- type DomainBindingData
- type DomainNamer
- type DomainRoster
- type ExecuteGate
- func (g *ExecuteGate) Caller() *Caller
- func (g *ExecuteGate) Enforce(ctx context.Context, txn ReadWriteTransaction, target ExecuteTarget, ...) error
- func (g *ExecuteGate) EnforceProposed(ctx context.Context, facts SubjectFactSource, target ExecuteTarget, ...) error
- func (g *ExecuteGate) EnforceView(ctx context.Context, txn ReadWriteTransaction, target ExecuteTarget, ...) error
- func (g *ExecuteGate) Settled() (granted, settled bool)
- func (g *ExecuteGate) VerifyTenancy(ctx context.Context, txn ReadWriteTransaction, target ExecuteTarget, ...) error
- type ExecuteTarget
- type Executor
- type ExpressionNode
- type Feature
- type FeatureApp
- type FeatureDeclaration
- type FeatureFlag
- type FeatureGates
- type FeatureOption
- type FeatureSet
- type FeaturesResponse
- type FieldDefaultFunc
- type FieldTags
- type File
- type FileDecoder
- func MustNewComputedFileDecoder[Resource Resourcer, Request any](collection *GeneratedCollection, segment string) *FileDecoder[Resource, Request]
- func MustNewFileDecoder[Resource Resourcer, Request any](collection *GeneratedCollection, segment string) *FileDecoder[Resource, Request]
- func NewComputedFileDecoder[Resource Resourcer, Request any](collection *GeneratedCollection, segment string) (*FileDecoder[Resource, Request], error)
- func NewFileDecoder[Resource Resourcer, Request any](collection *GeneratedCollection, segment string) (*FileDecoder[Resource, Request], error)
- func (d *FileDecoder[Resource, Request]) Decode(request *http.Request, userPermissions UserPermissions, ...) (*QuerySet[Resource], error)
- func (d *FileDecoder[Resource, Request]) Segment() accesstypes.Tag
- func (d *FileDecoder[Resource, Request]) WithSubjectFacts(source SubjectFactSource) *FileDecoder[Resource, Request]
- type FileHolder
- type FileIn
- type FileKey
- type FileRoute
- type FileStore
- type Files
- type FilesIn
- type FilterFieldInfo
- type FilterLexer
- type FilterParser
- type FilterShape
- type FormerNames
- type GeneratedCollection
- func (g *GeneratedCollection) AttributeComparisonType(scope accesstypes.PermissionScope, res accesstypes.Resource, name string) (accesstypes.AttributeType, bool)
- func (g *GeneratedCollection) AttributeIsColumn(scope accesstypes.PermissionScope, res accesstypes.Resource, name string) bool
- func (g *GeneratedCollection) AttributeIsList(scope accesstypes.PermissionScope, res accesstypes.Resource, name string) bool
- func (g *GeneratedCollection) Bindings(scope accesstypes.PermissionScope, res accesstypes.Resource) (Bindings, bool)
- func (g *GeneratedCollection) ConcealingKeys(scope accesstypes.PermissionScope, res accesstypes.Resource) (order, keys []accesstypes.Tag)
- func (g *GeneratedCollection) Data() CollectionData
- func (g *GeneratedCollection) FieldMasking(scope accesstypes.PermissionScope, res accesstypes.Resource, ...) Masking
- func (g *GeneratedCollection) FormerName(scope accesstypes.PermissionScope, res accesstypes.Resource) (accesstypes.Resource, bool)
- func (g *GeneratedCollection) FormerTagName(scope accesstypes.PermissionScope, res accesstypes.Resource, ...) (accesstypes.Tag, bool)
- func (g *GeneratedCollection) HasPermission(scope accesstypes.PermissionScope, permission accesstypes.Permission, ...) bool
- func (g *GeneratedCollection) IsComputedResource(scope accesstypes.PermissionScope, res accesstypes.Resource) bool
- func (g *GeneratedCollection) IsResourceImmutable(scope accesstypes.PermissionScope, res accesstypes.Resource) bool
- func (g *GeneratedCollection) List() map[accesstypes.Permission][]accesstypes.Resource
- func (g *GeneratedCollection) ListedAcrossTenants() []accesstypes.Resource
- func (g *GeneratedCollection) ListsAcrossTenants(res accesstypes.Resource) bool
- func (g *GeneratedCollection) MembersOf(parent accesstypes.Resource) []accesstypes.Resource
- func (g *GeneratedCollection) MethodTarget(scope accesstypes.PermissionScope, method accesstypes.Resource) (accesstypes.Resource, bool)
- func (g *GeneratedCollection) MethodsTargeting(target accesstypes.Resource) []TargetedMethod
- func (g *GeneratedCollection) RequiredOnCreate(scope accesstypes.PermissionScope, res accesstypes.Resource) []accesstypes.Tag
- func (g *GeneratedCollection) ResourceExists(r accesstypes.Resource) bool
- func (g *GeneratedCollection) Resources() []accesstypes.Resource
- func (g *GeneratedCollection) Scope(resource accesstypes.Resource) accesstypes.PermissionScope
- func (g *GeneratedCollection) SubjectSet(name string) (SubjectAnchor, bool)
- func (g *GeneratedCollection) SubjectSetComparisonType(name string) (accesstypes.AttributeType, bool)
- func (g *GeneratedCollection) SubjectValue(name string) (SubjectAnchor, bool)
- func (g *GeneratedCollection) SubjectValueComparisonType(name string) (accesstypes.AttributeType, bool)
- func (g *GeneratedCollection) TagsRequiring(res accesstypes.Resource, perm accesstypes.Permission) []accesstypes.Tag
- func (g *GeneratedCollection) TransitionsOnto(target accesstypes.Resource) []TransitionMethod
- func (g *GeneratedCollection) TypescriptData() *TypescriptData
- func (g *GeneratedCollection) TypescriptDataExcluding(excluded ...accesstypes.Resource) *TypescriptData
- type GroupNode
- type Ident
- func (i Ident[T]) Equal(v ...T) QueryClause
- func (i Ident[T]) GreaterThan(v T) QueryClause
- func (i Ident[T]) GreaterThanEq(v T) QueryClause
- func (i Ident[T]) IsNotNull() QueryClause
- func (i Ident[T]) IsNull() QueryClause
- func (i Ident[T]) LessThan(v T) QueryClause
- func (i Ident[T]) LessThanEq(v T) QueryClause
- func (i Ident[T]) NotEqual(v ...T) QueryClause
- type Key
- type KeyPart
- type KeySet
- type LocatedFileStore
- type LogicalOpNode
- type LogicalOperator
- type ManualRegistration
- type Masking
- type Metadata
- type MockClient
- func (c *MockClient) Close()
- func (c *MockClient) DBType() DBType
- func (c *MockClient) ExecuteFunc(ctx context.Context, ...) error
- func (c *MockClient) FileStore(name StoreName) FileStore
- func (c *MockClient) PostgresReadOnlyTransaction() any
- func (c *MockClient) ReadOnlyMocks() []any
- func (c *MockClient) ReadOnlyTransaction() ReadOnlyTransactionCloser
- func (c *MockClient) SpannerReadOnlyTransaction() spxapi.Querier
- type MockReadWriteTransaction
- func (c *MockReadWriteTransaction) BufferMap(r PatchSetMetadata, p map[string]any) error
- func (c *MockReadWriteTransaction) BufferStruct(p PatchSetMetadata) error
- func (c *MockReadWriteTransaction) Committed(ctx context.Context)
- func (c *MockReadWriteTransaction) DBType() DBType
- func (c *MockReadWriteTransaction) DataChangeEventIndex(res accesstypes.Resource, rowID string) int
- func (c *MockReadWriteTransaction) PostgresReadOnlyTransaction() any
- func (c *MockReadWriteTransaction) Released() []ReleasedKey
- func (c *MockReadWriteTransaction) SpannerReadOnlyTransaction() spxapi.Querier
- func (c *MockReadWriteTransaction) TxnReadMocks() []any
- func (c *MockReadWriteTransaction) WithSecretKeys(keys *SecretKeys) *MockReadWriteTransaction
- type NamedStore
- type Operation
- type OperationType
- type Option
- type Outcome
- type Page
- func (p *Page[Resource]) Add(row *Row[Resource]) bool
- func (p *Page[Resource]) Count(ctx context.Context, txn ReadOnlyTransaction) error
- func (p *Page[Resource]) Reversed() bool
- func (p *Page[Resource]) RowFields(i int) []accesstypes.Field
- func (p *Page[Resource]) Rows() []*Resource
- func (p *Page[Resource]) WriteHeaders(w http.ResponseWriter, r *http.Request) error
- type PageBounds
- type Paging
- type PartialQueryClause
- type PatchSet
- func (p *PatchSet[Resource]) Apply(ctx context.Context, client Client, eventSource ...string) error
- func (p *PatchSet[Resource]) AsTouch() *PatchSet[Resource]
- func (p *PatchSet[Resource]) Buffer(ctx context.Context, txn ReadWriteTransaction, eventSource ...string) error
- func (p *PatchSet[Resource]) Data() map[accesstypes.Field]any
- func (p *PatchSet[Resource]) Diff(old any) (map[accesstypes.Field]DiffElem, error)
- func (p *PatchSet[Resource]) EnableUserPermissionEnforcement(rSet *Set[Resource], userPermissions UserPermissions, scope accesstypes.Scope, ...) *PatchSet[Resource]
- func (p *PatchSet[Resource]) Enforce(caller *Caller, rSet *Set[Resource], requiredPermission accesstypes.Permission) *PatchSet[Resource]
- func (p *PatchSet[Resource]) Fields() []accesstypes.Field
- func (p *PatchSet[Resource]) FromStruct(input any, skip ...string) error
- func (p *PatchSet[Resource]) Get(field accesstypes.Field) any
- func (p *PatchSet[Resource]) HasKey() bool
- func (p *PatchSet[Resource]) IsSet(field accesstypes.Field) bool
- func (p *PatchSet[Resource]) Key(field accesstypes.Field) any
- func (p *PatchSet[Resource]) Len() int
- func (p *PatchSet[Resource]) OrCreate(createSet *Set[Resource]) *PatchSet[Resource]
- func (p *PatchSet[Resource]) OrSkip() *PatchSet[Resource]
- func (p *PatchSet[Resource]) Outcome() Outcome
- func (p *PatchSet[Resource]) PatchType() PatchType
- func (p *PatchSet[Resource]) Permitted(ctx context.Context, txn ReadWriteTransaction) error
- func (p *PatchSet[Resource]) PrimaryKey() KeySet
- func (p *PatchSet[Resource]) RegisterDefaultCreateFunc(field accesstypes.Field, fn FieldDefaultFunc)
- func (p *PatchSet[Resource]) RegisterDefaultsCreateFunc(fn DefaultsFunc)
- func (p *PatchSet[Resource]) RegisterDefaultsUpdateFunc(fn DefaultsFunc)
- func (p *PatchSet[Resource]) RegisterOutputOnlyUpdateFunc(field accesstypes.Field, fn FieldDefaultFunc)
- func (p *PatchSet[Resource]) RegisterValidateCreateFunc(fn ValidateFunc)
- func (p *PatchSet[Resource]) RegisterValidateUpdateFunc(fn ValidateFunc)
- func (p *PatchSet[Resource]) Resolve(dbType DBType, keys *SecretKeys) (map[string]any, error)
- func (p *PatchSet[Resource]) Resource() accesstypes.Resource
- func (p *PatchSet[Resource]) Set(field accesstypes.Field, value any) *PatchSet[Resource]
- func (p *PatchSet[Resource]) SetKey(field accesstypes.Field, value any) *PatchSet[Resource]
- func (p *PatchSet[Resource]) SetPatchType(t PatchType) *PatchSet[Resource]
- func (p *PatchSet[Resource]) ToStruct() *Resource
- type PatchSetComparer
- type PatchSetMetadata
- type PatchType
- type PostgreSQLGenerator
- type PostgresClient
- func (c *PostgresClient) Close()
- func (c *PostgresClient) DBType() DBType
- func (c *PostgresClient) ExecuteFunc(_ context.Context, _ func(ctx context.Context, _ ReadWriteTransaction) error) error
- func (c *PostgresClient) FileStore(name StoreName) FileStore
- func (c *PostgresClient) PostgresReadOnlyTransaction() any
- func (c *PostgresClient) ReadOnlyTransaction() ReadOnlyTransactionCloser
- func (c *PostgresClient) SpannerReadOnlyTransaction() spxapi.Querier
- type PostgresReadOnlyTransaction
- type PostgresReadWriteTransaction
- func (c *PostgresReadWriteTransaction) BufferMap(_ PatchSetMetadata, _ map[string]any) error
- func (c *PostgresReadWriteTransaction) BufferStruct(_ PatchSetMetadata) error
- func (c *PostgresReadWriteTransaction) DBType() DBType
- func (c *PostgresReadWriteTransaction) DataChangeEventIndex(res accesstypes.Resource, rowID string) int
- func (c *PostgresReadWriteTransaction) List(_ context.Context, _ Resourcer, _ []any, _ *Statement) error
- func (c *PostgresReadWriteTransaction) PostgresReadOnlyTransaction() any
- func (c *PostgresReadWriteTransaction) Read(_ context.Context, _ Resourcer, _ any, _ *Statement) error
- func (c *PostgresReadWriteTransaction) SpannerReadOnlyTransaction() spxapi.Querier
- func (c *PostgresReadWriteTransaction) WithSecretKeys(keys *SecretKeys) *PostgresReadWriteTransaction
- type QueryClause
- type QueryDecoder
- func (d *QueryDecoder[Resource, Request]) Decode(request *http.Request, userPermissions UserPermissions, ...) (*QuerySet[Resource], error)
- func (d *QueryDecoder[Resource, Request]) DecodeAcrossTenants(request *http.Request, userPermissions UserPermissions) (*QuerySet[Resource], error)
- func (d *QueryDecoder[Resource, Request]) DecodeWithoutPermissions(request *http.Request) (*QuerySet[Resource], error)
- func (d *QueryDecoder[Resource, Request]) WithCursorKey(key *CursorKey) *QueryDecoder[Resource, Request]
- func (d *QueryDecoder[Resource, Request]) WithFeatures(features *FeatureSet) *QueryDecoder[Resource, Request]
- func (d *QueryDecoder[Resource, Request]) WithPaging(paging Paging) *QueryDecoder[Resource, Request]
- type QueryParam
- type QuerySet
- func (q *QuerySet[Resource]) AddField(field accesstypes.Field) *QuerySet[Resource]
- func (q *QuerySet[Resource]) Admit(row *Resource) (fields []accesstypes.Field, shown bool, err error)
- func (q *QuerySet[Resource]) BatchList(ctx context.Context, client Client, size int) iter.Seq[iter.Seq2[*Row[Resource], error]]
- func (q *QuerySet[Resource]) Caller() *Caller
- func (q *QuerySet[Resource]) Collect(rows iter.Seq2[*Resource, error]) (*Page[Resource], error)
- func (q *QuerySet[Resource]) Count(ctx context.Context, txn ReadOnlyTransaction) (int64, error)
- func (q *QuerySet[Resource]) EnableUserPermissionEnforcement(rSet *Set[Resource], userPermissions UserPermissions, scope accesstypes.Scope, ...) *QuerySet[Resource]
- func (q *QuerySet[Resource]) Enforce(caller *Caller, rSet *Set[Resource], requiredPermission accesstypes.Permission) *QuerySet[Resource]
- func (q *QuerySet[Resource]) Fields() []accesstypes.Field
- func (q *QuerySet[Resource]) Filter() *FilterShape
- func (q *QuerySet[Resource]) FilterAst(dbType DBType) (ExpressionNode, error)
- func (q *QuerySet[Resource]) JudgesRows() bool
- func (q *QuerySet[Resource]) Key(field accesstypes.Field) any
- func (q *QuerySet[Resource]) KeySet() KeySet
- func (q *QuerySet[Resource]) Len() int
- func (q *QuerySet[Resource]) List(ctx context.Context, txn ReadOnlyTransaction) iter.Seq2[*Row[Resource], error]
- func (q *QuerySet[Resource]) Order() []SortField
- func (q *QuerySet[Resource]) Page() *Page[Resource]
- func (q *QuerySet[Resource]) Permitted(ctx context.Context) (bool, error)
- func (q *QuerySet[Resource]) Read(ctx context.Context, txn ReadOnlyTransaction) (*Row[Resource], error)
- func (q *QuerySet[Resource]) RequestCapabilities(perms ...accesstypes.Permission)
- func (q *QuerySet[Resource]) RequiredPermission() accesstypes.Permission
- func (q *QuerySet[Resource]) Resource() accesstypes.Resource
- func (q *QuerySet[Resource]) ReturnAccessibleFields(b bool) *QuerySet[Resource]
- func (q *QuerySet[Resource]) Scope() accesstypes.Scope
- func (q *QuerySet[Resource]) SetFilterAst(ast ExpressionNode)
- func (q *QuerySet[Resource]) SetFilterParser(parser func(DBType) (ExpressionNode, error))
- func (q *QuerySet[Resource]) SetKey(field accesstypes.Field, value any)
- func (q *QuerySet[Resource]) SetLimit(limit *uint64)
- func (q *QuerySet[Resource]) SetSortFields(sortFields []SortField)
- func (q *QuerySet[Resource]) SetWhereClause(qc QueryClause)
- func (q *QuerySet[Resource]) TakePage() (PageBounds, bool)
- func (q *QuerySet[Resource]) TakeSort() []SortField
- func (q *QuerySet[Resource]) TenantsListed(ctx context.Context) (set, narrowed []accesstypes.Domain, err error)
- func (q *QuerySet[Resource]) User() accesstypes.User
- type QuerySetComparer
- type RPCDecoder
- func (s *RPCDecoder[Request]) Decode(request *http.Request, scope accesstypes.Scope) (*Request, error)
- func (s *RPCDecoder[Request]) DecodeCaller(request *http.Request, scope accesstypes.Scope) (*Request, *Caller, error)
- func (s *RPCDecoder[Request]) WithCollection(collection *GeneratedCollection) *RPCDecoder[Request]
- func (s *RPCDecoder[Request]) WithValidator(v ValidatorFunc) *RPCDecoder[Request]
- type ReadOnlyTransaction
- type ReadOnlyTransactionCloser
- type ReadWriteTransaction
- type Reader
- type ReleaseFile
- type ReleaseOutlet
- type ReleaseProgram
- type ReleasedKey
- type RequestFieldMapper
- func (f *RequestFieldMapper) Fields() []accesstypes.Field
- func (f *RequestFieldMapper) FormerNames() map[string]string
- func (f *RequestFieldMapper) JSONNames() map[accesstypes.Field]string
- func (f *RequestFieldMapper) Len() int
- func (f *RequestFieldMapper) StructFieldName(jsonTag string) (accesstypes.Field, bool)
- type Resourcer
- type RolePermissions
- type Row
- type RowChange
- type SQLDialect
- type ScheduledRoute
- type SearchAnchor
- type SearchBranch
- type SearchColumn
- type SearchRole
- type SearchSpec
- type Secret
- func (s *Secret) DecodeSpanner(val any) error
- func (s Secret) EncodeSpanner() (any, error)
- func (s Secret) Equal(other Secret) bool
- func (Secret) Format(f fmt.State, _ rune)
- func (Secret) GoString() string
- func (s Secret) IsZero() bool
- func (s Secret) KeyVersion() int
- func (Secret) LogValue() slog.Value
- func (Secret) MarshalJSON() ([]byte, error)
- func (Secret) MarshalText() ([]byte, error)
- func (s *Secret) Scan(src any) error
- func (Secret) String() string
- func (*Secret) UnmarshalJSON([]byte) error
- func (s Secret) Value() (driver.Value, error)
- type SecretFieldRetirement
- type SecretHolder
- type SecretKeys
- type SecretRetirement
- type SessionUserChecker
- type Set
- func (r *Set[Resource]) BaseResource() accesstypes.Resource
- func (r *Set[Resource]) ImmutableFields() map[accesstypes.Tag]struct{}
- func (r *Set[Resource]) PermissionRequired(fieldName accesstypes.Field, perm accesstypes.Permission) bool
- func (r *Set[Resource]) Permissions() []accesstypes.Permission
- func (r *Set[Resource]) Positional(fieldName accesstypes.Field) bool
- func (r *Set[Resource]) Resource(fieldName accesstypes.Field) accesstypes.Resource
- func (r *Set[Resource]) ResourceMetadata() *Metadata[Resource]
- func (r *Set[Resource]) TagPermissions() accesstypes.TagPermissions
- type SetCache
- type SetData
- type SetFeatureRequest
- type SetFeatureResult
- type SignalKind
- type SignalSubscriber
- type Signaler
- type SortDirection
- type SortField
- type SpannerClient
- func (c *SpannerClient) DBType() DBType
- func (c *SpannerClient) ExecuteFunc(ctx context.Context, ...) error
- func (c *SpannerClient) FileStore(name StoreName) FileStore
- func (c *SpannerClient) PostgresReadOnlyTransaction() any
- func (c *SpannerClient) ReadOnlyTransaction() ReadOnlyTransactionCloser
- func (c *SpannerClient) SpannerReadOnlyTransaction() spxapi.Querier
- type SpannerGenerator
- type SpannerReadOnlyTransaction
- type SpannerReadWriteTransaction
- func (c *SpannerReadWriteTransaction) BufferMap(r PatchSetMetadata, patch map[string]any) error
- func (c *SpannerReadWriteTransaction) BufferStruct(patch PatchSetMetadata) error
- func (c *SpannerReadWriteTransaction) Committed(ctx context.Context)
- func (c *SpannerReadWriteTransaction) DBType() DBType
- func (c *SpannerReadWriteTransaction) DataChangeEventIndex(res accesstypes.Resource, rowID string) int
- func (c *SpannerReadWriteTransaction) PostgresReadOnlyTransaction() any
- func (c *SpannerReadWriteTransaction) Released() []ReleasedKey
- func (c *SpannerReadWriteTransaction) SpannerReadOnlyTransaction() spxapi.Querier
- func (c *SpannerReadWriteTransaction) WithSecretKeys(keys *SecretKeys) *SpannerReadWriteTransaction
- type Statement
- type Store
- type StoreName
- type StoredFile
- type SubjectAnchor
- type SubjectBindingData
- type SubjectColumnData
- type SubjectFactSource
- type SubjectWhereData
- type SubjectWhoData
- type Surface
- type SurfaceKind
- type TagData
- type TargetedMethod
- type TargetedRPCDecoder
- type TenantDeclarationColumns
- type TenantDeclarations
- type TenantDirectory
- type TenantDirectoryRules
- func (r *TenantDirectoryRules) Directory(ctx context.Context, txn ReadWriteTransaction, tenant accesstypes.Domain) (*TenantDirectory, error)
- func (r *TenantDirectoryRules) DirectoryOnly(ctx context.Context, txn ReadWriteTransaction, tenant accesstypes.Domain, ...) error
- func (r *TenantDirectoryRules) DirectoryOnlyWarning(ctx context.Context, txn ReadWriteTransaction, tenant accesstypes.Domain, ...) (*Warning, error)
- func (r *TenantDirectoryRules) FromSession(ctx context.Context, txn ReadWriteTransaction, tenant accesstypes.Domain) (signin.Directory, error)
- func (r *TenantDirectoryRules) NamedBy(namers ...DirectoryNamer) *TenantDirectoryRules
- func (r *TenantDirectoryRules) OpenToDirectoryWarning(directory *TenantDirectory, role accesstypes.Role) *Warning
- func (r *TenantDirectoryRules) PasswordsBy(readers ...CallerPassword) *TenantDirectoryRules
- func (r *TenantDirectoryRules) Remove(ctx context.Context, txn ReadWriteTransaction, tenant accesstypes.Domain) error
- func (r *TenantDirectoryRules) Set(ctx context.Context, txn ReadWriteTransaction, tenant accesstypes.Domain, ...) error
- func (r *TenantDirectoryRules) State(ctx context.Context, txn ReadWriteTransaction, tenant accesstypes.Domain) (*DirectoryOnlyState, error)
- type TenantRoster
- func (r *TenantRoster) Add(domain accesstypes.Domain)
- func (r *TenantRoster) Declarations(_ context.Context, domain accesstypes.Domain) (*signin.TenantDeclaration, error)
- func (r *TenantRoster) Domains(context.Context) ([]accesstypes.Domain, error)
- func (r *TenantRoster) Has(domain accesstypes.Domain) bool
- func (r *TenantRoster) Name(domain accesstypes.Domain) string
- func (r *TenantRoster) Named(name string) (accesstypes.Domain, error)
- func (r *TenantRoster) Reload(ctx context.Context) error
- func (r *TenantRoster) Remove(domain accesstypes.Domain)
- func (r *TenantRoster) Start(ctx context.Context) error
- type TenantRosterOption
- type TenantSignals
- type TextIdent
- type Token
- type TokenType
- type TouchedRows
- type TransitionData
- type TransitionMethod
- type TypescriptData
- type UnknownSecretVersionError
- type Upload
- type UserDomain
- type UserDomainsOption
- type UserPermissionChecker
- type UserPermissions
- func Masked(perms UserPermissions, mask accesstypes.PermissionMask) UserPermissions
- func RolePrincipalPermissions(role RolePermissions, actor accesstypes.User) UserPermissions
- func SessionPermissions[U SessionUserChecker, R RolePermissions](ctx context.Context, forUser func(accesstypes.User) U, ...) UserPermissions
- type ValidateFunc
- type ValidatorFunc
- type ValueKind
- type Warning
Examples ¶
Constants ¶
const ( AttributeTypeString = accesstypes.AttributeTypeString AttributeTypeNumber = accesstypes.AttributeTypeNumber AttributeTypeBool = accesstypes.AttributeTypeBool AttributeTypeTimestamp = accesstypes.AttributeTypeTimestamp AttributeTypeDate = accesstypes.AttributeTypeDate )
The vocabulary's values, re-exported for generated code and callers already importing resource.
const ( // FeatureFlagsResource is the flags' resource: the FeatureFlags table, served as a // read-only resource (List, Read) on every session-serving outlet. FeatureFlagsResource accesstypes.Resource = "FeatureFlags" // FeatureFlagChangesTable is the audit table every flip writes a row into, in the // transaction that flips the flag. FeatureFlagChangesTable = "FeatureFlagChanges" // SetFeatureMethod is the RPC method that flips a flag, gated by Execute. SetFeatureMethod accesstypes.Resource = "SetFeature" // FeaturesRoute is the route every outlet serves the enabled flags on, to anyone // signed in: GET <prefix>/features answers {"enabled": [...]}. FeaturesRoute = "features" // FeatureFlagsRoute is the FeatureFlags resource's route segment under a session // outlet's prefix; the read route appends /{featureFlagName}. FeatureFlagsRoute = "feature-flags" // SetFeatureRoute is the SetFeature method's route segment under a session outlet's // prefix, named by the RPC route rule (the method name in kebab case). SetFeatureRoute = "set-feature" // FeatureFlagNameParam is the read route's parameter, named as every single-key read // route's is: the resource and its key field. FeatureFlagNameParam httpio.ParamType = "featureFlagName" )
The names the generated code and the client library mirror.
const ( // FeatureBackstop is how often a FeatureSet rereads the table whether or not a // signal arrived, so an instance that missed a signal is at most this far behind. FeatureBackstop = 5 * time.Minute // FeatureSignalTimeout bounds a flip's signal: past it the failure is logged and // the request answers, since the other instances reload at their backstop. FeatureSignalTimeout = 2 * time.Second // FeatureNameMaxLength is the longest name the table holds. FeatureNameMaxLength = 64 )
The numbers.
const ( LinkHeader = "Link" TotalCountHeader = "Total-Count" )
Response headers a list carries. Link (RFC 8288) positions the walk with a complete URL per relation that exists; Total-Count answers count=true on a first page, the whole list (limit=all, or a key-less list, which is only ever whole) included. Every paged request carries an order (QueryDecoder.requireOrder), so every page has its Link relations or is the whole list.
const ( RequestLogAlways = "always" RequestLogOnEvent = "onEvent" RequestLogSampled = "sampled" RequestLogNever = "never" )
The request log words, as the release file and the annotations spell them: the entry is written for every request, when a line attached or the request failed, as on event plus a fraction of the quiet requests, or never.
const ( TracesFollowFrontEnd = "followFrontEnd" TracesCapped = "capped" TracesOff = "off" )
The trace settings, as the release file and the annotations spell them: a surface's spans follow the front end, are capped at a rate, or are off.
const ( // FileRouteUpload is an @upload method's route. FileRouteUpload = "upload" // FileRouteStored is a stored file's read route, a @file column's. FileRouteStored = "file" )
The kinds of file route.
const ( // UploadRequestPart names the JSON part, which comes first. UploadRequestPart = "request" // UploadFilePart names each file part. UploadFilePart = "file" )
The multipart part names an upload request carries.
const APIVersionHeader = "X-Api-Version"
APIVersionHeader carries a browser application's release on every request it sends, and the server's release on a refusal: a request the server will not answer is refused with 412 and this header naming the release the server was built from, so the application can pick up the current build.
const ( // CapabilitiesProperty is the reserved per-row JSON property the generated // handlers attach capability answers under. Generation rejects resource // columns that would collide with it. CapabilitiesProperty = "zzCapabilities" )
const DefaultPageSize uint64 = 50
DefaultPageSize is the generator-wide page size a resource takes when it declares none.
const DirectoryOnlyRoute = "directory-only"
DirectoryOnlyRoute is the route of the read of a tenant's directory-only switch as it stands (DirectoryOnlyState), under the tenant's own route: GET <prefix>/<tenants>/{tenant}/directory-only. The generated router registers it beside the two methods that turn the switch (Make<Record>DirectoryOnly and End<Record>DirectoryOnly) on every outlet that serves sessions and the tenant record, for a record that declares the switch.
const DirectoryOnlyWord = "close"
DirectoryOnlyWord is the word a person types before a tenant is made directory only (the warning of Make<Record>DirectoryOnly): the tenant is closed to every sign-in but one through its directory. A warning's word is one lowercase word, which a directory's name is not, so the word is the same for every tenant.
const DryRunHeader = "X-Dry-Run"
DryRunHeader asks a transaction-form RPC method to run its whole frame — decode, the entry check, the target's location and state checks, the body with every write it arms — and then roll the transaction back instead of committing. Every refusal answers exactly as the real call would; a call that would have succeeded answers 200 with no body, since a result could name rows that never came to be. A client-form method refuses the header: effects outside a transaction cannot be previewed. The header takes the value true or is left off the request, and a frame refuses any other value (400) without running the call. A route whose frame does not read the header refuses a request that carries it (NoDryRunOrWarning): no call runs for real under a header that asked it be held back.
const ListAcrossTenants accesstypes.Permission = "ListAcrossTenants"
ListAcrossTenants is the permission the global permission digest answers for a resource declared for listing across tenants (@listAcrossTenants): granted while the person may list the resource in at least one tenant the session reaches. It is the digest's own entry and no grant's, so no role names it. A page that lists the resource across tenants is shown, and its route opened, to whoever the digest answers it for.
const OpenToDirectoryWord = "open"
OpenToDirectoryWord is the word a person types before a tenant is opened to its directory's people (the warning of Open<Record>ToDirectory).
const ReleaseFileName = "zz_gen_release.json"
ReleaseFileName is the generated release file's name. The generator writes it beside the generated router (zz_gen_router.go) in the router package's directory whenever a router is generated, and the stale sweep removes it when the router goes. It names every outlet the generator knows and, for each session outlet, the oldest release of the browser application the outlet still answers (OldestAnswered in the generator program), so a deploy reads from the checkout, never from a binary, whether a release needs a maintenance window: a release whose outlet answers only the server's own does. It also lists the scheduled routes (@schedule) with their schedules, which the application's stack reads to create a Cloud Scheduler job for each, and the programs each machine outlet ships (ShipsProgram), which the version build compiles for their platforms and copies into the image.
const ( // SecretOverhead is how many bytes sealing adds to a value: the version, the random // number and the check. A secret's column is BYTES(n) with n at least the longest // value it takes plus this, and the patch decoder sizes a value against the column // less this. SecretOverhead = secretVersionSize + secretNonceSize + chacha20poly1305.Overhead )
The layout of a stored secret.
const StateAttribute = "state"
StateAttribute is the uniform attribute name the generator synthesizes on every stateful resource and workflow member (@state / @stateRoot): one condition text — and the capability envelope's transition-membership boolean — reads identically across a workflow through this name.
const TenantBackstop = 5 * time.Minute
TenantBackstop is how often a TenantRoster rereads its table whether or not a signal arrived: the correctness guard behind the push, so an instance that missed a signal is at most this far behind.
const TenantProperty = "zzTenant"
TenantProperty is the reserved per-row JSON property the generated handlers of a list across tenants name each row's tenant under. Generation rejects resource columns that would collide with it.
const ThisRelease = "this release"
ThisRelease names the server's own release as an outlet's oldest answered: only an application built from the same release is answered. A generator program writes it for a release that changes the API inside a maintenance window.
const TimeZoneHeader = "Time-Zone"
TimeZoneHeader names the request header that carries the person's time zone, an IANA name such as America/New_York, which the browser knows and the resource client sends on every request. A filter value written with no zone of its own, 2026-12-15 or 2026-12-15T09:30, is read in it; a request without the header reads such a value in the zone the column's date search fact declares, and in UTC where none does.
const ( // VersionParam is the live pages' version parameter: a client that holds a live // row or list appends it so the browser's cache keys the answer by the change it // last saw (the change document's timestamp, or a seed minted at login before any // change arrived). The decoders accept and skip it, and a list or read response // to a request carrying it is the one response that carries a Cache-Control // header (resource/live). It is exported because the live package names it to // the client library. VersionParam = "_v" )
Reserved query-string parameter names consumed by QueryDecoder; they can never be used as filterable field names. Documented in README.md alongside the struct tags — register new parameters in reservedQueryParams below.
const WarningHeader = "X-Warning"
WarningHeader asks a method that declares a warning (@warning) what the call would do, in place of doing it: the generated frame decodes the request and checks the caller exactly as the call itself is checked, locates the target row where the method names one, calls the method's Warning in place of its Execute, and rolls the transaction back. The answer is the Warning, 200. Every refusal answers as the call's own would, so a caller who may not run the method reads no warning of it. A method that declares no warning refuses the header (400): a request that asks for a warning never runs the call. The header takes the value true or is left off the request, and a frame refuses any other value (400) without running the call. A route whose frame does not read the header refuses a request that carries it (NoDryRunOrWarning).
Variables ¶
var Demonstrations = []Demonstration{}/* 306 elements not displayed */
Demonstrations is the registry: every capability a demonstration application is expected to prove, seeded from the Lodestar design plan's coverage matrix.
var ErrDryRun = errors.New("dry run: the transaction rolls back by design")
ErrDryRun is the sentinel a generated frame returns from its transaction function on a dry run: the transaction rolls back and nothing retries. It never reaches the wire.
var ErrFileNotFound = errors.New("file not found")
ErrFileNotFound is what a FileStore's Open returns for a key with no object behind it. The frame answers 404 with the row's identity and never the key.
var ErrSecretNotOpened = errors.New("the stored secret does not open on this row: it was written for another row, or was altered after it was written")
ErrSecretNotOpened is the error of opening a stored secret that does not open: its bytes were written for another row, or were altered after they were written.
var ErrUnsupportedNodeType = errors.New("unsupported AST node type for SQL generation")
ErrUnsupportedNodeType indicates an AST node type that the SQL generator cannot handle.
var ErrUnsupportedOperator = errors.New("unsupported operator for SQL generation")
ErrUnsupportedOperator indicates a condition operator that the SQL generator cannot handle.
var ErrWarningAsked = errors.New("warning asked: the transaction rolls back by design")
ErrWarningAsked is the sentinel a generated frame returns from its transaction function once it has read a method's warning: the transaction rolls back, nothing retries, and the frame answers the warning. It never reaches the wire.
Functions ¶
func AfterCommit ¶ added in v0.3.0
func AfterCommit(txn ReadWriteTransaction, f func(ctx context.Context)) error
AfterCommit registers f to run once the transaction has committed, after the commit and before ExecuteFunc returns, in registration order. A transaction that does not commit, for any reason, runs nothing, and a transaction Spanner retries runs only what the attempt that committed registered. f runs detached from the request's cancellation and answers nothing: the rows are committed, so a failure in it is f's own to log.
A transaction an application wraps itself and commits outside ExecuteFunc has no executor to make the calls: run them with Committed after the commit.
func AfterCommitOnce ¶ added in v0.3.0
func AfterCommitOnce(txn ReadWriteTransaction, key any, f func(ctx context.Context)) error
AfterCommitOnce is AfterCommit for work that is owed once however many writes ask for it: a registration under a key the transaction already holds is dropped. The key is compared with ==, so it is a comparable value that names the work (the pointer of the engine to tell, a constant).
func AsksWarning ¶ added in v0.5.0
AsksWarning reports whether the request asks for the method's warning in place of the call: the header says true. A request without the header asks for none, and a header that says anything else is refused (asksByHeader), which the frame answers in place of running the call.
func AuthFrom ¶ added in v0.4.0
AuthFrom returns the name of the auth the request came through, as WithAuth bound it. ok is false when nothing bound one: a request served outside an outlet's generated routes, or a call made outside any request.
func AwaitFirstAdministrator ¶ added in v0.3.0
func AwaitFirstAdministrator(ctx context.Context, perms UserPermissions, domain accesstypes.Domain) error
AwaitFirstAdministrator returns once the permission engine answers the session's user a foothold in the tenant whose row and administrator membership the request just committed, bounded by administratorVisibleTimeout, so the answer the route gives is one the person's next request stands on. The generated write paths call it after the commit and once this instance's roster lists the tenant, since the question it asks is the one the next request asks. An error says the engine did not answer in time: the tenant and the membership are committed all the same, so the caller logs it and answers the request.
func BodyLimit ¶
BodyLimit returns middleware that bounds every request body it serves to limit bytes. The generated router applies it once per route, on the group that holds the resource routes and the other JSON routes; the upload, live and RPC routes sit beside that group and bound their own bodies, since a nested limit can only tighten the one outside it. A body that runs past the limit fails the handler's read with *http.MaxBytesError, which the decoders answer with 413 naming the limit, and the server closes the connection behind the response rather than read the rest.
func CheckAPIVersion ¶
func CheckAPIVersion(check APIVersionCheck) func(http.Handler) http.Handler
CheckAPIVersion is the middleware a session outlet's API routes run under. A request carrying APIVersionHeader is answered when its release is between the oldest answered release and the server's, inclusive, and refused with 412 otherwise, before any handler runs and before its body is read; the refusal carries the server's release in APIVersionHeader. A request without the header is answered, and so is any request when either side's version is not a release (dev, or anything that is not a semantic version). Every response on a checked route carries Vary: APIVersionHeader, so a browser never serves one application's cached answer to another. Routes named in Exempt pass untouched. Versions compare as semantic versions, with or without a leading v.
func CheckWarning ¶ added in v0.5.0
CheckWarning holds a method's warning to what a dialog needs of it before the frame answers it: a consequence to read and the words for the button. A warning that lacks either is the method's mistake, and is an error, never a dialog with an empty warning over a button that says nothing.
func CloneRequest ¶
CloneRequest creates a deep copy of an http.Request, including its body. This is useful when the request body needs to be read multiple times, as the original body can only be read once. The cloned request gets a new body that can be read and seeked independently.
func ClosedDomains ¶ added in v0.5.0
func ClosedDomains(ctx context.Context, perms UserPermissions) ([]accesstypes.Domain, error)
ClosedDomains lists the tenants that are closed to this session: the domains of the application's roster where the person holds at least one grant and that the session does not reach (UserPermissions.Reaches), sorted; never nil. A tenant is closed to a session when it admits its people through its own directory only and the session was not established through that directory. The session's tenant list carries each with the reason (UserDomainsHandler), so a person sees the tenant they hold a seat in and why this sign-in does not open it; nothing else changes for the tenant, whose routes answer the session as a tenant that does not exist. It tells the person nothing new: they hold a seat there.
The permissions SessionPermissions composes answer it, for a person's own sign-in. A session that views the application as someone else, and one that acts as a role, list none: the list is the word a person is given about their own seats and their own sign-in, and such a session is neither. Any other UserPermissions, and an application that keeps no declarations, list none.
func CommitTimestamp ¶
func CommitTimestamp(_ context.Context, _ ReadWriteTransaction) (any, error)
CommitTimestamp is a FieldDefaultFunc that returns the Spanner commit timestamp.
func CommitTimestampPtr ¶
func CommitTimestampPtr(_ context.Context, _ ReadWriteTransaction) (any, error)
CommitTimestampPtr is a FieldDefaultFunc that returns a pointer to the Spanner commit timestamp.
func DeclaredLength ¶
DeclaredLength is the length a STRING(n) or BYTES(n) column declares, or the element of an array of one; zero for MAX, for every other type, and for a value that does not parse. The TypeScript generator emits it as the field's maxLength.
func DefaultFalse ¶
func DefaultFalse(_ context.Context, _ ReadWriteTransaction) (any, error)
DefaultFalse is a FieldDefaultFunc that returns false.
func DefaultTrue ¶
func DefaultTrue(_ context.Context, _ ReadWriteTransaction) (any, error)
DefaultTrue is a FieldDefaultFunc that returns true.
func DemonstrationDescriptions ¶
DemonstrationDescriptions returns the registry as a map from key to description.
func DemonstrationKeys ¶
func DemonstrationKeys() []string
DemonstrationKeys returns the registry's keys, sorted.
func DirectoryName ¶ added in v0.5.0
func DirectoryName(directory signin.Directory, namers ...DirectoryNamer) string
DirectoryName is DirectoryWords with the kind of directory before a name, as a sentence that first speaks of a directory says it: "Google Workspace acme.example", "Microsoft Entra tenant Lakeside", "OpenID Connect provider id.acme.example". A directory nobody has a name for is said by its label as DirectoryWords says it, which names the kind already.
func DirectoryOnlyStateHandler ¶ added in v0.5.0
func DirectoryOnlyStateHandler( client Client, rules *TenantDirectoryRules, userPermissions func(r *http.Request) UserPermissions, tenantParam httpio.ParamType, methods ...accesstypes.Resource, ) http.HandlerFunc
DirectoryOnlyStateHandler serves a tenant's directory-only switch as it stands (DirectoryOnlyState, DirectoryOnlyRoute): what a tenant's Sign-in page shows the person who may turn it. The read is the tenant's own: it is served under the tenant's route and asked under the grants of the methods that turn the switch, Execute in the tenant's scope on one of methods (the one that turns it on, or the one that turns it off), where a caller with neither is Forbidden and learns nothing of the tenant. A grant that holds on a condition is refused the same way: a read has no request for the condition to judge. It writes nothing. client runs it in one transaction, rules are the tenant record's, and tenantParam is the route parameter that names the tenant. The generated handler of a tenant record that declares the switch builds it.
func DirectoryWords ¶ added in v0.5.0
func DirectoryWords(directory signin.Directory, namers ...DirectoryNamer) string
DirectoryWords says a directory as the middle of a sentence names it to a person: the name the first namer that knows one gives it ("Lakeside", "acme.example"), and where none does, the directory by the first label a namer answers ("your organization's Microsoft directory"). Where no namer answers anything, an application whose management is not generated or a directory no registration takes any more, it reads what the directory alone says: a Google Workspace's connection is its name or its domain, an OpenID Connect provider's is the application's name for it or its issuer, said by its host, and any other is said by its kind. It never says a tenant id.
func DiscardUpload ¶
DiscardUpload deletes the streamed objects (keys, the Files' or the FilesIn's Keys) of an upload whose transaction did not commit and returns cause, the failure that ended it, so the frame answers with the original refusal. The delete runs detached from the request's cancellation under its own timeout, and only when nothing committed: when the Spanner client reports the commit's outcome as unknown (*spanner.TransactionOutcomeUnknownError, a deadline or a cancel after the commit was sent), the rows may hold the keys, so the objects are kept and the keys logged for the orphaned-file cleanup, which removes them if no row claims them. A delete failure is noted on the cause: the objects it left are the cleanup's too.
func DryRunRolledBack ¶
DryRunRolledBack reports whether a transaction ended by the dry-run sentinel.
func FeatureFlagHandler ¶
func FeatureFlagHandler(a FeatureApp, collection *GeneratedCollection) http.HandlerFunc
FeatureFlagHandler serves one flag, to a Read grant on FeatureFlags. The generated router registers it at GET <prefix>/feature-flags/{featureFlagName} on every session-serving outlet.
func FeatureFlagsDDL ¶
FeatureFlagsDDL is the CREATE TABLE statements of the FeatureFlags table and its audit table, FeatureFlagChanges, for the application database's type. An application copies the statements into a schema migration; a Lodestar test pins its migration to them.
FeatureFlags holds one row per declared flag: Name (the key), Description, Enabled, UpdatedAt (the commit timestamp of the last write) and UpdatedBy (who wrote it: the migration process, or the principal that flipped it). FeatureFlagChanges holds one row per flip: Name, ChangedAt (the commit timestamp), Enabled (the value written) and ChangedBy. The audit rows are never deleted, so a flag's history outlives the flag.
func FeatureFlagsHandler ¶
func FeatureFlagsHandler(a FeatureApp, collection *GeneratedCollection) http.HandlerFunc
FeatureFlagsHandler serves the flags as a list, to a List grant on FeatureFlags: the FeatureAdministrator's dialog reads it. The generated router registers it at GET <prefix>/feature-flags on every session-serving outlet.
func FeatureFlagsQueryKeys ¶
func FeatureFlagsQueryKeys() (order, keys []accesstypes.Tag)
FeatureFlagsQueryKeys are the wire names a FeatureFlags list sorts and filters by: the name alone, which is the key.
func FeatureGuard ¶
func FeatureGuard(features *FeatureSet, feature Feature) func(http.HandlerFunc) http.HandlerFunc
FeatureGuard is the middleware the generated routes wrap a gated resource's and a gated method's routes in: while the flag is off the route answers exactly as the outlet's not-found handler does, so a gated-off route is indistinguishable from one that does not exist.
func FeatureNotFound ¶
func FeatureNotFound(w http.ResponseWriter)
FeatureNotFound answers as the generated router's not-found handler does under every outlet prefix: the one answer a gated-off route gives.
func FeaturesHandler ¶
func FeaturesHandler(features *FeatureSet) http.HandlerFunc
FeaturesHandler serves the enabled flags to anyone the outlet let through: no permission beyond being signed in, since a page needs to know which gated surfaces to show before it holds any grant on them. The generated router registers it at GET <prefix>/features on every outlet, the API-key outlets included.
func FormatByteSize ¶
FormatByteSize renders a byte count the way @upload declares it: whole gigabytes, megabytes, or kilobytes (1024-based) when the count divides evenly, bytes otherwise.
func HasValueLimit ¶
HasValueLimit reports whether the decoder sizes a field of the given kind, or a slice of it, declared on a column of the given Spanner type. The generator writes the sqltype tag exactly where this is true, so a tag the runtime cannot pair with its field is a stale struct.
func IsDryRun ¶
IsDryRun reports whether the request asks for a dry run: the header says true. A request without the header asks for none. A header that says anything else is refused (asksByHeader), and the frame answers the refusal in place of running the call, so a client that sends "1" to rehearse a call never writes for real.
func ListedInSomeTenant ¶ added in v0.5.0
func ListedInSomeTenant(ctx context.Context, perms UserPermissions, resources []accesstypes.Resource) ([]accesstypes.Resource, error)
ListedInSomeTenant returns, of the resources, the ones the person may list in at least one tenant the session reaches (UserPermissions.Domains), in name order: the people a list of the record across tenants has something to show, which is who its page is for (WithListsAcrossTenants). It asks the List grant alone, as TenantsListed does, one check for each reached tenant until every resource is answered.
func MigrateFeatures ¶
func MigrateFeatures(ctx context.Context, db Client, declared []FeatureDeclaration) error
MigrateFeatures brings the FeatureFlags table to the declared flags, in one transaction: a declared flag the table lacks is inserted disabled, a flag the table holds keeps its Enabled and takes the declared description, and a flag no longer declared is deleted. The audit rows are untouched. It runs in the deploy step beside the role check, before the release takes traffic.
func MockIterSeq2 ¶
func MockIterSeq2[Resource Resourcer](err error, resource ...*Resource) iter.Seq2[*Row[Resource], error]
MockIterSeq2 is used for mocking the iter.Seq2[*Row[Resource], error] type returned by List. Each resource is wrapped in the Row envelope. If both err and resource are provided, it will yield all elements in resource first and then err
func NewTenantDeclarationReader ¶
func NewTenantDeclarationReader(table, keyColumn string, columns *TenantDeclarationColumns) signin.DeclarationReader[*spanner.ReadWriteTransaction]
NewTenantDeclarationReader returns the reader of a tenant's declaration for the sign-in policy (signin.TenantPolicy): it reads the tenant record's row and the directories record's rows for the tenant in the sign-in's own transaction, on Spanner, where the session's transaction is *spanner.ReadWriteTransaction. The generated New<Record>DeclarationReader constructor supplies the table and the columns; an application calls that one. A tenant the table does not hold declares nothing (nil). The reader has no side effects, as a retried transaction needs.
func NewTenantDirectoryReader ¶
func NewTenantDirectoryReader(columns *TenantDeclarationColumns) signin.DirectoryReader[*spanner.ReadWriteTransaction]
NewTenantDirectoryReader returns the reader of the declaration of one directory, for a person's first sign-in through it (session.Auth.SetDirectoryAdmission, through signin.DirectoryReader): the directories record's row whose method and connection are the directory's, as its tenant with the directory's default seat (DefaultSeatColumn, "" where the record carries no such column or the row names none), read in the sign-in's own transaction on Spanner. A directory is one tenant's, so the answer names one tenant at most. The generated New<Record>DirectoryReader constructor supplies the columns; an application calls that one. A directory no tenant has answers nothing, and so does a record that declares no directories. The reader has no side effects, as a retried transaction needs.
func NoDryRunOrWarning ¶ added in v0.5.0
NoDryRunOrWarning is the middleware of a route whose frame reads neither the X-Dry-Run header nor the X-Warning header: a list, a read, a resource's create, patch and delete, a tenant's creation, a scheduled call. A request that asks for a dry run or for a warning asks that the call be held back, and a frame that never reads the header would run it for real. So the request is refused here (400), naming the header and saying the call has none, and nothing runs. A header that says anything but true is refused as a frame that reads it refuses it (asksByHeader). A request that carries neither header passes through.
The generated router mounts every route under it but the ones whose frames answer the two headers themselves: a method's, an upload's and SetFeature's. A route knows what its frame reads, so the rule is written once, where the routes are registered, and no frame carries a copy of it.
func OpenNullableSecretIn ¶ added in v0.5.0
func OpenNullableSecretIn[Resource Resourcer](ctx context.Context, txn ReadWriteTransaction, key KeySet, field accesstypes.Field, stored *Secret) (*string, error)
OpenNullableSecretIn is OpenSecretIn for the secret of a nullable column: no value for a row that holds none.
func OpenSecretIn ¶ added in v0.5.0
func OpenSecretIn[Resource Resourcer](ctx context.Context, txn ReadWriteTransaction, key KeySet, field accesstypes.Field, stored Secret) (string, error)
OpenSecretIn opens the secret field of a row inside a read-write transaction, with the keys of the transaction's client, and rewrites a value sealed under an older version of the application secret under the current one in the same transaction. It is what the generated Open<Field>In method of a row calls, with the row's own key; application code calls that method.
The rewrite is the stored bytes alone: the value does not change, so no permission is asked, no update function stamps the row and no change record is written. It is buffered only when the row still holds the bytes that were opened, read inside the transaction, so a row read before the transaction began never overwrites a value set since, and never for a row a patch of the same transaction has already written, whose buffered write no read sees.
func Operations ¶
Operations parses a batch JSON patch request and yields an iterator of individual Operation objects.
func ParseByteSize ¶
ParseByteSize reads a size the way @upload declares it: a count of bytes, or a count suffixed KB, MB, or GB (1024-based).
func PatchSetDiff ¶
func PatchSetDiff(opts ...cmp.Option) func(a, b PatchSetComparer) string
PatchSetDiff compares two PatchSetComparer objects for equality. It checks resource, patch type, data, fields, and primary keys. A difference in a secret field is reported with [secret] on both sides: what it answers is printed by tests and carried in errors, and a patch holds a secret as the text it was given.
func PermissionDigestHandler ¶
func PermissionDigestHandler(userPermissions func(r *http.Request) UserPermissions, opts ...DigestOption) http.HandlerFunc
PermissionDigestHandler serves the per-scope permission digest: the session user's structural grant enumeration, resource → permission → granted|conditional, with denied targets absent so consumers fail closed. The generated router registers it on the default outlet; applications wire nothing.
The scope is the request's input, never payload structure: ?domain= names one tenant partition, its absence means the global scope. There is no domain validation — an unknown tenant simply holds no grants, so its digest is empty, which also keeps concealed tenancy unprobeable from this endpoint. The payload is advisory UI material (which surfaces to render); enforcement stays with the endpoint gate, the read rules, and the write stages. With WithFeatureGates the entries behind a flag that is off are left out too.
func ProcessEvent ¶
ProcessEvent generates a standard event source string for a system process.
func QuerySetDiff ¶
func QuerySetDiff(opts ...cmp.Option) func(a, b QuerySetComparer) string
QuerySetDiff compares two QuerySetComparer objects for equality. It checks resource, fields, and primary keys.
func ReleaseHeader ¶
ReleaseHeader names the server's release on every response of the routes it wraps: APIVersionHeader set to release before the handler runs, so a browser application reads which release it talks to from any answer, the methods list its login page reads before any sign-in first of all, and curl shows it. The generated router puts it on every outlet; CheckAPIVersion, behind it on a session outlet, keeps naming the release on its refusal. An empty release names nothing; dev, the local build's name, is named as it is.
func RequestEnvironment ¶
func RequestEnvironment() accesstypes.Environment
RequestEnvironment samples the request's decision context. The decoders are the construction point for every decoded artifact: each carries one Environment, so the instant a permission check folds conditions against is the identical instant later bound into SQL — the two consumers can never disagree about a window boundary. A check run outside a decoder on the request's behalf (the live renewal's re-check of a tab's subscriptions) samples its own through the same function, so it sees the same local zone.
func RequireFileStores ¶
RequireFileStores reports which of the named stores the client holds no store for: the generated router calls it at start with every store the package uses, and refuses to start naming the first store that is not wired. The message names the store and the option that wires it, never a configuration variable, since where the URL comes from is the application's configuration's convention.
func RequireSecretKeys ¶ added in v0.5.0
RequireSecretKeys refuses a client built with no secret keys for an application that stores secrets: the generated router calls it at start with every secret field its package declares, and refuses to start naming them. Without the check the first write of a secret would be the first to fail. A client wired to an environment that carries no version (SecretKeysFromEnv) is refused naming the variable that is missing, the first version's, under the name the application declares; a client that was never given a holder is refused naming the wiring.
func ResponseStatus ¶
ResponseStatus is the status a generated frame writes a method's answer with: the result's own choice, checked against the statuses the method declared. An undeclared status is a programming error; the frame answers 500 with it, naming the method and the code. A result that does not choose answers 200.
func RowKey ¶
RowKey spells a row's primary key the way the read route does: the key values in route order, each in its text form, joined with "/". It is the key a live row subscription names and a change document carries, so a client that addresses the row by its route and the publisher that saw the patch spell it identically.
func ServeRenderedFile ¶
func ServeRenderedFile(w http.ResponseWriter, r *http.Request, content *Content, segment, label string, key ...any) error
ServeRenderedFile answers a computed resource's @file route with what its content function rendered: 304 when the request's validator matches the content's Tag, the bytes otherwise, and, for a nil content, a 404 in the row's words returned for the handler to encode. The function never touches the response; the frame does.
func ServeStoredFile ¶
func ServeStoredFile(ctx context.Context, w http.ResponseWriter, r *http.Request, store FileStore, file StoredFile, segment, label string, key ...any) error
ServeStoredFile answers a @file route from the store the column names, read off the resource client by the generated handler: 304 when the request's validator matches the key, before the store is opened, and the bytes otherwise, typed by the row's type column, then the object's, then the name's extension, under the file headers (nosniff, the frame's sandbox policy, and the disposition the type decides). A row carrying no key, or a key the store holds nothing under, is a 404 returned for the handler to encode, in the row's words (label and key, "MissionDocument 0193…") and never the store key's; so is any other failure. A nil store, the column's store not wired on the client, is an error naming the wiring, answered 500.
func SessionDirectory ¶ added in v0.5.0
SessionDirectory answers the directory the request's session was established through: what "make the directory I am signed in through this tenant's directory" names. A session that came through no directory (a password, a session the application started itself, an impersonation) is refused with a Conflict that says how to sign in instead; a personal account is answered as it is, for the rules to refuse it by name (TenantDirectoryRules.Set).
func SetFeatureEnabled ¶
func SetFeatureEnabled(ctx context.Context, db Client, name Feature, enabled bool, eventSource string) error
SetFeatureEnabled flips one flag in its own transaction: the row takes the value, the commit timestamp and eventSource, and the audit table gains the flip's row. A name the table does not hold is a not-found error. SetFeatureHandler flips through the same write; a bootstrap or a test flips a flag directly through this.
func SetFeatureHandler ¶
func SetFeatureHandler(a FeatureApp, collection *GeneratedCollection, signals Signaler) http.HandlerFunc
SetFeatureHandler flips a flag, to an Execute grant on SetFeature: the row takes the value with the commit timestamp and the principal, the audit table gains the flip's row in the same transaction, KindFeatures is signaled after the commit and before the answer (bounded by FeatureSignalTimeout; a failure is logged, since the other instances reload at their backstop), this instance's copy reloads, and the answer is the flag from the reloaded copy. An unknown name is 404. A dry run (X-Dry-Run: true) runs the frame and rolls back, as every transaction-form method does. The signaler is the application's live service, which every application wires; the handler refuses to be built without one. The generated router registers it at POST <prefix>/set-feature on every session-serving outlet.
func SetLocalZone ¶
SetLocalZone wires the timezone the bare word local resolves to inside a temporal grant condition — timeOfDay(now, local), dayOfWeek(now, local) (design plan §05). Call it once at application startup, before serving; where the zone comes from is the application's business (a config constant today; a session- or tenant-resolved source rides the same seam later). Unwired, a condition using local fails its check loudly at first use — the same posture as a missing now — while explicit-zone conditions need no wiring at all.
func SignInRoles ¶
func SignInRoles(manager signin.UserRoleManager) signin.UserRoleManager
SignInRoles adapts the access library's user manager to the sign-in policy (signin.TenantPolicy) on Spanner. The policy reads the person's memberships inside the sign-in's read-write transaction, with the transaction's context, and the Spanner client refuses a read made with that context as a nested transaction, so the manager handed to the policy directly fails every sign-in the policy decides. The adapter reads the memberships outside the transaction, under the sign-in's deadline and cancellation and nothing else of its context, as the committed memberships, which is what the policy decides over on PostgreSQL too, and it reads which tenants the person administers the same way. The manager's other operations pass through unchanged.
func SortRows ¶
SortRows orders rows in memory by the given fields: each field by its type, with NULL placed where the application's database (dbType) places it — Spanner first ascending and last descending, PostgreSQL last ascending and first descending — stably so equal rows keep their yielded order. A computed resource's generated handler sorts the body's rows with it, so a computed list places NULL at the same end as the tables beside it; a body that takes the sort (QuerySet.TakeSort) orders its own query instead, and a plain ORDER BY there produces the same placement. An unsupported dbType is an error.
func TenantKeyEquals ¶
func TenantKeyEquals(value any, domain accesstypes.Domain) (bool, error)
TenantKeyEquals reports whether a row's tenant-key value equals the request partition. It is the generated transition handlers' row-location test: a mismatch renders the target NotFound, indistinguishable from a row that does not exist. The domain converts into the value's own type exactly the way the decode-seam stamp converts it.
func TenantsListed ¶ added in v0.5.0
func TenantsListed(ctx context.Context, perms UserPermissions, res accesstypes.Resource, narrowed []accesstypes.Domain) ([]accesstypes.Domain, error)
TenantsListed is the set of tenants a list of the record across tenants reads for the person: the tenants the session reaches (UserPermissions.Domains), narrowed to the ones narrowed names when it is not nil, in which the person holds the List grant on the record, sorted. The live renewal works a subscription's set out again with it, as the list's own request worked it out (QuerySet.TenantsListed).
func UserDomainsHandler ¶
func UserDomainsHandler(userPermissions func(r *http.Request) UserPermissions, opts ...UserDomainsOption) http.HandlerFunc
UserDomainsHandler serves the session's tenant list: the domains where the user holds at least one grant, sorted, each with its name (UserDomain), and each that the session does not reach marked closed, with the reason. It is the tenant picker's question, answered by the library so applications wire nothing — the generated router registers it on the default outlet beside the digest. The picker shows a tenant's name: the people of a tenant cannot read the tenant record, a global resource, so the list carries the name for them (WithDomainNames).
The predicate is concealed tenancy's own foothold test over the session's admission (UserPermissions.HasGrants, UserPermissions.Reaches), so a domain listed here is exactly a domain whose routes answer the user with ordinary 403s rather than a concealing 404; the picker and the guard can never disagree. A tenant is offered only when the session may enter it, and the application's tenant declaration decides (TenantDeclarations): a tenant whose declaration does not admit the way the session was established is listed closed (UserDomain.Closed), since the person holds a seat there and is owed the reason, and its routes answer the session with the concealing 404 all the same. The global scope is never a domain. The answer reports grants, not tenants: a domain the application has since removed still lists while grants in it remain, and existence is the tenant roster's (TenantRoster.Has). Structural and non-folding, so it caches cleanly per user and session. The payload is always a JSON array — an empty membership is [], never null.
func UserEvent ¶
UserEvent generates a standard event source string for an action performed by a user. It extracts user information from the context. A person is written as their username with the id of their account, since the name is what people read and can change, and the id is who they are; the session comes last, as the evidence of how they were signed in: "username (account id), session id" for an ordinary session. For an impersonated session the actor comes first, so every data change carries evidence of the real person: "actor (account id) impersonating username (account id), session id" for an impersonated user, "actor (account id) as role name, session id" for a role. A person with no account here (a session type that keeps none, an actor another application authenticated) is written by name alone.
func UserProcessEvent ¶
UserProcessEvent generates a standard event source string for an action performed by a user within a specific system process.
func ValidFeatureName ¶
ValidFeatureName reports whether name has a flag name's shape.
func ValidateFeatureDeclarations ¶
func ValidateFeatureDeclarations(declared []FeatureDeclaration) error
ValidateFeatureDeclarations refuses a declaration whose name is malformed and two declarations of one name, each refusal naming the constant.
func WarningAsked ¶ added in v0.5.0
WarningAsked reports whether a transaction ended by the warning sentinel.
func WithAuth ¶ added in v0.4.0
WithAuth binds the request to the auth whose sessions its outlet serves, by the auth's name (the auth package's Name). An outlet's generated routes bind it on every request (live.Subscribing), so whatever answers for the request can tell the people of one auth from another's: two auths over one database may each hold a person of the same username, and they are two people.
Types ¶
type APIVersionCheck ¶
type APIVersionCheck struct {
// ServerVersion is the release the server was built from, the configuration's
// APP_VERSION. A value that is not a release, dev for one, checks nothing.
ServerVersion string
// OldestAnswered is the oldest release still answered: a release such as 1.5.0,
// ThisRelease for the server's own, or empty for every release that sends the
// header.
OldestAnswered string
// Exempt are the route patterns answered whatever the header says: the
// stored-file routes, which a link or an image reaches.
Exempt []string
}
APIVersionCheck is what a session outlet's version check compares a request's APIVersionHeader against. The generated router builds one per session outlet from the server version the application reports and the oldest answered release the generator program declared.
type AcrossTenantsLists ¶ added in v0.5.0
type AcrossTenantsLists interface {
ListedAcrossTenants() []accesstypes.Resource
}
AcrossTenantsLists answers the resources declared for listing across tenants (@listAcrossTenants), as the generated collection does.
type Answer ¶
type Answer struct {
Status int
}
Answer is the sentinel a generated frame returns from its transaction function when a method's answer is a refusal (a 4xx): the transaction rolls back, nothing retries, and the frame writes the status with the typed body it captured. It never reaches the wire as an error.
type Answerer ¶
type Answerer interface {
HTTPStatus() int
}
Answerer is what a method's result type declares to choose the status of each response.
type AttributeData ¶
type AttributeData struct {
Name string
Column string
Type AttributeType
Path []BindingHop
List bool
}
AttributeData is one attribute binding: the vocabulary name grant conditions reference, resolved to data. Column is the anchor column on the resource's own table — the attribute itself when Path is empty, or the foreign key the join path leaves through. Type is the attribute's comparison type, derived by generation from the bound column's Go type.
List marks an attribute over a list column (an ARRAY): Type is then the type of one item, and a condition that reads the attribute is judged once for each item of the row's list and holds only when it holds for every one (lowerRowCondition). On a method's request field it marks a list field, which the decoder judges the same way.
type AttributeType ¶
type AttributeType = accesstypes.AttributeType
AttributeType is the attribute comparison-type vocabulary, canonically defined in accesstypes so deployment tooling (MigrateRoles) shares one definition with generation.
type BindingHop ¶
BindingHop is one resolved step of a join path: read Table, joined on JoinColumn equal to the previous step's value, continuing through (or terminating at) Column. Every hop follows a real foreign key, validated at generation, so the walk is many-to-one.
type Bindings ¶
type Bindings struct {
Attributes []AttributeData
Domain *DomainBindingData
SubjectSets []SubjectBindingData
SubjectValues []SubjectBindingData
}
Bindings is one resource's complete binding vocabulary.
type BodyDecoder ¶
type BodyDecoder[Request any] struct { // contains filtered or unexported fields }
BodyDecoder decodes a JSON request body into a request struct and validates it, for a generated route that serves no resource and no method of the collection and so meets no permission gate: the create-your-tenant route, whose gate is the session holding no tenant. The field tags the generated patch requests carry (json, sqltype, nullable) are read the same way, so a value the column cannot hold answers 400 naming the field, and the validator the application supplies runs over the struct's validate tags.
func MustNewBodyDecoder ¶
func MustNewBodyDecoder[Request any](validate ValidatorFunc) *BodyDecoder[Request]
MustNewBodyDecoder is NewBodyDecoder for generated code, which builds its decoders where the application wires its handlers: a request type the decoder cannot read is a programming error surfaced there.
func NewBodyDecoder ¶
func NewBodyDecoder[Request any](validate ValidatorFunc) (*BodyDecoder[Request], error)
NewBodyDecoder builds the decoder for a request type, which must be a struct, with the application's validator.
type BrowserApp ¶
type BrowserApp struct {
// contains filtered or unexported fields
}
BrowserApp serves a built browser application, an Angular bundle, from a directory under a mount path: "/" for the application at the root, "/console" for one under a path, the value the application's generated router declares with WebApp. An application's DeepLink and Assets handlers delegate to it, one line each.
Two cache classes, by file name. A file whose name carries the build hash (eight uppercase letters or digits before the extension: main-ZPJWNJT4.js, styles-A4ABYBXD.css, media/font-ABCDEFGH.woff2) answers "public, max-age=31536000, immutable": the name changes with the content, so the service worker and any cache between may keep it for good. Every other file answers "no-cache": the entry document, ngsw.json, the worker scripts, the web manifest, the favicon, the icons, the prerendered-routes file, and the licenses file may be kept and are revalidated before each use; an unchanged file answers 304. Their validator is a strong ETag over the content, since the files ride in a container image whose modification times are the build's and may repeat, and the standard library's conditional handling answers it. A .webmanifest answers application/manifest+json. A directory is never listed: its path is an application route through DeepLink and 404 through Assets alone.
func NewBrowserApp ¶
func NewBrowserApp(dir, mountPath string) *BrowserApp
NewBrowserApp returns the server of the bundle built into dir, mounted at mountPath: "/" or a path starting with "/" and without a trailing "/", as WebApp takes it. Any other mount path is a programming error and panics, naming the rule.
func (*BrowserApp) Assets ¶
func (b *BrowserApp) Assets() http.HandlerFunc
Assets serves the bundle's files under the mount path: the mount prefix removed, the file read from the directory with the cache class its name selects, a path outside the mount, a missing file, or a directory answered 404. The mount path itself, with or without a trailing slash, and <mount>/index.html serve the entry document.
func (*BrowserApp) DeepLink ¶
func (b *BrowserApp) DeepLink(next http.Handler) http.Handler
DeepLink rewrites the application's own routes to its entry document, so a bookmarked or reloaded route loads the application. A request whose last path segment has no extension, Angular matrix parameters (";key=value") removed, is rewritten to <mount>/index.html and passed on; a path with an extension passes through unchanged, matrix parameters and all, and is a file or a 404.
type Buffer ¶
type Buffer interface {
Buffer(ctx context.Context, txn ReadWriteTransaction, eventSource ...string) error
}
Buffer is an interface for types that can buffer their mutations into a transaction. This is used for batching operations.
type Caller ¶
type Caller struct {
// Permissions is the checker the entry check ran with: the session's user, or
// the role an act-as-role session assumed, behind the session's mask.
Permissions UserPermissions
// Scope is the partition the request was checked in.
Scope accesstypes.Scope
// Env is the decision environment the entry check sampled.
Env accesstypes.Environment
// contains filtered or unexported fields
}
Caller is what the generated frame knows about a request's caller once the entry check has run: the checker that check ran with, the scope it ran in, and the environment it sampled, so a body that arms a write or a read against the caller evaluates the same facts the entry check did (the decision instant included). The generated handlers stamp it into the context before the application's code runs: a method's frame before Execute and Warning, and a computed resource's frames before its List function, its Read function and the function that renders a file. That code reads it back with CallerFrom. Within such a request a zero Caller is therefore never seen; no caller means a call the application makes outside any request, or a handler that stamped none.
func CallerFrom ¶
CallerFrom returns the caller the frame stamped, or a zero Caller when none was: a mutation or query armed with a zero Caller refuses at execution instead of running unchecked. Code that reads a zero Caller as a call of the application's own, as the identity library's rules do, relies on every frame that serves a person stamping one.
func (*Caller) As ¶
func (c *Caller) As(perms UserPermissions) *Caller
As returns the caller acting through another checker in the same scope and environment: a body that should act as a named role composes the checker the way act-as-role sessions do (RolePrincipalPermissions over access.ForRole) and arms its operations with the result. The actor stays who it was.
func (*Caller) Check ¶
func (c *Caller) Check(ctx context.Context, perm accesstypes.Permission, resources ...accesstypes.Resource) (accesstypes.Decisions, error)
Check answers, as data, what the caller may do: the decision for perm on each resource (a resource, or a field of one as "Resource.field"), evaluated in the caller's scope and environment. A body branches on the answers where policy should decide what it does, without arming a write.
func (*Caller) ExecuteGate ¶ added in v0.5.0
func (c *Caller) ExecuteGate(ctx context.Context, method accesstypes.Resource, request any) (*ExecuteGate, error)
ExecuteGate answers the caller's Execute decision on another method, for a request the body builds in place of one a decoder read: what that method's own frame would decide for the request, in the scope and the environment the caller was checked in. A body that does through one method what another method does asks it, so the grant of the method that does the thing directly judges the same thing done another way: a person put in a group is given the group's roles, and is judged by the grant of the method that gives a role.
Denied is the Forbidden the method's own decode answers. The atoms of a conditional grant that read the method's request fields (new.<name>) are settled against request, a value of the method's own request struct. What is left reads the method's target row and rides the gate: Settled says whether anything is left, and Enforce, EnforceView or EnforceProposed judges it against the row.
type CallerPassword ¶ added in v0.5.0
type CallerPassword func(ctx context.Context, txn ReadWriteTransaction) (has, applies bool, err error)
CallerPassword answers, for one auth, whether the person behind the request holds a password in it, in the caller's transaction. applies is false where the auth asks nothing of the request: its caller is another auth's person, or the auth has no password method, so nobody of it could have a password. The generated identity client of each auth supplies it (CallerPassword); an application names none.
type Client ¶
type Client interface {
// DBType is the application database's type: the placement its lists sort NULL
// in, which a computed resource's handler follows (NewComputedQueryDecoder).
DBType() DBType
// FileStore returns the file store wired under name (WithFileStore for
// DefaultStore, WithNamedFileStore for a named store's StoreNameFor), or nil when
// none is: the generated upload frames and file routes read their store here, the
// one wiring point, and the generated router refuses to start when a store the
// package uses is not wired (RequireFileStores). The Postgres client holds none.
FileStore(name StoreName) FileStore
ReadOnlyTransaction() ReadOnlyTransactionCloser
ReadOnlyTransaction
Executor
}
Client is an interface for the supported database Client's to implement. It is not intended for mocking since each database requires an implementation in this package.
type ClientOption ¶
type ClientOption func(*clientOptions)
ClientOption configures a database client at construction.
func WithFileStore ¶
func WithFileStore(store FileStore) ClientOption
WithFileStore wires the default store: the one an untyped @file column, an unnamed @upload and resource.Files belong to. The upload frames stream into it, the file routes open from it, and a transaction that deletes a row carrying a default-store key, or points it at another object, has the old object deleted from it once the commit lands. Wired twice, the client panics at construction naming the store.
func WithNamedFileStore ¶
func WithNamedFileStore[S NamedStore](store FileStore) ClientOption
WithNamedFileStore wires the named store S: the one a Key[S] column, an @upload(store: S) and FilesIn[S] belong to. Any number of named stores of different types can be wired; the same type wired twice panics at construction naming the store.
func WithSecretKeys ¶ added in v0.5.0
func WithSecretKeys(keys *SecretKeys) ClientOption
WithSecretKeys hands the client the application's secret keys: the write path seals every secret field a patch sets with them, where it turns the patch's fields into columns, so no application code encrypts anything. A client built without them refuses to write a secret, and the generated router of an application that stores one refuses to start (RequireSecretKeys). Given twice, the client panics at construction.
type CollectionBuilder ¶
type CollectionBuilder struct {
// contains filtered or unexported fields
}
CollectionBuilder assembles CollectionData by replaying the registration semantics a permission collection enforces: duplicate detection, null-permission filtering, and immutable-field replacement (the last registration for a resource wins).
func NewCollectionBuilder ¶
func NewCollectionBuilder() *CollectionBuilder
NewCollectionBuilder creates an empty CollectionBuilder.
func (*CollectionBuilder) AddMethodResource ¶
func (b *CollectionBuilder) AddMethodResource(scope accesstypes.PermissionScope, permission accesstypes.Permission, res accesstypes.Resource) error
AddMethodResource registers a method resource permission, rejecting duplicate registrations (generated RPC handlers).
func (*CollectionBuilder) AddResource ¶
func (b *CollectionBuilder) AddResource(scope accesstypes.PermissionScope, permission accesstypes.Permission, res accesstypes.Resource) error
AddResource registers a single resource permission, allowing duplicate registrations (the hand-written registration path).
func (*CollectionBuilder) AddResourceSet ¶
func (b *CollectionBuilder) AddResourceSet(scope accesstypes.PermissionScope, res accesstypes.Resource, set SetData) error
AddResourceSet registers a request struct's SetData under scope.
func (*CollectionBuilder) Data ¶
func (b *CollectionBuilder) Data() CollectionData
Data returns the canonical, deterministically sorted form of everything registered so far.
func (*CollectionBuilder) GeneratedCollection ¶
func (b *CollectionBuilder) GeneratedCollection() *GeneratedCollection
GeneratedCollection returns the built collection directly, for consumers that do not need the serializable form. The builder must not be used again afterward: the returned collection shares its storage.
func (*CollectionBuilder) SetMethodFormerName ¶
func (b *CollectionBuilder) SetMethodFormerName(scope accesstypes.PermissionScope, method, former accesstypes.Resource)
SetMethodFormerName records an RPC method resource's former name within scope: the name older browser applications still execute it under.
func (*CollectionBuilder) SetMethodTarget ¶
func (b *CollectionBuilder) SetMethodTarget(scope accesstypes.PermissionScope, method, target accesstypes.Resource)
SetMethodTarget records the row resource an RPC method's @target field addresses within scope.
func (*CollectionBuilder) SetMethodTransition ¶
func (b *CollectionBuilder) SetMethodTransition(scope accesstypes.PermissionScope, method accesstypes.Resource, transition TransitionData)
SetMethodTransition records an RPC method resource's declared state transition (@transition) within scope.
func (*CollectionBuilder) SetResourceBindings ¶
func (b *CollectionBuilder) SetResourceBindings(scope accesstypes.PermissionScope, res accesstypes.Resource, bindings *Bindings)
SetResourceBindings registers a resource's binding vocabulary, replacing any previous registration for that resource — the generator computes one vocabulary per resource.
func (*CollectionBuilder) SetResourceComputed ¶
func (b *CollectionBuilder) SetResourceComputed(scope accesstypes.PermissionScope, res accesstypes.Resource)
SetResourceComputed marks res as a computed resource within scope: one whose rows come from the application's Go function, so its permission checks run at decode time, and a grant's condition that reads the row is judged in Go over the rows the function yields, no query of the library's being there to judge it.
func (*CollectionBuilder) SetResourceListsAcrossTenants ¶ added in v0.5.0
func (b *CollectionBuilder) SetResourceListsAcrossTenants(res accesstypes.Resource)
SetResourceListsAcrossTenants marks res, a tenant's resource, as declared for listing across tenants (@listAcrossTenants).
func (*CollectionBuilder) SetResourceParent ¶
func (b *CollectionBuilder) SetResourceParent(scope accesstypes.PermissionScope, member, parent accesstypes.Resource)
SetResourceParent records a workflow member's immediate parent within scope: the resource its @stateRoot foreign key references.
func (*CollectionBuilder) SetResourceQueryKeys ¶
func (b *CollectionBuilder) SetResourceQueryKeys(scope accesstypes.PermissionScope, res accesstypes.Resource, order, queryKeys []accesstypes.Tag)
SetResourceQueryKeys records how a list of res is ordered and narrowed within scope: its declared default order and the fields a request may filter and sort by with an index behind it (see CollectionResource).
func (*CollectionBuilder) SetResourceRequiredTags ¶ added in v0.4.0
func (b *CollectionBuilder) SetResourceRequiredTags(scope accesstypes.PermissionScope, res accesstypes.Resource, required []accesstypes.Tag)
SetResourceRequiredTags records the fields a create of res must be given by the client within scope (see CollectionResource.RequiredTags). A tag that does not carry Create by the time the data is read is left out of it: no grant could name it.
type CollectionData ¶
type CollectionData struct {
Resources []CollectionResource
}
CollectionData is the stable, serializable description of a permission collection. It is the schema the generator emits into generated collection files and the input NewGeneratedCollection validates, decoupling generated code from the collection's internal representation.
type CollectionResource ¶
type CollectionResource struct {
Name accesstypes.Resource
Scope accesstypes.PermissionScope
// Computed marks a computed resource: one whose rows come from the
// application's Go function, with no query of the library's for the database
// to judge a row's condition in. The library judges the rows the function
// yields, in Go, against the Attributes below (each one's Column is the row
// struct's Go field), and deploy-time grant validation (access.MigrateRoles)
// uses the marker to name that declaration where a condition reads a field
// the resource has not declared.
Computed bool
Permissions []accesstypes.Permission
Tags []TagData
ImmutableTags []accesstypes.Tag
// Formerly is an RPC method resource's former name (@formerly on the method): the
// name older browser applications still execute it under, which the generated
// router answers at the former route and the permission digest mirrors beside the
// current name. Empty for a method never renamed and for every other resource.
Formerly accesstypes.Resource
// The resource's binding vocabulary (ABAC design plan §04), compiled from
// the field-level binding annotations: attributes conditions reference,
// the structural tenancy binding, and the subject-side vocabulary.
Attributes []AttributeData
Domain *DomainBindingData
SubjectSets []SubjectBindingData
SubjectValues []SubjectBindingData
// Transition is an RPC method resource's declared state transition
// (@transition, design plan §09); nil for everything else.
Transition *TransitionData
// Target is the row resource an RPC method's @target field addresses —
// set for every @target method, transition or plain (a transition's
// Target repeats its TransitionData.Target); empty for everything else.
// A targeted method's Execute grants may carry row-referencing
// conditions: the generated handler locates the row in its transaction
// and evaluates them there (design plan §12).
Target accesstypes.Resource
// Parent is a workflow member's immediate parent: the resource its
// @stateRoot foreign key references (the root, or another member on the
// chain); empty for everything else. The create-under-parent affordance
// (design plan §11) rides it: capabilities=Create on the parent's read
// answers, per row, which member resources the user may create beneath it.
Parent accesstypes.Resource
// How a list of the resource is ordered and narrowed, for a listed table
// or view resource. Order is the declared default order (@order), the
// fields every page sorts by when the request carries no sort; QueryKeys
// are the fields a request may name in a filter and sort by with an index
// behind it — the indexed and allow_filter fields — primary keys aside,
// which are exempt from masking. Deploy-time role validation
// (access.MigrateRoles) reads them with each tag's Masking to warn where a
// conditional grant puts a CASE in the ORDER BY or the WHERE.
Order []accesstypes.Tag
QueryKeys []accesstypes.Tag
// RequiredTags are the fields a create of the resource must be given by the
// client, as wire tags: the column takes no NULL, and neither a column default
// nor the server fills it (no default_create_fn, no key, no field the server
// owns). A create that leaves one out is refused at commit, so deploy-time role
// validation (access.MigrateRoles) reads them to warn where a role's Create
// grants on the resource cover none of its grants' fields for one: no holder of
// that role alone can create a row. Each is a tag of the resource that carries
// Create.
RequiredTags []accesstypes.Tag
// ListsAcrossTenants marks a tenant's resource declared for listing across
// tenants (@listAcrossTenants): its list is also served without the tenant's
// route segment. Only such a resource is decoded as a list across tenants
// (QueryDecoder.DecodeAcrossTenants), named to the page in the permission digest
// (WithListsAcrossTenants), or held as one live subscription over a set of
// tenants.
ListsAcrossTenants bool
}
CollectionResource describes one resource's registrations within a permission collection. RPC methods and manually registered resources carry only Permissions.
type Columns ¶
type Columns string
Columns is a string representing a comma-separated list of database column names.
type ComputedQueryDecoder ¶
type ComputedQueryDecoder[Resource Resourcer, Request any] struct { // contains filtered or unexported fields }
ComputedQueryDecoder decodes an HTTP request for a computed resource and enforces user permissions at decode time.
Computed resources execute application-written functions, so — like RPC methods — there is no library execution underneath them to carry the permission check: decode is the last library-controlled point before application code runs. QueryDecoder's deferred enforcement (discharged by QuerySet.Read/List) therefore cannot serve the computed path; this decoder checks eagerly instead, and the QuerySet it returns carries the request with the checks passed and the fields materialized. What is left for after the application's function is a grant's condition that reads the row: the QuerySet judges each row the function yields (computed_conditions.go).
func MustNewComputedQueryDecoder ¶
func MustNewComputedQueryDecoder[Resource Resourcer, Request any](dbType DBType, permissions ...accesstypes.Permission) *ComputedQueryDecoder[Resource, Request]
MustNewComputedQueryDecoder builds a query decoder for a computed resource and request pair over the application database's type (see NewComputedQueryDecoder). It panics on construction errors: they are programming errors (a request struct out of sync with its resource, a database type the package does not know), surfaced at application startup where generated handlers construct their decoders.
func NewComputedQueryDecoder ¶
func NewComputedQueryDecoder[Resource Resourcer, Request any](resSet *Set[Resource], dbType DBType) (*ComputedQueryDecoder[Resource, Request], error)
NewComputedQueryDecoder creates a new ComputedQueryDecoder for a given Resource and Request type. dbType is the application database's type: a computed list sorts and pages NULL where that database does, the same end as the tables beside it, so the decoder carries the placement even though no library query runs underneath it. An unsupported type is a construction error.
func (*ComputedQueryDecoder[Resource, Request]) Decode ¶
func (d *ComputedQueryDecoder[Resource, Request]) Decode(request *http.Request, userPermissions UserPermissions, scope accesstypes.Scope) (*QuerySet[Resource], error)
Decode decodes an http.Request into a QuerySet and checks user permissions in the given domain partition. The semantics mirror the deferred enforcement table resources get at execution time: a missing resource-level grant is Forbidden, an explicitly requested field without its grant is Forbidden, and when no fields are requested the QuerySet is narrowed to the fields some grant covers.
The checks are eager (application code produces the rows), and a grant under a condition is a grant, as on a table: the resource and the fields it covers pass here, and the Conditional decisions ride the QuerySet, which judges each row the application's function yields (QuerySet.Collect, QuerySet.Admit). A sort or filter field alone needs the caller's unconditional grant.
func (*ComputedQueryDecoder[Resource, Request]) WithCollection ¶ added in v0.3.0
func (d *ComputedQueryDecoder[Resource, Request]) WithCollection(collection *GeneratedCollection) *ComputedQueryDecoder[Resource, Request]
WithCollection installs the application's generated collection: the attributes the computed resource declares, which a grant's condition that reads the row resolves against. A decoder without one refuses such a grant when it is met.
func (*ComputedQueryDecoder[Resource, Request]) WithCursorKey ¶
func (d *ComputedQueryDecoder[Resource, Request]) WithCursorKey(key *CursorKey) *ComputedQueryDecoder[Resource, Request]
WithCursorKey installs the key that seals this decoder's cursors (see QueryDecoder.WithCursorKey).
func (*ComputedQueryDecoder[Resource, Request]) WithFeatures ¶
func (d *ComputedQueryDecoder[Resource, Request]) WithFeatures(features *FeatureSet) *ComputedQueryDecoder[Resource, Request]
WithFeatures installs the FeatureSet the gated fields' flags are read from (see QueryDecoder.WithFeatures).
func (*ComputedQueryDecoder[Resource, Request]) WithPaging ¶
func (d *ComputedQueryDecoder[Resource, Request]) WithPaging(paging Paging) *ComputedQueryDecoder[Resource, Request]
WithPaging installs the computed resource's declared paging contract (see QueryDecoder.WithPaging).
func (*ComputedQueryDecoder[Resource, Request]) WithSubjectFacts ¶ added in v0.3.0
func (d *ComputedQueryDecoder[Resource, Request]) WithSubjectFacts(source SubjectFactSource) *ComputedQueryDecoder[Resource, Request]
WithSubjectFacts installs the client the facts about the caller are read through: a grant's condition that compares a row against a subject value or a subject set (subject.<name>) has the fact read once for the request, when it is decoded. A decoder without one refuses such a grant when it is met.
type Condition ¶
type Condition struct {
Field string
Operator string
Value any // For eq, ne, gt, lt, gte, lte, startswith, endswith, contains, and the box's text
Values []any // For in, notin
IsNullOp bool // For isnull, isnotnull
// contains filtered or unexported fields
}
Condition represents a single condition (e.g., name:eq:John).
func (*Condition) IsSearch ¶
IsSearch reports whether the condition is the search box, *:search:"…".
func (*Condition) IsTextMatch ¶
IsTextMatch reports whether the condition is a startswith, endswith or contains match on a text field.
func (*Condition) MatchesText ¶
MatchesText evaluates a text match against a cell's text the way the handler evaluates it over a row: the text folded as the search index folds it, the term read for the field's role and folded the same way. A body that took the field answers its matches with it, since Take is all-or-nothing per field. False on any other condition.
func (*Condition) SearchFields ¶
SearchFields names the Go fields the box searches on the resource, in declaration order, for a body that took the box.
func (*Condition) SearchTerms ¶
SearchTerms returns the box's terms, the words the typed text split into, for a body that took the box and pushes it down itself.
func (*Condition) TypedValues ¶
TypedValues returns an in or notin list as a slice of the values' own type, the shape an array query parameter binds: Spanner types IN UNNEST(@p) from the slice's element type and refuses []any. The parser types every value by its column, so the slice is []string for a STRING column, []int64 for INT64, and []*big.Rat for NUMERIC, following paramValue. A value that carries its own Spanner encoding binds as what it encodes to, an id as its text: the client binds one such value and no array of them. A body that pushes a taken filter down to its own query binds the result as it is. An empty list, or one the values do not type uniformly, is returned unchanged.
type ConditionNode ¶
type ConditionNode struct {
Condition Condition
}
ConditionNode represents a simple condition in the AST.
func (*ConditionNode) String ¶
func (cn *ConditionNode) String() string
String returns a string representation of the ConditionNode.
type Config ¶
Config holds database-specific configuration for a resource.
func (Config) SetChangeTrackingTable ¶
SetChangeTrackingTable returns a new Config with the change tracking table name set.
func (Config) SetTrackChanges ¶
SetTrackChanges returns a new Config with the change tracking flag set.
type Content ¶
type Content struct {
// Name is the file's name, sent as the Content-Disposition's filename and, with
// no ContentType, the source of the type by extension.
Name string
// ContentType is the media type sent; empty defers to the name's extension, then
// to application/octet-stream.
ContentType string
// Size is the body's length in bytes, -1 when unknown.
Size int64
// ModTime is the file's last modification, the zero time when unknown.
ModTime time.Time
// Tag is the validator a rendered document sends as its ETag, quoted by the frame
// when it is not; empty sends none, and the outlet's caching headers stand. A stored
// file's validator is its key, set by the frame.
Tag string
// Body is the bytes. A body that also seeks is served with range support; any
// other is copied. The frame closes it.
Body io.ReadCloser
}
Content is a file as the frame serves it: a stored object as the FileStore opened it, or the document a computed resource's content function rendered. Every field but the body is optional; the frame fills what it can from the row and the name.
type CursorKey ¶
type CursorKey struct {
// contains filtered or unexported fields
}
CursorKey seals and opens list cursors. An application builds one from its cookie key (NewCursorKey) and hands it to every query decoder (QueryDecoder.WithCursorKey); a decoder without one refuses paging past the first page.
func NewCursorKey ¶
NewCursorKey derives the cursor sealing key from the application's base64-encoded cookie key, the value the session library is configured with.
type DBType ¶
type DBType string
DBType represents the type of database, such as Spanner or PostgreSQL.
type DataChangeEvent ¶
type DataChangeEvent struct {
TableName accesstypes.Resource `spanner:"TableName"`
RowID string `spanner:"RowId"`
Sequence int `spanner:"Sequence"`
EventTime time.Time `spanner:"EventTime"`
EventSource string `spanner:"EventSource"`
ChangeSet spanner.NullJSON `spanner:"ChangeSet"`
}
DataChangeEvent represents a record of a change made to a database table.
func (DataChangeEvent) PatchType ¶
func (DataChangeEvent) PatchType() PatchType
PatchType returns the PatchType for DataChangeEvent
func (*DataChangeEvent) PrimaryKey ¶
func (d *DataChangeEvent) PrimaryKey() KeySet
PrimaryKey returns an empty key set since this resource is only used for inserts, not deletes.
func (DataChangeEvent) Resource ¶
func (DataChangeEvent) Resource() accesstypes.Resource
Resource returns the Resource name for DataChangeEvent
type Decoder ¶
Decoder is a struct that can be used for decoding http requests and validating those requests
func MustNewDecoder ¶
func MustNewDecoder[Resource Resourcer, Request any](a DecoderAccessor, collection *GeneratedCollection, permissions ...accesstypes.Permission) *Decoder[Resource, Request]
MustNewDecoder builds a patch decoder for a resource and request pair, validating requests with the accessor's validator and wired to the application's generated collection so conditional grants can render into the mutations' live check. It panics on construction errors: they are programming errors (a request struct out of sync with its resource), surfaced at application startup where generated handlers construct their decoders.
func NewDecoder ¶
func NewDecoder[Resource Resourcer, Request any](rSet *Set[Resource]) (*Decoder[Resource, Request], error)
NewDecoder creates a new Decoder for a given Resource and Request type.
func (*Decoder[Resource, Request]) DecideOperation ¶ added in v0.4.0
func (d *Decoder[Resource, Request]) DecideOperation(ctx context.Context, txn ReadWriteTransaction, oper *Operation, userPermissions UserPermissions, scope accesstypes.Scope, key KeySet) (*Operation, error)
DecideOperation answers the operation a patch-or-add runs as: the patch when the row its path names is there, the add when it is not. The handler then decodes and runs that operation as it does any patch or add.
A patch-or-add is an update first: the caller's Update grant on the resource is asked for before the row is looked for, so a caller who may not update is refused the same way whether or not the row is there, and learns nothing from the answer. Which fields the caller may write, and on which rows, is the decoded operation's own check.
The read is the one an OrCreate patch makes (patch_fork.go): the key alone, inside the transaction, held to the tenant in a tenant's scope, after the transaction's own record of the rows it wrote, so an earlier operation of the same batch counts.
func (*Decoder[Resource, Request]) Decode ¶
func (d *Decoder[Resource, Request]) Decode(request *http.Request, userPermissions UserPermissions, scope accesstypes.Scope, requiredPermission accesstypes.Permission) (*PatchSet[Resource], error)
Decode decodes an http.Request into a PatchSet and enables user permission enforcement in the given domain partition.
func (*Decoder[Resource, Request]) DecodeOperation ¶
func (d *Decoder[Resource, Request]) DecodeOperation(oper *Operation, userPermissions UserPermissions, scope accesstypes.Scope) (*PatchSet[Resource], error)
DecodeOperation decodes an Operation into a PatchSet and enables user permission enforcement in the given domain partition.
func (*Decoder[Resource, Request]) DecodeOperationWithoutPermissions ¶
func (d *Decoder[Resource, Request]) DecodeOperationWithoutPermissions(oper *Operation) (*PatchSet[Resource], error)
DecodeOperationWithoutPermissions decodes an Operation into a PatchSet without enforcing user permissions.
func (*Decoder[Resource, Request]) DecodeWithoutPermissions ¶
func (d *Decoder[Resource, Request]) DecodeWithoutPermissions(request *http.Request) (*PatchSet[Resource], error)
DecodeWithoutPermissions decodes an http.Request into a PatchSet without enforcing any user permissions.
func (*Decoder[Resource, Request]) WithFeatures ¶
func (d *Decoder[Resource, Request]) WithFeatures(features *FeatureSet) *Decoder[Resource, Request]
WithFeatures installs the FeatureSet the decoder reads the gated fields' flags from; the generated wiring passes the application's. Without it every gated field stays hidden.
func (*Decoder[Resource, Request]) WithValidator ¶
func (d *Decoder[Resource, Request]) WithValidator(v ValidatorFunc) *Decoder[Resource, Request]
WithValidator sets the validator function for the Decoder.
type DecoderAccessor ¶
type DecoderAccessor interface {
Validator() ValidatorFunc
UserPermissions(r *http.Request) UserPermissions
}
DecoderAccessor is the application seam the Must* decoder constructors draw on: the request validator and the per-request user permissions. Generated application code implements and consumes it via the generated decoder constructors.
type DefaultsFunc ¶
type DefaultsFunc func(ctx context.Context, txn ReadWriteTransaction) error
DefaultsFunc is the signature for a function that applies default values to a PatchSet.
type Demonstration ¶
Demonstration is one capability of the resource package a demonstration application proves. The key is the vocabulary an application declares against: the annotation, option, grammar function, or API name where one exists, a short coined slug where none does. A demonstration application ends the doc comment of every struct, method, test, component, and persona row that proves a key with a "Demonstrates: key, key." paragraph, and a test in the application fails when a key here has no declaration in code or in a test, when a declaration names a key not here, or when a README example link points at a file that does not declare the key its row documents. The same test writes the generated key-to-files table (lodestar/DEMONSTRATIONS.md).
type DiffElem ¶
type DiffElem struct {
Old any
New any
// Secret marks the change of a secret field, whose values are not kept. Its key is
// spelled as Old and New are, which carry no tag and so are stored under their names.
Secret bool `json:",omitempty"` //nolint:tagliatelle // a change record's keys are Old, New and Secret
}
DiffElem represents the old and new values of a field that has been changed. A field that holds a secret (conditions:"secret" on the resource struct) is recorded as changed with neither value: Secret is set, and Old and New stay empty, so a change record says that a password or a key was set and never what it was or is.
type DigestOption ¶
type DigestOption func(*digestOptions)
DigestOption configures PermissionDigestHandler.
func WithFeatureGates ¶
func WithFeatureGates(gates FeatureGates, features *FeatureSet) DigestOption
WithFeatureGates filters the digest by the feature flags: an entry for a gated resource, one of its fields, or a gated RPC method is left out while the flag is off, so the frontend never renders a surface the routes would answer 404 for. The gates are the generated declaration (FeatureGates()), the features the application's FeatureSet.
func WithFormerNames ¶
func WithFormerNames(names FormerNames) DigestOption
WithFormerNames mirrors the entry of every renamed field or method under its former name too, with the same states: an application built before the rename asks the digest for the name it knows, and keeps its column or its action while the server still answers it. The names are the generated collection's (Collection()). A former name already present in the digest is left as the engine answered it.
func WithListsAcrossTenants ¶ added in v0.5.0
func WithListsAcrossTenants(lists AcrossTenantsLists) DigestOption
WithListsAcrossTenants adds, to the digest of the global scope, the answer a page that lists a resource across tenants is shown by: each resource declared for it carries ListAcrossTenants, granted, while the person may list it in at least one tenant the session reaches (ListedInSomeTenant), and is left as it was otherwise. The resources are the generated collection's (Collection()). A tenant's digest is untouched: it speaks for that tenant alone.
type DirectoryNamer ¶ added in v0.5.0
DirectoryNamer answers what the sign-in registrations of one auth call a directory: name is the name a registration that takes the directory's connection gives it, "" where none names it, and label is the label of the button of the registration a person signs in to it through, "" where the auth's login page offers none. The generated identity client of an auth supplies it (DirectoryName), from the session library's own answer (session.AuthAPI.DirectoryName); an application names none.
type DirectoryOnlyState ¶ added in v0.5.0
type DirectoryOnlyState struct {
DirectoryOnly bool `json:"directoryOnly"`
}
DirectoryOnlyState is a tenant's directory-only switch as it stands.
type DirectoryOutsider ¶ added in v0.5.0
type DirectoryOutsider struct {
// UserID is the id of the person's account, and Username what identifies them.
UserID impulse.UUID `json:"userId"`
Username string `json:"username"`
// Name is the person's name as people read it, absent where the account holds none.
Name *string `json:"name,omitempty"`
}
DirectoryOutsider is a person who holds a seat in a tenant, has never signed in through the tenant's directory and has no other way in: someone the tenant's directory-only switch keeps out for as long as it is on.
type DirectoryOutsiders ¶ added in v0.5.0
type DirectoryOutsiders func(ctx context.Context, txn ReadWriteTransaction, tenant accesstypes.Domain) ([]DirectoryOutsider, error)
DirectoryOutsiders reads the people of one auth who hold a seat in tenant, in the tenant itself or in every tenant, and have no sign-in through the tenant's directory, in the caller's transaction. A super administrator is left out: no tenant's sign-in settings shut them out. So is the tenant's own administrator who has a password: they enter with it and a second factor (signin.TenantDeclaration.AdmitsAdministrator), and lose nothing. The generated identity client of each auth whose people a tenant seats supplies it (DirectoryOutsiders), over the tenant's own list of its people; an application names none of them.
type DirectoryPeople ¶ added in v0.5.0
type DirectoryPeople struct {
// List is the tenant's list of the auth's people as grants name it, and Fields the
// fields of it that name a person: the ones the warning lists a person by
// (DirectoryOutsider).
List accesstypes.Resource
Fields []accesstypes.Tag
// Outsiders reads the people the switch would keep out.
Outsiders DirectoryOutsiders
// AdministratorsEnter says the auth's people keep the administrators' way in: the
// auth has a password method and names the roles that administer a tenant, so the
// tenant's own administrator who has a password still enters, with a code mailed to
// them. The warning says so, since it is the one other way into the tenant.
AdministratorsEnter bool
}
DirectoryPeople is one auth's part of what turning a tenant's directory-only switch on would do: the reader of the people it would keep out, and the tenant's list of that auth's people, which decides whether the caller is told who they are. The warning names people only to someone who may list them: a caller who holds List, in the tenant, on the list and, on no condition, on each field of it that names a person. Anyone else is told how many there are and nobody's name. A reader with no list, or with no field named, names nobody.
type DomainBindingData ¶
type DomainBindingData struct {
Column string
Path []BindingHop
}
DomainBindingData is the structural tenancy binding: how every row of a domain-scoped resource resolves to its tenant. Column is the tenant-key column itself when Path is empty, or the foreign key the path to it leaves through. It is deliberately not an attribute — tenancy injection consumes it, and conditions can never reference it.
type DomainNamer ¶ added in v0.4.0
type DomainNamer interface {
Name(domain accesstypes.Domain) string
}
DomainNamer answers a tenant's name, "" for one it holds none for: the tenant roster (TenantRoster.Name), which reads the tenant record's name column beside its keys.
type DomainRoster ¶
type DomainRoster func(ctx context.Context) ([]accesstypes.Domain, error)
DomainRoster lists the application's tenant domains: the roster the tenant picker is filtered from. A tenanted application passes its TenantRoster's Domains, which has this signature and answers from the roster's set; an application without tenants passes nil to SessionPermissions, and its sessions list no domain.
type ExecuteGate ¶
type ExecuteGate struct {
// contains filtered or unexported fields
}
ExecuteGate carries one request's Execute decision to the generated frame. A nil condition (the grant was unconditional) enforces nothing.
func (*ExecuteGate) Caller ¶
func (g *ExecuteGate) Caller() *Caller
Caller returns the caller the decode-time check ran as — checker, scope, sampled environment, and the collection — for the handler to stamp into the context the method's body runs under.
func (*ExecuteGate) Enforce ¶
func (g *ExecuteGate) Enforce(ctx context.Context, txn ReadWriteTransaction, target ExecuteTarget, pkValues ...any) error
Enforce evaluates the carried condition against the target row inside the frame's transaction: one check-SELECT locating the row by key, its single boolean the condition lowered against the target resource's bindings, bound to the same @subject, @now, and @domain the permission check folded with. A false or NULL answer is Forbidden with the frame's uniform refusal — the wire never says whether the state or the condition refused. The frame has located a table's row before it calls Enforce, so a grant with no condition enforces nothing; a view's row is located by EnforceView instead.
func (*ExecuteGate) EnforceProposed ¶ added in v0.5.0
func (g *ExecuteGate) EnforceProposed(ctx context.Context, facts SubjectFactSource, target ExecuteTarget, row map[string]any) error
EnforceProposed judges the carried condition against a row the body proposes, where the database holds no row to locate: a role a person holds through a group is no row of the list of the roles held, and the method that takes a role away is granted on the rows of that list. row holds the target's attributes by the names a condition reads them, the target's @attribute declarations, each as the value the condition language compares (a string, an int64, a float64, a bool, a time.Time or a condition.Date, nil for no value).
The condition is judged by the language's own evaluator (condition.Evaluate), the statement of its meaning that the SQL rendering is held to, with the caller and the decision instant the permission check folded with. A fact about the caller that is held in a table (subject.<name>) is read through facts, the body's transaction. A false or unknown answer is the frame's uniform refusal, and a grant with no condition enforces nothing. A condition that reads an attribute row does not carry is generated code out of step with the library, and fails as that.
func (*ExecuteGate) EnforceView ¶ added in v0.3.0
func (g *ExecuteGate) EnforceView(ctx context.Context, txn ReadWriteTransaction, target ExecuteTarget, pkValues ...any) error
EnforceView is the whole located-row check for a target that is a row of a view. One SELECT in the frame's transaction does both halves: it selects from the view's query by the key and, for a tenant-scoped view, the request's tenant, and its single boolean is the carried condition lowered against the view's bindings — TRUE where the grant carries none, since the row still has to be found. No row is the NotFound a missing row and another tenant's row share; a false or NULL answer is the frame's uniform refusal. A key that names more than one row there is a fault of the view's query, never a row to pick between, and fails as one.
func (*ExecuteGate) Settled ¶ added in v0.5.0
func (g *ExecuteGate) Settled() (granted, settled bool)
Settled reports what the gate decides before any row is read. settled is true where nothing of the grant's condition is left to judge against the target row: the grant carries no condition, or its condition read the request's fields alone, and granted says which way it went. Where settled is false the decision is the row's to make (Enforce, EnforceView, EnforceProposed).
func (*ExecuteGate) VerifyTenancy ¶
func (g *ExecuteGate) VerifyTenancy(ctx context.Context, txn ReadWriteTransaction, target ExecuteTarget, pkValues ...any) error
VerifyTenancy confirms the located target row resolves to the request's domain, for a target whose @domain binding leaves through a join path — a bare-column binding is read off the located row in the generated frame instead (resource.TenantKeyEquals), so the row itself carries no tenant key here. One SELECT in the frame's transaction: the tenancy predicate rendered from the Collection's domain binding as a single boolean, the row located by its primary key. A missing row and a cross-tenant row are the same NotFound the locate step answers — a row outside the caller's tenant never reveals it exists.
type ExecuteTarget ¶
type ExecuteTarget struct {
// Resource is the target row resource: its table, or the view's resource.
Resource accesstypes.Resource
// Label is the target's struct name, for the refusal message — the same
// words the frame's own state check refuses with, so the wire never
// distinguishes a wrong-state refusal from a condition refusal.
Label string
// PKColumns are the primary-key columns the check-SELECT locates the row by,
// in the key's order: one for a single-column key, each column of a compound
// one. The key values the gate is handed follow the same order.
PKColumns []string
// View is the target's query when the target is a row of a view (a @virtual
// struct): the struct's own value, whose Subquery the check-SELECT selects
// from under the resource's name, as the view's lists and reads do. Nil for
// a table.
View interface {
Subquery() (query string, params map[string]any)
}
}
ExecuteTarget describes the located row an ExecuteGate evaluates against. The generated frame supplies it from generation-time facts.
type Executor ¶
type Executor interface {
ExecuteFunc(ctx context.Context, f func(ctx context.Context, txn ReadWriteTransaction) error) error
}
Executor interface exposes ability to run a function inside a transaction.
type ExpressionNode ¶
type ExpressionNode interface {
// String returns a string representation of the node (for debugging/testing).
String() string
}
ExpressionNode represents a node in the filter AST.
type Feature ¶
type Feature string
Feature names a feature flag. An application declares its flags as constants of this type in its resources package, each with a doc comment that is the flag's description, and gates a resource, a field or an RPC method with @feature(<Constant>). The generator collects the declarations into Features(), the deploy step writes them into the FeatureFlags table (MigrateFeatures), and the running application reads the table into a FeatureSet the gated routes, decoders and the permission digest consult.
A flag's value is its name as the table holds it: lowercase letters, digits and underscores, opening with a letter, at most 64 characters.
type FeatureApp ¶
type FeatureApp interface {
DecoderAccessor
ResourceClient() Client
CursorKey() *CursorKey
FeatureSet() *FeatureSet
}
FeatureApp is the application surface the feature flag handlers draw on: the decoder seam, the database client, the cursor key the flags' list pages with, and the FeatureSet the application loaded at start.
type FeatureDeclaration ¶
FeatureDeclaration is one declared flag: its name, the description the dialog shows, and the constant that declared it.
type FeatureFlag ¶
type FeatureFlag struct {
Name string `json:"name" spanner:"Name"`
Description string `json:"description" spanner:"Description"`
Enabled bool `json:"enabled" spanner:"Enabled"`
UpdatedAt time.Time `json:"updatedAt" spanner:"UpdatedAt"`
UpdatedBy string `json:"updatedBy" spanner:"UpdatedBy"`
}
FeatureFlag is a row of the FeatureFlags table, and the resource the FeatureFlags routes serve.
func (FeatureFlag) DefaultConfig ¶
func (FeatureFlag) DefaultConfig() Config
DefaultConfig tracks no changes through the change-tracking table: the flips are audited in FeatureFlagChanges, in the same transaction.
func (FeatureFlag) Resource ¶
func (FeatureFlag) Resource() accesstypes.Resource
Resource names the table.
type FeatureGates ¶
type FeatureGates map[accesstypes.Resource]Feature
FeatureGates is what the generated code declares gated, keyed the way the permission digest keys its entries: a resource or RPC method by its name, a field by "<Resource>.<field>". A gated-off resource takes its fields with it.
func (FeatureGates) Off ¶
func (g FeatureGates) Off(features *FeatureSet, key accesstypes.Resource) bool
Off reports whether the digest key is behind a flag that is off: its own flag, or its resource's flag for a field key.
type FeatureOption ¶
type FeatureOption func(*FeatureSet)
FeatureOption configures a FeatureSet at load.
func WithFeatureBackstop ¶
func WithFeatureBackstop(d time.Duration) FeatureOption
WithFeatureBackstop sets how often Follow rereads the table without a signal; FeatureBackstop by default. Tests shorten it.
type FeatureSet ¶
type FeatureSet struct {
// contains filtered or unexported fields
}
FeatureSet is one instance's copy of the FeatureFlags table: what the gated routes, the decoders and the permission digest consult. LoadFeatures reads it once at start; Follow keeps it current on the features signals and the backstop; Reload rereads it now. A nil FeatureSet answers every flag off, so an application that wires none fails closed on every gate. It is safe for concurrent use.
func LoadFeatures ¶
func LoadFeatures(ctx context.Context, db Client, opts ...FeatureOption) (*FeatureSet, error)
LoadFeatures reads the FeatureFlags table into a FeatureSet.
func (*FeatureSet) Enabled ¶
func (s *FeatureSet) Enabled(name Feature) bool
Enabled reports whether the flag is on. A flag the table does not hold, and every flag of a nil FeatureSet, is off.
func (*FeatureSet) EnabledNames ¶
func (s *FeatureSet) EnabledNames() []string
EnabledNames lists the flags that are on, sorted: the features route's answer.
func (*FeatureSet) Flag ¶
func (s *FeatureSet) Flag(name Feature) (FeatureFlag, bool)
Flag returns the flag's row and whether the table holds it.
func (*FeatureSet) Follow ¶
func (s *FeatureSet) Follow(ctx context.Context, signals SignalSubscriber) error
Follow keeps the copy current until ctx ends: it rereads the table on every signal of KindFeatures the subscriber delivers, and at the backstop interval regardless, the backstop being the correctness guard should a signal be missed. The subscriber is the application's live service, which every application wires; nil is refused. A failed reread is logged and the copy stays as it was until the next.
type FeaturesResponse ¶
type FeaturesResponse struct {
Enabled []string `json:"enabled"`
}
FeaturesResponse is the features route's answer: the names of the flags that are on.
type FieldDefaultFunc ¶
type FieldDefaultFunc func(ctx context.Context, txn ReadWriteTransaction) (any, error)
FieldDefaultFunc is the signature for a function that applies a default value to one field of a PatchSet.
func DefaultString ¶
func DefaultString(v string) FieldDefaultFunc
DefaultString returns a FieldDefaultFunc that provides the given string value.
type FieldTags ¶
type FieldTags struct {
Field accesstypes.Field
JSON string // json tag name (first comma-separated part); "" or "-" is unregistered
Perm string // raw perm tag value; "" (enforced) or "-" (primary-key exemption) are the only legal values
Immutable bool // immutable:"true"
Masking string // raw masking tag value; "" (concealing) or "positional" are the only legal values
SQLType string // raw sqltype tag value, the column's declared Spanner type; "" where the decoder sizes nothing
Nullable string // raw nullable tag value; "" or "true" are the only legal values, and true only on a slice-typed field
Feature string // raw feature tag value, the flag the field is gated behind; "" where the field is not gated
Formerly string // raw formerly tag value, the field's former wire name; "" where the field was never renamed
}
FieldTags describes the registration-relevant struct tags of a single request-struct field. It is the shared input for permission collection: the runtime path builds it by reflecting over generated request structs, and the generator builds it from the same tag values it writes into those structs, so both paths flow through identical logic.
func FeatureFlagFieldTags ¶
func FeatureFlagFieldTags() []FieldTags
FeatureFlagFieldTags are the FeatureFlags routes' field registrations, the way the generator registers a generated resource's: what a List or Read grant on FeatureFlags may name. The generator registers them into every application's collection.
func FieldTagsFromStructTag ¶
func FieldTagsFromStructTag(field accesstypes.Field, tag reflect.StructTag) FieldTags
FieldTagsFromStructTag extracts the registration-relevant values from a struct tag: the runtime path (permissionsFromTags) calls it directly on a reflected field's tag, and the generator's static path (fieldTagsFromTemplateTags) assembles an equivalent reflect.StructTag from the same fragments the templates render, so both share this exact parsing and can never disagree on it.
type File ¶
type File struct {
// Key is the store key the frame minted; the body records it in a @file column of
// the default store, and the transaction's commit is what claims it. Empty on a
// dry run, which streams nothing.
Key string
// Name is the part's filename as the client sent it.
Name string
// ContentType is the part's declared media type, application/octet-stream
// (octetStream) when the client declared none. It is recorded as declared, the
// uploader's word: the @file route sends it as the Content-Type under nosniff and
// decides from it whether the file displays inline or downloads (file.go).
ContentType string
// Size is the part's length in bytes.
Size int64
}
File describes one uploaded part as the body receives it, in the default store.
type FileDecoder ¶
type FileDecoder[Resource Resourcer, Request any] struct { // contains filtered or unexported fields }
FileDecoder gates one @file route of a resource. It checks Read on the resource and on the route's own field, the segment, exactly as the read route checks its fields, and returns the QuerySet that locates the row through the resource's read path with the caller's Read conditions and tenancy, projecting only what the frame needs to deliver the file: the key, the store key, the name, and the type, every one read for the frame itself without a field grant. Request is that projection, a struct of the resource's fields the generated handler declares with perm:"-" throughout.
func MustNewComputedFileDecoder ¶
func MustNewComputedFileDecoder[Resource Resourcer, Request any](collection *GeneratedCollection, segment string) *FileDecoder[Resource, Request]
MustNewComputedFileDecoder is NewComputedFileDecoder for the generated handlers; a construction error panics at application startup.
func MustNewFileDecoder ¶
func MustNewFileDecoder[Resource Resourcer, Request any](collection *GeneratedCollection, segment string) *FileDecoder[Resource, Request]
MustNewFileDecoder is NewFileDecoder for the generated handlers, which construct their decoders at application startup: a construction error is a programming error (a request struct out of sync with its resource) and panics.
func NewComputedFileDecoder ¶
func NewComputedFileDecoder[Resource Resourcer, Request any](collection *GeneratedCollection, segment string) (*FileDecoder[Resource, Request], error)
NewComputedFileDecoder builds the decoder for a computed resource's @file route. A computed resource executes application code, so the gate is checked at decode. A Read grant under a condition that reads the row passes it, as on a table, and the QuerySet judges the row the application's read function answers (QuerySet.Admit), against the attributes the collection holds for the resource.
func NewFileDecoder ¶
func NewFileDecoder[Resource Resourcer, Request any](collection *GeneratedCollection, segment string) (*FileDecoder[Resource, Request], error)
NewFileDecoder builds the decoder for a table or view resource's @file route: the Set over the frame's projection, and the collection that renders a conditional Read grant into the row's statement.
func (*FileDecoder[Resource, Request]) Decode ¶
func (d *FileDecoder[Resource, Request]) Decode(request *http.Request, userPermissions UserPermissions, scope accesstypes.Scope) (*QuerySet[Resource], error)
Decode checks the gate and returns the QuerySet that reads the row. Read on the resource and on the segment field are checked in one call, as the read route checks its base and its fields: a Denied decision on either is Forbidden in the read route's words, a Conditional one on the segment is the row condition the statement renders, so a row the condition does not admit is 404 as on the read route. A computed resource's conditions are judged over the row its read function answers, to the same end. The request's query string is not read: the route takes no parameters.
func (*FileDecoder[Resource, Request]) Segment ¶
func (d *FileDecoder[Resource, Request]) Segment() accesstypes.Tag
Segment is the route's own field: the tag a Read grant names to open the route.
func (*FileDecoder[Resource, Request]) WithSubjectFacts ¶ added in v0.3.0
func (d *FileDecoder[Resource, Request]) WithSubjectFacts(source SubjectFactSource) *FileDecoder[Resource, Request]
WithSubjectFacts installs the client the facts about the caller are read through on a computed resource's route (ComputedQueryDecoder.WithSubjectFacts). A table's route needs none: its statement reads them beside the row.
type FileHolder ¶
type FileHolder struct {
// Resource is the resource holding the keys.
Resource accesstypes.Resource
// Keys are the key columns, each with the store its keys name.
Keys []FileKey
// Computed marks a computed resource: its rows come from application code and there
// is no table to read, so the cleanup needs the application to supply its keys, or
// it refuses.
Computed bool
// contains filtered or unexported fields
}
FileHolder is a resource that records stored files' keys: the @file key columns, each with its store, and how the orphaned-file cleanup reads the keys they hold. The generator writes one per resource with a stored @file into the resources package's FileHolders(), and an application's job process hands every package's list to the cleanup.
func ComputedFileHolder ¶
func ComputedFileHolder(res accesstypes.Resource, keys ...FileKey) FileHolder
ComputedFileHolder declares a computed resource with a stored @file as a holder whose keys the application supplies. The generated FileHolders calls it.
func FileHolderOf ¶
func FileHolderOf[R Resourcer]() FileHolder
FileHolderOf declares a table resource as a holder of stored files, its key columns read from the generated FileKeys. The generated FileHolders calls it.
func (FileHolder) HeldKeys ¶
HeldKeys reads every key the holder's columns of the given store hold, each column read once, through a strong read on the client, NULL and empty keys left out. It returns an error for a computed holder, whose keys the application supplies.
func (FileHolder) Stores ¶
func (h FileHolder) Stores() []StoreName
Stores lists the distinct stores the holder's key columns name, in column order.
type FileIn ¶
type FileIn[S NamedStore] struct { // Key is the store key the frame minted, typed by the store. Empty on a dry run. Key Key[S] // Name is the part's filename as the client sent it. Name string // ContentType is the part's declared media type, application/octet-stream when // the client declared none; the uploader's word, as File.ContentType is. ContentType string // Size is the part's length in bytes. Size int64 }
FileIn describes one uploaded part as the body receives it, in the named store S: File with its Key typed Key[S], so the body records it in a column of that store and nowhere else, since the generated setter of any other column refuses the type.
type FileKey ¶
type FileKey struct {
Field accesstypes.Field
Store StoreName
}
FileKey is one @file key column of a resource and the store its keys name: what the generated FileKeys method declares, one per field-scope @file, so the release after a commit and the orphaned-file cleanup know which store each key belongs to.
type FileRoute ¶
type FileRoute struct {
// Kind is FileRouteUpload or FileRouteStored.
Kind string `json:"kind"`
// Method is the HTTP method the route answers: POST for an upload, GET for a stored
// file.
Method string `json:"method"`
// Path is the route as the router mounts it, under its outlet's prefix, with its
// parameters in braces (/api/photos/{id}/file).
Path string `json:"path"`
// Source names the declaration the route comes from: the method's struct
// (AttachPhoto) or the resource and its key column (Photo.Key).
Source string `json:"source"`
}
FileRoute is one route in the release file that carries a file rather than JSON: an @upload method's route, whose body is multipart, or a stored file's read route (@file on a key column), whose answer is the object. The application's stack reads them to put each ahead of its web application firewall's rules: a body of bytes trips rules written for text, so the route is matched before the rules and never evaluated by them, and the rule the stack writes names the declaration here.
type FileStore ¶
type FileStore interface {
Put(ctx context.Context, key string, contentType string, r io.Reader) error
Delete(ctx context.Context, keys []string) error
Open(ctx context.Context, key string) (*Content, error)
}
FileStore is a file store as the frame drives it: the framework's stores (resource/filestore: a Cloud Storage bucket, a directory, memory) or one an application writes. Put writes one object under a key the frame minted, permanently: an @upload method's frame Puts each part before the body runs, and the transaction claims the keys by recording them in @file columns; on any failure before commit the frame Deletes the keys it streamed and answers with the failure, so an object with no claiming row is left only by a crash between the two, and that one is the orphaned-file cleanup's (an object no row claims, older than the application's window). Open reads one object back for a @file route, ErrFileNotFound when nothing is stored under the key.
The rules every store follows. A failed Put leaves no object: a write the store could not finish is removed before the error returns, and the frame deletes the key besides. Deleting a key that holds no object succeeds. A key is any safe relative object name: non-empty, at most 1024 bytes, no leading slash, no empty, dot or dot-dot segment, and no backslash or control character; the upload frame mints UUIDs, which is a fact about the frame and not a check in the store, so an adopter with existing files may pass its rows' names as keys. A missing object on Open is ErrFileNotFound; a refused permission is any other error, answered 500 and never 404. The root package imports no object-store SDK; the stores do.
type Files ¶
type Files []File
Files is the uploaded parts, in the order they were sent, in the default store.
type FilesIn ¶
type FilesIn[S NamedStore] []FileIn[S]
FilesIn is the uploaded parts, in the order they were sent, in the named store S: what an @upload(store: S) method's Execute takes third.
func StreamInto ¶
func StreamInto[S NamedStore](ctx context.Context, u *Upload, store FileStore, dryRun bool) (FilesIn[S], error)
StreamInto is Upload.Stream for an @upload(store: S) method: the parts stream to the named store's FileStore, read off the resource client under StoreNameFor[S], and the body receives them typed by the store.
type FilterFieldInfo ¶
type FilterFieldInfo struct {
JSONFieldName string
GOFieldName string
Kind reflect.Kind
FieldType reflect.Type
Indexed bool
PII bool
// Positional marks a field declared masking:"positional": a filter on it
// compares the raw column even where the caller's grant is conditional.
Positional bool
// Search is the field's search tag, read back from the request struct: the matches
// it answers and the columns they render through, and whether it joins the box. Nil
// on a field with neither fact.
Search *SearchSpec
// contains filtered or unexported fields
}
FilterFieldInfo holds metadata about a field that can be used in a filter.
func (*FilterFieldInfo) ColumnName ¶
func (f *FilterFieldInfo) ColumnName(dbType DBType) (string, error)
ColumnName returns the column name for the given DBType.
type FilterLexer ¶
type FilterLexer struct {
// contains filtered or unexported fields
}
FilterLexer parses the filter producing tokens
func NewFilterLexer ¶
func NewFilterLexer(input string) *FilterLexer
NewFilterLexer creates a new lexer for the given input filter string.
func (*FilterLexer) NextToken ¶
func (l *FilterLexer) NextToken() (Token, error)
NextToken returns the next token from the input string.
func (*FilterLexer) Reset ¶
func (l *FilterLexer) Reset()
Reset resets the lexer to its beginning state so it can be used again
type FilterParser ¶
type FilterParser struct {
// contains filtered or unexported fields
}
FilterParser builds an AST from tokens.
func NewFilterParser ¶
func NewFilterParser(lexer *FilterLexer, jsonToFieldInfo map[jsonFieldName]FilterFieldInfo) (*FilterParser, error)
NewFilterParser creates a new parser with the given lexer and field information map.
func (*FilterParser) Parse ¶
func (p *FilterParser) Parse(dbType DBType) (ExpressionNode, error)
Parse is the main entry point for parsing the filter string.
func (*FilterParser) ParseFields ¶
func (p *FilterParser) ParseFields() (ExpressionNode, error)
ParseFields parses the filter with every condition named by Go field, for evaluation against rows in memory rather than rendering into SQL.
func (*FilterParser) WithSearch ¶
func (p *FilterParser) WithSearch(branches []SearchBranch, keys map[DBType]string) *FilterParser
WithSearch hands the parser the resource's @searchAlso branches and its key column per parse target (the Go field under the in-memory target), which a *:search condition carries into the statement. The decoders pass them from the resource's metadata; a parser without them serves a resource that declares no branch.
func (*FilterParser) WithZone ¶
func (p *FilterParser) WithZone(zone *time.Location) *FilterParser
WithZone hands the parser the person's time zone, read from the request's Time-Zone header, which a written date or time with no zone of its own is read in (zoneFor). A parser without one reads such a value in the column's declared zone, and in UTC where the column declares none.
type FilterShape ¶
type FilterShape struct {
// contains filtered or unexported fields
}
FilterShape is the request's filter over Go field names, as a computed resource's List function and its generated handler share it. The body may take the conditions it will apply in its own queries; the handler evaluates whatever was not taken against every row the body yields (Match), so a body that takes nothing is correct by default and a body that takes part is never wrong. Take is defined on a conjunction: a filter carrying OR takes nothing, and the handler evaluates the whole tree.
func (*FilterShape) Conditions ¶
func (f *FilterShape) Conditions() []Condition
Conditions lists every condition in the filter, taken or not, in source order.
func (*FilterShape) Fields ¶
func (f *FilterShape) Fields() []string
Fields names the fields the filter touches, each once, in source order.
func (*FilterShape) IsConjunction ¶
func (f *FilterShape) IsConjunction() bool
IsConjunction reports whether the filter is one AND of conditions, the shape whose parts can be taken independently.
func (*FilterShape) Match ¶
func (f *FilterShape) Match(row any) (bool, error)
Match evaluates the conditions the body did not take against one row: the same operators, literal typing, and NULL semantics the SQL rendering has.
func (*FilterShape) Take ¶
func (f *FilterShape) Take(fields ...string) []Condition
Take removes the conditions on the named fields from what the handler evaluates and returns them to the body, which applies them in its own queries. On a filter that is not a conjunction it takes nothing: a part of an OR cannot be applied apart from the rest.
type FormerNames ¶
type FormerNames interface {
FormerTagName(scope accesstypes.PermissionScope, res accesstypes.Resource, tag accesstypes.Tag) (accesstypes.Tag, bool)
FormerName(scope accesstypes.PermissionScope, res accesstypes.Resource) (accesstypes.Resource, bool)
}
FormerNames answers the former wire names of renamed fields and methods (their @formerly annotations) within a permission scope, as the generated collection does.
type GeneratedCollection ¶
type GeneratedCollection struct {
// contains filtered or unexported fields
}
GeneratedCollection is a read-only permission collection constructed from generated CollectionData. It is immutable after construction: nothing in its API mutates it once built, so concurrent reads require no synchronization.
func MustNewGeneratedCollection ¶
func MustNewGeneratedCollection(data CollectionData) *GeneratedCollection
MustNewGeneratedCollection is NewGeneratedCollection panicking on invalid data, for use by generated code.
func NewGeneratedCollection ¶
func NewGeneratedCollection(data CollectionData) (*GeneratedCollection, error)
NewGeneratedCollection validates data and constructs the collection. It rejects duplicate resources, duplicate or null permissions, and duplicate tags, so invalid generated data fails at startup rather than surfacing as wrong permission decisions.
func (*GeneratedCollection) AttributeComparisonType ¶
func (g *GeneratedCollection) AttributeComparisonType(scope accesstypes.PermissionScope, res accesstypes.Resource, name string) (accesstypes.AttributeType, bool)
AttributeComparisonType resolves an attribute's comparison type on one resource; ok is false when the resource declares no such attribute.
func (*GeneratedCollection) AttributeIsColumn ¶
func (g *GeneratedCollection) AttributeIsColumn(scope accesstypes.PermissionScope, res accesstypes.Resource, name string) bool
AttributeIsColumn reports whether an attribute is a column binding on the resource's own row — the shape a post-image (new.attr) reference requires.
func (*GeneratedCollection) AttributeIsList ¶ added in v0.3.0
func (g *GeneratedCollection) AttributeIsList(scope accesstypes.PermissionScope, res accesstypes.Resource, name string) bool
AttributeIsList reports whether an attribute reads a list column, which a condition judges item by item.
func (*GeneratedCollection) Bindings ¶
func (g *GeneratedCollection) Bindings(scope accesstypes.PermissionScope, res accesstypes.Resource) (Bindings, bool)
Bindings returns a resource's binding vocabulary; ok is false when the resource declares none.
func (*GeneratedCollection) ConcealingKeys ¶
func (g *GeneratedCollection) ConcealingKeys(scope accesstypes.PermissionScope, res accesstypes.Resource) (order, keys []accesstypes.Tag)
ConcealingKeys reports the fields a list of res orders or filters on whose masked cells conceal: the declared default order, and the request-time filter and sort keys, each less the positional fields. Deploy-time role validation (access.MigrateRoles) warns where a conditional grant lands on one of these and the row filter does not prove its condition, because the CASE then stands in the ORDER BY or the WHERE and no index serves it.
func (*GeneratedCollection) Data ¶
func (g *GeneratedCollection) Data() CollectionData
Data returns the canonical, deterministically sorted form of the collection.
func (*GeneratedCollection) FieldMasking ¶
func (g *GeneratedCollection) FieldMasking(scope accesstypes.PermissionScope, res accesstypes.Resource, tag accesstypes.Tag) Masking
FieldMasking reports how the field's masked cells meet a sort or a filter within scope: MaskingPositional where the field declared it, else MaskingConcealing, the default for every field.
func (*GeneratedCollection) FormerName ¶
func (g *GeneratedCollection) FormerName(scope accesstypes.PermissionScope, res accesstypes.Resource) (accesstypes.Resource, bool)
FormerName reports the former name of a renamed RPC method within scope (the method's @formerly), and whether the method was renamed. The permission digest mirrors the method's entry under the former name (WithFormerNames), so an application built before the rename keeps its action.
func (*GeneratedCollection) FormerTagName ¶
func (g *GeneratedCollection) FormerTagName(scope accesstypes.PermissionScope, res accesstypes.Resource, tag accesstypes.Tag) (accesstypes.Tag, bool)
FormerTagName reports the former wire name of a renamed field within scope (the field's @formerly), and whether the field was renamed. The permission digest mirrors the field's entry under the former name (WithFormerNames), so an application built before the rename keeps its column.
func (*GeneratedCollection) HasPermission ¶
func (g *GeneratedCollection) HasPermission(scope accesstypes.PermissionScope, permission accesstypes.Permission, res accesstypes.Resource) bool
HasPermission reports whether the collection registers permission on res within scope.
func (*GeneratedCollection) IsComputedResource ¶
func (g *GeneratedCollection) IsComputedResource(scope accesstypes.PermissionScope, res accesstypes.Resource) bool
IsComputedResource reports whether res is a computed resource within scope: a hand-written query surface whose permission checks run at decode time, and whose rows the library judges in Go as its function yields them. A field resource answers as its base resource.
func (*GeneratedCollection) IsResourceImmutable ¶
func (g *GeneratedCollection) IsResourceImmutable(scope accesstypes.PermissionScope, res accesstypes.Resource) bool
IsResourceImmutable checks if a resource is marked as immutable within a given scope.
func (*GeneratedCollection) List ¶
func (g *GeneratedCollection) List() map[accesstypes.Permission][]accesstypes.Resource
List returns a map of permissions to the resources that have them.
func (*GeneratedCollection) ListedAcrossTenants ¶ added in v0.5.0
func (g *GeneratedCollection) ListedAcrossTenants() []accesstypes.Resource
ListedAcrossTenants returns the resources declared for listing across tenants, in name order. A nil collection declares none.
func (*GeneratedCollection) ListsAcrossTenants ¶ added in v0.5.0
func (g *GeneratedCollection) ListsAcrossTenants(res accesstypes.Resource) bool
ListsAcrossTenants reports whether res is a tenant's resource declared for listing across tenants (@listAcrossTenants). A nil collection declares none.
func (*GeneratedCollection) MembersOf ¶
func (g *GeneratedCollection) MembersOf(parent accesstypes.Resource) []accesstypes.Resource
MembersOf lists the workflow member resources whose immediate parent hop is parent, sorted by name — the create-under-parent affordance's candidates (design plan §11): capabilities=Create on the parent's read answers, per row, which of these the user may create beneath it. Every scope is searched: a member and its parent share their scope kind by construction.
func (*GeneratedCollection) MethodTarget ¶
func (g *GeneratedCollection) MethodTarget(scope accesstypes.PermissionScope, method accesstypes.Resource) (accesstypes.Resource, bool)
MethodTarget reports the row resource method's @target field addresses within scope, and whether the method declares one. A targeted method's Execute grants may carry row-referencing conditions — the generated handler locates the row inside its transaction and evaluates them there — so deploy-time grant validation (access.MigrateRoles) asks this to tell a targeted method from a plain one.
func (*GeneratedCollection) MethodsTargeting ¶
func (g *GeneratedCollection) MethodsTargeting(target accesstypes.Resource) []TargetedMethod
MethodsTargeting lists the RPC method resources whose @target field addresses target, sorted by method name — the capability envelope's Execute candidates: a transition method's affordance is gated on the row's state membership in its from set, a plain method's only on its Execute grant's condition. Every scope is searched: a targeted method and its row resource share their scope kind by construction.
func (*GeneratedCollection) RequiredOnCreate ¶ added in v0.4.0
func (g *GeneratedCollection) RequiredOnCreate(scope accesstypes.PermissionScope, res accesstypes.Resource) []accesstypes.Tag
RequiredOnCreate reports the fields a create of res must be given by the client within scope, as wire tags, sorted: each takes no NULL, nothing but the client fills it, and a grant names it for Create. Deploy-time role validation (access.MigrateRoles) warns where a role may create the resource and may set none of its grants' fields for one of them. Empty for a resource every create of which the server can complete.
func (*GeneratedCollection) ResourceExists ¶
func (g *GeneratedCollection) ResourceExists(r accesstypes.Resource) bool
ResourceExists checks if a resource exists in the collection.
func (*GeneratedCollection) Resources ¶
func (g *GeneratedCollection) Resources() []accesstypes.Resource
Resources returns a sorted list of all unique base resource names in the collection.
func (*GeneratedCollection) Scope ¶
func (g *GeneratedCollection) Scope(resource accesstypes.Resource) accesstypes.PermissionScope
Scope returns the permission scope for a given resource, or an empty scope if the resource is not found.
func (*GeneratedCollection) SubjectSet ¶
func (g *GeneratedCollection) SubjectSet(name string) (SubjectAnchor, bool)
SubjectSet resolves a @subjectSet name across the collection — subject.<name> is one application-wide namespace, validated unique at construction.
func (*GeneratedCollection) SubjectSetComparisonType ¶
func (g *GeneratedCollection) SubjectSetComparisonType(name string) (accesstypes.AttributeType, bool)
SubjectSetComparisonType resolves the comparison type of the column a declared subject set (subject.<name>) yields; ok is false when the application declares no such set.
func (*GeneratedCollection) SubjectValue ¶
func (g *GeneratedCollection) SubjectValue(name string) (SubjectAnchor, bool)
SubjectValue resolves a @subjectValue name across the collection.
func (*GeneratedCollection) SubjectValueComparisonType ¶
func (g *GeneratedCollection) SubjectValueComparisonType(name string) (accesstypes.AttributeType, bool)
SubjectValueComparisonType resolves the comparison type of the column a declared scalar subject value (subject.<name>) yields; ok is false when the application declares no such value.
func (*GeneratedCollection) TagsRequiring ¶
func (g *GeneratedCollection) TagsRequiring(res accesstypes.Resource, perm accesstypes.Permission) []accesstypes.Tag
TagsRequiring reports the tags of res whose registration requires perm, sorted by name: the fields a caller needs perm on, whether or not a read projects them. The per-row write affordance (design plan §13) is planned over this set, so a write-only field, registered under the write permissions alone and never returned, still answers capabilities=Update. A tag registered without a permission (a permission-exempt primary key) is never in the set. Every scope is searched: a resource registers under one.
func (*GeneratedCollection) TransitionsOnto ¶
func (g *GeneratedCollection) TransitionsOnto(target accesstypes.Resource) []TransitionMethod
TransitionsOnto lists the RPC method resources whose declared transitions target res, sorted by method name — the capability envelope's Execute candidates. Every scope is searched: a transition's method and root share their scope kind by construction.
func (*GeneratedCollection) TypescriptData ¶
func (g *GeneratedCollection) TypescriptData() *TypescriptData
TypescriptData returns a struct containing all the data needed for TypeScript code generation.
func (*GeneratedCollection) TypescriptDataExcluding ¶
func (g *GeneratedCollection) TypescriptDataExcluding(excluded ...accesstypes.Resource) *TypescriptData
TypescriptDataExcluding returns the TypeScript generation data with every registration on the named resources omitted: the resources themselves and their tags. The TypeScript generator passes the resources and methods that belong exclusively to other router outlets, so an outlet-scoped target emits only its own members. Permissions and scopes are the framework's whole vocabulary regardless: a browser app names Permissions.Execute before the application registers a method, and an all-global application still names the domain scope.
type GroupNode ¶
type GroupNode struct {
Expression ExpressionNode
}
GroupNode represents a parenthesized group of expressions in the AST.
type Ident ¶
type Ident[T comparable] struct { // contains filtered or unexported fields }
Ident represents a database column identifier in a query, typed to ensure compile-time correctness of comparisons.
func NewIdent ¶
func NewIdent[T comparable](column string, px PartialQueryClause, indexed bool) Ident[T]
NewIdent creates a new identifier for a column.
func (Ident[T]) Equal ¶
func (i Ident[T]) Equal(v ...T) QueryClause
Equal creates an equality (`=`) or `IN` condition.
func (Ident[T]) GreaterThan ¶
func (i Ident[T]) GreaterThan(v T) QueryClause
GreaterThan creates a `>` condition.
func (Ident[T]) GreaterThanEq ¶
func (i Ident[T]) GreaterThanEq(v T) QueryClause
GreaterThanEq creates a `>=` condition.
func (Ident[T]) IsNotNull ¶
func (i Ident[T]) IsNotNull() QueryClause
IsNotNull creates an `IS NOT NULL` condition.
func (Ident[T]) IsNull ¶
func (i Ident[T]) IsNull() QueryClause
IsNull creates an `IS NULL` condition.
func (Ident[T]) LessThan ¶
func (i Ident[T]) LessThan(v T) QueryClause
LessThan creates a `<` condition.
func (Ident[T]) LessThanEq ¶
func (i Ident[T]) LessThanEq(v T) QueryClause
LessThanEq creates a `<=` condition.
func (Ident[T]) NotEqual ¶
func (i Ident[T]) NotEqual(v ...T) QueryClause
NotEqual creates a not-equal (`<>`) or `NOT IN` condition.
type Key ¶
type Key[S NamedStore] string
Key is a stored file's key in the named store S: what a @file column typed Key[S] holds, what FileIn[S].Key carries, and what the generated setter of that column takes. The generator maps it to a STRING column. Copying an existing key, or recording one the application made, takes an explicit conversion, visible in review; code that opens an object itself converts with string(key) at the store boundary, since FileStore is untyped.
type KeyPart ¶
type KeyPart struct {
Key accesstypes.Field
Value any
}
KeyPart represents a single component of a primary key, consisting of a field name and its value.
type KeySet ¶
type KeySet struct {
// contains filtered or unexported fields
}
KeySet is an object that represents a single or composite primary key and its value.
func (KeySet) Add ¶
func (p KeySet) Add(key accesstypes.Field, value any) KeySet
Add adds an additional column to the primary key creating a composite primary key
- KeySet is immutable.
- Add returns a new KeySet that should be used for all subsequent operations.
func (KeySet) KeyMap ¶
func (p KeySet) KeyMap() map[accesstypes.Field]any
KeyMap returns a map representation of the key set, with field names as keys and their values as values.
func (KeySet) KeySet ¶
KeySet converts the resource KeySet into a `spanner.KeySet`, which can be used in Spanner read or delete operations.
func (KeySet) Len ¶
Len returns the number of parts in the key set (for composite keys, this will be greater than 1).
type LocatedFileStore ¶
LocatedFileStore is a FileStore that knows where it keeps its objects, as the framework's stores (resource/filestore) do: the URL it was opened from. The client refuses two stores on one location at construction.
type LogicalOpNode ¶
type LogicalOpNode struct {
Left ExpressionNode
Operator LogicalOperator
Right ExpressionNode
}
LogicalOpNode represents a logical operation (AND/OR) in the AST.
func (*LogicalOpNode) String ¶
func (ln *LogicalOpNode) String() string
String returns a string representation of the LogicalOpNode.
type LogicalOperator ¶
type LogicalOperator string
LogicalOperator defines the type of logical operator (AND, OR).
const ( // OperatorAnd represents a logical AND. OperatorAnd LogicalOperator = "AND" // OperatorOr represents a logical OR. OperatorOr LogicalOperator = "OR" )
type ManualRegistration ¶
type ManualRegistration struct {
// Scope is empty when the declaration leaves the scope to the default
// (accesstypes.GlobalPermissionScope).
Scope accesstypes.PermissionScope
Permission accesstypes.Permission
Resource accesstypes.Resource
// Outlets names the router outlets the hand-written route is mounted under, as
// @outlet does for a generated one. Empty means the default outlet only. A
// TypeScript target filtered to an outlet (ForOutlet) emits the registration's
// constants only when the target's outlet is named here.
Outlets []string
}
ManualRegistration declares a permission registration that is not derived from generated handlers: a hand-written route that checks a permission on a resource with no generated handler. Declare them to the Resource Generator with an @manualAddResource annotation or WithManualResources.
type Masking ¶
type Masking string
Masking is how a field's masked cells meet a sort or a filter. A conditionally granted field is masked on the rows its condition does not select; the question is what the query sees there.
const ( // MaskingConcealing is the default: the query runs over the visible // projection, CASE WHEN <condition> THEN column END, so a masked cell is // NULL wherever the query looks at it and nothing about a hidden value // leaks through order or match. No index serves the expression, so a page // sorted or filtered by the field sorts the tenant's partition. The empty // Masking means the same. MaskingConcealing Masking = "concealing" // MaskingPositional is the field-level opt-in (struct tag // masking:"positional"): the cell stays hidden in the output, but ordering // and filtering run on the real column, so the index serves the page and // the field's rank is disclosed — a reader who sees some values can tell // where the hidden ones fall between them. MaskingPositional Masking = "positional" )
type Metadata ¶
type Metadata[Resource Resourcer] struct { // contains filtered or unexported fields }
Metadata contains cached metadata about a resource, such as its database schema mapping and configuration.
func NewMetadata ¶
NewMetadata creates or retrieves cached metadata for a resource.
func (*Metadata[Resource]) DBFieldCount ¶
DBFieldCount returns the number of fields for a given database type.
type MockClient ¶
type MockClient struct {
// contains filtered or unexported fields
}
MockClient is a wrapper around the database.
func NewMockClient ¶
func NewMockClient(txnMock ReadWriteTransaction, readOnlyMocks, txnReadMocks []any, opts ...ClientOption) *MockClient
NewMockClient creates a new MockClient for testing resource database interactions.
It uses the following mocks: - txnMock: Mocks Buffer calls. - readOnlyMocks: Mocks Read/List calls outside a transaction. - txnReadMocks: Mocks Read/List calls inside a transaction.
IMPORTANT: For readOnlyMocks and txnReadMocks, provide only one mock per resource type (e.g., Read[MyResource]). Multiple calls for the same Resource must be configured on that single mock.
WithFileStore and WithNamedFileStore hand it the stores ExecuteFunc deletes released file objects from after the function returns, so a test can assert what a patch released. WithSecretKeys hands it the keys its transactions seal a patch's secret fields with, built from fixed bytes in a test (NewSecretKeys), so what a patch buffers is the sealed value and the test can open it.
func (*MockClient) DBType ¶
func (c *MockClient) DBType() DBType
DBType returns the database type the mock stands in for.
func (*MockClient) ExecuteFunc ¶
func (c *MockClient) ExecuteFunc(ctx context.Context, f func(ctx context.Context, txn ReadWriteTransaction) error) error
ExecuteFunc executes a function within a read-write transaction. As the Spanner client's does, it refuses a function that released an object of a store the client holds none for, deletes the file objects the function's patches released from their stores once the function returns nil, hands the rows the patches wrote to the collector ctx carries (CollectTouchedRows), runs what the patches registered for after the commit (AfterCommit), and does none of it when it errors.
func (*MockClient) FileStore ¶
func (c *MockClient) FileStore(name StoreName) FileStore
FileStore returns the store wired under name, nil when none is.
func (*MockClient) PostgresReadOnlyTransaction ¶
func (c *MockClient) PostgresReadOnlyTransaction() any
PostgresReadOnlyTransaction panics because it is not implemented for the MockClient.
func (*MockClient) ReadOnlyMocks ¶
func (c *MockClient) ReadOnlyMocks() []any
ReadOnlyMocks returns the read-only mocks for the Mock client.
func (*MockClient) ReadOnlyTransaction ¶
func (c *MockClient) ReadOnlyTransaction() ReadOnlyTransactionCloser
ReadOnlyTransaction returns a ReadOnlyTransaction that can be used for multiple reads from the database. You must call Close() when the ReadOnlyTransaction is no longer needed to release resources on the server.
func (*MockClient) SpannerReadOnlyTransaction ¶
func (c *MockClient) SpannerReadOnlyTransaction() spxapi.Querier
SpannerReadOnlyTransaction returns a read-only transaction for the Mock client.
type MockReadWriteTransaction ¶
type MockReadWriteTransaction struct {
// contains filtered or unexported fields
}
MockReadWriteTransaction represents a database transaction that can be used for both reads and writes.
func NewMockReadWriteTransaction ¶
func NewMockReadWriteTransaction(mock ReadWriteTransaction, txnReaderMocks ...any) *MockReadWriteTransaction
NewMockReadWriteTransaction creates a new MockReadWriteTransaction. A test whose patches set a secret field gives it the secret keys with WithSecretKeys.
func (*MockReadWriteTransaction) BufferMap ¶
func (c *MockReadWriteTransaction) BufferMap(r PatchSetMetadata, p map[string]any) error
BufferMap buffers a map of changes to be applied to the database.
func (*MockReadWriteTransaction) BufferStruct ¶
func (c *MockReadWriteTransaction) BufferStruct(p PatchSetMetadata) error
BufferStruct buffers a struct of changes to be applied to the database.
func (*MockReadWriteTransaction) Committed ¶ added in v0.3.0
func (c *MockReadWriteTransaction) Committed(ctx context.Context)
Committed runs what the transaction's writes registered for after the commit (AfterCommit), as SpannerReadWriteTransaction.Committed does: for a transaction a test builds itself (NewMockReadWriteTransaction); the Mock client's ExecuteFunc makes the calls once the function returns nil.
func (*MockReadWriteTransaction) DBType ¶
func (c *MockReadWriteTransaction) DBType() DBType
DBType returns the database type.
func (*MockReadWriteTransaction) DataChangeEventIndex ¶
func (c *MockReadWriteTransaction) DataChangeEventIndex(res accesstypes.Resource, rowID string) int
DataChangeEventIndex provides a sequence number for data change events on the same Resource inside the same transaction.
func (*MockReadWriteTransaction) PostgresReadOnlyTransaction ¶
func (c *MockReadWriteTransaction) PostgresReadOnlyTransaction() any
PostgresReadOnlyTransaction panics because it is not implemented for the MockReadWriteTransaction.
func (*MockReadWriteTransaction) Released ¶
func (c *MockReadWriteTransaction) Released() []ReleasedKey
Released returns the file objects the transaction's patches released so far, each with its store, as SpannerReadWriteTransaction.Released does.
func (*MockReadWriteTransaction) SpannerReadOnlyTransaction ¶
func (c *MockReadWriteTransaction) SpannerReadOnlyTransaction() spxapi.Querier
SpannerReadOnlyTransaction returns a read-only transaction for the MockReadWriteTransaction.
func (*MockReadWriteTransaction) TxnReadMocks ¶
func (c *MockReadWriteTransaction) TxnReadMocks() []any
TxnReadMocks returns the read mocks inside a transaction for the MockReadWriteTransaction.
func (*MockReadWriteTransaction) WithSecretKeys ¶ added in v0.5.0
func (c *MockReadWriteTransaction) WithSecretKeys(keys *SecretKeys) *MockReadWriteTransaction
WithSecretKeys gives the transaction the secret keys it seals a patch's secret fields with, and returns the transaction. The Mock client's ExecuteFunc gives a transaction its own; this is for one a test builds itself (NewMockReadWriteTransaction).
type NamedStore ¶
type NamedStore interface {
// contains filtered or unexported methods
}
NamedStore is the constraint a named store's type satisfies: a struct embedding Store. It is the type parameter of Key, FilesIn, FileIn, StoreNameFor and WithNamedFileStore.
type Operation ¶
type Operation struct {
Type OperationType
Req *http.Request
// contains filtered or unexported fields
}
Operation represents a single operation within a batch request, containing its type and a corresponding http.Request.
func (*Operation) AsCreate ¶ added in v0.4.0
AsCreate returns a copy of the operation that runs as an add: what a patch-or-add whose row is not there turns into, and what an add-or-skip is decoded as. The request, with the key its path carries, is the operation's own.
func (*Operation) AsUpdate ¶ added in v0.4.0
AsUpdate returns a copy of the operation that runs as a patch: what a patch-or-add whose row is there turns into.
func (*Operation) PathDepth ¶
PathDepth returns the number of segments in the operation's path ("/organizations" → 1, "/organizations/abc" → 2). The consolidated handler uses it to distinguish operations on the resource named like the domain route segment (the tenant record, depth ≤ 2) from domain descents (depth ≥ 3) — disjoint by construction because the segment-named resource is required to have a single primary key.
func (*Operation) ReqWithPattern ¶
ReqWithPattern creates a new http.Request from the operation, applying a new URL pattern to its context. This is useful when a batch operation's path contains more segments than the initial prefix pattern.
func (*Operation) WithPrefixPattern ¶
WithPrefixPattern returns a copy of the operation re-anchored to a longer path prefix: the pattern is prefix-matched against the operation's path, binding its params into the request context, and the copy's create-path semantics use the new, longer prefix. The consolidated handler uses it to descend into the domain route segment (binding the domain param) before dispatching on the resource segment.
type OperationType ¶
type OperationType string
OperationType defines the type of a patch operation (add, patch, remove, and the two that decide from whether the row is there: patch-or-add and add-or-skip).
const ( // OperationCreate corresponds to an "add" operation. OperationCreate OperationType = "add" // OperationUpdate corresponds to a "patch" operation. OperationUpdate OperationType = "patch" // OperationDelete corresponds to a "remove" operation. OperationDelete OperationType = "remove" // OperationUpdateOrCreate corresponds to a "patch-or-add" operation: an update of // the row its path names, and a create of that row when it is not there. A handler // asks the decoder which of the two it is (Decoder.DecideOperation: the caller's // Update grant on the resource, then a look for the row inside the transaction) and // runs the operation as the patch or the add it turned out to be, so everything a // patch or an add is held to holds for it. OperationUpdateOrCreate OperationType = "patch-or-add" // OperationCreateOrSkip corresponds to an "add-or-skip" operation: a create of the // row its path names that leaves the row exactly as it is when it is there. A // handler runs it as the add it is (AsCreate) with the create patch marked OrSkip. OperationCreateOrSkip OperationType = "add-or-skip" )
type Option ¶
type Option func(opt options) options
Option is a function that configures the behavior of the Operations parser.
func MatchPrefix ¶
func MatchPrefix() Option
MatchPrefix is an option that allows matching only the prefix of an operation's path against the provided pattern.
func RequireCreatePath ¶
func RequireCreatePath() Option
RequireCreatePath is an option that mandates a path for "add" operations.
type Outcome ¶ added in v0.4.0
type Outcome string
Outcome is what buffering an OrCreate or an OrSkip patch did with its row.
const ( // OutcomeCreated says the row was not there and the patch created it. OutcomeCreated Outcome = "created" // OutcomeUpdated says the row was there and the update ran. An update with no // fields set is the silent no-op it is everywhere (see Apply and Buffer). OutcomeUpdated Outcome = "updated" // OutcomeSkipped says the row was there and an OrSkip patch left it as it is: // nothing was written and no default or validation ran. OutcomeSkipped Outcome = "skipped" )
type Page ¶
type Page[Resource Resourcer] struct { // contains filtered or unexported fields }
Page collects one page of a decoded list on the generated handler's behalf. The statement fetches one row past the page size; Add keeps the page's rows and reports the extra one, which tells the page a next page exists and is never encoded. WriteHeaders then writes the Link and Total-Count headers from the rows it saw, before the handler encodes the body.
func (*Page[Resource]) Add ¶
Add records a row the statement yielded and reports whether it belongs to the page. The row past the page size is the more-exists signal: Add answers false and the handler stops without encoding it. The envelope, not the bare data, because a boundary row's masked sort cell must position the cursor as NULL, which is how the statement ordered it.
func (*Page[Resource]) Count ¶
func (p *Page[Resource]) Count(ctx context.Context, txn ReadOnlyTransaction) error
Count runs the total query when the request asked for one (count=true) and nothing otherwise. The handler calls it before listing, so the total and the page are read under the same request.
func (*Page[Resource]) Reversed ¶
Reversed reports whether the page was read backwards, walking to the previous page, so the handler reverses the encoded rows into the list's order.
func (*Page[Resource]) RowFields ¶ added in v0.3.0
func (p *Page[Resource]) RowFields(i int) []accesstypes.Field
RowFields returns the projected fields the i-th of Rows shows: the query set's fields, without those granted under a condition the row does not meet. The handler encodes these and no other, so a cell the caller's grants refuse on this row never reaches the response.
func (*Page[Resource]) Rows ¶
func (p *Page[Resource]) Rows() []*Resource
Rows returns the page's rows in read order when the QuerySet collected them (Collect); the handler reverses them when Reversed reports a backward walk.
func (*Page[Resource]) WriteHeaders ¶
WriteHeaders writes the page's headers onto the response before the body: Total-Count when a count was asked for, and Link with a complete URL per relation that exists — the first page has no prev, the last page no next. The URLs carry the request's own query with the cursor set and count removed, so a client follows them as given and never assembles one. A hand-built QuerySet writes nothing; the whole list (limit=all, or a key-less list) writes Total-Count when asked and no Link, since it has no neighboring pages.
type PageBounds ¶
type PageBounds struct {
// contains filtered or unexported fields
}
PageBounds is the page a body pages for itself: how many rows to yield and where to start. Order is the read order the rows must arrive in — the total order, or its reverse when the request walks back — and Boundary the values of the row the page starts after, one per order field, nil on a first page. The body yields the rows strictly after the boundary in that order, up to Fetch of them: the page and one more, which tells the handler a next page exists and is never encoded. A nullable order field's NULL region sits where the application's database places it (the side a plain ORDER BY puts it on), so a body that renders its own cursor predicate admits the NULL region on that side: after a non-null boundary when the region follows the values, and every non-null row after a NULL boundary (a nil entry) when the region precedes them.
func (PageBounds) Boundary ¶
func (b PageBounds) Boundary() []any
Boundary is the row the page starts after, as one value per order field in the row's own Go types (a nil entry is a NULL); nil on a first page.
func (PageBounds) Fetch ¶
func (b PageBounds) Fetch() uint64
Fetch is how many rows the body should yield: the page size plus one.
func (PageBounds) Order ¶
func (b PageBounds) Order() []SortField
Order is the order the body's rows must arrive in.
type Paging ¶
type Paging struct {
// Order is the order a list takes when the request carries no sort. The
// primary key is appended so the order is total; a request's sort replaces
// it for that request. Empty, a sort-less request is served only as
// limit=all, the whole list with no order (the statement carries no ORDER
// BY, a computed body's yielded order stands); a sort-less paged request is
// refused at decode.
Order []SortField
// DefaultLimit is the page size a request without limit receives; 0 means
// DefaultPageSize.
DefaultLimit uint64
// MaxLimit is the largest page a request may ask for; 0 means no maximum,
// which also permits limit=all.
MaxLimit uint64
}
Paging is a resource's declared paging contract: the order its list takes when the request states none, and the page sizes the decoder applies and admits. The generator reads it off the @order and @page annotations and hands it to the resource's query decoder (WithPaging); a resource that declares nothing takes the zero value, which the decoder reads as no order, a page of DefaultPageSize, and no maximum.
type PartialQueryClause ¶
type PartialQueryClause struct {
// contains filtered or unexported fields
}
PartialQueryClause represents an incomplete query clause, typically the left-hand side of a logical operation.
func NewPartialQueryClause ¶
func NewPartialQueryClause() PartialQueryClause
NewPartialQueryClause creates an empty PartialQueryClause.
func (PartialQueryClause) Group ¶
func (p PartialQueryClause) Group(qc QueryClause) QueryClause
Group wraps a QueryClause in parentheses.
func (PartialQueryClause) Search ¶
func (p PartialQueryClause) Search(text, key string, columns []SearchColumn, branches []SearchBranch) (QueryClause, error)
Search creates the search box over the resource's searchable columns, as the filter grammar's *:search:"…" does: every term of the text must be found in one of the columns, or in one of the resource's @searchAlso branches. The generated query builder passes the columns in declaration order, the resource's single-column key (which a box over several search indexes joins its key sets on; "" when the resource declares none) and its branches. The grammar's limits apply, so a text they refuse is refused here with the same message.
type PatchSet ¶
type PatchSet[Resource Resourcer] struct { // contains filtered or unexported fields }
PatchSet represents a set of changes to be applied to a resource.
func NewPatchSet ¶
NewPatchSet creates a new, empty PatchSet for a given resource metadata.
func (*PatchSet[Resource]) Apply ¶
Apply applies the patch within a new read-write transaction.
An update or insert-or-update patch with no fields set is a silent no-op: nothing runs — no permission check, no output-only update functions, no mutation, no change event. To run the update pipeline with the content supplied entirely by the registered output-only update functions, mark the patch with AsTouch.
An OrCreate or OrSkip patch decides its case first, from whether its row is there (patch_fork.go), and then runs as the create or the update it decided on.
func (*PatchSet[Resource]) AsTouch ¶
AsTouch marks an update patch as a touch: an update whose entire content is supplied by the registered output-only update functions. A touch runs the full update pipeline — permission check, output-only update functions, write conditions, change events — even though the caller sets no fields, whereas a plain update patch with no fields set is a silent no-op (see Apply and Buffer). Only UpdatePatchType patches can be touches, and a touch requires at least one registered output-only update function; Apply and Buffer reject anything else.
func (*PatchSet[Resource]) Buffer ¶
func (p *PatchSet[Resource]) Buffer(ctx context.Context, txn ReadWriteTransaction, eventSource ...string) error
Buffer buffers the patch's mutations into an existing transaction buffer.
An update or insert-or-update patch with no fields set is a silent no-op: nothing runs — no permission check, no output-only update functions, no mutation, no change event. To run the update pipeline with the content supplied entirely by the registered output-only update functions, mark the patch with AsTouch.
An OrCreate or OrSkip patch decides its case first, from whether its row is there (patch_fork.go), and then runs as the create or the update it decided on.
func (*PatchSet[Resource]) Data ¶
func (p *PatchSet[Resource]) Data() map[accesstypes.Field]any
Data returns the underlying map of field-value pairs.
func (*PatchSet[Resource]) Diff ¶
Diff returns a map of fields that have changed between old and patchSet. A field the resource struct declares a secret (conditions:"secret") is in the map when it changed, marked Secret, with neither value. Whether a secret changed cannot be told from its stored bytes, which differ at every write: the write path opens what the row holds and compares it with the value given, and Diff, which holds no keys, counts a secret the patch sets as changed unless the row holds none and the patch sets none.
func (*PatchSet[Resource]) EnableUserPermissionEnforcement ¶
func (p *PatchSet[Resource]) EnableUserPermissionEnforcement(rSet *Set[Resource], userPermissions UserPermissions, scope accesstypes.Scope, requiredPermission accesstypes.Permission) *PatchSet[Resource]
EnableUserPermissionEnforcement enables the checking of user permissions for the PatchSet, evaluating requiredPermission for the user in the given scope partition.
An enforced PatchSet is single-shot: it binds the user (via userPermissions) and the domain for a single operation's evaluation. Build a new PatchSet per operation; never reuse one across requests or domains.
func (*PatchSet[Resource]) Enforce ¶
func (p *PatchSet[Resource]) Enforce(caller *Caller, rSet *Set[Resource], requiredPermission accesstypes.Permission) *PatchSet[Resource]
Enforce arms the mutation against the caller: Apply and Buffer run the full pipeline the resource routes run — the static field gate against the Set, the fold of conditional grants, the live check against the real row inside the transaction, and the tenancy check — before buffering anything. A refusal is the same Forbidden the routes answer, naming the grant that said no. A zero Caller refuses at execution.
func (*PatchSet[Resource]) Fields ¶
func (p *PatchSet[Resource]) Fields() []accesstypes.Field
Fields returns a slice of all fields that have been set in the PatchSet.
func (*PatchSet[Resource]) FromStruct ¶
FromStruct populates the PatchSet from a given struct. It reflects on the input struct and sets the fields in the PatchSet. Fields from the input struct that do not exist in the resource and are not in the skip list will result in an error.
func (*PatchSet[Resource]) Get ¶
func (p *PatchSet[Resource]) Get(field accesstypes.Field) any
Get retrieves the value of a field from the PatchSet.
func (*PatchSet[Resource]) IsSet ¶
func (p *PatchSet[Resource]) IsSet(field accesstypes.Field) bool
IsSet checks if a field has been set in the PatchSet.
func (*PatchSet[Resource]) Key ¶
func (p *PatchSet[Resource]) Key(field accesstypes.Field) any
Key retrieves the value of a primary key field.
func (*PatchSet[Resource]) OrCreate ¶ added in v0.4.0
OrCreate turns an update patch into update-or-create: when the row is there the update runs as it is, and when it is not the patch creates the row with the fields it carries, through the create path whole. createSet is the Set a create of the resource is checked against, used when the patch is armed against a caller (Enforce); a patch that runs trusted passes nil. The generated update patch's OrCreate passes the resource's own and registers the create's defaults and validation beside the update's.
The fields the patch sets are written in both cases. A caller that needs the two cases to write different things reads the row and builds the create patch or the update patch.
func (*PatchSet[Resource]) OrSkip ¶ added in v0.4.0
OrSkip turns a create patch into create-unless-there: when the row is not there the create runs as it is, and when it is the patch does nothing at all. The caller's Create grant is checked before the row is looked for, so a caller who may not create is refused either way. A grant's row condition is judged only when the row is created.
func (*PatchSet[Resource]) Outcome ¶ added in v0.4.0
Outcome reports what the last Apply or Buffer of an OrCreate or OrSkip patch did with its row. It is empty on a patch that is neither, and before the patch has run.
func (*PatchSet[Resource]) Permitted ¶ added in v0.5.0
func (p *PatchSet[Resource]) Permitted(ctx context.Context, txn ReadWriteTransaction) error
Permitted checks the caller's grants for the write an armed PatchSet carries, as Apply and Buffer check them before anything else: the permission on the resource and on each field the patch names. The conditions a grant carries are left to Apply and Buffer, which evaluate them against the row. A write whose answer depends on what the database holds (a rule that reads other rows and refuses in words) calls it before the rule is asked, so a caller the grants refuse gets the same Forbidden whatever the rule would have said, and learns nothing from it. A PatchSet that is not armed passes, since it runs trusted.
func (*PatchSet[Resource]) PrimaryKey ¶
PrimaryKey returns the KeySet containing the primary key(s) for the resource.
func (*PatchSet[Resource]) RegisterDefaultCreateFunc ¶
func (p *PatchSet[Resource]) RegisterDefaultCreateFunc(field accesstypes.Field, fn FieldDefaultFunc)
RegisterDefaultCreateFunc registers a function to set a default value for a field during a create operation.
func (*PatchSet[Resource]) RegisterDefaultsCreateFunc ¶
func (p *PatchSet[Resource]) RegisterDefaultsCreateFunc(fn DefaultsFunc)
RegisterDefaultsCreateFunc registers a function that will be called on all Create Patches just before the patch is buffered to set necessary default values
func (*PatchSet[Resource]) RegisterDefaultsUpdateFunc ¶
func (p *PatchSet[Resource]) RegisterDefaultsUpdateFunc(fn DefaultsFunc)
RegisterDefaultsUpdateFunc registers a function that will be called on all Update Patches just before the patch is buffered to set necessary default values
func (*PatchSet[Resource]) RegisterOutputOnlyUpdateFunc ¶
func (p *PatchSet[Resource]) RegisterOutputOnlyUpdateFunc(field accesstypes.Field, fn FieldDefaultFunc)
RegisterOutputOnlyUpdateFunc registers a function that supplies a field's value during an update operation. It fills the field only when the caller left it unset — explicitly setting the field pre-empts it — and it never reaches an update patch with no fields set at all, because such a patch is a silent no-op (see Apply and Buffer). An update carried entirely by these functions is a touch: mark the patch with AsTouch.
func (*PatchSet[Resource]) RegisterValidateCreateFunc ¶
func (p *PatchSet[Resource]) RegisterValidateCreateFunc(fn ValidateFunc)
RegisterValidateCreateFunc registers a function that will be called on all Create Patches just before the patch is buffered to validate the patch
func (*PatchSet[Resource]) RegisterValidateUpdateFunc ¶
func (p *PatchSet[Resource]) RegisterValidateUpdateFunc(fn ValidateFunc)
RegisterValidateUpdateFunc registers a function that will be called on all Update Patches just before the patch is buffered to validate the patch
func (*PatchSet[Resource]) Resolve ¶
Resolve returns a map with the keys set to the database struct tags found on databaseType, and the values set to the values in patchSet. A field the resource declares a secret (conditions:"secret") is sealed here, with keys and the row's primary key, so its column is never handed the value as it was given: the write path passes the keys of its transaction's client, and a patch that sets a secret is refused when there are none. A patch that sets no secret resolves with nil keys.
func (*PatchSet[Resource]) Resource ¶
func (p *PatchSet[Resource]) Resource() accesstypes.Resource
Resource returns the name of the resource this PatchSet applies to.
func (*PatchSet[Resource]) Set ¶
func (p *PatchSet[Resource]) Set(field accesstypes.Field, value any) *PatchSet[Resource]
Set adds or updates a field's value in the PatchSet.
func (*PatchSet[Resource]) SetKey ¶
func (p *PatchSet[Resource]) SetKey(field accesstypes.Field, value any) *PatchSet[Resource]
SetKey sets a primary key field and value for the PatchSet.
func (*PatchSet[Resource]) SetPatchType ¶
SetPatchType sets the type of the patch (Create, CreateOrUpdate, Update, or Delete).
func (*PatchSet[Resource]) ToStruct ¶
func (p *PatchSet[Resource]) ToStruct() *Resource
ToStruct returns an instance of Resource, with its struct fields populated with the contents of data. A secret field the patch was given as text is left out: the struct's field holds the bytes its column stores, and the value is sealed only when the patch is written.
type PatchSetComparer ¶
type PatchSetComparer interface {
Resource() accesstypes.Resource
Data() map[accesstypes.Field]any
Fields() []accesstypes.Field
PatchType() PatchType
PrimaryKey() KeySet
}
PatchSetComparer is an interface for comparing two PatchSet-like objects.
type PatchSetMetadata ¶
type PatchSetMetadata interface {
PatchType() PatchType
PrimaryKey() KeySet
Resource() accesstypes.Resource
}
PatchSetMetadata is an interface that all PatchSet types must implement to allow their mutations to be buffered
type PatchType ¶
type PatchType string
PatchType defines the type of operation for a PatchSet.
const ( // CreatePatchType indicates an insert operation. CreatePatchType PatchType = "CreatePatchType" // UpdatePatchType indicates an update operation. UpdatePatchType PatchType = "UpdatePatchType" // CreateOrUpdatePatchType indicates an insert or update operation. CreateOrUpdatePatchType PatchType = "CreateOrUpdatePatchType" // DeletePatchType indicates a delete operation. DeletePatchType PatchType = "DeletePatchType" )
type PostgreSQLGenerator ¶
type PostgreSQLGenerator struct {
// contains filtered or unexported fields
}
PostgreSQLGenerator is a SQL generator for PostgreSQL.
func NewPostgreSQLGenerator ¶
func NewPostgreSQLGenerator() *PostgreSQLGenerator
NewPostgreSQLGenerator creates a new PostgreSQLGenerator.
func (*PostgreSQLGenerator) GenerateSQL ¶
func (g *PostgreSQLGenerator) GenerateSQL(node ExpressionNode) (sqlStr string, params map[string]any, err error)
GenerateSQL generates SQL for the given node.
type PostgresClient ¶
type PostgresClient struct {
// contains filtered or unexported fields
}
PostgresClient is a wrapper around the database.
func NewPostgresClient ¶
func NewPostgresClient(db *pgxpool.Pool, opts ...ClientOption) *PostgresClient
NewPostgresClient creates a new Client. WithFileStore and WithNamedFileStore hand it the stores the generated handlers read off it, the options the Spanner client takes; a store wired twice, or two stores on one location, panics here. WithSecretKeys hands it the keys a patch's secret fields are sealed with.
func (*PostgresClient) Close ¶
func (c *PostgresClient) Close()
Close closes the database connection.
func (*PostgresClient) DBType ¶
func (c *PostgresClient) DBType() DBType
DBType returns the database type.
func (*PostgresClient) ExecuteFunc ¶
func (c *PostgresClient) ExecuteFunc(_ context.Context, _ func(ctx context.Context, _ ReadWriteTransaction) error) error
ExecuteFunc executes a function within a read-write transaction.
func (*PostgresClient) FileStore ¶
func (c *PostgresClient) FileStore(name StoreName) FileStore
FileStore returns the store wired under name, nil when none is.
func (*PostgresClient) PostgresReadOnlyTransaction ¶
func (c *PostgresClient) PostgresReadOnlyTransaction() any
PostgresReadOnlyTransaction panics because it is not implemented for the PostgresClient.
func (*PostgresClient) ReadOnlyTransaction ¶
func (c *PostgresClient) ReadOnlyTransaction() ReadOnlyTransactionCloser
ReadOnlyTransaction returns a ReadOnlyTransaction that can be used for multiple reads from the database. You must call Close() when the ReadOnlyTransaction is no longer needed to release resources on the server.
func (*PostgresClient) SpannerReadOnlyTransaction ¶
func (c *PostgresClient) SpannerReadOnlyTransaction() spxapi.Querier
SpannerReadOnlyTransaction panics because it is not implemented for the PostgresClient.
type PostgresReadOnlyTransaction ¶
type PostgresReadOnlyTransaction struct {
// contains filtered or unexported fields
}
PostgresReadOnlyTransaction represents a database transaction that can only be used for reads.
func (*PostgresReadOnlyTransaction) Close ¶
func (c *PostgresReadOnlyTransaction) Close()
Close closes the readonly transaction
func (*PostgresReadOnlyTransaction) PostgresReadOnlyTransaction ¶
func (c *PostgresReadOnlyTransaction) PostgresReadOnlyTransaction() any
PostgresReadOnlyTransaction returns a read-only transaction for the Postgres client.
func (*PostgresReadOnlyTransaction) SpannerReadOnlyTransaction ¶
func (c *PostgresReadOnlyTransaction) SpannerReadOnlyTransaction() spxapi.Querier
SpannerReadOnlyTransaction panics because it is not implemented for the PostgresReadOnlyTransaction.
type PostgresReadWriteTransaction ¶
type PostgresReadWriteTransaction struct {
// contains filtered or unexported fields
}
PostgresReadWriteTransaction represents a database transaction that can be used for both reads and writes.
func (*PostgresReadWriteTransaction) BufferMap ¶
func (c *PostgresReadWriteTransaction) BufferMap(_ PatchSetMetadata, _ map[string]any) error
BufferMap panics because it is not implemented for the PostgresReadWriteTransaction.
func (*PostgresReadWriteTransaction) BufferStruct ¶
func (c *PostgresReadWriteTransaction) BufferStruct(_ PatchSetMetadata) error
BufferStruct panics because it is not implemented for the PostgresReadWriteTransaction.
func (*PostgresReadWriteTransaction) DBType ¶
func (c *PostgresReadWriteTransaction) DBType() DBType
DBType returns the database type.
func (*PostgresReadWriteTransaction) DataChangeEventIndex ¶
func (c *PostgresReadWriteTransaction) DataChangeEventIndex(res accesstypes.Resource, rowID string) int
DataChangeEventIndex provides a sequence number for data change events on the same Resource inside the same transaction.
func (*PostgresReadWriteTransaction) List ¶
func (c *PostgresReadWriteTransaction) List(_ context.Context, _ Resourcer, _ []any, _ *Statement) error
List reads a list of resources from the database.
func (*PostgresReadWriteTransaction) PostgresReadOnlyTransaction ¶
func (c *PostgresReadWriteTransaction) PostgresReadOnlyTransaction() any
PostgresReadOnlyTransaction panics because it is not implemented for the PostgresReadWriteTransaction.
func (*PostgresReadWriteTransaction) Read ¶
func (c *PostgresReadWriteTransaction) Read(_ context.Context, _ Resourcer, _ any, _ *Statement) error
Read reads a single resource from the database.
func (*PostgresReadWriteTransaction) SpannerReadOnlyTransaction ¶
func (c *PostgresReadWriteTransaction) SpannerReadOnlyTransaction() spxapi.Querier
SpannerReadOnlyTransaction panics because it is not implemented for the PostgresReadWriteTransaction.
func (*PostgresReadWriteTransaction) WithSecretKeys ¶ added in v0.5.0
func (c *PostgresReadWriteTransaction) WithSecretKeys(keys *SecretKeys) *PostgresReadWriteTransaction
WithSecretKeys gives the transaction the application's secret keys, which a patch's secret fields are sealed with, and returns the transaction.
type QueryClause ¶
type QueryClause struct {
// contains filtered or unexported fields
}
QueryClause represents a complete, valid query expression that can be part of a WHERE clause.
func (QueryClause) And ¶
func (qc QueryClause) And() PartialQueryClause
And starts a logical AND operation, returning a PartialQueryClause to which the right-hand side can be appended.
func (QueryClause) Or ¶
func (qc QueryClause) Or() PartialQueryClause
Or starts a logical OR operation, returning a PartialQueryClause to which the right-hand side can be appended.
func (QueryClause) Validate ¶
func (qc QueryClause) Validate() error
Validate checks if the query clause has at least one indexed field.
type QueryDecoder ¶
type QueryDecoder[Resource Resourcer, Request any] struct { // contains filtered or unexported fields }
QueryDecoder is a struct that returns columns that a given user has access to view
func MustNewQueryDecoder ¶
func MustNewQueryDecoder[Resource Resourcer, Request any](collection *GeneratedCollection, permissions ...accesstypes.Permission) *QueryDecoder[Resource, Request]
MustNewQueryDecoder builds a query decoder for a resource and request pair, wired to the application's generated collection so conditional grants can render. It panics on construction errors: they are programming errors (a request struct out of sync with its resource), surfaced at application startup where generated handlers construct their decoders.
func NewQueryDecoder ¶
func NewQueryDecoder[Resource Resourcer, Request any](resSet *Set[Resource]) (*QueryDecoder[Resource, Request], error)
NewQueryDecoder creates a new QueryDecoder for a given Resource and Request type.
func (*QueryDecoder[Resource, Request]) Decode ¶
func (d *QueryDecoder[Resource, Request]) Decode(request *http.Request, userPermissions UserPermissions, scope accesstypes.Scope) (*QuerySet[Resource], error)
Decode decodes an http.Request into a QuerySet and enables user permission enforcement in the given domain partition. A search box in the URL is admitted when the PII fields it would search are all denied to the caller; one the caller may search sends the filter to the body (DecodeWithoutPermissions, with no caller to ask, refuses it outright).
func (*QueryDecoder[Resource, Request]) DecodeAcrossTenants ¶ added in v0.5.0
func (d *QueryDecoder[Resource, Request]) DecodeAcrossTenants(request *http.Request, userPermissions UserPermissions) (*QuerySet[Resource], error)
DecodeAcrossTenants decodes a list request asked without the tenant's route segment into a QuerySet over a set of tenants: every tenant the session reaches (UserPermissions.Domains) in which the person holds the record's List grant, narrowed by the request's domains parameter when it carries one. Each row is checked under the person's grants in its own tenant and says which tenant it is in (Row.Tenant). The generated handler of a record declared for it calls this where the tenant's own list calls Decode; a record the generated collection does not carry as declared (@listAcrossTenants) is refused, so no list across tenants, and no live subscription over a set of tenants, is made for one.
A tenant the request names that the session does not reach narrows the set to nothing and is never an error, so the answer never says whether a tenant exists. The capability envelope is refused: a row's write permissions are its tenant's, asked on the row's page inside its tenant.
func (*QueryDecoder[Resource, Request]) DecodeWithoutPermissions ¶
func (d *QueryDecoder[Resource, Request]) DecodeWithoutPermissions(request *http.Request) (*QuerySet[Resource], error)
DecodeWithoutPermissions decodes an http.Request into a QuerySet without enforcing user permissions.
func (*QueryDecoder[Resource, Request]) WithCursorKey ¶
func (d *QueryDecoder[Resource, Request]) WithCursorKey(key *CursorKey) *QueryDecoder[Resource, Request]
WithCursorKey installs the key that seals the cursors of the pages this decoder builds and opens the ones requests carry. The generated wiring passes the application's one key (resource.NewCursorKey over the cookie key) to every decoder; without it a list serves first pages only.
func (*QueryDecoder[Resource, Request]) WithFeatures ¶
func (d *QueryDecoder[Resource, Request]) WithFeatures(features *FeatureSet) *QueryDecoder[Resource, Request]
WithFeatures installs the FeatureSet the decoder reads the gated fields' flags from; the generated wiring passes the application's. Without it every gated field stays hidden.
func (*QueryDecoder[Resource, Request]) WithPaging ¶
func (d *QueryDecoder[Resource, Request]) WithPaging(paging Paging) *QueryDecoder[Resource, Request]
WithPaging installs the resource's declared paging contract: the default order a sort-less request takes and the page sizes. The generator emits the call from the @order and @page annotations. An order field the request type does not carry is a programming error and panics at construction, like every other generated-code mismatch, and so is a page size on a key-less list, which the generator refuses at @page and which does not page (wholeListOnly).
type QueryParam ¶
QueryParam holds a single query parameter's name and value.
type QuerySet ¶
type QuerySet[Resource Resourcer] struct { // contains filtered or unexported fields }
QuerySet represents a query for a resource, including fields, keys, filters, and permissions.
func NewQuerySet ¶
NewQuerySet creates a new, empty QuerySet for a given resource metadata.
func (*QuerySet[Resource]) AddField ¶
func (q *QuerySet[Resource]) AddField(field accesstypes.Field) *QuerySet[Resource]
AddField adds a field to be returned by the query. A secret field brings its row's primary key with it (the generated SecretContext): the stored bytes open on the key, and the row's generated Open method takes the key from the row, so a row read for its secret alone would open on no key at all.
func (*QuerySet[Resource]) Admit ¶ added in v0.3.0
func (q *QuerySet[Resource]) Admit(row *Resource) (fields []accesstypes.Field, shown bool, err error)
Admit judges the row a computed resource's Read function answered. It reports whether the caller is shown the row, and the projected fields the row shows: the query set's own, without those granted under a condition the row does not meet. A nil row is not shown, so a row the caller's grants do not admit is answered as a row that is not there. With nothing to judge every row is shown whole.
func (*QuerySet[Resource]) BatchList ¶
func (q *QuerySet[Resource]) BatchList(ctx context.Context, client Client, size int) iter.Seq[iter.Seq2[*Row[Resource], error]]
BatchList executes the query and returns an iterator for the results in batches, each result wrapped in the Row envelope.
Example ¶
package main
import (
"context"
iter "iter"
"github.com/impulseframework/impulse/accesstypes"
)
type ExampleResource struct{}
func (ExampleResource) Resource() accesstypes.Resource {
return "ExampleResources"
}
func (ExampleResource) DefaultConfig() Config {
return Config{}
}
func main() {
ctx := context.Background()
client := SpannerClient{}
qSet := &QuerySet[ExampleResource]{}
// Each batch iterator must be iterated on at least once before iterating on the next batch.
// If a database iter.Seq2 errors, all following batches are invalid and iteration should halt.
for batch := range qSet.BatchList(ctx, &client, 10) {
if err := processExampleBatch(batch); err != nil {
return
}
}
// It's acceptable to break out of an iterator early and move onto the next batch iterator.
for batch := range qSet.BatchList(ctx, &client, 10) {
for row, err := range batch {
if err != nil {
return
}
if row.Data.Resource() == "" {
break
}
}
}
// BAD: Handing off batched iterators to go routines and progressing to the next batched iterator is illegal behavior.
for batch := range qSet.BatchList(ctx, &client, 10) {
go func() { _ = processExampleBatch(batch) }()
}
}
func processExampleBatch(batch iter.Seq2[*Row[ExampleResource], error]) error {
for row, err := range batch {
if err != nil {
return err
}
_ = row
}
return nil
}
Output:
func (*QuerySet[Resource]) Caller ¶ added in v0.5.0
Caller returns the caller the query was checked as: the checker, the scope and the environment its decode bound, with the collection its conditions resolve against. It is what a computed resource's generated frames stamp into the context (WithCaller) once the decode has checked the request, before the List function, the Read function or the function that renders a file runs, as a method's frame stamps the caller for its body. Such a function reads it with CallerFrom and asks as the request's own check did (Caller.Check, Caller.ExecuteGate), so a list that offers what a method takes lists what the method would accept from this caller, and nothing the function calls mistakes the request for a call the application makes itself. A handler written by hand over a computed query stamps it the same way. A QuerySet bound to no permissions answers a zero Caller, which every question refuses.
func (*QuerySet[Resource]) Collect ¶
Collect runs a computed List function's rows through the caller's grants and the parts of the query the body did not take — the residual filter, the sort, the cursor position, and the page — and returns the page the handler encodes, with the headers it writes. The order inside is fixed: the rows the caller's grants admit, then filter, then count, then sort, then page, because any other order gives a different answer. A grant under a condition that reads the row is judged here, row by row (computed_conditions.go): a row it refuses is not listed and not counted, and a field it refuses is left out of the row (Page.RowFields). A whole list (limit=all, or a key-less list) with no sort asked and no order declared is not sorted: the rows keep the order the body yielded them in, after the filter. The sort and the cursor position place NULL where the application's database does (the type the computed decoder stamped), so they agree with the rows a body's plain ORDER BY yields; a QuerySet no computed decoder produced is refused.
func (*QuerySet[Resource]) Count ¶
Count executes the query's WHERE under SELECT COUNT(*) and returns the number of rows it admits: the same filter, tenancy, and read-rule predicates as List, with no order, page, or cursor. The generated list handler runs it before the page query when the request asks count=true.
func (*QuerySet[Resource]) EnableUserPermissionEnforcement ¶
func (q *QuerySet[Resource]) EnableUserPermissionEnforcement(rSet *Set[Resource], userPermissions UserPermissions, scope accesstypes.Scope, requiredPermission accesstypes.Permission) *QuerySet[Resource]
EnableUserPermissionEnforcement enables the checking of user permissions for the QuerySet, evaluating requiredPermission for the user in the given scope partition.
An enforced QuerySet is single-shot: it binds the user (via userPermissions) and the scope for a single operation's evaluation. Build a new QuerySet per operation; never reuse one across requests or scopes.
func (*QuerySet[Resource]) Enforce ¶
func (q *QuerySet[Resource]) Enforce(caller *Caller, rSet *Set[Resource], requiredPermission accesstypes.Permission) *QuerySet[Resource]
Enforce arms the query against the caller: Read and List run the read permission gate the resource routes run (resource then requested fields, with conditional grants riding the query) before touching the database. A zero Caller refuses at execution.
func (*QuerySet[Resource]) Fields ¶
func (q *QuerySet[Resource]) Fields() []accesstypes.Field
Fields returns the list of fields to be returned by the query.
func (*QuerySet[Resource]) Filter ¶
func (q *QuerySet[Resource]) Filter() *FilterShape
Filter returns the request's filter over Go field names. Without a filter every query answers empty and Match admits every row.
func (*QuerySet[Resource]) FilterAst ¶
func (q *QuerySet[Resource]) FilterAst(dbType DBType) (ExpressionNode, error)
FilterAst returns the filter AST for the query.
func (*QuerySet[Resource]) JudgesRows ¶ added in v0.3.0
JudgesRows reports whether a grant the caller holds carries a condition the rows are judged by: some rows may be left out, or shown without a field. A List function needs nothing from it (Collect judges the rows it yields, and TakePage declines while it is true); the generated @file route asks, to know whether the row has to be read before the file is rendered.
func (*QuerySet[Resource]) Key ¶
func (q *QuerySet[Resource]) Key(field accesstypes.Field) any
Key retrieves the value of a primary key field.
func (*QuerySet[Resource]) KeySet ¶
KeySet returns the KeySet containing the primary key(s) for the resource.
func (*QuerySet[Resource]) List ¶
func (q *QuerySet[Resource]) List(ctx context.Context, txn ReadOnlyTransaction) iter.Seq2[*Row[Resource], error]
List executes the query and returns an iterator for the results, each wrapped in the Row envelope.
func (*QuerySet[Resource]) Order ¶
Order returns the total order the list is read in: the request's sort fields, or the resource's declared order when the request states none, followed by the primary-key fields not already named, ascending, so a keyset cursor walks a total order. With neither a sort nor a declared order the list is not sorted: Order answers nothing, the statement carries no ORDER BY and its rows arrive in the database's own order, and a computed list keeps the order its body yielded. A decoded request reaches that state only as a whole list, limit=all or a key-less list, in one response; a paged request with no order is refused at decode (QueryDecoder.requireOrder). A key-less list has no key fields to append, so its order is exactly the sort or the declared default. On a hand-built QuerySet it is exactly the sort the caller set.
func (*QuerySet[Resource]) Page ¶
Page returns the collector for the page this QuerySet was decoded to read.
func (*QuerySet[Resource]) Permitted ¶
Permitted reports whether the request's own gate admits the query: the required permission is granted, or granted under a condition, on the resource in the scope the decode bound, against the environment it sampled. It asks the same question the read asks of the resource before it touches a field, so a live subscription written on its answer is written exactly for a request the read would not refuse at the gate; the field and row rules still run when the query does. A QuerySet bound to no permissions is not permitted.
func (*QuerySet[Resource]) Read ¶
func (q *QuerySet[Resource]) Read(ctx context.Context, txn ReadOnlyTransaction) (*Row[Resource], error)
Read executes the query and returns a single result wrapped in the Row envelope.
func (*QuerySet[Resource]) RequestCapabilities ¶
func (q *QuerySet[Resource]) RequestCapabilities(perms ...accesstypes.Permission)
RequestCapabilities asks the read to evaluate per-row write affordances for perms and attach them under the reserved capability property (§13). The supported permissions are Update (a positive list of editable JSON field names), Delete (a boolean), and Execute (a positive list of the RPC methods whose declared transitions apply to the row). The answers are advisory hints for the UI; enforcement stays with the write stages.
func (*QuerySet[Resource]) RequiredPermission ¶
func (q *QuerySet[Resource]) RequiredPermission() accesstypes.Permission
RequiredPermission returns the permission required to execute the query.
func (*QuerySet[Resource]) Resource ¶
func (q *QuerySet[Resource]) Resource() accesstypes.Resource
Resource returns the name of the resource this QuerySet applies to.
func (*QuerySet[Resource]) ReturnAccessibleFields ¶
ReturnAccessibleFields configures the QuerySet to automatically include all fields the user has access to if no specific fields are requested.
func (*QuerySet[Resource]) Scope ¶
func (q *QuerySet[Resource]) Scope() accesstypes.Scope
Scope returns the permission scope the query is checked in: the request's tenant domain for a domain-scoped resource, the global scope otherwise. It is set by EnableUserPermissionEnforcement, which every generated handler runs at decode, so application query logic — a computed resource's List and Read — partitions its rows on the same value the permission check ran against.
func (*QuerySet[Resource]) SetFilterAst ¶
func (q *QuerySet[Resource]) SetFilterAst(ast ExpressionNode)
SetFilterAst sets the filter condition for the query using a raw expression tree.
func (*QuerySet[Resource]) SetFilterParser ¶
func (q *QuerySet[Resource]) SetFilterParser(parser func(DBType) (ExpressionNode, error))
SetFilterParser sets the filter parser.
func (*QuerySet[Resource]) SetKey ¶
func (q *QuerySet[Resource]) SetKey(field accesstypes.Field, value any)
SetKey sets a primary key field and value for the query's WHERE clause.
func (*QuerySet[Resource]) SetSortFields ¶
SetSortFields sets the sorting order for the query results.
func (*QuerySet[Resource]) SetWhereClause ¶
func (q *QuerySet[Resource]) SetWhereClause(qc QueryClause)
SetWhereClause sets the filter condition for the query using a QueryClause.
func (*QuerySet[Resource]) TakePage ¶
func (q *QuerySet[Resource]) TakePage() (PageBounds, bool)
TakePage returns the page to yield and marks paging as the body's, when paging in the body is correct: no filter condition remains for the handler, the sort was taken (the body controls the order), the request asks for a page rather than every row, no count was asked for (a total needs every row), and no grant's condition is left to judge the rows by (a row the handler leaves out would leave the body's page short). Otherwise it answers false and the handler pages; a body written for pushdown then degrades to the correct answer instead of the wrong page. A key-less list is only ever whole, so it always answers false.
func (*QuerySet[Resource]) TakeSort ¶
TakeSort returns the list's total order (the request's sort or the declared default, then the primary key) and marks it as the body's: the handler will not sort. A body that takes the sort must yield its rows in exactly this order, or its pages are wrong. An empty order means the list is not sorted, no sort asked and none declared, which a decoded request reaches only as a whole list (limit=all, or a key-less list), and the body's own yielded order is the list's; the handler leaves that order alone whether or not the body takes it. The order's NULL placement is the application database's own — Spanner first ascending and last descending, PostgreSQL the reverse — so a plain ORDER BY in the body's query produces it with no NULL handling of its own, and the handler's sort and page boundary follow the same placement whenever they still run.
func (*QuerySet[Resource]) TenantsListed ¶ added in v0.5.0
func (q *QuerySet[Resource]) TenantsListed(ctx context.Context) (set, narrowed []accesstypes.Domain, err error)
TenantsListed returns what a live subscription to this list across tenants is held over: set, the tenants the list may read (the session's reach, narrowed by the request's filter on the tenant) in which the person holds the List grant on the record, sorted; and narrowed, that filter as the request sent it, nil when it sent none. It asks the grant alone, as Permitted asks it of one tenant's list: the field and row rules run when the query does. It fails on a query that is not a list across tenants.
func (*QuerySet[Resource]) User ¶
func (q *QuerySet[Resource]) User() accesstypes.User
User returns the identity the permission check ran as: the session's user, the viewed person under a view-as session, or the real actor under an act-as-role session. A computed resource's List or Read function reads it to yield the caller's own row without reaching into the session; empty when no check was bound.
type QuerySetComparer ¶
type QuerySetComparer interface {
Resource() accesstypes.Resource
Fields() []accesstypes.Field
KeySet() KeySet
}
QuerySetComparer is an interface for comparing two QuerySet-like objects.
type RPCDecoder ¶
type RPCDecoder[Request any] struct { // contains filtered or unexported fields }
RPCDecoder decodes an HTTP request for an RPC-style endpoint, validates the request body, and enforces permissions for the RPC method.
func MustNewRPCDecoder ¶
func MustNewRPCDecoder[Request any](a DecoderAccessor, methodName accesstypes.Resource, perm accesstypes.Permission) *RPCDecoder[Request]
MustNewRPCDecoder builds a decoder for an RPC method request, resolving user permissions and validating request bodies through the accessor. It panics on construction errors: they are programming errors (a malformed request struct), surfaced at application startup where generated handlers construct their decoders.
func NewRPCDecoder ¶
func NewRPCDecoder[Request any](userPermissions func(*http.Request) UserPermissions, methodName accesstypes.Resource, perm accesstypes.Permission) (*RPCDecoder[Request], error)
NewRPCDecoder creates a new RPCDecoder for a given request type, method name, and required permission.
func (*RPCDecoder[Request]) Decode ¶
func (s *RPCDecoder[Request]) Decode(request *http.Request, scope accesstypes.Scope) (*Request, error)
Decode decodes the HTTP request body into the Request struct and checks user permissions in the given domain partition.
The check is eager (decode is the last library-controlled point before application code executes), so it must resolve to Granted or Denied: a Conditional decision here is a 500-class invariant breach — an RPC method has no rows for a condition to evaluate against, and MigrateRoles rejects such grants at deploy.
func (*RPCDecoder[Request]) DecodeCaller ¶
func (s *RPCDecoder[Request]) DecodeCaller(request *http.Request, scope accesstypes.Scope) (*Request, *Caller, error)
DecodeCaller decodes and checks like Decode and also returns the Caller the check ran as — checker, scope, and sampled environment — for the handler to stamp into the context the method's body runs under.
func (*RPCDecoder[Request]) WithCollection ¶
func (s *RPCDecoder[Request]) WithCollection(collection *GeneratedCollection) *RPCDecoder[Request]
WithCollection wires the generated collection to the decoder, so the caller it stamps can render conditional grants into the live check of a body's armed writes.
func (*RPCDecoder[Request]) WithValidator ¶
func (s *RPCDecoder[Request]) WithValidator(v ValidatorFunc) *RPCDecoder[Request]
WithValidator sets a validator function on the decoder.
type ReadOnlyTransaction ¶
type ReadOnlyTransaction interface {
SpannerReadOnlyTransaction() spxapi.Querier
PostgresReadOnlyTransaction() any
}
ReadOnlyTransaction is an interface that represents a database transaction that can be used for reads only.
type ReadOnlyTransactionCloser ¶
type ReadOnlyTransactionCloser interface {
ReadOnlyTransaction
Close()
}
ReadOnlyTransactionCloser is an interface that represents a database transaction that can be used for reads only and must be closed when it is no longer needed.
type ReadWriteTransaction ¶
type ReadWriteTransaction interface {
DBType() DBType
ReadOnlyTransaction
BufferMap(res PatchSetMetadata, patch map[string]any) error
BufferStruct(res PatchSetMetadata) error
// DataChangeEventIndex provides a sequence number for data change events on the same Resource inside the same transaction
DataChangeEventIndex(res accesstypes.Resource, rowID string) int
}
ReadWriteTransaction is an interface that represents a database transaction that can be used for both reads and writes.
type Reader ¶
type Reader[Resource Resourcer] interface { DBType() DBType Read(ctx context.Context, stmt *Statement) (*Row[Resource], error) List(ctx context.Context, stmt *Statement) iter.Seq2[*Row[Resource], error] // Count runs a statement whose single row and column is a count and returns it. Count(ctx context.Context, stmt *Statement) (int64, error) }
Reader is an interface that wraps methods for reading resources from a database. Read and List return each row wrapped in the Row envelope, which carries the row data alongside per-row metadata.
type ReleaseFile ¶
type ReleaseFile struct {
Outlets map[string]ReleaseOutlet `json:"outlets"`
Scheduled []ScheduledRoute `json:"scheduled,omitempty"`
// FileRoutes are the routes that carry a file rather than JSON, in path order: each
// @upload method's route and each stored file's read route (@file). None when the
// code declares neither.
FileRoutes []FileRoute `json:"fileRoutes,omitempty"`
// Surfaces are the surfaces the code declares a request log word or a trace setting
// for, in prefix order: the application default as the surface at /
// (WithRequestLog), each outlet that declares a word or a setting as its prefix
// (OutletRequestLog, OutletTraces), each prefix the application mounts routes under
// by hand (WithMountedRoutes), and each generated route with its own words (@rpc,
// @file, @schedule) as the path the router mounts it at. Each says whether it is a
// prefix or a route (Kind), since the router matches the two differently. The
// nearest declaration wins, so a reader resolves a path by its longest matching
// surface. The application's stack reads them to render the cloud's own request-log
// exclusion. None when the code declares nothing, and then every request's entry is
// written and every span follows the front end.
Surfaces []Surface `json:"surfaces,omitempty"`
}
ReleaseFile is the generated release file: one entry per outlet, keyed by the outlet's name (default for the outlet GenerateRoutes declares, the name given to WithRouterOutlet otherwise), and the scheduled routes in path order, absent when the application declares none.
func ReadReleaseFile ¶
func ReadReleaseFile(dir string) (ReleaseFile, error)
ReadReleaseFile reads the generated release file from dir, the router package's directory. A missing file is an error wrapping fs.ErrNotExist: no router is generated there, or the application predates the file. A file that is not the shape the generator writes, or that names no outlet, is refused naming what is wrong.
type ReleaseOutlet ¶
type ReleaseOutlet struct {
// APIKey marks a machine outlet (Tokens in the generator program), written as
// {"kind": "api-key"}: its clients carry no release, so nothing is checked against
// one, and the entry carries no oldestAnswered.
APIKey bool
// OldestAnswered is a session outlet's oldest answered release as the generator
// program declared it: a release such as 1.5.0; ThisRelease, written as "this", for
// a release that changes the API inside a maintenance window; or empty, written as
// "", when the option is absent and every release that sends the header is
// answered. Empty on a machine outlet.
OldestAnswered string
// Programs are the programs the release ships through a machine outlet
// (ShipsProgram in the generator program), in declaration order, written as
// "programs" on the outlet's entry and absent when it ships none: the version build
// compiles each for its platforms and the outlet serves the compiled files to their
// installed copies. A session outlet ships none.
Programs []ReleaseProgram
}
ReleaseOutlet is one outlet's entry in the release file. A session outlet carries its oldest answered release; a machine outlet is never checked against a release and carries its kind and the programs the release ships through it.
func (ReleaseOutlet) MarshalJSON ¶
func (o ReleaseOutlet) MarshalJSON() ([]byte, error)
MarshalJSON writes the entry as the file spells it: {"kind": "api-key"} for a machine outlet, with its programs when it ships any, {"oldestAnswered": <release>} for a session outlet with ThisRelease as "this". A session outlet carrying programs, or a program the generator would not write, is refused.
func (*ReleaseOutlet) UnmarshalJSON ¶
func (o *ReleaseOutlet) UnmarshalJSON(data []byte) error
UnmarshalJSON reads an entry as the file spells it and refuses one that is neither a machine outlet nor a session outlet naming its oldest answered release: a kind other than api-key, a machine outlet carrying oldestAnswered, a session outlet without it or carrying programs, an oldestAnswered that is neither a release, "this" nor empty, or a program that is not the shape the generator writes.
type ReleaseProgram ¶
type ReleaseProgram struct {
Name string `json:"name"`
Dir string `json:"dir"`
Platforms []string `json:"platforms"`
}
ReleaseProgram is one program a machine outlet ships, as the release file spells it: the main package's root-relative directory (cmd/corral), the program's name, the base of that directory (corral), and the platforms it is compiled for, each as <os>/<arch> (linux/amd64).
type ReleasedKey ¶
ReleasedKey is one object a transaction's patches let go of: the key, and the store it belongs to.
type RequestFieldMapper ¶
type RequestFieldMapper struct {
// contains filtered or unexported fields
}
RequestFieldMapper provides a mapping between JSON field names (from struct tags) and their corresponding Go struct field names. A field's former wire name (its formerly tag) maps to the field as its current name does, so a request naming the former name reaches the same field.
func NewRequestFieldMapper ¶
func NewRequestFieldMapper(v any) (*RequestFieldMapper, error)
NewRequestFieldMapper creates a new RequestFieldMapper by inspecting the struct tags of the provided value.
func (*RequestFieldMapper) Fields ¶
func (f *RequestFieldMapper) Fields() []accesstypes.Field
Fields returns a slice of all Go struct field names.
func (*RequestFieldMapper) FormerNames ¶
func (f *RequestFieldMapper) FormerNames() map[string]string
FormerNames returns the mapping from each field's former wire name to its current one; empty when no field declares a former name.
func (*RequestFieldMapper) JSONNames ¶
func (f *RequestFieldMapper) JSONNames() map[accesstypes.Field]string
JSONNames returns the mapping from Go struct field names to their primary JSON names — a field without a json tag maps to its own name.
func (*RequestFieldMapper) Len ¶
func (f *RequestFieldMapper) Len() int
Len returns the number of mapped names, former names included.
func (*RequestFieldMapper) StructFieldName ¶
func (f *RequestFieldMapper) StructFieldName(jsonTag string) (accesstypes.Field, bool)
StructFieldName retrieves the Go struct field name for a given JSON tag, the field's current wire name or its former one.
type Resourcer ¶
type Resourcer interface {
Resource() accesstypes.Resource
}
Resourcer is an interface that all resource structs must implement.
type RolePermissions ¶
type RolePermissions interface {
// Check returns the Decision for perm on each of resources within scope,
// evaluated against the role's effective grants. See
// UserPermissionChecker.Check for the contract every implementation owes:
// an entry per resource, no short-circuit, one snapshot per call.
Check(ctx context.Context, env accesstypes.Environment, scope accesstypes.Scope, perm accesstypes.Permission, resources ...accesstypes.Resource) (accesstypes.Decisions, error)
// PermissionDigest returns the role's structural grant enumeration within
// scope. See UserPermissionChecker.PermissionDigest.
PermissionDigest(ctx context.Context, scope accesstypes.Scope) (accesstypes.PermissionDigest, error)
// HasGrants reports whether the role holds at least one grant in scope.
// See UserPermissionChecker.HasGrants.
HasGrants(ctx context.Context, scope accesstypes.Scope) (bool, error)
}
RolePermissions is the permission surface of a session that operates as a role principal: UserPermissionChecker without User(), because a role is not anyone. SessionPermissions completes it into the UserPermissions every decoder consumes by supplying the session's effective identity as User().
The canonical implementation is the access package's request-bound role checker (Client.ForRole), which satisfies this interface structurally — neither package imports the other.
func RolePrincipalsUnsupported ¶
func RolePrincipalsUnsupported(accesstypes.Role) RolePermissions
RolePrincipalsUnsupported is the forRole argument for SessionPermissions in an application that does not operate sessions as roles. It returns nil, which SessionPermissions replaces with a fail-closed checker for the role.
type Row ¶
type Row[Resource Resourcer] struct { // Data is the row itself, exactly as scanned from the database. A masked cell // holds its type's zero value (a date cell the earliest date, 0001-01-01); // Masked is what distinguishes it from a genuine zero. Data Resource // contains filtered or unexported fields }
Row is the generic per-row envelope yielded by List and returned by Read. It carries the row data together with per-row metadata; cell masking is the envelope's first metadata tenant, populated from the read statement's reserved masked-names column when conditional grants render into the query.
func (Row[Resource]) Capabilities ¶
func (r Row[Resource]) Capabilities() map[accesstypes.Permission]any
Capabilities returns this row's capability answers (§13): per requested permission, Update's positive list of editable JSON field names or Delete's boolean. Nil when the request did not opt in — handlers attach the reserved capability property only when this is non-nil. The answers are advisory hints for the UI; enforcement stays with the write stages.
func (Row[Resource]) MarshalJSON ¶
MarshalJSON delegates to the row data: marshaling a Row produces exactly the bytes that marshaling the Resource itself would.
func (Row[Resource]) Masked ¶
Masked reports whether the cell with the given JSON name is masked on this row.
func (Row[Resource]) Tenant ¶ added in v0.5.0
func (r Row[Resource]) Tenant() accesstypes.Domain
Tenant returns the tenant the row is in, on a row of a list across tenants (QueryDecoder.DecodeAcrossTenants): the generated handler names it on the row under TenantProperty, so a page groups the rows by tenant and opens each one inside its tenant's routes. Empty on every other row.
type RowChange ¶
RowChange is one row a committed transaction wrote: its key as the read route spells it (RowKey), and whether the write deleted it.
type SQLDialect ¶
type SQLDialect int
SQLDialect defines the type of SQL dialect to generate.
const ( // PostgreSQL dialect. PostgreSQL SQLDialect = iota // Spanner dialect. Spanner )
type ScheduledRoute ¶
type ScheduledRoute struct {
// Path is the route's path, under the scheduled prefix: /_scheduled/<method in kebab
// case>.
Path string `json:"path"`
// Schedule is the cron expression as declared: five fields, minute, hour, day of the
// month, month and day of the week.
Schedule string `json:"schedule"`
// TimeZone is the zone the schedule is read in, an IANA zone name as declared, or
// UTC when the declaration names none.
TimeZone string `json:"timeZone"`
}
ScheduledRoute is one scheduled route in the release file: the method declared with @schedule, as the generated router mounts it and Cloud Scheduler calls it.
type SearchAnchor ¶
type SearchAnchor string
SearchAnchor is a relative search type a token column was tokenized with.
const ( // SearchAnchorPrefix is relative_search_types value_prefix: the term matches at the // start of the value. SearchAnchorPrefix SearchAnchor = "prefix" // SearchAnchorSuffix is value_suffix: the term matches at the end of the value. SearchAnchorSuffix SearchAnchor = "suffix" )
type SearchBranch ¶
type SearchBranch struct {
// Name is the field's dotted name in the parent's search field list and the box's
// placeholder: clientContact.displayName.
Name string
// Resource is the child resource and Field its Go field; Tag is the field's wire
// name, under which its permission is checked (Resource.Tag).
Resource accesstypes.Resource
Field accesstypes.Field
Tag accesstypes.Tag
// Table is the child table, Column the text column, JoinColumn the foreign key to
// the parent's key, and TenantColumn the child's bare tenant column, "" when the
// pair is global.
Table string
Column string
JoinColumn string
TenantColumn string
// The child field's search fact.
Token string
Index string
Role SearchRole
Anchors []SearchAnchor
Contains bool
Zone string
// PII says the child field is PII, so the box posts.
PII bool
}
SearchBranch is one @searchAlso declaration as the generated SearchBranches method carries it: a child table's text a parent's box also searches, mapped to the parent's key through the child's foreign key. The renderer adds one branch per declaration to each term's key set; the child field's own permission governs the branch.
type SearchColumn ¶
SearchColumn is one searchable column of a resource as the generated query builder declares it for the search box: the column and its search tag.
type SearchRole ¶
type SearchRole string
SearchRole is how a field's token column reads its column, which decides how a typed term is normalized before it is bound.
const ( // SearchRoleText tokenizes the column as it is: TOKENIZE_SUBSTRING(col). The term // binds as typed; Spanner folds case and punctuation. SearchRoleText SearchRole = "text" // SearchRoleDigits tokenizes the column's digits: TOKENIZE_SUBSTRING(REGEXP_REPLACE // (col, r'\D', ”)). Everything but digits is stripped from the term, so "123-45" // meets "123454321". SearchRoleDigits SearchRole = "digits" // SearchRoleDate tokenizes a date or timestamp as YYYYMMDD: TOKENIZE_SUBSTRING // (FORMAT_DATE('%Y%m%d', col)), or FORMAT_TIMESTAMP with the zone the day is read // in. The term is read as a date in the forms the server accepts and binds YYYYMMDD // or its prefix. SearchRoleDate SearchRole = "date" )
type SearchSpec ¶
type SearchSpec struct {
// Token is the TOKENLIST column tokenizing the field's column, "" without the
// search fact.
Token string
// Index is the search index carrying Token: the key-set statement groups a view's
// fields by it.
Index string
// Role is how Token reads the column.
Role SearchRole
// Anchors are the relative search types Token was tokenized with.
Anchors []SearchAnchor
// Contains says Token answers an unanchored match: false under
// short_tokens_only_for_anchors, where the field answers its anchors alone.
Contains bool
// Lower is the stored LOWER(col) column that leads an index or sits after the tenant
// column in one: the prefix fact. "" without it.
Lower string
// Diacritics says Token was tokenized with remove_diacritics, so the in-memory
// matcher folds them too.
Diacritics bool
// Zone is the time zone a date role over a timestamp formats its day in, as the
// schema names it; "" on a DATE column, which has none.
Zone string
// InMemory marks a computed resource's allow_filter string field: every match and the
// box are evaluated by the handler over the rows the body yields, with no column
// behind them.
InMemory bool
}
SearchSpec is the search tag's content: what a field answers and through which columns. The generator writes it onto a list or read request struct field (Tag), the decoder reads it back (parseSearchSpec), and the renderer binds the field's matches through it. A field with a Token joins its resource's box; a field with a Lower column alone answers startswith and nothing else.
func (*SearchSpec) Answers ¶
func (s *SearchSpec) Answers(operator string) bool
Answers reports whether the field answers the match as an explicit operator on a string field: contains through an unanchored token column, startswith through the lowercased column or a prefix anchor, endswith through a suffix anchor; an evaluated field answers all three.
func (*SearchSpec) HasAnchor ¶
func (s *SearchSpec) HasAnchor(anchor SearchAnchor) bool
HasAnchor reports whether the token column was tokenized with the anchor.
func (*SearchSpec) JoinsBox ¶
func (s *SearchSpec) JoinsBox() bool
JoinsBox reports whether the field takes part in its resource's search box: a field with the search fact, or a computed resource's evaluated field. A field with the prefix fact alone does not: the box over a table with a search index never mixes in the prefix fact, so a table serves its box from one index.
func (*SearchSpec) Matches ¶
func (s *SearchSpec) Matches() []string
Matches lists the explicit matches the field answers, in the order the metadata spells them.
func (*SearchSpec) Tag ¶
func (s *SearchSpec) Tag() string
Tag renders the spec as the search tag's value, the form parseSearchSpec reads.
type Secret ¶ added in v0.5.0
type Secret struct {
// contains filtered or unexported fields
}
Secret is the type of a resource field that holds a secret (conditions:"secret"): the bytes its column stores and nothing else. It goes in and out of the database unchanged, on Spanner and on PostgreSQL. It prints as [secret] in JSON, in logs, through fmt and in error text, and it has no method that gives the value that was sealed: SecretKeys opens it, through the generated Open<Field> method of its row. A nullable column is typed *Secret. The zero Secret holds no value.
func (*Secret) DecodeSpanner ¶ added in v0.5.0
DecodeSpanner implements spanner.Decoder: the stored bytes of a BYTES column, which the client hands over in base64, and no value for NULL.
func (Secret) EncodeSpanner ¶ added in v0.5.0
EncodeSpanner implements spanner.Encoder: the stored bytes, for a BYTES column; NULL for a Secret that holds no value.
func (Secret) Equal ¶ added in v0.5.0
Equal reports whether two Secrets hold the same stored bytes. Two writes of one value never do, since each draws its own random number.
func (Secret) Format ¶ added in v0.5.0
Format implements fmt.Formatter: every verb prints [secret], so no verb reaches the stored bytes.
func (Secret) KeyVersion ¶ added in v0.5.0
KeyVersion returns the version of the application secret the value was sealed under, which its first two bytes name; 0 for a Secret that holds no value, or too few bytes to name a version.
func (Secret) MarshalJSON ¶ added in v0.5.0
MarshalJSON implements json.Marshaler and answers "[secret]".
func (Secret) MarshalText ¶ added in v0.5.0
MarshalText implements encoding.TextMarshaler and answers [secret].
func (*Secret) Scan ¶ added in v0.5.0
Scan implements sql.Scanner: the stored bytes of a bytea column, and no value for NULL.
func (*Secret) UnmarshalJSON ¶ added in v0.5.0
UnmarshalJSON refuses: a Secret holds stored bytes, which only the database gives it. A request carries a secret as text, in a string field declared conditions:"secret".
type SecretFieldRetirement ¶ added in v0.5.0
type SecretFieldRetirement struct {
Resource accesstypes.Resource
Field accesstypes.Field
Rewritten int
}
SecretFieldRetirement is one secret field of a retirement: how many of its values named the retired version and were written again under the current one.
type SecretHolder ¶ added in v0.5.0
type SecretHolder struct {
// Resource is the resource holding the secrets.
Resource accesstypes.Resource
// Fields are its secret fields, in the struct's order.
Fields []accesstypes.Field
// contains filtered or unexported fields
}
SecretHolder is a resource that stores secrets: its secret fields, and how a retirement of a version of the application secret reads and rewrites the values they hold. The generator writes one for each resource with a stored secret into the resources package's SecretHolders(), which the application's migrate command hands to RetireSecretVersion.
func SecretHolderOf ¶ added in v0.5.0
func SecretHolderOf[R Resourcer]() SecretHolder
SecretHolderOf declares a table resource as a holder of stored secrets: the fields its struct declares conditions:"secret". The generated SecretHolders calls it.
type SecretKeys ¶ added in v0.5.0
type SecretKeys struct {
// contains filtered or unexported fields
}
SecretKeys seals and opens the secrets a resource stores (Secret). It is built once at start from the versions of the application secret (NewSecretKeys) and handed to the database client (WithSecretKeys), and it is the one thing in the process that holds key material: the versions it was built from are not kept, only the working keys derived from them. A value is sealed under the highest version given, the current one, and opened under whichever version its first two bytes name.
func NewSecretKeys ¶ added in v0.5.0
func NewSecretKeys(versions map[int][]byte) (*SecretKeys, error)
NewSecretKeys builds the key holder from the versions of the application secret: each version's number, 1 to 65535, with its 32 random bytes. The highest version is the current one. A deployment hands the versions over in the environment (SecretKeysFromEnv); a test builds the holder from fixed bytes.
func SecretKeysFromEnv ¶ added in v0.5.0
func SecretKeysFromEnv(name string, environ []string) (*SecretKeys, error)
SecretKeysFromEnv builds the key holder from the environment, where a deployment hands over every enabled version of the application secret in a variable of its own: the name the configuration declares secret:"versioned", an underscore and the version's number (APP_SECRET_KEY_1, APP_SECRET_KEY_2), each holding the version's 32 random bytes in Base64. environ is os.Environ(): the whole list is read, so every variable the name numbers is either a version or an error, and none is passed over.
With no version in the environment it answers no error and a holder that holds no key: an application that stores no secret runs without the variable, and one that stores a secret is refused at start by its generated router (RequireSecretKeys), which names the variable that is missing from the name the holder was read under. A variable that is set and does not hold a version is an error naming the variable, never its value. The declared name with no version number is no version, and is not read: set to a value with no numbered version beside it, it is the secret put in the wrong variable, and is refused by name with the variable to use. A stored value names the version that sealed it in two bytes, so versions run from 1 to 65535: the variable of a version past the last is an error, since the service would otherwise go on sealing under an older version than the deployment's newest, and so is the variable of version 0, which no deployment hands over.
func (*SecretKeys) Current ¶ added in v0.5.0
func (k *SecretKeys) Current() int
Current returns the version new values are sealed under: the highest one given.
func (*SecretKeys) Open ¶ added in v0.5.0
func (k *SecretKeys) Open(key KeySet, stored Secret) (string, error)
Open decrypts the stored bytes of a secret field of the row whose primary key is key, under the version they name. The generated Open<Field> method of a row calls it with the row's own key, so an author never passes one. Bytes that name a version the holder was not given answer an UnknownSecretVersionError, and bytes that were written for another row or altered answer ErrSecretNotOpened.
func (*SecretKeys) OpenNullable ¶ added in v0.5.0
func (k *SecretKeys) OpenNullable(key KeySet, stored *Secret) (*string, error)
OpenNullable opens the secret of a nullable column: no value for a row that holds none, and what Open answers otherwise.
func (*SecretKeys) Seal ¶ added in v0.5.0
func (k *SecretKeys) Seal(key KeySet, plain string) (Secret, error)
Seal encrypts a value for the row whose primary key is key, under the current version: the stored bytes of the row's secret field. key carries every key column's value in key order; the write path, which calls this for a patch, takes it from the patch.
func (*SecretKeys) Versions ¶ added in v0.5.0
func (k *SecretKeys) Versions() []int
Versions returns the versions the holder was given, ascending.
type SecretRetirement ¶ added in v0.5.0
type SecretRetirement struct {
// Variable is the variable the retired version is handed over in, as it was given.
Variable string
// Version is the version retired, and Current the one its values now name.
Version int
Current int
// Fields are the secret fields read, in holder order.
Fields []SecretFieldRetirement
}
SecretRetirement is what a retirement did: the version retired, the current version its values were written under, and how many values of each secret field it rewrote. It holds no value.
func RetireSecretVersion ¶ added in v0.5.0
func RetireSecretVersion(ctx context.Context, client Client, variable string, holders ...SecretHolder) (*SecretRetirement, error)
RetireSecretVersion writes every stored secret that names one version of the application secret again under the current version, and confirms that none is left: what makes the version safe to disable. variable is the variable the version is handed over in, the name the configuration declares secret:"versioned", an underscore and the version's number (APP_SECRET_KEY_1), as the migrate command's -retire-secret flag is given it. holders are the application's resources that store a secret (the generated SecretHolders of each resources package).
The client holds the secret keys (WithSecretKeys), built from every enabled version, the one being retired among them: its values are opened under it, so a retirement that was not handed that version is refused before anything is read, naming the variable that is missing. The current version, the highest the client was given, cannot be retired, since new values are sealed under it. A value that does not open (its bytes were moved from another row, or altered) is passed over, and every value that opens, in every field of every holder, is written all the same; the retirement then fails with how many do not open, naming the resource, field and row of the first of them, never a value. A value that still names the version when the retirement has finished is an error too. Running it again is safe: a second run finds nothing to write and answers a retirement that rewrote nothing.
The service keeps serving meanwhile. A value is written back only while its row still holds the bytes that were opened, read again inside the writing transaction, so a value set since is never overwritten; the rewrite is the stored bytes alone, with no permission check, no update function and no change record, since the value did not change.
func (*SecretRetirement) Rewritten ¶ added in v0.5.0
func (r *SecretRetirement) Rewritten() int
Rewritten is how many values the retirement wrote again, over every field.
type SessionUserChecker ¶ added in v0.5.0
type SessionUserChecker interface {
UserPermissionChecker
// SuperAdministrator reports whether the user holds the Super
// Administrator role (accesstypes.SuperAdministrator), the role the
// framework defines in every auth: its holder enters every tenant,
// whatever the tenant's sign-in settings say. Holding another role in the
// global partition, or a role in every tenant, is not it.
SuperAdministrator(ctx context.Context) (bool, error)
// AdministersTenant reports whether the user administers the tenant: they
// hold one of the roles the application names as a tenant's
// administrator's in the tenant itself, inside its period, by a membership
// of their own in the tenant's domain or through a group kept in that
// tenant. A role held in every tenant, or through a group kept for the
// whole application, is not it. A tenant that admits its people through
// its directory only still admits its own administrators with a password
// and a second factor (signin.TenantDeclaration.AdmitsAdministrator).
AdministersTenant(ctx context.Context, domain accesstypes.Domain) (bool, error)
}
SessionUserChecker is the checker SessionPermissions takes for a person: a UserPermissionChecker that also says whether the person is a super administrator. The session's reach into a tenant asks it of the session's actor, so the answer is the real person's behind an impersonated session.
The canonical implementation is the access package's request-bound checker (Client.ForUser), which satisfies this interface structurally.
type Set ¶
type Set[Resource Resourcer] struct { // contains filtered or unexported fields }
Set holds metadata about a resource, including its permissions and field-to-tag mappings.
func NewSet ¶
func NewSet[Resource Resourcer, Request any](permissions ...accesstypes.Permission) (*Set[Resource], error)
NewSet creates a new Set for a given Resource and Request type. Field-level enforcement is structural: every client-addressable field of Request requires the given permissions (Delete stays resource-level and is never required per field), except fields carrying the perm:"-" primary-key exemption, whose readability follows the resource-level grant.
func (*Set[Resource]) BaseResource ¶
func (r *Set[Resource]) BaseResource() accesstypes.Resource
BaseResource returns the base name of the resource (without any tags).
func (*Set[Resource]) ImmutableFields ¶
func (r *Set[Resource]) ImmutableFields() map[accesstypes.Tag]struct{}
ImmutableFields returns a map of tags for fields that are marked as immutable.
func (*Set[Resource]) PermissionRequired ¶
func (r *Set[Resource]) PermissionRequired(fieldName accesstypes.Field, perm accesstypes.Permission) bool
PermissionRequired checks if a specific permission is required for a given field.
func (*Set[Resource]) Permissions ¶
func (r *Set[Resource]) Permissions() []accesstypes.Permission
Permissions returns all permissions associated with the resource set.
func (*Set[Resource]) Positional ¶
func (r *Set[Resource]) Positional(fieldName accesstypes.Field) bool
Positional reports whether the field declared masking:"positional": its masked cells stay hidden in the output, but a sort or filter on it runs on the real column (see MaskingPositional).
func (*Set[Resource]) Resource ¶
func (r *Set[Resource]) Resource(fieldName accesstypes.Field) accesstypes.Resource
Resource returns the full resource name for a field, including its tag (e.g., "myresource.myfield").
func (*Set[Resource]) ResourceMetadata ¶
ResourceMetadata returns the metadata for the resource.
func (*Set[Resource]) TagPermissions ¶
func (r *Set[Resource]) TagPermissions() accesstypes.TagPermissions
TagPermissions returns the mapping of tags to their required permissions.
type SetCache ¶
SetCache holds a resource's canonical permission Sets, one per operation, built on first use from the generated wire struct that mirrors what the resource routes accept. The generated resources package declares one per resource and shape, so hand-written operations armed with Enforce meet exactly the field permissions the routes enforce.
func (*SetCache[Resource, Request]) For ¶
func (c *SetCache[Resource, Request]) For(perm accesstypes.Permission) *Set[Resource]
For returns the Set requiring perm on every addressable field. Construction errors are programming errors in generated code and panic.
type SetData ¶
type SetData struct {
Permissions []accesstypes.Permission
TagPermissions accesstypes.TagPermissions
ImmutableFields map[accesstypes.Tag]struct{}
// PositionalFields are the tags declared masking:"positional".
PositionalFields map[accesstypes.Tag]struct{}
// FormerTags maps each renamed field's tag to its former wire name (the formerly
// tag); nil when no field was renamed.
FormerTags map[accesstypes.Tag]accesstypes.Tag
}
SetData describes what registering a resource.Set built from a request struct adds to a GeneratedCollection: the resource-level permissions, the tag-to-permission mappings (including tags registered without permissions), and the immutable tags.
func NewSetData ¶
func NewSetData(fields []FieldTags, permissions ...accesstypes.Permission) (SetData, error)
NewSetData computes the registration data for a request struct described by fields, mirroring NewSet over the equivalent struct, always registering every field (even exempt ones) so generated Collection/TypeScript output is complete.
It diverges from the runtime Set in exactly one documented way: Update is stripped from immutable tags. The grantable matrix is the enforcement matrix minus Update-on-immutable — an immutable field's Update requirement must never be satisfiable, so the Collection (and therefore MigrateRoles) never exposes it as grantable, while the runtime Set keeps requiring it (defense-in-depth behind the decoder's 400-on-update).
type SetFeatureRequest ¶
SetFeatureRequest is the SetFeature method's body: the flag and the value to write.
type SetFeatureResult ¶
type SetFeatureResult struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
UpdatedAt time.Time `json:"updatedAt"`
}
SetFeatureResult is the SetFeature method's answer: the flag as the table holds it after the write, read back from the reloaded copy.
type SignalKind ¶
type SignalKind string
SignalKind names one kind of shared state an application's instances signal each other about: a signal carries nothing but the fact that something of the kind changed, and every instance subscribed to the kind rereads what it keeps of it. The live service carries the signals (live.Signaler and live.Subscriber over one signals document per application, a field per kind), and the kinds are declared here, in the package the live package imports, so the live package, the access adapter and the tenant roster all name one type without an import cycle; the live package re-exports it as live.Kind with the same constants.
const ( // KindFeatures is a feature flag flip: every FeatureSet following it rereads the // FeatureFlags table. KindFeatures SignalKind = "features" // KindTenants is a change of the tenant roster: an instance holding the roster // rereads it. KindTenants SignalKind = "tenants" // KindPolicy is a change of the permission policy (roles, grants, memberships): an // instance holding a policy snapshot rereads it. KindPolicy SignalKind = "policy" )
The kinds.
type SignalSubscriber ¶
type SignalSubscriber interface {
Subscribe(kind SignalKind, onSignal func()) (stop func(), err error)
}
SignalSubscriber delivers the signals of a kind: what a FeatureSet follows. onSignal runs on every signal of the kind after the subscription began, on the subscriber's goroutine, so it must return quickly; stop ends the subscription. The live service implements it (live.Subscriber).
type Signaler ¶
type Signaler interface {
Signal(ctx context.Context, kind SignalKind) error
}
Signaler signals every instance of the application that a kind of shared state changed: what a flip signals through. The live service implements it (live.Signaler); a failure is the caller's to log and never fails the request, since every subscriber also rereads at its own backstop.
type SortDirection ¶
type SortDirection string
SortDirection defines the sort direction for a field.
const ( // SortAscending specifies sorting in ascending order. SortAscending SortDirection = "asc" // SortDescending specifies sorting in descending order. SortDescending SortDirection = "desc" )
type SortField ¶
type SortField struct {
Field string
Direction SortDirection
}
SortField represents a field to sort by, including the field name and sort direction.
type SpannerClient ¶
type SpannerClient struct {
// contains filtered or unexported fields
}
SpannerClient is a wrapper around the database.
func NewSpannerClient ¶
func NewSpannerClient(db *spanner.Client, opts ...ClientOption) *SpannerClient
NewSpannerClient creates a new Client. WithFileStore and WithNamedFileStore hand it the stores the frames drive and a committed transaction's released file objects are deleted from; a store wired twice, or two stores on one location, panics here. WithSecretKeys hands it the keys its transactions seal a patch's secret fields with.
func (*SpannerClient) DBType ¶
func (c *SpannerClient) DBType() DBType
DBType returns the database type.
func (*SpannerClient) ExecuteFunc ¶
func (c *SpannerClient) ExecuteFunc(ctx context.Context, f func(ctx context.Context, txn ReadWriteTransaction) error) error
ExecuteFunc executes a function within a read-write transaction. A commit Spanner refuses for a reason the caller can act on (a referential refusal, a duplicate key or unique value, a violated CHECK constraint, an update of a row that does not exist) answers as a 4xx whose message is composed from the patches the transaction buffered (see translateCommitError); an error the function itself returns, and a commit refused with any other code, pass through unchanged.
Before the commit, a transaction whose patches release a file object of a store the client holds no store for is refused naming the store: the rows would go and the object would stay with nothing to delete it. Once the commit lands, the file objects the transaction's patches released (a deleted row's @file keys, the old key of a row pointed at another object) are deleted from their stores, synchronously, before ExecuteFunc returns, detached from the request's cancellation; a failed delete is logged naming the keys and the call still returns nil, since the rows are gone. A transaction that does not commit, for any reason, releases nothing. Last, what the transaction's writes registered for after the commit runs (AfterCommit), in registration order; a transaction that does not commit runs none of it.
func (*SpannerClient) FileStore ¶
func (c *SpannerClient) FileStore(name StoreName) FileStore
FileStore returns the store wired under name, nil when none is.
func (*SpannerClient) PostgresReadOnlyTransaction ¶
func (c *SpannerClient) PostgresReadOnlyTransaction() any
PostgresReadOnlyTransaction panics because it is not implemented for the SpannerClient.
func (*SpannerClient) ReadOnlyTransaction ¶
func (c *SpannerClient) ReadOnlyTransaction() ReadOnlyTransactionCloser
ReadOnlyTransaction returns a read-only transaction that can be used for multiple reads from the database. You must call Close() when the ReadOnlyTransaction is no longer needed to release resources on the server.
func (*SpannerClient) SpannerReadOnlyTransaction ¶
func (c *SpannerClient) SpannerReadOnlyTransaction() spxapi.Querier
SpannerReadOnlyTransaction returns a read-only transaction for the Spanner client.
type SpannerGenerator ¶
type SpannerGenerator struct {
// contains filtered or unexported fields
}
SpannerGenerator is a SQL generator for Spanner.
func NewSpannerGenerator ¶
func NewSpannerGenerator() *SpannerGenerator
NewSpannerGenerator creates a new SpannerGenerator.
func (*SpannerGenerator) GenerateSQL ¶
func (g *SpannerGenerator) GenerateSQL(node ExpressionNode) (sqlStr string, params map[string]any, err error)
GenerateSQL generates SQL for the given node and returns named parameters.
type SpannerReadOnlyTransaction ¶
type SpannerReadOnlyTransaction struct {
// contains filtered or unexported fields
}
SpannerReadOnlyTransaction represents a database transaction that can only be used for reads.
func (*SpannerReadOnlyTransaction) Close ¶
func (c *SpannerReadOnlyTransaction) Close()
Close closes the readonly transaction
func (*SpannerReadOnlyTransaction) PostgresReadOnlyTransaction ¶
func (c *SpannerReadOnlyTransaction) PostgresReadOnlyTransaction() any
PostgresReadOnlyTransaction panics because it is not implemented for the SpannerReadOnlyTransaction.
func (*SpannerReadOnlyTransaction) SpannerReadOnlyTransaction ¶
func (c *SpannerReadOnlyTransaction) SpannerReadOnlyTransaction() spxapi.Querier
SpannerReadOnlyTransaction returns a read-only transaction for the Spanner client.
type SpannerReadWriteTransaction ¶
type SpannerReadWriteTransaction struct {
// contains filtered or unexported fields
}
SpannerReadWriteTransaction represents a database transaction that can be used for both reads and writes. It records the resource and patch type of every patch it buffers, so a commit Spanner refuses can be answered in terms of what the transaction was asked to do; the file objects its patches release, so the executor deletes them once the commit lands; and the rows its patches write, so the request publishes them to the live pages once the commit lands.
func NewSpannerReadWriteTransaction ¶
func NewSpannerReadWriteTransaction(txn *spanner.ReadWriteTransaction) *SpannerReadWriteTransaction
NewSpannerReadWriteTransaction creates a new SpannerReadWriteTransaction from a spanner.ReadWriteTransaction. A transaction an application wraps itself and commits outside ExecuteFunc has no executor to delete the file objects its patches released: read them off the wrapper with Released after the commit and delete them from the store yourself. It also has no executor to hand the rows it wrote to the request's collector, so nothing it writes reaches the live pages, and none to run what its writes registered for after the commit (AfterCommit): call Committed once the commit has landed. And it has no client to take the application's secret keys from: a transaction whose patches set a secret field is given them with WithSecretKeys.
func (*SpannerReadWriteTransaction) BufferMap ¶
func (c *SpannerReadWriteTransaction) BufferMap(r PatchSetMetadata, patch map[string]any) error
BufferMap buffers a map of changes to be applied to the database.
func (*SpannerReadWriteTransaction) BufferStruct ¶
func (c *SpannerReadWriteTransaction) BufferStruct(patch PatchSetMetadata) error
BufferStruct buffers a struct of changes to be applied to the database.
func (*SpannerReadWriteTransaction) Committed ¶ added in v0.3.0
func (c *SpannerReadWriteTransaction) Committed(ctx context.Context)
Committed runs what the transaction's writes registered for after the commit (AfterCommit), for a transaction committed outside ExecuteFunc, whose executor makes the calls itself. Call it once, after the commit has landed, and never for a transaction that did not commit.
func (*SpannerReadWriteTransaction) DBType ¶
func (c *SpannerReadWriteTransaction) DBType() DBType
DBType returns the database type.
func (*SpannerReadWriteTransaction) DataChangeEventIndex ¶
func (c *SpannerReadWriteTransaction) DataChangeEventIndex(res accesstypes.Resource, rowID string) int
DataChangeEventIndex provides a sequence number for data change events on the same Resource inside the same transaction.
func (*SpannerReadWriteTransaction) PostgresReadOnlyTransaction ¶
func (c *SpannerReadWriteTransaction) PostgresReadOnlyTransaction() any
PostgresReadOnlyTransaction panics because it is not implemented for the SpannerReadWriteTransaction.
func (*SpannerReadWriteTransaction) Released ¶
func (c *SpannerReadWriteTransaction) Released() []ReleasedKey
Released returns the file objects the transaction's patches released so far, each with its store: a deleted row's @file keys, and the old key of a row pointed at another object. Under ExecuteFunc the executor deletes them from the client's stores after the commit; a transaction committed outside it leaves that to its caller.
func (*SpannerReadWriteTransaction) SpannerReadOnlyTransaction ¶
func (c *SpannerReadWriteTransaction) SpannerReadOnlyTransaction() spxapi.Querier
SpannerReadOnlyTransaction returns a read-only transaction for the Spanner client.
func (*SpannerReadWriteTransaction) WithSecretKeys ¶ added in v0.5.0
func (c *SpannerReadWriteTransaction) WithSecretKeys(keys *SecretKeys) *SpannerReadWriteTransaction
WithSecretKeys gives the transaction the application's secret keys, which it seals a patch's secret fields with, and returns the transaction. ExecuteFunc gives a transaction its client's; this is for one an application wraps itself (NewSpannerReadWriteTransaction).
type Statement ¶
type Statement struct {
SQL string
Params map[string]any
// contains filtered or unexported fields
}
Statement is a generic container for a SQL statement and its parameters, supporting both Spanner and PostgreSQL.
func (*Statement) SpannerStatement ¶
SpannerStatement converts the generic Statement into a Spanner-specific Statement.
type Store ¶
type Store struct{}
Store is embedded by a named file store's type:
// Documents holds mission documents in their own bucket.
type Documents struct{ resource.Store }
Only a type embedding it satisfies NamedStore, so Key[int] does not compile.
type StoreName ¶
type StoreName string
StoreName names a wired file store: DefaultStore for the default, and the name StoreNameFor derives from a named store's type.
const DefaultStore StoreName = ""
DefaultStore is the default store's name: the store an untyped @file column, an unnamed @upload and resource.Files belong to.
func StoreNameFor ¶
func StoreNameFor[S NamedStore]() StoreName
StoreNameFor derives a named store's name from its type's name, lower-cased with underscores between its words: Documents gives documents, ClientFiles gives client_files. The configuration variable that holds the store's URL is APP_FILE_STORE_<NAME> upper-cased (APP_FILE_STORE_DOCUMENTS), and the infrastructure names its bucket with the suffix files-<name> hyphenated (files-documents).
type StoredFile ¶
StoredFile is what a @file row says about its stored file: the key column's value (empty for NULL), and the name and type columns where the declaration names them.
type SubjectAnchor ¶
type SubjectAnchor struct {
Resource accesstypes.Resource
Scope accesstypes.PermissionScope
Binding SubjectBindingData
Domain *DomainBindingData
}
SubjectAnchor is a subject-vocabulary entry with everything its rendering needs: the anchor table (the resource declaring it), the entry itself, and the anchor table's own tenancy binding — the rendered subquery filters to the request's partition exactly when both the request and the anchor table are partitioned, derived here, never authored.
type SubjectBindingData ¶
type SubjectBindingData struct {
Name string
UserColumn string
Column string
Type AttributeType
Path []BindingHop
Who []SubjectWhoData
Where *SubjectWhereData
}
SubjectBindingData is one entry of the subject-side vocabulary (subject.<name>), anchored on the declaring resource's user-id column. UserColumn correlates rows to the requester; Column is the local column the set or value yields — the terminal when Path is empty, or the foreign key a dotted value: continues through. Type is the comparison type of the column the set or value yields (the terminal of a dotted value), derived by generation from that column's Go type exactly as an attribute's is; deploy validation admits a grant only where it compares or tests the entry against an attribute of the same type.
A subject set may write two more parts. Who says which rows of the table are the requester's: empty, it is UserColumn equal to the requester; written, it is the tests below joined by OR, and UserColumn is the column of one of them, the one the declaration sits on. Where says which of those rows count: nil, every one does. A subject value writes neither.
type SubjectColumnData ¶ added in v0.5.0
type SubjectColumnData struct {
Name string
Column string
Type AttributeType
}
SubjectColumnData is one column a subject set's where: part reads: the name the condition writes for it, the column, and the column's comparison type.
type SubjectFactSource ¶ added in v0.3.0
SubjectFactSource is the database a computed decoder reads the caller's facts from: the application's resource client.
type SubjectWhereData ¶ added in v0.5.0
type SubjectWhereData struct {
Condition string
Columns []SubjectColumnData
}
SubjectWhereData is a subject set's where: part: a condition over the columns of the set's own row, compared to literals and to now (condition.ParseWhere). Condition is the part as the declaration writes it, and Columns resolves each name it reads to the row's column and that column's comparison type, which a literal binds as.
type SubjectWhoData ¶ added in v0.5.0
SubjectWhoData is one test of a subject set's who: part. Column is the column of the set's row the test reads. With Set empty the test is the column equal to the requester; with Set named it is the column's membership in that subject set of the requester's (Column IN subject.<Set>), the test a grant's condition writes with the row's column where the attribute stands.
type Surface ¶
type Surface struct {
// Prefix is the path as mounted: a prefix such as /beacons/ or /droids/, or a route
// pattern such as /api/widgets/{id}/content, where a segment in braces stands for any
// one segment; / is the application default.
Prefix string `json:"prefix"`
// Kind says how the router matches the prefix against a request's path:
// SurfacePrefix by prefix, so everything under /beacons/ is the surface's, or
// SurfaceRoute to the end of the path, so /api/widgets/{id}/content is the surface's
// and /api/widgets/{id}/content-extra is not. The application default, an outlet and
// a hand-mounted prefix are prefixes; an annotated method's route (@rpc, @file,
// @schedule) is a route. A file written before the surfaces carried their kind reads
// as prefixes throughout.
Kind SurfaceKind `json:"kind"`
// Log is the request log word: RequestLogAlways, RequestLogOnEvent, RequestLogSampled
// or RequestLogNever; empty when the surface declares its trace setting alone.
Log string `json:"log,omitempty"`
// Fraction is the share of the quiet requests a sampled surface writes the entry for,
// above 0 and at most 1; set with RequestLogSampled alone.
Fraction float64 `json:"fraction,omitempty"`
// Traces is the trace setting: TracesFollowFrontEnd, TracesCapped or TracesOff; empty
// when the surface declares its request log word alone.
Traces string `json:"traces,omitempty"`
// Rate is the share of the front end's traces a capped surface keeps, above 0 and at
// most 1; set with TracesCapped alone.
Rate float64 `json:"rate,omitempty"`
}
Surface is one declared surface in the release file: a path prefix or a route pattern as the router mounts it, with the request log word, the trace setting, or both.
type SurfaceKind ¶
type SurfaceKind string
SurfaceKind is how the router matches a surface's prefix against a request's path, as the release file spells it.
const ( // SurfacePrefix is a path prefix, matched by strings.HasPrefix as the router does: the // application default at /, an outlet's prefix, or a prefix mounted by hand. SurfacePrefix SurfaceKind = "prefix" // SurfaceRoute is a route pattern, matched whole as the router does: an annotated // method's path, a parameter in braces standing for one segment. SurfaceRoute SurfaceKind = "route" )
The surface kinds: a prefix is matched against the start of the path and a route to its end.
type TagData ¶
type TagData struct {
Name accesstypes.Tag
Permissions []accesstypes.Permission
// Masking is how the field's masked cells meet a sort or a filter; empty
// is MaskingConcealing, the default.
Masking Masking
// Formerly is the field's former wire name (@formerly on the field): the name
// older browser applications still send and read, which the decoders accept, every
// row carries beside Name and the permission digest mirrors with Name's states.
// Empty for a field never renamed.
Formerly accesstypes.Tag
}
TagData describes one field-level tag registration. An empty Permissions slice records a tag that is registered without requiring any permission.
type TargetedMethod ¶
type TargetedMethod struct {
Method accesstypes.Resource
Target accesstypes.Resource
Transition *TransitionData
}
TargetedMethod pairs an RPC method resource with the row resource its @target field addresses; Transition carries the declared edge when the method is a transition, nil for the plain located-row form.
type TargetedRPCDecoder ¶
type TargetedRPCDecoder[Request any] struct { // contains filtered or unexported fields }
TargetedRPCDecoder decodes an HTTP request for a @target-bearing RPC method. Unlike RPCDecoder, a Conditional Execute decision here is not an invariant breach: the generated handler has a located row to evaluate it against, so Decode carries the condition forward as an ExecuteGate.
func MustNewTargetedRPCDecoder ¶
func MustNewTargetedRPCDecoder[Request any](a DecoderAccessor, collection *GeneratedCollection, methodName accesstypes.Resource, perm accesstypes.Permission) *TargetedRPCDecoder[Request]
MustNewTargetedRPCDecoder builds a decoder for a @target-bearing RPC method request, wired to the generated collection so a carried condition can lower against the target resource's bindings. It panics on construction errors: they are programming errors (a malformed request struct), surfaced at application startup where generated handlers construct their decoders.
func (*TargetedRPCDecoder[Request]) Decode ¶
func (s *TargetedRPCDecoder[Request]) Decode(request *http.Request, scope accesstypes.Scope) (*Request, *ExecuteGate, error)
Decode decodes the HTTP request body into the Request struct and checks the caller's Execute permission in the given scope. Denied is Forbidden here; Granted and Conditional both admit — a Conditional decision's payload rides the returned ExecuteGate, which the generated frame enforces against the located target row inside its transaction.
func (*TargetedRPCDecoder[Request]) WithValidator ¶
func (s *TargetedRPCDecoder[Request]) WithValidator(v ValidatorFunc) *TargetedRPCDecoder[Request]
WithValidator sets a validator function on the decoder.
type TenantDeclarationColumns ¶
type TenantDeclarationColumns struct {
// DirectoryOnly is the tenant record's BOOL column saying the tenant's people enter
// through its directories only, so a password does not reach it; empty when the
// record declares none, and every tenant admits a password.
DirectoryOnly string
// DirectoriesTable is the directories record's table, one row for the directory a
// tenant admits its people through: TenantColumn holds the tenant's key, MethodColumn
// the sign-in method as sessioninfo.AuthMethod spells it (google, azure, workos) and
// ConnectionColumn the connection the method's identities carry (a Google Workspace
// by its domain, a Microsoft Entra tenant by its tenant id). A tenant has one
// directory and a directory is one tenant's: the schema holds both with a unique
// index on TenantColumn and one on MethodColumn and ConnectionColumn, and the record's
// write paths refuse each first (TenantDirectoryRules).
DirectoriesTable string
TenantColumn string
MethodColumn string
ConnectionColumn string
// DirectoriesKeyColumn is the directories record's key column, which the methods
// that say how a tenant admits its directory's people write the tenant's row
// through (TenantDirectoryRules.Directory); empty where the record carries no
// default seat column.
DirectoriesKeyColumn string
// DefaultSeatColumn is the directories record's column naming the role a person is
// seated with in the tenant at their first sign-in through its directory, NULL or
// empty for none (the tenant admits a stranger from its directory by invitation
// only); empty when the record carries no such column, and every directory admits
// by invitation only. Read by the sign-in's directory reader
// (NewTenantDirectoryReader), never by the roster.
DefaultSeatColumn string
}
TenantDeclarationColumns names where the tenant record keeps its declaration of who may enter it (signin.TenantDeclaration), so the roster reads the declaration beside the keys and the sign-in policy reads it in its own transaction (NewTenantDeclarationReader): the record's directory-only column, and the directories record's table with its tenant, method and connection columns. The generated New<Record>Roster and New<Record>DeclarationReader constructors supply them from the @directoryOnly and @tenantDirectory declarations; an application names none of them.
type TenantDeclarations ¶
type TenantDeclarations func(ctx context.Context, domain accesstypes.Domain) (*signin.TenantDeclaration, error)
TenantDeclarations reads what a tenant declares about who may enter it: the tenant's declaration (signin.TenantDeclaration) by domain, as the application keeps it, which SessionPermissions applies to each tenant the session holds a grant in. It answers nil for a tenant that declares nothing, which admits a password and refuses a sign-in through a directory, as the sign-in policy does (signin.TenantPolicy). An application that keeps no declarations passes nil to SessionPermissions, and every tenant admits every session.
type TenantDirectory ¶ added in v0.5.0
type TenantDirectory struct {
// Key is the row's key as text, which the generated methods write the row through.
Key string
// Directory is the organization the tenant's people sign in through.
Directory signin.Directory
// DefaultRole is the role a person is given in the tenant at their first sign-in
// through the directory, "" where the tenant admits the directory's people by
// invitation only.
DefaultRole accesstypes.Role
}
TenantDirectory is a tenant's directory as its row of the directories record holds it.
type TenantDirectoryRules ¶ added in v0.5.0
type TenantDirectoryRules struct {
// contains filtered or unexported fields
}
TenantDirectoryRules holds a tenant's directory to its rules at every write of the directories record (@tenantDirectory):
- a tenant has one directory;
- a directory, its method and its connection together, is one tenant's;
- a personal account (any Google account, a Microsoft personal account) is no organization's directory, so it is no tenant's;
- a directory is not removed while the tenant is directory only, since nobody could then enter the tenant.
The schema holds the first two as well, with a unique index on the directories record's tenant column and one on its method and connection: the rules read what is committed, so two writes that race, or that one transaction buffers together, are refused by the index at the commit. The rules refuse first, each with a sentence the person can act on, where the index can only say that a unique value exists.
A directory is never typed in. It is set from a sign-in: FromSession answers the directory the caller is signed in through, held to the rules, which the directories record's generated create stamps on the row, and Set holds a directory a sign-in names to the rules, for a write made inside that sign-in. The generated New<Record>DirectoryRules supplies the tables and the word for one tenant; an application names none of them.
func NewTenantDirectoryRules ¶ added in v0.5.0
func NewTenantDirectoryRules(table, keyColumn string, columns *TenantDeclarationColumns, word string) *TenantDirectoryRules
NewTenantDirectoryRules builds the rules over the tenant record's table and key column and its declaration's columns. word is what the refusals call one tenant ("tenant", "sector"), as the application's people say it.
func (*TenantDirectoryRules) Directory ¶ added in v0.5.0
func (r *TenantDirectoryRules) Directory(ctx context.Context, txn ReadWriteTransaction, tenant accesstypes.Domain) (*TenantDirectory, error)
Directory answers tenant's directory as committed, in the caller's transaction: the row the two methods that say how the tenant admits the directory's people write. A tenant with no directory has nobody to open to and nothing to make invite only, and is refused with a Conflict that says to set the directory first.
func (*TenantDirectoryRules) DirectoryOnly ¶ added in v0.5.0
func (r *TenantDirectoryRules) DirectoryOnly(ctx context.Context, txn ReadWriteTransaction, tenant accesstypes.Domain, value any) error
DirectoryOnly holds a write of tenant's directory-only switch to its rules, in the caller's transaction, and writes nothing: value is the flag the write carries. Turning the switch off is plain, and so is a write that leaves it on. Turning it on is refused, each time as a Conflict with a sentence the person can act on:
- until the tenant has its directory: with none there is nothing to be only of, and nobody could enter;
- unless the caller is signed in through that directory themselves: the session proves the directory works, and the person who closes the tenant to every other sign-in is not shut out by it;
- unless the caller's own account has a password, where their auth has a password method (PasswordsBy): a tenant's own administrator enters a directory-only tenant with a password and a second factor, which is the way back in if the directory has a problem, and a person who has only ever signed in through the directory would have none. The refusal says to choose a password first. Where the caller's auth has no password method the rule stands down, and nothing is said of it.
The rules read what is committed, and a transaction's reads do not see what it has buffered, so the transaction notes each write the rules pass (directoryWrites): a request that removes the tenant's directory and turns the switch on is refused, whichever comes first, as each would be after the other had committed.
Nobody is exempt from them, a super administrator included: the rules are about the directory and the way back in, not about who may enter. The switch is the tenant's own, turned by the tenant's administrator: the generated methods of a tenant record that declares it (@directoryOnly) and a directories record, Make<Record>DirectoryOnly and End<Record>DirectoryOnly in the tenant's scope, ask the rule once the caller's Execute grant has answered and then write the flag. No other request writes it: the record's field is output only on the wire, so neither the record's update nor its create carries it.
func (*TenantDirectoryRules) DirectoryOnlyWarning ¶ added in v0.5.0
func (r *TenantDirectoryRules) DirectoryOnlyWarning(ctx context.Context, txn ReadWriteTransaction, tenant accesstypes.Domain, people ...DirectoryPeople) (*Warning, error)
DirectoryOnlyWarning says what turning tenant's directory-only switch on would do, in the caller's transaction, and writes nothing: the warning the method that turns it on (Make<Record>DirectoryOnly) answers before it is run, which a dialog shows and holds its button under until the person has typed DirectoryOnlyWord. The consequence says who will be able to enter the tenant and how many of the people seated in it will not, counted through people, one entry for each auth whose people the tenant seats; the confirm words say what the button does. Where no entry reads anybody (an application whose people no generated management lists) nobody was counted, and the sentence says who will lose access without a number: it never says that everyone has signed in through the directory on a count nobody made.
Everyone the switch would keep out is counted. A person is named only to a caller who may list them: the people of an auth are named where the request's caller (CallerFrom) holds the tenant's list of that auth's people (DirectoryPeople), and counted alone where the caller does not. A call outside a request names nobody.
It refuses as DirectoryOnly refuses, with the same sentences, so a page that asks first shows the refusal instead of a dialog; a tenant the record does not hold is NotFound. A tenant that is directory only already has nothing to turn on, and the warning is refused as a Conflict that says so and names neither its directory nor its people: the write that leaves the switch on is plain whoever makes it, and the warning answers nobody what that write would not ask them to prove.
func (*TenantDirectoryRules) FromSession ¶ added in v0.5.0
func (r *TenantDirectoryRules) FromSession(ctx context.Context, txn ReadWriteTransaction, tenant accesstypes.Domain) (signin.Directory, error)
FromSession answers the directory the caller is signed in through, held to the rules for tenant: the directory the directories record's generated create stamps on the row, so no request types a method or a connection. Every refusal is a Conflict: SessionDirectory's and Set's.
func (*TenantDirectoryRules) NamedBy ¶ added in v0.5.0
func (r *TenantDirectoryRules) NamedBy(namers ...DirectoryNamer) *TenantDirectoryRules
NamedBy answers the rules with the namers of the application's auths, which say what each auth's sign-in registrations call a directory: every sentence of the rules that names a directory then says it in words a person knows (DirectoryWords), the name a registration gives it or the label of its button, and never its connection, which for a Microsoft Entra tenant is an id. The generated frames of a tenant's own methods pass the namer of each auth's generated identity client. Rules nobody names read what a directory alone says.
func (*TenantDirectoryRules) OpenToDirectoryWarning ¶ added in v0.5.0
func (r *TenantDirectoryRules) OpenToDirectoryWarning(directory *TenantDirectory, role accesstypes.Role) *Warning
OpenToDirectoryWarning says what opening a tenant to its directory's people with role would do, in the words a person reads before they confirm it, and the words for the button that does it. It writes nothing and judges no role: the method that opens the tenant holds the role to its rules before it asks. A request that names no role yet is answered, since the warning is read while the role is still being picked, and says the role is to be chosen. The directory is said in the words a person knows it by (DirectoryWords, through the namers the rules were given), never by its connection.
func (*TenantDirectoryRules) PasswordsBy ¶ added in v0.5.0
func (r *TenantDirectoryRules) PasswordsBy(readers ...CallerPassword) *TenantDirectoryRules
PasswordsBy answers the rules with what each of the application's auths says of the caller's password: a tenant is made directory only by a person who has a password, since a tenant's own administrator enters a directory-only tenant with a password and a second factor (signin.TenantDeclaration.AdmitsAdministrator), and that is the way back in if the directory has a problem. The generated frames of a tenant's own methods pass the reader of each auth's generated identity client. Where no auth's answer applies, as in an application whose people have no passwords, the rule stands down and nothing is said of it; rules built without readers ask nothing.
func (*TenantDirectoryRules) Remove ¶ added in v0.5.0
func (r *TenantDirectoryRules) Remove(ctx context.Context, txn ReadWriteTransaction, tenant accesstypes.Domain) error
Remove holds the removal of tenant's directory to its rule, in the caller's transaction, and writes nothing: a tenant that is directory only keeps its directory, since its people enter through it alone and nobody could enter the tenant without it. The refusal is a Conflict that says to turn directory only off first. A request that turns the tenant directory only and removes its directory is refused the same way, though the switch it turns on is not yet committed: the transaction notes the writes the rules pass (directoryWrites). A tenant record with no directory-only column removes freely.
func (*TenantDirectoryRules) Set ¶ added in v0.5.0
func (r *TenantDirectoryRules) Set(ctx context.Context, txn ReadWriteTransaction, tenant accesstypes.Domain, directory signin.Directory) error
Set holds directory to the rules as tenant's directory, in the caller's transaction, and writes nothing: the caller buffers the row once Set answers nil. It refuses, each as a Conflict with a sentence the person can act on, a directory that is no organization's (a personal account, or no directory at all), a tenant that has a directory already, and a directory another tenant has. The last says the organization already has a tenant, which a rule of one tenant per directory cannot keep from being learned; it does not say which.
func (*TenantDirectoryRules) State ¶ added in v0.5.0
func (r *TenantDirectoryRules) State(ctx context.Context, txn ReadWriteTransaction, tenant accesstypes.Domain) (*DirectoryOnlyState, error)
State answers tenant's directory-only switch as it stands, in the caller's transaction; a tenant the record does not hold is NotFound.
type TenantRoster ¶
type TenantRoster struct {
// contains filtered or unexported fields
}
TenantRoster is one instance's copy of the tenant record's keys: the set of tenants the application serves, which the generated DomainGuard and the consolidated dispatcher ask before a tenant-scoped request runs. Start reads the set once and then keeps it current until the context ends: on every tenants signal the channel delivers and at the backstop interval regardless. The generated write paths of the tenant record call Add and Remove after their commit, so the instance that wrote a tenant serves it at once, and signal the tenants kind so every other instance reloads.
With WithTenantDeclarations the copy carries what each tenant declares about who may enter it beside its key, read in the same snapshot, and Declarations answers the generated DomainGuard's and the session's tenant list's question from it (TenantDeclarations) with no read and no wait; the generated write paths of the tenant record and of the directories record call Reload after their commit, so a declaration changed on this instance decides the next request here, and signal the tenants kind so every other instance reloads.
The set sits behind an atomic pointer, so Has never waits on a reload or a writer and performs no read: a domain the set does not hold is unknown, whatever the table says at that moment. A nil roster holds no tenant, so an application that wires none fails closed on every tenant-scoped route. It is safe for concurrent use.
func NewTenantRoster ¶
func NewTenantRoster(client Client, table, keyColumn string, opts ...TenantRosterOption) *TenantRoster
func (*TenantRoster) Add ¶
func (r *TenantRoster) Add(domain accesstypes.Domain)
Add puts the domain in the set at once, declaring nothing: what a test harness calls to hold a tenant the schema has no row for. The generated write paths call Reload instead, so the tenant's declaration comes with it. A nil roster takes nothing.
func (*TenantRoster) Declarations ¶
func (r *TenantRoster) Declarations(_ context.Context, domain accesstypes.Domain) (*signin.TenantDeclaration, error)
Declarations answers what the domain declares about who may enter it, from the copy: the TenantDeclarations an application hands SessionPermissions, so the session's tenant list and the generated DomainGuard decide with no read and no wait. A tenant the set does not hold, a tenant that declares nothing, and every tenant of a roster built without WithTenantDeclarations answer nil, which declares nothing. A nil roster answers nil too. It never fails.
func (*TenantRoster) Domains ¶
func (r *TenantRoster) Domains(context.Context) ([]accesstypes.Domain, error)
Domains lists the tenants, sorted. It never fails and reads nothing; the signature is DomainRoster's, so the roster's Domains is what an application hands SessionPermissions. A nil roster lists none.
func (*TenantRoster) Has ¶
func (r *TenantRoster) Has(domain accesstypes.Domain) bool
Has reports whether the domain is a tenant the roster holds. It loads the set and looks the domain up: no read, no wait. A domain the set does not hold is unknown, and every domain is unknown to a nil roster.
func (*TenantRoster) Name ¶ added in v0.4.0
func (r *TenantRoster) Name(domain accesstypes.Domain) string
Name answers the tenant's name as the record's name column held it at the last read (WithTenantNames), from the copy: no read, no wait. It is "" for a tenant the copy names nothing for, for every tenant of a roster that reads no names, and on a nil roster. The roster is the DomainNamer the session's tenant list names tenants with.
func (*TenantRoster) Named ¶ added in v0.5.0
func (r *TenantRoster) Named(name string) (accesstypes.Domain, error)
Named answers the tenant that carries the name, as the record's name column held it at the last read (WithTenantNames), from the copy: no read, no wait. A tenant's key is an id nobody reads, so what names a tenant by hand names it by its name: a development bootstrap reads its logins' tenants this way. A name no tenant carries and a name more than one tenant carries are errors: the first names nothing, and the second does not say which. A nil roster and one that reads no names hold no name.
func (*TenantRoster) Reload ¶
func (r *TenantRoster) Reload(ctx context.Context) error
Reload rereads the table, the declarations with it, and replaces the set whole: what the tenant record's and the directories record's generated write paths call after their commit, so the instance that wrote serves the change at its next request, and what Start calls on every tenants signal and backstop tick. A failed read leaves the set as it was. A nil roster reads nothing.
func (*TenantRoster) Remove ¶
func (r *TenantRoster) Remove(domain accesstypes.Domain)
Remove drops the domain from the set at once. A nil roster drops nothing.
func (*TenantRoster) Start ¶
func (r *TenantRoster) Start(ctx context.Context) error
Start loads the set once, failing when the read fails, so an application never starts serving on an empty roster it could not fill, and then keeps it current until ctx ends: a goroutine rereads the table on every tenants signal (when a channel is wired) and at the backstop interval regardless. A failed reread is logged and the copy stays as it was until the next.
type TenantRosterOption ¶
type TenantRosterOption func(*TenantRoster)
TenantRosterOption configures a TenantRoster at construction.
func WithTenantBackstop ¶
func WithTenantBackstop(d time.Duration) TenantRosterOption
WithTenantBackstop sets how often Start rereads the table without a signal; TenantBackstop by default. Tests shorten it.
func WithTenantDeclarations ¶
func WithTenantDeclarations(columns *TenantDeclarationColumns) TenantRosterOption
WithTenantDeclarations has the roster read what each tenant declares about who may enter it beside its key: the columns the generated New<Record>Roster constructor supplies from the @directoryOnly and @tenantDirectory declarations. Without it every tenant's declaration is nil, which declares nothing.
func WithTenantNames ¶ added in v0.4.0
func WithTenantNames(column string) TenantRosterOption
NewTenantRoster builds the roster over the tenant record's table, reading the key column into the set. The generated New<Record>Roster constructor supplies the table and the column from the @tenant declaration; an application calls that one. Nothing is read until Start. WithTenantNames has the roster read each tenant's name from the record's name column (the field the tenant record marks @tenantName) in the snapshot of its keys, so Name answers from the copy and the session's tenant list names each tenant (WithDomainNames) with no read of its own. The generated New<Record>Roster passes it when the record marks a name; an empty column reads none.
func WithTenantSignals ¶
func WithTenantSignals(s TenantSignals) TenantRosterOption
WithTenantSignals wires the application's signal channel: Start subscribes the roster to the tenants kind on it, so a tenant another instance wrote reaches this one within a moment instead of at the backstop. Without it the backstop alone keeps the copy current.
type TenantSignals ¶
type TenantSignals interface {
Signaler
SignalSubscriber
}
TenantSignals is the signal channel a TenantRoster follows: what the live service offers (resource.Signaler and resource.SignalSubscriber together). Signal tells every instance that a kind changed; Subscribe runs onSignal on every signal of the kind after the subscription began, on the channel's own goroutine, and stop ends the subscription. The roster never opens a listener of its own: it subscribes to the application's one watch, for KindTenants.
type TextIdent ¶
TextIdent is a text column's identifier with the search vocabulary its schema gives it, the field's search tag (README section 4). The generated query builder declares one per text field that answers a match and forwards only the matches the field answers, so a match the field cannot answer does not compile; a match it answers builds the same condition the filter grammar's operator does, rendered through the same columns.
func NewTextIdent ¶
func NewTextIdent(column string, px PartialQueryClause, indexed bool, tag string) TextIdent
NewTextIdent creates a text column's identifier from its search tag. A tag the runtime cannot read is generated code out of step with the package and panics, like every other generated-code mismatch.
func (TextIdent) Contains ¶
func (i TextIdent) Contains(term string) QueryClause
Contains creates a contains condition: the term appears anywhere in the column's value.
func (TextIdent) EndsWith ¶
func (i TextIdent) EndsWith(term string) QueryClause
EndsWith creates an endswith condition: the column's value ends with the term.
func (TextIdent) StartsWith ¶
func (i TextIdent) StartsWith(term string) QueryClause
StartsWith creates a startswith condition: the column's value begins with the term.
type TokenType ¶
type TokenType int
TokenType defines the types of tokens in the filter string.
const ( // TokenEOF represents the end of the input string. TokenEOF TokenType = iota // TokenLParen represents '(' TokenLParen // TokenRParen represents ')' TokenRParen // TokenComma represents ',' TokenComma // TokenPipe represents '|' TokenPipe // TokenCondition represents 'field:operator:value' or 'field:operator:(value1,value2,...)' or 'field:operator' TokenCondition )
type TouchedRows ¶
type TouchedRows struct {
// contains filtered or unexported fields
}
TouchedRows collects what the transactions a request commits wrote, so the request publishes them once the commit lands and before it answers. CollectTouchedRows puts one in the context the generated handler runs its transaction under; the executor adds each committed transaction's rows, and the handler reads them back with Rows. It is safe for concurrent use.
func CollectTouchedRows ¶
func CollectTouchedRows(ctx context.Context) (context.Context, *TouchedRows)
CollectTouchedRows returns ctx carrying a fresh collector, and the collector. Every transaction committed under the returned context (ExecuteFunc, a patch's Apply) adds the rows it wrote; a transaction that does not commit adds nothing.
func (*TouchedRows) Empty ¶
func (t *TouchedRows) Empty() bool
Empty reports whether nothing was committed.
func (*TouchedRows) Rows ¶
func (t *TouchedRows) Rows(fallback accesstypes.Domain) map[accesstypes.Domain]map[accesstypes.Resource][]RowChange
Rows returns the committed rows grouped by the domain each was written in and then by resource, in first-written order within each resource. A row whose patch carried no domain (a global resource, or a patch built by hand) is listed under fallback: the mutating request's route domain, which is the zero Domain on a global route.
type TransitionData ¶
type TransitionData struct {
Target accesstypes.Resource
From []string
To string
}
TransitionData records a declared state transition on an RPC method resource: the workflow root it moves, the pre-image states it may run from, and the state the generated handler stamps after the body.
type TransitionMethod ¶
type TransitionMethod struct {
Method accesstypes.Resource
Transition TransitionData
}
TransitionMethod pairs an RPC method resource with its declared transition.
type TypescriptData ¶
type TypescriptData struct {
Permissions []accesstypes.Permission
Resources []accesstypes.Resource
// Methods are the Execute-gated registrations: generated RPC methods and
// manual declarations (@manualAddResource(Execute)) alike.
Methods []accesstypes.Resource
ResourceTags map[accesstypes.Resource][]accesstypes.Tag
PermissionScopes []accesstypes.PermissionScope
}
TypescriptData holds all the collected resource and permission information needed for TypeScript code generation.
type UnknownSecretVersionError ¶ added in v0.5.0
type UnknownSecretVersionError struct {
// Version is the version the stored value names.
Version int
// Held are the versions the service was given, ascending.
Held []int
}
UnknownSecretVersionError is the error of opening a stored secret sealed under a version of the application secret the service was not given.
func (*UnknownSecretVersionError) Error ¶ added in v0.5.0
func (e *UnknownSecretVersionError) Error() string
Error names the version the value was sealed under and the versions the service holds.
type Upload ¶
type Upload struct {
// contains filtered or unexported fields
}
Upload is one multipart upload request the frame opened: the request part, ready for the method's decoder, with the file parts still on the wire behind it.
func OpenUpload ¶
OpenUpload bounds the request body to maxBytes, opens the multipart form, and positions it on the request part, which must come first. A body over the limit answers 413 naming the maximum, a body that is not multipart/form-data 415, and a form whose first part is not the request part 400.
func (*Upload) Request ¶
Request returns the request the method's decoder reads: the upload request with the request part as its body, so field validation, the entry check, and the target's checks run exactly as for a JSON RPC.
func (*Upload) Stream ¶
Stream reads the file parts behind the request part and streams each to the store under a fresh key, returning the Files the body receives. A dry run streams nothing: the parts are measured and described with empty keys. A form with no file part, or with a part under another name, is a 400; a body over the declared maximum is a 413. A failure after a part was stored (a later part malformed, over the limit, or refused by the store) deletes the parts already stored before the failure is returned, so no object is left behind by a request that never reaches its transaction. A nil store, the store the declaration names not wired on the resource client, is an error naming the wiring.
type UserDomain ¶ added in v0.4.0
type UserDomain struct {
Domain accesstypes.Domain `json:"domain"`
Name string `json:"name"`
Closed string `json:"closed,omitempty"`
}
UserDomain is one tenant of the session's tenant list: its domain, the key in every tenant-scoped URL, and its name as the tenant record holds it, for the tenant picker to show. Name is the domain itself where the application's roster reads no names (WithDomainNames) or the record holds none for the tenant.
Closed marks a tenant the person holds a seat in and this session cannot enter (ClosedDomains), with the reason in a sentence for the person: what the tenant admits and how they signed in ("Acme admits only people who sign in through its own directory. You signed in with a password."), a directory said in the words a person knows it by (WithDirectoryNames). The tenant's own administrator, who signed in with a password and whose session carries no second factor, is told the way in they hold as well ("As one of its administrators you can still enter it: sign out, then sign in again with your password and the code we email you."): the code is all that is missing, and the reason says what to do. It is empty, and absent from the JSON, for a tenant the session reaches. A picker shows a closed tenant marked, with the reason, and never as a place to open. Only a person's own sign-in is told of one: a session that views the application as someone else, and one that acts as a role, list none closed.
type UserDomainsOption ¶ added in v0.4.0
type UserDomainsOption func(*userDomainsSettings)
UserDomainsOption configures UserDomainsHandler.
func WithDirectoryNames ¶ added in v0.5.0
func WithDirectoryNames(namers ...DirectoryNamer) UserDomainsOption
WithDirectoryNames names the directory a session came through in a closed tenant's reason, from the namers of the application's auths: what each auth's sign-in registrations call it (DirectoryName). The generated UserDomains handler passes the namer of each auth's generated identity client. Without one the reason reads what the directory alone says, and it never says a tenant id.
func WithDomainNames ¶ added in v0.4.0
func WithDomainNames(names DomainNamer) UserDomainsOption
WithDomainNames names each tenant of the list from the namer, the application's tenant roster: what the generated UserDomains handler passes when the tenant record marks its name field (@tenantName). The roster answers from its copy, so naming the list reads nothing. A nil namer names nothing.
type UserPermissionChecker ¶
type UserPermissionChecker interface {
// Check returns the Decision for perm on each of resources within scope.
//
// env is the request's decision context, sampled once at decode; the check
// folds environment-referencing conditions against it and fails loudly
// (error, never a silent allow or deny) when a referenced attribute is
// absent.
//
// The returned Decisions must carry an entry for every resource passed. A
// resource absent from the map reads as the zero Decision — Denied — so a
// short implementation fails closed, never open. Implementations must not
// short-circuit on the first denial.
//
// Snapshot pinning: a single Check call must evaluate every resource against one
// consistent authorization snapshot — a concurrent grant or revocation must affect
// all of the call's results or none of them. Distinct calls may observe different
// snapshots; callers must not assume pinning across calls.
Check(ctx context.Context, env accesstypes.Environment, scope accesstypes.Scope, perm accesstypes.Permission, resources ...accesstypes.Resource) (accesstypes.Decisions, error)
// PermissionDigest returns the user's structural grant enumeration within
// scope — the payload the generated permission-digest endpoint serves.
// Advisory UI material only, never consulted for enforcement: denied
// targets are absent (fail closed) and nothing folds, so a payload is
// stable for the life of a policy snapshot.
PermissionDigest(ctx context.Context, scope accesstypes.Scope) (accesstypes.PermissionDigest, error)
// HasGrants reports whether the user holds at least one grant in scope —
// the foothold concealed tenancy's visibility check asks, and the
// predicate the tenant picker filters the application's roster by. A
// membership that resolves to no grants is not a foothold; a membership
// held in every tenant domain is a foothold in each.
HasGrants(ctx context.Context, scope accesstypes.Scope) (bool, error)
User() accesstypes.User
}
UserPermissionChecker is what an application's per-request accessor for a user principal hands SessionPermissions: UserPermissions without Domains, since a checker holds no tenant list — the roster is the application's, and SessionPermissions filters it by HasGrants.
The canonical implementation is the access package's request-bound checker (Client.ForUser), which satisfies this interface structurally — neither package imports the other.
type UserPermissions ¶
type UserPermissions interface {
UserPermissionChecker
// Domains lists the domains where the user holds at least one grant and
// that the session reaches, sorted — the payload the generated
// user-domains endpoint serves and the tenant picker's question: the
// application's tenant roster filtered by HasGrants and by Reaches, so a
// domain listed here is exactly a domain whose routes answer the user
// with ordinary 403s rather than concealed tenancy's 404; the picker and
// the guard can never disagree. Never nil: an application without
// tenants lists none.
Domains(ctx context.Context) ([]accesstypes.Domain, error)
// Reaches reports whether the session may enter domain: the tenant's
// declaration (TenantDeclarations) admits the way the session was
// established, its sign-in's method and connection; or the session's
// actor is a super administrator, who holds the Super Administrator role
// and enters every tenant; or the tenant is directory only and the
// session is its own administrator's, established with a password and
// carrying a second factor. Nobody else is exempt from a tenant's sign-in
// settings. It is the generated domain guard's
// question before the foothold, and the attenuation behind every other
// answer: in a tenant the session does not reach it holds nothing —
// every check Denied, an empty digest, no foothold. Whether domain is a
// tenant at all is the roster's question (TenantRoster.Has), which the
// guard asks first. A session composed without declarations reaches
// every domain.
Reaches(ctx context.Context, domain accesstypes.Domain) (bool, error)
}
UserPermissions is the permission surface a request's decoders consume: the checks, the frontend's advisory enumerations, the identity a row condition's subject binds to, and the session's reach into the application's tenants. SessionPermissions composes it per request from the session's principal, the application's checker for that principal, the application's tenant roster and its tenant declarations; applications hand the composed value to the PatchSet and QuerySet types, which enforce permissions through it.
func Masked ¶
func Masked(perms UserPermissions, mask accesstypes.PermissionMask) UserPermissions
Masked returns perms attenuated by mask: a permission the mask does not allow is Denied for every resource before policy is consulted — and evidenced as a mask denial — and the permission digest omits it. A foothold is answered through the masked digest, so a session masked to nothing has none and lists no domain. User and Reaches pass through. The unrestricted mask returns perms itself.
func RolePrincipalPermissions ¶
func RolePrincipalPermissions(role RolePermissions, actor accesstypes.User) UserPermissions
RolePrincipalPermissions is a checker acting as a role on behalf of a real actor: the role's permissions answer the checks, and the actor's identity is what row conditions bind and change events record — the same composition an act-as-role session gets. It lists no domain: a body acting as a role asks no tenant picker.
func SessionPermissions ¶
func SessionPermissions[U SessionUserChecker, R RolePermissions]( ctx context.Context, forUser func(accesstypes.User) U, forRole func(accesstypes.Role) R, roster DomainRoster, declarations TenantDeclarations, ) UserPermissions
SessionPermissions composes the request's UserPermissions from the session in ctx. It picks the checker by the session's principal — forUser for a user principal (an ordinary session, or an impersonated user), forRole for a role principal — admits the session into the tenants that admit the way it was established, lists the session's domains as the application's roster filtered by that admission and by the checker's HasGrants, and applies the session's permission mask. It is the per-request accessor for an application with impersonated sessions:
return resource.SessionPermissions(r.Context(), a.access.ForUser, a.access.ForRole, a.tenants.Domains, a.declarations)
The roster is the application's: access holds no tenant list, so the tenant picker's question — which tenants may this session see — is the roster asked, tenant by tenant, whether the session holds a grant there and whether the tenant admits the session. An application without tenants passes nil for the roster and the declarations.
The declarations are the application's too: what each tenant declares about who may enter it (signin.TenantDeclaration), read by domain. A tenant's declaration restricts that tenant's own door and nobody else's: the session reaches every tenant that seats the person, except a tenant that is directory only and whose directory is not the one the person signed in through. A tenant is offered only when the session may enter it, and the tenant's declaration decides: it admits the session's establishment, the sign-in's method and connection the session's first auth event records (sessioninfo.SessionData.EstablishedBy; signin.TenantDeclaration.Admits is the decision), or the session's actor is a super administrator, a holder of the Super Administrator role (SessionUserChecker.SuperAdministrator), who enters every tenant whatever its sign-in settings say, as the sign-in policy admits them (signin.TenantPolicy), or the session's actor administers the tenant and came by the administrators' way in: a tenant that is directory only still admits its own administrators, in a session established with a password that carries a second factor (signin.TenantDeclaration.AdmitsAdministrator is the decision, the one the sign-in policy asks; SessionUserChecker.AdministersTenant says who administers, asked at every request, so the way in closes at the next request once the role is taken away or its period ends). Nobody else enters a directory-only tenant another way than through its directory: a person holding another global role, or a role in every tenant, the administrator's among them, is held to each tenant's declaration like anyone, and so is the tenant's administrator who signed in through another organization's directory, with a personal account, or with a password and no second factor. An impersonated session is established by its impersonation event, so a directory-only tenant refuses it unless the actor, the real person behind it, is a super administrator; whom the session is viewed as changes nothing. In a tenant the session does not reach it holds nothing: every check Denied, an empty digest, no foothold, and the tenant is not among its domains, so the picker never offers it as a place to open and the generated domain guard refuses a direct request for it as it refuses a domain that is not a tenant (UserPermissions.Reaches). The person holds a seat there all the same, so the tenant list of a person's own sign-in carries the tenant closed, with the reason (ClosedDomains, UserDomainsHandler); an impersonated session and a session that acts as a role are told of none. An application that keeps no declarations passes nil, and every tenant admits every session.
A person is named as the permission store names them: by the id of their account (sessioninfo.SessionData.User), never by the username, which can change and which two auths over one database can each hold. User() is that id, a row condition's subject binds to it, and a column that records who did something holds it.
A role checker has no User(): a role is not anyone. For a role principal the composed UserPermissions reports the session's effective identity — the actor who established a session that acts as a role, and otherwise the session's own person, whom a resolver gave the role (roleSessionUser) — so a row condition's subject binds to a real person and nobody's identity is borrowed. An application that does not operate sessions as roles passes RolePrincipalsUnsupported as forRole: a role principal then fails closed — every check Denied, an empty digest, no footholds, no domains — with the same User(), so a deployment that mints role principals without a checker is loud rather than permissive.
type ValidateFunc ¶
type ValidateFunc func(ctx context.Context, txn ReadWriteTransaction) error
ValidateFunc is the signature for a function that validates a PatchSet prior to committing it.
type ValidatorFunc ¶
ValidatorFunc is the interface used to validate a struct, in whole or in part. Its methods return an error if the validation fails.
type ValueKind ¶
type ValueKind int
ValueKind is how the patch decoder sizes a request field's value against its column's declared type: by code point, by byte, or by decimal digit. The generator classifies a source field's Go type into a kind with go/types and the runtime classifies the request struct's field with reflection; HasValueLimit is where the two agree on which pairs of kind and column type carry a rule.
const ( // ValueKindOther is every type the decoder does not size: keys, integers, floats, // booleans, dates, timestamps, JSON, and the null wrappers of those. ValueKindOther ValueKind = iota // ValueKindString is a string-kinded type: string, a named string type, a pointer to // one, or spanner.NullString. Sized by code point against STRING(n), as Spanner // counts. ValueKindString // ValueKindBytes is []byte, sized by byte against BYTES(n). ValueKindBytes // ValueKindDecimal is decimal.Decimal, a pointer to one, decimal.NullDecimal, or // spanner.NullNumeric, sized by digit against NUMERIC. ValueKindDecimal // ValueKindSecret is the value of a secret field as a request carries it: text, // sized by byte against the BYTES(n) column its sealed form is stored in, less the // bytes sealing adds (SecretOverhead). The generator classifies a source field typed // Secret as this kind; the runtime meets it as a string-kinded request field and // takes it for a secret only where the resource declares the field one // (conditions:"secret"). A string-kinded field on a BYTES column that is no secret, // a named string type with an encoding of its own, has no rule. ValueKindSecret )
type Warning ¶ added in v0.5.0
type Warning struct {
// Consequence is what the call will do, in sentences a person reads before they
// confirm it: who is affected and how.
Consequence string `json:"consequence"`
// Names are the people or things the consequence speaks of, one a line, where the
// method can name them and the caller may be told: a dialog shows them as a list
// under the sentences. Nil where the method names none; the consequence stands
// without them, and says how many there are where that matters.
Names []string `json:"names,omitempty"`
// Confirm is the words on the button that runs the call, which say what it does
// ("Open to anyone with a Google account"), so nobody confirms by a bare "OK".
Confirm string `json:"confirm"`
}
Warning is what a method that declares one (@warning) says before it is run, in the server's words for the call the request describes.
Source Files
¶
- across_tenants.go
- after_commit.go
- answer.go
- apiversion.go
- body_decoder.go
- body_limit.go
- browser_app.go
- caller.go
- capabilities.go
- clone.go
- closed_domains.go
- collection_bindings.go
- commit_refusal.go
- computed_conditions.go
- computed_page.go
- computed_query_decoder.go
- cursor.go
- cursor_predicate.go
- decoder.go
- demonstrations.go
- directory_words.go
- dml.go
- dryrun.go
- environment.go
- eventsource.go
- feature.go
- fieldmapper.go
- fieldset.go
- file.go
- file_release.go
- file_store.go
- filterdates.go
- filterparser.go
- filtershape.go
- formerly.go
- generated_collection.go
- keyset.go
- lowering.go
- nullable_fields.go
- operations.go
- page.go
- paging.go
- patch_fork.go
- patchset.go
- permission_digest.go
- principal.go
- query_decoder.go
- querybuilder.go
- queryset.go
- read_rendering.go
- release_file.go
- resource.go
- resource_iface.go
- resource_mock.go
- resource_postgres.go
- resource_spanner.go
- resourceset.go
- roster.go
- row.go
- rpc_decoder.go
- rpc_execute_gate.go
- rpc_request_fields.go
- search.go
- search_grants.go
- search_render.go
- secret.go
- secret_keys.go
- secret_patch.go
- secret_retire.go
- signal.go
- signinroles.go
- sortrows.go
- sqlgenerator.go
- sqlgenerator_lowered.go
- struct_decoder.go
- structfields.go
- subject_facts.go
- tags.go
- tenancy.go
- tenant_directory.go
- tenant_directory_only.go
- tenant_directory_role.go
- tenantcreation.go
- tokentype_string.go
- touched.go
- types.go
- upload.go
- user_domains.go
- value_limits.go
- warning.go
- write_checks.go
Directories
¶
| Path | Synopsis |
|---|---|
|
database
|
|
|
postgres
Package postgres is the PostgreSQL database driver: from the variables it declares, it opens a connection pool on the application's database and the resource client over it.
|
Package postgres is the PostgreSQL database driver: from the variables it declares, it opens a connection pool on the application's database and the resource client over it. |
|
postgres/declaration
Package declaration publishes the declaration of the PostgreSQL database driver's settings struct for the tools that read an application embedding it without loading its packages (impulse's checks, bedrock's stack): what postgres.Settings declares, in the shape the cloud package defines.
|
Package declaration publishes the declaration of the PostgreSQL database driver's settings struct for the tools that read an application embedding it without loading its packages (impulse's checks, bedrock's stack): what postgres.Settings declares, in the shape the cloud package defines. |
|
spanner
Package spanner is the Spanner database driver: from the variables it declares, it opens the application's database, the Spanner client over it and the resource client the generated handlers read and write through.
|
Package spanner is the Spanner database driver: from the variables it declares, it opens the application's database, the Spanner client over it and the resource client the generated handlers read and write through. |
|
spanner/declaration
Package declaration publishes the declaration of the Spanner database driver's settings struct for the tools that read an application embedding it without loading its packages (impulse's checks, bedrock's stack): what spanner.Settings declares, in the shape the cloud package defines.
|
Package declaration publishes the declaration of the Spanner database driver's settings struct for the tools that read an application embedding it without loading its packages (impulse's checks, bedrock's stack): what spanner.Settings declares, in the shape the cloud package defines. |
|
Package filestore holds the framework's file stores: the stores an application's uploaded files live in, opened from one URL per store.
|
Package filestore holds the framework's file stores: the stores an application's uploaded files live in, opened from one URL per store. |
|
internal
|
|
|
declarationtest
Package declarationtest holds a driver's settings declaration to its settings struct, for the drivers' tests: the live, job and database drivers each publish a declaration in the package beside them, and each driver's test calls Hold on it, as the cloud driver's test does on its own, so a field renamed, retagged or re-documented without the declaration following fails in the resource module and never only in a tool reading it.
|
Package declarationtest holds a driver's settings declaration to its settings struct, for the drivers' tests: the live, job and database drivers each publish a declaration in the package beside them, and each driver's test calls Hold on it, as the cloud driver's test does on its own, so a field renamed, retagged or re-documented without the declaration following fails in the resource module and never only in a tool reading it. |
|
Package jobs is the seam between the application's scheduled methods and its job process: Starter, which starts one execution of the job with the command's arguments.
|
Package jobs is the seam between the application's scheduled methods and its job process: Starter, which starts one execution of the job with the command's arguments. |
|
cloudrun
Package cloudrun is the Cloud Run job driver: from the variable it declares, it names the job process of this build and starts its executions through the Cloud Run Admin API.
|
Package cloudrun is the Cloud Run job driver: from the variable it declares, it names the job process of this build and starts its executions through the Cloud Run Admin API. |
|
cloudrun/declaration
Package declaration publishes the declaration of the Cloud Run job driver's settings struct for the tools that read an application embedding it without loading its packages (impulse's checks, bedrock's stack): what cloudrun.Settings declares, in the shape the cloud package defines.
|
Package declaration publishes the declaration of the Cloud Run job driver's settings struct for the tools that read an application embedding it without loading its packages (impulse's checks, bedrock's stack): what cloudrun.Settings declares, in the shape the cloud package defines. |
|
Package live is the server side of live pages: a page that asked for a live list or a live row stays current without polling and without refetching while nothing changed, and a page mounted again inside a short window is served by the browser with no request.
|
Package live is the server side of live pages: a page that asked for a live list or a live row stays current without polling and without refetching while nothing changed, and a page mounted again inside a short window is served by the browser with no request. |
|
firestore
Package firestore is the Firestore implementation of the live service: the subscription record in one server-owned collection, the change sets under each user's document, the browser's identity as a Firebase custom token, and the application's signals in one server-owned document with a field per kind, which this instance's one snapshot listener watches.
|
Package firestore is the Firestore implementation of the live service: the subscription record in one server-owned collection, the change sets under each user's document, the browser's identity as a Firebase custom token, and the application's signals in one server-owned document with a field per kind, which this instance's one snapshot listener watches. |
|
firestore/declaration
Package declaration publishes the declaration of the Firestore live driver's settings struct for the tools that read an application embedding it without loading its packages (impulse's checks, bedrock's stack): what firestore.Settings declares, in the shape the cloud package defines.
|
Package declaration publishes the declaration of the Firestore live driver's settings struct for the tools that read an application embedding it without loading its packages (impulse's checks, bedrock's stack): what firestore.Settings declares, in the shape the cloud package defines. |
|
Package maintenance is what an application serves while it is down for maintenance: a revision the deploy pipeline starts with the maintenance variable set, before a release that replaces or interrupts the database, so that the people using the application see a maintenance page instead of errors while the database is away.
|
Package maintenance is what an application serves while it is down for maintenance: a revision the deploy pipeline starts with the maintenance variable set, before a release that replaces or interrupts the database, so that the people using the application see a maintenance page instead of errors while the database is away. |
|
Package scheduled is the framework's side of a scheduled route: a method the application declares with @schedule, which Cloud Scheduler calls on its schedule.
|
Package scheduled is the framework's side of a scheduled route: a method the application declares with @schedule, which Cloud Scheduler calls on its schedule. |
|
Package server starts the HTTP server an application runs behind, speaking HTTP/1.1 and unencrypted HTTP/2 (h2c) on one listener.
|
Package server starts the HTTP server an application runs behind, speaking HTTP/1.1 and unencrypted HTTP/2 (h2c) on one listener. |
|
Package shipped is the handshake between a machine outlet and the installed copies of the programs a release ships through it: the route the outlet serves the compiled programs at, the header that carries each file's checksum, and the release header every answer of the outlet already carries.
|
Package shipped is the handshake between a machine outlet and the installed copies of the programs a release ships through it: the route the outlet serves the compiled programs at, the header that carries each file's checksum, and the release header every answer of the outlet already carries. |