@yjsync/snapshot-store-d1
v0.1.0
Published
Cloudflare D1 implementation of @yjsync/snapshot-server's SnapshotStore.
Downloads
130
Maintainers
Readme
@yjsync/snapshot-store-d1
Cloudflare D1 implementation of @yjsync/snapshot-server's SnapshotStore. One row per room, monotonic revisions enforced.
Install
bun add @yjsync/snapshot-store-d1Set up the table
Apply the migration to your D1 database. The package ships the SQL at node_modules/@yjsync/snapshot-store-d1/migrations/0001_snapshots.sql. From your project's wrangler.toml-aware directory:
bunx wrangler d1 execute DB --file=node_modules/@yjsync/snapshot-store-d1/migrations/0001_snapshots.sqlOr copy the file into your repo's migrations/ folder and run wrangler d1 migrations apply DB.
Use it
import { createSnapshotHandler } from '@yjsync/snapshot-server'
import { D1SnapshotStore } from '@yjsync/snapshot-store-d1'
export type Env = { DB: D1Database; INTERNAL_SNAPSHOT_SECRET: string }
export default {
async fetch(req: Request, env: Env) {
const handle = createSnapshotHandler({
store: new D1SnapshotStore(env.DB),
internalSecret: env.INTERNAL_SNAPSHOT_SECRET,
})
return (await handle(req)) ?? new Response('Not Found', { status: 404 })
},
}Custom table name
new D1SnapshotStore(env.DB, { table: 'custom_snapshots' })The default is 'snapshots'. The name is validated with a strict identifier regex ([A-Za-z_][A-Za-z0-9_]*) to keep it free of injection concerns.
Monotonicity
put is idempotent on retry and never regresses revision:
| Incoming revision relative to stored | Result |
|--------------------------------------|--------|
| Higher | { accepted: true } (row updated) |
| Equal | { accepted: false, reason: 'duplicate' } |
| Lower | { accepted: false, reason: 'stale' } |
