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
@@ -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.0",
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
  };