akanjs 3.2.0 → 3.2.1-rc.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 (47) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/document/dataLoader.ts +55 -25
  3. package/package.json +1 -1
  4. package/server/akanApp.ts +13 -2
  5. package/server/akanServer.ts +4 -0
  6. package/server/contentEncoding.ts +39 -9
  7. package/server/flightSanitizeRecorded.fixture.json +545 -0
  8. package/server/gateway/gatewayHttpProxy.ts +2 -2
  9. package/server/hmr/devBaseArtifact.ts +40 -0
  10. package/server/htmlResultCache.ts +11 -10
  11. package/server/routing/routeHosts.ts +4 -0
  12. package/server/rscFlightStream.ts +34 -2
  13. package/server/rscHostRequests.ts +27 -2
  14. package/server/rscRenderControl.ts +2 -0
  15. package/server/rscRenderHandler.ts +17 -18
  16. package/server/rscRenderManifest.ts +13 -0
  17. package/server/rscResultCaches.ts +2 -2
  18. package/server/rscWorker.tsx +14 -2
  19. package/server/rscWorkerCache.ts +13 -15
  20. package/server/rscWorkerHost.ts +3 -0
  21. package/service/predefinedAdaptor/solidCache.adaptor.ts +57 -15
  22. package/service/predefinedAdaptor/sql/AggregateQuery.ts +66 -0
  23. package/service/predefinedAdaptor/sql/BoundList.ts +34 -0
  24. package/service/predefinedAdaptor/sql/QueryCompiler.ts +27 -4
  25. package/service/predefinedAdaptor/sql/QueryScope.ts +41 -7
  26. package/service/predefinedAdaptor/sql/RawDocumentTable.ts +7 -1
  27. package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +45 -42
  28. package/service/predefinedAdaptor/sql/SqlTableSchema.ts +2 -2
  29. package/service/predefinedAdaptor/sql/types.ts +2 -0
  30. package/types/document/dataLoader.d.ts +1 -0
  31. package/types/server/contentEncoding.d.ts +3 -2
  32. package/types/server/gateway/gatewayHttpProxy.d.ts +1 -0
  33. package/types/server/hmr/devBaseArtifact.d.ts +10 -0
  34. package/types/server/htmlResultCache.d.ts +3 -2
  35. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  36. package/types/server/routing/routeHosts.d.ts +1 -0
  37. package/types/server/rscHostRequests.d.ts +1 -0
  38. package/types/server/rscRenderControl.d.ts +2 -0
  39. package/types/server/rscRenderManifest.d.ts +5 -0
  40. package/types/server/rscWorkerCache.d.ts +4 -5
  41. package/types/service/predefinedAdaptor/sql/AggregateQuery.d.ts +16 -0
  42. package/types/service/predefinedAdaptor/sql/BoundList.d.ts +10 -0
  43. package/types/service/predefinedAdaptor/sql/QueryCompiler.d.ts +1 -0
  44. package/types/service/predefinedAdaptor/sql/QueryScope.d.ts +2 -2
  45. package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +1 -1
  46. package/types/service/predefinedAdaptor/sql/SqlTableSchema.d.ts +1 -1
  47. package/types/service/predefinedAdaptor/sql/types.d.ts +2 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,94 @@
1
1
  # akanjs
2
2
 
