@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
|
@@ -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
|
-
|
|
5
|
-
|
|
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",
|
|
10
|
-
|
|
11
|
-
|
|
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) =>
|
|
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<{}, {}, {}>>,
|
|
39
|
-
|
|
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,
|
|
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:
|
|
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>;
|
|
@@ -33,6 +33,7 @@ function storedResponse(row) {
|
|
|
33
33
|
|
|
34
34
|
class PostgresSyncAdapter {
|
|
35
35
|
notificationChannel;
|
|
36
|
+
publishesNotifications;
|
|
36
37
|
scope = "distributed";
|
|
37
38
|
namespace;
|
|
38
39
|
sql;
|
|
@@ -41,12 +42,19 @@ class PostgresSyncAdapter {
|
|
|
41
42
|
throw new Error("[furin-sync-postgres] namespace must not be empty.");
|
|
42
43
|
}
|
|
43
44
|
this.notificationChannel = notificationChannel(options.namespace);
|
|
45
|
+
this.publishesNotifications = options.publishNotifications !== false;
|
|
44
46
|
this.namespace = options.namespace;
|
|
45
47
|
this.sql = options.sql;
|
|
46
48
|
}
|
|
47
49
|
beginMutation(input) {
|
|
48
50
|
return this.sql.begin(async (tx) => {
|
|
49
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
|
+
}
|
|
50
58
|
await tx`
|
|
51
59
|
DELETE FROM furin_sync.mutations
|
|
52
60
|
WHERE ctid IN (
|
|
@@ -59,9 +67,9 @@ class PostgresSyncAdapter {
|
|
|
59
67
|
AND expires_at <= clock_timestamp()
|
|
60
68
|
)
|
|
61
69
|
LIMIT 100
|
|
70
|
+
FOR UPDATE SKIP LOCKED
|
|
62
71
|
)
|
|
63
72
|
`;
|
|
64
|
-
await tx`SELECT pg_advisory_xact_lock(hashtextextended(${`${this.namespace}:${key}`}, 0))`;
|
|
65
73
|
const rows = await tx`
|
|
66
74
|
SELECT mutation_id, fingerprint, state, response_status, response_headers,
|
|
67
75
|
response_body,
|
|
@@ -126,19 +134,15 @@ class PostgresSyncAdapter {
|
|
|
126
134
|
return rows.length === 1 ? "renewed" : "lost";
|
|
127
135
|
}
|
|
128
136
|
completeMutation(input) {
|
|
137
|
+
return this.completeMutationInTransaction(input, true);
|
|
138
|
+
}
|
|
139
|
+
completeLockedMutation(input) {
|
|
140
|
+
return this.completeMutationInTransaction(input, false);
|
|
141
|
+
}
|
|
142
|
+
completeMutationInTransaction(input, checkExpiration) {
|
|
129
143
|
return this.sql.begin(async (tx) => {
|
|
130
144
|
const key = mutationKey(input.lease);
|
|
131
|
-
await tx
|
|
132
|
-
const active = await tx`
|
|
133
|
-
SELECT mutation_id FROM furin_sync.mutations
|
|
134
|
-
WHERE namespace = ${this.namespace}
|
|
135
|
-
AND mutation_key = ${key}
|
|
136
|
-
AND mutation_id = ${input.lease.id}
|
|
137
|
-
AND state = 'in-progress'
|
|
138
|
-
AND lease_expires_at > clock_timestamp()
|
|
139
|
-
FOR UPDATE
|
|
140
|
-
`;
|
|
141
|
-
if (active.length === 0) {
|
|
145
|
+
if (!await this.lockMutationInTransaction(tx, input.lease, checkExpiration)) {
|
|
142
146
|
return { kind: "lost" };
|
|
143
147
|
}
|
|
144
148
|
let cursor;
|
|
@@ -187,12 +191,29 @@ class PostgresSyncAdapter {
|
|
|
187
191
|
AND mutation_key = ${key}
|
|
188
192
|
AND mutation_id = ${input.lease.id}
|
|
189
193
|
`;
|
|
190
|
-
if (cursor !== undefined) {
|
|
194
|
+
if (cursor !== undefined && this.publishesNotifications) {
|
|
191
195
|
await tx.notify(this.notificationChannel, cursor);
|
|
192
196
|
}
|
|
193
197
|
return { cursor, kind: "committed" };
|
|
194
198
|
});
|
|
195
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
|
+
}
|
|
196
217
|
async abortMutation(lease) {
|
|
197
218
|
await this.sql`
|
|
198
219
|
DELETE FROM furin_sync.mutations
|
|
@@ -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 =
|
|
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
|
|
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
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export declare const BEGIN_MUTATION_SCRIPT = "\nlocal raw = redis.call('GET', KEYS[1])\nlocal now_parts = redis.call('TIME')\nlocal now = tonumber(now_parts[1]) * 1000 + math.floor(tonumber(now_parts[2]) / 1000)\nif raw then\n local value = cjson.decode(raw)\n if value.fingerprint ~= ARGV[1] then\n return {'conflict', 'payload-mismatch'}\n end\n if value.state == 'succeeded' then\n return {'replay', raw}\n end\n if value.leaseUntil > now then\n return {'conflict', 'in-progress'}\n end\nend\nlocal value = {\n fingerprint = ARGV[1],\n id = ARGV[2],\n leaseUntil = now + tonumber(ARGV[3]),\n state = 'in-progress'\n}\nredis.call('SET', KEYS[1], cjson.encode(value), 'PX', ARGV[4])\nreturn {'execute', ARGV[2]}\n";
|
|
2
2
|
export declare const RENEW_MUTATION_SCRIPT = "\nlocal raw = redis.call('GET', KEYS[1])\nif not raw then return 'lost' end\nlocal value = cjson.decode(raw)\nlocal now_parts = redis.call('TIME')\nlocal now = tonumber(now_parts[1]) * 1000 + math.floor(tonumber(now_parts[2]) / 1000)\nif value.state ~= 'in-progress' or value.id ~= ARGV[1] or value.leaseUntil <= now then\n return 'lost'\nend\nvalue.leaseUntil = now + tonumber(ARGV[2])\nredis.call('SET', KEYS[1], cjson.encode(value), 'PX', ARGV[3])\nreturn 'renewed'\n";
|
|
3
|
-
export declare const COMPLETE_MUTATION_SCRIPT = "\nlocal raw = redis.call('GET', KEYS[1])\nif not raw then return {'lost'} end\nlocal value = cjson.decode(raw)\nlocal now_parts = redis.call('TIME')\nlocal now = tonumber(now_parts[1]) * 1000 + math.floor(tonumber(now_parts[2]) / 1000)\nif value.state ~= 'in-progress' or value.id ~= ARGV[1] or value.leaseUntil <= now then\n return {'lost'}\nend\nvalue.state = 'succeeded'\nvalue.response =
|
|
3
|
+
export declare const COMPLETE_MUTATION_SCRIPT = "\nlocal raw = redis.call('GET', KEYS[1])\nif not raw then return {'lost'} end\nlocal value = cjson.decode(raw)\nlocal now_parts = redis.call('TIME')\nlocal now = tonumber(now_parts[1]) * 1000 + math.floor(tonumber(now_parts[2]) / 1000)\nif value.state ~= 'in-progress' or value.id ~= ARGV[1] or value.leaseUntil <= now then\n return {'lost'}\nend\nvalue.state = 'succeeded'\nvalue.response = ARGV[2]\nvalue.leaseUntil = nil\nlocal cursor = ''\nif ARGV[3] ~= '[]' then\n local length = redis.call('XLEN', KEYS[2])\n if length >= tonumber(ARGV[5]) then\n local oldest = redis.call('XRANGE', KEYS[2], '-', '+', 'COUNT', 1)\n if oldest[1] then redis.call('SET', KEYS[3], oldest[1][1]) end\n end\n cursor = redis.call('XADD', KEYS[2], 'MAXLEN', '=', ARGV[5], '*', 'data', ARGV[3])\nend\nredis.call('SET', KEYS[1], cjson.encode(value), 'PX', ARGV[4])\nreturn {'committed', cursor}\n";
|
|
4
4
|
export declare const ABORT_MUTATION_SCRIPT = "\nlocal raw = redis.call('GET', KEYS[1])\nif not raw then return 0 end\nlocal value = cjson.decode(raw)\nif value.state == 'in-progress' and value.id == ARGV[1] then\n return redis.call('DEL', KEYS[1])\nend\nreturn 0\n";
|
|
@@ -10,4 +10,5 @@ export type StoreResponseResult = {
|
|
|
10
10
|
};
|
|
11
11
|
export declare function mergeStoredResponseHeaders(storedResponse: StoredResponse, headers: Context["set"]["headers"]): StoredResponse;
|
|
12
12
|
export declare function storeResponse(responseValue: unknown, set: Context["set"]): Promise<StoreResponseResult>;
|
|
13
|
+
export declare function storeResponseSync(responseValue: unknown, set: Context["set"]): StoreResponseResult;
|
|
13
14
|
export declare function replayResponse(stored: StoredResponse): Response;
|