resource

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2026 License: MIT, MIT Imports: 72 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

resource

The resource package provides permission-enforced CRUD over Spanner-backed resources: the resource package is the runtime (query decoding, permission enforcement, patch sets), and the generation package at the module root is the Resource Generator that turns annotated source structs and schema migrations into handlers, routes, request structs, and TypeScript — including zz_gen_api.ts, the typed client surface the framework-neutral @impulseframework/resource runtime interprets (see the lodestar demo).

Every generated handler is a frame around the application's code: the generated part of one request, from reading the route parameters and the body, through the permission check at the gate and the row lookup within the caller's tenancy, to the call into the application and the response, refusals included. What sits inside the frame is the application's own: an RPC method's Execute, a computed resource's Read<Name> and List<Name>, a file's content function. The frame owns the response writer, the transaction, and every status the application does not choose through @answers, which is the guarantee the rest of this document leans on: JSON in, JSON out, permission-gated, transactional. This document says "the generated frame", or just "the frame", for that part and "the body" for the application's code inside it.

Annotation and Struct-Tag Reference

The generator and the runtime are driven by three small vocabularies, all defined in this document:

  1. Comment annotations (@resource, @suppress(...), …) written in doc comments, parsed by the generator.
  2. Struct tags you write on your source structs (spanner, conditions, …), read by the generator.
  3. Struct tags the generator writes into zz_gen request structs (json, perm, immutable:"true", …), read back by the resource runtime. You never write these by hand — they are listed so you can read generated code, not so you can author it.

Completeness is enforced by tests: every keyword registered in resourceKeywords() and every tag-key constant in generation/annotations.go and tags.go must appear in this document, so a new annotation cannot land undocumented.

The lodestar demo app is the living example; links below point into it.

1. Comment annotations

Annotations are written in the doc comment of the declaration they configure. Only comment lines that start with @ are parsed; anything after the annotation on the same line is treated as a comment. Arguments go in parentheses, comma-separated; annotations that take no arguments are written bare. The rule is positional: a prose line that happens to begin with an @ word is parsed as an annotation too, and one that repeats a keyword is refused as used twice, so start such a line with another word.

// Ship is a starship registered with the port authority.
//
// @resource
type Ship struct { ... }
Annotation Attaches to Arguments Effect
@resource struct in the resources package none Marks the struct as a resource backed by a Spanner table. The generator emits query builders, request structs, handlers, routes, and TypeScript for it. Example: Ship.
@virtual struct in the resources package none A resource backed by a view instead of a base table. Because there is no table metadata, indexed fields must be declared with index/uniqueindex tags (see §2), and the read identity (if any) with @primarykey. A view that declares its key serves a keyed read route beside its list, as a table does (@suppress(readHandler) removes it). Without a key the view is a whole read-only list, with no read route and no paging: one list route serves every row the filter admits in one response, sorted when a sort is asked or an @order declared, a numeric limit or a cursor is refused with a 400 naming @primarykey as the way to page (section 4), @page is refused at generation, and its metadata says readDisabled. A view that carries a table's rows one to one declares the table with @rowsOf, so a page listing the view writes to the table; without it the view is a read-only list. A view declares two bindings on fields of its own, each in its bare form, since a view has no schema to resolve a join path against: @domain on the tenant column its query selects, and @attribute on a column a grant's condition reads by name (a fact about the row, which the view's query computes). A view keyed by one field may be a method's @target: the method's Execute grant is then judged against the row, within the tenant (see @target). Examples: OpenMissionsBySquadron; SectorPilot, a view with a fact that is a method's target.
@computed struct in the resources package none A read-only resource (List/Read only) whose rows are produced by hand-written query logic rather than a table. Primary-key fields are marked with @primarykey, and the key is optional: without one the resource is a whole read-only list, with no read route and no paging (one list route, every row the filter admits in one response, sorted when asked or declared; a numeric limit or a cursor is refused naming @primarykey as the way to page, @page is refused at generation, and the Collection registers List only, so a Read grant on it is refused at deploy). Example: StandingOrder. A computed view that carries a table's rows one to one declares the table with @rowsOf, so a page listing it writes to the table. Its permission checks run when the request is decoded, since the rows come from a Go function and no query of the library's. A grant on it may still carry a condition that reads the row: the struct declares the fields a condition may read with a bare @attribute(name) on the field, and the library judges each row the function yields, in Go, by the rules a table's rows follow (a row the condition on the resource refuses is not listed, not counted, and read as a row that is not there; a field granted under a condition the row does not meet is left out of that row; a row that would show none of the fields a grant covers is left out). The condition reads the declared fields, subject, now, and the facts about the caller that are held in tables (subject.<name>, a subject set or a subject value). A table's statement reads such a fact as a subquery beside its rows; for a computed resource the library reads it once for the request, when the request is decoded, through the resource client, by a statement built from the same pieces (the anchor table, the caller's rows on it, the anchor's own tenancy filter, a dotted value hop by hop). So a request costs one read for each fact its conditions name, whatever the number of rows, and none where no condition names one. The read is implemented for Spanner, the database the resource client reads; the PostgreSQL statements are rendered and proven by test, as the rest of the PostgreSQL rendering is. Deploy-time role migration validates a computed resource's condition as a table's, against the fields the resource declares, and the generated Collection marks the resource computed so a refusal names that declaration. Example: Lodestar's Flight Lead reads the expense manifests of the missions their own squadrons fly (assignedSquadron IN subject.squadrons), through the list, the read and the rendered file. A field a list sorts, filters or searches by needs an unconditional grant, and qSet.TakePage() answers false while a condition is left to judge the rows by. Example: the roles a tenant picks from (section 22). From the browser a computed resource answers a list query exactly as a table does, with no code in its List function: the generated handler applies the filter, then the sort when the request asks one or the struct declares one (@order), then the page (cursor, Link header, count) over the rows the function yields; with neither a sort nor an @order only the whole list (limit=all) is served, the rows in the order the function yielded them, after the filter; a paged request without an order is refused (section 4). A field is filterable when it carries allow_filter, as on a table; index and uniqueindex are refused (there is no database index), and allow_filter on a field the in-memory evaluator cannot compare fails generation with the field named. A List function that runs its own queries may take pieces of the work to push down — qSet.Filter().Take(fields…) returns the conditions on those fields and leaves the handler the rest (defined on an AND-only filter; an OR takes nothing; a field is taken whole, so a body that takes a text field answers its matches too, Condition.MatchesText, and one that takes the box reads its SearchTerms and SearchFields, section 4), qSet.TakeSort() returns the total order (empty when the list is not sorted: the body's own order stands) and marks it the body's, and qSet.TakePage() returns the page bounds only when paging in the body is correct (nothing left to filter, the sort taken, no count asked) and otherwise answers false so the handler pages. Taking is the only way to opt out, so a body can never make the result wrong. A computed list sorts and pages NULL where the application's database does, the same end as the tables beside it (Spanner first ascending and last descending, PostgreSQL the reverse); a body's plain ORDER BY already produces that placement, and the generated decoder carries the database type so the handler's in-memory sort and page boundary agree with the rows a body yields. Example: SectorHazardBoard.
@rpc struct in the rpc package none, or max: 8MB, log: onEvent, trace: off Declares an RPC method: the struct's fields are the request payload, and the struct declares Execute in one of two forms, read off its signature — Execute(ctx context.Context, txn resource.ReadWriteTransaction, client *Client) error runs inside the generated handler's read-write transaction; Execute(ctx context.Context, client resource.Client, rpcClient *Client) error runs outside one. The third parameter is the application's own RPC client type. Execute returns error alone, and the handler answers with an empty 200, or (Result, error) with Result a struct type or a pointer to one, and the handler answers with the result after the transaction commits, mirrored with generated wire names (a nil pointer answers empty). A method answers with identifiers and outcomes, never rows: a @resource or @computed struct in the result position is refused, since rows are read through their own routes, where permission masking applies. A struct with no Execute, or one of another shape, fails generation naming the struct; no interface declaration takes part. Example of an answering method: InspectShip. The generated frame stamps the caller into the context before Execute (resource.CallerFrom), so a body may arm a typed patch or query with .Enforce(caller) and run the pipeline the resource routes run, or ask caller.Check for a decision to branch on; without either the body is trusted, the default. A transaction-form method honors X-Dry-Run: true: the whole frame and the body run and the transaction rolls back, refusing exactly as the real call would and answering an empty 200 where it would have succeeded; a client-form method refuses the header with 400. The generated TypeScript method metadata says which a method is (dryRun: true on a transaction-form method, nothing on a client-form one), so a page knows a dry run previews the call before it sends one, and names on each request field the name a grant's condition reads it by (attribute: 'role' for a bare @attribute(role) on the field): the Angular library's method dialog rehearses a method this way where the caller's grant on it carries a condition, waiting for the fields a condition may read and marking them when the dry run is refused as not permitted. Examples: HoldMission (armed), CompleteMission (decision as data). Gated by the Execute permission. The struct lives in a file named after it in snake case (claim_mission.go), as every generated kind does; a name ending in Test carries the _rpc marker instead (start_flight_test_rpc.go), so neither it nor the zz_gen_ files generated beside it are Go _test.go files. Example: ClaimMission. max: bounds the method's request body (a byte count or KB/MB/GB, 1024-based), applied by its generated handler in place of the application's limit (section 8, request body limits); a method that declares none takes that limit. Example: IssueBulletin. log: is the method's own request log word, always, onEvent, sampled (with fraction: 0.01) or never, and trace: its own trace setting, followFrontEnd, capped (with rate: 0.1) or off: the nearest declaration, over its outlet's and the application's (section 8, request logs and traces). A word is refused on a scheduled method, which declares it on @schedule, and with @suppress, where no route carries it; a trace setting needs GenerateRouter. Example: IngestDroidReports.
@enumerate named type with underlying type string enum table name Generates typed constants for the named type from the rows of an enum table, and declares the table an enumeration: its rows are the program's constants, fixed at generation time. Two rules follow. A table-backed field whose foreign key points into the table is emitted as an enumerated picker whose values ride in the TypeScript metadata (enumeration: [{ id, display }], Description as the display), so the browser needs neither a request nor a List grant, and this wins even when a struct also exposes the table as a resource. A @resource struct backing the table is read-only by derivation: no patch handler, no Create/Update/Delete in the collection, fields marked readOnly, and create or update defaults, validators, or a manual patch Set on it fail generation. A table is an enum table when it has an Id column and a Description column (the generator runs SELECT DISTINCT Id, Description against the migrated schema); a Description column on a table keyed otherwise, such as the feature flags or an auth's roles, names no enumeration. An enum table with more than 500 rows warns at every generation, since each field keyed into it carries every row in the TypeScript metadata; the warning names the bytes and the fields, and the way out is to drop @enumerate from the type and expose the table with a @resource struct, whose picker reads it whole or, under a @page maximum, one page at a time. Example: ShipRole behind ShipClass.RoleID.
@enumerate field of an @rpc, @resource, @virtual, or @computed struct resource or enum table name Declares which resource a picker for the field lists — the field holds another resource's identifier, and the generator alone says which. The generated metadata emits displayType: 'enumerated' with enumeratedResource: Resources.X; the browser narrows and presents X's rows and never chooses another resource. X must exist — a table-backed, virtual, or computed resource — and be keyed by a single column, since a picker stores one key. On a list field of an @rpc struct (a list of plain values) the field holds several picked keys and the metadata emits displayType: 'enumerated[]'; a list field of a table, a view or a computed resource refuses the annotation, since a column stores one key, and so does a list of nested values; a picker of several reads X whole, so an X with a @page maximum fails generation there. A picker reads X in one of two ways, chosen by X's @page maximum: with none, the whole list in one request (limit=all), the chosen row resolved from it, so X may suppress its read; with a maximum, one server page at a time, the chosen row read by key, so X must serve a read — a bounded X with a suppressed read fails generation naming the two ways out (keep the read, or drop the maximum), on this path and on an undeclared foreign key into a routed resource alike. A list field cannot declare one: the field would store many keys where a picker stores one, so @enumerate on a slice, an array, or a named list type fails generation on every path naming the struct and field (struct Ship field Tags: @enumerate on a list field; a picker stores one key), and a byte slice, one value on the wire, is not a list here. Four rules: a plain column (no foreign key) names the resource the picker lists, with no Go validation and no database check, as for an identifier held from outside the schema (example: Mission.BriefingTemplateID → BriefingTemplates); a foreign key may name a resource other than its target whose rows key into the same space, typically a virtual view over the target carrying display columns the target lacks, while the constraint stays the guard at write time — naming the target itself is refused as redundant, the schema already says so (example: Mission.ClientID → ClientRosters); naming an enum table — one an @enumerate type declares, with or without a struct over it — renders the field from the inline enumeration values exactly as an inferred key into that table does, one rule for declared and inferred (example: FailMission.ReasonID); and a declaration on a foreign key that already points into an enum table is refused as a contradiction, since those values are program constants baked into the metadata. A request field has no schema, so it always declares (example: CompileBriefing.TemplateID, naming a computed resource). A declared enumeration follows the RPC outlet rule: naming a resource that is not on the target outlet fails generation with the fix named, where an inferred key degrades to its plain type.
@suppress @resource, @computed, or @rpc struct one or more of listHandler, readHandler, patchHandler, allHandlers, allRoutes Skips generating the named handlers, or all routes. Suppressing readHandler on a resource a picker lists is refused where the resource declares a @page maximum (@enumerate). Suppressing patchHandler also removes the resource from the consolidated patch handler. allRoutes is rejected on consolidated resources unless the patch handler is suppressed or the resource is excluded from consolidation. On an @rpc struct, any argument suppresses the generated handler.
@defaultsCreateType @resource struct type name The generated create path calls Defaults() on the named type to set defaults when creating the resource.
@defaultsUpdateType @resource struct type name As above, for updates.
@validateCreateType @resource struct type name The generated create path calls Validate() on the named type to validate the incoming resource.
@validateUpdateType @resource struct type name As above, for updates.
@primarykey field of a @computed or @virtual struct none Marks the field as (part of) the resource's primary key; multiple annotated fields form a compound key in declaration order. Primary-key fields are exempt from field-level permission enforcement (their readability follows the resource-level grant). The key is what gives a row identity: the read route (/{key}), the cursor's tie-break (the key fields end every order, so a keyset cursor walks a total order), and the browser's row identity (keyOf). Without a key the resource is a whole read-only list, with no read route and no paging: served in one response, sorted when asked or declared, refusing a numeric limit or a cursor with a 400 that names @primarykey as the way to page, and refusing @page at generation. Rejected on table-backed @resource structs, whose keys come from the schema. Compound example: SectorHazardBoard; key-less example: StandingOrder.
@rowsOf @virtual or @computed struct table resource name The view declares its backing table, a create goes into the table, and the new row shows up in the view on the next list because the view's SQL reads that table. The declaration states row identity, not columns: every row of the view is one row of the named table under the same key, and the view's other columns are its own — joined from other tables, aggregated, or computed in the projection; the generator compares none of them to the table. It checks, each refusal naming the fix: the named resource exists and is a table-backed @resource (a @virtual or @computed target is refused, since a view cannot back a view, and an @enumerate table — with or without a struct over it — is refused as a contradiction, since its rows are the program's constants and a create button for them would be policy about nothing); the view declares @primarykey fields matching the table's key in count, order, Go field name, and Go type, nullability included, and on a @virtual the spanner columns as well, the message naming the first mismatch and the table's key; the two share a @permissionScope; the table is served on every outlet the view is served on (fail loud, never a silent degrade); and the view does not name itself. Refused on @resource and @rpc structs. Several views may name one table. The view's TypeScript metadata carries rowsOf: Resources.X, so a page listing the view sends its create, edit, and delete to the table and opens a row on the table's page; a view without the declaration is what it is today, a read-only list. One backing table only: two tables sharing one key (a table and its one-to-one extension) is the door left open and not built, and a parent joined to its children is never one to one with anything and stays a read-only list or an RPC. Examples: MissionBoard, a same-row view over Missions; SquadronRoster and PilotAssignment, two association views over SquadronMemberships whose compound key is edited and deleted from the list. OpenMissionsBySquadron and FeeByKind declare nothing and stay read-only lists.
@changedBy @virtual or @computed struct table names The tables whose changes change the resource, so a commit on them reaches the resource's live pages. On a virtual resource the declaration replaces what the generator reads off the query (the text behind its Subquery method, an embedded file, a string literal or a concatenation of constants, walked with memefish's lexer for the names in table positions, section 14), so it can drop a table the walk misread as well as add one the query does not show; the generator still reads the query, and a declaration that differs from the reading is a warning naming both sides, never a refusal. It is the way out when the reading refuses (a name in a table position that is neither a table nor a CTE in scope, a recursive WITH, a text the lexer refuses) and required for a query built at run time. A computed resource is Go, so the declaration is its only source: without one its changes are not published, its pages stay plain, and nothing refuses. The @rowsOf root must be in the set, read or declared, and a name the schema lacks is refused; refused on @resource and @rpc structs. The sets are recorded next to the resources, as each package's generated LiveDerivations, and assembled in the handler package's zz_gen_live_derivations.go (section 14), so what the generator concluded shows in the diff, and the resource's TypeScript metadata says live: true. A table of an Auth's generated management (section 22) is read or declared like any other and recorded by its name, since the type over it is internal to the management's tree. Examples: MissionBoard, read off its query; SectorHazardBoard, declared.
@typescript the declaration of a type used as a field: a struct, or a named type over another type (type Position json.RawMessage) Name, or Name, from: "module" Declares the TypeScript type of a Go type whose shape lives outside Go, once, on the type's declaration, and every generated file that carries the type imports Name from module, spelled verbatim. A table column, a computed field, or an RPC field typed by it is Name in its interface, with display type object in the metadata. Without from:, Name must be a TypeScript built-in (string, number, boolean, unknown). A plain struct needs no declaration: its interface is derived from its fields (section 12). A type that writes its own JSON (MarshalJSON or UnmarshalJSON) must declare, since its fields say nothing about the wire, and is refused without it. A type declared over json.RawMessage, or over any type with JSON methods, needs no hand-written methods: the generator writes its JSON pair (section 12), so the type is its declaration and this annotation and nothing else; json.RawMessage itself is unknown without any declaration. A declaration promising anything but string on a plain byte slice (type Token []byte with no JSON methods) is refused, since the wire carries base64 there. A slice comes from the field ([]Position is Position[]), never from the declaration; the declaration is read wherever the type is declared, in the application or in a dependency. Two declarations importing one Name from different modules are refused, as is from: on a built-in and a non-built-in without it. Not valid on a @resource, @virtual, @computed, or @rpc struct, which are typed field by field. Example: Position.
@attribute field of a @resource struct (bare form also on a @virtual struct and on a field of an @rpc or @computed struct) name[, via: Remote.Segments] Declares an attribute binding: the vocabulary name grant conditions reference for this row attribute (ABAC). Bare, the annotated column itself carries the attribute; with via:, the binding is a join path leaving through the annotated foreign key — via: carries only the remote segments, Go field names on each successive struct, dotted for multi-hop (via: StationId.Sector), and every hop must resolve many-to-one through a real foreign key or generation fails. On a virtual resource only the bare form is valid, naming a column the view's projection carries: a fact about the row is a column the view's query selects, whatever join computes it, and a via: there is refused with that as the way to the same fact. A view's attribute is a table's from there on: the collection carries it, access.MigrateRoles validates a condition's names and literals against it, a grant on the view (the resource's or a field's) may carry a condition that reads it, and so may the Execute grant of a method whose @target is the view. Example on a view: SectorPilot. On a field of a @computed struct the bare form names the row's own Go field: the row comes from the resource's function, so there is no schema for a via: path (a fact from elsewhere is a field the function fills), the type is one the library compares in Go (a string, an id, an integer, a float, a bool, a time.Time or a civil.Date, a pointer to one, or a list of one), and the library judges each row the function yields by reading the field (the @computed row). On a list column (an ARRAY: a slice field, never a byte slice) the bare form declares a list attribute, typed by one item: a condition that reads it is judged once for each item of the row's list, the whole condition each time with the item as the attribute's value, and holds only when it holds for every item. So role != 'Administrator' over the roles an invitation gives says none of them is Administrator, and role IN ('Staff', 'Viewer') that every one is Staff or Viewer. A list with no item, and no list at all, is judged once with no value: no value never permits, and role IS NULL OR role != 'Administrator' admits it. The database judges it in one statement (no item fails the condition), on Spanner and on PostgreSQL alike, and it is the rule a request's list field follows. A condition reads one list, on the left of a comparison, as the row holds it: a second list, a list on the right side, the list an update proposes (new.) and any list in a Create grant's condition are refused when the roles are deployed, and a list at the end of a via: path at generation. Example: the roles of a tenant's invitation (section 22). Every attribute is drawn in the package's generated zz_gen_bindings.dot: a via: path hop by hop, a bare attribute as a line in its resource's box, pointing at its table when the column is a foreign key (see @domain). On a field of an @rpc struct the bare form declares a request field a grant's condition may read: the method's Execute grant reads it as new.<name>, the word a Create grant uses for the row being written, so a role file can limit what its holder asks for (new.role != 'Administrator' on a method that gives a role). The field is a string, an id (impulse.UUID), an integer, a float, a bool, a time.Time or a civil.Date, a pointer to one, or a list of one; a decimal, a database wrapper (spanner.NullString) and a struct are refused at generation, since the value is compared as it was decoded. The condition is settled the moment the request is decoded, before any row is looked for: on a method with no @target the call is then allowed or refused, in the words a caller with no grant hears, and on a method with a @target the part that reads the row goes on to the gate, so one condition may hold both (fliesElsewhere = false AND new.clearance <= 3). A request field compares against literals alone: a comparison against subject, a subject value or set, now or an attribute of the row is refused when the roles are deployed, as is a new.<name> the method does not declare. A field left out of the request is its type's empty value, which the condition judges; a nil pointer is no value, and no value never permits. A list is judged once per element and every element has to pass; a list with no element is no value. A method declares one list field this way, and a second is refused at generation. The row's capabilities=Execute answer counts a new. term as possibly true, since no value is proposed yet, and the permission digest says conditional; a dry run of the method (X-Dry-Run) answers for a value. Examples: SetSectorPilotClearance, a request field beside a fact of the target row; the generated management's methods that give a role (section 22). Names follow the condition language's identifier rules ([A-Za-z_][A-Za-z0-9_]*); subject, now, and new are reserved; a name is declared once per resource, or once per method.
@domain field of a @resource struct (bare form also on a @virtual struct) none, or via: Remote.Segments Declares the structural tenancy binding: how every row of a domain-scoped resource resolves to its tenant. Bare on the tenant-key column itself, or via: a foreign-key path to it (same grammar as @attribute). Mandatory on every domain-scoped table-backed or virtual resource — missing is a generation error, and so is declaring it on a resource that is not domain-scoped: global scope is the explicit opt-out (design plan §06). On a virtual resource only the bare form is valid, naming a column the view's projection carries. A bare @domain derives the tenant column's runtime behavior — never stated twice: the column decodes output-only (create and update closed, so the wire cannot express a tenant write or re-tenant a row) and the framework stamps it from the request's domain partition on create, so the checked domain and the written domain are the same value by construction; restating behavior through conditions or default_create_fn tags is rejected, and Create/Update on the column are ungrantable while reads stay grantable. Deliberately not an @attribute — it is consumed by tenancy injection and never referencable from grant conditions. At most one per resource. It also tenant-filters the subject subqueries anchored on the resource (see the subject rows). The via: path is resolved through foreign-key metadata, not through the remote resource's own bindings — a domain-scoped parent table does not transitively supply tenancy to resources referencing it; each resource declares its own @domain. Generation warns at every run for a listed table-backed resource whose lists the schema does not serve under this binding: a bare @domain with an @order and no index leading with the tenant column and then the order columns, where the warning names the index wanted, or a via: path, whose lists scan the whole table (section 9). Every attribute and subject binding a package declares, and every @domain(via:) path, is drawn in one committed, drift-tested zz_gen_bindings.dot beside the workflow graphs: a box per resource declaring a binding, listing its bare bindings as name: column (subject.name: column for subject vocabulary); dashed boxes for the tables a path lands on or a foreign key points at; a subject ellipse for the requester, entering each anchor once with every set and value it yields there; one edge per hop drawn once however many paths share it (solid attribute, dotted domain, dashed subject), labeled name: column on a continuing hop and name: column ⇒ column where the path terminates; and a thin grey edge from a bare binding on a foreign key to its table, so the two names a condition pairs (assignedSquadron IN subject.squadrons) meet at one table. The bare tenant column is not listed, the state column's reference to its enum table is not drawn (the workflow graph covers the states), and a package declaring no binding writes no file. Example: Lodestar.
@state field of a @resource struct default: <value> Marks the resource's state column (ABAC design plan §09). The column must be a foreign key to its state enum table (the ordinary Id/Description convention — the FK identifies the table, nothing is declared on it), and the declared default must be one of that table's values. The marker derives the field's behavior — never stated twice: the field decodes output-only (create and update closed, so the wire cannot express a state write; transitions happen inside RPC bodies), Create/Update on it are ungrantable, reads stay grantable, and the generated create patch applies the declared initial state on insert (never a database DEFAULT). State values change only by migration: a mutation permission registered against the state enum table is a generation error, while Read stays grantable.
@stateRoot FK field of a @resource struct RootStructName Declares workflow membership (ABAC design plan §09) on the foreign key anchoring the member — the field is the hop, so only the workflow root's struct name is spelled. Each member declares only its immediate hop; chains compose through other members and must reach the root (a cycle or a hop outside the workflow fails generation), every hop is many-to-one through a real foreign key, and member and root permission scopes must match. The generator synthesizes the uniform state attribute binding on the root (a column binding on its @state field) and every member (a join path through the chain), so one condition text reads identically across the workflow, and emits the assembled graph as a committed, drift-tested zz_gen_workflow_<root>.dot file per stateful root: the whole tree — root and members as solid nodes with one edge per hop labeled with the anchoring FK field, dashed context nodes for every FK reference leaving the tree (the tenant record included), a state cluster with every value and the default marked, one labeled edge per declared @transition, and a legend; undeclared state changes stay RPC-body business rules the framework cannot see. The TypeScript resource metadata carries the same facts (root, members with hops, states, default, transitions) as a Workflows constant, so a frontend can render the graph itself. A resource belongs to at most one workflow.
@transition @rpc struct RootStructName, from: a[, b…], to: c Declares the RPC method as a workflow state transition (ABAC design plan §09): the method moves rows of the named root resource along one edge. The root must carry @state, every from/to value must be a value of its state enum table, method and root permission scopes must match, and the struct's Execute must be the transaction form, carrying exactly one @target field. The generated handler owns the mechanical frame inside the transaction it already runs: before the body it locates the target row within the tenancy predicate (absent or cross-tenant is NotFound) and verifies the pre-image state is in the from set, then evaluates any row-referencing condition the caller's Execute grant carries against the same located row — either refusal is one uniform Forbidden naming the method and the row, so the wire never says whether the state or the condition said no (§12); after the body returns without error it stamps the to state as the last mutation. The body never reads or writes the state field — it carries only the edge's business effect. Who may run the method stays its Execute grant (grants-only, §09). The declared edge travels in the generated Collection, draws labeled edges in the workflow DOT file, rides the TypeScript method metadata, and answers capabilities=Execute per row. Example: LaunchMission.
@target field of an @rpc struct none, RootStructName, or RootStructName, key: KeyField Marks the field carrying the target row's key, its type matching the key column it carries. A method addresses one row: a target keyed by one column is named by one field, and a target keyed by several is named by one field for each column, every one declaring @target(Root, key: KeyField) with the key field it carries (the fields may be declared in any order; a column left uncarried, a column carried twice, a field naming no key field, and fields naming two resources are generation errors). With @transition it is bare and single (the declared root is the target, and a workflow root is keyed by one column); without one, @target(Root) names the row resource directly and the method gets the plain located-row form (ABAC design plan §12): the generated handler locates the row inside its transaction (absent or cross-tenant is NotFound) and evaluates any row-referencing condition on the caller's Execute grant against it, with no state check and no stamp. Either way, a targeted method's Execute grants may carry row conditions — access.MigrateRoles validates them against the target resource's binding vocabulary — and the method joins the target resource's per-row capabilities=Execute answer. Requires the transaction form of Execute; method and target permission scopes must match. A domain-scoped target resolves tenancy through its @domain binding, either form: a bare tenant column is read off the located row, a join-path binding is verified with one query in the same transaction — absent and cross-tenant rows answer the same NotFound either way. In the plain form the target may be a view (a @virtual struct) keyed by its @primarykey field or fields. A view's row is one row of the view's query, and in a tenant-scoped view its key names a row in each tenant that holds one — the tenant column is not part of the key, since @domain already holds a row to its tenant, and a key that includes it is refused — so the handler reads no row by the key: it hands the gate the view's own value, named in the package the view is declared in, and one SELECT over the view's query, by the key within the request's tenant, both locates the row and evaluates the grant's condition against it (ExecuteGate.EnforceView), a condition that may read the view's @attribute facts. No row there answers NotFound, whether the key names nothing or another tenant's row; a key that names two rows there fails the call, as a fault of the view's query. Refused on a view: @transition, since a view has no @state to move; and a view with no @primarykey. The TypeScript method metadata names the target as target: { resource, key }, key mapping each request field to the row field it carries, so a page fills the request from a row. Examples: HailShip, a table's row; SetSectorPilotClearance, a view's; RemoveCrewSectorRole of the generated management (section 21), a view's row keyed by two columns.
@answers @rpc struct 200, 409 Declares the statuses the method may answer with; the result type carries HTTPStatus() int and chooses one per response. Allowed: 200, 201, 202, 204, and any 4xx except 401, 403, and 404, which stay the frame's own refusals; at least one must be a 2xx. A 4xx answer is the method's refusal with its typed body: in the transaction form the transaction rolls back first, so nothing the body armed commits. 204 writes no body and requires a pointer result returned nil, or an answerless method, whose only permitted declaration is @answers(204). A result declaring HTTPStatus() without @answers, or the reverse, is a generation error; an undeclared status at runtime answers 500. The TypeScript client resolves { status, result } for a method with declared statuses and still throws on every undeclared 4xx. Example: CompleteMission.
@upload @rpc struct max: 5MB, and store: S for a named store Declares the method as a multipart upload. Its Execute takes resource.Files third, Execute(ctx, txn resource.ReadWriteTransaction, files resource.Files, client *Client), the transaction form only, since the transaction is what claims the files, and the declaration and the signature go together (either alone is a generation error). With store: S, the files go to the named store S (section 13) and Execute takes resource.FilesIn[S], whose keys are resource.Key[S]; the declaration and the signature name one store or neither, and a mismatch is a generation error. The request is multipart/form-data: one part named request first, carrying the JSON the method's decoder reads exactly as for a JSON RPC, then one or more parts named file. max (a byte count or KB/MB/GB, 1024-based) bounds the whole body; over it is a 413 naming the maximum, no file part a 400, a body that is not multipart a 415. The frame streams each file to the method's store, read off the resource client, under a key it minted, runs the body with the files, and on any failure before commit deletes the objects it streamed and answers with the failure; after a commit nothing more happens, since the rows the body wrote claim the keys. The body records each key in a @file column of the same store, a string column for the default store and a resource.Key[S] column for S, whose generated setter takes the typed key, so a key of another store does not compile into it; a key recorded anywhere else is invisible to the release and is the orphaned-file cleanup's. An upload naming a store no @file column holds is refused at generation. Reading a file back is the @file route (section 13). A dry run streams nothing: the files describe the parts with empty keys. The TypeScript handle gains upload(body, files), which refuses locally over the maximum. Examples: AttachRefitPhoto on the default store, AttachMissionDocument on a named one.
@warning @rpc struct typed: open Declares that the method warns before it runs (section 7): a person reads what the call will do, in the server's words, and types the word before the confirm button works. The struct declares Warning(ctx context.Context, txn resource.ReadWriteTransaction, client *Client) (*resource.Warning, error) beside Execute, and the declaration and the method go together (either alone is a generation error). A request that carries X-Warning: true is decoded and checked exactly as the call is, answers the resource.Warning in place of running the call, and saves nothing; a method that declares no warning refuses the header with 400. The typed word is one lowercase word of 2 to 24 letters, which the generated metadata carries (warning: { typed }). Refused on the client form of Execute (the warning is read inside the handler's transaction, which is rolled back), on an @upload method, with @suppress, and with @schedule.
@schedule @rpc struct the cron expression in quotes, zone: "<IANA zone>" (UTC when absent), and log: onEvent: @schedule("30 3 * * *", zone: "America/Denver") Declares the method a scheduled route: Cloud Scheduler calls it on the schedule, read in the zone. The expression is five fields separated by single spaces (minute, hour, day of the month, month, day of the week), each a comma list of *, a value, or a range, the * and the range optionally stepped (*/15, 1-5/2), months and days of the week also by name (JAN, MON); an expression outside that, a zone the time zone database does not know, and Local are generation errors. A scheduled method takes no input: no field, no @upload, no @permissionScope (a domain scope is a path parameter, and a scheduled method checks no permission), no @target or @transition, no @outlet, @feature, @formerly or @suppress, each refused naming the struct, and it needs GenerateRouter. It is served at POST /_scheduled/<method in kebab case> behind the scheduler's token check alone, never on an outlet, never in the permission collection or a TypeScript client. log: is the method's own request log word (always, onEvent, sampled with fraction:, never), set ahead of its handler as a route's is (section 8, request logs and traces); a scheduled method's spans follow the front end, so trace: is refused here and on its @rpc. Section 19. Example: PruneDroidReports.
@file field of a @resource, @virtual, or keyed @computed struct (the column holding the store key); or a keyed @computed struct none, segment, on a field name: Field, type: Field, and log: onEvent, trace: off A row says which stored object is its file, and the generator serves that file under the row's read route: GET <read route>/content answers the bytes with their type, name, size, time, and validator, gated by Read on the resource and a Read grant on content, the route's own field, which the Collection registers with no column behind it (columns=content on a read stays a 400; a grant naming it is accepted by access.MigrateRoles). On a field, the annotation marks the column holding the store key: @file bare serves under content, @file(thumbnail) under its own segment, and name: and type: name sibling columns carrying the file's name and media type (a struct may carry several, one per segment). The column's type says which store holds the file: string or *string is the default store, resource.Key[S] or *resource.Key[S] the named store S, a type the application declares by embedding resource.Store (section 13); both are STRING columns, and the generated FileKeys() names each column with its store. The key column goes off the wire in both directions: never returned on read or list, never accepted on create or update, absent from the TypeScript interface and metadata; a NOT NULL key means a row is added by the @upload method that stores its file, so Create is not registered and the patch handlers refuse a create op naming that way in, while a nullable key leaves Create ordinary. On a keyed @computed struct, @file or @file(segment) declares a rendered file: the computed package declares <Name><Segment>(ctx, key…, qSet *resource.QuerySet[Name], client resource.Client, computedClient *Client) (*resource.Content, error) beside Read<Name>, checked at generation as Read<Name>'s callers are, and a nil content is 404. Deleting a row that carries a key, or pointing it at another object, releases the old object: the patch machinery records the key on the transaction and the executor deletes it from the column's store, wired on the resource client (resource.WithFileStore, resource.WithNamedFileStore[S]), once the commit lands, from every transaction the application runs; one row owns one object, and a row the database deletes by cascade releases nothing (section 13). Under a suppressed read route the declaration serves nothing and still names the key column, so the release and the orphaned-file cleanup see its keys. log: and trace: are the file route's own request log word and trace setting, as on @rpc (section 8, request logs and traces), refused under a suppressed read route, where no route carries them. Refused at generation, naming the struct: a key-less struct, an unknown sibling, two declarations on one segment, a name or type field that is not a string or *string, a key field that is none of string, *string, resource.Key[S] and *resource.Key[S], a resource.Key[S] column without the declaration, the struct-scope form on a table or view, a rendered file under a suppressed read route, and a content function that is missing or has another signature. Examples: MissionDocument.StoreKey, a stored file; ExpenseManifest, a rendered one.
@subjectSet user-id field of a @resource struct; with a who: written, one of the fields the who: names name, value: Field, and the two optional parts who: <tests> and where: <condition> Declares subject-side set vocabulary: subject.<name> in grant conditions is the set of value: values on this table's rows whose annotated column matches the requesting user (crew IN subject.crews). The annotation designates the user-id column — no separate marker — and is repeatable per anchor; value: names the sibling Go field the set yields, dotted to continue through foreign-key hops with the same many-to-one validation as via:; every set is drawn in the package's zz_gen_bindings.dot: the requester enters the anchor once naming its sets, a bare set is listed in the anchor's box and points at its table when the column is a foreign key, and a dotted value continues as edges (see @domain). Tenancy: the rendered subject subquery is tenant-filtered by the anchor resource's own @domain binding, so a domain-scoped anchor must declare one — generation rejects it otherwise, because without it subject.<name> matches the user's rows from every tenant (a membership held at tenant B would satisfy conditions evaluated at tenant A). A global-scoped anchor is the deliberately shared pattern — a certification earned once applies everywhere — and stays unfiltered. Note the anchor's own binding is what counts: tenancy never arrives transitively from a domain-scoped parent table (see @domain). Type: the set's comparison type is derived from the value: column (the terminal of a dotted value) exactly as @attribute's is, and a grant may test only an attribute of the same type for membership in it; MigrateRoles refuses the mismatch at deploy. The two parts: a set's definition may say two more things, each in the language grant conditions are written in (accesstypes/condition, whose package documentation states the grammar of both) over the fields of the same struct, named as Go fields. Both are optional, and a set that writes neither is the set described above and generates as it always has. who: says which rows are the requester's: one test or several joined by OR, each tying a column of the row to the requester, Field = subject or Field IN subject.<another set>. Left out, it is the annotated column equal to the requester. where: says which of those rows count: a condition over the row's own columns compared to literals and to now, with the comparisons, IN (…), IS NULL, AND, OR and NOT, judged as every condition is, so a row counts only where it is TRUE. One table then yields a set for each level it records, an expired row drops out at its hour, and a set follows a person through any table that declares a set of its own: @subjectSet(hangarsRun, value: HangarID, who: UserID = subject OR SquadronID IN subject.squadrons, where: LevelID = 'run' AND (ExpiresAt IS NULL OR ExpiresAt > now)), written on one line or continued over the comment's next lines. A role file does not change: a grant names the set (hangar IN subject.hangarsRun) and nothing of the table behind it. Sets build on sets to any depth, and each keeps its own tenant filter: a set on a tenant-scoped table reads the request's tenant, a set on a global table reads every row, whichever of the two names the other, so a table kept outside every tenant answers the same in each. Both parts render inside the one EXISTS the set already is, the set a who: follows as that set's own EXISTS with the row's column where an attribute would stand. With a who: written the annotation sits on one of the fields the who: names, as every annotation that ties a row to the requester or the tenant sits on the column it reads. Refused at generation, naming the struct, the field and the set: a who: test that does not tie the row to the requester (a comparison to a literal, !=, a negated test, tests joined by AND), since a set of everyone's rows is one mistake away without it; a who: naming a field the struct does not have or one no condition can compare, comparing a column that is not a string to the requester, or writing one test twice; a who: naming a set no @subjectSet declares (the message lists the sets declared), a @subjectValue, or a set whose value type differs from the tested column's; sets that build on each other in a loop, a set on itself included, with the loop spelled out; the annotation on a field its who: does not name, with the fields it may sit on; a where: naming something that is not a field of the struct, or a field no condition can compare; a where: literal that does not fit the column it is compared to (a string against a number, a timestamp that is not RFC 3339, a date that is not YYYY-MM-DD, now against anything but a timestamp); a where: value that an enumerated column does not hold (a foreign key into an @enumerate table, or a field-scope @enumerate naming one), with the values it does hold; and a where: that names the requester (subject, subject.<name>) or a proposed value (new.), since the test that ties a row to the requester is the who: and a set's rows are read as the database holds them. Index warning: generation warns, and never refuses, when no index of the set's table serves the set's lookup, one warning for each column the who: names (the annotated column for a set that writes none), each naming the CREATE INDEX it wants: the tenant column first where the row carries one, then the column, then the value (section 9). Strings: a string literal in a where: is written in single quotes and holds any character, a comma or a parenthesis among them; a quote inside it is written twice (Code = ':)', Note != 'it''s'). A string that is never closed is refused as an unclosed single quote, at the annotation. Examples: SquadronMembership, a set that writes neither part; HangarPass, two sets on one table, each with both.
@subjectValue user-id field of a @resource struct name, value: Field Declares subject-side scalar vocabulary for threshold comparisons (amount <= subject.approvalLimit). Same grammar — and the same tenancy rule, and the same place in zz_gen_bindings.dot — as @subjectSet, valid only where the annotated user-id column is the whole key of a unique index, the single-column primary key included, so the database enforces exactly one row per user; a column of a composite key or composite unique index does not qualify. It takes neither who: nor where:, the parts of a @subjectSet: its one row is the requester's by the unique column, and generation refuses either on it. Type: the value's comparison type is derived from the value: column as @attribute's is, and a grant may compare it only against an attribute of the same type (now only against a timestamp-typed value); MigrateRoles refuses the mismatch at deploy.
@manualAddResource accesstypes.Resource constant permission[, scope] Registers the permission on the resource in the generated Collection for a hand-written route with no generated handler. Repeatable. Scope is global or domain; omitted means the global default. An @outlet annotation on the same constant names the outlets the hand-written route is mounted under, so an outlet-filtered TypeScript target (ForOutlet) carries the registration only when it names that outlet; omitted means the default outlet. The constant's value is the resource name and must not contain : (reserved for access-defined markers like accesstypes.GlobalResource); generation rejects it. The registration reaches the TypeScript constants like a generated one: an Execute registration joins Methods, any other permission joins Resources.
@manualAddResourceSet @resource struct comma list of listHandler, readHandler, patchHandler, or allHandlers Declares that hand-written handlers register this resource's permission Sets for the given handler types; validated against the set of generated handlers.
@outlet @resource, @virtual, @computed, or @rpc struct; accesstypes.Resource constant carrying @manualAddResource comma list of outlet names Names the router outlets the struct's routes — or the constant's hand-written route — are registered under. Outlets are independent registration surfaces with their own route prefixes — the generator emits a Generated<Name>Handlers interface and generated<Name>Routes function per outlet, so the application composes different authentication and middleware around each (a browser app on one, a machine REST API on another). The default outlet is declared by generation.GenerateRoutes and carries the reserved name default; additional outlets are declared with generation.WithRouterOutlet(name, routePrefix), and referencing an undeclared name is a generation error. An outlet serving browser sessions declares it (WithRouterOutlet(name, prefix, Auth(pkg, flavor)) under the generated router, ServesSessions() under a hand-written one; section 8): the generated route tables register the permission-digest and user-domains routes under its prefix, and only a session-serving outlet may be the target of a GenerateTypescript call (ForOutlet(name)), which filters every emitted TypeScript file to that outlet's members — a client for a session-less outlet would have no permission channels and fail closed on every page, so it is a generation error. Without the annotation a struct is on the default outlet only; naming outlets replaces that default, so @outlet(default, automation) serves both while @outlet(automation) serves the automation outlet only. Consolidated resources get one consolidated patch dispatcher per outlet (PatchResources, Patch<Name>Resources), each bundling exactly that outlet's members. The generated router tests cover every outlet's routes and additionally prove isolation: a route's path under an outlet it is not attached to must 404. Example: Consignment.
@permissionScope @resource, @virtual, @computed, or @rpc struct global or domain Sets the permission scope used by all of the resource's registrations. Default: global. It also selects the domain the generated handlers evaluate permissions in: global-scoped handlers pass accesstypes.GlobalDomain, while domain-scoped handlers read it from a required /<tenants>/{<tenant>ID}/ route segment pair between the route prefix and the resource path (pair-style, so domain values can never collide with resource or method route names). Both names derive from the package's @tenant record: the segment is the record's route name and the parameter its key's route parameter (Sector keyed by ID gives /sectors/{sectorID}/), and a tenant-scoped resource in a package with no @tenant record is refused. Domain-scoped routes are wrapped in the generated DomainGuard, which asks the application's tenant roster (TenantRoster().Has, section 16) and answers 404 for a domain the roster does not hold before the handler runs, and the same 404 for a tenant the session does not reach (UserPermissions.Reaches: the tenant's declaration does not admit the way the session was established, section 6). With generation.WithConcealedDomains() the guard asks the caller's foothold next (UserPermissions.HasGrants in the domain): a domain where the requesting user holds zero grants answers identically to a domain that does not exist (404 on routes, 400 in consolidated op paths), so refusals never confirm a tenant; any grant in the domain restores ordinary 403s (access.Client.UserHasGrants answers the foothold question from the in-memory snapshot, so the check stays legal inside the consolidated mutation transaction). Tenant identifiers must be a single URL-safe path segment and must never contain : (the character is reserved for access-defined markers; accesstypes.GlobalDomain is access:global); a URL domain is pure data, and accesstypes.DomainScope routes it to a tenant partition by construction, so no value can address the global partition. In the consolidated patch handler, a domain-scoped resource's operations carry the domain in the path exactly as the URL grammar does ({"op":"patch","path":"/sectors/sector-alpha/berths/…"}); global operations stay domainless, an unknown domain in an operation path is a 400, and cross-domain batches are legal (each operation is checked in its own partition; the batch is one transaction). Example: Sector.
@tenant @resource struct none, or label: "<word>": @tenant(label: "Service district") The struct is the tenant record: the table whose rows are the tenants, one per package. Its route name is the segment tenant-scoped routes are served under and its key's route parameter is the domain parameter (Sector keyed by ID gives /sectors/{sectorID}/…); the generator emits New<Record>Roster(client, opts...) into the handler package, which builds the resource.TenantRoster the generated DomainGuard and the consolidated dispatcher ask (section 16); what makes a tenant (the generated New<Record>Maker, at the first sign-in of a person staff invited, and the create-your-tenant route) and the record's generated delete path reread the roster after their commit and signal the tenants kind, so a tenant made at run time is served by every instance without a restart or a release. Nobody creates a tenant directly: the record's create op is refused with how one is made (section 16). The record must be global, table-backed, and keyed by one generated id (ID impulse.UUID, whose text is the domain in every tenant-scoped URL; what people call the tenant is its @tenantName column, changed like any field): @tenant on a @permissionScope(domain) struct, on a compound key, on a key that is not a generated id (a typed string, a foreign key, an interleaved table), on a @virtual, @computed or @rpc struct, or on a second struct is refused naming the rule, and a tenant-scoped resource, view, computed resource or method in a package with no @tenant record is refused (a tenant-scoped resource needs a tenant record; annotate it @tenant). A key cannot change on update. The record names what the screen calls a tenant: the generated browser descriptor carries the word, one and many (domainRoute.word), for the frame's place switcher and menus, from the record's name in words (Sector reads "Sector" and "Sectors", ShipClass "Ship class" and "Ship classes"), or from label: where an application in production changes the word without renaming its tables; the plural is the generator's, as it spells the table. A label is letters, digits, single spaces and hyphens, starting with a letter; any other is refused. Example: Sector.
@directoryOnly field of the @tenant record, a bool column none The tenant's people enter through its directory only: a tenant whose flag is true admits a sign-in through its own directory and nothing else, so a password, a personal account and a sign-in through another organization's directory do not reach it. Two people are not held to it: a super administrator, and an administrator of the tenant itself, who enters with a password and a second factor so that a tenant whose directory is broken can be mended from inside (section 16, "Directory only"). The flag restricts that tenant's own door alone: a tenant whose flag is false admits everyone it seats, however they signed in, and a person the flag keeps out of one tenant still enters every other tenant that seats them. The flag is half of what the tenant record declares about who may enter a tenant (section 16); the other half is the directories record (@tenantDirectory), which the flag needs, since a tenant whose people enter through its directory only needs a directory to enter through, and the directory of such a tenant is not removed until the flag is turned off. The switch is the tenant's own: the generator writes two methods in the tenant's scope, Make<Record>DirectoryOnly and End<Record>DirectoryOnly, which the tenant's administrator runs under an Execute grant on each; turning the flag on is held to three rules (the tenant has its directory, the caller is signed in through it, and the caller has a password where their auth has passwords; section 16, "Directory only"). The record's own write paths, which are global, show the flag and never write it: the field is output only on the wire, at create and at update, and the record's change events are the audit. The generated create-your-tenant route leaves it out of its body: a new tenant declares nothing beyond its creator's directory. Refused on a resource that is not the tenant record, on a column that is not a bool, and on a second column. Example: Sector.
@tenantName field of the @tenant record, a string or *string column none The tenant's name as its people know it. The generated New<Record>Roster reads the column beside the key (resource.WithTenantNames), and the generated UserDomains handler names each tenant of the session's tenant list from the roster (resource.WithDomainNames), so a tenant's own people see its name in the place switcher without holding Read on the record, a global resource; without it the list names each tenant by its key. The generated browser metadata names the column on the record (nameField), so a picker over the tenant record lists tenants by name and the people pages name the tenant a role or an invitation is in. Refused on a resource that is not the tenant record, on a column that is not a string, and on a second column. Example: Sector.
@tenantDirectory @resource struct, @permissionScope(domain) none The struct is the directories record: the tenant-scoped table that holds each tenant's directory, the organization its people sign in through, as the sign-in method (@directoryMethod) and the connection (@directoryConnection). A tenant has one directory and a directory belongs to one tenant: the generator refuses a record whose table has no unique index on the tenant column alone, or none on the method and the connection together, naming the index to add, and the generated write paths refuse first, each with a sentence the person can act on (resource.TenantDirectoryRules, section 16). Nobody types a directory in: the method and the connection are output-only, the record's generated create sets both from the directory the caller is signed in through and refuses a session that came by password or with a personal account (any Google account, a Microsoft personal account), and its generated delete is refused while the tenant is directory only. The record's key is an id its create generates. Its tenant is the bare @domain column, the tenant's key on the row itself, so a tenant's administrator sets and removes its own directory under the record's Create and Delete grants, and the record's change events are the audit. With it the generated New<Record>Roster reads what each tenant declares beside its key (resource.WithTenantDeclarations), New<Record>DeclarationReader reads one tenant's declaration in the sign-in's transaction for signin.TenantPolicy, the record's write paths reload the roster after their commit and signal the tenants kind as the tenant record's do, and the generator emits Set<Record>Directory, the one step that sets a tenant's directory from a sign-in, which the create-your-tenant route calls with the directory its creator came through. Refused on a global resource, on the tenant record itself, on a second struct, with a join-path @domain, without either column, with a key that is not a generated id, and without either unique index. Example: SectorDirectory.
@directoryMethod field of the @tenantDirectory record, a string column none The column holds the sign-in method a directory is reached through, as sessioninfo.AuthMethod spells it: google, azure, workos or oidc (an organization's own OpenID Connect provider, named by its registration's connection). The column is output-only: the generated create sets it from the caller's session, and no request writes it. Refused off the directories record, on a column that is not a string, and on a second column. Example: SectorDirectory.
@directoryConnection field of the @tenantDirectory record, a string column none The column holds the connection a directory's identities carry, the value the session's first auth event records beside the method: a Google Workspace by its domain (the registration admitting any Workspace writes the account's domain), a Microsoft Entra tenant by its tenant id, a WorkOS connection by its id. The column is output-only, as the method is. Refused off the directories record, on a column that is not a string, and on a second column. Example: SectorDirectory.
@directoryDefaultSeat field of the @tenantDirectory record, a string or *string column none The column names the role a person is given in the tenant at their first sign-in through the tenant's directory, whether their account is created then or stood before, chosen by the tenant's administrator from the tenant's roles on its Sign-in page, with the generated method Open<Record>ToDirectory (section 16); NULL (or empty), which Make<Record>InviteOnly writes, says the tenant admits the directory's people by invitation only: a stranger is refused with the invitation_only refusal and no account is created, and an invitation link is the way in. A directories record without the column admits every stranger by invitation only. The role is given once for the link between the account and the directory: a person whose role an administrator removes is not given it back by signing in, and a link that is deleted and made again gives it again where the person holds no role in the tenant. With it the generated New<Record>DirectoryReader answers the tenant whose directory an identity came through with its seat, which the auth's directory admission reads (session.Auth.SetDirectoryAdmission) before the method's account rule, and the role is given by the Auth's generated identity client in the transaction that links the account to the directory (section 16). The column is output only on the wire: the two methods write it, and the record's create and update do not. Refused off the directories record, on a column that is neither a string nor a nullable string, and on a second column. Example: SectorDirectory.
@page @resource, @virtual, or @computed struct default: N and/or max: M Declares the list's page sizes: the page a request without limit receives, and the largest page a request may ask for. Both are positive integers; the default never exceeds the maximum, and a maximum alone must be at least the generator-wide default of 50. Undeclared, the list serves pages of 50 with no maximum. A request over the maximum is refused with a 400 naming it, never clamped, and a resource with a maximum refuses limit=all. The maximum is also the switch a picker reads: a resource with none is small enough to load whole, read in one request with limit=all and sort optional; a resource with a maximum is paged, one server page at a time, so its list needs an order (@order, or sort on the request) and a picker over it reads the chosen row by key, which is why a bounded picker source may not suppress its read (@enumerate). Declaring the maximum is the deliberate choice; nothing decides at runtime from an observed size. Refused on a @computed or @virtual struct with no @primarykey, naming the struct and the two ways out (declare the key, or drop @page): without a key the resource is a whole read-only list, with no read route and no paging, so a page size on it is a contradiction. The generated TypeScript descriptor carries both numbers. Example: Mission.
@order @resource, @virtual, or @computed struct comma list of Field [asc|desc] Declares the order a list takes when the request carries no sort, naming Go fields of the struct; the direction defaults to asc. The primary key is appended at runtime so the order is total, and a request's sort replaces the declared order for that request. The declaration is optional, and every paged request needs an order from somewhere: a resource that declares none serves a request without sort only as the whole list (limit=all), which is not sorted — its table or view statement carries no ORDER BY and the rows arrive in the database's own order, a computed list keeps the order its body yielded — and refuses a bare GET or a limit with a 400 naming the resource and the way out (section 4). A nullable column renders as the plain direction and sorts in its database's own NULL placement, so an index on the column serves the order: Spanner places NULL first ascending and last descending, PostgreSQL last ascending and first descending. A computed resource follows the same placement: its handler sorts and pages the body's rows where the application's database would. On a computed resource only a leaf field may be named (a nested field is opaque). The generated TypeScript descriptor carries the declared order (order: [{ field, direction }], JSON names), so a browser client knows a request without a sort is already ordered and pages by cursor; to a resource that declares none it sends a sort of its own or asks limit=all. On a table-backed resource with a bare @domain, generation warns when no index leads with the tenant column and then these columns in this order and direction, naming the index it wants (section 9). Example: Mission.

| @feature | @resource, @virtual, @computed, or @rpc struct; field of a @resource, @virtual, or @computed struct | the flag's constant, Debriefs | Puts the resource, the field, or the method behind a feature flag, so it exists for the browser and the API only while the flag is on (section 15). The argument is the identifier of a resource.Feature constant declared in the resources package (const Debriefs resource.Feature = "debriefs", its doc comment the flag's description); the constant's value is the flag's name, [a-z][a-z0-9_]{0,63}, and a name declared twice, a malformed name, an unknown identifier, or a value in place of the identifier is refused at generation naming the constants. On a struct every route of the resource or the method answers 404 while the flag is off, exactly as an unregistered route does, its consolidated arm answers as an unknown resource, and the resource, its fields and the method are absent from the permission digest. On a field the decoders answer the field as unknown while the flag is off (a 400 on columns, sort, filter and a patch body naming it) and the handlers leave it out of every response; a primary key, the tenant key, the state column, a @file key, and a column a create must supply (NOT NULL with no default, on a resource that serves a create) cannot be gated, and an @rpc struct's fields are not gated one by one. The TypeScript metadata and the descriptor carry feature: '<name>' on the gated entry, and the client file declares the Feature union and constants. | | @searchAlso | @resource struct | Child.Field, and via: Column where the child has several foreign keys to the parent | Adds a child table's text to the resource's search box (section 4): a term the box searches is found in the parent's own searchable fields or in the named child field, and the parent row is admitted when any of its child rows matches. The child is a table-backed @resource of the same package one hop down a foreign key to the parent's single-column key, under the same tenancy (both tenant-scoped on the row, or both global), and the child field carries a search fact (a token column in the child's search index); each is refused otherwise, naming the rule. The child field's own grant governs the branch: a caller denied the field searches the parent without it, a conditional grant conjoins its condition inside the branch. The generated resource declares SearchBranches(), the metadata lists the branch in searchFields under its dotted name (clientContact.displayName), and a box over the parent reads one key set per term (section 4). Generation warns where the child's search index does not store the foreign key, since every matching child row is then read back for its key. Example: Client. | | @listAcrossTenants | @resource or @virtual struct with @permissionScope(domain) | none | Serves the resource's list a second time without the tenant's segment: GET (and POST) /<prefix>/<resources> reads the resource's rows in every tenant the session reaches in which the caller holds the List grant, with one filter, one sort, one page and one count across them (section 4, a list across tenants). Each row is checked under the caller's grants in its own tenant and carries the reserved zzTenant property, the tenant it is in. Only a declared resource gets the route, and the tenant's own list is unchanged by the declaration. It adds the handler <Plural>AcrossTenants beside the list handler, the route on the outlets and behind the @feature flag the resource declares, outside the DomainGuard, and acrossTenants: true on the resource's TypeScript descriptor, which gives the browser client client.acrossTenants.<resources>. It adds no permission: the list is the resource's List grant, asked in each tenant, and the global permission digest tells the list's page whether that is anything at all for the person (ListAcrossTenants, section 5). The generated collection marks the resource, and only a marked resource is decoded as a list across tenants or holds a live subscription over a set of tenants. Reads only: every write stays inside one tenant. Refused on a global resource (there is no tenant to read across), on a resource whose list is suppressed, on a @computed resource (its rows come from the application's own function, which answers for the one tenant it is handed) and on an @rpc struct, and where another route of the outlet already answers at the list's path (an RPC method named as the resource's plural). A column or field named zzTenant is refused on every resource, as the other reserved row names are. Generation warns where a declared table-backed resource with an @order has no index that leads with the order columns and carries the tenant column (section 9). Example: Mission. | | @formerly | field of a @resource or @virtual struct; field of an @rpc struct or of the struct its Execute answers with; @rpc struct | the former name as it was written, Title | Keeps a renamed field or method answering under its former name while applications built before the rename are still answered (section 18). The column never changes; only the wire name moves, and the former wire name derives from the argument as the current one does from the field (@formerly(Title) on Headline answers title beside headline). On a field, a request body naming the former name is read as the current one and a body naming both is refused with a 400 saying to send one; columns, sort and filter take either name, with the permission checks running against the current field; and every row carries both keys, each masked when the field is. On an @rpc struct the router registers the former route (/release beside /publish) on the same handler, and the generated router test drives both. The generated collection carries the former names (TagData.Formerly on a field, CollectionResource.Formerly on a method), and the permission digest mirrors a renamed field's or method's entry under its former name, so an application built before the rename keeps its column or its action. The TypeScript knows only the current name. A former name equal to the current one, or to another field's or method's name or former name, is refused at generation, as is the annotation on a @computed struct and the struct form on a @resource or @virtual struct. | Exactly one of @resource, @virtual, @computed, or @rpc may appear on a struct. The generator refuses a struct carrying more than one, naming the kinds it found.

2. Struct tags you write (source structs)

Field-level permissions are structural, not annotated: every non-primary-key field of a resource implicitly requires the endpoint's permission on Resource.field (List and Read for reads, Create/Update for mutations; Delete stays resource-level). Primary keys are exempt — their readability follows the resource-level grant. There is no per-field permission tag to write: a perm: tag on a source struct is a generation error, and a stale one in a generated request struct fails Set construction at startup.

Tag Where Effect
spanner:"ColumnName" every field of @resource/@virtual structs Maps the field to its Spanner column. Required — a missing tag or unknown column is a generation error, and field nullability must match the column's: a pointer or a Null wrapper on a nullable column, a plain value on a NOT NULL one. A slice-typed field follows the column's nullability, since a Go slice has one form: the Spanner client reads NULL into a nil slice and writes nil as NULL, so []byte types a nullable BYTES column and a NOT NULL one alike, as []T does an ARRAY<T> (section 12, nullable slices). A pointer to a slice is refused.
conditions:"…" resource fields Comma-separated list of field conditions, see below. Values match exactly (no spaces); a value the generator does not recognize is refused, with the nearest recognized one suggested.
default_create_fn:"pkg.Func" resource fields The generated create path calls the referenced function to populate the field when the request doesn't supply it. A field with a default function is not treated as required.
output_only_update_fn:"pkg.Func" resource fields The generated update path sets the field by calling the referenced function on every update; implies output-only. This is the mechanical enforcement stamp — a field whose meaning is "this row was updated", like UpdatedAt. A timestamp with domain meaning (a "last serviced" written by one business transition) is not an update function: it is an explicit update in the code that owns the business event — see Ship.LastRefitAt. Declaring an update function on any field also gives the resource a generated New<Resource>Touch(keys…): an update carried entirely by the update functions, running the full update pipeline (permission check, stamps, write conditions, change events) with no caller-set fields — the only way to express "bump the row" (an update patch with no fields set is a silent no-op). Example: Ship.UpdatedAt using resource.CommitTimestampPtr.
allow_filter:"true" resource fields Permits filter expressions on a field that isn't indexed (indexed fields are filterable automatically). Copied through to the generated request structs. On a table or view the filter must also touch an indexed field, which the database parse enforces: once one index has narrowed the rows a second is rarely used, and indexes are a scarce commodity on Spanner, so allow_filter conserves them. On a resource with a bare @domain column the tenant predicate is not that indexed field: it is the baseline every unfiltered page pays, and the rule asks the filter to narrow below it. The TypeScript field metadata says so: filterable: 'withIndexed' on a table or view field, 'always' on a computed resource's, whose List function filters in memory. Refused on a list field (a slice, an array, or a named type over one; a byte slice is one value) on every kind of struct, since Spanner has no array equality and a computed resource's evaluator compares single values: Ship.CargoBays: allow_filter on a list field; a filter compares single values.
index:"true" @virtual struct fields only Declares the field indexed (filterable/sortable). Rejected on table-backed resources, which get index information from the schema. Refused on a list field: no index serves an ARRAY column.
uniqueindex:"true" @virtual struct fields only As index, and marks the index unique. Refused on a list field, as index is.
search:"Table.Column" @virtual struct fields only Names the table column whose search fact the field carries (section 4): the view's SQL projects that column's token column under its own name, and the field answers the matches and joins the box as the table's field does. The generator cannot read a view's projection, so the author states it, as index is stated; the fact itself is read off the schema, and a value that is not Table.Column, a table or column the schema does not have, or a column with no search fact is refused naming it. On a table-backed struct the tag is refused: the schema states the facts. Example: ClientRoster.Name.
masking:"positional" @resource and @virtual struct fields The field's masked cells stay hidden on the wire, but a list orders and filters on the real column, so the page comes off the index and a reader can tell where the hidden values fall. Every untagged field conceals: a sort or filter on it runs over CASE WHEN <condition> THEN column END (section 4), which hides where the masked values fall and which no index serves, so a page sorted or filtered by it sorts the tenant's whole partition. Declare positional on a field whose rank is not sensitive (a deadline; a fee's rank is) and that a list pays for: named in @order, indexed, or allow_filter. masking:"concealing" is accepted and says the default; another value is refused with the nearest one suggested. Refused as a contradiction on a primary key (keys are exempt from masking), on a field no query sorts or filters by with an index behind it (neither indexed, nor allow_filter, nor named in @order: there is no index to restore and the rank would be disclosed for nothing), and on @computed and @rpc structs (a computed list sorts and filters only by fields granted unconditionally, so no masked cell meets a sort or a filter there, and a method is never listed). Copied through to the generated list and read request structs and surfaced in the TypeScript field metadata as masking: 'positional'. Deploy-time role validation (access.MigrateRoles, access.ValidateRoles) warns where a role's conditional grant lands on a concealing field the resource orders by or admits as a sort or filter key and the role's other grants leave the CASE standing; the warning names the field, the cost, and the three ways out (grant the field unconditionally, tag it positional, accept the cost for a table that never pages at volume). Example: Mission.Deadline.

Values recognized in a conditions tag:

  • immutable — the client sets the field on create, and it can never change afterward: an update touching it is rejected with a 400 (the generator emits immutable:"true" into the patch request struct — you write the condition, never the emitted tag), and the generated Collection never exposes Update on the field's tag as grantable.
  • pii — marks the field as personally identifiable. Emitted as pii:"true", surfaced in the TypeScript metadata, and the field is rejected in URL filter expressions (filter via the POST body instead, which doesn't land in access logs).
  • input_only — write-only: the client sets the field on create and update, and the server never returns it. Read and list structs get json:"-", and a columns=<field> naming it answers 400. The generated TypeScript row interface omits the property, since no list or read response carries it; the metadata entry stays, flagged writeOnly: true, so a config-driven form still renders the input; the Create and Patch shapes and the field-name constants carry it, since a client writes it and a grant check names it; and a row read with capabilities=Update names it in the envelope when the caller's Update grant covers it, since the envelope speaks for every field the caller may write, projected or not (section 4). Example: DistressCall.Transcript.
  • secret — the field holds a secret the application must use itself: an API key, a signing key, a credential of another system. It says everything input_only says, since a secret is never served, and three things more. The value is kept encrypted: the field is typed resource.Secret (*resource.Secret where the column allows NULL) on a BYTES column, the write path seals the value where it turns a patch into columns, and code that needs the value opens it with the row's generated Open<Field> method (section 23). The metadata entry is flagged secret: true beside writeOnly: true, so a form types the value into a masked input whose toggle shows what is being typed; there is no stored value for it to show, since the server returns none. And a change record names the field as changed and keeps neither its old value nor its new one ("Secret": true in the change set), where it keeps both for every other field, write-only ones included. input_only alone does not mean secret: a write-only field can be something a person files and the server does not serve back, which is read as it is typed and belongs in the record. A value a caller presents to the application to be let in (an application token, a password) is not a secret field either: the session library stores those as hashes, since the application never needs the original back. The generator refuses secret where the field cannot honor it: on a primary key, on a field the server owns (output_only, an @state column, the tenant key), on a view, on a foreign key or a field with a picker (@enumerate), on a field typed anything but resource.Secret (a plain string or []byte would be stored as it was typed; the refusal names the type to give it), and on a column that is not BYTES with room for the 42 bytes sealing adds. A method's request field takes the same word, unchanged: text or bytes, no picker, and the method's dialog draws the same masked input (the generated temporary-password methods declare theirs so). That value is never stored, so it is never sealed, and a request field typed resource.Secret is refused. Example: Ship.TransponderKey.
  • output_only — the server owns the value: returned to clients but never accepted from them (patch structs get json:"-", excluding it from both create and update input). The value comes from the database or from default_create_fn / output_only_update_fn — and a field with an output_only_update_fn is output-only even without the condition. Example: DistressCall.CaseNumber.

immutable, input_only, secret, and output_only each answer the same question — what may a REST client do with the field, and when — so they are easy to confuse. In particular, immutable is not output_only: an immutable field is client-supplied exactly once (e.g. an identifier chosen at creation), while an output-only field is never client-supplied at all (e.g. a commit timestamp).

conditions: Client reads it Client sets it on create Client sets it on update
(none) ✔ ✔ ✔
input_only ✘ ✔ ✔
secret ✘ ✔ ✔
output_only ✔ ✘ ✘
immutable ✔ ✔ ✘ (rejected with a 400)

These conditions describe the REST contract only: what an untrusted client can read and write over the wire. Application code calling the generated CRUD layer is not constrained by them — it can write any field; that path is guarded by code review, not by these rules. Two parts of secret are not the wire's alone: the value is sealed and a change record leaves it out whoever wrote it, application code included, since the patch layer does both. The default_create_fn / output_only_update_fn functions are not REST-specific, however: they run inside the generated patch pipeline and fire for application code exactly as for REST requests. They fill a field the caller left unset — explicitly setting the field pre-empts them, which a REST client can never do for an output-only field but application code can.

One contract to know when driving the patch layer from application code: an update patch with no fields set is a silent no-op. Apply and Buffer return immediately — no permission check, no output_only_update_fn, no mutation, no change event — so a keys-only patch does nothing at all (and a REST PATCH with an empty body is a harmless 200 for the same reason). "Bump this row's enforcement stamps with no field changes" — a touch — is therefore not expressible as a bare update patch: use the generated New<Resource>Touch(keys…), which exists exactly when the resource declares an output_only_update_fn field and runs the full update pipeline with the update functions supplying the write. Keep the two kinds of server-owned timestamp apart: update functions enforce mechanical stamps (UpdatedAt), while a timestamp with domain meaning (LastServicedAt) is an ordinary explicit update performed by the one piece of application code that owns the business event — output_only keeps clients out, and the writing code sets the field like any other.

A second contract sits beside it: an update that changes nothing is no error. Where every field an update sets already holds that value, the update succeeds, and on a resource that keeps change records it writes no record, since nothing changed. A request repeated after a timeout, a task a queue delivers twice and a sync that runs again find the row as they asked, and a REST PATCH that restates the row answers 200. Only the low-level insert-or-update (resource.CreateOrUpdatePatchType) keeps its refusal.

Two more things a patch can be told from application code, each decided from whether its row is there: an update that creates the row when it is not (OrCreate), and a create that leaves the row alone when it is (OrSkip). Section 22 has both.

3. Struct tags the generator writes (zz_gen request structs)

Read back at runtime by the resource package; listed here for reading generated code.

Tag Meaning
json:"camelName" Wire name of the field and the key under which its permissions are registered. json:"-" hides the field (input-only fields in read structs; primary keys and output-only fields in patch structs).
perm:"-" The primary-key exemption marker, emitted only on primary-key fields of list/read (and computed) structs: the field requires no field-level grant, and its readability follows the resource-level grant. Every field without the marker is enforced structurally with the endpoint's permission. - is the only legal value — any other perm value in a request struct is a startup error (the stale-struct guard).
immutable:"true" From conditions:"immutable"; the patch decoder rejects updates to the field. On the grant side, the generated Collection never lists Update on an immutable field's tag, so the (unsatisfiable) update grant can never be assigned to a role.
index:"true" From the schema's indexes: the field's column leads some index of the table, the primary key and Spanner's foreign-key backing indexes included, or, on a resource with a bare @domain column, sits directly after the tenant column in one, since the list binds the tenant by equality and the index then seeks on both. A trailing key column anywhere else and a STORING column carry no tag: a filter on either alone would scan the index. On a virtual resource the tag is authored (index/uniqueindex, section 2). Makes the field filterable; sort is not gated on it.
allow_filter:"true" Copied from the source struct; makes an unindexed field filterable.
pii:"true" From conditions:"pii"; the field is rejected in URL filter expressions.
masking:"positional" Copied from the source struct; a sort, filter, or cursor on the field runs on the real column while the cell stays masked in the output. Absent on a concealing field. positional is the only value written; any other value in a request struct is a startup error (the stale-struct guard).
sqltype:"STRING(64)" The column's declared type, verbatim from the schema, on a patch request-struct field whose value the decoder sizes before anything is buffered (section 11): a string-kinded field on STRING(n), []byte on BYTES(n), a decimal on NUMERIC, and a slice of one of those, named or not, on the matching ARRAY<…>. Absent on MAX columns, on keys and output-only fields (hidden from the patch wire), and on every other type. A value the runtime cannot pair with the field's type is a startup error (the stale-struct guard).
nullable:"true" On a patch request-struct field typed by a slice whose column allows NULL, and nowhere else: a Go slice has one form, so the decoder cannot read the fact off the field's type as it does off a pointer or a Null wrapper. The decoder accepts a JSON null for the field and stores the nil slice, which the Spanner client writes as NULL (section 12, nullable slices); a slice field without the tag refuses null with <field> cannot be null, since its column is NOT NULL. true is the only value written; any other value, or the tag on a field that is not a slice, is a startup error (the stale-struct guard).

| feature:"debriefs" | From @feature on the field: the flag the field is gated behind, on the list, read and patch request-struct fields alike. While the flag is off the decoders answer the field as an unknown column and the handlers leave it out of the response; the digest leaves Resource.field out. The value is the flag's name; a value that is not one is a startup error (the stale-struct guard). | | formerly:"title" | From @formerly on the field: the former wire name, on the list, read and patch request-struct fields alike. The decoders read a body key, a column, a sort field and a filter field under it as the current field, and refuse a body naming both; the generated collection carries it as the tag's Formerly, which the permission digest mirrors (section 18). | | search:"token=Name_Search;index=ClientsSearch;role=text;anchors=prefix,suffix;contains" | The field's search vocabulary (section 4), on the list and read request-struct fields of a table or view: the token column and the search index behind it, how the token column reads the column (role=text, digits or date, with zone= for a timestamp's), the anchors it was tokenized with (anchors=prefix,suffix), whether it answers an unanchored match (contains), whether it folds diacritics (diacritics), and the lowercased stored column that gives a case-folded startswith (lower=Name_Lower). A computed resource's allow_filter text fields carry search:"memory": the handler evaluates their matches and the box over the rows the body yields. The decoder reads the tag back to decide which startswith, endswith and contains conditions a field answers and which fields the box searches; a value it cannot read is a startup error (the stale-struct guard). |

4. Reserved query parameters

List/Read requests accept exactly these query parameters — anything else is a 400, and none of them can be used as field names in filters:

Parameter Meaning
columns Comma-separated JSON field names to return; omitted means all accessible fields. Leaving out a sort field or the primary key changes nothing about paging: the cursor reads those keys from the statement, not from the returned row.
filter Filter expression over indexed/allow_filter fields, e.g. name:eq:Vanta. Operators: eq, ne, gt, lt, gte, lte, in, notin, isnull, isnotnull, and on a text field with a search fact startswith, endswith and contains (below). A value may be written in double quotes, name:eq:"Vanta, Ltd.", where it carries a comma, a pipe, a parenthesis or a space; a backslash escapes a quote or a backslash inside the quotes. The search box is the condition *:search:"nguyen 1987 4321", one per filter (below). On POST query routes the filter may be sent in the body as {"filter": "…"} instead (required for pii fields, and for the box where it searches one), but not in both places. The expression is validated when the request is decoded, with the rest of the request's shape: a field that is unknown or not filterable, a malformed condition, or a value that does not fit its field is a 400 before any permission check runs, any query executes, or a computed resource's List function is called. A table filter must also touch at least one indexed field, which the database parse enforces; an indexed field is one whose column leads an index or, on a bare-@domain resource, follows the tenant column in one (section 3), and the tenant predicate itself does not count. The generated field metadata states the same eligibility, so a browser draws a filter control only where the server will answer: filterable: 'always' on an indexed table or view field and on a computed resource's allow_filter field, 'withIndexed' on a table or view allow_filter field and on one filterable through its search fact alone (its search list names the matches that stand alone, below), and nothing on a field a filter may not name.
sort Comma-separated field[:direction] entries, e.g. name:asc,rank:desc; direction is asc (default) or desc. Omitted, the resource's @order applies. Every paged request needs one or the other: with neither, a request that is not limit=all is refused with a 400 naming the resource and the way out (<Resource> declares no order; add a sort, or ask limit=all; on a resource with a maximum, <Resource> serves at most N rows per page and declares no order; add a sort), and limit=all alone is served unsorted.
limit The page size: rows returned per request. Omitted, the resource's declared default applies (@page, generator-wide default 50). A value over the resource's declared maximum is refused with a 400 naming the maximum, never clamped; 0 is refused. limit=all returns every row with no Link header, is permitted only on a resource that declares no maximum, and is the one list request that needs no order (sort). A @computed or @virtual resource with no @primarykey is served whole on every request, limit=all or none: a numeric limit on it is refused with a 400 (<Resource> declares no primary key, so its list is served whole and does not page; drop the limit, or declare @primarykey to page).
cursor The page position, copied from the Link header of the page that issued it (rel="next" or rel="prev"); never assembled by a client. A sealed token carrying the boundary row's sort values, the direction, and a fingerprint of the resource, scope, filter, sort, and limit — a cursor altered, sealed by another application, or presented with a different query, tenant, or page size is a 400. A cursor is valid for the database that issued it: the seal binds it to the application, and its position is read back in that database's NULL placement. A request with a cursor carries the same sort and limit as the page that issued it. Every paged request carries an order (@order or sort), so every page has its Link relations; a cursor never names a position in an unsorted list, because such a list is served only whole. A cursor on a resource with no @primarykey is refused with a 400 naming the missing key: the list has no row identity to anchor a position on, so it is served whole (limit).
count count=true on a first page asks for the total number of rows the same WHERE admits, answered in the Total-Count header; later pages carry no count and refuse the parameter. A whole list (limit=all, or a key-less resource) answers it too. A request that does not ask pays nothing.
offset Removed. A request carrying it is refused with a 400 naming cursor as its replacement; pages are positioned by the row the cursor names, not by a count of rows to skip.
_v The live pages' version (section 14): a client holding a live row or list appends it so the browser's cache keys the answer by the change it last saw. 1 to 64 characters of [A-Za-z0-9_.:-]; accepted and skipped, never a filter. A list or read response to a request carrying it is the one response that carries Cache-Control: private, max-age=300.
capabilities Comma-separated write permissions (Create, Update, Delete, Execute) to evaluate per row — the §13 capability envelope. Each returned row gains the reserved zzCapabilities property: Update carries the positive list of editable JSON field names, every field the caller may write on the row whether or not the read projected it, in name order (a write-only input_only field, which no read returns, is named when the caller's Update grant covers it, so an edit form draws its blank input), Delete a boolean, Execute the positive list of @target methods that apply to the row — a declared @transition requires the row's pre-image state in its from set, a conditional Execute grant ANDs its condition into the same boolean (a plain @target method's is the condition alone; unconditional plain methods are structural, no SQL), and the user holds the method's Execute grant — and Create the positive list of workflow member resources the user may create beneath the row (§11): the members whose immediate @stateRoot hop is this resource, gated by the user's member Create grants, a conditional grant's state terms evaluated against this row's own uniform state binding while terms the parent row cannot answer count potentially-true (an unconditional member grant is structural, no SQL). Advisory hints computed from the same row image and decision instant as the read (conditions render as booleans in the same statement; pure RBAC adds no SQL; a new.-referencing term counts potentially-true while the rest of its condition still renders). Enforcement is unchanged.
domains On a list across tenants alone (@listAcrossTenants, below): the filter on the tenant, tenant keys separated by commas, domains=<key>,<key>. The list reads the named tenants among those it would read without the parameter, down to one. A tenant the session does not reach, or one that does not exist, contributes nothing and is never an error, so the answer never says whether a tenant exists; an empty entry is a 400. On every other route, the tenant's own list included, it is an unknown parameter.

Dates and times. A filter value on a date or timestamp column is read the way a person writes a date, and means the whole of what is written: deadline:eq:2026-12-15 is that day, deadline:lte:12/2026 is through the end of December, and deadline:gte:2026-12-15T09:30 is from that minute. The forms are the day in ISO, US or eight-digit shape (2026-12-15, 12/15/2026, 20261215), the month (2026-12, 12/2026), the year (2026), and an ISO day with a time of day to the minute or the second (2026-12-15T09:30, "2026-12-15 09:30:15"); an RFC 3339 timestamp with its zone, 2026-12-15T09:30:00Z, stays the instant it names. Each operator reads the span as the person means it: eq inside it, ne outside, lt before its start, lte before its end, gt from its end, gte from its start; an in list ORs the spans and a notin list ANDs their outsides. The parse expands the condition into those comparisons, so the SQL and the in-memory evaluation see plain comparisons on typed parameters, (Deadline >= @p1 AND Deadline < @p2). A value with no zone of its own is read in the person's zone, which the resource client sends on every request as the Time-Zone header (an IANA name, America/New_York), so the browser filters by the same day it shows; without the header, in the zone the column's date search fact declares (below), and in UTC where it declares none. A date column (civil.Date) reads the day, month and year forms with no zone, a month or a year being its days, and refuses a time of day. What cannot be read is refused in plain words naming the field as written and the forms with today's date, deadline: 'tomorrow' is not a date. Write it as 2026-11-03, 11/3/2026, or 2026-11-03T09:30 with the time., and the other types answer in the same shape: age: 'ten' is not a whole number., fee: 'abc' is not a number., active: 'maybe' is not true or false., shipId: 'nope' is not an identifier like 0f8fad5b-d9cb-469f-a165-70867728950e. A header naming no zone is refused in the header's name. Relative words (today, last week) are not read.

Search. A text field answers startswith, endswith and contains, and a resource answers the search box, exactly where the schema states a fact for it; the generator derives the vocabulary, writes it onto the request structs as the search tag (section 3) and into the TypeScript field metadata as search: ['contains', 'startswith'], and the decoder refuses a match a field does not answer with the same 400 shape as an unknown operator, naming the matches it does. Two facts. The search fact: a hidden TOKENLIST column generated by TOKENIZE_SUBSTRING over the column, carried by the table's one CREATE SEARCH INDEX, gives the field contains (SEARCH_SUBSTRING(token, @term)), the anchored matches it was tokenized with (relative_search_types => ['value_prefix', 'value_suffix'] give startswith and endswith; short_tokens_only_for_anchors leaves the field its anchors alone), and a place in the box. The token column reads the column in one of three shapes: the column itself (role=text, the term bound as typed, Spanner folding case and punctuation), its digits (REGEXP_REPLACE(col, r'\D', ''), role=digits, the term stripped to its digits so 123-45 meets 123454321), or its date as YYYYMMDD (FORMAT_DATE('%Y%m%d', col) or FORMAT_TIMESTAMP('%Y%m%d', col, zone), role=date: a date field joins the box, where a typed 1987, 1987-03 or 3/14/1987 meets it as a prefix of YYYYMMDD, and answers no text match of its own; a timestamp names the zone its day is read in, since the database's default zone is not UTC, and one without is refused). remove_diacritics is read and folded the same way in memory; a word or n-gram tokenizer states no fact and is left alone, and any other expression over a TOKENLIST column is refused at generation rather than half-read. The prefix fact: a stored LOWER(col) column that leads an index, or sits directly after the tenant column in one on a bare-@domain resource, gives the field a case-folded startswith (STARTS_WITH(col_lower, @term), the term lowercased by the server) and nothing else; it never joins the box, so a table serves its box from one index. A view's author names the table column a field carries with search:"Table.Column" (section 2) and projects the token column under its own name; a computed resource's allow_filter text fields answer all three matches and the box in memory. A field with a search fact is filterable through its matches without index or allow_filter, and a match through the search index, or through the index the lowercased column leads, is the indexed touch a table filter needs; the box is one too.

The box, *:search:"nguyen 1987 4321", is one condition on the pseudo-field *: the text splits into terms at whitespace, at most 8 terms of at most 64 characters each within 200 in all, and the condition holds where every term is found in at least one of the fields the box searches, each term read for each field's role (a term with no digits never meets a digits field; a term that is not a date never meets a date field). The fields are the resource's own fields with the search fact, in declaration order, and the @searchAlso branches (section 1); the TypeScript resource metadata lists them as searchFields: ['name', 'contactEmail', 'clientContact.displayName'], so a screen can say what the box searches, and the resource decides the list, never the screen. Beside it the metadata carries what the browser needs to apply the same grants: pii: true on a field declared pii (a box reaching one is posted), and searchBranches: [{ field: 'clientContact.displayName', resource: Resources.ClientContacts, fieldName: 'displayName' }], the child resource and field whose List grant governs each branch, with pii: true on a PII child field, so a denied branch leaves the box's placeholder as it leaves the search. Every token field contributes contains to the box, anchors or not, so a term is found anywhere in the value; the anchors give the field startswith and endswith beside it. One box per filter; a second is a 400. The box is sent as a filter condition like any other, so it joins the rest of the filter with , and |, and the whole filter travels in the URL, or in the POST body where the box searches a pii field, as a pii field's own condition does. Under the caller's grants a box field the caller is denied drops out of the box silently (the box names what it searches, so its absence discloses nothing, where an explicit match on a denied field is a 403 like any filter on one), a conditionally granted field stays with its condition conjoined inside its match ((condition AND SEARCH_SUBSTRING(…)), so the search index still serves it, where an eq runs over the visible projection), a positional field renders bare, and a @searchAlso branch follows the child field's grant the same way; on a computed resource every searched field needs the caller's unconditional grant, as its sort and filter fields do. On Spanner a box whose fields come from one search index renders inline; a box whose fields span several search indexes (a view projecting two tables' token columns) or whose resource declares @searchAlso branches reads the resource through one key set per term, a UNION DISTINCT of the matching keys from each index and each child, joined on the key and apply-joined into the resource, since the service refuses an OR touching two search indexes in one query block; such a box joins the rest of the filter with , alone (a box under | is a 400 naming the rule), and the statement names the query optimizer version the search functions need in its request options. A view whose box spans several indexes declares @rowsOf, and its root table carries an index on (tenant column, join column) for each other table its box reaches, which generation refuses without, naming the index: the branch into that table's index comes back to the view's rows through the foreign key, and the key set costs the matches only when that index serves it. On PostgreSQL every match renders as ILIKE over the role's expression of the column and a branch as a correlated EXISTS; the matching trigram or expression index is the application's DDL, as every PostgreSQL index is. count=true counts under the same box, and a cursor's fingerprint covers the filter as before.

A sort or filter runs over the projection the caller can see. A field the caller is denied cannot be sorted or filtered on: the request is a 403 naming the field, because the order or the membership of the result would leak its values. A conditionally granted field can be: the statement orders and filters on CASE WHEN <condition> THEN column END, so a cell the caller may not see is NULL for the query — it sorts in the NULL region where the database places it (Spanner first ascending and last descending, PostgreSQL the reverse, the same as a genuinely NULL cell), matches isnull and nothing else, and a cursor positioned on it carries the NULL key. A condition permits only when it is TRUE, and evaluation is three-valued as in SQL: a comparison against a missing value (a NULL column, a NULL foreign key or a join path that reaches no row, a subject value whose requester has no anchor row) is UNKNOWN, IN and NOT IN against a missing value are UNKNOWN whether the list is literals or a subject set, IS NULL is TRUE and IS NOT NULL FALSE; UNKNOWN refuses exactly as FALSE does — the row is filtered, the cell masked, the write refused, the capability withheld. A number literal takes the attribute's storage type: exact against an INT64 or a NUMERIC column, a double against a FLOAT64 one. A join-path attribute renders as one scalar subquery per hop, a subject set as an EXISTS guarded by the attribute's nullness, so the database's own three-valued logic gives these readings. A set's own definition renders inside that EXISTS: its who: as the tests that make a row the requester's (a test against another set is that set's EXISTS over the row's column, under that set's own tenant filter), its where: as a condition over the row's columns, then the match of the set's value to the attribute and the set's tenant filter, as before. A row is the requester's only where its who: is TRUE and counts only where its where: is TRUE, so a NULL in either drops the row; the reference evaluator in conditiontest states them in Go and the semantic differential in this package's tests compares the rendered SQL against it on the emulator over random conditions and rows. When the field's condition covers the whole row predicate (every returned row shows the field) the raw column is used instead. A grant whose condition implies the field's counts as covered, under a closed set of same-attribute rules: an equality or IN list whose values sit inside the field's IN list, a != or NOT IN naming every value the field's does, and a conjunction one of whose terms does; anything else must spell the field's condition the same way (condition.Implies). A CASE in WHERE or ORDER BY cannot use an index, so only such a field pays for it, and it pays on every page: the partition sorts whole (finding 5). That is the concealing behavior, and it is the default for every field. A field declared masking:"positional" (section 2) keeps its cell hidden but sorts, filters, and pages on the real column: the index serves the page, and the field's rank is disclosed. Its cursor still carries the boundary row's real value: the statement selects it a second time under a reserved zzCursor… column that never reaches the wire, and the token carries it sealed. Every sort key the request did not select rides the same column — a columns= list that leaves out the sort field or the primary key, or an @order field the grid does not show — so the cursor carries what the statement ordered by (a concealing key's visible projection, NULL where the cell is masked) and the row data stays exactly what was selected. index:"true" stays the declaration of which fields may be filtered. A @computed resource's rows are judged in Go as its function yields them, and no statement renders a visible projection over them, so its sort and filter fields still require an unconditional grant.

The primary key sits outside these rules: it needs no field grant, is never masked, and its presence in a request keeps no row. So a request for the key alone (columns=id) has no column's condition to stand for the row's, and the condition on the resource itself filters it: the rows are the ones some grant of the caller's admits, in the list and in its count.

A paged list answers with headers beside its JSON array body. Link (RFC 8288) carries a complete URL per relation that exists — rel="next" and rel="prev", each the request's own URL with cursor set — so the first page has no prev and the last no next, and a client follows the URLs as given. Total-Count carries the total when the first page asked count=true. Every paged request carries an order (@order or sort; without one it is refused, see sort), so a page always has the Link relations that exist. limit=all answers with no Link: the whole list, unsorted when neither an @order nor a sort orders it, a table statement then carrying no ORDER BY and a computed list keeping its body's order, with Total-Count when asked. A @computed or @virtual resource with no @primarykey is that whole list on every request: it has no read route, no page, and no row identity, and a numeric limit or a cursor on it is a 400 naming @primarykey as the way to page. A list served cross-origin must add Link and Total-Count to the CORS exposed headers, or the browser client cannot read them.

A list across tenants. A tenant-scoped resource is served under its tenant's segment, one tenant to a request. A resource that declares @listAcrossTenants (section 1) is also served without the segment, and that one request reads its rows in a set of tenants: every tenant the session reaches (the tenants user-domains lists, section 5) in which the caller holds the resource's List grant, narrowed by domains when the request carries it. The request is the list request above in every other respect: the same columns, filter, sort, limit, cursor and count, one order and one page across the set, and one Total-Count for all of it.

Each row is checked in its own tenant. A person's roles differ by tenant, so the condition on the resource, each field's visibility and the mask are rendered for the caller's grants in the row's tenant: a row one tenant's grant admits is listed while the same row in another tenant would not be, and a field shows on the rows of the tenants whose grants cover it. Tenants in which the caller's checks come out the same share one rendering, and the statement carries one branch per such group of tenants, each led by the group's tenants as a bound array. A field the request names that no grant covers in one of the tenants is masked on that tenant's rows, left out of the row as any masked cell is, where the tenant's own list would refuse the request; a sort or a filter on it reads NULL there, as it does for a masked cell. The request is refused (403) only where a field it names by columns, sort or filter is denied in every tenant the list reads. A subject set follows the row: the tenant filter of a subject subquery compares the anchor's tenant to the row's tenant, never to a parameter, so a membership held in one tenant answers only for that tenant's rows. The search box works across the set the same way: a field's grant decides per tenant whether the box searches it there, and a @searchAlso branch is judged in the child row's own tenant.

Each row says which tenant it is in, under the reserved zzTenant property beside its fields, so a page groups by tenant and opens a row inside its tenant's routes; a resource bound through a join path (@domain(via: ...)) answers the tenant the path resolves to. A tenant the session does not reach contributes no row and is named in no answer, as the tenant's guard conceals it. A caller who holds the List grant in no tenant, or whose domains names none the list would read, reads a list of no tenant: 200 with an empty array and a count of 0, and no statement runs. A set that comes to exactly one tenant is that tenant's own list: the statement and its parameters are the ones the tenant's route renders, byte for byte, so its indexes and its plans are the tenant route's, its refusals are too (a named field no grant covers is a 403 there), and each row still carries zzTenant.

The list is read-only and has no keyed read: a row's link names its tenant, and the row is read, written and asked for its capabilities on its page inside the tenant. capabilities on the list across tenants is refused with a 400 saying so. Only a declared resource is listed this way: the generated collection carries the declaration (CollectionResource.ListsAcrossTenants), and QueryDecoder.DecodeAcrossTenants refuses a resource the collection does not mark, saying to declare @listAcrossTenants, so a hand-written handler cannot read an undeclared record across tenants. A cursor of the list is bound to the resource, the domains the request sent, the filter, the order and the page size, and is refused on the tenant's own route as that route's are refused here; it is not bound to the set of tenants the session reaches, which is worked out again on every request, so a person seated in another tenant between two pages reads its rows from the next page on. The list is plain unless the page asks: a request that carries the subscribe header registers one live subscription over the set of tenants the list reads for the person, up to the most one subscription holds, where a tenant's own list is one over that tenant (section 14). The set is worked out when the list is asked for and again at each renewal, which carries the page's domains back, so a tenant the person was seated in or removed from since is in or out of it from the next renewal on. After a write the publisher asks what it asks of every list, who is subscribed to this list in this tenant, and the record answers from the sets: the page hears a change in a tenant of its set as that tenant's list changing and fetches once, and it is never woken by a change in a tenant the person cannot enter. A subscription over a set of tenants exists for a declared resource alone: the list's request is the only thing that makes one, and the renewal drops one whose resource the collection does not mark, before working out its set (live.WithListsAcrossTenants, which the generated LiveRenew passes). What this costs and where it stops:

  • One subscription holds at most 10,000 tenants (live.MaxSubscriptionTenants). The record keeps the set on the subscription's one document, and the store bounds what it indexes of one document: Firestore allows 40,000 index entries, a tenant of the set costs two, so a document's write fails near 20,000 tenants, and the ceiling is half of that (the arithmetic is in the Firestore implementation's README). A list that reads more tenants than the ceiling registers nothing when the page asks: it is answered as a plain list, not marked cacheable and with nothing logged, since that is a decision and no failure, and the page shows it as any list that is not live. A subscription whose set has grown past the ceiling by a renewal is dropped by it, named in the answer's dropped, and the tab's other subscriptions are kept and extended.
  • A subscription the record does not take at a renewal, a document the store judges invalid, is dropped too, with the store's reason logged, and stops none of the tab's others; the record out of reach fails the renewal as a whole, and the tab renews again.
  • A list the page did not narrow with domains is told of a change to the resource's list in any tenant of its set, whichever rows the page is showing: it fetches its page again and shows what the fetch answers.
  • A subscription the renewal dropped, because its set came to no tenant or to more than one subscription holds, or its resource is no longer declared, is not made again by a later renewal: the page's next request for the list makes it, if there is then a set to make it over.

On PostgreSQL the membership renders as = ANY(@array) where Spanner's is IN UNNEST(@array).

5. The permission endpoints

Every generated router registers two library-owned endpoints on the default outlet (applications wire nothing):

GET /<prefix>/permission-digest              → the session user's global digest
GET /<prefix>/permission-digest?domain={id}  → one tenant partition's digest
GET /<prefix>/user-domains                   → the domains the session user can see

An additional outlet that serves sessions (Auth(...) under the generated router, ServesSessions() under a hand-written one) gets the same two routes under its own prefix, served by the same generated handlers behind the outlet's session middleware; an outlet without the declaration gets neither (the generated router tests prove its prefix 404s them). The default outlet serves them unless it is declared Tokens(...): a machine outlet's generated routes are the resource routes its tokens open and the device flow's two endpoints, nothing else, so a machine outlet, the default included, registers neither of these nor the live routes, and when no outlet serves sessions the generated PermissionDigest, UserDomains and live handlers are not written at all.

The digest. The payload is the user's structural grant enumeration for the requested scope: resource → permission → granted | conditional, with field targets under their dotted names ("WorkOrders.title") and absence meaning denied — consumers fail closed by construction. It is advisory UI material (which menus, routes, and form inputs to render); enforcement stays with the endpoint gate, the read rules, and the write stages. Nothing folds — no now, no row data — so a payload is stable for the life of a policy snapshot and caches cleanly per scope. An unknown or grant-free domain digests to {}, so the endpoint never confirms tenant existence under WithConcealedDomains. @impulseframework/resource-angular/types carries the matching PermissionDigest / PermissionDigestState types (and RowCapabilities for the capability envelope).

Who a list across tenants is for. No one tenant's digest can say whether a page that lists a resource across tenants (section 4) has anything to show a person, so the global digest says it. For each resource declared @listAcrossTenants, the digest of the global scope carries the entry <Resource>: {"ListAcrossTenants": "granted"} while the person may list the resource in at least one tenant the session reaches (resource.ListedInSomeTenant: the session's reach, then the List grant, granted or under a condition, one check for each reached tenant until the resource is answered), and no such entry otherwise. ListAcrossTenants is the digest's own answer and no grant's: no role names it. It follows the session, as the reach does: a tenant that admits its people through its directory alone does not count for a password session, and counts for a super administrator's. The entry sits behind the resource's feature flag with the rest of its entries, and a tenant's digest never carries it. The generated PermissionDigest handler passes resource.WithListsAcrossTenants(Collection()) in an application that declares such a resource; the browser library asks the entry for the page's menu entry and its route, so the application names no permission for the page.

User domains. The payload is the sorted list of domains where the user holds at least one grant, each with the tenant's name ([{"domain": "11111111-1111-4111-8111-111111111111", "name": "North"}]) — the place switcher's question, answered by the library so no application hand-writes it. A tenant the session reaches is listed plainly. A tenant that seats the person and that this session cannot enter, a directory-only tenant whose directory the person did not sign in through, stays in the list marked closed, with the reason as a sentence ({"domain": "…", "name": "Acme", "closed": "Acme admits only people who sign in through its own directory. You signed in with a password."}): the person holds a seat there, so the list tells them nothing new, and it says why this sign-in does not open the tenant. A session that came through another directory is told which, in the words a person knows it by ("You signed in through Google Workspace north.example.", "You signed in through your organization's Microsoft directory."): the generated handler passes WithDirectoryNames with each auth's namer (section 16, "How a sentence names a directory"), and the reason never says a connection that is an id. The tenant's own administrator who signed in with a password, and whose session carries no second factor, is told the way in they hold: the reason ends "As one of its administrators you can still enter it: sign out, then sign in again with your password and the code we email you." It is asked of the same decision the reach is (signin.TenantDeclaration.AdmitsAdministrator), with the code taken as given, so the sentence and the next sign-in agree; such a session arises when the role, or the switch, came after the sign-in, and when a password change left the session without its code. Only a person's own sign-in is told so: a session that views the application as someone else, and one that acts as a role, are refused the tenant and are listed none closed. The browser library keeps a closed tenant out of the session's domains (PermissionStore.domains, so the tenant guard refuses it as it refuses any tenant the session does not reach) and lists it apart in the place switcher, under "Closed to this sign-in", with the reason (PermissionStore.closedDomains, AuthService.closedDomains, PlaceService.closed). resource.ClosedDomains(ctx, perms) is the list on the server. The name is the tenant roster's copy of the record's name column, the field the record marks @tenantName (section 1): the generated roster constructor passes WithTenantNames and the generated handler WithDomainNames(roster) to UserDomainsHandler, so a tenant's own people read its name without holding Read on the record; the domain stands in where no name is held. The predicate is concealed tenancy's own foothold test (access.Client.UserHasGrants) over the session's admission (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 switcher and the domain guard can never disagree. A tenant is offered only when the session may enter it, and the application's tenant declaration decides (section 6); a tenant marked closed answers the session as a tenant that does not exist, as it did before the list named it. 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; existence is the tenant roster's (@tenant, section 16). An empty membership is [], never null.

6. Impersonated sessions

The session package can establish a session that operates as another user or as a role on behalf of an authenticated actor, optionally attenuated by an accesstypes.PermissionMask. Such a session is an ordinary session to every consumer; this package supplies the two pieces that must know about it:

  • SessionPermissions(ctx, forUser, forRole, roster, declarations) composes the request's UserPermissions from the session: forUser (typically access.Client.ForUser) for a user principal — an ordinary session or an impersonated user — and forRole (typically access.Client.ForRole) for a role principal, admits the session into the application's tenants, lists its domains from the roster, then applies the session's mask. A role checker satisfies RolePermissions — UserPermissions without User(), because a role is not anyone — and the composition supplies User() itself: the session's effective identity, which for a role principal is the actor who established it, so a row condition's subject binds to the real person and nobody's identity is borrowed. A person is named as the permission store names them, by the id of their account (sessioninfo.SessionData.User), never by the username, which can change and which two Auths over one database can each hold: User() is that id, subject binds to it, and a column that records who did something (the anchor of a @subjectSet, a filedBy) holds it. An application that does not operate sessions as roles passes RolePrincipalsUnsupported as forRole; a role principal then fails closed (every check Denied, empty digest, no domains) with the same User(). Masked(perms, mask) is the attenuation on its own: a permission the mask does not allow is Denied for every resource before policy is consulted and dropped from the permission digest, so the frontend's digest agrees with what Check enforces. Forgetting the mask fails open, which is why the composition is here rather than hand-rolled per application.
  • The tenant list and the admission. roster is the application's tenant roster (DomainRoster, the TenantRoster's Domains; nil in an application without tenants), and declarations is the application's reader of what a tenant declares about who may enter it (TenantDeclarations: a signin.TenantDeclaration by domain — the directories the tenant admits its people through, and whether through those only; nil when the application keeps none, and every tenant admits every session). A tenant is offered only when the session may enter it, and the tenant's declaration decides: UserPermissions.Reaches(domain) is true when the declaration admits the way the session was established — its sign-in's method and connection, the session's first auth event (sessioninfo.SessionData.EstablishedBy; signin.TenantDeclaration.Admits is the decision, the same one the sign-in policy makes over every tenant of the person) — or when the session's actor is a super administrator, a holder of the role the access library defines in every auth (accesstypes.SuperAdministrator), who reaches every tenant whatever its declaration says; or when the tenant is directory only and the session is its own administrator's, established with a password and carrying a second factor (signin.TenantDeclaration.AdmitsAdministrator, the decision the sign-in policy's second rule makes): a tenant's administrators keep a way into their own tenant, so one whose directory is broken is not one nobody in it can mend. An administrator here is a person who holds one of the roles the application names as a tenant's administrator's (access.WithTenantAdministratorRoles) in that tenant itself, by a membership of their own or through a group kept in the tenant, inside its period, asked of the engine at every request (SessionUserChecker.AdministersTenant, which access.UserChecker implements), so the way closes at the next request once the role is taken away. Nobody else is exempt, a person holding another role in the global partition, a role in every tenant or a role through a group kept for the whole application included, and an administrator who signed in through another organization's directory or with a personal account. The checker handed to SessionPermissions answers the super administrator's question (SessionUserChecker.SuperAdministrator), by the test the sign-in policy's first rule asks (accesstypes.RoleCollection.HoldsSuperAdministrator). A tenant's declaration restricts that tenant's own door alone: a tenant that is not directory only, and a tenant that declares nothing, admits every session of a person it seats, a password, a personal account and a sign-in through another organization's directory included, and a directory-only tenant admits a session established through its own directory and no other. So a session reaches every tenant that seats the person, except a tenant that is directory only and whose directory is not the one the person signed in through; those are the session's closed tenants (ClosedDomains), which the tenant list of a person's own sign-in names with the reason (section 5). An impersonated session is established by its impersonation event, so a directory-only tenant refuses it unless the actor, the real person behind it, is a super administrator; a super administrator's session started by a person who is none is refused it. The administrators' way in is never an impersonated session's: it is a password sign-in's. In a tenant the session does not reach it holds nothing — every Check Denied, an empty digest, no foothold — so Domains, the picker's list, is the roster filtered by the grant and the admission, the generated DomainGuard refuses a direct request for the tenant exactly as it refuses a domain that is not a tenant, and the two can never disagree. One composed value reads a tenant's declaration once, whatever is asked about the tenant after.
  • UserEvent(ctx) — the event source every generated write handler stamps onto DataChangeEvents — writes a person as their username with the id of their account, and the session last: bob (account id), session id. It names the actor first for an impersonated session: alice (account id) impersonating bob (account id), session id and alice (account id) as role PartnerViewer, session id. A person with no account here (an actor another application authenticated) is written by name alone. Every tracked data change carries evidence of the real person with no regeneration, and a rename changes nothing about who a change was made by.

7. RPC methods: what a method is for

The generator enforces a method's shape (@rpc, the Execute forms, the wire vocabulary, the frame). Three conventions it cannot see are stated here, and hold across every application on this stack:

  • A method answers with identifiers and outcomes, never rows. Execute may return (Result, error), and the result is for what the call decided or created: the id of the row it opened, the timestamp it stamped, the readings it folded. Rows are read through their resource routes, where permission masking applies field by field; a result that carried a row would carry it unmasked. The generator refuses a @resource or @computed struct in the result position; this sentence covers the shapes it cannot recognize.
  • A method that only answers a question is a computed resource, not an RPC. A read with no write belongs on a List/Read route with a List/Read grant, where the digest, the client handles, and the masking all already apply. There is no read-only RPC form, by decision. A caller-scoped question ("my standing", "my current level") is a computed resource whose List yields the caller's one row: QuerySet.User() names the identity the permission check ran as — the viewed person under a view-as session, the real actor under an act-as-role session — beside QuerySet.Scope(), and the context carries the same caller a method's body reads (resource.CallerFrom). A table row that is the caller's own is a List grant whose condition binds the user column to subject; nothing new is needed.
  • A transaction-form body keeps its effects inside the transaction. A message, a webhook, a file written from inside Execute cannot be rolled back, so a dry run of that method lies and a retried transaction repeats the effect. Write an outbox row the transaction commits and let a worker deliver it; if an effect truly cannot wait, the method is the client form, which the dry run refuses for exactly this reason. A file a request carries is the one exception, and it has its own form: an @upload method's frame streams the files to the store the method names before the body runs, the body records the minted keys in @file columns of that store, and the transaction's commit is what claims them; on any failure before commit the frame deletes the objects it streamed. The body never writes the store. The other direction is the executor's: a row deleted or pointed at another object releases the old object, which the executor deletes from the store once the commit lands (section 13). What neither covers is a crash between the stream and the commit, or between the commit and the delete, which leaves an object no row claims; the orphaned-file cleanup the framework ships (resource/filestore, section 13) removes such objects once they are older than the window, and the window is the application's decision. The cleanup is the safety net, never the mechanism.
A method that warns before it runs

Some calls a person should not be able to make by a slip of the hand: the one that opens a sign-in method to the world, the one that deletes a year of records. Such a method declares a warning, and the dialog a page runs it through shows the warning before anything is saved. Three things make a warning, and the method declares all of them:

  • The consequence, in the server's words for that call. The method's Warning writes it, inside the handler's transaction, with the request as the person has filled it so far: it can read the row the call runs against and count what the call would touch, which no page can. It answers a resource.Warning: Consequence, the sentences a person reads, and Confirm, the words on the button, which say what the button does ("Retire the Kestrel"), never "OK". A warning whose consequence falls on things a person would want to read one by one (the people who lose access, the missions that are canceled) may carry them in Names, and the dialog draws them as a list of their own under the sentence. Names holds only what the caller may see: the method decides it, as it decides the sentence.
  • The typed word. @warning(typed: retire) names the word a person types before the confirm button works.
  • The warning style. The library's method dialog draws the consequence in its warning colors under a warning icon, with no configuration.
// RetireShip takes a ship out of service and cancels the missions it was assigned.
//
// @rpc
// @warning(typed: retire)
type RetireShip struct {
	// @target(Ship)
	ShipID impulse.UUID
}

// Warning says what retiring this ship will do, before anyone confirms it.
func (m *RetireShip) Warning(ctx context.Context, txn resource.ReadWriteTransaction, client *Client) (*resource.Warning, error) {
	ship, missions, err := client.shipAndOpenMissions(ctx, txn, m.ShipID)
	if err != nil {
		return nil, errors.Wrap(err, "Client.shipAndOpenMissions()")
	}

	return &resource.Warning{
		Consequence: fmt.Sprintf("%s is taken out of service for good. Its %d open missions are canceled, and their crews are told.", ship.Name, missions),
		Confirm:     "Retire " + ship.Name,
	}, nil
}

// Execute retires the ship.
func (m *RetireShip) Execute(ctx context.Context, txn resource.ReadWriteTransaction, client *Client) error {
	...
}

The dialog asks for the warning by sending the request to the method's own route with X-Warning: true (resource.WarningHeader; the browser client's handle.warning(body)). The generated frame decodes that request and checks the caller exactly as it checks the call: the same Execute grant, the same located row, the same condition on the grant, so a caller who may not run the method reads no warning of it, and every refusal answers as the call's own would. It then calls Warning in place of Execute, rolls the transaction back, and answers the warning with 200. Nothing is saved by asking, so the dialog asks as it opens and again after each change to an input, and the words follow what the person has picked. A request field the method marks validate:"required" must be in the request, as in the call's, so the dialog waits for those inputs before it asks; a field the warning should speak of before it is filled is left to Execute to require, in its own words. A method that declares no warning refuses the header with 400 and does not run, so a client generated apart from the server never runs a call it meant to ask about. A warning with no consequence, or with no words for the button, is the method's mistake and fails the request (500).

X-Warning and X-Dry-Run each take the value true, in any case, or are left off the request. Every generated frame that reads either refuses any other value with 400, naming the header, the value it takes and what was sent, and does not run the call (resource.AsksWarning, resource.IsDryRun, each answering the refusal): 1, yes, false, an empty value, and the header sent twice. A client that sends X-Dry-Run: 1 to rehearse a write is told so, and writes nothing.

Either header asks that the call be held back, so a call that has no dry run and no warning refuses a request that carries one: 400, naming the header and saying the call has none, and the call is not run. Only a method has either (an @rpc struct's, an upload's, a tenant's own that the generator writes, and SetFeature), and its frame answers both headers itself. Every other route the generated router mounts (a list, a read, a collection's patch, the consolidated patch with its creates, patches and deletes, the creation of a tenant, a scheduled call, the live routes, and the session library's own: the sign-in, a person's account routes, the device flow) is mounted behind one middleware, resource.NoDryRunOrWarning, which refuses either header with the value true and any other value as the frames do. The router knows which routes read the headers, so the refusal is said once there and no frame repeats it. The generated router test (TestGeneratedDryRunAndWarning) sends both headers to every route in its table, the resources' routes and the ones beside them, and holds each to one side or the other; that a frame registered ahead of the refusal reads both headers is pinned on the generator's templates, and for SetFeature on its handler's test. The browser client sends the two headers only from a method's handle (dryRun, warning), to the method's own route. What stands outside the refusal serves no call: the files of a browser application and of the programs a release ships, and the redirect at the root. A route an application mounts beside the generated ones is its own, and takes the middleware by naming it.

The warning is no permission check and no second gate on the route: a script that holds the grant calls the method without asking. It is what stands between a person and a click, which is why the generator makes it the method's own and no page's: every page that runs the method, the library's and a hand-written one's through openMethodDialog, draws the same warning. The generated authorization matrix carries a denied case under X-Warning for every method that declares one.

Two things a method deliberately cannot do. It cannot reach the response writer: no cookies, no session started or ended, no header of its own. Its status is chosen through @answers and the result's HTTPStatus(), never written directly, so a declared 4xx still travels as a typed body with the transaction rolled back. A method whose Execute returns only an error has no result to choose with, so the one status it may declare is @answers(204), and the frame writes No Content where the empty 200 would go; the response encoder has no status setter to reach for. The moment a body can write the response, every method can start a session, and the frame's guarantee — JSON in, JSON out, permission-gated, transactional — stops meaning anything; sign-up flows that end in a login belong beside the login routes in the auth package. And it cannot be armed by default: inside Execute, typed queries and patches run trusted unless the body calls Enforce(caller), because @state columns are structurally unwritable from the wire and the frame's own status stamp must stay privileged. The method's entry contract with the permission system is Execute on itself, its target row, its transition, and any row condition on the Execute grant, all visible in the collection.

A body may ask the caller's grant on another method, where one act is made of another's: resource.CallerFrom(ctx).ExecuteGate(ctx, method, request) answers the decision the other method's own decode would reach for the request the body builds, in the scope the request was checked in. No grant is the frame's refusal (403). A condition on the grant that reads the request's fields (new.<name>) is settled against the request handed, and ExecuteGate.Settled says whether that decided it. What is left reads the other method's target row: EnforceView judges a row the database holds, and EnforceProposed the values of a row the body proposes where the database holds none, by the condition language's own evaluator. A condition that reads an attribute the proposed row does not carry is an error, never a pass. The generated user management asks this way what a change to a group needs (section 21), and which roles may be the default role of a sign-in method opened to sign-up.

A computed resource's functions are asked as the caller too. Its generated frames stamp the caller the request was checked as (qSet.Caller(): the checker, the scope and the environment of the query's own check) into the context before the List function, the Read function or the function that renders a file runs, as a method's frame does before Execute. So resource.CallerFrom(ctx) answers the same person in a list as in a method, and a list whose rows depend on what the caller may do elsewhere asks it there: the generated list of the roles an open method's default role is picked from lists the roles the caller may give through the method that gives a role, so a picker offers what the method it feeds would accept. Within a request served by a generated frame of a method or of a computed resource there is always a caller. No caller means a call the application makes outside any request (its bootstrap, a job, a hook of the sign-in) or one of the acts a generated route does in the application's name, such as seating the person who creates a tenant; the user management reads it that way and judges nothing there (section 21). A handler written by hand that runs code which asks who the caller is stamps one itself (resource.WithCaller).

8. The generated router

GenerateRoutes emits the route tables: one generated<Outlet>Routes function and Generated<Outlet>Handlers interface per outlet, plus NewTestRouter, which serves them bare for test composition. What sits in front of them in production is the router, and generation.GenerateRouter() emits that too, beside the tables in the same package: zz_gen_router.go and its proof, zz_gen_router_test.go. Without the option the contract is unchanged: generated route tables plus a hand-written router.

What the program declares. Two facts per outlet that the generator cannot derive. The auth behind a session outlet, generation.Auth(importPath, methods...): the auth package (the package exporting Name) and the sign-in methods its session.Auth registers, in the order the login page offers them: PasswordMethod(), and each external method under its registration name, GoogleMethod("google"), AzureMethod("lakeside-entra"), WorkOSMethod("sso"), OIDCMethod("okta"), PersonaMethod("persona"), with .Labeled(text) for the label the page shows (the method's own name otherwise: Password, Google, Microsoft, Single sign-on, Persona; for an OIDCMethod, the registration name with each word capitalized, Okta). OIDCMethod is one organization's identity provider, registered with the session library's generic OpenID Connect method (oidc.SignIn), a provider known by its issuer alone such as Okta or Keycloak: it takes .SyncsRoles() (the registration reconciles roles to the ID token's roles claim). A persona method is optional at run time: the router mounts its login and callback and the methods route offers it only where the auth's handlers are non-nil (the method is registered where the persona provider is configured, the test environments), so the same build offers it nowhere else; it does not take .SyncsRoles(). No method declares who it admits with no invitation: each starts invite only, and an administrator opens one to sign-up, or makes it invite only again, in the running application (section 21, "Who may sign up"). An outlet naming no method, a registration name outside [a-z][a-z0-9-]*, an external method named password, a name declared twice or an empty label is refused. A machine outlet declares generation.Tokens(importPath) instead, naming the auth package of a session outlet whose Auth issues the bearer tokens its requests carry (machine outlets, below). And the browser application an outlet serves, when it serves one: generation.WebApp(mountPath), "/" for the application at the root, "/console" for one under a path. The default outlet declares them on GenerateRoutes, the others on WithRouterOutlet. A session Auth makes the outlet serve sessions exactly as ServesSessions() does; ServesSessions() stays for applications that keep a hand-written router. Lodestar's program:

generation.GenerateRouter(),
generation.GenerateRoutes("pkg/router", "api",
	generation.Auth("github.com/impulseframework/impulse/lodestar/pkg/auth/crew", generation.PasswordMethod(), generation.GoogleMethod("google")),
	generation.Manages("github.com/impulseframework/impulse/lodestar/pkg/auth/members"),
	generation.WebApp("/console"),
),
generation.WithRouterOutlet("droids", "droids", generation.Tokens("github.com/impulseframework/impulse/lodestar/pkg/auth/crew")),
generation.WithRouterOutlet("portal", "portal/api",
	generation.Auth("github.com/impulseframework/impulse/lodestar/pkg/auth/members", generation.GoogleMethod("directory").Labeled("Company directory").SyncsRoles()),
	generation.WebApp("/portal"),
),

A registration's .SyncsRoles() and an outlet's Manages(importPath) shape the Auth's generated management (section 21): whose roles a directory writes, and which other Auth's people the outlet manages. A registration declaring .SyncsRoles() stands alone on its Auth: the directory is then the authority for everyone the Auth holds, and a second method beside it is refused.

Under GenerateRouter every outlet says how it authenticates, one way: an outlet with neither Auth nor Tokens, or with both, fails generation, as do a machine outlet with a WebApp, a machine outlet whose Tokens names an auth no session outlet declares with Auth, the retired APIKey() (the refusal names Tokens as its replacement), two outlets on one mount path, and a browser application mounted under an API prefix. Without the option the three declarations are refused rather than ignored.

A browser application at "/" must be the only one. An installed browser application's scope is every URL under its start, so beside a second application one at / would own the origin: the application under a prefix would never get its own install prompt, and its notifications and links would be attributed to the one at /. Generation refuses WebApp("/") declared beside any other WebApp, naming both outlets; one application at / with no other stays valid and is then the catch-all. With several applications none is mounted at /, and the router answers GET / alone with a temporary redirect to the default outlet's application, its mount path with a trailing slash (/console/), or to the first declared outlet's that serves one when the default outlet serves none. Nothing else changes at the root: every other unmatched path is 404.

The generated file holds four things, in this order. The chain comment opens it as the package documentation: every outlet's middleware in order, outermost first, one line per group, each chain followed by what it stands in front of. It is the review surface: what sits in front of every REST handler, readable without the code beneath it. Handlers is the full surface the router needs: the generated handlers of every outlet; each session outlet's session surface as an interface the generator writes for it, <Outlet>Session: the Auth's middleware and session routes, Methods, the pending sign-in's three handlers, and each declared method's handlers under its registration name (PasswordLogin; GoogleLogin and GoogleCallback for a method named google; LakesideEntraLogout too for an Azure one), the default outlet's embedded (DefaultSession) and each additional one's through a getter named after it (Portal() PortalSession); BindAuth(name) only when more than one session auth is declared, so a misspelled or removed auth package is a compile error at BindAuth(crew.Name); <Outlet>Tokens per machine outlet (Droids() DroidsTokens, embedded as DefaultTokens for a default machine outlet), the token check the issuing auth's *session.MachineOutlet satisfies, and on the issuing auth's session surface the device and token handlers (DeviceAuthorize, DeviceToken, DeviceLookup, DeviceApprove, DeviceDeny, TokensList, TokensCreate, TokensRevoke), which the auth's Device() and ApplicationTokens() return; LogExporter, where the request log goes, from which the router builds the request logger; SecurityHeaders, NoCaching, and CompressionMiddleware; and per WebApp a DeepLink and Assets pair, prefixed with the outlet's name for an additional outlet (PortalDeepLink, PortalAssets), which the application builds on resource.BrowserApp (section 17). Route-parameter capture (httpio.WithParams) is mounted by the router itself. Hooks is a struct, never a map, so an outlet added or removed surfaces as a compile error at every hook that names it:

type Hooks struct {
	// Outermost runs after tracing and ahead of the request logger on every request.
	Outermost []func(http.Handler) http.Handler
	// Root registers routes outside every outlet: health checks, webhooks, scheduler
	// triggers. They sit behind the every-request chain and nothing else.
	Root func(r chi.Router)
	// One field per outlet, named after it. The hook runs inside the outlet's
	// authenticated group (or the machine outlet's token-checked group): r already sits behind the outlet's
	// guards, and generated registers the outlet's generated routes, behind the
	// read-only mask the router mounts for them on a session outlet. Nil registers them
	// directly.
	Default func(r chi.Router, generated func(chi.Router))
	Portal  func(r chi.Router, generated func(chi.Router))
	Droids  func(r chi.Router, generated func(chi.Router))
}

Hooks compose inward only. A hook adds middleware and routes under the guards it is handed and chooses where inside its own group the generated routes register; it never sees the outer router, so no generated route can be lifted out from behind session validation or the XSRF guard. A hook must call generated exactly once; the router refuses one that does not, at construction. New(h Handlers, hooks Hooks) *chi.Mux is written linear and inline, the way a hand router reads: tracing, hooks.Outermost, the request logger, the security headers, and parameter capture; hooks.Root; one group per outlet, top to bottom; a not-found handler per outlet prefix, so an unknown API path is 404 and never a browser application's entry document; then the web apps, longer mount paths first, so an application at "/" is the catch-all; and, with several web apps, the root redirect.

A session outlet's group is BindAuth(<pkg>.Name) (with two session auths), NoCaching, CompressionMiddleware, StartSession, SetXSRFToken; the session routes under the prefix; then the authenticated sub-group, ValidateSession and ValidateXSRFToken around the hook and the generated routes. In that sub-group the routes a signed-in person calls on their own account (an invitation's acceptance, the address they add and verify, their tokens and device authorizations) stand in front of the hook: what a hook asks of a request, a tenant or a role say, gates the application's routes and never a person's own account. What must hold for every route the router registers there it mounts itself, wherever the hook registers the generated routes and whatever middleware it adds: the read-only mask of a session that views as someone else (EnforceReadOnlyMask) in front of the account routes and, behind the hook, in front of the generated routes, and each account route that writes refuses an impersonated session in its handler. A route the hook registers by hand carries what the hook gives it: an application that views as people mounts the mask on its own writes, and its route that ends a view in front of it. The session routes, every one under <prefix>/user/: GET user/methods, what the login page is told (session.Auth.Methods, handed the declared methods at the paths below, so the page and the router read one declaration); GET user/session and DELETE user/session; GET user/pending; and per external method under its registration name, GET user/<name>/login and GET user/<name>/callback (GET user/<name>/logout too for Azure, the directory's front-channel logout). The sign-in's POSTs sit behind the outlet's XSRF guard alone, as the session library wires them: POST user/password/login, POST user/password/change, POST user/password/remove, POST user/pending/confirm, POST user/pending/cancel, POST user/pending/code (mails the sign-in code to a sign-in that waits for the second factor), POST user/pending/code/verify and POST user/pending/email (the address a person who holds none gives for the code); a browser reaches them with the XSRF cookie its first request was issued, echoed in the header. The password change (PasswordChange, the password method's ChangeUserPassword) validates the session itself, so it sits outside ValidateSession: a person whose operator-set password must change before anything else is served reaches it, and the methods route tells the login page where (changePassword), which renders the change form before the signed-in page (section 21). The removal of a person's own password (PasswordRemove, the password method's RemoveUserPassword) is mounted beside it the same way, and the methods route names it as removePassword: where the person's account page posts the password as proof.

Machine outlets. A machine outlet declares the auth whose Auth issues its tokens, Tokens(importPath), the same *session.Auth a session outlet of the program binds to through Auth; its people issue the tokens there. The outlet's group is BindAuth (when several auths are declared), NoCaching, CompressionMiddleware, ReleaseHeader, the device flow's two public endpoints (POST <prefix>/oauth/device/authorize and POST <prefix>/oauth/token, RFC 8628 and the refresh grant, served by the issuing auth's DeviceAuthorize and DeviceToken), then the token check, <Outlet>Tokens().ValidateToken, the hook and the routes: no session handling and no XSRF guard. The check requires Authorization: Bearer <token>, answers a request without a live token of the outlet's with 401 and WWW-Authenticate: Bearer realm="<outlet>", and binds the request to the person the token acts for, so the handlers behind it run the same permission checks as the browser's. The issuing auth's session outlet gains the token routes behind its session and XSRF guards, GET and POST user/tokens, POST user/tokens/revoke, GET user/device, POST user/device/approve and POST user/device/deny: a signed-in person issues, lists and revokes their own application tokens (the secret is in the answer once) and approves or denies a command-line client's device authorization by the code it shows. The console carries those two pages from the client library: the token page, where the person issues, lists and revokes their tokens, which the library's frame serves in every place (Your API keys in the person's menu, <mount>/api-keys), and a device page at <mount>/device, where the link a program prints (/console/device?userCode=XXXX-XXXX) lands for approval; the issuing auth names the device page as its device verification path (session.WithDeviceVerificationURL("/console/device")), which the device authorization tells the client. The issuing outlet's generated descriptor carries a tokens block the pages configure themselves from, the routes above in the form of userDomainsRoute and the machine outlets the auth issues for, by name and mount path (outlets: [{ name: 'droids', prefix: '/droids' }]); an outlet whose auth issues none, and one that only manages the issuing auth, carry no block. The chain comment names the issuing auth per machine outlet and the generated test proves the check: no token and a token the auth never issued are challenged, a token opens the routes, and the device endpoints sit in front of the check. The application writes nothing for the check: the auth package registers the outlet on its Auth before the first request (session.RegisterMachineOutlet(auth, "droids"), beside its sign-in methods) and the Handlers getter returns it.

Shipped programs. A machine outlet serves the programs the release ships to their installed copies, which fetch their next release there with the token they already carry: generation.ShipsProgram("cmd/corral", generation.Platforms("linux/amd64")) beside Tokens, naming the program's main package by its root-relative directory (its name is the directory's base) and the platforms, each <os>/<arch>. The release file lists the programs on the outlet's entry ("programs": [{"name": "corral", "dir": "cmd/corral", "platforms": ["linux/amd64"]}]), from which the version build compiles each for its platforms and copies the files into the image beside the server, one per platform named corral-linux-amd64, in the directory APP_PROGRAMS names. The generated router mounts the handler of resource/shipped behind the token check at GET <prefix>/programs/<name>/<release>/<os>/<arch>, which answers the file with its SHA-256 in X-Program-Sha256, or 404 with one sentence saying why: the program or platform is not shipped, the release is not the server's (naming which it is, so a copy asks again for the release it read from X-Api-Version), the image carries no programs, or the file is missing. A copy follows the release every answer names through shipped.Follower: its Transport wraps the program's transport and keeps the newest release seen, Newer says when it is newer than the copy's own (shipped.OwnRelease: the release stamped at link time, else the module version a go install copy carries; a development copy never upgrades), and Upgrade fetches the file with the copy's token, writes it beside the running executable, verifies the checksum, keeps the running file as .old, renames the new file over the running path and returns the release; the program logs it and exits 0 for its service manager to start the new release. A session outlet declaring the option is refused, and the generated test proves the route sits behind the token check.

The auth in the route tables. Each session outlet's routes function binds the name of its auth to every request, for the live pages (section 14) and for the generated management's rules on a person acting on themselves: generatedRoutes opens with live.Subscribing(crew.Name), so the routes file imports every declared auth package, whether one auth is declared or several, and NewTestRouter binds the same names. Where the application writes its own router, the generator does not know the auths, so each session outlet's routes function takes the name as its last parameter, generatedRoutes(r, h, staff.Name), and NewTestRouter takes one per session outlet in outlet order, NewTestRouter(h, staff.Name); a router that passes none does not compile. A machine outlet binds none and registers no live routes: its resource routes refuse a request carrying X-Subscribe, and so do the default outlet's when it is declared Tokens(...).

Release versions. A browser application and the server each carry the release they were built from, and the server refuses an application it no longer answers. The application sends its release in X-Api-Version with every request. The server's is Handlers.ServerVersion(), which the application answers from its configuration's APP_VERSION (dev where no release built it), and the generator program declares how far back a session outlet answers with generation.OldestAnswered("1.5.0") on GenerateRoutes or WithRouterOutlet, or generation.OldestAnswered(generation.ThisRelease) for a release that changes the API inside a maintenance window, when only the server's own release is answered. Without the option every release that sends the header is answered. The check (resource.CheckAPIVersion) sits behind the outlet's guards and ahead of its hook, so it covers the generated routes and the hook's own: a request whose release is between the oldest answered and the server's, inclusive, is answered; any other is refused with 412 and X-Api-Version: <server release> before any handler runs and before its body is read. A request without the header is answered, so file links in <img> and <a>, navigations, curl, and bundles built before the header shipped keep working, and a version that is not a release on either side (dev, or anything that is not a semantic version) never refuses and is never refused. The session routes (login, callback, /user/session) sit outside the check, and the stored-file routes (@file) are exempt, so a login always works and a file link never fails on a version. A machine outlet is not checked, and refuses the option. Every response on a checked route carries Vary: X-Api-Version, so a browser never serves one release's cached answer to another. Every answer of an outlet, checked or not, names the server's release in X-Api-Version (resource.ReleaseHeader, ahead of the session handling on every outlet, the machine and scheduled outlets included), so the methods list a login page reads before any sign-in carries it, a browser application shows which release it talks to, and curl shows it; a dev server is named as it is. Versions compare as semantic versions, with or without a leading v. The chain comment names the check per outlet with its oldest answered release, and the generated test proves it: in range answered, below or above refused with the header and no handler run and no body read, no header and dev answered, session and file routes answered at any release, the machine outlets unchecked, and the refusal landing before the hook.

The release file. Beside the router the generator writes zz_gen_release.json, which names every outlet and, for each session outlet, the oldest release it answers, so a deploy tells from the checkout alone, without building or running the server, whether a release needs a maintenance window. It is written only when a router is generated, with the other generated files, and the sweep removes it when the router goes. One entry per outlet, keyed by the outlet's name (default for GenerateRoutes, the name given to WithRouterOutlet otherwise): a session outlet carries oldestAnswered, the release as declared ("1.5.0"), "this" for generation.ThisRelease, or "" when the option is absent and every release that sends the header is answered; a machine outlet carries "kind": "api-key" (the machine kind's name in the file) and no oldestAnswered, since it is never checked. Lodestar's, with no release declared on either session outlet:

{
  "outlets": {
    "default": {
      "oldestAnswered": ""
    },
    "droids": {
      "kind": "api-key"
    },
    "portal": {
      "oldestAnswered": ""
    }
  }
}

resource.ReadReleaseFile(dir) reads it from the router package's directory into a resource.ReleaseFile (Outlets by name, each a ReleaseOutlet with APIKey and OldestAnswered, "this" read back as resource.ThisRelease), refusing a file that is not this shape, so the deploy and the tests share one parser; the name is resource.ReleaseFileName. An application with scheduled methods (section 19) also finds them listed there, under scheduled, in path order: each route's path, its cron schedule and its timeZone, read into ReleaseFile.Scheduled; the key is absent when there are none. An application that declares request log words or trace settings (below, request logs and traces) also finds its surfaces listed there, under surfaces, in prefix order: each surface's prefix (/ for the application default, an outlet's prefix, a route's path, or a prefix mounted by hand), its kind (prefix for the application default, an outlet and a prefix mounted by hand, matched against the start of the path; route for an annotated method's path, matched to its end; a file written before the kind existed reads as prefixes), its log word (always, onEvent, sampled with its fraction, never) and its traces setting (followFrontEnd, capped with its rate, off), the words and the setting each present only where declared, read into ReleaseFile.Surfaces; bedrock renders the stack's own log exclusion from them, a route matched to the end of its path and a prefix by prefix.

The generated test drives every generated route through New with recording stubs and asserts the middleware each request passed through, in order, for its outlet; that each flavor's session routes answer behind the group and before the guards; that under every prefix an unknown path is 404 and nothing under one outlet's prefix reaches another outlet's group; that each browser application answers at its mount path through its deep-link rewrite; with several applications, that the root alone redirects to the default outlet's and an unmatched path is 404; and that the hooks sit where the chain comment says. The chain comment is proven, not stated. NewTestRouter and the route tests are unchanged, and the application's own hooks are the application's suite's to exercise.

Adopting it. Lodestar keeps one hand file in its router package, hooks.go: an AppHandlers interface (the generated Handlers plus its own routes) and an AppHooks(h AppHandlers) Hooks function, and main calls router.New(app, router.AppHooks(app)). An application whose router is exactly the base passes router.Hooks{}. The escape hatch stays: an application that needs something the shape cannot carry removes the option and hand-writes its router on the generated route tables, losing only the boilerplate and the generated chain test, and passes each session outlet's auth name to its routes function.

The generated authorization matrix. GenerateHandlerTests(dir) emits, beside the emulator bootstrap, a test that drives every generated route through NewTestRouter: without the required permission each must fail closed, and with exactly that permission a list or read must reach data access. The application hand-writes one function, newTestHandler, wiring its App to the scripted grants; Lodestar's is test/authz/harness_test.go. For domain-scoped routes newTestHandler adds the suite's tenant, the generated router's TestDomain constant (an id's text, as a tenant's key is one), to the test application's tenant roster with Add, since the empty schema holds no tenant row; under concealed domains a case with no grants has no foothold and is answered as if the domain did not exist. The scripted grants are unconditional and the schema is empty, so the matrix pins the endpoint gate alone: a granted case means the request passed the gate, never that a row is visible, and a conditional grant would pass the gate exactly as an unconditional one does. What a condition admits or refuses is proven by the application's integration suites over seeded rows and the real permission engine provisioned from its role files, as Lodestar's test/integration suites do.

Request body limits

Every request body the generated router serves is bounded, in one place, at a limit the application sets once. generation.WithBodyLimit(bytes) sets it; an application that sets none gets 4 MiB. The routes file declares it as the router package's BodyLimit, and a body over its limit answers 413 naming the limit, before the handler reads past it.

Two groups carry it. The resource routes, the consolidated patch route, the session routes, the scheduled routes and the other generated JSON routes register on a group the router wraps in resource.BodyLimit(BodyLimit). The upload, live and RPC routes register beside that group, not inside it, and bound their own bodies where they read them: an upload at its @upload(max:), a live route at its own constant, and an RPC method at its @rpc(max:) or, when it declares none, at BodyLimit, which its generated handler applies before decoding. They sit beside the group rather than inside it because a nested http.MaxBytesReader can only tighten the limit outside it: an upload inside the default group would be cut off at 4 MiB however large its declaration. The generated router test proves the split, sending every route a body one byte over BodyLimit and expecting the read refused on the bounded routes and intact on the self-bounded ones, so a hook that wrapped the body above the generated routes fails the test on the next generate.

The application's own routes under hooks.Root take the limit too; a route an outlet hook registers runs beside the generated routes with no limit of its own, and applies resource.BodyLimit itself if it reads a body. Lodestar sets 2 MiB (generator.go) and declares a 64 KB limit on IssueBulletin.

Request logs and traces

An application declares, per surface, what a request writes to the log and how its spans are sampled, and the generated router applies the declarations as a request descends. An application that declares nothing keeps today's behavior: every request writes its entry, and its spans follow the front end.

The words. A request log word says when the request's entry is written, decided by the root's request logger when the request ends: generation.LogAlways() writes every entry; generation.LogOnEvent() writes it when any line attached or the status is 400 or above; generation.LogSampled(fraction) is on event plus a per-request draw at the fraction, between 0 and 1; generation.LogNever() writes nothing. Each takes .MinSeverity(logging.Warning) to drop the lines below a floor before they attach. A trace setting says how the request's spans are sampled, applied by the tracer as the span starts, since a span's sampled flag is fixed then: generation.TracesFollowFrontEnd() is today's behavior, the front end's decision carried in the trace header; generation.TracesCapped(rate) is that and a cap at the rate, decided by the trace ID so one trace is kept or dropped the same way wherever it is capped at the rate; generation.TracesOff() records nothing. On an annotation the words are log: always, log: onEvent, log: sampled with fraction: 0.01, log: never, and the settings trace: followFrontEnd, trace: capped with rate: 0.1, trace: off.

Where they are declared. generation.WithRequestLog(word) sets the application default, the word every request starts with. generation.OutletRequestLog(word) and generation.OutletTraces(setting) are outlet options on GenerateRoutes and WithRouterOutlet: the outlet's word is set on its group, and on its not-found handler, so an unknown path under the prefix is logged as its requests are. @rpc(log: onEvent), @rpc(trace: off), the same two on @file, and @schedule(log: onEvent) are a route's own, set ahead of its handler in the routes file with logger.WithPolicy. A prefix the application mounts by hand, through hooks.Root or an outlet's hook, is declared with generation.WithMountedRoutes(prefix, word, setting), so the router, the tracer and the release file learn it from one place; a prefix at or under /_scheduled, or equal to an outlet's, is refused, since those are the router's own. The nearest declaration wins: a route's over its outlet's, an outlet's over the application default, and a prefix mounted by hand beneath an outlet keeps its own word under the outlet's. A handler may change its own request at run time through logger.FromReq(r).SetPolicy(word). Every one of these needs GenerateRouter, which builds the request logger and the tracer with them; a hand-written router passes logger.DefaultPolicy and logger.PolicyByPrefix to logger.NewRequestLogger itself.

What the router renders. The root's request logger takes logger.DefaultPolicy with the application default and, with any prefix mounted by hand, logger.PolicyByPrefix with the prefixes, longest first; the tracer's handler takes tracer.Surfaces with every surface that declares a trace setting, by the pattern it is mounted at, where {segment} matches one path segment and the longest pattern wins; each outlet group that declares a word starts with logger.WithPolicy, and with prefixes mounted by hand beneath it with a generated outletRequestLog that excepts them. The chain comment names the word and the setting at each place, and the generated router test proves them with the logger's console exporter deciding each request's entry: the application default on a root route, quiet and failed; an outlet's word inside its group, and an outlet without one taking the default; a route's own word on the generated route; a prefix mounted by hand keeping its word; and a handler setting its own request's word. The release file lists every declared surface under surfaces (above). Lodestar declares one quiet surface, the beacon pulses under /beacons/ on event with traces off, and IngestDroidReports on event (generator.go, ingest_droid_reports.go), and request_log_test.go reads the console exporter's decisions on the served stack.

9. Indexes for the shapes the package injects

Tenancy, grant conditions, subject sets and values, the visible projection, and the write checks all land inside the application's queries. Measured on a real Spanner instance at half a million rows (lodestar/perf/REPORT.md), they need this much from the schema:

  • A resource with a bare @domain column that is listed at volume wants an index on the tenant key followed by its @order columns. Spanner's foreign-key backing index on the tenant column alone drives the list, but every page then sorts the whole partition; the composite index reads the page's rows and nothing else (52 rows against 20,060 at 10,000 rows per tenant). Generation warns at every run for a listed resource in this shape whose table has no index leading with the tenant column and then the @order columns, in order and direction, and names the CREATE INDEX it wants; the primary key is not named because Spanner appends it to every secondary index. A resource with no @order is silent: its sort-less list is not sorted, and the backing index on the tenant column serves it. So is a resource whose table a unique index on the tenant column alone holds to one row for a tenant (a tenant's directory, for one): one row has nothing to sort.
  • A nullable @order column renders as the plain direction with no stated NULL placement, so the same composite index serves it. Each database keeps its own placement (Spanner sorts NULL first ascending and last descending, PostgreSQL the reverse) and the keyset cursor follows it across the NULL boundary; a cursor is read by the database that issued it.
  • A filter seeks the same way. A filter on a column that leads an index, or that follows the tenant column in one on a bare @domain resource, reads the index from that prefix, and those are the columns the generated list struct tags index:"true" (section 3); a filter on any other column alone is refused at decode rather than scanned, and allow_filter admits one beside an indexed field. A global request carries no partition predicate, so for it the tenant-second seek is an index scan, the same cost class as its ordered list, which already sorts the whole table.
  • A resource with join-path tenancy, @domain(via: ...), is scanned whole when listed: every row of the table, all tenants, with a lookup per row up the path. No index on the child changes that, because no column on the child names the tenant. Join paths suit writes and small or parent-scoped tables; a table listed at volume carries its tenant key on the row. Generation warns at every run for every listed join-path resource, so the application decides knowingly. The warnings are informational, never a refusal, and the generator returns them through Generator.Warnings(); an application's generate program prints them after a successful run, one per line as Warning: <text>, as Lodestar's does. The same program, run with -audit, prints the audit pass's findings after them as Audit: <text> (section 13): advisory findings a normal generation never prints.
  • A list across tenants (@listAcrossTenants, section 4) is not served by the index the tenant's own list wants. That index leads with the tenant column, and a list over several tenants has no one tenant to seek to: its statement filters the tenant column against a bound array and orders by the @order columns across every tenant of the set. It wants an index of its own that leads with the @order columns, in order and direction, and carries the tenant column, later in its key or in STORING, so the page is read in order and the filter on the tenant is answered from the index before a row is read; without it every page reads and sorts the rows of every tenant the caller reaches. Generation warns at every run for a declared table-backed resource with a bare @domain column and an @order whose table has no such index, naming the CREATE INDEX ... STORING (<tenant column>) it wants; a tenant column in the primary key rides every index and needs no STORING. A declared resource with no @order lists by primary key, which the table serves, and is silent; one bound through a join path carries the join-path warning above. This shape is reasoned from the statement and is not in the measured study the other bullets cite: the measure at volume is still to be taken. A set of one tenant is the tenant's own list and uses the tenant's index.
  • A search (section 4) reads the table's one search index: CREATE SEARCH INDEX ClientsSearch ON Clients(Name_Search, ContactEmail_Search), over hidden TOKENLIST columns generated by TOKENIZE_SUBSTRING. A tenant-scoped resource partitions it, PARTITION BY SectorId, so a search reads one tenant's tokens; generation refuses a partition by any other column and warns at every run for a tenant-scoped resource whose search index is unpartitioned. A @searchAlso child's index stores the foreign key the branch joins through, STORING (ClientId), or generation warns that every matching child row is read back for its key. A case-folded startswith alone needs no search index: a stored LOWER(Name) column second in the tenant's index, CREATE INDEX HangarsBySectorIdNameLower ON Hangars(SectorId, Name_Lower), serves it as a seek. A box over several indexes runs one key set per term, each a search-index read, and the box's limits (8 terms, 64 characters each, 200 in all) bound the statement.
  • Subject-set conditions are key lookups per row against the anchor (its key leads with the compared column and the user), so their cost is the partition's size per page, not the anchor's. Subject values are one row through the unique index generation requires. On a computed resource each fact a condition names is read once per request and the rows are judged in memory. A subject set's read selects the caller's anchor rows by the user column (in the request's tenant where the anchor is partitioned), so it is a seek where the anchor's key or an index leads with the user and a scan of the anchor, once per request, where none does: an anchor a computed resource's conditions read at volume carries an index by user.
  • A subject set's lookup wants an index on the set's table that leads with the tenant column (where the row carries one), the column that ties the row to the requester, and the value the set yields, in any order: the lookup binds each by equality. A set whose who: names several columns is one lookup for each, so it wants one index for each. Generation warns at every run for each column no index serves, naming the statement (SubjectSetIndexWarning: CREATE INDEX HangarPassesBySectorIdSquadronIdHangarId ON HangarPasses(SectorId, SquadronId, HangarId)). The primary key counts, and so does a secondary index with the key columns Spanner appends to it; a null-filtered index and a search index do not. It is a warning as the tenant list's is, accepted the way the others are: a small table needs no index. A where: adds no lookup of its own; it filters the rows the lookup finds.
  • A sort on a conditionally visible column runs over CASE WHEN <condition> THEN column END, which no index serves: the page sorts the partition. The CASE is dropped when the field's condition covers the whole row predicate (a role whose every grant on the resource carries the one condition, or a condition that implies it: an equality inside the field's IN list prunes too), and a field declared masking:"positional" never renders one; access.MigrateRoles warns, per role, where a concealing sort or filter key keeps its CASE. Lists that page at volume sort on unconditionally visible columns, on positional ones, or on columns whose condition the row filter proves.
  • Write and insert checks are point lookups at any volume.
  • After a bulk load, ANALYZE; Spanner otherwise refreshes statistics about every three days, and a plan can flip with them.

10. Refused commits

Spanner checks foreign keys, interleaved parents, NOT NULL, column lengths, primary and unique keys, and CHECK constraints for buffered mutations when the transaction commits, so a write the schema refuses surfaces from the commit, not from the patch that caused it. SpannerClient.ExecuteFunc answers such a commit with a 4xx and a message the library composes itself. The translation keys on the gRPC code alone, never on the message text, which differs between the emulator and the service and is not documented. The message names only the resources whose patches the transaction buffered, in the order they were buffered, and never the referencing table, the constraint, the index, the key, the value, or a count:

gRPC code The transaction buffered Status Message
FailedPrecondition (a delete of a row other rows still reference through a foreign key without ON DELETE CASCADE or as an interleaved parent under ON DELETE NO ACTION; a write whose foreign key names a row that does not exist; a required column left empty; a string longer than its column's declared length) Deletes on one resource 409 Hangars: this record cannot be deleted while other records still reference it.
Deletes on several resources 409 Hangars, Ships: a record cannot be deleted while other records still reference it.
Creates or updates only 409 Ships: a referenced record does not exist, or a value is too long for its field.
Deletes and writes together, or nothing buffered through the transaction wrapper 409 The request could not be applied: a deleted record is still referenced, or a referenced record does not exist.
AlreadyExists (a duplicate primary key; a duplicate unique-index value) Any create 409 Ships: a record with this key or a unique value already exists.
Updates only 409 Clients: a unique value already exists on another record.
Nothing buffered 409 The request could not be applied: a record with this key or a unique value already exists.
OutOfRange (a violated CHECK constraint) Any write 400 Missions: a value is outside the range the record allows.
Nothing buffered 400 The request could not be applied: a value is outside the range the record allows.
NotFound (an update of a row that does not exist; an interleaved child whose parent does not exist) Updates only 404 Clients: this record does not exist.
Any create 409 RefitTasks: a referenced record does not exist.
Nothing buffered 409 The request could not be applied: a record to update does not exist, or a referenced record does not exist.
anything else (InvalidArgument, Internal, Aborted, …) 500 passes through unchanged

"Create" is a create or a create-or-update; a touch is an update. Deletes cannot cause any code but FailedPrecondition, so deletes buffered beside writes do not change the other codes' sentences. A tracked resource's change-event rows do not count among the buffered patches. An error the transaction function itself returns passes through unchanged, whatever its code.

What the library does not do: it reads nothing before buffering to name the offending field. A read inside the transaction does not see the transaction's own buffered writes, so two creates sharing a value in one batch would pass such a check and fail at commit anyway, and concurrent requests would race past it; the commit translation is needed regardless. The application's validators (@validateCreateType, @validateUpdateType) are where a rule is answered as 400 naming the field before anything is buffered; the commit translation is the backstop for what they do not cover. A value the decoder can size never reaches the commit through the API: a string longer than its STRING(n) column, a byte slice longer than its BYTES(n) column, and a decimal beyond NUMERIC's digits answer 400 naming the field at decode (section 11). The 409 for a too-long string remains for STRING(MAX), whose ceiling the decoder does not check, and for application code that drives the patch layer directly.

Two consequences to know:

  • A unique index is global across tenants. The 409 for a duplicate unique value confirms that the value exists somewhere, in any tenant; that is the schema's choice in declaring the index, not the message's, which names no tenant, row, or value.
  • NotFound is also Spanner's code for an unknown column or table. A deployment whose schema disagrees with the generated code answers 404 or 409 with Spanner's text in the server log instead of 500. A schema mismatch fails every write that touches the column, so it does not hide behind one request.

The tenancy check's 404 for a referenced row outside the request's partition, and the 404 a tenanted or tracked update answers when its row is missing, are unchanged; they run before the commit, so the same request answers 404 whatever the resource's shape. A request that deletes children and their parent in one transaction still succeeds in either order, because nothing is checked before the commit.

11. Value limits from the schema

A value the column cannot hold answers 400 naming the field when the request is decoded, before anything is buffered and before any permission check. The generator carries each sized column's declared type onto the patch request structs as sqltype:"…" (section 3), the runtime derives the rule from it when the handler's Set is constructed, and the decoder applies it after the per-field refusals (an unknown field, an immutable field on update, a null into a field whose column is NOT NULL: a value with no null form, or a slice without the nullable:"true" tag) and before the application validator. A limit is a fact about the wire value alone, the same class as cannot be null; naming it before the permission check discloses schema shape the metadata already publishes, nothing about rows.

The tag is written exactly where the field's Go type and the column type together have a rule:

Go type Column type Rule
string, a named string type, *string, spanner.NullString STRING(n) at most n code points (utf8.RuneCountInString); Spanner counts code points, so a combining mark counts and a CJK character counts once
[]byte BYTES(n) at most n bytes
a field declared conditions:"secret" (resource.Secret on the resource, text on the request) BYTES(n) at most n − 42 bytes of text, the 42 being what sealing adds (section 23). The rule is the secret's alone: a string-kinded field that is not declared a secret takes no rule from a BYTES(n) column (a named string type that encodes itself to bytes is sized by its own encoding, which the decoder does not know), so it carries no tag and is not sized
decimal.Decimal, *decimal.Decimal, decimal.NullDecimal, spanner.NullNumeric NUMERIC trailing zeros trimmed, then at most 29 digits before the decimal point and 9 after (GoogleSQL NUMERIC is 38 digits of precision with 9 of scale); 1.1234567890 is accepted, 1.1234567891 is not
a slice of a checked type, named or not ([]string, type Marks []string, []decimal.Decimal) ARRAY<…> of the matching type each element by its rule

No tag, and no check, on STRING(MAX) and BYTES(MAX) (Spanner's ceiling of 2,621,440 characters stays a 409 at commit, section 10); on impulse.UUID and impulse.NullUUID, whose unmarshal fixes the shape; on INT64, FLOAT64, BOOL, DATE, TIMESTAMP, and JSON columns; on keys and output-only fields, which the patch wire never carries; on @virtual fields (a view has no schema types; an @rowsOf write lands on the table resource, which is tagged); and on @computed and @rpc structs, which have no schema. A null in a nullable wrapper, or in a slice whose column allows NULL, passes: there is nothing to size. Application code that drives PatchSet.Set directly is trusted and keeps the commit backstop.

One message names every offending field the request carried, in struct-field order, joined with ; , so a form fixes everything in one round trip. Field names are the JSON names:

  • name is limited to 64 characters
  • codes: each value is limited to 4 characters
  • blob is limited to 4 bytes
  • fee is limited to 29 digits before the decimal point and 9 after

A PATCH checks only the fields it carries. The consolidated handler decodes each operation through the same function.

The tag follows the Go type and the column alone: a type's name changes nothing, and a @typescript declaration on the type (section 1) changes the interface, never the limit.

The TypeScript field metadata carries the character limit as maxLength for the string-kinded pairs (STRING(n), and per element for ARRAY<STRING(n)>) on the fields whose display type is string, string[], or enumerated (a picker's key is a string the column sizes), so a form control refuses before sending; nothing is emitted for bytes or NUMERIC. A field typed by a declaration importing a name (@typescript(Name, from: "module") over a named string or a named slice on a sized column) has display type object: it carries the tag, since the decoder sizes the column's value, and no maxLength, since the interface type is not a string and a form would count the wrong thing. JavaScript measures a string in UTF-16 units, so a form refuses a little early on astral characters and never accepts what the server refuses. The framework-neutral client does not pre-check a string: the server stays the single authority. Example: Ship.Registry on STRING(16), and Mission.Fee on NUMERIC.

12. TypeScript types for columns

A field's TypeScript type comes from its Go type alone, and a field whose type reaches no TypeScript type fails generation naming the resource, the field, the Go type, and the fix. Nothing falls back to string. The same rule types a table column, a view column, a computed field, and an RPC field, so one Go type is one TypeScript type wherever it appears.

How a type resolves. After aliases are read through (type NullKindID = impulse.NullEnum[KindID] is read as the NullEnum), and one pointer is read through (a pointer column is nullable, as before; a pointer to a slice is refused, below), the generator tries, in order:

  1. the built-in table, by the type's qualified name;
  2. a generic row, by the type's origin: impulse.NullEnum[T] is T's type;
  3. a @typescript declaration on the type's declaration (section 1);
  4. the type a defined type is declared over, when that type writes its own JSON: type Payload json.RawMessage is JSON by declaration and resolves as json.RawMessage does (below);
  5. a basic type, or a named type over one, by the basic type's row (type KindID string is string);
  6. a byte slice: an unnamed []byte, or a named slice over byte with no JSON methods, is the bytes leaf (below).

A field that resolves here is a leaf. A field that does not is read once more as a list: one slice level is stripped from a []T, an array, or a named slice type (type Attachments []Attachment is Attachment[]), and the element resolves by the same steps. An element that is a struct with no declaration is derived (below). Anything else is refused:

  • Ships.Manifest: resources.Manifest has no TypeScript type; declare the type's TypeScript form with @typescript(Name, from: "module") on its declaration, or use a struct for a derived interface

Every offending field in a run is reported together.

The built-in table. string, bool, and the numeric types by their names; impulse.UUID and impulse.NullUUID (uuid, a string in the interface); decimal.Decimal and decimal.NullDecimal (number); time.Time (Date); civil.Date (civilDate, a Date in the interface); the Spanner Null wrappers (spanner.NullString is string, NullInt64, NullFloat32, NullFloat64, and NullNumeric are number, NullBool is boolean, NullTime is Date, NullDate is civilDate); securehash.Hash (string, its text form); and spanner.NullJSON and json.RawMessage (unknown, a value with no fixed shape, display type object; the two share one wire form, any JSON value or null, and neither can carry a @typescript declaration). unknown passes @typescript-eslint/no-explicit-any, which rejects any alone, and the generated files are lint-ignored in every web application besides. Nullability keeps coming from the schema, so a nullable spanner.NullBool column renders nullboolean exactly as *bool does. A json.RawMessage is pass-through: a nil one marshals as null, and bytes that are not valid JSON fail encoding/json at response time, the application's own responsibility. Declare a type whenever a TypeScript type exists for the value (below); json.RawMessage is for the value the application does not model.

json.RawMessage on a Spanner column is refused. The Spanner client types a named byte slice as BYTES, so a read of a JSON column through it fails with a type mismatch at the first row and a write sends BYTES to a JSON column, and the client's one hook, the EncodeSpanner and DecodeSpanner pair, is one a standard-library type cannot take. A table or view column typed json.RawMessage, a pointer to it, or a slice of it fails generation naming the two spellings that work, and no @typescript clause, since none can apply; a computed field and an RPC field carry the type as unknown without restriction. The refusal is lifted when the client reads and writes the type on JSON columns (googleapis/google-cloud-go#10720, the open request it cites):

  • Shipments.Payload: the Spanner client stores json.RawMessage as BYTES, so a JSON column cannot be read or written through it (googleapis/google-cloud-go#10720); type the column spanner.NullJSON, or declare a type over json.RawMessage with @typescript(...), whose JSON and Spanner methods the generator writes

The database/sql Null wrappers are refused. A field typed sql.NullString, sql.NullInt64, any of their six siblings, the generic sql.Null[T], or a pointer to one fails generation on every path (a table or view column, a computed field, an RPC request or result field). None of them writes its own JSON, so encoding/json carries the wrapper as {"Int64":7,"Valid":true} where the interface would promise number, refuses a bare 7 into it, and reads null as the zero value silently; the field lies in both directions. The pointer to the value (*int64) carries null on the wire and through the patch decoder, and is what every adopter writes, so the refusal names it. The rule is keyed on the package and the Null prefix, so a wrapper Go adds later is refused too; the Spanner wrappers, impulse.NullUUID, impulse.NullEnum[T], and decimal.NullDecimal keep their rows, since each writes the value or null through its own JSON methods. A standard-library type cannot carry a @typescript declaration, so the message offers none:

  • Ships.Count: sql.NullInt64 has no JSON form of its own (encoding/json writes it as {Int64, Valid}); type a nullable column with the pointer *int64

Byte slices. A []byte is one leaf, never a list of numbers, because that is what the wire carries: encoding/json writes a byte slice as a base64 string and a nil one as null, and reads a base64 string back. The field is string in the interface and bytes in the metadata, on every path (a table or view column, a computed field, an RPC request or result field), so a browser knows the value is not text: a grid shows its size or offers a download rather than the base64, and a form draws no free-text control for it (a typed word fails the server's base64 decode with a 400). The line is the one the value limits draw (section 11): an unnamed []byte, a named slice type over byte (type Digest []byte) with no JSON methods, and, on an RPC or computed field, a pointer to either (on a table or view column a pointer to a slice is refused, below); a [][]byte (an ARRAY<BYTES> column) is string[] with display type bytes[]. Not on it: a byte array ([N]byte stays number[], since encoding/json writes an array as an array), a named type carrying @typescript (it keeps what it declares; a declaration promising anything but string on a plain byte slice with no JSON methods is refused, naming the two ways to carry JSON: declare the type over json.RawMessage, or write its MarshalJSON and UnmarshalJSON), one writing its own JSON, and json.RawMessage and the types declared over it, which write JSON, not base64 (the unknown row above, and JSON by declaration below). maxLength is never emitted for bytes (section 11); a byte limit can ride the bytes type later.

JSON by declaration. A defined type inherits none of the methods of the type it is declared over, so type Payload json.RawMessage would marshal as its underlying byte slice, base64 where json.RawMessage writes JSON. The generator reads the declaration's right-hand side and gives the pair back: a defined type a field uses on any path (a table or view column, a computed field, an RPC request or result field, and the fields of every struct those reach) whose right-hand side is a type with JSON methods, and which has none of its own, gets MarshalJSON (value receiver) and UnmarshalJSON (pointer receiver) converting to and from the right-hand side, generated into zz_gen_json.go in the type's package. Such a type is JSON by declaration: with a @typescript declaration it is typed as declared, and without one it resolves as the type it is declared over does (json.RawMessage to unknown, time.Time to Date), never bytes. The whole declaration is two lines:

// @typescript(Point, from: "geojson")
type Position json.RawMessage

A type with hand-written JSON methods keeps them; one method without the other is refused. A right-hand side without JSON methods (a plain struct, a basic type) gets no pair, and the type marshals as before. Declare a type whenever a TypeScript type exists for the value; json.RawMessage itself is pass-through for the value the application does not model. Example: Position, whose two hand-written methods the generated pair replaced.

Nullable slices. A slice-typed column takes its nullability from the schema, since a Go slice has one form: the Spanner client reads a NULL BYTES or ARRAY<T> column into a nil slice and writes a nil slice as NULL, and encoding/json carries nil as null. So []byte types a nullable BYTES(n) column and a NOT NULL one alike, []int64 an ARRAY<INT64> either way, and the nullability check (section 2) leaves slice fields out. The generated metadata says required: false for the nullable column and required: true for the NOT NULL one without a default; the patch request struct carries nullable:"true" on the nullable one (section 3), so a null in a PATCH clears the column, while a null into the NOT NULL one answers cannot be null at decode. A pointer to a slice is refused on a table or view column, naming the plain slice: the client decodes through one pointer and no more, so *[]string fails on the column's first read, NULL or not, and the message quotes the client's own words for the column's type (a view has no schema type, so there the quote is left out):

  • Squadrons.Callsigns: *[]string cannot be read by the Spanner client (type **[]string cannot be used for decoding ARRAY[STRING]); type the column with the plain slice []string, which reads NULL as nil

Element nullability is not carried: an ARRAY<INT64> row holding a NULL element fails at read into a []int64. Example: Squadron.Callsigns, an ARRAY<STRING(16)> column that is NULL until the marshal files the squadron's callsigns and [] for a squadron that flies silent.

The display-type vocabulary. Beside its interface type, every field carries a display type in the generated metadata (FieldMeta.displayType, RPCFieldMeta.displayType): the name a browser chooses a control and a cell renderer by. The vocabulary is one closed set for a table column, a view column, a computed field, and an RPC field, and a leaf's display type is its own name on every path, so a computed impulse.UUID field is uuid as a column of the same type is, and a computed civil.Date field civildate. The generator holds the set as typed constants (generation/displaytype.go), renders every display type through one function that refuses anything outside it, and a unit test asserts that what the three paths emit is exactly this list; @impulseframework/resource lists the same members in ValidDisplayTypes, spelled the same, so an adopter's build passes by construction and never checks the generator's output.

Display type In the interface Emitted for
string string text columns and fields, named string types, securehash.Hash
number number integers, floats, and decimals
boolean boolean a bool column that is NOT NULL, and every bool field on the other paths
nullboolean NullBoolean a nullable BOOL column (*bool, spanner.NullBool); the tri-state rule for one column
date Date time.Time, spanner.NullTime
civildate Date civil.Date, spanner.NullDate
uuid string impulse.UUID, impulse.NullUUID
enumerated the key's type a declared or inferred picker (@enumerate, a key into a resource or an enumeration table)
object the derived or imported interface, or unknown a struct, a @typescript type, spanner.NullJSON, json.RawMessage and a type declared over it
bytes string a byte slice, base64 on the wire
string[], number[], boolean[], date[], civildate[], uuid[], object[], bytes[] the element's interface type with [] a slice, an array, or a named slice type of the leaf (an ARRAY<...> column); element pointers are read through, so []*int64 is number[] and a nullable []*bool is boolean[]

Never nullboolean[] (the tri-state rule is for one nullable BOOL column). enumerated[] is a method's request field alone: a list field of an @rpc struct that carries @enumerate holds several picked keys (the roles a new user is given), and a form draws it as a picker of several. A picker of several shows every row of its source with a mark beside each chosen one, so it reads the source whole: a source with a @page maximum fails generation, naming the maximum to drop. A column stores one key, so a list field of a table, a view or a computed resource still refuses @enumerate. A list is one value to the query surface: allow_filter, index, and uniqueindex on a list field are refused at generation (section 2), and a sort naming one answers 400, since Spanner has no array equality and cannot index an ARRAY column. The Angular library renders the scalars; an array falls to its text control until it gains a list renderer.

Derived structs. A struct a column holds is its own TypeScript interface, derived from its fields with no annotation and no option, declared in the resource's namespace (MissionDocuments.Provenance) exactly as a computed resource's nested structs are, and the field is typed MissionDocuments.Provenance with display type object. The runtime marshals the column value as declared, so the struct's json tags are its wire names: every field carries one (a missing tag is refused naming the field), json:"-" leaves the field out of the interface, and omitempty makes it optional. The walk keeps the wire rules (exported fields, no embedded fields, no map, interface, array, or recursion), and the fields inside the struct resolve as leaves by the same steps, so a nested struct is a second interface in the same namespace and a nested declared type is the same imported type. Permissions are unchanged: the object is one field, granted, masked, and selected whole.

A struct that writes its own JSON (MarshalJSON or UnmarshalJSON) is refused on the column path unless it declares its type, since its fields do not describe the wire:

  • MissionDocuments.Seal: resources.Seal writes its own JSON (MarshalJSON or UnmarshalJSON), so its fields do not describe the wire; add @typescript(...) to its declaration

RPC and computed shapes are unchanged: their mirrors carry generated camel-case tags, and the mirror is the wire, so a nested struct's own MarshalJSON never runs there and derivation by fields stays consistent. A @typescript declaration on a plain struct wins over derivation, so an application can give a struct a richer TypeScript type when it wants one.

Storage. A struct, a named slice of structs, a declared type over anything but a basic type, or a type JSON by declaration, held by a JSON column and implementing no Spanner methods of its own, gets EncodeSpanner (value receiver, spanner.NullJSON{Value: v, Valid: true}, so a type's own or generated MarshalJSON is honored for storage too) and DecodeSpanner (pointer receiver, reading the column's JSON text back, a NULL cell the zero value) generated into zz_gen_storage.go in the package that declares the type, beside the zz_gen_json.go the JSON pair goes into. An application writes no encoder. A type with hand-written Spanner methods keeps them, whatever column it handles; one method without the other is refused. Such a type on a column that is not JSON, on an unnamed slice ([]Provenance has nothing for a method to attach to), or declared in a package the generator does not write into is refused naming the fixes:

  • MissionDocuments.Provenance: resources.Provenance is stored by generated JSON methods, but column Provenance is STRING(MAX); declare the column JSON, or implement EncodeSpanner and DecodeSpanner on the type
  • DroidReports.Frame: telemetry.Frame is stored by generated JSON methods, but it is declared in example.com/app/pkg/telemetry, where the generator writes nothing; declare the type in the resources package, implement EncodeSpanner and DecodeSpanner on it, or name its package with WithTypes

Writable packages and WithTypes(dir). The generator writes the two method files into the resources package, the virtual, computed, and RPC packages when configured, and every package named by generation.WithTypes(dir), a ResourceOption in the shape of WithRPC(dir): a directory whose package name matches, loaded with the run, given more than once when several packages qualify, and to one generator run when a module has several (the shared run owns the shared resources package). It is for a shared package whose types the resources package uses: an external system's client package whose model type a column holds, which a move into the resources package would misplace and a wrapper would make a conversion at every boundary, or a package the resources package already imports, which can never receive its types back without an import cycle. Nothing else is generated into a WithTypes package and its structs do not become resources. Example: telemetry.Frame, the droid link's frame type on a DroidReports column, named in Lodestar's generator.

Imports. The names every @typescript declaration imports are grouped per module into one import line each, placed after the @impulseframework/resource import of the file that carries them (zz_gen_resources.ts for table, view, and computed fields; zz_gen_methods.ts for request and result fields; zz_gen_api.ts for the key, create, and patch shapes). The client library exports no application types.

Nullable columns in the write shapes. A row interface leaves a NULL cell absent, so a nullable column is an optional property there (notes?: string). The Create and Patch shapes say what the wire takes: an explicit null clears the column and an absent property leaves it alone, so a nullable column renders notes?: string | null in both, and in the create-your-tenant body (section 16). A key is never nullable, and a nullable boolean keeps its NullBoolean value type, which carries its own null.

Examples: MissionDocument.Provenance, a plain struct on a JSON column, derived and stored by generated methods; DistressCall.Position, a GeoJSON Point declared with @typescript(Point, from: "geojson") over json.RawMessage, its JSON pair generated; BriefingTemplate.Layout, a computed field typed json.RawMessage itself, unknown in both clients; and MissionDocument.Digest, the SHA-256 of an uploaded document on a BYTES(32) column, a string in both clients' interfaces with display type bytes; and Ship.CargoBays, an ARRAY<INT64> column typed []int64, number[] in the console's interface and its metadata.

The generated client files compile against an older client. A regenerated zz_gen_api.ts and zz_gen_resources.ts compile against a @impulseframework/resource release that predates a field they carry, so the generator and the client package release in either order. Each file hands the one literal the client types through a local generic identity function, defineApiDescriptor<T extends ApiDescriptor>(descriptor: T): T for the descriptor and defineResourceMap<T extends ResourceMap>(map: T): T & ResourceMap for the resource metadata (the intersection keeps an empty map indexable by a resource name): TypeScript checks a literal passed through a generic constraint against the fields the declaration knows and no others, the literal keeps its narrow types (scope: 'global', the display types), and the client reads an absent field as not served, since every field added to the client's types after the package's first release is optional. zz_gen_methods.ts types its map by the file's own MethodMeta and zz_gen_constants.ts casts each value on its own, so neither carries a literal the client types. The wrappers give up the excess-property check a typed literal had, so the generator's tests carry it instead: Test_typescriptClientFiles_compile type-checks the four emitted files against two declarations in generation/testdata/clientdecl, one standing for a client released before live, features and the feature gate and the one the next release publishes with every field today's generator emits, and the descriptor and the map taken out of their wrappers and typed directly must compile against the current one, so a field the generator learns is a field that declaration learns in the same change.

13. Files

A row says which stored object is its file, and the generator serves that file under the row's read route. Two halves make a file's life: an @upload method (section 7) stores it and a row records the key the frame minted, and a @file declaration serves it back at GET <read route>/<segment>, content by default. Nothing is hand-written: not the permission check, not the not-found answer, not the content type, not the headers that keep an uploaded file from running script.

The gate. Read on the resource and a Read grant on the segment, a field of the resource with no column behind it. A role that lists documents and reads their rows but holds no grant on content sees the listing and cannot download; the store key is never the gate. It leaves the server in one place only, as the file's validator (the ETag below), which no route accepts back as a key: nothing answers a link, and no bucket is public.

The row. Located through the resource's own read path with the caller's Read conditions and tenancy: an absent, cross-tenant, or hidden row is 404, as on the read route, and a conditional grant on content (client = subject.client) is the row condition the statement renders. The columns that deliver the file — the key, and the name: and type: columns where declared — are read by the frame for itself, without field grants. A NULL key is 404 in the row's words, and so is a key the store does not hold; the key itself is never written into a refusal.

The response. Every file is served as a document that can do nothing, because its type is the uploader's word. Content-Type comes from the type column, then the stored object's type, then the name's extension, then application/octet-stream. Every response that serves the file (the bytes, a range of them, or a 304) carries X-Content-Type-Options: nosniff, so the browser honors that type and a file lying about it renders as that type or not at all, and the frame's own Content-Security-Policy: sandbox; default-src 'none', which gives the file document an opaque origin and lets no script run in it, whatever its type. The frame adds its policy beside the one an application's security-headers middleware set, never in its place: every policy on a response is enforced, so the application keeps its frame-ancestors and the file keeps its sandbox, and an application with no such middleware is protected the same, since the frame sets both headers itself. Content-Length and Last-Modified follow when known; ETag is the key, quoted, for a stored file, or the Tag a content function sets for a rendered one. When a validator is sent the frame sends Cache-Control: private, no-cache over the outlet's no-store, so the browser may keep the file and asks again with If-None-Match, which the frame answers 304 after the gate and the row lookup, before the store is opened. A body that seeks (a file on disk) goes through http.ServeContent, range requests included; any other body is copied. Refusals are JSON bodies with their status, as on every generated route. Bytes go through the application: no store is exposed and no link is answered.

What displays and what downloads. A direct visit to a file route shows the file inline only when its type is on a short fixed list the browser only displays: PNG, JPEG, GIF, WebP, AVIF, PDF, and plain text get Content-Disposition: inline; filename="…". Everything else downloads, with Content-Disposition: attachment; filename="…": HTML, XHTML, SVG, XML and JavaScript, which can carry script, application/octet-stream, and any type the frame does not recognize. The name is the name column's or the content's. The rule exists because the type is declared by whoever uploaded the file: without it, a person who can upload could store an HTML page that runs script on the application's own origin, in the session of whoever opens its link. The list is the frame's, not the application's; an application that must show untrusted HTML to a person builds a sandboxed iframe of its own around the downloaded content. The disposition governs a navigation alone, so an <img> whose source is a file route shows the image whatever the disposition: an SVG logo in an <img> keeps showing while a direct visit to it downloads. A rendered file follows the same rule, so a text/csv manifest downloads.

The store. resource.FileStore is a file store as the frames drive it: Put(ctx, key, contentType, r) writes an object once, Delete(ctx, keys) removes objects, Open(ctx, key) reads one back as a *resource.Content (ErrFileNotFound when nothing is stored under the key). resource.Content carries Name, ContentType, Size (-1 unknown), ModTime (zero unknown), Tag, and the Body the frame closes. The framework's stores are resource/filestore, opened from one URL each: gs://<bucket> is a Cloud Storage bucket, file://<dir> a directory confined by os.Root, and mem:// memory, for tests. The URL is configuration, APP_FILE_STORE for the default store and APP_FILE_STORE_<NAME> for a named one, so development keeps files in a directory and Cloud Run keeps them in a bucket on the same code path; filestore.Open refuses a bad URL and a missing bucket at start, and on Cloud Run (K_SERVICE or CLOUD_RUN_JOB set) refuses file://, mem://, STORAGE_EMULATOR_HOST and GOOGLE_APPLICATION_CREDENTIALS, each of which would send the service's files somewhere other than its bucket under its own identity. A bucket whose permission is refused at start does not stop the process, since a new grant takes minutes to take effect: the store probes again every five seconds for ninety seconds, and still refused it logs loudly, answers 503 on every file operation, and probes again on the next one. Every store follows the rules the frames rely on: a failed write leaves no object, deleting a missing key succeeds, a key is any safe relative object name (the upload frame mints UUIDs, which is a fact about the frame, so an adopter with existing files may pass its rows' names as keys), and a refused permission is an error of its own, answered 500 and never 404. The root package imports no object-store SDK; the stores do.

Named stores. An application keeps kinds of files apart by declaring a store as a Go type embedding resource.Store, in one line of its own code, in the resources package or any package the generator run reads:

// Documents holds mission documents in their own bucket.
type Documents struct{ resource.Store }

The store's name derives from the type's: Documents is the store documents, read from APP_FILE_STORE_DOCUMENTS, and ClientFiles is client_files, read from APP_FILE_STORE_CLIENT_FILES; renaming the store is renaming the type. A column says its store by its field type, StoreKey resource.Key[Documents], and an upload by the same type, @upload(max: 5MB, store: resources.Documents), whose Execute takes resource.FilesIn[resources.Documents]; the generated setter for the column takes resource.Key[Documents], so a key minted for another store, or for the default, does not compile into it, and copying a key the application made takes a conversion visible in review. Application code that opens an object itself converts with string(key) at the store boundary; the store interface stays untyped. The default store has no type: a string column and an @upload with no store: are its, as before. One bucket per store: two stores on one location would have the orphaned-file cleanup delete each other's files, and where the framework can see it (the stores it opens know their location) two stores on one location are refused where the client is built.

Wiring. The resource client is the one wiring point: resource.NewSpannerClient(db, resource.WithFileStore(files), resource.WithNamedFileStore[resources.Documents](docs)), which the database drivers' Open takes the same options for (database.Open(ctx, settings, resource.WithFileStore(files)), resource/database/spanner or resource/database/postgres under the alias database, section 20), each store at most once, a second wiring of one store refused with a panic naming it, as a duplicate route is. The generated handlers read a store off the client (Client.FileStore(name), nil when none is wired), and the generated router refuses to start when a store the package uses is not wired: every @file column's store, routed or not, and every @upload's. An unwired store would otherwise surface on the first upload, file request or releasing delete; the message names the store and the option that wires it, never an environment variable. The executor refuses, before the commit, a transaction that would release a key of a store that is not wired, so the object is not left behind; this guard covers a job process, which builds no router. Lodestar opens its two stores from APP_FILE_STORE and APP_FILE_STORE_DOCUMENTS (data.go); its suites open mem://.

Release. Deleting a row that carries a @file key, or pointing it at a new key, removes the old object from the store once the transaction commits, from every transaction the application runs: a generated frame, a patch applied on its own, application code calling ExecuteFunc. Nothing is generated into the frames and a body has nothing to remember. The generator declares the key fields on the resource (FileKeys() []resource.FileKey, beside DefaultConfig, each field with its store), a fact of the schema that no configuration carries and nothing an application writes changes, and the patch machinery reads them on the transaction: a delete makes one point read of the row's key columns and records each non-NULL key as released; an update or insert-or-update that sets a key field reads that field's current value and records it when the row exists, the value is non-NULL, and it differs from the new one (a new value of NULL included); an update that leaves the key fields alone reads nothing, and an insert records nothing. The record lives on the transaction wrapper and belongs to one attempt, so a retried transaction releases what its committing attempt recorded. When the commit lands, ExecuteFunc calls each store's Delete with the keys released from it, synchronously, and the request answers after it; the delete runs detached from the request's cancellation under its own timeout, since Cloud Run gives a process CPU only while a request is in flight, and a failed delete is logged naming the keys and the call still succeeds, since the rows are gone. The stores are the client's (the Mock client takes the same options, so a unit test can assert what a patch released); a transaction that would release a key of a store the client does not hold is refused before it commits, naming the store and the option that wires it. Any error from the body (ErrDryRun included), a commit refusal, or an abort that ends the transaction releases nothing, because nothing committed. A transaction an application wraps itself through NewSpannerReadWriteTransaction and commits outside the executor reads what it released with Released(), each key with its store, and deletes it itself. The upload frame's discard, the deletes after a failed transaction, runs detached the same way and only when nothing committed: a commit whose outcome the Spanner client cannot report keeps its objects, since the rows may hold them, and logs the keys for the cleanup.

Limitations.

  • One row owns one object. The keys the upload frame mints are UUIDs, so a key is never shared by construction, and no claim check runs before the delete: a body that records one key on two rows loses the object at the first release. A file several rows share is a row of its own, a table with @file, that the other rows reference by foreign key; the foreign-key refusal protects it while anything references it, and its own delete releases the object.
  • Rows the database deletes by cascade (ON DELETE CASCADE, an interleaved child) or by a row deletion policy never pass through the patch machinery; their objects are the orphaned-file cleanup's. An application that cares deletes the children by patch first. The audit pass names the cascade tables.
  • A crash between the commit and the delete leaves an object no row claims; the cleanup's.
  • A reader that located the row before the delete committed may find the object gone; the @file route answers 404 as for any absent object.

The audit pass. The generator can tell you which @file tables the cascade limitation applies to. A finding of that kind is advisory, a shape the framework handles under a stated limitation, and raising it as a warning would print it on every generation of every application that carries the shape, so the generator reports it through a separate pass instead: Generator.Audit() returns the findings of the last Generate() (a []Finding, each a sealed kind beside Warnings(); nil before a run), and a normal generation never prints them. An application's generate program prints them on demand: go run ./cmd/generate/resourcegenerator -audit in Lodestar, which prints the warnings as Warning: <text> and then each finding as Audit: <text>, one per line (impulse audit runs the same for a skeleton application once it lands); go generate ./... passes no flag and prints no finding. The first finding, CascadeReleaseFinding, names a resource that stores files on a table whose rows the database deletes by cascade, because the table is an interleaved child declared ON DELETE CASCADE (the finding names the parent) or a foreign key on it carries the CASCADE delete rule (the finding names the column), one finding per cause, in resource order: a cascade releases none of their objects and the orphaned-file cleanup removes them. The facts ride the table map the schema read records, INFORMATION_SCHEMA.TABLES.ON_DELETE_ACTION and REFERENTIAL_CONSTRAINTS.DELETE_RULE, so a cached schema audits like a fresh one. Further findings of this class arrive with their own register items. Example: RefitTask.PhotoKey, interleaved in Refits on cascade.

The orphaned-file cleanup. An object no row holds is left behind only by a crash between the stream and the commit, a cascade, or a row deletion policy, and the framework ships the command that removes it: filestore.Cleanup, run as a command of the application's job process, one store per run. It lists the store's objects older than the window whose names are UUIDs, the keys the frame mints, keeps every key the store's @file columns hold, and deletes the rest. The keys come from the holders the generator writes into each resources package, FileHolders() in zz_gen_file_holders.go: one resource.FileHolderOf[T]() per table resource with a stored file, read with strong reads, every key column once per run, and one resource.ComputedFileHolder per computed resource with a stored file, whose rows come from application code, so the cleanup takes its keys from the application's ComputedKeys or refuses. A view's keys are its tables', so views are left out. The job process hands the cleanup every resources package's list; the framework cannot verify the list is complete, so the window and the rules below stand between a forgotten package and a deleted file. The window is at least a day (filestore.MinimumWindow), two by default (filestore.DefaultWindow), and never shorter than the longest request or job. The cleanup refuses to run when no row holds any key in the store while aged objects are in it, since the holders it was handed would then be the wrong ones (a store with nothing aged to delete is reported and left alone, so an application that has stored no file yet runs its daily cleanup without a failure), and when the unclaimed share of the aged objects is above half (filestore.UnclaimedShare) with at least a hundred unclaimed (filestore.UnclaimedFloor), since the live keys were then most likely not all read; it touches only UUID-shaped names, so an object named by its row (an adopter's existing files) is never the cleanup's; and a dry run lists what it would delete. It never runs in a pull-request stack, and in production a bucket's soft delete is the recovery. Lodestar's cmd/jobs cleanup-files runs it over both stores and the walkthrough proves it with one orphan and one live file. The cleanup runs from the service: a scheduled method (@schedule, daily) starts one execution of the job process with the cleanup command through the job driver (resource/jobs/cloudrun), whose settings the site's configuration embeds (cloudrun.Settings, the template job the stack sets on the service as APP_JOBS_TEMPLATE) and whose Open takes the version the image bakes in (APP_VERSION): the job of this build is the template's name with the version's key (…-jobs-v0-1-15), which the pipeline made on this build's image, so Cloud Scheduler calls the service and the service starts the job deployed with it, which a traffic rollback rolls back too; where no job is configured (development, a pull-request stack) the start is refused and the call says so. Lodestar's CleanUpFiles is the method.

Rendered files. A document produced at request time is a computed resource's content: struct-scope @file on a keyed @computed struct, and the computed package declares <Name><Segment>(ctx, key…, qSet, client, computedClient) (*resource.Content, error) beside Read<Name>, the QuerySet carrying the checked scope and identity as it does for Read<Name>. The function renders and returns; it never touches the response. A nil content is 404. Set Tag to something that changes when the document does and the browser revalidates for free.

The browser client. The generated descriptor lists a resource's segments (files: ['content']), and its handle gains fileUrl(key, segment = 'content') beside url(key). Nothing fetches: the browser addresses the route itself, in an <img src> or an <a href>, and the session cookie rides along.

Examples: MissionDocument.StoreKey, a stored file with its name and type columns, served to the console's crew and listed but not served to the client portal; ExpenseManifest, a rendered text/csv manifest of a mission's booked expenses.

14. 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. The server holds no push connection and keeps scaling to zero.

The shape. A request opts in by carrying the header X-Subscribe: <tab>, a client-minted tab id of 1 to 64 characters of [A-Za-z0-9_-]; the client library sends it only on a live page's requests (list pages and record pages, live by default on a table-backed resource, whose generated metadata says its changes are published, unless the page says live: false), never from a picker, an edit form or an export. On a permitted list or read the generated handler registers the subscription — who, which tab, which resource, which key or which tenant domain, until when — before it runs the query, so a commit that lands during the query is not missed; a refused request registers nothing. A row is named by its key as the read route spells it: a single key's string form, a compound key's parts joined with / in route order (resource.RowKey). A list is named by its resource and the request's domain, empty for a global resource; filter, sort and cursor are not part of a subscription, so any change to the resource in that domain refetches the page. A mutation (a patch, the consolidated patch, an RPC method) publishes after its commit and before its answer: for each row it wrote, the subscribers of the row get a row document and the subscribers of the resource's list in the row's domain a list document; above 100 rows of one resource in one request, every subscriber of the resource gets one resource document instead. Writes to one target within one second coalesce. The publish is bounded by two seconds and a failure is logged; it never fails the request. The write's answer then names what the write put into the caller's own change set, so the tab that wrote fetches at once (below). A request's calls on the subscription record and the identity (register, renew, unsubscribe, revoke, token) are bounded by five seconds (live.RecordTimeout), so a backend that stops answering never holds a request open. The browser listens to its own change set (users/{uid}/changes, timestamps after the last one it saw) and refetches the row or list with _v=<the change's timestamp> (section 4), or _v=<the write's id> for a write the tab made itself, and such a response carries Cache-Control: private, max-age=300 so a remount inside the window is the browser's own; before any change arrived the client mints a seed at login, so a second user on a shared machine never hits the first's cached answers. Every other response stays uncached; the session and digest routes never carry the header.

Whose change it is, and when a page fetches. A page shows a person's own change at once and groups other people's, and what tells the two apart is the write's id. A committed request is one write: live.Publish mints its id (26 random characters) once, whatever tenants its rows were written in, and every change document the write publishes carries it as write, in every subscriber's change set. A document that several writes within one second became carries the last one's, as it carries the last one's timestamp, so the tab that wrote first finds somebody else's id on the document and fetches for it. The change's time could not serve: it is Firestore's server timestamp, set when Firestore commits the document, which the server answering the write never learns; and the document's id is the target and the second, shared by everybody who wrote to the target in that second. The write's answer names the id and the documents that went into the caller's own change set, the ones its own tabs will hear of, in the response header X-Changes (live.Answer), as JSON, percent-encoded so a key or a tenant outside ASCII travels in a header; decoded:

X-Changes: {"write":"<id>","changes":[{"kind":"list","resource":"Ships","domain":"<domain>"},{"kind":"row","resource":"Ships","key":"<key>","deleted":true}]}

The generated write handlers hand live.Publish the answer they have yet to write, so every write path carries it: a resource's patch route, the consolidated patch, an RPC method and the create-your-tenant route. The header is at most 2048 bytes (live.MaxChangesHeaderLength); a write that reached more of the caller's subscriptions than fit answers {"write":"<id>","all":true}, and the tab fetches everything it holds live. An answer carries no header when the write reached nothing the caller holds live, when the request speaks for no session principal (a machine outlet's, a scheduled call's), and when a publish of the write failed (it may have written some of its documents, which a tab told the id would take for changes it had fetched for). Nothing is lost by the header's absence: the change set reports the change and the page fetches for it as for anyone's.

The browser does the rest (the client library's README, "Live pages"). The tab that wrote fetches what the header names when the write is answered, without waiting for its change set, and does nothing when the change set reports a document carrying that write's id. A document carrying any other id, or none, is somebody else's change: the first one starts a wait of two seconds and everything that arrives in the wait becomes one fetch, and while changes keep arriving a page fetches at most once every five seconds. A tab that is not shown fetches nothing; it remembers that something changed and fetches once when it is shown again. The two times are the client library's defaults, and an application sets its own where it creates its client. The server holds none of this: it publishes each write as it always did, once.

Derived resources. A virtual or computed resource has no rows of its own, so a commit reaches it through the tables it reads, which the generator records next to the resource: each package holding published virtual or computed resources gets a generated zz_gen_live_derivations.go with an exported LiveDerivations (a live.Derivations) naming, per resource, its @rowsOf root, its other tables and whether the set was read off the query or declared, every table as the generated Resource method of the type over it, so a renamed or dropped table fails to compile there; the handler package's zz_gen_live_derivations.go is the assembly, liveDerivations, which imports those packages and merges their values (live.Merge) into the one value every publish expands its writes with (live.Publish, Derivations.Expand). A virtual resource's set is read off the embedded query behind its Subquery method with memefish's lexer, never its parser, so a Spanner feature the parser has not learned does not stop generation: the names in table positions, after FROM, JOIN and the commas of a FROM list, with a WITH name in scope from the end of its own body, so a CTE named like a table shadows the table after its body and not inside it, and functions, subqueries, hints and aliases passed over. A name in a table position that is neither a table nor a CTE in scope, a recursive WITH, and a text the lexer refuses each refuse generation, naming the place; @changedBy on the resource replaces the reading and is the way out, and a declaration that differs from what the query names is a warning naming both sides, not a refusal. A computed resource's set is its declaration alone (section 1). A table whose rows the resource carries one to one under the same key (@rowsOf, the root) reaches it exactly as the table itself is reached: a row document under the same key to the row's subscribers and a list document to the list's subscribers in the write's domain. Any other table it reads reaches every subscriber of the resource with one resource document, the same document the bulk path writes, to its row subscribers and to its list subscribers in the write's domain, or in every domain when the table or the resource is global; nothing is read from the database to name the derived rows, and a page may refetch and find nothing changed, the tolerance a table's list document already has. A resource reached both ways in one commit gets the resource document alone. The metadata's live is true for a resource with a known set, so its pages are live by default like a table's; a computed resource with no declaration stays live: false.

One kind of table the record names differently. A table of an Auth is declared by the generated management inside its tree (section 21), in a package Go lets nothing outside the tree import, so a view of the application's that reads one, a sector's people over the crew's memberships for instance, cannot write the type. Its entry names the table by the table's name, as text ({Name: "CrewUserRoles", Global: true}), and its comment and the file's say so. Nothing is given up: the compile failure a type gives protects a record that outlived a rename, and here the declaration and the record are written by the same run from the same schema; and a name brings no import, so the tree's own methods may read the view. The view's query is read, or @changedBy declared, exactly as for any other table. The Auth's handlers publish their commits with the application's derivations, which the application hands them where it constructs them, so a membership given or an account disabled through the management reaches the view's pages; a write to those tables that no generated handler commits (a sign-in, the session library's own routes) is published by nothing, as a write behind any table's back is not.

The views the generated management declares itself, a tenant's lists (section 21), are recorded where the assembly can reach them: in the Auth's handlers package (crewhandlers.LiveDerivations), since the declarations package is internal to the tree. That record is inside the tree, so it names every table by its type, the Auth's own and the application's, and the assembly merges it with the packages' values.

The routes, on every session-serving outlet under its API prefix, behind the outlet's session middleware like every other route:

POST <prefix>/live/renew        {"tab":"<tab>","subscriptions":[{"resource":"Ships","key":"<key>","domain":"<domain>"},{"resource":"Ships","domain":"<domain>"}]}
                                → 200 {"kept":[...],"dropped":[...],"expiresAt":"<RFC 3339>"}
POST <prefix>/live/unsubscribe  {"tab":"<tab>"} or {"tab":"<tab>","all":true}   → 204
GET  <prefix>/live/token        → 200 {"uid","token","project","database","apiKey","emulator"}

The client renews every 120 seconds; a subscription expires 300 seconds after it was written or renewed. The renewal re-checks each subscription against the user's grants — Read on the resource for a row, List for a list, in the subscription's domain (the global scope when none is sent) — writes the kept ones with a fresh expiry in one batch, and echoes, in the order sent, which were kept and which dropped; a resource the grants do not know is dropped, never refused. A row subscription of a domain-scoped resource sends the domain the row was read in, or its re-check runs in the global scope, where a domain-scoped resource holds no grant, and the subscription is dropped. Revocation therefore ends a subscription at the next renewal, and the refetch is refused meanwhile; the publisher never checks permission. A page sends unsubscribe {tab} best effort as it leaves; a logout sends {tab, all: true}, which deletes every subscription of the principal and revokes the browser's identity. The token route answers the session principal's id (below), how to reach the change set, and the identity: in production a Firebase custom token the browser signs in with, against the emulator an empty token and the emulator host, which the browser connects to with the SDK's mock user token. A request carrying X-Subscribe on a machine outlet answers 400 naming the header: machine clients wanting change notification are a different consumer on a topic. Every subscribing request, the live routes included, carries subscribe=<tab> on its request log line (AddRequestAttribute).

The principal id. Every subscription, change set and browser identity belongs to a principal id (live.PrincipalID): the name of the auth the request came through, |, and the session's user name, or role:<role> for a session established as a role, so crew|alice, members|alice@example.com and crew|role:Auditor. The auth's name is the one the outlet's routes bind (section 8), so two auths over one database never share an id: a password user name equal to a directory user's email is two ids and two change sets, and a logout through one auth ends that person's subscriptions and identity alone. The id is the Firebase user id (uid) the browser signs in as, and Firebase allows a uid of at most 128 bytes (live.MaxPrincipalIDLength). Nothing is truncated or hashed: a person whose id is longer uses the application as always while the live pages refuse them. The token, renew and unsubscribe routes answer 403 naming the length and the limit, and a subscribing list or read registers nothing, each with the reason logged. The refusal sits in the live routes because the sign-in belongs to the session library and the auth package, which the generated code does not configure. The session library sets no length on a user name (its username columns are STRING(MAX)), so nothing is checked when the server starts.

The seams are in resource/live: SubscriptionRecord (register and renew in one batch, unsubscribe a tab or a principal, the subscribers of a row, of a list in a domain, of a resource), ChangePublisher (Publish(ctx, domain, writes), which answers the documents it wrote, per principal), Identity (the token payload and the revocation), Signaler and Subscriber (the signals below), bundled as Service; Fanout is the fan-out every publisher implementation writes, and Fake an in-memory service for tests. The Firestore implementation is the live driver, resource/live/firestore: the configuration embeds its Settings (the project, the database, the web API key and the emulator host) and opens it with Open, as it opens the database driver (resource/database/spanner, whose Settings are the three Spanner variables and the emulator host and whose Open builds the resource client) and the job driver (resource/jobs/cloudrun), each bound under a neutral import alias (section 20); each driver publishes the declaration of its settings in the package beside it, which impulse's checks and bedrock's stack read. Against the emulator with no project named, the live driver opens the emulator's database under firestore.EmulatorProject (live-emulator), and the token route hands the browser the same id. The layout is subscriptions/{id}, a flat server-owned collection with a time-to-live on expiry and one composite index per lookup shape, and users/{uid}/changes/{id} with a time-to-live on expires, which a user may read for their own uid and nobody writes from a client; firestore.rules, firestore.indexes.json and the layout's README sit beside it. The generated handlers reach all of it through the application's LiveService() live.Service accessor, and the three routes are generated in zz_gen_live.go as delegations to the library's handlers.

The signals document. The live service is also how an application's instances tell each other that something shared changed. One document per application, application/signals, has a field per kind of change, features, tenants and policy, each {at: <server timestamp>, by: <the writer: its Cloud Run revision or job execution, else its host, and its process id>}; a Signal(ctx, kind) writes that kind's field alone (a merge write on the field path), so two kinds never clobber each other, and one snapshot after quick signals of two kinds carries both. Each instance holds one snapshot listener on the document (Subscribe(kind, onSignal), several subscriptions per kind, a subscription made after the listener began included; Subscribe waits on nothing): every snapshot wakes the subscriptions of each kind whose at advanced past the last seen, the first snapshot against no time seen, so a subscription made before it is woken once for the kinds the document already holds (a nudge to reread, never a fact) and misses nothing written after it was made, while one made after it hears only the signals after it. A listener Firestore ends on its own is logged and reopened with backoff by the subscriber, the one place that owns reconnection, and on the reopen every kind that advanced while it was down wakes once. A signal carries nothing but the fact of a change, so the signaler coalesces: while a write of a kind is in flight, later signals of the kind are absorbed into one following write. A signal's failure is returned for the caller to log and never fails the request, since every subscriber also rereads at its own backstop. The kinds are resource.SignalKind (KindFeatures, KindTenants, KindPolicy), re-exported by the live package as live.Kind; the document needs no index, no time-to-live and no rules exposure, since no client reads it.

What an application wires. One method, LiveService() live.Service, returning the Firestore service: the configured Firestore database (APP_FIRESTORE_DATABASE, the database bedrock hands the application; the project, and the optional Firebase web API key APP_FIREBASE_API_KEY), or the emulator (FIRESTORE_EMULATOR_HOST). Every application wires one; the generated handlers assume it, and a test harness wires live.NewFake(). The infrastructure applies the indexes and the time-to-live policies. Lodestar's wiring is pkg/config/data.go and app/app.go.

The names the client library mirrors: the header X-Subscribe, the parameter _v, the routes live/renew, live/unsubscribe and live/token under the outlet's prefix, the renewal interval 120 s, the expiry 300 s, the cache header Cache-Control: private, max-age=300, the bulk threshold 100, the response header X-Changes and its JSON (write, changes, all), and the change document's shape (kind of row, list or resource; resource; key and deleted on a row; domain on a list; at, expires and write). The generated descriptor names the routes per outlet: live: { renewRoute, unsubscribeRoute, tokenRoute }.

15. Feature flags

A resource, a field, or a method can be put behind a flag that an administrator turns on and off at runtime, without a release: while the flag is off, the thing does not exist for the browser or the API, and when it is turned on, every instance serves it within a moment.

Declaring a flag. A flag is a resource.Feature constant in the resources package; its value is the flag's name ([a-z][a-z0-9_]{0,63}) and its doc comment the description an administrator reads:

// Debriefs lets a crew write and read mission debriefs after a return.
const Debriefs resource.Feature = "debriefs"

@feature(Debriefs) on a @resource, @virtual, @computed or @rpc struct gates it whole; on a field of a table, view or computed struct it gates the field (section 1). The generator writes zz_gen_features.go into the resources package on every application: Features(), the declarations in constant order, and FeatureGates(), every gated resource (by its plural), field (Resource.field) and method (by name) with its flag. Both are written whether or not anything is declared, so the generated handlers call them unconditionally.

What a flag does while it is off. A gated resource's and method's routes answer 404 with the router's not-found body, before the handler runs: the generated route registration wraps exactly those routes in the application's FeatureGuard (outside the domain guard, where both apply), and a gated resource's arm of the consolidated patch answers unknown resource. A gated field is unknown to the decoders (columns, sort, filter, a patch body naming it: 400) and absent from every response. The permission digest leaves the resource, the field (Resource.field) and the method out, exactly as a denied target is left out, so the browser's navigation and forms never show them. Nothing is checked twice: the gate and the permission check are the same two answers a denied route gives, and a flag that is off never changes what a grant means. A FeatureSet that is nil (the application wired none) leaves every gated target off.

The table. Every application has two tables, FeatureFlags (Name STRING(64) the key, Description, Enabled, UpdatedAt a commit timestamp, UpdatedBy) and FeatureFlagChanges (Name, ChangedAt a commit timestamp, Enabled, ChangedBy), the second a record of every flip written in the flip's own transaction; the rows outlive their flag, so there is no foreign key. resource.FeatureFlagsDDL(dbType) renders the statements for Spanner and for PostgreSQL, and an application copies them into a migration as Lodestar does in 000001_Baseline.up.sql, pinned to the function by a test. The generator never derives a resource from the table: FeatureFlags has a Description column but no Id, and an enumeration table is recognized by the two together.

Deploying. resource.MigrateFeatures(ctx, client, resources.Features()) runs beside the role check, after the schema migration: a flag declared for the first time is inserted off, a known flag keeps its state and takes the release's description, and a flag the release no longer declares is deleted, all in one transaction, with UpdatedBy the process event. A flag's state therefore survives releases and never leaks a flag the code cannot serve; a new flag is always off until an administrator turns it on. Lodestar's deploy step is pkg/deploy/deploy.go, called from the migrate and bootstrap commands.

The copy every instance holds. resource.LoadFeatures(ctx, client) reads the table into a FeatureSet, and FeatureSet.Follow(ctx, liveService) keeps it current until ctx ends: the flags ride the features kind of the live service's signals document (section 14), so on every signal of that kind, and at the five-minute backstop regardless, the table is reread; a failed reread is logged and the copy stays as it was. A flip therefore reaches every instance within a moment, and the backstop is the guard should a signal be missed. The subscriber is the application's live service, which every application wires; Follow refuses a nil one. The application exposes the copy as FeatureSet() *resource.FeatureSet, asserted on the application type beside LiveService, and the generated decoders, routes and digest read it. Lodestar reads it through the configuration's database client when the App is built and follows it from Start: app/app.go.

The routes, generated on every application:

GET  <prefix>/features                       → 200 {"enabled":["debriefs", ...]}     anyone signed in, every outlet
GET  <prefix>/feature-flags                  → the FeatureFlags list, sort=name       List on FeatureFlags (global)
GET  <prefix>/feature-flags/{featureFlagName} → one flag                              Read on FeatureFlags (global)
POST <prefix>/set-feature                    {"name":"debriefs","enabled":true}      Execute on SetFeature (global)
                                             → 200 {"name","enabled","updatedAt"}; an undeclared flag is 404

The features route is open to anyone signed in: what the browser reads at start and again after a flip, and what the client's features state (enabled(name), subscribe, canSet()) answers from. FeatureFlags is a read-only global resource the generator registers in every application's collection (List and Read over description, enabled, updatedAt and updatedBy, name the key, listed by name) and carries in the TypeScript constants, metadata and descriptor exactly as a generated resource, so the feature flags dialog reads it through an ordinary handle; the routes are the library's handlers (resource.FeatureFlagsHandler, resource.FeatureFlagHandler), delegated to from the generated zz_gen_features.go in the handler package, and a struct or a manual registration that would take the name FeatureFlags is refused. SetFeature is the library's method (resource.SetFeatureHandler), registered with Execute and carried as an RPC method entry: it writes the row and its change record in one transaction, honors X-Dry-Run, refuses X-Warning (it declares no warning), signals the other instances through the live service (Signal(ctx, resource.KindFeatures), bounded by two seconds, a failure logged), reloads this instance's copy, and answers the flag as written. An @rpc struct named SetFeature is refused.

The role. A role that administers flags holds Execute on SetFeature and List and Read on FeatureFlags with its four non-key fields, in the global scope:

{
  "name": "FeatureAdministrator",
  "permissions": {
    "List": [{ "resource": "FeatureFlags", "fields": ["description", "enabled", "updatedAt", "updatedBy"] }],
    "Read": [{ "resource": "FeatureFlags", "fields": ["description", "enabled", "updatedAt", "updatedBy"] }],
    "Execute": [{ "resource": "SetFeature" }]
  }
}

The digest decides what the dialog may do: a user without Execute sees the flags and cannot flip them; a user without List is never shown the dialog.

Tests. The generated authorization matrix carries the features route as an open case (200 without a grant), the FeatureFlags routes as query pairs, and SetFeature as denied-only with its dry run, on every outlet serving them. When anything is gated, the generator also writes zz_gen_features_test.go into the handler tests package: every gated route and field driven in both states of its flag, the flag flipped in the test database through resource.SetFeatureEnabled between them after resource.MigrateFeatures wrote every declared flag, so the suite proves the 404 and the unknown column off, and the matrix's answers on. The matrix puts every declared flag on in its own test database before it drives a route, because a gated route is absent while its flag is off and would answer 404 before the permission gate the matrix pins; the application's harness needs no rule of its own for that. The application's newTestHandler builds the App over the test database, which reads its flags as it is built.

The names the client library mirrors: the routes features, feature-flags, feature-flags/{featureFlagName} and set-feature under the outlet's prefix; the features answer {"enabled": [...]}; the resource FeatureFlags with the JSON fields name, description, enabled, updatedAt, updatedBy; the method SetFeature with the body {"name", "enabled"} and the result {"name", "enabled", "updatedAt"}; the descriptor's features: { route: 'features' } on every application and feature: '<name>' on a gated resource's, method's and field's entry; and in the client file the Feature union of the declared names with the Feature constants keyed by the Go constants' identifiers (Feature.Debriefs). The kind the instances signal each other with is features (resource.KindFeatures), a field of the application/signals document in the Firestore layout.

16. Tenant records

A tenant made at run time is served by every instance without a restart or a release. The application declares one table as its tenant record with @tenant (section 1), and the library keeps a copy of its keys on every instance: the roster. Nobody creates a tenant directly: staff bring an organization in by inviting one person, and that person's first sign-in makes the tenant ("How a tenant comes to exist", below).

The record. @tenant goes on the global, table-backed @resource whose rows are the tenants; its one key is a generated id (impulse.UUID), whose text is the domain in every tenant-scoped URL. The record's route name is the segment tenant-scoped routes are served under and its key's route parameter is the domain parameter: Lodestar's Sector, keyed by ID, puts the sector-scoped routes at /console/api/sectors/{sectorID}/… while /console/api/sectors lists the sectors. A tenant-scoped resource, view, computed resource or method in a package with no @tenant record is refused, so a tenanted application always has one, and a second @tenant is refused naming the first.

The key and the name. A tenant's key is never a word a person types. It is written into every row the tenant owns (the @domain column, typed impulse.UUID, or string holding the id's text) and is the domain of every role held in the tenant, so it cannot change, and a key a person typed could be used again for another tenant after a delete. The generator therefore refuses a @tenant record keyed by anything but an id the framework generates when the tenant is made. What people call the tenant is the column the record marks @tenantName: an ordinary field, changed under the record's Update grant, and every instance's roster carries the new name after the write, so the place switcher and the session's tenant list show it at once. Whether two tenants may carry one name is the application's to say in its schema: a unique index on the name column refuses the second (409, as any duplicate of a unique value), and an application that allows it has no such index; the skeletons and impulse add tenancy write the index. An add on the record's collection makes no tenant: it is answered 400, with or without a key in its path, in a sentence that says how one is made ("a sector is not created directly: invite one person, and the sector is made when that person first signs in"), whoever asks and whatever they hold. What names a tenant by hand names it by its name: TenantRoster.Named(name) answers the one tenant that carries a name, and is an error for a name no tenant or more than one tenant carries, which is how a development bootstrap reads the tenants of its logins. The development seed inserts its tenants under fixed ids, so an application's suites name them.

The roster. resource.TenantRoster is the set of the record's keys an instance holds, built by the generated constructor in the handler package, New<Record>Roster(client, opts...) (NewSectorRoster for Sector), which carries the record's table and key column so the application names neither. Start(ctx) reads the set once, failing the start when the read fails, and then keeps it current until ctx ends. Has(domain) answers from the set behind an atomic pointer, so it never waits and performs no read: a domain the set does not hold is unknown, whatever the table says at that moment. Domains(ctx) lists the set sorted, in DomainRoster's signature, so the roster's Domains is what the application hands SessionPermissions. Add and Remove change the set at once. The read is one statement selecting the key column, rendered for Spanner and for PostgreSQL and run outside any request transaction. The application exposes the roster as TenantRoster() *resource.TenantRoster, asserted on the application type by the generated contract beside DomainGuard; a nil roster holds no tenant, so an application that wires none fails closed on every tenant-scoped route.

The guard. The generated DomainGuard and the consolidated dispatcher's descent ask the roster first (TenantRoster().Has(domain)) and answer an unknown domain with the guard's 404 or the dispatcher's 400; then the session's reach (UserPermissions.Reaches: whether the tenant's declaration admits the way the session was established, section 6) and answer a tenant the session may not enter the same way, in every mode; under WithConcealedDomains they ask the caller's foothold last (UserPermissions.HasGrants in the domain) and answer a caller without one the same way. Without concealment the roster and the reach answer. The record's own routes stay unguarded: they terminate at the segment's value and are global. The application hand-writes no existence seam; the generated contract asks for the roster alone, and the reach is the composed session permissions' answer.

Keeping up. What writes the record calls Reload after the commit, never inside it, so the instance that wrote the tenant, or its declaration, serves it at once: the generated maker an invitation's first sign-in makes the tenant through and the create-your-tenant route (both below), and the record's generated write paths for an update or a delete, the standalone PATCH handler and the consolidated dispatcher's case for the record and for its directories (below); a key cannot change on update. The same path then signals the tenants kind (resource.KindTenants) through the live service's Signal, the application's one signals document, after the commit and before the response, as a feature flip signals the features kind; a failure to reload or to signal is logged and never fails the request. Every instance's roster reloads on the signal: Start subscribes to the application's one watch when resource.WithTenantSignals(liveService) is passed, and never opens a listener of its own. Behind the push, a backstop reread (resource.WithTenantBackstop, five minutes by default) is the correctness guard, so an instance that missed a signal is at most that far behind; a failed reread is logged and the set stays as it was until the next. A role held in every tenant domain reaches a new tenant with nothing written for it; the one membership written when a tenant is made is its first administrator's. Add stays for a test harness that seeds a roster without a table; the generated paths never call it.

The declaration. Who may enter a tenant is data on the tenant record, read in two places. The record declares it with two annotations (section 1): @directoryOnly on a bool column, which says the tenant's people enter through its directory only (no other sign-in reaches it: not a password, a personal account or another organization's directory, but for the tenant's own administrator's password with a second factor), and @tenantDirectory on a second, tenant-scoped resource that holds the tenant's directory, the organization its people sign in through, one row for a tenant, with @directoryMethod on its sign-in method column (google, azure, workos, oidc, as the session library spells them) and @directoryConnection on the column carrying the connection the method's identities record (a Google Workspace by its domain or by the name the registration gives it, a Microsoft Entra tenant by its tenant id); the directories record binds to the tenant with the bare @domain on the row, never through a join path, and a second directories record is refused naming the first. Both halves are the tenant's own to change: its directory under the tenant's grants on the directories record, and the flag by the method the generator writes in the tenant's scope ("Directory only", below), never by the tenant record's global write paths; with TrackChanges on the two records, every edit leaves a change event, and no second audit is needed. The generator then emits, in the handler package, New<Record>DeclarationReader(), a signin.DeclarationReader[*spanner.ReadWriteTransaction] that reads one tenant's declaration in the sign-in's own transaction: the application hands it to each auth, whose New sets the library's sign-in rule over it (signin.TenantPolicy(resource.SignInRoles(engine.UserManager()), reader); the auth whose people may sign up and create a tenant of their own adds signin.AdmitWithoutTenant()), and resource.SignInRoles reads the person's memberships outside the transaction, since the Spanner client refuses the engine's read under the transaction's context as a nested transaction. The roster keeps the request-time copy: New<Record>Roster is built with resource.WithTenantDeclarations naming the columns, Reload reads the keys and the declarations in one read, and Declarations(ctx, domain) answers from the copy, nil for a tenant the roster does not hold, which is what SessionPermissions takes as its fifth argument (section 6): a tenant is offered to a session only when its declaration admits the way the session was established, or the session's actor is a super administrator. A declaration restricts its own tenant and nobody else's: a tenant that is not directory only admits everyone it seats, however they signed in, and its directory closes it to nobody; it is what seats a stranger at their first sign-in through it (the default seat, below) and what the tenant can be made only of. An invitation that makes a tenant, accepted through an organization's directory, and the record's create-your-tenant route ("How a tenant comes to exist", below) each set the directory the person came through on the new tenant in the row's transaction, beside the person's administrator membership; the route reloads the roster before it waits on that membership, so the wait's probe asks what the next request asks.

One directory, set from a sign-in. A tenant has one directory, and a directory, its method and its connection together, belongs to one tenant. The schema holds both with two unique indexes on the directories table, one on the tenant column and one on the method and the connection, and the generator refuses a directories record whose table lacks either, naming the statement to add:

CREATE UNIQUE INDEX TenantDirectoriesByTenantId ON TenantDirectories(TenantId);
CREATE UNIQUE INDEX TenantDirectoriesByMethodConnection ON TenantDirectories(Method, Connection);

The indexes refuse two writes that race, at the commit, where a unique index can only say that a value exists. The generated write paths refuse first, through resource.TenantDirectoryRules, which the roster file builds for the record (New<Record>DirectoryRules), each refusal a Conflict (409) whose sentence says what is wrong and what to do, in the record's own word for a tenant:

  • a second directory for a tenant: "This tenant already has a directory, Google Workspace acme.example. A tenant has one directory: remove it first to set another.";
  • a directory another tenant has: "Google Workspace acme.example already has a tenant here, and a directory belongs to one tenant. Ask that tenant's administrator to invite you." The sentence says the organization has a tenant, which a rule of one tenant for a directory cannot keep from being learned; it does not say which;
  • a personal account, one of the two values that stand for everyone who is in no organization (any Google account, accounts.google.com, and Microsoft's personal accounts, the consumer tenant id; signin.Directory.PersonalAccounts): "A personal Google account is not an organization's directory, so it cannot be a tenant's directory. Sign in with your organization's account (Google Workspace or Microsoft Entra) and try again.";
  • removing the directory of a tenant that is directory only: "This tenant is directory only: its people sign in through its directory alone, so nobody could enter it without one. Turn directory only off first, then remove the directory." Once removed, the roles the directory gave stand, and the directory is free for another tenant.

How a sentence names a directory. A directory's connection is a key: for a Microsoft Entra tenant it is the tenant's id, which no person knows. So no sentence a person reads says the connection itself. resource.DirectoryWords(directory, namers...) says a directory as the middle of a sentence names it, and resource.DirectoryName(directory, namers...) with its kind before a name ("Google Workspace acme.example", "Microsoft Entra tenant Lakeside"). A namer (resource.DirectoryNamer) answers what one auth's sign-in registrations call the directory: the name a registration that takes its connection gives it, and the label of the button a person signs in to it with. The words are the first name any namer gives; where none names the directory, the first label, as "your organization's Microsoft directory" for a button labeled Microsoft; and where no namer answers at all (an application whose user management is not generated, or a directory no registration takes any more), what the directory alone says: a Google Workspace's connection is its name or its domain, an OpenID Connect provider's is the application's name for it or its issuer, said by its host, and any other directory is said by its kind ("your organization's Microsoft directory", "your organization's directory"). A generated auth's identity client is a namer (<Auth>Identity().DirectoryName, from session.AuthAPI.DirectoryName), and the generated frames pass every auth's: New<Record>DirectoryRules().NamedBy(...) wherever a handler builds the rules, so the refusals above, the directory-only warning and the open-to-directory warning say the same words, and WithDirectoryNames(...) on the tenant list, for a closed tenant's reason. Which registrations name a directory is the session library's to say (its README, "DirectoryName"): a Microsoft Entra tenant has a name only where the registration lists it with azure.NamedTenant.

The caller's grants answer before a rule does: the generated create and delete ask PatchSet.Permitted first, the check Buffer opens with (the permission on the record and on each field the request names), so a caller who holds no grant for the write is refused with the Forbidden (403) any record answers, and learns nothing a rule's sentence says.

Nobody types a directory in. The record's method and connection are output-only, so a request that names either is refused as naming fields the record does not take, and the generated create (the record's add, under its Create grant in the tenant) sets both from the session: TenantDirectoryRules.FromSession answers the directory the caller is signed in through, held to the rules, and refuses a session that came through none ("You are signed in with a password. A directory is set by signing in through it: sign in with your organization's account (Google Workspace or Microsoft Entra), then make it the directory."). The person who sets a directory is therefore always a member of the organization; no other proof that a tenant controls it is asked for. The session read (GET .../user/session) carries directory, the method and the connection of the organization's directory the session came through, absent for a password, a personal account and an impersonation, which is what a tenant's Sign-in page offers its administrator to make the tenant's ("Make acme.example this tenant's directory") and what tells it to offer nothing. A write that sets a directory in code, from a sign-in, takes one step: the generated Set<Record>Directory(ctx, txn, tenant, directory), which asks the rules and buffers the row through the record's create patch, so its change event is written with it. The create-your-tenant route calls it with the directory its creator came through, so a creation from an organization that already has a tenant is refused with the sentence above and nothing is written, and the maker of an invited tenant holds the directory the accepting person came through to the same rules; a caller inside a sign-in hands it the identity's method and connection over the sign-in's transaction (resource.NewSpannerReadWriteTransaction). The rules read what is committed, on Spanner; their statements render for PostgreSQL too ($1, $2, $3), where the two unique indexes hold the rules as they do on Spanner.

Directory only. Turning a tenant's directory-only flag on closes the tenant to everyone who does not sign in through its directory, so the switch is the tenant's own, turning it on is held to three rules, and the method that turns it on warns before it runs. For a tenant record that declares the flag and the directories record, the generator writes two methods in the tenant's scope, served on every session outlet that serves the record: Make<Record>DirectoryOnly, at POST /<prefix>/<tenants>/{tenant}/make-<record>-directory-only, turns the flag on, and End<Record>DirectoryOnly, at POST /<prefix>/<tenants>/{tenant}/end-<record>-directory-only, turns it off. Neither takes anything in its body ({}: the route names the tenant), and X-Dry-Run: true runs the frame and rolls back, as on every method. The tenant's administrator runs them: a role file grants Execute on each to the domain role that manages the tenant's sign-in settings, and the record's own write paths, which are global, show the flag and never write it (the field is output only on the wire, so a create or an update that carries it is refused as naming an unknown field, and a role file that grants Create or Update on it is refused by the deploy-time validation of the role files, access.ValidateRoles, the field requiring neither). Make<Record>DirectoryOnly asks TenantDirectoryRules.DirectoryOnly once the caller's Execute grant has answered and before the flag is written through the record's update patch, and each refusal is a Conflict (409) whose sentence the person can act on, in the record's own word for a tenant:

  • a tenant that has no directory: "This tenant has no directory, so it cannot be directory only: nobody could enter it. Set its directory first: sign in through your organization's directory, make it this tenant's directory, then turn directory only on.";
  • a caller who is not signed in through the tenant's directory themselves: "Directory only is turned on by a person who is signed in through this tenant's directory, Google Workspace acme.example: that shows the directory works, and that you will not shut yourself out. You signed in with a password. Sign in through Google Workspace acme.example and try again.";
  • a caller whose own account has no password, where their auth has the password method: "Directory only is turned on by a person who has a password: an administrator of this tenant enters it with a password and a code sent to their email, and that is your way back in if the directory has a problem. Choose a password on Your account first, then try again." A person who has only ever signed in through the directory has none, and chooses one on their account page (the session library's "A person's first password"). Where the caller's auth has no password method the rule stands down and says nothing: there is no password to have, and such a tenant is opened again by a super administrator alone. The rules are told about each auth's passwords by its generated identity client (TenantDirectoryRules.PasswordsBy, CallerPassword), which answers for the real person behind the session.

Nobody is exempt from the three, a super administrator included: they are about the directory and the way back in, not about who may enter. A tenant is directory only from the start in one case: the invitation that makes it says so, and is then accepted through an organization's directory and no other way, so the tenant is made with the flag on and that directory as its own in one transaction ("How a tenant comes to exist", below). The create-your-tenant route makes no tenant with the flag on. Turning the flag off, and a call that leaves it on, are plain: no rule holds them. While the flag is on, the tenant's routes, these two among them, are served to the people the tenant admits: a person signed in through its directory, a super administrator, and the tenant's own administrator who signed in with a password and the code sent to their email. So a tenant whose directory has stopped working is opened again by one of its own administrators, who turns the flag off or sets the directory right, or by a super administrator; to an administrator who signed in any other way, and to one whose password session carries no second factor, the tenant answers as one that does not exist. The first two rules and the rule that keeps a directory-only tenant's directory read what is committed, and a transaction's reads do not see its own writes, so the library's transaction notes each write the rules pass: one transaction that turns the flag on and removes the tenant's directory is refused, whichever comes first ("This same request removes this tenant's directory, so it cannot also turn directory only on: nobody could enter the tenant. Keep the directory, or leave directory only off."); each method is a request of its own, so over the wire the two are always two requests, each held to what the other committed, and the note holds an application's own code that does both in one transaction. After the commit each method reloads this instance's roster and signals the tenants kind, so the next request on every instance is decided by the flag. What the flag does once it is on has two exemptions: the super administrator, who enters every tenant (section 6), and the tenant's own administrators, who enter their own tenant with a password and a second factor. A person seated through a role held in every tenant, an administrator's role among them, is kept out like anyone else, which is the tenant's way to close itself to the application's own people all at once.

Make<Record>DirectoryOnly declares a warning (section 7), so the dialog a page runs it through shows what the call would do before anything is saved, and holds its button until the person has typed the word close (resource.DirectoryOnlyWord: a warning's word is one fixed lowercase word, which a directory's name is not, so it is the same for every tenant). Asked for its warning (X-Warning: true), the method answers in place of running (TenantDirectoryRules.DirectoryOnlyWarning), naming the directory in the words a person knows it by ("How a sentence names a directory", above: here a Workspace by its domain; a Microsoft Entra tenant its registration does not name reads "Only people who sign in through your organization's Microsoft directory will be able to enter this tenant."):

{
  "consequence": "Only people who sign in through acme.example will be able to enter this tenant. An administrator of this tenant who has a password can still sign in with it and a code sent to their email. 2 people seated here sign in another way and will lose access.",
  "names": ["Gale Ferris (gale)", "hollis"],
  "confirm": "Admit only people who sign in through acme.example"
}

The sentence counts everyone seated in the tenant, in the tenant itself or in every tenant, who has no sign-in through its directory, in every auth whose people the tenant seats (each auth's generated identity client answers its own, DirectoryOutsiders); a super administrator is not among them, and neither is an administrator of the tenant who has a password, who does not lose access: the second sentence says how they still get in, and is there where an auth whose people the tenant seats has the password method (DirectoryPeople.AdministratorsEnter). It is a general sentence and counts nobody: who the administrators are is the People list's to say. names lists them, each by their name and sign-in name, only to someone who may list them: the people of an auth are named where the caller holds List, in the tenant, on the tenant's list of that auth's people (section 21) and, on no condition, on its username and name fields, and counted alone where the caller does not. Where the list is shorter than the count the sentence says so ("The one of them you may list is named here.", "The 3 of them you may list are named here."), so a part of them is never read as all of them, and where the caller may list nobody the warning carries no names and a page says how many without saying who. An application whose people no generated management lists counts nobody, and the sentence then gives no number ("Anyone seated here who signs in another way will lose access."): a count nobody made is never read as nobody. The warning is refused as the call is refused, with the same sentences, so a page that asks for it first shows the refusal and opens no dialog. For a tenant that is directory only already there is nothing to turn on, and the warning is a Conflict that says so and names neither the directory nor the people ("This tenant is directory only already: only people who sign in through its directory enter it. There is nothing to turn on."); who the flag keeps out now is the people list's to say, below. End<Record>DirectoryOnly declares no warning, and a request for one is refused (400) and does not run.

The switch as it stands is read in the tenant too: GET /<prefix>/<tenants>/{tenant}/directory-only answers {"directoryOnly": false} under the Execute grant of either method in the tenant, held without a condition (a read has no request for a condition to judge, so it is Forbidden under a grant that holds on one), and writes nothing (resource.DirectoryOnlyStateHandler). The tenant's administrator does not read the global record, and this is what a Sign-in page shows them. The browser client's directoryOnlyState(api, tenant) is the typed read, and the methods are handles of the tenant's client (api.domain(tenant).make<Record>DirectoryOnly, .end<Record>DirectoryOnly); the skeletons' Sign-in page runs each through the library's method dialog (openMethodDialog), which draws the warning with its list of people and the typed word, and turning the flag off is a plain confirmation.

The tenant's own list of its people (section 21) is made from who holds a role in the tenant, never from who can sign in, so a person the flag keeps out stays in it with their roles. Where the record declares the flag the list carries one more field, cannotEnter: while the tenant is directory only, the row of a person who has no sign-in through the tenant's directory says so ("Has not signed in through this tenant's directory, so cannot enter while this tenant is directory only"), and it is empty for everyone else and while the flag is off. It is empty too for an administrator of the tenant who has a password, who enters with it and a code sent to their email: the list, the count the warning gives and the sign-in agree on who that is (an administrator's role held in the tenant itself, by a membership of the person's own or through a group kept in the tenant, inside its period; the roles are the ones the permission engine was told, access.WithTenantAdministratorRoles). The list reads whether the person has a password and not whether a session of theirs carries the second factor, which is asked at the sign-in. The sentence speaks of the tenant's directory and does not name it: the list is a query, which reads the directory's connection and not what the sign-in registrations call it, and a connection is never said to a person. The library's People page shows it as a column ("Cannot enter") to a role that is granted the field, so the tenant's administrator sees who the flag keeps out for as long as it is on.

The default seat. What a person gets at their first sign-in through a tenant's directory is the directory row's to say, before the method's account rule is reached. The directories record may carry one more column, @directoryDefaultSeat (section 1), a nullable string naming a role of the tenant. A person no user exists for who signs in through a tenant's directory is created and seated with that role in the tenant, and signed in; where the row names none (NULL, the default, and every row of a record without the column), they are refused with the invitation_only refusal and no account is created, unless they followed an invitation link, which is the way past. A person whose account stood before, made by another tenant's invitation or before the tenant set its directory or named a role, is given the role too: the sign-in that links their account to the directory is their first through it, whether the directory's identity is linked at once or after their password confirmed it, and the link gives the default role where they hold no role in the tenant. Who is the directory's person is decided by how they signed in, the link between the account and the directory, never by their address. The role is given once for a link: a second sign-in finds the link and gives nothing, so a person whose role an administrator removes is not seated again by signing in, and an administrator who wants one person out removes the role and leaves the link, or disables the account. A link that is deleted and made again is a first sign-in again, and gives the default role where the person holds no role in the tenant. A person whose link was made before the tenant named a default role is given a role by hand. A directory no tenant has falls to what was chosen for the method (invite only, or open to sign-up: section 21, "Who may sign up"), and so does a personal account, which is no tenant's directory. The generator emits New<Record>DirectoryReader(), a signin.DirectoryReader[*spanner.ReadWriteTransaction] reading the tenant whose directory an identity came through with its seat in the sign-in's own transaction, and the application hands it, with the seat hook, to each auth whose roles are the application's own: authSession.SetDirectoryAdmission(settings.TenantDirectories, identityClient.DirectorySeated()). An auth whose directory names the roles (a registration that syncs them) sets no admission: its directory is the authority on who holds what, and a default seat would be overwritten at the next sign-in. The role is written the way an accepted invitation's roles are, by the Auth's generated identity client in the transaction that links the account to the directory (section 21, "At a sign-in"), so the link and its role are committed together or not at all, and the sign-in policy, which decides after the commit, finds the membership.

How a tenant admits its directory's people is the tenant's own to say, as the switch is: the column is output only on the wire, so the record's create and update never write it, and the generator writes two methods in the tenant's scope, served on every session outlet that serves the directories record. Open<Record>ToDirectory, at POST /<prefix>/<tenants>/{tenant}/open-<record>-to-directory with {"role": "Member"}, names the role, and Make<Record>InviteOnly, at POST /<prefix>/<tenants>/{tenant}/make-<record>-invite-only with {}, clears it, so an empty default seat is invite only, as it always was. A role file grants Execute on each to the role that manages the tenant's sign-in settings. Opening a tenant lets in people nobody named, so Open<Record>ToDirectory declares a warning (section 7), which a person confirms by typing open (resource.OpenToDirectoryWord). Its words are the server's, for the role as picked so far (TenantDirectoryRules.OpenToDirectoryWarning): "Anyone who signs in through acme.example will be able to enter this tenant without an invitation and gets the role Member.", under the button "Open to people who sign in through acme.example"; before a role is picked the sentence ends "Choose the role each of them gets." The directory is named as the directory-only warning names it, never by a connection that is an id. The role is held to what giving it by hand needs (identity.Manager.DirectoryRole, through the generated identity client): it is a role of the tenant ("... is not a role of this tenant: choose one of the roles the picker lists", 400), and the caller could give it there directly, by the grant of the method that gives a role in a tenant, conditions included (403, saying which role and what to do; the grant answers before the role is looked for, so the refusal is the same for a role the tenant holds and one it does not, and tells nobody of a role the grant keeps from them). A default role is given to people who are not known yet, so the grant is judged for no person: a grant whose condition reads the person a role is given to admits no default role. A tenant with no directory is refused (409): there is nobody to open it to. Make<Record>InviteOnly is plain and declares no warning. Each method writes the column through the directories record's update patch, so the record's change events are the audit of who opened the door and when. The role is picked from a list of its own, <Auth><Record>DirectoryRoles (Lodestar's CrewSectorDirectoryRoles), a computed resource the generated management declares for the auth that judges the role: the roles of the tenant that the caller could give there directly (identity.Manager.DirectoryRoles, which asks the same grant for each role), and no other. The browser metadata names it as the role's picker, so the library's method dialog offers each role the method would take, with its description, and none it would refuse; a role file grants List on it to the role that holds the method, and writes no condition on it, since the grant of the method that gives a role is what the list reads.

The role is judged through the generated management of one auth, so the two methods are written where the session outlets that serve the directories record are all of one auth, the program generates that auth's management (GenerateIdentity), and the auth's roles are given by hand. The judgment is the one a method opened to sign-up is held to (section 21, "Who may sign up"): the role file's grant of the method that gives a role, which the generated management answers (grants.go) for an auth whose directories record carries the default seat, as it does for one that keeps groups or opens its methods to sign-up. Where they are not, the program writes neither method, and the application sets the column in its own code. One consequence: while a method is open to sign-up, a colleague of a tenant's creator who signs in from the directory that tenant already has gets no account and no second tenant, but the invitation-only answer, or the tenant's default role where its row names one: the tenant's row decides before the method's does.

How a tenant comes to exist. Nobody creates a tenant directly. The tenant record's create operation is refused in the standalone patch handler and in the consolidated dispatcher (400, "a sector is not created directly: invite one person, and the sector is made when that person first signs in"), the record's metadata tells the browser client so (createDisabled, so the generic list draws no Create button and the client's handle has no create), and there are two ways a tenant is made, neither a declaration:

  • Staff invite one person. Where the record is served by session outlets of one auth, the program generates that auth's management and no directory writes its roles, the generator writes three pieces into that auth's management (section 21, "The invitation that makes a tenant"): Invite<Auth><Record>, which staff send with the person's address and the tenant's details; the list <Auth>Invited<Record>s of the invitations that still stand; and Withdraw<Auth>Invited<Record>. Sending one takes the method's grant and the Create grant on the tenant record, on the record and on each field the invitation carries. No tenant exists while the invitation waits. The first sign-in of the person who follows the mailed link makes the tenant from the details, under an id generated then, seats the person as its first administrator and, where they signed in through their organization's directory, makes that directory the tenant's own, in the transaction that consumes the invitation: all of it or none.
  • A person who signs up creates their own. Under the same conditions the generator writes the create-your-tenant route (POST <prefix>/create-<record>, no grant needed), which a signed-in person holding no tenant calls with the new tenant's fields. Whether anyone may is no declaration: the route reads, in the transaction that writes the row, whether an administrator has a sign-in method of the auth open to sign-up (section 21, "Who may sign up"), and refuses while every method is invite only. The same route answers GET with whether the caller may create one now ({"offered": true}, the generated client's Create<Record>Offered), by the two facts the creation refuses on: the caller holds no tenant, and a method is open. A page reads it before it offers the creation, so nobody is shown a dialog the server would refuse; the skeletons' home page shows its create-your-tenant card only while the answer is yes.

@tenant(creation: ...), which declared the choice in code, is refused at generation with these words. A record served by session outlets bound to different auths is refused at generation, since a tenant is made through one auth's client, and so is a program that does not generate that auth's management (GenerateIdentity). A record served by no session auth (a hand-written router, a machine outlet alone), or by an auth whose roles a directory writes, has neither way: its create answers "a sector is not created directly: the application makes one in its own code", and the application writes the row through the record's create patch in a transaction of its own, then reloads the roster.

The first administrator. The person who makes a tenant is its first administrator, whichever way it is made, and the tenant and the membership are committed together or not at all. An accepted invitation gives the person the roles that administer a tenant in the auth (identity.WithAdministratorRoles, the domain roles the auth names as its administrator's), written by the auth's generated identity client in the transaction that consumes the invitation. The create-your-tenant route gives its caller the roles <Record>AdministratorRoles() names (asserted against the application type in the generated file of the route), through the same client (<Auth>Identity().AssignRole, section 21), in the transaction that writes the tenant's row; a role that does not exist fails the creation. After the route's commit, and once this instance's roster lists the tenant, the answer waits until the permission engine answers the membership, so the person's next request stands in the tenant; an engine that does not answer within ten seconds is logged and the request answered, since the rows are committed.

The maker. What makes a tenant from an accepted invitation is generated beside the roster: New<Record>Maker(roster, liveService) in the handler package answers an identity.TenantMaker over the record's own create patch, so the record's rules apply to a tenant an invitation makes and its change event is written with it. The auth a tenant is made through takes it: that auth's generated NewClient has it as a required argument (section 21), and the application hands it in where it builds the auth, so the composition root builds the roster before that auth:

tenants := app.NewSectorRoster(db.ResourceClient, resource.WithTenantSignals(liveService))
crewAuth, err := crew.New(ctx, db.SpannerClient, &crew.Settings{
    // ...
    TenantMaker: app.NewSectorMaker(tenants, liveService),
})

The auth packages impulse renders carry the field (Settings.TenantMaker), refuse a nil one at the start with a sentence, and pass it to the client. Once the sign-in's transaction has committed, the maker has this instance's roster reread its table and signals the tenants kind, so the person's first request stands in the new tenant and every instance serves it at once.

Deleting a tenant. The record's generated delete clears what each auth holds for the tenant in the transaction that deletes its row, through the generated identity client of every auth whose management the program generates (<Auth>Identity().ClearTenant, identity.Manager.ClearTenant): every membership held in the tenant, the custom roles made in it with their grants, and the invitations into it that still stand, which are withdrawn. A person who held roles in the tenant alone then holds none anywhere and is deleted with their identity links and sessions, by the rule on an account nothing admits (section 21, "The rules"); a person who holds a role anywhere else stays, and so does a role held in every tenant, which is no one tenant's. The permission engine is told once the delete has committed. The rows the tenant owns are the application's: a foreign key on a tenancy column refuses the delete while they remain. An application that deletes a tenant in a transaction of its own calls ClearTenant there, and a program that generates no auth's management removes the memberships itself.

With the last-owner rule (section 21, "The rules") an operator brings a customer's tenant in by inviting its first administrator and holds no role in it: the tenant is its administrator's from its first moment, and is never left with nobody to give the next role.

Tests. The generated authorization matrix drives domain-scoped routes with one tenant, the generated router's TestDomain constant (an id's text), and the application's newTestHandler adds it to the test application's roster with Add (roster.Add(router.TestDomain)), since the empty schema holds no tenant row; under concealed domains a case with no grants has no foothold and is answered as if the domain did not exist.

17. The served browser app

A built browser application is served by one type, resource.BrowserApp, from the directory the build wrote into and under the mount path the application's router declares (generation.WebApp, section 8): / for the application at the root, /console for one under a path. NewBrowserApp(dir, mountPath) builds it, and the application's two handlers delegate to it, one line each:

// DeepLink rewrites the console's Angular routes to its entry document.
func (a *App) DeepLink(next http.Handler) http.Handler {
	return a.console.DeepLink(next)
}

// Assets serves the console's built Angular application.
func (a *App) Assets() http.HandlerFunc {
	return a.console.Assets()
}

The deep-link rule. A request whose last path segment has no extension, Angular matrix parameters (;key=value) removed, is an application route: DeepLink rewrites it to <mount>/index.html and passes it on, so a bookmarked or reloaded route loads the application. A path with an extension passes through unchanged and is a file or a 404. Assets strips the mount prefix, serves the file from the directory, and answers 404 for a missing file, a path outside the mount, and a directory; a directory is never listed.

Two cache classes, by file name. The build stamps most of its files with a content hash, eight uppercase letters or digits before the extension (main-ZPJWNJT4.js, chunk-3ANMYK5A.js, styles-A4ABYBXD.css, media/<name>-<hash>.woff2). Such a file answers Cache-Control: public, max-age=31536000, immutable: its name changes with its content, so the service worker and any cache between the browser and the server may keep it for a year without asking. Every other file answers Cache-Control: no-cache: index.html, ngsw.json, ngsw-worker.js, safety-worker.js, worker-basic.min.js, manifest.webmanifest, the favicon, the icons, prerendered-routes.json and 3rdpartylicenses.txt keep their names across builds, so a copy may be kept but must be revalidated before each use, and an unchanged file answers 304. The validator is a strong ETag over the file's content, beside Last-Modified, because the files ride in a container image whose modification times are the build's. The two classes are what make the worker safe under any cache: a cache that kept a stale ngsw.json or entry document would hand the worker a build whose hashed files the server no longer has, and a cache that asked again for every hashed file would make the worker's prefetch of a build cost a round trip per file. manifest.webmanifest answers Content-Type: application/manifest+json, which Go's type table lacks.

The kill switch. A build deployed without ngsw.json makes every installed worker unregister itself and drop its caches: the worker fetches ngsw.json after each page load and on each of its checks, and a 404 there is its signal to stand down, after which the page is served by the network alone.

18. Renaming a field or a method

A field or a method can change its name without breaking the browser applications already built against the old one. @formerly (section 1) keeps the old name answered beside the new one, and the outlet's oldest answered release (section 8) says when the old name can go.

What moves and what stays. The column never changes: @formerly moves the wire name only, so no migration runs and no row is rewritten. On a field, the generated request structs carry formerly:"<old wire name>" (section 3) and the runtime reads the old name as the new one: a create or patch body naming title writes the Headline column, a body naming both title and headline is refused with a 400 saying to send one, and columns=title, sort=title and filter=title:eq:... run against the live field with its permission checks. Every row carries both keys, headline and title, each masked when the field is. On a method, the router registers the former route on the same handler, so POST /console/api/release and POST /console/api/publish run the one method, and the generated router test drives both. The generated collection carries the former names (TagData.Formerly on a field, CollectionResource.Formerly on a method), and the permission digest mirrors a renamed field's or method's entry under its former name, so an application built before the rename keeps its column or its action. The TypeScript knows only the new name: an application built from it sends and reads headline, and only an application built before the rename still sends title.

Two releases. Release 1 renames the field and keeps the old name answered:

// @formerly(Title)
Headline string `spanner:"Headline"`

Applications built before release 1 keep sending title and keep working; applications built from release 1 send headline. Release 2 removes the annotation and raises the outlet's oldest answered release to release 1 (generation.OldestAnswered("1.0.0") where release 1 is 1.0.0): an application built before release 1 is answered with a 412 telling it to reload, and title leaves the wire. A method renames the same way, with @formerly(Release) on the Publish struct in release 1 and the annotation gone in release 2.

Cursors. A page cursor fingerprints its order by the Go field names (section 4), so a cursor an application holds across release 1 over an order that names the renamed field is refused once, and that list restarts from its first page; a cursor over any other order carries across.

19. Scheduled methods

A scheduled method is an RPC method Cloud Scheduler calls on a schedule, not a person: pruning old rows every night, sending a digest every morning. It is an @rpc struct with @schedule (section 1) and an Execute in either form, and it runs on the service itself; a schedule never starts a job process. Lodestar's:

// @rpc
// @schedule("30 3 * * *", zone: "America/Denver")
PruneDroidReports struct{}

What a scheduled method is. It takes no input, since the scheduler sends no body and names no row or tenant: the struct declares no field, and nothing that adds a path parameter or a body is admitted. It checks no permission and is in no outlet: the scheduler's token is its gate, so no role names it, the permission collection and the digest leave it out, and no TypeScript client carries it. Execute runs as the application, with no caller stamped on its context, so Enforce and Check refuse inside it and its queries and patches run trusted; it records its writes under a process (resource.ProcessEvent) rather than a person. The frame is a method's otherwise: the transaction form runs inside the handler's transaction, the rows it writes are published to the live pages after the commit, and it answers with its result or its chosen status (@answers), which the scheduler records as the call's success or failure. There is no dry run.

The route. The generated router mounts every scheduled method under one prefix it reserves, /_scheduled (scheduled.Prefix), one POST each at the method's name in kebab case: /_scheduled/prune-droid-reports. Its group is NoCaching, CompressionMiddleware and SchedulerAuth, and nothing else: no session handling, no XSRF guard, no version check, no hook. Under the prefix an unknown path is 404, as under an outlet's. No outlet's prefix and no browser application's mount path may sit at or under it; each is a generation error. The route tables carry GeneratedScheduledHandlers and generatedScheduledRoutes beside the outlets', Handlers embeds the one and declares SchedulerAuth(next http.Handler) http.Handler, the chain comment names the group, and the generated test drives each scheduled route through New behind exactly that chain. NewTestRouter does not mount them.

The check. The service is open to the load balancer, so Cloud Run's own permission check lets every caller through, and the check is the application's. Cloud Scheduler calls with an OpenID Connect token (an OIDC token: a JSON web token Google signs) minted for the invoker identity, a service account the application's stack creates for its schedules, with the route's URL as the token's audience. resource/scheduled holds the check: a Guard admits a call whose Authorization: Bearer token verifies against Google's signing keys (google.golang.org/api/idtoken: the signature and the expiry) for the audience https://<host the call names><path>, was issued by Google, and carries the invoker identity as its verified email. Any other call answers 401 Unauthorized, and the reason (no token, a token that does not verify for this URL, another issuer, an unverified email, another identity) is logged, never written into the answer. The stack hands the service the invoker's email in APP_SCHEDULER_INVOKER (scheduled.InvokerVariable), which the framework reads itself, as it reads APP_MAINTENANCE, so no configuration level declares it: scheduled.FromEnvironment(ctx) builds the guard when the application starts, and with the variable empty, as in development and in a pull-request stack, the scheduled routes are off, the start logs so, and every scheduled call is refused. The application's SchedulerAuth delegates to the guard (return a.scheduler.Middleware(next)); a nil guard refuses every call too. scheduled.NewFake() stands in for Google's keys in a test: a token it mints for a URL and an email is one Cloud Scheduler would present.

The schedule. The generator writes each scheduled route with its schedule and zone into the release file (section 8), and that is where the application's stack reads them: bedrock renders one Cloud Scheduler job per scheduled route in every environment, never in a pull-request stack, calling https://<the environment's canonical hostname><path> with a token of the invoker identity it creates, and sets APP_SCHEDULER_INVOKER on the service.

20. The provider drivers

The database, the live service and the job starter open through provider drivers, one package per provider in the shape the cloud driver set: resource/database/spanner and resource/database/postgres (the database), resource/live/firestore (the live service) and resource/jobs/cloudrun (the job starter), beside the cloud driver, cloud/gcp. Every driver exports the same names: Settings, the env-tagged variables it reads, which the application's configuration embeds; Open, which builds the driver from them; a Driver (the live driver's is its Service) with Close; and a declaration package beside it that publishes the settings' declaration for the tools that read an application without loading it (impulse's checks, bedrock's stack).

The application binds each driver under one neutral import alias, one per kind of driver: database, liveservice (live is the seam package, resource/live, which the same file imports), jobstarter (jobs is resource/jobs, the starter's interface) and cloud. Named so, the application names the vendor once, on the import line, and moving to another provider's driver is that line alone:

import database "github.com/impulseframework/impulse/resource/database/spanner"   // the only line that changes for PostgreSQL

type DatabaseSettings struct{ database.Settings }
db, err := database.Open(ctx, env.Database.Settings)

The wrappers the configuration declares follow the kind, not the vendor (DatabaseSettings and LiveSettings, the config fields Database and Live, the accessor Database(), LoadDatabaseSettings), and a local variable never shadows an alias (db, err := database.Open(...)). The two database drivers take the same Open (Open(ctx, settings, opts ...resource.ClientOption), the file store options of section 13), and the live driver resolves its own emulator project (firestore.EmulatorProject), so nothing but the import line differs between two applications on two providers. What stays vendor-specific is the Spanner client the database driver also holds (Driver.SpannerClient), which the session store and the permission engine open on until the PostgreSQL client lands; the data level names that seam in one comment. Lodestar (data.go, site.go) and the skeleton candidates are the examples.

21. User management: an auth's management as generated code

generation.GenerateIdentity(treeDir) writes the management of every Auth the program declares as code of the application: a resource declaration over each table the Auth keeps, and the methods that change them. The lists are read through the application's permission surface like any resource, each method is a route behind an Execute grant, and the same method is a Go call the application makes in a transaction of its own, so a person is created and seated beside the application's own rows and committed with them. The option requires GenerateRoutes and GenerateHandlers, and a program that declares at least one Auth. It is the user management of the whole application: accounts, roles, temporary passwords, the second factor's reset, lockouts and invitations. In an application with a tenant record it is also one tenant's management of the people who hold a role in it: the tenant's lists (its people, the roles held there, its invitations) and the methods the tenant changes them through, both below; and, for the Auth a tenant is made through, the invitation staff bring a tenant in by ("The invitation that makes a tenant", below).

The tree. treeDir (Lodestar's is pkg/identity) is the generator's alone. Per Auth it holds three packages, the crew Auth's being:

  • internal/crewresources: the declarations, with the query builders and patch types the generator writes for any resource, and beside them the views that are a tenant's lists, where the application has a tenant record. The package is internal to the tree, so no application code reaches a patch constructor: the compiler refuses the import.
  • crewidentity: the methods, each an @rpc struct whose Execute is one call into the framework's identity package, where the rules are, and the Client they run over.
  • crewhandlers: the generated frames of those resources and methods, over a Deps interface the application's handler type satisfies, constructed with the application's live derivations (crewhandlers.New(app, derivations)), which every frame publishes its commit with. It also holds the record of what changes the tenant's lists (crewhandlers.LiveDerivations), which the application's assembly merges into those derivations (section 14).

The generator writes the declarations and the methods before it loads the packages, so the same run extracts them as it extracts the application's own. From there they are resources and methods like any other: the route tables, the collection, the TypeScript client, the generated authorization matrix and the role-file validation carry them with no further declaration. A Go file in the tree that the generator did not write refuses the run. The packages an earlier run wrote for an Auth the program no longer declares are removed, so an Auth taken out of the program, or renamed, leaves nothing to clear by hand. A tree belongs to one program, since a run removes what it does not write: impulse check refuses two programs naming one tree, and holds every file under a tree to the regeneration.

The routes, for an Auth in the package crew, under the prefix of the Auth's own outlet and of every outlet that declares Manages on it. A resource is declared where the schema holds its table, so an Auth that issues no tokens has no tokens list:

GET  <prefix>/crew-session-users, …/{id}                   List, Read on CrewSessionUsers (sort=username)
GET  <prefix>/crew-sessions, …/{id}                        List, Read on CrewSessions (newest first)
GET  <prefix>/crew-session-identities, …/{id}              List, Read on CrewSessionIdentities
GET  <prefix>/crew-sign-in-ways?filter=userId:eq:{id}      List on CrewSignInWays (how one person signs in: the password, then the identities that count)
GET  <prefix>/crew-session-tokens, …/{id}                  List, Read on CrewSessionTokens
GET  <prefix>/crew-session-mail-links, …/{id}              List, Read on CrewSessionMailLinks
GET  <prefix>/crew-session-impersonations, …/{sessionId}   List, Read on CrewSessionImpersonations
GET  <prefix>/crew-session-trusted-devices, …/{id}         List, Read on CrewSessionTrustedDevices (the remembered browsers)
GET  <prefix>/crew-session-sign-in-attempts                List on CrewSessionSignInAttempts
GET  <prefix>/crew-session-auth-events                     List on CrewSessionAuthEvents
GET  <prefix>/crew-user-roles                              List on CrewUserRoles (the role memberships)
GET  <prefix>/crew-roles                                   List on CrewRoles (the custom roles)
GET  <prefix>/crew-role-grants                             List on CrewRoleGrants
GET  <prefix>/crew-groups, …/{id}                          List, Read on CrewGroups (the groups of people, sort=name)
GET  <prefix>/crew-group-members                           List on CrewGroupMembers
GET  <prefix>/crew-group-roles                             List on CrewGroupRoles (the roles the groups hold)
GET  <prefix>/crew-group-users, …/{id}                     List, Read on CrewGroupUsers (the people of the groups, with their names)
GET  <prefix>/crew-user-group-roles, …/{id}                List, Read on CrewUserGroupRoles (the roles people hold through a group)
GET  <prefix>/crew-sign-in-methods                         List on CrewSignInMethods (the methods the Auth registers, with what was chosen for each)
GET  <prefix>/crew-invited-sectors                         List on CrewInvitedSectors (the invitations that make a sector and still stand)
GET  <prefix>/sectors/{sectorID}/crew-sector-users, …/{id}         List, Read on CrewSectorUsers (sort=username)
GET  <prefix>/sectors/{sectorID}/crew-sector-user-roles, …/{id}    List, Read on CrewSectorUserRoles (sort=username,role)
GET  <prefix>/sectors/{sectorID}/crew-sector-invitations, …/{id}   List, Read on CrewSectorInvitations (newest first)
GET  <prefix>/sectors/{sectorID}/crew-sector-identities, …/{id}    List, Read on CrewSectorIdentities (newest first)
GET  <prefix>/sectors/{sectorID}/crew-sector-sign-in-ways?filter=userId:eq:{id}   List on CrewSectorSignInWays (how one of the sector's people signs in)
GET  <prefix>/sectors/{sectorID}/crew-sector-groups, …/{id}             List, Read on CrewSectorGroups (the sector's own groups)
GET  <prefix>/sectors/{sectorID}/crew-sector-group-users, …/{id}        List, Read on CrewSectorGroupUsers
GET  <prefix>/sectors/{sectorID}/crew-sector-group-roles, …/{id}        List, Read on CrewSectorGroupRoles
GET  <prefix>/sectors/{sectorID}/crew-sector-user-group-roles, …/{id}   List, Read on CrewSectorUserGroupRoles
POST <prefix>/create-crew-user                {"username","name","email","password","roles","domain","everyDomain"} → {"id"}   Execute on CreateCrewUser
POST <prefix>/rename-crew-user                {"userId","username"}            Execute on RenameCrewUser, targeting CrewSessionUsers
POST <prefix>/delete-crew-user                {"userId"}                       Execute on DeleteCrewUser, targeting CrewSessionUsers
POST <prefix>/set-crew-user-name              {"userId","name"}                Execute on SetCrewUserName, targeting CrewSessionUsers
POST <prefix>/set-crew-user-email             {"userId","email"}               Execute on SetCrewUserEmail, targeting CrewSessionUsers
POST <prefix>/set-crew-temporary-password     {"userId","password"}            Execute on SetCrewTemporaryPassword, targeting CrewSessionUsers
POST <prefix>/revoke-crew-user-trusted-devices {"userId"}                      Execute on RevokeCrewUserTrustedDevices, targeting CrewSessionUsers
POST <prefix>/unlock-crew-sign-in             {"name"}                         Execute on UnlockCrewSignIn, targeting CrewSessionSignInAttempts
POST <prefix>/invite-crew-user                {"email","name","roles","domain"} → {"id","sent"}   Execute on InviteCrewUser
POST <prefix>/withdraw-crew-invitation        {"invitationId"}                 Execute on WithdrawCrewInvitation, targeting CrewSessionMailLinks
POST <prefix>/invite-crew-sector              {"email","name","sectorName",…,"sectorDirectoryOnly","defaultRole"} → {"id","sent"}   Execute on InviteCrewSector, and Create on Sectors
POST <prefix>/withdraw-crew-invited-sector    {"invitationId"}                 Execute on WithdrawCrewInvitedSector
POST <prefix>/disable-crew-user               {"userId"}                       Execute on DisableCrewUser, targeting CrewSessionUsers
POST <prefix>/enable-crew-user                {"userId"}                       Execute on EnableCrewUser, targeting CrewSessionUsers
POST <prefix>/end-crew-user-sessions          {"userId"}                       Execute on EndCrewUserSessions, targeting CrewSessionUsers
POST <prefix>/require-crew-password-change    {"userId"}                       Execute on RequireCrewPasswordChange, targeting CrewSessionUsers
POST <prefix>/end-crew-session                {"sessionId"}                    Execute on EndCrewSession, targeting CrewSessions
POST <prefix>/end-crew-session-impersonation  {"sessionId"}                    Execute on EndCrewSessionImpersonation, targeting CrewSessionImpersonations
POST <prefix>/unlink-crew-session-identity    {"identityId"}                   Execute on UnlinkCrewSessionIdentity, targeting CrewSessionIdentities
POST <prefix>/remove-crew-password            {"userId"}                       Execute on RemoveCrewPassword, targeting CrewSessionUsers
POST <prefix>/revoke-crew-session-token       {"tokenId"}                      Execute on RevokeCrewSessionToken, targeting CrewSessionTokens
POST <prefix>/assign-crew-role                {"userId","role","domain","everyDomain"}   Execute on AssignCrewRole
POST <prefix>/remove-crew-role                {"userId","role","domain","everyDomain"}   Execute on RemoveCrewRole
POST <prefix>/create-crew-group               {"name","description","domain"} → {"id"}   Execute on CreateCrewGroup
POST <prefix>/describe-crew-group             {"groupId","description"}        Execute on DescribeCrewGroup, targeting CrewGroups
POST <prefix>/delete-crew-group               {"groupId"}                      Execute on DeleteCrewGroup, targeting CrewGroups
POST <prefix>/add-crew-group-member           {"groupId","userId"}             Execute on AddCrewGroupMember, targeting CrewGroups
POST <prefix>/remove-crew-group-member        {"groupId","userId"}             Execute on RemoveCrewGroupMember, targeting CrewGroupUsers
POST <prefix>/give-crew-group-role            {"groupId","role","domain","everyDomain"}   Execute on GiveCrewGroupRole, targeting CrewGroups
POST <prefix>/take-crew-group-role            {"groupId","role","domain","everyDomain"}   Execute on TakeCrewGroupRole
POST <prefix>/open-crew-sign-up               {"name"}                         Execute on OpenCrewSignUp (declares a warning; {"name","defaultRole"} without tenants)
POST <prefix>/make-crew-invite-only           {"name"}                         Execute on MakeCrewInviteOnly
POST <prefix>/sectors/{sectorID}/create-crew-sector-user   {"username","name","email","password","roles"} → {"id"}   Execute on CreateCrewSectorUser
POST <prefix>/sectors/{sectorID}/invite-crew-sector-user   {"email","name","roles"} → {"id","sent"}                  Execute on InviteCrewSectorUser
POST <prefix>/sectors/{sectorID}/withdraw-crew-sector-invitation   {"invitationId"}     Execute on WithdrawCrewSectorInvitation, targeting CrewSectorInvitations
POST <prefix>/sectors/{sectorID}/assign-crew-sector-role   {"userId","role"}            Execute on AssignCrewSectorRole, targeting CrewSectorUsers
POST <prefix>/sectors/{sectorID}/remove-crew-sector-role   {"userId","role"}            Execute on RemoveCrewSectorRole, targeting CrewSectorUserRoles
POST <prefix>/sectors/{sectorID}/unlink-crew-sector-session-identity   {"identityId"}   Execute on UnlinkCrewSectorSessionIdentity, targeting CrewSectorIdentities
POST <prefix>/sectors/{sectorID}/remove-crew-sector-password           {"userId"}       Execute on RemoveCrewSectorPassword, targeting CrewSectorUsers
POST <prefix>/sectors/{sectorID}/create-crew-sector-group          {"name","description"} → {"id"}   Execute on CreateCrewSectorGroup
POST <prefix>/sectors/{sectorID}/describe-crew-sector-group        {"groupId","description"}   Execute on DescribeCrewSectorGroup, targeting CrewSectorGroups
POST <prefix>/sectors/{sectorID}/delete-crew-sector-group          {"groupId"}          Execute on DeleteCrewSectorGroup, targeting CrewSectorGroups
POST <prefix>/sectors/{sectorID}/add-crew-sector-group-member      {"groupId","userId"} Execute on AddCrewSectorGroupMember, targeting CrewSectorGroups
POST <prefix>/sectors/{sectorID}/remove-crew-sector-group-member   {"groupId","userId"} Execute on RemoveCrewSectorGroupMember, targeting CrewSectorGroupUsers
POST <prefix>/sectors/{sectorID}/give-crew-sector-group-role       {"groupId","role"}   Execute on GiveCrewSectorGroupRole, targeting CrewSectorGroups
POST <prefix>/sectors/{sectorID}/take-crew-sector-group-role       {"groupId","role"}   Execute on TakeCrewSectorGroupRole, targeting CrewSectorGroupRoles
POST <prefix>/sectors/{sectorID}/disable-crew-sector-user, enable-…, delete-…, rename-…, set-crew-sector-user-name, set-crew-sector-user-email,
     set-crew-sector-temporary-password, require-crew-sector-password-change, revoke-crew-sector-user-trusted-devices,
     end-crew-sector-user-sessions            the whole application's bodies                Execute on each, targeting CrewSectorUsers

The names are table-derived: the Auth's package name in PascalCase and the library's own name for the table, with the tenant record's name between them for a tenant's list (Sector in the ones under the domain pair, which exist only where the application has a tenant record). Every resource over a table is global, none has a write route, and none carries a password hash or a token hash: no declaration has such a field. A method that targets a resource is listed in that resource's rows' Execute answer (capabilities=Execute), so a page draws its buttons from the row. The Auth's shape decides which methods exist: the two role methods, the two invitation methods, the create, and the list and the two methods of the sign-in methods ("Who may sign up", below) are left out for an Auth whose roles a directory writes (SyncsRoles), where the directory admits its own members and the first sign-in creates the row, the two password methods (and the create's password) for an Auth with no password method, as are the method that removes a person's password and the list of how a person signs in, which are also written only where the schema holds the identities table (the rule they keep reads a person's identity links), the rename and the address set by hand for an Auth whose usernames are the addresses (UsernameIsEmail: the name is the address, and it changes when the person verifies a new one), and the token, impersonation, remembered-browser and unlock methods where the schema holds no such table. The list of invited tenants and its two methods are written for one Auth, the one a tenant is made through ("The invitation that makes a tenant", below). A tenant's method is written where the whole application's method of the same act is, and the list whose rows it names is declared. The roles table is declared too (CrewRole): the custom roles, which the role rule below reads, served as a list. An application's own resource or method under one of these names is refused at generation, as is a resource field named for a method of the generated set (Resource, DefaultConfig, FileKeys, SearchBranches).

A tenant's lists. An account is one row for the whole application, and a role held is a row that names where it is held, so neither table can be served under a tenant's address. In an application with a tenant record (@tenant) the generated management declares four views per Auth, each a tenant record like any other (@virtual, @permissionScope(domain), the tenant in a domain column), listed and read under the domain pair on the outlets that serve the Auth's management. The whole application's lists carry the names of their tables; a tenant's list is named for what it holds, with the Auth's name and the application's tenant record's before it. A tenant record whose name would give a list the name of one of the tables' declarations (a record named Session or User) is refused at generation:

  • CrewSectorUsers, the tenant's people: one row per person who holds a role in the tenant or in every tenant, keyed by the account's id, with the columns of CrewSessionUsers. A person who holds a role in two tenants is a row in each. Two facts: heldElsewhere (the person also holds a role outside this tenant's own: in another tenant, or in every tenant) and heldGlobally (the person holds a role for the whole application).
  • CrewSectorUserRoles, the roles held there: one row per person and role, keyed by the account's id and the role (userId, role), with username and createdAt. Two facts: role, the role itself, and everyDomain, true where the role is held there through a membership in every tenant alone, so it is not the tenant's to take away. A role held both ways is the tenant's own row.
  • CrewSectorInvitations, the tenant's invitations: the mail links of the invitation kind that name the tenant, with email, roleNames, invitedByUserId, createdAt, expiresAt and consumedAt. Two facts: pending, true while the invitation stands (not accepted, not withdrawn, not expired), and role, the roles it gives: a list, so a condition that reads it is judged once for each role and holds only when it holds for every one (section 2, @attribute on a list column).
  • CrewSectorIdentities, the identities of the tenant's people: one row per identity link of a person of the first list, keyed by the link's id, with the columns of CrewSessionIdentities (tenant is the link's own, the organization its directory vouched for), the person's userId and username, and the person's two facts, heldElsewhere and heldGlobally. The identity of a person who holds a role in two tenants is a row in each. A person's page lists their identities by userId.

Each fact is a column of the view under a bare @attribute, so a grant's condition reads it by name, and the role file says what a tenant's administrator sees of a person who is not the tenant's alone. Lodestar's Sector Marshal sees every person of the sector and their address only where the sector holds them alone, and its Dispatcher the roles the sector itself gave:

"List": [
  { "resource": "CrewSectorUsers", "fields": ["username", "disabled", "createdAt", "lastSignInAt", "heldElsewhere", "heldGlobally"] },
  { "resource": "CrewSectorUsers", "fields": ["email", "emailVerifiedAt", "passwordChangeRequired"], "condition": "heldElsewhere = false" }
]
"List": [{ "resource": "CrewSectorUserRoles", "fields": ["username", "role"], "condition": "everyDomain = false" }]

So an application where a tenant owns its people and one where the people are shared between tenants are two role files over the same lists. A grant names its fields, as on any view: a grant with none answers the key alone. The people's list filters and sorts by username and by the two facts; the account's other columns are no filter keys, so a grant may carry any of them under a condition at no cost to a page.

A view is a query the framework selects from (FROM (<query>) AS <Resource>), not a database object: nothing is created in the schema and nothing is migrated. The generator writes each view beside the tables it reads, with its query as a constant of the file, which reads the Auth's memberships, its users, identities or mail links, and the tenant record's table (a membership held in every tenant is a row in each). A membership names its person by the id of their account, and the join finds the account by the users table's key. The generator reads the tenant record before it loads the packages, off the syntax of the resources package and the schema, since the views are written before the load: a tenant record whose table the schema does not hold is refused there. A list is written only where the schema holds the tables it reads, so an Auth with no mail links table has no invitations list, and one that links no identities has no identities list. The lists are published like any view (section 14): a role given, a person created or disabled, or an invitation written through the generated methods reaches the pages that have a tenant's list open.

What a request of these lists reads. The people's list, the roles held and the identities read the tenant's memberships and then the account of each person: one row of the users table, found by its key, since a membership names its person by the id of their account. The identities and the invitations are read from two indexes of the Auth's schema that carry the columns the lists show (the identities by user, the mail links by tenant, newest first). The database joins before it cuts the page, so the cost follows the size of the tenant and not of the page or of the application.

The lists were measured on Cloud Spanner over 1.07 million users in 2,200 tenants on 2026-11-15, on the smallest instance (100 processing units). A first page of people took 12 ms for a tenant of 100, 18 ms for 500, 89 ms for 5,000 and 0.75 s for 50,000, and a count about the same; the roles held 10 ms, 34 ms, 0.1 s and 0.8 s; the identities 0.17 s for a tenant of 100 and 2 s for 50,000. Each reads the tenant's memberships and one account row per person: no request reads the users table whole, and the rows read are those of the tenant, at any size of the application. (Read through an index by username, when a membership named its person by username, the people took 0.45 s at 50,000 and the roles and identities longer.) The invitations read their own page from the index (26 rows at any size). Three costs are worth knowing. A filter on heldElsewhere or heldGlobally, or a grant on the list whose condition reads one and so holds every row to it, costs two index reads for each person of the tenant (seconds at 50,000 people; a condition on a field costs them for the page's rows alone). A row of the roles held is keyed by the user's id and the role, two columns the database looks up, so a read of one row, and the check a method makes of the role it names, reads the one person's memberships (2 to 4 ms and three rows at 50,000 people; a key that joined the two in one value could not be looked up, and the same read joined the tenant's memberships, about a second there). And a schema applied by hand without those two indexes serves the identities and the invitations by reading their tables whole.

The roles a tenant picks from. Where a tenant gives roles by hand, the generated management declares one more list per Auth, CrewSectorRoles: the roles that exist in the tenant, each with its name and description. They are the tenant roles of the role file, the custom roles held in the tenant, and the custom roles held in every tenant; a role of the whole application and another tenant's custom role are not among them. It is a computed resource (@computed, section 2), declared beside the methods: the role file's roles are held by the permission engine and only a custom role is a row of a table, so its list function asks the engine (identity.Manager.TenantRoles) and no query selects it. It serves a list and no read, under the domain pair, and the role file grants it like any resource.

The role field of each method a person gives a role with in a tenant names the list (@enumerate): AssignCrewSectorRole, the create and the invitation that start a person with a role (CreateCrewSectorUser, InviteCrewSectorUser), and GiveCrewSectorGroupRole. A page draws the field as a picker, and a page offers what the caller may do, so the list holds the roles the caller could give and no other. A role file says which roles a person hands out once, on the methods' Execute grants, where a condition reads the role:

"Execute": [{ "resource": "AssignCrewSectorRole", "condition": "new.role != 'SectorMarshal'" }]

For each role of the tenant the list asks the grant of every one of those methods, with the role and nobody named (identity.Manager.RolesToGive, which asks the generated CouldGive of identity.RoleGrants), and leaves out a role every one of them refuses the caller: Lodestar's Sector Marshal is offered every role of the sector but the Marshal's own. A grant whose condition also reads the row the method names (the person, the group) could admit the role for some of them, so the role is offered and the method decides. One list serves all four pickers, so it holds a role that one method takes and another refuses, which the method then says; a role file that gives the methods the same limit, as Lodestar's does, has a picker that offers exactly what each takes. A request that names a role the list left out is refused by the method's own grant, as before.

The list's own List grant may carry a condition too, which narrows it further. The role's name is declared for conditions (@attribute(name) on the field), and the library judges the condition over each role the list answers (a computed resource's rows, section 2); a request for the names alone and the list's count are trimmed the same way. Lodestar keeps one, which says nothing its methods' grants do not, to show a condition judged over a computed resource's rows:

"List": [{ "resource": "CrewSectorRoles", "fields": ["description"], "condition": "name != 'SectorMarshal'" }]

An Auth whose directory writes the roles gives none by hand and has no such list. The roles of the whole application are given by a field a person types, with no list to pick from, and the two other lists a role is picked from are limited the same way: the default role of a method opened to sign-up (CrewSignUpRoles) and the role a tenant is opened to its directory's people with (CrewSectorDirectoryRoles) each hold the roles the caller may give by the method that gives one (MayGive).

A tenant's methods. Beside the lists the generated management writes the methods a tenant changes its people through. Each is a method of the tenant's scope (@permissionScope(domain)), served under the domain pair behind an Execute grant of the tenant's roles, and is named as the whole application's method with the tenant record's name after the Auth's: DisableCrewSectorUser beside DisableCrewUser.

  • The tenant is the one the request was made under. No body carries a tenant, so no request names another: the create and the invitation have no domain, and a role is given and taken in that tenant alone. A tenant's method acts for a request, so one run in a transaction of the application's own, outside any request, is an error: there the application runs the whole application's method and names the tenant.
  • A method that names something names a row of one of the tenant's lists (@target on the view): a person by their row of CrewSectorUsers, a role held by its row of CrewSectorUserRoles (userId and role, the two columns of the row's key, each a @target field naming the column it carries), an invitation by its row of CrewSectorInvitations, an identity by its row of CrewSectorIdentities. The frame locates the row within the tenant, so a person who holds no role there, or an invitation into another tenant, is not found (404), and it judges the grant's condition against the row. The method joins the row's Execute answer, so a page draws a row's buttons from the row.
  • A role is given to a person who holds one in the tenant already (AssignCrewSectorRole, its role picked from CrewSectorRoles); a person new to the tenant is created in it or invited to it, holding a role from the start. A role held in every tenant alone is a row of the tenant's list and is not the tenant's to take: RemoveCrewSectorRole refuses it (409) whatever the role file says.
  • The rules are the whole application's, in the same code: nobody disables or deletes their own account, the tenant's last administrator keeps the role, a rename moves the roles, the last role a person holds anywhere takes the account with it, a create and an invitation give at least one role. A refusal that speaks of a tenant says the application's word for one, the tenant record's label or its name in words ("you are the last administrator of this sector"): the generated client hands it to the rules (identity.WithTenantWord).

What a tenant may do to a person who also holds a role outside it, and which roles its administrator hands out, the role file says, in the conditions of the Execute grants: over the facts of the row, and over the request's own fields (new.role, section 2's @attribute on a field of an @rpc struct). Lodestar's Sector Marshal acts on the account of a person the sector holds alone, gives every role but the Marshal's own, takes a role away where the sector itself gave it, and withdraws an invitation that stands and gives no Marshal's role:

"Execute": [
  { "resource": "DisableCrewSectorUser", "condition": "heldElsewhere = false AND heldGlobally = false" },
  { "resource": "AssignCrewSectorRole", "condition": "new.role != 'SectorMarshal'" },
  { "resource": "CreateCrewSectorUser", "condition": "new.role != 'SectorMarshal'" },
  { "resource": "RemoveCrewSectorRole", "condition": "role != 'SectorMarshal' AND everyDomain = false" },
  { "resource": "WithdrawCrewSectorInvitation", "condition": "pending = true AND role != 'SectorMarshal'" }
]

A grant with no condition on an account method lets a tenant's administrator rename, disable or delete a person another tenant also holds: the account is one row for the whole application. roles is a list, judged role by role, and a create or an invitation with no role is refused by a grant that reads new.role, since no value never permits. The roles of an invitation's row are a list too, judged the same way: an invitation the whole application's administrator sent in the Marshal's role, alone or among others, is not the Marshal's to withdraw, and its row's Execute answer leaves the withdrawal out.

The invitation that makes a tenant. Nobody creates a tenant directly (section 16, "How a tenant comes to exist"): staff bring an organization in by inviting one person, and that person's first sign-in makes the tenant. The generator writes the three pieces into the management of one Auth, the one a tenant is made through: its people are the ones the tenant record's session outlets sign in, the application gives its roles (no directory writes them), and the schema holds its mail links and its memberships. The Auth's mail links table carries the column the invitation keeps the tenant in (NewTenant STRING(MAX), which the session migration impulse renders has), and a schema without it is refused at generation, naming the column.

  • Invite<Auth><Record> (InviteCrewSector) sends one. Its request is the person's address (email), the name the sender gives them (name), and the tenant record's own fields, each named for the record (sectorName, sectorRegion, sectorEstablished), required where the record's create requires them, so the form a page draws from the method is the record's own. Where the record declares @directoryOnly the request carries the switch (sectorDirectoryOnly), and where the directories record carries @directoryDefaultSeat it carries the role the people of the tenant's directory start with (defaultRole). It answers the invitation's id and whether its message went ({"id","sent"}); an invitation whose message did not go is withdrawn, so no link stands that nobody holds.
  • <Auth>Invited<Record>s (CrewInvitedSectors) lists the invitations that make a tenant and still stand: not one that was accepted or withdrawn, not one that expired, and not an invitation into a tenant that exists. A row carries the address, the person's name, the details, the switch, the starting role, who sent it and when it was sent and expires. The list is its own grant, and a detail of the tenant is in a row only for a caller who may list that field on the tenant record: a caller who lists a sector's name alone reads the name the invitation carries and none of its other details.
  • Withdraw<Auth>Invited<Record> (WithdrawCrewInvitedSector) withdraws one by its id (204), and answers 404 for anything but an invitation that makes a tenant and still stands. An invitation is not edited: staff who want other details withdraw it and send another.

Sending is held to what the sender could have done by creating the tenant. Beside the method's own grant it takes the Create grant on the tenant record, on the record and on each field the invitation carries, with every condition: the details are run through the record's own create, armed with the sender, in a transaction that is rolled back, so a rule the record's create applies is applied when the invitation is sent, and the answer goes to the person who can correct it. The starting role is a role the sender could give a person directly. A value the record keeps unique in a single column that takes no NULL (the name, under the skeletons' index) is looked up when the invitation is sent and again when it is accepted, and one that is taken is refused with a sentence (409, "a sector with the name Anvil already exists: give the new one another"). The lookup runs once the sender's grants have answered, so the refusal tells nobody who may not create a tenant which values are taken. A rule the database alone applies at a commit, a CHECK constraint or a unique index over several columns, is not seen when the invitation is sent: it refuses the commit of the first sign-in, nothing is made, and the invitation stands for staff to withdraw. Two invitations may wait with the same new name: the first acceptance takes it, and the second is refused at its first sign-in the same way.

What an invitation says beyond the record's fields, the switch and the starting role, no Create grant covers. A role file withholds either by a condition on the method's own grant, which reads each as the attribute its field declares (@attribute(directoryOnly), @attribute(role)): a role that may invite but not close a tenant to its directory is granted Invite<Auth><Record> where new.directoryOnly = false.

No invitation carries a secret. A field the wire cannot write is not among the details, and neither is a secret field (section 23) or a write-only one: a tenant made by invitation is given such a value afterward, by its administrator. A tenant record whose create requires one, a column that takes no NULL and has no default, is refused at generation where an Auth invites, with what to do: let the column take NULL or give it a default.

While the invitation waits no tenant exists and nothing of it is public. The mailed message names the application and carries the link, and says nothing of the tenant. The invitation page, which a person not signed in reads (POST <prefix>/user/invitation, the session library's), is told that the invitation makes a tenant (newTenant), what people will call it (tenantName), the invited address, whether it is accepted through a directory only (directoryOnly) and whether an account with a password is offered (signUp), and none of the other details.

The first sign-in of the person who follows the link makes the tenant, in the transaction that consumes the invitation: the tenant's row through the generated maker (New<Record>Maker, over the record's create patch, so its change event is written), the person's membership in the roles that administer a tenant (identity.WithAdministratorRoles), and, where they signed in through their organization's directory, that directory as the tenant's own with the starting role the invitation names. All of it commits or none does.

  • Accepted with a password, the tenant has no directory.
  • An invitation that says directory only is accepted through an organization's directory alone. Its page offers no account with a password, and a sign-up with one, or a sign-in with a personal account, is refused with what to sign in with (organization_account_required); nothing is made and the invitation stands. Accepted through a directory, the tenant is made directory only with that directory as its own: the one case in which a tenant is directory only from the start.
  • A directory belongs to one tenant, so a first sign-in through a directory another tenant has is refused (organization_has_tenant), the person told their organization is already set up and whom to ask; nothing is made and the invitation stands.

The person enters nothing and changes nothing by accepting: the details are the sender's. After the commit the instance that took the sign-in rereads its roster and signals the tenants kind, so the person's next request stands in the new tenant and every instance serves it.

Groups of people. Where the schema holds the permission store's three group tables under the Auth's prefix (CrewGroups, CrewGroupMembers, CrewGroupRoles; the store's DDL() has them), the generated management serves the Auth's groups. A group holds roles the way a person does, and a person put in a group holds the group's roles wherever the group holds them, at their next request, until they leave the group or the group loses the role. The permission engine folds a group's roles into its members when it compiles its snapshot, so a check, a sign-in, a tenant's list of its people and the picker of a person's tenants all see through a group with nothing more said. An Auth whose roles a directory writes (SyncsRoles) keeps no groups, whatever tables the schema holds: the directory's own groups do that job. The three tables are migrated together, and a schema holding some of them is refused at generation.

  • A group is kept for the whole application or in one tenant. A tenant's group is made and managed under the tenant's address by the tenant's own roles, holds any account, and holds roles in that tenant alone. A group kept for the whole application is managed by the whole application's methods and holds a role in the global scope, in one tenant or in every tenant; no tenant's group is ever given a role in another tenant (400).
  • A tenant puts its own people in its groups. The tenant's method (AddCrewSectorGroupMember) takes a person the tenant already has, a row of its list of people (CrewSectorUsers), and answers 404 for any other id, an account or not: a tenant's administrator pulls no account into the tenant through a group, and the answer says nothing of who belongs elsewhere. An account from outside the tenant is put in a tenant's group by whoever manages the whole application's people, with the whole application's method (AddCrewGroupMember), which takes any account and any group.
  • A group gives nobody a power that giving the role directly would not. A change to a group is a change to what people hold, so it is judged as the role changes it makes, beside the grant of the group's own method, which says who manages groups at all. Putting a person in a group needs what giving that person each role the group holds, where it holds it, needs. Taking a person out needs what taking each of those roles from them needs. Giving a group a role needs what giving it to each person in the group needs, and taking a role from a group what taking it from each of them needs. What a role change needs of the caller is the role file's to say, in the grants of the methods that give a role and take one away (AssignCrewRole, RemoveCrewRole; for a request made under a tenant the tenant's own, AssignCrewSectorRole and RemoveCrewSectorRole). The generated package asks the permission engine for the caller's grant on that method with the role in question (crewidentity's grants.go, its answer to identity.RoleGrants, over resource.Caller.ExecuteGate), so a condition on the grant is read as it is for the method itself: where the role file grants a sector's marshal AssignCrewSectorRole with new.role != 'SectorMarshal', the marshal puts nobody in a group that holds SectorMarshal, whatever the grant on AddCrewSectorGroupMember says. A change the caller could not make directly is refused (403), naming the role. A place or a group's role whose period has ended gives nobody anything and is not judged; one that has not begun is. A method the application runs in a transaction of its own, outside any request, is the application's act and is not judged.
  • Taking a role away from a person removes the membership of their own. What they hold through a group stays, and goes when they leave the group or the group loses the role.
  • No group holds the Super Administrator role (400): a super administrator gives it to one person at a time, so a group is no way around the rule that only a super administrator makes another. The methods a super administrator always executes stay the two that give and take a person's own role.
  • A group that still has a member or holds a role is not deleted (409): empty it first. Nobody loses a role because a group was deleted. Deleting a tenant removes the tenant's groups with their members and roles, and every role a group of the whole application holds in it (ClearTenant); deleting a person takes them out of their groups.
  • A place in a group keeps an account as a role of the person's own does: a person whose last role is taken away stays while they are in a group, and a person taken out of their last group who holds no role is deleted with their identity links and sessions. Where a person belongs to one tenant (identity.WithOneTenantPerPerson()), a place in a tenant's group counts as a role in that tenant.
  • The declaration over the members table declares a subject set, the ids of the groups the caller is in: subject.groups (section 2, @subjectSet). Every list over groups carries the group's id under the attribute group, so a role file holds a grant to the caller's own groups (group IN subject.groups: Lodestar's sector crew see the groups they are in and the people in them), and a table of the application's own whose rows name a group follows a person through it in a set of its own (who: GroupID IN subject.groups). An application with several Auths that keep groups has one set for each, named for its Auth (subject.crewGroups, subject.staffGroups), since subject.<name> is one namespace for the application. The set holds every group the caller is in, whichever tenant keeps it: a group's id names one group in the whole application, so a tenant's group counts in a condition wherever a row names it, and a tenant's rows name a tenant's groups by the picker the application offers.

The lists: CrewGroups (the groups, with where each is kept), CrewGroupUsers (the people of the groups, with their names), CrewGroupRoles (the roles the groups hold) and CrewUserGroupRoles (the roles people hold through a group, which stands beside CrewUserRoles, the roles each holds themselves, so a page says which is which). A tenant has its own four (CrewSectorGroups, CrewSectorGroupUsers, CrewSectorGroupRoles, CrewSectorUserGroupRoles): the first three hold the tenant's own groups, and the last every role a person holds in the tenant through a group, with globalGroup where the group is the whole application's and so not the tenant's to change. A group of the whole application that holds a role both in the tenant and in every tenant is one row there, the one that counts now: the tenant's own row gives way while it has not begun and the one held in every tenant counts. The lists of what people hold leave out a row the engine gives nobody (the Super Administrator role in a group, a tenant's group with a role outside its tenant). A tenant's list of its people (CrewSectorUsers) holds who a group puts there: the members of its own groups, and the members of a group of the whole application that holds a role there, the latter with heldGlobally.

The period of an assignment. A role given to a person, a person's place in a group and a role given to a group may each carry a period: a start and an end, each optional, kept in two nullable columns of the permission store's memberships, group members and group roles tables (StartsAt, EndsAt; the store's DDL() has them, and every policy store's schema holds them). No start is from now, and no end is until it is taken away. An assignment counts inside its period alone, and nothing is written when a period begins or ends: everything that reads an assignment leaves out one outside its period. An Auth whose roles a directory writes gives none by hand and so gives no period.

  • The methods that give a role (AssignCrewRole, AssignCrewSectorRole), a place in a group (AddCrewGroupMember, AddCrewSectorGroupMember) and a group's role (GiveCrewGroupRole, GiveCrewSectorGroupRole) take the two times, startsAt and endsAt. Whoever may give the role there gives it its period: the method's Execute grant, with its condition on new.role, is the whole of it.
  • Changing a period is giving again: a role the person holds there already is given the period of the new request in place of the one it had, so a request that names neither time makes the role stand until it is taken away. Ending a role now is taking it away, and a period that is over already is refused (400), as one that ends at or before its start is.
  • Nobody lengthens their own holding. A request that would make something its caller holds last longer than it was given for is refused (403): a period for the caller's own role or the caller's own place in a group that ends later, or never, or begins sooner while it has not begun, and the same for a role of a group the caller is in. It holds for a period that has ended too, while its row stands. Someone else who may give the role gives it its new period; the caller shortens their own freely.
  • The Super Administrator role takes no period (400): there is always a super administrator, and a period could leave none.
  • The permission engine applies the period at the instant a check is made with, the clock a grant's now is folded with, so an open session loses a role at its next request after the end. The sign-in rule and the session's list of tenants read what a person holds at the moment, and so do a tenant's list of its people (CrewSectorUsers) and the list of the identities of those people: a person whose only role in a tenant has ended, or has not begun, is not one of its people. The two facts about a person (heldElsewhere, heldGlobally) read what has not ended.
  • The lists of roles and of places carry the period (startsAt, endsAt) under a field grant of their own, leave out a row that has ended and show one that has not begun, where it is given another period or taken away: CrewSectorUserRoles, the lists of a group's people and of the roles it holds, and the roles held through a group, whose period is where the place's and the group role's meet. The declarations over the three tables themselves (CrewUserRoles, CrewGroupMembers, CrewGroupRoles) list each row as the table holds it, period included.
  • The subject set of a person's groups counts a place inside its period alone: the members' declaration says so with the set's where: part, so a condition that tests subject.groups leaves a group out exactly when the engine stops giving its roles.
  • An ended row goes at its person's next sign-in, and no job runs on a schedule. The generated client answers the session library's hook for a sign-in that stands (crewidentity.Client.SignedIn(db)), and the Auth's package sets it where it sets the invitation's hook (session.Auth.SetSignedInHook); an application that has a hook of its own calls the client's from it, since one Auth has one hook. The session library calls it once the session is committed and logs an error it answers, so the removal neither fails a sign-in nor undoes one, and a sign-in with nothing to clear costs one read of the person's own rows. What has ended is the database's to say, by its own clock, the one the lists and the sign-in rule read: the statement that finds the rows carries the condition, before the transaction and again inside the transaction that removes them, so a server whose clock runs fast removes nothing that still counts. It removes the person's ended roles and places and nothing else: never the account, also when the ended role was the last thing the person held; the rule on a tenant's last administrator does not judge it; the engine is told nothing, since an ended assignment already counts for nothing; and each removal is written under the source identity.EndedByItself. A role a group held for a period is no one person's, so it stands, counting for nothing, until it is taken away or given again. Where the sign-in rule refuses a person who holds nothing, a person whose every assignment has ended is refused, nothing is cleared for them, and the rows go with the account.

The rules are the identity package's, written once over a Store the generated crewidentity package implements with the Auth's own typed queries and patches:

  • A new user holds at least one role (400 without one) and, where the create carries one, a temporary password: required where the password is the Auth's one way in, optional beside another registration, whose people may sign in through it instead. A username or an address another user holds is refused at the commit.
  • A temporary password, given at the create or set on an account, is hashed by the session library and marks the account: the person chooses a password of their own before anything else is served. Set on an account, it also ends every session the person holds and clears the count of failed sign-ins under their name, so a person locked out signs in with it at once.
  • A rename takes with it what is held under the old name: the person's sessions, the sessions they hold as someone else with their impersonation records, and every role membership. A name another user holds is refused (409).
  • An address set by hand is written bare and held unverified, whatever the one before it was: it is trusted for nothing until the person verifies it themselves, and it reserves the address, so one another user holds is refused at the commit. No address (email null or left out) takes the one held off.
  • Deleting a user removes their role memberships, ends their sessions, and removes their identity links and the account; whatever else the Auth keeps for the person goes with the row.
  • Resetting a person's second factor forgets every browser the Auth remembered for them, so their next sign-in from any of them is asked for the factor. The sessions that stand are left.
  • A lockout is cleared by removing the count of failed sign-ins kept under the name. Each instance of the application trusts what it remembers of a name for five seconds, a lock included, so the lock is gone from every instance within that time of the commit. The hold on a client that kept trying (its address, its browser) is in the memory of the instance that counted it and is not cleared: it ends when its time has passed.
  • Disabling a user ends every session they hold: their own, and the ones they hold as someone else, each with its impersonation record. Ending all of a user's sessions is the same act without the disable.
  • One session ends by its id; an impersonated session also ends by its record, which is then closed as revoked.
  • A password change is required only of a user who has a password (400 otherwise): a person with none would be shut out with no way back in. Whether a user has one is asked of the database, never read into a row.
  • An identity link is removed unless it is the last way in of a user with no password (409): another identity linked to them must be one that can sign them in, by the judgment the removal of a password is held to (below). The last identity that counts stays while only ones left from a sign-in the Auth no longer has would remain, and one of those goes from beside an identity that counts. A user who holds a password may lose every identity. The last super administrator is held to the same rule.
  • A password is removed only from a user an identity that can sign them in is linked to (409 otherwise, 400 for a user with no password). An identity counts when the session library says a sign-in through it is possible (AuthAPI.SignsInThrough): its method is a sign-in the Auth's login page offers, and a registration of that method takes the connection it came through. One left from a sign-in the Auth no longer has does not count, so the password stays the person's way in. The last super administrator is held to the same rule.
  • How a person signs in is read by the same judgment (CrewSignInWays, and a tenant's CrewSectorSignInWays): a row for the password where the person holds one (way is password), and a row for each identity that counts, with the method and the connection the identities list shows and the words the login page's button carries for the sign-in it comes through (through: "Lodestar"; where two registrations of one method both take the identity and nothing of it tells them apart, both, joined by "or"). Never a hash, a subject or an address. It is a computed list, asked for one person at a time (filter=userId:eq:<id>): a request that names nobody lists nobody's, and one that names people any other way is refused (400). A tenant's answers for a person of the tenant's own list of people, nothing for anyone else, and carries the two facts of the person's row (heldElsewhere, heldGlobally) for a grant's condition, with password, which says whether the row is the password. A role file grants it to whoever reads the identities. Lodestar's and the skeletons' grant a tenant's administrator the list under password = false OR heldElsewhere = false: the identities that count of every person of the tenant, and the password only of a person no other tenant holds, the condition passwordChangeRequired is read under. Whether a person another tenant holds too has a password is then not the tenant's to learn, the page offers no removal for them (it offers one by the rows), and the removal is the whole application's administrator's, who reads the password in the whole application's list. Every field of that grant is under the condition, so a tenant's administrator cannot ask for the list sorted or filtered by one of them (a sort or filter field needs an unconditional grant): the list comes in its declared order, the password first.
  • A token is revoked with the rest of its device authorization; a token that is expired or already revoked is not found (404).
  • A role is assigned in the global scope, in one domain, or in every domain, and must exist there: a default role of the role file, or a custom role, which is read in the caller's transaction. A membership committed by a method reaches the permission engine without the caller saying so (the commit calls the engine's PolicyChanged).
  • An invitation gives roles: at least one (400 without), each of which must exist where it is given, the global scope or the tenant domain names. The session library prepares it (AuthAPI.PrepareInvitation: the checks on the address, the token, how long the link stands) and keeps the token, the message and the sender. The row is written in the caller's transaction, beside whatever else the transaction writes, and the link is mailed once the transaction has committed (resource.AfterCommit). The answer's sent says whether the message went: an invitation whose message could not be sent is withdrawn, so no link stands that nobody received, and the caller invites again.
  • Withdrawing holds to invitations. A mail link of another kind (a verification, a sign-up) is not found, and neither is an invitation that was accepted, withdrawn or has expired (404).

Who may sign up. Whether a sign-in method admits a person who has no account and no invitation is chosen for each method in the running application, never in code. The choice is a row of the Auth's sign-in methods table (CrewSessionSignInMethods, declared with the Auth's other tables and migrated with them): the method's registration name, whether it is open to sign-up, whom the method admitted when it was opened (OpenedFor), and the default role a new person gets. A method with no row is invite only, which is how every method starts, and the sign-in reads the row in its own transaction. The generated management gives every Auth whose roles the application assigns the page's two halves, with nothing written by the application:

  • CrewSignInMethods, a list with one row for each method the Auth registers, ordered by label: its registration name and label, who can sign in with it in words (admits: "Anyone with a Google account", "Anyone with an account at acme.example", from how wide the method's registration is), openSignUp, defaultRole, directoryGivesRoles and ownRule (the two kinds of method nothing is chosen for, below), and says, what a person with no invitation meets, as a sentence. It is computed from the Auth's registrations and the table's rows, so a method with no row is listed as invite only, and a row of a method the Auth no longer registers is not listed.
  • OpenCrewSignUp and MakeCrewInviteOnly, the two methods that write the row. Opening declares a warning (@warning(typed: open), section 7): asked with X-Warning, the server says who will be able to sign in without an invitation and what each of them gets, with the words for the confirm button ("Open to anyone with a Google account"), and saves nothing. Making a method invite only says nothing first: the people who have accounts keep them, and new people need an invitation.

What a person who signs up gets depends on the application. Without tenants they get the method's default role, a role held for the whole application: opening a method without one is refused at the save, the Super Administrator's role is never one, and the roles to pick from are the list CrewSignUpRoles (name and description). A default role is a role given to every person who signs up, so it is one the opener could give a person directly: the generated client asks the permission engine for the caller's grant on the Auth's assign method with the role as the new value (the judge that already holds a role given to a group to what its giver may give, identity.RoleGrants, written to the client's grants.go), so a role file that conditions the assign method's grant on the role ("when": "new.role in [...]") holds the default role to the same list. Opening a method with a role the caller may not give is refused with 403 naming the role, at the warning as at the save, and CrewSignUpRoles lists only the roles the caller may give. The grant answers before the role is looked for, so the refusal is the same for a role the application holds and one it does not, and tells nobody of a role the grant keeps from them. The role is given by the identity client in the transaction that makes the account (authSession.SetSignUpSeated(identityClient.SignedUp()), which the Auth's package sets beside the invitation's hook), so no account is left holding nothing. With tenants the person gets an account and creates a tenant of their own (section 16, "How a tenant comes to exist"), so the request names no role, and the choice belongs to one Auth: the one whose session outlets serve the tenant record, whose sign-in rule admits a person who holds no tenant yet (signin.AdmitWithoutTenant()). Another Auth of a tenanted application carries neither the list nor the methods: a person who signed up to it could be given nothing, so its methods stay invite only, and a stranger enters through an invitation or through the directory of a tenant that names a default role. A method whose directory gives the roles (SyncsRoles) is neither opened nor made invite only: the directory decides who signs in, the two methods refuse it, and its Auth, where the directory is the one way in, has neither. A registration that carries an account rule of its own in code (signin.AccountRule) is decided by that rule, which the page cannot read, so nothing is chosen for it either: its row of the list says the application's own rule decides (ownRule), and the two methods refuse it by name with 409.

An open method is open for the audience it was opened for. The warning an administrator confirms names who can sign in with the method ("Anyone with an account at acme.example"), and that is a fact of the method's registration in code, which a later release can widen. So opening a method writes into its row whom the registration admitted then (OpenedFor, the registration's audience in a form that compares exactly: signin.Audience.Key), and the sign-in honors the row only while the registration's audience is still that one. The row keeps what identifies the people (each Microsoft Entra tenant's id, each Google Workspace's domain, a generic provider's issuer, each kind of account outside them) and never what they are called, so a second organization a release lists under the first one's label is a wider audience, and a renamed organization is the same one. A method whose registration has changed since, wider or narrower, is invite only until someone opens it again: the list says that the people it admits have changed since it was opened and whom it admits now, openSignUp is false, the page offers Open sign-up, and the warning names the audience of today. An invitation, and a person who has an account, are not affected. A row that keeps no audience opens nothing, and neither does one that keeps something that is no such key: the list says the method was opened before its audience was kept.

A person who has an account, and a person who follows an invitation, sign in the same under either choice. The password method's sign-up routes (POST <prefix>/user/sign-up, …/sign-up/open, …/sign-up/complete) are on the router of every Auth with the method and answer 404 while it is invite only; the completion reads the row again in the transaction that makes the account, so a link mailed while the method was open creates nothing once it is closed. The table's rows are written through its generated patches with change tracking on, so the change record keeps who opened a method and who made it invite only, and when (DataChangeEvents under CrewSessionSignInMethods); the table itself has no route, and nothing but the two methods writes it. The role file grants List on CrewSignInMethods (and CrewSignUpRoles) and Execute on the two methods to the roles that may decide, and nobody else reads the list or the warning.

What the application supplies. One client per Auth, built by the Auth's own package where it builds the Auth (the skeletons' New, which answers it from Auth.Identity), and handed to the handler type, which returns it from an accessor named for the Auth:

// In the Auth's package, once its permission engine and session manager exist.
identityClient, err := crewidentity.NewClient(accessClient,  // the Auth's permission engine
	authSession.API(),                                        // the API of the session.Auth that signs its people in
	settings.TenantMaker,                                     // what makes a tenant, for the Auth a tenant is made through
	identity.WithAdministratorRoles(tenantAdministrators))    // the roles that administer a tenant

// In the handler type's package.
func (a *App) CrewIdentity() *crewidentity.Client {
	return a.crewIdentity // crew.Auth.Identity(), handed in by the configuration
}

The third argument is there for one Auth, the one a tenant is made through, and for no other: its generated NewClient(access, sessions, tenants identity.TenantMaker, opts...) requires what makes a tenant from an accepted invitation and refuses nil. The application builds it with the generated New<Record>Maker(roster, liveService) of the handler package (section 16, "The maker") and hands it to the Auth's package where the Auth is built, so the roster is built before that Auth; the client hands it to the identity package (identity.WithTenantMaker), which an application never calls. The same client needs the roles that administer a tenant (identity.WithAdministratorRoles): the person who accepts is seated with them, and an invitation is refused while the Auth names none. The client of every other Auth takes the engine and the session API alone.

The generated zz_gen_identity.go in the handlers package asserts the accessor (var _ crewhandlers.Deps = (*App)(nil)) and holds the Auth package's TablePrefix equal to the one the management was generated for, so an Auth whose tables were renamed fails the build until the application is generated again. Each method it writes there constructs the Auth's handlers with the application's own live derivations, so a view of the application's over the Auth's tables is live under the management's writes (section 14). The role file grants List and Read on the resources and Execute on the methods to the roles that manage people, in the grammar every other resource uses.

At a sign-in. A person comes to hold a role with no administrator signed in in three ways: they accept an invitation, which names roles, they sign in for the first time through the directory of a tenant that names a default role (section 16), and they sign up through a method an administrator opened, which names a default role ("Who may sign up", above). The session library runs a hook inside the transaction of each step and hands it the transaction, and the client answers each hook over its own membership write, so a role a sign-in gives is held to the rule a role given by hand is and is committed with the step that causes it: the invitation is spent and its roles given together, or neither; the account is linked to the directory and given its role together, or neither, and a person who holds a role in the tenant already is given nothing. Both read what the person holds by its period, and neither waits for an ended row to be removed: a role whose period has ended is nothing the person holds, so the invitation gives it afresh and the directory seats a person whose only role in the tenant has ended; a role the person holds for a period, or one that has not begun, is left exactly as it stands, since an invitation gives what is not held and erases no period. The Auth's package sets them on its session manager where it builds the client, so no Auth is open without them:

authSession.SetInvitationAccepted(identityClient.InvitationAccepted())
authSession.SetSignUpSeated(identityClient.SignedUp())
authSession.SetDirectoryAdmission(settings.TenantDirectories, identityClient.DirectorySeated())

An invitation into a tenant gives its roles in that tenant; one into the application gives each role where the role is held, the global scope or every tenant; one that makes a tenant makes it there, in the same transaction, and gives the person the roles that administer it ("The invitation that makes a tenant", below). A role that can no longer be given (the role file changed since the invitation was sent) fails the transaction: the invitation stands and no account is created. The permission engine is told once the transaction has committed, before the sign-in policy decides. The client of an Auth whose roles a directory writes has none of the hooks: the directory's answer at every sign-in is that Auth's roles.

A third hook runs once a sign-in stands, apart from it: the client's SignedIn removes the person's roles and places in groups whose period has ended (the period of an assignment, above), in a transaction of its own on the application's database. It is set beside the other two, and an Auth whose roles a directory writes has none:

authSession.SetSignedInHook(identityClient.SignedIn(resource.NewSpannerClient(db)))

A rename moves nothing the person holds, whoever makes it (an administrator through the management, or the session library where the sign-in name is the person's email address and a verified new address renames the user): the permission store names a person by the id of their account (identity.User), so every role stays where it is, and the username is what people read.

In a transaction of the application's. A method is a struct with an Execute, so the application runs it wherever it holds a transaction, beside its own writes:

err := resourceClient.ExecuteFunc(ctx, func(ctx context.Context, txn resource.ReadWriteTransaction) error {
	sector := anvil.String() // the tenant's id
	created, err := (&crewidentity.CreateCrewUser{Username: "ada", Roles: []string{"Dispatcher"}, Domain: &sector}).Execute(ctx, txn, a.CrewIdentity())
	if err != nil {
		return err
	}
	// A further role for the person just created, by the client's own call: it looks
	// nobody up, and the new user is not readable until the commit.
	if err := a.CrewIdentity().AssignRole(ctx, txn, accesstypes.GlobalPolicyScope(), identity.User(created.ID), "CrewCommon"); err != nil {
		return err
	}

	return recordHire(ctx, txn, created.ID) // the application's own rows, in the same commit
})

The served method that gives a role (AssignCrewRole) names a person a request gave it, so it reads the user first and answers 404 for an id no user holds; run in the transaction that creates the user it would not find it, which is why the example gives the further role through the client.

A person is created holding a role: Roles names at least one, all held in one place (the global scope, the one tenant Domain names, or every tenant with EveryDomain), and the memberships are written in the transaction that writes the user. A create without a role is refused, since an account that holds no role anywhere is not kept. A role held somewhere else is one more AssignCrewRole beside it, as above.

Nothing is written until the commit, so a method does not read what an earlier method of the same transaction buffered: a role is given to a person who has an account already (a person new to the application is created holding their roles), and one identity link is removed per user per transaction.

Limits. It runs on Spanner. A rule reads the rows as committed: a method does not see what an earlier method of the same transaction buffered, so the rule on a person's last role judges one removal per person per transaction, and the rule on the last super administrator one holder per transaction. The rules of a group read the group as committed too: who is in it and what it holds, so a person put in a group and a role given to the group in one transaction of the application's are each judged without the other. Every generated route runs one method, which names one person, in a transaction of its own, so no request puts two in one; the limit is for an application that runs the methods in a transaction it opens itself. A temporary password is the one the session library has today: the operator chooses it and passes it on.

The rules on who is asking. Who may run a method is the role file's to say. Four rules of the user management are the methods' own, whatever the role file grants, and each judges the request's caller (a method an application runs in a transaction of its own, outside any request, has no caller and is the application's act):

  • Nobody disables or deletes their own account, which is the account of the real person behind the session: a person who views as someone else is refused their own account, which they could not get back. They are refused the account they view as too ("you cannot disable the account you are viewing as"): a session that views as a person does no more than that person may, and nobody disables or deletes themselves.
  • A person who removes a role from themselves in a tenant keeps an administrator role nobody else would hold there. The application names the roles that administer a tenant when it builds the client (identity.WithAdministratorRoles(domain)): they are judged among the tenant's holders and those who hold the role in every tenant. A holder through a group is a holder, in both directions: a person in a group that holds the role there administers the tenant and is counted, and a person who takes themselves out of the group that gives them the role, or takes the role from a group they are in, is judged as one who removes it from themselves. Each holding counts inside its period alone. Without the option a person removes no role from themselves in a tenant. A role held in the global partition goes freely, since a super administrator gives it back.
  • The Super Administrator role (accesstypes.SuperAdministrator) is the framework's, in every auth and in no role file, held in the global partition alone. Only a holder makes or removes another: giving the role, taking it away, inviting a person to it and deleting a holder's account each take a caller who holds it, and so do disabling a holder's account, which removes a super administrator in effect, and enabling one, which makes one who can sign in. A caller who came through another Auth (Manages) holds no role of this one. Only a holder changes how another signs in, since each such act is a way to become the person or to shut them out: setting a holder's temporary password, removing their password, requiring them to change it, renaming them, setting their email address (where the code of their second factor is mailed) and unlinking one of their sign-in identities each take a caller who holds the role, whatever the role file grants; a holder acts on themselves and on another holder as the role file allows. The caller these rules judge is the real person behind the session: a person who views as a super administrator is not one. Giving the role ends nothing: the sessions the person holds, their bearer tokens and the browsers they asked to be remembered stand, and the session they are signed in with acts with the role at its next request. A person who is signed in when the role is given is no risk for being signed in; what the role guards is the account, which is asked for a second factor at every sign-in from then on. What an administrator set on the account before the role, a password or an email address, is left as it is too: nobody but a holder gives the role, and the holder who gives it chooses whom to trust, the account as it stands included. These are the rules of an auth whose roles the application gives. In one whose roles come from its directory the directory decides who is a super administrator, the role synchronization writes and removes the role at each sign-in as it does any other, and none is seeded. There is always one who can sign in: the role is not taken from the last holder whose account is not disabled, and that account is neither disabled nor deleted, whoever asks, the application's own transactions included. What the role does is fixed where the engine is built: the generated client names the methods that give and take the Auth's roles (crewidentity.SuperAdministratorMethods()), the Auth's package hands them to the engine (access.WithSuperAdministratorMethods), and a super administrator then runs them whatever the role file grants, for any person, in the global scope, in one tenant and in every tenant. The client refuses an engine built without them, so an application that left the option out does not start.
  • While a tenant is directory only, who administers it is changed from inside it, or by a super administrator. Directory only is the tenant's switch to keep everyone out who does not come through its directory, the application's own staff included, and the administrators' way in (a password and the mailed code) is for a person given an administrator's role in that tenant itself; a caller whose role file lets them hand out roles everywhere would otherwise make that true of themselves. So one judgment is asked before each act that could: does the tenant admit the caller's own session (resource.UserPermissions.Reaches, the reach every request of theirs is held to: a session through the tenant's directory, a super administrator's, and the session of one of the tenant's own administrators signed in with a password and the code). A caller it does not admit is refused (403) giving or taking one of the tenant's administrator roles (access.WithTenantAdministratorRoles) in that tenant, to a person or to a group kept in that tenant, putting a person in or taking one out of a group kept there that holds such a role, and an invitation that carries such a role there: "… is a role that administers a tenant, and this tenant admits only people who sign in through its own directory, which your sign-in does not enter. Who holds the role there is changed by one of its administrators, or by a super administrator". The account of a person who holds such a role there, of their own or through a group kept in that tenant, in an assignment that has not ended, is held to the same judgment, since each act on it is a way to become the person or to shut them out: a temporary password, a required change of password, a removed password, a new sign-in name, an address set, an identity unlinked, the account disabled, enabled or deleted are refused with a sentence that says the same of the account. A person who administers more than one tenant is changed by a caller every one of them admits, and the refusal says so: "Their account is changed by someone whose sign-in enters every tenant they administer, or by a super administrator". The sentences use the application's word for a tenant (WithTenantWord). The list of roles a caller could give (RolesToGive) leaves such a role out for a caller who would be refused. A session that views the application as one of the tenant's administrators gains nothing: an impersonated session reaches a directory-only tenant only when the real person behind it is a super administrator, so it is refused the same acts. What makes a person a tenant's administrator is the permission engine's statement (access.AdministersTenant), the one the way in is decided on: a role held in every tenant or in the whole application, or by a group kept for the whole application, administers no one tenant and is not judged, and neither is an assignment that has ended, an act in a tenant that is not directory only, or one the application runs in a transaction of its own outside any request. The judgment covers the acts that give the way in or take over an administrator's sign-in, and no others: ending a person's sessions, forgetting their remembered browsers, unlocking their sign-in, revoking a token, withdrawing an invitation, changing the name a person is shown by and clearing a deleted tenant are not judged. Nor does it look back or ahead: a person put in a tenant's group before the group holds an administrator's role, an invitation that carried the role, sent before the tenant became directory only and accepted after, and a password or an address set on an account before its person was given the role all stand. The caller's reach is read from the tenant roster and the engine's snapshot each instance holds, as every request's is, so a change made on another instance decides once it has arrived. The methods a list offers on a row are drawn from the role file's grants and do not know this judgment: a page may offer one of these acts on such a person's row, and the method then refuses with the sentence.
  • The removal of a person's last role anywhere deletes the account, with its identity links and sessions, in the same transaction and whoever removed the role: an account nothing admits is not kept.

A caller is named by the id of their account, as the permission store names anyone, and the first three rules take the caller for the person acted on only where the request came through the Auth being managed. An outlet's routes bind the name of the Auth that signs its people in to every request (live.Subscribing(crew.Name), read back with resource.AuthFrom), and the client holds the name it was generated for (crewidentity.AuthName, which the application's generated handlers hold equal to the auth package's Name at compile time). On an outlet that serves another Auth's management (Manages), the caller is another Auth's person, whose id is no account of the one being managed: there nobody is refused as acting on themselves.

One tenant per person. In an application whose tenants own their people, a person belongs to one tenant: the tenant that created or invited them manages the account, which it cannot do for a person another tenant holds too. The application says so where it builds the client, beside its administrator roles (identity.WithOneTenantPerPerson()), and every way a person comes to hold a role in a tenant is then held to it:

  • A role in a tenant given by hand is refused (409) for a person who holds a role in another tenant.
  • A role is held by an account and never by a name, so an account that is created holds nothing until a role is given to it and a rename moves no role: neither brings a person into a second tenant.
  • An invitation into a tenant is refused when it is sent (409) where a user has confirmed the address and holds a role in another tenant, so the sender is told and nobody is mailed a link they cannot accept. An address counts once its holder has confirmed it, as at a sign-in: one an administrator typed onto an account says nothing of who reads its mail, so a tenant cannot keep another from inviting an address by writing it on one of its own accounts. An address no user has confirmed is invited, and whoever accepts is held to the rule then.
  • An invitation that makes a tenant is held to it the same way: sent to an address whose confirmed account already belongs to a tenant, it is refused when it is sent (409), since the account would belong to two, and whoever accepts one is held to the rule at the acceptance, where nothing is made for a person who belongs to another tenant.
  • An invitation accepted, and a directory's default role, are refused inside the sign-in's transaction: nothing is consumed and no account is made, and the sign-in ends on the login refusal code other_tenant, which the login page holds a sentence for. The roles of one sign-in are judged together, so a stranger from one tenant's directory who carries another tenant's invitation is refused, and so is a stranger from a directory two tenants declare with a default role.

A refusal says the person belongs to another tenant and never which.

The application's own people are outside the rule. A person who holds a role for the whole application or in every tenant is no tenant's to manage, whatever else they hold (the role files grant a tenant its account methods on a person it holds alone, heldElsewhere = false AND heldGlobally = false), so they are given a role in any tenant: an operator who is asked into one customer's tenant after another holds a role in each. Such a role is no tenant's either, so it never counts as one and is never refused. So that nobody is left in several tenants with nothing outside them, the last role a person holds outside the tenants is not taken away while they hold roles in more than one (409): take the roles in all but one tenant away first. A place in a group of the whole application is held outside the tenants as a role is, so a person is not taken out of the last such group either while nothing else of theirs is.

The rule reads what is committed, as the other rules do: one transaction of the application's own gives a person roles in one tenant. A person who already holds roles in two tenants when the option is turned on is given no further role in a tenant until they are down to one. One writer is outside it: a directory's role sync gives and takes roles for the whole application and in every tenant alone, on the directory's word. Without the option a person may hold roles in any number of tenants, as in the skeletons and in Lodestar.

The pages. No application writes a page for an Auth's management. The generated API description (zz_gen_api.ts) carries an identity block beside its resources and methods: for each Auth whose management the outlet serves, the Auth's name and label, the tenant record's name where the application has one, and a side for each scope (global, the whole application's; domain, a tenant's) that names the lists by what each holds (users, roles, identities, signInWays, invitations, and for the whole application sessions, signInAttempts, signInMethods, signUpRoles and, for the Auth a tenant is made through, invitedTenants) and the methods by what each does (create, invite, withdrawInvitation, assignRole, removeRole, disable, enable, delete, rename, setEmail, setTemporaryPassword, requirePasswordChange, endUserSessions, revokeTrustedDevices, unlinkIdentity, removePassword, and for the whole application endSession, unlockSignIn, openSignUp, makeInviteOnly, inviteTenant and withdrawInvitedTenant). The names differ in every application (CrewSectorUsers, DisableCrewSectorUser); the keys do not. A side names only what the outlet serves, so a method the Auth's shape leaves out, or a list the schema has no table for, is absent, and a side without its list of people is not listed. The Angular library builds the pages from the block at run time (identityRoutes(apiDescriptor, resourceMeta, { auth, scope }), from @impulseframework/resource-angular/identity-pages): the people with a menu on each row holding the methods the server lists for that row, a person's row page with the roles held, the ways they sign in and the sign-in identities under it (and the sessions, for the whole application), the invitations, and for the whole application the page staff bring a tenant in from, named by the tenant record ("Invited sectors": the invitations that still stand with a column for each detail the caller may read, the method that sends one above the list, and Withdraw on each row, each offered only under its grant), the sessions, the failed sign-ins and the Sign-in page: one row for each sign-in method, Open sign-up on a method that is invite only and Make invite only on one that is open, each only where the caller holds the grant and never on a method the directory or the application's own rule decides, the method's warning drawn by the method dialog, and a notice above the list while a method is open. Above the ways a person signs in, the page offers Remove password for an Auth with a password method where the removal can happen: the server's answer for the person's row lists the method, and the list shows a password and an identity that counts. It asks first, naming what is left by the words of the rows, and the offer goes with the password once the list is read again. A period is picked and shown in days. The server keeps an end as the first instant the assignment no longer counts, and "until 1 December" means through the end of 1 December: the dialog of a method that gives something for a period sends the day picked for its end as the first instant of the day after it, in the viewer's time zone (the method presentation's throughDay), and a list shows the last day the assignment counts, the day that was picked. They are the library's list and row pages over these resources, drawn from a configuration the library writes; what a page offers is what the server answers the caller may do. Lodestar's console takes its accounts pages this way, once for each side.

Tests. The generated authorization matrix carries the lists and reads as query pairs and the methods as denied-only cases. Lodestar's test/integration/generated_identity_test.go drives the methods over the served application (the invitations, whose mail the test reads, in generated_identity_invitation_test.go), generated_identity_lists_test.go holds a sector's lists (each sector's rows, a person of two sectors in each, the facts, and the grants that carry a condition on one), generated_identity_tenant_methods_test.go a sector's methods (each account method allowed on a person the sector holds alone, refused on one it shares and not found for another sector's; the roles given and taken; the create; the identities and the unlink) with generated_identity_tenant_invitation_test.go for the ones that need the session manager (the invitation, its withdrawal, the temporary password), generated_identity_remove_password_test.go holds the removal of a person's password at a sector and the list of how a person signs in beside it (the password and the identities that count, an identity of a retired sign-in left out, the sector's people alone), and generated_identity_remove_password_skipauth_test.go over the served application with the simulated directory (refused while the person holds no identity and for a role without the grant; once removed, the password signs nobody in and the directory does; the list in each state), generated_identity_one_tenant_test.go holds the rule of one tenant per person through a second client built with the option, since Lodestar itself lets a person hold roles in several sectors, generated_identity_groups_test.go and generated_identity_periods_test.go hold the groups of people and the period of an assignment, and generated_identity_group_rules_test.go the rules of a change to a group (a sector's form takes the sector's people; who is in a group is changed by someone who may give or take the roles it holds; nobody lengthens their own holding; the roles held through groups show the one that counts), generated_identity_live_test.go holds that a method's commit reaches the pages of a resource derived from the Auth's tables, a sector's open list among them, and its console's identity-pages.spec.ts holds the pages the library builds for the two Auths to the generated metadata: every resource, column, field and method a page names is one the description carries.

22. Update-or-create and create-unless-there

Application code sometimes writes a row without knowing whether it is there: a task a queue delivers twice, a sync that runs again, a membership given to a person who may hold it already. The generated patches say both intents, and neither is a third kind of write:

// Update the row; create it when it is not there.
patch := resources.NewTenantSettingUpdatePatch(tenantID).SetTheme(theme).OrCreate()
if err := patch.Buffer(ctx, txn); err != nil {
	return err
}
created := patch.RowCreated()

// Create the row; leave it exactly as it is when it is there.
patch := resources.NewUserRoleCreatePatch(kind, axis, domain, role, user).SetCreatedAt(now).OrSkip()
if err := patch.Buffer(ctx, txn); err != nil {
	return err
}
skipped := patch.RowSkipped()

What runs. Apply and Buffer read the row's key inside the transaction and then run the create or the update exactly as a plain CreatePatch or UpdatePatch runs it. So the two cases differ in everything the resource declares for them, with nothing said at the call: a default_create_fn and the @state default fill only a row that is created, an output_only_update_fn stamps only a row that is updated, the create's or the update's validation runs, an armed patch (Enforce) is held to the Create grant or the Update grant with its condition, and the change record is the create's or the update's. The mutation is a plain insert or a plain update; Spanner's insert-or-update is not used, and resource.CreateOrUpdatePatchType is left as it was.

The row is there The row is not there
UpdatePatch.OrCreate() the update, whole; RowCreated() is false the create, whole, with the fields the patch carries; RowCreated() is true
CreatePatch.OrSkip() nothing: no default, no validation, no write, no change record; RowSkipped() is true the create, whole; RowSkipped() is false

Which patches. Every update patch offers OrCreate, since an update names its row. A create patch offers OrSkip only where the caller names the key (a composite key, an interleaved table's key, a key that is a foreign key, a key that is not a UUID): a create patch that makes its own id never names a row that is there, so the method is not generated and a call does not compile.

The same fields in both cases. An OrCreate patch writes the fields it carries whether it updates or creates. Where the two must write different things (a value given only at creation, a counter raised from the stored value), read the row and build the create patch or the update patch; OrCreate is the short form for the case where both write the same.

The read. It asks for the key alone. In a tenant request it is held to the tenant, so a row another tenant holds under the same key reads as not there, and the create that follows is refused at commit as any create of a taken key is (section 10). It is made inside the read-write transaction, so of several writers racing to update-or-create one row exactly one creates it and the others update it; none is refused.

The grant. A patch armed against a caller (Enforce) is asked for the grant of what it is before the row is looked for, so a caller who does not hold it gets the same refusal whether or not the row is there, and learns nothing from the answer. An OrSkip is a create: it is checked for Create with the fields it carries, and a Create grant's row condition is judged only when the row is created. An OrCreate is an update: it is asked for Update on the resource, and the fields it carries are then held to the Update grant when the row is there and to the Create grant when it is not, each with its condition. A caller who holds Update and not Create is refused when the row is not there, which says no more than the 404 a plain update gives the same caller.

Rows of the same transaction. A read does not see what its own transaction buffered, which is why two plain creates of one row in one transaction are refused at commit. An OrCreate or OrSkip patch asks the transaction's record of the rows its patches wrote before it reads: a row an earlier patch of the transaction wrote is there, and one it deleted is not. So a second OrSkip of one row skips, and a second OrCreate updates. One limit is the update path's own: on a resource that keeps change records, under a grant with a row condition, and in a tenant request, an update reads the stored row, so an OrCreate of a row the same transaction created is answered not found, exactly as a plain update of that row is. An OrSkip of such a row skips.

A transaction that runs again. A transaction Spanner aborts runs its function again, and the row may be there on the second attempt where it was not on the first. The patch decides again on every attempt, and what the earlier attempt's path put on it (a create's default, a value a hook rewrote) is taken back first, so a patch built once outside the function is safe to buffer inside it.

In a batch. The consolidated endpoint and a resource's own PATCH route take both as operations, beside add, patch and remove:

[
  {"op": "patch-or-add", "path": "/work-order-tasks/7f3c9a52-0c1e-4d6b-9a57-2f1d6f0b8e11/4", "value": {"instructions": "Seal the aft lock", "done": false}},
  {"op": "add-or-skip", "path": "/work-order-tasks/7f3c9a52-0c1e-4d6b-9a57-2f1d6f0b8e11/5", "value": {"instructions": "Test the seal"}}
]

Each names its row in the path, as a patch does. A patch-or-add is decided inside the batch's transaction (Decoder.DecideOperation: the caller's Update grant on the resource, then the read of the key) and is then decoded and run as the patch or the add it turned out to be. An add-or-skip runs as the add it is, with its create patch marked OrSkip. So the fields a body may carry, the grant with its condition, the validation and the change record are a patch's or an add's, with nothing of their own, and an earlier operation of the same batch counts: two add-or-skip of one row land, where two add of it are refused at commit.

Only a resource whose key the client supplies takes them. One whose id the server makes answers 400 (Missions takes add, patch and remove, not "patch-or-add"): no request names a row of it that may or may not be there. A patch-or-add carries one value, written in both cases, and over the wire a patch may not carry every field a create may. So a resource whose create must carry a field no patch may carry (an immutable field with no default) takes add-or-skip alone, and answers a patch-or-add with a 400 that names the field.

In the browser. The generated client builds both for client.batch (web/projects/resource): handle.ops.patchOrAdd(value) and handle.ops.addOrSkip(value), where the value's key fields become the path. Each builder exists only on the handle of a resource that takes the operation, so a call the server would refuse does not compile. The value of patchOrAdd holds what a create must have and what a patch may change; a field only a create takes does not compile in it. A page offers an action built on patchOrAdd where the caller holds both Create and Update, since it cannot know which of the two the server will ask for.

In the library. The generated identity store writes a membership as a create-unless-there (InsertMembership), so a role a person holds already keeps the time it was given and giving it twice in one transaction is no error.

Tests. resource/patch_fork_test.go holds the decision, the rows of the same transaction, the attempts and the armed cases against the mock transaction, with the refusal that comes before the read; resource/patch_fork_spanner_test.go holds the same over the emulator, with the racing writers, the change records and the commit that refuses two plain creates; resource/operations_fork_test.go holds the two batch operations and the decoder's decision; generation/patchfork_test.go holds which generated patch offers which method, and which handler and which client takes which operation. Lodestar serves both operations over a refit's tasks (lodestar/test/integration/batch_decided_test.go), and the browser client's specs are web/projects/resource/src/batch.spec.ts and patch-or-add.types.spec.ts.

23. Secrets at rest

A field declared conditions:"secret" is kept in the database encrypted. Anyone who can query the database, or read a backup or an export, reads bytes that open only inside the service. There is no plain kind: the generator refuses a stored secret that is not typed resource.Secret, so a new secret field cannot be stored as it was typed.

// TransponderKey is the key the ship's transponder signs its answers with.
TransponderKey *resource.Secret `spanner:"TransponderKey" conditions:"secret"`
TransponderKey BYTES(106),  -- a key of up to 64 bytes, and the 42 sealing adds

The application secret. One secret of the application, 32 random bytes, kept in versions. It never encrypts anything itself: at start the service derives one working key for each use and each version from it with HKDF, under a fixed label naming the use and the version (the session library derives its cookie key the same way), so the keys that seal resource fields have no relation to the keys of any other use.

What a column holds. One value of three parts: the version of the application secret that sealed it (two bytes, the high byte first, 1 to 65535), a random number drawn for the write (24 bytes), and the encrypted value with its 16-byte check. The cipher is XChaCha20-Poly1305 (golang.org/x/crypto/chacha20poly1305). Sealing adds 42 bytes (resource.SecretOverhead), so a column that takes a value of up to n bytes is BYTES(n+42), or BYTES(MAX); the value limit a request is held to (section 11) and the form's maxLength are the column's length less 42, counted in bytes. The version takes two bytes because a deployment's version numbers never repeat, and a rotation that fails uses one up: the 255 versions one byte names would run out in a secret's life, with no way forward.

The context. The row's primary key, every key column in key order, is mixed into the check when a value is sealed and again when it is opened. It is never stored: each operation takes it from the row it works on. Bytes copied onto another row do not open there. The table's and the column's names are left out, so renaming either breaks nothing; the key order is the key's own (the generated SecretContext), so reordering the struct's fields breaks nothing either. A key column the database stamps at commit cannot bind a secret, and a write of one is refused.

resource.Secret. The field's type. It holds the stored bytes and nothing else, and goes in and out of the database unchanged, on Spanner and on PostgreSQL. It prints as [secret] in JSON, in a log line, through fmt and in an error's text; it refuses to be read from JSON; and it has no method that gives the value. KeyVersion() says which version sealed it.

resource.SecretKeys. The key holder, built once at start from the versions of the application secret, and the one thing in the process that holds key material (it keeps the derived keys, not the versions it was built from). The highest version given is the current one. The data level builds it and hands it to the database client:

keys, err := resource.SecretKeysFromEnv("APP_SECRET_KEY", os.Environ())
// ...
db, err := database.Open(ctx, env.Database.Settings, resource.WithSecretKeys(keys))

resource.WithSecretKeys is an option of the Spanner, PostgreSQL and mock clients alike (resource.NewSpannerClient(db, resource.WithSecretKeys(keys))); given twice, the client panics at construction. resource.NewSecretKeys(map[int][]byte{1: ...}) builds the holder from fixed bytes, which is what a test does.

The configuration. The application's configuration declares the secret beside its other variables, secret:"versioned": a secret the deployment generates, of which the service is handed every enabled version.

SecretKey string `env:"APP_SECRET_KEY" secret:"versioned"`

No variable has the declared name. Each version arrives in a variable of its own, the name and the version's number (APP_SECRET_KEY_1, APP_SECRET_KEY_2), holding the version's 32 bytes in Base64, and resource.SecretKeysFromEnv collects whichever are set, reading the whole environment so that no variable the name numbers is passed over. With none set it answers no error and a holder that holds no key, so an application that stores no secret runs without the variable, and one that stores a secret is refused at start by the name of the variable that is missing (APP_SECRET_KEY_1). The declared name itself set to a value, with no numbered version beside it (APP_SECRET_KEY=...), is the secret put in the wrong variable: an error naming it and the variable to use. A variable that is set and does not hold a version is an error naming the variable, never its value. A stored value names its version in two bytes, so a secret's versions run from 1 to 65535: the variable of a version past 65535, or of version 0 (APP_SECRET_KEY_65536, APP_SECRET_KEY_0), is an error at start that says the range. The development environment file carries APP_SECRET_KEY_1, generated: the skeletons' and Lodestar's .envrc.template write 32 random bytes to .app-secret-key.dev the first time the file is sourced from the application's root and read the variable from that file from then on, so a checkout keeps one key and .gitignore keeps it out of git. No template holds a key: a key in a tracked file is every checkout's, and the library cannot tell it from a real one. impulse check (env-template) holds the template to that: the variable set by a line, never a key written in the template, the key's file ignored; and --fix writes the two lines.

Writing. No code of the author's. A request and a typed patch give the value as text (patch.SetTransponderKey(&key); the generated request structs, the typed patches' setters and the TypeScript shapes carry a string), and the write path seals it where it turns the patch's fields into columns (PatchSet.Resolve), with the keys of its transaction's client and the row's primary key. The same value sealed twice gives different bytes. A secret set to the value its row already holds is still no change: the write path opens the stored value to compare, so the update that changes nothing writes no change record. A grant's condition never reads a secret: the proposed value is left out of the statement the conditions are judged in.

Using a value. The generator writes two methods on the resource struct for each secret field. Both take the context from the row, so an author cannot pass another row's key, and a query that reads a secret field reads the row's key columns with it.

ship, err := resources.NewShipQuery().AddColumns(resources.NewShipColumns().TransponderKey()).SetID(id).Read(ctx, txn)
// ...
key, err := ship.Data.OpenTransponderKey(keys)       // anywhere: opens, writes nothing
key, err := ship.Data.OpenTransponderKeyIn(ctx, txn) // in a read-write transaction

Rewriting under a new version. A value that names an older version than the current one is written again under the current one the next time it is set, like any write, and the next time it is opened inside a read-write transaction (Open<Field>In, which takes the keys from the transaction's client). That rewrite is the stored bytes alone: the value does not change, so no permission is asked, no update function stamps the row and no change record is written, and it is buffered only when the row, read again inside the transaction, still holds the bytes that were opened, and never for a row a patch of the same transaction has already written, since no read sees a buffered write. Open<Field>(keys) never writes. At a rotation, a request already running on a revision that was not handed the new version can meet a value the new revision rewrote, and answers an error for that request.

Retiring a version. A version of the application secret can be disabled once no stored value names it, and a value nobody sets or opens keeps the version that sealed it. The application's migrate command retires a version, named by the variable it is handed over in:

migrate -retire-secret APP_SECRET_KEY_1

The command opens the data level and calls resource.RetireSecretVersion with the application's secret holders, the generated SecretHolders() of each resources package (one resource.SecretHolderOf[T]() for each resource that stores a secret; nil for a package that stores none). Every stored value that names the version is opened and written again under the current version, a batch to a transaction, and a final read of every secret field finds none left. It exits 0 only then, and prints how many values of each field it wrote, never a value.

A retirement reads the packages its call is handed and no other, and the call names them by hand: one package's resources.SecretHolders()..., or several joined, slices.Concat(consoleresources.SecretHolders(), sharedresources.SecretHolders()).... impulse check (secret-holders) fails an application whose call leaves out a package that carries the generated list, takes its holders from where the check cannot read them (a parameter, a function of the application's own, a list written by hand), or is missing.

Its environment is the migration's with one variable for each enabled version, the one being retired among them, since its values are opened under it: a run that was not handed the version it retires is refused before anything is read, naming the variable that is missing (APP_SECRET_KEY_1 is not set) and the versions it was handed. The current version, the highest the environment carries, is refused: new values are sealed under it. So is a variable that is not a version of the secret the keys were read from, and one whose number is 0 or past 65535, with the range a version's number takes.

A value that does not open (bytes moved from another row, or altered) is left as it is and does not stop the run: every value that opens is written, in every field of every holder, and the retirement then fails saying how many values in all do not open and how many it wrote, and naming the first ten by resource, field and row. Set each again or clear it, and run the retirement again. A second run finds nothing to write and exits 0. The service keeps serving meanwhile: a value is written back only while its row still holds the bytes that were opened, read again inside the writing transaction, and the rewrite is the stored bytes alone, with no permission check, no update function and no change record. It runs on Spanner through the resource client and on PostgreSQL by statements of its own, the PostgreSQL client's transactions not being built; on both the rows are read in key order and each row once, PostgreSQL a page of 200 at a time after the last key of the page before, so values that do not open never hide the ones behind them.

Refusals.

  • A stored field declared secret and typed a plain string or []byte, or on a column that is not BYTES with room for a sealed value: refused at generation, with the type and the column to give it. A field typed resource.Secret and not declared secret is refused the same way.
  • An application that stores a secret and was handed no version of the application secret: refused at start. The generated router's New calls resource.RequireSecretKeys with every secret field and panics naming them and the variable that is not set (APP_SECRET_KEY_1, from the name the keys were read under), with what it holds and how to make one; a client built with no keys at all is told to read them (resource.SecretKeysFromEnv) and wire them (resource.WithSecretKeys). A write of a secret through a transaction that holds no keys is an error too, and names the variable the same way. A command that opens the data level without the generated router (the migrate and bootstrap commands) is not refused at start, and fails at its first use of a secret.
  • The declared name set with no number (APP_SECRET_KEY) and no numbered version beside it: refused where the keys are read, naming it and APP_SECRET_KEY_1.
  • A value that names a version the service was not given: a *resource.UnknownSecretVersionError when it is opened, naming the version and the versions the service holds.
  • Bytes moved from another row, or altered: resource.ErrSecretNotOpened when they are opened.
  • A configuration variable named as a version of a versioned secret is (APP_SECRET_KEY_1 beside APP_SECRET_KEY declared secret:"versioned"): refused when the application is read (impulse check, the deployment's tooling), since the deployment hands the version over under that name.

Tests. resource/secret_test.go holds the type (nothing prints it), the key holder (a value opens on its row and on no other, under the version that sealed it and no version the holder was not given, the versions one byte cannot name among them), the write path and the rewrite against a capturing transaction; resource/secret_spanner_test.go and resource/secret_postgres_test.go hold the column (no plain value, the change record names the field without its values) and a rotation over the emulator and a PostgreSQL container, and the retirement of a version on both, of versions 256 and 258 under version 65535 as of version 1 under version 2; resource/secret_retire_test.go holds the retirement's refusals, its final check, and that it tells a version from one that shares one of its two bytes; generation/secret_test.go holds the refusals, the generated methods and the secret holders. Lodestar's ship carries a transponder key (lodestar/test/integration/secret_test.go), and its migrate command retires a version over the emulator (lodestar/cmd/deployment/migrate/main_test.go).

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

Examples

Constants

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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"
)
View Source
const DefaultPageSize uint64 = 50

DefaultPageSize is the generator-wide page size a resource takes when it declares none.

View Source
const DirectoryOnlyRoute = "directory-only"

DirectoryOnlyRoute is the route of the read of a tenant's directory-only switch as it stands (DirectoryOnlyState), under the tenant's own route: GET <prefix>/<tenants>/{tenant}/directory-only. The generated router registers it beside the two methods that turn the switch (Make<Record>DirectoryOnly and End<Record>DirectoryOnly) on every outlet that serves sessions and the tenant record, for a record that declares the switch.

View Source
const DirectoryOnlyWord = "close"

DirectoryOnlyWord is the word a person types before a tenant is made directory only (the warning of Make<Record>DirectoryOnly): the tenant is closed to every sign-in but one through its directory. A warning's word is one lowercase word, which a directory's name is not, so the word is the same for every tenant.

View Source
const DryRunHeader = "X-Dry-Run"

DryRunHeader asks a transaction-form RPC method to run its whole frame — decode, the entry check, the target's location and state checks, the body with every write it arms — and then roll the transaction back instead of committing. Every refusal answers exactly as the real call would; a call that would have succeeded answers 200 with no body, since a result could name rows that never came to be. A client-form method refuses the header: effects outside a transaction cannot be previewed. The header takes the value true or is left off the request, and a frame refuses any other value (400) without running the call. A route whose frame does not read the header refuses a request that carries it (NoDryRunOrWarning): no call runs for real under a header that asked it be held back.

View Source
const ListAcrossTenants accesstypes.Permission = "ListAcrossTenants"

ListAcrossTenants is the permission the global permission digest answers for a resource declared for listing across tenants (@listAcrossTenants): granted while the person may list the resource in at least one tenant the session reaches. It is the digest's own entry and no grant's, so no role names it. A page that lists the resource across tenants is shown, and its route opened, to whoever the digest answers it for.

View Source
const OpenToDirectoryWord = "open"

OpenToDirectoryWord is the word a person types before a tenant is opened to its directory's people (the warning of Open<Record>ToDirectory).

View Source
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.

View Source
const (

	// SecretOverhead is how many bytes sealing adds to a value: the version, the random
	// number and the check. A secret's column is BYTES(n) with n at least the longest
	// value it takes plus this, and the patch decoder sizes a value against the column
	// less this.
	SecretOverhead = secretVersionSize + secretNonceSize + chacha20poly1305.Overhead
)

The layout of a stored secret.

View Source
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.

View Source
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.

View Source
const TenantProperty = "zzTenant"

TenantProperty is the reserved per-row JSON property the generated handlers of a list across tenants name each row's tenant under. Generation rejects resource columns that would collide with it.

View Source
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.

View Source
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.

View Source
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.

View Source
const WarningHeader = "X-Warning"

WarningHeader asks a method that declares a warning (@warning) what the call would do, in place of doing it: the generated frame decodes the request and checks the caller exactly as the call itself is checked, locates the target row where the method names one, calls the method's Warning in place of its Execute, and rolls the transaction back. The answer is the Warning, 200. Every refusal answers as the call's own would, so a caller who may not run the method reads no warning of it. A method that declares no warning refuses the header (400): a request that asks for a warning never runs the call. The header takes the value true or is left off the request, and a frame refuses any other value (400) without running the call. A route whose frame does not read the header refuses a request that carries it (NoDryRunOrWarning).

Variables

View Source
var Demonstrations = []Demonstration{}/* 306 elements not displayed */

Demonstrations is the registry: every capability a demonstration application is expected to prove, seeded from the Lodestar design plan's coverage matrix.

View Source
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.

View Source
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.

View Source
var ErrSecretNotOpened = errors.New("the stored secret does not open on this row: it was written for another row, or was altered after it was written")

ErrSecretNotOpened is the error of opening a stored secret that does not open: its bytes were written for another row, or were altered after they were written.

View Source
var ErrUnsupportedNodeType = errors.New("unsupported AST node type for SQL generation")

ErrUnsupportedNodeType indicates an AST node type that the SQL generator cannot handle.

View Source
var ErrUnsupportedOperator = errors.New("unsupported operator for SQL generation")

ErrUnsupportedOperator indicates a condition operator that the SQL generator cannot handle.

View Source
var ErrWarningAsked = errors.New("warning asked: the transaction rolls back by design")

ErrWarningAsked is the sentinel a generated frame returns from its transaction function once it has read a method's warning: the transaction rolls back, nothing retries, and the frame answers the warning. It never reaches the wire.

Functions

func AfterCommit added in v0.3.0

func AfterCommit(txn ReadWriteTransaction, f func(ctx context.Context)) error

AfterCommit registers f to run once the transaction has committed, after the commit and before ExecuteFunc returns, in registration order. A transaction that does not commit, for any reason, runs nothing, and a transaction Spanner retries runs only what the attempt that committed registered. f runs detached from the request's cancellation and answers nothing: the rows are committed, so a failure in it is f's own to log.

A transaction an application wraps itself and commits outside ExecuteFunc has no executor to make the calls: run them with Committed after the commit.

func AfterCommitOnce added in v0.3.0

func AfterCommitOnce(txn ReadWriteTransaction, key any, f func(ctx context.Context)) error

AfterCommitOnce is AfterCommit for work that is owed once however many writes ask for it: a registration under a key the transaction already holds is dropped. The key is compared with ==, so it is a comparable value that names the work (the pointer of the engine to tell, a constant).

func AsksWarning added in v0.5.0

func AsksWarning(r *http.Request) (bool, error)

AsksWarning reports whether the request asks for the method's warning in place of the call: the header says true. A request without the header asks for none, and a header that says anything else is refused (asksByHeader), which the frame answers in place of running the call.

func AuthFrom added in v0.4.0

func AuthFrom(ctx context.Context) (auth string, ok bool)

AuthFrom returns the name of the auth the request came through, as WithAuth bound it. ok is false when nothing bound one: a request served outside an outlet's generated routes, or a call made outside any request.

func AwaitFirstAdministrator added in v0.3.0

func AwaitFirstAdministrator(ctx context.Context, perms UserPermissions, domain accesstypes.Domain) error

AwaitFirstAdministrator returns once the permission engine answers the session's user a foothold in the tenant whose row and administrator membership the request just committed, bounded by administratorVisibleTimeout, so the answer the route gives is one the person's next request stands on. The generated write paths call it after the commit and once this instance's roster lists the tenant, since the question it asks is the one the next request asks. An error says the engine did not answer in time: the tenant and the membership are committed all the same, so the caller logs it and answers the request.

func BodyLimit

func BodyLimit(limit int64) func(http.Handler) http.Handler

BodyLimit returns middleware that bounds every request body it serves to limit bytes. The generated router applies it once per route, on the group that holds the resource routes and the other JSON routes; the upload, live and RPC routes sit beside that group and bound their own bodies, since a nested limit can only tighten the one outside it. A body that runs past the limit fails the handler's read with *http.MaxBytesError, which the decoders answer with 413 naming the limit, and the server closes the connection behind the response rather than read the rest.

func CheckAPIVersion

func CheckAPIVersion(check APIVersionCheck) func(http.Handler) http.Handler

CheckAPIVersion is the middleware a session outlet's API routes run under. A request carrying APIVersionHeader is answered when its release is between the oldest answered release and the server's, inclusive, and refused with 412 otherwise, before any handler runs and before its body is read; the refusal carries the server's release in APIVersionHeader. A request without the header is answered, and so is any request when either side's version is not a release (dev, or anything that is not a semantic version). Every response on a checked route carries Vary: APIVersionHeader, so a browser never serves one application's cached answer to another. Routes named in Exempt pass untouched. Versions compare as semantic versions, with or without a leading v.

func CheckWarning added in v0.5.0

func CheckWarning(method string, warning *Warning) error

CheckWarning holds a method's warning to what a dialog needs of it before the frame answers it: a consequence to read and the words for the button. A warning that lacks either is the method's mistake, and is an error, never a dialog with an empty warning over a button that says nothing.

func CloneRequest

func CloneRequest(r *http.Request) (*http.Request, error)

CloneRequest creates a deep copy of an http.Request, including its body. This is useful when the request body needs to be read multiple times, as the original body can only be read once. The cloned request gets a new body that can be read and seeked independently.

func ClosedDomains added in v0.5.0

func ClosedDomains(ctx context.Context, perms UserPermissions) ([]accesstypes.Domain, error)

ClosedDomains lists the tenants that are closed to this session: the domains of the application's roster where the person holds at least one grant and that the session does not reach (UserPermissions.Reaches), sorted; never nil. A tenant is closed to a session when it admits its people through its own directory only and the session was not established through that directory. The session's tenant list carries each with the reason (UserDomainsHandler), so a person sees the tenant they hold a seat in and why this sign-in does not open it; nothing else changes for the tenant, whose routes answer the session as a tenant that does not exist. It tells the person nothing new: they hold a seat there.

The permissions SessionPermissions composes answer it, for a person's own sign-in. A session that views the application as someone else, and one that acts as a role, list none: the list is the word a person is given about their own seats and their own sign-in, and such a session is neither. Any other UserPermissions, and an application that keeps no declarations, list none.

func CommitTimestamp

func CommitTimestamp(_ context.Context, _ ReadWriteTransaction) (any, error)

CommitTimestamp is a FieldDefaultFunc that returns the Spanner commit timestamp.

func CommitTimestampPtr

func CommitTimestampPtr(_ context.Context, _ ReadWriteTransaction) (any, error)

CommitTimestampPtr is a FieldDefaultFunc that returns a pointer to the Spanner commit timestamp.

func DeclaredLength

func DeclaredLength(sqltype string) int

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

func DemonstrationDescriptions() map[string]string

DemonstrationDescriptions returns the registry as a map from key to description.

func DemonstrationKeys

func DemonstrationKeys() []string

DemonstrationKeys returns the registry's keys, sorted.

func DirectoryName added in v0.5.0

func DirectoryName(directory signin.Directory, namers ...DirectoryNamer) string

DirectoryName is DirectoryWords with the kind of directory before a name, as a sentence that first speaks of a directory says it: "Google Workspace acme.example", "Microsoft Entra tenant Lakeside", "OpenID Connect provider id.acme.example". A directory nobody has a name for is said by its label as DirectoryWords says it, which names the kind already.

func DirectoryOnlyStateHandler added in v0.5.0

func DirectoryOnlyStateHandler(
	client Client, rules *TenantDirectoryRules, userPermissions func(r *http.Request) UserPermissions,
	tenantParam httpio.ParamType, methods ...accesstypes.Resource,
) http.HandlerFunc

DirectoryOnlyStateHandler serves a tenant's directory-only switch as it stands (DirectoryOnlyState, DirectoryOnlyRoute): what a tenant's Sign-in page shows the person who may turn it. The read is the tenant's own: it is served under the tenant's route and asked under the grants of the methods that turn the switch, Execute in the tenant's scope on one of methods (the one that turns it on, or the one that turns it off), where a caller with neither is Forbidden and learns nothing of the tenant. A grant that holds on a condition is refused the same way: a read has no request for the condition to judge. It writes nothing. client runs it in one transaction, rules are the tenant record's, and tenantParam is the route parameter that names the tenant. The generated handler of a tenant record that declares the switch builds it.

func DirectoryWords added in v0.5.0

func DirectoryWords(directory signin.Directory, namers ...DirectoryNamer) string

DirectoryWords says a directory as the middle of a sentence names it to a person: the name the first namer that knows one gives it ("Lakeside", "acme.example"), and where none does, the directory by the first label a namer answers ("your organization's Microsoft directory"). Where no namer answers anything, an application whose management is not generated or a directory no registration takes any more, it reads what the directory alone says: a Google Workspace's connection is its name or its domain, an OpenID Connect provider's is the application's name for it or its issuer, said by its host, and any other is said by its kind. It never says a tenant id.

func DiscardUpload

func DiscardUpload(ctx context.Context, store FileStore, keys []string, cause error) error

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

func DryRunRolledBack(err error) bool

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

func FeatureFlagsDDL(dbType DBType) []string

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

func FormatByteSize(n int64) string

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

func HasValueLimit(sqltype string, kind ValueKind, slice bool) bool

HasValueLimit reports whether the decoder sizes a field of the given kind, or a slice of it, declared on a column of the given Spanner type. The generator writes the sqltype tag exactly where this is true, so a tag the runtime cannot pair with its field is a stale struct.

func IsDryRun

func IsDryRun(r *http.Request) (bool, error)

IsDryRun reports whether the request asks for a dry run: the header says true. A request without the header asks for none. A header that says anything else is refused (asksByHeader), and the frame answers the refusal in place of running the call, so a client that sends "1" to rehearse a call never writes for real.

func ListedInSomeTenant added in v0.5.0

func ListedInSomeTenant(ctx context.Context, perms UserPermissions, resources []accesstypes.Resource) ([]accesstypes.Resource, error)

ListedInSomeTenant returns, of the resources, the ones the person may list in at least one tenant the session reaches (UserPermissions.Domains), in name order: the people a list of the record across tenants has something to show, which is who its page is for (WithListsAcrossTenants). It asks the List grant alone, as TenantsListed does, one check for each reached tenant until every resource is answered.

func MigrateFeatures

func MigrateFeatures(ctx context.Context, db Client, declared []FeatureDeclaration) error

MigrateFeatures brings the FeatureFlags table to the declared flags, in one transaction: a declared flag the table lacks is inserted disabled, a flag the table holds keeps its Enabled and takes the declared description, and a flag no longer declared is deleted. The audit rows are untouched. It runs in the deploy step beside the role check, before the release takes traffic.

func MockIterSeq2

func MockIterSeq2[Resource Resourcer](err error, resource ...*Resource) iter.Seq2[*Row[Resource], error]

MockIterSeq2 is used for mocking the iter.Seq2[*Row[Resource], error] type returned by List. Each resource is wrapped in the Row envelope. If both err and resource are provided, it will yield all elements in resource first and then err

func NewTenantDeclarationReader

func NewTenantDeclarationReader(table, keyColumn string, columns *TenantDeclarationColumns) signin.DeclarationReader[*spanner.ReadWriteTransaction]

NewTenantDeclarationReader returns the reader of a tenant's declaration for the sign-in policy (signin.TenantPolicy): it reads the tenant record's row and the directories record's rows for the tenant in the sign-in's own transaction, on Spanner, where the session's transaction is *spanner.ReadWriteTransaction. The generated New<Record>DeclarationReader constructor supplies the table and the columns; an application calls that one. A tenant the table does not hold declares nothing (nil). The reader has no side effects, as a retried transaction needs.

func NewTenantDirectoryReader

func NewTenantDirectoryReader(columns *TenantDeclarationColumns) signin.DirectoryReader[*spanner.ReadWriteTransaction]

NewTenantDirectoryReader returns the reader of the declaration of one directory, for a person's first sign-in through it (session.Auth.SetDirectoryAdmission, through signin.DirectoryReader): the directories record's row whose method and connection are the directory's, as its tenant with the directory's default seat (DefaultSeatColumn, "" where the record carries no such column or the row names none), read in the sign-in's own transaction on Spanner. A directory is one tenant's, so the answer names one tenant at most. The generated New<Record>DirectoryReader constructor supplies the columns; an application calls that one. A directory no tenant has answers nothing, and so does a record that declares no directories. The reader has no side effects, as a retried transaction needs.

func NoDryRunOrWarning added in v0.5.0

func NoDryRunOrWarning() func(http.Handler) http.Handler

NoDryRunOrWarning is the middleware of a route whose frame reads neither the X-Dry-Run header nor the X-Warning header: a list, a read, a resource's create, patch and delete, a tenant's creation, a scheduled call. A request that asks for a dry run or for a warning asks that the call be held back, and a frame that never reads the header would run it for real. So the request is refused here (400), naming the header and saying the call has none, and nothing runs. A header that says anything but true is refused as a frame that reads it refuses it (asksByHeader). A request that carries neither header passes through.

The generated router mounts every route under it but the ones whose frames answer the two headers themselves: a method's, an upload's and SetFeature's. A route knows what its frame reads, so the rule is written once, where the routes are registered, and no frame carries a copy of it.

func OpenNullableSecretIn added in v0.5.0

func OpenNullableSecretIn[Resource Resourcer](ctx context.Context, txn ReadWriteTransaction, key KeySet, field accesstypes.Field, stored *Secret) (*string, error)

OpenNullableSecretIn is OpenSecretIn for the secret of a nullable column: no value for a row that holds none.

func OpenSecretIn added in v0.5.0

func OpenSecretIn[Resource Resourcer](ctx context.Context, txn ReadWriteTransaction, key KeySet, field accesstypes.Field, stored Secret) (string, error)

OpenSecretIn opens the secret field of a row inside a read-write transaction, with the keys of the transaction's client, and rewrites a value sealed under an older version of the application secret under the current one in the same transaction. It is what the generated Open<Field>In method of a row calls, with the row's own key; application code calls that method.

The rewrite is the stored bytes alone: the value does not change, so no permission is asked, no update function stamps the row and no change record is written. It is buffered only when the row still holds the bytes that were opened, read inside the transaction, so a row read before the transaction began never overwrites a value set since, and never for a row a patch of the same transaction has already written, whose buffered write no read sees.

func Operations

func Operations(r *http.Request, pattern string, opts ...Option) iter.Seq2[*Operation, error]

Operations parses a batch JSON patch request and yields an iterator of individual Operation objects.

func ParseByteSize

func ParseByteSize(text string) (int64, error)

ParseByteSize reads a size the way @upload declares it: a count of bytes, or a count suffixed KB, MB, or GB (1024-based).

func PatchSetDiff

func PatchSetDiff(opts ...cmp.Option) func(a, b PatchSetComparer) string

PatchSetDiff compares two PatchSetComparer objects for equality. It checks resource, patch type, data, fields, and primary keys. A difference in a secret field is reported with [secret] on both sides: what it answers is printed by tests and carried in errors, and a patch holds a secret as the text it was given.

func PermissionDigestHandler

func PermissionDigestHandler(userPermissions func(r *http.Request) UserPermissions, opts ...DigestOption) http.HandlerFunc

PermissionDigestHandler serves the per-scope permission digest: the session user's structural grant enumeration, resource → permission → granted|conditional, with denied targets absent so consumers fail closed. The generated router registers it on the default outlet; applications wire nothing.

The scope is the request's input, never payload structure: ?domain= names one tenant partition, its absence means the global scope. There is no domain validation — an unknown tenant simply holds no grants, so its digest is empty, which also keeps concealed tenancy unprobeable from this endpoint. The payload is advisory UI material (which surfaces to render); enforcement stays with the endpoint gate, the read rules, and the write stages. With WithFeatureGates the entries behind a flag that is off are left out too.

func ProcessEvent

func ProcessEvent(processName string) string

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 Refused

func Refused(err error) (int, bool)

Refused reports whether a transaction ended by an Answer, and with which status.

func ReleaseHeader

func ReleaseHeader(release string) func(http.Handler) http.Handler

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

func RequireFileStores(client Client, names ...StoreName) error

RequireFileStores reports which of the named stores the client holds no store for: the generated router calls it at start with every store the package uses, and refuses to start naming the first store that is not wired. The message names the store and the option that wires it, never a configuration variable, since where the URL comes from is the application's configuration's convention.

func RequireSecretKeys added in v0.5.0

func RequireSecretKeys(client Client, fields ...string) error

RequireSecretKeys refuses a client built with no secret keys for an application that stores secrets: the generated router calls it at start with every secret field its package declares, and refuses to start naming them. Without the check the first write of a secret would be the first to fail. A client wired to an environment that carries no version (SecretKeysFromEnv) is refused naming the variable that is missing, the first version's, under the name the application declares; a client that was never given a holder is refused naming the wiring.

func ResponseStatus

func ResponseStatus(method string, result any, declared ...int) (int, error)

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

func RowKey(values ...any) string

RowKey spells a row's primary key the way the read route does: the key values in route order, each in its text form, joined with "/". It is the key a live row subscription names and a change document carries, so a client that addresses the row by its route and the publisher that saw the patch spell it identically.

func ServeRenderedFile

func ServeRenderedFile(w http.ResponseWriter, r *http.Request, content *Content, segment, label string, key ...any) error

ServeRenderedFile answers a computed resource's @file route with what its content function rendered: 304 when the request's validator matches the content's Tag, the bytes otherwise, and, for a nil content, a 404 in the row's words returned for the handler to encode. The function never touches the response; the frame does.

func ServeStoredFile

func ServeStoredFile(ctx context.Context, w http.ResponseWriter, r *http.Request, store FileStore, file StoredFile, segment, label string, key ...any) error

ServeStoredFile answers a @file route from the store the column names, read off the resource client by the generated handler: 304 when the request's validator matches the key, before the store is opened, and the bytes otherwise, typed by the row's type column, then the object's, then the name's extension, under the file headers (nosniff, the frame's sandbox policy, and the disposition the type decides). A row carrying no key, or a key the store holds nothing under, is a 404 returned for the handler to encode, in the row's words (label and key, "MissionDocument 0193…") and never the store key's; so is any other failure. A nil store, the column's store not wired on the client, is an error naming the wiring, answered 500.

func SessionDirectory added in v0.5.0

func SessionDirectory(ctx context.Context) (signin.Directory, error)

SessionDirectory answers the directory the request's session was established through: what "make the directory I am signed in through this tenant's directory" names. A session that came through no directory (a password, a session the application started itself, an impersonation) is refused with a Conflict that says how to sign in instead; a personal account is answered as it is, for the rules to refuse it by name (TenantDirectoryRules.Set).

func SetFeatureEnabled

func SetFeatureEnabled(ctx context.Context, db Client, name Feature, enabled bool, eventSource string) error

SetFeatureEnabled flips one flag in its own transaction: the row takes the value, the commit timestamp and eventSource, and the audit table gains the flip's row. A name the table does not hold is a not-found error. SetFeatureHandler flips through the same write; a bootstrap or a test flips a flag directly through this.

func SetFeatureHandler

func SetFeatureHandler(a FeatureApp, collection *GeneratedCollection, signals Signaler) http.HandlerFunc

SetFeatureHandler flips a flag, to an Execute grant on SetFeature: the row takes the value with the commit timestamp and the principal, the audit table gains the flip's row in the same transaction, KindFeatures is signaled after the commit and before the answer (bounded by FeatureSignalTimeout; a failure is logged, since the other instances reload at their backstop), this instance's copy reloads, and the answer is the flag from the reloaded copy. An unknown name is 404. A dry run (X-Dry-Run: true) runs the frame and rolls back, as every transaction-form method does. The signaler is the application's live service, which every application wires; the handler refuses to be built without one. The generated router registers it at POST <prefix>/set-feature on every session-serving outlet.

func SetLocalZone

func SetLocalZone(zone *time.Location)

SetLocalZone wires the timezone the bare word local resolves to inside a temporal grant condition — timeOfDay(now, local), dayOfWeek(now, local) (design plan §05). Call it once at application startup, before serving; where the zone comes from is the application's business (a config constant today; a session- or tenant-resolved source rides the same seam later). Unwired, a condition using local fails its check loudly at first use — the same posture as a missing now — while explicit-zone conditions need no wiring at all.

func SignInRoles

func SignInRoles(manager signin.UserRoleManager) signin.UserRoleManager

SignInRoles adapts the access library's user manager to the sign-in policy (signin.TenantPolicy) on Spanner. The policy reads the person's memberships inside the sign-in's read-write transaction, with the transaction's context, and the Spanner client refuses a read made with that context as a nested transaction, so the manager handed to the policy directly fails every sign-in the policy decides. The adapter reads the memberships outside the transaction, under the sign-in's deadline and cancellation and nothing else of its context, as the committed memberships, which is what the policy decides over on PostgreSQL too, and it reads which tenants the person administers the same way. The manager's other operations pass through unchanged.

func SortRows

func SortRows[T any](rows []*T, order []SortField, dbType DBType) error

SortRows orders rows in memory by the given fields: each field by its type, with NULL placed where the application's database (dbType) places it — Spanner first ascending and last descending, PostgreSQL last ascending and first descending — stably so equal rows keep their yielded order. A computed resource's generated handler sorts the body's rows with it, so a computed list places NULL at the same end as the tables beside it; a body that takes the sort (QuerySet.TakeSort) orders its own query instead, and a plain ORDER BY there produces the same placement. An unsupported dbType is an error.

func TenantKeyEquals

func TenantKeyEquals(value any, domain accesstypes.Domain) (bool, error)

TenantKeyEquals reports whether a row's tenant-key value equals the request partition. It is the generated transition handlers' row-location test: a mismatch renders the target NotFound, indistinguishable from a row that does not exist. The domain converts into the value's own type exactly the way the decode-seam stamp converts it.

func TenantsListed added in v0.5.0

func TenantsListed(ctx context.Context, perms UserPermissions, res accesstypes.Resource, narrowed []accesstypes.Domain) ([]accesstypes.Domain, error)

TenantsListed is the set of tenants a list of the record across tenants reads for the person: the tenants the session reaches (UserPermissions.Domains), narrowed to the ones narrowed names when it is not nil, in which the person holds the List grant on the record, sorted. The live renewal works a subscription's set out again with it, as the list's own request worked it out (QuerySet.TenantsListed).

func UserDomainsHandler

func UserDomainsHandler(userPermissions func(r *http.Request) UserPermissions, opts ...UserDomainsOption) http.HandlerFunc

UserDomainsHandler serves the session's tenant list: the domains where the user holds at least one grant, sorted, each with its name (UserDomain), and each that the session does not reach marked closed, with the reason. It is the tenant picker's question, answered by the library so applications wire nothing — the generated router registers it on the default outlet beside the digest. The picker shows a tenant's name: the people of a tenant cannot read the tenant record, a global resource, so the list carries the name for them (WithDomainNames).

The predicate is concealed tenancy's own foothold test over the session's admission (UserPermissions.HasGrants, UserPermissions.Reaches), so a domain listed here is exactly a domain whose routes answer the user with ordinary 403s rather than a concealing 404; the picker and the guard can never disagree. A tenant is offered only when the session may enter it, and the application's tenant declaration decides (TenantDeclarations): a tenant whose declaration does not admit the way the session was established is listed closed (UserDomain.Closed), since the person holds a seat there and is owed the reason, and its routes answer the session with the concealing 404 all the same. The global scope is never a domain. The answer reports grants, not tenants: a domain the application has since removed still lists while grants in it remain, and existence is the tenant roster's (TenantRoster.Has). Structural and non-folding, so it caches cleanly per user and session. The payload is always a JSON array — an empty membership is [], never null.

func UserEvent

func UserEvent(ctx context.Context) string

UserEvent generates a standard event source string for an action performed by a user. It extracts user information from the context. A person is written as their username with the id of their account, since the name is what people read and can change, and the id is who they are; the session comes last, as the evidence of how they were signed in: "username (account id), session id" for an ordinary session. For an impersonated session the actor comes first, so every data change carries evidence of the real person: "actor (account id) impersonating username (account id), session id" for an impersonated user, "actor (account id) as role name, session id" for a role. A person with no account here (a session type that keeps none, an actor another application authenticated) is written by name alone.

func UserProcessEvent

func UserProcessEvent(ctx context.Context, processName string) string

UserProcessEvent generates a standard event source string for an action performed by a user within a specific system process.

func ValidFeatureName

func ValidFeatureName(name string) bool

ValidFeatureName reports whether name has a flag name's shape.

func ValidateFeatureDeclarations

func ValidateFeatureDeclarations(declared []FeatureDeclaration) error

ValidateFeatureDeclarations refuses a declaration whose name is malformed and two declarations of one name, each refusal naming the constant.

func WarningAsked added in v0.5.0

func WarningAsked(err error) bool

WarningAsked reports whether a transaction ended by the warning sentinel.

func WithAuth added in v0.4.0

func WithAuth(ctx context.Context, auth string) context.Context

WithAuth binds the request to the auth whose sessions its outlet serves, by the auth's name (the auth package's Name). An outlet's generated routes bind it on every request (live.Subscribing), so whatever answers for the request can tell the people of one auth from another's: two auths over one database may each hold a person of the same username, and they are two people.

func WithCaller

func WithCaller(ctx context.Context, caller *Caller) context.Context

WithCaller stamps the caller into the context for the code that runs under it. The generated frames call it; a handler written by hand calls it too where what it runs asks who the caller is.

Types

type APIVersionCheck

type APIVersionCheck struct {
	// ServerVersion is the release the server was built from, the configuration's
	// APP_VERSION. A value that is not a release, dev for one, checks nothing.
	ServerVersion string
	// OldestAnswered is the oldest release still answered: a release such as 1.5.0,
	// ThisRelease for the server's own, or empty for every release that sends the
	// header.
	OldestAnswered string
	// Exempt are the route patterns answered whatever the header says: the
	// stored-file routes, which a link or an image reaches.
	Exempt []string
}

APIVersionCheck is what a session outlet's version check compares a request's APIVersionHeader against. The generated router builds one per session outlet from the server version the application reports and the oldest answered release the generator program declared.

type AcrossTenantsLists added in v0.5.0

type AcrossTenantsLists interface {
	ListedAcrossTenants() []accesstypes.Resource
}

AcrossTenantsLists answers the resources declared for listing across tenants (@listAcrossTenants), as the generated collection does.

type Answer

type Answer struct {
	Status int
}

Answer is the sentinel a generated frame returns from its transaction function when a method's answer is a refusal (a 4xx): the transaction rolls back, nothing retries, and the frame writes the status with the typed body it captured. It never reaches the wire as an error.

func (*Answer) Error

func (a *Answer) Error() string

Error names the refusal; the frame never writes it.

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

type BindingHop struct {
	Table      string
	JoinColumn string
	Column     string
}

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.

func (*BodyDecoder[Request]) Decode

func (b *BodyDecoder[Request]) Decode(r *http.Request) (*Request, error)

Decode decodes the request's body into the request type and validates it.

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 (b *BrowserApp) DeepLink(next http.Handler) http.Handler

DeepLink rewrites the application's own routes to its entry document, so a bookmarked or reloaded route loads the application. A request whose last path segment has no extension, Angular matrix parameters (";key=value") removed, is rewritten to <mount>/index.html and passed on; a path with an extension passes through unchanged, matrix parameters and all, and is a file or a 404.

type Buffer

type Buffer interface {
	Buffer(ctx context.Context, txn ReadWriteTransaction, eventSource ...string) error
}

Buffer is an interface for types that can buffer their mutations into a transaction. This is used for batching operations.

type Caller

type Caller struct {
	// Permissions is the checker the entry check ran with: the session's user, or
	// the role an act-as-role session assumed, behind the session's mask.
	Permissions UserPermissions
	// Scope is the partition the request was checked in.
	Scope accesstypes.Scope
	// Env is the decision environment the entry check sampled.
	Env accesstypes.Environment
	// contains filtered or unexported fields
}

Caller is what the generated frame knows about a request's caller once the entry check has run: the checker that check ran with, the scope it ran in, and the environment it sampled, so a body that arms a write or a read against the caller evaluates the same facts the entry check did (the decision instant included). The generated handlers stamp it into the context before the application's code runs: a method's frame before Execute and Warning, and a computed resource's frames before its List function, its Read function and the function that renders a file. That code reads it back with CallerFrom. Within such a request a zero Caller is therefore never seen; no caller means a call the application makes outside any request, or a handler that stamped none.

func CallerFrom

func CallerFrom(ctx context.Context) *Caller

CallerFrom returns the caller the frame stamped, or a zero Caller when none was: a mutation or query armed with a zero Caller refuses at execution instead of running unchecked. Code that reads a zero Caller as a call of the application's own, as the identity library's rules do, relies on every frame that serves a person stamping one.

func (*Caller) As

func (c *Caller) As(perms UserPermissions) *Caller

As returns the caller acting through another checker in the same scope and environment: a body that should act as a named role composes the checker the way act-as-role sessions do (RolePrincipalPermissions over access.ForRole) and arms its operations with the result. The actor stays who it was.

func (*Caller) Check

Check answers, as data, what the caller may do: the decision for perm on each resource (a resource, or a field of one as "Resource.field"), evaluated in the caller's scope and environment. A body branches on the answers where policy should decide what it does, without arming a write.

func (*Caller) ExecuteGate added in v0.5.0

func (c *Caller) ExecuteGate(ctx context.Context, method accesstypes.Resource, request any) (*ExecuteGate, error)

ExecuteGate answers the caller's Execute decision on another method, for a request the body builds in place of one a decoder read: what that method's own frame would decide for the request, in the scope and the environment the caller was checked in. A body that does through one method what another method does asks it, so the grant of the method that does the thing directly judges the same thing done another way: a person put in a group is given the group's roles, and is judged by the grant of the method that gives a role.

Denied is the Forbidden the method's own decode answers. The atoms of a conditional grant that read the method's request fields (new.<name>) are settled against request, a value of the method's own request struct. What is left reads the method's target row and rides the gate: Settled says whether anything is left, and Enforce, EnforceView or EnforceProposed judges it against the row.

func (*Caller) IsZero

func (c *Caller) IsZero() bool

IsZero reports whether no frame stamped the caller.

type CallerPassword added in v0.5.0

type CallerPassword func(ctx context.Context, txn ReadWriteTransaction) (has, applies bool, err error)

CallerPassword answers, for one auth, whether the person behind the request holds a password in it, in the caller's transaction. applies is false where the auth asks nothing of the request: its caller is another auth's person, or the auth has no password method, so nobody of it could have a password. The generated identity client of each auth supplies it (CallerPassword); an application names none.

type Client

type Client interface {
	// DBType is the application database's type: the placement its lists sort NULL
	// in, which a computed resource's handler follows (NewComputedQueryDecoder).
	DBType() DBType
	// FileStore returns the file store wired under name (WithFileStore for
	// DefaultStore, WithNamedFileStore for a named store's StoreNameFor), or nil when
	// none is: the generated upload frames and file routes read their store here, the
	// one wiring point, and the generated router refuses to start when a store the
	// package uses is not wired (RequireFileStores). The Postgres client holds none.
	FileStore(name StoreName) FileStore
	ReadOnlyTransaction() ReadOnlyTransactionCloser
	ReadOnlyTransaction
	Executor
}

Client is an interface for the supported database Client's to implement. It is not intended for mocking since each database requires an implementation in this package.

type ClientOption

type ClientOption func(*clientOptions)

ClientOption configures a database client at construction.

func WithFileStore

func WithFileStore(store FileStore) ClientOption

WithFileStore wires the default store: the one an untyped @file column, an unnamed @upload and resource.Files belong to. The upload frames stream into it, the file routes open from it, and a transaction that deletes a row carrying a default-store key, or points it at another object, has the old object deleted from it once the commit lands. Wired twice, the client panics at construction naming the store.

func WithNamedFileStore

func WithNamedFileStore[S NamedStore](store FileStore) ClientOption

WithNamedFileStore wires the named store S: the one a Key[S] column, an @upload(store: S) and FilesIn[S] belong to. Any number of named stores of different types can be wired; the same type wired twice panics at construction naming the store.

func WithSecretKeys added in v0.5.0

func WithSecretKeys(keys *SecretKeys) ClientOption

WithSecretKeys hands the client the application's secret keys: the write path seals every secret field a patch sets with them, where it turns the patch's fields into columns, so no application code encrypts anything. A client built without them refuses to write a secret, and the generated router of an application that stores one refuses to start (RequireSecretKeys). Given twice, the client panics at construction.

type CollectionBuilder

type CollectionBuilder struct {
	// contains filtered or unexported fields
}

CollectionBuilder assembles CollectionData by replaying the registration semantics a permission collection enforces: duplicate detection, null-permission filtering, and immutable-field replacement (the last registration for a resource wins).

func NewCollectionBuilder

func NewCollectionBuilder() *CollectionBuilder

NewCollectionBuilder creates an empty CollectionBuilder.

func (*CollectionBuilder) AddMethodResource

func (b *CollectionBuilder) AddMethodResource(scope accesstypes.PermissionScope, permission accesstypes.Permission, res accesstypes.Resource) error

AddMethodResource registers a method resource permission, rejecting duplicate registrations (generated RPC handlers).

func (*CollectionBuilder) AddResource

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

Data returns the canonical, deterministically sorted form of everything registered so far.

func (*CollectionBuilder) GeneratedCollection

func (b *CollectionBuilder) GeneratedCollection() *GeneratedCollection

GeneratedCollection returns the built collection directly, for consumers that do not need the serializable form. The builder must not be used again afterward: the returned collection shares its storage.

func (*CollectionBuilder) SetMethodFormerName

func (b *CollectionBuilder) SetMethodFormerName(scope accesstypes.PermissionScope, method, former accesstypes.Resource)

SetMethodFormerName records an RPC method resource's former name within scope: the name older browser applications still execute it under.

func (*CollectionBuilder) SetMethodTarget

func (b *CollectionBuilder) SetMethodTarget(scope accesstypes.PermissionScope, method, target accesstypes.Resource)

SetMethodTarget records the row resource an RPC method's @target field addresses within scope.

func (*CollectionBuilder) SetMethodTransition

func (b *CollectionBuilder) SetMethodTransition(scope accesstypes.PermissionScope, method accesstypes.Resource, transition TransitionData)

SetMethodTransition records an RPC method resource's declared state transition (@transition) within scope.

func (*CollectionBuilder) SetResourceBindings

func (b *CollectionBuilder) SetResourceBindings(scope accesstypes.PermissionScope, res accesstypes.Resource, bindings *Bindings)

SetResourceBindings registers a resource's binding vocabulary, replacing any previous registration for that resource — the generator computes one vocabulary per resource.

func (*CollectionBuilder) SetResourceComputed

func (b *CollectionBuilder) SetResourceComputed(scope accesstypes.PermissionScope, res accesstypes.Resource)

SetResourceComputed marks res as a computed resource within scope: one whose rows come from the application's Go function, so its permission checks run at decode time, and a grant's condition that reads the row is judged in Go over the rows the function yields, no query of the library's being there to judge it.

func (*CollectionBuilder) SetResourceListsAcrossTenants added in v0.5.0

func (b *CollectionBuilder) SetResourceListsAcrossTenants(res accesstypes.Resource)

SetResourceListsAcrossTenants marks res, a tenant's resource, as declared for listing across tenants (@listAcrossTenants).

func (*CollectionBuilder) SetResourceParent

func (b *CollectionBuilder) SetResourceParent(scope accesstypes.PermissionScope, member, parent accesstypes.Resource)

SetResourceParent records a workflow member's immediate parent within scope: the resource its @stateRoot foreign key references.

func (*CollectionBuilder) SetResourceQueryKeys

func (b *CollectionBuilder) SetResourceQueryKeys(scope accesstypes.PermissionScope, res accesstypes.Resource, order, queryKeys []accesstypes.Tag)

SetResourceQueryKeys records how a list of res is ordered and narrowed within scope: its declared default order and the fields a request may filter and sort by with an index behind it (see CollectionResource).

func (*CollectionBuilder) SetResourceRequiredTags added in v0.4.0

func (b *CollectionBuilder) SetResourceRequiredTags(scope accesstypes.PermissionScope, res accesstypes.Resource, required []accesstypes.Tag)

SetResourceRequiredTags records the fields a create of res must be given by the client within scope (see CollectionResource.RequiredTags). A tag that does not carry Create by the time the data is read is left out of it: no grant could name it.

type CollectionData

type CollectionData struct {
	Resources []CollectionResource
}

CollectionData is the stable, serializable description of a permission collection. It is the schema the generator emits into generated collection files and the input NewGeneratedCollection validates, decoupling generated code from the collection's internal representation.

type CollectionResource

type CollectionResource struct {
	Name  accesstypes.Resource
	Scope accesstypes.PermissionScope

	// Computed marks a computed resource: one whose rows come from the
	// application's Go function, with no query of the library's for the database
	// to judge a row's condition in. The library judges the rows the function
	// yields, in Go, against the Attributes below (each one's Column is the row
	// struct's Go field), and deploy-time grant validation (access.MigrateRoles)
	// uses the marker to name that declaration where a condition reads a field
	// the resource has not declared.
	Computed bool

	Permissions   []accesstypes.Permission
	Tags          []TagData
	ImmutableTags []accesstypes.Tag

	// Formerly is an RPC method resource's former name (@formerly on the method): the
	// name older browser applications still execute it under, which the generated
	// router answers at the former route and the permission digest mirrors beside the
	// current name. Empty for a method never renamed and for every other resource.
	Formerly accesstypes.Resource

	// The resource's binding vocabulary (ABAC design plan §04), compiled from
	// the field-level binding annotations: attributes conditions reference,
	// the structural tenancy binding, and the subject-side vocabulary.
	Attributes    []AttributeData
	Domain        *DomainBindingData
	SubjectSets   []SubjectBindingData
	SubjectValues []SubjectBindingData

	// Transition is an RPC method resource's declared state transition
	// (@transition, design plan §09); nil for everything else.
	Transition *TransitionData

	// Target is the row resource an RPC method's @target field addresses —
	// set for every @target method, transition or plain (a transition's
	// Target repeats its TransitionData.Target); empty for everything else.
	// A targeted method's Execute grants may carry row-referencing
	// conditions: the generated handler locates the row in its transaction
	// and evaluates them there (design plan §12).
	Target accesstypes.Resource

	// Parent is a workflow member's immediate parent: the resource its
	// @stateRoot foreign key references (the root, or another member on the
	// chain); empty for everything else. The create-under-parent affordance
	// (design plan §11) rides it: capabilities=Create on the parent's read
	// answers, per row, which member resources the user may create beneath it.
	Parent accesstypes.Resource

	// How a list of the resource is ordered and narrowed, for a listed table
	// or view resource. Order is the declared default order (@order), the
	// fields every page sorts by when the request carries no sort; QueryKeys
	// are the fields a request may name in a filter and sort by with an index
	// behind it — the indexed and allow_filter fields — primary keys aside,
	// which are exempt from masking. Deploy-time role validation
	// (access.MigrateRoles) reads them with each tag's Masking to warn where a
	// conditional grant puts a CASE in the ORDER BY or the WHERE.
	Order     []accesstypes.Tag
	QueryKeys []accesstypes.Tag

	// RequiredTags are the fields a create of the resource must be given by the
	// client, as wire tags: the column takes no NULL, and neither a column default
	// nor the server fills it (no default_create_fn, no key, no field the server
	// owns). A create that leaves one out is refused at commit, so deploy-time role
	// validation (access.MigrateRoles) reads them to warn where a role's Create
	// grants on the resource cover none of its grants' fields for one: no holder of
	// that role alone can create a row. Each is a tag of the resource that carries
	// Create.
	RequiredTags []accesstypes.Tag

	// ListsAcrossTenants marks a tenant's resource declared for listing across
	// tenants (@listAcrossTenants): its list is also served without the tenant's
	// route segment. Only such a resource is decoded as a list across tenants
	// (QueryDecoder.DecodeAcrossTenants), named to the page in the permission digest
	// (WithListsAcrossTenants), or held as one live subscription over a set of
	// tenants.
	ListsAcrossTenants bool
}

CollectionResource describes one resource's registrations within a permission collection. RPC methods and manually registered resources carry only Permissions.

type Columns

type Columns string

Columns is a string representing a comma-separated list of database column names.

type ComputedQueryDecoder

type ComputedQueryDecoder[Resource Resourcer, Request any] struct {
	// contains filtered or unexported fields
}

ComputedQueryDecoder decodes an HTTP request for a computed resource and enforces user permissions at decode time.

Computed resources execute application-written functions, so — like RPC methods — there is no library execution underneath them to carry the permission check: decode is the last library-controlled point before application code runs. QueryDecoder's deferred enforcement (discharged by QuerySet.Read/List) therefore cannot serve the computed path; this decoder checks eagerly instead, and the QuerySet it returns carries the request with the checks passed and the fields materialized. What is left for after the application's function is a grant's condition that reads the row: the QuerySet judges each row the function yields (computed_conditions.go).

func MustNewComputedQueryDecoder

func MustNewComputedQueryDecoder[Resource Resourcer, Request any](dbType DBType, permissions ...accesstypes.Permission) *ComputedQueryDecoder[Resource, Request]

MustNewComputedQueryDecoder builds a query decoder for a computed resource and request pair over the application database's type (see NewComputedQueryDecoder). It panics on construction errors: they are programming errors (a request struct out of sync with its resource, a database type the package does not know), surfaced at application startup where generated handlers construct their decoders.

func NewComputedQueryDecoder

func NewComputedQueryDecoder[Resource Resourcer, Request any](resSet *Set[Resource], dbType DBType) (*ComputedQueryDecoder[Resource, Request], error)

NewComputedQueryDecoder creates a new ComputedQueryDecoder for a given Resource and Request type. dbType is the application database's type: a computed list sorts and pages NULL where that database does, the same end as the tables beside it, so the decoder carries the placement even though no library query runs underneath it. An unsupported type is a construction error.

func (*ComputedQueryDecoder[Resource, Request]) Decode

func (d *ComputedQueryDecoder[Resource, Request]) Decode(request *http.Request, userPermissions UserPermissions, scope accesstypes.Scope) (*QuerySet[Resource], error)

Decode decodes an http.Request into a QuerySet and checks user permissions in the given domain partition. The semantics mirror the deferred enforcement table resources get at execution time: a missing resource-level grant is Forbidden, an explicitly requested field without its grant is Forbidden, and when no fields are requested the QuerySet is narrowed to the fields some grant covers.

The checks are eager (application code produces the rows), and a grant under a condition is a grant, as on a table: the resource and the fields it covers pass here, and the Conditional decisions ride the QuerySet, which judges each row the application's function yields (QuerySet.Collect, QuerySet.Admit). A sort or filter field alone needs the caller's unconditional grant.

func (*ComputedQueryDecoder[Resource, Request]) WithCollection added in v0.3.0

func (d *ComputedQueryDecoder[Resource, Request]) WithCollection(collection *GeneratedCollection) *ComputedQueryDecoder[Resource, Request]

WithCollection installs the application's generated collection: the attributes the computed resource declares, which a grant's condition that reads the row resolves against. A decoder without one refuses such a grant when it is met.

func (*ComputedQueryDecoder[Resource, Request]) WithCursorKey

func (d *ComputedQueryDecoder[Resource, Request]) WithCursorKey(key *CursorKey) *ComputedQueryDecoder[Resource, Request]

WithCursorKey installs the key that seals this decoder's cursors (see QueryDecoder.WithCursorKey).

func (*ComputedQueryDecoder[Resource, Request]) WithFeatures

func (d *ComputedQueryDecoder[Resource, Request]) WithFeatures(features *FeatureSet) *ComputedQueryDecoder[Resource, Request]

WithFeatures installs the FeatureSet the gated fields' flags are read from (see QueryDecoder.WithFeatures).

func (*ComputedQueryDecoder[Resource, Request]) WithPaging

func (d *ComputedQueryDecoder[Resource, Request]) WithPaging(paging Paging) *ComputedQueryDecoder[Resource, Request]

WithPaging installs the computed resource's declared paging contract (see QueryDecoder.WithPaging).

func (*ComputedQueryDecoder[Resource, Request]) WithSubjectFacts added in v0.3.0

func (d *ComputedQueryDecoder[Resource, Request]) WithSubjectFacts(source SubjectFactSource) *ComputedQueryDecoder[Resource, Request]

WithSubjectFacts installs the client the facts about the caller are read through: a grant's condition that compares a row against a subject value or a subject set (subject.<name>) has the fact read once for the request, when it is decoded. A decoder without one refuses such a grant when it is met.

type Condition

type Condition struct {
	Field    string
	Operator string
	Value    any   // For eq, ne, gt, lt, gte, lte, startswith, endswith, contains, and the box's text
	Values   []any // For in, notin
	IsNullOp bool  // For isnull, isnotnull
	// contains filtered or unexported fields
}

Condition represents a single condition (e.g., name:eq:John).

func (*Condition) IsSearch

func (c *Condition) IsSearch() bool

IsSearch reports whether the condition is the search box, *:search:"…".

func (*Condition) IsTextMatch

func (c *Condition) IsTextMatch() bool

IsTextMatch reports whether the condition is a startswith, endswith or contains match on a text field.

func (*Condition) MatchesText

func (c *Condition) MatchesText(text string) bool

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

func (c *Condition) SearchFields() []string

SearchFields names the Go fields the box searches on the resource, in declaration order, for a body that took the box.

func (*Condition) SearchTerms

func (c *Condition) SearchTerms() []string

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

func (c *Condition) TypedValues() any

TypedValues returns an in or notin list as a slice of the values' own type, the shape an array query parameter binds: Spanner types IN UNNEST(@p) from the slice's element type and refuses []any. The parser types every value by its column, so the slice is []string for a STRING column, []int64 for INT64, and []*big.Rat for NUMERIC, following paramValue. A value that carries its own Spanner encoding binds as what it encodes to, an id as its text: the client binds one such value and no array of them. A body that pushes a taken filter down to its own query binds the result as it is. An empty list, or one the values do not type uniformly, is returned unchanged.

type ConditionNode

type ConditionNode struct {
	Condition Condition
}

ConditionNode represents a simple condition in the AST.

func (*ConditionNode) String

func (cn *ConditionNode) String() string

String returns a string representation of the ConditionNode.

type Config

type Config struct {
	ChangeTrackingTable string
	TrackChanges        bool
}

Config holds database-specific configuration for a resource.

func (Config) SetChangeTrackingTable

func (c Config) SetChangeTrackingTable(changeTrackingTable string) Config

SetChangeTrackingTable returns a new Config with the change tracking table name set.

func (Config) SetTrackChanges

func (c Config) SetTrackChanges(trackChanges bool) Config

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

func NewCursorKey(cookieKeyBase64 string) (*CursorKey, error)

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.

const (
	// SpannerDBType represents the Google Cloud Spanner database.
	SpannerDBType DBType = "spanner"

	// PostgresDBType represents the PostgreSQL database.
	PostgresDBType DBType = "postgres"

	// MockDBType represents a database type for mocking
	MockDBType DBType = "mock"
)

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

Resource returns the Resource name for DataChangeEvent

type Decoder

type Decoder[Resource Resourcer, Request any] struct {
	// contains filtered or unexported fields
}

Decoder is a struct that can be used for decoding http requests and validating those requests

func MustNewDecoder

func MustNewDecoder[Resource Resourcer, Request any](a DecoderAccessor, collection *GeneratedCollection, permissions ...accesstypes.Permission) *Decoder[Resource, Request]

MustNewDecoder builds a patch decoder for a resource and request pair, validating requests with the accessor's validator and wired to the application's generated collection so conditional grants can render into the mutations' live check. It panics on construction errors: they are programming errors (a request struct out of sync with its resource), surfaced at application startup where generated handlers construct their decoders.

func NewDecoder

func NewDecoder[Resource Resourcer, Request any](rSet *Set[Resource]) (*Decoder[Resource, Request], error)

NewDecoder creates a new Decoder for a given Resource and Request type.

func (*Decoder[Resource, Request]) DecideOperation added in v0.4.0

func (d *Decoder[Resource, Request]) DecideOperation(ctx context.Context, txn ReadWriteTransaction, oper *Operation, userPermissions UserPermissions, scope accesstypes.Scope, key KeySet) (*Operation, error)

DecideOperation answers the operation a patch-or-add runs as: the patch when the row its path names is there, the add when it is not. The handler then decodes and runs that operation as it does any patch or add.

A patch-or-add is an update first: the caller's Update grant on the resource is asked for before the row is looked for, so a caller who may not update is refused the same way whether or not the row is there, and learns nothing from the answer. Which fields the caller may write, and on which rows, is the decoded operation's own check.

The read is the one an OrCreate patch makes (patch_fork.go): the key alone, inside the transaction, held to the tenant in a tenant's scope, after the transaction's own record of the rows it wrote, so an earlier operation of the same batch counts.

func (*Decoder[Resource, Request]) Decode

func (d *Decoder[Resource, Request]) Decode(request *http.Request, userPermissions UserPermissions, scope accesstypes.Scope, requiredPermission accesstypes.Permission) (*PatchSet[Resource], error)

Decode decodes an http.Request into a PatchSet and enables user permission enforcement in the given domain partition.

func (*Decoder[Resource, Request]) DecodeOperation

func (d *Decoder[Resource, Request]) DecodeOperation(oper *Operation, userPermissions UserPermissions, scope accesstypes.Scope) (*PatchSet[Resource], error)

DecodeOperation decodes an Operation into a PatchSet and enables user permission enforcement in the given domain partition.

func (*Decoder[Resource, Request]) DecodeOperationWithoutPermissions

func (d *Decoder[Resource, Request]) DecodeOperationWithoutPermissions(oper *Operation) (*PatchSet[Resource], error)

DecodeOperationWithoutPermissions decodes an Operation into a PatchSet without enforcing user permissions.

func (*Decoder[Resource, Request]) DecodeWithoutPermissions

func (d *Decoder[Resource, Request]) DecodeWithoutPermissions(request *http.Request) (*PatchSet[Resource], error)

DecodeWithoutPermissions decodes an http.Request into a PatchSet without enforcing any user permissions.

func (*Decoder[Resource, Request]) WithFeatures

func (d *Decoder[Resource, Request]) WithFeatures(features *FeatureSet) *Decoder[Resource, Request]

WithFeatures installs the FeatureSet the decoder reads the gated fields' flags from; the generated wiring passes the application's. Without it every gated field stays hidden.

func (*Decoder[Resource, Request]) WithValidator

func (d *Decoder[Resource, Request]) WithValidator(v ValidatorFunc) *Decoder[Resource, Request]

WithValidator sets the validator function for the Decoder.

type DecoderAccessor

type DecoderAccessor interface {
	Validator() ValidatorFunc
	UserPermissions(r *http.Request) UserPermissions
}

DecoderAccessor is the application seam the Must* decoder constructors draw on: the request validator and the per-request user permissions. Generated application code implements and consumes it via the generated decoder constructors.

type DefaultsFunc

type DefaultsFunc func(ctx context.Context, txn ReadWriteTransaction) error

DefaultsFunc is the signature for a function that applies default values to a PatchSet.

type Demonstration

type Demonstration struct {
	Key         string
	Description string
}

Demonstration is one capability of the resource package a demonstration application proves. The key is the vocabulary an application declares against: the annotation, option, grammar function, or API name where one exists, a short coined slug where none does. A demonstration application ends the doc comment of every struct, method, test, component, and persona row that proves a key with a "Demonstrates: key, key." paragraph, and a test in the application fails when a key here has no declaration in code or in a test, when a declaration names a key not here, or when a README example link points at a file that does not declare the key its row documents. The same test writes the generated key-to-files table (lodestar/DEMONSTRATIONS.md).

type DiffElem

type DiffElem struct {
	Old any
	New any
	// Secret marks the change of a secret field, whose values are not kept. Its key is
	// spelled as Old and New are, which carry no tag and so are stored under their names.
	Secret bool `json:",omitempty"` //nolint:tagliatelle // a change record's keys are Old, New and Secret
}

DiffElem represents the old and new values of a field that has been changed. A field that holds a secret (conditions:"secret" on the resource struct) is recorded as changed with neither value: Secret is set, and Old and New stay empty, so a change record says that a password or a key was set and never what it was or is.

type DigestOption

type DigestOption func(*digestOptions)

DigestOption configures PermissionDigestHandler.

func WithFeatureGates

func WithFeatureGates(gates FeatureGates, features *FeatureSet) DigestOption

WithFeatureGates filters the digest by the feature flags: an entry for a gated resource, one of its fields, or a gated RPC method is left out while the flag is off, so the frontend never renders a surface the routes would answer 404 for. The gates are the generated declaration (FeatureGates()), the features the application's FeatureSet.

func WithFormerNames

func WithFormerNames(names FormerNames) DigestOption

WithFormerNames mirrors the entry of every renamed field or method under its former name too, with the same states: an application built before the rename asks the digest for the name it knows, and keeps its column or its action while the server still answers it. The names are the generated collection's (Collection()). A former name already present in the digest is left as the engine answered it.

func WithListsAcrossTenants added in v0.5.0

func WithListsAcrossTenants(lists AcrossTenantsLists) DigestOption

WithListsAcrossTenants adds, to the digest of the global scope, the answer a page that lists a resource across tenants is shown by: each resource declared for it carries ListAcrossTenants, granted, while the person may list it in at least one tenant the session reaches (ListedInSomeTenant), and is left as it was otherwise. The resources are the generated collection's (Collection()). A tenant's digest is untouched: it speaks for that tenant alone.

type DirectoryNamer added in v0.5.0

type DirectoryNamer func(directory signin.Directory) (name, label string)

DirectoryNamer answers what the sign-in registrations of one auth call a directory: name is the name a registration that takes the directory's connection gives it, "" where none names it, and label is the label of the button of the registration a person signs in to it through, "" where the auth's login page offers none. The generated identity client of an auth supplies it (DirectoryName), from the session library's own answer (session.AuthAPI.DirectoryName); an application names none.

type DirectoryOnlyState added in v0.5.0

type DirectoryOnlyState struct {
	DirectoryOnly bool `json:"directoryOnly"`
}

DirectoryOnlyState is a tenant's directory-only switch as it stands.

type DirectoryOutsider added in v0.5.0

type DirectoryOutsider struct {
	// UserID is the id of the person's account, and Username what identifies them.
	UserID   impulse.UUID `json:"userId"`
	Username string       `json:"username"`
	// Name is the person's name as people read it, absent where the account holds none.
	Name *string `json:"name,omitempty"`
}

DirectoryOutsider is a person who holds a seat in a tenant, has never signed in through the tenant's directory and has no other way in: someone the tenant's directory-only switch keeps out for as long as it is on.

type DirectoryOutsiders added in v0.5.0

type DirectoryOutsiders func(ctx context.Context, txn ReadWriteTransaction, tenant accesstypes.Domain) ([]DirectoryOutsider, error)

DirectoryOutsiders reads the people of one auth who hold a seat in tenant, in the tenant itself or in every tenant, and have no sign-in through the tenant's directory, in the caller's transaction. A super administrator is left out: no tenant's sign-in settings shut them out. So is the tenant's own administrator who has a password: they enter with it and a second factor (signin.TenantDeclaration.AdmitsAdministrator), and lose nothing. The generated identity client of each auth whose people a tenant seats supplies it (DirectoryOutsiders), over the tenant's own list of its people; an application names none of them.

type DirectoryPeople added in v0.5.0

type DirectoryPeople struct {
	// List is the tenant's list of the auth's people as grants name it, and Fields the
	// fields of it that name a person: the ones the warning lists a person by
	// (DirectoryOutsider).
	List   accesstypes.Resource
	Fields []accesstypes.Tag
	// Outsiders reads the people the switch would keep out.
	Outsiders DirectoryOutsiders
	// AdministratorsEnter says the auth's people keep the administrators' way in: the
	// auth has a password method and names the roles that administer a tenant, so the
	// tenant's own administrator who has a password still enters, with a code mailed to
	// them. The warning says so, since it is the one other way into the tenant.
	AdministratorsEnter bool
}

DirectoryPeople is one auth's part of what turning a tenant's directory-only switch on would do: the reader of the people it would keep out, and the tenant's list of that auth's people, which decides whether the caller is told who they are. The warning names people only to someone who may list them: a caller who holds List, in the tenant, on the list and, on no condition, on each field of it that names a person. Anyone else is told how many there are and nobody's name. A reader with no list, or with no field named, names nobody.

type DomainBindingData

type DomainBindingData struct {
	Column string
	Path   []BindingHop
}

DomainBindingData is the structural tenancy binding: how every row of a domain-scoped resource resolves to its tenant. Column is the tenant-key column itself when Path is empty, or the foreign key the path to it leaves through. It is deliberately not an attribute — tenancy injection consumes it, and conditions can never reference it.

type DomainNamer added in v0.4.0

type DomainNamer interface {
	Name(domain accesstypes.Domain) string
}

DomainNamer answers a tenant's name, "" for one it holds none for: the tenant roster (TenantRoster.Name), which reads the tenant record's name column beside its keys.

type DomainRoster

type DomainRoster func(ctx context.Context) ([]accesstypes.Domain, error)

DomainRoster lists the application's tenant domains: the roster the tenant picker is filtered from. A tenanted application passes its TenantRoster's Domains, which has this signature and answers from the roster's set; an application without tenants passes nil to SessionPermissions, and its sessions list no domain.

type ExecuteGate

type ExecuteGate struct {
	// contains filtered or unexported fields
}

ExecuteGate carries one request's Execute decision to the generated frame. A nil condition (the grant was unconditional) enforces nothing.

func (*ExecuteGate) Caller

func (g *ExecuteGate) Caller() *Caller

Caller returns the caller the decode-time check ran as — checker, scope, sampled environment, and the collection — for the handler to stamp into the context the method's body runs under.

func (*ExecuteGate) Enforce

func (g *ExecuteGate) Enforce(ctx context.Context, txn ReadWriteTransaction, target ExecuteTarget, pkValues ...any) error

Enforce evaluates the carried condition against the target row inside the frame's transaction: one check-SELECT locating the row by key, its single boolean the condition lowered against the target resource's bindings, bound to the same @subject, @now, and @domain the permission check folded with. A false or NULL answer is Forbidden with the frame's uniform refusal — the wire never says whether the state or the condition refused. The frame has located a table's row before it calls Enforce, so a grant with no condition enforces nothing; a view's row is located by EnforceView instead.

func (*ExecuteGate) EnforceProposed added in v0.5.0

func (g *ExecuteGate) EnforceProposed(ctx context.Context, facts SubjectFactSource, target ExecuteTarget, row map[string]any) error

EnforceProposed judges the carried condition against a row the body proposes, where the database holds no row to locate: a role a person holds through a group is no row of the list of the roles held, and the method that takes a role away is granted on the rows of that list. row holds the target's attributes by the names a condition reads them, the target's @attribute declarations, each as the value the condition language compares (a string, an int64, a float64, a bool, a time.Time or a condition.Date, nil for no value).

The condition is judged by the language's own evaluator (condition.Evaluate), the statement of its meaning that the SQL rendering is held to, with the caller and the decision instant the permission check folded with. A fact about the caller that is held in a table (subject.<name>) is read through facts, the body's transaction. A false or unknown answer is the frame's uniform refusal, and a grant with no condition enforces nothing. A condition that reads an attribute row does not carry is generated code out of step with the library, and fails as that.

func (*ExecuteGate) EnforceView added in v0.3.0

func (g *ExecuteGate) EnforceView(ctx context.Context, txn ReadWriteTransaction, target ExecuteTarget, pkValues ...any) error

EnforceView is the whole located-row check for a target that is a row of a view. One SELECT in the frame's transaction does both halves: it selects from the view's query by the key and, for a tenant-scoped view, the request's tenant, and its single boolean is the carried condition lowered against the view's bindings — TRUE where the grant carries none, since the row still has to be found. No row is the NotFound a missing row and another tenant's row share; a false or NULL answer is the frame's uniform refusal. A key that names more than one row there is a fault of the view's query, never a row to pick between, and fails as one.

func (*ExecuteGate) Settled added in v0.5.0

func (g *ExecuteGate) Settled() (granted, settled bool)

Settled reports what the gate decides before any row is read. settled is true where nothing of the grant's condition is left to judge against the target row: the grant carries no condition, or its condition read the request's fields alone, and granted says which way it went. Where settled is false the decision is the row's to make (Enforce, EnforceView, EnforceProposed).

func (*ExecuteGate) VerifyTenancy

func (g *ExecuteGate) VerifyTenancy(ctx context.Context, txn ReadWriteTransaction, target ExecuteTarget, pkValues ...any) error

VerifyTenancy confirms the located target row resolves to the request's domain, for a target whose @domain binding leaves through a join path — a bare-column binding is read off the located row in the generated frame instead (resource.TenantKeyEquals), so the row itself carries no tenant key here. One SELECT in the frame's transaction: the tenancy predicate rendered from the Collection's domain binding as a single boolean, the row located by its primary key. A missing row and a cross-tenant row are the same NotFound the locate step answers — a row outside the caller's tenant never reveals it exists.

type ExecuteTarget

type ExecuteTarget struct {
	// Resource is the target row resource: its table, or the view's resource.
	Resource accesstypes.Resource

	// Label is the target's struct name, for the refusal message — the same
	// words the frame's own state check refuses with, so the wire never
	// distinguishes a wrong-state refusal from a condition refusal.
	Label string

	// PKColumns are the primary-key columns the check-SELECT locates the row by,
	// in the key's order: one for a single-column key, each column of a compound
	// one. The key values the gate is handed follow the same order.
	PKColumns []string

	// View is the target's query when the target is a row of a view (a @virtual
	// struct): the struct's own value, whose Subquery the check-SELECT selects
	// from under the resource's name, as the view's lists and reads do. Nil for
	// a table.
	View interface {
		Subquery() (query string, params map[string]any)
	}
}

ExecuteTarget describes the located row an ExecuteGate evaluates against. The generated frame supplies it from generation-time facts.

type Executor

type Executor interface {
	ExecuteFunc(ctx context.Context, f func(ctx context.Context, txn ReadWriteTransaction) error) error
}

Executor interface exposes ability to run a function inside a transaction.

type ExpressionNode

type ExpressionNode interface {
	// String returns a string representation of the node (for debugging/testing).
	String() string
}

ExpressionNode represents a node in the filter AST.

type Feature

type Feature string

Feature names a feature flag. An application declares its flags as constants of this type in its resources package, each with a doc comment that is the flag's description, and gates a resource, a field or an RPC method with @feature(<Constant>). The generator collects the declarations into Features(), the deploy step writes them into the FeatureFlags table (MigrateFeatures), and the running application reads the table into a FeatureSet the gated routes, decoders and the permission digest consult.

A flag's value is its name as the table holds it: lowercase letters, digits and underscores, opening with a letter, at most 64 characters.

type FeatureApp

type FeatureApp interface {
	DecoderAccessor
	ResourceClient() Client
	CursorKey() *CursorKey
	FeatureSet() *FeatureSet
}

FeatureApp is the application surface the feature flag handlers draw on: the decoder seam, the database client, the cursor key the flags' list pages with, and the FeatureSet the application loaded at start.

type FeatureDeclaration

type FeatureDeclaration struct {
	Name        Feature
	Description string
	Constant    string
}

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.

func (*FeatureSet) Reload

func (s *FeatureSet) Reload(ctx context.Context) error

Reload rereads the table. A failed read leaves the copy as it was; a nil FeatureSet has nothing to reread and says so.

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

func (h FileHolder) HeldKeys(ctx context.Context, client Client, store StoreName) ([]string, error)

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.

func (Files) Keys

func (f Files) Keys() []string

Keys returns the keys the frame minted, skipping the empty keys of a dry run.

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.

func (FilesIn[S]) Keys

func (f FilesIn[S]) Keys() []string

Keys returns the keys the frame minted, skipping the empty keys of a dry run.

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

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

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

Data returns the canonical, deterministically sorted form of the collection.

func (*GeneratedCollection) FieldMasking

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

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

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

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

List returns a map of permissions to the resources that have them.

func (*GeneratedCollection) ListedAcrossTenants added in v0.5.0

func (g *GeneratedCollection) ListedAcrossTenants() []accesstypes.Resource

ListedAcrossTenants returns the resources declared for listing across tenants, in name order. A nil collection declares none.

func (*GeneratedCollection) ListsAcrossTenants added in v0.5.0

func (g *GeneratedCollection) ListsAcrossTenants(res accesstypes.Resource) bool

ListsAcrossTenants reports whether res is a tenant's resource declared for listing across tenants (@listAcrossTenants). A nil collection declares none.

func (*GeneratedCollection) MembersOf

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

MethodTarget reports the row resource method's @target field addresses within scope, and whether the method declares one. A targeted method's Execute grants may carry row-referencing conditions — the generated handler locates the row inside its transaction and evaluates them there — so deploy-time grant validation (access.MigrateRoles) asks this to tell a targeted method from a plain one.

func (*GeneratedCollection) MethodsTargeting

func (g *GeneratedCollection) MethodsTargeting(target accesstypes.Resource) []TargetedMethod

MethodsTargeting lists the RPC method resources whose @target field addresses target, sorted by method name — the capability envelope's Execute candidates: a transition method's affordance is gated on the row's state membership in its from set, a plain method's only on its Execute grant's condition. Every scope is searched: a targeted method and its row resource share their scope kind by construction.

func (*GeneratedCollection) RequiredOnCreate added in v0.4.0

RequiredOnCreate reports the fields a create of res must be given by the client within scope, as wire tags, sorted: each takes no NULL, nothing but the client fills it, and a grant names it for Create. Deploy-time role validation (access.MigrateRoles) warns where a role may create the resource and may set none of its grants' fields for one of them. Empty for a resource every create of which the server can complete.

func (*GeneratedCollection) ResourceExists

func (g *GeneratedCollection) ResourceExists(r accesstypes.Resource) bool

ResourceExists checks if a resource exists in the collection.

func (*GeneratedCollection) Resources

func (g *GeneratedCollection) Resources() []accesstypes.Resource

Resources returns a sorted list of all unique base resource names in the collection.

func (*GeneratedCollection) Scope

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

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.

func (*GroupNode) String

func (gn *GroupNode) String() string

String returns a string representation of the GroupNode.

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

func (p KeySet) KeySet() spanner.KeySet

KeySet converts the resource KeySet into a `spanner.KeySet`, which can be used in Spanner read or delete operations.

func (KeySet) Len

func (p KeySet) Len() int

Len returns the number of parts in the key set (for composite keys, this will be greater than 1).

func (KeySet) Parts

func (p KeySet) Parts() []KeyPart

Parts returns the slice of KeyPart components that make up the key set.

func (KeySet) RowID

func (p KeySet) RowID() string

RowID generates a string representation of the key set, typically for use in logging or as a unique identifier.

type LocatedFileStore

type LocatedFileStore interface {
	FileStore
	Location() string
}

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

func NewMetadata[Resource Resourcer]() *Metadata[Resource]

NewMetadata creates or retrieves cached metadata for a resource.

func (*Metadata[Resource]) DBFieldCount

func (r *Metadata[Resource]) DBFieldCount(dbType DBType) int

DBFieldCount returns the number of fields for a given database type.

func (*Metadata[Resource]) DBFields

func (r *Metadata[Resource]) DBFields(dbType DBType) []accesstypes.Field

DBFields returns all field names for a given database type in struct declaration order — deterministic, so default field sets and generated query column order are stable across processes.

type MockClient

type MockClient struct {
	// contains filtered or unexported fields
}

MockClient is a wrapper around the database.

func NewMockClient

func NewMockClient(txnMock ReadWriteTransaction, readOnlyMocks, txnReadMocks []any, opts ...ClientOption) *MockClient

NewMockClient creates a new MockClient for testing resource database interactions.

It uses the following mocks: - txnMock: Mocks Buffer calls. - readOnlyMocks: Mocks Read/List calls outside a transaction. - txnReadMocks: Mocks Read/List calls inside a transaction.

IMPORTANT: For readOnlyMocks and txnReadMocks, provide only one mock per resource type (e.g., Read[MyResource]). Multiple calls for the same Resource must be configured on that single mock.

WithFileStore and WithNamedFileStore hand it the stores ExecuteFunc deletes released file objects from after the function returns, so a test can assert what a patch released. WithSecretKeys hands it the keys its transactions seal a patch's secret fields with, built from fixed bytes in a test (NewSecretKeys), so what a patch buffers is the sealed value and the test can open it.

func (*MockClient) Close

func (c *MockClient) Close()

Close closes the database connection.

func (*MockClient) DBType

func (c *MockClient) DBType() DBType

DBType returns the database type the mock stands in for.

func (*MockClient) ExecuteFunc

func (c *MockClient) ExecuteFunc(ctx context.Context, f func(ctx context.Context, txn ReadWriteTransaction) error) error

ExecuteFunc executes a function within a read-write transaction. As the Spanner client's does, it refuses a function that released an object of a store the client holds none for, deletes the file objects the function's patches released from their stores once the function returns nil, hands the rows the patches wrote to the collector ctx carries (CollectTouchedRows), runs what the patches registered for after the commit (AfterCommit), and does none of it when it errors.

func (*MockClient) FileStore

func (c *MockClient) FileStore(name StoreName) FileStore

FileStore returns the store wired under name, nil when none is.

func (*MockClient) PostgresReadOnlyTransaction

func (c *MockClient) PostgresReadOnlyTransaction() any

PostgresReadOnlyTransaction panics because it is not implemented for the MockClient.

func (*MockClient) ReadOnlyMocks

func (c *MockClient) ReadOnlyMocks() []any

ReadOnlyMocks returns the read-only mocks for the Mock client.

func (*MockClient) ReadOnlyTransaction

func (c *MockClient) ReadOnlyTransaction() ReadOnlyTransactionCloser

ReadOnlyTransaction returns a ReadOnlyTransaction that can be used for multiple reads from the database. You must call Close() when the ReadOnlyTransaction is no longer needed to release resources on the server.

func (*MockClient) SpannerReadOnlyTransaction

func (c *MockClient) SpannerReadOnlyTransaction() spxapi.Querier

SpannerReadOnlyTransaction returns a read-only transaction for the Mock client.

type MockReadWriteTransaction

type MockReadWriteTransaction struct {
	// contains filtered or unexported fields
}

MockReadWriteTransaction represents a database transaction that can be used for both reads and writes.

func NewMockReadWriteTransaction

func NewMockReadWriteTransaction(mock ReadWriteTransaction, txnReaderMocks ...any) *MockReadWriteTransaction

NewMockReadWriteTransaction creates a new MockReadWriteTransaction. A test whose patches set a secret field gives it the secret keys with WithSecretKeys.

func (*MockReadWriteTransaction) BufferMap

func (c *MockReadWriteTransaction) BufferMap(r PatchSetMetadata, p map[string]any) error

BufferMap buffers a map of changes to be applied to the database.

func (*MockReadWriteTransaction) BufferStruct

func (c *MockReadWriteTransaction) BufferStruct(p PatchSetMetadata) error

BufferStruct buffers a struct of changes to be applied to the database.

func (*MockReadWriteTransaction) Committed added in v0.3.0

func (c *MockReadWriteTransaction) Committed(ctx context.Context)

Committed runs what the transaction's writes registered for after the commit (AfterCommit), as SpannerReadWriteTransaction.Committed does: for a transaction a test builds itself (NewMockReadWriteTransaction); the Mock client's ExecuteFunc makes the calls once the function returns nil.

func (*MockReadWriteTransaction) DBType

func (c *MockReadWriteTransaction) DBType() DBType

DBType returns the database type.

func (*MockReadWriteTransaction) DataChangeEventIndex

func (c *MockReadWriteTransaction) DataChangeEventIndex(res accesstypes.Resource, rowID string) int

DataChangeEventIndex provides a sequence number for data change events on the same Resource inside the same transaction.

func (*MockReadWriteTransaction) PostgresReadOnlyTransaction

func (c *MockReadWriteTransaction) PostgresReadOnlyTransaction() any

PostgresReadOnlyTransaction panics because it is not implemented for the MockReadWriteTransaction.

func (*MockReadWriteTransaction) Released

func (c *MockReadWriteTransaction) Released() []ReleasedKey

Released returns the file objects the transaction's patches released so far, each with its store, as SpannerReadWriteTransaction.Released does.

func (*MockReadWriteTransaction) SpannerReadOnlyTransaction

func (c *MockReadWriteTransaction) SpannerReadOnlyTransaction() spxapi.Querier

SpannerReadOnlyTransaction returns a read-only transaction for the MockReadWriteTransaction.

func (*MockReadWriteTransaction) TxnReadMocks

func (c *MockReadWriteTransaction) TxnReadMocks() []any

TxnReadMocks returns the read mocks inside a transaction for the MockReadWriteTransaction.

func (*MockReadWriteTransaction) WithSecretKeys added in v0.5.0

WithSecretKeys gives the transaction the secret keys it seals a patch's secret fields with, and returns the transaction. The Mock client's ExecuteFunc gives a transaction its own; this is for one a test builds itself (NewMockReadWriteTransaction).

type NamedStore

type NamedStore interface {
	// contains filtered or unexported methods
}

NamedStore is the constraint a named store's type satisfies: a struct embedding Store. It is the type parameter of Key, FilesIn, FileIn, StoreNameFor and WithNamedFileStore.

type Operation

type Operation struct {
	Type OperationType
	Req  *http.Request
	// contains filtered or unexported fields
}

Operation represents a single operation within a batch request, containing its type and a corresponding http.Request.

func (*Operation) AsCreate added in v0.4.0

func (o *Operation) AsCreate() *Operation

AsCreate returns a copy of the operation that runs as an add: what a patch-or-add whose row is not there turns into, and what an add-or-skip is decoded as. The request, with the key its path carries, is the operation's own.

func (*Operation) AsUpdate added in v0.4.0

func (o *Operation) AsUpdate() *Operation

AsUpdate returns a copy of the operation that runs as a patch: what a patch-or-add whose row is there turns into.

func (*Operation) PathDepth

func (o *Operation) PathDepth() int

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

func (o *Operation) ReqWithPattern(pattern string, opts ...Option) (*http.Request, error)

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

func (o *Operation) WithPrefixPattern(pattern string) (*Operation, error)

WithPrefixPattern returns a copy of the operation re-anchored to a longer path prefix: the pattern is prefix-matched against the operation's path, binding its params into the request context, and the copy's create-path semantics use the new, longer prefix. The consolidated handler uses it to descend into the domain route segment (binding the domain param) before dispatching on the resource segment.

type OperationType

type OperationType string

OperationType defines the type of a patch operation (add, patch, remove, and the two that decide from whether the row is there: patch-or-add and add-or-skip).

const (
	// OperationCreate corresponds to an "add" operation.
	OperationCreate OperationType = "add"
	// OperationUpdate corresponds to a "patch" operation.
	OperationUpdate OperationType = "patch"
	// OperationDelete corresponds to a "remove" operation.
	OperationDelete OperationType = "remove"
	// OperationUpdateOrCreate corresponds to a "patch-or-add" operation: an update of
	// the row its path names, and a create of that row when it is not there. A handler
	// asks the decoder which of the two it is (Decoder.DecideOperation: the caller's
	// Update grant on the resource, then a look for the row inside the transaction) and
	// runs the operation as the patch or the add it turned out to be, so everything a
	// patch or an add is held to holds for it.
	OperationUpdateOrCreate OperationType = "patch-or-add"
	// OperationCreateOrSkip corresponds to an "add-or-skip" operation: a create of the
	// row its path names that leaves the row exactly as it is when it is there. A
	// handler runs it as the add it is (AsCreate) with the create patch marked OrSkip.
	OperationCreateOrSkip OperationType = "add-or-skip"
)

type Option

type Option func(opt options) options

Option is a function that configures the behavior of the Operations parser.

func MatchPrefix

func MatchPrefix() Option

MatchPrefix is an option that allows matching only the prefix of an operation's path against the provided pattern.

func RequireCreatePath

func RequireCreatePath() Option

RequireCreatePath is an option that mandates a path for "add" operations.

type Outcome added in v0.4.0

type Outcome string

Outcome is what buffering an OrCreate or an OrSkip patch did with its row.

const (
	// OutcomeCreated says the row was not there and the patch created it.
	OutcomeCreated Outcome = "created"
	// OutcomeUpdated says the row was there and the update ran. An update with no
	// fields set is the silent no-op it is everywhere (see Apply and Buffer).
	OutcomeUpdated Outcome = "updated"
	// OutcomeSkipped says the row was there and an OrSkip patch left it as it is:
	// nothing was written and no default or validation ran.
	OutcomeSkipped Outcome = "skipped"
)

type Page

type Page[Resource Resourcer] struct {
	// contains filtered or unexported fields
}

Page collects one page of a decoded list on the generated handler's behalf. The statement fetches one row past the page size; Add keeps the page's rows and reports the extra one, which tells the page a next page exists and is never encoded. WriteHeaders then writes the Link and Total-Count headers from the rows it saw, before the handler encodes the body.

func (*Page[Resource]) Add

func (p *Page[Resource]) Add(row *Row[Resource]) bool

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

func (p *Page[Resource]) Reversed() bool

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

func (p *Page[Resource]) WriteHeaders(w http.ResponseWriter, r *http.Request) error

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

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

func NewPatchSet[Resource Resourcer](rMeta *Metadata[Resource]) *PatchSet[Resource]

NewPatchSet creates a new, empty PatchSet for a given resource metadata.

func (*PatchSet[Resource]) Apply

func (p *PatchSet[Resource]) Apply(ctx context.Context, client Client, eventSource ...string) error

Apply applies the patch within a new read-write transaction.

An update or insert-or-update patch with no fields set is a silent no-op: nothing runs — no permission check, no output-only update functions, no mutation, no change event. To run the update pipeline with the content supplied entirely by the registered output-only update functions, mark the patch with AsTouch.

An OrCreate or OrSkip patch decides its case first, from whether its row is there (patch_fork.go), and then runs as the create or the update it decided on.

func (*PatchSet[Resource]) AsTouch

func (p *PatchSet[Resource]) AsTouch() *PatchSet[Resource]

AsTouch marks an update patch as a touch: an update whose entire content is supplied by the registered output-only update functions. A touch runs the full update pipeline — permission check, output-only update functions, write conditions, change events — even though the caller sets no fields, whereas a plain update patch with no fields set is a silent no-op (see Apply and Buffer). Only UpdatePatchType patches can be touches, and a touch requires at least one registered output-only update function; Apply and Buffer reject anything else.

func (*PatchSet[Resource]) Buffer

func (p *PatchSet[Resource]) Buffer(ctx context.Context, txn ReadWriteTransaction, eventSource ...string) error

Buffer buffers the patch's mutations into an existing transaction buffer.

An update or insert-or-update patch with no fields set is a silent no-op: nothing runs — no permission check, no output-only update functions, no mutation, no change event. To run the update pipeline with the content supplied entirely by the registered output-only update functions, mark the patch with AsTouch.

An OrCreate or OrSkip patch decides its case first, from whether its row is there (patch_fork.go), and then runs as the create or the update it decided on.

func (*PatchSet[Resource]) Data

func (p *PatchSet[Resource]) Data() map[accesstypes.Field]any

Data returns the underlying map of field-value pairs.

func (*PatchSet[Resource]) Diff

func (p *PatchSet[Resource]) Diff(old any) (map[accesstypes.Field]DiffElem, error)

Diff returns a map of fields that have changed between old and patchSet. A field the resource struct declares a secret (conditions:"secret") is in the map when it changed, marked Secret, with neither value. Whether a secret changed cannot be told from its stored bytes, which differ at every write: the write path opens what the row holds and compares it with the value given, and Diff, which holds no keys, counts a secret the patch sets as changed unless the row holds none and the patch sets none.

func (*PatchSet[Resource]) EnableUserPermissionEnforcement

func (p *PatchSet[Resource]) EnableUserPermissionEnforcement(rSet *Set[Resource], userPermissions UserPermissions, scope accesstypes.Scope, requiredPermission accesstypes.Permission) *PatchSet[Resource]

EnableUserPermissionEnforcement enables the checking of user permissions for the PatchSet, evaluating requiredPermission for the user in the given scope partition.

An enforced PatchSet is single-shot: it binds the user (via userPermissions) and the domain for a single operation's evaluation. Build a new PatchSet per operation; never reuse one across requests or domains.

func (*PatchSet[Resource]) Enforce

func (p *PatchSet[Resource]) Enforce(caller *Caller, rSet *Set[Resource], requiredPermission accesstypes.Permission) *PatchSet[Resource]

Enforce arms the mutation against the caller: Apply and Buffer run the full pipeline the resource routes run — the static field gate against the Set, the fold of conditional grants, the live check against the real row inside the transaction, and the tenancy check — before buffering anything. A refusal is the same Forbidden the routes answer, naming the grant that said no. A zero Caller refuses at execution.

func (*PatchSet[Resource]) Fields

func (p *PatchSet[Resource]) Fields() []accesstypes.Field

Fields returns a slice of all fields that have been set in the PatchSet.

func (*PatchSet[Resource]) FromStruct

func (p *PatchSet[Resource]) FromStruct(input any, skip ...string) error

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]) HasKey

func (p *PatchSet[Resource]) HasKey() bool

HasKey checks if any primary key has been set.

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]) Len

func (p *PatchSet[Resource]) Len() int

Len returns the number of fields in the PatchSet.

func (*PatchSet[Resource]) OrCreate added in v0.4.0

func (p *PatchSet[Resource]) OrCreate(createSet *Set[Resource]) *PatchSet[Resource]

OrCreate turns an update patch into update-or-create: when the row is there the update runs as it is, and when it is not the patch creates the row with the fields it carries, through the create path whole. createSet is the Set a create of the resource is checked against, used when the patch is armed against a caller (Enforce); a patch that runs trusted passes nil. The generated update patch's OrCreate passes the resource's own and registers the create's defaults and validation beside the update's.

The fields the patch sets are written in both cases. A caller that needs the two cases to write different things reads the row and builds the create patch or the update patch.

func (*PatchSet[Resource]) OrSkip added in v0.4.0

func (p *PatchSet[Resource]) OrSkip() *PatchSet[Resource]

OrSkip turns a create patch into create-unless-there: when the row is not there the create runs as it is, and when it is the patch does nothing at all. The caller's Create grant is checked before the row is looked for, so a caller who may not create is refused either way. A grant's row condition is judged only when the row is created.

func (*PatchSet[Resource]) Outcome added in v0.4.0

func (p *PatchSet[Resource]) Outcome() Outcome

Outcome reports what the last Apply or Buffer of an OrCreate or OrSkip patch did with its row. It is empty on a patch that is neither, and before the patch has run.

func (*PatchSet[Resource]) PatchType

func (p *PatchSet[Resource]) PatchType() PatchType

PatchType returns the type of the patch.

func (*PatchSet[Resource]) Permitted added in v0.5.0

func (p *PatchSet[Resource]) Permitted(ctx context.Context, txn ReadWriteTransaction) error

Permitted checks the caller's grants for the write an armed PatchSet carries, as Apply and Buffer check them before anything else: the permission on the resource and on each field the patch names. The conditions a grant carries are left to Apply and Buffer, which evaluate them against the row. A write whose answer depends on what the database holds (a rule that reads other rows and refuses in words) calls it before the rule is asked, so a caller the grants refuse gets the same Forbidden whatever the rule would have said, and learns nothing from it. A PatchSet that is not armed passes, since it runs trusted.

func (*PatchSet[Resource]) PrimaryKey

func (p *PatchSet[Resource]) PrimaryKey() KeySet

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

func (p *PatchSet[Resource]) Resolve(dbType DBType, keys *SecretKeys) (map[string]any, error)

Resolve returns a map with the keys set to the database struct tags found on databaseType, and the values set to the values in patchSet. A field the resource declares a secret (conditions:"secret") is sealed here, with keys and the row's primary key, so its column is never handed the value as it was given: the write path passes the keys of its transaction's client, and a patch that sets a secret is refused when there are none. A patch that sets no secret resolves with nil keys.

func (*PatchSet[Resource]) Resource

func (p *PatchSet[Resource]) Resource() accesstypes.Resource

Resource returns the name of the resource this PatchSet applies to.

func (*PatchSet[Resource]) Set

func (p *PatchSet[Resource]) Set(field accesstypes.Field, value any) *PatchSet[Resource]

Set adds or updates a field's value in the PatchSet.

func (*PatchSet[Resource]) SetKey

func (p *PatchSet[Resource]) SetKey(field accesstypes.Field, value any) *PatchSet[Resource]

SetKey sets a primary key field and value for the PatchSet.

func (*PatchSet[Resource]) SetPatchType

func (p *PatchSet[Resource]) SetPatchType(t PatchType) *PatchSet[Resource]

SetPatchType sets the type of the patch (Create, CreateOrUpdate, Update, or Delete).

func (*PatchSet[Resource]) ToStruct

func (p *PatchSet[Resource]) ToStruct() *Resource

ToStruct returns an instance of Resource, with its struct fields populated with the contents of data. A secret field the patch was given as text is left out: the struct's field holds the bytes its column stores, and the value is sealed only when the patch is written.

type PatchSetComparer

type PatchSetComparer interface {
	Resource() accesstypes.Resource
	Data() map[accesstypes.Field]any
	Fields() []accesstypes.Field
	PatchType() PatchType
	PrimaryKey() KeySet
}

PatchSetComparer is an interface for comparing two PatchSet-like objects.

type PatchSetMetadata

type PatchSetMetadata interface {
	PatchType() PatchType
	PrimaryKey() KeySet
	Resource() accesstypes.Resource
}

PatchSetMetadata is an interface that all PatchSet types must implement to allow their mutations to be buffered

type PatchType

type PatchType string

PatchType defines the type of operation for a PatchSet.

const (
	// CreatePatchType indicates an insert operation.
	CreatePatchType PatchType = "CreatePatchType"
	// UpdatePatchType indicates an update operation.
	UpdatePatchType PatchType = "UpdatePatchType"
	// CreateOrUpdatePatchType indicates an insert or update operation.
	CreateOrUpdatePatchType PatchType = "CreateOrUpdatePatchType"
	// DeletePatchType indicates a delete operation.
	DeletePatchType PatchType = "DeletePatchType"
)

type PostgreSQLGenerator

type PostgreSQLGenerator struct {
	// contains filtered or unexported fields
}

PostgreSQLGenerator is a SQL generator for PostgreSQL.

func NewPostgreSQLGenerator

func NewPostgreSQLGenerator() *PostgreSQLGenerator

NewPostgreSQLGenerator creates a new PostgreSQLGenerator.

func (*PostgreSQLGenerator) GenerateSQL

func (g *PostgreSQLGenerator) GenerateSQL(node ExpressionNode) (sqlStr string, params map[string]any, err error)

GenerateSQL generates SQL for the given node.

type PostgresClient

type PostgresClient struct {
	// contains filtered or unexported fields
}

PostgresClient is a wrapper around the database.

func NewPostgresClient

func NewPostgresClient(db *pgxpool.Pool, opts ...ClientOption) *PostgresClient

NewPostgresClient creates a new Client. WithFileStore and WithNamedFileStore hand it the stores the generated handlers read off it, the options the Spanner client takes; a store wired twice, or two stores on one location, panics here. WithSecretKeys hands it the keys a patch's secret fields are sealed with.

func (*PostgresClient) Close

func (c *PostgresClient) Close()

Close closes the database connection.

func (*PostgresClient) DBType

func (c *PostgresClient) DBType() DBType

DBType returns the database type.

func (*PostgresClient) ExecuteFunc

func (c *PostgresClient) ExecuteFunc(_ context.Context, _ func(ctx context.Context, _ ReadWriteTransaction) error) error

ExecuteFunc executes a function within a read-write transaction.

func (*PostgresClient) FileStore

func (c *PostgresClient) FileStore(name StoreName) FileStore

FileStore returns the store wired under name, nil when none is.

func (*PostgresClient) PostgresReadOnlyTransaction

func (c *PostgresClient) PostgresReadOnlyTransaction() any

PostgresReadOnlyTransaction panics because it is not implemented for the PostgresClient.

func (*PostgresClient) ReadOnlyTransaction

func (c *PostgresClient) ReadOnlyTransaction() ReadOnlyTransactionCloser

ReadOnlyTransaction returns a ReadOnlyTransaction that can be used for multiple reads from the database. You must call Close() when the ReadOnlyTransaction is no longer needed to release resources on the server.

func (*PostgresClient) SpannerReadOnlyTransaction

func (c *PostgresClient) SpannerReadOnlyTransaction() spxapi.Querier

SpannerReadOnlyTransaction panics because it is not implemented for the PostgresClient.

type PostgresReadOnlyTransaction

type PostgresReadOnlyTransaction struct {
	// contains filtered or unexported fields
}

PostgresReadOnlyTransaction represents a database transaction that can only be used for reads.

func (*PostgresReadOnlyTransaction) Close

func (c *PostgresReadOnlyTransaction) Close()

Close closes the readonly transaction

func (*PostgresReadOnlyTransaction) PostgresReadOnlyTransaction

func (c *PostgresReadOnlyTransaction) PostgresReadOnlyTransaction() any

PostgresReadOnlyTransaction returns a read-only transaction for the Postgres client.

func (*PostgresReadOnlyTransaction) SpannerReadOnlyTransaction

func (c *PostgresReadOnlyTransaction) SpannerReadOnlyTransaction() spxapi.Querier

SpannerReadOnlyTransaction panics because it is not implemented for the PostgresReadOnlyTransaction.

type PostgresReadWriteTransaction

type PostgresReadWriteTransaction struct {
	// contains filtered or unexported fields
}

PostgresReadWriteTransaction represents a database transaction that can be used for both reads and writes.

func (*PostgresReadWriteTransaction) BufferMap

BufferMap panics because it is not implemented for the PostgresReadWriteTransaction.

func (*PostgresReadWriteTransaction) BufferStruct

BufferStruct panics because it is not implemented for the PostgresReadWriteTransaction.

func (*PostgresReadWriteTransaction) 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

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

Read reads a single resource from the database.

func (*PostgresReadWriteTransaction) SpannerReadOnlyTransaction

func (c *PostgresReadWriteTransaction) SpannerReadOnlyTransaction() spxapi.Querier

SpannerReadOnlyTransaction panics because it is not implemented for the PostgresReadWriteTransaction.

func (*PostgresReadWriteTransaction) WithSecretKeys added in v0.5.0

WithSecretKeys gives the transaction the application's secret keys, which a patch's secret fields are sealed with, and returns the transaction.

type QueryClause

type QueryClause struct {
	// contains filtered or unexported fields
}

QueryClause represents a complete, valid query expression that can be part of a WHERE clause.

func (QueryClause) And

And starts a logical AND operation, returning a PartialQueryClause to which the right-hand side can be appended.

func (QueryClause) Or

Or starts a logical OR operation, returning a PartialQueryClause to which the right-hand side can be appended.

func (QueryClause) Validate

func (qc QueryClause) Validate() error

Validate checks if the query clause has at least one indexed field.

type QueryDecoder

type QueryDecoder[Resource Resourcer, Request any] struct {
	// contains filtered or unexported fields
}

QueryDecoder is a struct that returns columns that a given user has access to view

func MustNewQueryDecoder

func MustNewQueryDecoder[Resource Resourcer, Request any](collection *GeneratedCollection, permissions ...accesstypes.Permission) *QueryDecoder[Resource, Request]

MustNewQueryDecoder builds a query decoder for a resource and request pair, wired to the application's generated collection so conditional grants can render. It panics on construction errors: they are programming errors (a request struct out of sync with its resource), surfaced at application startup where generated handlers construct their decoders.

func NewQueryDecoder

func NewQueryDecoder[Resource Resourcer, Request any](resSet *Set[Resource]) (*QueryDecoder[Resource, Request], error)

NewQueryDecoder creates a new QueryDecoder for a given Resource and Request type.

func (*QueryDecoder[Resource, Request]) Decode

func (d *QueryDecoder[Resource, Request]) Decode(request *http.Request, userPermissions UserPermissions, scope accesstypes.Scope) (*QuerySet[Resource], error)

Decode decodes an http.Request into a QuerySet and enables user permission enforcement in the given domain partition. A search box in the URL is admitted when the PII fields it would search are all denied to the caller; one the caller may search sends the filter to the body (DecodeWithoutPermissions, with no caller to ask, refuses it outright).

func (*QueryDecoder[Resource, Request]) DecodeAcrossTenants added in v0.5.0

func (d *QueryDecoder[Resource, Request]) DecodeAcrossTenants(request *http.Request, userPermissions UserPermissions) (*QuerySet[Resource], error)

DecodeAcrossTenants decodes a list request asked without the tenant's route segment into a QuerySet over a set of tenants: every tenant the session reaches (UserPermissions.Domains) in which the person holds the record's List grant, narrowed by the request's domains parameter when it carries one. Each row is checked under the person's grants in its own tenant and says which tenant it is in (Row.Tenant). The generated handler of a record declared for it calls this where the tenant's own list calls Decode; a record the generated collection does not carry as declared (@listAcrossTenants) is refused, so no list across tenants, and no live subscription over a set of tenants, is made for one.

A tenant the request names that the session does not reach narrows the set to nothing and is never an error, so the answer never says whether a tenant exists. The capability envelope is refused: a row's write permissions are its tenant's, asked on the row's page inside its tenant.

func (*QueryDecoder[Resource, Request]) DecodeWithoutPermissions

func (d *QueryDecoder[Resource, Request]) DecodeWithoutPermissions(request *http.Request) (*QuerySet[Resource], error)

DecodeWithoutPermissions decodes an http.Request into a QuerySet without enforcing user permissions.

func (*QueryDecoder[Resource, Request]) WithCursorKey

func (d *QueryDecoder[Resource, Request]) WithCursorKey(key *CursorKey) *QueryDecoder[Resource, Request]

WithCursorKey installs the key that seals the cursors of the pages this decoder builds and opens the ones requests carry. The generated wiring passes the application's one key (resource.NewCursorKey over the cookie key) to every decoder; without it a list serves first pages only.

func (*QueryDecoder[Resource, Request]) WithFeatures

func (d *QueryDecoder[Resource, Request]) WithFeatures(features *FeatureSet) *QueryDecoder[Resource, Request]

WithFeatures installs the FeatureSet the decoder reads the gated fields' flags from; the generated wiring passes the application's. Without it every gated field stays hidden.

func (*QueryDecoder[Resource, Request]) WithPaging

func (d *QueryDecoder[Resource, Request]) WithPaging(paging Paging) *QueryDecoder[Resource, Request]

WithPaging installs the resource's declared paging contract: the default order a sort-less request takes and the page sizes. The generator emits the call from the @order and @page annotations. An order field the request type does not carry is a programming error and panics at construction, like every other generated-code mismatch, and so is a page size on a key-less list, which the generator refuses at @page and which does not page (wholeListOnly).

type QueryParam

type QueryParam struct {
	Name  string
	Value any
}

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

func NewQuerySet[Resource Resourcer](rMeta *Metadata[Resource]) *QuerySet[Resource]

NewQuerySet creates a new, empty QuerySet for a given resource metadata.

func (*QuerySet[Resource]) AddField

func (q *QuerySet[Resource]) AddField(field accesstypes.Field) *QuerySet[Resource]

AddField adds a field to be returned by the query. A secret field brings its row's primary key with it (the generated SecretContext): the stored bytes open on the key, and the row's generated Open method takes the key from the row, so a row read for its secret alone would open on no key at all.

func (*QuerySet[Resource]) Admit added in v0.3.0

func (q *QuerySet[Resource]) Admit(row *Resource) (fields []accesstypes.Field, shown bool, err error)

Admit judges the row a computed resource's Read function answered. It reports whether the caller is shown the row, and the projected fields the row shows: the query set's own, without those granted under a condition the row does not meet. A nil row is not shown, so a row the caller's grants do not admit is answered as a row that is not there. With nothing to judge every row is shown whole.

func (*QuerySet[Resource]) BatchList

func (q *QuerySet[Resource]) BatchList(ctx context.Context, client Client, size int) iter.Seq[iter.Seq2[*Row[Resource], error]]

BatchList executes the query and returns an iterator for the results in batches, each result wrapped in the Row envelope.

Example
package main

import (
	"context"
	iter "iter"

	"github.com/impulseframework/impulse/accesstypes"
)

type ExampleResource struct{}

func (ExampleResource) Resource() accesstypes.Resource {
	return "ExampleResources"
}

func (ExampleResource) DefaultConfig() Config {
	return Config{}
}

func main() {
	ctx := context.Background()
	client := SpannerClient{}
	qSet := &QuerySet[ExampleResource]{}

	// Each batch iterator must be iterated on at least once before iterating on the next batch.
	// If a database iter.Seq2 errors, all following batches are invalid and iteration should halt.
	for batch := range qSet.BatchList(ctx, &client, 10) {
		if err := processExampleBatch(batch); err != nil {
			return
		}
	}

	// It's acceptable to break out of an iterator early and move onto the next batch iterator.
	for batch := range qSet.BatchList(ctx, &client, 10) {
		for row, err := range batch {
			if err != nil {
				return
			}

			if row.Data.Resource() == "" {
				break
			}
		}
	}

	// BAD: Handing off batched iterators to go routines and progressing to the next batched iterator is illegal behavior.
	for batch := range qSet.BatchList(ctx, &client, 10) {
		go func() { _ = processExampleBatch(batch) }()
	}
}

func processExampleBatch(batch iter.Seq2[*Row[ExampleResource], error]) error {
	for row, err := range batch {
		if err != nil {
			return err
		}

		_ = row
	}

	return nil
}

func (*QuerySet[Resource]) Caller added in v0.5.0

func (q *QuerySet[Resource]) Caller() *Caller

Caller returns the caller the query was checked as: the checker, the scope and the environment its decode bound, with the collection its conditions resolve against. It is what a computed resource's generated frames stamp into the context (WithCaller) once the decode has checked the request, before the List function, the Read function or the function that renders a file runs, as a method's frame stamps the caller for its body. Such a function reads it with CallerFrom and asks as the request's own check did (Caller.Check, Caller.ExecuteGate), so a list that offers what a method takes lists what the method would accept from this caller, and nothing the function calls mistakes the request for a call the application makes itself. A handler written by hand over a computed query stamps it the same way. A QuerySet bound to no permissions answers a zero Caller, which every question refuses.

func (*QuerySet[Resource]) Collect

func (q *QuerySet[Resource]) Collect(rows iter.Seq2[*Resource, error]) (*Page[Resource], error)

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

func (q *QuerySet[Resource]) Count(ctx context.Context, txn ReadOnlyTransaction) (int64, error)

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

func (q *QuerySet[Resource]) JudgesRows() bool

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

func (q *QuerySet[Resource]) KeySet() KeySet

KeySet returns the KeySet containing the primary key(s) for the resource.

func (*QuerySet[Resource]) Len

func (q *QuerySet[Resource]) Len() int

Len returns the number of fields to be returned by the query.

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

func (q *QuerySet[Resource]) Order() []SortField

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

func (q *QuerySet[Resource]) Page() *Page[Resource]

Page returns the collector for the page this QuerySet was decoded to read.

func (*QuerySet[Resource]) Permitted

func (q *QuerySet[Resource]) Permitted(ctx context.Context) (bool, error)

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

func (q *QuerySet[Resource]) ReturnAccessibleFields(b bool) *QuerySet[Resource]

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]) SetLimit

func (q *QuerySet[Resource]) SetLimit(limit *uint64)

SetLimit sets the maximum number of results to return.

func (*QuerySet[Resource]) SetSortFields

func (q *QuerySet[Resource]) SetSortFields(sortFields []SortField)

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

func (q *QuerySet[Resource]) TakeSort() []SortField

TakeSort returns the list's total order (the request's sort or the declared default, then the primary key) and marks it as the body's: the handler will not sort. A body that takes the sort must yield its rows in exactly this order, or its pages are wrong. An empty order means the list is not sorted, no sort asked and none declared, which a decoded request reaches only as a whole list (limit=all, or a key-less list), and the body's own yielded order is the list's; the handler leaves that order alone whether or not the body takes it. The order's NULL placement is the application database's own — Spanner first ascending and last descending, PostgreSQL the reverse — so a plain ORDER BY in the body's query produces it with no NULL handling of its own, and the handler's sort and page boundary follow the same placement whenever they still run.

func (*QuerySet[Resource]) TenantsListed added in v0.5.0

func (q *QuerySet[Resource]) TenantsListed(ctx context.Context) (set, narrowed []accesstypes.Domain, err error)

TenantsListed returns what a live subscription to this list across tenants is held over: set, the tenants the list may read (the session's reach, narrowed by the request's filter on the tenant) in which the person holds the List grant on the record, sorted; and narrowed, that filter as the request sent it, nil when it sent none. It asks the grant alone, as Permitted asks it of one tenant's list: the field and row rules run when the query does. It fails on a query that is not a list across tenants.

func (*QuerySet[Resource]) User

func (q *QuerySet[Resource]) User() accesstypes.User

User returns the identity the permission check ran as: the session's user, the viewed person under a view-as session, or the real actor under an act-as-role session. A computed resource's List or Read function reads it to yield the caller's own row without reaching into the session; empty when no check was bound.

type QuerySetComparer

type QuerySetComparer interface {
	Resource() accesstypes.Resource
	Fields() []accesstypes.Field
	KeySet() KeySet
}

QuerySetComparer is an interface for comparing two QuerySet-like objects.

type RPCDecoder

type RPCDecoder[Request any] struct {
	// contains filtered or unexported fields
}

RPCDecoder decodes an HTTP request for an RPC-style endpoint, validates the request body, and enforces permissions for the RPC method.

func MustNewRPCDecoder

func MustNewRPCDecoder[Request any](a DecoderAccessor, methodName accesstypes.Resource, perm accesstypes.Permission) *RPCDecoder[Request]

MustNewRPCDecoder builds a decoder for an RPC method request, resolving user permissions and validating request bodies through the accessor. It panics on construction errors: they are programming errors (a malformed request struct), surfaced at application startup where generated handlers construct their decoders.

func NewRPCDecoder

func NewRPCDecoder[Request any](userPermissions func(*http.Request) UserPermissions, methodName accesstypes.Resource, perm accesstypes.Permission) (*RPCDecoder[Request], error)

NewRPCDecoder creates a new RPCDecoder for a given request type, method name, and required permission.

func (*RPCDecoder[Request]) Decode

func (s *RPCDecoder[Request]) Decode(request *http.Request, scope accesstypes.Scope) (*Request, error)

Decode decodes the HTTP request body into the Request struct and checks user permissions in the given domain partition.

The check is eager (decode is the last library-controlled point before application code executes), so it must resolve to Granted or Denied: a Conditional decision here is a 500-class invariant breach — an RPC method has no rows for a condition to evaluate against, and MigrateRoles rejects such grants at deploy.

func (*RPCDecoder[Request]) DecodeCaller

func (s *RPCDecoder[Request]) DecodeCaller(request *http.Request, scope accesstypes.Scope) (*Request, *Caller, error)

DecodeCaller decodes and checks like Decode and also returns the Caller the check ran as — checker, scope, and sampled environment — for the handler to stamp into the context the method's body runs under.

func (*RPCDecoder[Request]) WithCollection

func (s *RPCDecoder[Request]) WithCollection(collection *GeneratedCollection) *RPCDecoder[Request]

WithCollection wires the generated collection to the decoder, so the caller it stamps can render conditional grants into the live check of a body's armed writes.

func (*RPCDecoder[Request]) WithValidator

func (s *RPCDecoder[Request]) WithValidator(v ValidatorFunc) *RPCDecoder[Request]

WithValidator sets a validator function on the decoder.

type ReadOnlyTransaction

type ReadOnlyTransaction interface {
	SpannerReadOnlyTransaction() spxapi.Querier
	PostgresReadOnlyTransaction() any
}

ReadOnlyTransaction is an interface that represents a database transaction that can be used for reads only.

type ReadOnlyTransactionCloser

type ReadOnlyTransactionCloser interface {
	ReadOnlyTransaction
	Close()
}

ReadOnlyTransactionCloser is an interface that represents a database transaction that can be used for reads only and must be closed when it is no longer needed.

type ReadWriteTransaction

type ReadWriteTransaction interface {
	DBType() DBType
	ReadOnlyTransaction
	BufferMap(res PatchSetMetadata, patch map[string]any) error
	BufferStruct(res PatchSetMetadata) error

	// DataChangeEventIndex provides a sequence number for data change events on the same Resource inside the same transaction
	DataChangeEventIndex(res accesstypes.Resource, rowID string) int
}

ReadWriteTransaction is an interface that represents a database transaction that can be used for both reads and writes.

type Reader

type Reader[Resource Resourcer] interface {
	DBType() DBType
	Read(ctx context.Context, stmt *Statement) (*Row[Resource], error)
	List(ctx context.Context, stmt *Statement) iter.Seq2[*Row[Resource], error]
	// Count runs a statement whose single row and column is a count and returns it.
	Count(ctx context.Context, stmt *Statement) (int64, error)
}

Reader is an interface that wraps methods for reading resources from a database. Read and List return each row wrapped in the Row envelope, which carries the row data alongside per-row metadata.

type ReleaseFile

type ReleaseFile struct {
	Outlets   map[string]ReleaseOutlet `json:"outlets"`
	Scheduled []ScheduledRoute         `json:"scheduled,omitempty"`
	// FileRoutes are the routes that carry a file rather than JSON, in path order: each
	// @upload method's route and each stored file's read route (@file). None when the
	// code declares neither.
	FileRoutes []FileRoute `json:"fileRoutes,omitempty"`
	// Surfaces are the surfaces the code declares a request log word or a trace setting
	// for, in prefix order: the application default as the surface at /
	// (WithRequestLog), each outlet that declares a word or a setting as its prefix
	// (OutletRequestLog, OutletTraces), each prefix the application mounts routes under
	// by hand (WithMountedRoutes), and each generated route with its own words (@rpc,
	// @file, @schedule) as the path the router mounts it at. Each says whether it is a
	// prefix or a route (Kind), since the router matches the two differently. The
	// nearest declaration wins, so a reader resolves a path by its longest matching
	// surface. The application's stack reads them to render the cloud's own request-log
	// exclusion. None when the code declares nothing, and then every request's entry is
	// written and every span follows the front end.
	Surfaces []Surface `json:"surfaces,omitempty"`
}

ReleaseFile is the generated release file: one entry per outlet, keyed by the outlet's name (default for the outlet GenerateRoutes declares, the name given to WithRouterOutlet otherwise), and the scheduled routes in path order, absent when the application declares none.

func ReadReleaseFile

func ReadReleaseFile(dir string) (ReleaseFile, error)

ReadReleaseFile reads the generated release file from dir, the router package's directory. A missing file is an error wrapping fs.ErrNotExist: no router is generated there, or the application predates the file. A file that is not the shape the generator writes, or that names no outlet, is refused naming what is wrong.

type ReleaseOutlet

type ReleaseOutlet struct {
	// APIKey marks a machine outlet (Tokens in the generator program), written as
	// {"kind": "api-key"}: its clients carry no release, so nothing is checked against
	// one, and the entry carries no oldestAnswered.
	APIKey bool
	// OldestAnswered is a session outlet's oldest answered release as the generator
	// program declared it: a release such as 1.5.0; ThisRelease, written as "this", for
	// a release that changes the API inside a maintenance window; or empty, written as
	// "", when the option is absent and every release that sends the header is
	// answered. Empty on a machine outlet.
	OldestAnswered string
	// Programs are the programs the release ships through a machine outlet
	// (ShipsProgram in the generator program), in declaration order, written as
	// "programs" on the outlet's entry and absent when it ships none: the version build
	// compiles each for its platforms and the outlet serves the compiled files to their
	// installed copies. A session outlet ships none.
	Programs []ReleaseProgram
}

ReleaseOutlet is one outlet's entry in the release file. A session outlet carries its oldest answered release; a machine outlet is never checked against a release and carries its kind and the programs the release ships through it.

func (ReleaseOutlet) MarshalJSON

func (o ReleaseOutlet) MarshalJSON() ([]byte, error)

MarshalJSON writes the entry as the file spells it: {"kind": "api-key"} for a machine outlet, with its programs when it ships any, {"oldestAnswered": <release>} for a session outlet with ThisRelease as "this". A session outlet carrying programs, or a program the generator would not write, is refused.

func (*ReleaseOutlet) UnmarshalJSON

func (o *ReleaseOutlet) UnmarshalJSON(data []byte) error

UnmarshalJSON reads an entry as the file spells it and refuses one that is neither a machine outlet nor a session outlet naming its oldest answered release: a kind other than api-key, a machine outlet carrying oldestAnswered, a session outlet without it or carrying programs, an oldestAnswered that is neither a release, "this" nor empty, or a program that is not the shape the generator writes.

type ReleaseProgram

type ReleaseProgram struct {
	Name      string   `json:"name"`
	Dir       string   `json:"dir"`
	Platforms []string `json:"platforms"`
}

ReleaseProgram is one program a machine outlet ships, as the release file spells it: the main package's root-relative directory (cmd/corral), the program's name, the base of that directory (corral), and the platforms it is compiled for, each as <os>/<arch> (linux/amd64).

type ReleasedKey

type ReleasedKey struct {
	Store StoreName
	Key   string
}

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

func (r Row[Resource]) MarshalJSON() ([]byte, error)

MarshalJSON delegates to the row data: marshaling a Row produces exactly the bytes that marshaling the Resource itself would.

func (Row[Resource]) Masked

func (r Row[Resource]) Masked(jsonName string) bool

Masked reports whether the cell with the given JSON name is masked on this row.

func (Row[Resource]) Tenant added in v0.5.0

func (r Row[Resource]) Tenant() accesstypes.Domain

Tenant returns the tenant the row is in, on a row of a list across tenants (QueryDecoder.DecodeAcrossTenants): the generated handler names it on the row under TenantProperty, so a page groups the rows by tenant and opens each one inside its tenant's routes. Empty on every other row.

type RowChange

type RowChange struct {
	Key     string
	Deleted bool
}

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

type SearchColumn struct {
	Column string
	Tag    string
}

SearchColumn is one searchable column of a resource as the generated query builder declares it for the search box: the column and its search tag.

type SearchRole

type SearchRole string

SearchRole is how a field's token column reads its column, which decides how a typed term is normalized before it is bound.

const (
	// SearchRoleText tokenizes the column as it is: TOKENIZE_SUBSTRING(col). The term
	// binds as typed; Spanner folds case and punctuation.
	SearchRoleText SearchRole = "text"
	// SearchRoleDigits tokenizes the column's digits: TOKENIZE_SUBSTRING(REGEXP_REPLACE
	// (col, r'\D', ”)). Everything but digits is stripped from the term, so "123-45"
	// meets "123454321".
	SearchRoleDigits SearchRole = "digits"
	// SearchRoleDate tokenizes a date or timestamp as YYYYMMDD: TOKENIZE_SUBSTRING
	// (FORMAT_DATE('%Y%m%d', col)), or FORMAT_TIMESTAMP with the zone the day is read
	// in. The term is read as a date in the forms the server accepts and binds YYYYMMDD
	// or its prefix.
	SearchRoleDate SearchRole = "date"
)

type SearchSpec

type SearchSpec struct {
	// Token is the TOKENLIST column tokenizing the field's column, "" without the
	// search fact.
	Token string
	// Index is the search index carrying Token: the key-set statement groups a view's
	// fields by it.
	Index string
	// Role is how Token reads the column.
	Role SearchRole
	// Anchors are the relative search types Token was tokenized with.
	Anchors []SearchAnchor
	// Contains says Token answers an unanchored match: false under
	// short_tokens_only_for_anchors, where the field answers its anchors alone.
	Contains bool
	// Lower is the stored LOWER(col) column that leads an index or sits after the tenant
	// column in one: the prefix fact. "" without it.
	Lower string
	// Diacritics says Token was tokenized with remove_diacritics, so the in-memory
	// matcher folds them too.
	Diacritics bool
	// Zone is the time zone a date role over a timestamp formats its day in, as the
	// schema names it; "" on a DATE column, which has none.
	Zone string
	// InMemory marks a computed resource's allow_filter string field: every match and the
	// box are evaluated by the handler over the rows the body yields, with no column
	// behind them.
	InMemory bool
}

SearchSpec is the search tag's content: what a field answers and through which columns. The generator writes it onto a list or read request struct field (Tag), the decoder reads it back (parseSearchSpec), and the renderer binds the field's matches through it. A field with a Token joins its resource's box; a field with a Lower column alone answers startswith and nothing else.

func (*SearchSpec) Answers

func (s *SearchSpec) Answers(operator string) bool

Answers reports whether the field answers the match as an explicit operator on a string field: contains through an unanchored token column, startswith through the lowercased column or a prefix anchor, endswith through a suffix anchor; an evaluated field answers all three.

func (*SearchSpec) HasAnchor

func (s *SearchSpec) HasAnchor(anchor SearchAnchor) bool

HasAnchor reports whether the token column was tokenized with the anchor.

func (*SearchSpec) JoinsBox

func (s *SearchSpec) JoinsBox() bool

JoinsBox reports whether the field takes part in its resource's search box: a field with the search fact, or a computed resource's evaluated field. A field with the prefix fact alone does not: the box over a table with a search index never mixes in the prefix fact, so a table serves its box from one index.

func (*SearchSpec) Matches

func (s *SearchSpec) Matches() []string

Matches lists the explicit matches the field answers, in the order the metadata spells them.

func (*SearchSpec) Tag

func (s *SearchSpec) Tag() string

Tag renders the spec as the search tag's value, the form parseSearchSpec reads.

type Secret added in v0.5.0

type Secret struct {
	// contains filtered or unexported fields
}

Secret is the type of a resource field that holds a secret (conditions:"secret"): the bytes its column stores and nothing else. It goes in and out of the database unchanged, on Spanner and on PostgreSQL. It prints as [secret] in JSON, in logs, through fmt and in error text, and it has no method that gives the value that was sealed: SecretKeys opens it, through the generated Open<Field> method of its row. A nullable column is typed *Secret. The zero Secret holds no value.

func (*Secret) DecodeSpanner added in v0.5.0

func (s *Secret) DecodeSpanner(val any) error

DecodeSpanner implements spanner.Decoder: the stored bytes of a BYTES column, which the client hands over in base64, and no value for NULL.

func (Secret) EncodeSpanner added in v0.5.0

func (s Secret) EncodeSpanner() (any, error)

EncodeSpanner implements spanner.Encoder: the stored bytes, for a BYTES column; NULL for a Secret that holds no value.

func (Secret) Equal added in v0.5.0

func (s Secret) Equal(other Secret) bool

Equal reports whether two Secrets hold the same stored bytes. Two writes of one value never do, since each draws its own random number.

func (Secret) Format added in v0.5.0

func (Secret) Format(f fmt.State, _ rune)

Format implements fmt.Formatter: every verb prints [secret], so no verb reaches the stored bytes.

func (Secret) GoString added in v0.5.0

func (Secret) GoString() string

GoString implements fmt.GoStringer and answers [secret].

func (Secret) IsZero added in v0.5.0

func (s Secret) IsZero() bool

IsZero reports whether the Secret holds no stored value.

func (Secret) KeyVersion added in v0.5.0

func (s Secret) KeyVersion() int

KeyVersion returns the version of the application secret the value was sealed under, which its first two bytes name; 0 for a Secret that holds no value, or too few bytes to name a version.

func (Secret) LogValue added in v0.5.0

func (Secret) LogValue() slog.Value

LogValue implements slog.LogValuer and answers [secret].

func (Secret) MarshalJSON added in v0.5.0

func (Secret) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler and answers "[secret]".

func (Secret) MarshalText added in v0.5.0

func (Secret) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler and answers [secret].

func (*Secret) Scan added in v0.5.0

func (s *Secret) Scan(src any) error

Scan implements sql.Scanner: the stored bytes of a bytea column, and no value for NULL.

func (Secret) String added in v0.5.0

func (Secret) String() string

String implements fmt.Stringer and answers [secret].

func (*Secret) UnmarshalJSON added in v0.5.0

func (*Secret) UnmarshalJSON([]byte) error

UnmarshalJSON refuses: a Secret holds stored bytes, which only the database gives it. A request carries a secret as text, in a string field declared conditions:"secret".

func (Secret) Value added in v0.5.0

func (s Secret) Value() (driver.Value, error)

Value implements driver.Valuer: the stored bytes, for a bytea column; NULL for a Secret that holds no value.

type SecretFieldRetirement added in v0.5.0

type SecretFieldRetirement struct {
	Resource  accesstypes.Resource
	Field     accesstypes.Field
	Rewritten int
}

SecretFieldRetirement is one secret field of a retirement: how many of its values named the retired version and were written again under the current one.

type SecretHolder added in v0.5.0

type SecretHolder struct {
	// Resource is the resource holding the secrets.
	Resource accesstypes.Resource
	// Fields are its secret fields, in the struct's order.
	Fields []accesstypes.Field
	// contains filtered or unexported fields
}

SecretHolder is a resource that stores secrets: its secret fields, and how a retirement of a version of the application secret reads and rewrites the values they hold. The generator writes one for each resource with a stored secret into the resources package's SecretHolders(), which the application's migrate command hands to RetireSecretVersion.

func SecretHolderOf added in v0.5.0

func SecretHolderOf[R Resourcer]() SecretHolder

SecretHolderOf declares a table resource as a holder of stored secrets: the fields its struct declares conditions:"secret". The generated SecretHolders calls it.

type SecretKeys added in v0.5.0

type SecretKeys struct {
	// contains filtered or unexported fields
}

SecretKeys seals and opens the secrets a resource stores (Secret). It is built once at start from the versions of the application secret (NewSecretKeys) and handed to the database client (WithSecretKeys), and it is the one thing in the process that holds key material: the versions it was built from are not kept, only the working keys derived from them. A value is sealed under the highest version given, the current one, and opened under whichever version its first two bytes name.

func NewSecretKeys added in v0.5.0

func NewSecretKeys(versions map[int][]byte) (*SecretKeys, error)

NewSecretKeys builds the key holder from the versions of the application secret: each version's number, 1 to 65535, with its 32 random bytes. The highest version is the current one. A deployment hands the versions over in the environment (SecretKeysFromEnv); a test builds the holder from fixed bytes.

func SecretKeysFromEnv added in v0.5.0

func SecretKeysFromEnv(name string, environ []string) (*SecretKeys, error)

SecretKeysFromEnv builds the key holder from the environment, where a deployment hands over every enabled version of the application secret in a variable of its own: the name the configuration declares secret:"versioned", an underscore and the version's number (APP_SECRET_KEY_1, APP_SECRET_KEY_2), each holding the version's 32 random bytes in Base64. environ is os.Environ(): the whole list is read, so every variable the name numbers is either a version or an error, and none is passed over.

With no version in the environment it answers no error and a holder that holds no key: an application that stores no secret runs without the variable, and one that stores a secret is refused at start by its generated router (RequireSecretKeys), which names the variable that is missing from the name the holder was read under. A variable that is set and does not hold a version is an error naming the variable, never its value. The declared name with no version number is no version, and is not read: set to a value with no numbered version beside it, it is the secret put in the wrong variable, and is refused by name with the variable to use. A stored value names the version that sealed it in two bytes, so versions run from 1 to 65535: the variable of a version past the last is an error, since the service would otherwise go on sealing under an older version than the deployment's newest, and so is the variable of version 0, which no deployment hands over.

func (*SecretKeys) Current added in v0.5.0

func (k *SecretKeys) Current() int

Current returns the version new values are sealed under: the highest one given.

func (*SecretKeys) Open added in v0.5.0

func (k *SecretKeys) Open(key KeySet, stored Secret) (string, error)

Open decrypts the stored bytes of a secret field of the row whose primary key is key, under the version they name. The generated Open<Field> method of a row calls it with the row's own key, so an author never passes one. Bytes that name a version the holder was not given answer an UnknownSecretVersionError, and bytes that were written for another row or altered answer ErrSecretNotOpened.

func (*SecretKeys) OpenNullable added in v0.5.0

func (k *SecretKeys) OpenNullable(key KeySet, stored *Secret) (*string, error)

OpenNullable opens the secret of a nullable column: no value for a row that holds none, and what Open answers otherwise.

func (*SecretKeys) Seal added in v0.5.0

func (k *SecretKeys) Seal(key KeySet, plain string) (Secret, error)

Seal encrypts a value for the row whose primary key is key, under the current version: the stored bytes of the row's secret field. key carries every key column's value in key order; the write path, which calls this for a patch, takes it from the patch.

func (*SecretKeys) Versions added in v0.5.0

func (k *SecretKeys) Versions() []int

Versions returns the versions the holder was given, ascending.

type SecretRetirement added in v0.5.0

type SecretRetirement struct {
	// Variable is the variable the retired version is handed over in, as it was given.
	Variable string
	// Version is the version retired, and Current the one its values now name.
	Version int
	Current int
	// Fields are the secret fields read, in holder order.
	Fields []SecretFieldRetirement
}

SecretRetirement is what a retirement did: the version retired, the current version its values were written under, and how many values of each secret field it rewrote. It holds no value.

func RetireSecretVersion added in v0.5.0

func RetireSecretVersion(ctx context.Context, client Client, variable string, holders ...SecretHolder) (*SecretRetirement, error)

RetireSecretVersion writes every stored secret that names one version of the application secret again under the current version, and confirms that none is left: what makes the version safe to disable. variable is the variable the version is handed over in, the name the configuration declares secret:"versioned", an underscore and the version's number (APP_SECRET_KEY_1), as the migrate command's -retire-secret flag is given it. holders are the application's resources that store a secret (the generated SecretHolders of each resources package).

The client holds the secret keys (WithSecretKeys), built from every enabled version, the one being retired among them: its values are opened under it, so a retirement that was not handed that version is refused before anything is read, naming the variable that is missing. The current version, the highest the client was given, cannot be retired, since new values are sealed under it. A value that does not open (its bytes were moved from another row, or altered) is passed over, and every value that opens, in every field of every holder, is written all the same; the retirement then fails with how many do not open, naming the resource, field and row of the first of them, never a value. A value that still names the version when the retirement has finished is an error too. Running it again is safe: a second run finds nothing to write and answers a retirement that rewrote nothing.

The service keeps serving meanwhile. A value is written back only while its row still holds the bytes that were opened, read again inside the writing transaction, so a value set since is never overwritten; the rewrite is the stored bytes alone, with no permission check, no update function and no change record, since the value did not change.

func (*SecretRetirement) Rewritten added in v0.5.0

func (r *SecretRetirement) Rewritten() int

Rewritten is how many values the retirement wrote again, over every field.

type SessionUserChecker added in v0.5.0

type SessionUserChecker interface {
	UserPermissionChecker

	// SuperAdministrator reports whether the user holds the Super
	// Administrator role (accesstypes.SuperAdministrator), the role the
	// framework defines in every auth: its holder enters every tenant,
	// whatever the tenant's sign-in settings say. Holding another role in the
	// global partition, or a role in every tenant, is not it.
	SuperAdministrator(ctx context.Context) (bool, error)

	// AdministersTenant reports whether the user administers the tenant: they
	// hold one of the roles the application names as a tenant's
	// administrator's in the tenant itself, inside its period, by a membership
	// of their own in the tenant's domain or through a group kept in that
	// tenant. A role held in every tenant, or through a group kept for the
	// whole application, is not it. A tenant that admits its people through
	// its directory only still admits its own administrators with a password
	// and a second factor (signin.TenantDeclaration.AdmitsAdministrator).
	AdministersTenant(ctx context.Context, domain accesstypes.Domain) (bool, error)
}

SessionUserChecker is the checker SessionPermissions takes for a person: a UserPermissionChecker that also says whether the person is a super administrator. The session's reach into a tenant asks it of the session's actor, so the answer is the real person's behind an impersonated session.

The canonical implementation is the access package's request-bound checker (Client.ForUser), which satisfies this interface structurally.

type Set

type Set[Resource Resourcer] struct {
	// contains filtered or unexported fields
}

Set holds metadata about a resource, including its permissions and field-to-tag mappings.

func NewSet

func NewSet[Resource Resourcer, Request any](permissions ...accesstypes.Permission) (*Set[Resource], error)

NewSet creates a new Set for a given Resource and Request type. Field-level enforcement is structural: every client-addressable field of Request requires the given permissions (Delete stays resource-level and is never required per field), except fields carrying the perm:"-" primary-key exemption, whose readability follows the resource-level grant.

func (*Set[Resource]) BaseResource

func (r *Set[Resource]) BaseResource() accesstypes.Resource

BaseResource returns the base name of the resource (without any tags).

func (*Set[Resource]) ImmutableFields

func (r *Set[Resource]) ImmutableFields() map[accesstypes.Tag]struct{}

ImmutableFields returns a map of tags for fields that are marked as immutable.

func (*Set[Resource]) PermissionRequired

func (r *Set[Resource]) PermissionRequired(fieldName accesstypes.Field, perm accesstypes.Permission) bool

PermissionRequired checks if a specific permission is required for a given field.

func (*Set[Resource]) Permissions

func (r *Set[Resource]) Permissions() []accesstypes.Permission

Permissions returns all permissions associated with the resource set.

func (*Set[Resource]) Positional

func (r *Set[Resource]) Positional(fieldName accesstypes.Field) bool

Positional reports whether the field declared masking:"positional": its masked cells stay hidden in the output, but a sort or filter on it runs on the real column (see MaskingPositional).

func (*Set[Resource]) Resource

func (r *Set[Resource]) Resource(fieldName accesstypes.Field) accesstypes.Resource

Resource returns the full resource name for a field, including its tag (e.g., "myresource.myfield").

func (*Set[Resource]) ResourceMetadata

func (r *Set[Resource]) ResourceMetadata() *Metadata[Resource]

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

type SetCache[Resource Resourcer, Request any] struct {
	// contains filtered or unexported fields
}

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

type SetFeatureRequest struct {
	Name    string `json:"name"`
	Enabled bool   `json:"enabled"`
}

SetFeatureRequest is the SetFeature method's body: the flag and the value to write.

type SetFeatureResult

type SetFeatureResult struct {
	Name      string    `json:"name"`
	Enabled   bool      `json:"enabled"`
	UpdatedAt time.Time `json:"updatedAt"`
}

SetFeatureResult is the SetFeature method's answer: the flag as the table holds it after the write, read back from the reloaded copy.

type SignalKind

type SignalKind string

SignalKind names one kind of shared state an application's instances signal each other about: a signal carries nothing but the fact that something of the kind changed, and every instance subscribed to the kind rereads what it keeps of it. The live service carries the signals (live.Signaler and live.Subscriber over one signals document per application, a field per kind), and the kinds are declared here, in the package the live package imports, so the live package, the access adapter and the tenant roster all name one type without an import cycle; the live package re-exports it as live.Kind with the same constants.

const (
	// KindFeatures is a feature flag flip: every FeatureSet following it rereads the
	// FeatureFlags table.
	KindFeatures SignalKind = "features"
	// KindTenants is a change of the tenant roster: an instance holding the roster
	// rereads it.
	KindTenants SignalKind = "tenants"
	// KindPolicy is a change of the permission policy (roles, grants, memberships): an
	// instance holding a policy snapshot rereads it.
	KindPolicy SignalKind = "policy"
)

The kinds.

type SignalSubscriber

type SignalSubscriber interface {
	Subscribe(kind SignalKind, onSignal func()) (stop func(), err error)
}

SignalSubscriber delivers the signals of a kind: what a FeatureSet follows. onSignal runs on every signal of the kind after the subscription began, on the subscriber's goroutine, so it must return quickly; stop ends the subscription. The live service implements it (live.Subscriber).

type Signaler

type Signaler interface {
	Signal(ctx context.Context, kind SignalKind) error
}

Signaler signals every instance of the application that a kind of shared state changed: what a flip signals through. The live service implements it (live.Signaler); a failure is the caller's to log and never fails the request, since every subscriber also rereads at its own backstop.

type SortDirection

type SortDirection string

SortDirection defines the sort direction for a field.

const (
	// SortAscending specifies sorting in ascending order.
	SortAscending SortDirection = "asc"
	// SortDescending specifies sorting in descending order.
	SortDescending SortDirection = "desc"
)

type SortField

type SortField struct {
	Field     string
	Direction SortDirection
}

SortField represents a field to sort by, including the field name and sort direction.

type SpannerClient

type SpannerClient struct {
	// contains filtered or unexported fields
}

SpannerClient is a wrapper around the database.

func NewSpannerClient

func NewSpannerClient(db *spanner.Client, opts ...ClientOption) *SpannerClient

NewSpannerClient creates a new Client. WithFileStore and WithNamedFileStore hand it the stores the frames drive and a committed transaction's released file objects are deleted from; a store wired twice, or two stores on one location, panics here. WithSecretKeys hands it the keys its transactions seal a patch's secret fields with.

func (*SpannerClient) DBType

func (c *SpannerClient) DBType() DBType

DBType returns the database type.

func (*SpannerClient) ExecuteFunc

func (c *SpannerClient) ExecuteFunc(ctx context.Context, f func(ctx context.Context, txn ReadWriteTransaction) error) error

ExecuteFunc executes a function within a read-write transaction. A commit Spanner refuses for a reason the caller can act on (a referential refusal, a duplicate key or unique value, a violated CHECK constraint, an update of a row that does not exist) answers as a 4xx whose message is composed from the patches the transaction buffered (see translateCommitError); an error the function itself returns, and a commit refused with any other code, pass through unchanged.

Before the commit, a transaction whose patches release a file object of a store the client holds no store for is refused naming the store: the rows would go and the object would stay with nothing to delete it. Once the commit lands, the file objects the transaction's patches released (a deleted row's @file keys, the old key of a row pointed at another object) are deleted from their stores, synchronously, before ExecuteFunc returns, detached from the request's cancellation; a failed delete is logged naming the keys and the call still returns nil, since the rows are gone. A transaction that does not commit, for any reason, releases nothing. Last, what the transaction's writes registered for after the commit runs (AfterCommit), in registration order; a transaction that does not commit runs none of it.

func (*SpannerClient) FileStore

func (c *SpannerClient) FileStore(name StoreName) FileStore

FileStore returns the store wired under name, nil when none is.

func (*SpannerClient) PostgresReadOnlyTransaction

func (c *SpannerClient) PostgresReadOnlyTransaction() any

PostgresReadOnlyTransaction panics because it is not implemented for the SpannerClient.

func (*SpannerClient) ReadOnlyTransaction

func (c *SpannerClient) ReadOnlyTransaction() ReadOnlyTransactionCloser

ReadOnlyTransaction returns a read-only transaction that can be used for multiple reads from the database. You must call Close() when the ReadOnlyTransaction is no longer needed to release resources on the server.

func (*SpannerClient) SpannerReadOnlyTransaction

func (c *SpannerClient) SpannerReadOnlyTransaction() spxapi.Querier

SpannerReadOnlyTransaction returns a read-only transaction for the Spanner client.

type SpannerGenerator

type SpannerGenerator struct {
	// contains filtered or unexported fields
}

SpannerGenerator is a SQL generator for Spanner.

func NewSpannerGenerator

func NewSpannerGenerator() *SpannerGenerator

NewSpannerGenerator creates a new SpannerGenerator.

func (*SpannerGenerator) GenerateSQL

func (g *SpannerGenerator) GenerateSQL(node ExpressionNode) (sqlStr string, params map[string]any, err error)

GenerateSQL generates SQL for the given node and returns named parameters.

type SpannerReadOnlyTransaction

type SpannerReadOnlyTransaction struct {
	// contains filtered or unexported fields
}

SpannerReadOnlyTransaction represents a database transaction that can only be used for reads.

func (*SpannerReadOnlyTransaction) Close

func (c *SpannerReadOnlyTransaction) Close()

Close closes the readonly transaction

func (*SpannerReadOnlyTransaction) PostgresReadOnlyTransaction

func (c *SpannerReadOnlyTransaction) PostgresReadOnlyTransaction() any

PostgresReadOnlyTransaction panics because it is not implemented for the SpannerReadOnlyTransaction.

func (*SpannerReadOnlyTransaction) SpannerReadOnlyTransaction

func (c *SpannerReadOnlyTransaction) SpannerReadOnlyTransaction() spxapi.Querier

SpannerReadOnlyTransaction returns a read-only transaction for the Spanner client.

type SpannerReadWriteTransaction

type SpannerReadWriteTransaction struct {
	// contains filtered or unexported fields
}

SpannerReadWriteTransaction represents a database transaction that can be used for both reads and writes. It records the resource and patch type of every patch it buffers, so a commit Spanner refuses can be answered in terms of what the transaction was asked to do; the file objects its patches release, so the executor deletes them once the commit lands; and the rows its patches write, so the request publishes them to the live pages once the commit lands.

func NewSpannerReadWriteTransaction

func NewSpannerReadWriteTransaction(txn *spanner.ReadWriteTransaction) *SpannerReadWriteTransaction

NewSpannerReadWriteTransaction creates a new SpannerReadWriteTransaction from a spanner.ReadWriteTransaction. A transaction an application wraps itself and commits outside ExecuteFunc has no executor to delete the file objects its patches released: read them off the wrapper with Released after the commit and delete them from the store yourself. It also has no executor to hand the rows it wrote to the request's collector, so nothing it writes reaches the live pages, and none to run what its writes registered for after the commit (AfterCommit): call Committed once the commit has landed. And it has no client to take the application's secret keys from: a transaction whose patches set a secret field is given them with WithSecretKeys.

func (*SpannerReadWriteTransaction) BufferMap

func (c *SpannerReadWriteTransaction) BufferMap(r PatchSetMetadata, patch map[string]any) error

BufferMap buffers a map of changes to be applied to the database.

func (*SpannerReadWriteTransaction) BufferStruct

func (c *SpannerReadWriteTransaction) BufferStruct(patch PatchSetMetadata) error

BufferStruct buffers a struct of changes to be applied to the database.

func (*SpannerReadWriteTransaction) Committed added in v0.3.0

func (c *SpannerReadWriteTransaction) Committed(ctx context.Context)

Committed runs what the transaction's writes registered for after the commit (AfterCommit), for a transaction committed outside ExecuteFunc, whose executor makes the calls itself. Call it once, after the commit has landed, and never for a transaction that did not commit.

func (*SpannerReadWriteTransaction) DBType

func (c *SpannerReadWriteTransaction) DBType() DBType

DBType returns the database type.

func (*SpannerReadWriteTransaction) DataChangeEventIndex

func (c *SpannerReadWriteTransaction) DataChangeEventIndex(res accesstypes.Resource, rowID string) int

DataChangeEventIndex provides a sequence number for data change events on the same Resource inside the same transaction.

func (*SpannerReadWriteTransaction) PostgresReadOnlyTransaction

func (c *SpannerReadWriteTransaction) PostgresReadOnlyTransaction() any

PostgresReadOnlyTransaction panics because it is not implemented for the SpannerReadWriteTransaction.

func (*SpannerReadWriteTransaction) Released

func (c *SpannerReadWriteTransaction) Released() []ReleasedKey

Released returns the file objects the transaction's patches released so far, each with its store: a deleted row's @file keys, and the old key of a row pointed at another object. Under ExecuteFunc the executor deletes them from the client's stores after the commit; a transaction committed outside it leaves that to its caller.

func (*SpannerReadWriteTransaction) SpannerReadOnlyTransaction

func (c *SpannerReadWriteTransaction) SpannerReadOnlyTransaction() spxapi.Querier

SpannerReadOnlyTransaction returns a read-only transaction for the Spanner client.

func (*SpannerReadWriteTransaction) WithSecretKeys added in v0.5.0

WithSecretKeys gives the transaction the application's secret keys, which it seals a patch's secret fields with, and returns the transaction. ExecuteFunc gives a transaction its client's; this is for one an application wraps itself (NewSpannerReadWriteTransaction).

type Statement

type Statement struct {
	SQL    string
	Params map[string]any
	// contains filtered or unexported fields
}

Statement is a generic container for a SQL statement and its parameters, supporting both Spanner and PostgreSQL.

func (*Statement) SpannerStatement

func (s *Statement) SpannerStatement() spanner.Statement

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).

func (StoreName) String

func (n StoreName) String() string

String spells the name as refusals and logs name the store: "the default store", or "store documents".

type StoredFile

type StoredFile struct {
	Key         string
	Name        string
	ContentType string
}

StoredFile is what a @file row says about its stored file: the key column's value (empty for NULL), and the name and type columns where the declaration names them.

type SubjectAnchor

type SubjectAnchor struct {
	Resource accesstypes.Resource
	Scope    accesstypes.PermissionScope
	Binding  SubjectBindingData
	Domain   *DomainBindingData
}

SubjectAnchor is a subject-vocabulary entry with everything its rendering needs: the anchor table (the resource declaring it), the entry itself, and the anchor table's own tenancy binding — the rendered subquery filters to the request's partition exactly when both the request and the anchor table are partitioned, derived here, never authored.

type SubjectBindingData

type SubjectBindingData struct {
	Name       string
	UserColumn string
	Column     string
	Type       AttributeType
	Path       []BindingHop
	Who        []SubjectWhoData
	Where      *SubjectWhereData
}

SubjectBindingData is one entry of the subject-side vocabulary (subject.<name>), anchored on the declaring resource's user-id column. UserColumn correlates rows to the requester; Column is the local column the set or value yields — the terminal when Path is empty, or the foreign key a dotted value: continues through. Type is the comparison type of the column the set or value yields (the terminal of a dotted value), derived by generation from that column's Go type exactly as an attribute's is; deploy validation admits a grant only where it compares or tests the entry against an attribute of the same type.

A subject set may write two more parts. Who says which rows of the table are the requester's: empty, it is UserColumn equal to the requester; written, it is the tests below joined by OR, and UserColumn is the column of one of them, the one the declaration sits on. Where says which of those rows count: nil, every one does. A subject value writes neither.

type SubjectColumnData added in v0.5.0

type SubjectColumnData struct {
	Name   string
	Column string
	Type   AttributeType
}

SubjectColumnData is one column a subject set's where: part reads: the name the condition writes for it, the column, and the column's comparison type.

type SubjectFactSource added in v0.3.0

type SubjectFactSource interface {
	DBType() DBType
	SpannerReadOnlyTransaction() spxapi.Querier
}

SubjectFactSource is the database a computed decoder reads the caller's facts from: the application's resource client.

type SubjectWhereData added in v0.5.0

type SubjectWhereData struct {
	Condition string
	Columns   []SubjectColumnData
}

SubjectWhereData is a subject set's where: part: a condition over the columns of the set's own row, compared to literals and to now (condition.ParseWhere). Condition is the part as the declaration writes it, and Columns resolves each name it reads to the row's column and that column's comparison type, which a literal binds as.

type SubjectWhoData added in v0.5.0

type SubjectWhoData struct {
	Column string
	Set    string
}

SubjectWhoData is one test of a subject set's who: part. Column is the column of the set's row the test reads. With Set empty the test is the column equal to the requester; with Set named it is the column's membership in that subject set of the requester's (Column IN subject.<Set>), the test a grant's condition writes with the row's column where the attribute stands.

type Surface

type Surface struct {
	// Prefix is the path as mounted: a prefix such as /beacons/ or /droids/, or a route
	// pattern such as /api/widgets/{id}/content, where a segment in braces stands for any
	// one segment; / is the application default.
	Prefix string `json:"prefix"`
	// Kind says how the router matches the prefix against a request's path:
	// SurfacePrefix by prefix, so everything under /beacons/ is the surface's, or
	// SurfaceRoute to the end of the path, so /api/widgets/{id}/content is the surface's
	// and /api/widgets/{id}/content-extra is not. The application default, an outlet and
	// a hand-mounted prefix are prefixes; an annotated method's route (@rpc, @file,
	// @schedule) is a route. A file written before the surfaces carried their kind reads
	// as prefixes throughout.
	Kind SurfaceKind `json:"kind"`
	// Log is the request log word: RequestLogAlways, RequestLogOnEvent, RequestLogSampled
	// or RequestLogNever; empty when the surface declares its trace setting alone.
	Log string `json:"log,omitempty"`
	// Fraction is the share of the quiet requests a sampled surface writes the entry for,
	// above 0 and at most 1; set with RequestLogSampled alone.
	Fraction float64 `json:"fraction,omitempty"`
	// Traces is the trace setting: TracesFollowFrontEnd, TracesCapped or TracesOff; empty
	// when the surface declares its request log word alone.
	Traces string `json:"traces,omitempty"`
	// Rate is the share of the front end's traces a capped surface keeps, above 0 and at
	// most 1; set with TracesCapped alone.
	Rate float64 `json:"rate,omitempty"`
}

Surface is one declared surface in the release file: a path prefix or a route pattern as the router mounts it, with the request log word, the trace setting, or both.

type SurfaceKind

type SurfaceKind string

SurfaceKind is how the router matches a surface's prefix against a request's path, as the release file spells it.

const (
	// SurfacePrefix is a path prefix, matched by strings.HasPrefix as the router does: the
	// application default at /, an outlet's prefix, or a prefix mounted by hand.
	SurfacePrefix SurfaceKind = "prefix"
	// SurfaceRoute is a route pattern, matched whole as the router does: an annotated
	// method's path, a parameter in braces standing for one segment.
	SurfaceRoute SurfaceKind = "route"
)

The surface kinds: a prefix is matched against the start of the path and a route to its end.

type TagData

type TagData struct {
	Name        accesstypes.Tag
	Permissions []accesstypes.Permission
	// Masking is how the field's masked cells meet a sort or a filter; empty
	// is MaskingConcealing, the default.
	Masking Masking
	// Formerly is the field's former wire name (@formerly on the field): the name
	// older browser applications still send and read, which the decoders accept, every
	// row carries beside Name and the permission digest mirrors with Name's states.
	// Empty for a field never renamed.
	Formerly accesstypes.Tag
}

TagData describes one field-level tag registration. An empty Permissions slice records a tag that is registered without requiring any permission.

type TargetedMethod

type TargetedMethod struct {
	Method     accesstypes.Resource
	Target     accesstypes.Resource
	Transition *TransitionData
}

TargetedMethod pairs an RPC method resource with the row resource its @target field addresses; Transition carries the declared edge when the method is a transition, nil for the plain located-row form.

type TargetedRPCDecoder

type TargetedRPCDecoder[Request any] struct {
	// contains filtered or unexported fields
}

TargetedRPCDecoder decodes an HTTP request for a @target-bearing RPC method. Unlike RPCDecoder, a Conditional Execute decision here is not an invariant breach: the generated handler has a located row to evaluate it against, so Decode carries the condition forward as an ExecuteGate.

func MustNewTargetedRPCDecoder

func MustNewTargetedRPCDecoder[Request any](a DecoderAccessor, collection *GeneratedCollection, methodName accesstypes.Resource, perm accesstypes.Permission) *TargetedRPCDecoder[Request]

MustNewTargetedRPCDecoder builds a decoder for a @target-bearing RPC method request, wired to the generated collection so a carried condition can lower against the target resource's bindings. It panics on construction errors: they are programming errors (a malformed request struct), surfaced at application startup where generated handlers construct their decoders.

func (*TargetedRPCDecoder[Request]) Decode

func (s *TargetedRPCDecoder[Request]) Decode(request *http.Request, scope accesstypes.Scope) (*Request, *ExecuteGate, error)

Decode decodes the HTTP request body into the Request struct and checks the caller's Execute permission in the given scope. Denied is Forbidden here; Granted and Conditional both admit — a Conditional decision's payload rides the returned ExecuteGate, which the generated frame enforces against the located target row inside its transaction.

func (*TargetedRPCDecoder[Request]) WithValidator

func (s *TargetedRPCDecoder[Request]) WithValidator(v ValidatorFunc) *TargetedRPCDecoder[Request]

WithValidator sets a validator function on the decoder.

type TenantDeclarationColumns

type TenantDeclarationColumns struct {
	// DirectoryOnly is the tenant record's BOOL column saying the tenant's people enter
	// through its directories only, so a password does not reach it; empty when the
	// record declares none, and every tenant admits a password.
	DirectoryOnly string
	// DirectoriesTable is the directories record's table, one row for the directory a
	// tenant admits its people through: TenantColumn holds the tenant's key, MethodColumn
	// the sign-in method as sessioninfo.AuthMethod spells it (google, azure, workos) and
	// ConnectionColumn the connection the method's identities carry (a Google Workspace
	// by its domain, a Microsoft Entra tenant by its tenant id). A tenant has one
	// directory and a directory is one tenant's: the schema holds both with a unique
	// index on TenantColumn and one on MethodColumn and ConnectionColumn, and the record's
	// write paths refuse each first (TenantDirectoryRules).
	DirectoriesTable string
	TenantColumn     string
	MethodColumn     string
	ConnectionColumn string
	// DirectoriesKeyColumn is the directories record's key column, which the methods
	// that say how a tenant admits its directory's people write the tenant's row
	// through (TenantDirectoryRules.Directory); empty where the record carries no
	// default seat column.
	DirectoriesKeyColumn string
	// DefaultSeatColumn is the directories record's column naming the role a person is
	// seated with in the tenant at their first sign-in through its directory, NULL or
	// empty for none (the tenant admits a stranger from its directory by invitation
	// only); empty when the record carries no such column, and every directory admits
	// by invitation only. Read by the sign-in's directory reader
	// (NewTenantDirectoryReader), never by the roster.
	DefaultSeatColumn string
}

TenantDeclarationColumns names where the tenant record keeps its declaration of who may enter it (signin.TenantDeclaration), so the roster reads the declaration beside the keys and the sign-in policy reads it in its own transaction (NewTenantDeclarationReader): the record's directory-only column, and the directories record's table with its tenant, method and connection columns. The generated New<Record>Roster and New<Record>DeclarationReader constructors supply them from the @directoryOnly and @tenantDirectory declarations; an application names none of them.

type TenantDeclarations

type TenantDeclarations func(ctx context.Context, domain accesstypes.Domain) (*signin.TenantDeclaration, error)

TenantDeclarations reads what a tenant declares about who may enter it: the tenant's declaration (signin.TenantDeclaration) by domain, as the application keeps it, which SessionPermissions applies to each tenant the session holds a grant in. It answers nil for a tenant that declares nothing, which admits a password and refuses a sign-in through a directory, as the sign-in policy does (signin.TenantPolicy). An application that keeps no declarations passes nil to SessionPermissions, and every tenant admits every session.

type TenantDirectory added in v0.5.0

type TenantDirectory struct {
	// Key is the row's key as text, which the generated methods write the row through.
	Key string
	// Directory is the organization the tenant's people sign in through.
	Directory signin.Directory
	// DefaultRole is the role a person is given in the tenant at their first sign-in
	// through the directory, "" where the tenant admits the directory's people by
	// invitation only.
	DefaultRole accesstypes.Role
}

TenantDirectory is a tenant's directory as its row of the directories record holds it.

type TenantDirectoryRules added in v0.5.0

type TenantDirectoryRules struct {
	// contains filtered or unexported fields
}

TenantDirectoryRules holds a tenant's directory to its rules at every write of the directories record (@tenantDirectory):

  • a tenant has one directory;
  • a directory, its method and its connection together, is one tenant's;
  • a personal account (any Google account, a Microsoft personal account) is no organization's directory, so it is no tenant's;
  • a directory is not removed while the tenant is directory only, since nobody could then enter the tenant.

The schema holds the first two as well, with a unique index on the directories record's tenant column and one on its method and connection: the rules read what is committed, so two writes that race, or that one transaction buffers together, are refused by the index at the commit. The rules refuse first, each with a sentence the person can act on, where the index can only say that a unique value exists.

A directory is never typed in. It is set from a sign-in: FromSession answers the directory the caller is signed in through, held to the rules, which the directories record's generated create stamps on the row, and Set holds a directory a sign-in names to the rules, for a write made inside that sign-in. The generated New<Record>DirectoryRules supplies the tables and the word for one tenant; an application names none of them.

func NewTenantDirectoryRules added in v0.5.0

func NewTenantDirectoryRules(table, keyColumn string, columns *TenantDeclarationColumns, word string) *TenantDirectoryRules

NewTenantDirectoryRules builds the rules over the tenant record's table and key column and its declaration's columns. word is what the refusals call one tenant ("tenant", "sector"), as the application's people say it.

func (*TenantDirectoryRules) Directory added in v0.5.0

Directory answers tenant's directory as committed, in the caller's transaction: the row the two methods that say how the tenant admits the directory's people write. A tenant with no directory has nobody to open to and nothing to make invite only, and is refused with a Conflict that says to set the directory first.

func (*TenantDirectoryRules) DirectoryOnly added in v0.5.0

func (r *TenantDirectoryRules) DirectoryOnly(ctx context.Context, txn ReadWriteTransaction, tenant accesstypes.Domain, value any) error

DirectoryOnly holds a write of tenant's directory-only switch to its rules, in the caller's transaction, and writes nothing: value is the flag the write carries. Turning the switch off is plain, and so is a write that leaves it on. Turning it on is refused, each time as a Conflict with a sentence the person can act on:

  • until the tenant has its directory: with none there is nothing to be only of, and nobody could enter;
  • unless the caller is signed in through that directory themselves: the session proves the directory works, and the person who closes the tenant to every other sign-in is not shut out by it;
  • unless the caller's own account has a password, where their auth has a password method (PasswordsBy): a tenant's own administrator enters a directory-only tenant with a password and a second factor, which is the way back in if the directory has a problem, and a person who has only ever signed in through the directory would have none. The refusal says to choose a password first. Where the caller's auth has no password method the rule stands down, and nothing is said of it.

The rules read what is committed, and a transaction's reads do not see what it has buffered, so the transaction notes each write the rules pass (directoryWrites): a request that removes the tenant's directory and turns the switch on is refused, whichever comes first, as each would be after the other had committed.

Nobody is exempt from them, a super administrator included: the rules are about the directory and the way back in, not about who may enter. The switch is the tenant's own, turned by the tenant's administrator: the generated methods of a tenant record that declares it (@directoryOnly) and a directories record, Make<Record>DirectoryOnly and End<Record>DirectoryOnly in the tenant's scope, ask the rule once the caller's Execute grant has answered and then write the flag. No other request writes it: the record's field is output only on the wire, so neither the record's update nor its create carries it.

func (*TenantDirectoryRules) DirectoryOnlyWarning added in v0.5.0

func (r *TenantDirectoryRules) DirectoryOnlyWarning(ctx context.Context, txn ReadWriteTransaction, tenant accesstypes.Domain, people ...DirectoryPeople) (*Warning, error)

DirectoryOnlyWarning says what turning tenant's directory-only switch on would do, in the caller's transaction, and writes nothing: the warning the method that turns it on (Make<Record>DirectoryOnly) answers before it is run, which a dialog shows and holds its button under until the person has typed DirectoryOnlyWord. The consequence says who will be able to enter the tenant and how many of the people seated in it will not, counted through people, one entry for each auth whose people the tenant seats; the confirm words say what the button does. Where no entry reads anybody (an application whose people no generated management lists) nobody was counted, and the sentence says who will lose access without a number: it never says that everyone has signed in through the directory on a count nobody made.

Everyone the switch would keep out is counted. A person is named only to a caller who may list them: the people of an auth are named where the request's caller (CallerFrom) holds the tenant's list of that auth's people (DirectoryPeople), and counted alone where the caller does not. A call outside a request names nobody.

It refuses as DirectoryOnly refuses, with the same sentences, so a page that asks first shows the refusal instead of a dialog; a tenant the record does not hold is NotFound. A tenant that is directory only already has nothing to turn on, and the warning is refused as a Conflict that says so and names neither its directory nor its people: the write that leaves the switch on is plain whoever makes it, and the warning answers nobody what that write would not ask them to prove.

func (*TenantDirectoryRules) FromSession added in v0.5.0

FromSession answers the directory the caller is signed in through, held to the rules for tenant: the directory the directories record's generated create stamps on the row, so no request types a method or a connection. Every refusal is a Conflict: SessionDirectory's and Set's.

func (*TenantDirectoryRules) NamedBy added in v0.5.0

NamedBy answers the rules with the namers of the application's auths, which say what each auth's sign-in registrations call a directory: every sentence of the rules that names a directory then says it in words a person knows (DirectoryWords), the name a registration gives it or the label of its button, and never its connection, which for a Microsoft Entra tenant is an id. The generated frames of a tenant's own methods pass the namer of each auth's generated identity client. Rules nobody names read what a directory alone says.

func (*TenantDirectoryRules) OpenToDirectoryWarning added in v0.5.0

func (r *TenantDirectoryRules) OpenToDirectoryWarning(directory *TenantDirectory, role accesstypes.Role) *Warning

OpenToDirectoryWarning says what opening a tenant to its directory's people with role would do, in the words a person reads before they confirm it, and the words for the button that does it. It writes nothing and judges no role: the method that opens the tenant holds the role to its rules before it asks. A request that names no role yet is answered, since the warning is read while the role is still being picked, and says the role is to be chosen. The directory is said in the words a person knows it by (DirectoryWords, through the namers the rules were given), never by its connection.

func (*TenantDirectoryRules) PasswordsBy added in v0.5.0

func (r *TenantDirectoryRules) PasswordsBy(readers ...CallerPassword) *TenantDirectoryRules

PasswordsBy answers the rules with what each of the application's auths says of the caller's password: a tenant is made directory only by a person who has a password, since a tenant's own administrator enters a directory-only tenant with a password and a second factor (signin.TenantDeclaration.AdmitsAdministrator), and that is the way back in if the directory has a problem. The generated frames of a tenant's own methods pass the reader of each auth's generated identity client. Where no auth's answer applies, as in an application whose people have no passwords, the rule stands down and nothing is said of it; rules built without readers ask nothing.

func (*TenantDirectoryRules) Remove added in v0.5.0

Remove holds the removal of tenant's directory to its rule, in the caller's transaction, and writes nothing: a tenant that is directory only keeps its directory, since its people enter through it alone and nobody could enter the tenant without it. The refusal is a Conflict that says to turn directory only off first. A request that turns the tenant directory only and removes its directory is refused the same way, though the switch it turns on is not yet committed: the transaction notes the writes the rules pass (directoryWrites). A tenant record with no directory-only column removes freely.

func (*TenantDirectoryRules) Set added in v0.5.0

Set holds directory to the rules as tenant's directory, in the caller's transaction, and writes nothing: the caller buffers the row once Set answers nil. It refuses, each as a Conflict with a sentence the person can act on, a directory that is no organization's (a personal account, or no directory at all), a tenant that has a directory already, and a directory another tenant has. The last says the organization already has a tenant, which a rule of one tenant per directory cannot keep from being learned; it does not say which.

func (*TenantDirectoryRules) State added in v0.5.0

State answers tenant's directory-only switch as it stands, in the caller's transaction; a tenant the record does not hold is NotFound.

type TenantRoster

type TenantRoster struct {
	// contains filtered or unexported fields
}

TenantRoster is one instance's copy of the tenant record's keys: the set of tenants the application serves, which the generated DomainGuard and the consolidated dispatcher ask before a tenant-scoped request runs. Start reads the set once and then keeps it current until the context ends: on every tenants signal the channel delivers and at the backstop interval regardless. The generated write paths of the tenant record call Add and Remove after their commit, so the instance that wrote a tenant serves it at once, and signal the tenants kind so every other instance reloads.

With WithTenantDeclarations the copy carries what each tenant declares about who may enter it beside its key, read in the same snapshot, and Declarations answers the generated DomainGuard's and the session's tenant list's question from it (TenantDeclarations) with no read and no wait; the generated write paths of the tenant record and of the directories record call Reload after their commit, so a declaration changed on this instance decides the next request here, and signal the tenants kind so every other instance reloads.

The set sits behind an atomic pointer, so Has never waits on a reload or a writer and performs no read: a domain the set does not hold is unknown, whatever the table says at that moment. A nil roster holds no tenant, so an application that wires none fails closed on every tenant-scoped route. It is safe for concurrent use.

func NewTenantRoster

func NewTenantRoster(client Client, table, keyColumn string, opts ...TenantRosterOption) *TenantRoster

func (*TenantRoster) Add

func (r *TenantRoster) Add(domain accesstypes.Domain)

Add puts the domain in the set at once, declaring nothing: what a test harness calls to hold a tenant the schema has no row for. The generated write paths call Reload instead, so the tenant's declaration comes with it. A nil roster takes nothing.

func (*TenantRoster) Declarations

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

Domains lists the tenants, sorted. It never fails and reads nothing; the signature is DomainRoster's, so the roster's Domains is what an application hands SessionPermissions. A nil roster lists none.

func (*TenantRoster) Has

func (r *TenantRoster) Has(domain accesstypes.Domain) bool

Has reports whether the domain is a tenant the roster holds. It loads the set and looks the domain up: no read, no wait. A domain the set does not hold is unknown, and every domain is unknown to a nil roster.

func (*TenantRoster) Name added in v0.4.0

func (r *TenantRoster) Name(domain accesstypes.Domain) string

Name answers the tenant's name as the record's name column held it at the last read (WithTenantNames), from the copy: no read, no wait. It is "" for a tenant the copy names nothing for, for every tenant of a roster that reads no names, and on a nil roster. The roster is the DomainNamer the session's tenant list names tenants with.

func (*TenantRoster) Named added in v0.5.0

func (r *TenantRoster) Named(name string) (accesstypes.Domain, error)

Named answers the tenant that carries the name, as the record's name column held it at the last read (WithTenantNames), from the copy: no read, no wait. A tenant's key is an id nobody reads, so what names a tenant by hand names it by its name: a development bootstrap reads its logins' tenants this way. A name no tenant carries and a name more than one tenant carries are errors: the first names nothing, and the second does not say which. A nil roster and one that reads no names hold no name.

func (*TenantRoster) Reload

func (r *TenantRoster) Reload(ctx context.Context) error

Reload rereads the table, the declarations with it, and replaces the set whole: what the tenant record's and the directories record's generated write paths call after their commit, so the instance that wrote serves the change at its next request, and what Start calls on every tenants signal and backstop tick. A failed read leaves the set as it was. A nil roster reads nothing.

func (*TenantRoster) Remove

func (r *TenantRoster) Remove(domain accesstypes.Domain)

Remove drops the domain from the set at once. A nil roster drops nothing.

func (*TenantRoster) Start

func (r *TenantRoster) Start(ctx context.Context) error

Start loads the set once, failing when the read fails, so an application never starts serving on an empty roster it could not fill, and then keeps it current until ctx ends: a goroutine rereads the table on every tenants signal (when a channel is wired) and at the backstop interval regardless. A failed reread is logged and the copy stays as it was until the next.

type TenantRosterOption

type TenantRosterOption func(*TenantRoster)

TenantRosterOption configures a TenantRoster at construction.

func WithTenantBackstop

func WithTenantBackstop(d time.Duration) TenantRosterOption

WithTenantBackstop sets how often Start rereads the table without a signal; TenantBackstop by default. Tests shorten it.

func WithTenantDeclarations

func WithTenantDeclarations(columns *TenantDeclarationColumns) TenantRosterOption

WithTenantDeclarations has the roster read what each tenant declares about who may enter it beside its key: the columns the generated New<Record>Roster constructor supplies from the @directoryOnly and @tenantDirectory declarations. Without it every tenant's declaration is nil, which declares nothing.

func WithTenantNames added in v0.4.0

func WithTenantNames(column string) TenantRosterOption

NewTenantRoster builds the roster over the tenant record's table, reading the key column into the set. The generated New<Record>Roster constructor supplies the table and the column from the @tenant declaration; an application calls that one. Nothing is read until Start. WithTenantNames has the roster read each tenant's name from the record's name column (the field the tenant record marks @tenantName) in the snapshot of its keys, so Name answers from the copy and the session's tenant list names each tenant (WithDomainNames) with no read of its own. The generated New<Record>Roster passes it when the record marks a name; an empty column reads none.

func WithTenantSignals

func WithTenantSignals(s TenantSignals) TenantRosterOption

WithTenantSignals wires the application's signal channel: Start subscribes the roster to the tenants kind on it, so a tenant another instance wrote reaches this one within a moment instead of at the backstop. Without it the backstop alone keeps the copy current.

type TenantSignals

type TenantSignals interface {
	Signaler
	SignalSubscriber
}

TenantSignals is the signal channel a TenantRoster follows: what the live service offers (resource.Signaler and resource.SignalSubscriber together). Signal tells every instance that a kind changed; Subscribe runs onSignal on every signal of the kind after the subscription began, on the channel's own goroutine, and stop ends the subscription. The roster never opens a listener of its own: it subscribes to the application's one watch, for KindTenants.

type TextIdent

type TextIdent struct {
	Ident[string]
	// contains filtered or unexported fields
}

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 Token

type Token struct {
	Type  TokenType
	Value string
}

Token represents a single token.

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
)

func (TokenType) String

func (i TokenType) String() string

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

Rows returns the committed rows grouped by the domain each was written in and then by resource, in first-written order within each resource. A row whose patch carried no domain (a global resource, or a patch built by hand) is listed under fallback: the mutating request's route domain, which is the zero Domain on a global route.

type TransitionData

type TransitionData struct {
	Target accesstypes.Resource
	From   []string
	To     string
}

TransitionData records a declared state transition on an RPC method resource: the workflow root it moves, the pre-image states it may run from, and the state the generated handler stamps after the body.

type TransitionMethod

type TransitionMethod struct {
	Method     accesstypes.Resource
	Transition TransitionData
}

TransitionMethod pairs an RPC method resource with its declared transition.

type TypescriptData

type TypescriptData struct {
	Permissions []accesstypes.Permission
	Resources   []accesstypes.Resource
	// Methods are the Execute-gated registrations: generated RPC methods and
	// manual declarations (@manualAddResource(Execute)) alike.
	Methods          []accesstypes.Resource
	ResourceTags     map[accesstypes.Resource][]accesstypes.Tag
	PermissionScopes []accesstypes.PermissionScope
}

TypescriptData holds all the collected resource and permission information needed for TypeScript code generation.

type UnknownSecretVersionError added in v0.5.0

type UnknownSecretVersionError struct {
	// Version is the version the stored value names.
	Version int
	// Held are the versions the service was given, ascending.
	Held []int
}

UnknownSecretVersionError is the error of opening a stored secret sealed under a version of the application secret the service was not given.

func (*UnknownSecretVersionError) Error added in v0.5.0

func (e *UnknownSecretVersionError) Error() string

Error names the version the value was sealed under and the versions the service holds.

type Upload

type Upload struct {
	// contains filtered or unexported fields
}

Upload is one multipart upload request the frame opened: the request part, ready for the method's decoder, with the file parts still on the wire behind it.

func OpenUpload

func OpenUpload(r *http.Request, maxBytes int64) (*Upload, error)

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

func (u *Upload) Request() *http.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

func (u *Upload) Stream(ctx context.Context, store FileStore, dryRun bool) (Files, error)

Stream reads the file parts behind the request part and streams each to the store under a fresh key, returning the Files the body receives. A dry run streams nothing: the parts are measured and described with empty keys. A form with no file part, or with a part under another name, is a 400; a body over the declared maximum is a 413. A failure after a part was stored (a later part malformed, over the limit, or refused by the store) deletes the parts already stored before the failure is returned, so no object is left behind by a request that never reaches its transaction. A nil store, the store the declaration names not wired on the resource client, is an error naming the wiring.

type UserDomain added in v0.4.0

type UserDomain struct {
	Domain accesstypes.Domain `json:"domain"`
	Name   string             `json:"name"`
	Closed string             `json:"closed,omitempty"`
}

UserDomain is one tenant of the session's tenant list: its domain, the key in every tenant-scoped URL, and its name as the tenant record holds it, for the tenant picker to show. Name is the domain itself where the application's roster reads no names (WithDomainNames) or the record holds none for the tenant.

Closed marks a tenant the person holds a seat in and this session cannot enter (ClosedDomains), with the reason in a sentence for the person: what the tenant admits and how they signed in ("Acme admits only people who sign in through its own directory. You signed in with a password."), a directory said in the words a person knows it by (WithDirectoryNames). The tenant's own administrator, who signed in with a password and whose session carries no second factor, is told the way in they hold as well ("As one of its administrators you can still enter it: sign out, then sign in again with your password and the code we email you."): the code is all that is missing, and the reason says what to do. It is empty, and absent from the JSON, for a tenant the session reaches. A picker shows a closed tenant marked, with the reason, and never as a place to open. Only a person's own sign-in is told of one: a session that views the application as someone else, and one that acts as a role, list none closed.

type UserDomainsOption added in v0.4.0

type UserDomainsOption func(*userDomainsSettings)

UserDomainsOption configures UserDomainsHandler.

func WithDirectoryNames added in v0.5.0

func WithDirectoryNames(namers ...DirectoryNamer) UserDomainsOption

WithDirectoryNames names the directory a session came through in a closed tenant's reason, from the namers of the application's auths: what each auth's sign-in registrations call it (DirectoryName). The generated UserDomains handler passes the namer of each auth's generated identity client. Without one the reason reads what the directory alone says, and it never says a tenant id.

func WithDomainNames added in v0.4.0

func WithDomainNames(names DomainNamer) UserDomainsOption

WithDomainNames names each tenant of the list from the namer, the application's tenant roster: what the generated UserDomains handler passes when the tenant record marks its name field (@tenantName). The roster answers from its copy, so naming the list reads nothing. A nil namer names nothing.

type UserPermissionChecker

type UserPermissionChecker interface {
	// Check returns the Decision for perm on each of resources within scope.
	//
	// env is the request's decision context, sampled once at decode; the check
	// folds environment-referencing conditions against it and fails loudly
	// (error, never a silent allow or deny) when a referenced attribute is
	// absent.
	//
	// The returned Decisions must carry an entry for every resource passed. A
	// resource absent from the map reads as the zero Decision — Denied — so a
	// short implementation fails closed, never open. Implementations must not
	// short-circuit on the first denial.
	//
	// Snapshot pinning: a single Check call must evaluate every resource against one
	// consistent authorization snapshot — a concurrent grant or revocation must affect
	// all of the call's results or none of them. Distinct calls may observe different
	// snapshots; callers must not assume pinning across calls.
	Check(ctx context.Context, env accesstypes.Environment, scope accesstypes.Scope, perm accesstypes.Permission, resources ...accesstypes.Resource) (accesstypes.Decisions, error)

	// PermissionDigest returns the user's structural grant enumeration within
	// scope — the payload the generated permission-digest endpoint serves.
	// Advisory UI material only, never consulted for enforcement: denied
	// targets are absent (fail closed) and nothing folds, so a payload is
	// stable for the life of a policy snapshot.
	PermissionDigest(ctx context.Context, scope accesstypes.Scope) (accesstypes.PermissionDigest, error)

	// HasGrants reports whether the user holds at least one grant in scope —
	// the foothold concealed tenancy's visibility check asks, and the
	// predicate the tenant picker filters the application's roster by. A
	// membership that resolves to no grants is not a foothold; a membership
	// held in every tenant domain is a foothold in each.
	HasGrants(ctx context.Context, scope accesstypes.Scope) (bool, error)

	User() accesstypes.User
}

UserPermissionChecker is what an application's per-request accessor for a user principal hands SessionPermissions: UserPermissions without Domains, since a checker holds no tenant list — the roster is the application's, and SessionPermissions filters it by HasGrants.

The canonical implementation is the access package's request-bound checker (Client.ForUser), which satisfies this interface structurally — neither package imports the other.

type UserPermissions

type UserPermissions interface {
	UserPermissionChecker

	// Domains lists the domains where the user holds at least one grant and
	// that the session reaches, sorted — the payload the generated
	// user-domains endpoint serves and the tenant picker's question: the
	// application's tenant roster filtered by HasGrants and by Reaches, so a
	// domain listed here is exactly a domain whose routes answer the user
	// with ordinary 403s rather than concealed tenancy's 404; the picker and
	// the guard can never disagree. Never nil: an application without
	// tenants lists none.
	Domains(ctx context.Context) ([]accesstypes.Domain, error)

	// Reaches reports whether the session may enter domain: the tenant's
	// declaration (TenantDeclarations) admits the way the session was
	// established, its sign-in's method and connection; or the session's
	// actor is a super administrator, who holds the Super Administrator role
	// and enters every tenant; or the tenant is directory only and the
	// session is its own administrator's, established with a password and
	// carrying a second factor. Nobody else is exempt from a tenant's sign-in
	// settings. It is the generated domain guard's
	// question before the foothold, and the attenuation behind every other
	// answer: in a tenant the session does not reach it holds nothing —
	// every check Denied, an empty digest, no foothold. Whether domain is a
	// tenant at all is the roster's question (TenantRoster.Has), which the
	// guard asks first. A session composed without declarations reaches
	// every domain.
	Reaches(ctx context.Context, domain accesstypes.Domain) (bool, error)
}

UserPermissions is the permission surface a request's decoders consume: the checks, the frontend's advisory enumerations, the identity a row condition's subject binds to, and the session's reach into the application's tenants. SessionPermissions composes it per request from the session's principal, the application's checker for that principal, the application's tenant roster and its tenant declarations; applications hand the composed value to the PatchSet and QuerySet types, which enforce permissions through it.

func Masked

Masked returns perms attenuated by mask: a permission the mask does not allow is Denied for every resource before policy is consulted — and evidenced as a mask denial — and the permission digest omits it. A foothold is answered through the masked digest, so a session masked to nothing has none and lists no domain. User and Reaches pass through. The unrestricted mask returns perms itself.

func RolePrincipalPermissions

func RolePrincipalPermissions(role RolePermissions, actor accesstypes.User) UserPermissions

RolePrincipalPermissions is a checker acting as a role on behalf of a real actor: the role's permissions answer the checks, and the actor's identity is what row conditions bind and change events record — the same composition an act-as-role session gets. It lists no domain: a body acting as a role asks no tenant picker.

func SessionPermissions

func SessionPermissions[U SessionUserChecker, R RolePermissions](
	ctx context.Context, forUser func(accesstypes.User) U, forRole func(accesstypes.Role) R, roster DomainRoster, declarations TenantDeclarations,
) UserPermissions

SessionPermissions composes the request's UserPermissions from the session in ctx. It picks the checker by the session's principal — forUser for a user principal (an ordinary session, or an impersonated user), forRole for a role principal — admits the session into the tenants that admit the way it was established, lists the session's domains as the application's roster filtered by that admission and by the checker's HasGrants, and applies the session's permission mask. It is the per-request accessor for an application with impersonated sessions:

return resource.SessionPermissions(r.Context(), a.access.ForUser, a.access.ForRole, a.tenants.Domains, a.declarations)

The roster is the application's: access holds no tenant list, so the tenant picker's question — which tenants may this session see — is the roster asked, tenant by tenant, whether the session holds a grant there and whether the tenant admits the session. An application without tenants passes nil for the roster and the declarations.

The declarations are the application's too: what each tenant declares about who may enter it (signin.TenantDeclaration), read by domain. A tenant's declaration restricts that tenant's own door and nobody else's: the session reaches every tenant that seats the person, except a tenant that is directory only and whose directory is not the one the person signed in through. A tenant is offered only when the session may enter it, and the tenant's declaration decides: it admits the session's establishment, the sign-in's method and connection the session's first auth event records (sessioninfo.SessionData.EstablishedBy; signin.TenantDeclaration.Admits is the decision), or the session's actor is a super administrator, a holder of the Super Administrator role (SessionUserChecker.SuperAdministrator), who enters every tenant whatever its sign-in settings say, as the sign-in policy admits them (signin.TenantPolicy), or the session's actor administers the tenant and came by the administrators' way in: a tenant that is directory only still admits its own administrators, in a session established with a password that carries a second factor (signin.TenantDeclaration.AdmitsAdministrator is the decision, the one the sign-in policy asks; SessionUserChecker.AdministersTenant says who administers, asked at every request, so the way in closes at the next request once the role is taken away or its period ends). Nobody else enters a directory-only tenant another way than through its directory: a person holding another global role, or a role in every tenant, the administrator's among them, is held to each tenant's declaration like anyone, and so is the tenant's administrator who signed in through another organization's directory, with a personal account, or with a password and no second factor. An impersonated session is established by its impersonation event, so a directory-only tenant refuses it unless the actor, the real person behind it, is a super administrator; whom the session is viewed as changes nothing. In a tenant the session does not reach it holds nothing: every check Denied, an empty digest, no foothold, and the tenant is not among its domains, so the picker never offers it as a place to open and the generated domain guard refuses a direct request for it as it refuses a domain that is not a tenant (UserPermissions.Reaches). The person holds a seat there all the same, so the tenant list of a person's own sign-in carries the tenant closed, with the reason (ClosedDomains, UserDomainsHandler); an impersonated session and a session that acts as a role are told of none. An application that keeps no declarations passes nil, and every tenant admits every session.

A person is named as the permission store names them: by the id of their account (sessioninfo.SessionData.User), never by the username, which can change and which two auths over one database can each hold. User() is that id, a row condition's subject binds to it, and a column that records who did something holds it.

A role checker has no User(): a role is not anyone. For a role principal the composed UserPermissions reports the session's effective identity — the actor who established a session that acts as a role, and otherwise the session's own person, whom a resolver gave the role (roleSessionUser) — so a row condition's subject binds to a real person and nobody's identity is borrowed. An application that does not operate sessions as roles passes RolePrincipalsUnsupported as forRole: a role principal then fails closed — every check Denied, an empty digest, no footholds, no domains — with the same User(), so a deployment that mints role principals without a checker is loud rather than permissive.

type ValidateFunc

type ValidateFunc func(ctx context.Context, txn ReadWriteTransaction) error

ValidateFunc is the signature for a function that validates a PatchSet prior to committing it.

type ValidatorFunc

type ValidatorFunc interface {
	Struct(s any) error
	StructPartial(s any, fields ...string) error
}

ValidatorFunc is the interface used to validate a struct, in whole or in part. Its methods return an error if the validation fails.

type ValueKind

type ValueKind int

ValueKind is how the patch decoder sizes a request field's value against its column's declared type: by code point, by byte, or by decimal digit. The generator classifies a source field's Go type into a kind with go/types and the runtime classifies the request struct's field with reflection; HasValueLimit is where the two agree on which pairs of kind and column type carry a rule.

const (
	// ValueKindOther is every type the decoder does not size: keys, integers, floats,
	// booleans, dates, timestamps, JSON, and the null wrappers of those.
	ValueKindOther ValueKind = iota
	// ValueKindString is a string-kinded type: string, a named string type, a pointer to
	// one, or spanner.NullString. Sized by code point against STRING(n), as Spanner
	// counts.
	ValueKindString
	// ValueKindBytes is []byte, sized by byte against BYTES(n).
	ValueKindBytes
	// ValueKindDecimal is decimal.Decimal, a pointer to one, decimal.NullDecimal, or
	// spanner.NullNumeric, sized by digit against NUMERIC.
	ValueKindDecimal
	// ValueKindSecret is the value of a secret field as a request carries it: text,
	// sized by byte against the BYTES(n) column its sealed form is stored in, less the
	// bytes sealing adds (SecretOverhead). The generator classifies a source field typed
	// Secret as this kind; the runtime meets it as a string-kinded request field and
	// takes it for a secret only where the resource declares the field one
	// (conditions:"secret"). A string-kinded field on a BYTES column that is no secret,
	// a named string type with an encoding of its own, has no rule.
	ValueKindSecret
)

type Warning added in v0.5.0

type Warning struct {
	// Consequence is what the call will do, in sentences a person reads before they
	// confirm it: who is affected and how.
	Consequence string `json:"consequence"`
	// Names are the people or things the consequence speaks of, one a line, where the
	// method can name them and the caller may be told: a dialog shows them as a list
	// under the sentences. Nil where the method names none; the consequence stands
	// without them, and says how many there are where that matters.
	Names []string `json:"names,omitempty"`
	// Confirm is the words on the button that runs the call, which say what it does
	// ("Open to anyone with a Google account"), so nobody confirms by a bare "OK".
	Confirm string `json:"confirm"`
}

Warning is what a method that declares one (@warning) says before it is run, in the server's words for the call the request describes.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL