@fitzzero/quickdraw-core
v5.1.4
Published
Fast fullstack patterns for real-time applications with Socket.io and TanStack Query
Downloads
4,783
Maintainers
Readme
@fitzzero/quickdraw-core
Typed real-time fullstack services on Socket.IO, TanStack Query and Prisma. A service is declared once, as a contract in the app's shared package; the server implements it and the client is typed from it. Writes are tracked, so every subscriber's live rows, lists and cached queries follow them without a single hand-written event.
- Contracts: methods, projections, field tiers, collections, streams, channels and events, as plain data plus schemas (Standard Schema; Zod 4.2 or later where JSON Schema is needed).
- Services:
qd.defineService(contract, { ... }), one handler per method, access declared and failing closed, row policies shared by every surface. - Live data: tracked Prisma writes become entity frames, collection deltas and change topics, with revisions, resume after reconnect, and revocation when access is lost.
- Client:
qd.<service>.<member>hooks over TanStack Query, live entities and collections, optimistic mutations, one invalidation coordinator. - Kits: read/write, search, sharing and membership, admin, presence and streams, auth routes.
- Transports: Socket.IO (protocol 5), HTTP, in process, MCP, and a shim for 4.x clients.
- Testing: a real test server, access matrices, performance budgets that count statements and bytes, strict development warnings.
Design record: docs/rfcs/0003-v5.md.
Install
bun add @fitzzero/quickdraw-core zod
bun add express socket.io @prisma/client # the server
bun add socket.io-client @tanstack/react-query react # the web app
bun add -d @fitzzero/quickdraw-lint @fitzzero/quickdraw-skills oxlintNode 24 or later. Every peer dependency is optional: install the ones the entries you import need.
| Entry | Needs |
| --------------------------------------- | ----------------------------------------------------------------------- |
| . (contracts, errors, protocol types) | a Standard Schema library: Zod 4.2 or later where JSON Schema is needed |
| ./server, ./server/mcp | socket.io; an Express 4 or 5 app (or none) for the HTTP transport |
| ./server/auth | express-rate-limit for its default sign-in limits |
| ./server/express | express-rate-limit |
| ./server/otel | @opentelemetry/api |
| ./prisma | @prisma/client 7 |
| ./client | socket.io-client, @tanstack/react-query 5, react 19 |
| ./client/core | socket.io-client |
| ./utils, ./parser | nothing more |
| ./testing | socket.io, socket.io-client |
| ./testing/client | the ./client peers, and @testing-library/react |
| ./testing/prisma | pg or @electric-sql/pglite |
Quick start
A board of tasks in the quickdraw template's layout: contracts in
packages/shared, the server in apps/api, the web app in apps/web. The
examples in this README compile: they are copies of
packages/core/test/readme/,
which the package's typecheck builds. The pieces the quick start imports
without showing (the schemas, the auth helpers, the Prisma models) are under
The example app.
1. The contract
packages/shared/src/contracts/task.ts. The shared package exports the
contracts, and a map of them for the client:
contracts = { label, project, task }.
import { crud, defineContract, mutation, query } from "@fitzzero/quickdraw-core";
import { z } from "zod";
import { cardSchema, taskSchema } from "../schemas";
export const taskContract = defineContract("taskService", {
// what the service is for: MCP tools and the generated docs show it
describe: "Tasks on a project's board.",
// the full row; it must contain `id: string`
entity: taskSchema,
// lean shapes of the row
projections: { card: cardSchema },
// only callers with Admin on the task receive notes
fields: { notes: "Admin" },
methods: {
// the read/write kit's get (one task by id) and create
...crud.contract({
entity: taskSchema,
get: true,
// `id`: one the client may make (`newId()`), which the create keeps
create: {
input: z.object({ id: z.string().optional(), projectId: z.string(), title: z.string() }),
},
}),
rename: mutation({
input: z.object({ id: z.string(), title: z.string() }),
output: "entity",
describe: "Renames a task.",
}),
countOnBoard: query({
input: z.object({ projectId: z.string() }),
output: z.number(),
// fetched again whenever the project's board changes
watch: { collection: "board", scope: (input) => input.projectId },
describe: "Counts the tasks on a project's board.",
}),
},
collections: {
// every task of a project, live, in board order
board: {
describe: "A project's tasks, in board order.",
scope: "projectId",
item: "card",
order: [
["ordinal", "asc"],
["id", "asc"],
],
// sent for the whole board
index: ["status", "ordinal", "assigneeId"],
views: { mine: (row, who) => row.assigneeId === who.userId },
},
},
});2. The service
The app states its types once, with one tracked database client.
import { trackPrisma } from "@fitzzero/quickdraw-core/prisma";
import { prisma } from "@project/db";
// Every write through `db` is tracked: subscribers see it. Apply trackPrisma
// last, after any other client extension.
export const db = trackPrisma(prisma);import { initQuickdraw, type Principal } from "@fitzzero/quickdraw-core/server";
import type { contracts } from "@project/shared";
import type { db } from "./db";
/** Who calls: a signed-in user, or an agent acting for one. */
export interface AppPrincipal extends Principal {
readonly kind: "user" | "agent";
}
// The app's types, stated once: every service, handler and caller is typed from them.
export const qd = initQuickdraw<{
db: typeof db;
principal: AppPrincipal;
// what the MCP bridge's context hook gives an agent's calls, as ctx.mcp
mcp: { readonly scopes: readonly string[] };
contracts: typeof contracts;
}>();apps/api/src/services/task.ts implements every method of the contract,
each with its access: the read/write kit's get and create in one spread,
and a handler for each of the others:
import { crud, inherit } from "@fitzzero/quickdraw-core/server";
import { projectContract, taskContract } from "@project/shared";
import { qd } from "../quickdraw";
export const taskService = qd.defineService(taskContract, {
// the Prisma model its rows live in
model: "task",
// the level on the task's project
access: inherit({ from: projectContract, via: "projectId" }),
// a board opens with Read on its project
collections: { board: { anchor: projectContract } },
methods: {
// the kit implements get and create; each names who may call it
...crud.handlers(taskContract, {
access: {
get: { entry: "Read" },
create: { scope: "Moderate", of: projectContract, id: "projectId" },
},
}),
rename: {
access: { entry: "Moderate" },
// return the row: the framework sends the projection's fields, dates as ISO strings
handler: ({ input, db }) =>
db.task.update({ where: { id: input.id }, data: { title: input.title } }),
},
countOnBoard: {
access: { scope: "Read", of: projectContract, id: "projectId" },
// identical concurrent calls by one user run once
share: "caller",
handler: ({ input, db }) => db.task.count({ where: { projectId: input.projectId } }),
},
},
});3. The server
apps/api/src/index.ts: the services on the app's own Express app.
import { socketAuth } from "@fitzzero/quickdraw-core/server/auth";
import express, { type Express } from "express";
import { jwtSecret, loadGrants, sessions } from "./auth";
import { db } from "./db";
import { qd, type AppPrincipal } from "./quickdraw";
import { labelService } from "./services/label";
import { projectService } from "./services/project";
import { taskService } from "./services/task";
// the web app's origins: CORS, and the pages that may open a socket with the session cookie
const webOrigins = ["http://localhost:3000"];
export const app: Express = express();
export const server = qd.createServer({
// the HTTP transport is mounted on it: POST /qd/{service}/{method}
app,
services: [labelService, projectService, taskService],
db,
cors: { origin: webOrigins, credentials: true },
auth: {
// the session cookie the auth routes set, else a bearer token (`auth.token`); none is anonymous
authenticate: socketAuth({
sessions,
jwtSecret,
allowedOrigins: webOrigins,
loadPrincipal: (userId): AppPrincipal => ({ userId, kind: "user" }),
}),
loadServiceAccess: (userId) => loadGrants(userId),
// a tracked write to User.serviceAccess refreshes that user's open sockets
serviceAccessSource: { model: "user", column: "serviceAccess" },
},
// close on SIGTERM and SIGINT; the process is never exited
handleSignals: true,
});
server.httpServer.listen(4000);4. The client
import { createQuickdrawClient } from "@fitzzero/quickdraw-core/client";
import { contracts } from "@project/shared";
// One typed client for the app: qd.task and qd.project, from the contracts.
export const qd = createQuickdrawClient(contracts);"use client";
import { QuickdrawProvider } from "@fitzzero/quickdraw-core/client";
import type { ReactNode } from "react";
import { qd } from "../lib/quickdraw";
export function Providers({ children }: { readonly children: ReactNode }) {
// Cookie sessions need no `auth`; a bearer token is `auth={token}`.
return (
<QuickdrawProvider client={qd} url="http://localhost:4000">
{children}
</QuickdrawProvider>
);
}"use client";
import { qd } from "../lib/quickdraw";
export function TaskBoard({ projectId }: { readonly projectId: string }) {
// Live: tasks added, changed, moved or removed by anyone show at once.
const { items, isLoading } = qd.task.board.useCollection(projectId);
const { data: count } = qd.task.countOnBoard.useQuery({ projectId });
// Optimistic: the new title shows before the server answers.
const rename = qd.task.rename.useMutation();
if (isLoading) {
return <p>Loading…</p>;
}
return (
<section>
<h2>{`${String(count ?? items.length)} tasks`}</h2>
<ul>
{items.map((task) => (
<li key={task.id}>
{task.title}
<button type="button" onClick={() => rename.mutate({ id: task.id, title: "Done" })}>
Rename
</button>
</li>
))}
</ul>
</section>
);
}When another user adds, renames or moves a task, the board changes at once,
and countOnBoard is fetched again because it watches the board.
The example app
The quick start is part of a small app in the template's layout, whose
every file compiles with the package:
packages/core/test/readme/.
The label and project services the server registers are there, with the
other sections' examples. These are the pieces the quick start imports
without showing, which an app writes itself.
The schemas the contracts are built on, packages/shared/src/schemas.ts
(the shared package exports them beside the contracts):
import { z } from "zod";
export const projectSchema = z.object({ id: z.string(), name: z.string(), ownerId: z.string() });
export const taskSchema = z.object({
id: z.string(),
projectId: z.string(),
title: z.string(),
status: z.string(),
ordinal: z.number(),
assigneeId: z.string().nullable(),
notes: z.string().nullable(),
});
/** The lean shape a board shows. */
export const cardSchema = taskSchema.omit({ notes: true });The sessions, the secret and the grants the server reads,
apps/api/src/auth.ts. Sessions are issued by the auth routes, mounted on
the same app (see the auth routes kit). verifySession
checks a bearer token against the session store on every call
(bearerAuth), so a signed-out or revoked session stops at once:
// The app's sessions, token check and grants, for the README's server examples.
import type { AccessLevel } from "@fitzzero/quickdraw-core";
import { bearerAuth, createMemorySessionStore } from "@fitzzero/quickdraw-core/server/auth";
import { db } from "./db";
import type { AppPrincipal } from "./quickdraw";
/** Signs the session JWTs: one secret for the auth routes and `socketAuth`, 32 characters or more. */
export const jwtSecret = process.env.JWT_SECRET ?? "";
/** The sessions the auth routes issue. In production, a store over the database (see the auth routes kit). */
export const sessions = createMemorySessionStore();
/**
* The agent a bearer token signs in, or `null` for no token: checked against
* the session store on every call, so a signed-out or revoked session stops
* at once. An agent, so methods with `kinds: ["user"]` refuse it. Never
* `verifyJWT` alone, which checks no session.
*/
export const verifySession = bearerAuth({
sessions,
jwtSecret,
loadPrincipal: (userId): AppPrincipal => ({ userId, kind: "agent" }),
});
/** A user's service-wide grants, as stored in `User.serviceAccess`. */
export async function loadGrants(userId: string): Promise<Record<string, AccessLevel>> {
const user = await db.user.findUnique({ where: { id: userId }, select: { serviceAccess: true } });
const stored: unknown = user?.serviceAccess;
return typeof stored === "object" && stored !== null
? (stored as Record<string, AccessLevel>)
: {};
}The Prisma models of @project/db (packages/db/prisma/schema.prisma),
User.serviceAccess among them, which loadGrants reads and
serviceAccessSource watches:
model User {
id String @id @default(cuid())
email String @unique
name String
// Service-wide grants, as 4.x apps store them: { "taskService": "Admin" }.
serviceAccess Json?
ownedProjects Project[]
memberships ProjectMember[]
assigned Task[]
}
model Project {
id String @id @default(cuid())
name String
ownerId String
// A JSON access list, [{ userId, level }].
acl Json?
archived Boolean @default(false)
owner User @relation(fields: [ownerId], references: [id])
members ProjectMember[]
tasks Task[]
labels Label[]
}
// A membership table: role holds an access level ("Read" | "Moderate" | "Admin").
// It has an id, and its pair is unique by @@unique: the write tracker keys
// rows by id, so a table keyed by a composite @@id is never tracked, and a
// member removed from it would never be revoked.
model ProjectMember {
id String @id @default(cuid())
projectId String
userId String
role String
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([projectId, userId])
@@index([userId])
}
model Task {
id String @id @default(cuid())
projectId String
parentTaskId String?
status String @default("open")
ordinal Int @default(0)
title String
assigneeId String?
notes String?
// A flag and a JSON column: every field type the admin kit edits.
pinned Boolean @default(false)
details Json?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
parent Task? @relation("Subtasks", fields: [parentTaskId], references: [id], onDelete: SetNull)
subtasks Task[] @relation("Subtasks")
assignee User? @relation(fields: [assigneeId], references: [id], onDelete: SetNull)
labels TaskLabel[]
@@index([projectId, status, ordinal])
}
model Label {
id String @id @default(cuid())
projectId String
name String
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
tasks TaskLabel[]
}
model TaskLabel {
id String @id @default(cuid())
taskId String
labelId String
task Task @relation(fields: [taskId], references: [id], onDelete: Cascade)
label Label @relation(fields: [labelId], references: [id], onDelete: Cascade)
@@unique([taskId, labelId])
@@index([labelId])
}Contracts
A contract is plain data plus schemas, so browser code imports it without
any server code (design: docs/rfcs/0003-v5.md, section 2).
export const labelContract = defineContract("labelService", {
describe: "Labels a project puts on its tasks.",
entity: labelSchema,
projections: { chip: z.object({ id: z.string(), name: z.string() }) },
methods: {
find: query({
input: z.object({ name: z.string() }),
output: nullable("entity"),
describe: "Finds a label by its name, or null.",
}),
chips: query({
input: z.object({ projectId: z.string() }),
output: listOf("chip"),
describe: "Lists a project's labels as chips.",
}),
usage: query({
input: z.undefined(),
output: z.record(z.string(), z.number()),
describe: "Counts the tasks of each label.",
}),
},
});
// No entity: an RPC-only service, with no projections, field tiers or collections.
export const healthContract = defineContract("healthService", {
describe: "Tells a caller the server is up.",
methods: {
ping: query({
input: z.undefined(),
output: z.literal("pong"),
describe: "Answers pong while the server runs.",
}),
},
});- Every method is a
queryor amutation, with aninputand anoutput. The kind decides request sharing, cancellation, the concurrency cap, the MCP read-only hint and which client hook exists. - Every member takes a
describe, a sentence or two for people and agents: the contract itself (what the service is for), each method (its MCP tool's description), collection, stream, channel and event.quickdraw-docsleads each section of the API docs with it. It is optional in the types; lint'srequire-describe(a warning) lists each member without one. outputis a schema, or a projection:"entity", a named projection,nullable("entity")orlistOf("card"). A handler returns database rows for a projection output, and the framework projects them.entityand every projection containid: string. A contract without anentityis an RPC-only service.- Only a query may
watch({ collection, scope: (input) => scopeId }): the client joins that scope's change topic and fetches the query again when it changes. - Methods, collections, streams, channels and events share one namespace,
because the client exposes each as
qd.<service>.<name>.subscribe,unsubscribe,call,then,useEntity,useEntities,adminand names starting with$are reserved. - A service name holds no
:or@: it is part of every room name of the service (qd:e:{service}:{id}@{level},qd:c:{service}:{collection}:{scope}), which must split one way only, sodefineContractthrows on one. - Schemas are any Standard Schema. A projection's keys, admin field
metadata, MCP tool schemas and
quickdraw-docsread Standard JSON Schema, which Zod 4.2 or later provides; a projection whose schema cannot describe itself declareskeysin the service'sprojectoption.
Types come from the contract too:
// { id: string; title: string }
export type RenameInput = InputOf<typeof taskContract, "rename">;
// the entity, as the wire has it
export type Task = OutputOf<typeof taskContract, "get">;
// one item of the board
export type Card = ItemOf<typeof taskContract, "board">;InputOf, ParsedInputOf, OutputOf, EntityOf, ProjectionOf,
ItemOf, ScopeOf, IndexRowOf, ViewName and the rest are exported from
the package root. FullProjectionOf<C, P> is a projection's full row (what
a handler builds, every tiered field present), and ReceivedRow<C, Row>
makes a row's tiered fields optional, as a reader receives it.
Services
qd.defineService(contract, definition) implements a contract (design:
section 3). methods must implement exactly the contract's methods; each is
{ access, handler }, plus timeoutMs, and for a query share, ttlMs and
version.
export const taskService = qd.defineService(task, {
model: "task",
methods: {
assign: {
access: { service: "Moderate" },
// instead of the dispatcher's callTimeoutMs (30 s)
timeoutMs: 5_000,
handler: async ({ input, ctx, db }) => {
// an agent's call carries its token's scopes as ctx.mcp; a user's call has none
if (ctx.mcp !== undefined && !ctx.mcp.scopes.includes("tasks")) {
throw new QuickdrawError("FORBIDDEN", "This token may not assign tasks");
}
const found = await db.task.findUnique({ where: { id: input.id } });
if (found === null) {
// the caller receives the code
throw new QuickdrawError("NOT_FOUND", "No such task");
}
ctx.log.info("assigning", { by: ctx.principal.userId, transport: ctx.transport });
return db.task.update({ where: { id: input.id }, data: { assigneeId: input.assigneeId } });
},
},
},
});- A handler receives
{ input, ctx, db }: the input after its schema ran, the call's context, and the tracked database client.ctxholdsprincipal(userId,kind,claims,serviceAccess;nullonly in a"public"method called anonymously),signal(aborts on cancel or time limit),log,requestId,transport("socket","http","mcp","internal"or"legacy"),touch(below),roomsandpresence(realtime, below),mcp(the MCP bridge's context) andservices. ctx.servicescalls the app's services in process, as the same principal, by service name:await ctx.services.projectService.get({ id }). Each call runs the whole pipeline with transport"internal"(input check, access, handler, output check), so access is checked on the inner call too; its writes join the calling method's unit of work, so both flush together once; and it is cancelled withctx.signal. It carries the calling method'sctx.mcpas well: every call an MCP call makes throughctx.services, nested ones included, sees the MCP call's fields with transport"internal", so tell a token's call apart byctx.mcp, never byctx.transport. It is typed by thecontractsofinitQuickdraw's types, asqd.calleris.timeoutMsis how long the caller waits (else the dispatcher'slimits.callTimeoutMs, 30 s). At the limit the caller getsTIMEOUTandctx.signalaborts, but a handler still running runs on, and what it writes still commits and is pushed:TIMEOUTsays the server stopped waiting, not that nothing happened. A method that waits on a slow outside API passes itctx.signal, callsctx.signal.throwIfAborted()before it writes the outcome, and setstimeoutMsabove its slowest path. The server logs a warning (categoryquickdraw.call) when a call that answeredTIMEOUTgoes on to commit writes. A nestedctx.servicescall's writes flush with its caller's run, so the warning fires only when that outermost call answeredTIMEOUT.share: "caller"runs identical concurrent calls of one principal once,share: "all"across principals;ttlMskeeps a shared result. A"all"run's handler sees the first caller'sctxand every caller gets its result, so a result shared across principals must depend on the input only: it never readsctx.principal,ctx.services,ctx.mcp,ctx.accessor a context field made from them (in development, reading one of the first four warns[quickdraw:shared-principal]; copying or logging the wholectxreads them too)."all"is refused withcustomaccess and on the kit methods whose result depends on the caller (the read/write kit'slistandgetMany,search, the sharing kit'slistSharesandlistMembers, the admin kit'sadminListandadminGet): give those"caller". Callers of a shared run whose levels hide the same fields get one copy of its result, encoded once for all of their sockets.version(input, ctx)answers "not modified" for a query whose result the caller already holds.- Every call runs a pipeline: look up, concurrency (16 queries in flight per
socket and 64 queued, then
RATE_LIMITED; mutations are not queued behind queries), input validation, access, "not modified", sharing, the handler under a time limit (30 s by default), the result shaped to its output (below), output validation outside production, the reply, the flush, and one completion record (onCall). A mutation ignores the caller's cancel: only its time limit ends the call early, and its handler runs on even then (timeoutMs, above). - A method's output is sent as it declares it, on every transport and in
production too, so a handler may return the whole row: a projection
output (
"entity", a named projection) sends the projection's keys, stripped per caller (below), and an output schema of the method's own sends what its JSON Schema declares (Zod 4.2 or later). An object keeps the keys itspropertiesdeclare, and every key only whereadditionalPropertiesallows them (z.looseObject,.catchall) or it is a record; an array keeps its items, each reduced by its item schema; a union keeps what any branch declares; a value the schema allows to be anything (z.unknown(), aDate) goes as it is. An output schema without JSON Schema (Zod 3) is sent as the handler returns it.
Errors are QuickdrawError(code, message, data?). Anything else a handler
throws reaches the caller as INTERNAL with a generic message, and is
logged; Prisma's unique violation becomes CONFLICT and its missing row
NOT_FOUND.
| Code | HTTP | Meaning |
| ----------------- | ---- | -------------------------------------------------------- |
| UNAUTHENTICATED | 401 | no principal |
| FORBIDDEN | 403 | access denied |
| NOT_FOUND | 404 | unknown service, method or row |
| CONFLICT | 409 | unique or state conflict |
| VALIDATION | 422 | input failed its schema; data.issues lists paths |
| RATE_LIMITED | 429 | limiter or queue overflow; data.retryAfterMs |
| CANCELLED | 499 | the caller cancelled |
| TIMEOUT | 504 | the server stopped waiting; the handler may still commit |
| INTERNAL | 500 | everything else |
An app adds its own fields to every ctx once, through initQuickdraw:
interface AppContext {
/** The tenant every query of this call is scoped to. */
readonly tenantId: string;
}
export const qd = initQuickdraw<{ db: typeof db; principal: Principal; context: AppContext }>({
// runs once per call, before access is checked, so custom checks see it too
context: (base) => ({ tenantId: String(base.principal?.claims?.tenant ?? "public") }),
});Access control
Each method declares who may call it, and a service with rows declares one
access policy that says how a principal's level on a row is found (design:
section 4). Everything fails closed: a method without access does not
compile, and a missing grant, an unknown level, a missing id, a row that does
not exist or a malformed access list denies.
import { anyOf, crud, custom, inherit, jsonAcl, members } from "@fitzzero/quickdraw-core/server";
export const projectService = qd.defineService(project, {
// the Prisma model the rows live in
model: "project",
access: anyOf(
// [{ userId, level }] plus Admin for the owner
jsonAcl("acl", { owner: "ownerId" }),
members({ model: "projectMember", entry: "projectId", user: "userId", level: "role" }),
),
methods: {
// the read/write kit's get: Read on the project itself
...crud.handlers(project, { access: { get: { entry: "Read" } } }),
title: {
// anyone may read any project's name by its id: the form is the whole check, on purpose
access: "public",
rowless: true,
handler: async ({ input, db }) =>
await db.project.findUniqueOrThrow({ where: { id: input.id }, select: { name: true } }),
},
},
});
export const taskService = qd.defineService(task, {
model: "task",
// the level on the task's project
access: inherit({ from: project, via: "projectId" }),
methods: {
rename: {
access: { entry: "Moderate" },
handler: ({ input, db }) =>
db.task.update({ where: { id: input.id }, data: { title: input.title } }),
},
// the kit's create: Moderate on the project the task goes into
...crud.handlers(task, {
access: { create: { scope: "Moderate", of: project, id: "projectId" } },
}),
archiveAll: {
access: { service: "Admin" },
handler: async ({ db }) => (await db.task.updateMany({ data: { status: "archived" } })).count,
},
claim: {
access: { entry: "Moderate" },
// users only: an agent acting for one is refused, whatever its grants
kinds: ["user"],
handler: ({ input, ctx, db }) =>
db.task.update({ where: { id: input.id }, data: { assigneeId: ctx.principal.userId } }),
},
triage: {
// Moderate on the task's project, from a token that may triage: claims add to the form
access: { entry: "Moderate" },
claims: (claims, input) => claims?.scope === "triage" && input.status !== "archived",
handler: ({ input, db }) =>
db.task.update({ where: { id: input.id }, data: { status: input.status } }),
},
assigned: {
// Read on the project the input names, asked through ctx.access; none named, the caller's
// own that they may still read
access: custom(
async (ctx, input) =>
input.projectId === undefined || (await ctx.access.can(project, input.projectId, "Read")),
),
handler: async ({ input, ctx, db }) => {
const readable = await ctx.access.where(task, "Read");
if (readable === "none") return [];
return db.task.findMany({
where: {
AND: [{ assigneeId: ctx.principal.userId, projectId: input.projectId }, readable],
},
take: 100,
});
},
},
},
});- Forms:
"public","authenticated",{ service: L }(the user's service-wide grant),{ entry: L, id? }(the policy's level on the row;iddefaults toinput.id),{ service: L1, entry: L2 }(either),{ scope: L, of, id }(the level on a row of another service) andcustom(fn). Without a principal every form but"public"answersUNAUTHENTICATED; a principal that fails getsFORBIDDEN. The levels, lowest first, arePublic,Read,ModerateandAdmin. Acustomform replaces the row check, and a service-wideAdmingrant skips it: a check on the caller's claims isclaims(below), and one that needs the caller's level on a row asksctx.access(assignedabove, and below). kinds, besideaccess, says which kinds of principal (principal.kind) may call:initQuickdraw({ kinds: ["user", "agent"] })for every service the app defines,defineService(contract, { kinds })for one service, and a method's ownkinds(claimabove). Each level only narrows the one above it: a wider or empty list is refused when the service is defined. A principal of another kind, or without akind, getsFORBIDDENbefore the form is asked, and no grant passes the check, a service-wideAdmingrant included, since a token acting with someone's grants is what it stops. An anonymous caller is left to the form, so a"public"method takes nokindsof its own: a refused caller would call it signed out. A service's list also holds for its entity, collection, topic and stream subscriptions, and its channels drop the messages of other kinds.claims: (claims, input) => boolean, besideaccesson a method, is a requirement on the caller's verified claims (principal.claims, a token'sscope;triageabove). It adds to the form, sotriageneeds Moderate on the task's project and a triage token. It runs right afterkinds, outside the access engine, so no grant passes it, a service-wideAdmingrant included. Without a principal the call isUNAUTHENTICATED; when it returns anything buttrue,FORBIDDEN. It is synchronous, and a"public"method takes none. A token narrowed byclaimsis narrowed only on the methods that declare it; elsewhere it acts with its user's grants (kindskeeps a kind of token out).- On a service with a policy, a method whose input has
idunder a form that asks the policy nothing about the row that id names would let anyone that form admits reach any row by its id, sodefineServicerefuses it, naming the method and the ways out. Those forms are the ones that check no row ("public","authenticated",{ service: L }belowAdmin),custom(fn),{ scope, of, id }(a row of another service) and{ entry, id }naming another key. The ways out: a form the policy decides ({ entry: L }, or{ service: L, entry: L }to keep the grant, withclaimsbeside it for a check on the caller's claims), orrowless: trueon the method when every such caller may reach any row on purpose (thetitlemethod above; public profiles, lookups by an id that tells nothing), or whenidnames a row the method creates (an id the client made, under ascopeform). Arowlessquery under a form that checks no row also answers "not modified" for anyid; under any other form it runs its handler every time. A kit's methods take it asrowless: ["get"]in the kit's options. The input's keys come from its JSON Schema: anidin any branch of a union counts, and so does one beside a value JSON Schema cannot write (aDate, aSet). Not checked: an input without JSON Schema (Zod 3) or whose JSON Schema names no keys (atodoSchemawithoutkeys), one that is no object (a bare string that is the id itself), a row named by another key (ids,taskId, a nestedwhere.id) under a form that checks the rowidnames, and anentryform whoseidis a function, which names its row in code. - A service-wide
Admingrant passes every access form on its service (adminBypass: falseturns that off), though notkindsorclaims. A grant belowAdmincounts only where the form namesservice: aReadgrant does not read every row. - Grants come from
principal.serviceAccess, asauthenticatereturns it orcreateServer({ auth: { loadServiceAccess } })loads it for a principal that carries none: at a socket's handshake, for each HTTP call, and for an in-process caller (qd.caller) at its first call. Withauth.serviceAccessSource: { model: "user", column: "serviceAccess" }, a tracked write to that column refreshes the user's open sockets (qd:access), and in-process callers load the grants again. - Policies:
owner(field),jsonAcl(field, { owner? }),members({ model, entry, user, level, levels? }),inherit({ from, via }),anyOf(...),resolver({ levelsFor, where?, reads })andeveryone(level)(every signed-in user haslevelon every row, reading nothing: public profiles areanyOf(owner("id"), everyone("Read")); unlikerowless: trueon a method, it covers subscriptions and lists too). Aresolveris app code, so it says what its levels depend on:reads: { columns, memberships }names columns of the service's model and membership tables asmemberstakes them (entryholding this service's row id), and tracked writes to them re-check what it decided, as for the other policies;reads: "none"says nothing a tracked write changes can change a level (the principal's grants alone, say). A resolver with neither is never re-checked, and the server warns[quickdraw:resolver-without-reads]when it starts. Their column and table names are checked against the Prisma client's models at compile time. A lookup is one batched query per table, memoized for the call, so checking 60 ids costs what checking one does.entryaccess needs a policy; a service withoutmodelmay only use"public","authenticated",{ service }andcustom.inherituses the parent's policy only: grants on the parent's service do not flow down. A membership table needs anidcolumn (the pair unique by@@unique), or its writes are not tracked and a removed member is never revoked. - One policy decides every surface: method calls, entity subscriptions, collection scopes, the kits' lists and searches, streams and channels.
- When a tracked write lowers or removes someone's access, a relation-form
foreign key included (
project: { connect }), their sockets leave the rooms anchored on that row and getqd:revoked; a changed level moves them to that level's room. In a cluster the change is broadcast to every node. Every socket's re-resolution settles before the flush's frames go out, a failed one included. server.dispatcher.accessgives the same answers to other code:levelsFor(service, principal, ids),accessWhere(service, principal, level)(awherefilter forfindMany, or"none") andonAccessChanged(listener).ctx.accessgives them to a handler or acustomform, as the caller:levelsFor(service, ids),can(service, id, level)andwhere(service, level)are those bound toctx.principal, with the grants the call runs with (a socket's, or those an in-process caller loaded);serviceis a contract or a service name. A form can then check a row no{ entry }or{ scope }form names: a parent the input names, or a key that is optional, as inassignedabove, which passes without a project and needs Read on one it names. Its handler addswhere(task, "Read")to its query withAND, so a list without a project still follows the row policy. Never spread the filter intowhere: it and the input both setprojectId, and whichever comes last wins, widening a list with a project or dropping the policy from one without.ctx.accesscounts levels as{ entry }does: a service-wideAdmingrant reaches every row (withadminBypass), a row that is not found gives anyone else no level (canisfalse), and an anonymous caller has none anywhere (an empty map,false,"none"). So a form that asks it about a parent counts a service-wideAdmingrant on the parent's service, which{ scope, of }does not: prefer{ scope: L, of, id }when the input always names the parent. Acustomform is still no row check of the method's ownid: a method whose input has one needsrowless: truebeside it (above). Every method call has it, MCP andctx.servicescalls included, and so do thectxthe kits pass to their forms and callbacks; a context no dispatcher built throwsINTERNALon its use, andqdhas none: a job asksserver.dispatcher.access.createServer({ access: { cacheMs: 30_000 } })keeps policy lookups across requests; tracked writes to the columns and membership tables the policies read evict them as soon as the write is durable (a transaction's at its commit, a rolled-back one never), so a check later in the same call sees it, as does any other request on that node. Servers behind a cluster adapter evict when the write's flush broadcasts its access change, after the call. A process that broadcasts nothing (a job on a barecreateDispatcher, or a server without a cluster adapter) reaches other processes' caches only when the time passes, as do writes the tracked client cannot see, so the cache is off by default. A lookup inside a transaction (db.$transaction, a sharing change) reads the database, never the cache.
Tracked writes
@fitzzero/quickdraw-core/prisma wraps the app's Prisma client so the
framework sees every write made through it (design: section 5). Pass the
tracked client as db; the server finds the rest on it.
- Every handler runs in a unit of work. Each
create,update,upsert,delete,createMany,updateManyanddeleteManymade throughdbis recorded with its row ids, merged per row, and handed to the flush sinks once the response has been sent, with one revision per flush. A handler may returndb.task.update(...)without awaiting it. - A write that certainly changed nothing is not recorded, so it sends no
frame, no collection delta, no topic change and no
refreshEntry: anupdateMany,updateManyAndReturnordeleteManythat matched no row, and adata(or an upsert'supdate) with nothing to write,{}. An upsert withupdate: {}("make sure this row exists") reads the row first in its place: one statement when the row is there, and the upsert after it when it is not. Every other write is recorded, one that sets a column to the value it already held too: the values the framework reads before a write cannot prove it changed nothing, since another write may land between that read and the write. - Writes inside
db.$transactionjoin the unit only when it commits; a rollback drops them. Prefer the interactive form (db.$transaction(async (tx) => ...)): an array-formdb.$transaction([...])has no transaction client, so the rows adeleteManyorupdateManyin it reads first, and the old values anupdatethat moves a row or changes who may see it reads first, are read outside the batch, and rows its earlier statements changed may be missed (a development warning names the model and operation). - A transaction nested in an interactive one,
tx.$transaction(async (inner) => ...), runs as a savepoint of it (Prisma 7) and is tracked the same way: its writes join the transaction around it when the savepoint is released, and are dropped when it rolls back, even when the transaction around it catches the error and commits. Inside a transaction's callback, write through its client (tx,inner) what must commit or roll back with it. Work ondbthere runs outside the transaction, on a connection of its own, and is tracked as such: a write (acreateManyorupdateManytoo) commits at once, and adb.$transactionof its own commits on its own, so their frames are sent whatever the transaction then does. (A database with one connection, as PGlite in tests, runs that work only once the transaction ends.) A transaction's client writes to its own transaction wherever it is used, inside another transaction's callback too, and once that transaction ended its writes are refused, as Prisma refuses them. An array-form$transaction([...])begun on either client is a transaction of its own, as Prisma runs it: the root client's operations in it commit with it, while one made ontxin it runs intx's transaction (the tracking hook awaits it there; Prisma alone would run it in the batch). - Write many rows in one statement when every row gets the same data
(
updateMany,createMany). When each row's data differs (moving tasks to different projects, say), write each row by id inside an interactive transaction: insidedb.$transaction(async (tx) => ...), loop over the rows and awaittx.task.update({ where: { id }, data })for each. Neither the N+1 warning norno-db-call-in-loopcounts those writes. - A service lists the other models its handlers write
(
writes: ["taskLabel"]); theno-foreign-writelint rule checks it. - Jobs, scripts and webhooks wrap their writes in
qd.run(fn), which flushes before it returns. A write made outside any unit of work flushes on its own on the next tick, with a development warning. Inside a handlerqd.runjoins the handler's unit; background work the reply does not wait for (a push sent after a message, pruning what it reports dead) runs inqd.run(fn, { detached: true }), a unit of its own that flushes whenfnsettles (catch what the promise rejects with: nothing awaits it). Before any server exists (a seed at boot, beforecreateServer),qd.run(fn)still runsfnin a unit of its own, and its writes reach no one: no socket can be subscribed yet (behind a cluster, write aftercreateServerwhen other nodes' subscribers must hear of it).
export async function markStale(before: Date): Promise<number> {
// a job's writes flush to subscribers when qd.run settles, as a method's do
const { count } = await qd.run(() =>
db.task.updateMany({
where: { status: "open", updatedAt: { lt: before } },
data: { status: "stale" },
}),
);
return count;
}- A helper that writes takes the tracked client by its type.
trackPrismareturnsTracked<C>: still aCwherever one is asked for, while the untracked client is noTracked<C>. Type the helper's clientTracked<PrismaClient>, orTrackedTransaction<PrismaClient>when it may also run insidedb.$transaction(async (tx) => ...), whosetxis one (dbis one too), and the untracked client passed to it is a type error. A helper typedPrismaClienttakes either client. Both types are type-only, on./prismaand on the root export, so a shared package names them without Prisma.no-untracked-writereads the type too, when the file imports it from quickdraw (under any name): a parameter, a destructured binding or a class member so typed may be namedprisma.
import type { TrackedTransaction } from "@fitzzero/quickdraw-core/prisma";
import type { PrismaClient } from "@project/db";
// takes the tracked client, or a transaction's: passing the untracked `prisma` is a type error
export async function reopenStale(
client: TrackedTransaction<PrismaClient>,
projectId: string,
): Promise<number> {
const { count } = await client.task.updateMany({
where: { projectId, status: "stale" },
data: { status: "open" },
});
return count;
}
export async function restoreProject(projectId: string): Promise<number> {
return await qd.run(() =>
db.$transaction(async (tx) => {
await tx.project.update({ where: { id: projectId }, data: { archived: false } });
return await reopenStale(tx, projectId);
}),
);
}- Not seen: the related rows of a nested write
(
{ labels: { create: [...] } }, which warns in development), raw SQL and database cascades. A foreign key a nested write sets on the written row (project: { connect },parent: { disconnect: true }) is seen: such anupdateorupsertreads the row's interested columns first, one more statement. Before deleting a row, delete or clear throughdbthe rows a cascade would take with it (for the admin kit'sadminDelete, in itsprepare). Record raw SQL withctx.touch("task", ids), or{ removed: true }for deleted rows. A touch inside a transaction's callback joins that transaction, as a write throughtxthere would: touch a rootdb.$executeRawmade there after the callback, or the transaction's rollback drops it. A job gets the sametouchfromqd.run, whosefnreceives{ touch, log, principal: null }:
export async function spreadOrdinals(projectId: string): Promise<void> {
await qd.run(async (ctx) => {
const rows = await db.$queryRaw<{ id: string }[]>`
UPDATE "Task" SET "ordinal" = "ordinal" * 2 WHERE "projectId" = ${projectId} RETURNING "id"`;
// raw SQL is invisible to the tracked client: record the rows it changed
ctx.touch(
"task",
rows.map((row) => row.id),
);
});
}- Tracked models need a string
idcolumn; writes to other models pass through untracked, with one warning. Membership and junction tables included: give themid String @id @default(cuid())and keep the pair unique with@@unique([...]), never a composite@@id.createServerchecks, at start, every model a policy, a membership table or aviajunction depends on, and logs[quickdraw:untracked-access-model]as an error, in every environment, for one it cannot track; a test app made withstrictWarningsfails to start. createServer({ flushSink })adds the app's own sinks (an audit log, say);createRecordingSink()on./testingrecords what is flushed, for tests.
Projections and entity subscriptions
A projection is the wire shape of a row (design: section 6). Its keys decide what a read selects, so a row is never read wider than what is sent:
import { crud, inherit } from "@fitzzero/quickdraw-core/server";
export const taskService = qd.defineService(task, {
model: "task",
access: inherit({ from: projectContract, via: "projectId" }),
// answers "not modified" from the row's own time
versionColumn: "updatedAt",
// a write to a subtask sends its parent again
affects: [{ service: task, id: "parentTaskId" }],
project: {
// a relation count: read with select, built by a pure, synchronous map. Read the relation's
// ids, which Prisma fetches for the rows read only; its _count aggregates the whole TaskLabel
// table (a GROUP BY over every row) on every snapshot and flush
card: {
select: { title: true, status: true, labels: { select: { id: true } } },
map: (row: { id: string; title: string; status: string; labels: { id: string }[] }) => ({
id: row.id,
title: row.title,
status: row.status,
labelCount: row.labels.length,
}),
},
},
methods: {
// the kit's get reads the entity's keys only, and sends dates as ISO strings
...crud.handlers(task, { access: { get: { entry: "Read" } } }),
// returns the database row `map` takes: the framework builds the card from it
card: {
access: { entry: "Read" },
handler: ({ input, db }) =>
db.task.findUniqueOrThrow({
where: { id: input.id },
select: { id: true, title: true, status: true, labels: { select: { id: true } } },
}),
},
},
});- A count over a relation reads the relation's ids (
labels: { select: { id: true } }) and counts them inmap: Prisma reads them for the rows read only (a second SQL query,WHERE "taskId" IN (...)). Its_countcompiles to aGROUP BYover the whole relation table, joined in, on every snapshot, page and flush that reads the projection. For a relation too large to read (a chat's members), keep a counter column that the writes maintain. - A projection's keys come from its schema's JSON Schema (Zod 4.2 or later),
or from
project: { <name>: { keys } }; a service whose projection has neither fails when it is defined. A handler returning a projection returns rows (aDateis fine where the wire has a string, a PrismaJsoncolumn (JsonColumnValue) where it has an object, an array or a record, and extra columns are dropped); withmap, it returns whatmaptakes. - Fields the contract's
fieldsmap puts above the caller's level on a row are stripped from that caller's copy, after any shared run. Only a projection output is stripped per caller ("entity", a named projection, andnullable(...)orlistOf(...)of one): a method whose output is a schema of its own sends what that schema declares to every caller its access admits, so a tiered key the schema declares, at any depth (emailin a hand-written{ id, name, email }, or in{ user: { id, email } }), reaches callers below its level. When a server is made, each such method raises the development warning[quickdraw:tiered-field-in-output](thrown bycreateTestApp({ strictWarnings: true }), so the test app fails to start): answer"entity"or a projection, or drop the key from the schema. Not warned: a method whose access admits no caller below the field's level ({ service: "Admin" }with the Admin bypass on,{ entry: L }withLat the field's level or above), and a kit's methods, which strip their own replies. An output without JSON Schema (Zod 3) cannot be reduced, so in development each tiered key its replies carry raises the warning when a reply first carries it. affectsnames rows of other services a write changes too ({ service, id: column }, or{ service, id: (row) => ids, columns }); they are sent again after the flush, one hop.qd.<service>.useEntity(id)subscribes withqd:sub { s, ids, revs? }(up to 500 ids per batch), which authorizes every id in one lookup, reads the allowed rows in one query and joins the room of each row found for the subscriber's level. A socket is never in the room of a row it could not read.- After each flush, subscribers get
qd:e:{ t: "u", s, id, rev, d }with the whole row (a create, a touch, a projection withmap, anaffectsrow),{ t: "p", s, id, rev, d }with the changed fields only (an update of plain projection fields), or{ t: "r", s, id, rev }(a delete). One read per service per flush, none when no room has subscribers, and each frame is stripped once per subscriber tier. - "Not modified" (for
qd:suband for queries returning one projection row byid) comes fromversionColumn, or from an in-process change log of recent flushes. The change log sees only this process's writes: an app running several processes without a Socket.IO cluster adapter declaresversionColumns or passeschangeLog: false. For a query, it comes only when its form checked the rowidnames (anentryform onid, ascopeform on the service's own rows byid,{ service: "Admin" }), for a caller the service'sAdminbypass passes, or for arowlessmethod under a form that checks no row ("public","authenticated",{ service: L }): it answers before the handler runs, so it would tell any other caller that the row exists and has not changed. Any other query runs its handler. - Revisions are microseconds since the epoch: a flush takes
max(Date.now() * 1000, last + 1). Clients compare them as numbers. - Behind a cluster adapter (
setupRedisAdapter), every touched row is read (deleted ones too) and sent, whole, decided by the row as read at flush time, since other nodes' rooms are not visible and frames from two nodes can arrive out of order; access changes and refreshed grants are broadcast to every node, and a flush sends its frames once every node applied them (without waiting while a node does not answer, fail-open). Flushes take their revisions from a counter in the cluster's Valkey, on Valkey's clock in microseconds, so revisions from all nodes are one order; its key needs persistence or replication. A node whose Valkey connection comes back has its clients reconnect to catch up. Give each deployment its own Valkey, or its owncluster.keyPrefix(whichsetupRedisAdaptertakes as its key): a node applies only its own deployment's events (once every deployment that shares the Valkey runs this version), and a Valkey'sdbdoes not separate pub/sub. docs/deploying.md has the wiring, what holds across nodes, what it costs, what happens when a node or Valkey stops answering, and a production checklist.
Collections and change topics
A collection is the rows of one service grouped by a scope value (design: section 7). The contract declares it; the service says whose policy authorizes a scope:
export const task = defineContract("taskService", {
describe: "Tasks on a project's board.",
entity: taskSchema,
projections: { card: cardSchema },
methods: { ...crud.contract({ entity: taskSchema, get: true }) },
collections: {
byProject: {
describe: "A project's open tasks, in board order.",
// a column holding the scope value
scope: "projectId",
// the projection each item is sent as
item: "card",
// membership: only open tasks
where: { status: "open" },
// ends in "id": the keyset cursor
order: [
["ordinal", "asc"],
["id", "asc"],
],
// sent for the whole scope
index: ["ordinal", "assigneeId"],
views: { mine: (row, who) => row.assigneeId === who.userId },
},
// each user's own
assigned: {
describe: "The tasks assigned to a user.",
scope: "assigneeId",
item: "card",
order: [["id", "asc"]],
},
},
});import { crud, inherit } from "@fitzzero/quickdraw-core/server";
export const taskService = qd.defineService(task, {
model: "task",
// derived from the anchor
access: inherit({ from: projectContract, via: "projectId" }),
collections: {
// Read on the project opens its scope
byProject: { anchor: projectContract },
// a user opens only the scope that is their id; its items still follow access above
assigned: { scopeAccess: "self" },
},
// opens the service topic to Read grants; closed without it
watchAccess: { service: "Read" },
methods: { ...crud.handlers(task, { access: { get: { entry: "Read" } } }) },
});scopeis a string column, orvia({ model, entry, scope })for scopes that come from a junction table (a chat in each member's list).orderends inid;limit(default 100) andmaxLimit(default 500) size its pages;whereis an equality filter on membership;accessis the level needed on the anchor (defaultRead).- A junction write adds or removes its entry in the one scope it links.
Over the item service's own
memberstable (amembersread of the policy, alone or insideanyOf, whoseentryis the via'sentryand whoseuseris the via'sscope), a link counts only when its role gives at least the collection'saccess: a role change across that line adds or removes the entry, and a link below it is in no page, count, index,qd:col:itemsor scoped search. When the item reads the junction (a chat'smemberCount), declarevia({ model, entry, scope, refreshEntry: true }): every junction write then also sends the entry again,updated, to each scope that still holds it, for one more read of the item per flush. qd:col:sub { s, c, scope }authorizes the scope through its anchor's policy, then answers a page and joins the scope's room; flushes sendqd:cdeltas to it (added,updated,patched,removed, orresetfor more thanbulkThresholdrows, default 200). A"self"scope is the subscriber's own user id: its items are stripped atRead, and it may not declare a higheraccess. On a service with an access policy its items still follow that policy: a page,qd:col:itemsand every flush hold only the rows its user may read atRead. A row the user loses goes outremoved, and a change to their membership of a parent row (or a reload of their grants) sendsreset, so the list loads again; a client that resumes the list after such a change reads a page. A change to a parent row's own access columns (a project's owner or access list) reaches the list only at the rows' next write or the list's next load.requires: { service: L }, besideanchororscopeAccess, also asks for a service-wide grant of at leastLon the collection's service, as its methods under{ service: L }do: both checks must pass, and a service-wideAdminpasses either. It is for a list whose methods need the grant,mine: { scopeAccess: "self", requires: { service: "Read" } }beside methods under{ service: "Read" }; a list whose rows its users read by their level on each row (assignedabove) takes none. Without the grant,qd:col:sub(cursor pages included), the scope's change topic and a search kept to the scope areFORBIDDEN. The grant comes from the socket's principal, never a read: when the user's grants reload below it (server.access.refresh, a tracked write of the grants column, on any node), each of their sockets leaves the scope withqd:revoked(reason: "access") and gets nothing more of it. A collection withoutrequiresis unchanged.- Items are visible to everyone in an anchored scope: no per-row policy or
field tier applies inside it. Derive the item service's own access from
the anchor (
inheritfrom it, as above): a per-row policy on the item service (an owner column, a row's access list) is not applied to an anchored scope's items, so a row it would hide still reaches everyone in its scope. A"self"scope is the exception: its items follow the item service's policy for its user. indexsends one small row per member ([id, rev, ...fields], up to 50,000) with the first page, so the client knows the whole membership and order at once;viewsare pure predicates over index rows the client runs. When a collection declaresindex, everyordercolumn butidmust be an index field.- A deleted anchor row (a project, for its tasks) closes its scopes with
qd:revoked;qd.collections.reset(contract, collection, scope)resets a scope after a change tracked writes cannot describe. qd:watch { s, topic }joins a change topic:{collection}:{scope}, authorized like a subscribe to that scope, orservice, which changes whenever any row of the service does, or a row of a model it lists inwrites(a game's high scores, which no service owns). A query declareswatch: "service"to be invalidated by it. A query over some of those models names them,watch: { service: ["gameScore"] }(typeServiceModelsWatch; the service'smodeland models in itswrites;defineServicerefuses others), and is invalidated only after a flush that wrote one of them: high scores are not read again when a chat membership the same service writes changes. It is the same topic: itsqd:changedframe names the models that changed it (models). The service topic is closed (FORBIDDEN) unless the service declareswatchAccess("public","authenticated"or{ service: level }). A watcher that loses access leaves the topic after one lastqd:changed. A watch whose access changed while it was answered is authorized again before it joins the topic, with the socket's principal as it is then, and answeredFORBIDDENwhen it lost access; it hears nothing until it joins. Entity and collection subscribes re-check the same way, with the grants the socket holds then (a grant lowered mid-subscribe denies, a raised one answers at its level), but from inside their room, which they need to catch every change after the snapshot
