@compforge/harness-toolbox 0.3.3 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -157,6 +157,49 @@ fall back to Pod Python. Completion, truncation, timeout, and cancellation destr
157
157
  session without replay or changes to ordinary borrowed sessions. Disconnect does not prove immediate
158
158
  server cancellation. The byte budget limits retained JSON rows, not individual wire packets or fields.
159
159
 
160
+ ## Reusable bounded queries and read caches
161
+
162
+ For trusted, caller-owned SELECT statements, `queryLimited(database, target, statement, maxRows)`
163
+ appends an integer `LIMIT maxRows + 1` and returns `{ rows, truncated }`. SQL must not already have
164
+ LIMIT or a trailing terminator; the helper does not parse or rewrite arbitrary SQL. Business values
165
+ stay bound parameters. `limitedStatement` and `limitedRows` expose the same preparation/projection
166
+ for `Database.queryBatch`. `maxRows` must be a positive integer below 2147483647. These helpers
167
+ bound row count only: use `queryReadonly` when a disposable readonly session and byte/time budgets
168
+ are required.
169
+
170
+ `DataLoader` shares results, failures and in-flight work within one explicit read scope, similar to
171
+ Guava's LoadingCache but scoped to a single collection round. Consumers must not mutate shared results.
172
+ Use `withReadScope` to bind caller-approved database reads; do not use it for writes or polling.
173
+
174
+ ```ts
175
+ import { DataLoader } from '@compforge/harness-toolbox/data-loader';
176
+ import { withReadScope, queryLimited } from '@compforge/harness-toolbox/mysql';
177
+
178
+ const scope = new DataLoader({
179
+ maxEntries: 256, maxBytes: 4 * 1024 * 1024, signal: client.signal,
180
+ });
181
+ const reads = withReadScope(client.database, scope);
182
+ try {
183
+ const page = await queryLimited(reads, client.target, {
184
+ sql: 'SELECT id FROM items WHERE owner = ? ORDER BY id', values: [owner],
185
+ }, 100);
186
+ } finally {
187
+ await scope.close(); // Root still owns client.dispose().
188
+ }
189
+ ```
190
+
191
+ Keys include full database identity, SQL and typed parameters as an opaque digest. Nonserializable
192
+ parameters bypass caching. Batch reads reuse cached entries and send misses as one ordered native
193
+ batch, or sequential queries when batching is unavailable. Failures are shared without replay;
194
+ use a new scope for fresh observations. This is not a consistent database snapshot.
195
+
196
+ Entry capacity includes failures and pending reads; new keys bypass caching when full. Serialized
197
+ result bytes bound retained results, excluding keys/errors and active operation memory. Oversized
198
+ or nonserializable results are returned but not retained. Scope close signals cancellation and joins
199
+ operations, including uncached reads. Operations must honor the signal for prompt cancellation;
200
+ MySQL reads retain their underlying client's timeout/cancellation policy. Adapter close owns neither
201
+ the scope nor the database. A waiter's optional signal to `scope.read` cancels only that waiter.
202
+
160
203
  ## Shared Pod relay transport
161
204
 
162
205
  `PodRelayTransport` opens TCP routes through an existing Running/Ready Pod. It discovers an
