resource

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT, MIT Imports: 66 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. Example: OpenMissionsBySquadron.
@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 at decode time, where no row exists, so the generated Collection marks it computed and deploy-time role migration rejects grants on it whose conditions are not row-free (the same rule Execute grants follow). 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. 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. 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. 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 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. 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). 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.
@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, or RootStructName Marks the field carrying the target row's key — exactly one per method, its type matching the target's single-column primary key. With @transition it is bare (the declared root is the target); 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. Example: HailShip.
@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.
@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 name, value: Field 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. Example: SquadronMembership.
@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. 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 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); and the record's generated create and delete paths add and remove the tenant in the roster after their commit and signal the tenants kind, so a tenant created at run time is served by every instance without a restart or a release. The record must be global, table-backed, and keyed by one string column (the slug in every tenant-scoped URL): @tenant on a @permissionScope(domain) struct, on a compound key, on a key that is not a string, 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. Example: Sector.
@directoryOnly field of the @tenant record, a bool column none The tenant's people enter through its directories only: a password, or any sign-in that is not through a directory, does not reach a tenant whose flag is true. 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 directories only needs directories to enter through. Whoever holds the record's Update grant on the column sets it, and the record's change events are the audit. The generated create-your-tenant route (@tenant(creation: ...)) 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.
@tenantDirectory @resource struct, @permissionScope(domain) none The struct is the directories record: the tenant-scoped table whose rows are the directories a tenant admits its people through, one row per declaration (one domain, one directory by default; a second directory is a second row), each naming the sign-in method (@directoryMethod) and the connection (@directoryConnection). Its tenant is the bare @domain column, the tenant's key on the row itself, so a tenant's administrator declares its own directories 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 create-your-tenant route declares the creator's directory on the new tenant. Refused on a global resource, on the tenant record itself, on a second struct, with a join-path @domain, and without either column. 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 or workos. 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. 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 stranger the directory vouches for is seated with in the tenant at their first sign-in, chosen by the tenant's administrator from the tenant's roles on its Sign-in page; NULL (or empty) says the tenant admits the directory's strangers by invitation only: they are 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. With it the generated New<Record>DirectoryReader answers every tenant's declaration of a directory with its seat, which the auth's directory admission reads (session.Auth.SetDirectoryAdmission) before the method's account rule, and the seat is written through resource.SeatDeclared once the sign-in's transaction has committed (section 16). 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. | | @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 (conditions are refused at decode there, nothing is ever masked). 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.
  • 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, 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 ✘ ✔ ✔
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. 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.

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.

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; 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 evaluates no conditions at read time, so its sort and filter fields still require an unconditional grant.

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.

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).

User domains. The payload is the sorted list of domains where the user holds at least one grant and that the session reaches — the tenant picker's question, answered by the library so no application hand-writes it. 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 picker 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). 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. 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 holds a grant in the global partition, the application's staff, who reach every tenant as the sign-in policy admits them. A tenant that declares nothing admits a password and refuses a sign-in through a directory. An impersonated session is established by its impersonation event, so a directory-only tenant refuses it unless the actor, the real person behind it, is staff. In a tenant the session does not reach it holds nothing — every Check Denied, an empty digest, no foothold — 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 — names the actor first for an impersonated session: alice impersonating bob (session id) and alice as role PartnerViewer (session id), unchanged (bob (session id)) otherwise. Every tracked data change carries evidence of the real person with no regeneration.

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(). 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.

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.

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"), PersonaMethod("persona"), with .Labeled(text) for the label the page shows (the method's own name otherwise: Password, Google, Microsoft, Single sign-on, Persona). 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 takes .InvitedUsers() and neither .SyncsRoles() nor .OpenSignUp(). 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 .InvitedUsers() and .SyncsRoles(), and an outlet's Manages(importPath), describe the Auth's user-management surface (section 21): what a directory admits, whose seats it writes, and which other Auth's users 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. 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. 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/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).

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: a token page at <mount>/tokens, where the person issues, lists and revokes their tokens, 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 for the live pages (section 14): 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 domain value testDomain 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.
  • 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 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.
  • 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
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) and never enumerated[] (a picker stores one key). 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. 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), 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.

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.

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, touched)), 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, and the change document's shape (kind of row, list or resource; resource; key and deleted on a row; domain on a list; at and expires). 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, 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 created 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.

The record. @tenant goes on the global, table-backed @resource whose rows are the tenants; its one string key 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 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. The record's generated write paths, the standalone PATCH handler and the consolidated dispatcher's case for the record and for its directories (below), call Reload after the commit, never inside it, so the instance that wrote the tenant, or its declaration, serves it at once; 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. Nothing is written to the permission store when a tenant is created: a role held in every tenant domain reaches the new tenant with nothing written for it. 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 directories only (a password does not reach it), and @tenantDirectory on a second, tenant-scoped resource whose rows are the directories the tenant admits its people through, one row each, with @directoryMethod on its sign-in method column (google, azure, workos, 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 columns are the record's own, edited under its grants, so the people who may change the declaration are the ones who hold them; 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); a record created by its own people 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 holds a grant in the global partition. A tenant that declares nothing admits its people by password and through no directory. A self-service record's create route (@tenant(creation: ...)) declares the creator's directory on the new tenant in the row's transaction, when the creator came through one, reloads the roster before it seats the creator, so the seat's probe asks what the next request asks, and removes the directory with the row when the seat fails.

The default seat. What a stranger from a declared directory gets at a first sign-in 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 directory a tenant declares is created and seated with that role in that 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 already seated in a declaring tenant, or holding a global or every-domain role, is let through as before, and the directory a stranger comes through that no tenant declares falls to the method's rule (members, invited, open). The generator emits New<Record>DirectoryReader(), a signin.DirectoryReader[*spanner.ReadWriteTransaction] reading every tenant's declaration of one directory 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, resource.SignInRoles(engine.UserManager()), resource.SeatDeclared(engine.UserManager())). 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 seat is written the way an accepted invitation's seats are, after the sign-in's transaction has committed and before the sign-in policy decides, so the policy finds the membership. The tenant's administrator sets the row's seat on the Sign-in page, a picker over the tenant's roles, and the record's change events are the audit of who opened the door and when. Two consequences: in a self-service application a colleague of a tenant's creator who signs in from the directory that tenant already declared gets no account and no second tenant, but the invitation-only answer; and the directory-vouched door of the user surface (section 21) no longer applies to a declared directory with a null seat, since no such account exists, while it keeps applying to undeclared directories under open sign-up.

The creator's seat. The person who creates a tenant is its first administrator, whatever the creation shape: the record's create path (the standalone patch handler and the consolidated dispatcher) seats the creator in each tenant the request created with the roles <Record>AdministratorRoles() names, through the user-management surface of the auth bound to the session outlets serving the record (<Auth>UserSurface().SeatStore(), both asserted against the application type in the generated roster file), after the commit and once this instance's roster lists the tenant, as the self-service route does; a seat that cannot be written removes the rows the request created, reloads the roster, signals, and answers the failure. A record served by session outlets bound to different auths is refused at generation, since the handler seats through one surface; a record served by no session auth (a hand-written router, a machine outlet alone) seats nobody. With the last-owner rule (section 21) an operator creates a customer's tenant, seats or invites its first administrator as a second owner, and leaves; an existing tenant gains no seat after the fact.

Tests. The generated authorization matrix drives domain-scoped routes with the domain value testDomain, and the application's newTestHandler adds it to the test application's 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.

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

Every Auth the generated router binds gets a user-management surface: its users, their seats and the roles a seat may take, served as resources beside the application's own, with the same grants, conditions, capability envelope and client handles. Nothing is configured by hand: the Auth's sign-in methods decide what the surface does, the tenant record decides whether it has a tenant partition, and the role file decides who may do what, in the grammar every other resource uses.

The routes, for an Auth in the package crew with a tenant record Sector, under the outlet's prefix (the global partition) and under the domain pair (the tenant partition):

GET   <prefix>/crew-users                            the users, sort=username            List on CrewUsers
GET   <prefix>/crew-users/{crewUserID}               one user                            Read on CrewUsers
PATCH <prefix>/crew-users                            operations body: add /, replace     Create, Update (username, disabled), Delete on CrewUsers
                                                     and remove /{id} → {"ids":[...]}
GET   <prefix>/crew-seats, …/crew-seats/{user}/{role} the seats, sort=username,role       List, Read on CrewSeats
PATCH <prefix>/crew-seats                            add /{user}/{role} {}, remove       Create, Delete on CrewSeats (a seat is never updated)
GET   <prefix>/crew-roles, …/crew-roles/{crewRoleName} the roles a seat may take          List, Read on CrewRoles (read-only)
POST  <prefix>/set-crew-user-password                {"user","password"}                 Execute on SetCrewUserPassword, targeting CrewUsers
POST  <prefix>/unlink-crew-user-identity             {"user","identity"}                 Execute on UnlinkCrewUserIdentity, targeting CrewUsers
POST  <prefix>/reset-crew-user-factors               {"user"}                            Execute on ResetCrewUserFactors, targeting CrewUsers
GET/PATCH <prefix>/sectors/{sectorID}/crew-sector-users, -seats, -roles,                 the same on CrewSectorUsers, CrewSectorSeats,
POST  <prefix>/sectors/{sectorID}/set-crew-sector-user-password, unlink-crew-sector-user-identity,   CrewSectorRoles and their methods (domain scope)
      reset-crew-sector-user-factors

The resource names are the Auth's package name in PascalCase, the tenant record's name for the tenant partition, and Users, Seats, Roles; the methods Set<…>UserPassword, Unlink<…>UserIdentity and Reset<…>UserFactors (forgets the browsers a user asked to be remembered after a sign-in code, so their next sign-in asks for the second factor again; served on every Auth). The global partition is every user of the Auth with the seats held in the global scope and in every domain; the tenant partition is the users seated in the route's tenant or everywhere, with their seats there. A create in the tenant partition takes a role beside username, password and disabled: the seat is what makes the person the tenant's user. Account-level actions from a tenant route (a rename, a disable, a delete, a password reset, an unlink) are refused with 409 for a user also seated outside the tenant; those belong to the global partition. Every PATCH honors X-Dry-Run. A struct, a computed resource, an RPC method or a manual registration that would take one of these names is refused at generation.

