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

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 (230) hide show
  1. package/dist/adapter/runtime-build.d.ts +3 -1
  2. package/dist/build/client.d.ts +4 -1
  3. package/dist/build/entry-template.d.ts +5 -0
  4. package/dist/build/entry-template.ts +9 -0
  5. package/dist/build/hydrate.d.ts +1 -1
  6. package/dist/build/index.js +9589 -6685
  7. package/dist/build/preload-manifest.d.ts +17 -0
  8. package/dist/build/request-keys.d.ts +4 -0
  9. package/dist/build/types.d.ts +6 -0
  10. package/dist/cli/index.js +9539 -6644
  11. package/dist/client/browser-events-runtime.d.ts +2 -1
  12. package/dist/client/client-module.d.ts +26 -0
  13. package/dist/client/define-route.d.ts +9 -1
  14. package/dist/client/dev-error-overlay.ts +1 -0
  15. package/dist/client/document.d.ts +3 -0
  16. package/dist/client/hmr.d.ts +1 -1
  17. package/dist/client/internal/runtime-types.d.ts +2 -0
  18. package/dist/client/link.js +1011 -157
  19. package/dist/client/mutation.d.ts +38 -0
  20. package/dist/client/query-store.d.ts +85 -0
  21. package/dist/client/query.d.ts +14 -0
  22. package/dist/client/route-api.d.ts +11 -0
  23. package/dist/client/router/context.d.ts +3 -2
  24. package/dist/client/router/index.d.ts +1 -1
  25. package/dist/client/router/link-utils.d.ts +8 -1
  26. package/dist/client/router/navigation.d.ts +2 -9
  27. package/dist/client/router/optimistic.d.ts +41 -0
  28. package/dist/client/router/search/index.d.ts +3 -3
  29. package/dist/client/router/search-store.d.ts +1 -0
  30. package/dist/client/router/sync-catch-up.d.ts +3 -0
  31. package/dist/client/router/types.d.ts +49 -7
  32. package/dist/client/sync.d.ts +39 -22
  33. package/dist/client.d.ts +11 -33
  34. package/dist/client.js +1222 -57
  35. package/dist/config.d.ts +7 -0
  36. package/dist/config.js +1 -0
  37. package/dist/define-route.d.ts +231 -123
  38. package/dist/env.d.ts +2 -2
  39. package/dist/furin.d.ts +4 -2
  40. package/dist/furin.js +9717 -6796
  41. package/dist/plugin/hmr-dependencies.d.ts +2 -0
  42. package/dist/plugin/index.js +811 -145
  43. package/dist/plugin/transform-client-module.d.ts +16 -0
  44. package/dist/plugin/transform-client.d.ts +2 -0
  45. package/dist/plugin/transform-dev-page.d.ts +7 -0
  46. package/dist/plugin/transform-isomorphic.d.ts +1 -1
  47. package/dist/routes.d.ts +6 -0
  48. package/dist/rsc-client.js +87 -16
  49. package/dist/rsc.js +87 -16
  50. package/dist/server/auto-invalidate/registry.d.ts +5 -2
  51. package/dist/server/auto-invalidate/types.d.ts +2 -0
  52. package/dist/server/browser-events/plugin.d.ts +3 -0
  53. package/dist/server/cache/isr.d.ts +2 -4
  54. package/dist/server/cache/route-cache.d.ts +5 -0
  55. package/dist/server/dev/graph.d.ts +1 -0
  56. package/dist/server/dev/runtime.production.d.ts +1 -0
  57. package/dist/server/dev-page-plugin.d.ts +6 -19
  58. package/dist/server/internal.d.ts +5 -0
  59. package/dist/server/internal.js +105 -57
  60. package/dist/server/production-server.js +104 -56
  61. package/dist/server/render/assemble.d.ts +6 -6
  62. package/dist/server/render/document.d.ts +1 -1
  63. package/dist/server/render/element.d.ts +1 -1
  64. package/dist/server/render/loaders.d.ts +15 -5
  65. package/dist/server/render/mixed-cache.d.ts +6 -0
  66. package/dist/server/render/react-stream.d.ts +3 -0
  67. package/dist/server/render/ssr.d.ts +5 -4
  68. package/dist/server/render/template.d.ts +4 -0
  69. package/dist/server/router/defined-route.d.ts +2 -0
  70. package/dist/server/router/discovery.d.ts +1 -0
  71. package/dist/server/router/hmr.d.ts +1 -1
  72. package/dist/server/router/patterns.d.ts +3 -0
  73. package/dist/server/router/plugin.d.ts +3 -0
  74. package/dist/server/router/types.d.ts +4 -0
  75. package/dist/server/security/csp.d.ts +12 -0
  76. package/dist/server/sync/adapter.d.ts +25 -4
  77. package/dist/server/sync/atomic.d.ts +25 -0
  78. package/dist/server/sync/drizzle/index.d.ts +45 -0
  79. package/dist/server/sync/drizzle/index.js +540 -0
  80. package/dist/server/sync/execution-error.d.ts +2 -0
  81. package/dist/server/sync/index.d.ts +2 -1
  82. package/dist/server/sync/index.js +580 -124
  83. package/dist/server/sync/mutation-handler.d.ts +4 -0
  84. package/dist/server/sync/plugin.d.ts +34 -11
  85. package/dist/server/sync/postgres/execute.d.ts +3 -0
  86. package/dist/server/sync/postgres/index.d.ts +12 -1
  87. package/dist/server/sync/postgres/index.js +42 -13
  88. package/dist/server/sync/postgres/sql.d.ts +8 -0
  89. package/dist/server/sync/prisma/index.d.ts +24 -0
  90. package/dist/server/sync/prisma/index.js +340 -0
  91. package/dist/server/sync/queries.d.ts +21 -0
  92. package/dist/server/sync/query-context.d.ts +5 -0
  93. package/dist/server/sync/redis/index.js +3 -3
  94. package/dist/server/sync/redis/scripts.d.ts +1 -1
  95. package/dist/server/sync/response.d.ts +1 -0
  96. package/dist/server/sync/sqlite/index.d.ts +3 -0
  97. package/dist/server/sync/sqlite/index.js +10 -4
  98. package/dist/server/sync/stream.d.ts +2 -5
  99. package/dist/server/sync/validation.d.ts +4 -0
  100. package/dist/shared/defer.d.ts +31 -0
  101. package/dist/shared/error.d.ts +2 -2
  102. package/dist/shared/page-key.d.ts +7 -0
  103. package/dist/shared/query-bindings.d.ts +12 -0
  104. package/dist/shared/route-frame.d.ts +1 -0
  105. package/dist/shared/sync-query.d.ts +40 -0
  106. package/package.json +40 -16
  107. package/src/adapter/README.md +3 -0
  108. package/src/adapter/bun.ts +3 -0
  109. package/src/adapter/package.ts +16 -2
  110. package/src/adapter/runtime-build.ts +99 -14
  111. package/src/adapter/static.ts +17 -6
  112. package/src/adapter/vercel.ts +33 -23
  113. package/src/build/client.ts +23 -5
  114. package/src/build/entry-template.ts +9 -0
  115. package/src/build/hydrate.ts +18 -3
  116. package/src/build/preload-manifest.ts +100 -0
  117. package/src/build/production-instrumentation.ts +6 -3
  118. package/src/build/request-keys.ts +93 -0
  119. package/src/build/ssg-cache.ts +9 -4
  120. package/src/build/types.ts +4 -0
  121. package/src/cli/index.ts +1 -0
  122. package/src/client/boundaries.tsx +1 -1
  123. package/src/client/browser-events-runtime.ts +73 -16
  124. package/src/client/client-module.ts +57 -0
  125. package/src/client/define-route.ts +11 -2
  126. package/src/client/dev-error-overlay.ts +1 -0
  127. package/src/client/document.tsx +47 -20
  128. package/src/client/hmr.ts +4 -2
  129. package/src/client/internal/runtime-types.ts +2 -0
  130. package/src/client/link.tsx +8 -8
  131. package/src/client/mutation.ts +136 -0
  132. package/src/client/query-store.ts +418 -0
  133. package/src/client/query.tsx +67 -0
  134. package/src/client/route-api.tsx +75 -0
  135. package/src/client/router/boundary-tree.tsx +10 -6
  136. package/src/client/router/context.ts +57 -4
  137. package/src/client/router/index.ts +3 -0
  138. package/src/client/router/link-utils.ts +29 -1
  139. package/src/client/router/navigation.ts +3 -50
  140. package/src/client/router/optimistic.ts +233 -0
  141. package/src/client/router/provider.tsx +404 -96
  142. package/src/client/router/search/index.ts +37 -17
  143. package/src/client/router/search-store.ts +4 -0
  144. package/src/client/router/sync-catch-up.ts +7 -0
  145. package/src/client/router/types.ts +71 -9
  146. package/src/client/sync.ts +438 -65
  147. package/src/client.ts +20 -60
  148. package/src/config.ts +5 -0
  149. package/src/define-route.ts +442 -155
  150. package/src/env.d.ts +2 -2
  151. package/src/furin.ts +213 -38
  152. package/src/plugin/hmr-dependencies.ts +58 -0
  153. package/src/plugin/index.ts +38 -2
  154. package/src/plugin/route-config-autofix.ts +2 -2
  155. package/src/plugin/routes.ts +19 -8
  156. package/src/plugin/transform-client-module.ts +123 -0
  157. package/src/plugin/transform-client.ts +293 -13
  158. package/src/plugin/transform-dev-page.ts +231 -0
  159. package/src/plugin/transform-isomorphic.ts +11 -5
  160. package/src/routes.ts +8 -0
  161. package/src/rsc/shared.tsx +104 -18
  162. package/src/rsc/version.ts +5 -0
  163. package/src/server/auto-invalidate/registry.ts +56 -24
  164. package/src/server/auto-invalidate/runtime.ts +17 -0
  165. package/src/server/auto-invalidate/types.ts +6 -0
  166. package/src/server/browser-events/plugin.ts +112 -1
  167. package/src/server/cache/dev-loader.ts +1 -1
  168. package/src/server/cache/invalidation.ts +2 -0
  169. package/src/server/cache/isr-ssg.ts +1 -1
  170. package/src/server/cache/isr.ts +6 -34
  171. package/src/server/cache/route-cache.ts +40 -4
  172. package/src/server/cache/ssg.ts +1 -1
  173. package/src/server/dev/diagnostics.ts +4 -2
  174. package/src/server/dev/error.ts +2 -1
  175. package/src/server/dev/graph.ts +70 -7
  176. package/src/server/dev/runtime.production.ts +4 -0
  177. package/src/server/dev/symbolicate.ts +2 -0
  178. package/src/server/dev-page-plugin.ts +160 -63
  179. package/src/server/evlog.ts +1 -1
  180. package/src/server/internal.ts +5 -0
  181. package/src/server/render/assemble.ts +15 -11
  182. package/src/server/render/document.tsx +13 -2
  183. package/src/server/render/element.tsx +11 -6
  184. package/src/server/render/isr.ts +71 -33
  185. package/src/server/render/loaders.ts +328 -70
  186. package/src/server/render/mixed-cache.ts +327 -0
  187. package/src/server/render/not-found.ts +14 -11
  188. package/src/server/render/ppr-document.ts +47 -11
  189. package/src/server/render/ppr-route.ts +54 -20
  190. package/src/server/render/react-stream.ts +17 -0
  191. package/src/server/render/route-frame-transport.ts +3 -0
  192. package/src/server/render/ssg.ts +53 -19
  193. package/src/server/render/ssr.ts +105 -36
  194. package/src/server/render/static-params.ts +1 -1
  195. package/src/server/render/template.ts +23 -0
  196. package/src/server/router/defined-route.ts +3 -0
  197. package/src/server/router/discovery.ts +14 -0
  198. package/src/server/router/hmr.ts +109 -18
  199. package/src/server/router/patterns.ts +27 -0
  200. package/src/server/router/plugin.ts +94 -19
  201. package/src/server/router/source-version.ts +20 -2
  202. package/src/server/router/types.ts +4 -0
  203. package/src/server/security/csp.ts +44 -0
  204. package/src/server/sync/adapter.ts +41 -4
  205. package/src/server/sync/atomic.ts +303 -0
  206. package/src/server/sync/drizzle/index.ts +145 -0
  207. package/src/server/sync/execution-error.ts +1 -0
  208. package/src/server/sync/fingerprint.ts +2 -6
  209. package/src/server/sync/index.ts +6 -0
  210. package/src/server/sync/mutation-handler.ts +69 -0
  211. package/src/server/sync/plugin.ts +177 -60
  212. package/src/server/sync/postgres/execute.ts +20 -0
  213. package/src/server/sync/postgres/index.ts +60 -16
  214. package/src/server/sync/postgres/sql.ts +20 -0
  215. package/src/server/sync/prisma/index.ts +70 -0
  216. package/src/server/sync/queries.ts +75 -0
  217. package/src/server/sync/query-context.ts +85 -0
  218. package/src/server/sync/redis/index.ts +7 -3
  219. package/src/server/sync/redis/scripts.ts +1 -1
  220. package/src/server/sync/response.ts +21 -0
  221. package/src/server/sync/sqlite/index.ts +19 -8
  222. package/src/server/sync/stream.ts +14 -22
  223. package/src/server/sync/validation.ts +34 -0
  224. package/src/shared/defer.ts +48 -0
  225. package/src/shared/error.ts +2 -2
  226. package/src/shared/page-key.ts +36 -0
  227. package/src/shared/query-bindings.ts +138 -0
  228. package/src/shared/route-frame.ts +13 -1
  229. package/src/shared/route-map.ts +12 -2
  230. package/src/shared/sync-query.ts +138 -0
