@teyik0/furin 0.6.0-alpha.1 → 0.7.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/dist/adapter/runtime-build.d.ts +1 -1
  2. package/dist/build/client.d.ts +4 -1
  3. package/dist/build/elysia-aot-worker.d.ts +22 -0
  4. package/dist/build/elysia-aot.d.ts +1 -1
  5. package/dist/build/entry-template.d.ts +3 -0
  6. package/dist/build/entry-template.ts +7 -0
  7. package/dist/build/hydrate.d.ts +1 -1
  8. package/dist/build/index.js +1880 -401
  9. package/dist/build/preload-manifest.d.ts +17 -0
  10. package/dist/build/types.d.ts +6 -0
  11. package/dist/cli/index.js +1878 -408
  12. package/dist/client/client-module.d.ts +26 -0
  13. package/dist/client/define-route.d.ts +9 -0
  14. package/dist/client/document.d.ts +2 -0
  15. package/dist/client/internal/runtime-types.d.ts +2 -0
  16. package/dist/client/link.js +942 -122
  17. package/dist/client/mutation.d.ts +38 -0
  18. package/dist/client/query-store.d.ts +85 -0
  19. package/dist/client/query.d.ts +14 -0
  20. package/dist/client/route-api.d.ts +11 -0
  21. package/dist/client/router/context.d.ts +3 -2
  22. package/dist/client/router/index.d.ts +1 -1
  23. package/dist/client/router/link-utils.d.ts +8 -1
  24. package/dist/client/router/navigation.d.ts +2 -9
  25. package/dist/client/router/optimistic.d.ts +41 -0
  26. package/dist/client/router/search/index.d.ts +3 -3
  27. package/dist/client/router/search-store.d.ts +1 -0
  28. package/dist/client/router/sync-catch-up.d.ts +3 -0
  29. package/dist/client/router/types.d.ts +51 -7
  30. package/dist/client/sync.d.ts +39 -22
  31. package/dist/client.d.ts +11 -33
  32. package/dist/client.js +1219 -59
  33. package/dist/config.d.ts +7 -0
  34. package/dist/config.js +1 -0
  35. package/dist/define-route.d.ts +78 -32
  36. package/dist/env.d.ts +2 -2
  37. package/dist/furin.d.ts +1 -2
  38. package/dist/furin.js +2484 -708
  39. package/dist/plugin/hmr-dependencies.d.ts +2 -0
  40. package/dist/plugin/index.js +349 -18
  41. package/dist/plugin/transform-client-module.d.ts +16 -0
  42. package/dist/plugin/transform-client.d.ts +2 -0
  43. package/dist/plugin/transform-isomorphic.d.ts +1 -1
  44. package/dist/routes.d.ts +6 -0
  45. package/dist/rsc-client.js +87 -16
  46. package/dist/rsc.js +87 -16
  47. package/dist/server/auto-invalidate/registry.d.ts +1 -0
  48. package/dist/server/auto-invalidate/types.d.ts +2 -0
  49. package/dist/server/cache/isr.d.ts +2 -4
  50. package/dist/server/cache/route-cache.d.ts +5 -0
  51. package/dist/server/dev/graph.d.ts +1 -0
  52. package/dist/server/dev-page-plugin.d.ts +5 -19
  53. package/dist/server/internal.d.ts +3 -0
  54. package/dist/server/internal.js +55 -35
  55. package/dist/server/production-server.js +54 -34
  56. package/dist/server/render/loaders.d.ts +4 -2
  57. package/dist/server/render/react-stream.d.ts +3 -0
  58. package/dist/server/render/ssr.d.ts +2 -1
  59. package/dist/server/render/template.d.ts +4 -0
  60. package/dist/server/router/defined-route.d.ts +2 -0
  61. package/dist/server/router/hmr.d.ts +1 -1
  62. package/dist/server/router/patterns.d.ts +2 -0
  63. package/dist/server/router/types.d.ts +1 -1
  64. package/dist/server/sync/adapter.d.ts +25 -4
  65. package/dist/server/sync/atomic.d.ts +25 -0
  66. package/dist/server/sync/drizzle/index.d.ts +45 -0
  67. package/dist/server/sync/drizzle/index.js +540 -0
  68. package/dist/server/sync/execution-error.d.ts +2 -0
  69. package/dist/server/sync/index.d.ts +2 -1
  70. package/dist/server/sync/index.js +533 -105
  71. package/dist/server/sync/mutation-handler.d.ts +4 -0
  72. package/dist/server/sync/plugin.d.ts +34 -11
  73. package/dist/server/sync/postgres/execute.d.ts +3 -0
  74. package/dist/server/sync/postgres/index.d.ts +12 -1
  75. package/dist/server/sync/postgres/index.js +34 -13
  76. package/dist/server/sync/postgres/sql.d.ts +8 -0
  77. package/dist/server/sync/prisma/index.d.ts +24 -0
  78. package/dist/server/sync/prisma/index.js +340 -0
  79. package/dist/server/sync/queries.d.ts +21 -0
  80. package/dist/server/sync/query-context.d.ts +5 -0
  81. package/dist/server/sync/redis/index.js +3 -3
  82. package/dist/server/sync/redis/scripts.d.ts +1 -1
  83. package/dist/server/sync/response.d.ts +1 -0
  84. package/dist/server/sync/sqlite/index.d.ts +3 -0
  85. package/dist/server/sync/sqlite/index.js +10 -4
  86. package/dist/server/sync/stream.d.ts +2 -5
  87. package/dist/server/sync/validation.d.ts +4 -0
  88. package/dist/shared/defer.d.ts +31 -0
  89. package/dist/shared/error.d.ts +2 -2
  90. package/dist/shared/page-key.d.ts +7 -0
  91. package/dist/shared/query-bindings.d.ts +12 -0
  92. package/dist/shared/route-frame.d.ts +1 -0
  93. package/dist/shared/sync-query.d.ts +40 -0
  94. package/package.json +29 -6
  95. package/src/adapter/package.ts +12 -2
  96. package/src/adapter/runtime-build.ts +63 -12
  97. package/src/adapter/static.ts +7 -2
  98. package/src/adapter/vercel.ts +15 -13
  99. package/src/build/client.ts +23 -5
  100. package/src/build/elysia-aot-worker.ts +51 -0
  101. package/src/build/elysia-aot.ts +83 -19
  102. package/src/build/entry-template.ts +7 -0
  103. package/src/build/hydrate.ts +21 -3
  104. package/src/build/preload-manifest.ts +100 -0
  105. package/src/build/production-instrumentation.ts +6 -3
  106. package/src/build/types.ts +4 -0
  107. package/src/cli/index.ts +1 -0
  108. package/src/client/browser-events-runtime.ts +4 -0
  109. package/src/client/client-module.ts +57 -0
  110. package/src/client/define-route.ts +11 -1
  111. package/src/client/document.tsx +28 -18
  112. package/src/client/hmr.ts +2 -1
  113. package/src/client/internal/runtime-types.ts +2 -0
  114. package/src/client/link.tsx +8 -8
  115. package/src/client/mutation.ts +136 -0
  116. package/src/client/query-store.ts +418 -0
  117. package/src/client/query.tsx +67 -0
  118. package/src/client/route-api.tsx +75 -0
  119. package/src/client/router/boundary-tree.tsx +19 -12
  120. package/src/client/router/context.ts +57 -4
  121. package/src/client/router/index.ts +3 -0
  122. package/src/client/router/link-utils.ts +29 -1
  123. package/src/client/router/navigation.ts +3 -50
  124. package/src/client/router/optimistic.ts +233 -0
  125. package/src/client/router/provider.tsx +306 -46
  126. package/src/client/router/search/index.ts +37 -17
  127. package/src/client/router/search-store.ts +4 -0
  128. package/src/client/router/sync-catch-up.ts +7 -0
  129. package/src/client/router/types.ts +73 -9
  130. package/src/client/sync.ts +438 -65
  131. package/src/client.ts +20 -60
  132. package/src/config.ts +5 -0
  133. package/src/define-route.ts +113 -55
  134. package/src/env.d.ts +2 -2
  135. package/src/furin.ts +75 -13
  136. package/src/plugin/hmr-dependencies.ts +58 -0
  137. package/src/plugin/index.ts +38 -2
  138. package/src/plugin/routes.ts +28 -16
  139. package/src/plugin/transform-client-module.ts +123 -0
  140. package/src/plugin/transform-client.ts +293 -13
  141. package/src/plugin/transform-isomorphic.ts +11 -5
  142. package/src/routes.ts +8 -0
  143. package/src/rsc/shared.tsx +104 -18
  144. package/src/server/auto-invalidate/registry.ts +4 -0
  145. package/src/server/auto-invalidate/runtime.ts +17 -0
  146. package/src/server/auto-invalidate/types.ts +6 -0
  147. package/src/server/cache/isr.ts +6 -34
  148. package/src/server/cache/route-cache.ts +40 -4
  149. package/src/server/dev/graph.ts +16 -2
  150. package/src/server/dev-page-plugin.ts +93 -59
  151. package/src/server/internal.ts +3 -0
  152. package/src/server/render/document.tsx +10 -1
  153. package/src/server/render/element.tsx +21 -11
  154. package/src/server/render/isr.ts +61 -29
  155. package/src/server/render/loaders.ts +118 -47
  156. package/src/server/render/mixed-cache.ts +33 -4
  157. package/src/server/render/not-found.ts +4 -7
  158. package/src/server/render/ppr-document.ts +2 -1
  159. package/src/server/render/ppr-route.ts +30 -10
  160. package/src/server/render/react-stream.ts +17 -0
  161. package/src/server/render/route-frame-transport.ts +3 -0
  162. package/src/server/render/ssg.ts +51 -18
  163. package/src/server/render/ssr.ts +53 -8
  164. package/src/server/render/template.ts +23 -0
  165. package/src/server/router/defined-route.ts +3 -0
  166. package/src/server/router/discovery.ts +25 -9
  167. package/src/server/router/hmr.ts +3 -2
  168. package/src/server/router/patterns.ts +16 -0
  169. package/src/server/router/plugin.ts +27 -12
  170. package/src/server/router/types.ts +1 -1
  171. package/src/server/sync/adapter.ts +41 -4
  172. package/src/server/sync/atomic.ts +303 -0
  173. package/src/server/sync/drizzle/index.ts +145 -0
  174. package/src/server/sync/execution-error.ts +1 -0
  175. package/src/server/sync/fingerprint.ts +2 -6
  176. package/src/server/sync/index.ts +6 -0
  177. package/src/server/sync/mutation-handler.ts +69 -0
  178. package/src/server/sync/plugin.ts +177 -60
  179. package/src/server/sync/postgres/execute.ts +20 -0
  180. package/src/server/sync/postgres/index.ts +52 -16
  181. package/src/server/sync/postgres/sql.ts +20 -0
  182. package/src/server/sync/prisma/index.ts +70 -0
  183. package/src/server/sync/queries.ts +75 -0
  184. package/src/server/sync/query-context.ts +85 -0
  185. package/src/server/sync/redis/index.ts +7 -3
  186. package/src/server/sync/redis/scripts.ts +1 -1
  187. package/src/server/sync/response.ts +21 -0
  188. package/src/server/sync/sqlite/index.ts +19 -8
  189. package/src/server/sync/stream.ts +14 -22
  190. package/src/server/sync/validation.ts +34 -0
  191. package/src/shared/defer.ts +48 -0
  192. package/src/shared/error.ts +2 -2
  193. package/src/shared/page-key.ts +36 -0
  194. package/src/shared/query-bindings.ts +138 -0
  195. package/src/shared/route-frame.ts +13 -1
  196. package/src/shared/route-map.ts +12 -2
  197. package/src/shared/sync-query.ts +138 -0
