@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.
- package/dist/adapter/runtime-build.d.ts +1 -1
- package/dist/build/client.d.ts +4 -1
- package/dist/build/elysia-aot-worker.d.ts +22 -0
- package/dist/build/elysia-aot.d.ts +1 -1
- package/dist/build/entry-template.d.ts +3 -0
- package/dist/build/entry-template.ts +7 -0
- package/dist/build/hydrate.d.ts +1 -1
- package/dist/build/index.js +1880 -401
- package/dist/build/preload-manifest.d.ts +17 -0
- package/dist/build/types.d.ts +6 -0
- package/dist/cli/index.js +1878 -408
- package/dist/client/client-module.d.ts +26 -0
- package/dist/client/define-route.d.ts +9 -0
- package/dist/client/document.d.ts +2 -0
- package/dist/client/internal/runtime-types.d.ts +2 -0
- package/dist/client/link.js +942 -122
- package/dist/client/mutation.d.ts +38 -0
- package/dist/client/query-store.d.ts +85 -0
- package/dist/client/query.d.ts +14 -0
- package/dist/client/route-api.d.ts +11 -0
- package/dist/client/router/context.d.ts +3 -2
- package/dist/client/router/index.d.ts +1 -1
- package/dist/client/router/link-utils.d.ts +8 -1
- package/dist/client/router/navigation.d.ts +2 -9
- package/dist/client/router/optimistic.d.ts +41 -0
- package/dist/client/router/search/index.d.ts +3 -3
- package/dist/client/router/search-store.d.ts +1 -0
- package/dist/client/router/sync-catch-up.d.ts +3 -0
- package/dist/client/router/types.d.ts +51 -7
- package/dist/client/sync.d.ts +39 -22
- package/dist/client.d.ts +11 -33
- package/dist/client.js +1219 -59
- package/dist/config.d.ts +7 -0
- package/dist/config.js +1 -0
- package/dist/define-route.d.ts +78 -32
- package/dist/env.d.ts +2 -2
- package/dist/furin.d.ts +1 -2
- package/dist/furin.js +2484 -708
- package/dist/plugin/hmr-dependencies.d.ts +2 -0
- package/dist/plugin/index.js +349 -18
- package/dist/plugin/transform-client-module.d.ts +16 -0
- package/dist/plugin/transform-client.d.ts +2 -0
- package/dist/plugin/transform-isomorphic.d.ts +1 -1
- package/dist/routes.d.ts +6 -0
- package/dist/rsc-client.js +87 -16
- package/dist/rsc.js +87 -16
- package/dist/server/auto-invalidate/registry.d.ts +1 -0
- package/dist/server/auto-invalidate/types.d.ts +2 -0
- package/dist/server/cache/isr.d.ts +2 -4
- package/dist/server/cache/route-cache.d.ts +5 -0
- package/dist/server/dev/graph.d.ts +1 -0
- package/dist/server/dev-page-plugin.d.ts +5 -19
- package/dist/server/internal.d.ts +3 -0
- package/dist/server/internal.js +55 -35
- package/dist/server/production-server.js +54 -34
- package/dist/server/render/loaders.d.ts +4 -2
- package/dist/server/render/react-stream.d.ts +3 -0
- package/dist/server/render/ssr.d.ts +2 -1
- package/dist/server/render/template.d.ts +4 -0
- package/dist/server/router/defined-route.d.ts +2 -0
- package/dist/server/router/hmr.d.ts +1 -1
- package/dist/server/router/patterns.d.ts +2 -0
- package/dist/server/router/types.d.ts +1 -1
- package/dist/server/sync/adapter.d.ts +25 -4
- package/dist/server/sync/atomic.d.ts +25 -0
- package/dist/server/sync/drizzle/index.d.ts +45 -0
- package/dist/server/sync/drizzle/index.js +540 -0
- package/dist/server/sync/execution-error.d.ts +2 -0
- package/dist/server/sync/index.d.ts +2 -1
- package/dist/server/sync/index.js +533 -105
- package/dist/server/sync/mutation-handler.d.ts +4 -0
- package/dist/server/sync/plugin.d.ts +34 -11
- package/dist/server/sync/postgres/execute.d.ts +3 -0
- package/dist/server/sync/postgres/index.d.ts +12 -1
- package/dist/server/sync/postgres/index.js +34 -13
- package/dist/server/sync/postgres/sql.d.ts +8 -0
- package/dist/server/sync/prisma/index.d.ts +24 -0
- package/dist/server/sync/prisma/index.js +340 -0
- package/dist/server/sync/queries.d.ts +21 -0
- package/dist/server/sync/query-context.d.ts +5 -0
- package/dist/server/sync/redis/index.js +3 -3
- package/dist/server/sync/redis/scripts.d.ts +1 -1
- package/dist/server/sync/response.d.ts +1 -0
- package/dist/server/sync/sqlite/index.d.ts +3 -0
- package/dist/server/sync/sqlite/index.js +10 -4
- package/dist/server/sync/stream.d.ts +2 -5
- package/dist/server/sync/validation.d.ts +4 -0
- package/dist/shared/defer.d.ts +31 -0
- package/dist/shared/error.d.ts +2 -2
- package/dist/shared/page-key.d.ts +7 -0
- package/dist/shared/query-bindings.d.ts +12 -0
- package/dist/shared/route-frame.d.ts +1 -0
- package/dist/shared/sync-query.d.ts +40 -0
- package/package.json +29 -6
- package/src/adapter/package.ts +12 -2
- package/src/adapter/runtime-build.ts +63 -12
- package/src/adapter/static.ts +7 -2
- package/src/adapter/vercel.ts +15 -13
- package/src/build/client.ts +23 -5
- package/src/build/elysia-aot-worker.ts +51 -0
- package/src/build/elysia-aot.ts +83 -19
- package/src/build/entry-template.ts +7 -0
- package/src/build/hydrate.ts +21 -3
- package/src/build/preload-manifest.ts +100 -0
- package/src/build/production-instrumentation.ts +6 -3
- package/src/build/types.ts +4 -0
- package/src/cli/index.ts +1 -0
- package/src/client/browser-events-runtime.ts +4 -0
- package/src/client/client-module.ts +57 -0
- package/src/client/define-route.ts +11 -1
- package/src/client/document.tsx +28 -18
- package/src/client/hmr.ts +2 -1
- package/src/client/internal/runtime-types.ts +2 -0
- package/src/client/link.tsx +8 -8
- package/src/client/mutation.ts +136 -0
- package/src/client/query-store.ts +418 -0
- package/src/client/query.tsx +67 -0
- package/src/client/route-api.tsx +75 -0
- package/src/client/router/boundary-tree.tsx +19 -12
- package/src/client/router/context.ts +57 -4
- package/src/client/router/index.ts +3 -0
- package/src/client/router/link-utils.ts +29 -1
- package/src/client/router/navigation.ts +3 -50
- package/src/client/router/optimistic.ts +233 -0
- package/src/client/router/provider.tsx +306 -46
- package/src/client/router/search/index.ts +37 -17
- package/src/client/router/search-store.ts +4 -0
- package/src/client/router/sync-catch-up.ts +7 -0
- package/src/client/router/types.ts +73 -9
- package/src/client/sync.ts +438 -65
- package/src/client.ts +20 -60
- package/src/config.ts +5 -0
- package/src/define-route.ts +113 -55
- package/src/env.d.ts +2 -2
- package/src/furin.ts +75 -13
- package/src/plugin/hmr-dependencies.ts +58 -0
- package/src/plugin/index.ts +38 -2
- package/src/plugin/routes.ts +28 -16
- package/src/plugin/transform-client-module.ts +123 -0
- package/src/plugin/transform-client.ts +293 -13
- package/src/plugin/transform-isomorphic.ts +11 -5
- package/src/routes.ts +8 -0
- package/src/rsc/shared.tsx +104 -18
- package/src/server/auto-invalidate/registry.ts +4 -0
- package/src/server/auto-invalidate/runtime.ts +17 -0
- package/src/server/auto-invalidate/types.ts +6 -0
- package/src/server/cache/isr.ts +6 -34
- package/src/server/cache/route-cache.ts +40 -4
- package/src/server/dev/graph.ts +16 -2
- package/src/server/dev-page-plugin.ts +93 -59
- package/src/server/internal.ts +3 -0
- package/src/server/render/document.tsx +10 -1
- package/src/server/render/element.tsx +21 -11
- package/src/server/render/isr.ts +61 -29
- package/src/server/render/loaders.ts +118 -47
- package/src/server/render/mixed-cache.ts +33 -4
- package/src/server/render/not-found.ts +4 -7
- package/src/server/render/ppr-document.ts +2 -1
- package/src/server/render/ppr-route.ts +30 -10
- package/src/server/render/react-stream.ts +17 -0
- package/src/server/render/route-frame-transport.ts +3 -0
- package/src/server/render/ssg.ts +51 -18
- package/src/server/render/ssr.ts +53 -8
- package/src/server/render/template.ts +23 -0
- package/src/server/router/defined-route.ts +3 -0
- package/src/server/router/discovery.ts +25 -9
- package/src/server/router/hmr.ts +3 -2
- package/src/server/router/patterns.ts +16 -0
- package/src/server/router/plugin.ts +27 -12
- package/src/server/router/types.ts +1 -1
- package/src/server/sync/adapter.ts +41 -4
- package/src/server/sync/atomic.ts +303 -0
- package/src/server/sync/drizzle/index.ts +145 -0
- package/src/server/sync/execution-error.ts +1 -0
- package/src/server/sync/fingerprint.ts +2 -6
- package/src/server/sync/index.ts +6 -0
- package/src/server/sync/mutation-handler.ts +69 -0
- package/src/server/sync/plugin.ts +177 -60
- package/src/server/sync/postgres/execute.ts +20 -0
- package/src/server/sync/postgres/index.ts +52 -16
- package/src/server/sync/postgres/sql.ts +20 -0
- package/src/server/sync/prisma/index.ts +70 -0
- package/src/server/sync/queries.ts +75 -0
- package/src/server/sync/query-context.ts +85 -0
- package/src/server/sync/redis/index.ts +7 -3
- package/src/server/sync/redis/scripts.ts +1 -1
- package/src/server/sync/response.ts +21 -0
- package/src/server/sync/sqlite/index.ts +19 -8
- package/src/server/sync/stream.ts +14 -22
- package/src/server/sync/validation.ts +34 -0
- package/src/shared/defer.ts +48 -0
- package/src/shared/error.ts +2 -2
- package/src/shared/page-key.ts +36 -0
- package/src/shared/query-bindings.ts +138 -0
- package/src/shared/route-frame.ts +13 -1
- package/src/shared/route-map.ts +12 -2
- package/src/shared/sync-query.ts +138 -0
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { type Context, Elysia } from "elysia";
|
|
1
|
+
import { type Context, Elysia, ElysiaStatus } from "elysia";
|
|
2
|
+
import { queryTag, serializeQueryHeader } from "../../shared/sync-query.ts";
|
|
2
3
|
import {
|
|
3
4
|
appendPendingInvalidationHeader,
|
|
4
5
|
isSuccessfulMutationResponse,
|
|
@@ -7,16 +8,40 @@ import {
|
|
|
7
8
|
import type { InvalidationInput } from "../auto-invalidate/types.ts";
|
|
8
9
|
import { peekPendingInvalidations } from "../cache/invalidation.ts";
|
|
9
10
|
import { getLogger } from "../context-logger.ts";
|
|
10
|
-
import type {
|
|
11
|
+
import type {
|
|
12
|
+
MutationLease,
|
|
13
|
+
StoredResponse,
|
|
14
|
+
SyncAdapter,
|
|
15
|
+
SyncMutation,
|
|
16
|
+
SyncRuntimeOptions,
|
|
17
|
+
SyncTransaction,
|
|
18
|
+
TransactionalSyncAdapter,
|
|
19
|
+
} from "./adapter.ts";
|
|
20
|
+
import {
|
|
21
|
+
conflictResponse,
|
|
22
|
+
executeAtomicMutation,
|
|
23
|
+
normalizedInvalidations,
|
|
24
|
+
pendingPathInvalidations,
|
|
25
|
+
} from "./atomic.ts";
|
|
26
|
+
import { MutationLeaseLost } from "./execution-error.ts";
|
|
11
27
|
import { createMutationFingerprint } from "./fingerprint.ts";
|
|
28
|
+
import { installMutationHandlers, prepareMutationHandler } from "./mutation-handler.ts";
|
|
29
|
+
import {
|
|
30
|
+
appendQueryInvalidations,
|
|
31
|
+
resolveSyncInvalidations,
|
|
32
|
+
type SyncInvalidationSelector,
|
|
33
|
+
type SyncReadOption,
|
|
34
|
+
} from "./queries.ts";
|
|
12
35
|
import { mergeStoredResponseHeaders, replayResponse, storeResponse } from "./response.ts";
|
|
13
36
|
import { resolveSyncRuntime } from "./runtime.ts";
|
|
37
|
+
import { bindSyncValidation, syncValidationApp } from "./validation.ts";
|
|
14
38
|
|
|
15
39
|
export type SyncRouteOption =
|
|
16
40
|
| false
|
|
17
41
|
| InvalidationInput
|
|
42
|
+
| SyncReadOption
|
|
18
43
|
| {
|
|
19
|
-
invalidate:
|
|
44
|
+
invalidate: SyncInvalidationSelector;
|
|
20
45
|
};
|
|
21
46
|
|
|
22
47
|
/** @deprecated Use SyncRouteOption. */
|
|
@@ -24,7 +49,8 @@ export type SyncInput = Exclude<SyncRouteOption, false>;
|
|
|
24
49
|
|
|
25
50
|
interface RouteSyncMetadata {
|
|
26
51
|
disabled: boolean;
|
|
27
|
-
invalidate?:
|
|
52
|
+
invalidate?: SyncInvalidationSelector;
|
|
53
|
+
read?: SyncReadOption;
|
|
28
54
|
}
|
|
29
55
|
|
|
30
56
|
interface ActiveMutation {
|
|
@@ -43,10 +69,11 @@ interface MutationContext {
|
|
|
43
69
|
type TransportHook<TContext> = (context: TContext) => Promise<void>;
|
|
44
70
|
|
|
45
71
|
type CompletionContext = MutationContext & Parameters<typeof isSuccessfulMutationResponse>[0];
|
|
46
|
-
type PathInvalidation = Extract<SyncInvalidation, { kind: "path" }>;
|
|
47
72
|
|
|
48
73
|
const routeMetadata = new WeakMap<Request, RouteSyncMetadata>();
|
|
49
74
|
const activeMutations = new WeakMap<Request, ActiveMutation>();
|
|
75
|
+
const atomicCalls = new WeakSet<Request>();
|
|
76
|
+
const atomicResponses = new WeakMap<Request, { response: StoredResponse; value: unknown }>();
|
|
50
77
|
|
|
51
78
|
function hideTransportResponse<TContext>(
|
|
52
79
|
hook: (context: TContext) => Promise<Response | undefined>
|
|
@@ -55,10 +82,15 @@ function hideTransportResponse<TContext>(
|
|
|
55
82
|
return hook as TransportHook<TContext>;
|
|
56
83
|
}
|
|
57
84
|
|
|
58
|
-
function invalidationInputFromSync(
|
|
85
|
+
function invalidationInputFromSync(
|
|
86
|
+
input: Exclude<SyncRouteOption, false>
|
|
87
|
+
): SyncInvalidationSelector | undefined {
|
|
59
88
|
if (input && typeof input === "object" && "invalidate" in input) {
|
|
60
89
|
return input.invalidate;
|
|
61
90
|
}
|
|
91
|
+
if ("id" in input) {
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
62
94
|
return input;
|
|
63
95
|
}
|
|
64
96
|
|
|
@@ -87,22 +119,6 @@ function supportsReplayBody(request: Request): boolean {
|
|
|
87
119
|
);
|
|
88
120
|
}
|
|
89
121
|
|
|
90
|
-
function conflictResponse(reason: "in-progress" | "payload-mismatch"): Response {
|
|
91
|
-
const inProgress = reason === "in-progress";
|
|
92
|
-
return Response.json(
|
|
93
|
-
{
|
|
94
|
-
code: inProgress ? "FURIN_MUTATION_IN_PROGRESS" : "FURIN_IDEMPOTENCY_MISMATCH",
|
|
95
|
-
message: inProgress
|
|
96
|
-
? "A mutation with this Idempotency-Key is still running."
|
|
97
|
-
: "The Idempotency-Key was already used with a different request.",
|
|
98
|
-
},
|
|
99
|
-
{
|
|
100
|
-
headers: inProgress ? { "retry-after": "1" } : undefined,
|
|
101
|
-
status: 409,
|
|
102
|
-
}
|
|
103
|
-
);
|
|
104
|
-
}
|
|
105
|
-
|
|
106
122
|
function leaseLostResponse(): Response {
|
|
107
123
|
return Response.json(
|
|
108
124
|
{
|
|
@@ -113,33 +129,50 @@ function leaseLostResponse(): Response {
|
|
|
113
129
|
);
|
|
114
130
|
}
|
|
115
131
|
|
|
116
|
-
function
|
|
117
|
-
if (!input) {
|
|
118
|
-
return [];
|
|
119
|
-
}
|
|
120
|
-
const rules = Array.isArray(input) ? input : [input];
|
|
121
|
-
const invalidations: SyncInvalidation[] = [];
|
|
122
|
-
for (const rule of rules) {
|
|
123
|
-
if ("path" in rule && rule.path) {
|
|
124
|
-
invalidations.push({ kind: "path", path: rule.path, type: rule.type });
|
|
125
|
-
}
|
|
126
|
-
if (rule.tags && rule.tags.length > 0) {
|
|
127
|
-
invalidations.push({ kind: "tags", tags: [...rule.tags] });
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
return invalidations;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
function pendingPathInvalidations(entries: readonly string[]): PathInvalidation[] {
|
|
134
|
-
return entries.map((entry) =>
|
|
135
|
-
entry.endsWith(":layout")
|
|
136
|
-
? { kind: "path" as const, path: entry.slice(0, -":layout".length), type: "layout" }
|
|
137
|
-
: { kind: "path" as const, path: entry, type: "page" }
|
|
138
|
-
);
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
export function furinSync(options: SyncRuntimeOptions) {
|
|
132
|
+
function createSyncPlugin<Adapter extends SyncAdapter>(options: SyncRuntimeOptions<Adapter>) {
|
|
142
133
|
const runtime = resolveSyncRuntime(options);
|
|
134
|
+
const transactional =
|
|
135
|
+
"executeMutation" in options.adapter
|
|
136
|
+
? (options.adapter as Adapter &
|
|
137
|
+
TransactionalSyncAdapter<SyncTransaction<Adapter>, "async" | "sync">)
|
|
138
|
+
: undefined;
|
|
139
|
+
|
|
140
|
+
function mutationFor(ctx: MutationContext & Pick<Context, "set">): SyncMutation<Adapter> {
|
|
141
|
+
const mutation = async (callback: (tx: SyncTransaction<Adapter>) => unknown) => {
|
|
142
|
+
const active = activeMutations.get(ctx.request);
|
|
143
|
+
if (!(transactional && active)) {
|
|
144
|
+
throw new Error(
|
|
145
|
+
"[furin] mutation() requires a transactional sync adapter and an enabled mutation route."
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
if (atomicCalls.has(ctx.request)) {
|
|
149
|
+
throw new Error("[furin] Call mutation() once and return its result from the handler.");
|
|
150
|
+
}
|
|
151
|
+
atomicCalls.add(ctx.request);
|
|
152
|
+
try {
|
|
153
|
+
return await executeAtomicMutation(
|
|
154
|
+
{
|
|
155
|
+
adapter: transactional,
|
|
156
|
+
app: syncValidationApp(ctx as Context),
|
|
157
|
+
context: ctx as Context,
|
|
158
|
+
lease: active.lease,
|
|
159
|
+
invalidate: routeMetadata.get(ctx.request)?.invalidate,
|
|
160
|
+
runtime,
|
|
161
|
+
onCommit: (result) => atomicResponses.set(ctx.request, result),
|
|
162
|
+
},
|
|
163
|
+
callback
|
|
164
|
+
);
|
|
165
|
+
} finally {
|
|
166
|
+
if (atomicResponses.has(ctx.request)) {
|
|
167
|
+
releaseMutation(ctx.request);
|
|
168
|
+
} else {
|
|
169
|
+
await abortMutation(ctx.request).catch(() => undefined);
|
|
170
|
+
}
|
|
171
|
+
atomicCalls.delete(ctx.request);
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
return mutation as SyncMutation<Adapter>;
|
|
175
|
+
}
|
|
143
176
|
|
|
144
177
|
async function beginMutation(ctx: MutationContext): Promise<Response | undefined> {
|
|
145
178
|
if (!isMutationMethod(ctx.request.method) || routeMetadata.get(ctx.request)?.disabled) {
|
|
@@ -191,16 +224,20 @@ export function furinSync(options: SyncRuntimeOptions) {
|
|
|
191
224
|
scheduleRenewal();
|
|
192
225
|
}
|
|
193
226
|
|
|
194
|
-
|
|
227
|
+
function releaseMutation(request: Request): ActiveMutation | undefined {
|
|
195
228
|
const active = activeMutations.get(request);
|
|
196
|
-
if (!active) {
|
|
197
|
-
return;
|
|
198
|
-
}
|
|
199
229
|
activeMutations.delete(request);
|
|
200
|
-
if (active
|
|
230
|
+
if (active?.renewal) {
|
|
201
231
|
clearTimeout(active.renewal);
|
|
202
232
|
}
|
|
203
|
-
|
|
233
|
+
return active;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async function abortMutation(request: Request): Promise<void> {
|
|
237
|
+
const active = releaseMutation(request);
|
|
238
|
+
if (active) {
|
|
239
|
+
await runtime.adapter.abortMutation(active.lease);
|
|
240
|
+
}
|
|
204
241
|
}
|
|
205
242
|
|
|
206
243
|
async function persistMutation(
|
|
@@ -209,7 +246,12 @@ export function furinSync(options: SyncRuntimeOptions) {
|
|
|
209
246
|
): Promise<Response | undefined> {
|
|
210
247
|
const result = await storeResponse(ctx.responseValue, ctx.set);
|
|
211
248
|
const manualPending = peekPendingInvalidations();
|
|
212
|
-
const invalidate =
|
|
249
|
+
const invalidate = resolveSyncInvalidations(
|
|
250
|
+
routeMetadata.get(ctx.request)?.invalidate,
|
|
251
|
+
ctx as Context,
|
|
252
|
+
ctx.responseValue
|
|
253
|
+
);
|
|
254
|
+
appendQueryInvalidations(invalidate, ctx);
|
|
213
255
|
const logger = getLogger();
|
|
214
256
|
if (invalidate) {
|
|
215
257
|
try {
|
|
@@ -245,6 +287,7 @@ export function furinSync(options: SyncRuntimeOptions) {
|
|
|
245
287
|
return leaseLostResponse();
|
|
246
288
|
}
|
|
247
289
|
const notificationAlreadyPublished =
|
|
290
|
+
runtime.adapter.publishesNotifications !== false &&
|
|
248
291
|
runtime.adapter.notificationChannel !== undefined &&
|
|
249
292
|
runtime.adapter.notificationChannel === runtime.notifier.notificationChannel;
|
|
250
293
|
if (completion.cursor !== undefined && !notificationAlreadyPublished) {
|
|
@@ -256,6 +299,19 @@ export function furinSync(options: SyncRuntimeOptions) {
|
|
|
256
299
|
}
|
|
257
300
|
|
|
258
301
|
async function finishMutation(ctx: CompletionContext): Promise<Response | undefined> {
|
|
302
|
+
const atomic = atomicResponses.get(ctx.request);
|
|
303
|
+
atomicResponses.delete(ctx.request);
|
|
304
|
+
atomicCalls.delete(ctx.request);
|
|
305
|
+
if (atomic && ctx.responseValue === atomic.value) {
|
|
306
|
+
if (atomic.value instanceof Response) {
|
|
307
|
+
return atomic.value;
|
|
308
|
+
}
|
|
309
|
+
if (atomic.value instanceof ElysiaStatus) {
|
|
310
|
+
ctx.set.status = atomic.value.status;
|
|
311
|
+
Object.assign(ctx.set.headers, atomic.value.headers);
|
|
312
|
+
}
|
|
313
|
+
return replayResponse(atomic.response);
|
|
314
|
+
}
|
|
259
315
|
const active = activeMutations.get(ctx.request);
|
|
260
316
|
if (!active) {
|
|
261
317
|
return;
|
|
@@ -277,13 +333,59 @@ export function furinSync(options: SyncRuntimeOptions) {
|
|
|
277
333
|
}
|
|
278
334
|
}
|
|
279
335
|
|
|
280
|
-
const beginMutationHook = hideTransportResponse(beginMutation);
|
|
281
336
|
const finishMutationHook = hideTransportResponse(finishMutation);
|
|
282
337
|
|
|
283
|
-
|
|
284
|
-
.
|
|
338
|
+
const plugin = new Elysia({ name: "furin-sync" })
|
|
339
|
+
.derive("global", (ctx) => ({ mutation: mutationFor(ctx) }))
|
|
340
|
+
.beforeHandle("global", (context) => {
|
|
341
|
+
if (
|
|
342
|
+
isMutationMethod(context.request.method) &&
|
|
343
|
+
!routeMetadata.get(context.request)?.disabled
|
|
344
|
+
) {
|
|
345
|
+
prepareMutationHandler(context, () => beginMutation(context));
|
|
346
|
+
}
|
|
347
|
+
})
|
|
285
348
|
.afterHandle("global", finishMutationHook)
|
|
286
|
-
.
|
|
349
|
+
.afterHandle("global", async (ctx) => {
|
|
350
|
+
const read = routeMetadata.get(ctx.request)?.read;
|
|
351
|
+
if (
|
|
352
|
+
ctx.request.method !== "GET" ||
|
|
353
|
+
!read ||
|
|
354
|
+
!isSuccessfulMutationResponse({
|
|
355
|
+
set: ctx.set,
|
|
356
|
+
responseValue:
|
|
357
|
+
ctx.responseValue instanceof Response || ctx.responseValue instanceof ElysiaStatus
|
|
358
|
+
? ctx.responseValue
|
|
359
|
+
: undefined,
|
|
360
|
+
})
|
|
361
|
+
) {
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
const principal = await options.principal(ctx as Context);
|
|
365
|
+
if (principal.length === 0) {
|
|
366
|
+
throw new Error("[furin] Sync principal must not be empty.");
|
|
367
|
+
}
|
|
368
|
+
const identity = {
|
|
369
|
+
id: read.id,
|
|
370
|
+
scope: typeof read.scope === "function" ? read.scope(ctx as Context) : (read.scope ?? {}),
|
|
371
|
+
session: new Bun.CryptoHasher("sha256").update(principal).digest("hex"),
|
|
372
|
+
};
|
|
373
|
+
queryTag(identity);
|
|
374
|
+
ctx.set.headers["x-furin-query"] = serializeQueryHeader(identity);
|
|
375
|
+
})
|
|
376
|
+
.error(
|
|
377
|
+
"global",
|
|
378
|
+
MutationLeaseLost,
|
|
379
|
+
hideTransportResponse(() => Promise.resolve(leaseLostResponse()))
|
|
380
|
+
)
|
|
381
|
+
.error(
|
|
382
|
+
"global",
|
|
383
|
+
hideTransportResponse(async ({ request }: { request: Request }) => {
|
|
384
|
+
atomicResponses.delete(request);
|
|
385
|
+
atomicCalls.delete(request);
|
|
386
|
+
await abortMutation(request);
|
|
387
|
+
})
|
|
388
|
+
)
|
|
287
389
|
.macro({
|
|
288
390
|
sync(input: SyncRouteOption) {
|
|
289
391
|
return {
|
|
@@ -292,10 +394,25 @@ export function furinSync(options: SyncRuntimeOptions) {
|
|
|
292
394
|
request,
|
|
293
395
|
input === false
|
|
294
396
|
? { disabled: true }
|
|
295
|
-
: {
|
|
397
|
+
: {
|
|
398
|
+
disabled: false,
|
|
399
|
+
invalidate: invalidationInputFromSync(input),
|
|
400
|
+
read: "id" in input ? input : undefined,
|
|
401
|
+
}
|
|
296
402
|
);
|
|
297
403
|
},
|
|
298
404
|
};
|
|
299
405
|
},
|
|
300
406
|
});
|
|
407
|
+
return plugin;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
export function furinSync<Adapter extends SyncAdapter>(options: SyncRuntimeOptions<Adapter>) {
|
|
411
|
+
return (app: Elysia) => {
|
|
412
|
+
installMutationHandlers(app);
|
|
413
|
+
if ("executeMutation" in options.adapter) {
|
|
414
|
+
bindSyncValidation(app);
|
|
415
|
+
}
|
|
416
|
+
return app.use(createSyncPlugin(options));
|
|
417
|
+
};
|
|
301
418
|
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { AtomicMutationResult, AtomicMutationValue, MutationLease } from "../adapter.ts";
|
|
2
|
+
import { MutationLeaseLost } from "../execution-error.ts";
|
|
3
|
+
import type { PostgresSyncAdapter } from "./index.ts";
|
|
4
|
+
|
|
5
|
+
export async function executePostgresMutation<T, Tx>(
|
|
6
|
+
journal: PostgresSyncAdapter,
|
|
7
|
+
lease: MutationLease,
|
|
8
|
+
tx: Tx,
|
|
9
|
+
callback: (tx: Tx) => AtomicMutationValue<T> | Promise<AtomicMutationValue<T>>
|
|
10
|
+
): Promise<AtomicMutationResult<T>> {
|
|
11
|
+
if (!(await journal.lockMutation(lease))) {
|
|
12
|
+
throw new MutationLeaseLost("[furin] Mutation lease lost; the transaction was rolled back.");
|
|
13
|
+
}
|
|
14
|
+
const result = await callback(tx);
|
|
15
|
+
const completion = await journal.completeLockedMutation({ ...result, lease });
|
|
16
|
+
if (completion.kind === "lost") {
|
|
17
|
+
throw new MutationLeaseLost("[furin] Mutation lease lost; the transaction was rolled back.");
|
|
18
|
+
}
|
|
19
|
+
return { ...result, cursor: completion.cursor, kind: "committed" };
|
|
20
|
+
}
|
|
@@ -14,6 +14,7 @@ import type {
|
|
|
14
14
|
SyncNotifier,
|
|
15
15
|
SyncSubscription,
|
|
16
16
|
} from "../adapter.ts";
|
|
17
|
+
import type { SyncSql, SyncSqlQuery } from "./sql.ts";
|
|
17
18
|
|
|
18
19
|
const CHANGE_RETENTION = 1000;
|
|
19
20
|
const LEASE_MS = 30_000;
|
|
@@ -53,7 +54,7 @@ function notificationChannel(namespace: string): string {
|
|
|
53
54
|
return `furin_sync_${digest.slice(0, 52)}`;
|
|
54
55
|
}
|
|
55
56
|
|
|
56
|
-
async function readCurrentCursor(sql:
|
|
57
|
+
async function readCurrentCursor(sql: SyncSqlQuery, namespace: string): Promise<string> {
|
|
57
58
|
const rows = await sql<Pick<CursorRow, "current_cursor">[]>`
|
|
58
59
|
SELECT current_cursor FROM furin_sync.streams WHERE namespace = ${namespace}
|
|
59
60
|
`;
|
|
@@ -79,15 +80,17 @@ function storedResponse(row: MutationRow): StoredResponse {
|
|
|
79
80
|
|
|
80
81
|
export class PostgresSyncAdapter implements SyncAdapter {
|
|
81
82
|
readonly notificationChannel: string;
|
|
83
|
+
readonly publishesNotifications: boolean;
|
|
82
84
|
readonly scope = "distributed" as const;
|
|
83
85
|
private readonly namespace: string;
|
|
84
|
-
private readonly sql:
|
|
86
|
+
private readonly sql: SyncSql;
|
|
85
87
|
|
|
86
|
-
constructor(options:
|
|
88
|
+
constructor(options: { namespace: string; sql: SyncSql; publishNotifications?: false }) {
|
|
87
89
|
if (options.namespace.length === 0) {
|
|
88
90
|
throw new Error("[furin-sync-postgres] namespace must not be empty.");
|
|
89
91
|
}
|
|
90
92
|
this.notificationChannel = notificationChannel(options.namespace);
|
|
93
|
+
this.publishesNotifications = options.publishNotifications !== false;
|
|
91
94
|
this.namespace = options.namespace;
|
|
92
95
|
this.sql = options.sql;
|
|
93
96
|
}
|
|
@@ -95,6 +98,12 @@ export class PostgresSyncAdapter implements SyncAdapter {
|
|
|
95
98
|
beginMutation(input: BeginMutationInput): Promise<BeginMutationResult> {
|
|
96
99
|
return this.sql.begin(async (tx) => {
|
|
97
100
|
const key = mutationKey(input);
|
|
101
|
+
const [lock] = await tx<{ acquired: boolean }[]>`
|
|
102
|
+
SELECT pg_try_advisory_xact_lock(hashtextextended(${`${this.namespace}:${key}`}, 0)) AS acquired
|
|
103
|
+
`;
|
|
104
|
+
if (!lock?.acquired) {
|
|
105
|
+
return { kind: "conflict", reason: "in-progress" } as const;
|
|
106
|
+
}
|
|
98
107
|
await tx`
|
|
99
108
|
DELETE FROM furin_sync.mutations
|
|
100
109
|
WHERE ctid IN (
|
|
@@ -107,9 +116,9 @@ export class PostgresSyncAdapter implements SyncAdapter {
|
|
|
107
116
|
AND expires_at <= clock_timestamp()
|
|
108
117
|
)
|
|
109
118
|
LIMIT 100
|
|
119
|
+
FOR UPDATE SKIP LOCKED
|
|
110
120
|
)
|
|
111
121
|
`;
|
|
112
|
-
await tx`SELECT pg_advisory_xact_lock(hashtextextended(${`${this.namespace}:${key}`}, 0))`;
|
|
113
122
|
const rows = await tx<MutationRow[]>`
|
|
114
123
|
SELECT mutation_id, fingerprint, state, response_status, response_headers,
|
|
115
124
|
response_body,
|
|
@@ -177,19 +186,21 @@ export class PostgresSyncAdapter implements SyncAdapter {
|
|
|
177
186
|
}
|
|
178
187
|
|
|
179
188
|
completeMutation(input: CompleteMutationInput): Promise<CompleteMutationResult> {
|
|
189
|
+
return this.completeMutationInTransaction(input, true);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Only used on the native transaction that already holds lockMutation's row lock. */
|
|
193
|
+
completeLockedMutation(input: CompleteMutationInput): Promise<CompleteMutationResult> {
|
|
194
|
+
return this.completeMutationInTransaction(input, false);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
private completeMutationInTransaction(
|
|
198
|
+
input: CompleteMutationInput,
|
|
199
|
+
checkExpiration: boolean
|
|
200
|
+
): Promise<CompleteMutationResult> {
|
|
180
201
|
return this.sql.begin(async (tx) => {
|
|
181
202
|
const key = mutationKey(input.lease);
|
|
182
|
-
|
|
183
|
-
const active = await tx<{ mutation_id: string }[]>`
|
|
184
|
-
SELECT mutation_id FROM furin_sync.mutations
|
|
185
|
-
WHERE namespace = ${this.namespace}
|
|
186
|
-
AND mutation_key = ${key}
|
|
187
|
-
AND mutation_id = ${input.lease.id}
|
|
188
|
-
AND state = 'in-progress'
|
|
189
|
-
AND lease_expires_at > clock_timestamp()
|
|
190
|
-
FOR UPDATE
|
|
191
|
-
`;
|
|
192
|
-
if (active.length === 0) {
|
|
203
|
+
if (!(await this.lockMutationInTransaction(tx, input.lease, checkExpiration))) {
|
|
193
204
|
return { kind: "lost" } as const;
|
|
194
205
|
}
|
|
195
206
|
|
|
@@ -240,13 +251,36 @@ export class PostgresSyncAdapter implements SyncAdapter {
|
|
|
240
251
|
AND mutation_key = ${key}
|
|
241
252
|
AND mutation_id = ${input.lease.id}
|
|
242
253
|
`;
|
|
243
|
-
if (cursor !== undefined) {
|
|
254
|
+
if (cursor !== undefined && this.publishesNotifications) {
|
|
244
255
|
await tx.notify(this.notificationChannel, cursor);
|
|
245
256
|
}
|
|
246
257
|
return { cursor, kind: "committed" } as const;
|
|
247
258
|
});
|
|
248
259
|
}
|
|
249
260
|
|
|
261
|
+
lockMutation(lease: MutationLease): Promise<boolean> {
|
|
262
|
+
return this.sql.begin((tx) => this.lockMutationInTransaction(tx, lease, true));
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
private async lockMutationInTransaction(
|
|
266
|
+
tx: SyncSqlQuery,
|
|
267
|
+
lease: MutationLease,
|
|
268
|
+
checkExpiration: boolean
|
|
269
|
+
): Promise<boolean> {
|
|
270
|
+
const key = mutationKey(lease);
|
|
271
|
+
await tx`SELECT pg_advisory_xact_lock(hashtextextended(${`${this.namespace}:${key}`}, 0))::text`;
|
|
272
|
+
const active = await tx<{ mutation_id: string }[]>`
|
|
273
|
+
SELECT mutation_id FROM furin_sync.mutations
|
|
274
|
+
WHERE namespace = ${this.namespace}
|
|
275
|
+
AND mutation_key = ${key}
|
|
276
|
+
AND mutation_id = ${lease.id}
|
|
277
|
+
AND state = 'in-progress'
|
|
278
|
+
AND (NOT ${checkExpiration} OR lease_expires_at > clock_timestamp())
|
|
279
|
+
FOR UPDATE
|
|
280
|
+
`;
|
|
281
|
+
return active.length > 0;
|
|
282
|
+
}
|
|
283
|
+
|
|
250
284
|
async abortMutation(lease: MutationLease): Promise<void> {
|
|
251
285
|
await this.sql`
|
|
252
286
|
DELETE FROM furin_sync.mutations
|
|
@@ -287,6 +321,8 @@ export class PostgresSyncAdapter implements SyncAdapter {
|
|
|
287
321
|
ORDER BY cursor ASC
|
|
288
322
|
LIMIT ${input.limit + 1}
|
|
289
323
|
`;
|
|
324
|
+
// Re-read after the changes query to detect retention pruning during that query.
|
|
325
|
+
// react-doctor-disable-next-line react-doctor/server-sequential-independent-await
|
|
290
326
|
const latestCursorRows = await this.sql<CursorRow[]>`
|
|
291
327
|
SELECT current_cursor, oldest_cursor
|
|
292
328
|
FROM furin_sync.streams WHERE namespace = ${this.namespace}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export interface SyncSqlQuery {
|
|
2
|
+
notify: (channel: string, cursor: string) => Promise<void>;
|
|
3
|
+
<Rows>(strings: TemplateStringsArray, ...values: unknown[]): Promise<Rows>;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export interface SyncSql extends SyncSqlQuery {
|
|
7
|
+
begin: <T>(callback: (tx: SyncSqlQuery) => Promise<T>) => Promise<T>;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function transactionSql(
|
|
11
|
+
query: <Rows>(strings: TemplateStringsArray, values: unknown[]) => Promise<Rows>
|
|
12
|
+
): SyncSql {
|
|
13
|
+
const sql = (<Rows>(strings: TemplateStringsArray, ...values: unknown[]) =>
|
|
14
|
+
query<Rows>(strings, values)) as SyncSql;
|
|
15
|
+
sql.begin = (callback) => callback(sql);
|
|
16
|
+
sql.notify = async (channel, cursor) => {
|
|
17
|
+
await sql`SELECT pg_notify(${channel}, ${cursor})::text`;
|
|
18
|
+
};
|
|
19
|
+
return sql;
|
|
20
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AtomicMutationResult,
|
|
3
|
+
AtomicMutationValue,
|
|
4
|
+
MutationLease,
|
|
5
|
+
TransactionalSyncAdapter,
|
|
6
|
+
} from "../adapter.ts";
|
|
7
|
+
import { executePostgresMutation } from "../postgres/execute.ts";
|
|
8
|
+
import { PostgresSyncAdapter } from "../postgres/index.ts";
|
|
9
|
+
import { transactionSql } from "../postgres/sql.ts";
|
|
10
|
+
|
|
11
|
+
interface PrismaQuery {
|
|
12
|
+
$queryRawUnsafe: <Rows>(query: string, ...values: unknown[]) => Promise<Rows>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
interface PrismaClient<Tx extends PrismaQuery> extends PrismaQuery {
|
|
16
|
+
$transaction: <T>(callback: (tx: Tx) => Promise<T>) => Promise<T>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function prismaSql(client: PrismaQuery) {
|
|
20
|
+
return transactionSql(<Rows>(strings: TemplateStringsArray, values: unknown[]) => {
|
|
21
|
+
const query = strings.reduce(
|
|
22
|
+
(text, part, index) => text + (index === 0 ? "" : `$${index}`) + part,
|
|
23
|
+
""
|
|
24
|
+
);
|
|
25
|
+
return client.$queryRawUnsafe<Rows>(query, ...values);
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export class PrismaSyncAdapter<Tx extends PrismaQuery>
|
|
30
|
+
extends PostgresSyncAdapter
|
|
31
|
+
implements TransactionalSyncAdapter<Tx, "async">
|
|
32
|
+
{
|
|
33
|
+
readonly transactionMode = "async" as const;
|
|
34
|
+
private readonly client: PrismaClient<Tx>;
|
|
35
|
+
private readonly syncNamespace: string;
|
|
36
|
+
|
|
37
|
+
constructor(options: { client: PrismaClient<Tx>; namespace: string }) {
|
|
38
|
+
const sql = prismaSql(options.client);
|
|
39
|
+
sql.begin = (callback) => options.client.$transaction((tx) => callback(prismaSql(tx)));
|
|
40
|
+
super({ namespace: options.namespace, sql, publishNotifications: false });
|
|
41
|
+
this.client = options.client;
|
|
42
|
+
this.syncNamespace = options.namespace;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
executeMutation<T>(
|
|
46
|
+
lease: MutationLease,
|
|
47
|
+
callback: (tx: Tx) => AtomicMutationValue<T> | Promise<AtomicMutationValue<T>>
|
|
48
|
+
): Promise<AtomicMutationResult<T>> {
|
|
49
|
+
return this.client.$transaction((tx) =>
|
|
50
|
+
executePostgresMutation(
|
|
51
|
+
new PostgresSyncAdapter({
|
|
52
|
+
namespace: this.syncNamespace,
|
|
53
|
+
sql: prismaSql(tx),
|
|
54
|
+
publishNotifications: false,
|
|
55
|
+
}),
|
|
56
|
+
lease,
|
|
57
|
+
tx,
|
|
58
|
+
callback
|
|
59
|
+
)
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Prisma 7, PostgreSQL. The sync SQL migration must run on the same database. */
|
|
65
|
+
export function prismaSyncAdapter<Tx extends PrismaQuery>(options: {
|
|
66
|
+
client: PrismaClient<Tx>;
|
|
67
|
+
namespace: string;
|
|
68
|
+
}): PrismaSyncAdapter<Tx> {
|
|
69
|
+
return new PrismaSyncAdapter(options);
|
|
70
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { Context } from "elysia";
|
|
2
|
+
import {
|
|
3
|
+
type QueryIdentity,
|
|
4
|
+
type QueryScope,
|
|
5
|
+
queryFromTag,
|
|
6
|
+
queryTag,
|
|
7
|
+
type SyncQueryIdentity,
|
|
8
|
+
serializeQueryHeader,
|
|
9
|
+
} from "../../shared/sync-query.ts";
|
|
10
|
+
import type {
|
|
11
|
+
InvalidationInput,
|
|
12
|
+
InvalidationRule,
|
|
13
|
+
SyncInvalidationInput,
|
|
14
|
+
} from "../auto-invalidate/types.ts";
|
|
15
|
+
|
|
16
|
+
export type SyncInvalidationSelector =
|
|
17
|
+
| SyncInvalidationInput
|
|
18
|
+
| ((context: Context & { responseValue: unknown }) => SyncInvalidationInput);
|
|
19
|
+
|
|
20
|
+
interface UnregisteredRead {
|
|
21
|
+
id: string;
|
|
22
|
+
scope?: QueryScope | ((context: Context) => QueryScope);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
type RegisteredRead<Identity> = Identity extends SyncQueryIdentity
|
|
26
|
+
? { id: Identity["id"] } & (string extends keyof Identity["scope"]
|
|
27
|
+
? { scope?: Identity["scope"] | ((context: Context) => Identity["scope"]) }
|
|
28
|
+
: { scope: Identity["scope"] | ((context: Context) => Identity["scope"]) })
|
|
29
|
+
: never;
|
|
30
|
+
|
|
31
|
+
export type SyncReadOption = string extends SyncQueryIdentity["id"]
|
|
32
|
+
? UnregisteredRead
|
|
33
|
+
: RegisteredRead<SyncQueryIdentity>;
|
|
34
|
+
|
|
35
|
+
export function resolveSyncInvalidations(
|
|
36
|
+
input: SyncInvalidationSelector | undefined,
|
|
37
|
+
context: Context,
|
|
38
|
+
value: unknown
|
|
39
|
+
): InvalidationInput | undefined {
|
|
40
|
+
if (input === undefined) {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const selected =
|
|
44
|
+
typeof input === "function"
|
|
45
|
+
? input(
|
|
46
|
+
Object.assign(Object.create(Object.getPrototypeOf(context)), context, {
|
|
47
|
+
responseValue: value,
|
|
48
|
+
})
|
|
49
|
+
)
|
|
50
|
+
: input;
|
|
51
|
+
const rules = Array.isArray(selected) ? selected : [selected];
|
|
52
|
+
return rules.map((rule): InvalidationRule => ("id" in rule ? { tags: [queryTag(rule)] } : rule));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function appendQueryInvalidations(
|
|
56
|
+
input: InvalidationInput | undefined,
|
|
57
|
+
context: Pick<Context, "set">
|
|
58
|
+
): void {
|
|
59
|
+
if (input === undefined) {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
const queries: QueryIdentity[] = [];
|
|
63
|
+
for (const rule of Array.isArray(input) ? input : [input]) {
|
|
64
|
+
for (const tag of rule.tags ?? []) {
|
|
65
|
+
const identity = queryFromTag(tag);
|
|
66
|
+
if (identity) {
|
|
67
|
+
queries.push(identity);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (queries.length > 0) {
|
|
72
|
+
context.set.headers["x-furin-queries"] = serializeQueryHeader(queries);
|
|
73
|
+
context.set.headers["x-furin-sync"] = "1";
|
|
74
|
+
}
|
|
75
|
+
}
|