The row. A user row carries id, username, disabled, hasPassword, passwordChangeRequired, createdAt, lastSignInAt, organization (the tenant key the person's directory links carry, when they agree), identities (each link: id, method, connection, subject, organization, email, linkedAt, lastUsedAt), roles (the seats held in the partition's scope), everywhereRoles (the seats held in every domain) and rolesSynced (the seats are a directory's, see below). A seat row carries user, role, username and everyDomain (everywhere in the tenant partition); a role row name, description (what the role is for, in a sentence or two: the role file's for a default role, the one given when a custom role was made) and, in the global partition, kind (global or domain). A role is named for its job in PascalCase (Administrator, SectorMarshal), never for where it is held: the role file declares that by its structure, and the row's kind serves it. The rows are composed in Go from the Auth's account store (the session library's users and identities) and its engine's memberships, so a condition on a grant is judged over the composed row, and the capability envelope (capabilities=Update,Delete,Execute) answers from the grants and the rules below.

What the shape derives. The password method (PasswordMethod()) gives create with an optional password, the set-password method and the forced change: a password an operator sets marks the account, and the person changes it before anything else is served (section 8 lists the change route the router mounts). A registration declaring InvitedUsers() gives create without a password: the directory admits only people the application created first. A registration declaring SyncsRoles() writes the roles of everyone on its Auth at every sign-in, and stands alone there (the generator refuses another method beside it, since the directory is then the authority for everyone the Auth holds), so the surface leaves every seat to the directory: seating or unseating a user by hand is refused with 409, and every row says rolesSynced. An Auth with no password method and no invited-users registration creates nobody; its Unlink method exists once it has any registration. Several Auths give one surface each.

generation.GenerateRoutes("pkg/router", "console/api",
	generation.Auth("…/pkg/auth/crew", generation.PasswordMethod(), generation.GoogleMethod("google")),
	generation.Manages("…/pkg/auth/members"),
	generation.WebApp("/console"),
),
generation.WithRouterOutlet("portal", "portal/api",
	generation.Auth("…/pkg/auth/members", generation.GoogleMethod("directory").Labeled("Company directory").SyncsRoles()),
	generation.WebApp("/portal"),
),

Manages(importPath) makes an outlet serve another Auth's surface beside its own: the members' users, seats and roles under /console/api too, read and written through the members Auth's stores and checked in the console's engine against the console's role file. The collection is shared, so either role file may grant them; an application that wants only staff to manage members leaves the resources out of the members' file. The option must name a declared Auth other than the outlet's own.

What the application supplies. The generator writes zz_gen_user_surfaces.go into the router package, a marker type per Auth (router.CrewAuth) carrying the declaration it derived, and New<Auth>UserSurface(accounts, seats); and zz_gen_users.go into the handler package, every handler as a delegation to the surface the application returns from <Auth>UserSurface(), which the file asserts at compile time. The accounts are the session library's, adapted by sessionusers.Accounts(auth.API()); the seats are the engine's UserManager():

func (c *DataConfiguration) CrewUserSurface() *resource.UserSurface[router.CrewAuth] {
	return router.NewCrewUserSurface(sessionusers.Accounts(c.crew.Session().API()), c.crew.Access().UserManager())
}

A test harness hands the constructor resource.NewMemUserStore() for both: the generated authorization matrix drives the surface's routes like every other, so every Auth needs a surface there, and the in-memory store answers an empty list to a granted case and is never read by a denied one. A harness that reads the roles declares them with what each is for (DeclareRoles(scope, access.RoleInfo{Name: "Pilot", Description: "Flies for a sector."})), as a role file's roles exist in a permission engine's.

The role file. Every role in it is named in the one grammar the access library keeps, letters and digits starting with a capital letter (Administrator, SectorMarshal), and carries a description, one or two plain sentences saying what the role is for; the engine refuses a file whose role has another kind of name or no description, and the surface serves the description beside the name. The surface's resources are granted like any other, fields included (a user's non-key fields for List and Read, username, password, disabled and, in the tenant partition, role for Create, username and disabled for Update; a seat's user and role for Create). A condition may use the row's attributes (username, disabled, hasPassword, passwordChangeRequired, createdAt, lastSignInAt, organization, rolesSynced on a user; user, username, role, everyDomain/everywhere on a seat; name and kind on a role) and two subject bindings the first Auth declares for the application: subject.ownOrganization, the caller's own organization, and subject.ownRoles, the roles the caller holds in the partition. Lodestar's marshal seats crew in the sector in every role but the marshal's own:

"Create": [{ "resource": "CrewSectorSeats", "fields": ["user", "role"], "condition": "new.role != 'SectorMarshal'" }],
"Delete": [{ "resource": "CrewSectorSeats", "condition": "role != 'SectorMarshal'" }]

A seat is a resource rather than a method because a Create grant's condition may read the row being written (new.role) and an Execute grant's cannot.

The rules the library keeps whatever the role file says: nobody disables or deletes themselves (403); nobody unseats themselves from the last administrator seat of a partition (403), the last-owner rule: the surface is built with resource.WithAdministratorRoles(global, domain) naming the auth's administrator roles (the ones its first administrator is seeded with: the global roles are the global partition's, the domain roles a tenant partition's, held in the tenant or everywhere), and a self-unseat goes unless the seat is one of them and no other person holding one would remain in the partition (the same person's role held in every tenant stands behind their seat in one of them; their other administrator role is no other person), so a tenant's creator seats its first administrator and leaves, and a person who left is brought back by one who stayed; without the option every self-unseat is refused; a user whose only way in is the identity being unlinked keeps it (409); a tenant seat needs the user already seated in the tenant, from the global surface (400); a password is set through the set-password method, never through an update (400); a username rename moves the person's seats to the new name; and a seat removed that was the person's last anywhere deletes the account with its identity links, whoever removed it (the orphan rule). Grants are checked before any store is read, so a denied caller learns nothing, and every refusal is one the client library's error hook already renders.

Tests. The generated authorization matrix carries the lists and reads as query pairs and the patches and methods as denied-only cases, each method with its dry run, on every outlet serving the surface; the dispatch tests drive every route, and an outlet that does not serve a surface answers its routes 404.

The names the client library mirrors: the resources and methods above with their routes, keys (id; user, role; name), operations, patchable fields and order in the descriptor; the row interfaces and the shared UserIdentity interface in the resources file; the method bodies (SetCrewUserPassword, UnlinkCrewUserIdentity) in the methods file. The descriptor also carries a userSurfaces block, one entry per Auth the outlet serves: the Auth's name and label, whether it has a password method, its registrations (name, kind, label, invited, syncsRoles) and its partitions, each naming its three resources and the methods the Auth's shape gives it. The user-management component of @impulseframework/resource-angular configures itself from that block and reads the surface through the handles.

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 (

	// UserSubjectOrganization and UserSubjectRoles are the subject bindings the surface
	// declares once per application: the caller's own organization
	// (subject.ownOrganization) and the roles the caller holds in the partition
	// (subject.ownRoles), read off the caller's row in the Auth whose surface serves the
	// request. A resource's attributes and subject bindings share one namespace, so the
	// caller's facts are named apart from the row's (organization = subject.ownOrganization).
	UserSubjectOrganization = "ownOrganization"
	UserSubjectRoles        = "ownRoles"
)

The condition vocabulary of the user surface: the attributes a grant's condition may name on each resource, with the comparison types deploy validation checks literals against, and the application-wide subject bindings the caller's own row gives (subject.ownOrganization, subject.ownRoles). The names are the rows' wire names.

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

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

Variables

