@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
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/server/sync/redis/scripts.ts
|
|
3
|
+
var BEGIN_MUTATION_SCRIPT = `
|
|
4
|
+
local raw = redis.call('GET', KEYS[1])
|
|
5
|
+
local now_parts = redis.call('TIME')
|
|
6
|
+
local now = tonumber(now_parts[1]) * 1000 + math.floor(tonumber(now_parts[2]) / 1000)
|
|
7
|
+
if raw then
|
|
8
|
+
local value = cjson.decode(raw)
|
|
9
|
+
if value.fingerprint ~= ARGV[1] then
|
|
10
|
+
return {'conflict', 'payload-mismatch'}
|
|
11
|
+
end
|
|
12
|
+
if value.state == 'succeeded' then
|
|
13
|
+
return {'replay', raw}
|
|
14
|
+
end
|
|
15
|
+
if value.leaseUntil > now then
|
|
16
|
+
return {'conflict', 'in-progress'}
|
|
17
|
+
end
|
|
18
|
+
end
|
|
19
|
+
local value = {
|
|
20
|
+
fingerprint = ARGV[1],
|
|
21
|
+
id = ARGV[2],
|
|
22
|
+
leaseUntil = now + tonumber(ARGV[3]),
|
|
23
|
+
state = 'in-progress'
|
|
24
|
+
}
|
|
25
|
+
redis.call('SET', KEYS[1], cjson.encode(value), 'PX', ARGV[4])
|
|
26
|
+
return {'execute', ARGV[2]}
|
|
27
|
+
`;
|
|
28
|
+
var RENEW_MUTATION_SCRIPT = `
|
|
29
|
+
local raw = redis.call('GET', KEYS[1])
|
|
30
|
+
if not raw then return 'lost' end
|
|
31
|
+
local value = cjson.decode(raw)
|
|
32
|
+
local now_parts = redis.call('TIME')
|
|
33
|
+
local now = tonumber(now_parts[1]) * 1000 + math.floor(tonumber(now_parts[2]) / 1000)
|
|
34
|
+
if value.state ~= 'in-progress' or value.id ~= ARGV[1] or value.leaseUntil <= now then
|
|
35
|
+
return 'lost'
|
|
36
|
+
end
|
|
37
|
+
value.leaseUntil = now + tonumber(ARGV[2])
|
|
38
|
+
redis.call('SET', KEYS[1], cjson.encode(value), 'PX', ARGV[3])
|
|
39
|
+
return 'renewed'
|
|
40
|
+
`;
|
|
41
|
+
var COMPLETE_MUTATION_SCRIPT = `
|
|
42
|
+
local raw = redis.call('GET', KEYS[1])
|
|
43
|
+
if not raw then return {'lost'} end
|
|
44
|
+
local value = cjson.decode(raw)
|
|
45
|
+
local now_parts = redis.call('TIME')
|
|
46
|
+
local now = tonumber(now_parts[1]) * 1000 + math.floor(tonumber(now_parts[2]) / 1000)
|
|
47
|
+
if value.state ~= 'in-progress' or value.id ~= ARGV[1] or value.leaseUntil <= now then
|
|
48
|
+
return {'lost'}
|
|
49
|
+
end
|
|
50
|
+
value.state = 'succeeded'
|
|
51
|
+
value.response = cjson.decode(ARGV[2])
|
|
52
|
+
value.leaseUntil = nil
|
|
53
|
+
local cursor = ''
|
|
54
|
+
if ARGV[3] ~= '[]' then
|
|
55
|
+
local length = redis.call('XLEN', KEYS[2])
|
|
56
|
+
if length >= tonumber(ARGV[5]) then
|
|
57
|
+
local oldest = redis.call('XRANGE', KEYS[2], '-', '+', 'COUNT', 1)
|
|
58
|
+
if oldest[1] then redis.call('SET', KEYS[3], oldest[1][1]) end
|
|
59
|
+
end
|
|
60
|
+
cursor = redis.call('XADD', KEYS[2], 'MAXLEN', '=', ARGV[5], '*', 'data', ARGV[3])
|
|
61
|
+
end
|
|
62
|
+
redis.call('SET', KEYS[1], cjson.encode(value), 'PX', ARGV[4])
|
|
63
|
+
return {'committed', cursor}
|
|
64
|
+
`;
|
|
65
|
+
var ABORT_MUTATION_SCRIPT = `
|
|
66
|
+
local raw = redis.call('GET', KEYS[1])
|
|
67
|
+
if not raw then return 0 end
|
|
68
|
+
local value = cjson.decode(raw)
|
|
69
|
+
if value.state == 'in-progress' and value.id == ARGV[1] then
|
|
70
|
+
return redis.call('DEL', KEYS[1])
|
|
71
|
+
end
|
|
72
|
+
return 0
|
|
73
|
+
`;
|
|
74
|
+
|
|
75
|
+
// src/server/sync/redis/index.ts
|
|
76
|
+
var CHANGE_RETENTION = 1000;
|
|
77
|
+
var LEASE_MS = 30000;
|
|
78
|
+
var MUTATION_TTL_MS = 24 * 60 * 60 * 1000;
|
|
79
|
+
var REDIS_STREAM_CURSOR_PATTERN = /^\d+-\d+$/;
|
|
80
|
+
function assertNamespace(namespace) {
|
|
81
|
+
if (namespace.length === 0) {
|
|
82
|
+
throw new Error("[furin-sync-redis] namespace must not be empty.");
|
|
83
|
+
}
|
|
84
|
+
if (!namespace.isWellFormed()) {
|
|
85
|
+
throw new Error("[furin-sync-redis] namespace must contain valid Unicode.");
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function mutationDigest(input) {
|
|
89
|
+
return new Bun.CryptoHasher("sha256").update(`${input.principal.length}:${input.principal}${input.key}`).digest("hex");
|
|
90
|
+
}
|
|
91
|
+
function arrayResult(value, operation) {
|
|
92
|
+
if (!Array.isArray(value)) {
|
|
93
|
+
throw new Error(`[furin-sync-redis] Invalid ${operation} response.`);
|
|
94
|
+
}
|
|
95
|
+
return value;
|
|
96
|
+
}
|
|
97
|
+
function stringResult(value, operation) {
|
|
98
|
+
if (typeof value !== "string") {
|
|
99
|
+
throw new Error(`[furin-sync-redis] Invalid ${operation} response.`);
|
|
100
|
+
}
|
|
101
|
+
return value;
|
|
102
|
+
}
|
|
103
|
+
function parseMutation(raw) {
|
|
104
|
+
const value = JSON.parse(raw);
|
|
105
|
+
if (typeof value !== "object" || value === null || !("fingerprint" in value) || typeof value.fingerprint !== "string" || !("id" in value) || typeof value.id !== "string" || !("state" in value) || value.state !== "in-progress" && value.state !== "succeeded") {
|
|
106
|
+
throw new Error("[furin-sync-redis] Invalid mutation document.");
|
|
107
|
+
}
|
|
108
|
+
return value;
|
|
109
|
+
}
|
|
110
|
+
function deserializeResponse(document) {
|
|
111
|
+
const { response } = document;
|
|
112
|
+
if (response === undefined) {
|
|
113
|
+
throw new Error("[furin-sync-redis] Succeeded mutation has no replay response.");
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
body: Uint8Array.fromBase64(response.body),
|
|
117
|
+
headers: response.headers,
|
|
118
|
+
status: response.status
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
function serializeResponse(response) {
|
|
122
|
+
return {
|
|
123
|
+
body: response.body.toBase64(),
|
|
124
|
+
headers: response.headers,
|
|
125
|
+
status: response.status
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
function compareStreamIds(left, right) {
|
|
129
|
+
if (!(REDIS_STREAM_CURSOR_PATTERN.test(left) && REDIS_STREAM_CURSOR_PATTERN.test(right))) {
|
|
130
|
+
throw new Error("[furin-sync-redis] Invalid Redis Stream cursor.");
|
|
131
|
+
}
|
|
132
|
+
const leftParts = left.split("-");
|
|
133
|
+
const rightParts = right.split("-");
|
|
134
|
+
const leftTime = BigInt(leftParts[0]);
|
|
135
|
+
const rightTime = BigInt(rightParts[0]);
|
|
136
|
+
if (leftTime !== rightTime) {
|
|
137
|
+
return leftTime < rightTime ? -1 : 1;
|
|
138
|
+
}
|
|
139
|
+
const leftSequence = BigInt(leftParts[1]);
|
|
140
|
+
const rightSequence = BigInt(rightParts[1]);
|
|
141
|
+
if (leftSequence === rightSequence) {
|
|
142
|
+
return 0;
|
|
143
|
+
}
|
|
144
|
+
return leftSequence < rightSequence ? -1 : 1;
|
|
145
|
+
}
|
|
146
|
+
function streamEntries(value) {
|
|
147
|
+
const entries = arrayResult(value, "stream read");
|
|
148
|
+
return entries.map((entry) => {
|
|
149
|
+
const tuple = arrayResult(entry, "stream entry");
|
|
150
|
+
const cursor = stringResult(tuple[0], "stream cursor");
|
|
151
|
+
const fields = arrayResult(tuple[1], "stream fields");
|
|
152
|
+
if (fields[0] !== "data") {
|
|
153
|
+
throw new Error("[furin-sync-redis] Invalid stream fields.");
|
|
154
|
+
}
|
|
155
|
+
return [cursor, stringResult(fields[1], "stream data")];
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
class RedisSyncAdapter {
|
|
160
|
+
scope = "distributed";
|
|
161
|
+
client;
|
|
162
|
+
prefix;
|
|
163
|
+
constructor(options) {
|
|
164
|
+
assertNamespace(options.namespace);
|
|
165
|
+
this.client = options.client;
|
|
166
|
+
this.prefix = `furin:sync:{${encodeURIComponent(options.namespace)}}`;
|
|
167
|
+
}
|
|
168
|
+
async beginMutation(input) {
|
|
169
|
+
const id = crypto.randomUUID();
|
|
170
|
+
const result = arrayResult(await this.client.send("EVAL", [
|
|
171
|
+
BEGIN_MUTATION_SCRIPT,
|
|
172
|
+
"1",
|
|
173
|
+
this.mutationKey(input),
|
|
174
|
+
input.fingerprint,
|
|
175
|
+
id,
|
|
176
|
+
String(LEASE_MS),
|
|
177
|
+
String(MUTATION_TTL_MS)
|
|
178
|
+
]), "begin mutation");
|
|
179
|
+
const kind = stringResult(result[0], "begin mutation kind");
|
|
180
|
+
if (kind === "execute") {
|
|
181
|
+
return {
|
|
182
|
+
kind,
|
|
183
|
+
lease: { id, key: input.key, leaseMs: LEASE_MS, principal: input.principal }
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
if (kind === "replay") {
|
|
187
|
+
const document = parseMutation(stringResult(result[1], "replay mutation"));
|
|
188
|
+
return { kind, response: deserializeResponse(document) };
|
|
189
|
+
}
|
|
190
|
+
if (kind === "conflict") {
|
|
191
|
+
const reason = stringResult(result[1], "mutation conflict");
|
|
192
|
+
if (reason === "in-progress" || reason === "payload-mismatch") {
|
|
193
|
+
return { kind, reason };
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
throw new Error("[furin-sync-redis] Invalid begin mutation result.");
|
|
197
|
+
}
|
|
198
|
+
async renewMutation(lease) {
|
|
199
|
+
const result = await this.client.send("EVAL", [
|
|
200
|
+
RENEW_MUTATION_SCRIPT,
|
|
201
|
+
"1",
|
|
202
|
+
this.mutationKey(lease),
|
|
203
|
+
lease.id,
|
|
204
|
+
String(lease.leaseMs),
|
|
205
|
+
String(MUTATION_TTL_MS)
|
|
206
|
+
]);
|
|
207
|
+
if (result === "lost" || result === "renewed") {
|
|
208
|
+
return result;
|
|
209
|
+
}
|
|
210
|
+
throw new Error("[furin-sync-redis] Invalid lease renewal result.");
|
|
211
|
+
}
|
|
212
|
+
async completeMutation(input) {
|
|
213
|
+
const result = arrayResult(await this.client.send("EVAL", [
|
|
214
|
+
COMPLETE_MUTATION_SCRIPT,
|
|
215
|
+
"3",
|
|
216
|
+
this.mutationKey(input.lease),
|
|
217
|
+
this.streamKey,
|
|
218
|
+
this.trimmedKey,
|
|
219
|
+
input.lease.id,
|
|
220
|
+
JSON.stringify(serializeResponse(input.response)),
|
|
221
|
+
JSON.stringify(input.invalidations),
|
|
222
|
+
String(MUTATION_TTL_MS),
|
|
223
|
+
String(CHANGE_RETENTION)
|
|
224
|
+
]), "complete mutation");
|
|
225
|
+
const kind = stringResult(result[0], "complete mutation kind");
|
|
226
|
+
if (kind === "lost") {
|
|
227
|
+
return { kind };
|
|
228
|
+
}
|
|
229
|
+
if (kind !== "committed") {
|
|
230
|
+
throw new Error("[furin-sync-redis] Invalid complete mutation result.");
|
|
231
|
+
}
|
|
232
|
+
const cursor = stringResult(result[1], "complete mutation cursor");
|
|
233
|
+
return cursor.length === 0 ? { cursor: undefined, kind } : { cursor, kind };
|
|
234
|
+
}
|
|
235
|
+
async abortMutation(lease) {
|
|
236
|
+
await this.client.send("EVAL", [ABORT_MUTATION_SCRIPT, "1", this.mutationKey(lease), lease.id]);
|
|
237
|
+
}
|
|
238
|
+
async currentCursor() {
|
|
239
|
+
const entries = streamEntries(await this.client.send("XREVRANGE", [this.streamKey, "+", "-", "COUNT", "1"]));
|
|
240
|
+
return entries[0]?.[0] ?? "0-0";
|
|
241
|
+
}
|
|
242
|
+
async readChanges(input) {
|
|
243
|
+
const currentCursor = await this.currentCursor();
|
|
244
|
+
if (input.after === undefined) {
|
|
245
|
+
return { changes: [], cursor: currentCursor, hasMore: false, reset: false };
|
|
246
|
+
}
|
|
247
|
+
try {
|
|
248
|
+
compareStreamIds(input.after, "0-0");
|
|
249
|
+
} catch {
|
|
250
|
+
return { changes: [], cursor: currentCursor, hasMore: false, reset: true };
|
|
251
|
+
}
|
|
252
|
+
if (compareStreamIds(input.after, currentCursor) > 0) {
|
|
253
|
+
return { changes: [], cursor: currentCursor, hasMore: false, reset: true };
|
|
254
|
+
}
|
|
255
|
+
const trimmed = await this.client.get(this.trimmedKey);
|
|
256
|
+
if (trimmed !== null && compareStreamIds(input.after, trimmed) < 0) {
|
|
257
|
+
return { changes: [], cursor: currentCursor, hasMore: false, reset: true };
|
|
258
|
+
}
|
|
259
|
+
const entries = streamEntries(await this.client.send("XRANGE", [
|
|
260
|
+
this.streamKey,
|
|
261
|
+
`(${input.after}`,
|
|
262
|
+
"+",
|
|
263
|
+
"COUNT",
|
|
264
|
+
String(input.limit + 1)
|
|
265
|
+
]));
|
|
266
|
+
const latestTrimmed = await this.client.get(this.trimmedKey);
|
|
267
|
+
if (latestTrimmed !== null && compareStreamIds(input.after, latestTrimmed) < 0) {
|
|
268
|
+
return {
|
|
269
|
+
changes: [],
|
|
270
|
+
cursor: await this.currentCursor(),
|
|
271
|
+
hasMore: false,
|
|
272
|
+
reset: true
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
const hasMore = entries.length > input.limit;
|
|
276
|
+
const changes = entries.slice(0, input.limit).map(([cursor, raw]) => ({
|
|
277
|
+
cursor,
|
|
278
|
+
invalidations: JSON.parse(raw)
|
|
279
|
+
}));
|
|
280
|
+
return {
|
|
281
|
+
changes,
|
|
282
|
+
cursor: changes.at(-1)?.cursor ?? input.after,
|
|
283
|
+
hasMore,
|
|
284
|
+
reset: false
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
mutationKey(input) {
|
|
288
|
+
return `${this.prefix}:mutation:${mutationDigest(input)}`;
|
|
289
|
+
}
|
|
290
|
+
get streamKey() {
|
|
291
|
+
return `${this.prefix}:changes`;
|
|
292
|
+
}
|
|
293
|
+
get trimmedKey() {
|
|
294
|
+
return `${this.prefix}:trimmed`;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
class RedisSyncNotifier {
|
|
299
|
+
channel;
|
|
300
|
+
client;
|
|
301
|
+
constructor(options) {
|
|
302
|
+
assertNamespace(options.namespace);
|
|
303
|
+
this.client = options.client;
|
|
304
|
+
this.channel = `furin:sync:${options.namespace}:notify`;
|
|
305
|
+
}
|
|
306
|
+
async publish(cursor) {
|
|
307
|
+
await this.client.publish(this.channel, cursor);
|
|
308
|
+
}
|
|
309
|
+
async subscribe(listener) {
|
|
310
|
+
const subscriber = await this.client.duplicate();
|
|
311
|
+
try {
|
|
312
|
+
await subscriber.subscribe(this.channel, listener);
|
|
313
|
+
} catch (error) {
|
|
314
|
+
subscriber.close();
|
|
315
|
+
throw error;
|
|
316
|
+
}
|
|
317
|
+
return {
|
|
318
|
+
unsubscribe: async () => {
|
|
319
|
+
await subscriber.unsubscribe(this.channel, listener);
|
|
320
|
+
subscriber.close();
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
function redisSyncAdapter(options) {
|
|
326
|
+
return new RedisSyncAdapter(options);
|
|
327
|
+
}
|
|
328
|
+
function redisSyncNotifier(options) {
|
|
329
|
+
return new RedisSyncNotifier(options);
|
|
330
|
+
}
|
|
331
|
+
export {
|
|
332
|
+
RedisSyncAdapter,
|
|
333
|
+
RedisSyncNotifier,
|
|
334
|
+
redisSyncAdapter,
|
|
335
|
+
redisSyncNotifier
|
|
336
|
+
};
|
|
@@ -0,0 +1,4 @@
|
|
|
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
|
+
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 = cjson.decode(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
|
+
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";
|
|
@@ -1,4 +1,13 @@
|
|
|
1
1
|
import { type Context } from "elysia";
|
|
2
2
|
import type { StoredResponse } from "./adapter.ts";
|
|
3
|
-
export declare
|
|
3
|
+
export declare const MAX_SYNC_REPLAY_RESPONSE_BYTES: number;
|
|
4
|
+
export type StoreResponseResult = {
|
|
5
|
+
kind: "stored";
|
|
6
|
+
response: StoredResponse;
|
|
7
|
+
} | {
|
|
8
|
+
kind: "unreplayable";
|
|
9
|
+
response: StoredResponse;
|
|
10
|
+
};
|
|
11
|
+
export declare function mergeStoredResponseHeaders(storedResponse: StoredResponse, headers: Context["set"]["headers"]): StoredResponse;
|
|
12
|
+
export declare function storeResponse(responseValue: unknown, set: Context["set"]): Promise<StoreResponseResult>;
|
|
4
13
|
export declare function replayResponse(stored: StoredResponse): Response;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { SyncAdapter, SyncNotifier, SyncRuntimeOptions } from "./adapter.ts";
|
|
2
|
+
export interface ResolvedSyncRuntime {
|
|
3
|
+
adapter: SyncAdapter;
|
|
4
|
+
notifier: SyncNotifier;
|
|
5
|
+
}
|
|
6
|
+
export declare function resolveSyncRuntime(options: SyncRuntimeOptions): ResolvedSyncRuntime;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Database } from "bun:sqlite";
|
|
2
|
+
import type { BeginMutationInput, BeginMutationResult, ChangePage, CompleteMutationInput, CompleteMutationResult, MutationLease, ReadChangesInput, SyncAdapter } from "../adapter.ts";
|
|
3
|
+
export interface SqliteSyncAdapterOptions {
|
|
4
|
+
database: Database;
|
|
5
|
+
namespace: string;
|
|
6
|
+
}
|
|
7
|
+
export declare function migrateSqliteSync(database: Database): void;
|
|
8
|
+
export declare class SqliteSyncAdapter implements SyncAdapter {
|
|
9
|
+
readonly scope: "host-local" | "process-local";
|
|
10
|
+
private readonly database;
|
|
11
|
+
private readonly namespace;
|
|
12
|
+
constructor(options: SqliteSyncAdapterOptions);
|
|
13
|
+
beginMutation(input: BeginMutationInput): Promise<BeginMutationResult>;
|
|
14
|
+
completeMutation(input: CompleteMutationInput): Promise<CompleteMutationResult>;
|
|
15
|
+
abortMutation(lease: MutationLease): Promise<void>;
|
|
16
|
+
currentCursor(): Promise<string>;
|
|
17
|
+
readChanges(input: ReadChangesInput): Promise<ChangePage>;
|
|
18
|
+
renewMutation(lease: MutationLease): Promise<"lost" | "renewed">;
|
|
19
|
+
}
|
|
20
|
+
export declare function sqliteSyncAdapter(options: SqliteSyncAdapterOptions): SqliteSyncAdapter;
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/server/sync/sqlite/migration.sql
|
|
3
|
+
var migration_default = `CREATE TABLE IF NOT EXISTS furin_sync_mutations (
|
|
4
|
+
namespace TEXT NOT NULL,
|
|
5
|
+
mutation_key TEXT NOT NULL,
|
|
6
|
+
mutation_id TEXT NOT NULL,
|
|
7
|
+
fingerprint TEXT NOT NULL,
|
|
8
|
+
state TEXT NOT NULL CHECK (state IN ('in-progress', 'succeeded')),
|
|
9
|
+
response_status INTEGER,
|
|
10
|
+
response_headers TEXT,
|
|
11
|
+
response_body BLOB,
|
|
12
|
+
lease_expires_at INTEGER NOT NULL,
|
|
13
|
+
expires_at INTEGER NOT NULL,
|
|
14
|
+
created_at INTEGER NOT NULL,
|
|
15
|
+
completed_at INTEGER,
|
|
16
|
+
CONSTRAINT furin_sync_mutations_succeeded_response_check CHECK (
|
|
17
|
+
state <> 'succeeded'
|
|
18
|
+
OR (
|
|
19
|
+
response_status IS NOT NULL
|
|
20
|
+
AND response_headers IS NOT NULL
|
|
21
|
+
AND response_body IS NOT NULL
|
|
22
|
+
AND completed_at IS NOT NULL
|
|
23
|
+
)
|
|
24
|
+
),
|
|
25
|
+
PRIMARY KEY (namespace, mutation_key),
|
|
26
|
+
UNIQUE (mutation_id)
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
CREATE TRIGGER IF NOT EXISTS furin_sync_mutations_succeeded_response_insert
|
|
30
|
+
BEFORE INSERT ON furin_sync_mutations
|
|
31
|
+
WHEN NEW.state = 'succeeded'
|
|
32
|
+
AND (
|
|
33
|
+
NEW.response_status IS NULL
|
|
34
|
+
OR NEW.response_headers IS NULL
|
|
35
|
+
OR NEW.response_body IS NULL
|
|
36
|
+
OR NEW.completed_at IS NULL
|
|
37
|
+
)
|
|
38
|
+
BEGIN
|
|
39
|
+
SELECT RAISE(ABORT, 'CHECK constraint failed: furin_sync_mutations_succeeded_response_check');
|
|
40
|
+
END;
|
|
41
|
+
|
|
42
|
+
CREATE TRIGGER IF NOT EXISTS furin_sync_mutations_succeeded_response_update
|
|
43
|
+
BEFORE UPDATE ON furin_sync_mutations
|
|
44
|
+
WHEN NEW.state = 'succeeded'
|
|
45
|
+
AND (
|
|
46
|
+
NEW.response_status IS NULL
|
|
47
|
+
OR NEW.response_headers IS NULL
|
|
48
|
+
OR NEW.response_body IS NULL
|
|
49
|
+
OR NEW.completed_at IS NULL
|
|
50
|
+
)
|
|
51
|
+
BEGIN
|
|
52
|
+
SELECT RAISE(ABORT, 'CHECK constraint failed: furin_sync_mutations_succeeded_response_check');
|
|
53
|
+
END;
|
|
54
|
+
|
|
55
|
+
CREATE TABLE IF NOT EXISTS furin_sync_streams (
|
|
56
|
+
namespace TEXT PRIMARY KEY,
|
|
57
|
+
current_cursor INTEGER NOT NULL DEFAULT 0,
|
|
58
|
+
oldest_cursor INTEGER NOT NULL DEFAULT 0
|
|
59
|
+
);
|
|
60
|
+
|
|
61
|
+
CREATE TABLE IF NOT EXISTS furin_sync_changes (
|
|
62
|
+
namespace TEXT NOT NULL,
|
|
63
|
+
cursor INTEGER NOT NULL,
|
|
64
|
+
invalidations TEXT NOT NULL,
|
|
65
|
+
created_at INTEGER NOT NULL,
|
|
66
|
+
PRIMARY KEY (namespace, cursor)
|
|
67
|
+
);
|
|
68
|
+
|
|
69
|
+
CREATE INDEX IF NOT EXISTS furin_sync_mutations_expiry_idx
|
|
70
|
+
ON furin_sync_mutations (expires_at);
|
|
71
|
+
|
|
72
|
+
DROP INDEX IF EXISTS furin_sync_changes_created_idx;
|
|
73
|
+
`;
|
|
74
|
+
|
|
75
|
+
// src/server/sync/sqlite/index.ts
|
|
76
|
+
var CHANGE_RETENTION = 1000;
|
|
77
|
+
var LEASE_MS = 30000;
|
|
78
|
+
var MUTATION_TTL_MS = 24 * 60 * 60 * 1000;
|
|
79
|
+
var UNSIGNED_INTEGER_PATTERN = /^\d+$/;
|
|
80
|
+
function mutationKey(input) {
|
|
81
|
+
return `${input.principal.length}:${input.principal}${input.key}`;
|
|
82
|
+
}
|
|
83
|
+
function storedResponse(row) {
|
|
84
|
+
if (row.response_body === null || row.response_headers === null || row.response_status === null) {
|
|
85
|
+
throw new Error("[furin-sync-sqlite] Succeeded mutation has no replay response.");
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
body: new Uint8Array(row.response_body),
|
|
89
|
+
headers: JSON.parse(row.response_headers),
|
|
90
|
+
status: row.response_status
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function migrateSqliteSync(database) {
|
|
94
|
+
database.run(migration_default);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
class SqliteSyncAdapter {
|
|
98
|
+
scope;
|
|
99
|
+
database;
|
|
100
|
+
namespace;
|
|
101
|
+
constructor(options) {
|
|
102
|
+
if (options.namespace.length === 0) {
|
|
103
|
+
throw new Error("[furin-sync-sqlite] namespace must not be empty.");
|
|
104
|
+
}
|
|
105
|
+
this.database = options.database;
|
|
106
|
+
this.namespace = options.namespace;
|
|
107
|
+
this.scope = options.database.filename === "" || options.database.filename === ":memory:" ? "process-local" : "host-local";
|
|
108
|
+
}
|
|
109
|
+
async beginMutation(input) {
|
|
110
|
+
const transaction = this.database.transaction((mutation) => {
|
|
111
|
+
const now = Date.now();
|
|
112
|
+
const key = mutationKey(mutation);
|
|
113
|
+
this.database.query(`DELETE FROM furin_sync_mutations WHERE rowid IN (
|
|
114
|
+
SELECT rowid FROM furin_sync_mutations
|
|
115
|
+
WHERE
|
|
116
|
+
(state = 'succeeded' AND expires_at <= ?)
|
|
117
|
+
OR (
|
|
118
|
+
state = 'in-progress'
|
|
119
|
+
AND lease_expires_at <= ?
|
|
120
|
+
AND expires_at <= ?
|
|
121
|
+
)
|
|
122
|
+
LIMIT 100
|
|
123
|
+
)`).run(now, now, now);
|
|
124
|
+
const existing = this.database.query(`SELECT mutation_id, fingerprint, state, response_status, response_headers,
|
|
125
|
+
response_body, lease_expires_at, expires_at
|
|
126
|
+
FROM furin_sync_mutations
|
|
127
|
+
WHERE namespace = ? AND mutation_key = ?`).get(this.namespace, key);
|
|
128
|
+
if (existing?.fingerprint !== undefined && existing.fingerprint !== mutation.fingerprint) {
|
|
129
|
+
return { kind: "conflict", reason: "payload-mismatch" };
|
|
130
|
+
}
|
|
131
|
+
const expired = existing?.state === "in-progress" ? existing.lease_expires_at <= now : existing?.expires_at !== undefined && existing.expires_at <= now;
|
|
132
|
+
if (existing && !expired) {
|
|
133
|
+
return existing.state === "in-progress" ? { kind: "conflict", reason: "in-progress" } : { kind: "replay", response: storedResponse(existing) };
|
|
134
|
+
}
|
|
135
|
+
const id = crypto.randomUUID();
|
|
136
|
+
this.database.query(`INSERT INTO furin_sync_mutations (
|
|
137
|
+
namespace, mutation_key, mutation_id, fingerprint, state,
|
|
138
|
+
lease_expires_at, expires_at, created_at
|
|
139
|
+
) VALUES (?, ?, ?, ?, 'in-progress', ?, ?, ?)
|
|
140
|
+
ON CONFLICT (namespace, mutation_key) DO UPDATE SET
|
|
141
|
+
mutation_id = excluded.mutation_id,
|
|
142
|
+
fingerprint = excluded.fingerprint,
|
|
143
|
+
state = 'in-progress',
|
|
144
|
+
response_status = NULL,
|
|
145
|
+
response_headers = NULL,
|
|
146
|
+
response_body = NULL,
|
|
147
|
+
lease_expires_at = excluded.lease_expires_at,
|
|
148
|
+
expires_at = excluded.expires_at,
|
|
149
|
+
created_at = excluded.created_at,
|
|
150
|
+
completed_at = NULL`).run(this.namespace, key, id, mutation.fingerprint, now + LEASE_MS, now + MUTATION_TTL_MS, now);
|
|
151
|
+
return {
|
|
152
|
+
kind: "execute",
|
|
153
|
+
lease: { id, key: mutation.key, leaseMs: LEASE_MS, principal: mutation.principal }
|
|
154
|
+
};
|
|
155
|
+
});
|
|
156
|
+
return transaction.immediate(input);
|
|
157
|
+
}
|
|
158
|
+
async completeMutation(input) {
|
|
159
|
+
const transaction = this.database.transaction((completion) => {
|
|
160
|
+
const now = Date.now();
|
|
161
|
+
const key = mutationKey(completion.lease);
|
|
162
|
+
const active = this.database.query(`SELECT mutation_id FROM furin_sync_mutations
|
|
163
|
+
WHERE namespace = ? AND mutation_key = ? AND mutation_id = ?
|
|
164
|
+
AND state = 'in-progress' AND lease_expires_at > ?`).get(this.namespace, key, completion.lease.id, now);
|
|
165
|
+
if (!active) {
|
|
166
|
+
return { kind: "lost" };
|
|
167
|
+
}
|
|
168
|
+
let cursor;
|
|
169
|
+
if (completion.invalidations.length > 0) {
|
|
170
|
+
this.database.query(`INSERT INTO furin_sync_streams (namespace, current_cursor, oldest_cursor)
|
|
171
|
+
VALUES (?, 0, 0) ON CONFLICT (namespace) DO NOTHING`).run(this.namespace);
|
|
172
|
+
this.database.query(`UPDATE furin_sync_streams SET current_cursor = current_cursor + 1
|
|
173
|
+
WHERE namespace = ?`).run(this.namespace);
|
|
174
|
+
const cursorRow = this.database.query(`SELECT CAST(current_cursor AS TEXT) AS current_cursor
|
|
175
|
+
FROM furin_sync_streams WHERE namespace = ?`).get(this.namespace);
|
|
176
|
+
if (!cursorRow) {
|
|
177
|
+
throw new Error("[furin-sync-sqlite] Could not allocate a change cursor.");
|
|
178
|
+
}
|
|
179
|
+
cursor = cursorRow.current_cursor;
|
|
180
|
+
this.database.query(`INSERT INTO furin_sync_changes (namespace, cursor, invalidations, created_at)
|
|
181
|
+
VALUES (?, ?, ?, ?)`).run(this.namespace, cursorRow.current_cursor, JSON.stringify(completion.invalidations), now);
|
|
182
|
+
const removed = this.database.query(`DELETE FROM furin_sync_changes
|
|
183
|
+
WHERE namespace = ? AND cursor <= MAX(0, CAST(? AS INTEGER) - ?)`).run(this.namespace, cursorRow.current_cursor, CHANGE_RETENTION);
|
|
184
|
+
if (removed.changes > 0) {
|
|
185
|
+
const oldest = this.database.query(`SELECT CAST(MIN(cursor) AS TEXT) AS cursor
|
|
186
|
+
FROM furin_sync_changes WHERE namespace = ?`).get(this.namespace);
|
|
187
|
+
this.database.query("UPDATE furin_sync_streams SET oldest_cursor = ? WHERE namespace = ?").run(oldest?.cursor ?? cursorRow.current_cursor, this.namespace);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
this.database.query(`UPDATE furin_sync_mutations
|
|
191
|
+
SET state = 'succeeded', response_status = ?, response_headers = ?,
|
|
192
|
+
response_body = ?, completed_at = ?, expires_at = ?
|
|
193
|
+
WHERE namespace = ? AND mutation_key = ? AND mutation_id = ?`).run(completion.response.status, JSON.stringify(completion.response.headers), completion.response.body, now, now + MUTATION_TTL_MS, this.namespace, key, completion.lease.id);
|
|
194
|
+
return { cursor, kind: "committed" };
|
|
195
|
+
});
|
|
196
|
+
return transaction.immediate(input);
|
|
197
|
+
}
|
|
198
|
+
async abortMutation(lease) {
|
|
199
|
+
this.database.query(`DELETE FROM furin_sync_mutations
|
|
200
|
+
WHERE namespace = ? AND mutation_key = ? AND mutation_id = ? AND state = 'in-progress'`).run(this.namespace, mutationKey(lease), lease.id);
|
|
201
|
+
}
|
|
202
|
+
async currentCursor() {
|
|
203
|
+
const row = this.database.query(`SELECT CAST(current_cursor AS TEXT) AS current_cursor
|
|
204
|
+
FROM furin_sync_streams WHERE namespace = ?`).get(this.namespace);
|
|
205
|
+
return row?.current_cursor ?? "0";
|
|
206
|
+
}
|
|
207
|
+
async readChanges(input) {
|
|
208
|
+
const transaction = this.database.transaction((page) => {
|
|
209
|
+
const cursorRow = this.database.query(`SELECT CAST(current_cursor AS TEXT) AS current_cursor,
|
|
210
|
+
CAST(oldest_cursor AS TEXT) AS oldest_cursor
|
|
211
|
+
FROM furin_sync_streams WHERE namespace = ?`).get(this.namespace);
|
|
212
|
+
const currentCursor = cursorRow?.current_cursor ?? "0";
|
|
213
|
+
if (page.after === undefined) {
|
|
214
|
+
return { changes: [], cursor: currentCursor, hasMore: false, reset: false };
|
|
215
|
+
}
|
|
216
|
+
if (!UNSIGNED_INTEGER_PATTERN.test(page.after) || BigInt(page.after) > BigInt(currentCursor) || BigInt(page.after) < BigInt(cursorRow?.oldest_cursor ?? "0") - 1n) {
|
|
217
|
+
return { changes: [], cursor: currentCursor, hasMore: false, reset: true };
|
|
218
|
+
}
|
|
219
|
+
const rows = this.database.query(`SELECT CAST(cursor AS TEXT) AS cursor, invalidations FROM furin_sync_changes
|
|
220
|
+
WHERE namespace = ? AND cursor > CAST(? AS INTEGER) ORDER BY cursor ASC LIMIT ?`).all(this.namespace, page.after, page.limit + 1);
|
|
221
|
+
const hasMore = rows.length > page.limit;
|
|
222
|
+
const changes = rows.slice(0, page.limit).map((row) => ({
|
|
223
|
+
cursor: row.cursor,
|
|
224
|
+
invalidations: JSON.parse(row.invalidations)
|
|
225
|
+
}));
|
|
226
|
+
return {
|
|
227
|
+
changes,
|
|
228
|
+
cursor: changes.at(-1)?.cursor ?? page.after,
|
|
229
|
+
hasMore,
|
|
230
|
+
reset: false
|
|
231
|
+
};
|
|
232
|
+
});
|
|
233
|
+
return transaction(input);
|
|
234
|
+
}
|
|
235
|
+
async renewMutation(lease) {
|
|
236
|
+
const now = Date.now();
|
|
237
|
+
const result = this.database.query(`UPDATE furin_sync_mutations SET lease_expires_at = ?
|
|
238
|
+
WHERE namespace = ? AND mutation_key = ? AND mutation_id = ?
|
|
239
|
+
AND state = 'in-progress' AND lease_expires_at > ?`).run(now + lease.leaseMs, this.namespace, mutationKey(lease), lease.id, now);
|
|
240
|
+
return result.changes === 1 ? "renewed" : "lost";
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
function sqliteSyncAdapter(options) {
|
|
244
|
+
return new SqliteSyncAdapter(options);
|
|
245
|
+
}
|
|
246
|
+
export {
|
|
247
|
+
SqliteSyncAdapter,
|
|
248
|
+
migrateSqliteSync,
|
|
249
|
+
sqliteSyncAdapter
|
|
250
|
+
};
|
|
@@ -1,14 +1,7 @@
|
|
|
1
1
|
import { Elysia } from "elysia";
|
|
2
|
+
import type { FurinSyncOptions } from "./config.ts";
|
|
2
3
|
export type { ChangePage as SyncChangePage, SyncChange } from "./adapter.ts";
|
|
3
|
-
export declare function
|
|
4
|
-
/**
|
|
5
|
-
* Builds the SSE plugin serving one instance's sync stream. Routes are
|
|
6
|
-
* registered at the logical `path` (the parent instance's Elysia prefix makes
|
|
7
|
-
* them physical); `channel` is the adapter key the stream reads from — pass
|
|
8
|
-
* the PHYSICAL path (`prefix + path`) so two mounted apps never share a
|
|
9
|
-
* cursor sequence.
|
|
10
|
-
*/
|
|
11
|
-
export declare function createSyncStreamPlugin(path?: string, channel?: string): Elysia<"", {
|
|
4
|
+
export declare function createSyncStreamPlugin(options: FurinSyncOptions): Elysia<"", {
|
|
12
5
|
decorator: {};
|
|
13
6
|
store: {};
|
|
14
7
|
derive: {};
|
|
@@ -32,7 +25,15 @@ export declare function createSyncStreamPlugin(path?: string, channel?: string):
|
|
|
32
25
|
query: unknown;
|
|
33
26
|
headers: unknown;
|
|
34
27
|
response: {
|
|
35
|
-
200: Response |
|
|
28
|
+
200: Response | {
|
|
29
|
+
cursor: string;
|
|
30
|
+
hasMore: boolean;
|
|
31
|
+
reset: boolean;
|
|
32
|
+
changes: {
|
|
33
|
+
cursor: string;
|
|
34
|
+
invalidations: string[];
|
|
35
|
+
}[];
|
|
36
|
+
};
|
|
36
37
|
};
|
|
37
38
|
};
|
|
38
39
|
};
|
|
@@ -62,5 +63,5 @@ export declare function createSyncStreamPlugin(path?: string, channel?: string):
|
|
|
62
63
|
standaloneSchema: {};
|
|
63
64
|
response: {};
|
|
64
65
|
}>;
|
|
65
|
-
/** @internal —
|
|
66
|
+
/** @internal — closes process-local stream state between tests. */
|
|
66
67
|
export declare function __resetSyncState(): void;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
// @bun
|