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

worker.mjs

290 lines7.8 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​
101export class PersistenceObject extends DurableObject {
102 constructor(ctx, env) {
103 super(ctx, env)
104 this.collectionId = env.PERSISTENCE_COLLECTION_ID ?? DEFAULT_COLLECTION_ID
105 this.syncEnabled = parseSyncEnabled(env.PERSISTENCE_WITH_SYNC)
106 this.schemaVersion = parseSchemaVersion(env.PERSISTENCE_SCHEMA_VERSION)
107 this.persistence = createCloudflareDOSQLitePersistence({
108 storage: this.ctx.storage,
109 })
110 this.collectionPersistence = resolveCollectionPersistence({
111 persistence: this.persistence,
112 collectionId: this.collectionId,
113 syncEnabled: this.syncEnabled,
114 schemaVersion: this.schemaVersion,
115 })
116 this.ready = this.collectionPersistence.adapter.loadSubset(
117 this.collectionId,
118 {
119 limit: 0,
120 },
121 )
122​
123 const baseCollectionOptions = {
124 id: this.collectionId,
125 schemaVersion: this.schemaVersion,
126 getKey: (todo) => todo.id,
127 persistence: this.persistence,
128 }
129 this.collection = createCollection(
130 this.syncEnabled
131 ? persistedCollectionOptions({
132 ...baseCollectionOptions,
133 sync: {
134 sync: ({ markReady }) => {
135 markReady()
136 },
137 },
138 })
139 : persistedCollectionOptions(baseCollectionOptions),
140 )
141 this.collectionReady = this.collection.stateWhenReady()
142 }
143​
144 async fetch(request) {
145 const url = new URL(request.url)
146​
147 try {
148 if (request.method === `GET` && url.pathname === `/health`) {
149 return jsonResponse(200, {
150 ok: true,
151 })
152 }
153​
154 await this.ready
155​
156 if (request.method === `GET` && url.pathname === `/runtime-config`) {
157 return jsonResponse(200, {
158 ok: true,
159 collectionId: this.collectionId,
160 mode: this.syncEnabled ? `sync` : `local`,
161 syncEnabled: this.syncEnabled,
162 schemaVersion: this.schemaVersion,
163 })
164 }
165​
166 const requestBody = await request.json()
167 const collectionId = requestBody.collectionId ?? this.collectionId
168​
169 if (request.method === `POST` && url.pathname === `/write-todo`) {
170 if (collectionId !== this.collectionId) {
171 throw createUnknownCollectionError(collectionId)
172 }
173 if (this.syncEnabled) {
174 const txId =
175 typeof requestBody.txId === `string`
176 ? requestBody.txId
177 : crypto.randomUUID()
178 const seq =
179 typeof requestBody.seq === `number` ? requestBody.seq : Date.now()
180 const rowVersion =
181 typeof requestBody.rowVersion === `number`
182 ? requestBody.rowVersion
183 : seq
184 await this.collectionPersistence.adapter.applyCommittedTx(
185 collectionId,
186 {
187 txId,
188 term: 1,
189 seq,
190 rowVersion,
191 mutations: [
192 {
193 type: `insert`,
194 key: requestBody.todo.id,
195 value: requestBody.todo,
196 },
197 ],
198 },
199 )
200​
201 return jsonResponse(200, {
202 ok: true,
203 })
204 }
205 await this.collectionReady
206 const tx = this.collection.insert(requestBody.todo)
207 await tx.isPersisted.promise
208​
209 return jsonResponse(200, {
210 ok: true,
211 })
212 }
213​
214 if (request.method === `POST` && url.pathname === `/load-todos`) {
215 if (collectionId !== this.collectionId) {
216 throw createUnknownCollectionError(collectionId)
217 }
218 if (this.syncEnabled) {
219 const rows = await this.collectionPersistence.adapter.loadSubset(
220 collectionId,
221 {},
222 )
223 return jsonResponse(200, {
224 ok: true,
225 rows: rows.map((row) => ({
226 key: row.key,
227 value: row.value,
228 })),
229 })
230 }
231 await this.collectionReady
232 const rows = this.collection.toArray.map((todo) => ({
233 key: todo.id,
234 value: todo,
235 }))
236 return jsonResponse(200, {
237 ok: true,
238 rows,
239 })
240 }
241​
242 if (
243 request.method === `POST` &&
244 url.pathname === `/load-unknown-collection-error`
245 ) {
246 const unknownCollectionId = requestBody.collectionId ?? `missing`
247 if (unknownCollectionId !== this.collectionId) {
248 throw createUnknownCollectionError(unknownCollectionId)
249 }
250 const rows = await this.persistence.adapter.loadSubset(
251 unknownCollectionId,
252 {},
253 )
254 return jsonResponse(200, {
255 ok: true,
256 rows,
257 })
258 }
259​
260 return jsonResponse(404, {
261 ok: false,
262 error: {
263 name: `NotFound`,
264 message: `Unknown durable object endpoint "${url.pathname}"`,
265 code: `NOT_FOUND`,
266 },
267 })
268 } catch (error) {
269 return jsonResponse(500, {
270 ok: false,
271 error: serializeError(error),
272 })
273 }
274 }
276​
277export default {
278 async fetch(request, env) {
279 const url = new URL(request.url)
280 if (url.pathname === `/health`) {
281 return jsonResponse(200, {
282 ok: true,
283 })
284 }
285​
286 const id = env.PERSISTENCE.idFromName(`default`)
287 const stub = env.PERSISTENCE.get(id)
288 return stub.fetch(request)
289 },