@@ -0,0 +1,20 @@
1
+ // src/mysql/limited.ts
2
+ function validateLimit(maxRows) {
3
+ if (!Number.isSafeInteger(maxRows) || maxRows < 1 || maxRows >= 2147483647) {
4
+ throw new Error("maxRows must be a positive integer < 2147483647");
5
+ }
6
+ }
7
+ function limitedStatement(statement, maxRows) {
8
+ validateLimit(maxRows);
9
+ return { sql: `${statement.sql} LIMIT ${maxRows + 1}`, values: statement.values };
10
+ }
11
+ function limitedRows(rows, maxRows) {
12
+ validateLimit(maxRows);
13
+ return { rows: rows.slice(0, maxRows), truncated: rows.length > maxRows };
14
+ }
15
+ async function queryLimited(database, target, statement, maxRows) {
16
+ const bounded = limitedStatement(statement, maxRows);
17
+ return limitedRows(await database.query(target, bounded.sql, bounded.values), maxRows);
18
+ }
19
+
20
+ export { limitedStatement, limitedRows, queryLimited };
@@ -0,0 +1,51 @@
1
+ // src/mysql/scoped.ts
2
+ import { createHash } from "node:crypto";
3
+ import { serialize } from "node:v8";
4
+ function queryKey(kind, target, statement) {
5
+ try {
6
+ return createHash("sha256").update(serialize([
7
+ kind,
8
+ target.host,
9
+ target.port,
10
+ target.database,
11
+ target.user,
12
+ target.password,
13
+ statement.sql,
14
+ statement.values
15
+ ])).digest("hex");
16
+ } catch {
17
+ return;
18
+ }
19
+ }
20
+ function withReadScope(database, scope) {
21
+ const query = (target, sql, values) => scope.read(queryKey("query", target, { sql, values }), () => database.query(target, sql, values));
22
+ return {
23
+ query,
24
+ queryOne: (target, sql, values) => scope.read(queryKey("one", target, { sql, values }), () => database.queryOne(target, sql, values)),
25
+ queryBatch: async (target, statements) => {
26
+ const misses = [];
27
+ let batch;
28
+ if (!statements.length)
29
+ return scope.read(undefined, async () => []);
30
+ return Promise.all(statements.map((statement) => scope.read(queryKey("query", target, statement), (signal) => {
31
+ const position = misses.length;
32
+ misses.push(statement);
33
+ batch ??= Promise.resolve().then(async () => {
34
+ signal.throwIfAborted();
35
+ if (database.queryBatch)
36
+ return database.queryBatch(target, misses);
37
+ const rows = [];
38
+ for (const item of misses) {
39
+ signal.throwIfAborted();
40
+ rows.push(await database.query(target, item.sql, item.values));
41
+ }
42
+ return rows;
43
+ });
44
+ return batch.then((rows) => rows[position]);
45
+ })));
46
+ },
47
+ close: async () => {}
48
+ };
49
+ }
50
+
51
+ export { withReadScope };
@@ -0,0 +1,21 @@
1
+ export interface DataLoaderOptions {
2
+ maxEntries: number;
3
+ /** Serialized result bytes retained, excluding keys/errors and active operation memory. */
4
+ maxBytes: number;
5
+ signal: AbortSignal;
6
+ }
7
+ /** A scoped async loading cache, similar to Guava's LoadingCache.
8
+ * Shares results, failures and in-flight reads until close; consumers must not mutate results.
9
+ * Unlike a long-lived LoadingCache, this scope has no refresh/expiry or automatic batching.
10
+ * Keys and loading operations belong to adapters; the same key must have the same result type.
11
+ * Operations must honor their signal for prompt cancellation. No underlying client is owned.
12
+ */
13
+ export declare class DataLoader {
14
+ #private;
15
+ private readonly options;
16
+ constructor(options: DataLoaderOptions);
17
+ /** Undefined keys bypass caching. A waiter's signal cancels only that wait, not shared work. */
18
+ read<T>(key: unknown, operation: (signal: AbortSignal) => Promise<T>, signal?: AbortSignal): Promise<T>;
19
+ /** Abort cooperative operations and join all reads, including capacity-bypass reads. */
20
+ close(reason?: unknown): Promise<void>;
21
+ }
@@ -0,0 +1,91 @@
1
+ // src/data-loader.ts
2
+ import { serialize } from "node:v8";
3
+
4
+ class DataLoader {
5
+ options;
6
+ #entries = new Map;
7
+ #pending = new Set;
8
+ #controller = new AbortController;
9
+ #bytes = 0;
10
+ #closing;
11
+ constructor(options) {
12
+ this.options = options;
13
+ for (const name of ["maxEntries", "maxBytes"]) {
14
+ if (!Number.isSafeInteger(options[name]) || options[name] < 1)
15
+ throw new Error(`${name} must be a positive safe integer`);
16
+ }
17
+ options.signal.throwIfAborted();
18
+ options.signal.addEventListener("abort", this.#abort, { once: true });
19
+ }
20
+ #abort = () => {
21
+ this.close(this.options.signal.reason);
22
+ };
23
+ async read(key, operation, signal) {
24
+ this.#controller.signal.throwIfAborted();
25
+ signal?.throwIfAborted();
26
+ let pending = key === undefined ? undefined : this.#entries.get(key);
27
+ if (!pending) {
28
+ const retain = key !== undefined && this.#entries.size < this.options.maxEntries;
29
+ pending = Promise.resolve().then(async () => {
30
+ this.#controller.signal.throwIfAborted();
31
+ const value = await operation(this.#controller.signal);
32
+ this.#controller.signal.throwIfAborted();
33
+ if (retain) {
34
+ let bytes;
35
+ try {
36
+ bytes = serialize(value).byteLength;
37
+ } catch {
38
+ bytes = Infinity;
39
+ }
40
+ if (this.#bytes + bytes <= this.options.maxBytes)
41
+ this.#bytes += bytes;
42
+ else
43
+ this.#entries.delete(key);
44
+ }
45
+ return value;
46
+ });
47
+ if (retain)
48
+ this.#entries.set(key, pending);
49
+ this.#pending.add(pending);
50
+ const done = () => {
51
+ this.#pending.delete(pending);
52
+ };
53
+ pending.then(done, done);
54
+ }
55
+ if (!signal)
56
+ return await pending;
57
+ return new Promise((resolve, reject) => {
58
+ const abort = () => {
59
+ cleanup();
60
+ reject(signal.reason);
61
+ };
62
+ const cleanup = () => {
63
+ signal.removeEventListener("abort", abort);
64
+ };
65
+ signal.addEventListener("abort", abort, { once: true });
66
+ pending.then((value) => {
67
+ cleanup();
68
+ resolve(value);
69
+ }, (error) => {
70
+ cleanup();
71
+ reject(error);
72
+ });
73
+ });
74
+ }
75
+ close(reason = new Error("DataLoader scope is closed")) {
76
+ if (!this.#closing) {
77
+ this.#closing = Promise.resolve().then(async () => {
78
+ await Promise.allSettled([...this.#pending]);
79
+ this.#entries.clear();
80
+ this.#bytes = 0;
81
+ });
82
+ this.options.signal.removeEventListener("abort", this.#abort);
83
+ this.#controller.abort(reason);
84
+ this.#entries.clear();
85
+ }
86
+ return this.#closing;
87
+ }
88
+ }
89
+ export {
90
+ DataLoader
91
+ };
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  PodLogClient
3
- } from "../chunk-010339ga.js";
3
+ } from "../chunk-mnad4zkp.js";
4
4
  import"../chunk-8nm9f0hh.js";
5
- import"../chunk-1vfwvgkj.js";
6
5
  import"../chunk-mp88s7r7.js";
6
+ import"../chunk-1vfwvgkj.js";
7
7
  import"../chunk-a9htb6cr.js";
8
8
  import"../chunk-v3hxvnrc.js";
9
9
  export {
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  PodLogClient
3
- } from "../chunk-010339ga.js";
3
+ } from "../chunk-mnad4zkp.js";
4
4
  import"../chunk-8nm9f0hh.js";