3
+ ## 3.2.1
4
+
5
+ ### Patch Changes
6
+
7
+ - bf582c1: A page stored in the HTML cache is kept as the bytes it streamed, instead of being decoded to text and encoded again before compression. Storing a 600 KB page takes about a fifth of the main-thread time it did, and the stored page and every response from it are unchanged.
8
+ - c10f7cf: A loader sends its store at most 500 distinct keys per query and splits a larger batch into several queries that run together. A `load<Model>Many` or a nested list with more ids than a database takes in one statement now loads instead of failing: Postgres refused more than 65,534 values, and SQLite refused a `byQuery` batch of about 1,000 keys.
9
+ - c10f7cf: A loader asks its store for each key once per batch: loads of the same key in one batch share one lookup, and each caller still gets its own document wherever the loader has `copy`, as every model and declared loader does. A `new DataLoader(...)` without `copy` now hands the callers of a repeated key one result object, where a batch function that built a fresh object per position gave each its own: pass `copy` to keep them apart. A batch function that throws, or resolves to something that is not an array, now rejects its callers instead of leaving them waiting.
10
+ - 5c7e083: Every page of a list is read with one SQL text: the page offset is a bound parameter, so paging no longer adds a prepared statement per page to the SQLite statement cache or to each Postgres connection. On Postgres a list of two or more values (`q.oneOf`, `q.notOneOf`, a raw table's `$in` and `$nin`) is bound as one array, so its length adds no prepared statement either, and a list past the 65,534 parameters one statement may bind is now read. An insight is read in one statement instead of one per field, so its counts and sums come from one snapshot and, with six fields, in about a third of the time.
11
+ - aead1aa: A page render no longer sends the whole client manifest to the RSC worker with every request. The worker process receives a manifest once and each render names it by revision, which takes a burst of cached pages from about 38 ms to about 7 ms at the median on the docs app.
12
+
13
+ A page the RSC worker has cached replays as one message instead of one message and one timer wait per chunk: a cached page of the docs app answers in about 0.3 ms instead of 4.7 ms.
14
+
15
+ A render that produces many small chunks at once sends them as a few messages of up to 32 KB. A page still waiting on data sends what it has rendered at once, as before.
16
+
17
+ The server still fails a render whose stream it has 256 messages of undrained, and since a message now holds up to 32 KB that is about 8 MB of a streamed page where it was about 1 MB; a cached page arrives as one message, so it is never counted.
18
+
19
+ - 5c6d039: A precompressed `.br` or `.gz` asset is now streamed from disk instead of being read whole and copied on every request, which cuts the server CPU per asset request to about a quarter. In production the answer of whether a sidecar exists is remembered per path.
20
+ An existing zero-byte `.br` or `.gz` sibling is skipped, because an empty body is not valid brotli or gzip.
21
+ - 0492e0b: The SQLite cache sweeps expired entries through an index on their expiry, a thousand at a time with a pause between, so a large backlog no longer stalls the server for hundreds of milliseconds, and `hkeys` and `hentries` no longer run a sweep on every call. They skip expired fields themselves, so they return the same fields as before. The index is built once, at the first start after upgrading.
22
+ - 0492e0b: On the SQLite cache, a value or hash field written by another process is no longer removed by a `get` or `hget` that saw the key's previous, expired entry.
23
+ - 5c7e083: On SQLite a read, count or write by a list of ids (`q.oneOf` on `id`, which is how a batched load by id reads) goes through the primary key. A model with an index that leads with `removedAt` had a list of five or more ids read every live row instead: at 20,000 rows a load of five ids took about 6 ms and now takes about 0.03 ms.
24
+ - 98931e4: `akan start` boots the backend while the first base build runs: the backend loads its server graph beside the build and mounts the web surface as soon as the build's artifact is on disk, so the dev server is ready sooner.
25
+
26
+ The port now answers from the start of the build. A request to `localhost` or an IP address, page or API, waits for the first artifact; a build longer than the 15 s the gateway holds a request ends the wait with a 503 "Backend is starting" page that reloads itself. A request to one of the app's own domains (a custom local domain) gets that 503 at once until the backend is ready, because the build has not written the app's hosts yet; after that it is served as before, and any other Host is refused as before.
27
+
28
+ ## 3.2.0
29
+
30
+ ### Minor Changes
31
+
32
+ - 038d918: Akan.js 3.2.0. Read **Upgrade notes** before deploying an app that runs 3.1.1: unguarded endpoints, log levels, the `Err` class, loaders, SQLite transactions, exit codes and a CLI version check change behaviour.
33
+
34
+ **Highlights**
35
+
36
+ - **`agentService.loop`.** A server-side agent run over the `/mcp` tool catalogue, in-process, with `toolkits`, `remotes` (other MCP servers), `clientTools` (a screen the member has open), `ask` (a question parked between runs), `answer`, overflow retry, and a read rule that counts what a run reads as untrusted. `plug(AgentToolsRole)` runs the catalogue as a given account; `mcp: "agent"` keeps an entry off `/mcp` for the in-process agent only.
37
+ - **Akan Graph and Akan Studio.** `get_graph` (MCP) returns the Akan Graph, read from source with no dev server: models, scalars, slices, endpoints with guards, services, jobs, adaptors, routes, layouts, the framework itself, and the Change Map for `since: <revision>`. `akan start` serves Studio at `/_akan/studio`, and it opens from the CLI and the editor.
38
+ - **Editor support.** `@akanjs/language` resolves names Akan.js derives (`fetch.initMemoInPublic`, `st.do.setNameOnMemo`, `this.memoService.listByName`) and ships `akan-language-server`. The VS Code / Cursor extension opens a module side by side, runs `akan verify` and workflows, and publishes from CI to the VS Marketplace and Open VSX.
39
+ - **Secure defaults.** Signals, websocket rooms, MCP, OAuth, the agent relay, the server edge, the ops channel, native builds, `akan code`, the CLI's tunnels and workflows, and the in-page agent each take the narrower default. Every change names how to get the old behaviour back.
40
+ - **Faster pages.** Every SSR page loads 72K less framework JS (22K less Brotli); client modules preload from `<head>`; Link prefetch; Flight rows share inline scripts; one preloaded font face per family; faster RSC decoding and store writes; a route JS budget (`akan build --check-budget`).
41
+ - **Realtime.** Per-socket, per-caller and per-model room limits, subscribe budgets, gateway subscribe acks, per-model live-sync routing, Redis room sharding, resync after a Redis outage, and an outbox limit for a down socket.
42
+ - **Native.** `external-view` on Linux (Wayland and X11) with `sendKey`; Android 12 launch crash fixed; AppImage relaunch; tighter CSP, external-link, temp-folder and update defaults.
43
+
44
+ **Upgrade notes**
45
+
46
+ - **Guards.** An endpoint, slice query or pubsub room that declares no guards is refused with 403; open it with `[Public]`. Outside local operation a server whose signals declare a guardless endpoint stops at boot and names each one. `AKAN_UNGUARDED_ENDPOINTS=open` answers them as before. A slice whose `guards` leaves out `root` mounts no root list or insight. `guard(name)` refuses until `canPass` is overridden.
47
+ - **`Err`.** Every `Err` is one class, `Err` from `akanjs/common`, and an `AkanError`. `err.code` is always set (a generalized failure's code, else its status's code), so `{ ...err }` now holds it. `Err.NotFound.is(error)` also requires status 404. Check across a page bundle and the framework with `Err.is`, not `instanceof`. `setErrorConstructor`, `HttpClientOptions.ErrorCls` and `FetchClient.build`'s `Err` option are deprecated.
48
+ - **Coded failures.** The signal, service, server, route-tree, RSC and client facets throw coded `AkanError`s instead of a bare `Error`; messages and statuses are unchanged. A production 500 shows the status reason and code only. `bun run error:codes` lists the codes. A failed tool call and a failed agent turn carry a `code`.
49
+ - **Log levels.** A failure under 500 logs at `warn`, a 5xx is one `error` record with `type` and `stack`, a declared error, a 429 and a by-id read of a missing id log at `debug`, and a crashed RSC worker logs at `warn`. Alerts and `--level error` filters see fewer lines. A page `redirect()` is `ok` at `info` with its 3xx status, and `notFound()` is `warn` with 404. Every log record reaches ndjson stdout, and a request line is never folded.
50
+ - **Loaders.** A loader no longer shares a batch between a transaction and the requests outside it, and each caller gets its own document. A loader that keeps its keys forgets them when the model is written; a write by query clears every kept key of the model, and `cache: true` keeps the 10,000 most recent keys. A custom `DatabaseAdaptor` can implement `transactionKey()`; a `batchScheduleFn` must run its callback in the caller's async context.
51
+ - **SQLite.** Work outside an open `this.transaction()` no longer sees its uncommitted rows, on `:memory:` or a non-WAL file either. `SqliteDatabase.getMeta` and `listMeta` return promises, so await them. A reader pays one database copy per transaction on `:memory:`; past a few tens of megabytes, put the database in a file.
52
+ - **Indexes.** A boot keeps an index the release no longer declares and warns about it. After every instance runs this release, run `akan migrate <app> prune-indexes` once. `migrationActions` gains `indexes` and `prune-indexes`, so code that switches over every action needs the two cases.
53
+ - **Websockets.** A socket holds at most 256 rooms, a caller 2,000 per process, a model 50,000 evaluated live rooms; a subscribe past a limit gets a 429 frame coded `liveRoomLimit`. Subscribes are budgeted at 1,000 a minute per socket and 10,000 per caller. A `pubsub` room's `onResync` also runs after Redis returns; a custom `WebsocketAdaptor.onRecovered` handler now takes the held rooms. A down socket keeps at most 100 emits.
54
+ - **Gateway.** `/_akan/app/ready` answers 503 while no replica's RSC worker can render. A subscribe is acknowledged once the gateway routes the room.
55
+ - **CLI.** A CLI whose major.minor differs from the workspace's `akanjs` refuses every command that writes, with exit 2; run `akan update`, or set `AKAN_ALLOW_VERSION_MISMATCH=1`. Exit codes: 2 for usage and unknown targets, 3 for failed checks (`verify`, `typecheck`), 130 for an interrupted prompt; a script that tested for exit 1 tests for non-zero. With `--json`, a failure ends stdout with `{"ok":false,"error":"<message>","code":"<code>"}`. `akan doctor` exits 1 on `"status": "failed"`; `akan workflow plan`, `apply` and `validate` exit non-zero on failure. A shell `AKAN_PUBLIC_ENV` now outranks the workspace `.env`, and `akan build --env <env>` builds another environment.
56
+ - **Package budget.** `akan lint` and `akan verify` hold each package under `pkgs/` to the file, function and class budget. Run `akan quality baseline` once in a workspace whose packages are over it. `akan verify` also typechecks every app and lib that uses a changed lib.
57
+ - **Secure defaults.**
58
+ - Write tools in the in-page agent confirm by default (`submit`, `create`, `update`, `send`, `export` and the rest, not only `remove`); opt out with `{ confirm: false }`. Page text reaches the model fenced as data, and a transcript belongs to one account.
59
+ - A `FetchClient` sends its session token only to its own origin; pass `clone({ origin, jwt })` to send one elsewhere.
60
+ - A connection idle for 120 s closes (`AKAN_IDLE_TIMEOUT`), a body is capped at 128 MiB (`AKAN_MAX_UPLOAD_BODY`) and 16 MiB for a non-multipart one (`AKAN_MAX_REQUEST_BODY`), `akan start` binds 127.0.0.1 (`AKAN_LISTEN_HOST=*` restores it), and HTML carries `Cache-Control`, HSTS and a `frame-ancestors` policy.
61
+ - The dev server answers only `localhost`, `*.localhost` and IP hosts unless `AKAN_ALLOWED_HOSTS` is set.
62
+ - A 500 shows its message and stack only under `akan start`, `NODE_ENV` `development` or `test`, or `AKAN_ERROR_DETAIL=1`.
63
+ - `ops snapshot` outside local operation needs `AKAN_BACKUP_RECIPIENT` or `--allow-plaintext`; the ops key must differ from `AKAN_MACHINE_PUBLIC_KEY`.
64
+ - `/__rsc/manifest` is dev-only (`AKAN_EXPOSE_RSC_MANIFEST=1`), and health detail, metrics and devtools need a local dev runtime.
65
+ - Filter arguments are parsed against their declared type and an `Any` filter argument throws at declaration; `q.search()` text is capped at 32 terms and 1000 characters.
66
+ - The image optimizer refuses non-public remote hosts (`images.dangerouslyAllowLocalIP`).
67
+ - The CLI's tunnels listen on loopback and check the SSH host key, workflow commands run without a shell, `akan download-env` copies only env and secret files, a Dockerfile built with `AKAN_PUBLIC_ENV=local` needs `--build-arg AKAN_ALLOW_LOCAL_IMAGE=1`, and `akan code` asks before network access and trusts a repository's MCP servers and extensions only after one terminal approval.
68
+ - MCP rate-limits an unverified bearer by address, checks the browser Origin, and bounds client registration; the agent relay refuses a request past fixed limits with `agent.error.requestRefused` (413) unless a policy sets its own.
69
+ - Native builds ship a Content-Security-Policy, open only `https:`, `mailto:` and `tel:` links, and recheck a downloaded desktop update before installing it; `updates.windowsSigners` and `updates.expiresIn` are new.
70
+ - **UI.** `Field.Switch`'s on position is `primary` (pass `variant="accent"` for the old look), and two `Data.Item` status tags change color. `useCamera` and `useGeoLocation` no longer send the user to Settings after a denial. A page `.head()` can set `theme-color`, and a level that writes an image no longer inherits the image tags above it. `--akan-theme-color` drives the browser's `theme-color`.
71
+ - **Libraries.** The `shared` and `util` libraries `akan install-library` copies are refreshed; compare your copy. In `util`, `security` and `security.jwtSecret` are optional in `ModulesOptions`. `libs/shared` keeps its SSO and refresh cookies on `__Host-` names outside local.
72
+ - **Other.** `LLM` stream endings are read more completely: a cut tool call ends as `length`, and unparseable arguments in a finished answer get `argsError` and the code `invalidArgument`. `ConformanceEnv.has` fails instead of skipping when `AKAN_TEST_REQUIRE_BACKENDS=1`. A new workspace has no `patches/` folder, no `agent:sample:*` scripts and one `setup:agent` script; `create-akan-workspace` no longer hangs when `akan` is not on PATH.
73
+
74
+ **Features**
75
+
76
+ - **Agent.** `Agent.Chat` modals and toasts stack above the panel and its header takes a node; the tool row is the `AgentToolRow` override slot; a restored transcript that ends on an unanswered `askUser` reopens on it; a turn its caller stops is billed at what the provider plausibly charged, and every turn the quota passes is billed.
77
+ - **Rendering and navigation.** `{ static: true }` page apps answer a host that asks for script-less HTML; `i18n.localePrefix: "as-needed"` serves the default locale unprefixed; a route guard receives `{ path }` and `signedIn({ path })` adds `?redirect=`; a failed route level or `Load.Stream` draws a notice with "Try again" in its own place; `router.refresh()` in CSR no longer reloads the document; a lazy chunk the server no longer serves reloads the page once; `forwardVisitor: false` keeps a render cacheable; a query takes `signal` and identical in-flight queries share one request.
78
+ - **Data.** `create<Model>Many(rows)` runs every row through `_preCreate`, `_postCreate` and the document hooks; `bulkWrite` runs in one transaction; a cascade removes a long array's documents 200 ids at a time; `Binary` arguments are typed `Uint8Array<ArrayBuffer>`; a hidden `.optional()` field is optional in create inputs; store form setters and writes cost about one copy of the state; `onError` on store writes receives the failed request's dictionary error.
79
+ - **Server and ops.** `/_akan/app/ready`; `RestartSchedule` shared by every child-restart loop; a single-flight `cache` endpoint; stopped or failed starts tear down what they brought up; the Redis WebSocket adaptor shards channels per room and model and flushes publishes on shutdown; a log stream stops growing for a client that stops reading; missing assets answer `no-store`.
80
+ - **CLI.** `akan test --parallel=<n>`, `--junit <path>` and `--coverage`; `akan build --env`; a `rename-key` workflow; `akan remove-module pokedex:_billing` removes a service module; `akan create-workspace` works in an existing folder, without sample code, and without a git identity; `akan preview` opens `/_akan/studio`, `/openapi.json` and `/mcp` as written and restarts a dead browser; `akan verify` reports step durations and gives a dictionary hint for a missing key; commands without a terminal take the workspace's only app, lib or package, and remove commands never pick a target themselves; release candidates publish from CI with npm provenance.
81
+ - **Native.** `external-view` and `sendKey` on Linux; Android 12 and 12L launch fix; AppImage relaunch; a `single-instance` pipe that another account cannot own on Windows.
82
+ - **Types and styling.** A new app's default style is Pretendard with -3% letter spacing, even sizes from 12px, 150% line height for wrapping text and `leading-auto` for one line.
83
+
84
+ **Fixes**
85
+
86
+ - A dev page keeps its styles after a stylesheet change arrives with a pages rebuild; idle-suspended dev servers apply every save, stay awake when work arrives, and stop cleanly; `[BarrelAnalyzer] ERROR scan failed` is gone; a backend replica's builder answer no longer reaches its replacement.
87
+ - A page that renders a string of 1024 characters or more renders and hydrates whatever its lines say; a page cut off by a disconnected client, or one that streamed an error, is no longer cached; partial RSC commit (`AKAN_PUBLIC_RSC_PARTIAL_COMMIT=1`) patches real pages, replays patches from cache and cancels overtaken navigations.
88
+ - In production, a render error no longer reaches the browser as its message; reading the client address from a crafted forwarded header no longer stalls the server; `happy-dom` peers ask for `^21.0.4`; the pi agent packages move to 1.5.2, dropping undici and minimatch advisories.
89
+ - The build lock records its host and survives a dead remover, a Windows antivirus hold and a devcontainer; `akan` no longer rebuilds the dev CLI from a command it runs; the typecheck behind `akan verify` and `akan build` uses its incremental cache.
90
+ - Internal: the largest classes and methods in `akanjs`, `@akanjs/devkit` and `@akanjs/cli` are split by concern with unchanged public members, and the `akanjs` facets import sibling files instead of their own barrel and list every export by name.
91
+
3
92
  ## 3.1.1
4
93
 
5
94
  ### Patch Changes
@@ -24,19 +24,29 @@ interface DataLoaderOptions<Key, Value, CacheKey> {
24
24
  batchScheduleFn?: (callback: () => void) => void;
25
25
  /** What a load belongs to, such as its open transaction: a scope's loads batch apart and never touch the cache. */
26
26
  scopeFn?: () => object | undefined;
27
+ /** How many distinct keys one call of the batch function takes (500 by default); a larger queue goes out as several. */
27
28
  maxBatchSize?: number;
28
29
  name?: string;
29
30
  }
30
31
 
31
- interface BatchItem<Key, Value> {
32
+ interface BatchItem<Key, Value, CacheKey> {
32
33
  key: Key;
34
+ cacheKey: CacheKey;
35
+ slot: number;
33
36
  resolve: (value: Value) => void;
34
37
  reject: (reason: unknown) => void;
35
38
  }
36
39
 
40
+ interface Batch<Key, Value, CacheKey> {
41
+ keys: Key[];
42
+ items: BatchItem<Key, Value, CacheKey>[];
43
+ }
44
+
37
45
  export class DataLoader<Key, Value, CacheKey = Key> {
38
46
  static readonly #minSweepSize = 1024;
39
47
  static readonly #defaultMaxCacheSize = 10_000;
48
+
49
+ static readonly #defaultMaxBatchSize = 500;
40
50
  readonly name?: string;
41
51
  readonly #batchLoadFn: BatchLoadFn<Key, Value>;
42
52
  readonly #ttl: number;
@@ -49,7 +59,7 @@ export class DataLoader<Key, Value, CacheKey = Key> {
49
59
  readonly #scopeFn: (() => object | undefined) | null;
50
60
  readonly #promiseCache = new Map<CacheKey, { promise: Promise<Value>; expiresAt: number }>();
51
61
  #sweepAt = DataLoader.#minSweepSize;
52
- readonly #queues = new Map<object | undefined, BatchItem<Key, Value>[]>();
62
+ readonly #queues = new Map<object | undefined, BatchItem<Key, Value, CacheKey>[]>();
53
63
 
54
64
  constructor(batchLoadFn: BatchLoadFn<Key, Value>, options: DataLoaderOptions<Key, Value, CacheKey> = {}) {
55
65
  this.#batchLoadFn = batchLoadFn;
@@ -63,7 +73,7 @@ export class DataLoader<Key, Value, CacheKey = Key> {
63
73
  this.#cacheKeyFn = options.cacheKeyFn ?? ((key) => key as unknown as CacheKey);
64
74
  this.#batch = options.batch !== false;
65
75
  this.#batchScheduleFn = options.batchScheduleFn ?? ((callback) => queueMicrotask(callback));
66
- this.#maxBatchSize = options.maxBatchSize ?? Number.POSITIVE_INFINITY;
76
+ this.#maxBatchSize = Math.max(1, Math.floor(options.maxBatchSize ?? DataLoader.#defaultMaxBatchSize));
67
77
  this.#copy = options.copy ?? null;
68
78
  this.#scopeFn = options.scopeFn ?? null;
69
79
  this.name = options.name;
@@ -76,9 +86,9 @@ export class DataLoader<Key, Value, CacheKey = Key> {
76
86
  if (cached) return this.#copy ? cached.then(this.#copy) : cached;
77
87
 
78
88
  const promise = new Promise<Value>((resolve, reject) => {
79
- const item = { key, resolve, reject };
89
+ const item = { key, cacheKey, slot: 0, resolve, reject };
80
90
  const queue = this.#queues.get(scope);
81
- if (!this.#batch) this.#run([item]);
91
+ if (!this.#batch) this.#run({ keys: [key], items: [item] });
82
92
  else if (queue) queue.push(item);
83
93
  else {
84
94
  this.#queues.set(scope, [item]);
@@ -144,39 +154,58 @@ export class DataLoader<Key, Value, CacheKey = Key> {
144
154
  #dispatch(scope: object | undefined) {
145
155
  const queue = this.#queues.get(scope);
146
156
  if (!queue) return;
147
- const batch = queue.splice(0, this.#maxBatchSize);
148
- if (queue.length > 0) this.#batchScheduleFn(() => this.#dispatch(scope));
149
- else this.#queues.delete(scope);
150
- this.#run(batch);
157
+ this.#queues.delete(scope);
158
+ const batches: Batch<Key, Value, CacheKey>[] = [];
159
+ const slots = new Map<CacheKey, number>();
160
+ for (const item of queue) {
161
+ const known = slots.get(item.cacheKey);
162
+ const slot = known ?? slots.size;
163
+ const index = Math.floor(slot / this.#maxBatchSize);
164
+ const batch = batches[index] ?? { keys: [], items: [] };
165
+ batches[index] = batch;
166
+ if (known === undefined) {
167
+ slots.set(item.cacheKey, slot);
168
+ batch.keys.push(item.key);
169
+ }
170
+ item.slot = slot % this.#maxBatchSize;
171
+ batch.items.push(item);
172
+ }
173
+ for (const batch of batches) this.#run(batch);
151
174
  }
152
175
 
153
- #run(batch: BatchItem<Key, Value>[]) {
154
- const keys = batch.map(({ key }) => key);
155
- Promise.resolve(this.#batchLoadFn(keys)).then(
176
+ #run({ keys, items }: Batch<Key, Value, CacheKey>) {
177
+ let loading: PromiseLike<ReadonlyArray<Value | Error>>;
178
+ try {
179
+ loading = Promise.resolve(this.#batchLoadFn(keys));
180
+ } catch (error) {
181
+ loading = Promise.reject(error);
182
+ }
183
+ loading.then(
156
184
  (values) => {
157
- if (values.length !== batch.length) {
158
- const error = new Error(`DataLoader expected ${batch.length} values, received ${values.length}`);
159
- for (const { reject } of batch) reject(error);
185
+ const received = Array.isArray(values) ? values.length : "no array";
186
+ if (received !== keys.length) {
187
+ const error = new Error(`DataLoader expected ${keys.length} values, received ${received}`);
188
+ for (const { reject } of items) reject(error);
160
189
  return;
161
190
  }
162
191
  const handedOut = new Set<Value | Error>();
163
- values.forEach((value, index) => {
164
- const item = batch[index];
165
- if (value instanceof Error) item?.reject(value);
166
- else if (this.#copy && handedOut.has(value)) {
192
+ for (const item of items) {
193
+ const value = values[item.slot];
194
+ if (value instanceof Error) item.reject(value);
195
+ else if (this.#copy && handedOut.has(value as Value)) {
167
196
  try {
168
- item?.resolve(this.#copy(value as Value));
197
+ item.resolve(this.#copy(value as Value));
169
198
  } catch (error) {
170
- item?.reject(error);
199
+ item.reject(error);
171
200
  }
172
201
  } else {
173
- handedOut.add(value);
174
- item?.resolve(value as Value);
202
+ handedOut.add(value as Value);
203
+ item.resolve(value as Value);
175
204
  }
176
- });
205
+ }
177
206
  },
178
207
  (error) => {
179
- for (const { reject } of batch) reject(error);
208
+ for (const { reject } of items) reject(error);
180
209
  },
181
210
  );
182
211
  }
@@ -215,6 +244,7 @@ export const createArrayLoader = <K, V>(model: LoaderModel, fieldName = "id", de
215
244
  findWhere(model, defaultQuery, fieldName, "has", fields).then((list) =>
216
245
  fields.map((field) => list.filter((item) => field === item[fieldName])),
217
246
  ) as unknown as Promise<V[]>,
247
+ { copy: (list) => (Array.isArray(list) ? ([...list] as V) : list) },
218
248
  );
219
249
  export const createArrayElementLoader = <K, V>(
220
250
  model: LoaderModel,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.2.0",
3
+ "version": "3.2.1-rc.1",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
package/server/akanApp.ts CHANGED
@@ -50,6 +50,8 @@ export class AkanApp {
50
50
  #metricsTimer: Timer | null = null;
51
51
  #ops: OpsRoute | null = null;
52
52
  #hostAllowlist = HostAllowlist.fromEnv();
53
+
54
+ #routeHostsPending = false;
53
55
  readonly #limits = new ServerLimits();
54
56
  readonly #statusAccess = StatusAccess.fromEnv();
55
57
  #resolveStopped: (() => void) | null = null;
@@ -195,7 +197,10 @@ export class AkanApp {
195
197
 
196
198
  #listen() {
197
199
 
198
- if (this.#hostAllowlist?.devDefault) RouteHosts.declare(this.#config.artifactDir);
200
+ if (this.#hostAllowlist?.devDefault) {
201
+ this.#routeHostsPending = !RouteHosts.written(this.#config.artifactDir);
202
+ RouteHosts.declare(this.#config.artifactDir);
203
+ }
199
204
  this.#server = Bun.serve({
200
205
  idleTimeout: this.#limits.idleTimeout,
201
206
  maxRequestBodySize: this.#limits.uploadBodyBytes,
@@ -219,7 +224,8 @@ export class AkanApp {
219
224
  }
220
225
 
221
226
  async #handleFetch(req: Request, server: Bun.Server<GatewayWsData>): Promise<Response | undefined> {
222
- if (this.#hostAllowlist && !this.#hostAllowlist.allows(req)) return this.#hostAllowlist.refuse();
227
+ if (this.#hostAllowlist && !this.#hostAllowlist.allows(req))
228
+ return this.#routeHostsPending ? this.#proxy.respondWithUnavailable(req) : this.#hostAllowlist.refuse();
223
229
  const oversized = this.#limits.refuseDeclared(req);
224
230
  if (oversized) return oversized;
225
231
  const url = new URL(req.url);
@@ -254,6 +260,11 @@ export class AkanApp {
254
260
  if (!message || typeof message !== "object") return;
255
261
  switch (message.type) {
256
262
  case "ready":
263
+
264
+ if (this.#hostAllowlist?.devDefault) RouteHosts.declare(this.#config.artifactDir);
265
+ this.#routeHostsPending = false;
266
+
267
+ delete process.env.AKAN_DEV_AWAIT_ARTIFACT;
257
268
  this.#supervisor.markReady(idx, message);
258
269
  return;
259
270
  case "pubsub.publish":
@@ -16,6 +16,7 @@ import { EndpointRateLimit } from "../signal/endpointRateLimit";
16
16
  import { AgentHooks } from "./agentHooks";
17
17
  import type { AkanLib, AkanLibProps } from "./akanLib";
18
18
  import { DiLifecycle } from "./di/diLifecycle";
19
+ import { DevBaseArtifact } from "./hmr/devBaseArtifact";
19
20
  import { ParentChannel } from "./lifecycle/parentChannel";
20
21
  import { ShutdownManager } from "./lifecycle/shutdownManager";
21
22
  import { StartGuard } from "./lifecycle/startGuard";
@@ -354,6 +355,9 @@ export class AkanServer {
354
355
  this.status = "initialized";
355
356
  return this;
356
357
  }
358
+ const artifactWaitMs = await DevBaseArtifact.arrived({ stopped: () => this.#start.stopHeld });
359
+ if (this.#start.stopHeld) return this;
360
+ if (artifactWaitMs > 0) this.#initTimings.set("artifact", artifactWaitMs);
357
361
  RouteHosts.declare();
358
362
  const requestedWeb = ServerConfig.narrowWeb(this.web, web);
359
363
  const noWeb = () => {
@@ -253,10 +253,35 @@ export const encodedBodyResponse = (
253
253
  };
254
254
 
255
255
  export interface EncodedSidecar {
256
- bytes: ArrayBuffer;
257
- encoding: string;
256
+ file: ReturnType<typeof Bun.file>;
257
+ size: number;
258
+ encoding: ContentEncoding;
258
259
  }
259
260
 
261
+ const MEMO_LIMIT = 4096;
262
+ const sidecarSizes = new Map<string, number>();
263
+
264
+ const isProductionServer = () => process.env.NODE_ENV === "production" && process.env.AKAN_COMMAND_TYPE !== "start";
265
+
266
+ const probeSidecar = async (sidecarPath: string) => {
267
+ const file = Bun.file(sidecarPath);
268
+ return { file, size: (await file.exists()) ? file.size : 0 };
269
+ };
270
+
271
+ const memoizedSidecar = async (sidecarPath: string) => {
272
+ const known = sidecarSizes.get(sidecarPath);
273
+ if (known === 0) return null;
274
+ if (known !== undefined) {
275
+ const file = Bun.file(sidecarPath);
276
+
277
+ if (file.size === known) return { file, size: known };
278
+ }
279
+ const probed = await probeSidecar(sidecarPath);
280
+ if (sidecarSizes.size >= MEMO_LIMIT) sidecarSizes.clear();
281
+ sidecarSizes.set(sidecarPath, probed.size);
282
+ return probed.size ? probed : null;
283
+ };
284
+
260
285
  export const resolveEncodedSidecar = async (
261
286
  req: Request,
262
287
  filePath: string,
@@ -264,13 +289,12 @@ export const resolveEncodedSidecar = async (
264
289
  ): Promise<EncodedSidecar | null> => {
265
290
  if (!isCompressibleContentType(contentType)) return null;
266
291
  const accepted = acceptedEncodings(req.headers.get("accept-encoding") ?? "");
292
+ const production = isProductionServer();
267
293
  for (const { encoding, ext } of CONTENT_ENCODINGS) {
268
294
  if (!accepted.includes(encoding)) continue;
269
- const file = Bun.file(`${filePath}${ext}`);
270
- if (!(await file.exists())) continue;
271
- const bytes = await file.bytes();
272
- const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
273
- return { bytes: buffer, encoding };
295
+ const sidecarPath = `${filePath}${ext}`;
296
+ const found = production ? await memoizedSidecar(sidecarPath) : await probeSidecar(sidecarPath);
297
+ if (found?.size) return { file: found.file, size: found.size, encoding };
274
298
  }
275
299
  return null;
276
300
  };
@@ -290,6 +314,12 @@ export const encodedFileResponse = async (
290
314
  return new Response(file, { headers });
291
315
  }
292
316
  headers.set("Content-Encoding", sidecar.encoding);
293
- headers.set("Content-Length", String(sidecar.bytes.byteLength));
294
- return new Response(sidecar.bytes, { headers });
317
+ if (req.headers.has("range")) {
318
+ const bytes = await sidecar.file.bytes();
319
+ const whole = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
320
+ headers.set("Content-Length", String(whole.byteLength));
321
+ return new Response(whole, { headers });
322
+ }
323
+ headers.set("Content-Length", String(sidecar.size));
324
+ return new Response(sidecar.file, { headers });
295
325
  };