nowity 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +751 -0
- package/dist/api/contract.d.ts +186 -0
- package/dist/api/contract.d.ts.map +1 -0
- package/dist/api/contract.js +251 -0
- package/dist/api/errors.d.ts +50 -0
- package/dist/api/errors.d.ts.map +1 -0
- package/dist/api/errors.js +50 -0
- package/dist/api/index.d.ts +13 -0
- package/dist/api/index.d.ts.map +1 -0
- package/dist/api/index.js +32 -0
- package/dist/client/confirmed-store.d.ts +33 -0
- package/dist/client/confirmed-store.d.ts.map +1 -0
- package/dist/client/confirmed-store.js +123 -0
- package/dist/client/connection.d.ts +102 -0
- package/dist/client/connection.d.ts.map +1 -0
- package/dist/client/connection.js +285 -0
- package/dist/client/list.d.ts +102 -0
- package/dist/client/list.d.ts.map +1 -0
- package/dist/client/list.js +257 -0
- package/dist/client/live-query.d.ts +153 -0
- package/dist/client/live-query.d.ts.map +1 -0
- package/dist/client/live-query.js +244 -0
- package/dist/client/nowity-client.d.ts +188 -0
- package/dist/client/nowity-client.d.ts.map +1 -0
- package/dist/client/nowity-client.js +580 -0
- package/dist/client/null-transport.d.ts +16 -0
- package/dist/client/null-transport.d.ts.map +1 -0
- package/dist/client/null-transport.js +17 -0
- package/dist/client/overlay.d.ts +44 -0
- package/dist/client/overlay.d.ts.map +1 -0
- package/dist/client/overlay.js +90 -0
- package/dist/client/query-source.d.ts +78 -0
- package/dist/client/query-source.d.ts.map +1 -0
- package/dist/client/query-source.js +57 -0
- package/dist/client/ssr-source.d.ts +70 -0
- package/dist/client/ssr-source.d.ts.map +1 -0
- package/dist/client/ssr-source.js +134 -0
- package/dist/client/transport.d.ts +19 -0
- package/dist/client/transport.d.ts.map +1 -0
- package/dist/client/transport.js +2 -0
- package/dist/client/ws-transport.d.ts +30 -0
- package/dist/client/ws-transport.d.ts.map +1 -0
- package/dist/client/ws-transport.js +89 -0
- package/dist/client.d.ts +47 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +80 -0
- package/dist/core/diff.d.ts +14 -0
- package/dist/core/diff.d.ts.map +1 -0
- package/dist/core/diff.js +56 -0
- package/dist/core/normalize.d.ts +16 -0
- package/dist/core/normalize.d.ts.map +1 -0
- package/dist/core/normalize.js +67 -0
- package/dist/core/protocol.d.ts +215 -0
- package/dist/core/protocol.d.ts.map +1 -0
- package/dist/core/protocol.js +14 -0
- package/dist/core/ssr-bridge.d.ts +69 -0
- package/dist/core/ssr-bridge.d.ts.map +1 -0
- package/dist/core/ssr-bridge.js +40 -0
- package/dist/core/types.d.ts +96 -0
- package/dist/core/types.d.ts.map +1 -0
- package/dist/core/types.js +17 -0
- package/dist/index.d.ts +47 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +98 -0
- package/dist/ironbean/client.d.ts +7 -0
- package/dist/ironbean/client.d.ts.map +1 -0
- package/dist/ironbean/client.js +38 -0
- package/dist/ironbean/server.d.ts +42 -0
- package/dist/ironbean/server.d.ts.map +1 -0
- package/dist/ironbean/server.js +62 -0
- package/dist/ironbean/tokens.d.ts +26 -0
- package/dist/ironbean/tokens.d.ts.map +1 -0
- package/dist/ironbean/tokens.js +23 -0
- package/dist/next/config.d.ts +7 -0
- package/dist/next/config.d.ts.map +1 -0
- package/dist/next/config.js +77 -0
- package/dist/next/live.d.ts +69 -0
- package/dist/next/live.d.ts.map +1 -0
- package/dist/next/live.js +70 -0
- package/dist/next/serve.d.ts +44 -0
- package/dist/next/serve.d.ts.map +1 -0
- package/dist/next/serve.js +107 -0
- package/dist/next/server.d.ts +62 -0
- package/dist/next/server.d.ts.map +1 -0
- package/dist/next/server.js +127 -0
- package/dist/react/connection-context.d.ts +4 -0
- package/dist/react/connection-context.d.ts.map +1 -0
- package/dist/react/connection-context.js +28 -0
- package/dist/react/grid-list.d.ts +34 -0
- package/dist/react/grid-list.d.ts.map +1 -0
- package/dist/react/grid-list.js +62 -0
- package/dist/react/hydrate.d.ts +22 -0
- package/dist/react/hydrate.d.ts.map +1 -0
- package/dist/react/hydrate.js +18 -0
- package/dist/react/index.d.ts +35 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +51 -0
- package/dist/react/list.d.ts +31 -0
- package/dist/react/list.d.ts.map +1 -0
- package/dist/react/list.js +35 -0
- package/dist/react/prerendered.d.ts +33 -0
- package/dist/react/prerendered.d.ts.map +1 -0
- package/dist/react/prerendered.js +165 -0
- package/dist/react/provider.d.ts +64 -0
- package/dist/react/provider.d.ts.map +1 -0
- package/dist/react/provider.js +130 -0
- package/dist/react/refusals.d.ts +31 -0
- package/dist/react/refusals.d.ts.map +1 -0
- package/dist/react/refusals.js +51 -0
- package/dist/react/restricted.d.ts +76 -0
- package/dist/react/restricted.d.ts.map +1 -0
- package/dist/react/restricted.js +126 -0
- package/dist/react/use-list.d.ts +42 -0
- package/dist/react/use-list.d.ts.map +1 -0
- package/dist/react/use-list.js +56 -0
- package/dist/react/use-query.d.ts +66 -0
- package/dist/react/use-query.d.ts.map +1 -0
- package/dist/react/use-query.js +126 -0
- package/dist/react/virtual.d.ts +60 -0
- package/dist/react/virtual.d.ts.map +1 -0
- package/dist/react/virtual.js +131 -0
- package/dist/server/api/auth.d.ts +37 -0
- package/dist/server/api/auth.d.ts.map +1 -0
- package/dist/server/api/auth.js +54 -0
- package/dist/server/api/bridge.d.ts +28 -0
- package/dist/server/api/bridge.d.ts.map +1 -0
- package/dist/server/api/bridge.js +330 -0
- package/dist/server/api/collector.d.ts +25 -0
- package/dist/server/api/collector.d.ts.map +1 -0
- package/dist/server/api/collector.js +184 -0
- package/dist/server/api/configure.d.ts +31 -0
- package/dist/server/api/configure.d.ts.map +1 -0
- package/dist/server/api/configure.js +67 -0
- package/dist/server/api/execution.d.ts +77 -0
- package/dist/server/api/execution.d.ts.map +1 -0
- package/dist/server/api/execution.js +97 -0
- package/dist/server/api/list.d.ts +141 -0
- package/dist/server/api/list.d.ts.map +1 -0
- package/dist/server/api/list.js +281 -0
- package/dist/server/api/prerender.d.ts +32 -0
- package/dist/server/api/prerender.d.ts.map +1 -0
- package/dist/server/api/prerender.js +69 -0
- package/dist/server/api/read-keys.d.ts +128 -0
- package/dist/server/api/read-keys.d.ts.map +1 -0
- package/dist/server/api/read-keys.js +464 -0
- package/dist/server/api/read-set.d.ts +103 -0
- package/dist/server/api/read-set.d.ts.map +1 -0
- package/dist/server/api/read-set.js +210 -0
- package/dist/server/api/runtime.d.ts +36 -0
- package/dist/server/api/runtime.d.ts.map +1 -0
- package/dist/server/api/runtime.js +49 -0
- package/dist/server/api/tracked-client.d.ts +6 -0
- package/dist/server/api/tracked-client.d.ts.map +1 -0
- package/dist/server/api/tracked-client.js +56 -0
- package/dist/server/change-source/change-source.d.ts +41 -0
- package/dist/server/change-source/change-source.d.ts.map +1 -0
- package/dist/server/change-source/change-source.js +2 -0
- package/dist/server/change-source/outbox-change-source.d.ts +106 -0
- package/dist/server/change-source/outbox-change-source.d.ts.map +1 -0
- package/dist/server/change-source/outbox-change-source.js +237 -0
- package/dist/server/change-source/wal-change-source.d.ts +85 -0
- package/dist/server/change-source/wal-change-source.d.ts.map +1 -0
- package/dist/server/change-source/wal-change-source.js +193 -0
- package/dist/server/db.d.ts +51 -0
- package/dist/server/db.d.ts.map +1 -0
- package/dist/server/db.js +53 -0
- package/dist/server/evaluate.d.ts +39 -0
- package/dist/server/evaluate.d.ts.map +1 -0
- package/dist/server/evaluate.js +61 -0
- package/dist/server/invalidation-index.d.ts +64 -0
- package/dist/server/invalidation-index.d.ts.map +1 -0
- package/dist/server/invalidation-index.js +0 -0
- package/dist/server/mutator.d.ts +59 -0
- package/dist/server/mutator.d.ts.map +1 -0
- package/dist/server/mutator.js +77 -0
- package/dist/server/query.d.ts +113 -0
- package/dist/server/query.d.ts.map +1 -0
- package/dist/server/query.js +35 -0
- package/dist/server/setup.d.ts +30 -0
- package/dist/server/setup.d.ts.map +1 -0
- package/dist/server/setup.js +107 -0
- package/dist/server/sql/setup.sql +215 -0
- package/dist/server/ssr.d.ts +29 -0
- package/dist/server/ssr.d.ts.map +1 -0
- package/dist/server/ssr.js +43 -0
- package/dist/server/sync-engine.d.ts +256 -0
- package/dist/server/sync-engine.d.ts.map +1 -0
- package/dist/server/sync-engine.js +805 -0
- package/dist/server/ws-server.d.ts +56 -0
- package/dist/server/ws-server.d.ts.map +1 -0
- package/dist/server/ws-server.js +241 -0
- package/package.json +81 -0
package/README.md
ADDED
|
@@ -0,0 +1,751 @@
|
|
|
1
|
+
# Nowity
|
|
2
|
+
|
|
3
|
+
A realtime framework over PostgreSQL, Ironbean and Next. Postgres is the source of
|
|
4
|
+
truth, changes reach the browser as field-level patches batched per transaction,
|
|
5
|
+
and the browser holds **live MobX objects** instead of JSON snapshots.
|
|
6
|
+
|
|
7
|
+
An endpoint is a method on a class. The class is the dependency token on both
|
|
8
|
+
sides — the server resolves it to the implementation, the browser to a proxy over
|
|
9
|
+
the socket — and a component reads it by calling it:
|
|
10
|
+
`useQuerySuspense(DocumentApi).byProject(id)`.
|
|
11
|
+
|
|
12
|
+
```
|
|
13
|
+
PostgreSQL → change stream → sync engine (queries + permissions) → WebSocket
|
|
14
|
+
→ confirmed store + pending mutations → MobX identity map → UI
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Implements the design in *Realtime objektový model (Postgres + MobX)*, including
|
|
18
|
+
the review section that supersedes the original sketch. All eleven acceptance
|
|
19
|
+
scenarios from §8 of that document run as tests against a real PostgreSQL.
|
|
20
|
+
|
|
21
|
+
## Quick start
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
docker compose up -d # PostgreSQL with wal_level=logical and wal2json
|
|
25
|
+
npm install
|
|
26
|
+
npm run db:push # push the demo Prisma schema
|
|
27
|
+
npm run prisma:generate # both delegate to example-next, where the schema lives
|
|
28
|
+
npm run example # end-to-end demo, prints what a UI observer sees
|
|
29
|
+
npx ts-node -P tsconfig.test.json example/contract-demo.ts # the class-based API
|
|
30
|
+
npm test # 137 tests, including all 11 acceptance scenarios
|
|
31
|
+
npm run perf # fan-out cost against a real database, before and after
|
|
32
|
+
|
|
33
|
+
cd example-next && npm run dev # http://localhost:3000/projects/demo?user=u-alice
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
`DATABASE_URL` defaults to `postgres://postgres:postgres@127.0.0.1:5432/mydb`.
|
|
37
|
+
|
|
38
|
+
## The five ideas
|
|
39
|
+
|
|
40
|
+
**1. The unit of subscription is a query, not a row.** A client subscribes to the
|
|
41
|
+
result of a query. A row that *enters* or *leaves* that result is handled by
|
|
42
|
+
construction — which a per-entity subscription cannot express at all, since none of
|
|
43
|
+
the data already in the result changed.
|
|
44
|
+
|
|
45
|
+
**2. The permission check lives inside the query.** There is no "permission filter"
|
|
46
|
+
stage between the database and the socket. A query a user may not see returns no
|
|
47
|
+
rows, so every recomputation is correct by construction rather than by remembering
|
|
48
|
+
to filter.
|
|
49
|
+
|
|
50
|
+
**3. Permission changes are invalidations, never data.** Nothing in `Document`
|
|
51
|
+
changes when someone is removed from a project, so there is no data event to fan
|
|
52
|
+
out. A change in a permission table bumps that scope's **epoch**, which drops and
|
|
53
|
+
recomputes the affected subscriptions. Recompute, not delete — the same mechanism
|
|
54
|
+
has to make *gaining* access work.
|
|
55
|
+
|
|
56
|
+
**4. Patches travel per transaction.** One message per database transaction,
|
|
57
|
+
applied inside one MobX action, so no observer can see money debited from one
|
|
58
|
+
account and not yet credited to the other.
|
|
59
|
+
|
|
60
|
+
**5. Writes are named mutators, run twice.** Once optimistically on the client,
|
|
61
|
+
once authoritatively on the server. The client keeps unconfirmed mutations in a
|
|
62
|
+
queue and replays them on top of confirmed data after every server message. That
|
|
63
|
+
one mechanism gives optimistic updates, rollback of refused writes, and immunity to
|
|
64
|
+
the echo of your own write.
|
|
65
|
+
|
|
66
|
+
## Usage
|
|
67
|
+
|
|
68
|
+
An endpoint is a method. The class it lives on is the dependency token, and it is
|
|
69
|
+
the same token on both sides — the server binds its implementation to it, the
|
|
70
|
+
browser binds a proxy over the socket.
|
|
71
|
+
|
|
72
|
+
### The contract, shared by both halves
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
import { contract } from "nowity/api";
|
|
76
|
+
import type { DocumentApiImpl } from "./server/document-api";
|
|
77
|
+
|
|
78
|
+
export const DocumentApi = contract<DocumentApiImpl>("documents");
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
One line, and the signatures are not in it — they come from the implementation
|
|
82
|
+
through a type-only import, which is erased, so nothing of the server follows it
|
|
83
|
+
into the bundle. Writing them out a second time would only create somewhere for
|
|
84
|
+
them to drift.
|
|
85
|
+
|
|
86
|
+
`DocumentApi` is a real class at runtime, so it works as a dependency token
|
|
87
|
+
exactly as a hand-written abstract class would. The name is explicit because it
|
|
88
|
+
is the wire identity of the service, and a class name does not survive a
|
|
89
|
+
production build.
|
|
90
|
+
|
|
91
|
+
### Server
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
import { component } from "ironbean";
|
|
95
|
+
import { api, Forbidden, Rejected, mutation, query } from "nowity/api";
|
|
96
|
+
import { DocumentApi } from "./contract";
|
|
97
|
+
import { Session } from "nowity";
|
|
98
|
+
|
|
99
|
+
@api(DocumentApi)
|
|
100
|
+
@component
|
|
101
|
+
export class DocumentApiImpl {
|
|
102
|
+
constructor(
|
|
103
|
+
private readonly db: Db, // class Db extends PrismaClient {}
|
|
104
|
+
private readonly session: Session,
|
|
105
|
+
) {}
|
|
106
|
+
|
|
107
|
+
@query()
|
|
108
|
+
async byProject(projectId: string) {
|
|
109
|
+
const member = await this.db.projectMember.findFirst({
|
|
110
|
+
where: { projectId, userId: this.session.requireUserId() },
|
|
111
|
+
});
|
|
112
|
+
if (!member) throw new Forbidden("Not a member of this project");
|
|
113
|
+
|
|
114
|
+
return this.db.document.findMany({
|
|
115
|
+
where: { projectId },
|
|
116
|
+
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
@mutation()
|
|
121
|
+
async rename(id: string, title: string) {
|
|
122
|
+
if (!title.trim()) throw new Rejected("Title must not be empty");
|
|
123
|
+
await this.db.document.update({ where: { id }, data: { title } });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
Nothing declares what invalidates what. `byProject` read `ProjectMember` to decide
|
|
129
|
+
whether the caller may look and `Document` to answer, and both land in the
|
|
130
|
+
subscription's dependency set — recorded while the query ran, from the arguments
|
|
131
|
+
it passed to Prisma. Deleting the membership row changes no document at all, and
|
|
132
|
+
still empties the list.
|
|
133
|
+
|
|
134
|
+
That the read set comes from the *arguments* rather than from the rows that came
|
|
135
|
+
back is what makes it work for permissions: a non-member reads `ProjectMember`
|
|
136
|
+
and finds nothing, but `ProjectMember` is in the set all the same, so being added
|
|
137
|
+
to the project later wakes the subscription up. There is nothing to declare and
|
|
138
|
+
nothing to keep in sync.
|
|
139
|
+
|
|
140
|
+
The same arguments say which *rows* were read, and that is what keeps the cost of
|
|
141
|
+
a change from growing with the number of people watching. `byProject` did not
|
|
142
|
+
read `Document`, it read the documents whose `projectId` is this one, so a write
|
|
143
|
+
in another project never reaches this subscription — it is not recomputed and
|
|
144
|
+
found unchanged, it is not considered at all. Equalities narrow (`where`, `in`,
|
|
145
|
+
compound uniques, relation filters through `some` and `is`); everything else —
|
|
146
|
+
ranges, `contains`, `NOT`, a `mode: "insensitive"`, an operator a later Prisma
|
|
147
|
+
release adds — falls back to watching the table whole, which is exactly what the
|
|
148
|
+
engine did before and is never wrong, only slower. A conjunction needs just one
|
|
149
|
+
narrowable side to stay narrow, so a single unrecognised operator costs its own
|
|
150
|
+
contribution and not the query's.
|
|
151
|
+
|
|
152
|
+
Measured on the demo's tic-tac-toe, with `npm run perf`:
|
|
153
|
+
|
|
154
|
+
| games, each watched by its two players | evaluations per move | fan-out per move |
|
|
155
|
+
| --- | --- | --- |
|
|
156
|
+
| 25 | 2 (was 50) | 2.1ms (was 17ms) |
|
|
157
|
+
| 100 | 2 (was 200) | 2.4ms (was 70ms) |
|
|
158
|
+
| 200 | 2 (was 400) | 2.1ms (was 132ms) |
|
|
159
|
+
|
|
160
|
+
A move used to cost one query re-execution per open game, so the total cost of a
|
|
161
|
+
room full of games grew with their square. It now costs two, whatever else the
|
|
162
|
+
process is doing, and a move reaches the opponent in 13ms at 200 concurrent games
|
|
163
|
+
where it used to take 114ms.
|
|
164
|
+
|
|
165
|
+
What stays explicit is what nothing can derive — the database, and a class to
|
|
166
|
+
inject it by:
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
export const nowity = createNowityServer({
|
|
170
|
+
prisma,
|
|
171
|
+
db: Db,
|
|
172
|
+
auth: CookieAuth,
|
|
173
|
+
services: [DocumentApiImpl, ProjectApiImpl],
|
|
174
|
+
});
|
|
175
|
+
await nowity.start();
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
`auth` is an {@link Authenticator} implementation, not a callback: authentication
|
|
179
|
+
is rarely a pure function of the request — it wants a session store, a token
|
|
180
|
+
verifier, a clock — so it is a class in the container like everything else. The
|
|
181
|
+
upgrade is an ordinary request on the application's own origin, so its cookie is
|
|
182
|
+
the session cookie the pages already use.
|
|
183
|
+
|
|
184
|
+
The schema is read from the Prisma client, which already carries it, and the
|
|
185
|
+
change source defaults to the outbox on `DATABASE_URL`.
|
|
186
|
+
|
|
187
|
+
`services` does nothing a decorator has not already done — a class registers
|
|
188
|
+
itself the moment its module is evaluated. What the list buys is that the import
|
|
189
|
+
is a real one, visible in the file rather than a side effect, and checked: a
|
|
190
|
+
class listed without `@api` fails at startup instead of at the first call.
|
|
191
|
+
|
|
192
|
+
### Client
|
|
193
|
+
|
|
194
|
+
```ts
|
|
195
|
+
const documents = getBaseApplicationContext().getBean(DocumentApi);
|
|
196
|
+
const rows = await documents.byProject(projectId); // DocumentRow[], live
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
The same line the server runs, resolving to a proxy instead of an
|
|
200
|
+
implementation, and the same signature: `byProject` returns `Promise<Document[]>`
|
|
201
|
+
on both sides. What differs is that the objects in the array are live — the array
|
|
202
|
+
gains and loses rows, MobX tracks the fields, and `documents.rename(id, title)`
|
|
203
|
+
is an ordinary call that rejects if the server refuses it.
|
|
204
|
+
|
|
205
|
+
Acquisition is asynchronous, so the two things a `status` field would carry are
|
|
206
|
+
not in the result at all: "not there yet" is a pending promise, "not allowed" is
|
|
207
|
+
a rejected one.
|
|
208
|
+
|
|
209
|
+
### React
|
|
210
|
+
|
|
211
|
+
```tsx
|
|
212
|
+
// app/layout.tsx
|
|
213
|
+
<NowityProvider>{children}</NowityProvider>
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
One provider, at the root, with nothing to pass it. The socket is served by the
|
|
217
|
+
page's own origin, so there is no address to configure, and *who* is connecting
|
|
218
|
+
comes from the request — the upgrade carries the session cookie like any other
|
|
219
|
+
request on that origin. The per-device id keeps itself in `localStorage`.
|
|
220
|
+
|
|
221
|
+
A page that read its queries on the server hands over what it read:
|
|
222
|
+
`<NowityProvider hydrate={hydration}>` applies `prerender`'s payloads during its
|
|
223
|
+
own render, before anything below it can ask, so the first paint has the rows
|
|
224
|
+
instead of a fallback that resolves into them.
|
|
225
|
+
|
|
226
|
+
Below it:
|
|
227
|
+
|
|
228
|
+
```tsx
|
|
229
|
+
const Documents = observer(({ projectId }: { projectId: string }) => {
|
|
230
|
+
const rows = useQuerySuspense(DocumentApi).byProject(projectId);
|
|
231
|
+
|
|
232
|
+
return <ul>{rows.map((row) => <Row key={row.id} row={row} />)}</ul>;
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
<Live fallback={<Spinner />}>
|
|
236
|
+
<Restricted fallback={<p>No access to this project.</p>}>
|
|
237
|
+
<Documents projectId={id} />
|
|
238
|
+
</Restricted>
|
|
239
|
+
</Live>
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
The hook hands back the contract, so reading is the call the server implements —
|
|
243
|
+
same method, same arguments, same types, and nothing in between to name a query
|
|
244
|
+
twice. Writing is the same contract without the hook's opinions:
|
|
245
|
+
|
|
246
|
+
```tsx
|
|
247
|
+
const documents = useService(DocumentApi);
|
|
248
|
+
<button onClick={() => documents.rename(row.id, draft)}>Save</button>
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
`useService` is `getBean(DocumentApi)` — the provider binds every contract into
|
|
252
|
+
the browser's container as a singleton, so a component and a service that
|
|
253
|
+
injects one are talking to the same object.
|
|
254
|
+
|
|
255
|
+
Three things can be true of a query, and none of them is a value. **Not yet**
|
|
256
|
+
suspends. **Not allowed** throws `Forbidden`. **Broken** throws too. All three
|
|
257
|
+
are therefore fallbacks in one place instead of branches in every component that
|
|
258
|
+
reads data — a component says what it renders *with* data, and where the other
|
|
259
|
+
two are caught is a decision about the page.
|
|
260
|
+
|
|
261
|
+
`Restricted` is the boundary for the middle one, and it exists because an error
|
|
262
|
+
boundary alone cannot express it: they stay caught, while permissions are
|
|
263
|
+
granted as often as they are taken away. So a refusal from a live query carries
|
|
264
|
+
the way out. The subscription stays registered and denied, watching the very
|
|
265
|
+
table that would grant access, and the boundary waits on it and un-catches
|
|
266
|
+
itself the moment the query is readable again — add someone to a project and
|
|
267
|
+
their open page fills in. Anything that is not a refusal is rethrown for the
|
|
268
|
+
next boundary up, because a broken query is a fault and this is not where faults
|
|
269
|
+
are handled. `fallback` may be a function, which is handed the refusal: its
|
|
270
|
+
message is whatever the endpoint said when it threw.
|
|
271
|
+
|
|
272
|
+
Server rendering is where this gets interesting, because React has no error
|
|
273
|
+
boundaries there at all: its streaming renderer has no commit phase, so a
|
|
274
|
+
component that throws takes the nearest **Suspense** boundary with it and that
|
|
275
|
+
part of the page is marked "render this again in the browser". Nothing above the
|
|
276
|
+
throw can help either — the renderer retries the component that suspended, never
|
|
277
|
+
its ancestors.
|
|
278
|
+
|
|
279
|
+
So `Restricted` carries its own `<Suspense>`, and the refusal is left on a baton
|
|
280
|
+
the boundary's fallback picks up: the fallback of a boundary that errored *is*
|
|
281
|
+
rendered, and does go into the HTML. A refused panel therefore still paints "no
|
|
282
|
+
access" from the first byte, and the damage stops at that panel instead of
|
|
283
|
+
costing the page its prerender. When what happened was an ordinary wait rather
|
|
284
|
+
than a refusal, that fallback suspends in turn on the query's own promise, which
|
|
285
|
+
hands the subtree to the next boundary up — so `<Live>`'s spinner is still what a
|
|
286
|
+
slow query shows.
|
|
287
|
+
|
|
288
|
+
Two costs, both honest. The refused panel is re-rendered in the browser after
|
|
289
|
+
hydration, since React marked it so; the content is the same either way. And
|
|
290
|
+
React reports every throw during a server render to `onError`, boundaried or
|
|
291
|
+
not, so a page with a panel the caller may not see logs a `Forbidden`
|
|
292
|
+
server-side. It is noise, not a failure.
|
|
293
|
+
|
|
294
|
+
`Live` is a `<Suspense>` boundary that also answers what the components under it
|
|
295
|
+
read, and it is not decoration: a live query has no socket to resolve against
|
|
296
|
+
while the server renders, so a plain `<Suspense>` leaves React holding the
|
|
297
|
+
boundary open and the response never finishes. Under Next it is a server
|
|
298
|
+
component and reads from the database — [below](#nextjs).
|
|
299
|
+
|
|
300
|
+
Which gives the one rule the framework asks for: **anything that reads live data
|
|
301
|
+
has a `Live` above it.** It is a server component, so that means a page or a
|
|
302
|
+
layout, and a layout carries its own for the chrome around the page — a nav that
|
|
303
|
+
reads sits outside the page's boundary. A `Live` that reads nothing costs
|
|
304
|
+
nothing; it does not even open a transaction.
|
|
305
|
+
|
|
306
|
+
Below it, `"use client"` changes nothing. The subtree reads through the render's
|
|
307
|
+
snapshot whichever kind of component asks, so a client island is prerendered like
|
|
308
|
+
anything else. An island that only mounts *after* hydration — a dialog, a tab —
|
|
309
|
+
was never part of the server's render, and a plain `<Suspense>` is all it needs
|
|
310
|
+
to draw its own waiting rather than replacing the page with the page's fallback.
|
|
311
|
+
|
|
312
|
+
### Collections
|
|
313
|
+
|
|
314
|
+
A list of five thousand rows is the same statement about what the caller may see
|
|
315
|
+
as a list of five. What differs is that nobody receives it. So the endpoint says
|
|
316
|
+
what the collection is, and takes no paging at all:
|
|
317
|
+
|
|
318
|
+
```ts
|
|
319
|
+
@list()
|
|
320
|
+
async all(projectId: string) {
|
|
321
|
+
await this.assertMember(projectId);
|
|
322
|
+
return this.db.document.findMany({
|
|
323
|
+
where: { projectId },
|
|
324
|
+
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
Which rows matter is a fact about a scrollbar, and it changes several times a
|
|
330
|
+
second — so it belongs to the browser, and the window is pushed in from outside.
|
|
331
|
+
The framework runs the method as written and puts `LIMIT` and `OFFSET` into the
|
|
332
|
+
one call that produces the collection, which is its last `findMany`. Everything
|
|
333
|
+
before it — the membership lookup that decides whether the caller may look —
|
|
334
|
+
runs untouched and lands in the read set as usual.
|
|
335
|
+
|
|
336
|
+
A window is therefore an ordinary live query: it re-runs when a table it read
|
|
337
|
+
changes, and the browser gets a patch for the rows it is actually showing.
|
|
338
|
+
|
|
339
|
+
```tsx
|
|
340
|
+
const documents = useList(DocumentApi).all(projectId);
|
|
341
|
+
|
|
342
|
+
<GridList of={documents} itemHeight={78} minItemWidth={200} gap={12}>
|
|
343
|
+
{(row) => (row ? <Card row={row} /> : <Skeleton />)}
|
|
344
|
+
</GridList>
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
`useList` hands back a store rather than rows, because rows are what it cannot
|
|
348
|
+
hand back: `documents.total` is how many there are, `documents.at(i)` is the one
|
|
349
|
+
at an index — or `undefined`, which is a cell whose window has not arrived and
|
|
350
|
+
is what the skeleton is for. Asking is subscribing. Windows are quantised to a
|
|
351
|
+
page size, so scrolling asks for the same few subscriptions over and over
|
|
352
|
+
instead of a new one per pixel, and a window that leaves the screen is released.
|
|
353
|
+
|
|
354
|
+
`GridList` owns the geometry — how tall a row is, how many fit across, which of
|
|
355
|
+
them exist — and nothing else; the item is styled by whoever renders it. Each
|
|
356
|
+
cell is its own `observer`, so a row edited by someone else re-renders that cell
|
|
357
|
+
and nothing around it.
|
|
358
|
+
|
|
359
|
+
`List` is the same component for one item per row, which is the shape that has
|
|
360
|
+
nothing to divide and therefore no width to wait for:
|
|
361
|
+
|
|
362
|
+
```tsx
|
|
363
|
+
const scores = useList(ScoreApi).all();
|
|
364
|
+
|
|
365
|
+
<List of={scores} itemHeight={44} height={600}>
|
|
366
|
+
{(row, index) => (row ? <Row score={row} /> : <Skeleton rank={index + 1} />)}
|
|
367
|
+
</List>
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
They are one implementation with two faces — the difference is a single function,
|
|
371
|
+
how many fit across, which for a list is one. Everything below is true of both.
|
|
372
|
+
|
|
373
|
+
On a server there is no viewport, so it renders its opening screenful — and
|
|
374
|
+
*waits* for it rather than drawing placeholders, because that render is the HTML
|
|
375
|
+
and a skeleton in it is not a moment before anything. It is also what the browser
|
|
376
|
+
hydrates against: a placeholder in the markup and a row in the store is the
|
|
377
|
+
mismatch React refuses, and the row is what both of them should have had. So the
|
|
378
|
+
first window is in the HTML, and only what nobody has scrolled to yet is a
|
|
379
|
+
skeleton.
|
|
380
|
+
|
|
381
|
+
The two things that make a collection affordable are that the wire never carries
|
|
382
|
+
more than one window, and that a row nobody is looking at is not watched at all.
|
|
383
|
+
A hundred thousand rows cost three subscriptions.
|
|
384
|
+
|
|
385
|
+
A collection ordered by something people edit needs one more thing: a row
|
|
386
|
+
changed here has to *move* here, not a round trip later. So the window carries
|
|
387
|
+
the collection's `orderBy` — read off the query the endpoint already wrote, sent
|
|
388
|
+
as data — and the browser places a locally changed row by it, for as long as the
|
|
389
|
+
write is unconfirmed. Nothing on the client restates the ordering, and nothing
|
|
390
|
+
sorts in the settled state: the server's order is used exactly as it arrived.
|
|
391
|
+
|
|
392
|
+
The same two facts place a row *created* here. It exists in the identity map and
|
|
393
|
+
in no result's id list — only the server puts an id in one — so the window
|
|
394
|
+
claims it: the filter says whether it belongs to the collection, and the
|
|
395
|
+
window's own first and last rows say whether it belongs to this slice of it.
|
|
396
|
+
Exactly one window claims it, so the collection gains one row rather than one
|
|
397
|
+
per window that happens to be open, and the rows behind it move down. A row
|
|
398
|
+
deleted here closes its gap the same way.
|
|
399
|
+
|
|
400
|
+
What the browser cannot derive is what a write *does*, because a mutation's body
|
|
401
|
+
is server code and never reaches the bundle. That is a `ClientMutatorDef`, and
|
|
402
|
+
it is the only part written twice:
|
|
403
|
+
|
|
404
|
+
```ts
|
|
405
|
+
{ name: "scores.add", local: ([id, delta], tx) => {
|
|
406
|
+
const row = tx.get("Score", id);
|
|
407
|
+
if (row) tx.update("Score", id, { points: row.points + delta });
|
|
408
|
+
} }
|
|
409
|
+
```
|
|
410
|
+
|
|
411
|
+
Rollback of a refused write and reconciliation with the confirmed one need no
|
|
412
|
+
code at all — that is what the rebase is.
|
|
413
|
+
|
|
414
|
+
The first execution of an endpoint is a *probe*: the method runs with every
|
|
415
|
+
query it makes capped to a single row, purely to find where its collection is.
|
|
416
|
+
The answer is thrown away and the position is kept, so finding out how not to
|
|
417
|
+
read the collection never costs reading it.
|
|
418
|
+
|
|
419
|
+
`observer` is what makes the tracking field-level: renaming one document
|
|
420
|
+
re-renders one `<Row>`, not the list. Subscriptions are shared by arguments and
|
|
421
|
+
released a moment after the last component stops holding one, which is also what
|
|
422
|
+
collects a render that Suspense threw away before its effects ever ran.
|
|
423
|
+
|
|
424
|
+
Call the endpoints during render, unconditionally, the way a hook is called:
|
|
425
|
+
each call is a subscription, and React needs those in the same order every time.
|
|
426
|
+
|
|
427
|
+
### Next.js
|
|
428
|
+
|
|
429
|
+
The App Router cannot take over a connection for a WebSocket upgrade, but the
|
|
430
|
+
HTTP server underneath it can. A custom server puts pages and socket on one port:
|
|
431
|
+
|
|
432
|
+
```ts
|
|
433
|
+
// server.ts — plain Node, never bundled
|
|
434
|
+
import { serveNext } from "nowity/next/serve";
|
|
435
|
+
|
|
436
|
+
serveNext({ prisma, db: Db, authenticate });
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
Nowity takes the upgrades on its own path and leaves every other one alone, so
|
|
440
|
+
the dev server's hot reload keeps working on the same port. The Next config it
|
|
441
|
+
needs comes from `withNowity()`, because `pg` and `ws` must stay external and
|
|
442
|
+
`serverExternalPackages` does not reach a library linked from above the app root.
|
|
443
|
+
|
|
444
|
+
Inside Next itself only the read half is needed, and `createNextNowity` provides
|
|
445
|
+
it:
|
|
446
|
+
|
|
447
|
+
```ts
|
|
448
|
+
export const nowity = createNextNowity(nowityConfig);
|
|
449
|
+
```
|
|
450
|
+
|
|
451
|
+
A page says where its live queries are read, and nothing more:
|
|
452
|
+
|
|
453
|
+
```tsx
|
|
454
|
+
<Live fallback={<Spinner />} as={user}>
|
|
455
|
+
<Documents projectId={id} />
|
|
456
|
+
<Membership projectId={id} />
|
|
457
|
+
</Live>
|
|
458
|
+
```
|
|
459
|
+
|
|
460
|
+
`Live` is a server component, which is what lets it be both above the components
|
|
461
|
+
that read and inside the request that knows who is asking. It opens one snapshot
|
|
462
|
+
for the render and answers whatever the components ask for, as they ask for it —
|
|
463
|
+
so nothing above them lists their queries, and a query added three levels down is
|
|
464
|
+
prerendered because the list is the render's own behaviour rather than a
|
|
465
|
+
declaration to keep in sync. What they asked for leaves with the page and seeds
|
|
466
|
+
the store before the socket is up.
|
|
467
|
+
|
|
468
|
+
Who the page renders for comes from the application's `Authenticator` — the same
|
|
469
|
+
class the socket asks, given this request's own headers — so a page and its
|
|
470
|
+
socket cannot disagree about who is looking. `as` says it outright, for an
|
|
471
|
+
application that has no session to read.
|
|
472
|
+
|
|
473
|
+
Everything a render touches comes from that one snapshot, so two panels on a page
|
|
474
|
+
cannot come from two different points in time. A refusal comes through it too —
|
|
475
|
+
the sync engine's own — so "no access" is the first thing painted rather than an
|
|
476
|
+
empty list that turns into an error.
|
|
477
|
+
|
|
478
|
+
The rows are in the *shell* of the HTML, not streamed in behind it. React's
|
|
479
|
+
server does not wait for a Suspense boundary: it sends the fallback, then patches
|
|
480
|
+
the rows in afterwards with a script, and the finished markup looks the same
|
|
481
|
+
either way while the first paint is a spinner. So `Live` holds the shell open
|
|
482
|
+
until the render has its answers — the page waits for its own queries, which is
|
|
483
|
+
what prerendering them was for, and a page whose data is slow was never going to
|
|
484
|
+
paint sooner than its data. Anything the render asked for too late for that still
|
|
485
|
+
arrives, on the socket, like any other query.
|
|
486
|
+
|
|
487
|
+
`nowity.read(...)` is the hand-rolled version, for a page that wants the rows as
|
|
488
|
+
a value rather than on screen — metadata, a check — and hands the payloads to
|
|
489
|
+
`<NowityProvider hydrate={…}>` if the browser should start from them too. As a
|
|
490
|
+
way of prerendering a page it is the one `Live` replaced: the page has to keep
|
|
491
|
+
saying what it reads as the components below it change, and it fails by going
|
|
492
|
+
quietly back to a spinner rather than by breaking.
|
|
493
|
+
|
|
494
|
+
`example-next/` is a working application: server-rendered lists, optimistic
|
|
495
|
+
edits, access revoked and granted from the UI, and — at `/archive` — five
|
|
496
|
+
thousand documents in a grid that subscribes to the forty it is showing.
|
|
497
|
+
|
|
498
|
+
### Requirements
|
|
499
|
+
|
|
500
|
+
Ironbean is not optional — the framework is built on it — and it uses
|
|
501
|
+
TypeScript's legacy decorators, so an application needs `experimentalDecorators`,
|
|
502
|
+
`emitDecoratorMetadata`, and `reflect-metadata` imported once. Next is a peer
|
|
503
|
+
dependency too, for everything under `nowity/next`.
|
|
504
|
+
|
|
505
|
+
What the package exposes is the framework: `nowity`, `nowity/api`,
|
|
506
|
+
`nowity/react`, and the four `nowity/next` entry points. The engine underneath —
|
|
507
|
+
the change stream, the sync engine, the store, the wire protocol — has no entry
|
|
508
|
+
point of its own on purpose: it is what the framework is made of, not what an
|
|
509
|
+
application writes against.
|
|
510
|
+
|
|
511
|
+
### More than one sync process
|
|
512
|
+
|
|
513
|
+
A second instance is additive, and nothing has to be told about the first. Both
|
|
514
|
+
read the same outbox at their own pace, both write to the same tables, and
|
|
515
|
+
everything they must agree on is already in PostgreSQL: the mutation sequence is
|
|
516
|
+
a row with a lock on it, the authorization epoch is a table, and the outbox is a
|
|
517
|
+
log with a cursor per reader.
|
|
518
|
+
|
|
519
|
+
```ts
|
|
520
|
+
export const nowity = createNowityServer({
|
|
521
|
+
prisma,
|
|
522
|
+
db: Db,
|
|
523
|
+
auth: CookieAuth,
|
|
524
|
+
services: [DocumentApiImpl],
|
|
525
|
+
changeSource: () =>
|
|
526
|
+
new OutboxChangeSource({
|
|
527
|
+
pool,
|
|
528
|
+
// Stable per deployment slot, so a restart reclaims its own
|
|
529
|
+
// watermark instead of leaving it to age out.
|
|
530
|
+
consumerId: process.env.NODE_NAME,
|
|
531
|
+
// Only set on the instances that should collect. Any of them may.
|
|
532
|
+
pruneIntervalMs: 60_000,
|
|
533
|
+
}),
|
|
534
|
+
});
|
|
535
|
+
```
|
|
536
|
+
|
|
537
|
+
Three things follow from it being the database that coordinates:
|
|
538
|
+
|
|
539
|
+
- **Connections are sticky, but only for their lifetime.** A socket lives on one
|
|
540
|
+
instance; a client that reconnects elsewhere resends its subscriptions and
|
|
541
|
+
continues its mutation sequence from where the database says it got to.
|
|
542
|
+
- **A new instance starts from now.** It resumes at the transaction horizon
|
|
543
|
+
rather than replaying history, and its clients are still correct because a
|
|
544
|
+
subscription's first answer is a snapshot of the database, not a replay of the
|
|
545
|
+
stream.
|
|
546
|
+
- **Retention waits for the slowest live reader.** `nowity_prune_outbox` deletes
|
|
547
|
+
only what every consumer seen recently has passed. A consumer silent longer
|
|
548
|
+
than the staleness window is treated as gone, so set it well above any pause a
|
|
549
|
+
healthy process can take.
|
|
550
|
+
|
|
551
|
+
Scenario 22 runs two instances against one database and checks each of these.
|
|
552
|
+
|
|
553
|
+
### Escape hatches
|
|
554
|
+
|
|
555
|
+
`@query({ tables: [...] })` for a query that reads through something the tracker
|
|
556
|
+
cannot see, and `@query({ entity })` when the rows are not from the last model it
|
|
557
|
+
touched. A query whose read set comes out empty is revalidated on every
|
|
558
|
+
transaction rather than quietly stopping — not knowing what a query reads may
|
|
559
|
+
never mean not recomputing it.
|
|
560
|
+
|
|
561
|
+
`@list` takes the same options, and needs no others: when the framework cannot
|
|
562
|
+
push a window into a collection — the last `findMany` is not the one that
|
|
563
|
+
produced the rows, or it limits itself — the method is run whole and the window
|
|
564
|
+
is taken from what it returned. Not being able to page may never mean answering
|
|
565
|
+
with the wrong rows; it may only mean answering the slow way.
|
|
566
|
+
|
|
567
|
+
### Prisma
|
|
568
|
+
|
|
569
|
+
The tracking client is a Prisma extension, so query definitions run inside the
|
|
570
|
+
engine's snapshot and inside its write transactions. It also refuses a write
|
|
571
|
+
inside a `@query`: such a query is re-executed on every change to a table it
|
|
572
|
+
read, and a write hidden in one would fire again every time.
|
|
573
|
+
|
|
574
|
+
## Decisions taken (§5 of the design doc)
|
|
575
|
+
|
|
576
|
+
| Question | Decision |
|
|
577
|
+
|---|---|
|
|
578
|
+
| **§5.1** WAL or outbox | **Outbox + LISTEN/NOTIFY is the default.** WAL/wal2json is implemented behind the same `ChangeSource` interface for the case that matters — changes made outside the application. Both are tested. |
|
|
579
|
+
| **§5.2** library or product | **Library, but no longer framework-free.** The API is built on Ironbean and Prisma: the DI container is where a contract meets its implementation, and Prisma's schema is where invalidation dependencies and entity shapes come from. Transport and change capture stay behind interfaces. |
|
|
580
|
+
| **§5.3** permission granularity | **Row level.** Field-level projection is whatever the query selects; there is no per-field ACL. |
|
|
581
|
+
|
|
582
|
+
### Why the outbox is the default
|
|
583
|
+
|
|
584
|
+
Logical replication's one real advantage is seeing writes that did not go through
|
|
585
|
+
the application. Everything else about it is a liability: one slot feeds exactly one
|
|
586
|
+
consumer, WAL accumulates on the primary while the consumer is down, and slots do
|
|
587
|
+
not survive failover before PG17. The outbox needs none of that, and its trigger
|
|
588
|
+
sees the full `OLD` row — which the WAL does not, unless you opt into
|
|
589
|
+
`REPLICA IDENTITY FULL`.
|
|
590
|
+
|
|
591
|
+
### How the outbox reads without gaps
|
|
592
|
+
|
|
593
|
+
`bigserial` alone is not a usable cursor: sequence values are handed out before
|
|
594
|
+
commit, so ordering by `seq` can walk past a row whose transaction commits later,
|
|
595
|
+
and `seq > cursor` would then hide it forever. Every outbox row therefore also
|
|
596
|
+
stores `pg_current_xact_id()`, and the reader only consumes rows whose `xid` is
|
|
597
|
+
below `pg_snapshot_xmin(pg_current_snapshot())` — the oldest transaction still in
|
|
598
|
+
flight. That set is fully committed, immutable, and grows as a *prefix* of the `xid`
|
|
599
|
+
order, so a single `xid` is a complete bookmark.
|
|
600
|
+
|
|
601
|
+
The same property closes the snapshot/stream hole: subscriptions are snapshotted
|
|
602
|
+
only while the stream is quiesced at a known cursor, and everything at or below that
|
|
603
|
+
cursor had already finished, so it is guaranteed visible in the snapshot. Anything
|
|
604
|
+
invisible in the snapshot is above the cursor and gets streamed. Delivery is
|
|
605
|
+
at-least-once; because patches come from re-running the query and diffing, a replay
|
|
606
|
+
produces an empty diff, so the client observes exactly once.
|
|
607
|
+
|
|
608
|
+
## Known limitations
|
|
609
|
+
|
|
610
|
+
- **A long-running write transaction stalls the outbox stream** until it finishes
|
|
611
|
+
(read-only transactions do not — they never get an xid). Short transactions, which
|
|
612
|
+
is the normal case, are unaffected. This is the price of the gap-free cursor.
|
|
613
|
+
- **Incremental view maintenance is naive**: on a relevant change the query is
|
|
614
|
+
re-executed and its result diffed. Correct for any query, O(result size) per
|
|
615
|
+
change. Which subscriptions are *relevant* is now decided by row rather than by
|
|
616
|
+
table (see above), so what is left is one database round trip per subscription
|
|
617
|
+
the change could actually have altered — about 1.3ms each, and the dominant
|
|
618
|
+
term in every remaining measurement.
|
|
619
|
+
- **Change batches are not coalesced.** Each committed transaction gets its own
|
|
620
|
+
fan-out pass, including its own snapshot, even when fifty of them are already
|
|
621
|
+
queued. Merging what is waiting would save about a quarter of the wall time
|
|
622
|
+
under a burst (measured: 250 moves/s in `npm run perf -- throughput`), at the
|
|
623
|
+
cost of the change source's "one batch per transaction" contract. Not done:
|
|
624
|
+
the contract is relied on elsewhere, and the ratio does not justify it yet.
|
|
625
|
+
- **Read keys narrow by equality only.** A range, a `contains`, a `NOT` or a
|
|
626
|
+
case-insensitive comparison contributes no narrowing, and a query with nothing
|
|
627
|
+
else to go on watches its whole table. The cost is the pre-existing one; the
|
|
628
|
+
fallback exists so an unknown operator can never be a subscription that quietly
|
|
629
|
+
stops updating.
|
|
630
|
+
- **Values that do not survive the round trip are never keyed.** `DateTime`,
|
|
631
|
+
`BigInt`, `Decimal`, `Float`, `Bytes` and `Json` are compared as they appear in
|
|
632
|
+
a change event, and those forms do not reliably match the argument a `where`
|
|
633
|
+
was written with, so equality on them widens to the whole table. `String`,
|
|
634
|
+
`Int`, `Boolean` and enums narrow.
|
|
635
|
+
- **The WAL source narrows less than the outbox one.** A row *leaving* a filter
|
|
636
|
+
is only visible in the previous image, and logical replication carries the
|
|
637
|
+
primary key alone unless the table is set to `REPLICA IDENTITY FULL`. Without
|
|
638
|
+
it, an update is matched against every subscription filed under a non-key
|
|
639
|
+
column of that table — the old cost, confined to the columns that actually lost
|
|
640
|
+
information. The outbox trigger stores `to_jsonb(OLD)` and never has this
|
|
641
|
+
problem.
|
|
642
|
+
- **The WAL source cannot attribute writes** to a client or mutation
|
|
643
|
+
(`set_config` is not in the WAL), and it needs `REPLICA IDENTITY FULL` on
|
|
644
|
+
permission tables or a `DELETE` arrives as a bare primary key. The engine treats
|
|
645
|
+
an underivable scope as "revalidate everything" rather than skipping the
|
|
646
|
+
invalidation.
|
|
647
|
+
- **A method's entity is guessed from its last Prisma call.** Right for almost
|
|
648
|
+
every endpoint, wrong for one that ends with an unrelated lookup;
|
|
649
|
+
`@query({ entity })` settles it. Aggregates and scalars are not supported as
|
|
650
|
+
query results at all — a live query returns rows.
|
|
651
|
+
- **A revoked query logs to the console in development.** React deliberately
|
|
652
|
+
re-throws errors that a boundary has already handled, so losing access — an
|
|
653
|
+
expected state, not a fault — shows up in the console and in Next's dev
|
|
654
|
+
overlay. The UI handles it and recovers; the noise is React's, and the price of
|
|
655
|
+
refusal being an exception rather than a field to branch on.
|
|
656
|
+
- **Server-rendered HTML stops at an error boundary.** React does not run error
|
|
657
|
+
boundaries while rendering on the server, so a refused query paints on the
|
|
658
|
+
client rather than in the HTML. The denial itself is hydrated, so it appears
|
|
659
|
+
without a round trip.
|
|
660
|
+
- **A collection is paged by its last `findMany`,** the same guess that names the
|
|
661
|
+
entity. A method that ends with an unrelated lookup, or whose collection sets
|
|
662
|
+
its own `take`, `skip`, `cursor` or `distinct`, is run whole and sliced in
|
|
663
|
+
memory: correct, and as expensive as not paging at all. A method that decides
|
|
664
|
+
which query to return by branching gets its plan re-learned when the branch
|
|
665
|
+
changes, at the cost of one extra execution.
|
|
666
|
+
- **A `@list` method must be readable one row at a time.** The count run asks its
|
|
667
|
+
collection for a single row, so a method that branches on how many rows came
|
|
668
|
+
back sees one rather than all of them. Guarding on emptiness is fine; guarding
|
|
669
|
+
on a count is not.
|
|
670
|
+
- **A collection's total and its windows are separate subscriptions.** Each is
|
|
671
|
+
computed inside one snapshot, so neither is ever internally torn, but between
|
|
672
|
+
two transactions a scrollbar can be a moment ahead of the rows under it. Rows
|
|
673
|
+
do not appear or vanish from it — the ordering is the query's own.
|
|
674
|
+
- **Placement needs the columns it decides by to be selected.** A collection
|
|
675
|
+
ordered by `createdAt` or filtered by `projectId` and not selecting them sends
|
|
676
|
+
no ordering and no filter: the rows do not carry the values, so nothing can be
|
|
677
|
+
compared against them. It declines silently, which is the wrong kind of quiet —
|
|
678
|
+
the write is still optimistic in its value, only its position waits.
|
|
679
|
+
- **An insert has to be given its id.** `local` runs again on every rebase, so a
|
|
680
|
+
`randomUUID()` inside one is a different row each time. The id belongs in the
|
|
681
|
+
mutation's arguments, which also makes the write idempotent.
|
|
682
|
+
- **The membership filter is the query's `where`, not the method's.** A method
|
|
683
|
+
that filters its rows again in JavaScript is not visible to the tracker, so the
|
|
684
|
+
filter describes a wider collection than the method returns and a row created
|
|
685
|
+
here may appear and then go away. Nothing detects it.
|
|
686
|
+
- **Optimistic placement is exact for numbers and dates, and declines on text.**
|
|
687
|
+
Collation belongs to the database, and a browser guessing at it would put a row
|
|
688
|
+
where the server is about to disagree. A text key therefore contributes nothing
|
|
689
|
+
to the local comparison and those rows keep the order the server sent. Placement
|
|
690
|
+
also reaches only as far as the window: a row whose new place is outside it ends
|
|
691
|
+
up at its edge until the server's answer moves it the rest of the way.
|
|
692
|
+
- **`GridList` and `List` assume uniform item height.** Measuring rendered items
|
|
693
|
+
would make the scrollbar exact and the arithmetic guesswork; it is not
|
|
694
|
+
implemented.
|
|
695
|
+
- **Optimistic inserts need a client-side predicate** (`QueryDescriptor.matches`)
|
|
696
|
+
to decide whether a locally created row belongs in a given query result. Without
|
|
697
|
+
it the row appears once the server confirms it. This is the one place where query
|
|
698
|
+
semantics are duplicated on the client.
|
|
699
|
+
- **A client id is one mutation sequence,** so every connection needs its own.
|
|
700
|
+
The browser keeps it in `sessionStorage`, which is per tab and survives a
|
|
701
|
+
refresh; duplicating a tab copies that storage in some browsers. The id now
|
|
702
|
+
belongs to whichever connection claimed it last, and the superseded one has its
|
|
703
|
+
writes *refused* rather than acknowledged and dropped — which is also what
|
|
704
|
+
catches the case no single process can see, the same id on two sync instances.
|
|
705
|
+
A reconnect claims the id afresh, and the refusal does not consume a mutation
|
|
706
|
+
number, so nothing is lost by being superseded mid-write.
|
|
707
|
+
- **Several sync instances share the outbox, and pay for all of it.** Each
|
|
708
|
+
process reads the whole change stream, so adding one multiplies the fan-out
|
|
709
|
+
capacity but not the cost of *receiving* changes — at some arrival rate every
|
|
710
|
+
node spends its time parsing events none of its clients care about. Cutting
|
|
711
|
+
that needs a router that knows each node's read keys and sends it only what it
|
|
712
|
+
could care about; the data structure for it is `InvalidationIndex`, filed by
|
|
713
|
+
node instead of by subscription, and it is not written.
|
|
714
|
+
- **The WAL source does not scale out.** One replication slot feeds one
|
|
715
|
+
consumer, so N processes means N slots and N times the retained WAL. Running
|
|
716
|
+
several instances is an outbox arrangement.
|
|
717
|
+
- **`user.name = "Jan"` is deliberately not supported.** Direct assignment cannot
|
|
718
|
+
be authorized on the server and cannot be replayed on rebase. §3 of the design
|
|
719
|
+
doc replaces it with named mutators; `client.mutate("renameUser", …)` is the
|
|
720
|
+
supported form, and the optimistic effect is just as immediate.
|
|
721
|
+
|
|
722
|
+
## Layout
|
|
723
|
+
|
|
724
|
+
```
|
|
725
|
+
src/index.ts the framework's surface ← entry point `nowity`
|
|
726
|
+
src/api/ contracts and decorators ← entry point `nowity/api`, shared
|
|
727
|
+
src/react/ useQuerySuspense, useList, Restricted, GridList, List, provider ← `nowity/react`
|
|
728
|
+
src/next/ App Router adapter: read, serve, config ← `nowity/next`, `/client`,
|
|
729
|
+
`/serve`, `/config`
|
|
730
|
+
src/ironbean/ the two containers and their tokens ← entry point `nowity/ironbean`
|
|
731
|
+
src/server/api/ read-set tracker, contract→engine bridge, prerender, auth
|
|
732
|
+
src/server/api/list.ts paging an endpoint that has no paging
|
|
733
|
+
src/client/list.ts the windows a collection is actually showing
|
|
734
|
+
src/server/ engine: change sources, sync engine, mutators, WebSocket server
|
|
735
|
+
src/client/ engine: confirmed store, overlay/rebase, identity map, live queries
|
|
736
|
+
src/client/connection.ts contract proxies, async acquisition, subscription lifetime
|
|
737
|
+
src/client/query-source.ts what a component reads through — the socket's, or a
|
|
738
|
+
render's (src/client/ssr-source.ts), and one shaping for both
|
|
739
|
+
src/core/ types, wire protocol, diffing
|
|
740
|
+
test/app/ demo app: shared.ts (client half) vs server.ts (server half),
|
|
741
|
+
contract.ts the same app as contracts, for the React scenarios
|
|
742
|
+
test/scenarios/ 00 milestones, 01–11 acceptance scenarios, 12 Prisma, 13 WAL,
|
|
743
|
+
14 React, 15 SSR hydration, 16 DI containers, 17 SSR collection,
|
|
744
|
+
18 live collections, the grid and list over them, and hydration,
|
|
745
|
+
19 two tabs of one browser
|
|
746
|
+
example/demo.ts runnable walkthrough of the engine under the framework
|
|
747
|
+
example/contract-demo.ts the same story through contracts, with nothing declared
|
|
748
|
+
example-next/ a Next.js application: SSR, optimistic edits, access revoked live,
|
|
749
|
+
and /archive, a five-thousand-row collection in a live grid
|
|
750
|
+
example-next/prisma/ the demo schema — the tests share this database and client
|
|
751
|
+
```
|