@@ -0,0 +1,4 @@
1
+ import type { Context, Elysia } from "elysia";
2
+ export declare function prepareMutationHandler(context: Pick<Context, "request">, begin: () => Promise<Response | undefined>): void;
3
+ /** Keep reservation and replay after authorization, including mounted route plugins. */
4
+ export declare function installMutationHandlers(app: Elysia): void;
@@ -1,15 +1,23 @@
1
- import { Elysia } from "elysia";
1
+ import { Elysia, ElysiaStatus } from "elysia";
2
2
  import type { InvalidationInput } from "../auto-invalidate/types.ts";
3
- import type { SyncRuntimeOptions } from "./adapter.ts";
4
- export type SyncRouteOption = false | InvalidationInput | {
5
- invalidate: InvalidationInput;
3
+ import type { SyncAdapter, SyncMutation, SyncRuntimeOptions } from "./adapter.ts";
4
+ import { MutationLeaseLost } from "./execution-error.ts";
5
+ import { type SyncInvalidationSelector, type SyncReadOption } from "./queries.ts";
6
+ export type SyncRouteOption = false | InvalidationInput | SyncReadOption | {
7
+ invalidate: SyncInvalidationSelector;
6
8
  };
7
9
  /** @deprecated Use SyncRouteOption. */
8
10
  export type SyncInput = Exclude<SyncRouteOption, false>;
9
- export declare function furinSync(options: SyncRuntimeOptions): Elysia<"", "local", import("elysia").DefaultSingleton, {
10
- typebox: {};
11
- error: [];
11
+ export declare function furinSync<Adapter extends SyncAdapter>(options: SyncRuntimeOptions<Adapter>): (app: Elysia) => Elysia<"", "local", {
12
+ decorator: {};
13
+ store: {};
14
+ derive: {
15
+ readonly mutation: SyncMutation<Adapter>;
16
+ };
12
17
  }, {
18
+ typebox: {};
19
+ error: [import("elysia/types").ErrorDefinitionEntry<typeof MutationLeaseLost, Promise<void>>];
20
+ }, import("elysia").DefaultMetadata & {
13
21
  schema: {};
14
22
  schemas: {};
15
23
  macro: Partial<{
@@ -26,7 +34,7 @@ export declare function furinSync(options: SyncRuntimeOptions): Elysia<"", "loca
26
34
  cookie?: Record<string, import("elysia").BaseCookie>;
27
35
  redirect?: never;
28
36
  };
29
- status: <const Code extends number | keyof import("elysia").StatusMap, const T = import("elysia").StatusResponse<Code>>(code: Code, response?: T) => import("elysia").ElysiaStatus<Code, T, import("elysia").NumericStatus<Code>>;
37
+ status: <const Code extends number | keyof import("elysia").StatusMap, const T = import("elysia").StatusResponse<Code>>(code: Code, response?: T) => ElysiaStatus<Code, T, import("elysia").NumericStatus<Code>>;
30
38
  problem: typeof import("elysia").problem;
31
39
  defer: (fn: import("elysia/types").AfterResponseHandler<import("elysia/types").IntersectIfObjectSchema<import("elysia/types").UnwrapMacroSchema<{
32
40
  body: undefined;
@@ -35,10 +43,18 @@ export declare function furinSync(options: SyncRuntimeOptions): Elysia<"", "loca
35
43
  params: undefined;
36
44
  cookie: undefined;
37
45
  response: undefined;
38
- }, {}>, import("elysia/types").MergeScopedSchemas<{}, {}, {}>>, import("elysia").DefaultSingleton & {
39
- derive: Partial<{}>;
46
+ }, {}>, import("elysia/types").MergeScopedSchemas<{}, {}, {}>>, {
47
+ decorator: {};
48
+ store: {};
49
+ derive: {
50
+ readonly mutation: SyncMutation<Adapter>;
51
+ };
40
52
  } & {
41
53
  derive: Partial<{}>;
54
+ } & {
55
+ derive: {
56
+ readonly mutation: SyncMutation<Adapter>;
57
+ } & Partial<{}>;
42
58
  }>) => import("elysia/types").MaybePromise<void>;
43
59
  readonly path: string;
44
60
  route?: string;
@@ -50,9 +66,16 @@ export declare function furinSync(options: SyncRuntimeOptions): Elysia<"", "loca
50
66
  params: Record<string, string>;
51
67
  headers: Record<string, string | undefined>;
52
68
  cookie: Record<string, import("elysia").Cookie<unknown>>;
69
+ readonly mutation: SyncMutation<Adapter>;
53
70
  }): void;
54
71
  };
