akanjs 2.4.2-rc.3 → 3.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/base/baseEnv.ts +0 -6
  2. package/client/cn.ts +52 -0
  3. package/client/csrTypes.ts +2 -2
  4. package/client/frameConfig.ts +2 -2
  5. package/client/index.ts +1 -0
  6. package/client/types.ts +0 -4
  7. package/common/index.ts +1 -0
  8. package/common/isThenable.ts +12 -0
  9. package/package.json +4 -7
  10. package/server/SSR_MEMORY_DIAGNOSIS.md +19 -2
  11. package/server/akanApp.ts +2 -0
  12. package/server/cachePolicy.ts +114 -12
  13. package/server/processMetricsCollector.ts +4 -0
  14. package/server/rscWorker.tsx +32 -4
  15. package/server/rscWorkerHost.ts +61 -12
  16. package/server/ssrFromRscRenderer.tsx +2 -2
  17. package/server/systemPageDocument.tsx +12 -12
  18. package/server/webRouter.ts +9 -0
  19. package/service/ipcTypes.ts +25 -0
  20. package/store/baseSt.ts +2 -2
  21. package/test/signalTestRuntime.ts +0 -2
  22. package/types/base/baseEnv.d.ts +0 -2
  23. package/types/client/cn.d.ts +12 -0
  24. package/types/client/index.d.ts +1 -0
  25. package/types/client/types.d.ts +0 -3
  26. package/types/common/index.d.ts +1 -0
  27. package/types/common/isThenable.d.ts +9 -0
  28. package/types/server/cachePolicy.d.ts +33 -2
  29. package/types/server/rscWorkerHost.d.ts +13 -0
  30. package/types/service/ipcTypes.d.ts +24 -0
  31. package/types/ui/Badge.d.ts +6 -0
  32. package/types/ui/Button.d.ts +26 -6
  33. package/types/ui/RecentTime.d.ts +1 -1
  34. package/types/ui/Signal/Collapse.d.ts +12 -0
  35. package/types/ui/Signal/style.d.ts +5 -6
  36. package/types/ui/Switch.d.ts +14 -0
  37. package/types/ui/Tooltip.d.ts +11 -0
  38. package/types/ui/UiOverride/Provider.d.ts +6 -5
  39. package/types/ui/UiOverride/context.d.ts +22 -1
  40. package/types/ui/UiOverride/index.d.ts +2 -1
  41. package/types/ui/UiOverride/override.d.ts +7 -6
  42. package/types/ui/UiOverride/useUiRecipe.d.ts +8 -0
  43. package/types/ui/index.d.ts +5 -1
  44. package/types/ui/recipe/badgeRecipe.d.ts +13 -0
  45. package/types/ui/recipe/buttonRecipe.d.ts +15 -0
  46. package/types/ui/recipe/factory.d.ts +24 -0
  47. package/types/ui/recipe/index.d.ts +18 -0
  48. package/types/ui/recipe/inputRecipe.d.ts +13 -0
  49. package/types/ui/recipe.d.ts +1 -0
  50. package/ui/Badge.tsx +17 -0
  51. package/ui/BottomSheet.tsx +8 -10
  52. package/ui/Button.tsx +158 -48
  53. package/ui/Clipboard.tsx +3 -3
  54. package/ui/Constant/Doc.tsx +108 -65
  55. package/ui/Constant/Mermaid.tsx +9 -9
  56. package/ui/Data/CardList.tsx +3 -3
  57. package/ui/Data/Dashboard.tsx +22 -13
  58. package/ui/Data/Insight.tsx +6 -6
  59. package/ui/Data/Item.tsx +49 -34
  60. package/ui/Data/ListContainer.tsx +11 -7
  61. package/ui/Data/Pagination.tsx +2 -2
  62. package/ui/DatePicker.tsx +5 -5
  63. package/ui/Dialog/Content.tsx +2 -2
  64. package/ui/Dialog/Modal.tsx +12 -8
  65. package/ui/Dialog/Provider.tsx +2 -2
  66. package/ui/DragAction.tsx +2 -2
  67. package/ui/DraggableList.tsx +10 -5
  68. package/ui/Dropdown.tsx +33 -26
  69. package/ui/Empty.tsx +5 -5
  70. package/ui/Field.tsx +82 -70
  71. package/ui/Image.tsx +2 -2
  72. package/ui/Input.tsx +62 -60
  73. package/ui/Layout/BottomInset.tsx +2 -2
  74. package/ui/Layout/BottomTab.tsx +5 -5
  75. package/ui/Layout/Header.tsx +3 -3
  76. package/ui/Layout/LeftSider.tsx +6 -5
  77. package/ui/Layout/Navbar.tsx +2 -12
  78. package/ui/Layout/RightSider.tsx +10 -8
  79. package/ui/Layout/Sider.tsx +5 -4
  80. package/ui/Layout/Template.tsx +2 -2
  81. package/ui/Layout/TopInset.tsx +2 -2
  82. package/ui/Layout/Unit.tsx +2 -2
  83. package/ui/Layout/View.tsx +2 -2
  84. package/ui/Layout/Zone.tsx +2 -2
  85. package/ui/Link/Back.tsx +2 -2
  86. package/ui/Link/Close.tsx +2 -2
  87. package/ui/Link/CsrLink.tsx +6 -4
  88. package/ui/Link/Lang.tsx +2 -2
  89. package/ui/Link/SsrLink.tsx +6 -5
  90. package/ui/Load/Page.tsx +1 -1
  91. package/ui/Load/Pagination.tsx +2 -2
  92. package/ui/Load/Units.tsx +2 -4
  93. package/ui/Load/View.tsx +2 -2
  94. package/ui/Loading/Area.tsx +4 -2
  95. package/ui/Loading/Button.tsx +2 -2
  96. package/ui/Loading/Input.tsx +2 -2
  97. package/ui/Loading/ProgressBar.tsx +2 -2
  98. package/ui/Loading/Skeleton.tsx +6 -6
  99. package/ui/Loading/Spin.tsx +2 -2
  100. package/ui/Menu.tsx +29 -27
  101. package/ui/Model/Edit.tsx +3 -3
  102. package/ui/Model/EditModal.tsx +5 -5
  103. package/ui/Model/EditWrapper.tsx +2 -2
  104. package/ui/Model/New.tsx +3 -3
  105. package/ui/Model/NewWrapper_Client.tsx +2 -2
  106. package/ui/Model/Remove.tsx +5 -4
  107. package/ui/Model/RemoveWrapper.tsx +2 -2
  108. package/ui/Model/SureToRemove.tsx +7 -6
  109. package/ui/Model/View.tsx +2 -2
  110. package/ui/Model/ViewEditModal.tsx +20 -21
  111. package/ui/Model/ViewWrapper.tsx +2 -2
  112. package/ui/More.tsx +2 -2
  113. package/ui/ObjectId.tsx +9 -3
  114. package/ui/Pagination.tsx +14 -11
  115. package/ui/Popconfirm.tsx +20 -11
  116. package/ui/Radio.tsx +4 -4
  117. package/ui/RecentTime.tsx +30 -83
  118. package/ui/Refresh.tsx +1 -1
  119. package/ui/ScreenNavigator.tsx +2 -2
  120. package/ui/Select.tsx +21 -23
  121. package/ui/Signal/Arg.tsx +20 -17
  122. package/ui/Signal/Collapse.tsx +29 -0
  123. package/ui/Signal/Doc.tsx +27 -22
  124. package/ui/Signal/Listener.tsx +3 -3
  125. package/ui/Signal/Message.tsx +31 -17
  126. package/ui/Signal/Object.tsx +13 -8
  127. package/ui/Signal/PubSub.tsx +26 -16
  128. package/ui/Signal/Request.tsx +3 -2
  129. package/ui/Signal/Response.tsx +5 -4
  130. package/ui/Signal/RestApi.tsx +27 -17
  131. package/ui/Signal/style.ts +16 -16
  132. package/ui/Switch.tsx +62 -0
  133. package/ui/System/CSR.tsx +40 -35
  134. package/ui/System/Client.tsx +2 -2
  135. package/ui/System/DevModeToggle.tsx +10 -12
  136. package/ui/System/Messages.tsx +14 -16
  137. package/ui/System/Reconnect.tsx +7 -7
  138. package/ui/System/SSR.tsx +25 -21
  139. package/ui/System/SelectLanguage.tsx +24 -28
  140. package/ui/System/ThemeToggle.tsx +38 -45
  141. package/ui/Tab/Menu.tsx +20 -18
  142. package/ui/Tab/Panel.tsx +3 -3
  143. package/ui/Tab/Provider.tsx +2 -2
  144. package/ui/Table.tsx +11 -8
  145. package/ui/ToggleSelect.tsx +14 -18
  146. package/ui/Tooltip.tsx +55 -0
  147. package/ui/UiOverride/Provider.tsx +10 -6
  148. package/ui/UiOverride/context.ts +22 -2
  149. package/ui/UiOverride/index.ts +8 -1
  150. package/ui/UiOverride/override.ts +7 -6
  151. package/ui/UiOverride/useUiRecipe.ts +15 -0
  152. package/ui/Unauthorized.tsx +5 -5
  153. package/ui/index.ts +16 -0
  154. package/ui/recipe/badgeRecipe.ts +23 -0
  155. package/ui/recipe/buttonRecipe.ts +32 -0
  156. package/ui/recipe/factory.ts +32 -0
  157. package/ui/recipe/index.ts +18 -0
  158. package/ui/recipe/inputRecipe.ts +13 -0
  159. package/ui/styles.css +150 -21