@@ -0,0 +1,540 @@
1
+ // @bun
2
+ // src/server/sync/drizzle/index.ts
3
+ import { Database } from "bun:sqlite";
4
+ import { sql as drizzleSql } from "drizzle-orm";
5
+
6
+ // src/server/sync/execution-error.ts
7
+ class MutationLeaseLost extends Error {
8
+ }
9
+
10
+ // src/server/sync/postgres/execute.ts
11
+ async function executePostgresMutation(journal, lease, tx, callback) {
12
+ if (!await journal.lockMutation(lease)) {
13
+ throw new MutationLeaseLost("[furin] Mutation lease lost; the transaction was rolled back.");
14
+ }
15
+ const result = await callback(tx);
16
+ const completion = await journal.completeLockedMutation({ ...result, lease });
17
+ if (completion.kind === "lost") {
18
+ throw new MutationLeaseLost("[furin] Mutation lease lost; the transaction was rolled back.");
19
+ }
20
+ return { ...result, cursor: completion.cursor, kind: "committed" };
21
+ }
22
+
23
+ // src/server/sync/postgres/index.ts
24
+ var CHANGE_RETENTION = 1000;
25
+ var LEASE_MS = 30000;
26
+ var MUTATION_TTL_MS = 24 * 60 * 60 * 1000;
27
+ var UNSIGNED_INTEGER_PATTERN = /^\d+$/;
28
+ function notificationChannel(namespace) {
29
+ const digest = new Bun.CryptoHasher("sha256").update(namespace).digest("hex");
30
+ return `furin_sync_${digest.slice(0, 52)}`;
31
+ }
32
+ async function readCurrentCursor(sql, namespace) {
33
+ const rows = await sql`
34
+ SELECT current_cursor FROM furin_sync.streams WHERE namespace = ${namespace}
35
+ `;
36
+ return String(rows[0]?.current_cursor ?? 0);
37
+ }
38
+ function mutationKey(input) {
39
+ return new Bun.CryptoHasher("sha256").update(`${input.principal.length}:${input.principal}${input.key}`).digest("hex");
40
+ }
41
+ function storedResponse(row) {
42
+ if (row.response_body === null || row.response_headers === null || row.response_status === null) {
43
+ throw new Error("[furin-sync-postgres] Succeeded mutation has no replay response.");
44
+ }
45
+ return {
46
+ body: new Uint8Array(row.response_body),
47
+ headers: row.response_headers,
48
+ status: row.response_status
49
+ };
50
+ }
51
+
52
+ class PostgresSyncAdapter {
53
+ notificationChannel;
54
+ publishesNotifications;
55
+ scope = "distributed";
56
+ namespace;
57
+ sql;
58
+ constructor(options) {
59
+ if (options.namespace.length === 0) {
60
+ throw new Error("[furin-sync-postgres] namespace must not be empty.");
61
+ }
62
+ this.notificationChannel = notificationChannel(options.namespace);
63
+ this.publishesNotifications = options.publishNotifications !== false;
64
+ this.namespace = options.namespace;
65
+ this.sql = options.sql;
66
+ }
67
+ beginMutation(input) {
68
+ return this.sql.begin(async (tx) => {
69
+ const key = mutationKey(input);
70
+ const [lock] = await tx`
71
+ SELECT pg_try_advisory_xact_lock(hashtextextended(${`${this.namespace}:${key}`}, 0)) AS acquired
72
+ `;
73
+ if (!lock?.acquired) {
74
+ return { kind: "conflict", reason: "in-progress" };
75
+ }
76
+ await tx`
77
+ DELETE FROM furin_sync.mutations
78
+ WHERE ctid IN (
79
+ SELECT ctid FROM furin_sync.mutations
80
+ WHERE
81
+ (state = 'succeeded' AND expires_at <= clock_timestamp())
82
+ OR (
83
+ state = 'in-progress'
84
+ AND lease_expires_at <= clock_timestamp()
85
+ AND expires_at <= clock_timestamp()
86
+ )
87
+ LIMIT 100
88
+ FOR UPDATE SKIP LOCKED
89
+ )
90
+ `;
91
+ const rows = await tx`
92
+ SELECT mutation_id, fingerprint, state, response_status, response_headers,
93
+ response_body,
94
+ CASE
95
+ WHEN state = 'succeeded' THEN expires_at <= clock_timestamp()
96
+ ELSE lease_expires_at <= clock_timestamp()
97
+ END AS expired
98
+ FROM furin_sync.mutations
99
+ WHERE namespace = ${this.namespace} AND mutation_key = ${key}
100
+ FOR UPDATE
101
+ `;
102
+ const [existing] = rows;
103
+ if (existing && existing.fingerprint !== input.fingerprint) {
104
+ return { kind: "conflict", reason: "payload-mismatch" };
105
+ }
106
+ if (existing && !existing.expired) {
107
+ if (existing.state === "in-progress") {
108
+ return { kind: "conflict", reason: "in-progress" };
109
+ }
110
+ return { kind: "replay", response: storedResponse(existing) };
111
+ }
112
+ const id = crypto.randomUUID();
113
+ await tx`
114
+ INSERT INTO furin_sync.mutations (
115
+ namespace, mutation_key, mutation_id, fingerprint, state,
116
+ lease_expires_at, expires_at, created_at
117
+ ) VALUES (
118
+ ${this.namespace}, ${key}, ${id}, ${input.fingerprint}, 'in-progress',
119
+ clock_timestamp() + (${LEASE_MS} * interval '1 millisecond'),
120
+ clock_timestamp() + (${MUTATION_TTL_MS} * interval '1 millisecond'),
121
+ clock_timestamp()
122
+ )
123
+ ON CONFLICT (namespace, mutation_key) DO UPDATE SET
124
+ mutation_id = EXCLUDED.mutation_id,
125
+ fingerprint = EXCLUDED.fingerprint,
126
+ state = 'in-progress',
127
+ response_status = NULL,
128
+ response_headers = NULL,
129
+ response_body = NULL,
130
+ lease_expires_at = EXCLUDED.lease_expires_at,
131
+ expires_at = EXCLUDED.expires_at,
132
+ created_at = EXCLUDED.created_at,
133
+ completed_at = NULL
134
+ `;
135
+ return {
136
+ kind: "execute",
137
+ lease: { id, key: input.key, leaseMs: LEASE_MS, principal: input.principal }
138
+ };
139
+ });
140
+ }
141
+ async renewMutation(lease) {
142
+ const rows = await this.sql`
143
+ UPDATE furin_sync.mutations
144
+ SET lease_expires_at = clock_timestamp() + (${lease.leaseMs} * interval '1 millisecond')
145
+ WHERE namespace = ${this.namespace}
146
+ AND mutation_key = ${mutationKey(lease)}
147
+ AND mutation_id = ${lease.id}
148
+ AND state = 'in-progress'
149
+ AND lease_expires_at > clock_timestamp()
150
+ RETURNING mutation_id
151
+ `;
152
+ return rows.length === 1 ? "renewed" : "lost";
153
+ }
154
+ completeMutation(input) {
155
+ return this.completeMutationInTransaction(input, true);
156
+ }
157
+ completeLockedMutation(input) {
158
+ return this.completeMutationInTransaction(input, false);
159
+ }
160
+ completeMutationInTransaction(input, checkExpiration) {
161
+ return this.sql.begin(async (tx) => {
162
+ const key = mutationKey(input.lease);
163
+ if (!await this.lockMutationInTransaction(tx, input.lease, checkExpiration)) {
164
+ return { kind: "lost" };
165
+ }
166
+ let cursor;
167
+ if (input.invalidations.length > 0) {
168
+ await tx`
169
+ INSERT INTO furin_sync.streams (namespace, current_cursor, oldest_cursor)
170
+ VALUES (${this.namespace}, 0, 0)
171
+ ON CONFLICT (namespace) DO NOTHING
172
+ `;
173
+ const cursors = await tx`
174
+ UPDATE furin_sync.streams
175
+ SET current_cursor = current_cursor + 1
176
+ WHERE namespace = ${this.namespace}
177
+ RETURNING current_cursor
178
+ `;
179
+ cursor = String(cursors[0]?.current_cursor);
180
+ await tx`
181
+ INSERT INTO furin_sync.changes (namespace, cursor, invalidations)
182
+ VALUES (
183
+ ${this.namespace},
184
+ ${cursor},
185
+ ${JSON.stringify(input.invalidations)}::text::jsonb
186
+ )
187
+ `;
188
+ await tx`
189
+ WITH removed AS (
190
+ DELETE FROM furin_sync.changes
191
+ WHERE namespace = ${this.namespace}
192
+ AND cursor <= GREATEST(0, ${cursor}::bigint - ${CHANGE_RETENTION})
193
+ RETURNING cursor
194
+ )
195
+ UPDATE furin_sync.streams
196
+ SET oldest_cursor = COALESCE((SELECT MAX(cursor) + 1 FROM removed), oldest_cursor)
197
+ WHERE namespace = ${this.namespace}
198
+ `;
199
+ }
200
+ await tx`
201
+ UPDATE furin_sync.mutations
202
+ SET state = 'succeeded',
203
+ response_status = ${input.response.status},
204
+ response_headers = ${JSON.stringify(input.response.headers)}::text::jsonb,
205
+ response_body = ${input.response.body},
206
+ completed_at = clock_timestamp(),
207
+ expires_at = clock_timestamp() + (${MUTATION_TTL_MS} * interval '1 millisecond')
208
+ WHERE namespace = ${this.namespace}
209
+ AND mutation_key = ${key}
210
+ AND mutation_id = ${input.lease.id}
211
+ `;
212
+ if (cursor !== undefined && this.publishesNotifications) {
213
+ await tx.notify(this.notificationChannel, cursor);
214
+ }
215
+ return { cursor, kind: "committed" };
216
+ });
217
+ }
218
+ lockMutation(lease) {
219
+ return this.sql.begin((tx) => this.lockMutationInTransaction(tx, lease, true));
220
+ }
221
+ async lockMutationInTransaction(tx, lease, checkExpiration) {
222
+ const key = mutationKey(lease);
223
+ await tx`SELECT pg_advisory_xact_lock(hashtextextended(${`${this.namespace}:${key}`}, 0))::text`;
224
+ const active = await tx`
225
+ SELECT mutation_id FROM furin_sync.mutations
226
+ WHERE namespace = ${this.namespace}
227
+ AND mutation_key = ${key}
228
+ AND mutation_id = ${lease.id}
229
+ AND state = 'in-progress'
230
+ AND (NOT ${checkExpiration} OR lease_expires_at > clock_timestamp())
231
+ FOR UPDATE
232
+ `;
233
+ return active.length > 0;
234
+ }
235
+ async abortMutation(lease) {
236
+ await this.sql`
237
+ DELETE FROM furin_sync.mutations
238
+ WHERE namespace = ${this.namespace}
239
+ AND mutation_key = ${mutationKey(lease)}
240
+ AND mutation_id = ${lease.id}
241
+ AND state = 'in-progress'
242
+ `;
243
+ }
244
+ currentCursor() {
245
+ return readCurrentCursor(this.sql, this.namespace);
246
+ }
247
+ async readChanges(input) {
248
+ const cursorRows = await this.sql`
249
+ SELECT current_cursor, oldest_cursor
250
+ FROM furin_sync.streams WHERE namespace = ${this.namespace}
251
+ `;
252
+ const currentCursor = String(cursorRows[0]?.current_cursor ?? 0);
253
+ if (input.after === undefined) {
254
+ return { changes: [], cursor: currentCursor, hasMore: false, reset: false };
255
+ }
256
+ if (!UNSIGNED_INTEGER_PATTERN.test(input.after)) {
257
+ return { changes: [], cursor: currentCursor, hasMore: false, reset: true };
258
+ }
259
+ if (BigInt(input.after) > BigInt(currentCursor)) {
260
+ return { changes: [], cursor: currentCursor, hasMore: false, reset: true };
261
+ }
262
+ const oldest = BigInt(cursorRows[0]?.oldest_cursor ?? 0);
263
+ if (BigInt(input.after) < oldest - 1n) {
264
+ return { changes: [], cursor: currentCursor, hasMore: false, reset: true };
265
+ }
266
+ const rows = await this.sql`
267
+ SELECT cursor, invalidations
268
+ FROM furin_sync.changes
269
+ WHERE namespace = ${this.namespace} AND cursor > ${input.after}::bigint
270
+ ORDER BY cursor ASC
271
+ LIMIT ${input.limit + 1}
272
+ `;
273
+ const latestCursorRows = await this.sql`
274
+ SELECT current_cursor, oldest_cursor
275
+ FROM furin_sync.streams WHERE namespace = ${this.namespace}
276
+ `;
277
+ const latestCurrentCursor = String(latestCursorRows[0]?.current_cursor ?? 0);
278
+ const latestOldest = BigInt(latestCursorRows[0]?.oldest_cursor ?? 0);
279
+ if (BigInt(input.after) < latestOldest - 1n) {
280
+ return {
281
+ changes: [],
282
+ cursor: latestCurrentCursor,
283
+ hasMore: false,
284
+ reset: true
285
+ };
286
+ }
287
+ const hasMore = rows.length > input.limit;
288
+ const changes = rows.slice(0, input.limit).map((row) => ({
289
+ cursor: String(row.cursor),
290
+ invalidations: row.invalidations
291
+ }));
292
+ return {
293
+ changes,
294
+ cursor: changes.at(-1)?.cursor ?? input.after,
295
+ hasMore,
296
+ reset: false
297
+ };
298
+ }
299
+ }
300
+
301
+ // src/server/sync/postgres/sql.ts
302
+ function transactionSql(query) {
303
+ const sql = (strings, ...values) => query(strings, values);
304
+ sql.begin = (callback) => callback(sql);
305
+ sql.notify = async (channel, cursor) => {
306
+ await sql`SELECT pg_notify(${channel}, ${cursor})::text`;
307
+ };
308
+ return sql;
309
+ }
310
+
311
+ // src/server/sync/sqlite/index.ts
312
+ var CHANGE_RETENTION2 = 1000;
313
+ var LEASE_MS2 = 30000;
314
+ var MUTATION_TTL_MS2 = 24 * 60 * 60 * 1000;
315
+ var UNSIGNED_INTEGER_PATTERN2 = /^\d+$/;
316
+ function mutationKey2(input) {
317
+ return `${input.principal.length}:${input.principal}${input.key}`;
318
+ }
319
+ function storedResponse2(row) {
320
+ if (row.response_body === null || row.response_headers === null || row.response_status === null) {
321
+ throw new Error("[furin-sync-sqlite] Succeeded mutation has no replay response.");
322
+ }
323
+ return {
324
+ body: new Uint8Array(row.response_body),
325
+ headers: JSON.parse(row.response_headers),
326
+ status: row.response_status
327
+ };
328
+ }
329
+ class SqliteSyncAdapter {
330
+ scope;
331
+ database;
332
+ namespace;
333
+ constructor(options) {
334
+ if (options.namespace.length === 0) {
335
+ throw new Error("[furin-sync-sqlite] namespace must not be empty.");
336
+ }
337
+ this.database = options.database;
338
+ this.namespace = options.namespace;
339
+ this.scope = options.database.filename === "" || options.database.filename === ":memory:" ? "process-local" : "host-local";
340
+ }
341
+ async beginMutation(input) {
342
+ return this.beginMutationSync(input);
343
+ }
344
+ beginMutationSync(input) {
345
+ const transaction = this.database.transaction((mutation) => {
346
+ const now = Date.now();
347
+ const key = mutationKey2(mutation);
348
+ this.database.query(`DELETE FROM furin_sync_mutations WHERE rowid IN (
349
+ SELECT rowid FROM furin_sync_mutations
350
+ WHERE
351
+ (state = 'succeeded' AND expires_at <= ?)
352
+ OR (
353
+ state = 'in-progress'
354
+ AND lease_expires_at <= ?
355
+ AND expires_at <= ?
356
+ )
357
+ LIMIT 100
358
+ )`).run(now, now, now);
359
+ const existing = this.database.query(`SELECT mutation_id, fingerprint, state, response_status, response_headers,
360
+ response_body, lease_expires_at, expires_at
361
+ FROM furin_sync_mutations
362
+ WHERE namespace = ? AND mutation_key = ?`).get(this.namespace, key);
363
+ if (existing?.fingerprint !== undefined && existing.fingerprint !== mutation.fingerprint) {
364
+ return { kind: "conflict", reason: "payload-mismatch" };
365
+ }
366
+ const expired = existing?.state === "in-progress" ? existing.lease_expires_at <= now : existing?.expires_at !== undefined && existing.expires_at <= now;
367
+ if (existing && !expired) {
368
+ return existing.state === "in-progress" ? { kind: "conflict", reason: "in-progress" } : { kind: "replay", response: storedResponse2(existing) };
369
+ }
370
+ const id = crypto.randomUUID();
371
+ this.database.query(`INSERT INTO furin_sync_mutations (
372
+ namespace, mutation_key, mutation_id, fingerprint, state,
373
+ lease_expires_at, expires_at, created_at
374
+ ) VALUES (?, ?, ?, ?, 'in-progress', ?, ?, ?)
375
+ ON CONFLICT (namespace, mutation_key) DO UPDATE SET
376
+ mutation_id = excluded.mutation_id,
377
+ fingerprint = excluded.fingerprint,
378
+ state = 'in-progress',
379
+ response_status = NULL,
380
+ response_headers = NULL,
381
+ response_body = NULL,
382
+ lease_expires_at = excluded.lease_expires_at,
383
+ expires_at = excluded.expires_at,
384
+ created_at = excluded.created_at,
385
+ completed_at = NULL`).run(this.namespace, key, id, mutation.fingerprint, now + LEASE_MS2, now + MUTATION_TTL_MS2, now);
386
+ return {
387
+ kind: "execute",
388
+ lease: { id, key: mutation.key, leaseMs: LEASE_MS2, principal: mutation.principal }
389
+ };
390
+ });
391
+ return transaction.immediate(input);
392
+ }
393
+ async completeMutation(input) {
394
+ return this.completeMutationSync(input);
395
+ }
396
+ completeMutationSync(input) {
397
+ const transaction = this.database.transaction((completion) => {
398
+ const now = Date.now();
399
+ const key = mutationKey2(completion.lease);
400
+ if (!this.hasMutationLeaseSync(completion.lease)) {
401
+ return { kind: "lost" };
402
+ }
403
+ let cursor;
404
+ if (completion.invalidations.length > 0) {
405
+ this.database.query(`INSERT INTO furin_sync_streams (namespace, current_cursor, oldest_cursor)
406
+ VALUES (?, 0, 0) ON CONFLICT (namespace) DO NOTHING`).run(this.namespace);
407
+ this.database.query(`UPDATE furin_sync_streams SET current_cursor = current_cursor + 1
408
+ WHERE namespace = ?`).run(this.namespace);
409
+ const cursorRow = this.database.query(`SELECT CAST(current_cursor AS TEXT) AS current_cursor
410
+ FROM furin_sync_streams WHERE namespace = ?`).get(this.namespace);
411
+ if (!cursorRow) {
412
+ throw new Error("[furin-sync-sqlite] Could not allocate a change cursor.");
413
+ }
414
+ cursor = cursorRow.current_cursor;
415
+ this.database.query(`INSERT INTO furin_sync_changes (namespace, cursor, invalidations, created_at)
416
+ VALUES (?, ?, ?, ?)`).run(this.namespace, cursorRow.current_cursor, JSON.stringify(completion.invalidations), now);
417
+ const removed = this.database.query(`DELETE FROM furin_sync_changes
418
+ WHERE namespace = ? AND cursor <= MAX(0, CAST(? AS INTEGER) - ?)`).run(this.namespace, cursorRow.current_cursor, CHANGE_RETENTION2);
419
+ if (removed.changes > 0) {
420
+ const oldest = this.database.query(`SELECT CAST(MIN(cursor) AS TEXT) AS cursor
421
+ FROM furin_sync_changes WHERE namespace = ?`).get(this.namespace);
422
+ this.database.query("UPDATE furin_sync_streams SET oldest_cursor = ? WHERE namespace = ?").run(oldest?.cursor ?? cursorRow.current_cursor, this.namespace);
423
+ }
424
+ }
425
+ this.database.query(`UPDATE furin_sync_mutations
426
+ SET state = 'succeeded', response_status = ?, response_headers = ?,
427
+ response_body = ?, completed_at = ?, expires_at = ?
428
+ WHERE namespace = ? AND mutation_key = ? AND mutation_id = ?`).run(completion.response.status, JSON.stringify(completion.response.headers), completion.response.body, now, now + MUTATION_TTL_MS2, this.namespace, key, completion.lease.id);
429
+ return { cursor, kind: "committed" };
430
+ });
431
+ return transaction.immediate(input);
432
+ }
433
+ hasMutationLeaseSync(lease) {
434
+ return this.database.query(`SELECT mutation_id FROM furin_sync_mutations WHERE namespace = ? AND mutation_key = ? AND mutation_id = ? AND state = 'in-progress' AND lease_expires_at > ?`).get(this.namespace, mutationKey2(lease), lease.id, Date.now()) !== null;
435
+ }
436
+ async abortMutation(lease) {
437
+ this.database.query(`DELETE FROM furin_sync_mutations
438
+ WHERE namespace = ? AND mutation_key = ? AND mutation_id = ? AND state = 'in-progress'`).run(this.namespace, mutationKey2(lease), lease.id);
439
+ }
440
+ async currentCursor() {
441
+ const row = this.database.query(`SELECT CAST(current_cursor AS TEXT) AS current_cursor
442
+ FROM furin_sync_streams WHERE namespace = ?`).get(this.namespace);
443
+ return row?.current_cursor ?? "0";
444
+ }
445
+ async readChanges(input) {
446
+ const transaction = this.database.transaction((page) => {
447
+ const cursorRow = this.database.query(`SELECT CAST(current_cursor AS TEXT) AS current_cursor,
448
+ CAST(oldest_cursor AS TEXT) AS oldest_cursor
449
+ FROM furin_sync_streams WHERE namespace = ?`).get(this.namespace);
450
+ const currentCursor = cursorRow?.current_cursor ?? "0";
451
+ if (page.after === undefined) {
452
+ return { changes: [], cursor: currentCursor, hasMore: false, reset: false };
453
+ }
454
+ if (!UNSIGNED_INTEGER_PATTERN2.test(page.after) || BigInt(page.after) > BigInt(currentCursor) || BigInt(page.after) < BigInt(cursorRow?.oldest_cursor ?? "0") - 1n) {
455
+ return { changes: [], cursor: currentCursor, hasMore: false, reset: true };
456
+ }
457
+ const rows = this.database.query(`SELECT CAST(cursor AS TEXT) AS cursor, invalidations FROM furin_sync_changes
458
+ WHERE namespace = ? AND cursor > CAST(? AS INTEGER) ORDER BY cursor ASC LIMIT ?`).all(this.namespace, page.after, page.limit + 1);
459
+ const hasMore = rows.length > page.limit;
460
+ const changes = rows.slice(0, page.limit).map((row) => ({
461
+ cursor: row.cursor,
462
+ invalidations: JSON.parse(row.invalidations)
463
+ }));
464
+ return {
465
+ changes,
466
+ cursor: changes.at(-1)?.cursor ?? page.after,
467
+ hasMore,
468
+ reset: false
469
+ };
470
+ });
471
+ return transaction(input);
472
+ }
473
+ async renewMutation(lease) {
474
+ const now = Date.now();
475
+ const result = this.database.query(`UPDATE furin_sync_mutations SET lease_expires_at = ?
476
+ WHERE namespace = ? AND mutation_key = ? AND mutation_id = ?
477
+ AND state = 'in-progress' AND lease_expires_at > ?`).run(now + lease.leaseMs, this.namespace, mutationKey2(lease), lease.id, now);
478
+ return result.changes === 1 ? "renewed" : "lost";
479
+ }
480
+ }
481
+
482
+ // src/server/sync/drizzle/index.ts
483
+ class DrizzleSqliteSyncAdapter extends SqliteSyncAdapter {
484
+ transactionMode = "sync";
485
+ db;
486
+ constructor(options) {
487
+ super({ database: options.db.$client, namespace: options.namespace });
488
+ this.db = options.db;
489
+ }
490
+ async executeMutation(lease, callback) {
491
+ return this.db.transaction((tx) => {
492
+ if (!this.hasMutationLeaseSync(lease)) {
493
+ throw new MutationLeaseLost("[furin] Mutation lease lost; the transaction was rolled back.");
494
+ }
495
+ const result = callback(tx);
496
+ if (result instanceof Promise) {
497
+ throw new Error("[furin] Bun SQLite mutation callbacks must be synchronous.");
498
+ }
499
+ const completion = this.completeMutationSync({ ...result, lease });
500
+ if (completion.kind === "lost") {
501
+ throw new MutationLeaseLost("[furin] Mutation lease lost; the transaction was rolled back.");
502
+ }
503
+ return { ...result, cursor: completion.cursor, kind: "committed" };
504
+ }, { behavior: "immediate" });
505
+ }
506
+ }
507
+
508
+ class DrizzlePostgresSyncAdapter extends PostgresSyncAdapter {
509
+ transactionMode = "async";
510
+ db;
511
+ syncNamespace;
512
+ constructor(options) {
513
+ const sql = transactionSql((strings, values) => Promise.resolve(options.db.execute(drizzleSql(strings, ...values))).then((rows) => rows));
514
+ sql.begin = (callback) => options.db.transaction((tx) => callback(transactionSql((strings, values) => Promise.resolve(tx.execute(drizzleSql(strings, ...values))).then((rows) => rows))));
515
+ super({ namespace: options.namespace, sql, publishNotifications: false });
516
+ this.db = options.db;
517
+ this.syncNamespace = options.namespace;
518
+ }
519
+ executeMutation(lease, callback) {
520
+ return this.db.transaction((tx) => {
521
+ const sql = transactionSql((strings, values) => Promise.resolve(tx.execute(drizzleSql(strings, ...values))).then((rows) => rows));
522
+ return executePostgresMutation(new PostgresSyncAdapter({
523
+ namespace: this.syncNamespace,
524
+ sql,
525
+ publishNotifications: false
526
+ }), lease, tx, callback);
527
+ });
528
+ }
529
+ }
530
+ function drizzleSyncAdapter(options) {
531
+ if (!(options.db.$client instanceof Database)) {
532
+ return new DrizzlePostgresSyncAdapter(options);
533
+ }
534
+ return new DrizzleSqliteSyncAdapter(options);
535
+ }
536
+ export {
537
+ DrizzlePostgresSyncAdapter,
538
+ DrizzleSqliteSyncAdapter,
539
+ drizzleSyncAdapter
540
+ };
@@ -0,0 +1,2 @@
1
+ export declare class MutationLeaseLost extends Error {
2
+ }
@@ -9,7 +9,8 @@ export declare const PollingSyncNotifier: typeof PollingSyncNotifierImplementati
9
9
  export declare const resolveSyncPath: typeof resolveSyncPathImplementation;
