@nichoth/simple-sync 0.0.0-stage → 0.0.5
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 +469 -2
- package/dist/client/db.d.ts +67 -0
- package/dist/client/db.d.ts.map +1 -0
- package/dist/client/db.js +1 -0
- package/dist/client/db.js.map +7 -0
- package/dist/client/idb.d.ts +12 -0
- package/dist/client/idb.d.ts.map +1 -0
- package/dist/client/idb.js +72 -0
- package/dist/client/idb.js.map +7 -0
- package/dist/client/index.d.ts +143 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +362 -0
- package/dist/client/index.js.map +7 -0
- package/dist/client/sqlite-opfs-rpc.d.ts +21 -0
- package/dist/client/sqlite-opfs-rpc.d.ts.map +1 -0
- package/dist/client/sqlite-opfs-rpc.js +55 -0
- package/dist/client/sqlite-opfs-rpc.js.map +7 -0
- package/dist/client/sqlite-opfs.d.ts +15 -0
- package/dist/client/sqlite-opfs.d.ts.map +1 -0
- package/dist/client/sqlite-opfs.js +31 -0
- package/dist/client/sqlite-opfs.js.map +7 -0
- package/dist/client/sqlite-opfs.worker.d.ts +6 -0
- package/dist/client/sqlite-opfs.worker.d.ts.map +1 -0
- package/dist/client/sqlite-opfs.worker.js +47 -0
- package/dist/client/sqlite-opfs.worker.js.map +7 -0
- package/dist/client/sqlite.d.ts +25 -0
- package/dist/client/sqlite.d.ts.map +1 -0
- package/dist/client/sqlite.js +117 -0
- package/dist/client/sqlite.js.map +7 -0
- package/dist/client.d.ts +6 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +11 -0
- package/dist/client.js.map +7 -0
- package/dist/hash.d.ts +23 -0
- package/dist/hash.d.ts.map +1 -0
- package/dist/hash.js +29 -0
- package/dist/hash.js.map +7 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +18 -0
- package/dist/index.js.map +7 -0
- package/dist/meta.json +511 -0
- package/dist/op.d.ts +41 -0
- package/dist/op.d.ts.map +1 -0
- package/dist/op.js +46 -0
- package/dist/op.js.map +7 -0
- package/dist/reduce.d.ts +55 -0
- package/dist/reduce.d.ts.map +1 -0
- package/dist/reduce.js +173 -0
- package/dist/reduce.js.map +7 -0
- package/dist/server/errors.d.ts +16 -0
- package/dist/server/errors.d.ts.map +1 -0
- package/dist/server/errors.js +14 -0
- package/dist/server/errors.js.map +7 -0
- package/dist/server/index.d.ts +75 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +324 -0
- package/dist/server/index.js.map +7 -0
- package/dist/server.d.ts +2 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +5 -0
- package/dist/server.js.map +7 -0
- package/dist/types.d.ts +105 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +1 -0
- package/dist/types.js.map +7 -0
- package/package.json +118 -4
package/README.md
CHANGED
|
@@ -1,3 +1,470 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Simple Sync
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The simplest possible state synchronization protocol.
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
## Contents
|
|
7
|
+
|
|
8
|
+
<!-- toc -->
|
|
9
|
+
|
|
10
|
+
- [Model](#model)
|
|
11
|
+
* [Ops](#ops)
|
|
12
|
+
* [State](#state)
|
|
13
|
+
+ [`state.id`](#stateid)
|
|
14
|
+
* [Asymmetric data flow](#asymmetric-data-flow)
|
|
15
|
+
* [Last-write-wins reducer](#last-write-wins-reducer)
|
|
16
|
+
- [Sync Protocol](#sync-protocol)
|
|
17
|
+
* [1. Client Hello](#1-client-hello)
|
|
18
|
+
+ [Example](#example)
|
|
19
|
+
* [2. Server Response: Ready](#2-server-response-ready)
|
|
20
|
+
* [2A. Server Response: Reduced State](#2a-server-response-reduced-state)
|
|
21
|
+
* [2B. Server Response: State-Deleted](#2b-server-response-state-deleted)
|
|
22
|
+
* [3. Client Response: Write](#3-client-response-write)
|
|
23
|
+
* [4. Reconciliation](#4-reconciliation)
|
|
24
|
+
- [Example](#example-1)
|
|
25
|
+
* [Create a Client](#create-a-client)
|
|
26
|
+
* [Create a Server](#create-a-server)
|
|
27
|
+
* [Choosing a reducer](#choosing-a-reducer)
|
|
28
|
+
* [Device identity](#device-identity)
|
|
29
|
+
- [Develop](#develop)
|
|
30
|
+
* [`npm start`](#npm-start)
|
|
31
|
+
* [`npm run dev:worker`](#npm-run-devworker)
|
|
32
|
+
* [`start` vs `dev:worker`](#start-vs-devworker)
|
|
33
|
+
- [Structure](#structure)
|
|
34
|
+
|
|
35
|
+
<!-- tocstop -->
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## Model
|
|
40
|
+
|
|
41
|
+
Each device writes operations (ops) to a local append-only log.
|
|
42
|
+
That is the source of truth. **Note**, there is never a conflict in this model.
|
|
43
|
+
At any time, there is only 1 possible event per device per moment in time.
|
|
44
|
+
|
|
45
|
+
The server's job is to transform events from multiple devices into
|
|
46
|
+
a single meaningful state.
|
|
47
|
+
|
|
48
|
+
### Ops
|
|
49
|
+
|
|
50
|
+
An op is a single intent record. It is unique per machine.
|
|
51
|
+
Each `op` has a field `seq`, and `seq` is just an incrementing integer.
|
|
52
|
+
The combination of the machine's ID + the `seq` number creates a unique ID
|
|
53
|
+
per `op` record.
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
{
|
|
57
|
+
seq:number, // per-device monotonic
|
|
58
|
+
id:string, // `op:${deviceId}:${seq}`
|
|
59
|
+
type:'create'|'patch'|'delete',
|
|
60
|
+
target:string|null, // state id; null for create
|
|
61
|
+
value:unknown, // payload (see below)
|
|
62
|
+
ts:number // monotonic-timestamp
|
|
63
|
+
}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Three op types:
|
|
67
|
+
|
|
68
|
+
- **`create`** — initialises a room's state. `target` is `null`;
|
|
69
|
+
`value` is the initial state value.
|
|
70
|
+
- **`patch`** -- shallow-merges `value` (an object) into the
|
|
71
|
+
state's value. Conflict resolution is per-field timestamp:
|
|
72
|
+
later `ts` wins.
|
|
73
|
+
- **`delete`** — with `value: { key:string }` removes a single
|
|
74
|
+
sub-field; with `value: null` removes the whole state entirely.
|
|
75
|
+
Use `op.delete(target, key)` for the field form and
|
|
76
|
+
`op.delete(target)` (no key argument) for the whole-state form.
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
-------------------------------
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
### State
|
|
83
|
+
|
|
84
|
+
A `ReducedState` is the server's authoritative view after applying
|
|
85
|
+
all ops. It is a _materialized view_, in database terms.
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
{
|
|
89
|
+
// The ID is set once when the state is created, never mutated.
|
|
90
|
+
// Constructed client-side at creation time.
|
|
91
|
+
id:string, // `state:${deviceId}:${createOpSeq}:${createOpTs}`
|
|
92
|
+
// The hash is over `value` only, not __ts. Recomputed on every
|
|
93
|
+
// state change.
|
|
94
|
+
hash:string, // SHA-256 hex of canonical JSON(value)
|
|
95
|
+
// Per-field write timestamps, keyed by top-level fields of `value`.
|
|
96
|
+
// Each value is the `ts` of the create/patch op that last wrote
|
|
97
|
+
// that field -- a device-authored monotonic timestamp. The reducer
|
|
98
|
+
// looks at these to resolve writes last-write-wins by `ts`,
|
|
99
|
+
// regardless of arrival order
|
|
100
|
+
__ts:Record<string, number>,
|
|
101
|
+
// Arbitrary JSON object — your application's state.
|
|
102
|
+
value:Record<string, unknown>
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
#### `state.id`
|
|
107
|
+
|
|
108
|
+
The ID for state objects is `state:${deviceId}:${createOpSeq}:${createOpTs}`,
|
|
109
|
+
where `createOpTs` is the create op's `ts` (a monotonic device-side
|
|
110
|
+
timestamp).
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
### Asymmetric data flow
|
|
114
|
+
|
|
115
|
+
Ops flow **client -> server only**. Reduced state flows
|
|
116
|
+
**server -> client only**. Clients are the source of truth for ops;
|
|
117
|
+
the server is the source of truth for reduced state.
|
|
118
|
+
|
|
119
|
+
Reconciliation happens on the server. The server should know how
|
|
120
|
+
to receive events with timestamps in the past. The server makes decisions like
|
|
121
|
+
_do we overwrite the current state with an older op_?
|
|
122
|
+
What if it came from device A, and the other ops came from device B?
|
|
123
|
+
That is your app's business logic.
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
### Last-write-wins reducer
|
|
127
|
+
|
|
128
|
+
The library exports `lastWriteWins`, a pure function
|
|
129
|
+
`(state, op) => Promise<ReducedState | null>` that you can pass
|
|
130
|
+
directly to `SyncServer.reduce` or use as a building block in your
|
|
131
|
+
own reducer. It tracks per-field write timestamps under a top-level
|
|
132
|
+
`__ts` field on `ReducedState`, so conflicting writes resolve by
|
|
133
|
+
`ts` regardless of arrival order.
|
|
134
|
+
|
|
135
|
+
For whole-state delete (`op.delete(stateId)` with no key argument),
|
|
136
|
+
the reducer returns `null` to signal "remove this state entirely."
|
|
137
|
+
The server interprets `null` by `DELETE`ing the row and broadcasting
|
|
138
|
+
`{ kind: 'state-deleted', id }`.
|
|
139
|
+
|
|
140
|
+
> [!IMPORTANT]
|
|
141
|
+
> Simple Sync assumes one user per state machine. Concurrent edits by
|
|
142
|
+
> different users to the same field will resolve by `ts`, but
|
|
143
|
+
> that is not intended operation.
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
---
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
## Sync Protocol
|
|
150
|
+
|
|
151
|
+
Transport is WebSocket via
|
|
152
|
+
[partyserver](https://github.com/cloudflare/partykit/tree/main/packages/partyserver).
|
|
153
|
+
HTTP fallback is planned for a future release; v1 is WebSocket-only.
|
|
154
|
+
|
|
155
|
+
The protocol has five JSON envelope kinds. Top-level discriminator
|
|
156
|
+
is `kind` (not `type`, which is reserved for op-level dispatch):
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
type Envelope =
|
|
160
|
+
| { kind:'hello', deviceId:string, lastSeq:number,
|
|
161
|
+
states?:{ id:string, hash:string }[] }
|
|
162
|
+
| { kind:'write', ops:Op[] }
|
|
163
|
+
| { kind:'ready', requestFrom?:number }
|
|
164
|
+
| { kind:'state', state:ReducedState }
|
|
165
|
+
| { kind:'state-deleted', id:string }
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
### 1. Client Hello
|
|
169
|
+
|
|
170
|
+
The client opens a session. Its first message is a `hello`
|
|
171
|
+
carrying the latest `seq` it has from its local log and (optionally)
|
|
172
|
+
the id + hash of any state it cares about.
|
|
173
|
+
|
|
174
|
+
#### Example
|
|
175
|
+
|
|
176
|
+
```ts
|
|
177
|
+
{
|
|
178
|
+
kind: 'hello',
|
|
179
|
+
deviceId: 'nihxw236tp43mkot6bo2oxlslf5lhiqt',
|
|
180
|
+
lastSeq: 42,
|
|
181
|
+
states: [
|
|
182
|
+
{
|
|
183
|
+
id: 'state:nihxw236tp43mkot6bo2oxlslf5lhiqt:1:1779230174292',
|
|
184
|
+
hash: 'def456...'
|
|
185
|
+
}
|
|
186
|
+
]
|
|
187
|
+
}
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
### 2. Server Response: Ready
|
|
191
|
+
|
|
192
|
+
The server computes the gap between what it has stored for the given
|
|
193
|
+
machine and what the client says it has (it tells the client what ops it needs).
|
|
194
|
+
|
|
195
|
+
It replies with `ready`, plus the latest `seq` it has for that client.
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
// Server is missing ops 7..42:
|
|
199
|
+
{ kind: 'ready', requestFrom: 6 }
|
|
200
|
+
|
|
201
|
+
// Server is caught up:
|
|
202
|
+
{ kind: 'ready' }
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
`requestFrom` is the server's _exclusive_ lower bound: "send me
|
|
206
|
+
ops with `seq > requestFrom`".
|
|
207
|
+
|
|
208
|
+
### 2A. Server Response: Reduced State
|
|
209
|
+
|
|
210
|
+
Immediately after `ready`, for each ID in `states` in the client hello,
|
|
211
|
+
the server pushes a `state` envelope if the server's hash doesn't match for the
|
|
212
|
+
given ID.
|
|
213
|
+
|
|
214
|
+
```ts
|
|
215
|
+
{
|
|
216
|
+
kind: 'state',
|
|
217
|
+
state: {
|
|
218
|
+
id: 'state:nihxw236tp43mkot6bo2oxlslf5lhiqt:1:1779230174292',
|
|
219
|
+
hash: 'def456...',
|
|
220
|
+
__ts: { title: 1779230174292, body: 1779230174295 },
|
|
221
|
+
value: { title: 'Hello', body: 'World' }
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
### 2B. Server Response: State-Deleted
|
|
227
|
+
|
|
228
|
+
When a `delete` op removes a state entirely (the client called
|
|
229
|
+
`op.delete(stateId)` with no key), the server broadcasts:
|
|
230
|
+
|
|
231
|
+
```ts
|
|
232
|
+
{ kind: 'state-deleted', id: 'state:nihxw...:1:1779230174292' }
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
to every connection in the room. Clients receiving this should
|
|
236
|
+
remove the state from their local view.
|
|
237
|
+
|
|
238
|
+
### 3. Client Response: Write
|
|
239
|
+
|
|
240
|
+
The client sends any ops the server requested in `ready`:
|
|
241
|
+
|
|
242
|
+
```ts
|
|
243
|
+
{
|
|
244
|
+
kind: 'write',
|
|
245
|
+
ops: [
|
|
246
|
+
{
|
|
247
|
+
seq: 7,
|
|
248
|
+
id: 'op:nihxw236tp...:7',
|
|
249
|
+
type: 'patch',
|
|
250
|
+
target: 'state:nihxw236tp...:1:1779230174292',
|
|
251
|
+
value: { body: 'hello again, world' },
|
|
252
|
+
ts: 1779401509223
|
|
253
|
+
},
|
|
254
|
+
// ... 8..42
|
|
255
|
+
]
|
|
256
|
+
}
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
### 4. Reconciliation
|
|
260
|
+
|
|
261
|
+
The server inserts each op idempotently (primary key is `id`;
|
|
262
|
+
`INSERT OR IGNORE`), applies it via `reduce`, persists the new
|
|
263
|
+
`ReducedState`, and broadcasts the result to every connection in
|
|
264
|
+
the room, including the sender.
|
|
265
|
+
|
|
266
|
+
If two devices wrote conflicting field values offline, both
|
|
267
|
+
`patch` ops will be applied; the LWW reducer (or a custom reducer)
|
|
268
|
+
arbitrates by `ts`.
|
|
269
|
+
|
|
270
|
+
---
|
|
271
|
+
|
|
272
|
+
## Example
|
|
273
|
+
|
|
274
|
+
See [`./example`](./example/) for a working demo using Cloudflare
|
|
275
|
+
Durable Objects (SQLite) + IndexedDB.
|
|
276
|
+
|
|
277
|
+
### Create a Client
|
|
278
|
+
|
|
279
|
+
```ts
|
|
280
|
+
import {
|
|
281
|
+
SyncClient,
|
|
282
|
+
idb,
|
|
283
|
+
op,
|
|
284
|
+
lastWriteWins
|
|
285
|
+
} from '@nichoth/simple-sync'
|
|
286
|
+
|
|
287
|
+
const deviceId = 'my-device-id' // 32-char hash, see below
|
|
288
|
+
const db = await idb('my-app.' + deviceId)
|
|
289
|
+
const url = 'wss://example.com/ws/sync/' + roomId
|
|
290
|
+
|
|
291
|
+
const client = new SyncClient({
|
|
292
|
+
url,
|
|
293
|
+
deviceId,
|
|
294
|
+
db,
|
|
295
|
+
reduce: lastWriteWins // optional: optimistic projection
|
|
296
|
+
})
|
|
297
|
+
|
|
298
|
+
client.on('state', s => render(s))
|
|
299
|
+
client.on('connected', online => updateBadge(online))
|
|
300
|
+
client.on('pending', n => updatePendingBadge(n))
|
|
301
|
+
|
|
302
|
+
await client.connect()
|
|
303
|
+
|
|
304
|
+
// Create a new state
|
|
305
|
+
const createdOp = await client.write(op.create({ body: 'hello' }))
|
|
306
|
+
const stateId = `state:${client.deviceId}:${createdOp.seq}:${createdOp.ts}`
|
|
307
|
+
|
|
308
|
+
// Patch the state
|
|
309
|
+
await client.write(op.patch(stateId, { body: 'hello again' }))
|
|
310
|
+
|
|
311
|
+
// Remove a single field from the state:
|
|
312
|
+
await client.write(op.delete(stateId, 'body'))
|
|
313
|
+
|
|
314
|
+
// Remove the whole state entirely:
|
|
315
|
+
await client.write(op.delete(stateId))
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
`SyncClient` handles sequence numbers, timestamps, the WS state
|
|
319
|
+
machine, reconnect with exponential backoff, offline write
|
|
320
|
+
buffering, and the `hello` / `ready` / `state` exchange. The local
|
|
321
|
+
`db` (any implementation of `ClientDB`) is the persistence layer;
|
|
322
|
+
`idb(dbName)` is the bundled IndexedDB adapter.
|
|
323
|
+
|
|
324
|
+
If you pass `reduce`, the client applies it locally for optimistic
|
|
325
|
+
rendering. The next server `state` broadcast overwrites the
|
|
326
|
+
optimistic projection with the canonical result.
|
|
327
|
+
|
|
328
|
+
### Create a Server
|
|
329
|
+
|
|
330
|
+
```ts
|
|
331
|
+
// example/server/index.ts
|
|
332
|
+
import { Hono } from 'hono'
|
|
333
|
+
import { partyserverMiddleware } from 'hono-party'
|
|
334
|
+
import {
|
|
335
|
+
SyncServer,
|
|
336
|
+
lastWriteWins
|
|
337
|
+
} from '@nichoth/simple-sync'
|
|
338
|
+
|
|
339
|
+
export class Sync extends SyncServer {
|
|
340
|
+
reduce = lastWriteWins
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
const app = new Hono()
|
|
344
|
+
app.use('*', partyserverMiddleware({
|
|
345
|
+
options: { prefix: 'ws' } // -> /ws/sync/<roomId>
|
|
346
|
+
}))
|
|
347
|
+
export default app
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
The matching `wrangler.jsonc` declares `Sync` as a SQLite-backed
|
|
351
|
+
Durable Object:
|
|
352
|
+
|
|
353
|
+
```jsonc
|
|
354
|
+
{
|
|
355
|
+
"durable_objects": {
|
|
356
|
+
"bindings": [
|
|
357
|
+
{ "name": "SYNC", "class_name": "Sync" }
|
|
358
|
+
]
|
|
359
|
+
},
|
|
360
|
+
"migrations": [
|
|
361
|
+
{ "tag": "v1", "new_sqlite_classes": ["Sync"] }
|
|
362
|
+
]
|
|
363
|
+
}
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
`SyncServer` runs inside the DO. `onStart()` rehydrates the
|
|
367
|
+
current `ReducedState` from SQLite on every wake (including
|
|
368
|
+
Hibernation API wake-ups). `onMessage` dispatches on the envelope
|
|
369
|
+
`kind` and broadcasts the new `state` to everyone in the room.
|
|
370
|
+
|
|
371
|
+
### Choosing a reducer
|
|
372
|
+
|
|
373
|
+
`lastWriteWins` ships with the library and covers the common case.
|
|
374
|
+
For custom semantics, write your own pure async function
|
|
375
|
+
`(state, op) => Promise<ReducedState | null>` and assign it instead:
|
|
376
|
+
|
|
377
|
+
```ts
|
|
378
|
+
import {
|
|
379
|
+
SyncServer,
|
|
380
|
+
type ReducedState,
|
|
381
|
+
type Op
|
|
382
|
+
} from '@nichoth/simple-sync'
|
|
383
|
+
|
|
384
|
+
export class Sync extends SyncServer {
|
|
385
|
+
async reduce (
|
|
386
|
+
state:ReducedState | null,
|
|
387
|
+
op:Op
|
|
388
|
+
):Promise<ReducedState | null> {
|
|
389
|
+
// your logic
|
|
390
|
+
// Return null to signal whole-state delete (removes the state entirely)
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
### Device identity
|
|
396
|
+
|
|
397
|
+
Each device needs a stable `deviceId`. The example app uses
|
|
398
|
+
[`@substrate-system/keys`](https://github.com/substrate-system/keys)
|
|
399
|
+
to generate a non-extractable Ed25519 keypair and derives a
|
|
400
|
+
32-character DNS-friendly hash of the public key, but any stable
|
|
401
|
+
string per device works.
|
|
402
|
+
|
|
403
|
+
---
|
|
404
|
+
|
|
405
|
+
## Develop
|
|
406
|
+
|
|
407
|
+
This example supports two local dev workflows.
|
|
408
|
+
|
|
409
|
+
### `npm start`
|
|
410
|
+
|
|
411
|
+
Start a vite + Cloudflare plugin localhost server on port `8888`.
|
|
412
|
+
|
|
413
|
+
```sh
|
|
414
|
+
npm start
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
To run the routing tests against vite mode:
|
|
418
|
+
|
|
419
|
+
```sh
|
|
420
|
+
npm test
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
### `npm run dev:worker`
|
|
424
|
+
|
|
425
|
+
Run wrangler dev against the built worker (port 9999).
|
|
426
|
+
|
|
427
|
+
```sh
|
|
428
|
+
npm run dev:worker
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
Runs `npm run build` first, then `wrangler dev` against the built
|
|
432
|
+
worker bundle and assets in `public/`. No HMR; every change requires
|
|
433
|
+
a rebuild. Use this before pushing to catch dev/prod parity issues
|
|
434
|
+
that vite mode can mask (asset hashing, real Miniflare routing,
|
|
435
|
+
worker-side request handling against the actual bundle).
|
|
436
|
+
|
|
437
|
+
To run the routing tests against wrangler dev mode:
|
|
438
|
+
|
|
439
|
+
```sh
|
|
440
|
+
npm run test:worker
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
### `start` vs `dev:worker`
|
|
444
|
+
|
|
445
|
+
| Concern | `npm start` (vite) | `npm run dev:worker` (wrangler) |
|
|
446
|
+
|---|---|---|
|
|
447
|
+
| Port | 8888 | 9999 |
|
|
448
|
+
| Hot reload | yes | no |
|
|
449
|
+
| Asset hashing | bypassed | real |
|
|
450
|
+
| Miniflare routing | partial | real |
|
|
451
|
+
| Build required | no | yes |
|
|
452
|
+
|
|
453
|
+
Iterate on UI code in vite mode for speed; verify a worker
|
|
454
|
+
change in wrangler mode before pushing.
|
|
455
|
+
|
|
456
|
+
---
|
|
457
|
+
|
|
458
|
+
## Structure
|
|
459
|
+
|
|
460
|
+
- `src/` — the publishable library (`@nichoth/simple-sync`).
|
|
461
|
+
Imports only `mitt`, `idb`, `monotonic-timestamp`, `partyserver`,
|
|
462
|
+
and the Web Crypto + Web Storage browser globals. No UI framework
|
|
463
|
+
dependency.
|
|
464
|
+
- `example/` — a demo app using Preact + signals + Cloudflare
|
|
465
|
+
Durable Objects to exercise the library end-to-end. NOT
|
|
466
|
+
published.
|
|
467
|
+
|
|
468
|
+
The library/example split is enforced in CI by a lint rule (no
|
|
469
|
+
`src/` file may import `preact`, `@preact/signals`, `htm`,
|
|
470
|
+
`@substrate-system/routes`, or `route-event`).
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local persistence contract for SyncClient. The default IDB
|
|
3
|
+
* adapter lives in `./idb.ts`. Consumers can implement this
|
|
4
|
+
* interface against any storage backend.
|
|
5
|
+
*/
|
|
6
|
+
import type { Op, ReducedState } from '../types.js';
|
|
7
|
+
export interface ClientDB {
|
|
8
|
+
/**
|
|
9
|
+
* Append a single op to the local log. Idempotent on `seq`
|
|
10
|
+
* (a re-put with the same seq overwrites; the client never
|
|
11
|
+
* does this, but it must not throw).
|
|
12
|
+
*/
|
|
13
|
+
write(op: Op): Promise<void>;
|
|
14
|
+
/**
|
|
15
|
+
* Return all ops with `seq > fromSeq`, in ascending seq order.
|
|
16
|
+
* Used to replay the client's pending ops to the server after
|
|
17
|
+
* reconnect.
|
|
18
|
+
*/
|
|
19
|
+
readFrom(fromSeq: number): Promise<Op[]>;
|
|
20
|
+
/**
|
|
21
|
+
* Return all ops with `loSeq <= seq <= hiSeq`, ascending.
|
|
22
|
+
*/
|
|
23
|
+
readRange(loSeq: number, hiSeq: number): Promise<Op[]>;
|
|
24
|
+
/**
|
|
25
|
+
* The highest `seq` written to the log, or `0` if empty.
|
|
26
|
+
* (0 is reserved — no real op ever has seq 0. The client's
|
|
27
|
+
* first op is seq 1.)
|
|
28
|
+
*/
|
|
29
|
+
last(): Promise<number>;
|
|
30
|
+
/**
|
|
31
|
+
* Delete every op whose `seq` is strictly less than `seq`, leaving
|
|
32
|
+
* ops with `seq >= seq` intact. Used to prune the local op-log down
|
|
33
|
+
* to a confirmed watermark while retaining the cursor op (the
|
|
34
|
+
* highest seq) so `last()` stays correct. A no-op on an empty log or
|
|
35
|
+
* when `seq <= 0` (no real op has seq <= 0).
|
|
36
|
+
*/
|
|
37
|
+
deleteBelow(seq: number): Promise<void>;
|
|
38
|
+
/**
|
|
39
|
+
* Persist a snapshot of the current reduced state for a given
|
|
40
|
+
* state id. Replaces any prior entry at that id.
|
|
41
|
+
*/
|
|
42
|
+
putState(state: ReducedState): Promise<void>;
|
|
43
|
+
/**
|
|
44
|
+
* Read the persisted ReducedState for a given id, or null if
|
|
45
|
+
* none.
|
|
46
|
+
*/
|
|
47
|
+
getState(id: string): Promise<ReducedState | null>;
|
|
48
|
+
/**
|
|
49
|
+
* Read every persisted ReducedState. Many states per room are
|
|
50
|
+
* first-class; callers should not assume a single result.
|
|
51
|
+
*/
|
|
52
|
+
getAllStates(): Promise<ReducedState[]>;
|
|
53
|
+
/**
|
|
54
|
+
* Remove a persisted ReducedState by id. Used by `SyncClient`
|
|
55
|
+
* when a whole-state delete op results in a null reduction.
|
|
56
|
+
*/
|
|
57
|
+
deleteState(id: string): Promise<void>;
|
|
58
|
+
/**
|
|
59
|
+
* Close the underlying database handle, releasing any IDB
|
|
60
|
+
* resources. After `close()`, no methods on this instance
|
|
61
|
+
* should be called. Test cleanup uses this before
|
|
62
|
+
* `indexedDB.deleteDatabase(name)` to avoid blocked-delete
|
|
63
|
+
* races.
|
|
64
|
+
*/
|
|
65
|
+
close(): void;
|
|
66
|
+
}
|
|
67
|
+
//# sourceMappingURL=db.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"db.d.ts","sourceRoot":"","sources":["../../src/client/db.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,EAAE,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAEnD,MAAM,WAAW,QAAQ;IACrB;;;;OAIG;IACH,KAAK,CAAE,EAAE,EAAC,EAAE,GAAE,OAAO,CAAC,IAAI,CAAC,CAAA;IAE3B;;;;OAIG;IACH,QAAQ,CAAE,OAAO,EAAC,MAAM,GAAE,OAAO,CAAC,EAAE,EAAE,CAAC,CAAA;IAEvC;;OAEG;IACH,SAAS,CAAE,KAAK,EAAC,MAAM,EAAE,KAAK,EAAC,MAAM,GAAE,OAAO,CAAC,EAAE,EAAE,CAAC,CAAA;IAEpD;;;;OAIG;IACH,IAAI,IAAI,OAAO,CAAC,MAAM,CAAC,CAAA;IAEvB;;;;;;OAMG;IACH,WAAW,CAAE,GAAG,EAAC,MAAM,GAAE,OAAO,CAAC,IAAI,CAAC,CAAA;IAEtC;;;OAGG;IACH,QAAQ,CAAE,KAAK,EAAC,YAAY,GAAE,OAAO,CAAC,IAAI,CAAC,CAAA;IAE3C;;;OAGG;IACH,QAAQ,CAAE,EAAE,EAAC,MAAM,GAAE,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAAA;IAEjD;;;OAGG;IACH,YAAY,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC,CAAA;IAEvC;;;OAGG;IACH,WAAW,CAAE,EAAE,EAAC,MAAM,GAAE,OAAO,CAAC,IAAI,CAAC,CAAA;IAErC;;;;;;OAMG;IACH,KAAK,IAAI,IAAI,CAAA;CAChB"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
//# sourceMappingURL=db.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* IndexedDB adapter for ClientDB interface.
|
|
3
|
+
*/
|
|
4
|
+
import type { ClientDB } from './db.js';
|
|
5
|
+
/**
|
|
6
|
+
* Open (or create) an IndexedDB-backed ClientDB.
|
|
7
|
+
*
|
|
8
|
+
* @param dbName Per-device DB name. Use the deviceId to scope.
|
|
9
|
+
* @returns A connected ClientDB instance.
|
|
10
|
+
*/
|
|
11
|
+
export declare function idb(dbName: string): Promise<ClientDB>;
|
|
12
|
+
//# sourceMappingURL=idb.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"idb.d.ts","sourceRoot":"","sources":["../../src/client/idb.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAevC;;;;;GAKG;AACH,wBAAsB,GAAG,CAAE,MAAM,EAAC,MAAM,GAAE,OAAO,CAAC,QAAQ,CAAC,CAiB1D"}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
3
|
+
import { openDB } from "idb";
|
|
4
|
+
const SCHEMA_VERSION = 1;
|
|
5
|
+
async function idb(dbName) {
|
|
6
|
+
const db = await openDB(
|
|
7
|
+
dbName,
|
|
8
|
+
SCHEMA_VERSION,
|
|
9
|
+
{
|
|
10
|
+
upgrade(db2) {
|
|
11
|
+
if (!db2.objectStoreNames.contains("ops")) {
|
|
12
|
+
db2.createObjectStore("ops", { keyPath: "seq" });
|
|
13
|
+
}
|
|
14
|
+
if (!db2.objectStoreNames.contains("states")) {
|
|
15
|
+
db2.createObjectStore("states", { keyPath: "id" });
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
);
|
|
20
|
+
return makeClientDb(db);
|
|
21
|
+
}
|
|
22
|
+
__name(idb, "idb");
|
|
23
|
+
function makeClientDb(db) {
|
|
24
|
+
return {
|
|
25
|
+
async write(op) {
|
|
26
|
+
await db.put("ops", op);
|
|
27
|
+
},
|
|
28
|
+
async readFrom(fromSeq) {
|
|
29
|
+
const range = IDBKeyRange.lowerBound(fromSeq, true);
|
|
30
|
+
return db.getAll("ops", range);
|
|
31
|
+
},
|
|
32
|
+
async readRange(loSeq, hiSeq) {
|
|
33
|
+
const range = IDBKeyRange.bound(loSeq, hiSeq);
|
|
34
|
+
return db.getAll("ops", range);
|
|
35
|
+
},
|
|
36
|
+
async last() {
|
|
37
|
+
const tx = db.transaction("ops", "readonly");
|
|
38
|
+
const store = tx.store;
|
|
39
|
+
const cursor = await store.openKeyCursor(null, "prev");
|
|
40
|
+
const seq = cursor ? cursor.key : 0;
|
|
41
|
+
await tx.done;
|
|
42
|
+
return seq;
|
|
43
|
+
},
|
|
44
|
+
async deleteBelow(seq) {
|
|
45
|
+
if (seq <= 0) return;
|
|
46
|
+
const tx = db.transaction("ops", "readwrite");
|
|
47
|
+
await tx.store.delete(IDBKeyRange.upperBound(seq, true));
|
|
48
|
+
await tx.done;
|
|
49
|
+
},
|
|
50
|
+
async putState(state) {
|
|
51
|
+
await db.put("states", state);
|
|
52
|
+
},
|
|
53
|
+
async getState(id) {
|
|
54
|
+
const found = await db.get("states", id);
|
|
55
|
+
return found ?? null;
|
|
56
|
+
},
|
|
57
|
+
async getAllStates() {
|
|
58
|
+
return db.getAll("states");
|
|
59
|
+
},
|
|
60
|
+
async deleteState(id) {
|
|
61
|
+
await db.delete("states", id);
|
|
62
|
+
},
|
|
63
|
+
close() {
|
|
64
|
+
db.close();
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
__name(makeClientDb, "makeClientDb");
|
|
69
|
+
export {
|
|
70
|
+
idb
|
|
71
|
+
};
|
|
72
|
+
//# sourceMappingURL=idb.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/client/idb.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * IndexedDB adapter for ClientDB interface.\n */\n\nimport { openDB, type DBSchema, type IDBPDatabase } from 'idb'\nimport type { Op, ReducedState } from '../types.js'\nimport type { ClientDB } from './db.js'\n\ninterface SimpleSyncSchema extends DBSchema {\n ops:{\n key:number // seq\n value:Op\n }\n states:{\n key:string // ReducedState.id\n value:ReducedState\n }\n}\n\nconst SCHEMA_VERSION = 1\n\n/**\n * Open (or create) an IndexedDB-backed ClientDB.\n *\n * @param dbName Per-device DB name. Use the deviceId to scope.\n * @returns A connected ClientDB instance.\n */\nexport async function idb (dbName:string):Promise<ClientDB> {\n const db = await openDB<SimpleSyncSchema>(\n dbName,\n SCHEMA_VERSION,\n {\n upgrade (db) {\n if (!db.objectStoreNames.contains('ops')) {\n db.createObjectStore('ops', { keyPath: 'seq' })\n }\n if (!db.objectStoreNames.contains('states')) {\n db.createObjectStore('states', { keyPath: 'id' })\n }\n }\n }\n )\n\n return makeClientDb(db)\n}\n\nfunction makeClientDb (\n db:IDBPDatabase<SimpleSyncSchema>\n):ClientDB {\n return {\n async write (op) {\n await db.put('ops', op)\n },\n\n async readFrom (fromSeq) {\n const range = IDBKeyRange.lowerBound(fromSeq, true)\n return db.getAll('ops', range)\n },\n\n async readRange (loSeq, hiSeq) {\n const range = IDBKeyRange.bound(loSeq, hiSeq)\n return db.getAll('ops', range)\n },\n\n async last () {\n // Open a reverse cursor on the primary key and read the\n // first entry \u2014 that's the max seq.\n const tx = db.transaction('ops', 'readonly')\n const store = tx.store\n const cursor = await store.openKeyCursor(null, 'prev')\n const seq = cursor ? cursor.key : 0\n await tx.done\n return seq\n },\n\n async deleteBelow (seq) {\n if (seq <= 0) return\n const tx = db.transaction('ops', 'readwrite')\n // upperBound(seq, true) => keys strictly < seq.\n await tx.store.delete(IDBKeyRange.upperBound(seq, true))\n await tx.done\n },\n\n async putState (state) {\n await db.put('states', state)\n },\n\n async getState (id) {\n const found = await db.get('states', id)\n return found ?? null\n },\n\n async getAllStates () {\n return db.getAll('states')\n },\n\n async deleteState (id) {\n await db.delete('states', id)\n },\n\n close () {\n db.close()\n }\n }\n}\n"],
|
|
5
|
+
"mappings": ";;AAIA,SAAS,cAAgD;AAezD,MAAM,iBAAiB;AAQvB,eAAsB,IAAK,QAAiC;AACxD,QAAM,KAAK,MAAM;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,MACI,QAASA,KAAI;AACT,YAAI,CAACA,IAAG,iBAAiB,SAAS,KAAK,GAAG;AACtC,UAAAA,IAAG,kBAAkB,OAAO,EAAE,SAAS,MAAM,CAAC;AAAA,QAClD;AACA,YAAI,CAACA,IAAG,iBAAiB,SAAS,QAAQ,GAAG;AACzC,UAAAA,IAAG,kBAAkB,UAAU,EAAE,SAAS,KAAK,CAAC;AAAA,QACpD;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AAEA,SAAO,aAAa,EAAE;AAC1B;AAjBsB;AAmBtB,SAAS,aACL,IACO;AACP,SAAO;AAAA,IACH,MAAM,MAAO,IAAI;AACb,YAAM,GAAG,IAAI,OAAO,EAAE;AAAA,IAC1B;AAAA,IAEA,MAAM,SAAU,SAAS;AACrB,YAAM,QAAQ,YAAY,WAAW,SAAS,IAAI;AAClD,aAAO,GAAG,OAAO,OAAO,KAAK;AAAA,IACjC;AAAA,IAEA,MAAM,UAAW,OAAO,OAAO;AAC3B,YAAM,QAAQ,YAAY,MAAM,OAAO,KAAK;AAC5C,aAAO,GAAG,OAAO,OAAO,KAAK;AAAA,IACjC;AAAA,IAEA,MAAM,OAAQ;AAGV,YAAM,KAAK,GAAG,YAAY,OAAO,UAAU;AAC3C,YAAM,QAAQ,GAAG;AACjB,YAAM,SAAS,MAAM,MAAM,cAAc,MAAM,MAAM;AACrD,YAAM,MAAM,SAAS,OAAO,MAAM;AAClC,YAAM,GAAG;AACT,aAAO;AAAA,IACX;AAAA,IAEA,MAAM,YAAa,KAAK;AACpB,UAAI,OAAO,EAAG;AACd,YAAM,KAAK,GAAG,YAAY,OAAO,WAAW;AAE5C,YAAM,GAAG,MAAM,OAAO,YAAY,WAAW,KAAK,IAAI,CAAC;AACvD,YAAM,GAAG;AAAA,IACb;AAAA,IAEA,MAAM,SAAU,OAAO;AACnB,YAAM,GAAG,IAAI,UAAU,KAAK;AAAA,IAChC;AAAA,IAEA,MAAM,SAAU,IAAI;AAChB,YAAM,QAAQ,MAAM,GAAG,IAAI,UAAU,EAAE;AACvC,aAAO,SAAS;AAAA,IACpB;AAAA,IAEA,MAAM,eAAgB;AAClB,aAAO,GAAG,OAAO,QAAQ;AAAA,IAC7B;AAAA,IAEA,MAAM,YAAa,IAAI;AACnB,YAAM,GAAG,OAAO,UAAU,EAAE;AAAA,IAChC;AAAA,IAEA,QAAS;AACL,SAAG,MAAM;AAAA,IACb;AAAA,EACJ;AACJ;AA1DS;",
|
|
6
|
+
"names": ["db"]
|
|
7
|
+
}
|