@teyik0/furin 0.5.0-alpha.1 → 0.5.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/build/entry-template.ts +3 -1
- package/dist/build/index.js +360 -219
- package/dist/build/private-server-sourcemaps.d.ts +2 -0
- package/dist/build/types.d.ts +2 -0
- package/dist/cli/index.js +363 -221
- package/dist/client/document.d.ts +2 -0
- package/dist/client/link.js +11 -0
- package/dist/client.js +11 -0
- package/dist/config.d.ts +7 -2
- package/dist/config.js +24 -1
- package/dist/furin.js +217 -82
- package/dist/rsc-client.js +9 -1
- package/dist/rsc.js +19 -7
- package/dist/server/browser-events/shutdown.d.ts +3 -0
- package/dist/server/cache/redis/index.d.ts +2 -0
- package/dist/server/cache/redis/index.js +67 -12
- package/dist/server/cache/redis/scripts.d.ts +5 -5
- package/dist/server/dev/plugin.d.ts +1 -0
- package/dist/server/evlog.d.ts +1 -1
- package/dist/server/internal.js +3 -1
- package/dist/server/production-server.d.ts +13 -0
- package/dist/server/production-server.js +2906 -0
- package/dist/server/router/hmr.d.ts +6 -0
- package/dist/server/router/hmr.production.d.ts +5 -0
- package/dist/server/router/plugin.d.ts +5 -1
- package/dist/server/sync/index.js +5 -2
- package/dist/server/sync/stream.d.ts +4 -0
- package/dist/shared/production-build.d.ts +2 -0
- package/package.json +8 -3
- package/src/adapter/bun.ts +74 -15
- package/src/adapter/vercel.ts +15 -1
- package/src/build/elysia-aot.ts +1 -1
- package/src/build/entry-template.ts +3 -1
- package/src/build/hydrate.ts +5 -1
- package/src/build/index.ts +5 -0
- package/src/build/private-server-sourcemaps.ts +20 -0
- package/src/build/server-app-entry.ts +3 -2
- package/src/build/types.ts +2 -0
- package/src/cli/index.ts +1 -0
- package/src/client/document.tsx +19 -0
- package/src/config.ts +30 -2
- package/src/furin.ts +37 -12
- package/src/rsc/codec.ts +11 -6
- package/src/rsc/render-error.ts +3 -1
- package/src/server/browser-events/plugin.ts +7 -0
- package/src/server/browser-events/shutdown.ts +32 -0
- package/src/server/cache/redis/index.ts +19 -2
- package/src/server/cache/redis/scripts.ts +47 -7
- package/src/server/dev/plugin.ts +10 -1
- package/src/server/evlog.ts +11 -4
- package/src/server/production-server.ts +135 -0
- package/src/server/render/document.tsx +7 -1
- package/src/server/render/ssr.ts +2 -1
- package/src/server/render/template.ts +5 -1
- package/src/server/router/discovery.ts +3 -1
- package/src/server/router/hmr.production.ts +11 -0
- package/src/server/router/hmr.ts +84 -77
- package/src/server/router/plugin.ts +76 -17
- package/src/server/router/schema-merge.ts +9 -2
- package/src/server/sync/stream.ts +43 -2
- package/src/shared/production-build.ts +20 -0
package/src/furin.ts
CHANGED
|
@@ -40,7 +40,7 @@ import {
|
|
|
40
40
|
setProductionTemplatePath,
|
|
41
41
|
} from "./server/render/template.ts";
|
|
42
42
|
import { loadProdRoutes } from "./server/router/discovery.ts";
|
|
43
|
-
import { invalidateStampedRouteModules } from "./server/router/hmr.ts";
|
|
43
|
+
import { invalidateStampedRouteModules, resolveCurrentDevRoute } from "./server/router/hmr.ts";
|
|
44
44
|
import { buildRouteMatcher } from "./server/router/patterns.ts";
|
|
45
45
|
import { createDataEndpoint, renderResolvedRoute } from "./server/router/plugin.ts";
|
|
46
46
|
import { mergeRouteSchemas } from "./server/router/schema-merge.ts";
|
|
@@ -432,9 +432,28 @@ function wrapWithRequestScope(app: AnyElysia): Elysia {
|
|
|
432
432
|
});
|
|
433
433
|
}
|
|
434
434
|
|
|
435
|
-
function createFurinPlugin(app: AnyElysia) {
|
|
435
|
+
function createFurinPlugin(app: AnyElysia, hmrPrefix: string | undefined) {
|
|
436
436
|
const scopedApp = wrapWithRequestScope(app);
|
|
437
|
-
return <ParentApp extends AnyElysia>(parentApp: ParentApp) =>
|
|
437
|
+
return <ParentApp extends AnyElysia>(parentApp: ParentApp) => {
|
|
438
|
+
const mounted = parentApp.use(scopedApp);
|
|
439
|
+
if (hmrPrefix !== undefined) {
|
|
440
|
+
const parentConfig = Reflect.get(parentApp, "~config") as { prefix?: string } | undefined;
|
|
441
|
+
const entryPath = `${parentConfig?.prefix ?? ""}${hmrPrefix}/_bun_hmr_entry`;
|
|
442
|
+
const routes = Reflect.get(mounted, "~routes") as
|
|
443
|
+
| [string, string, unknown, unknown, unknown, unknown, unknown?][]
|
|
444
|
+
| undefined;
|
|
445
|
+
for (const route of routes ?? []) {
|
|
446
|
+
if (
|
|
447
|
+
route[0] === "GET" &&
|
|
448
|
+
(route[1] === entryPath || route[1] === `${entryPath}/index.html`)
|
|
449
|
+
) {
|
|
450
|
+
// Bun serves these HTML bundles natively; inherited Elysia hooks cannot run.
|
|
451
|
+
route[6] = undefined;
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
return mounted;
|
|
456
|
+
};
|
|
438
457
|
}
|
|
439
458
|
|
|
440
459
|
async function loadDevelopmentRoutes(resolvedPagesDir: string) {
|
|
@@ -722,6 +741,7 @@ export async function furin({
|
|
|
722
741
|
};
|
|
723
742
|
writeCurrentDevFiles(initialSnapshot);
|
|
724
743
|
graph.commit(initialSnapshot);
|
|
744
|
+
const hmrEntry = (await import(join(furinDir, "index.html"))).default;
|
|
725
745
|
const refreshDevelopmentRoutes = (changedSources: readonly string[]): Promise<void> =>
|
|
726
746
|
withInstance(instance, async () => {
|
|
727
747
|
invalidateStampedRouteModules();
|
|
@@ -796,7 +816,8 @@ export async function furin({
|
|
|
796
816
|
routeTopologyWatcher?.close();
|
|
797
817
|
routeTopologyWatcher = undefined;
|
|
798
818
|
})
|
|
799
|
-
.
|
|
819
|
+
.get("/_bun_hmr_entry/index.html", hmrEntry)
|
|
820
|
+
.get("/_bun_hmr_entry", hmrEntry)
|
|
800
821
|
.use(loggerPlugin)
|
|
801
822
|
// Local scope (default) — a global hook would leak onto sibling furin
|
|
802
823
|
// instances mounted on the same parent app.
|
|
@@ -837,12 +858,16 @@ export async function furin({
|
|
|
837
858
|
: new Elysia()
|
|
838
859
|
)
|
|
839
860
|
.use(
|
|
840
|
-
createDataEndpoint(
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
861
|
+
createDataEndpoint(
|
|
862
|
+
async (request) => {
|
|
863
|
+
if (request.headers.get("x-furin-hmr-refresh") === "1") {
|
|
864
|
+
await routeTopologyWatcher?.refresh();
|
|
865
|
+
}
|
|
866
|
+
return currentSnapshot().routes;
|
|
867
|
+
},
|
|
868
|
+
undefined,
|
|
869
|
+
(route) => resolveCurrentDevRoute(route, currentSnapshot().root)
|
|
870
|
+
)
|
|
846
871
|
)
|
|
847
872
|
.decorate(FURIN_RENDER_DECORATOR, dispatchNativeRoute)
|
|
848
873
|
.use(nativeRoutesApp)
|
|
@@ -861,7 +886,7 @@ export async function furin({
|
|
|
861
886
|
})
|
|
862
887
|
);
|
|
863
888
|
registerInstance(instance);
|
|
864
|
-
return createFurinPlugin(devApp);
|
|
889
|
+
return createFurinPlugin(devApp, prefix);
|
|
865
890
|
}
|
|
866
891
|
|
|
867
892
|
// ── Production ──────────────────────────────────────────────────────────
|
|
@@ -935,7 +960,7 @@ export async function furin({
|
|
|
935
960
|
.use(ctx.nativeRoutes)
|
|
936
961
|
.use(createNotFoundHandling(prefix, routes, root));
|
|
937
962
|
registerInstance(instance);
|
|
938
|
-
return createFurinPlugin(prodApp);
|
|
963
|
+
return createFurinPlugin(prodApp, undefined);
|
|
939
964
|
}
|
|
940
965
|
|
|
941
966
|
/**
|
package/src/rsc/codec.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { existsSync, mkdirSync } from "node:fs";
|
|
|
2
2
|
import { tmpdir } from "node:os";
|
|
3
3
|
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
4
4
|
import { pathToFileURL } from "node:url";
|
|
5
|
+
import { isProductionBuild } from "../shared/production-build.ts";
|
|
5
6
|
import { drainFlight, type FlightRenderSession } from "./flight-drain.ts";
|
|
6
7
|
import type { RscRenderOperation } from "./render-error.ts";
|
|
7
8
|
|
|
@@ -9,7 +10,7 @@ interface ServerCodec {
|
|
|
9
10
|
renderFlight: (model: unknown, signal: AbortSignal | undefined) => FlightRenderSession;
|
|
10
11
|
}
|
|
11
12
|
|
|
12
|
-
|
|
13
|
+
const serverCodecPromises = new Map<"development" | "production", Promise<ServerCodec>>();
|
|
13
14
|
|
|
14
15
|
export function resolveConfiguredCodecPath(configuredPath: string | undefined): string | undefined {
|
|
15
16
|
if (configuredPath === undefined || configuredPath.trim() === "") {
|
|
@@ -31,11 +32,13 @@ export function resolveBuiltCodecPath(
|
|
|
31
32
|
}
|
|
32
33
|
|
|
33
34
|
function loadServerCodec(): Promise<ServerCodec> {
|
|
34
|
-
|
|
35
|
-
|
|
35
|
+
const mode = isProductionBuild() ? "production" : "development";
|
|
36
|
+
const existing = serverCodecPromises.get(mode);
|
|
37
|
+
if (existing !== undefined) {
|
|
38
|
+
return existing;
|
|
36
39
|
}
|
|
37
40
|
|
|
38
|
-
|
|
41
|
+
const codecPromise = (async () => {
|
|
39
42
|
const configuredCodecPath = resolveConfiguredCodecPath(process.env.FURIN_RSC_CODEC_PATH);
|
|
40
43
|
if (configuredCodecPath !== undefined) {
|
|
41
44
|
return import(pathToFileURL(configuredCodecPath).href) as Promise<ServerCodec>;
|
|
@@ -44,7 +47,7 @@ function loadServerCodec(): Promise<ServerCodec> {
|
|
|
44
47
|
if (builtCodecPath !== undefined) {
|
|
45
48
|
return import(pathToFileURL(builtCodecPath).href) as Promise<ServerCodec>;
|
|
46
49
|
}
|
|
47
|
-
const outdir = join(tmpdir(), `furin-rsc-${process.pid}-${Bun.hash(import.meta.url)}`);
|
|
50
|
+
const outdir = join(tmpdir(), `furin-rsc-${process.pid}-${Bun.hash(import.meta.url)}-${mode}`);
|
|
48
51
|
mkdirSync(outdir, { recursive: true });
|
|
49
52
|
const sourcePath = join(import.meta.dir, "server-codec.ts");
|
|
50
53
|
if (!existsSync(sourcePath)) {
|
|
@@ -54,6 +57,7 @@ function loadServerCodec(): Promise<ServerCodec> {
|
|
|
54
57
|
}
|
|
55
58
|
const result = await Bun.build({
|
|
56
59
|
conditions: ["react-server"],
|
|
60
|
+
define: { "process.env.NODE_ENV": JSON.stringify(mode) },
|
|
57
61
|
entrypoints: [sourcePath],
|
|
58
62
|
format: "esm",
|
|
59
63
|
minify: false,
|
|
@@ -72,7 +76,8 @@ function loadServerCodec(): Promise<ServerCodec> {
|
|
|
72
76
|
return import(pathToFileURL(output.path).href) as Promise<ServerCodec>;
|
|
73
77
|
})();
|
|
74
78
|
|
|
75
|
-
|
|
79
|
+
serverCodecPromises.set(mode, codecPromise);
|
|
80
|
+
return codecPromise;
|
|
76
81
|
}
|
|
77
82
|
|
|
78
83
|
export async function encodeFlight(
|
package/src/rsc/render-error.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { isProductionBuild } from "../shared/production-build.ts";
|
|
2
|
+
|
|
1
3
|
export type RscRenderOperation = "createCompositeComponent" | "renderServerComponent";
|
|
2
4
|
|
|
3
5
|
interface FurinRscRenderErrorOptions {
|
|
@@ -53,7 +55,7 @@ function detectComponent(error: unknown, hook: string | undefined): string | und
|
|
|
53
55
|
}
|
|
54
56
|
|
|
55
57
|
function renderErrorMessage(options: FurinRscRenderErrorOptions): string {
|
|
56
|
-
if (
|
|
58
|
+
if (isProductionBuild()) {
|
|
57
59
|
return `[furin/rsc] Server Component rendering failed inside ${options.operation}().`;
|
|
58
60
|
}
|
|
59
61
|
if (options.hook !== undefined && options.component !== undefined) {
|
|
@@ -9,6 +9,7 @@ import { forbiddenDevelopmentRequest } from "../dev/request-security.ts";
|
|
|
9
9
|
import { IS_DEV } from "../runtime-env.ts";
|
|
10
10
|
import type { FurinSyncOptions } from "../sync/config.ts";
|
|
11
11
|
import { subscribeSyncCursor } from "../sync/stream.ts";
|
|
12
|
+
import { registerBrowserEventConnection, unregisterBrowserEventConnection } from "./shutdown.ts";
|
|
12
13
|
import type { BrowserEventSource, BrowserEventSubscription } from "./types.ts";
|
|
13
14
|
|
|
14
15
|
const CLIENT_PATH = "/_furin/events/client.js";
|
|
@@ -23,8 +24,10 @@ interface BrowserEventsPluginOptions {
|
|
|
23
24
|
}
|
|
24
25
|
|
|
25
26
|
interface ConnectionState {
|
|
27
|
+
close: () => void;
|
|
26
28
|
closed: boolean;
|
|
27
29
|
heartbeat: ReturnType<typeof setInterval>;
|
|
30
|
+
server: Bun.Server<unknown>;
|
|
28
31
|
subscriptions: BrowserEventSubscription[];
|
|
29
32
|
}
|
|
30
33
|
|
|
@@ -33,6 +36,7 @@ function releaseConnection(state: ConnectionState): void {
|
|
|
33
36
|
return;
|
|
34
37
|
}
|
|
35
38
|
state.closed = true;
|
|
39
|
+
unregisterBrowserEventConnection(state.server, state.close);
|
|
36
40
|
clearInterval(state.heartbeat);
|
|
37
41
|
for (const subscription of state.subscriptions) {
|
|
38
42
|
subscription.unsubscribe();
|
|
@@ -107,15 +111,18 @@ export function createBrowserEventsPlugin(options: BrowserEventsPluginOptions):
|
|
|
107
111
|
}
|
|
108
112
|
};
|
|
109
113
|
const state: ConnectionState = {
|
|
114
|
+
close: () => ws.close(1001, "Server shutting down"),
|
|
110
115
|
closed: false,
|
|
111
116
|
heartbeat: setInterval(
|
|
112
117
|
() => (ws as unknown as { ping: () => number }).ping(),
|
|
113
118
|
HEARTBEAT_INTERVAL_MS
|
|
114
119
|
),
|
|
120
|
+
server: ws.server as Bun.Server<unknown>,
|
|
115
121
|
subscriptions: [],
|
|
116
122
|
};
|
|
117
123
|
state.heartbeat.unref?.();
|
|
118
124
|
connections.set(ws.id, state);
|
|
125
|
+
registerBrowserEventConnection(state.server, state.close);
|
|
119
126
|
const keep = (subscription: BrowserEventSubscription): void => {
|
|
120
127
|
if (state.closed) {
|
|
121
128
|
subscription.unsubscribe();
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const closeConnections = new WeakMap<Bun.Server<unknown>, Set<() => void>>();
|
|
2
|
+
|
|
3
|
+
export function registerBrowserEventConnection(
|
|
4
|
+
server: Bun.Server<unknown>,
|
|
5
|
+
close: () => void
|
|
6
|
+
): void {
|
|
7
|
+
let connections = closeConnections.get(server);
|
|
8
|
+
if (!connections) {
|
|
9
|
+
connections = new Set();
|
|
10
|
+
closeConnections.set(server, connections);
|
|
11
|
+
}
|
|
12
|
+
connections.add(close);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function unregisterBrowserEventConnection(
|
|
16
|
+
server: Bun.Server<unknown>,
|
|
17
|
+
close: () => void
|
|
18
|
+
): void {
|
|
19
|
+
closeConnections.get(server)?.delete(close);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function closeBrowserEventConnections(server: Bun.Server<unknown>): void {
|
|
23
|
+
const connections = closeConnections.get(server);
|
|
24
|
+
if (!connections) {
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
closeConnections.delete(server);
|
|
28
|
+
for (const close of connections) {
|
|
29
|
+
close();
|
|
30
|
+
}
|
|
31
|
+
connections.clear();
|
|
32
|
+
}
|
|
@@ -181,6 +181,8 @@ export class RedisPageCache implements PageCacheAdapter {
|
|
|
181
181
|
this.leaseKey(identity),
|
|
182
182
|
this.fenceKey(identity),
|
|
183
183
|
this.versionsKey(identity.scope),
|
|
184
|
+
this.leasesKey(identity.scope),
|
|
185
|
+
...[...new Set(identity.tags)].map((tag) => this.tagLeasesKey(identity.scope, tag)),
|
|
184
186
|
];
|
|
185
187
|
const raw = await this.client.send("EVAL", [
|
|
186
188
|
ACQUIRE_PAGE_CACHE_LEASE_SCRIPT,
|
|
@@ -190,6 +192,8 @@ export class RedisPageCache implements PageCacheAdapter {
|
|
|
190
192
|
String(leaseMs),
|
|
191
193
|
JSON.stringify(selectorFields(identity)),
|
|
192
194
|
String(this.metadataRetentionMs),
|
|
195
|
+
identity.path,
|
|
196
|
+
JSON.stringify(identity.tags),
|
|
193
197
|
]);
|
|
194
198
|
if (raw === null) {
|
|
195
199
|
return null;
|
|
@@ -234,6 +238,7 @@ export class RedisPageCache implements PageCacheAdapter {
|
|
|
234
238
|
entryKey,
|
|
235
239
|
this.versionsKey(identity.scope),
|
|
236
240
|
pathsKey,
|
|
241
|
+
this.leasesKey(identity.scope),
|
|
237
242
|
...tagKeys,
|
|
238
243
|
];
|
|
239
244
|
const result = await this.client.send("EVAL", [
|
|
@@ -259,9 +264,10 @@ export class RedisPageCache implements PageCacheAdapter {
|
|
|
259
264
|
const result = stringArrayResult(
|
|
260
265
|
await this.client.send("EVAL", [
|
|
261
266
|
INVALIDATE_PAGE_CACHE_PATH_SCRIPT,
|
|
262
|
-
"
|
|
267
|
+
"3",
|
|
263
268
|
this.versionsKey(input.scope),
|
|
264
269
|
this.pathsKey(input.scope),
|
|
270
|
+
this.leasesKey(input.scope),
|
|
265
271
|
`${input.type}:${path}`,
|
|
266
272
|
path,
|
|
267
273
|
input.type,
|
|
@@ -276,7 +282,9 @@ export class RedisPageCache implements PageCacheAdapter {
|
|
|
276
282
|
const keys = [
|
|
277
283
|
this.versionsKey(input.scope),
|
|
278
284
|
this.pathsKey(input.scope),
|
|
285
|
+
this.leasesKey(input.scope),
|
|
279
286
|
...tags.map((tag) => this.tagPathsKey(input.scope, tag)),
|
|
287
|
+
...tags.map((tag) => this.tagLeasesKey(input.scope, tag)),
|
|
280
288
|
];
|
|
281
289
|
const result = stringArrayResult(
|
|
282
290
|
await this.client.send("EVAL", [
|
|
@@ -313,8 +321,9 @@ export class RedisPageCache implements PageCacheAdapter {
|
|
|
313
321
|
}): Promise<void> {
|
|
314
322
|
await this.client.send("EVAL", [
|
|
315
323
|
RELEASE_PAGE_CACHE_LEASE_SCRIPT,
|
|
316
|
-
"
|
|
324
|
+
"2",
|
|
317
325
|
this.leaseKey(identity),
|
|
326
|
+
this.leasesKey(identity.scope),
|
|
318
327
|
lease.id,
|
|
319
328
|
String(lease.fence),
|
|
320
329
|
]);
|
|
@@ -336,10 +345,18 @@ export class RedisPageCache implements PageCacheAdapter {
|
|
|
336
345
|
return `${this.prefix}:paths:${digest(scope)}`;
|
|
337
346
|
}
|
|
338
347
|
|
|
348
|
+
private leasesKey(scope: string): string {
|
|
349
|
+
return `${this.prefix}:leases:${digest(scope)}`;
|
|
350
|
+
}
|
|
351
|
+
|
|
339
352
|
private tagPathsKey(scope: string, tag: string): string {
|
|
340
353
|
return `${this.prefix}:tag-paths:${digest(scope)}:${digest(tag)}`;
|
|
341
354
|
}
|
|
342
355
|
|
|
356
|
+
private tagLeasesKey(scope: string, tag: string): string {
|
|
357
|
+
return `${this.prefix}:tag-leases:${digest(scope)}:${digest(tag)}`;
|
|
358
|
+
}
|
|
359
|
+
|
|
343
360
|
private versionsKey(scope: string): string {
|
|
344
361
|
return `${this.prefix}:versions:${digest(scope)}`;
|
|
345
362
|
}
|
|
@@ -5,6 +5,10 @@ local now = tonumber(now_parts[1]) * 1000 + math.floor(tonumber(now_parts[2]) /
|
|
|
5
5
|
if raw then
|
|
6
6
|
local active = cjson.decode(raw)
|
|
7
7
|
if active.expiresAt > now then return nil end
|
|
8
|
+
if active.indexMember then redis.call('ZREM', KEYS[4], active.indexMember) end
|
|
9
|
+
for _, key in ipairs(active.tagLeaseKeys or {}) do
|
|
10
|
+
redis.call('ZREM', key, active.indexMember)
|
|
11
|
+
end
|
|
8
12
|
end
|
|
9
13
|
local fence = redis.call('INCR', KEYS[2])
|
|
10
14
|
redis.call('PEXPIRE', KEYS[2], ARGV[4])
|
|
@@ -14,14 +18,26 @@ for index, field in ipairs(fields) do
|
|
|
14
18
|
values[index] = tonumber(redis.call('HGET', KEYS[3], field) or '0')
|
|
15
19
|
end
|
|
16
20
|
redis.call('PEXPIRE', KEYS[3], ARGV[4])
|
|
21
|
+
local tag_lease_keys = {}
|
|
22
|
+
for index = 5, #KEYS do table.insert(tag_lease_keys, KEYS[index]) end
|
|
17
23
|
local lease = {
|
|
24
|
+
tagLeaseKeys = tag_lease_keys,
|
|
18
25
|
expiresAt = now + tonumber(ARGV[2]),
|
|
19
26
|
fence = fence,
|
|
20
27
|
fields = fields,
|
|
21
28
|
id = ARGV[1],
|
|
29
|
+
indexMember = cjson.encode({id = ARGV[1], path = ARGV[5], tags = cjson.decode(ARGV[6])}),
|
|
22
30
|
values = values
|
|
23
31
|
}
|
|
24
32
|
redis.call('SET', KEYS[1], cjson.encode(lease), 'PX', ARGV[2])
|
|
33
|
+
redis.call('ZREMRANGEBYSCORE', KEYS[4], '-inf', now)
|
|
34
|
+
redis.call('ZADD', KEYS[4], lease.expiresAt, lease.indexMember)
|
|
35
|
+
redis.call('PEXPIRE', KEYS[4], ARGV[4])
|
|
36
|
+
for _, key in ipairs(tag_lease_keys) do
|
|
37
|
+
redis.call('ZREMRANGEBYSCORE', key, '-inf', now)
|
|
38
|
+
redis.call('ZADD', key, lease.expiresAt, lease.indexMember)
|
|
39
|
+
redis.call('PEXPIRE', key, ARGV[4])
|
|
40
|
+
end
|
|
25
41
|
return cjson.encode(lease)
|
|
26
42
|
`;
|
|
27
43
|
|
|
@@ -38,6 +54,8 @@ for index, field in ipairs(lease.fields) do
|
|
|
38
54
|
local current = tonumber(redis.call('HGET', KEYS[3], field) or '0')
|
|
39
55
|
if current ~= lease.values[index] then
|
|
40
56
|
redis.call('DEL', KEYS[1])
|
|
57
|
+
if lease.indexMember then redis.call('ZREM', KEYS[5], lease.indexMember) end
|
|
58
|
+
for _, key in ipairs(lease.tagLeaseKeys or {}) do redis.call('ZREM', key, lease.indexMember) end
|
|
41
59
|
return 'superseded'
|
|
42
60
|
end
|
|
43
61
|
end
|
|
@@ -56,13 +74,15 @@ redis.call('SET', KEYS[2], ARGV[3], 'PX', ARGV[5])
|
|
|
56
74
|
redis.call('ZREMRANGEBYSCORE', KEYS[4], '-inf', now)
|
|
57
75
|
redis.call('ZADD', KEYS[4], expires_at, ARGV[4])
|
|
58
76
|
redis.call('PEXPIRE', KEYS[4], ARGV[6])
|
|
59
|
-
for index =
|
|
77
|
+
for index = 6, #KEYS do
|
|
60
78
|
redis.call('ZREMRANGEBYSCORE', KEYS[index], '-inf', now)
|
|
61
79
|
redis.call('ZADD', KEYS[index], expires_at, ARGV[4])
|
|
62
80
|
redis.call('PEXPIRE', KEYS[index], ARGV[6])
|
|
63
81
|
end
|
|
64
82
|
redis.call('PEXPIRE', KEYS[3], ARGV[6])
|
|
65
83
|
redis.call('DEL', KEYS[1])
|
|
84
|
+
if lease.indexMember then redis.call('ZREM', KEYS[5], lease.indexMember) end
|
|
85
|
+
for _, key in ipairs(lease.tagLeaseKeys or {}) do redis.call('ZREM', key, lease.indexMember) end
|
|
66
86
|
return 'stored'
|
|
67
87
|
`;
|
|
68
88
|
|
|
@@ -91,6 +111,8 @@ local raw = redis.call('GET', KEYS[1])
|
|
|
91
111
|
if not raw then return 0 end
|
|
92
112
|
local lease = cjson.decode(raw)
|
|
93
113
|
if lease.id == ARGV[1] and lease.fence == tonumber(ARGV[2]) then
|
|
114
|
+
if lease.indexMember then redis.call('ZREM', KEYS[2], lease.indexMember) end
|
|
115
|
+
for _, key in ipairs(lease.tagLeaseKeys or {}) do redis.call('ZREM', key, lease.indexMember) end
|
|
94
116
|
return redis.call('DEL', KEYS[1])
|
|
95
117
|
end
|
|
96
118
|
return 0
|
|
@@ -105,13 +127,13 @@ redis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', now)
|
|
|
105
127
|
local members = redis.call('ZRANGE', KEYS[2], 0, -1)
|
|
106
128
|
local seen = {}
|
|
107
129
|
local affected = {}
|
|
130
|
+
local function matches_path(path)
|
|
131
|
+
if path == ARGV[2] then return true end
|
|
132
|
+
return ARGV[3] == 'layout' and (ARGV[2] == '/' or string.sub(path, 1, string.len(ARGV[2]) + 1) == ARGV[2] .. '/')
|
|
133
|
+
end
|
|
108
134
|
for _, member in ipairs(members) do
|
|
109
135
|
local index = cjson.decode(member)
|
|
110
|
-
|
|
111
|
-
if ARGV[3] == 'layout' and not matches then
|
|
112
|
-
matches = ARGV[2] == '/' or string.sub(index.path, 1, string.len(ARGV[2]) + 1) == ARGV[2] .. '/'
|
|
113
|
-
end
|
|
114
|
-
if matches then
|
|
136
|
+
if matches_path(index.path) then
|
|
115
137
|
redis.call('DEL', index.entryKey)
|
|
116
138
|
redis.call('ZREM', index.pathsKey, member)
|
|
117
139
|
for _, tag_key in ipairs(index.tagKeys) do
|
|
@@ -123,6 +145,14 @@ for _, member in ipairs(members) do
|
|
|
123
145
|
end
|
|
124
146
|
end
|
|
125
147
|
end
|
|
148
|
+
redis.call('ZREMRANGEBYSCORE', KEYS[3], '-inf', now)
|
|
149
|
+
for _, member in ipairs(redis.call('ZRANGE', KEYS[3], 0, -1)) do
|
|
150
|
+
local lease = cjson.decode(member)
|
|
151
|
+
if matches_path(lease.path) and not seen[lease.path] then
|
|
152
|
+
seen[lease.path] = true
|
|
153
|
+
table.insert(affected, lease.path)
|
|
154
|
+
end
|
|
155
|
+
end
|
|
126
156
|
return affected
|
|
127
157
|
`;
|
|
128
158
|
|
|
@@ -137,7 +167,7 @@ local now = tonumber(now_parts[1]) * 1000 + math.floor(tonumber(now_parts[2]) /
|
|
|
137
167
|
local seen_members = {}
|
|
138
168
|
local seen_paths = {}
|
|
139
169
|
local affected = {}
|
|
140
|
-
for key_index =
|
|
170
|
+
for key_index = 4, 3 + #tags do
|
|
141
171
|
redis.call('ZREMRANGEBYSCORE', KEYS[key_index], '-inf', now)
|
|
142
172
|
local members = redis.call('ZRANGE', KEYS[key_index], 0, -1)
|
|
143
173
|
for _, member in ipairs(members) do
|
|
@@ -156,5 +186,15 @@ for key_index = 3, #KEYS do
|
|
|
156
186
|
end
|
|
157
187
|
end
|
|
158
188
|
end
|
|
189
|
+
for key_index = 4 + #tags, #KEYS do
|
|
190
|
+
redis.call('ZREMRANGEBYSCORE', KEYS[key_index], '-inf', now)
|
|
191
|
+
for _, member in ipairs(redis.call('ZRANGE', KEYS[key_index], 0, -1)) do
|
|
192
|
+
local lease = cjson.decode(member)
|
|
193
|
+
if not seen_paths[lease.path] then
|
|
194
|
+
seen_paths[lease.path] = true
|
|
195
|
+
table.insert(affected, lease.path)
|
|
196
|
+
end
|
|
197
|
+
end
|
|
198
|
+
end
|
|
159
199
|
return affected
|
|
160
200
|
`;
|
package/src/server/dev/plugin.ts
CHANGED
|
@@ -14,6 +14,15 @@ interface EmbeddedDiagnosticState {
|
|
|
14
14
|
event: Extract<DevDiagnosticEvent, { type: "error" }>;
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
+
export const extensionErrorFilterScript = `window.addEventListener("unhandledrejection", (event) => {
|
|
18
|
+
const stack = event.reason?.stack;
|
|
19
|
+
if (typeof stack !== "string") return;
|
|
20
|
+
const firstFrame = stack.match(/^(?:\\s*at [^\\n]*|[^\\n]*@[^\\n]*)/m)?.[0];
|
|
21
|
+
if (firstFrame && /\\b(?:chrome|moz)-extension:\\/\\//.test(firstFrame)) {
|
|
22
|
+
event.stopImmediatePropagation();
|
|
23
|
+
}
|
|
24
|
+
}, true);`;
|
|
25
|
+
|
|
17
26
|
let overlayClientSource: string | undefined;
|
|
18
27
|
|
|
19
28
|
async function clientSource(): Promise<string> {
|
|
@@ -118,7 +127,7 @@ export function renderDevDiagnosticResponse(
|
|
|
118
127
|
): Response {
|
|
119
128
|
const state = serializeForHtml({ basePath, event });
|
|
120
129
|
return new Response(
|
|
121
|
-
`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Furin development error</title>${browserEventsClientScript(basePath)}</head><body><script id="__FURIN_DEV_DIAGNOSTIC__" type="application/json">${state}</script><script type="module" src="${basePath}/_furin/dev/overlay.js"></script></body></html>`,
|
|
130
|
+
`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Furin development error</title><script data-furin-extension-error-filter="">${extensionErrorFilterScript}</script>${browserEventsClientScript(basePath)}</head><body><script id="__FURIN_DEV_DIAGNOSTIC__" type="application/json">${state}</script><script type="module" src="${basePath}/_furin/dev/overlay.js"></script></body></html>`,
|
|
122
131
|
{
|
|
123
132
|
headers: {
|
|
124
133
|
"cache-control": "no-store",
|
package/src/server/evlog.ts
CHANGED
|
@@ -35,12 +35,13 @@ export type FurinEvlogOptions = BaseEvlogOptions;
|
|
|
35
35
|
|
|
36
36
|
export const getRequestLogger = loggerStorage.useLogger;
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
const runtimeWaitUntil = new Set<NonNullable<FurinEvlogOptions["waitUntil"]>>();
|
|
39
39
|
|
|
40
40
|
export function setRuntimeEvlogWaitUntil(
|
|
41
41
|
waitUntil: NonNullable<FurinEvlogOptions["waitUntil"]>
|
|
42
|
-
): void {
|
|
43
|
-
runtimeWaitUntil
|
|
42
|
+
): () => void {
|
|
43
|
+
runtimeWaitUntil.add(waitUntil);
|
|
44
|
+
return () => runtimeWaitUntil.delete(waitUntil);
|
|
44
45
|
}
|
|
45
46
|
|
|
46
47
|
/** Elysia 2-native evlog integration built on evlog's public adapter toolkit. */
|
|
@@ -85,7 +86,13 @@ export function createFurinEvlog(options: FurinEvlogOptions) {
|
|
|
85
86
|
});
|
|
86
87
|
// Register before the Vercel request context closes, even though the
|
|
87
88
|
// emission itself starts after this response is returned.
|
|
88
|
-
(options.waitUntil
|
|
89
|
+
if (options.waitUntil) {
|
|
90
|
+
options.waitUntil(emission);
|
|
91
|
+
} else {
|
|
92
|
+
for (const waitUntil of runtimeWaitUntil) {
|
|
93
|
+
waitUntil(emission);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
89
96
|
return response;
|
|
90
97
|
} catch (error) {
|
|
91
98
|
await handle.finish({
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import type { AnyElysia } from "elysia";
|
|
2
|
+
import { closeBrowserEventConnections } from "./browser-events/shutdown.ts";
|
|
3
|
+
import { waitForPendingISRRevalidations } from "./cache/isr.ts";
|
|
4
|
+
import { setRuntimeEvlogWaitUntil } from "./evlog.ts";
|
|
5
|
+
import { closeSyncCursorStates, waitForSyncCursorUnsubscriptions } from "./sync/stream.ts";
|
|
6
|
+
|
|
7
|
+
const DEFAULT_PRE_STOP_DELAY_MS = 5000;
|
|
8
|
+
const DEFAULT_SHUTDOWN_TIMEOUT_MS = 30_000;
|
|
9
|
+
const activeShutdowns = new Set<() => Promise<void>>();
|
|
10
|
+
const syncDrainsReached = new Set<() => Promise<void>>();
|
|
11
|
+
|
|
12
|
+
const signalShutdown = (): void => {
|
|
13
|
+
Promise.allSettled([...activeShutdowns].map((shutdown) => shutdown())).then((results) => {
|
|
14
|
+
let code = process.exitCode ?? 0;
|
|
15
|
+
for (const result of results) {
|
|
16
|
+
if (result.status === "rejected") {
|
|
17
|
+
console.error("[furin] Graceful shutdown failed", result.reason);
|
|
18
|
+
code = 1;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
process.exit(code);
|
|
22
|
+
});
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export interface ProductionServerOptions {
|
|
26
|
+
app: AnyElysia;
|
|
27
|
+
idleTimeout?: number;
|
|
28
|
+
onShutdown?: () => Promise<void> | void;
|
|
29
|
+
port: number;
|
|
30
|
+
preStopDelayMs?: number;
|
|
31
|
+
shutdownTimeoutMs?: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function startProductionServer(options: ProductionServerOptions): {
|
|
35
|
+
server: Bun.Server<unknown>;
|
|
36
|
+
shutdown: () => Promise<void>;
|
|
37
|
+
} {
|
|
38
|
+
const { app } = options;
|
|
39
|
+
const pendingEmissions = new Set<Promise<unknown>>();
|
|
40
|
+
let draining = false;
|
|
41
|
+
let rejecting = false;
|
|
42
|
+
|
|
43
|
+
const unregisterWaitUntil = setRuntimeEvlogWaitUntil((emission) => {
|
|
44
|
+
pendingEmissions.add(emission);
|
|
45
|
+
emission.finally(() => pendingEmissions.delete(emission)).catch(() => undefined);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
app
|
|
49
|
+
.wrap((fetch) => (request, ...rest) => {
|
|
50
|
+
const path = new URL(request.url).pathname;
|
|
51
|
+
if (rejecting && path !== "/_furin/health/live" && path !== "/_furin/health/ready") {
|
|
52
|
+
return Promise.resolve(new Response("Service Unavailable", { status: 503 }));
|
|
53
|
+
}
|
|
54
|
+
return fetch(request, ...rest);
|
|
55
|
+
})
|
|
56
|
+
.get("/_furin/health/live", () =>
|
|
57
|
+
Response.json({ status: "alive" }, { headers: { "cache-control": "no-store" } })
|
|
58
|
+
)
|
|
59
|
+
.get("/_furin/health/ready", () =>
|
|
60
|
+
Response.json(
|
|
61
|
+
{ status: draining ? "draining" : "ready" },
|
|
62
|
+
{ headers: { "cache-control": "no-store" }, status: draining ? 503 : 200 }
|
|
63
|
+
)
|
|
64
|
+
);
|
|
65
|
+
|
|
66
|
+
app.listen(
|
|
67
|
+
options.idleTimeout === undefined
|
|
68
|
+
? options.port
|
|
69
|
+
: { idleTimeout: options.idleTimeout, port: options.port }
|
|
70
|
+
);
|
|
71
|
+
const { server } = app;
|
|
72
|
+
if (!server) {
|
|
73
|
+
throw new Error("[furin] Bun server did not start");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
let shutdownPromise: Promise<void> | undefined;
|
|
77
|
+
const shutdown = (): Promise<void> => {
|
|
78
|
+
if (shutdownPromise) {
|
|
79
|
+
return shutdownPromise;
|
|
80
|
+
}
|
|
81
|
+
draining = true;
|
|
82
|
+
const timeoutMs = options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;
|
|
83
|
+
const delayMs = options.preStopDelayMs ?? DEFAULT_PRE_STOP_DELAY_MS;
|
|
84
|
+
shutdownPromise = (async () => {
|
|
85
|
+
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
86
|
+
try {
|
|
87
|
+
await Bun.sleep(delayMs);
|
|
88
|
+
rejecting = true;
|
|
89
|
+
const deadline = new Promise<void>((resolve) => {
|
|
90
|
+
timeout = setTimeout(() => {
|
|
91
|
+
console.error("[furin] Shutdown deadline exceeded; forcing server stop");
|
|
92
|
+
server.stop(true).catch((error: unknown) => {
|
|
93
|
+
console.error("[furin] Forced server stop failed", error);
|
|
94
|
+
});
|
|
95
|
+
resolve();
|
|
96
|
+
}, timeoutMs);
|
|
97
|
+
});
|
|
98
|
+
const drain = async (): Promise<void> => {
|
|
99
|
+
closeBrowserEventConnections(server);
|
|
100
|
+
server.closeIdleConnections();
|
|
101
|
+
await server.stop();
|
|
102
|
+
await waitForPendingISRRevalidations();
|
|
103
|
+
await Promise.allSettled([...pendingEmissions]);
|
|
104
|
+
syncDrainsReached.add(shutdown);
|
|
105
|
+
if (syncDrainsReached.size === activeShutdowns.size) {
|
|
106
|
+
await closeSyncCursorStates();
|
|
107
|
+
} else {
|
|
108
|
+
await waitForSyncCursorUnsubscriptions();
|
|
109
|
+
}
|
|
110
|
+
await options.onShutdown?.();
|
|
111
|
+
};
|
|
112
|
+
await Promise.race([drain(), deadline]);
|
|
113
|
+
} finally {
|
|
114
|
+
if (timeout) {
|
|
115
|
+
clearTimeout(timeout);
|
|
116
|
+
}
|
|
117
|
+
activeShutdowns.delete(shutdown);
|
|
118
|
+
syncDrainsReached.delete(shutdown);
|
|
119
|
+
if (activeShutdowns.size === 0) {
|
|
120
|
+
process.off("SIGTERM", signalShutdown);
|
|
121
|
+
process.off("SIGINT", signalShutdown);
|
|
122
|
+
}
|
|
123
|
+
unregisterWaitUntil();
|
|
124
|
+
}
|
|
125
|
+
})();
|
|
126
|
+
return shutdownPromise;
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
if (activeShutdowns.size === 0) {
|
|
130
|
+
process.on("SIGTERM", signalShutdown);
|
|
131
|
+
process.on("SIGINT", signalShutdown);
|
|
132
|
+
}
|
|
133
|
+
activeShutdowns.add(shutdown);
|
|
134
|
+
return { server, shutdown };
|
|
135
|
+
}
|
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
type DocumentState,
|
|
6
6
|
} from "../../client/document.tsx";
|
|
7
7
|
import type { HeadOptions } from "../../client.ts";
|
|
8
|
+
import { containsRscSource, serializeRouteFrames } from "../../shared/route-frame.ts";
|
|
8
9
|
import { currentInstance } from "../instance.ts";
|
|
9
10
|
import { getSyncPath } from "../sync/config.ts";
|
|
10
11
|
import { safeJson } from "./shell.ts";
|
|
@@ -24,10 +25,15 @@ export function withDocumentState(
|
|
|
24
25
|
...assets,
|
|
25
26
|
frameworkModules: [browserEventsClientPath, ...assets.frameworkModules],
|
|
26
27
|
};
|
|
28
|
+
const routeFrames =
|
|
29
|
+
data !== undefined && containsRscSource(data)
|
|
30
|
+
? serializeRouteFrames(data, undefined)
|
|
31
|
+
: undefined;
|
|
27
32
|
const state: DocumentState = {
|
|
28
33
|
assets: resolvedAssets,
|
|
29
|
-
dataJson: data === undefined ? undefined : safeJson(data),
|
|
34
|
+
dataJson: data === undefined || routeFrames !== undefined ? undefined : safeJson(data),
|
|
30
35
|
head,
|
|
36
|
+
routeFrames,
|
|
31
37
|
syncJson: syncPath === undefined ? undefined : safeJson({ path: syncPath }),
|
|
32
38
|
};
|
|
33
39
|
return createElement(DocumentProvider, { value: state }, element);
|