10
10
  export declare const runWithSyncPath: typeof runWithSyncPathImplementation;
11
11
  export type PollingSyncNotifier = PollingSyncNotifierImplementation;
12
- export type { BeginMutationInput, BeginMutationResult, ChangePage, CompleteMutationInput, CompleteMutationResult, MutationLease, ReadChangesInput, StoredResponse, SyncAdapter, SyncChange, SyncInvalidation, SyncNotifier, SyncRuntimeOptions, SyncSubscription, } from "./adapter.ts";
12
+ export type { SyncInvalidationInput } from "../auto-invalidate/types.ts";
13
+ export type { AtomicMutationResult, AtomicMutationValue, BeginMutationInput, BeginMutationResult, ChangePage, CompleteMutationInput, CompleteMutationResult, MutationLease, ReadChangesInput, StoredResponse, SyncAdapter, SyncChange, SyncInvalidation, SyncMutation, SyncNotifier, SyncRuntimeOptions, SyncSubscription, SyncTransaction, TransactionalSyncAdapter, } from "./adapter.ts";
13
14
  export type { FurinSyncOption, FurinSyncOptions } from "./config.ts";
14
15
  export type { SyncInput, SyncRouteOption } from "./plugin.ts";
15
16
  export type { SyncChangePage } from "./stream.ts";