View Source
var Demonstrations = []Demonstration{}/* 274 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 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.

Functions

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 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 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 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

IsDryRun reports whether the request asks for a dry run.

func MigrateFeatures

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

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

func MockIterSeq2

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

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

func NewTenantDeclarationReader

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

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

func NewTenantDirectoryReader

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

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

func Operations

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.

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 RegisterUserSurface

func RegisterUserSurface(b *CollectionBuilder, decl *UserSurfaceDeclaration, withSubjects bool) error

RegisterUserSurface registers one Auth's surface into the collection: each partition's three resources with their field registrations, orders and vocabulary, and the methods that target its users. withSubjects declares the subject bindings on this Auth's global users resource; the generator sets it on the first Auth alone. The generator calls it for every Auth whose outlet the generated router serves.

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 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 SeatDeclared

func SeatDeclared(seats UserSeats) func(ctx context.Context, userID impulse.UUID, username string, declared []signin.DirectorySeat) error

SeatDeclared returns the application's half of a directory's default seat (session.Auth.SetDirectoryAdmission): the hook that seats the user a first sign-in provisioned with the default seats of the directories the tenants declared for the identity's connection, each a role in a tenant, through the auth's seats, once the resolution that created the user has committed and before the sign-in policy decides, so the policy finds the memberships. An application passes its engine's user manager, as it does to SeatInvited; the hook runs outside any transaction for the same reason.

func SeatFirstAdministrator

func SeatFirstAdministrator(ctx context.Context, seats UserSeats, perms UserPermissions, domain accesstypes.Domain, roles []accesstypes.Role) error

SeatFirstAdministrator seats the session's user as the first administrator of the tenant its row was just committed for: the roles are written in the tenant's domain scope through the auth's seats (the engine's user manager, which signals the policy change to every instance), and the call returns once the engine answers the person a foothold in the tenant, bounded by seatVisibleTimeout, so the answer the route gives is one the person's next request stands on. The generated route calls it after the commit and removes the row when it fails: the permission store writes memberships outside the row's transaction, so this is the one write that cannot ride it.

func SeatInvited

func SeatInvited(seats UserSeats) func(ctx context.Context, userID impulse.UUID, username string, inv *sessioninfo.Invitation) error

SeatInvited is the session library's acceptance hook (session.Auth.SetInvitationAccepted) over the Auth's membership store: when a person accepts an invitation, by signing in or signing up at it, the roles it carries are written as seats for them, in the invitation's tenant, or, for an invitation into the global partition, where each role is held (the global scope for a role of the global kind, every tenant for one of the domain kind), exactly as the surface seats by hand. The library runs the hook once the transaction that consumed the invitation has committed, outside any transaction, so the engine's own client writes the memberships; the writes are idempotent, so a sign-in that fails after them leaves seats a later seat of the same roles reuses.

func SeatsFollowRename

func SeatsFollowRename(seats UserSeats) func(ctx context.Context, userID impulse.UUID, from, to string) error

SeatsFollowRename is the session library's rename hook (session.Auth.SetUserRenamed) over the Auth's membership store: where the username is the person's email address, a verified new address renames the user, and the seats held under the old name move to the new one, as the surface's own rename moves them. Safe to run again after a failure midway.

func ServeRenderedFile

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

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

func ServeStoredFile

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

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

func SetFeatureEnabled

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

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

func SetFeatureHandler

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

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

func SetLocalZone

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. 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 UserDomainsHandler

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

UserDomainsHandler serves the session's tenant list: the sorted list of domains where the user holds at least one grant and that the session reaches. It is the tenant picker's question, answered by the library so applications wire nothing — the generated router registers it on the default outlet beside the digest.

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

func UserEvent

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: "username (session id)" for an ordinary session. For an impersonated session the actor comes first, so every data change carries evidence of the real person: "actor impersonating username (session id)" for an impersonated user, "actor as role name (session id)" for a role.

func UserProcessEvent

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 WithCaller

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

WithCaller stamps the caller into the context for the body that runs under it.

Types

type APIVersionCheck

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

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

type Answer

type Answer struct {
	Status int
}

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

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
}

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.

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 RPC handlers stamp it into the context before Execute runs; a body reads it back with CallerFrom.

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.

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) IsZero

func (c *Caller) IsZero() bool

IsZero reports whether no frame stamped the caller.

type Client

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

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

type ClientOption

type ClientOption func(*clientOptions)

ClientOption configures a database client at construction.

func WithFileStore

func WithFileStore(store FileStore) ClientOption

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

func WithNamedFileStore

func WithNamedFileStore[S NamedStore](store FileStore) ClientOption

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

type CollectionBuilder

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

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

func NewCollectionBuilder

func NewCollectionBuilder() *CollectionBuilder

NewCollectionBuilder creates an empty CollectionBuilder.

func (*CollectionBuilder) AddMethodResource

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

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

func (*CollectionBuilder) AddResource

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: a hand-written query surface whose permission checks run at decode time, where no row exists.

func (*CollectionBuilder) SetResourceParent

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

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

func (*CollectionBuilder) SetResourceQueryKeys

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

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

type CollectionData

type CollectionData struct {
	Resources []CollectionResource
}

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

type CollectionResource

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

	// Computed marks a computed resource: a hand-written query surface whose
	// permission checks run at decode time, where no row exists. Deploy-time
	// grant validation (access.MigrateRoles) uses it to reject conditions that
	// could never settle there.
	Computed bool

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

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

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

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

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

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

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

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

type Columns

type Columns string

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

type ComputedQueryDecoder

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

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

Computed resources execute application-written functions, so — like RPC methods — there is no library execution underneath them to carry the permission check: decode is the last library-controlled point before application code runs. QueryDecoder's deferred enforcement (discharged by QuerySet.Read/List) therefore cannot serve the computed path; this decoder checks eagerly instead, and the QuerySet it returns is a pure request carrier — checks already passed, fields already materialized.

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 accessible fields silently.

The checks are eager and decode-time-only (application code executes the query), so every decision must resolve to Granted or Denied: a Conditional decision anywhere on this path is a 500-class invariant breach — a computed resource has no library execution underneath it to evaluate a condition, and MigrateRoles rejects such grants at deploy.

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).

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

DiffElem represents the old and new values of a field that has been changed.

type DigestOption

type DigestOption func(*digestOptions)

DigestOption configures PermissionDigestHandler.

func WithFeatureGates

func WithFeatureGates(gates FeatureGates, features *FeatureSet) DigestOption

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

func WithFormerNames

func WithFormerNames(names FormerNames) DigestOption

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

type DomainBindingData

type DomainBindingData struct {
	Column string
	Path   []BindingHop
}

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

type DomainRoster

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

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

type ExecuteGate

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

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

func (*ExecuteGate) Caller

func (g *ExecuteGate) Caller() *Caller

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

func (*ExecuteGate) Enforce

func (g *ExecuteGate) Enforce(ctx context.Context, txn ReadWriteTransaction, target ExecuteTarget, pkValue 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.

func (*ExecuteGate) VerifyTenancy

func (g *ExecuteGate) VerifyTenancy(ctx context.Context, txn ReadWriteTransaction, target ExecuteTarget, pkValue 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).
	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

	// PKColumn is the primary-key column the check-SELECT locates the row by.
	PKColumn string
}

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](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](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, and a Conditional decision there is the invariant breach the computed decoder names: MigrateRoles refuses a row-referencing condition on a computed 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. 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.

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) 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, where no row exists. 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) 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) 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 InvitationRow

type InvitationRow[A UserAuth] struct {
	ID        impulse.UUID `json:"id"        spanner:"Id"`
	Email     string       `json:"email"     spanner:"Email"`
	Roles     []string     `json:"roles"     spanner:"Roles"`
	InvitedBy *string      `json:"invitedBy" spanner:"InvitedBy"`
	CreatedAt time.Time    `json:"createdAt" spanner:"CreatedAt"`
	ExpiresAt time.Time    `json:"expiresAt" spanner:"ExpiresAt"`
}

InvitationRow is one standing invitation of the global partition (<Auth>Invitations): an address invited to hold roles globally or in every tenant, until it is accepted, revoked or expires. InvitedBy is the username of the user who sent it, nil when unknown or gone.

func (InvitationRow[A]) DefaultConfig

func (InvitationRow[A]) DefaultConfig() Config

DefaultConfig tracks nothing: the rows are composed, not stored.

func (InvitationRow[A]) Resource

func (InvitationRow[A]) Resource() accesstypes.Resource

Resource is the Auth's name for the resource.

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 MemUserStore

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

MemUserStore is an in-memory account and seat store: a UserAccounts and a UserSeats over maps, for a test harness that builds a user-management surface (NewUserSurface) with no session database and no permission engine behind it. The generated authorization matrix needs one for every Auth the router binds, since the surface's handlers are mounted with the rest. It is safe for concurrent use.

func NewMemUserStore

func NewMemUserStore() *MemUserStore

NewMemUserStore returns an empty store.

func (*MemUserStore) AddUser

func (s *MemUserStore) AddUser(username string, withPassword bool) impulse.UUID

AddUser adds an account under the username, with a password the person has already changed when withPassword is set, and returns its id.

func (*MemUserStore) AddUserRoles

func (s *MemUserStore) AddUserRoles(_ context.Context, scope accesstypes.PolicyScope, user accesstypes.User, roles ...accesstypes.Role) error

AddUserRoles seats the user in the roles in the scope; a role that does not exist there is an error, as a permission engine's is.

func (*MemUserStore) CreateUser

func (s *MemUserStore) CreateUser(_ context.Context, username string, password, email *string, disabled bool) (impulse.UUID, error)

CreateUser adds an account; a password given marks it for the forced change, as the session library does, and an email given is held unverified. A username or an address in use is a Conflict.

func (*MemUserStore) DeclareRoles

func (s *MemUserStore) DeclareRoles(scope accesstypes.PolicyScope, roles ...access.RoleInfo)

DeclareRoles makes the roles exist in the scope, each with what it is for, as a role file's roles exist in a permission engine's; the surface serves the description beside the role's name. A role declared again takes the new description.

func (*MemUserStore) DeleteUser

func (s *MemUserStore) DeleteUser(_ context.Context, id impulse.UUID) error

DeleteUser removes the account and its identities.

func (*MemUserStore) DeleteUserRoles

func (s *MemUserStore) DeleteUserRoles(_ context.Context, scope accesstypes.PolicyScope, user accesstypes.User, roles ...accesstypes.Role) error

DeleteUserRoles unseats the user from the roles in the scope.

func (*MemUserStore) Identities

func (s *MemUserStore) Identities(_ context.Context, id impulse.UUID) ([]UserIdentity, error)

Identities lists the account's identities.

func (*MemUserStore) Invitations

func (s *MemUserStore) Invitations(context.Context) ([]UserInvitation, error)

Invitations lists the invitations that stand, in the order they were made.

func (*MemUserStore) Invite

Invite stores an invitation that stands for a week; nothing is mailed.

func (*MemUserStore) LinkIdentity

func (s *MemUserStore) LinkIdentity(id impulse.UUID, identity *UserIdentity)

LinkIdentity records an identity on the account, for a test that unlinks one.

func (*MemUserStore) RenameUser

func (s *MemUserStore) RenameUser(_ context.Context, id impulse.UUID, username string) error

RenameUser changes the account's username.

func (*MemUserStore) ResetUserFactors

func (s *MemUserStore) ResetUserFactors(_ context.Context, id impulse.UUID) error

ResetUserFactors has nothing to forget: the store keeps no remembered browsers.

func (*MemUserStore) ResetUserPassword

func (s *MemUserStore) ResetUserPassword(_ context.Context, id impulse.UUID, _ string) error

ResetUserPassword marks the account for the forced change.

func (*MemUserStore) RevokeInvitation

func (s *MemUserStore) RevokeInvitation(_ context.Context, id impulse.UUID) error

RevokeInvitation withdraws an invitation; NotFound where none stands under the id.

func (*MemUserStore) RoleUsers

RoleUsers lists the users seated in the role in the scope, sorted.

func (*MemUserStore) Roles

Roles lists the roles that exist in the scope, sorted by name, each with what it is for: the ones declared there and, for one domain, the ones declared in every domain under a name the domain does not hold.

func (*MemUserStore) Seat

func (s *MemUserStore) Seat(scope accesstypes.PolicyScope, user accesstypes.User, roles ...accesstypes.Role)

Seat seats the user in the roles in the scope. A role the scope does not hold is declared by the seat, saying nothing of what it is for until DeclareRoles does.

func (*MemUserStore) SetUserDisabled

func (s *MemUserStore) SetUserDisabled(_ context.Context, id impulse.UUID, disabled bool) error

SetUserDisabled sets the account's disabled flag.

func (*MemUserStore) SetUserEmail

func (s *MemUserStore) SetUserEmail(_ context.Context, id impulse.UUID, email *string) error

SetUserEmail enters the address unverified, or removes it (nil).

func (*MemUserStore) UnlinkIdentity

func (s *MemUserStore) UnlinkIdentity(_ context.Context, identityID impulse.UUID) error

UnlinkIdentity removes the identity from whichever account holds it.

func (*MemUserStore) User

User returns one account; a NotFound error where the store holds none under the id.

func (*MemUserStore) UserRoles

UserRoles returns the user's seats by scope: every scope with none given, the given ones otherwise.

func (*MemUserStore) Users

func (s *MemUserStore) Users(context.Context) ([]UserAccount, error)

Users lists every account, ordered by username.

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.

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), and does neither when it errors.

func (*MockClient) FileStore

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

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

func (*MockClient) PostgresReadOnlyTransaction

func (c *MockClient) PostgresReadOnlyTransaction() any

PostgresReadOnlyTransaction panics because it is not implemented for the MockClient.

func (*MockClient) ReadOnlyMocks

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

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

func (*MockClient) ReadOnlyTransaction

func (c *MockClient) ReadOnlyTransaction() ReadOnlyTransactionCloser

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

func (*MockClient) SpannerReadOnlyTransaction

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

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

type MockReadWriteTransaction

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

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

func NewMockReadWriteTransaction

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

NewMockReadWriteTransaction creates a new MockReadWriteTransaction.

func (*MockReadWriteTransaction) BufferMap

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

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

func (*MockReadWriteTransaction) BufferStruct

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

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

func (*MockReadWriteTransaction) DBType

func (c *MockReadWriteTransaction) DBType() DBType

DBType returns the database type.

func (*MockReadWriteTransaction) DataChangeEventIndex

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

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

func (*MockReadWriteTransaction) PostgresReadOnlyTransaction

func (c *MockReadWriteTransaction) PostgresReadOnlyTransaction() any

PostgresReadOnlyTransaction panics because it is not implemented for the MockReadWriteTransaction.

func (*MockReadWriteTransaction) Released

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

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

func (*MockReadWriteTransaction) SpannerReadOnlyTransaction

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

SpannerReadOnlyTransaction returns a read-only transaction for the MockReadWriteTransaction.

func (*MockReadWriteTransaction) TxnReadMocks

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

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

type NamedStore

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

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

type Operation

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

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

func (*Operation) PathDepth

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).

const (
	// OperationCreate corresponds to an "add" operation.
	OperationCreate OperationType = "add"
	// OperationUpdate corresponds to a "patch" operation.
	OperationUpdate OperationType = "patch"
	// OperationDelete corresponds to a "remove" operation.
	OperationDelete OperationType = "remove"
)

type Option

type Option func(opt options) options

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

func MatchPrefix

func MatchPrefix() Option

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

func RequireCreatePath

func RequireCreatePath() Option

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

type Page

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

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

func (*Page[Resource]) Add

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

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.

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.

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

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

PatchType returns the type of the patch.

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) (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.

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.

type PatchSetComparer

type PatchSetComparer interface {
	Resource() accesstypes.Resource
	Data() map[accesstypes.Field]any
	Fields() []accesstypes.Field
	PatchType() PatchType
	PrimaryKey() KeySet
}

PatchSetComparer is an interface for comparing two PatchSet-like objects.

type PatchSetMetadata

type PatchSetMetadata interface {
	PatchType() PatchType
	PrimaryKey() KeySet
	Resource() accesstypes.Resource
}

PatchSetMetadata is an interface that all PatchSet types must implement to allow their mutations to be buffered

type PatchType

type PatchType string

PatchType defines the type of operation for a PatchSet.

const (
	// CreatePatchType indicates an insert operation.
	CreatePatchType PatchType = "CreatePatchType"
	// UpdatePatchType indicates an update operation.
	UpdatePatchType PatchType = "UpdatePatchType"
	// CreateOrUpdatePatchType indicates an insert or update operation.
	CreateOrUpdatePatchType PatchType = "CreateOrUpdatePatchType"
	// DeletePatchType indicates a delete operation.
	DeletePatchType PatchType = "DeletePatchType"
)

type PostgreSQLGenerator

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

PostgreSQLGenerator is a SQL generator for PostgreSQL.

func NewPostgreSQLGenerator

func NewPostgreSQLGenerator() *PostgreSQLGenerator

NewPostgreSQLGenerator creates a new PostgreSQLGenerator.

func (*PostgreSQLGenerator) GenerateSQL

func (g *PostgreSQLGenerator) GenerateSQL(node ExpressionNode) (sqlStr string, params map[string]any, err error)

GenerateSQL generates SQL for the given node.

type PostgresClient

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

PostgresClient is a wrapper around the database.

func NewPostgresClient

func NewPostgresClient(db *pgxpool.Pool, opts ...ClientOption) *PostgresClient

NewPostgresClient creates a new Client. WithFileStore and WithNamedFileStore hand it the stores the generated handlers read off it, the options the Spanner client takes; a store wired twice, or two stores on one location, panics here.

func (*PostgresClient) Close

func (c *PostgresClient) Close()

Close closes the database connection.

func (*PostgresClient) DBType

func (c *PostgresClient) DBType() DBType

DBType returns the database type.

func (*PostgresClient) ExecuteFunc

func (c *PostgresClient) ExecuteFunc(_ context.Context, _ func(ctx context.Context, _ ReadWriteTransaction) error) error

ExecuteFunc executes a function within a read-write transaction.

func (*PostgresClient) FileStore

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

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

func (*PostgresClient) PostgresReadOnlyTransaction

func (c *PostgresClient) PostgresReadOnlyTransaction() any

PostgresReadOnlyTransaction panics because it is not implemented for the PostgresClient.

func (*PostgresClient) ReadOnlyTransaction

func (c *PostgresClient) ReadOnlyTransaction() ReadOnlyTransactionCloser

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

func (*PostgresClient) SpannerReadOnlyTransaction

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

SpannerReadOnlyTransaction panics because it is not implemented for the PostgresClient.

type PostgresReadOnlyTransaction

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

PostgresReadOnlyTransaction represents a database transaction that can only be used for reads.

func (*PostgresReadOnlyTransaction) Close

func (c *PostgresReadOnlyTransaction) Close()

Close closes the readonly transaction

func (*PostgresReadOnlyTransaction) PostgresReadOnlyTransaction

func (c *PostgresReadOnlyTransaction) PostgresReadOnlyTransaction() any

PostgresReadOnlyTransaction returns a read-only transaction for the Postgres client.

func (*PostgresReadOnlyTransaction) SpannerReadOnlyTransaction

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

SpannerReadOnlyTransaction panics because it is not implemented for the PostgresReadOnlyTransaction.

type PostgresReadWriteTransaction

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

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

func (*PostgresReadWriteTransaction) BufferMap

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.

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

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

func (q *QuerySet[Resource]) Collect(rows iter.Seq2[*Resource, error]) (*Page[Resource], error)

Collect runs a computed List function's rows through 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: filter, then count, then sort, then page, because any other order gives a different answer. 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]) 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, and no count was asked for (a total needs every row). 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]) 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 ResetUserFactorsRequest

type ResetUserFactorsRequest struct {
	User impulse.UUID `json:"user"`
}

ResetUserFactorsRequest is the body of Reset<Auth>UserFactors: the user whose remembered browsers are forgotten.

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 RoleRow

type RoleRow[A UserAuth] struct {
	Name        string `json:"name"        spanner:"Name"`
	Kind        string `json:"kind"        spanner:"Kind"`
	Description string `json:"description" spanner:"Description"`
}

RoleRow is one role a global seat may take (<Auth>Roles): a role of the global kind, held in the global scope, or of the domain kind, held in every tenant. Description is what the role is for, the role file's sentence or two about it.

func (RoleRow[A]) DefaultConfig

func (RoleRow[A]) DefaultConfig() Config

DefaultConfig tracks nothing: the rows are composed, not stored.

func (RoleRow[A]) Resource

func (RoleRow[A]) Resource() accesstypes.Resource

Resource is the Auth's name for the resource.

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.

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 SeatRow

type SeatRow[A UserAuth] struct {
	User        impulse.UUID `json:"user"        spanner:"User"`
	Role        string       `json:"role"        spanner:"Role"`
	Username    string       `json:"username"    spanner:"Username"`
	EveryDomain bool         `json:"everyDomain" spanner:"EveryDomain"`
}

SeatRow is one seat of the global partition (<Auth>Seats): a user holding a role globally, or in every tenant when the role is of the tenant kind (EveryDomain).

func (SeatRow[A]) DefaultConfig

func (SeatRow[A]) DefaultConfig() Config

DefaultConfig tracks nothing: the rows are composed, not stored.

func (SeatRow[A]) Resource

func (SeatRow[A]) Resource() accesstypes.Resource

Resource is the Auth's name for the resource.

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 SetUserPasswordRequest

type SetUserPasswordRequest struct {
	User     impulse.UUID `json:"user"`
	Password string       `json:"password"`
}

SetUserPasswordRequest is the body of Set<Auth>UserPassword: the user and the temporary password an operator chose, which the user changes at their next sign-in.

type SignalKind

type SignalKind string

SignalKind names one kind of shared state an application's instances signal each other about: a signal carries nothing but the fact that something of the kind changed, and every instance subscribed to the kind rereads what it keeps of it. The live service carries the signals (live.Signaler and live.Subscriber over one signals document per application, a field per kind), and the kinds are declared here, in the package the live package imports, so the live package, the access adapter and the tenant roster all name one type without an import cycle; the live package re-exports it as live.Kind with the same constants.

const (
	// KindFeatures is a feature flag flip: every FeatureSet following it rereads the
	// FeatureFlags table.
	KindFeatures SignalKind = "features"
	// KindTenants is a change of the tenant roster: an instance holding the roster
	// rereads it.
	KindTenants SignalKind = "tenants"
	// KindPolicy is a change of the permission policy (roles, grants, memberships): an
	// instance holding a policy snapshot rereads it.
	KindPolicy SignalKind = "policy"
)

The kinds.

type SignalSubscriber

type SignalSubscriber interface {
	Subscribe(kind SignalKind, onSignal func()) (stop func(), err error)
}

SignalSubscriber delivers the signals of a kind: what a FeatureSet follows. onSignal runs on every signal of the kind after the subscription began, on the subscriber's goroutine, so it must return quickly; stop ends the subscription. The live service implements it (live.Subscriber).

type Signaler

type Signaler interface {
	Signal(ctx context.Context, kind SignalKind) error
}

Signaler signals every instance of the application that a kind of shared state changed: what a flip signals through. The live service implements it (live.Signaler); a failure is the caller's to log and never fails the request, since every subscriber also rereads at its own backstop.

type SortDirection

type SortDirection string

SortDirection defines the sort direction for a field.

const (
	// SortAscending specifies sorting in ascending order.
	SortAscending SortDirection = "asc"
	// SortDescending specifies sorting in descending order.
	SortDescending SortDirection = "desc"
)

type SortField

type SortField struct {
	Field     string
	Direction SortDirection
}

SortField represents a field to sort by, including the field name and sort direction.

type SpannerClient

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

SpannerClient is a wrapper around the database.

func NewSpannerClient

func NewSpannerClient(db *spanner.Client, opts ...ClientOption) *SpannerClient

NewSpannerClient creates a new Client. WithFileStore and WithNamedFileStore hand it the stores the frames drive and a committed transaction's released file objects are deleted from; a store wired twice, or two stores on one location, panics here.

func (*SpannerClient) DBType

func (c *SpannerClient) DBType() DBType

DBType returns the database type.

func (*SpannerClient) ExecuteFunc

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

ExecuteFunc executes a function within a read-write transaction. A commit Spanner refuses for a reason the caller can act on (a referential refusal, a duplicate key or unique value, a violated CHECK constraint, an update of a row that does not exist) answers as a 4xx whose message is composed from the patches the transaction buffered (see translateCommitError); an error the function itself returns, and a commit refused with any other code, pass through unchanged.

Before the commit, a transaction whose patches release a file object of a store the client holds no store for is refused naming the store: the rows would go and the object would stay with nothing to delete it. Once the commit lands, the file objects the transaction's patches released (a deleted row's @file keys, the old key of a row pointed at another object) are deleted from their stores, synchronously, before ExecuteFunc returns, detached from the request's cancellation; a failed delete is logged naming the keys and the call still returns nil, since the rows are gone. A transaction that does not commit, for any reason, releases nothing.

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.

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) DBType

func (c *SpannerReadWriteTransaction) DBType() DBType

DBType returns the database type.

func (*SpannerReadWriteTransaction) DataChangeEventIndex

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

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

func (*SpannerReadWriteTransaction) PostgresReadOnlyTransaction

func (c *SpannerReadWriteTransaction) PostgresReadOnlyTransaction() any

PostgresReadOnlyTransaction panics because it is not implemented for the SpannerReadWriteTransaction.

func (*SpannerReadWriteTransaction) Released

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

Released returns the file objects the transaction's patches released so far, each with its store: a deleted row's @file keys, and the old key of a row pointed at another object. Under ExecuteFunc the executor deletes them from the client's stores after the commit; a transaction committed outside it leaves that to its caller.

func (*SpannerReadWriteTransaction) SpannerReadOnlyTransaction

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

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

type Statement

type Statement struct {
	SQL    string
	Params map[string]any
	// contains filtered or unexported fields
}

Statement is a generic container for a SQL statement and its parameters, supporting both Spanner and PostgreSQL.

func (*Statement) SpannerStatement

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
}

SubjectBindingData is one entry of the subject-side vocabulary (subject.<name>), anchored on the declaring resource's user-id column. UserColumn correlates rows to the requester; Column is the local column the set or value yields — the terminal when Path is empty, or the foreign key a dotted value: continues through. Type is the comparison type of the column the set or value yields (the terminal of a dotted value), derived by generation from that column's Go type exactly as an attribute's is; deploy validation admits a grant only where it compares or tests the entry against an attribute of the same type.

type Surface

type Surface struct {
	// Prefix is the path as mounted: a prefix such as /beacons/ or /droids/, or a route
	// pattern such as /api/widgets/{id}/content, where a segment in braces stands for any
	// one segment; / is the application default.
	Prefix string `json:"prefix"`
	// Kind says how the router matches the prefix against a request's path:
	// SurfacePrefix by prefix, so everything under /beacons/ is the surface's, or
	// SurfaceRoute to the end of the path, so /api/widgets/{id}/content is the surface's
	// and /api/widgets/{id}/content-extra is not. The application default, an outlet and
	// a hand-mounted prefix are prefixes; an annotated method's route (@rpc, @file,
	// @schedule) is a route. A file written before the surfaces carried their kind reads
	// as prefixes throughout.
	Kind SurfaceKind `json:"kind"`
	// Log is the request log word: RequestLogAlways, RequestLogOnEvent, RequestLogSampled
	// or RequestLogNever; empty when the surface declares its trace setting alone.
	Log string `json:"log,omitempty"`
	// Fraction is the share of the quiet requests a sampled surface writes the entry for,
	// above 0 and at most 1; set with RequestLogSampled alone.
	Fraction float64 `json:"fraction,omitempty"`
	// Traces is the trace setting: TracesFollowFrontEnd, TracesCapped or TracesOff; empty
	// when the surface declares its request log word alone.
	Traces string `json:"traces,omitempty"`
	// Rate is the share of the front end's traces a capped surface keeps, above 0 and at
	// most 1; set with TracesCapped alone.
	Rate float64 `json:"rate,omitempty"`
}

Surface is one declared surface in the release file: a path prefix or a route pattern as the router mounts it, with the request log word, the trace setting, or both.

type SurfaceKind

type SurfaceKind string

SurfaceKind is how the router matches a surface's prefix against a request's path, as the release file spells it.

const (
	// SurfacePrefix is a path prefix, matched by strings.HasPrefix as the router does: the
	// application default at /, an outlet's prefix, or a prefix mounted by hand.
	SurfacePrefix SurfaceKind = "prefix"
	// SurfaceRoute is a route pattern, matched whole as the router does: an annotated
	// method's path, a parameter in braces standing for one segment.
	SurfaceRoute SurfaceKind = "route"
)

The surface kinds: a prefix is matched against the start of the path and a route to its end.

type TagData

type TagData struct {
	Name        accesstypes.Tag
	Permissions []accesstypes.Permission
	// Masking is how the field's masked cells meet a sort or a filter; empty
	// is MaskingConcealing, the default.
	Masking Masking
	// Formerly is the field's former wire name (@formerly on the field): the name
	// older browser applications still send and read, which the decoders accept, every
	// row carries beside Name and the permission digest mirrors with Name's states.
	// Empty for a field never renamed.
	Formerly accesstypes.Tag
}

TagData describes one field-level tag registration. An empty Permissions slice records a tag that is registered without requiring any permission.

type TargetedMethod

type TargetedMethod struct {
	Method     accesstypes.Resource
	Target     accesstypes.Resource
	Transition *TransitionData
}

TargetedMethod pairs an RPC method resource with the row resource its @target field addresses; Transition carries the declared edge when the method is a transition, nil for the plain located-row form.

type TargetedRPCDecoder

type TargetedRPCDecoder[Request any] struct {
	// contains filtered or unexported fields
}

TargetedRPCDecoder decodes an HTTP request for a @target-bearing RPC method. Unlike RPCDecoder, a Conditional Execute decision here is not an invariant breach: the generated handler has a located row to evaluate it against, so Decode carries the condition forward as an ExecuteGate.

func MustNewTargetedRPCDecoder

func MustNewTargetedRPCDecoder[Request any](a DecoderAccessor, collection *GeneratedCollection, methodName accesstypes.Resource, perm accesstypes.Permission) *TargetedRPCDecoder[Request]

MustNewTargetedRPCDecoder builds a decoder for a @target-bearing RPC method request, wired to the generated collection so a carried condition can lower against the target resource's bindings. It panics on construction errors: they are programming errors (a malformed request struct), surfaced at application startup where generated handlers construct their decoders.

func (*TargetedRPCDecoder[Request]) Decode

func (s *TargetedRPCDecoder[Request]) Decode(request *http.Request, scope accesstypes.Scope) (*Request, *ExecuteGate, error)

Decode decodes the HTTP request body into the Request struct and checks the caller's Execute permission in the given scope. Denied is Forbidden here; Granted and Conditional both admit — a Conditional decision's payload rides the returned ExecuteGate, which the generated frame enforces against the located target row inside its transaction.

func (*TargetedRPCDecoder[Request]) WithValidator

func (s *TargetedRPCDecoder[Request]) WithValidator(v ValidatorFunc) *TargetedRPCDecoder[Request]

WithValidator sets a validator function on the decoder.

type TenantDeclarationColumns

type TenantDeclarationColumns struct {
	// DirectoryOnly is the tenant record's BOOL column saying the tenant's people enter
	// through its directories only, so a password does not reach it; empty when the
	// record declares none, and every tenant admits a password.
	DirectoryOnly string
	// DirectoriesTable is the directories record's table, one row per directory a tenant
	// admits its people through: TenantColumn holds the tenant's key, MethodColumn the
	// sign-in method as sessioninfo.AuthMethod spells it (google, azure, workos) and
	// ConnectionColumn the connection the method's identities carry (a Google Workspace
	// by its domain, a Microsoft Entra tenant by its tenant id).
	DirectoriesTable string
	TenantColumn     string
	MethodColumn     string
	ConnectionColumn string
	// DefaultSeatColumn is the directories record's column naming the role a person the
	// directory vouches for is seated with in the tenant at their first sign-in, NULL or
	// empty for none (the tenant admits its people through that directory by invitation
	// only); empty when the record carries no such column, and every directory admits
	// by invitation only. Read by the sign-in's directory reader
	// (NewTenantDirectoryReader), never by the roster.
	DefaultSeatColumn string
}

TenantDeclarationColumns names where the tenant record keeps its declaration of who may enter it (signin.TenantDeclaration), so the roster reads the declaration beside the keys and the sign-in policy reads it in its own transaction (NewTenantDeclarationReader): the record's directory-only column, and the directories record's table with its tenant, method and connection columns. The generated New<Record>Roster and New<Record>DeclarationReader constructors supply them from the @directoryOnly and @tenantDirectory declarations; an application names none of them.

type TenantDeclarations

type TenantDeclarations func(ctx context.Context, domain accesstypes.Domain) (*signin.TenantDeclaration, error)

TenantDeclarations reads what a tenant declares about who may enter it: the tenant's declaration (signin.TenantDeclaration) by domain, as the application keeps it, which SessionPermissions applies to each tenant the session holds a grant in. It answers nil for a tenant that declares nothing, which admits a password and refuses a sign-in through a directory, as the sign-in policy does (signin.TenantPolicy). An application that keeps no declarations passes nil to SessionPermissions, and every tenant admits every session.

type TenantInvitationRow

type TenantInvitationRow[A UserAuth] struct {
	ID        impulse.UUID `json:"id"        spanner:"Id"`
	Email     string       `json:"email"     spanner:"Email"`
	Roles     []string     `json:"roles"     spanner:"Roles"`
	InvitedBy *string      `json:"invitedBy" spanner:"InvitedBy"`
	CreatedAt time.Time    `json:"createdAt" spanner:"CreatedAt"`
	ExpiresAt time.Time    `json:"expiresAt" spanner:"ExpiresAt"`
}

TenantInvitationRow is one standing invitation of the tenant partition (<Auth><Tenant>Invitations): an address invited to hold roles in the tenant.

func (TenantInvitationRow[A]) DefaultConfig

func (TenantInvitationRow[A]) DefaultConfig() Config

DefaultConfig tracks nothing: the rows are composed, not stored.

func (TenantInvitationRow[A]) Resource

Resource is the Auth's name for the resource.

type TenantRoleRow

type TenantRoleRow[A UserAuth] struct {
	Name        string `json:"name"        spanner:"Name"`
	Description string `json:"description" spanner:"Description"`
}

TenantRoleRow is one role a tenant seat may take (<Auth><Tenant>Roles). Description is what the role is for, the role file's sentence or two about it.

func (TenantRoleRow[A]) DefaultConfig

func (TenantRoleRow[A]) DefaultConfig() Config

DefaultConfig tracks nothing: the rows are composed, not stored.

func (TenantRoleRow[A]) Resource

func (TenantRoleRow[A]) Resource() accesstypes.Resource

Resource is the Auth's name for the resource.

type TenantRoster

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

TenantRoster is one instance's copy of the tenant record's keys: the set of tenants the application serves, which the generated DomainGuard and the consolidated dispatcher ask before a tenant-scoped request runs. Start reads the set once and then keeps it current until the context ends: on every tenants signal the channel delivers and at the backstop interval regardless. The generated write paths of the tenant record call Add and Remove after their commit, so the instance that wrote a tenant serves it at once, and signal the tenants kind so every other instance reloads.

With WithTenantDeclarations the copy carries what each tenant declares about who may enter it beside its key, read in the same snapshot, and Declarations answers the generated DomainGuard's and the session's tenant list's question from it (TenantDeclarations) with no read and no wait; the generated write paths of the tenant record and of the directories record call Reload after their commit, so a declaration changed on this instance decides the next request here, and signal the tenants kind so every other instance reloads.

The set sits behind an atomic pointer, so Has never waits on a reload or a writer and performs no read: a domain the set does not hold is unknown, whatever the table says at that moment. A nil roster holds no tenant, so an application that wires none fails closed on every tenant-scoped route. It is safe for concurrent use.

func NewTenantRoster

func NewTenantRoster(client Client, table, keyColumn string, opts ...TenantRosterOption) *TenantRoster

NewTenantRoster builds the roster over the tenant record's table, reading the key column into the set. The generated New<Record>Roster constructor supplies the table and the column from the @tenant declaration; an application calls that one. Nothing is read until Start.

func (*TenantRoster) Add

func (r *TenantRoster) Add(domain accesstypes.Domain)

Add puts the domain in the set at once, declaring nothing: what a test harness calls to hold a tenant the schema has no row for. The generated write paths call Reload instead, so the tenant's declaration comes with it. A nil roster takes nothing.

func (*TenantRoster) Declarations

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) Reload

func (r *TenantRoster) Reload(ctx context.Context) error

Reload rereads the table, the declarations with it, and replaces the set whole: what the tenant record's and the directories record's generated write paths call after their commit, so the instance that wrote serves the change at its next request, and what Start calls on every tenants signal and backstop tick. A failed read leaves the set as it was. A nil roster reads nothing.

func (*TenantRoster) Remove

func (r *TenantRoster) Remove(domain accesstypes.Domain)

Remove drops the domain from the set at once. A nil roster drops nothing.

func (*TenantRoster) Start

func (r *TenantRoster) Start(ctx context.Context) error

Start loads the set once, failing when the read fails, so an application never starts serving on an empty roster it could not fill, and then keeps it current until ctx ends: a goroutine rereads the table on every tenants signal (when a channel is wired) and at the backstop interval regardless. A failed reread is logged and the copy stays as it was until the next.

type TenantRosterOption

type TenantRosterOption func(*TenantRoster)

TenantRosterOption configures a TenantRoster at construction.

func WithTenantBackstop

func WithTenantBackstop(d time.Duration) TenantRosterOption

WithTenantBackstop sets how often Start rereads the table without a signal; TenantBackstop by default. Tests shorten it.

func WithTenantDeclarations

func WithTenantDeclarations(columns *TenantDeclarationColumns) TenantRosterOption

WithTenantDeclarations has the roster read what each tenant declares about who may enter it beside its key: the columns the generated New<Record>Roster constructor supplies from the @directoryOnly and @tenantDirectory declarations. Without it every tenant's declaration is nil, which declares nothing.

func WithTenantSignals

func WithTenantSignals(s TenantSignals) TenantRosterOption

WithTenantSignals wires the application's signal channel: Start subscribes the roster to the tenants kind on it, so a tenant another instance wrote reaches this one within a moment instead of at the backstop. Without it the backstop alone keeps the copy current.

type TenantSeatRow

type TenantSeatRow[A UserAuth] struct {
	User       impulse.UUID `json:"user"       spanner:"User"`
	Role       string       `json:"role"       spanner:"Role"`
	Username   string       `json:"username"   spanner:"Username"`
	Everywhere bool         `json:"everywhere" spanner:"Everywhere"`
}

TenantSeatRow is one seat of the tenant partition (<Auth><Tenant>Seats): a user holding a role in the tenant, or everywhere (Everywhere), which the tenant partition shows and never writes.

func (TenantSeatRow[A]) DefaultConfig

func (TenantSeatRow[A]) DefaultConfig() Config

DefaultConfig tracks nothing: the rows are composed, not stored.

func (TenantSeatRow[A]) Resource

func (TenantSeatRow[A]) Resource() accesstypes.Resource

Resource is the Auth's name for the resource.

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 TenantUserRow

type TenantUserRow[A UserAuth] struct {
	ID                     impulse.UUID `json:"id"                     spanner:"Id"`
	Username               string       `json:"username"               spanner:"Username"`
	Disabled               bool         `json:"disabled"               spanner:"Disabled"`
	HasPassword            bool         `json:"hasPassword"            spanner:"HasPassword"`
	PasswordChangeRequired bool         `json:"passwordChangeRequired" spanner:"PasswordChangeRequired"`
	CreatedAt              time.Time    `json:"createdAt"              spanner:"CreatedAt"`
	LastSignInAt           *time.Time   `json:"lastSignInAt"           spanner:"LastSignInAt"`
	Organization           *string      `json:"organization"           spanner:"Organization"`
	// Email is the person's address, nil for none, and EmailVerifiedAt when the person
	// proved it by following a link sent to it (nil while it is an operator's entry).
	Email           *string        `json:"email"           spanner:"Email"`
	EmailVerifiedAt *time.Time     `json:"emailVerifiedAt" spanner:"EmailVerifiedAt"`
	Identities      []UserIdentity `json:"identities"      spanner:"Identities"`
	Roles           []string       `json:"roles"           spanner:"Roles"`
	EverywhereRoles []string       `json:"everywhereRoles" spanner:"EverywhereRoles"`
	RolesSynced     bool           `json:"rolesSynced"     spanner:"RolesSynced"`
}

TenantUserRow is one user of the tenant partition (<Auth><Tenant>Users): a user seated in the tenant or everywhere, with the seats held there.

func (TenantUserRow[A]) DefaultConfig

func (TenantUserRow[A]) DefaultConfig() Config

DefaultConfig tracks nothing: the rows are composed, not stored.

func (TenantUserRow[A]) Resource

func (TenantUserRow[A]) Resource() accesstypes.Resource

Resource is the Auth's name for the resource.

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 UnlinkUserIdentityRequest

type UnlinkUserIdentityRequest struct {
	User     impulse.UUID `json:"user"`
	Identity impulse.UUID `json:"identity"`
}

UnlinkUserIdentityRequest is the body of Unlink<Auth>UserIdentity: the user and the identity to unlink from them.

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 UserAccount

type UserAccount struct {
	ID       impulse.UUID
	Username string
	// HasPassword reports a password on the account; PasswordChangeRequired that the
	// password is one an operator set, which the person changes before anything else
	// is served.
	HasPassword            bool
	PasswordChangeRequired bool
	Disabled               bool
	CreatedAt              time.Time
	LastSignInAt           *time.Time
	// Email is the person's address, nil for none, and EmailVerifiedAt when the person
	// proved it by following a link sent to it, nil while it is an operator's entry
	// (the session library's two states: verified before trusted).
	Email           *string
	EmailVerifiedAt *time.Time
}

UserAccount is one user as the Auth's account store holds it.

type UserAccounts

type UserAccounts interface {
	// Users lists every account, ordered by username.
	Users(ctx context.Context) ([]UserAccount, error)
	User(ctx context.Context, id impulse.UUID) (*UserAccount, error)
	// CreateUser adds an account; a password given is one an operator set, so the
	// account carries the forced-change mark. Nil creates a password-less account that
	// signs in through a registration. An email given is an operator's entry of the
	// person's address, unverified, which reserves the address; nil enters none.
	CreateUser(ctx context.Context, username string, password, email *string, disabled bool) (impulse.UUID, error)
	RenameUser(ctx context.Context, id impulse.UUID, username string) error
	// SetUserEmail is an operator's entry of the person's address, unverified, or its
	// removal (nil). Refused (Conflict) where the username is the address.
	SetUserEmail(ctx context.Context, id impulse.UUID, email *string) error
	// Invite stores an invitation and mails its link; the invitation is returned as
	// stored. Invitations lists the ones that stand, and RevokeInvitation withdraws one
	// (NotFound when it no longer stands).
	Invite(ctx context.Context, req *UserInvitationRequest) (*UserInvitation, error)
	Invitations(ctx context.Context) ([]UserInvitation, error)
	RevokeInvitation(ctx context.Context, id impulse.UUID) error
	SetUserDisabled(ctx context.Context, id impulse.UUID, disabled bool) error
	// DeleteUser removes the account with its identities and sessions.
	DeleteUser(ctx context.Context, id impulse.UUID) error
	// ResetUserPassword sets a temporary password an operator chose: the account
	// takes the forced-change mark and its sessions end.
	ResetUserPassword(ctx context.Context, id impulse.UUID, temporary string) error
	// ResetUserFactors forgets every browser the person asked to be remembered after
	// a second factor, so their next sign-in from any of them asks for the factor
	// again (session.AuthAPI.ResetFactors).
	ResetUserFactors(ctx context.Context, id impulse.UUID) error
	Identities(ctx context.Context, id impulse.UUID) ([]UserIdentity, error)
	UnlinkIdentity(ctx context.Context, identityID impulse.UUID) error
}

UserAccounts is the account store the surface serves: the session library's users, identities and passwords of one Auth, as sessionusers.Accounts adapts them. A user the store does not hold answers an error httpio.HasNotFound reports.

type UserApp

type UserApp interface {
	DecoderAccessor
	CursorKey() *CursorKey
	ResourceClient() Client
}

UserApp is the application surface the user handlers draw on: the decoder seam, the cursor key the lists page with, and the database client, whose type decides where a sort places NULL.

type UserAuth

type UserAuth interface {
	UserSurfaceDeclaration() UserSurfaceDeclaration
}

UserAuth marks one Auth whose users the library manages. The generated router package declares a type per Auth whose method returns the declaration the generator derived from the Auth's methods; the surface, its rows and its handlers are instantiated with that type, so each Auth's resources are distinct Go types carrying their own names into the collection.

type UserIdentity

type UserIdentity struct {
	ID impulse.UUID `json:"id"`
	// Method is the method's kind (google, azure, workos). Connection and Subject are the
	// link's key: the connection is the directory the identity came from as the session
	// library keys it (a Google Workspace by the registration's name for it or its domain,
	// a Microsoft tenant by its id, a WorkOS connection by its id), and the subject is the
	// directory's identifier for the person. Neither is a name a person knows; a page
	// names the identity by its method and organization. The registration the identity
	// signed in through is not recorded on the link.
	Method     string `json:"method"`
	Connection string `json:"connection"`
	Subject    string `json:"subject"`
	// Organization is the tenant key the registration stored on the link: the Google
	// Workspace, the Entra tenant, the WorkOS organization; nil where it stored none.
	Organization *string `json:"organization"`
	// Email is the address the directory asserted when the identity was linked.
	Email      *string   `json:"email"`
	LinkedAt   time.Time `json:"linkedAt"`
	LastUsedAt time.Time `json:"lastUsedAt"`
}

UserIdentity is one external identity linked to a user: the way they sign in through a registration. It is a field of the user row, so its wire shape is fixed here.

type UserInvitation

type UserInvitation struct {
	ID    impulse.UUID
	Email string
	// Tenant is the tenant the invitation seats the person in, "" for the global
	// partition.
	Tenant string
	// Roles are the roles the acceptance grants.
	Roles []string
	// InvitedBy is the user who sent it, null when unknown.
	InvitedBy impulse.NullUUID
	CreatedAt time.Time
	ExpiresAt time.Time
}

UserInvitation is one standing invitation as the Auth's account store holds it: an address invited to hold roles, in a tenant or on the global surface, until it is accepted, revoked or expires.

type UserInvitationRequest

type UserInvitationRequest struct {
	Email     string
	Tenant    string
	Roles     []string
	InvitedBy impulse.NullUUID
}

UserInvitationRequest is what the surface asks the account store to invite: the address, the tenant ("" for the global partition), the roles, and the caller.

type UserPartitionNames

type UserPartitionNames struct {
	Tenanted bool

	Users, Seats, Roles, Invitations, SetPassword, UnlinkIdentity, ResetFactors accesstypes.Resource

	UsersRoute, SeatsRoute, RolesRoute, InvitationsRoute, SetPasswordRoute, UnlinkIdentityRoute, ResetFactorsRoute string

	// UserParam is the users read route's parameter (crewUserID), SeatUserParam and
	// SeatRoleParam the seats read route's, RoleParam the roles read route's,
	// InvitationParam the invitations read route's.
	UserParam, SeatUserParam, SeatRoleParam, RoleParam, InvitationParam httpio.ParamType
}

UserPartitionNames are one partition's names: its four resources and three methods, the route segments they are served at under the outlet's prefix (and, tenanted, the domain segment), and the parameters of their read routes.

func (*UserPartitionNames) Methods

func (n *UserPartitionNames) Methods() []accesstypes.Resource

Methods lists the partition's methods, which target its users resource.

func (*UserPartitionNames) Resources

func (n *UserPartitionNames) Resources() []accesstypes.Resource

Resources lists the partition's resources and methods, the names a role file grants.

func (*UserPartitionNames) ServedMethods

func (n *UserPartitionNames) ServedMethods(shape UserSurfaceShape) []accesstypes.Resource

ServedMethods lists the methods the shape serves in the partition: the password reset where the Auth has a password method, the unlinking where it has registrations to link identities through, and the second-factor reset on every Auth, since a person signs in with one whichever way they sign in.

type UserPermissionChecker

type UserPermissionChecker interface {
	// Check returns the Decision for perm on each of resources within scope.
	//
	// env is the request's decision context, sampled once at decode; the check
	// folds environment-referencing conditions against it and fails loudly
	// (error, never a silent allow or deny) when a referenced attribute is
	// absent.
	//
	// The returned Decisions must carry an entry for every resource passed. A
	// resource absent from the map reads as the zero Decision — Denied — so a
	// short implementation fails closed, never open. Implementations must not
	// short-circuit on the first denial.
	//
	// Snapshot pinning: a single Check call must evaluate every resource against one
	// consistent authorization snapshot — a concurrent grant or revocation must affect
	// all of the call's results or none of them. Distinct calls may observe different
	// snapshots; callers must not assume pinning across calls.
	Check(ctx context.Context, env accesstypes.Environment, scope accesstypes.Scope, perm accesstypes.Permission, resources ...accesstypes.Resource) (accesstypes.Decisions, error)

	// PermissionDigest returns the user's structural grant enumeration within
	// scope — the payload the generated permission-digest endpoint serves.
	// Advisory UI material only, never consulted for enforcement: denied
	// targets are absent (fail closed) and nothing folds, so a payload is
	// stable for the life of a policy snapshot.
	PermissionDigest(ctx context.Context, scope accesstypes.Scope) (accesstypes.PermissionDigest, error)

	// HasGrants reports whether the user holds at least one grant in scope —
	// the foothold concealed tenancy's visibility check asks, and the
	// predicate the tenant picker filters the application's roster by. A
	// membership that resolves to no grants is not a foothold; a membership
	// held in every tenant domain is a foothold in each.
	HasGrants(ctx context.Context, scope accesstypes.Scope) (bool, error)

	User() accesstypes.User
}

UserPermissionChecker is what an application's per-request accessor for a user principal hands SessionPermissions: UserPermissions without Domains, since a checker holds no tenant list — the roster is the application's, and SessionPermissions filters it by HasGrants.

The canonical implementation is the access package's request-bound checker (Client.ForUser), which satisfies this interface structurally — neither package imports the other.

type UserPermissions

type UserPermissions interface {
	UserPermissionChecker

	// Domains lists the domains where the user holds at least one grant and
	// that the session reaches, sorted — the payload the generated
	// user-domains endpoint serves and the tenant picker's question: the
	// application's tenant roster filtered by HasGrants and by Reaches, so a
	// domain listed here is exactly a domain whose routes answer the user
	// with ordinary 403s rather than concealed tenancy's 404; the picker and
	// the guard can never disagree. Never nil: an application without
	// tenants lists none.
	Domains(ctx context.Context) ([]accesstypes.Domain, error)

	// Reaches reports whether the session may enter domain: the tenant's
	// declaration (TenantDeclarations) admits the way the session was
	// established, its sign-in's method and connection, or the session's
	// actor is the application's staff, who hold a grant in the global
	// partition and reach every tenant. It is the generated domain guard's
	// question before the foothold, and the attenuation behind every other
	// answer: in a tenant the session does not reach it holds nothing —
	// every check Denied, an empty digest, no foothold. Whether domain is a
	// tenant at all is the roster's question (TenantRoster.Has), which the
	// guard asks first. A session composed without declarations reaches
	// every domain.
	Reaches(ctx context.Context, domain accesstypes.Domain) (bool, error)
}

UserPermissions is the permission surface a request's decoders consume: the checks, the frontend's advisory enumerations, the identity a row condition's subject binds to, and the session's reach into the application's tenants. SessionPermissions composes it per request from the session's principal, the application's checker for that principal, the application's tenant roster and its tenant declarations; applications hand the composed value to the PatchSet and QuerySet types, which enforce permissions through it.

func Masked

Masked returns perms attenuated by mask: a permission the mask does not allow is Denied for every resource before policy is consulted — and evidenced as a mask denial — and the permission digest omits it. A foothold is answered through the masked digest, so a session masked to nothing has none and lists no domain. User and Reaches pass through. The unrestricted mask returns perms itself.

func RolePrincipalPermissions

func RolePrincipalPermissions(role RolePermissions, actor accesstypes.User) UserPermissions

RolePrincipalPermissions is a checker acting as a role on behalf of a real actor: the role's permissions answer the checks, and the actor's identity is what row conditions bind and change events record — the same composition an act-as-role session gets. It lists no domain: a body acting as a role asks no tenant picker.

func SessionPermissions

func SessionPermissions[U UserPermissionChecker, R RolePermissions](
	ctx context.Context, forUser func(accesstypes.User) U, forRole func(accesstypes.Role) R, roster DomainRoster, declarations TenantDeclarations,
) UserPermissions

SessionPermissions composes the request's UserPermissions from the session in ctx. It picks the checker by the session's principal — forUser for a user principal (an ordinary session, or an impersonated user), forRole for a role principal — admits the session into the tenants that admit the way it was established, lists the session's domains as the application's roster filtered by that admission and by the checker's HasGrants, and applies the session's permission mask. It is the per-request accessor for an application with impersonated sessions:

return resource.SessionPermissions(r.Context(), a.access.ForUser, a.access.ForRole, a.tenants.Domains, a.declarations)

The roster is the application's: access holds no tenant list, so the tenant picker's question — which tenants may this session see — is the roster asked, tenant by tenant, whether the session holds a grant there and whether the tenant admits the session. An application without tenants passes nil for the roster and the declarations.

The declarations are the application's too: what each tenant declares about who may enter it (signin.TenantDeclaration), read by domain. A tenant is offered only when the session may enter it, and the tenant's declaration decides: it admits the session's establishment, the sign-in's method and connection the session's first auth event records (sessioninfo.SessionData.EstablishedBy; signin.TenantDeclaration.Admits is the decision), or the session's actor is the application's staff, holding a grant in the global partition, who reach every tenant as the sign-in policy admits them (signin.TenantPolicy). An impersonated session is established by its impersonation event, so a directory-only tenant refuses it unless the actor, the real person behind it, is staff. In a tenant the session does not reach it holds nothing: every check Denied, an empty digest, no foothold, and the tenant is not listed, so the picker never offers it and the generated domain guard refuses a direct request for it as it refuses a domain that is not a tenant (UserPermissions.Reaches). An application that keeps no declarations passes nil, and every tenant admits every session.

A role checker has no User(): a role is not anyone. For a role principal the composed UserPermissions reports the session's effective identity — its Username, which is the actor who established the session — so a row condition's subject binds to the real person and nobody's identity is borrowed. An application that does not operate sessions as roles passes RolePrincipalsUnsupported as forRole: a role principal then fails closed — every check Denied, an empty digest, no footholds, no domains — with the same User(), so a deployment that mints role principals without a checker is loud rather than permissive.

type UserRegistration

type UserRegistration struct {
	// Name is the registration's name on the Auth (google, lakeside-entra), Kind the
	// method behind it (google, azure, workos), Label what a page shows for it.
	Name  string
	Kind  string
	Label string
	// Invited marks a registration admitting invited users only: the surface creates
	// the user, without a password, and the person signs in through the directory.
	Invited bool
	// SyncsRoles marks a registration that writes the roles from its directory at every
	// sign-in. Such a registration stands alone on its Auth (Validate refuses another
	// method beside it), so the directory is the authority for everyone the surface
	// holds: every row says rolesSynced, and the seats are shown and never written here.
	SyncsRoles bool
}

UserRegistration is one external registration on the Auth, as the generator declared it.

type UserResourceNames

type UserResourceNames struct {
	Global UserPartitionNames
	// Tenant is the zero value where the application has no tenancy (Tenanted false).
	Tenant UserPartitionNames
}

UserResourceNames are the names of one Auth's surface: the global partition's and, where the application has tenancy, the tenant partition's.

type UserRow

type UserRow[A UserAuth] struct {
	ID                     impulse.UUID `json:"id"                     spanner:"Id"`
	Username               string       `json:"username"               spanner:"Username"`
	Disabled               bool         `json:"disabled"               spanner:"Disabled"`
	HasPassword            bool         `json:"hasPassword"            spanner:"HasPassword"`
	PasswordChangeRequired bool         `json:"passwordChangeRequired" spanner:"PasswordChangeRequired"`
	CreatedAt              time.Time    `json:"createdAt"              spanner:"CreatedAt"`
	LastSignInAt           *time.Time   `json:"lastSignInAt"           spanner:"LastSignInAt"`
	Organization           *string      `json:"organization"           spanner:"Organization"`
	// Email is the person's address, nil for none, and EmailVerifiedAt when the person
	// proved it by following a link sent to it (nil while it is an operator's entry).
	Email           *string        `json:"email"           spanner:"Email"`
	EmailVerifiedAt *time.Time     `json:"emailVerifiedAt" spanner:"EmailVerifiedAt"`
	Identities      []UserIdentity `json:"identities"      spanner:"Identities"`
	// Roles are the roles held in the partition's own scope, EverywhereRoles the ones
	// held in every tenant, and RolesSynced that a directory writes them.
	Roles           []string `json:"roles"           spanner:"Roles"`
	EverywhereRoles []string `json:"everywhereRoles" spanner:"EverywhereRoles"`
	RolesSynced     bool     `json:"rolesSynced"     spanner:"RolesSynced"`
}

UserRow is one user of the global partition (<Auth>Users): the account, its sign-in means, and the roles it holds globally and in every tenant.

func (UserRow[A]) DefaultConfig

func (UserRow[A]) DefaultConfig() Config

DefaultConfig tracks nothing: the rows are composed, not stored.

func (UserRow[A]) Resource

func (UserRow[A]) Resource() accesstypes.Resource

Resource is the Auth's name for the resource.

type UserSeats

type UserSeats interface {
	AddUserRoles(ctx context.Context, scope accesstypes.PolicyScope, user accesstypes.User, roles ...accesstypes.Role) error
	DeleteUserRoles(ctx context.Context, scope accesstypes.PolicyScope, user accesstypes.User, roles ...accesstypes.Role) error
	// UserRoles returns the user's memberships by where each is held: every one with no
	// scopes given, those of each given scope otherwise.
	UserRoles(ctx context.Context, user accesstypes.User, scopes ...accesstypes.PolicyScope) (accesstypes.RoleCollection, error)
	RoleUsers(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role) ([]accesstypes.User, error)
	// Roles lists the roles that exist in scope, each with what it is for: the default
	// roles of the scope's kind, described by the role file, and the custom roles held
	// there, described when they were made.
	Roles(ctx context.Context, scope accesstypes.PolicyScope) ([]access.RoleInfo, error)
}

UserSeats is the membership store the surface seats and unseats through: the access library's UserManager, structurally.

type UserSurface

type UserSurface[A UserAuth] struct {
	// contains filtered or unexported fields
}

UserSurface serves one Auth's users: the handlers of both partitions over the Auth's account store and membership store. The generated router package builds one per Auth (New<Auth>UserSurface) and the application hands it back through <Auth>UserSurface(), which the generated handlers call.

func NewUserSurface

func NewUserSurface[A UserAuth](accounts UserAccounts, seats UserSeats, opts ...UserSurfaceOption) *UserSurface[A]

NewUserSurface builds the surface of the Auth A over its stores. It panics on a declaration the surface cannot serve and on a nil store: both are programming errors surfaced where the application wires its handlers.

func (*UserSurface[A]) Declaration

func (s *UserSurface[A]) Declaration() UserSurfaceDeclaration

Declaration returns the surface's declaration.

func (*UserSurface[A]) Invitation

func (s *UserSurface[A]) Invitation(a UserApp, collection *GeneratedCollection) http.HandlerFunc

Invitation serves one invitation of the global partition: Read on <Auth>Invitations.

func (*UserSurface[A]) Invitations

func (s *UserSurface[A]) Invitations(a UserApp, collection *GeneratedCollection) http.HandlerFunc

Invitations serves the global partition's standing invitations: List on <Auth>Invitations.

func (*UserSurface[A]) Names

func (s *UserSurface[A]) Names() UserResourceNames

Names returns the surface's names.

func (*UserSurface[A]) PatchInvitations

func (s *UserSurface[A]) PatchInvitations(a UserApp, _ *GeneratedCollection) http.HandlerFunc

PatchInvitations serves the global partition's invitation writes: Create and Delete on <Auth>Invitations through the operations body.

func (*UserSurface[A]) PatchSeats

func (s *UserSurface[A]) PatchSeats(a UserApp, _ *GeneratedCollection) http.HandlerFunc

PatchSeats serves the global partition's seat writes: Create and Delete on <Auth>Seats.

func (*UserSurface[A]) PatchTenantInvitations

func (s *UserSurface[A]) PatchTenantInvitations(a UserApp, _ *GeneratedCollection) http.HandlerFunc

PatchTenantInvitations serves the tenant partition's invitation writes: Create and Delete on <Auth><Tenant>Invitations.

func (*UserSurface[A]) PatchTenantSeats

func (s *UserSurface[A]) PatchTenantSeats(a UserApp, _ *GeneratedCollection) http.HandlerFunc

PatchTenantSeats serves the tenant partition's seat writes.

func (*UserSurface[A]) PatchTenantUsers

func (s *UserSurface[A]) PatchTenantUsers(a UserApp, _ *GeneratedCollection) http.HandlerFunc

PatchTenantUsers serves the tenant partition's user writes.

func (*UserSurface[A]) PatchUsers

func (s *UserSurface[A]) PatchUsers(a UserApp, _ *GeneratedCollection) http.HandlerFunc

PatchUsers serves the global partition's user writes: Create, Update and Delete on <Auth>Users through the operations body.

func (*UserSurface[A]) ResetTenantUserFactors

func (s *UserSurface[A]) ResetTenantUserFactors(a UserApp, _ *GeneratedCollection) http.HandlerFunc

ResetTenantUserFactors serves Reset<Auth><Tenant>UserFactors.

func (*UserSurface[A]) ResetUserFactors

func (s *UserSurface[A]) ResetUserFactors(a UserApp, _ *GeneratedCollection) http.HandlerFunc

ResetUserFactors serves Reset<Auth>UserFactors: Execute, targeting <Auth>Users.

func (*UserSurface[A]) Role

func (s *UserSurface[A]) Role(a UserApp, collection *GeneratedCollection) http.HandlerFunc

Role serves one role of the global partition: Read on <Auth>Roles.

func (*UserSurface[A]) Roles

func (s *UserSurface[A]) Roles(a UserApp, collection *GeneratedCollection) http.HandlerFunc

Roles serves the global partition's roles: List on <Auth>Roles.

func (*UserSurface[A]) Seat

func (s *UserSurface[A]) Seat(a UserApp, collection *GeneratedCollection) http.HandlerFunc

Seat serves one seat of the global partition: Read on <Auth>Seats.

func (*UserSurface[A]) SeatStore

func (s *UserSurface[A]) SeatStore() UserSeats

SeatStore returns the membership store the surface seats and unseats through: the Auth's engine's user manager. The generated create-your-tenant route seats a tenant's first administrator through it, the one membership written outside the surface's handlers.

func (*UserSurface[A]) Seats

func (s *UserSurface[A]) Seats(a UserApp, collection *GeneratedCollection) http.HandlerFunc

Seats serves the global partition's seats list: List on <Auth>Seats.

func (*UserSurface[A]) SetTenantUserPassword

func (s *UserSurface[A]) SetTenantUserPassword(a UserApp, _ *GeneratedCollection) http.HandlerFunc

SetTenantUserPassword serves Set<Auth><Tenant>UserPassword.

func (*UserSurface[A]) SetUserPassword

func (s *UserSurface[A]) SetUserPassword(a UserApp, _ *GeneratedCollection) http.HandlerFunc

SetUserPassword serves Set<Auth>UserPassword: Execute, targeting <Auth>Users.

func (*UserSurface[A]) TenantInvitation

func (s *UserSurface[A]) TenantInvitation(a UserApp, collection *GeneratedCollection) http.HandlerFunc

TenantInvitation serves one invitation of the tenant partition: Read on <Auth><Tenant>Invitations.

func (*UserSurface[A]) TenantInvitations

func (s *UserSurface[A]) TenantInvitations(a UserApp, collection *GeneratedCollection) http.HandlerFunc

TenantInvitations serves the tenant partition's standing invitations: List on <Auth><Tenant>Invitations in the route's tenant.

func (*UserSurface[A]) TenantRole

func (s *UserSurface[A]) TenantRole(a UserApp, collection *GeneratedCollection) http.HandlerFunc

TenantRole serves one role of the tenant partition.

func (*UserSurface[A]) TenantRoles

func (s *UserSurface[A]) TenantRoles(a UserApp, collection *GeneratedCollection) http.HandlerFunc

TenantRoles serves the tenant partition's roles.

func (*UserSurface[A]) TenantSeat

func (s *UserSurface[A]) TenantSeat(a UserApp, collection *GeneratedCollection) http.HandlerFunc

TenantSeat serves one seat of the tenant partition.

func (*UserSurface[A]) TenantSeats

func (s *UserSurface[A]) TenantSeats(a UserApp, collection *GeneratedCollection) http.HandlerFunc

TenantSeats serves the tenant partition's seats list.

func (*UserSurface[A]) TenantUser

func (s *UserSurface[A]) TenantUser(a UserApp, collection *GeneratedCollection) http.HandlerFunc

TenantUser serves one user of the tenant partition: Read on <Auth><Tenant>Users.

func (*UserSurface[A]) TenantUsers

func (s *UserSurface[A]) TenantUsers(a UserApp, collection *GeneratedCollection) http.HandlerFunc

TenantUsers serves the tenant partition's users list: List on <Auth><Tenant>Users in the route's tenant.

func (*UserSurface[A]) UnlinkTenantUserIdentity

func (s *UserSurface[A]) UnlinkTenantUserIdentity(a UserApp, _ *GeneratedCollection) http.HandlerFunc

UnlinkTenantUserIdentity serves Unlink<Auth><Tenant>UserIdentity.

func (*UserSurface[A]) UnlinkUserIdentity

func (s *UserSurface[A]) UnlinkUserIdentity(a UserApp, _ *GeneratedCollection) http.HandlerFunc

UnlinkUserIdentity serves Unlink<Auth>UserIdentity: Execute, targeting <Auth>Users.

func (*UserSurface[A]) User

func (s *UserSurface[A]) User(a UserApp, collection *GeneratedCollection) http.HandlerFunc

User serves one user of the global partition: Read on <Auth>Users.

func (*UserSurface[A]) Users

func (s *UserSurface[A]) Users(a UserApp, collection *GeneratedCollection) http.HandlerFunc

Users serves the global partition's users list: List on <Auth>Users.

type UserSurfaceDeclaration

type UserSurfaceDeclaration struct {
	// Auth is the Auth's name in PascalCase, the resource names' prefix: Crew gives
	// CrewUsers.
	Auth string
	// Tenant is the application's tenant record in PascalCase (Sector), the tenant
	// partition's infix: CrewSectorUsers. Empty where the application has no tenancy,
	// which leaves the surface its global partition alone.
	Tenant string
	// DomainParam is the route parameter the tenant partition reads the tenant from,
	// the one the generated router's domain segment declares.
	DomainParam httpio.ParamType
	// Shape is what the Auth's sign-in methods give the surface.
	Shape UserSurfaceShape
}

UserSurfaceDeclaration is what the generator derives for one Auth: the names its resources are built from, the tenant route's parameter, and the shape of the surface.

func (*UserSurfaceDeclaration) Names

Names derives the resource, route and parameter names of the declaration's partitions: what the collection registers, the router mounts and the client descriptor carries, computed once here so every consumer spells them alike.

func (*UserSurfaceDeclaration) Validate

func (d *UserSurfaceDeclaration) Validate() error

Validate refuses a declaration the surface cannot serve: an Auth name that is not PascalCase, a tenant without its route parameter, a registration without a name, a registration that syncs roles beside another method.

type UserSurfaceOption

type UserSurfaceOption func(*userSurfaceSettings)

UserSurfaceOption configures a surface at construction.

func WithAdministratorRoles

func WithAdministratorRoles(global, domain []accesstypes.Role) UserSurfaceOption

WithAdministratorRoles names the roles whose holders administer a partition, which turns the surface's refusal of a self-unseat into the last-owner rule: a person may unseat themselves unless the seat is one of the partition's administrator roles and no other holder of one would remain there. The global roles are the global partition's (held in the global scope), the domain roles a tenant partition's (held in the tenant's own scope or in every tenant). Without the option every self-unseat is refused, as it was. An application passes its auth's administrator roles, the ones its first administrator is seeded with (the auth package's AdministratorRoles).

func WithTenantDirectories

func WithTenantDirectories(declarations TenantDeclarations) UserSurfaceOption

WithTenantDirectories gives the surface what each tenant declares about who may enter it, which opens the second door into a tenant: a user who signed in through a directory the tenant declares may be seated in the tenant directly, without holding a seat there first (the person entered through the tenant's own directory, was told they have no access yet, and asked their administrator). Without it a tenant seat goes to the tenant's users alone, and anyone else enters by invitation. A tenanted application passes its roster's Declarations.

type UserSurfaceShape

type UserSurfaceShape struct {
	Password bool
	// UsernameIsEmail marks a password method declared with the username as the
	// person's email address (session.UsernameIsEmail): the address columns derive
	// from the username, so the surface takes no address on a user and refuses a
	// rename, which the session library refuses too; a verified new address renames
	// the user (SeatsFollowRename keeps the seats with them).
	UsernameIsEmail bool
	// OpenSignUp marks a password method that offers sign-up to anyone with an address
	// (session.OpenSignUp): a fact for the client descriptor, since the login page
	// serves the sign-up; the surface's rows are the same.
	OpenSignUp    bool
	Registrations []UserRegistration
}

UserSurfaceShape is what an Auth's methods give its surface: a password method gives creation with a password, the temporary password and its forced change; the registrations give the sign-in means a row shows and, declared invited-only, creation without a password; a registration that writes the roles from its directory makes the role part read-only for the users it signs in.

func (UserSurfaceShape) CreatesUsers

func (s UserSurfaceShape) CreatesUsers() bool

CreatesUsers reports whether the surface creates users: a password method or an invited-only registration gives it that; a directory that admits its own members alone leaves creation to the first sign-in.

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
)

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 sessionusers adapts the session library's user API to the resource package's account store (resource.UserAccounts), so an application hands its Auth's users to the user-management surface in one line: resource.NewUserSurface[router.CrewAuth]( sessionusers.Accounts(crewAuth.API()), engine.UserManager()).
Package sessionusers adapts the session library's user API to the resource package's account store (resource.UserAccounts), so an application hands its Auth's users to the user-management surface in one line: resource.NewUserSurface[router.CrewAuth]( sessionusers.Accounts(crewAuth.API()), engine.UserManager()).
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