@krate/runtime 0.5.0-beta.1 → 0.5.0-beta.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/actions.js +2 -1
- package/dist/assets-static.d.ts +5 -0
- package/dist/assets-static.js +31 -0
- package/dist/boundary.d.ts +12 -0
- package/dist/boundary.js +53 -13
- package/dist/cache-adapter.d.ts +113 -0
- package/dist/cache-adapter.js +217 -0
- package/dist/cache-adapter.test.d.ts +1 -0
- package/dist/cache-adapter.test.js +244 -0
- package/dist/cache-redis.d.ts +27 -0
- package/dist/cache-redis.js +110 -0
- package/dist/cache-scope.d.ts +25 -9
- package/dist/cache-scope.js +60 -12
- package/dist/cache.d.ts +1 -0
- package/dist/cache.js +3 -3
- package/dist/class-component.js +6 -0
- package/dist/class-component.test.js +53 -2
- package/dist/dev-overlay.js +10 -10
- package/dist/dom.d.ts +8 -0
- package/dist/dom.js +28 -0
- package/dist/effect-errors.test.d.ts +1 -0
- package/dist/effect-errors.test.js +163 -0
- package/dist/effects.d.ts +8 -0
- package/dist/effects.js +13 -0
- package/dist/error-overlay.js +4 -4
- package/dist/handler-html.d.ts +63 -0
- package/dist/handler-html.js +285 -0
- package/dist/handler-html.test.d.ts +1 -0
- package/dist/handler-html.test.js +256 -0
- package/dist/handler-routing.d.ts +83 -0
- package/dist/handler-routing.js +579 -0
- package/dist/handler-routing.test.d.ts +1 -0
- package/dist/handler-routing.test.js +99 -0
- package/dist/handler-segments.d.ts +43 -0
- package/dist/handler-segments.js +115 -0
- package/dist/handler-segments.test.d.ts +1 -0
- package/dist/handler-segments.test.js +217 -0
- package/dist/head-tags.d.ts +51 -0
- package/dist/head-tags.js +329 -0
- package/dist/head-tags.test.d.ts +1 -0
- package/dist/head-tags.test.js +131 -0
- package/dist/highlight-bind.d.ts +42 -0
- package/dist/highlight-bind.js +176 -0
- package/dist/highlight-bind.test.d.ts +1 -0
- package/dist/highlight-bind.test.js +124 -0
- package/dist/highlight.d.ts +93 -0
- package/dist/highlight.js +426 -0
- package/dist/highlight.test.d.ts +1 -0
- package/dist/highlight.test.js +56 -0
- package/dist/hints.d.ts +19 -0
- package/dist/hints.js +97 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/jsx-types.d.ts +11 -0
- package/dist/krate-core.js +1 -1
- package/dist/krate-dev.js +10 -10
- package/dist/krate-f-actions.js +1 -1
- package/dist/krate-f-classes.js +5 -5
- package/dist/krate-f-highlight.js +2 -0
- package/dist/krate-f-list.js +1 -1
- package/dist/krate-f-navigation.js +2 -0
- package/dist/krate-f-router.js +1 -1
- package/dist/krate-features.json +254 -0
- package/dist/krate-hydrate-lite.js +5 -5
- package/dist/krate-hydrate.js +5 -5
- package/dist/krate-runtime.js +5 -5
- package/dist/list.js +4 -2
- package/dist/metadata-routes.d.ts +75 -0
- package/dist/metadata-routes.js +76 -0
- package/dist/metadata.d.ts +222 -0
- package/dist/metadata.js +452 -0
- package/dist/metadata.test.d.ts +1 -0
- package/dist/metadata.test.js +167 -0
- package/dist/navigation-server.d.ts +27 -0
- package/dist/navigation-server.js +90 -0
- package/dist/navigation.d.ts +37 -0
- package/dist/navigation.js +195 -0
- package/dist/navigation.test.d.ts +1 -0
- package/dist/navigation.test.js +130 -0
- package/dist/node-server.d.ts +22 -0
- package/dist/node-server.js +436 -0
- package/dist/node-server.test.d.ts +1 -0
- package/dist/node-server.test.js +492 -0
- package/dist/og-files.d.ts +2 -0
- package/dist/og-files.js +19 -0
- package/dist/og.d.ts +56 -0
- package/dist/og.js +156 -0
- package/dist/react.d.ts +47 -0
- package/dist/react.js +59 -1
- package/dist/react19.test.d.ts +1 -0
- package/dist/react19.test.js +176 -0
- package/dist/request-context.d.ts +23 -0
- package/dist/request-context.js +45 -0
- package/dist/resp.d.ts +55 -0
- package/dist/resp.js +239 -0
- package/dist/router-layout.test.js +70 -0
- package/dist/router-nav.test.js +27 -0
- package/dist/router.js +59 -4
- package/dist/segmented-lru.d.ts +19 -0
- package/dist/segmented-lru.js +87 -0
- package/dist/server-async.test.js +23 -1
- package/dist/server-handler.d.ts +165 -0
- package/dist/server-handler.js +1826 -0
- package/dist/server-handler.test.d.ts +1 -0
- package/dist/server-handler.test.js +522 -0
- package/dist/server-highlight.test.d.ts +1 -0
- package/dist/server-highlight.test.js +32 -0
- package/dist/server-renderer.js +146 -788
- package/dist/server-renderer.test.d.ts +1 -0
- package/dist/server-renderer.test.js +266 -0
- package/dist/server.d.ts +12 -1
- package/dist/server.js +42 -6
- package/dist/sha256.d.ts +1 -0
- package/dist/sha256.js +66 -0
- package/dist/sha256.test.d.ts +1 -0
- package/dist/sha256.test.js +13 -0
- package/dist/shared-isr.d.ts +31 -0
- package/dist/shared-isr.js +142 -0
- package/dist/signal.js +63 -8
- package/dist/ssr-core-behavior.test.d.ts +1 -0
- package/dist/ssr-core-behavior.test.js +620 -0
- package/dist/ssr-core.d.ts +175 -0
- package/dist/ssr-core.js +940 -0
- package/dist/ssr-core.test.d.ts +1 -0
- package/dist/ssr-core.test.js +324 -0
- package/dist/static-memory.d.ts +3 -0
- package/dist/static-memory.js +47 -0
- package/dist/static-memory.test.d.ts +1 -0
- package/dist/static-memory.test.js +26 -0
- package/dist/test-redis.d.ts +12 -0
- package/dist/test-redis.js +131 -0
- package/dist/use-id.d.ts +8 -0
- package/dist/use-id.js +40 -0
- package/package.json +29 -1
package/dist/actions.js
CHANGED
|
@@ -479,7 +479,8 @@ export function installActionForms(doc = typeof document !== 'undefined' ? docum
|
|
|
479
479
|
// Flash state from native form posts
|
|
480
480
|
function decodeFlash(value) {
|
|
481
481
|
try {
|
|
482
|
-
|
|
482
|
+
// The server signs the cookie as "<payload>.<signature>"; only the payload decodes.
|
|
483
|
+
const raw = value.split('.')[0].replace(/-/g, '+').replace(/_/g, '/');
|
|
483
484
|
const bin = atob(raw + '='.repeat((4 - (raw.length % 4)) % 4));
|
|
484
485
|
return JSON.parse(decodeURIComponent(escape(bin)));
|
|
485
486
|
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// A StaticLayer backed by a platform asset fetcher (Cloudflare's env.ASSETS).
|
|
2
|
+
// Used when the Worker runs first and falls through to the uploaded assets.
|
|
3
|
+
import { extName } from "./handler-routing.js";
|
|
4
|
+
export function createAssetsStaticLayer(assets) {
|
|
5
|
+
const probe = async (url, path) => {
|
|
6
|
+
const u = new URL(url);
|
|
7
|
+
u.pathname = path;
|
|
8
|
+
u.search = "";
|
|
9
|
+
const res = await assets.fetch(new Request(u.toString(), { method: "HEAD", redirect: "manual" }));
|
|
10
|
+
return res.status !== 404;
|
|
11
|
+
};
|
|
12
|
+
let origin = "https://assets.invalid";
|
|
13
|
+
return {
|
|
14
|
+
async exists(urlPath) {
|
|
15
|
+
const rel = urlPath.replace(/^\/+|\/+$/g, "");
|
|
16
|
+
return (await probe(origin + "/", rel === "" ? "/index.html" : "/" + rel)) || (rel !== "" && (await probe(origin + "/", "/" + rel + "/index.html")));
|
|
17
|
+
},
|
|
18
|
+
async isAsset(urlPath) {
|
|
19
|
+
const ext = extName(urlPath).toLowerCase();
|
|
20
|
+
if (ext === "" || ext === ".html")
|
|
21
|
+
return false;
|
|
22
|
+
return probe(origin + "/", urlPath);
|
|
23
|
+
},
|
|
24
|
+
async serve(request, urlPath) {
|
|
25
|
+
origin = new URL(request.url).origin;
|
|
26
|
+
void urlPath;
|
|
27
|
+
const res = await assets.fetch(request);
|
|
28
|
+
return res.status === 404 ? null : res;
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
}
|
package/dist/boundary.d.ts
CHANGED
|
@@ -38,6 +38,11 @@ export interface Owner {
|
|
|
38
38
|
readonly setup: (() => void) | null;
|
|
39
39
|
/** Free-form per-owner storage (class instances live here). */
|
|
40
40
|
readonly data: Record<string, unknown>;
|
|
41
|
+
/**
|
|
42
|
+
* Route scope (layout/template id) whose hydration created the owner, null for
|
|
43
|
+
* page code. A soft navigation that keeps a layout keeps its owners.
|
|
44
|
+
*/
|
|
45
|
+
readonly scope: string | null;
|
|
41
46
|
}
|
|
42
47
|
/** The owner whose code is running, or null. */
|
|
43
48
|
export declare function getOwner(): Owner | null;
|
|
@@ -71,6 +76,13 @@ export declare function handleError(thrown: unknown, source?: Owner | null): voi
|
|
|
71
76
|
* be mounted again by running their setup.
|
|
72
77
|
*/
|
|
73
78
|
export declare function unmountOwner(owner: Owner): void;
|
|
79
|
+
/**
|
|
80
|
+
* Reports whether an error boundary created under route scope `scope` is
|
|
81
|
+
* showing its fallback. The SPA router asks before it keeps such a boundary
|
|
82
|
+
* across a soft navigation: a failed boundary is not kept, so navigating clears
|
|
83
|
+
* the error.
|
|
84
|
+
*/
|
|
85
|
+
export declare function krateScopeFailed(scope: string): boolean;
|
|
74
86
|
/** Mounts a dormant owner (and its mountable descendants). */
|
|
75
87
|
export declare function mountOwner(owner: Owner): void;
|
|
76
88
|
/** Unmounts every child of owner (an error boundary dropping its subtree). */
|
package/dist/boundary.js
CHANGED
|
@@ -14,14 +14,13 @@
|
|
|
14
14
|
// unmounted (its cleanups run) when it is swapped out, so componentDidMount /
|
|
15
15
|
// componentWillUnmount and state resets match React. A dormant owner keeps its
|
|
16
16
|
// setup function and is remounted by running it again.
|
|
17
|
-
import { setOwnerHooks, untrack,
|
|
17
|
+
import { setOwnerHooks, untrack, krateGetOwner, krateSetOwner, krateCurrentScope, krateOnDispose, krateScopeOfId } from './signal.js';
|
|
18
18
|
import { krateForgetOwner, krateOnHookError } from './effects.js';
|
|
19
19
|
let current = null;
|
|
20
20
|
let nextOrder = 0;
|
|
21
21
|
const byId = new Map();
|
|
22
22
|
const condState = new Map();
|
|
23
23
|
const condOwners = new Map();
|
|
24
|
-
let resetRegistered = false;
|
|
25
24
|
let mountDepth = 0;
|
|
26
25
|
const deferredMounts = [];
|
|
27
26
|
function makeOwner(id, name, parent, creator, cond, branch, setup) {
|
|
@@ -40,6 +39,7 @@ function makeOwner(id, name, parent, creator, cond, branch, setup) {
|
|
|
40
39
|
branch,
|
|
41
40
|
setup,
|
|
42
41
|
data: {},
|
|
42
|
+
scope: krateCurrentScope(),
|
|
43
43
|
cleanups: [],
|
|
44
44
|
};
|
|
45
45
|
if (parent)
|
|
@@ -57,8 +57,6 @@ export function getOwner() {
|
|
|
57
57
|
export function createOwner(name, parent = current) {
|
|
58
58
|
const o = makeOwner('', name, parent || null, parent || null, '', '', null);
|
|
59
59
|
o.state = parent && parent.state !== 'mounted' ? 'dormant' : 'mounted';
|
|
60
|
-
if (!parent)
|
|
61
|
-
registerReset();
|
|
62
60
|
return o;
|
|
63
61
|
}
|
|
64
62
|
/**
|
|
@@ -178,6 +176,19 @@ function reportUncaughtLoose(err) {
|
|
|
178
176
|
export function unmountOwner(owner) {
|
|
179
177
|
disposeTree(owner, 'dormant');
|
|
180
178
|
}
|
|
179
|
+
/**
|
|
180
|
+
* Reports whether an error boundary created under route scope `scope` is
|
|
181
|
+
* showing its fallback. The SPA router asks before it keeps such a boundary
|
|
182
|
+
* across a soft navigation: a failed boundary is not kept, so navigating clears
|
|
183
|
+
* the error.
|
|
184
|
+
*/
|
|
185
|
+
export function krateScopeFailed(scope) {
|
|
186
|
+
for (const o of byId.values()) {
|
|
187
|
+
if (o.scope === scope && o.inError)
|
|
188
|
+
return true;
|
|
189
|
+
}
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
181
192
|
/** Mounts a dormant owner (and its mountable descendants). */
|
|
182
193
|
export function mountOwner(owner) {
|
|
183
194
|
const o = owner;
|
|
@@ -284,13 +295,15 @@ function mount(o) {
|
|
|
284
295
|
}
|
|
285
296
|
}
|
|
286
297
|
}
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
298
|
+
// Page teardown (SPA navigation). A full teardown drops every owner; a partial
|
|
299
|
+
// one, which keeps some layouts mounted, drops only the owners whose route scope
|
|
300
|
+
// is gone and leaves the kept layouts' owners (and their lifecycles) alone.
|
|
301
|
+
krateOnDispose((gone) => {
|
|
302
|
+
if (gone === null)
|
|
303
|
+
resetOwners();
|
|
304
|
+
else
|
|
305
|
+
disposeScopedOwners(gone);
|
|
306
|
+
});
|
|
294
307
|
function resetOwners() {
|
|
295
308
|
const roots = [];
|
|
296
309
|
for (const o of byId.values())
|
|
@@ -302,7 +315,35 @@ function resetOwners() {
|
|
|
302
315
|
condState.clear();
|
|
303
316
|
condOwners.clear();
|
|
304
317
|
deferredMounts.length = 0;
|
|
305
|
-
|
|
318
|
+
}
|
|
319
|
+
function disposeScopedOwners(gone) {
|
|
320
|
+
const dead = [];
|
|
321
|
+
for (const o of byId.values())
|
|
322
|
+
if (gone(o.scope))
|
|
323
|
+
dead.push(o);
|
|
324
|
+
for (const o of dead) {
|
|
325
|
+
if (o.state !== 'disposed')
|
|
326
|
+
disposeTree(o, 'disposed');
|
|
327
|
+
}
|
|
328
|
+
for (const o of dead) {
|
|
329
|
+
byId.delete(o.id);
|
|
330
|
+
const p = o.parent;
|
|
331
|
+
if (p && !gone(p.scope)) {
|
|
332
|
+
const i = p.children.indexOf(o);
|
|
333
|
+
if (i >= 0)
|
|
334
|
+
p.children.splice(i, 1);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
for (const id of Array.from(condState.keys())) {
|
|
338
|
+
if (gone(krateScopeOfId(id))) {
|
|
339
|
+
condState.delete(id);
|
|
340
|
+
condOwners.delete(id);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
for (let i = deferredMounts.length - 1; i >= 0; i--) {
|
|
344
|
+
if (deferredMounts[i].state === 'disposed')
|
|
345
|
+
deferredMounts.splice(i, 1);
|
|
346
|
+
}
|
|
306
347
|
}
|
|
307
348
|
/**
|
|
308
349
|
* Hydration entry point: the compiler wraps each component's hydration scope
|
|
@@ -318,7 +359,6 @@ export function __krateOwn(id, meta, setup) {
|
|
|
318
359
|
const creator = (m.k && byId.get(m.k)) || null;
|
|
319
360
|
const o = makeOwner(id, m.n || id, parent, creator, m.c || '', m.b || '', setup);
|
|
320
361
|
byId.set(id, o);
|
|
321
|
-
registerReset();
|
|
322
362
|
if (o.cond) {
|
|
323
363
|
let list = condOwners.get(o.cond);
|
|
324
364
|
if (!list) {
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { type SharedDataStore } from './cache-scope.js';
|
|
2
|
+
export interface CacheSetOptions {
|
|
3
|
+
/** Seconds to keep the entry; omitted or Infinity keeps it until it is deleted. */
|
|
4
|
+
ttlSeconds?: number;
|
|
5
|
+
/** Tags the entry can be deleted by (deleteByTags). */
|
|
6
|
+
tags?: string[];
|
|
7
|
+
}
|
|
8
|
+
/** The storage contract of a shared cache. Every method may reject; callers cope. */
|
|
9
|
+
export interface CacheAdapter {
|
|
10
|
+
readonly name: string;
|
|
11
|
+
/** The value stored under key, or null. */
|
|
12
|
+
get(key: string): Promise<string | null>;
|
|
13
|
+
set(key: string, value: string, options?: CacheSetOptions): Promise<void>;
|
|
14
|
+
delete(key: string): Promise<void>;
|
|
15
|
+
/** The keys stored with tag. */
|
|
16
|
+
keysByTag(tag: string): Promise<string[]>;
|
|
17
|
+
/** Deletes every key stored with one of tags; resolves with how many went. */
|
|
18
|
+
deleteByTags(tags: string[]): Promise<number>;
|
|
19
|
+
/** Sends message to every subscriber of channel, including this process. */
|
|
20
|
+
publish(channel: string, message: string): Promise<void>;
|
|
21
|
+
/**
|
|
22
|
+
* Calls handler for each message published on channel. After a lost
|
|
23
|
+
* connection that may have dropped messages, handler is called with "*":
|
|
24
|
+
* treat it as "everything may be stale". Resolves with an unsubscribe function.
|
|
25
|
+
*/
|
|
26
|
+
subscribe(channel: string, handler: (message: string) => void): Promise<() => void>;
|
|
27
|
+
/** Releases connections. */
|
|
28
|
+
close(): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
/** What the config and KRATE_CACHE carry. */
|
|
31
|
+
export interface CacheSpec {
|
|
32
|
+
/** "memory" (default), "redis", or a module specifier / path exporting an adapter factory. */
|
|
33
|
+
adapter?: string;
|
|
34
|
+
url?: string;
|
|
35
|
+
/** Key prefix, so several apps can share one store (default "krate:"). */
|
|
36
|
+
prefix?: string;
|
|
37
|
+
/** Milliseconds one cache call may take before it counts as a failure (default 250). */
|
|
38
|
+
timeoutMs?: number;
|
|
39
|
+
/** Milliseconds to keep ISR entries in the shared store (default 7 days). */
|
|
40
|
+
ttlSeconds?: number;
|
|
41
|
+
/** Adapter-specific options passed to a custom factory. */
|
|
42
|
+
options?: Record<string, unknown>;
|
|
43
|
+
}
|
|
44
|
+
export declare const INVALIDATE_CHANNEL = "invalidate";
|
|
45
|
+
/** The adapter tag a cache tag is stored under (kept apart from route index tags). */
|
|
46
|
+
export declare function tagName(tag: string): string;
|
|
47
|
+
export type GuardResult<T> = {
|
|
48
|
+
ok: true;
|
|
49
|
+
value: T;
|
|
50
|
+
} | {
|
|
51
|
+
ok: false;
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* Runs adapter calls with a timeout and a circuit breaker. After a few
|
|
55
|
+
* consecutive failures calls are skipped (reported as failed) for a cool-down,
|
|
56
|
+
* so a dead cache costs a microsecond per request, not a timeout.
|
|
57
|
+
*/
|
|
58
|
+
export declare class CacheGuard {
|
|
59
|
+
readonly adapter: CacheAdapter;
|
|
60
|
+
private readonly timeoutMs;
|
|
61
|
+
private readonly threshold;
|
|
62
|
+
private readonly coolDownMs;
|
|
63
|
+
private failures;
|
|
64
|
+
private openUntil;
|
|
65
|
+
private lastLog;
|
|
66
|
+
constructor(adapter: CacheAdapter, timeoutMs?: number, threshold?: number, coolDownMs?: number);
|
|
67
|
+
get healthy(): boolean;
|
|
68
|
+
call<T>(fn: (a: CacheAdapter) => Promise<T>): Promise<GuardResult<T>>;
|
|
69
|
+
}
|
|
70
|
+
export declare class SharedDataCache implements SharedDataStore {
|
|
71
|
+
private readonly guard;
|
|
72
|
+
constructor(guard: CacheGuard);
|
|
73
|
+
get(key: string): Promise<GuardResult<string | undefined>>;
|
|
74
|
+
set(key: string, json: string, ttlSeconds: number, tags: string[]): Promise<boolean>;
|
|
75
|
+
deleteTags(tags: string[]): Promise<number>;
|
|
76
|
+
}
|
|
77
|
+
/** A CacheAdapter over a Map. Two processes cannot share it; it exists for tests and as the reference. */
|
|
78
|
+
export declare class MemoryAdapter implements CacheAdapter {
|
|
79
|
+
readonly name = "memory";
|
|
80
|
+
private values;
|
|
81
|
+
private byTag;
|
|
82
|
+
private subs;
|
|
83
|
+
get(key: string): Promise<string | null>;
|
|
84
|
+
set(key: string, value: string, options?: CacheSetOptions): Promise<void>;
|
|
85
|
+
delete(key: string): Promise<void>;
|
|
86
|
+
keysByTag(tag: string): Promise<string[]>;
|
|
87
|
+
deleteByTags(tags: string[]): Promise<number>;
|
|
88
|
+
publish(channel: string, message: string): Promise<void>;
|
|
89
|
+
subscribe(channel: string, handler: (message: string) => void): Promise<() => void>;
|
|
90
|
+
close(): Promise<void>;
|
|
91
|
+
}
|
|
92
|
+
/** Resolves a spec to an adapter, or null for the default in-process caches. */
|
|
93
|
+
export declare function loadCacheAdapter(spec: CacheSpec | undefined): Promise<CacheAdapter | null>;
|
|
94
|
+
/** Reads the cache spec the Go host passes in KRATE_CACHE. */
|
|
95
|
+
export declare function cacheSpecFromEnv(env: Record<string, string | undefined>): CacheSpec | undefined;
|
|
96
|
+
export interface InstalledCache {
|
|
97
|
+
adapter: CacheAdapter;
|
|
98
|
+
guard: CacheGuard;
|
|
99
|
+
data: SharedDataCache;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Wires an adapter into the process: the data cache reads and writes through it
|
|
103
|
+
* (cacheRuntime().shared), and the returned stores replace the in-process ISR
|
|
104
|
+
* cache. Pass the returned `isr` as the renderer's isrStore.
|
|
105
|
+
*/
|
|
106
|
+
export declare function installCacheAdapter(adapter: CacheAdapter, spec?: CacheSpec): InstalledCache;
|
|
107
|
+
/**
|
|
108
|
+
* The cache spec a handler bundle carries (data.config.cache): the adapter and
|
|
109
|
+
* its tuning, with the URL left to the environment so no secret is bundled.
|
|
110
|
+
*/
|
|
111
|
+
export declare function cacheSpecFromConfig(cfg: (CacheSpec & {
|
|
112
|
+
urlEnv?: string;
|
|
113
|
+
}) | undefined): CacheSpec | undefined;
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
// Pluggable shared cache.
|
|
2
|
+
//
|
|
3
|
+
// By default every cache lives in the memory of one process. Setting
|
|
4
|
+
// `cache: { adapter: "redis", url }` in krate.config (or passing an adapter to
|
|
5
|
+
// createKrateHandler) moves the ISR page cache and the data cache (fetch with
|
|
6
|
+
// next options, unstable_cache) into a store every instance reads and writes, and
|
|
7
|
+
// makes revalidatePath / revalidateTag on one instance invalidate all of them.
|
|
8
|
+
//
|
|
9
|
+
// An adapter is a small key-value store with tag deletion and pub/sub. Write
|
|
10
|
+
// your own with the CacheAdapter interface below and point `cache.adapter` at a
|
|
11
|
+
// module that default-exports `(options) => CacheAdapter` (see the caching
|
|
12
|
+
// guide).
|
|
13
|
+
//
|
|
14
|
+
// Whatever the adapter does, a cache problem is never a request problem: every
|
|
15
|
+
// call is bounded by a timeout, failures are logged once, an unhealthy adapter
|
|
16
|
+
// is skipped for a while, and the page is rendered instead.
|
|
17
|
+
import { cacheRuntime } from './cache-scope.js';
|
|
18
|
+
export const INVALIDATE_CHANNEL = 'invalidate';
|
|
19
|
+
/** The adapter tag a cache tag is stored under (kept apart from route index tags). */
|
|
20
|
+
export function tagName(tag) {
|
|
21
|
+
return 'tag:' + tag;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Runs adapter calls with a timeout and a circuit breaker. After a few
|
|
25
|
+
* consecutive failures calls are skipped (reported as failed) for a cool-down,
|
|
26
|
+
* so a dead cache costs a microsecond per request, not a timeout.
|
|
27
|
+
*/
|
|
28
|
+
export class CacheGuard {
|
|
29
|
+
constructor(adapter, timeoutMs = 250, threshold = 3, coolDownMs = 5000) {
|
|
30
|
+
this.adapter = adapter;
|
|
31
|
+
this.timeoutMs = timeoutMs;
|
|
32
|
+
this.threshold = threshold;
|
|
33
|
+
this.coolDownMs = coolDownMs;
|
|
34
|
+
this.failures = 0;
|
|
35
|
+
this.openUntil = 0;
|
|
36
|
+
this.lastLog = 0;
|
|
37
|
+
}
|
|
38
|
+
get healthy() {
|
|
39
|
+
return Date.now() >= this.openUntil;
|
|
40
|
+
}
|
|
41
|
+
async call(fn) {
|
|
42
|
+
if (!this.healthy)
|
|
43
|
+
return { ok: false };
|
|
44
|
+
let timer;
|
|
45
|
+
try {
|
|
46
|
+
const value = await Promise.race([
|
|
47
|
+
fn(this.adapter),
|
|
48
|
+
new Promise((_, reject) => {
|
|
49
|
+
timer = setTimeout(() => reject(new Error(`cache ${this.adapter.name} did not answer within ${this.timeoutMs}ms`)), this.timeoutMs);
|
|
50
|
+
}),
|
|
51
|
+
]);
|
|
52
|
+
this.failures = 0;
|
|
53
|
+
return { ok: true, value };
|
|
54
|
+
}
|
|
55
|
+
catch (err) {
|
|
56
|
+
this.failures++;
|
|
57
|
+
if (this.failures >= this.threshold)
|
|
58
|
+
this.openUntil = Date.now() + this.coolDownMs;
|
|
59
|
+
const now = Date.now();
|
|
60
|
+
if (now - this.lastLog > 30000) {
|
|
61
|
+
this.lastLog = now;
|
|
62
|
+
console.warn(`[krate] shared cache (${this.adapter.name}) failed, serving without it: ${err?.message || err}`);
|
|
63
|
+
}
|
|
64
|
+
return { ok: false };
|
|
65
|
+
}
|
|
66
|
+
finally {
|
|
67
|
+
if (timer)
|
|
68
|
+
clearTimeout(timer);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
// Shared data cache (fetch with next options, unstable_cache)
|
|
73
|
+
const DATA_PREFIX = 'data:';
|
|
74
|
+
export class SharedDataCache {
|
|
75
|
+
constructor(guard) {
|
|
76
|
+
this.guard = guard;
|
|
77
|
+
}
|
|
78
|
+
async get(key) {
|
|
79
|
+
const r = await this.guard.call((a) => a.get(DATA_PREFIX + key));
|
|
80
|
+
if (!r.ok)
|
|
81
|
+
return r;
|
|
82
|
+
return { ok: true, value: r.value === null ? undefined : r.value };
|
|
83
|
+
}
|
|
84
|
+
async set(key, json, ttlSeconds, tags) {
|
|
85
|
+
const r = await this.guard.call((a) => a.set(DATA_PREFIX + key, json, { ttlSeconds: ttlSeconds === Infinity ? undefined : ttlSeconds, tags: tags.map(tagName) }));
|
|
86
|
+
return r.ok;
|
|
87
|
+
}
|
|
88
|
+
async deleteTags(tags) {
|
|
89
|
+
const r = await this.guard.call((a) => a.deleteByTags(tags.map(tagName)));
|
|
90
|
+
return r.ok ? r.value : 0;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
// In-process adapter (tests, and the reference for adapter authors)
|
|
94
|
+
/** A CacheAdapter over a Map. Two processes cannot share it; it exists for tests and as the reference. */
|
|
95
|
+
export class MemoryAdapter {
|
|
96
|
+
constructor() {
|
|
97
|
+
this.name = 'memory';
|
|
98
|
+
this.values = new Map();
|
|
99
|
+
this.byTag = new Map();
|
|
100
|
+
this.subs = new Map();
|
|
101
|
+
}
|
|
102
|
+
async get(key) {
|
|
103
|
+
const e = this.values.get(key);
|
|
104
|
+
if (!e)
|
|
105
|
+
return null;
|
|
106
|
+
if (e.expires <= Date.now()) {
|
|
107
|
+
await this.delete(key);
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
return e.value;
|
|
111
|
+
}
|
|
112
|
+
async set(key, value, options = {}) {
|
|
113
|
+
await this.delete(key);
|
|
114
|
+
const ttl = options.ttlSeconds;
|
|
115
|
+
const tags = options.tags || [];
|
|
116
|
+
this.values.set(key, { value, expires: ttl && ttl > 0 && ttl !== Infinity ? Date.now() + ttl * 1000 : Infinity, tags });
|
|
117
|
+
for (const t of tags) {
|
|
118
|
+
let keys = this.byTag.get(t);
|
|
119
|
+
if (!keys)
|
|
120
|
+
this.byTag.set(t, (keys = new Set()));
|
|
121
|
+
keys.add(key);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
async delete(key) {
|
|
125
|
+
const e = this.values.get(key);
|
|
126
|
+
if (!e)
|
|
127
|
+
return;
|
|
128
|
+
this.values.delete(key);
|
|
129
|
+
for (const t of e.tags)
|
|
130
|
+
this.byTag.get(t)?.delete(key);
|
|
131
|
+
}
|
|
132
|
+
async keysByTag(tag) {
|
|
133
|
+
return [...(this.byTag.get(tag) || [])];
|
|
134
|
+
}
|
|
135
|
+
async deleteByTags(tags) {
|
|
136
|
+
let n = 0;
|
|
137
|
+
for (const t of tags) {
|
|
138
|
+
for (const k of [...(this.byTag.get(t) || [])]) {
|
|
139
|
+
if (this.values.has(k))
|
|
140
|
+
n++;
|
|
141
|
+
await this.delete(k);
|
|
142
|
+
}
|
|
143
|
+
this.byTag.delete(t);
|
|
144
|
+
}
|
|
145
|
+
return n;
|
|
146
|
+
}
|
|
147
|
+
async publish(channel, message) {
|
|
148
|
+
for (const h of [...(this.subs.get(channel) || [])])
|
|
149
|
+
h(message);
|
|
150
|
+
}
|
|
151
|
+
async subscribe(channel, handler) {
|
|
152
|
+
let set = this.subs.get(channel);
|
|
153
|
+
if (!set)
|
|
154
|
+
this.subs.set(channel, (set = new Set()));
|
|
155
|
+
set.add(handler);
|
|
156
|
+
return async () => void set.delete(handler);
|
|
157
|
+
}
|
|
158
|
+
async close() {
|
|
159
|
+
this.values.clear();
|
|
160
|
+
this.byTag.clear();
|
|
161
|
+
this.subs.clear();
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
/** Resolves a spec to an adapter, or null for the default in-process caches. */
|
|
165
|
+
export async function loadCacheAdapter(spec) {
|
|
166
|
+
if (!spec || !spec.adapter || spec.adapter === 'memory')
|
|
167
|
+
return null;
|
|
168
|
+
const opts = { ...(spec.options || {}), url: spec.url, prefix: spec.prefix, timeoutMs: spec.timeoutMs };
|
|
169
|
+
if (spec.adapter === 'redis') {
|
|
170
|
+
const { RedisAdapter } = await import('./cache-redis.js');
|
|
171
|
+
if (!spec.url)
|
|
172
|
+
throw new Error('cache.adapter "redis" needs cache.url (redis://host:6379)');
|
|
173
|
+
return new RedisAdapter(opts);
|
|
174
|
+
}
|
|
175
|
+
const mod = (await import(spec.adapter));
|
|
176
|
+
const factory = (mod.default ?? mod.createAdapter);
|
|
177
|
+
if (typeof factory === 'function')
|
|
178
|
+
return factory(opts);
|
|
179
|
+
if (factory && typeof factory.get === 'function')
|
|
180
|
+
return factory;
|
|
181
|
+
throw new Error(`cache adapter module ${spec.adapter} must default-export a CacheAdapter or a (options) => CacheAdapter factory`);
|
|
182
|
+
}
|
|
183
|
+
/** Reads the cache spec the Go host passes in KRATE_CACHE. */
|
|
184
|
+
export function cacheSpecFromEnv(env) {
|
|
185
|
+
const raw = env.KRATE_CACHE;
|
|
186
|
+
if (!raw)
|
|
187
|
+
return undefined;
|
|
188
|
+
try {
|
|
189
|
+
return JSON.parse(raw);
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
console.warn('[krate] KRATE_CACHE is not valid JSON; using the in-process caches');
|
|
193
|
+
return undefined;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Wires an adapter into the process: the data cache reads and writes through it
|
|
198
|
+
* (cacheRuntime().shared), and the returned stores replace the in-process ISR
|
|
199
|
+
* cache. Pass the returned `isr` as the renderer's isrStore.
|
|
200
|
+
*/
|
|
201
|
+
export function installCacheAdapter(adapter, spec = {}) {
|
|
202
|
+
const guard = new CacheGuard(adapter, spec.timeoutMs && spec.timeoutMs > 0 ? spec.timeoutMs : 250);
|
|
203
|
+
const data = new SharedDataCache(guard);
|
|
204
|
+
cacheRuntime().shared = data;
|
|
205
|
+
return { adapter, guard, data };
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* The cache spec a handler bundle carries (data.config.cache): the adapter and
|
|
209
|
+
* its tuning, with the URL left to the environment so no secret is bundled.
|
|
210
|
+
*/
|
|
211
|
+
export function cacheSpecFromConfig(cfg) {
|
|
212
|
+
if (!cfg || !cfg.adapter || cfg.adapter === 'memory')
|
|
213
|
+
return undefined;
|
|
214
|
+
const env = globalThis.process?.env || {};
|
|
215
|
+
const url = cfg.url || (cfg.urlEnv ? env[cfg.urlEnv] : undefined) || env.KRATE_CACHE_URL;
|
|
216
|
+
return { ...cfg, url };
|
|
217
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|