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

worker.mjs

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