5
- import"../chunk-1vfwvgkj.js";
6
5
  import"../chunk-mp88s7r7.js";
6
+ import"../chunk-1vfwvgkj.js";
7
7
  import"../chunk-a9htb6cr.js";
8
8
  import {
9
9
  clientKey
@@ -2,9 +2,9 @@ import {
2
2
  MysqlClient,
3
3
  MysqlDatabase,
4
4
  openMysql
5
- } from "../chunk-jx740hjh.js";
6
- import"../chunk-kbewz29a.js";
5
+ } from "../chunk-56t4qyp7.js";
7
6
  import"../chunk-m91t44jh.js";
7
+ import"../chunk-kbewz29a.js";
8
8
  import"../chunk-v3hxvnrc.js";
9
9
  import"../chunk-h8fwx0k7.js";
10
10
  import"../chunk-5fgbhx2r.js";
@@ -1,3 +1,5 @@
1
1
  export * from "./types";
2
2
  export * from "./target";
3
3
  export * from "./client";
4
+ export * from "./limited";
5
+ export * from "./scoped";
@@ -1,14 +1,22 @@
1
+ import"../chunk-pfar9cm3.js";
2
+ import {
3
+ withReadScope
4
+ } from "../chunk-4sqvppz7.js";
1
5
  import {
2
6
  MysqlClient,
3
7
  MysqlDatabase,
4
8
  openMysql
5
- } from "../chunk-jx740hjh.js";
9
+ } from "../chunk-56t4qyp7.js";
10
+ import"../chunk-m91t44jh.js";
6
11
  import"../chunk-kbewz29a.js";
7
12
  import {
8
13
  parseMysqlEnvTarget
9
14
  } from "../chunk-qq77x9ek.js";
10
- import"../chunk-pfar9cm3.js";
11
- import"../chunk-m91t44jh.js";
15
+ import {
16
+ limitedRows,
17
+ limitedStatement,
18
+ queryLimited
19
+ } from "../chunk-1gyshqd9.js";
12
20
  import"../chunk-v3hxvnrc.js";
13
21
  import"../chunk-h8fwx0k7.js";
14
22
  import"../chunk-5fgbhx2r.js";
@@ -17,8 +25,12 @@ import"../chunk-hmah9t8e.js";
17
25
  import"../chunk-mn6dwsvh.js";
18
26
  import"../chunk-ssj93brx.js";
19
27
  export {
28
+ withReadScope,
29
+ queryLimited,
20
30
  parseMysqlEnvTarget,
21
31
  openMysql,
32
+ limitedStatement,
33
+ limitedRows,
22
34
  MysqlDatabase,
23
35
  MysqlClient
24
36
  };
