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 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 CloneRequest(r *http.Request) (*http.Request, 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 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
- 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 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 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 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 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 WithCaller(ctx context.Context, caller *Caller) context.Context
- type APIVersionCheck
- type Answer
- type Answerer
- type AttributeData
- type AttributeType
- type BindingHop
- type Bindings
- type BodyDecoder
- type BrowserApp
- type Buffer
- type Caller
- 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) SetResourceParent(scope accesstypes.PermissionScope, member, parent accesstypes.Resource)
- func (b *CollectionBuilder) SetResourceQueryKeys(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]) 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 DomainBindingData
- type DomainRoster
- type ExecuteGate
- func (g *ExecuteGate) Caller() *Caller
- func (g *ExecuteGate) Enforce(ctx context.Context, txn ReadWriteTransaction, target ExecuteTarget, ...) error
- func (g *ExecuteGate) EnforceView(ctx context.Context, txn ReadWriteTransaction, target ExecuteTarget, ...) error
- 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) 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) 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
- type NamedStore
- type Operation
- type OperationType
- type Option
- 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]) PatchType() PatchType
- 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) (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
- type QueryClause
- type QueryDecoder
- func (d *QueryDecoder[Resource, Request]) Decode(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]) 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]) 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 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
- type Statement
- type Store
- type StoreName
- type StoredFile
- type SubjectAnchor
- type SubjectBindingData
- type SubjectFactSource
- type Surface
- type SurfaceKind
- type TagData
- type TargetedMethod
- type TargetedRPCDecoder
- type TenantDeclarationColumns
- type TenantDeclarations
- 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) 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 Upload
- type UserPermissionChecker
- type UserPermissions
- func Masked(perms UserPermissions, mask accesstypes.PermissionMask) UserPermissions
- func RolePrincipalPermissions(role RolePermissions, actor accesstypes.User) UserPermissions
- func SessionPermissions[U UserPermissionChecker, R RolePermissions](ctx context.Context, forUser func(accesstypes.User) U, ...) UserPermissions
- type ValidateFunc
- type ValidatorFunc
- type ValueKind
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 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.
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 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 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.
Variables ¶
var Demonstrations = []Demonstration{}/* 287 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 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.
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 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 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 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 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 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 every tenant's declaration of one directory, for a first sign-in by a person no user was created for (session.Auth.SetDirectoryAdmission, through signin.DirectoryReader): the directories record's rows whose method and connection are the directory's, each 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. The generated New<Record>DirectoryReader constructor supplies the columns; an application calls that one. A directory no tenant declares answers nothing, and so does a record that declares no directories. The reader has no side effects, as a retried transaction needs.
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.
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 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 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. 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 UserDomainsHandler ¶
func UserDomainsHandler(userPermissions func(r *http.Request) UserPermissions) http.HandlerFunc
UserDomainsHandler serves the session's tenant list: the sorted list of domains where the user holds at least one grant and that the session reaches. 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 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 not listed. 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: "username (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 impersonating username (session id)" for an impersonated user, "actor as role name (session id)" for a role.
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.
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 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 RPC handlers stamp it into the context before Execute runs; a body reads it back with CallerFrom.
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.
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.
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.
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) 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).
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
}
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 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]) 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 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.
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 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) 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) 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) 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) 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.
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.
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.
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) 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).
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" )
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 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.
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.
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.
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]) 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.
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).
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.
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.
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]) 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.
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]) 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]) 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.
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 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.
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.
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.
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
}
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.
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 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 per 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).
DirectoriesTable string
TenantColumn string
MethodColumn string
ConnectionColumn string
// DefaultSeatColumn is the directories record's column naming the role a person the
// directory vouches for is seated with in the tenant at their first sign-in, NULL or
// empty for none (the tenant admits its people through that 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 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
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.
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) 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 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 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 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 the application's staff, who hold a grant in the global
// partition and reach every tenant. 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 UserPermissionChecker, 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 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 the application's staff, holding a grant in the global partition, who reach every tenant as the sign-in policy admits them (signin.TenantPolicy). 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 staff. In a tenant the session does not reach it holds nothing: every check Denied, an empty digest, no foothold, and the tenant is not listed, so the picker never offers it and the generated domain guard refuses a direct request for it as it refuses a domain that is not a tenant (UserPermissions.Reaches). An application that keeps no declarations passes nil, and every tenant admits every session.
A role checker has no User(): a role is not anyone. For a role principal the composed UserPermissions reports the session's effective identity — its Username, which is the actor who established the session — so a row condition's subject binds to the 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 )
Source Files
¶
- after_commit.go
- answer.go
- apiversion.go
- body_decoder.go
- body_limit.go
- browser_app.go
- caller.go
- capabilities.go
- clone.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
- 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
- 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
- signal.go
- signinroles.go
- sortrows.go
- sqlgenerator.go
- sqlgenerator_lowered.go
- struct_decoder.go
- structfields.go
- subject_facts.go
- tags.go
- tenancy.go
- tenantcreation.go
- tokentype_string.go
- touched.go
- types.go
- upload.go
- user_domains.go
- value_limits.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. |