akanjs 3.2.0 → 3.2.1-rc.0

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.
Files changed (46) hide show
  1. package/document/dataLoader.ts +55 -25
  2. package/package.json +1 -1
  3. package/server/akanApp.ts +13 -2
  4. package/server/akanServer.ts +4 -0
  5. package/server/contentEncoding.ts +39 -9
  6. package/server/flightSanitizeRecorded.fixture.json +545 -0
  7. package/server/gateway/gatewayHttpProxy.ts +2 -2
  8. package/server/hmr/devBaseArtifact.ts +40 -0
  9. package/server/htmlResultCache.ts +11 -10
  10. package/server/routing/routeHosts.ts +4 -0
  11. package/server/rscFlightStream.ts +34 -2
  12. package/server/rscHostRequests.ts +27 -2
  13. package/server/rscRenderControl.ts +2 -0
  14. package/server/rscRenderHandler.ts +17 -18
  15. package/server/rscRenderManifest.ts +13 -0
  16. package/server/rscResultCaches.ts +2 -2
  17. package/server/rscWorker.tsx +14 -2
  18. package/server/rscWorkerCache.ts +13 -15
  19. package/server/rscWorkerHost.ts +3 -0
  20. package/service/predefinedAdaptor/solidCache.adaptor.ts +57 -15
  21. package/service/predefinedAdaptor/sql/AggregateQuery.ts +66 -0
  22. package/service/predefinedAdaptor/sql/BoundList.ts +34 -0
  23. package/service/predefinedAdaptor/sql/QueryCompiler.ts +27 -4
  24. package/service/predefinedAdaptor/sql/QueryScope.ts +41 -7
  25. package/service/predefinedAdaptor/sql/RawDocumentTable.ts +7 -1
  26. package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +45 -42
  27. package/service/predefinedAdaptor/sql/SqlTableSchema.ts +2 -2
  28. package/service/predefinedAdaptor/sql/types.ts +2 -0
  29. package/types/document/dataLoader.d.ts +1 -0
  30. package/types/server/contentEncoding.d.ts +3 -2
  31. package/types/server/gateway/gatewayHttpProxy.d.ts +1 -0
  32. package/types/server/hmr/devBaseArtifact.d.ts +10 -0
  33. package/types/server/htmlResultCache.d.ts +3 -2
  34. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  35. package/types/server/routing/routeHosts.d.ts +1 -0
  36. package/types/server/rscHostRequests.d.ts +1 -0
  37. package/types/server/rscRenderControl.d.ts +2 -0
  38. package/types/server/rscRenderManifest.d.ts +5 -0
  39. package/types/server/rscWorkerCache.d.ts +4 -5
  40. package/types/service/predefinedAdaptor/sql/AggregateQuery.d.ts +16 -0
  41. package/types/service/predefinedAdaptor/sql/BoundList.d.ts +10 -0
  42. package/types/service/predefinedAdaptor/sql/QueryCompiler.d.ts +1 -0
  43. package/types/service/predefinedAdaptor/sql/QueryScope.d.ts +2 -2
  44. package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +1 -1
  45. package/types/service/predefinedAdaptor/sql/SqlTableSchema.d.ts +1 -1
  46. package/types/service/predefinedAdaptor/sql/types.d.ts +2 -0
