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

worker.mjs

286 lines7.6 KB

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