Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

worker.mjs

302 lines8.2 KB

1// @ts-nocheck
2import { DurableObject } from 'cloudflare:workers'
3// Wrangler resolves `@tanstack/*` through the package tsconfig paths, so the
4// persistence code below loads `@tanstack/db` from source. Import the
5// Collection from the same module graph: one runtime must load one copy of
6// `@tanstack/db`.
7import { createCollection } from '@tanstack/db'
8import {
9 createCloudflareDOSQLitePersistence,
10 persistedCollectionOptions,
11} from '../../dist/esm/index.js'
12import { runDemandCoverageSession } from './demand-coverage-session.mjs'
13​
14const DEFAULT_COLLECTION_ID = `todos`
15const DEFAULT_SCHEMA_VERSION = 1
16​
17function resolveCollectionPersistence({
18 persistence,
19 collectionId,
20 syncEnabled,
21 schemaVersion,
22}) {
23 const mode = syncEnabled ? `sync-present` : `sync-absent`
24 return (
25 persistence.resolvePersistenceForCollection?.({
26 collectionId,
27 mode,
28 schemaVersion,
29 }) ??
30 persistence.resolvePersistenceForMode?.(mode) ??
31 persistence
32 )
34​
35function parseSyncEnabled(rawValue) {
36 if (rawValue == null) {
37 return false
38 }
39​
40 const normalized = String(rawValue).toLowerCase()
41 if (normalized === `1` || normalized === `true`) {
42 return true
43 }
44 if (normalized === `0` || normalized === `false`) {
45 return false
46 }
47​
48 throw new Error(`Invalid PERSISTENCE_WITH_SYNC "${String(rawValue)}"`)
50​
51function parseSchemaVersion(rawSchemaVersion) {
52 if (rawSchemaVersion == null) {
53 return DEFAULT_SCHEMA_VERSION
54 }
55 const parsed = Number(rawSchemaVersion)
56 if (Number.isInteger(parsed) && parsed >= 0) {
57 return parsed
58 }
59 throw new Error(
60 `Invalid PERSISTENCE_SCHEMA_VERSION "${String(rawSchemaVersion)}"`,
61 )
63​
64function jsonResponse(status, body) {
65 return new Response(JSON.stringify(body), {
66 status,
67 headers: {
68 'content-type': 'application/json',
69 },
70 })
72​
73function serializeError(error) {
74 if (error && typeof error === `object`) {
75 const maybeCode = error.code
76 return {
77 name: typeof error.name === `string` ? error.name : `Error`,
78 message:
79 typeof error.message === `string`
80 ? error.message
81 : `Unknown Cloudflare DO runtime error`,
82 code: typeof maybeCode === `string` ? maybeCode : undefined,
83 }
84 }
85​
86 return {
87 name: `Error`,
88 message: `Unknown Cloudflare DO runtime error`,
89 code: undefined,
90 }
92​
93function createUnknownCollectionError(collectionId) {
94 const error = new Error(
95 `Unknown cloudflare durable object persistence collection "${collectionId}"`,
96 )
97 error.name = `UnknownCloudflareDOPersistenceCollectionError`
98 error.code = `UNKNOWN_COLLECTION`
99 return error
101​
102function eagerTarget(collectionId) {
103 return { kind: `eager`, collectionId }
105​
106export class PersistenceObject extends DurableObject {
107 constructor(ctx, env) {
108 super(ctx, env)
109 this.collectionId = env.PERSISTENCE_COLLECTION_ID ?? DEFAULT_COLLECTION_ID
110 this.syncEnabled = parseSyncEnabled(env.PERSISTENCE_WITH_SYNC)
111 this.schemaVersion = parseSchemaVersion(env.PERSISTENCE_SCHEMA_VERSION)
112 this.persistence = createCloudflareDOSQLitePersistence({
113 storage: this.ctx.storage,
114 })
115 this.collectionPersistence = resolveCollectionPersistence({
116 persistence: this.persistence,
117 collectionId: this.collectionId,
118 syncEnabled: this.syncEnabled,
119 schemaVersion: this.schemaVersion,
120 })
121 this.ready = this.collectionPersistence.adapter.loadSubset(
122 eagerTarget(this.collectionId),
123 {
124 limit: 0,
125 },
126 )
127​
128 const baseCollectionOptions = {
129 id: this.collectionId,
130 schemaVersion: this.schemaVersion,
131 getKey: (todo) => todo.id,
132 persistence: this.persistence,
133 }
134 this.collection = createCollection(
135 this.syncEnabled
136 ? persistedCollectionOptions({
137 ...baseCollectionOptions,
138 sync: {
139 sync: ({ markReady }) => {
140 markReady()
141 },
142 },
143 })
144 : persistedCollectionOptions(baseCollectionOptions),
145 )
146 this.collectionReady = this.collection.stateWhenReady()
147 }
148​
149 async fetch(request) {
150 const url = new URL(request.url)
151​
152 try {
153 if (request.method === `GET` && url.pathname === `/health`) {
154 return jsonResponse(200, {
155 ok: true,
156 })
157 }
158​
159 await this.ready
160​
161 if (request.method === `GET` && url.pathname === `/runtime-config`) {
162 return jsonResponse(200, {
163 ok: true,
164 collectionId: this.collectionId,
165 mode: this.syncEnabled ? `sync` : `local`,
166 syncEnabled: this.syncEnabled,
167 schemaVersion: this.schemaVersion,
168 })
169 }
170​
171 const requestBody = await request.json()
172 const collectionId = requestBody.collectionId ?? this.collectionId
173​
174 if (request.method === `POST` && url.pathname === `/demand-session`) {
175 return jsonResponse(200, {
176 ok: true,
177 rows: await runDemandCoverageSession(this.ctx.storage, requestBody),
178 })
179 }
180​
181 if (request.method === `POST` && url.pathname === `/write-todo`) {
182 if (collectionId !== this.collectionId) {
183 throw createUnknownCollectionError(collectionId)
184 }
185 if (this.syncEnabled) {
186 const txId =
187 typeof requestBody.txId === `string`
188 ? requestBody.txId
189 : crypto.randomUUID()
190 const seq =
191 typeof requestBody.seq === `number` ? requestBody.seq : Date.now()
192 const rowVersion =
193 typeof requestBody.rowVersion === `number`
194 ? requestBody.rowVersion
195 : seq
196 await this.collectionPersistence.adapter.applyCommittedTx(
197 eagerTarget(collectionId),
198 {
199 txId,
200 term: 1,
201 seq,
202 rowVersion,
203 mutations: [
204 {
205 type: `insert`,
206 key: requestBody.todo.id,
207 value: requestBody.todo,
208 },
209 ],
210 },
211 )
212​
213 return jsonResponse(200, {
214 ok: true,
215 })
216 }
217 await this.collectionReady
218 const tx = this.collection.insert(requestBody.todo)
219 await tx.when(`settled`)
220​
221 return jsonResponse(200, {
222 ok: true,
223 })
224 }
225​
226 if (request.method === `POST` && url.pathname === `/load-todos`) {
227 if (collectionId !== this.collectionId) {
228 throw createUnknownCollectionError(collectionId)
229 }
230 if (this.syncEnabled) {
231 const rows = await this.collectionPersistence.adapter.loadSubset(
232 eagerTarget(collectionId),
233 {},
234 )
235 return jsonResponse(200, {
236 ok: true,
237 rows: rows.map((row) => ({
238 key: row.key,
239 value: row.value,
240 })),
241 })
242 }
243 await this.collectionReady
244 const rows = this.collection.toArray.map((todo) => ({
245 key: todo.id,
246 value: todo,
247 }))
248 return jsonResponse(200, {
249 ok: true,
250 rows,
251 })
252 }
253​
254 if (
255 request.method === `POST` &&
256 url.pathname === `/load-unknown-collection-error`
257 ) {
258 const unknownCollectionId = requestBody.collectionId ?? `missing`
259 if (unknownCollectionId !== this.collectionId) {
260 throw createUnknownCollectionError(unknownCollectionId)
261 }
262 const rows = await this.persistence.adapter.loadSubset(
263 eagerTarget(unknownCollectionId),
264 {},
265 )
266 return jsonResponse(200, {
267 ok: true,
268 rows,
269 })
270 }
271​
272 return jsonResponse(404, {
273 ok: false,
274 error: {
275 name: `NotFound`,
276 message: `Unknown durable object endpoint "${url.pathname}"`,
277 code: `NOT_FOUND`,
278 },
279 })
280 } catch (error) {
281 return jsonResponse(500, {
282 ok: false,
283 error: serializeError(error),
284 })
285 }
286 }
288​
289export default {
290 async fetch(request, env) {
291 const url = new URL(request.url)
292 if (url.pathname === `/health`) {
293 return jsonResponse(200, {
294 ok: true,
295 })
296 }
297​
298 const id = env.PERSISTENCE.idFromName(`default`)
299 const stub = env.PERSISTENCE.get(id)
300 return stub.fetch(request)
301 },