@teyik0/furin 0.2.0-alpha.5 → 0.3.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.
- package/README.md +2 -3
- package/dist/adapter/static.d.ts +1 -1
- package/dist/build/bun-build.d.ts +3 -0
- package/dist/build/entry-template.d.ts +2 -0
- package/dist/build/entry-template.ts +3 -0
- package/dist/build/hydrate.d.ts +1 -1
- package/dist/build/index.js +6944 -5067
- package/dist/build/production-instrumentation.d.ts +1 -0
- package/dist/build/route-types.d.ts +1 -1
- package/dist/build/types.d.ts +1 -0
- package/dist/cli/index.js +7874 -5971
- package/dist/client/boundaries.d.ts +4 -4
- package/dist/client/internal/runtime-types.d.ts +30 -0
- package/dist/client/link.d.ts +2 -1
- package/dist/client/link.js +712 -338
- package/dist/client/router/boundary-tree.d.ts +1 -1
- package/dist/client/router/index.d.ts +1 -1
- package/dist/client/router/link-utils.d.ts +5 -1
- package/dist/client/router/sync-catch-up.d.ts +4 -4
- package/dist/client/router/types.d.ts +2 -2
- package/dist/client-only.d.ts +1 -0
- package/dist/client-only.js +1 -0
- package/dist/client.d.ts +108 -111
- package/dist/client.js +16 -17
- package/dist/config.d.ts +1 -1
- package/dist/config.js +2 -2
- package/dist/devtools/devtools-element.d.ts +1 -0
- package/dist/devtools/protocol.d.ts +119 -0
- package/dist/furin.d.ts +7 -6
- package/dist/furin.js +6547 -3187
- package/dist/isomorphic.d.ts +18 -0
- package/dist/plugin/binding-scope.d.ts +2 -0
- package/dist/plugin/dead-code-elimination.d.ts +3 -0
- package/dist/plugin/index.js +933 -423
- package/dist/plugin/transform-client.d.ts +0 -2
- package/dist/plugin/transform-isomorphic.d.ts +9 -0
- package/dist/rsc/build/environment.d.ts +2 -0
- package/dist/rsc/build/index.d.ts +15 -0
- package/dist/rsc/client-codec.d.ts +1 -0
- package/dist/rsc/codec.d.ts +4 -0
- package/dist/rsc/flight-drain.d.ts +11 -0
- package/dist/rsc/render-error.d.ts +17 -0
- package/dist/rsc/server-codec.d.ts +2 -0
- package/dist/rsc/server-codec.js +24 -0
- package/dist/rsc/shared.d.ts +30 -0
- package/dist/rsc/symbols.d.ts +2 -0
- package/dist/rsc/transport-benchmark.d.ts +13 -0
- package/dist/rsc/version.d.ts +7 -0
- package/dist/rsc-client.d.ts +4 -0
- package/dist/rsc-client.js +166 -0
- package/dist/rsc-server.d.ts +11 -0
- package/dist/rsc.d.ts +11 -0
- package/dist/rsc.js +353 -0
- package/dist/server/cache/index.d.ts +2 -2
- package/dist/server/cache/invalidation.d.ts +2 -3
- package/dist/server/cache/isr-ssg.d.ts +5 -1
- package/dist/server/cache/isr.d.ts +9 -0
- package/dist/server/cache/route-cache.d.ts +10 -8
- package/dist/server/cache/store-view.d.ts +7 -7
- package/dist/server/dev-page-plugin.d.ts +4 -0
- package/dist/server/devtools/hub.d.ts +11 -0
- package/dist/server/devtools/instrumentation.d.ts +22 -0
- package/dist/server/devtools/instrumentation.production.d.ts +44 -0
- package/dist/server/devtools/plugin.d.ts +3 -0
- package/dist/server/devtools/request-context.d.ts +6 -0
- package/dist/server/internal.d.ts +2 -0
- package/dist/server/internal.js +3 -3
- package/dist/server/lang-detect.d.ts +1 -0
- package/dist/server/render/assemble.d.ts +4 -0
- package/dist/server/render/element.d.ts +1 -1
- package/dist/server/render/index.d.ts +2 -2
- package/dist/server/render/index.ts +6 -2
- package/dist/server/render/loaders.d.ts +8 -0
- package/dist/server/render/not-found.d.ts +1 -1
- package/dist/server/render/ppr-route.d.ts +8 -0
- package/dist/server/render/route-frame-transport.d.ts +2 -0
- package/dist/server/render/shell.ts +0 -1
- package/dist/server/render/ssr.d.ts +2 -3
- package/dist/server/router/discovery.d.ts +1 -1
- package/dist/server/router/hmr.d.ts +1 -1
- package/dist/server/router/index.d.ts +2 -1
- package/dist/server/router/index.js +23 -23
- package/dist/server/router/index.ts +1 -1
- package/dist/server/router/patterns.d.ts +1 -1
- package/dist/server/router/plugin.d.ts +4 -7
- package/dist/server/router/schema-merge.d.ts +3 -0
- package/dist/server/router/schemas.d.ts +12 -7
- package/dist/server/router/types.d.ts +1 -1
- package/dist/server/runtime-env.js +2 -2
- package/dist/server/sync/adapter.d.ts +45 -26
- package/dist/server/sync/config.d.ts +5 -9
- package/dist/server/sync/fingerprint.d.ts +2 -1
- package/dist/server/sync/index.d.ts +15 -4
- package/dist/server/sync/index.js +2868 -0
- package/dist/server/sync/notifier.d.ts +18 -0
- package/dist/server/sync/plugin.d.ts +53 -54
- package/dist/server/sync/postgres/index.d.ts +19 -0
- package/dist/server/sync/postgres/index.js +252 -0
- package/dist/server/sync/postgres/migrate.d.ts +2 -0
- package/dist/server/sync/postgres/migrate.js +16 -0
- package/dist/server/sync/postgres/migration.sql +66 -0
- package/dist/server/sync/redis/index.d.ts +30 -0
- package/dist/server/sync/redis/index.js +336 -0
- package/dist/server/sync/redis/scripts.d.ts +4 -0
- package/dist/server/sync/response.d.ts +10 -1
- package/dist/server/sync/runtime.d.ts +6 -0
- package/dist/server/sync/sqlite/index.d.ts +20 -0
- package/dist/server/sync/sqlite/index.js +250 -0
- package/dist/server/sync/stream.d.ts +12 -11
- package/dist/server-only.d.ts +1 -0
- package/dist/server-only.js +1 -0
- package/dist/shared/parser.d.ts +2 -0
- package/dist/shared/route-frame.d.ts +49 -0
- package/dist/shared/utils/index.d.ts +1 -1
- package/package.json +54 -12
- package/src/adapter/bun.ts +73 -16
- package/src/adapter/package.ts +3 -1
- package/src/adapter/static.ts +94 -48
- package/src/build/bun-build.ts +11 -0
- package/src/build/client.ts +22 -24
- package/src/build/entry-template.ts +3 -0
- package/src/build/hydrate.ts +33 -8
- package/src/build/index.ts +12 -0
- package/src/build/production-instrumentation.ts +14 -0
- package/src/build/route-types.ts +7 -8
- package/src/build/scan-server.ts +3 -2
- package/src/build/ssg-cache.ts +7 -2
- package/src/build/types.ts +1 -0
- package/src/cli/index.ts +53 -22
- package/src/client/boundaries.tsx +42 -18
- package/src/client/default-screens.tsx +4 -4
- package/src/client/internal/runtime-types.ts +31 -0
- package/src/client/link.tsx +35 -37
- package/src/client/router/boundary-tree.tsx +2 -2
- package/src/client/router/context.ts +13 -9
- package/src/client/router/index.ts +3 -0
- package/src/client/router/link-utils.ts +66 -3
- package/src/client/router/navigation.ts +9 -15
- package/src/client/router/provider.tsx +74 -52
- package/src/client/router/search/index.ts +5 -7
- package/src/client/router/search-store.ts +5 -1
- package/src/client/router/spa-response.ts +3 -4
- package/src/client/router/sync-catch-up.ts +9 -8
- package/src/client/router/types.ts +2 -2
- package/src/client/sync.ts +3 -2
- package/src/client-only.ts +1 -0
- package/src/client.ts +221 -174
- package/src/devtools/devtools-element.js +884 -0
- package/src/devtools/protocol.ts +139 -0
- package/src/furin.ts +185 -96
- package/src/isomorphic.ts +66 -0
- package/src/plugin/binding-scope.ts +158 -0
- package/src/plugin/dead-code-elimination.ts +202 -0
- package/src/plugin/index.ts +14 -18
- package/src/plugin/transform-client.ts +237 -273
- package/src/plugin/transform-isomorphic.ts +464 -0
- package/src/rsc/build/environment.ts +30 -0
- package/src/rsc/build/index.ts +94 -0
- package/src/rsc/client-codec.ts +11 -0
- package/src/rsc/codec.ts +85 -0
- package/src/rsc/flight-drain.ts +68 -0
- package/src/rsc/react-server-dom-webpack.d.ts +23 -0
- package/src/rsc/render-error.ts +120 -0
- package/src/rsc/server-codec.ts +25 -0
- package/src/rsc/shared.tsx +113 -0
- package/src/rsc/symbols.ts +2 -0
- package/src/rsc/transport-benchmark.ts +73 -0
- package/src/rsc/version.ts +57 -0
- package/src/rsc-client.ts +12 -0
- package/src/rsc-server.tsx +91 -0
- package/src/rsc.tsx +75 -0
- package/src/server/auto-invalidate/runtime.ts +32 -6
- package/src/server/cache/dev-loader.ts +70 -10
- package/src/server/cache/index.ts +7 -3
- package/src/server/cache/invalidation.ts +33 -15
- package/src/server/cache/isr-ssg.ts +12 -3
- package/src/server/cache/isr.ts +84 -9
- package/src/server/cache/route-cache.ts +49 -36
- package/src/server/cache/store-view.ts +7 -7
- package/src/server/context-logger.ts +7 -7
- package/src/server/dev-page-plugin.ts +8 -6
- package/src/server/devtools/hub.ts +64 -0
- package/src/server/devtools/instrumentation.production.ts +80 -0
- package/src/server/devtools/instrumentation.ts +72 -0
- package/src/server/devtools/plugin.ts +267 -0
- package/src/server/devtools/request-context.ts +76 -0
- package/src/server/instance.ts +1 -1
- package/src/server/internal.ts +2 -0
- package/src/server/lang-detect.ts +14 -10
- package/src/server/render/assemble.ts +73 -10
- package/src/server/render/element.tsx +11 -8
- package/src/server/render/index.ts +6 -2
- package/src/server/render/isr.ts +154 -110
- package/src/server/render/loaders.ts +259 -45
- package/src/server/render/not-found.ts +10 -15
- package/src/server/render/ppr-route.ts +146 -0
- package/src/server/render/route-frame-transport.ts +62 -0
- package/src/server/render/shell.ts +0 -1
- package/src/server/render/ssg.ts +6 -5
- package/src/server/render/ssr.ts +155 -67
- package/src/server/render/template.ts +2 -1
- package/src/server/router/discovery.ts +39 -22
- package/src/server/router/hmr.ts +15 -13
- package/src/server/router/index.ts +1 -1
- package/src/server/router/patterns.ts +16 -15
- package/src/server/router/plugin.ts +151 -158
- package/src/server/router/schema-merge.ts +52 -0
- package/src/server/router/schemas.ts +55 -73
- package/src/server/router/types.ts +1 -1
- package/src/server/sync/adapter.ts +44 -28
- package/src/server/sync/config.ts +9 -27
- package/src/server/sync/fingerprint.ts +8 -3
- package/src/server/sync/index.ts +37 -13
- package/src/server/sync/notifier.ts +109 -0
- package/src/server/sync/plugin.ts +184 -89
- package/src/server/sync/postgres/index.ts +301 -0
- package/src/server/sync/postgres/migrate.ts +15 -0
- package/src/server/sync/postgres/migration.sql +66 -0
- package/src/server/sync/redis/index.ts +342 -0
- package/src/server/sync/redis/scripts.ts +74 -0
- package/src/server/sync/response.ts +141 -16
- package/src/server/sync/runtime.ts +27 -0
- package/src/server/sync/sql.d.ts +4 -0
- package/src/server/sync/sqlite/index.ts +337 -0
- package/src/server/sync/sqlite/migration.sql +70 -0
- package/src/server/sync/stream.ts +137 -81
- package/src/server-only.ts +1 -0
- package/src/shared/await.tsx +4 -4
- package/src/shared/deferred-ndjson.ts +34 -6
- package/src/shared/digest.ts +2 -2
- package/src/shared/parser.ts +5 -0
- package/src/shared/route-frame.ts +429 -0
- package/src/shared/search-params.ts +7 -7
- package/src/shared/utils/index.ts +5 -3
- package/dist/server/dev-inspector.d.ts +0 -89
- package/dist/server/sync/memory-adapter.d.ts +0 -17
- package/src/server/dev-inspector.ts +0 -60
- package/src/server/sync/memory-adapter.ts +0 -196
|
@@ -1,14 +1,15 @@
|
|
|
1
|
-
import { Elysia } from "elysia";
|
|
1
|
+
import { type Context, Elysia } from "elysia";
|
|
2
2
|
import {
|
|
3
3
|
appendPendingInvalidationHeader,
|
|
4
4
|
isSuccessfulMutationResponse,
|
|
5
5
|
runInvalidationRules,
|
|
6
6
|
} from "../auto-invalidate/runtime.ts";
|
|
7
7
|
import type { InvalidationInput } from "../auto-invalidate/types.ts";
|
|
8
|
+
import { peekPendingInvalidations } from "../cache/invalidation.ts";
|
|
9
|
+
import type { MutationLease, SyncInvalidation, SyncRuntimeOptions } from "./adapter.ts";
|
|
8
10
|
import { createMutationFingerprint } from "./fingerprint.ts";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import { publishSyncInvalidation } from "./stream.ts";
|
|
11
|
+
import { mergeStoredResponseHeaders, replayResponse, storeResponse } from "./response.ts";
|
|
12
|
+
import { resolveSyncRuntime } from "./runtime.ts";
|
|
12
13
|
|
|
13
14
|
export type SyncRouteOption =
|
|
14
15
|
| false
|
|
@@ -26,7 +27,8 @@ interface RouteSyncMetadata {
|
|
|
26
27
|
}
|
|
27
28
|
|
|
28
29
|
interface ActiveMutation {
|
|
29
|
-
|
|
30
|
+
lease: MutationLease;
|
|
31
|
+
renewal: ReturnType<typeof setTimeout> | undefined;
|
|
30
32
|
}
|
|
31
33
|
|
|
32
34
|
interface MutationContext {
|
|
@@ -37,9 +39,25 @@ interface MutationContext {
|
|
|
37
39
|
request: Request;
|
|
38
40
|
}
|
|
39
41
|
|
|
42
|
+
type TransportHook<TContext> = (context: TContext) => Promise<void>;
|
|
43
|
+
|
|
44
|
+
type CompletionContext = MutationContext &
|
|
45
|
+
Pick<Context, "set"> & {
|
|
46
|
+
response?: unknown;
|
|
47
|
+
responseValue?: unknown;
|
|
48
|
+
};
|
|
49
|
+
type PathInvalidation = Extract<SyncInvalidation, { kind: "path" }>;
|
|
50
|
+
|
|
40
51
|
const routeMetadata = new WeakMap<Request, RouteSyncMetadata>();
|
|
41
52
|
const activeMutations = new WeakMap<Request, ActiveMutation>();
|
|
42
53
|
|
|
54
|
+
function hideTransportResponse<TContext>(
|
|
55
|
+
hook: (context: TContext) => Promise<Response | undefined>
|
|
56
|
+
): TransportHook<TContext> {
|
|
57
|
+
// Sync responses short-circuit Elysia at runtime; they are not route success payloads for Eden.
|
|
58
|
+
return hook as TransportHook<TContext>;
|
|
59
|
+
}
|
|
60
|
+
|
|
43
61
|
function invalidationInputFromSync(input: Exclude<SyncRouteOption, false>): InvalidationInput {
|
|
44
62
|
if (input && typeof input === "object" && "invalidate" in input) {
|
|
45
63
|
return input.invalidate;
|
|
@@ -60,15 +78,6 @@ function getIdempotencyKey(ctx: MutationContext): string | undefined {
|
|
|
60
78
|
return fromRequest || undefined;
|
|
61
79
|
}
|
|
62
80
|
|
|
63
|
-
async function getPrincipalScope(request: Request): Promise<string> {
|
|
64
|
-
const authorization = request.headers.get("authorization");
|
|
65
|
-
const credentials = authorization
|
|
66
|
-
? JSON.stringify(["authorization", authorization])
|
|
67
|
-
: JSON.stringify(["cookie", request.headers.get("cookie") ?? ""]);
|
|
68
|
-
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(credentials));
|
|
69
|
-
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
70
|
-
}
|
|
71
|
-
|
|
72
81
|
function supportsReplayBody(request: Request): boolean {
|
|
73
82
|
const contentType = request.headers.get("content-type")?.toLowerCase();
|
|
74
83
|
const mediaType = contentType?.split(";", 1)[0]?.trim();
|
|
@@ -91,66 +100,179 @@ function conflictResponse(reason: "in-progress" | "payload-mismatch"): Response
|
|
|
91
100
|
: "The Idempotency-Key was already used with a different request.",
|
|
92
101
|
},
|
|
93
102
|
{
|
|
94
|
-
status: 409,
|
|
95
103
|
headers: inProgress ? { "retry-after": "1" } : undefined,
|
|
104
|
+
status: 409,
|
|
96
105
|
}
|
|
97
106
|
);
|
|
98
107
|
}
|
|
99
108
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
109
|
+
function leaseLostResponse(): Response {
|
|
110
|
+
return Response.json(
|
|
111
|
+
{
|
|
112
|
+
code: "FURIN_SYNC_LEASE_LOST",
|
|
113
|
+
message: "The mutation lease was lost before its response could be committed.",
|
|
114
|
+
},
|
|
115
|
+
{ status: 503 }
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function normalizedInvalidations(input: InvalidationInput | undefined): SyncInvalidation[] {
|
|
120
|
+
if (!input) {
|
|
121
|
+
return [];
|
|
110
122
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
123
|
+
const rules = Array.isArray(input) ? input : [input];
|
|
124
|
+
const invalidations: SyncInvalidation[] = [];
|
|
125
|
+
for (const rule of rules) {
|
|
126
|
+
if ("path" in rule && rule.path) {
|
|
127
|
+
invalidations.push({ kind: "path", path: rule.path, type: rule.type });
|
|
128
|
+
}
|
|
129
|
+
if (rule.tags && rule.tags.length > 0) {
|
|
130
|
+
invalidations.push({ kind: "tags", tags: [...rule.tags] });
|
|
131
|
+
}
|
|
119
132
|
}
|
|
133
|
+
return invalidations;
|
|
134
|
+
}
|
|
120
135
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
136
|
+
function pendingPathInvalidations(entries: readonly string[]): PathInvalidation[] {
|
|
137
|
+
return entries.map((entry) =>
|
|
138
|
+
entry.endsWith(":layout")
|
|
139
|
+
? { kind: "path" as const, path: entry.slice(0, -":layout".length), type: "layout" }
|
|
140
|
+
: { kind: "path" as const, path: entry, type: "page" }
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function furinSync(options: SyncRuntimeOptions) {
|
|
145
|
+
const runtime = resolveSyncRuntime(options);
|
|
146
|
+
|
|
147
|
+
async function beginMutation(ctx: MutationContext): Promise<Response | undefined> {
|
|
148
|
+
if (!isMutationMethod(ctx.request.method) || routeMetadata.get(ctx.request)?.disabled) {
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
const idempotencyKey = getIdempotencyKey(ctx);
|
|
152
|
+
if (!idempotencyKey) {
|
|
153
|
+
return new Response("Missing Idempotency-Key header", {
|
|
154
|
+
headers: { "content-type": "text/plain; charset=utf-8" },
|
|
155
|
+
status: 428,
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
if (!supportsReplayBody(ctx.request)) {
|
|
159
|
+
return Response.json(
|
|
160
|
+
{
|
|
161
|
+
code: "FURIN_UNSUPPORTED_SYNC_BODY",
|
|
162
|
+
message: "This request body cannot be replayed. Set sync: false on the route.",
|
|
163
|
+
},
|
|
164
|
+
{ status: 415 }
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const url = new URL(ctx.request.url);
|
|
169
|
+
const principal = await options.principal(ctx as Context);
|
|
170
|
+
if (principal.length === 0) {
|
|
171
|
+
throw new Error("[furin] Sync principal must not be empty.");
|
|
172
|
+
}
|
|
173
|
+
const key = `${ctx.request.method}:${url.pathname}:${idempotencyKey}`;
|
|
174
|
+
const fingerprint = createMutationFingerprint({ body: ctx.body, request: ctx.request });
|
|
175
|
+
const result = await runtime.adapter.beginMutation({ fingerprint, key, principal });
|
|
176
|
+
if (result.kind === "replay") {
|
|
177
|
+
return replayResponse(result.response);
|
|
178
|
+
}
|
|
179
|
+
if (result.kind === "conflict") {
|
|
180
|
+
return conflictResponse(result.reason);
|
|
181
|
+
}
|
|
182
|
+
const active: ActiveMutation = { lease: result.lease, renewal: undefined };
|
|
183
|
+
const renewAfter = Math.max(1000, Math.floor(result.lease.leaseMs / 3));
|
|
184
|
+
const scheduleRenewal = () => {
|
|
185
|
+
active.renewal = setTimeout(async () => {
|
|
186
|
+
if (activeMutations.get(ctx.request) === active) {
|
|
187
|
+
scheduleRenewal();
|
|
188
|
+
}
|
|
189
|
+
await runtime.adapter.renewMutation(result.lease).catch(() => undefined);
|
|
190
|
+
}, renewAfter);
|
|
191
|
+
active.renewal.unref?.();
|
|
192
|
+
};
|
|
193
|
+
activeMutations.set(ctx.request, active);
|
|
194
|
+
scheduleRenewal();
|
|
128
195
|
}
|
|
129
|
-
|
|
130
|
-
|
|
196
|
+
|
|
197
|
+
async function abortMutation(request: Request): Promise<void> {
|
|
198
|
+
const active = activeMutations.get(request);
|
|
199
|
+
if (!active) {
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
activeMutations.delete(request);
|
|
203
|
+
if (active.renewal) {
|
|
204
|
+
clearTimeout(active.renewal);
|
|
205
|
+
}
|
|
206
|
+
await runtime.adapter.abortMutation(active.lease);
|
|
131
207
|
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
);
|
|
208
|
+
|
|
209
|
+
async function persistMutation(
|
|
210
|
+
ctx: CompletionContext,
|
|
211
|
+
active: ActiveMutation
|
|
212
|
+
): Promise<Response | undefined> {
|
|
213
|
+
const result = await storeResponse(ctx.responseValue, ctx.set);
|
|
214
|
+
const manualPending = peekPendingInvalidations();
|
|
215
|
+
const invalidate = routeMetadata.get(ctx.request)?.invalidate;
|
|
216
|
+
if (invalidate) {
|
|
217
|
+
runInvalidationRules(invalidate);
|
|
218
|
+
}
|
|
219
|
+
const pending = appendPendingInvalidationHeader(ctx.set);
|
|
220
|
+
if (pending.length > 0) {
|
|
221
|
+
ctx.set.headers["x-furin-sync"] = "1";
|
|
222
|
+
}
|
|
223
|
+
const response = mergeStoredResponseHeaders(result.response, ctx.set.headers);
|
|
224
|
+
const semanticInvalidations = normalizedInvalidations(invalidate);
|
|
225
|
+
const invalidations = [...semanticInvalidations];
|
|
226
|
+
for (const manual of pendingPathInvalidations(manualPending)) {
|
|
227
|
+
const duplicated = semanticInvalidations.some(
|
|
228
|
+
(semantic) =>
|
|
229
|
+
semantic.kind === "path" && semantic.path === manual.path && semantic.type === manual.type
|
|
230
|
+
);
|
|
231
|
+
if (!duplicated) {
|
|
232
|
+
invalidations.push(manual);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
const completion = await runtime.adapter.completeMutation({
|
|
236
|
+
invalidations,
|
|
237
|
+
lease: active.lease,
|
|
238
|
+
response,
|
|
239
|
+
});
|
|
240
|
+
if (completion.kind === "lost") {
|
|
241
|
+
return leaseLostResponse();
|
|
242
|
+
}
|
|
243
|
+
if (completion.cursor !== undefined) {
|
|
244
|
+
runtime.notifier.publish(completion.cursor).catch(() => undefined);
|
|
245
|
+
}
|
|
246
|
+
if (result.kind === "unreplayable") {
|
|
247
|
+
return replayResponse(response);
|
|
248
|
+
}
|
|
140
249
|
}
|
|
141
|
-
activeMutations.set(ctx.request, { mutationId: result.mutationId });
|
|
142
|
-
}
|
|
143
250
|
|
|
144
|
-
async function
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
251
|
+
async function finishMutation(ctx: CompletionContext): Promise<Response | undefined> {
|
|
252
|
+
const active = activeMutations.get(ctx.request);
|
|
253
|
+
if (!active) {
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
try {
|
|
257
|
+
if (!isSuccessfulMutationResponse(ctx)) {
|
|
258
|
+
await runtime.adapter.abortMutation(active.lease);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
return await persistMutation(ctx, active);
|
|
262
|
+
} catch (error) {
|
|
263
|
+
await runtime.adapter.abortMutation(active.lease).catch(() => undefined);
|
|
264
|
+
throw error;
|
|
265
|
+
} finally {
|
|
266
|
+
activeMutations.delete(ctx.request);
|
|
267
|
+
if (active.renewal) {
|
|
268
|
+
clearTimeout(active.renewal);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
148
271
|
}
|
|
149
|
-
activeMutations.delete(request);
|
|
150
|
-
await memorySyncAdapter.abortMutation(active);
|
|
151
|
-
}
|
|
152
272
|
|
|
153
|
-
|
|
273
|
+
const beginMutationHook = hideTransportResponse(beginMutation);
|
|
274
|
+
const finishMutationHook = hideTransportResponse(finishMutation);
|
|
275
|
+
|
|
154
276
|
return new Elysia({ name: "furin-sync" })
|
|
155
277
|
.macro({
|
|
156
278
|
sync(input: SyncRouteOption) {
|
|
@@ -166,34 +288,7 @@ export function furinSync() {
|
|
|
166
288
|
};
|
|
167
289
|
},
|
|
168
290
|
})
|
|
169
|
-
.onBeforeHandle({ as: "global" },
|
|
170
|
-
.onAfterHandle({ as: "global" },
|
|
171
|
-
const active = activeMutations.get(ctx.request);
|
|
172
|
-
if (!active) {
|
|
173
|
-
return;
|
|
174
|
-
}
|
|
175
|
-
if (!isSuccessfulMutationResponse(ctx)) {
|
|
176
|
-
await abortMutation(ctx.request);
|
|
177
|
-
return;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
const invalidate = routeMetadata.get(ctx.request)?.invalidate;
|
|
181
|
-
if (invalidate) {
|
|
182
|
-
runInvalidationRules(invalidate);
|
|
183
|
-
}
|
|
184
|
-
const pending = appendPendingInvalidationHeader(ctx.set);
|
|
185
|
-
if (pending.length > 0) {
|
|
186
|
-
ctx.set.headers["x-furin-sync"] = "1";
|
|
187
|
-
}
|
|
188
|
-
const response = await storeResponse(ctx.responseValue, ctx.set);
|
|
189
|
-
await memorySyncAdapter.commitMutation({ ...active, response });
|
|
190
|
-
activeMutations.delete(ctx.request);
|
|
191
|
-
|
|
192
|
-
if (pending.length > 0) {
|
|
193
|
-
// Notify every mounted app's sync stream — a mutation on a shared API
|
|
194
|
-
// may invalidate pages rendered by any of them.
|
|
195
|
-
publishSyncInvalidation(pending);
|
|
196
|
-
}
|
|
197
|
-
})
|
|
291
|
+
.onBeforeHandle({ as: "global" }, beginMutationHook)
|
|
292
|
+
.onAfterHandle({ as: "global" }, finishMutationHook)
|
|
198
293
|
.onError({ as: "global" }, ({ request }) => abortMutation(request));
|
|
199
294
|
}
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import type { SQL } from "bun";
|
|
2
|
+
import type {
|
|
3
|
+
BeginMutationInput,
|
|
4
|
+
BeginMutationResult,
|
|
5
|
+
ChangePage,
|
|
6
|
+
CompleteMutationInput,
|
|
7
|
+
CompleteMutationResult,
|
|
8
|
+
MutationLease,
|
|
9
|
+
ReadChangesInput,
|
|
10
|
+
StoredResponse,
|
|
11
|
+
SyncAdapter,
|
|
12
|
+
SyncChange,
|
|
13
|
+
SyncInvalidation,
|
|
14
|
+
} from "../adapter.ts";
|
|
15
|
+
|
|
16
|
+
const CHANGE_RETENTION = 1000;
|
|
17
|
+
const LEASE_MS = 30_000;
|
|
18
|
+
const MUTATION_TTL_MS = 24 * 60 * 60 * 1000;
|
|
19
|
+
const UNSIGNED_INTEGER_PATTERN = /^\d+$/;
|
|
20
|
+
|
|
21
|
+
export interface PostgresSyncAdapterOptions {
|
|
22
|
+
namespace: string;
|
|
23
|
+
sql: SQL;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface MutationRow {
|
|
27
|
+
expired: boolean;
|
|
28
|
+
fingerprint: string;
|
|
29
|
+
mutation_id: string;
|
|
30
|
+
response_body: Uint8Array | null;
|
|
31
|
+
response_headers: [string, string][] | null;
|
|
32
|
+
response_status: number | null;
|
|
33
|
+
state: "in-progress" | "succeeded";
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface CursorRow {
|
|
37
|
+
current_cursor: string | number | bigint;
|
|
38
|
+
oldest_cursor: string | number | bigint;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface ChangeRow {
|
|
42
|
+
cursor: string | number | bigint;
|
|
43
|
+
invalidations: SyncInvalidation[];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function mutationKey(input: Pick<MutationLease, "key" | "principal">): string {
|
|
47
|
+
return new Bun.CryptoHasher("sha256")
|
|
48
|
+
.update(`${input.principal.length}:${input.principal}${input.key}`)
|
|
49
|
+
.digest("hex");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function storedResponse(row: MutationRow): StoredResponse {
|
|
53
|
+
if (row.response_body === null || row.response_headers === null || row.response_status === null) {
|
|
54
|
+
throw new Error("[furin-sync-postgres] Succeeded mutation has no replay response.");
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
body: new Uint8Array(row.response_body),
|
|
58
|
+
headers: row.response_headers,
|
|
59
|
+
status: row.response_status,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export class PostgresSyncAdapter implements SyncAdapter {
|
|
64
|
+
readonly scope = "distributed" as const;
|
|
65
|
+
private readonly namespace: string;
|
|
66
|
+
private readonly sql: SQL;
|
|
67
|
+
|
|
68
|
+
constructor(options: PostgresSyncAdapterOptions) {
|
|
69
|
+
if (options.namespace.length === 0) {
|
|
70
|
+
throw new Error("[furin-sync-postgres] namespace must not be empty.");
|
|
71
|
+
}
|
|
72
|
+
this.namespace = options.namespace;
|
|
73
|
+
this.sql = options.sql;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
beginMutation(input: BeginMutationInput): Promise<BeginMutationResult> {
|
|
77
|
+
return this.sql.begin(async (tx) => {
|
|
78
|
+
const key = mutationKey(input);
|
|
79
|
+
await tx`
|
|
80
|
+
DELETE FROM furin_sync.mutations
|
|
81
|
+
WHERE ctid IN (
|
|
82
|
+
SELECT ctid FROM furin_sync.mutations
|
|
83
|
+
WHERE
|
|
84
|
+
(state = 'succeeded' AND expires_at <= clock_timestamp())
|
|
85
|
+
OR (
|
|
86
|
+
state = 'in-progress'
|
|
87
|
+
AND lease_expires_at <= clock_timestamp()
|
|
88
|
+
AND expires_at <= clock_timestamp()
|
|
89
|
+
)
|
|
90
|
+
LIMIT 100
|
|
91
|
+
)
|
|
92
|
+
`;
|
|
93
|
+
await tx`SELECT pg_advisory_xact_lock(hashtextextended(${`${this.namespace}:${key}`}, 0))`;
|
|
94
|
+
const rows = await tx<MutationRow[]>`
|
|
95
|
+
SELECT mutation_id, fingerprint, state, response_status, response_headers,
|
|
96
|
+
response_body,
|
|
97
|
+
CASE
|
|
98
|
+
WHEN state = 'succeeded' THEN expires_at <= clock_timestamp()
|
|
99
|
+
ELSE lease_expires_at <= clock_timestamp()
|
|
100
|
+
END AS expired
|
|
101
|
+
FROM furin_sync.mutations
|
|
102
|
+
WHERE namespace = ${this.namespace} AND mutation_key = ${key}
|
|
103
|
+
FOR UPDATE
|
|
104
|
+
`;
|
|
105
|
+
const [existing] = rows;
|
|
106
|
+
if (existing && existing.fingerprint !== input.fingerprint) {
|
|
107
|
+
return { kind: "conflict", reason: "payload-mismatch" } as const;
|
|
108
|
+
}
|
|
109
|
+
if (existing && !existing.expired) {
|
|
110
|
+
if (existing.state === "in-progress") {
|
|
111
|
+
return { kind: "conflict", reason: "in-progress" } as const;
|
|
112
|
+
}
|
|
113
|
+
return { kind: "replay", response: storedResponse(existing) } as const;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const id = crypto.randomUUID();
|
|
117
|
+
await tx`
|
|
118
|
+
INSERT INTO furin_sync.mutations (
|
|
119
|
+
namespace, mutation_key, mutation_id, fingerprint, state,
|
|
120
|
+
lease_expires_at, expires_at, created_at
|
|
121
|
+
) VALUES (
|
|
122
|
+
${this.namespace}, ${key}, ${id}, ${input.fingerprint}, 'in-progress',
|
|
123
|
+
clock_timestamp() + (${LEASE_MS} * interval '1 millisecond'),
|
|
124
|
+
clock_timestamp() + (${MUTATION_TTL_MS} * interval '1 millisecond'),
|
|
125
|
+
clock_timestamp()
|
|
126
|
+
)
|
|
127
|
+
ON CONFLICT (namespace, mutation_key) DO UPDATE SET
|
|
128
|
+
mutation_id = EXCLUDED.mutation_id,
|
|
129
|
+
fingerprint = EXCLUDED.fingerprint,
|
|
130
|
+
state = 'in-progress',
|
|
131
|
+
response_status = NULL,
|
|
132
|
+
response_headers = NULL,
|
|
133
|
+
response_body = NULL,
|
|
134
|
+
lease_expires_at = EXCLUDED.lease_expires_at,
|
|
135
|
+
expires_at = EXCLUDED.expires_at,
|
|
136
|
+
created_at = EXCLUDED.created_at,
|
|
137
|
+
completed_at = NULL
|
|
138
|
+
`;
|
|
139
|
+
return {
|
|
140
|
+
kind: "execute",
|
|
141
|
+
lease: { id, key: input.key, leaseMs: LEASE_MS, principal: input.principal },
|
|
142
|
+
} as const;
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async renewMutation(lease: MutationLease): Promise<"lost" | "renewed"> {
|
|
147
|
+
const rows = await this.sql<{ mutation_id: string }[]>`
|
|
148
|
+
UPDATE furin_sync.mutations
|
|
149
|
+
SET lease_expires_at = clock_timestamp() + (${lease.leaseMs} * interval '1 millisecond')
|
|
150
|
+
WHERE namespace = ${this.namespace}
|
|
151
|
+
AND mutation_key = ${mutationKey(lease)}
|
|
152
|
+
AND mutation_id = ${lease.id}
|
|
153
|
+
AND state = 'in-progress'
|
|
154
|
+
AND lease_expires_at > clock_timestamp()
|
|
155
|
+
RETURNING mutation_id
|
|
156
|
+
`;
|
|
157
|
+
return rows.length === 1 ? "renewed" : "lost";
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
completeMutation(input: CompleteMutationInput): Promise<CompleteMutationResult> {
|
|
161
|
+
return this.sql.begin(async (tx) => {
|
|
162
|
+
const key = mutationKey(input.lease);
|
|
163
|
+
await tx`SELECT pg_advisory_xact_lock(hashtextextended(${`${this.namespace}:${key}`}, 0))`;
|
|
164
|
+
const active = await tx<{ mutation_id: string }[]>`
|
|
165
|
+
SELECT mutation_id FROM furin_sync.mutations
|
|
166
|
+
WHERE namespace = ${this.namespace}
|
|
167
|
+
AND mutation_key = ${key}
|
|
168
|
+
AND mutation_id = ${input.lease.id}
|
|
169
|
+
AND state = 'in-progress'
|
|
170
|
+
AND lease_expires_at > clock_timestamp()
|
|
171
|
+
FOR UPDATE
|
|
172
|
+
`;
|
|
173
|
+
if (active.length === 0) {
|
|
174
|
+
return { kind: "lost" } as const;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
let cursor: string | undefined;
|
|
178
|
+
if (input.invalidations.length > 0) {
|
|
179
|
+
await tx`
|
|
180
|
+
INSERT INTO furin_sync.streams (namespace, current_cursor, oldest_cursor)
|
|
181
|
+
VALUES (${this.namespace}, 0, 0)
|
|
182
|
+
ON CONFLICT (namespace) DO NOTHING
|
|
183
|
+
`;
|
|
184
|
+
const cursors = await tx<{ current_cursor: string | number | bigint }[]>`
|
|
185
|
+
UPDATE furin_sync.streams
|
|
186
|
+
SET current_cursor = current_cursor + 1
|
|
187
|
+
WHERE namespace = ${this.namespace}
|
|
188
|
+
RETURNING current_cursor
|
|
189
|
+
`;
|
|
190
|
+
cursor = String(cursors[0]?.current_cursor);
|
|
191
|
+
await tx`
|
|
192
|
+
INSERT INTO furin_sync.changes (namespace, cursor, invalidations)
|
|
193
|
+
VALUES (
|
|
194
|
+
${this.namespace},
|
|
195
|
+
${cursor},
|
|
196
|
+
${JSON.stringify(input.invalidations)}::text::jsonb
|
|
197
|
+
)
|
|
198
|
+
`;
|
|
199
|
+
await tx`
|
|
200
|
+
WITH removed AS (
|
|
201
|
+
DELETE FROM furin_sync.changes
|
|
202
|
+
WHERE namespace = ${this.namespace}
|
|
203
|
+
AND cursor <= GREATEST(0, ${cursor}::bigint - ${CHANGE_RETENTION})
|
|
204
|
+
RETURNING cursor
|
|
205
|
+
)
|
|
206
|
+
UPDATE furin_sync.streams
|
|
207
|
+
SET oldest_cursor = COALESCE((SELECT MAX(cursor) + 1 FROM removed), oldest_cursor)
|
|
208
|
+
WHERE namespace = ${this.namespace}
|
|
209
|
+
`;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
await tx`
|
|
213
|
+
UPDATE furin_sync.mutations
|
|
214
|
+
SET state = 'succeeded',
|
|
215
|
+
response_status = ${input.response.status},
|
|
216
|
+
response_headers = ${JSON.stringify(input.response.headers)}::text::jsonb,
|
|
217
|
+
response_body = ${input.response.body},
|
|
218
|
+
completed_at = clock_timestamp(),
|
|
219
|
+
expires_at = clock_timestamp() + (${MUTATION_TTL_MS} * interval '1 millisecond')
|
|
220
|
+
WHERE namespace = ${this.namespace}
|
|
221
|
+
AND mutation_key = ${key}
|
|
222
|
+
AND mutation_id = ${input.lease.id}
|
|
223
|
+
`;
|
|
224
|
+
return { cursor, kind: "committed" } as const;
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async abortMutation(lease: MutationLease): Promise<void> {
|
|
229
|
+
await this.sql`
|
|
230
|
+
DELETE FROM furin_sync.mutations
|
|
231
|
+
WHERE namespace = ${this.namespace}
|
|
232
|
+
AND mutation_key = ${mutationKey(lease)}
|
|
233
|
+
AND mutation_id = ${lease.id}
|
|
234
|
+
AND state = 'in-progress'
|
|
235
|
+
`;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async currentCursor(): Promise<string> {
|
|
239
|
+
const rows = await this.sql<Pick<CursorRow, "current_cursor">[]>`
|
|
240
|
+
SELECT current_cursor FROM furin_sync.streams WHERE namespace = ${this.namespace}
|
|
241
|
+
`;
|
|
242
|
+
return String(rows[0]?.current_cursor ?? 0);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async readChanges(input: ReadChangesInput): Promise<ChangePage> {
|
|
246
|
+
const cursorRows = await this.sql<CursorRow[]>`
|
|
247
|
+
SELECT current_cursor, oldest_cursor
|
|
248
|
+
FROM furin_sync.streams WHERE namespace = ${this.namespace}
|
|
249
|
+
`;
|
|
250
|
+
const currentCursor = String(cursorRows[0]?.current_cursor ?? 0);
|
|
251
|
+
if (input.after === undefined) {
|
|
252
|
+
return { changes: [], cursor: currentCursor, hasMore: false, reset: false };
|
|
253
|
+
}
|
|
254
|
+
if (!UNSIGNED_INTEGER_PATTERN.test(input.after)) {
|
|
255
|
+
return { changes: [], cursor: currentCursor, hasMore: false, reset: true };
|
|
256
|
+
}
|
|
257
|
+
if (BigInt(input.after) > BigInt(currentCursor)) {
|
|
258
|
+
return { changes: [], cursor: currentCursor, hasMore: false, reset: true };
|
|
259
|
+
}
|
|
260
|
+
const oldest = BigInt(cursorRows[0]?.oldest_cursor ?? 0);
|
|
261
|
+
if (BigInt(input.after) < oldest - 1n) {
|
|
262
|
+
return { changes: [], cursor: currentCursor, hasMore: false, reset: true };
|
|
263
|
+
}
|
|
264
|
+
const rows = await this.sql<ChangeRow[]>`
|
|
265
|
+
SELECT cursor, invalidations
|
|
266
|
+
FROM furin_sync.changes
|
|
267
|
+
WHERE namespace = ${this.namespace} AND cursor > ${input.after}::bigint
|
|
268
|
+
ORDER BY cursor ASC
|
|
269
|
+
LIMIT ${input.limit + 1}
|
|
270
|
+
`;
|
|
271
|
+
const latestCursorRows = await this.sql<CursorRow[]>`
|
|
272
|
+
SELECT current_cursor, oldest_cursor
|
|
273
|
+
FROM furin_sync.streams WHERE namespace = ${this.namespace}
|
|
274
|
+
`;
|
|
275
|
+
const latestCurrentCursor = String(latestCursorRows[0]?.current_cursor ?? 0);
|
|
276
|
+
const latestOldest = BigInt(latestCursorRows[0]?.oldest_cursor ?? 0);
|
|
277
|
+
if (BigInt(input.after) < latestOldest - 1n) {
|
|
278
|
+
return {
|
|
279
|
+
changes: [],
|
|
280
|
+
cursor: latestCurrentCursor,
|
|
281
|
+
hasMore: false,
|
|
282
|
+
reset: true,
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
const hasMore = rows.length > input.limit;
|
|
286
|
+
const changes: SyncChange[] = rows.slice(0, input.limit).map((row) => ({
|
|
287
|
+
cursor: String(row.cursor),
|
|
288
|
+
invalidations: row.invalidations,
|
|
289
|
+
}));
|
|
290
|
+
return {
|
|
291
|
+
changes,
|
|
292
|
+
cursor: changes.at(-1)?.cursor ?? input.after,
|
|
293
|
+
hasMore,
|
|
294
|
+
reset: false,
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export function postgresSyncAdapter(options: PostgresSyncAdapterOptions): PostgresSyncAdapter {
|
|
300
|
+
return new PostgresSyncAdapter(options);
|
|
301
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { SQL } from "bun";
|
|
3
|
+
|
|
4
|
+
const databaseUrl = process.env.FURIN_SYNC_POSTGRES_URL;
|
|
5
|
+
if (databaseUrl === undefined || databaseUrl.length === 0) {
|
|
6
|
+
throw new Error("FURIN_SYNC_POSTGRES_URL is required.");
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const sql = new SQL(databaseUrl);
|
|
10
|
+
try {
|
|
11
|
+
const migration = await Bun.file(new URL("./migration.sql", import.meta.url)).text();
|
|
12
|
+
await sql.unsafe(migration);
|
|
13
|
+
} finally {
|
|
14
|
+
await sql.close();
|
|
15
|
+
}
|