55
72
  };
56
73
  parser: {};
57
74
  response: {};
58
- }, {}, import("elysia").DefaultEphemeral, import("elysia").DefaultEphemeral>;
75
+ }, {}, import("elysia").DefaultEphemeral, {
76
+ derive: {};
77
+ schema: {};
78
+ schemas: {};
79
+ response: {};
80
+ error: [];
81
+ }>;
@@ -0,0 +1,3 @@
1
+ import type { AtomicMutationResult, AtomicMutationValue, MutationLease } from "../adapter.ts";
2
+ import type { PostgresSyncAdapter } from "./index.ts";
3
+ export declare function executePostgresMutation<T, Tx>(journal: PostgresSyncAdapter, lease: MutationLease, tx: Tx, callback: (tx: Tx) => AtomicMutationValue<T> | Promise<AtomicMutationValue<T>>): Promise<AtomicMutationResult<T>>;
@@ -1,18 +1,29 @@
1
1
  import type { SQL } from "bun";
2
2
  import type { BeginMutationInput, BeginMutationResult, ChangePage, CompleteMutationInput, CompleteMutationResult, MutationLease, ReadChangesInput, SyncAdapter, SyncNotifier, SyncSubscription } from "../adapter.ts";
3
+ import type { SyncSql } from "./sql.ts";
3
4
  export interface PostgresSyncAdapterOptions {
4
5
  namespace: string;
5
6
  sql: SQL;
6
7
  }