@@ -68,7 +68,7 @@ export class GatewayHttpProxy {
68
68
 
69
69
  async proxyHttp(req: Request, server: Bun.Server<GatewayWsData>): Promise<Response> {
70
70
  const child = await this.#pickReadyFederationChild(req);
71
- if (child?.upstream?.type !== "unix") return this.#respondWithUnavailable(req);
71
+ if (child?.upstream?.type !== "unix") return this.respondWithUnavailable(req);
72
72
 
73
73
  const { socketPath } = child.upstream;
74
74
  const url = new URL(req.url);
@@ -163,7 +163,7 @@ export class GatewayHttpProxy {
163
163
  return null;
164
164
  }
165
165
 
166
- #respondWithUnavailable(req: Request): Response {
166
+ respondWithUnavailable(req: Request): Response {
167
167
  const crashDetail = this.#supervisor.crashLoopDetail();
168
168
  const page = crashDetail
169
169
  ? {
@@ -0,0 +1,40 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { Logger } from "akanjs/common";
4
+ import { resolveArtifactDir } from "../proxy/hostBasePathWebProxy";
5
+
6
+ export class DevBaseArtifact {
7
+ static readonly #pollMs = 20;
8
+
9
+ static async arrived({
10
+ artifactDir = resolveArtifactDir(),
11
+ env = process.env,
12
+ stopped = () => false,
13
+ warnAfterMs = 30_000,
14
+ warn = (message: string) => new Logger("DevBaseArtifact").warn(message),
15
+ }: {
16
+ artifactDir?: string;
17
+ env?: Record<string, string | undefined>;
18
+ stopped?: () => boolean;
19
+ warnAfterMs?: number;
20
+ warn?: (message: string) => void;
21
+ } = {}): Promise<number> {
22
+ if (env.AKAN_DEV_AWAIT_ARTIFACT !== "1") return 0;
23
+ const file = path.join(artifactDir, "base-artifact.json");
24
+ const started = performance.now();
25
+ let warned = false;
26
+ while (!fs.existsSync(file)) {
27
+ if (stopped()) return performance.now() - started;
28
+ if (!warned && performance.now() - started >= warnAfterMs) {
29
+ warned = true;
30
+ warn(
31
+ `still waiting for the first base build to write ${file} after ${Math.round(warnAfterMs / 1000)}s; this server finishes booting once the file is there`,
32
+ );
33
+ }
34
+ await Bun.sleep(DevBaseArtifact.#pollMs);
35
+ }
36
+
37
+ delete env.AKAN_DEV_AWAIT_ARTIFACT;
38
+ return performance.now() - started;
39
+ }
40
+ }
@@ -20,19 +20,20 @@ export const DEFAULT_HTML_RESULT_CACHE_MAX_BODY_BYTES = 2 * 1024 * 1024;
20
20
  /** Well above any sensible TTL: this only has to reclaim a cache nobody is reading, not track expiry closely. */
21
21
  const ROUTE_CACHE_SWEEP_INTERVAL_MS = 60_000;
22
22
 
23
+ interface HtmlCacheStreamOptions {
24
+ shouldCache?: () => boolean | Promise<boolean>;
25
+ maxBodyBytes?: number | null;
26
+ onSkip?: (reason: "body-too-large" | "store-skip") => void;
27
+ }
28
+
23
29
  export function cacheHtmlWhileStreaming(
24
30
  stream: ReadableStream<Uint8Array>,
25
- onComplete: (html: string) => void,
26
- options: {
27
- shouldCache?: () => boolean | Promise<boolean>;
28
- maxBodyBytes?: number | null;
29
- onSkip?: (reason: "body-too-large" | "store-skip") => void;
30
- } = {},
31
+ onComplete: (body: Uint8Array<ArrayBuffer>) => void,
32
+ options: HtmlCacheStreamOptions = {},
31
33
  ): ReadableStream<Uint8Array> {
32
34
  const chunks: Uint8Array[] = [];
33
35
  let byteLength = 0;
34
36
  let exceededMaxBodyBytes = false;
35
- const decoder = new TextDecoder();
36
37
 
37
38
  return stream.pipeThrough(
38
39
  new TransformStream<Uint8Array, Uint8Array>({
@@ -64,7 +65,7 @@ export function cacheHtmlWhileStreaming(
64
65
  options.onSkip?.("store-skip");
65
66
  return;
66
67
  }
67
- onComplete(decoder.decode(body));
68
+ onComplete(body);
68
69
  } catch {
69
70
  }
70
71
  },
@@ -185,8 +186,8 @@ export class HtmlResultCache {
185
186
  });
186
187
  return cacheHtmlWhileStreaming(
187
188
  htmlStream,
188
- (html) => {
189
- void encodeBody(html).then((body) => this.#cache.set(entry.key, { body, ...htmlCacheMetadata }, htmlStoreTtl));
189
+ (bytes) => {
190
+ void encodeBody(bytes).then((body) => this.#cache.set(entry.key, { body, ...htmlCacheMetadata }, htmlStoreTtl));
190
191
  },
191
192
  {
192
193
  shouldCache: () => shouldCacheHtml,
@@ -21,6 +21,10 @@ export class RouteHosts {
21
21
  return hosts;
22
22
  }
23
23
 
24
+ static written(artifactDir: string = resolveArtifactDir()): boolean {
25
+ return fs.existsSync(path.join(artifactDir, "base-artifact.json"));
26
+ }
27
+
24
28
  static #read(file: string): Partial<BaseBuildArtifact> | null {
25
29
  try {
26
30
  return JSON.parse(fs.readFileSync(file, "utf8")) as Partial<BaseBuildArtifact>;
@@ -10,8 +10,11 @@ import { RouteElementComposer } from "./routeElementComposer";
10
10
  import type { RouteShellGate } from "./routeShellGate";
11
11
  import { concatBytes, encodeAkanRedirectDigest } from "./rscHttp";
12
12
  import { isAkanNotFoundError, isAkanRedirectError } from "./rscRenderControl";
13
+ import { joinRscChunks } from "./rscWorkerCache";
13
14
  import type { RscTraceMetadata } from "./ssrTypes";
14
15
 
16
+ const COALESCED_CHUNK_BYTES = 32 * 1024;
17
+
15
18
  export type RenderControl =
16
19
  | { type: "redirect"; location: string; method: "replace" | "push"; status: RedirectStatus }
17
20
  | { type: "not-found" }
@@ -64,6 +67,8 @@ export class RscFlightStream {
64
67
 
65
68
  #holding: RouteShellGate | null = null;
66
69
  #held: Uint8Array | null = null;
70
+ #batch: Uint8Array[] = [];
71
+ #batchBytes = 0;
67
72
  #reportedTheme: AkanTheme | undefined;
68
73
 
69
74
  constructor(props: RscFlightStreamProps, options: FlightRenderOptions) {
@@ -94,6 +99,8 @@ export class RscFlightStream {
94
99
  this.#releaseHeld();
95
100
  continue;
96
101
  }
102
+
103
+ if (this.#batch.length > 0 && !(await RscFlightStream.#isSettled(pendingRead))) this.#flush();
97
104
  const { value, done } = await pendingRead;
98
105
  pendingRead = null;
99
106
  if (options.requestId && this.#props.isCancelled(options.requestId))
@@ -132,6 +139,7 @@ export class RscFlightStream {
132
139
  if (this.#holding && this.#controlRef.current?.type !== "error") this.#releaseHeld();
133
140
  if (this.#controlRef.current && this.#sentChunk) this.#sendLateControl();
134
141
  if (this.#controlRef.current && !this.#sentChunk) return this.#resultOf(this.#controlRef.current, false);
142
+ this.#flush();
135
143
  if (options.requestId) {
136
144
  this.#sendMeta();
137
145
  const cacheState = (await options.onComplete?.({
@@ -219,9 +227,32 @@ export class RscFlightStream {
219
227
  if (options.collectChunks) this.#chunks.push(chunk);
220
228
  if (!options.requestId) return;
221
229
  this.#sendMeta();
222
- this.#sendLateTheme();
223
- this.#props.send({ type: "chunk", requestId: options.requestId, data: chunk });
230
+ if (this.#batchBytes + chunk.byteLength > COALESCED_CHUNK_BYTES) this.#flush();
231
+ this.#batch.push(chunk);
232
+ this.#batchBytes += chunk.byteLength;
224
233
  this.#sentChunk = true;
234
+ if (this.#batchBytes >= COALESCED_CHUNK_BYTES) this.#flush();
235
+ }
236
+
237
+ #flush(): void {
238
+ const options = this.#options;
239
+ const [first] = this.#batch;
240
+ if (!options.requestId || !first) return;
241
+ const data = this.#batch.length === 1 ? first : joinRscChunks(this.#batch);
242
+ this.#batch = [];
243
+ this.#batchBytes = 0;
244
+ this.#sendLateTheme();
245
+ this.#props.send({ type: "chunk", requestId: options.requestId, data });
246
+ }
247
+
248
+ static #isSettled(read: Promise<unknown>): Promise<boolean> {
249
+ return Promise.race([
250
+ read.then(
251
+ () => true,
252
+ () => false,
253
+ ),
254
+ Promise.resolve().then(() => false),
255
+ ]);
225
256
  }
226
257
 
227
258
  #releaseHeld(): void {
@@ -240,6 +271,7 @@ export class RscFlightStream {
240
271
  const control = this.#controlRef.current;
241
272
  if (!options.requestId || this.#lateControlSent || !control || control.type === "error") return;
242
273
  this.#lateControlSent = true;
274
+ this.#flush();
243
275
  if (control.type === "redirect") {
244
276
  this.#props.send({
245
277
  type: "late-redirect",
@@ -1,7 +1,8 @@
1
1
  import { AkanError } from "akanjs/base";
2
2
  import type { Logger } from "akanjs/common";
3
+ import type { ClientManifest } from "./artifact";
3
4
  import { createRscHostRenderStream, type RscPending, type RscRenderResult } from "./rscHostRenderStream";
4
- import type { RscWorkerErrorCode, RscWorkerProcess } from "./rscWorkerProcess";
5
+ import type { RscProcess, RscWorkerErrorCode, RscWorkerProcess } from "./rscWorkerProcess";
5
6
  import type { RscRenderOptions } from "./ssrTypes";
6
7
 
7
8
  interface RscCall {
@@ -19,6 +20,7 @@ export class RscHostRequests {
19
20
  readonly calls = new Map<string, RscCall>();
20
21
  #queuedSends: RscQueuedSend[] = [];
21
22
  #hostPendingChunkOverflowCount = 0;
23
+ #sentManifest: { proc: RscProcess; manifest: ClientManifest; revision: number } | null = null;
22
24
  readonly #worker: RscWorkerProcess;
23
25
  readonly #logger: Logger;
24
26
 
@@ -107,7 +109,20 @@ export class RscHostRequests {
107
109
  try {
108
110
  const headers = RscHostRequests.workerHeaders(req, clientIp);
109
111
  const { url, method } = req;
110
- this.#worker.proc.send({ type: "render", requestId, url, method, headers, clientManifest, prefetch });
112
+ const proc = this.#worker.proc;
113
+ const named = clientManifest ? this.#revisionOf(proc, clientManifest) : null;
114
+ proc.send({
115
+ type: "render",
116
+ requestId,
117
+ url,
118
+ method,
119
+ headers,
120
+ manifestRevision: named?.revision,
121
+ clientManifest: named?.held ? undefined : clientManifest,
122
+ prefetch,
123
+ });
124
+ if (clientManifest && named && !named.held)
125
+ this.#sentManifest = { proc, manifest: clientManifest, revision: named.revision };
111
126
  } catch (err) {
112
127
  this.resolvePending(requestId, (p) =>
113
128
  p.onError(`rsc worker send failed: ${err instanceof Error ? err.message : String(err)}`, "rscWorkerStopped"),
@@ -122,6 +137,16 @@ export class RscHostRequests {
122
137
  }
123
138
  }
124
139
 
140
+ #revisionOf(proc: RscProcess, manifest: ClientManifest): { revision: number; held: boolean } {
141
+ const sent = this.#sentManifest;
142
+ if (sent?.proc === proc && sent.manifest === manifest) return { revision: sent.revision, held: true };
143
+ return { revision: (sent?.revision ?? 0) + 1, held: false };
144
+ }
145
+
146
+ forgetManifest(): void {
147
+ this.#sentManifest = null;
148
+ }
149
+
125
150
  #cancelRender(requestId: string): void {
126
151
  if (this.#worker.status !== "ready") return;
127
152
  try {
@@ -6,6 +6,8 @@ export interface RscRenderRequest {
6
6
  url: string;
7
7
  method?: string;
8
8
  headers?: Record<string, string>;
9
+ /** Names the manifest to render against; the host sends that manifest itself once per worker process. */
10
+ manifestRevision?: number;
9
11
  clientManifest?: ClientManifest;
10
12
  prefetch?: boolean;
11
13
  }
@@ -37,6 +37,7 @@ import {
37
37
  createCachedRscPatchMetadata,
38
38
  createRscWorkerCachedPatchReplayDecision,
39
39
  isCachedRscPatchMetadataCompatible,
40
+ joinRscChunks,
40
41
  replayCachedRscResult,
41
42
  resolveRscWorkerPatchCacheEntry,
42
43
  rscWorkerTraceBaseOf,
@@ -152,11 +153,7 @@ export class RscRenderHandler {
152
153
  const target: RscRenderTarget = { msg, requestId, startedAt, request, url: urlObj, match, routeId };
153
154
  const plan = await this.#plan(target);
154
155
  if (!plan) return;
155
- const replay = this.#replayFromCache(target, plan);
156
- if (replay) {
157
- await replay;
158
- return;
159
- }
156
+ if (this.#replayFromCache(target, plan)) return;
160
157
  const { searchParams, notFoundFallback, admitted, cacheEntry, safePatchDecision, admittedHead } = plan;
161
158
  let element: ReactNode;
162
159
  let routeHead: ResolvedRouteHead | undefined;
@@ -297,7 +294,7 @@ export class RscRenderHandler {
297
294
  #replayFromCache(
298
295
  { requestId, routeId, startedAt }: RscRenderTarget,
299
296
  { cacheEntry, targetRouterState, safePatchDecision, admittedHead, patchCacheEntry, createTraceBase }: RscRenderPlan,
300
- ): Promise<void> | null {
297
+ ): boolean {
301
298
  const cachedPatch = patchCacheEntry
302
299
  ? this.#caches.getCached(this.#caches.patchResultCache, patchCacheEntry.key)
303
300
  : null;
@@ -319,24 +316,25 @@ export class RscRenderHandler {
319
316
  patchCacheEntry.key,
320
317
  RscPatchPlanner.routeStateWith(cachedPatch.patch.targetRouterState, admittedHead?.snapshots?.layoutsKey),
321
318
  );
322
- return this.#replayCached(requestId, routeId, startedAt, cachedPatch, {
319
+ this.#replayCached(requestId, routeId, startedAt, cachedPatch, {
323
320
  ...cachedTraceBase,
324
321
  cache: "hit",
325
322
  partial: "patch",
326
323
  partialReason: "cache-hit-patch-replay",
327
324
  });
325
+ return true;
328
326
  }
329
327
  const cached =
330
328
  shouldUseRscWorkerFullResultCache({ cacheEntry, patchCacheEntry }) && cacheEntry
331
329
  ? this.#caches.getCached(this.#caches.resultCache, cacheEntry.key)
332
330
  : null;
333
- if (!cached) return null;
331
+ if (!cached) return false;
334
332
  const traceBase = createTraceBase(
335
333
  safePatchDecision,
336
334
  patchCacheEntry?.key ?? cacheEntry?.key,
337
335
  RscPatchPlanner.routeStateWith(targetRouterState, cached.routeHeadKey),
338
336
  );
339
- return this.#replayCached(requestId, routeId, startedAt, cached, {
337
+ this.#replayCached(requestId, routeId, startedAt, cached, {
340
338
  ...traceBase,
341
339
  cache: "hit",
342
340
  partial: "full",
@@ -349,6 +347,7 @@ export class RscRenderHandler {
349
347
  patchHeadSnapshot: undefined,
350
348
  ssrBlocking: cached.ssrBlocking,
351
349
  });
350
+ return true;
352
351
  }
353
352
 
354
353
  #recordRendered(
@@ -373,7 +372,7 @@ export class RscRenderHandler {
373
372
  { url: urlObj, routeId }: RscRenderTarget,
374
373
  { cacheEntry, targetRouterState, patchCacheEntry }: RscRenderPlan,
375
374
  { effectivePatchDecision, routeHeadKey, ssrBlocking }: RscRenderedRoute,
376
- { chunks, bytes, chunksCount, control, lateControlSent }: Omit<FlightRenderResult, "cancelled">,
375
+ { chunks, chunksCount, control, lateControlSent }: Omit<FlightRenderResult, "cancelled">,
377
376
  ): RouteCacheRenderState {
378
377
  const cacheState = shouldStoreRouteCache({
379
378
  policy: getRequestPolicy(),
@@ -383,8 +382,7 @@ export class RscRenderHandler {
383
382
  });
384
383
  const storeTtl = cacheEntry ? resolveRouteCacheStoreTtl(cacheEntry.ttl, cacheState) : null;
385
384
  const stored = (): CachedRscResult => ({
386
- chunks,
387
- bytes,
385
+ body: joinRscChunks(chunks),
388
386
  chunksCount,
389
387
  pathname: urlObj.pathname,
390
388
  routeId,
@@ -414,21 +412,22 @@ export class RscRenderHandler {
414
412
  return cacheState;
415
413
  }
416
414
 
417
- async #replayCached(
415
+ #replayCached(
418
416
  requestId: string,
419
417
  routeId: string,
420
418
  startedAt: number,
421
419
  cached: CachedRscResult,
422
420
  trace: RscTraceMetadata,
423
- ): Promise<void> {
421
+ ): void {
422
+ const bytes = cached.body.byteLength;
424
423
  this.#stats.lastRenderDurationMs = Date.now() - startedAt;
425
424
  this.#stats.lastRenderLoadedModuleDelta = 0;
426
425
  this.#stats.lastRenderLoadedModules = [];
427
- this.#stats.recordFlight(cached);
428
- this.#stats.recordRouteStats(routeId, cached.bytes, this.#stats.lastRenderDurationMs);
429
- await replayCachedRscResult({
426
+ this.#stats.recordFlight({ bytes, chunksCount: cached.chunksCount });
427
+ this.#stats.recordRouteStats(routeId, bytes, this.#stats.lastRenderDurationMs);
428
+ replayCachedRscResult({
430
429
  requestId,
431
- chunks: cached.chunks,
430
+ body: cached.body,
432
431
  theme: cached.theme,
433
432
  cacheState: cached.cacheState,
434
433
  trace,
@@ -0,0 +1,13 @@
1
+ import type { ClientManifest } from "./artifact";
2
+ import type { RscRenderRequest } from "./rscRenderControl";
3
+
4
+ export class RscRenderManifest {
5
+ #held: { revision: number; manifest: ClientManifest } | null = null;
6
+
7
+ admit<T extends RscRenderRequest>(msg: T): T | null {
8
+ if (msg.manifestRevision === undefined) return msg;
9
+ if (msg.clientManifest) this.#held = { revision: msg.manifestRevision, manifest: msg.clientManifest };
10
+ if (this.#held?.revision !== msg.manifestRevision) return null;
11
+ return { ...msg, clientManifest: this.#held.manifest };
12
+ }
13
+ }
@@ -51,7 +51,7 @@ export class RscResultCaches {
51
51
 
52
52
  static #resultCacheOptions(): LruTtlCacheOptions<CachedRscResult> {
53
53
  return {
54
- sizeOf: (result) => result.bytes,
54
+ sizeOf: (result) => result.body.byteLength,
55
55
  maxBytes: LruTtlCache.parseByteCeiling(process.env.AKAN_RSC_RESULT_CACHE_MAX_BYTES),
56
56
  maxEntryBytes: LruTtlCache.parseByteCeiling(process.env.AKAN_RSC_RESULT_CACHE_MAX_BODY_BYTES),
57
57
  sweepIntervalMs: RESULT_CACHE_SWEEP_INTERVAL_MS,
@@ -68,7 +68,7 @@ export class RscResultCaches {
68
68
  store(kind: string, cache: LruTtlCache<CachedRscResult>, cacheKey: string, result: CachedRscResult, ttl: number) {
69
69
  if (cache.set(cacheKey, result, ttl)) return;
70
70
  this.#logger.verbose(
71
- `${kind} result cache store skipped pathname=${result.pathname} bytes=${result.bytes} reason=body-too-large`,
71
+ `${kind} result cache store skipped pathname=${result.pathname} bytes=${result.body.byteLength} reason=body-too-large`,
72
72
  );
73
73
  }
74
74
  }
@@ -15,6 +15,7 @@ import { RscPagePrompts } from "./rscPagePrompts";
15
15
  import { RscPatchPlanner } from "./rscPatchPlanner";
16
16
  import { RscRenderFallbacks } from "./rscRenderFallbacks";
17
17
  import { RscRenderHandler } from "./rscRenderHandler";
18
+ import { RscRenderManifest } from "./rscRenderManifest";
18
19
  import { RscRenderStats } from "./rscRenderStats";
19
20
  import { RscResultCaches } from "./rscResultCaches";
20
21
  import { RscRouteDocument } from "./rscRouteDocument";
@@ -38,6 +39,7 @@ interface RenderMsg {
38
39
  url: string;
39
40
  method?: string;
40
41
  headers?: Record<string, string>;
42
+ manifestRevision?: number;
41
43
  clientManifest?: ClientManifest;
42
44
  prefetch?: boolean;
43
45
  }
@@ -122,6 +124,7 @@ export class RscRenderer {
122
124
  #metricsTimer: Timer | null = null;
123
125
  readonly #stats = new RscRenderStats();
124
126
  readonly #caches = new RscResultCaches(this.#logger);
127
+ readonly #renderManifest = new RscRenderManifest();
125
128
  readonly #flights = new RscFlightRenderer(this.#logger, (message) => this.#send(message));
126
129
  readonly #staticApps = new RscStaticApp(this.#logger, this.#flights);
127
130
  readonly #send: (message: unknown) => void;
@@ -201,10 +204,19 @@ export class RscRenderer {
201
204
  this.#logger.verbose("received init message");
202
205
  void this.#handleInit(msg);
203
206
  return;
204
- case "render":
207
+ case "render": {
205
208
  this.#logger.verbose(`received render requestId=${msg.requestId} url=${msg.url} method=${msg.method ?? "GET"}`);
206
- void this.#renders.handleRender(msg);
209
+ const render = this.#renderManifest.admit(msg);
210
+ if (render) void this.#renders.handleRender(render);
211
+ else
212
+ this.#send({
213
+ type: "error",
214
+ requestId: msg.requestId,
215
+ manifestRevision: msg.manifestRevision,
216
+ message: `render names client manifest revision ${msg.manifestRevision}, which this worker was not sent`,
217
+ });
207
218
  return;
219
+ }
208
220
  case "cancel":
209
221
  this.#logger.verbose(`received cancel requestId=${msg.requestId}`);
210
222
  this.#flights.handleCancel(msg.requestId);
@@ -20,8 +20,7 @@ import {
20
20
  import type { RscTraceMetadata } from "./ssrTypes";
21
21
 
22
22
  export interface CachedRscResult {
23
- chunks: Uint8Array[];
24
- bytes: number;
23
+ body: Uint8Array;
25
24
  chunksCount: number;
26
25
  pathname: string;
27
26
  routeId?: string;
@@ -237,32 +236,31 @@ export type CachedRscReplayMessage =
237
236
  | { type: "chunk"; requestId: string; data: Uint8Array }
238
237
  | { type: "end"; requestId: string };
239
238
 
240
- function yieldToHostEventLoop(): Promise<void> {
241
- return new Promise((resolve) => setTimeout(resolve, 0));
239
+ export function joinRscChunks(chunks: readonly Uint8Array[]): Uint8Array {
240
+ const body = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.byteLength, 0));
241
+ let offset = 0;
242
+ for (const chunk of chunks) {
243
+ body.set(chunk, offset);
244
+ offset += chunk.byteLength;
245
+ }
246
+ return body;
242
247
  }
243
248
 
244
- export async function replayCachedRscResult(input: {
249
+ export function replayCachedRscResult(input: {
245
250
  requestId: string;
246
- chunks: readonly Uint8Array[];
251
+ body: Uint8Array;
247
252
  theme?: string;
248
253
  trace?: RscTraceMetadata;
249
254
  cacheState?: RouteCacheRenderState;
250
255
  send: (message: CachedRscReplayMessage) => void;
251
256
  isCancelled: () => boolean;
252
- yieldToHost?: () => Promise<void>;
253
- }): Promise<boolean> {
254
- const yieldToHost = input.yieldToHost ?? yieldToHostEventLoop;
257
+ }): boolean {
255
258
  if (input.isCancelled()) return false;
256
259
  const metaMessage: CachedRscReplayMessage = { type: "meta", requestId: input.requestId, theme: input.theme };
257
260
  if (input.trace) metaMessage.trace = input.trace;
258
261
  input.send(metaMessage);
259
262
  input.send({ type: "cache-state", requestId: input.requestId, state: input.cacheState ?? { cacheable: true } });
260
- for (let index = 0; index < input.chunks.length; index += 1) {
261
- if (input.isCancelled()) return false;
262
- input.send({ type: "chunk", requestId: input.requestId, data: input.chunks[index] });
263
- await yieldToHost();
264
- }
265
- if (input.isCancelled()) return false;
263
+ if (input.body.byteLength > 0) input.send({ type: "chunk", requestId: input.requestId, data: input.body });
266
264
  input.send({ type: "end", requestId: input.requestId });
267
265
  return true;
268
266
  }
@@ -134,6 +134,8 @@ type RscInMsg =
134
134
  buildId?: number;
135
135
  reloadId?: number;
136
136
  running?: RscAdoptedBundle;
137
+ /** Set when the worker refused a render for naming a manifest revision it does not hold. */
138
+ manifestRevision?: number;
137
139
  };
138
140
 
139
141
  export class RscWorker {
@@ -386,6 +388,7 @@ export class RscWorker {
386
388
  )
387
389
  )
388
390
  return;
391
+ if (message.manifestRevision !== undefined) this.#requests.forgetManifest();
389
392
  this.#requests.resolvePending(message.requestId, (p) => p.onError(String(message.message)));
390
393
  return;
391
394
  }
@@ -15,6 +15,9 @@ import {
15
15
  type CacheRow = { value: string | Buffer | null; valueType: SolidValueType; expiresAt: number | null };
16
16
  type CacheEntryRow = CacheRow & { subKey: string };
17
17
 
18
+ const CACHE_TABLES = ["_akan_solid_cache", "_akan_solid_cache_hash"] as const;
19
+ const SWEEP_BATCH = 1000;
20
+
18
21
  export class SolidCache
19
22
  extends adapt("solidCache", ({ env }) => ({
20
23
  config: env((env: SolidEnv) => getSolidConfig(env)),
@@ -23,6 +26,8 @@ export class SolidCache
23
26
  {
24
27
  #db!: Database;
25
28
  #cleanupTimer: Timer | null = null;
29
+ #sweeping: boolean = false;
30
+ #closed: boolean = false;
26
31
 
27
32
  override async onInit() {
28
33
  this.#db = await openSolidDatabase(this.config as Required<SolidConfig>);
@@ -51,11 +56,16 @@ export class SolidCache
51
56
  PRIMARY KEY ("topic", "key", "subKey")
52
57
  )`,
53
58
  );
54
- this.#cleanupTimer = setInterval(() => this.#cleanup(), this.config.cleanupIntervalMs);
55
- this.#cleanup();
59
+ for (const table of CACHE_TABLES)
60
+ this.#db.run(
61
+ `CREATE INDEX IF NOT EXISTS "${table}_expiry_idx" ON "${table}" ("expiresAt") WHERE "expiresAt" IS NOT NULL`,
62
+ );
63
+ this.#cleanupTimer = setInterval(() => this.#startCleanup(), this.config.cleanupIntervalMs);
64
+ this.#startCleanup();
56
65
  }
57
66
 
58
67
  override async onDestroy() {
68
+ this.#closed = true;
59
69
  if (this.#cleanupTimer) clearInterval(this.#cleanupTimer);
60
70
  this.#db?.run("PRAGMA wal_checkpoint(TRUNCATE)");
61
71
  this.#db?.close();
@@ -78,12 +88,15 @@ export class SolidCache
78
88
  }
79
89
 
80
90
  async get<T extends CacheValue = CacheValue>(topic: string, key: string): Promise<T | undefined> {
91
+ const now = Date.now();
81
92
  const row = this.#db
82
93
  .query(`SELECT "value", "valueType", "expiresAt" FROM "_akan_solid_cache" WHERE "topic" = ? AND "key" = ?`)
83
94
  .get(topic, key) as CacheRow | null;
84
95
  if (!row) return undefined;
85
- if (row.expiresAt !== null && row.expiresAt <= Date.now()) {
86
- await this.delete(topic, key);
96
+ if (row.expiresAt !== null && row.expiresAt <= now) {
97
+ this.#db
98
+ .query(`DELETE FROM "_akan_solid_cache" WHERE "topic" = ? AND "key" = ? AND "expiresAt" <= ?`)
99
+ .run(topic, key, now);
87
100
  return undefined;
88
101
  }
89
102
  return decodeSolidValue<T>(row.valueType, row.value);
@@ -191,14 +204,19 @@ export class SolidCache
191
204
  }
192
205
 
193
206
  async hget<T extends CacheValue = CacheValue>(topic: string, key: string, subKey: string): Promise<T | undefined> {
207
+ const now = Date.now();
194
208
  const row = this.#db
195
209
  .query(
196
210
  `SELECT "value", "valueType", "expiresAt" FROM "_akan_solid_cache_hash" WHERE "topic" = ? AND "key" = ? AND "subKey" = ?`,
197
211
  )
198
212
  .get(topic, key, subKey) as CacheRow | null;
199
213
  if (!row) return undefined;
200
- if (row.expiresAt !== null && row.expiresAt <= Date.now()) {
201
- await this.hdelete(topic, key, subKey);
214
+ if (row.expiresAt !== null && row.expiresAt <= now) {
215
+ this.#db
216
+ .query(
217
+ `DELETE FROM "_akan_solid_cache_hash" WHERE "topic" = ? AND "key" = ? AND "subKey" = ? AND "expiresAt" <= ?`,
218
+ )
219
+ .run(topic, key, subKey, now);
202
220
  return undefined;
203
221
  }
204
222
  return decodeSolidValue<T>(row.valueType, row.value);
@@ -211,20 +229,22 @@ export class SolidCache
211
229
  }
212
230
 
213
231
  async hkeys(topic: string, key: string): Promise<string[]> {
214
- this.#cleanup();
215
232
  const rows = this.#db
216
- .query(`SELECT "subKey" FROM "_akan_solid_cache_hash" WHERE "topic" = ? AND "key" = ? ORDER BY "subKey" ASC`)
217
- .all(topic, key) as { subKey: string }[];
233
+ .query(
234
+ `SELECT "subKey" FROM "_akan_solid_cache_hash"
235
+ WHERE "topic" = ? AND "key" = ? AND ("expiresAt" IS NULL OR "expiresAt" > ?) ORDER BY "subKey" ASC`,
236
+ )
237
+ .all(topic, key, Date.now()) as { subKey: string }[];
218
238
  return rows.map((row) => row.subKey);
219
239
  }
220
240
 
221
241
  async hentries<T extends CacheValue = CacheValue>(topic: string, key: string): Promise<[string, T][]> {
222
- this.#cleanup();
223
242
  const rows = this.#db
224
243
  .query(
225
- `SELECT "subKey", "value", "valueType", "expiresAt" FROM "_akan_solid_cache_hash" WHERE "topic" = ? AND "key" = ? ORDER BY "subKey" ASC`,
244
+ `SELECT "subKey", "value", "valueType", "expiresAt" FROM "_akan_solid_cache_hash"
245
+ WHERE "topic" = ? AND "key" = ? AND ("expiresAt" IS NULL OR "expiresAt" > ?) ORDER BY "subKey" ASC`,
226
246
  )
227
- .all(topic, key) as CacheEntryRow[];
247
+ .all(topic, key, Date.now()) as CacheEntryRow[];
228
248
  return rows.map((row) => [row.subKey, decodeSolidValue<T>(row.valueType, row.value) as T]);
229
249
  }
230
250
 
@@ -280,9 +300,31 @@ export class SolidCache
280
300
  return Number(row?.value);
281
301
  }
282
302
 
283
- #cleanup() {
303
+ #startCleanup() {
304
+ if (this.#sweeping) return;
305
+ this.#sweeping = true;
306
+ void this.#cleanup()
307
+ .catch((error: unknown) => {
308
+ this.logger.warn(`Solid cache cleanup failed: ${error instanceof Error ? error.message : String(error)}`);
309
+ })
310
+ .finally(() => {
311
+ this.#sweeping = false;
312
+ });
313
+ }
314
+
315
+ async #cleanup() {
284
316
  const now = Date.now();
285
- this.#db.query(`DELETE FROM "_akan_solid_cache" WHERE "expiresAt" IS NOT NULL AND "expiresAt" <= ?`).run(now);
286
- this.#db.query(`DELETE FROM "_akan_solid_cache_hash" WHERE "expiresAt" IS NOT NULL AND "expiresAt" <= ?`).run(now);
317
+ for (const table of CACHE_TABLES)
318
+ while (!this.#closed) {
319
+ const { changes } = this.#db
320
+ .query(
321
+ `DELETE FROM "${table}" WHERE rowid IN (
322
+ SELECT rowid FROM "${table}" WHERE "expiresAt" IS NOT NULL AND "expiresAt" <= ? LIMIT ${SWEEP_BATCH}
323
+ )`,
324
+ )
325
+ .run(now);
326
+ if (changes < SWEEP_BATCH) break;
327
+ await new Promise((resolve) => setTimeout(resolve, 0));
328
+ }
287
329
  }
288
330
  }