@@ -0,0 +1,13 @@
1
+ import type { Database, DatabaseRow, DatabaseTarget, SqlStatement } from "./types";
2
+ export interface LimitedRows {
3
+ rows: DatabaseRow[];
4
+ truncated: boolean;
5
+ }
6
+ /** Append to caller-owned SQL without an existing LIMIT or trailing terminator; never rewrite SQL.
7
+ * An integer literal avoids driver/server differences in numeric LIMIT parameter binding.
8
+ */
9
+ export declare function limitedStatement(statement: SqlStatement, maxRows: number): SqlStatement;
10
+ /** The extra row proves truncation; batch callers can use the same projection. */
11
+ export declare function limitedRows(rows: DatabaseRow[], maxRows: number): LimitedRows;
12
+ /** Row-count bound for trusted reads on the existing session, not a readonly transaction or byte cap. */
13
+ export declare function queryLimited(database: Pick<Database, "query">, target: DatabaseTarget, statement: SqlStatement, maxRows: number): Promise<LimitedRows>;
@@ -0,0 +1,10 @@
1
+ import {
2
+ limitedRows,
3
+ limitedStatement,
4
+ queryLimited
5
+ } from "../chunk-1gyshqd9.js";
6
+ export {
7
+ queryLimited,
8
+ limitedStatement,
9
+ limitedRows
10
+ };
@@ -0,0 +1,7 @@
1
+ import type { DataLoader } from "../data-loader";
2
+ import type { Database } from "./types";
3
+ /** Bind caller-approved reads to a borrowed scope. Results are shared and must not be mutated.
4
+ * Close is a no-op: the root owns both scope and database lifetimes. Database operations retain
5
+ * their client's cancellation/timeout policy; they cannot be individually aborted by this adapter.
6
+ */
7
+ export declare function withReadScope(database: Database, scope: DataLoader): Database & Required<Pick<Database, "queryBatch">>;
@@ -0,0 +1,6 @@
1
+ import {
2
+ withReadScope
3
+ } from "../chunk-4sqvppz7.js";
4
+ export {
5
+ withReadScope
6
+ };
@@ -29,5 +29,7 @@ export interface DatabaseQueryResult {
29
29
  export interface Database {
30
30
  query(target: DatabaseTarget, sql: string, values: readonly unknown[]): Promise<DatabaseRow[]>;
31
31
  queryOne(target: DatabaseTarget, sql: string, values: readonly unknown[]): Promise<DatabaseRow | undefined>;
32
+ /** Independent statements in submission order; fail-fast, without atomicity or replay. */
33
+ queryBatch?(target: DatabaseTarget, statements: readonly SqlStatement[]): Promise<DatabaseRow[][]>;
32
34
  close(): Promise<void>;
33
35
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@compforge/harness-toolbox",
3
- "version": "0.3.3",
3
+ "version": "0.3.4",
4
4
  "description": "Shared infrastructure clients, transports and bounded data capture",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -80,6 +80,10 @@
80
80
  "./concurrency": {
81
81
  "types": "./dist/concurrency.d.ts",
82
82
  "import": "./dist/concurrency.js"
83
+ },
84
+ "./data-loader": {
85
+ "types": "./dist/data-loader.d.ts",
86
+ "import": "./dist/data-loader.js"
83
87
  }
84
88
  },
85
89
  "files": [
@@ -102,9 +106,6 @@
102
106
  "@types/node-fetch": "2.6.13",
103
107
  "@types/node": "^22"
104
108
  },
105
- "overrides": {
106
- "@compforge/harness-common": "file:../common"
107
- },
108
109
  "publishConfig": {
109
110
  "access": "public"
110
111
  },
@@ -1,11 +1,11 @@
1
- import {
2
- queryReadonlySession,
3
- validateQueryLimits
4
- } from "./chunk-kbewz29a.js";
5
1
  import {
6
2
  queryMysqlViaPod,
7
3
  queryMysqlViaPodBatch
8
4
  } from "./chunk-m91t44jh.js";
5
+ import {
6
+ queryReadonlySession,
7
+ validateQueryLimits
8
+ } from "./chunk-kbewz29a.js";
9
9
  import {
10
10
  ConcurrencyPool
11
11
  } from "./chunk-v3hxvnrc.js";
@@ -2,12 +2,12 @@ import {
2
2
  PodLogByteBudget,
3
3
  runPodLogCapturePlan
4
4
  } from "./chunk-8nm9f0hh.js";
5
- import {
6
- LogCaptureFile
7
- } from "./chunk-1vfwvgkj.js";
8
5
  import {
9
6
  logTimestampNanos
10
7
  } from "./chunk-mp88s7r7.js";
8
+ import {
9
+ LogCaptureFile
10
+ } from "./chunk-1vfwvgkj.js";
11
11
  import {
12
12
  clientKey
13
13
  } from "./chunk-a9htb6cr.js";