7
8
  export declare class PostgresSyncAdapter implements SyncAdapter {
8
9
  readonly notificationChannel: string;
10
+ readonly publishesNotifications: boolean;
9
11
  readonly scope: "distributed";
10
12
  private readonly namespace;
11
13
  private readonly sql;
12
- constructor(options: PostgresSyncAdapterOptions);
14
+ constructor(options: {
15
+ namespace: string;
16
+ sql: SyncSql;
17
+ publishNotifications?: false;
18
+ });
13
19
  beginMutation(input: BeginMutationInput): Promise<BeginMutationResult>;
14
20
  renewMutation(lease: MutationLease): Promise<"lost" | "renewed">;
15
21
  completeMutation(input: CompleteMutationInput): Promise<CompleteMutationResult>;
22
+ /** Only used on the native transaction that already holds lockMutation's row lock. */
23
+ completeLockedMutation(input: CompleteMutationInput): Promise<CompleteMutationResult>;
24
+ private completeMutationInTransaction;
25
+ lockMutation(lease: MutationLease): Promise<boolean>;
26
+ private lockMutationInTransaction;
16
27
  abortMutation(lease: MutationLease): Promise<void>;
17
28
  currentCursor(): Promise<string>;
18
29
  readChanges(input: ReadChangesInput): Promise<ChangePage>;
@@ -5,6 +5,7 @@ var LEASE_MS = 30000;
5
5
  var MUTATION_TTL_MS = 24 * 60 * 60 * 1000;
6
6
  var RECOVERY_RETRY_INITIAL_MS = 250;
7
7
  var RECOVERY_RETRY_MAX_MS = 32000;
8
+ var CURSOR_CHECK_INTERVAL_MS = 15000;
8
9
  var UNSIGNED_INTEGER_PATTERN = /^\d+$/;
9
10
  function notificationChannel(namespace) {
10
11
  const digest = new Bun.CryptoHasher("sha256").update(namespace).digest("hex");
@@ -32,6 +33,7 @@ function storedResponse(row) {
32
33
 
33
34
  class PostgresSyncAdapter {
34
35
  notificationChannel;
36
+ publishesNotifications;
35
37
  scope = "distributed";
36
38
  namespace;
37
39
  sql;
@@ -40,12 +42,19 @@ class PostgresSyncAdapter {
40
42
  throw new Error("[furin-sync-postgres] namespace must not be empty.");
41
43
  }
42
44
  this.notificationChannel = notificationChannel(options.namespace);
45
+ this.publishesNotifications = options.publishNotifications !== false;
43
46
  this.namespace = options.namespace;
44
47
  this.sql = options.sql;
45
48
  }
46
49
  beginMutation(input) {
47
50
  return this.sql.begin(async (tx) => {
48
51
  const key = mutationKey(input);
52
+ const [lock] = await tx`
53
+ SELECT pg_try_advisory_xact_lock(hashtextextended(${`${this.namespace}:${key}`}, 0)) AS acquired
54
+ `;
55
+ if (!lock?.acquired) {
56
+ return { kind: "conflict", reason: "in-progress" };
57
+ }
49
58
  await tx`
50
59
  DELETE FROM furin_sync.mutations
51
60
  WHERE ctid IN (
@@ -58,9 +67,9 @@ class PostgresSyncAdapter {
58
67
  AND expires_at <= clock_timestamp()
59
68
  )
60
69
  LIMIT 100
70
+ FOR UPDATE SKIP LOCKED
61
71
  )
62
72
  `;
63
- await tx`SELECT pg_advisory_xact_lock(hashtextextended(${`${this.namespace}:${key}`}, 0))`;
64
73
  const rows = await tx`
65
74
  SELECT mutation_id, fingerprint, state, response_status, response_headers,
66
75
  response_body,
@@ -125,19 +134,15 @@ class PostgresSyncAdapter {
125
134
  return rows.length === 1 ? "renewed" : "lost";
126
135
  }
127
136
  completeMutation(input) {
137
+ return this.completeMutationInTransaction(input, true);
138
+ }
139
+ completeLockedMutation(input) {
140
+ return this.completeMutationInTransaction(input, false);
141
+ }
142
+ completeMutationInTransaction(input, checkExpiration) {
128
143
  return this.sql.begin(async (tx) => {
129
144
  const key = mutationKey(input.lease);
130
- await tx`SELECT pg_advisory_xact_lock(hashtextextended(${`${this.namespace}:${key}`}, 0))`;
131
- const active = await tx`
132
- SELECT mutation_id FROM furin_sync.mutations
133
- WHERE namespace = ${this.namespace}
134
- AND mutation_key = ${key}
135
- AND mutation_id = ${input.lease.id}
136
- AND state = 'in-progress'
137
- AND lease_expires_at > clock_timestamp()
138
- FOR UPDATE
139
- `;
140
- if (active.length === 0) {
145
+ if (!await this.lockMutationInTransaction(tx, input.lease, checkExpiration)) {
141
146
  return { kind: "lost" };
142
147
  }
143
148
  let cursor;
@@ -186,12 +191,29 @@ class PostgresSyncAdapter {
186
191
  AND mutation_key = ${key}
187
192
  AND mutation_id = ${input.lease.id}
188
193
  `;
189
- if (cursor !== undefined) {
194
+ if (cursor !== undefined && this.publishesNotifications) {
190
195
  await tx.notify(this.notificationChannel, cursor);
191
196
  }
192
197
  return { cursor, kind: "committed" };
193
198
  });
194
199
  }
200
+ lockMutation(lease) {
201
+ return this.sql.begin((tx) => this.lockMutationInTransaction(tx, lease, true));
202
+ }
203
+ async lockMutationInTransaction(tx, lease, checkExpiration) {
204
+ const key = mutationKey(lease);
205
+ await tx`SELECT pg_advisory_xact_lock(hashtextextended(${`${this.namespace}:${key}`}, 0))::text`;
206
+ const active = await tx`
207
+ SELECT mutation_id FROM furin_sync.mutations
208
+ WHERE namespace = ${this.namespace}
209
+ AND mutation_key = ${key}
210
+ AND mutation_id = ${lease.id}
211
+ AND state = 'in-progress'
212
+ AND (NOT ${checkExpiration} OR lease_expires_at > clock_timestamp())
213
+ FOR UPDATE
214
+ `;
215
+ return active.length > 0;
216
+ }
195
217
  async abortMutation(lease) {
196
218
  await this.sql`
197
219
  DELETE FROM furin_sync.mutations
@@ -324,9 +346,16 @@ class PostgresSyncNotifier {
324
346
  });
325
347
  };
326
348
  const subscription = await this.sql.listen(this.notificationChannel, emit, recover);
349
+ const cursorCheck = setInterval(() => {
350
+ if (!retry) {
351
+ recover();
352
+ }
353
+ }, CURSOR_CHECK_INTERVAL_MS);
354
+ cursorCheck.unref?.();
327
355
  return {
328
356
  unsubscribe: () => {
329
357
  active = false;
358
+ clearInterval(cursorCheck);
330
359
  if (retry) {
331
360
  clearTimeout(retry);
332
361
  retry = undefined;
@@ -0,0 +1,8 @@
1
+ export interface SyncSqlQuery {
2
+ notify: (channel: string, cursor: string) => Promise<void>;
3
+ <Rows>(strings: TemplateStringsArray, ...values: unknown[]): Promise<Rows>;
4
+ }
5
+ export interface SyncSql extends SyncSqlQuery {
6
+ begin: <T>(callback: (tx: SyncSqlQuery) => Promise<T>) => Promise<T>;
7
+ }
8
+ export declare function transactionSql(query: <Rows>(strings: TemplateStringsArray, values: unknown[]) => Promise<Rows>): SyncSql;
@@ -0,0 +1,24 @@
1
+ import type { AtomicMutationResult, AtomicMutationValue, MutationLease, TransactionalSyncAdapter } from "../adapter.ts";
2
+ import { PostgresSyncAdapter } from "../postgres/index.ts";
3
+ interface PrismaQuery {
4
+ $queryRawUnsafe: <Rows>(query: string, ...values: unknown[]) => Promise<Rows>;
5
+ }
6
+ interface PrismaClient<Tx extends PrismaQuery> extends PrismaQuery {
7
+ $transaction: <T>(callback: (tx: Tx) => Promise<T>) => Promise<T>;
8
+ }
9
+ export declare class PrismaSyncAdapter<Tx extends PrismaQuery> extends PostgresSyncAdapter implements TransactionalSyncAdapter<Tx, "async"> {
10
+ readonly transactionMode: "async";
11
+ private readonly client;
12
+ private readonly syncNamespace;
13
+ constructor(options: {
14
+ client: PrismaClient<Tx>;
15
+ namespace: string;
16
+ });
17
+ executeMutation<T>(lease: MutationLease, callback: (tx: Tx) => AtomicMutationValue<T> | Promise<AtomicMutationValue<T>>): Promise<AtomicMutationResult<T>>;
18
+ }
19
+ /** Prisma 7, PostgreSQL. The sync SQL migration must run on the same database. */
20
+ export declare function prismaSyncAdapter<Tx extends PrismaQuery>(options: {
21
+ client: PrismaClient<Tx>;
22
+ namespace: string;
23
+ }): PrismaSyncAdapter<Tx>;
24
+ export {};
@@ -0,0 +1,340 @@
1
+ // @bun
2
+ // src/server/sync/execution-error.ts
3
+ class MutationLeaseLost extends Error {
4
+ }
5
+
6
+ // src/server/sync/postgres/execute.ts
7
+ async function executePostgresMutation(journal, lease, tx, callback) {
8
+ if (!await journal.lockMutation(lease)) {
9
+ throw new MutationLeaseLost("[furin] Mutation lease lost; the transaction was rolled back.");
10
+ }
11
+ const result = await callback(tx);
12
+ const completion = await journal.completeLockedMutation({ ...result, lease });
13
+ if (completion.kind === "lost") {
14
+ throw new MutationLeaseLost("[furin] Mutation lease lost; the transaction was rolled back.");
15
+ }
16
+ return { ...result, cursor: completion.cursor, kind: "committed" };
17
+ }
18
+
19
+ // src/server/sync/postgres/index.ts
20
+ var CHANGE_RETENTION = 1000;
21
+ var LEASE_MS = 30000;
22
+ var MUTATION_TTL_MS = 24 * 60 * 60 * 1000;
23
+ var UNSIGNED_INTEGER_PATTERN = /^\d+$/;
24
+ function notificationChannel(namespace) {
25
+ const digest = new Bun.CryptoHasher("sha256").update(namespace).digest("hex");
26
+ return `furin_sync_${digest.slice(0, 52)}`;
27
+ }
28
+ async function readCurrentCursor(sql, namespace) {
29
+ const rows = await sql`
30
+ SELECT current_cursor FROM furin_sync.streams WHERE namespace = ${namespace}
31
+ `;
32
+ return String(rows[0]?.current_cursor ?? 0);
33
+ }
34
+ function mutationKey(input) {
35
+ return new Bun.CryptoHasher("sha256").update(`${input.principal.length}:${input.principal}${input.key}`).digest("hex");
36
+ }
37
+ function storedResponse(row) {
38
+ if (row.response_body === null || row.response_headers === null || row.response_status === null) {
39
+ throw new Error("[furin-sync-postgres] Succeeded mutation has no replay response.");
40
+ }
41
+ return {
42
+ body: new Uint8Array(row.response_body),
43
+ headers: row.response_headers,
44
+ status: row.response_status
45
+ };
46
+ }
47
+
48
+ class PostgresSyncAdapter {
49
+ notificationChannel;
50
+ publishesNotifications;
51
+ scope = "distributed";
52
+ namespace;
53
+ sql;
54
+ constructor(options) {
55
+ if (options.namespace.length === 0) {
56
+ throw new Error("[furin-sync-postgres] namespace must not be empty.");
57
+ }
58
+ this.notificationChannel = notificationChannel(options.namespace);
59
+ this.publishesNotifications = options.publishNotifications !== false;
60
+ this.namespace = options.namespace;
61
+ this.sql = options.sql;
62
+ }
63
+ beginMutation(input) {
64
+ return this.sql.begin(async (tx) => {
65
+ const key = mutationKey(input);
66
+ const [lock] = await tx`
67
+ SELECT pg_try_advisory_xact_lock(hashtextextended(${`${this.namespace}:${key}`}, 0)) AS acquired
68
+ `;
69
+ if (!lock?.acquired) {
70
+ return { kind: "conflict", reason: "in-progress" };
71
+ }
72
+ await tx`
73
+ DELETE FROM furin_sync.mutations
74
+ WHERE ctid IN (
75
+ SELECT ctid FROM furin_sync.mutations
76
+ WHERE
77
+ (state = 'succeeded' AND expires_at <= clock_timestamp())
78
+ OR (
79
+ state = 'in-progress'
80
+ AND lease_expires_at <= clock_timestamp()
81
+ AND expires_at <= clock_timestamp()
82
+ )
83
+ LIMIT 100
84
+ FOR UPDATE SKIP LOCKED
85
+ )
86
+ `;
87
+ const rows = await tx`
88
+ SELECT mutation_id, fingerprint, state, response_status, response_headers,
89
+ response_body,
90
+ CASE
91
+ WHEN state = 'succeeded' THEN expires_at <= clock_timestamp()
92
+ ELSE lease_expires_at <= clock_timestamp()
93
+ END AS expired
94
+ FROM furin_sync.mutations
95
+ WHERE namespace = ${this.namespace} AND mutation_key = ${key}
96
+ FOR UPDATE
97
+ `;
98
+ const [existing] = rows;
99
+ if (existing && existing.fingerprint !== input.fingerprint) {
100
+ return { kind: "conflict", reason: "payload-mismatch" };
101
+ }
102
+ if (existing && !existing.expired) {
103
+ if (existing.state === "in-progress") {
104
+ return { kind: "conflict", reason: "in-progress" };
105
+ }
106
+ return { kind: "replay", response: storedResponse(existing) };
107
+ }
108
+ const id = crypto.randomUUID();
109
+ await tx`
110
+ INSERT INTO furin_sync.mutations (
111
+ namespace, mutation_key, mutation_id, fingerprint, state,
112
+ lease_expires_at, expires_at, created_at
113
+ ) VALUES (
114
+ ${this.namespace}, ${key}, ${id}, ${input.fingerprint}, 'in-progress',
115
+ clock_timestamp() + (${LEASE_MS} * interval '1 millisecond'),
116
+ clock_timestamp() + (${MUTATION_TTL_MS} * interval '1 millisecond'),
117
+ clock_timestamp()
118
+ )
119
+ ON CONFLICT (namespace, mutation_key) DO UPDATE SET
120
+ mutation_id = EXCLUDED.mutation_id,
121
+ fingerprint = EXCLUDED.fingerprint,
122
+ state = 'in-progress',
123
+ response_status = NULL,
124
+ response_headers = NULL,
125
+ response_body = NULL,
126
+ lease_expires_at = EXCLUDED.lease_expires_at,
127
+ expires_at = EXCLUDED.expires_at,
128
+ created_at = EXCLUDED.created_at,
129
+ completed_at = NULL
130
+ `;
131
+ return {
132
+ kind: "execute",
133
+ lease: { id, key: input.key, leaseMs: LEASE_MS, principal: input.principal }
134
+ };
135
+ });
136
+ }
137
+ async renewMutation(lease) {
138
+ const rows = await this.sql`
139
+ UPDATE furin_sync.mutations
140
+ SET lease_expires_at = clock_timestamp() + (${lease.leaseMs} * interval '1 millisecond')
141
+ WHERE namespace = ${this.namespace}
142
+ AND mutation_key = ${mutationKey(lease)}
143
+ AND mutation_id = ${lease.id}
144
+ AND state = 'in-progress'
145
+ AND lease_expires_at > clock_timestamp()
146
+ RETURNING mutation_id
147
+ `;
148
+ return rows.length === 1 ? "renewed" : "lost";
149
+ }
150
+ completeMutation(input) {
151
+ return this.completeMutationInTransaction(input, true);
152
+ }
153
+ completeLockedMutation(input) {
154
+ return this.completeMutationInTransaction(input, false);
155
+ }
156
+ completeMutationInTransaction(input, checkExpiration) {
157
+ return this.sql.begin(async (tx) => {
158
+ const key = mutationKey(input.lease);
159
+ if (!await this.lockMutationInTransaction(tx, input.lease, checkExpiration)) {
160
+ return { kind: "lost" };
161
+ }
162
+ let cursor;
163
+ if (input.invalidations.length > 0) {
164
+ await tx`
165
+ INSERT INTO furin_sync.streams (namespace, current_cursor, oldest_cursor)
166
+ VALUES (${this.namespace}, 0, 0)
167
+ ON CONFLICT (namespace) DO NOTHING
168
+ `;
169
+ const cursors = await tx`
170
+ UPDATE furin_sync.streams
171
+ SET current_cursor = current_cursor + 1
172
+ WHERE namespace = ${this.namespace}
173
+ RETURNING current_cursor
174
+ `;
175
+ cursor = String(cursors[0]?.current_cursor);
176
+ await tx`
177
+ INSERT INTO furin_sync.changes (namespace, cursor, invalidations)
178
+ VALUES (
179
+ ${this.namespace},
180
+ ${cursor},
181
+ ${JSON.stringify(input.invalidations)}::text::jsonb
182
+ )
183
+ `;
184
+ await tx`
185
+ WITH removed AS (
186
+ DELETE FROM furin_sync.changes
187
+ WHERE namespace = ${this.namespace}
188
+ AND cursor <= GREATEST(0, ${cursor}::bigint - ${CHANGE_RETENTION})
189
+ RETURNING cursor
190
+ )
191
+ UPDATE furin_sync.streams
192
+ SET oldest_cursor = COALESCE((SELECT MAX(cursor) + 1 FROM removed), oldest_cursor)
193
+ WHERE namespace = ${this.namespace}
194
+ `;
195
+ }
196
+ await tx`
197
+ UPDATE furin_sync.mutations
198
+ SET state = 'succeeded',
199
+ response_status = ${input.response.status},
200
+ response_headers = ${JSON.stringify(input.response.headers)}::text::jsonb,
201
+ response_body = ${input.response.body},
202
+ completed_at = clock_timestamp(),
203
+ expires_at = clock_timestamp() + (${MUTATION_TTL_MS} * interval '1 millisecond')
204
+ WHERE namespace = ${this.namespace}
205
+ AND mutation_key = ${key}
206
+ AND mutation_id = ${input.lease.id}
207
+ `;
208
+ if (cursor !== undefined && this.publishesNotifications) {
209
+ await tx.notify(this.notificationChannel, cursor);
210
+ }
211
+ return { cursor, kind: "committed" };
212
+ });
213
+ }
214
+ lockMutation(lease) {
215
+ return this.sql.begin((tx) => this.lockMutationInTransaction(tx, lease, true));
216
+ }
217
+ async lockMutationInTransaction(tx, lease, checkExpiration) {
218
+ const key = mutationKey(lease);
219
+ await tx`SELECT pg_advisory_xact_lock(hashtextextended(${`${this.namespace}:${key}`}, 0))::text`;
220
+ const active = await tx`
221
+ SELECT mutation_id FROM furin_sync.mutations
222
+ WHERE namespace = ${this.namespace}
223
+ AND mutation_key = ${key}
224
+ AND mutation_id = ${lease.id}
225
+ AND state = 'in-progress'
226
+ AND (NOT ${checkExpiration} OR lease_expires_at > clock_timestamp())
227
+ FOR UPDATE
228
+ `;
229
+ return active.length > 0;
230
+ }
231
+ async abortMutation(lease) {
232
+ await this.sql`
233
+ DELETE FROM furin_sync.mutations
234
+ WHERE namespace = ${this.namespace}
235
+ AND mutation_key = ${mutationKey(lease)}
236
+ AND mutation_id = ${lease.id}
237
+ AND state = 'in-progress'
238
+ `;
239
+ }
240
+ currentCursor() {
241
+ return readCurrentCursor(this.sql, this.namespace);
242
+ }
243
+ async readChanges(input) {
244
+ const cursorRows = await this.sql`
245
+ SELECT current_cursor, oldest_cursor
246
+ FROM furin_sync.streams WHERE namespace = ${this.namespace}
247
+ `;
248
+ const currentCursor = String(cursorRows[0]?.current_cursor ?? 0);
249
+ if (input.after === undefined) {
250
+ return { changes: [], cursor: currentCursor, hasMore: false, reset: false };
251
+ }
252
+ if (!UNSIGNED_INTEGER_PATTERN.test(input.after)) {
253
+ return { changes: [], cursor: currentCursor, hasMore: false, reset: true };
254
+ }
255
+ if (BigInt(input.after) > BigInt(currentCursor)) {
256
+ return { changes: [], cursor: currentCursor, hasMore: false, reset: true };
257
+ }
258
+ const oldest = BigInt(cursorRows[0]?.oldest_cursor ?? 0);
259
+ if (BigInt(input.after) < oldest - 1n) {
260
+ return { changes: [], cursor: currentCursor, hasMore: false, reset: true };
261
+ }
262
+ const rows = await this.sql`
263
+ SELECT cursor, invalidations
264
+ FROM furin_sync.changes
265
+ WHERE namespace = ${this.namespace} AND cursor > ${input.after}::bigint
266
+ ORDER BY cursor ASC
267
+ LIMIT ${input.limit + 1}
268
+ `;
269
+ const latestCursorRows = await this.sql`
270
+ SELECT current_cursor, oldest_cursor
271
+ FROM furin_sync.streams WHERE namespace = ${this.namespace}
272
+ `;
273
+ const latestCurrentCursor = String(latestCursorRows[0]?.current_cursor ?? 0);
274
+ const latestOldest = BigInt(latestCursorRows[0]?.oldest_cursor ?? 0);
275
+ if (BigInt(input.after) < latestOldest - 1n) {
276
+ return {
277
+ changes: [],
278
+ cursor: latestCurrentCursor,
279
+ hasMore: false,
280
+ reset: true
281
+ };
282
+ }
283
+ const hasMore = rows.length > input.limit;
284
+ const changes = rows.slice(0, input.limit).map((row) => ({
285
+ cursor: String(row.cursor),
286
+ invalidations: row.invalidations
287
+ }));
288
+ return {
289
+ changes,
290
+ cursor: changes.at(-1)?.cursor ?? input.after,
291
+ hasMore,
292
+ reset: false
293
+ };
294
+ }
295
+ }
296
+
297
+ // src/server/sync/postgres/sql.ts
298
+ function transactionSql(query) {
299
+ const sql = (strings, ...values) => query(strings, values);
300
+ sql.begin = (callback) => callback(sql);
301
+ sql.notify = async (channel, cursor) => {
302
+ await sql`SELECT pg_notify(${channel}, ${cursor})::text`;
303
+ };
304
+ return sql;
305
+ }
306
+
307
+ // src/server/sync/prisma/index.ts
308
+ function prismaSql(client) {
309
+ return transactionSql((strings, values) => {
310
+ const query = strings.reduce((text, part, index) => text + (index === 0 ? "" : `$${index}`) + part, "");
311
+ return client.$queryRawUnsafe(query, ...values);
312
+ });
313
+ }
314
+
315
+ class PrismaSyncAdapter extends PostgresSyncAdapter {
316
+ transactionMode = "async";
317
+ client;
318
+ syncNamespace;
319
+ constructor(options) {
320
+ const sql = prismaSql(options.client);
321
+ sql.begin = (callback) => options.client.$transaction((tx) => callback(prismaSql(tx)));
322
+ super({ namespace: options.namespace, sql, publishNotifications: false });
323
+ this.client = options.client;
324
+ this.syncNamespace = options.namespace;
325
+ }
326
+ executeMutation(lease, callback) {
327
+ return this.client.$transaction((tx) => executePostgresMutation(new PostgresSyncAdapter({
328
+ namespace: this.syncNamespace,
329
+ sql: prismaSql(tx),
330
+ publishNotifications: false
331
+ }), lease, tx, callback));
332
+ }
333
+ }
334
+ function prismaSyncAdapter(options) {
335
+ return new PrismaSyncAdapter(options);
336
+ }
337
+ export {
338
+ PrismaSyncAdapter,
339
+ prismaSyncAdapter
340
+ };
@@ -0,0 +1,21 @@
1
+ import type { Context } from "elysia";
2
+ import { type QueryScope, type SyncQueryIdentity } from "../../shared/sync-query.ts";
3
+ import type { InvalidationInput, SyncInvalidationInput } from "../auto-invalidate/types.ts";
4
+ export type SyncInvalidationSelector = SyncInvalidationInput | ((context: Context & {
5
+ responseValue: unknown;
6
+ }) => SyncInvalidationInput);
7
+ interface UnregisteredRead {
8
+ id: string;
9
+ scope?: QueryScope | ((context: Context) => QueryScope);
10
+ }
11
+ type RegisteredRead<Identity> = Identity extends SyncQueryIdentity ? {
12
+ id: Identity["id"];
13
+ } & (string extends keyof Identity["scope"] ? {
14
+ scope?: Identity["scope"] | ((context: Context) => Identity["scope"]);
15
+ } : {
16
+ scope: Identity["scope"] | ((context: Context) => Identity["scope"]);
17
+ }) : never;
18
+ export type SyncReadOption = string extends SyncQueryIdentity["id"] ? UnregisteredRead : RegisteredRead<SyncQueryIdentity>;
19
+ export declare function resolveSyncInvalidations(input: SyncInvalidationSelector | undefined, context: Context, value: unknown): InvalidationInput | undefined;
20
+ export declare function appendQueryInvalidations(input: InvalidationInput | undefined, context: Pick<Context, "set">): void;
21
+ export {};
@@ -0,0 +1,5 @@
1
+ import type { Context } from "elysia";
2
+ import { type QuerySeed } from "../../shared/sync-query.ts";
3
+ import type { LoaderResult } from "../render/loaders.ts";
4
+ export declare function deferredQuerySeeds(promise: Promise<unknown>): QuerySeed[] | undefined;
5
+ export declare function captureQueryReads<Result extends LoaderResult>(ctx: Context, run: () => Promise<Result>, owner?: "eden-request-queries"): Promise<Result>;
@@ -48,7 +48,7 @@ if value.state ~= 'in-progress' or value.id ~= ARGV[1] or value.leaseUntil <= no
48
48
  return {'lost'}
49
49
  end
50
50
  value.state = 'succeeded'
51
- value.response = cjson.decode(ARGV[2])
51
+ value.response = ARGV[2]
52
52
  value.leaseUntil = nil
53
53
  local cursor = ''
54
54
  if ARGV[3] ~= '[]' then
@@ -108,13 +108,13 @@ function parseMutation(raw) {
108
108
  return value;
109
109
  }
110
110
  function deserializeResponse(document) {
111
- const { response } = document;
111
+ const response = typeof document.response === "string" ? JSON.parse(document.response) : document.response;
112
112
  if (response === undefined) {
113
113
  throw new Error("[furin-sync-redis] Succeeded mutation has no replay response.");
114
114
  }
115
115
  return {
116
116
  body: Uint8Array.fromBase64(response.body),
117
- headers: response.headers,
117
+ headers: Array.isArray(response.headers) ? response.headers : [],
118
118
  status: response.status
119
119
  };
120
120
  }