package/base/baseEnv.ts CHANGED
@@ -13,8 +13,6 @@ export interface BaseEnv {
13
13
  appName: string;
14
14
  environment: Environment;
15
15
  operationMode: "local" | "edge" | "cloud" | "module";
16
- tunnelUsername: string;
17
- tunnelPassword: string;
18
16
  databaseMode?: DatabaseMode;
19
17
  }
20
18
  export type BackendEnv = BaseEnv & {
@@ -87,16 +85,12 @@ export const getEnv = (): ClientEnv => {
87
85
  const environment = (process.env.AKAN_PUBLIC_ENV ?? "debug") as BaseEnv["environment"];
88
86
  const operationMode = (process.env.AKAN_PUBLIC_OPERATION_MODE ??
89
87
  (environment === "local" ? "local" : "cloud")) as BaseEnv["operationMode"];
90
- const tunnelUsername = process.env.SSH_TUNNEL_USERNAME ?? "root";
91
- const tunnelPassword = process.env.SSH_TUNNEL_PASSWORD ?? repoName;
92
88
  const baseEnv: BaseEnv = {
93
89
  repoName,
94
90
  serveDomain,
95
91
  appName,
96
92
  environment,
97
93
  operationMode,
98
- tunnelUsername,
99
- tunnelPassword,
100
94
  databaseMode: process.env.AKAN_DATABASE_MODE as DatabaseMode | undefined,
101
95
  } as const;
102
96
  const side = typeof window === "undefined" ? "server" : "client";
package/client/cn.ts ADDED
@@ -0,0 +1,52 @@
1
+ import { type ClassNameValue, extendTailwindMerge } from "tailwind-merge";
2
+
3
+ /**
4
+ * Akan's semantic color tokens beyond tailwind-merge's built-in Tailwind palette.
5
+ * Registering them under `theme.color` teaches tailwind-merge that `bg-*`/`text-*`/
6
+ * `border-*`/… built from these names belong to the same conflict group, so
7
+ * `cn("bg-primary", "bg-open")` correctly resolves to `"bg-open"` instead of keeping both.
8
+ */
9
+ export const colorTokens = [
10
+ "background",
11
+ "foreground",
12
+ "primary",
13
+ "primary-foreground",
14
+ "secondary",
15
+ "secondary-foreground",
16
+ "accent",
17
+ "accent-foreground",
18
+ "muted",
19
+ "muted-foreground",
20
+ "destructive",
21
+ "destructive-foreground",
22
+ "card",
23
+ "card-foreground",
24
+ "popover",
25
+ "popover-foreground",
26
+ "info",
27
+ "info-foreground",
28
+ "success",
29
+ "success-foreground",
30
+ "warning",
31
+ "warning-foreground",
32
+ "neutral",
33
+ "neutral-foreground",
34
+ "open",
35
+ "open-foreground",
36
+ "border",
37
+ "input",
38
+ "ring",
39
+ ];
40
+
41
+ const twMerge = extendTailwindMerge({
42
+ extend: {
43
+ theme: {
44
+ color: colorTokens,
45
+ },
46
+ },
47
+ });
48
+
49
+ /** The one class-combining function: joins strings/arrays/conditional parts (`cond && "x"`) and
50
+ * resolves Tailwind conflicts with a shared tailwind-merge instance that knows Akan's semantic
51
+ * color tokens. clsx-style object syntax (`{ x: cond }`) is not supported — write `cond && "x"`. */
52
+ export const cn = (...inputs: ClassNameValue[]) => twMerge(...inputs);
@@ -270,8 +270,8 @@ export const defaultPageState: PageState = {
270
270
  gesture: true,
271
271
  cache: false,
272
272
  ssr: "stream",
273
- topSafeAreaColor: "var(--color-base-100, Canvas)",
274
- bottomSafeAreaColor: "var(--color-base-100, Canvas)",
273
+ topSafeAreaColor: "var(--color-background, Canvas)",
274
+ bottomSafeAreaColor: "var(--color-background, Canvas)",
275
275
  };
276
276
 
277
277
  export interface Location {
@@ -152,8 +152,8 @@ export function resolvePageState({
152
152
  : (config.gesture ?? false),
153
153
  cache: config.cache ?? false,
154
154
  ssr: config.ssr ?? "stream",
155
- topSafeAreaColor: config.topSafeAreaColor ?? "var(--color-base-100, Canvas)",
156
- bottomSafeAreaColor: config.bottomSafeAreaColor ?? "var(--color-base-100, Canvas)",
155
+ topSafeAreaColor: config.topSafeAreaColor ?? "var(color-background, Canvas)",
156
+ bottomSafeAreaColor: config.bottomSafeAreaColor ?? "var(color-background, Canvas)",
157
157
  };
158
158
  }
159
159
 
package/client/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from "./clientRuntime";
2
+ export * from "./cn";
2
3
  export * from "./cookie";
3
4
  export * from "./createFont";
4
5
  export * from "./csrTypes";
package/client/types.ts CHANGED
@@ -1,11 +1,7 @@
1
1
  import type { BaseInsight } from "akanjs/constant";
2
2
  import type { FetchInitForm, SliceMeta } from "akanjs/fetch";
3
- import { type ClassValue, clsx as clsxLib } from "clsx";
4
3
  import type { ReactElement, ReactNode } from "react";
5
4
 
6
- /** Composes class names with the shared clsx implementation. */
7
- export const clsx = (...args: ClassValue[]) => clsxLib(...args);
8
-
9
5
  export type ReactFontStyle = "normal" | "italic" | "oblique";
10
6
  export type ReactFontDisplay = "auto" | "block" | "swap" | "fallback" | "optional";
11
7
  export type ReactFontCategory = "monospace" | "sans-serif" | "serif" | "display";
package/common/index.ts CHANGED
@@ -15,6 +15,7 @@ export { isDayjs } from "./isDayjs";
15
15
  export { isEmail } from "./isEmail";
16
16
  export { isPhoneNumber } from "./isPhoneNumber";
17
17
  export { isQueryEqual } from "./isQueryEqual";
18
+ export { isThenable } from "./isThenable";
18
19
  export { isValidDate } from "./isValidDate";
19
20
  export { decodeJwtPayload } from "./jwtDecode";
20
21
  export { Logger, type LoggerSink, type LoggerSinkEntry, type LogLevel } from "./Logger";
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Whether a value is awaitable. Duck-typed rather than `instanceof Promise` so a thenable produced by a
3
+ * different realm or promise implementation still counts — a same-realm check silently misses those.
4
+ *
5
+ * `<Button>` uses this to decide whether a click handler is asynchronous: a handler that returns a
6
+ * thenable gets the pending/success states, a plain one renders as an ordinary button. That makes the
7
+ * distinction impossible to forget, unlike an explicit flag.
8
+ */
9
+ export const isThenable = (value: unknown): value is PromiseLike<unknown> =>
10
+ !!value &&
11
+ (typeof value === "object" || typeof value === "function") &&
12
+ typeof Reflect.get(value, "then") === "function";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "2.4.2-rc.3",
3
+ "version": "3.0.0-alpha.1",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -178,10 +178,11 @@
178
178
  }
179
179
  },
180
180
  "dependencies": {
181
- "clsx": "^2.1.1",
182
181
  "dayjs": "^1.11.20",
183
182
  "immer": "^11.1.8",
184
- "sharp": "^0.34.5"
183
+ "sharp": "^0.34.5",
184
+ "tailwind-merge": "^3.3.1",
185
+ "tailwind-variants": "^3.3.0"
185
186
  },
186
187
  "peerDependencies": {
187
188
  "@capacitor-community/contacts": "^7.2.0",
@@ -210,7 +211,6 @@
210
211
  "chance": "^1.1.13",
211
212
  "cordova-plugin-purchase": "^13.16.0",
212
213
  "croner": "^10.0.1",
213
- "daisyui": "5.5.23",
214
214
  "firebase": "^12.13.0",
215
215
  "ioredis": "^5.10.1",
216
216
  "mermaid": "^11.15.0",
@@ -308,9 +308,6 @@
308
308
  "croner": {
309
309
  "optional": true
310
310
  },
311
- "daisyui": {
312
- "optional": true
313
- },
314
311
  "firebase": {
315
312
  "optional": true
316
313
  },
@@ -23,14 +23,31 @@ Read snapshots from:
23
23
  curl http://localhost:8080/_akan/app/metrics
24
24
  ```
25
25
 
26
+ A replica and its RSC worker are separate processes and are reported separately. **`rssBytes` is the
27
+ replica's own; the worker's is `rscWorkerRssBytes`.** Sum them for what the pod pays.
28
+
26
29
  Key fields:
27
30
 
28
- - `rssBytes`, `heapUsedBytes`, `jscHeapSizeBytes`: distinguish RSS-only native retention from JS heap retention.
31
+ - `rssBytes`, `heapUsedBytes`, `jscHeapSizeBytes`: the replica. Distinguish RSS-only native retention from JS
32
+ heap retention.
33
+ - `rscWorkerRssBytes`, `rscWorkerHeapUsedBytes`, `rscWorkerJscHeapSizeBytes`, `rscWorkerJscExtraMemorySizeBytes`:
34
+ the same for the worker. `jscExtra` is off-heap, mostly typed-array backing stores.
29
35
  - `rscRenderCount`, `rscInFlightRenderCount`: detect request lifecycle leaks.
30
36
  - `rscLoadedRouteModuleCount`, `rscRouteModuleCacheHits`, `rscRouteModuleCacheMisses`: detect route module warm-up.
31
- - `ssrChunkRegistrySize`, `ssrChunkLoadCount`: detect full-document SSR client chunk retention.
37
+ - `ssrChunkRegistrySize`, `ssrChunkLoadCount`: full-document SSR client chunk loading. **`…RegistrySize` counts
38
+ keys, not bytes** — evicting does not unload the module, so it can never fall on its own.
39
+ - `httpHtmlCacheEntries` / `httpHtmlCacheBytes`, `rscResultCacheEntries` / `rscResultCacheBytes`,
40
+ `rscPatchResultCacheEntries` / `rscPatchResultCacheBytes`: what each cache actually holds. Entry count alone
41
+ says nothing when entries span three orders of magnitude.
32
42
  - `httpFullSsrCount`, `httpRscNavigationCount`, `httpStaticAssetCount`, `httpImageCount`: separate request kinds.
33
43
 
44
+ Two things measured on `apps/akan` that shape how to read all of the above:
45
+
46
+ - **Growth converges; it is not a leak.** Ten passes over the same routes plateau by roughly the sixth, with a
47
+ flat JS heap throughout. Three passes is not enough to tell a plateau from a ratchet.
48
+ - **Freeing JS objects does not lower RSS.** Emptying both result caches returns their bytes to the heap and
49
+ leaves RSS unchanged. Only not allocating, or restarting the process, reduces what the pod pays.
50
+
34
51
  ## Scenarios
35
52
 
36
53
  ### Same Route Repeated
package/server/akanApp.ts CHANGED
@@ -1,3 +1,5 @@
1
+
2
+
1
3
  import { mkdir, readdir, rm } from "node:fs/promises";
2
4
  import path from "node:path";
3
5
  import { Logger } from "akanjs/common";
@@ -234,20 +234,62 @@ export function shouldInvalidateRouteCacheEntry(
234
234
  return false;
235
235
  }
236
236
 
237
- export class LruTtlCache<T> {
238
- readonly #entries = new Map<string, { value: T; expiresAt: number }>();
237
+ export interface LruTtlCacheOptions<T> {
238
+ /**
239
+ * Measures one entry's payload. Entry count alone says nothing about a cache whose entries span
240
+ * three orders of magnitude, and a byte ceiling needs a running total to enforce. The default
241
+ * reports 0 rather than guessing, so `byteSize` stays honest about not knowing.
242
+ */
243
+ sizeOf?: (value: T) => number;
244
+ /** Total payload ceiling. 0 leaves the cache bounded only by `maxEntries`. */
245
+ maxBytes?: number;
246
+ /** An entry over this is not stored at all, rather than evicting everything else to fit it. */
247
+ maxEntryBytes?: number;
248
+ /**
249
+ * Cadence of the idle sweep. Without one a filled cache never shrinks: an entry is dropped only
250
+ * when its own key is fetched after expiry or when a write evicts it, so a pod that stops
251
+ * serving holds its peak forever — measured at 100 entries / 21.4 MiB still resident 310s after
252
+ * the last request, with a 30s TTL. 0 disables it.
253
+ */
254
+ sweepIntervalMs?: number;
255
+ }
239
256
 
240
- constructor(readonly maxEntries = 100) {}
257
+ export class LruTtlCache<T> {
258
+ readonly #entries = new Map<string, { value: T; expiresAt: number; byteLength: number }>();
259
+ #byteLength = 0;
260
+ #sweepTimer: ReturnType<typeof setInterval> | null = null;
261
+ readonly #sizeOf: (value: T) => number;
262
+ readonly #maxBytes: number;
263
+ readonly #maxEntryBytes: number;
264
+
265
+ constructor(
266
+ readonly maxEntries = 100,
267
+ options: LruTtlCacheOptions<T> = {},
268
+ ) {
269
+ this.#sizeOf = options.sizeOf ?? (() => 0);
270
+ this.#maxBytes = options.maxBytes ?? 0;
271
+ this.#maxEntryBytes = options.maxEntryBytes ?? 0;
272
+ const sweepIntervalMs = options.sweepIntervalMs ?? 0;
273
+ if (sweepIntervalMs > 0) {
274
+ this.#sweepTimer = setInterval(() => this.sweepExpired(), sweepIntervalMs);
275
+
276
+ (this.#sweepTimer as { unref?: () => void }).unref?.();
277
+ }
278
+ }
241
279
 
242
280
  get size(): number {
243
281
  return this.#entries.size;
244
282
  }
245
283
 
284
+ get byteSize(): number {
285
+ return this.#byteLength;
286
+ }
287
+
246
288
  get(key: string): T | null {
247
289
  const entry = this.#entries.get(key);
248
290
  if (!entry) return null;
249
291
  if (entry.expiresAt <= Date.now()) {
250
- this.#entries.delete(key);
292
+ this.#remove(key);
251
293
  return null;
252
294
  }
253
295
  this.#entries.delete(key);
@@ -255,26 +297,56 @@ export class LruTtlCache<T> {
255
297
  return entry.value;
256
298
  }
257
299
 
258
- set(key: string, value: T, ttlSeconds: number): void {
259
- this.#entries.delete(key);
300
+ /** Returns whether the entry was stored; a payload over `maxEntryBytes` is rejected. */
301
+ set(key: string, value: T, ttlSeconds: number): boolean {
302
+ this.#remove(key);
303
+ const byteLength = LruTtlCache.#measure(this.#sizeOf, value);
304
+ if (this.#maxEntryBytes > 0 && byteLength > this.#maxEntryBytes) return false;
305
+ this.sweepExpired();
260
306
  const maxEntries = this.maxEntries > 0 ? this.maxEntries : 100;
261
307
  while (this.#entries.size >= maxEntries) {
262
- const oldest = this.#entries.keys().next().value;
263
- if (!oldest) break;
264
- this.#entries.delete(oldest);
308
+ if (!this.#removeOldest()) break;
309
+ }
310
+ while (this.#maxBytes > 0 && this.#entries.size > 0 && this.#byteLength + byteLength > this.#maxBytes) {
311
+ if (!this.#removeOldest()) break;
265
312
  }
266
- this.#entries.set(key, { value, expiresAt: Date.now() + ttlSeconds * 1000 });
313
+ this.#entries.set(key, { value, expiresAt: Date.now() + ttlSeconds * 1000, byteLength });
314
+ this.#byteLength += byteLength;
315
+ return true;
316
+ }
317
+
318
+ /**
319
+ * Drops every expired entry. Deliberately a full scan rather than a walk from the oldest that
320
+ * stops at the first live entry: insertion order is *LRU* order because `get` reinserts, and TTLs
321
+ * differ per entry, so expiry is not monotonic in map order and an early break would leave
322
+ * expired entries behind. The map is bounded by `maxEntries`, so the scan is cheap.
323
+ */
324
+ sweepExpired(now = Date.now()): number {
325
+ let removed = 0;
326
+ for (const [key, entry] of this.#entries) {
327
+ if (entry.expiresAt > now) continue;
328
+ this.#remove(key);
329
+ removed += 1;
330
+ }
331
+ return removed;
332
+ }
333
+
334
+ /** Stops the idle sweep. The cache stays usable; only the timer goes away. */
335
+ dispose(): void {
336
+ if (!this.#sweepTimer) return;
337
+ clearInterval(this.#sweepTimer);
338
+ this.#sweepTimer = null;
267
339
  }
268
340
 
269
341
  delete(key: string): boolean {
270
- return this.#entries.delete(key);
342
+ return this.#remove(key);
271
343
  }
272
344
 
273
345
  invalidate(predicate: (key: string, value: T) => boolean): number {
274
346
  let count = 0;
275
347
  for (const [key, entry] of this.#entries) {
276
348
  if (!predicate(key, entry.value)) continue;
277
- this.#entries.delete(key);
349
+ this.#remove(key);
278
350
  count += 1;
279
351
  }
280
352
  return count;
@@ -282,5 +354,35 @@ export class LruTtlCache<T> {
282
354
 
283
355
  clear(): void {
284
356
  this.#entries.clear();
357
+ this.#byteLength = 0;
358
+ }
359
+
360
+ static parseByteCeiling(value: string | undefined | null, fallback = 0): number {
361
+ const parsed = Number.parseInt(value ?? "", 10);
362
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
363
+ }
364
+
365
+ #remove(key: string): boolean {
366
+ const entry = this.#entries.get(key);
367
+ if (!entry) return false;
368
+ this.#entries.delete(key);
369
+ this.#byteLength -= entry.byteLength;
370
+ return true;
371
+ }
372
+
373
+ #removeOldest(): boolean {
374
+ const oldest = this.#entries.keys().next().value;
375
+ if (!oldest) return false;
376
+ return this.#remove(oldest);
377
+ }
378
+
379
+ /** A measurement must never fail a cache write, and a bad measurement must never skew the total. */
380
+ static #measure<T>(sizeOf: (value: T) => number, value: T): number {
381
+ try {
382
+ const measured = sizeOf(value);
383
+ return Number.isFinite(measured) && measured > 0 ? measured : 0;
384
+ } catch {
385
+ return 0;
386
+ }
285
387
  }
286
388
  }
@@ -138,6 +138,10 @@ export class ProcessMetricsCollector {
138
138
  ...(metrics.jscHeapSizeBytes !== undefined
139
139
  ? [`jscHeap=${ProcessMetricsCollector.formatBytes(metrics.jscHeapSizeBytes)}`]
140
140
  : []),
141
+
142
+ ...(metrics.rscWorkerRssBytes !== undefined
143
+ ? [`rscWorkerRss=${ProcessMetricsCollector.formatBytes(metrics.rscWorkerRssBytes)}`]
144
+ : []),
141
145
  ...(metrics.eventLoopLagMeanMs !== undefined
142
146
  ? [`elLag=${metrics.eventLoopLagMeanMs}/${metrics.eventLoopLagP99Ms ?? 0}/${metrics.eventLoopLagMaxMs ?? 0}ms`]
143
147
  : []),
@@ -24,6 +24,7 @@ import { renderToReadableStream } from "react-server-dom-webpack/server.node";
24
24
  import type { ClientManifest } from "./artifact";
25
25
  import {
26
26
  LruTtlCache,
27
+ type LruTtlCacheOptions,
27
28
  parsePositiveInt,
28
29
  type RouteCacheEntry,
29
30
  type RouteCacheInvalidation,
@@ -122,6 +123,9 @@ interface FlightRenderResult {
122
123
  cancelled: boolean;
123
124
  }
124
125
 
126
+ /** Well above any sensible TTL: this reclaims a cache nobody is reading, not tracks expiry closely. */
127
+ const RESULT_CACHE_SWEEP_INTERVAL_MS = 60_000;
128
+
125
129
  function hashRscTraceCacheKey(cacheKey: string): string {
126
130
  let hash = 5381;
127
131
  for (let index = 0; index < cacheKey.length; index += 1) hash = (hash * 33) ^ cacheKey.charCodeAt(index);
@@ -197,11 +201,14 @@ export class RscRenderer {
197
201
  pagesBundleBuildId: 0,
198
202
  };
199
203
  readonly #routeStats = new Map<string, RouteRenderStats>();
204
+
200
205
  #resultCache = new LruTtlCache<CachedRscResult>(
201
206
  parsePositiveInt(process.env.AKAN_RSC_RESULT_CACHE_MAX_ENTRIES) ?? 100,
207
+ RscRenderer.#resultCacheOptions(),
202
208
  );
203
209
  #patchResultCache = new LruTtlCache<CachedRscResult>(
204
210
  parsePositiveInt(process.env.AKAN_RSC_RESULT_CACHE_MAX_ENTRIES) ?? 100,
211
+ RscRenderer.#resultCacheOptions(),
205
212
  );
206
213
  readonly #activeRenderReaders = new Map<string, ReadableStreamDefaultReader<Uint8Array>>();
207
214
  readonly #cancelledRenderRequests = new Set<string>();
@@ -818,7 +825,11 @@ export class RscRenderer {
818
825
  rscLoadedRouteModuleKeys: routeStats.loadedModuleKeys,
819
826
  rscTopRoutesByRenderCount: this.#topRoutes((route) => route.count),
820
827
  rscTopRoutesByFlightBytes: this.#topRoutes((route) => route.flightBytes),
821
- rscResultCacheEntries: this.#resultCache.size + this.#patchResultCache.size,
828
+
829
+ rscResultCacheEntries: this.#resultCache.size,
830
+ rscResultCacheBytes: this.#resultCache.byteSize,
831
+ rscPatchResultCacheEntries: this.#patchResultCache.size,
832
+ rscPatchResultCacheBytes: this.#patchResultCache.byteSize,
822
833
  rscResultCacheHits: this.#resultCacheHits,
823
834
  rscResultCacheMisses: this.#resultCacheMisses,
824
835
  rscResultCacheBypass: this.#resultCacheBypass,
@@ -899,7 +910,7 @@ export class RscRenderer {
899
910
  });
900
911
  };
901
912
  try {
902
- while (true) {
913
+ for (;;) {
903
914
  if (options.requestId && this.#cancelledRenderRequests.has(options.requestId)) {
904
915
  await reader.cancel();
905
916
  return { chunks, bytes, chunksCount, control: null, lateControlSent, cancelled: true };
@@ -1125,6 +1136,15 @@ export class RscRenderer {
1125
1136
  return decision;
1126
1137
  }
1127
1138
 
1139
+ static #resultCacheOptions(): LruTtlCacheOptions<CachedRscResult> {
1140
+ return {
1141
+ sizeOf: (result) => result.bytes,
1142
+ maxBytes: LruTtlCache.parseByteCeiling(process.env.AKAN_RSC_RESULT_CACHE_MAX_BYTES),
1143
+ maxEntryBytes: LruTtlCache.parseByteCeiling(process.env.AKAN_RSC_RESULT_CACHE_MAX_BODY_BYTES),
1144
+ sweepIntervalMs: RESULT_CACHE_SWEEP_INTERVAL_MS,
1145
+ };
1146
+ }
1147
+
1128
1148
  #getCachedResult(cacheKey: string): CachedRscResult | null {
1129
1149
  const cached = this.#resultCache.get(cacheKey);
1130
1150
  if (!cached) {
@@ -1146,11 +1166,19 @@ export class RscRenderer {
1146
1166
  }
1147
1167
 
1148
1168
  #setCachedResult(cacheKey: string, result: CachedRscResult, ttl: number): void {
1149
- this.#resultCache.set(cacheKey, result, ttl);
1169
+ this.#logRejectedStore("full", result, this.#resultCache.set(cacheKey, result, ttl));
1150
1170
  }
1151
1171
 
1152
1172
  #setCachedPatchResult(cacheKey: string, result: CachedRscResult, ttl: number): void {
1153
- this.#patchResultCache.set(cacheKey, result, ttl);
1173
+ this.#logRejectedStore("patch", result, this.#patchResultCache.set(cacheKey, result, ttl));
1174
+ }
1175
+
1176
+ /** A silently dropped store looks identical to a cache miss; say which route is too big to cache. */
1177
+ #logRejectedStore(kind: string, result: CachedRscResult, stored: boolean): void {
1178
+ if (stored) return;
1179
+ this.#logger.verbose(
1180
+ `${kind} result cache store skipped pathname=${result.pathname} bytes=${result.bytes} reason=body-too-large`,
1181
+ );
1154
1182
  }
1155
1183
 
1156
1184
  #runWithRequest<T>(request: Request, fn: () => Promise<T>): Promise<T> {
@@ -89,6 +89,66 @@ export function createRscWorkerInvalidateCacheMessage(
89
89
  };
90
90
  }
91
91
 
92
+ /**
93
+ * The RSC worker samples its own process with the same `ProcessMetricsCollector.collect` its host
94
+ * replica uses, so its report carries `pid` / `rssBytes` / `role` / … under the identical names.
95
+ * `AkanServer` spreads the host's report into its own `collect({ role, ...webRouter.getMetrics() })`
96
+ * and `collect` spreads `extra` last (`processMetricsCollector.ts:122`) — so passing these through
97
+ * unprefixed silently overwrote the replica's own process fields, and the replica's RSS was reported
98
+ * nowhere. Rename them onto `rscWorker*`; the `rsc*` render counters, which only the worker
99
+ * produces, pass through untouched.
100
+ *
101
+ * XXX A new process-level field in `ProcessMetricsCollector.collect` must be added here too, or it
102
+ * starts shadowing the replica again.
103
+ */
104
+ export function projectRscWorkerProcessMetrics(metrics: AkanMetricsReport): AkanMetricsReport {
105
+ const {
106
+ role: _role,
107
+ pid: _pid,
108
+ trace: _trace,
109
+ reportedAt,
110
+ rssBytes,
111
+ heapTotalBytes,
112
+ heapUsedBytes,
113
+ externalBytes,
114
+ arrayBuffersBytes,
115
+ cpuUserMicros,
116
+ cpuSystemMicros,
117
+ maxRssKb,
118
+ jscHeapSizeBytes,
119
+ jscHeapCapacityBytes,
120
+ jscExtraMemorySizeBytes,
121
+ jscObjectCount,
122
+ jscProtectedObjectCount,
123
+ eventLoopLagMeanMs,
124
+ eventLoopLagP99Ms,
125
+ eventLoopLagMaxMs,
126
+ gcDurationMs,
127
+ ...renderMetrics
128
+ } = metrics;
129
+ return {
130
+ ...renderMetrics,
131
+ rscWorkerReportedAt: reportedAt,
132
+ rscWorkerRssBytes: rssBytes,
133
+ rscWorkerHeapTotalBytes: heapTotalBytes,
134
+ rscWorkerHeapUsedBytes: heapUsedBytes,
135
+ rscWorkerExternalBytes: externalBytes,
136
+ rscWorkerArrayBuffersBytes: arrayBuffersBytes,
137
+ rscWorkerCpuUserMicros: cpuUserMicros,
138
+ rscWorkerCpuSystemMicros: cpuSystemMicros,
139
+ rscWorkerMaxRssKb: maxRssKb,
140
+ rscWorkerJscHeapSizeBytes: jscHeapSizeBytes,
141
+ rscWorkerJscHeapCapacityBytes: jscHeapCapacityBytes,
142
+ rscWorkerJscExtraMemorySizeBytes: jscExtraMemorySizeBytes,
143
+ rscWorkerJscObjectCount: jscObjectCount,
144
+ rscWorkerJscProtectedObjectCount: jscProtectedObjectCount,
145
+ rscWorkerEventLoopLagMeanMs: eventLoopLagMeanMs,
146
+ rscWorkerEventLoopLagP99Ms: eventLoopLagP99Ms,
147
+ rscWorkerEventLoopLagMaxMs: eventLoopLagMaxMs,
148
+ rscWorkerGcDurationMs: gcDurationMs,
149
+ };
150
+ }
151
+
92
152
  export function createRscHostRenderStream(input: {
93
153
  setPending: (pending: RscPending) => void;
94
154
  deletePending: () => void;
@@ -464,18 +524,7 @@ export class RscWorker {
464
524
  }
465
525
 
466
526
  getMetrics(): AkanMetricsReport {
467
- const {
468
- rscWorkerPid: _rscWorkerPid,
469
- rscWorkerStatus: _rscWorkerStatus,
470
- rscWorkerRestartCount: _rscWorkerRestartCount,
471
- rscWorkerRecycleCount: _rscWorkerRecycleCount,
472
- rscWorkerLastRecycleReason: _rscWorkerLastRecycleReason,
473
- rscPendingRenderCount: _rscPendingRenderCount,
474
- rscQueuedSendCount: _rscQueuedSendCount,
475
- rscHostPendingChunkOverflowCount: _rscHostPendingChunkOverflowCount,
476
- ...workerMetrics
477
- } = this.#lastWorkerMetrics;
478
- return Object.assign(workerMetrics, {
527
+ return Object.assign(projectRscWorkerProcessMetrics(this.#lastWorkerMetrics), {
479
528
  rscWorkerPid: this.#proc.pid,
480
529
  rscWorkerStatus: this.#status,
481
530
  rscWorkerRestartCount: this.#restartCount,
@@ -411,7 +411,7 @@ export function interleaveRscScriptsWithHtml(
411
411
  const pumpRscScripts = async () => {
412
412
  rscReader = rscClientStream.getReader();
413
413
  try {
414
- while (true) {
414
+ for (;;) {
415
415
  const { value, done } = await rscReader.read();
416
416
  if (done || errored) break;
417
417
  await waitForRscQueueDrain();
@@ -446,7 +446,7 @@ export function interleaveRscScriptsWithHtml(
446
446
 
447
447
  htmlReader = htmlStream.getReader();
448
448
  try {
449
- while (true) {
449
+ for (;;) {
450
450
  const { value, done } = await htmlReader.read();
451
451
  if (done || errored) break;
452
452
  controller.enqueue(value);
@@ -39,19 +39,19 @@ export const SYSTEM_PAGE_STATUS_COPY = {
39
39
  } as const;
40
40
 
41
41
  const FALLBACK_STYLE = `
42
- :root { color-scheme: dark; --akan-primary: #ff493b; --akan-secondary: #2b2e33; --akan-accent: #d1a23b; --akan-base-content: #ffffff; --akan-base-100: #1a1a1a; --akan-base-200: #2a2a2a; --akan-error: #f02020; }
43
- body { margin: 0; min-height: 100vh; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: var(--akan-base-100); color: var(--akan-base-content); }
42
+ :root { color-scheme: dark; --akan-primary: #ff493b; --akan-secondary: #2b2e33; --akan-accent: #d1a23b; --akan-foreground: #ffffff; --akan-background: #1a1a1a; --akan-base-200: #2a2a2a; --akan-error: #f02020; }
43
+ body { margin: 0; min-height: 100vh; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: var(--akan-background); color: var(--akan-foreground); }
44
44
  a { color: inherit; }
45
- .akan-system-page { min-height: 100vh; display: grid; place-items: center; padding: 32px 18px; box-sizing: border-box; background: radial-gradient(circle at top left, rgba(255, 73, 59, 0.16), transparent 34%), linear-gradient(135deg, var(--akan-base-100), #111); }
45
+ .akan-system-page { min-height: 100vh; display: grid; place-items: center; padding: 32px 18px; box-sizing: border-box; background: radial-gradient(circle at top left, rgba(255, 73, 59, 0.16), transparent 34%), linear-gradient(135deg, var(--akan-background), #111); }
46
46
  .akan-system-card { width: min(720px, 100%); border: 1px solid rgba(255, 255, 255, 0.12); border-radius: 32px; background: linear-gradient(145deg, rgba(42, 42, 42, 0.96), rgba(43, 46, 51, 0.78)); box-shadow: 0 24px 80px rgba(0, 0, 0, 0.36); padding: clamp(28px, 6vw, 56px); }
47
47
  .akan-system-status { margin: 0 0 18px; font-weight: 800; font-size: clamp(4rem, 18vw, 8rem); line-height: 0.85; letter-spacing: -0.08em; color: var(--akan-primary); }
48
48
  .akan-system-eyebrow { margin: 0 0 10px; color: var(--akan-accent); font-size: 0.78rem; font-weight: 800; letter-spacing: 0.18em; text-transform: uppercase; }
49
- .akan-system-title { margin: 0; max-width: 12ch; font-size: clamp(2rem, 7vw, 4rem); line-height: 0.95; letter-spacing: -0.055em; color: var(--akan-base-content); }
49
+ .akan-system-title { margin: 0; max-width: 12ch; font-size: clamp(2rem, 7vw, 4rem); line-height: 0.95; letter-spacing: -0.055em; color: var(--akan-foreground); }
50
50
  .akan-system-description { margin: 22px 0 0; max-width: 56ch; color: rgba(255, 255, 255, 0.76); font-size: 1.05rem; line-height: 1.75; }
51
51
  .akan-system-path { margin: 22px 0 0; overflow-wrap: anywhere; border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 16px; background: rgba(26, 26, 26, 0.72); padding: 12px 14px; color: rgba(255, 255, 255, 0.72); font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; font-size: 0.88rem; }
52
52
  .akan-system-actions { margin-top: 30px; display: flex; flex-wrap: wrap; gap: 12px; }
53
- .akan-system-action { display: inline-flex; min-height: 44px; align-items: center; justify-content: center; border: 1px solid var(--akan-primary); border-radius: 999px; background: var(--akan-primary); box-shadow: 0 12px 34px rgba(255, 73, 59, 0.26); color: var(--akan-base-content); padding: 0 18px; font-weight: 800; text-decoration: none; }
54
- .akan-system-secondary { border: 1px solid rgba(255, 255, 255, 0.12); background: var(--akan-secondary); color: var(--akan-base-content); }
53
+ .akan-system-action { display: inline-flex; min-height: 44px; align-items: center; justify-content: center; border: 1px solid var(--akan-primary); border-radius: 999px; background: var(--akan-primary); box-shadow: 0 12px 34px rgba(255, 73, 59, 0.26); color: var(--akan-foreground); padding: 0 18px; font-weight: 800; text-decoration: none; }
54
+ .akan-system-secondary { border: 1px solid rgba(255, 255, 255, 0.12); background: var(--akan-secondary); color: var(--akan-foreground); }
55
55
  .akan-system-details { margin-top: 28px; max-height: 260px; overflow: auto; border-radius: 18px; background: rgba(26, 26, 26, 0.82); border: 1px solid rgba(240, 32, 32, 0.22); padding: 16px; color: rgba(255, 255, 255, 0.78); font-size: 0.82rem; line-height: 1.55; white-space: pre-wrap; }
56
56
  `;
57
57
 
@@ -73,9 +73,9 @@ export function createSystemPageDocument(options: SystemPageOptions): ReactNode
73
73
  <style data-akan-system-page>{FALLBACK_STYLE}</style>
74
74
  </head>
75
75
  <body>
76
- <main className="akan-system-page min-h-screen bg-base-100 text-base-content">
76
+ <main className="akan-system-page min-h-screen bg-background text-foreground">
77
77
  <section
78
- className="akan-system-card rounded-3xl border border-base-content/10 bg-base-content/4 p-8 shadow-2xl backdrop-blur-xl"
78
+ className="akan-system-card rounded-3xl border border-foreground/10 bg-foreground/4 p-8 shadow-2xl backdrop-blur-xl"
79
79
  aria-labelledby="akan-system-title"
80
80
  >
81
81
  <p className="akan-system-status text-primary">{copy.status}</p>
@@ -83,15 +83,15 @@ export function createSystemPageDocument(options: SystemPageOptions): ReactNode
83
83
  <h1 id="akan-system-title" className="akan-system-title font-black">
84
84
  {copy.title}
85
85
  </h1>
86
- <p className="akan-system-description text-base-content/70">{copy.description}</p>
87
- <p className="akan-system-path border border-base-content/10 bg-base-200/50" aria-label="Requested path">
86
+ <p className="akan-system-description text-foreground/70">{copy.description}</p>
87
+ <p className="akan-system-path border border-foreground/10 bg-muted/50" aria-label="Requested path">
88
88
  {options.pathname}
89
89
  </p>
90
90
  <div className="akan-system-actions">
91
- <a className="akan-system-action btn btn-primary" href={options.homeHref}>
91
+ <a className="akan-system-action" href={options.homeHref}>
92
92
  {copy.actionLabel}
93
93
  </a>
94
- <a className="akan-system-action akan-system-secondary btn" href={options.pathname}>
94
+ <a className="akan-system-action akan-system-secondary" href={options.pathname}>
95
95
  Try again
96
96
  </a>
97
97
  </div>