@noego/sqlego 0.1.3 → 0.1.4-dev.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.
package/dist/client.d.ts CHANGED
@@ -81,6 +81,9 @@ export declare class SqlegoClient {
81
81
  private socket;
82
82
  /** Reply frames from `socket`; the socket decodes UTF-8 itself (`setEncoding`), split characters included. */
83
83
  private readonly frames;
84
+ /** Request frames queued in this microtask turn, joined and written once before the turn ends. */
85
+ private readonly outbound;
86
+ private flushScheduled;
84
87
  private nextId;
85
88
  private readonly pending;
86
89
  private hello;
package/dist/index.js CHANGED
@@ -98,7 +98,8 @@ var SAFE_MIN = -9007199254740991n;
98
98
  var DECIMAL_INTEGER = /^(?:0|-?[1-9][0-9]{0,18})$/;
99
99
  var BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
100
100
  function toJson(value, indent) {
101
- const encoded = Trust.try(() => JSON.stringify(value, replaceBigInt, indent), (cause) => ({ kind: "encode-failed", message: errorMessage(cause) }));
101
+ const fast = Trust.try(() => indent === undefined ? JSON.stringify(value) : JSON.stringify(value, undefined, indent), (cause) => ({ kind: "encode-failed", message: errorMessage(cause) }));
102
+ const encoded = fast.ok ? fast : Trust.try(() => JSON.stringify(value, replaceBigInt, indent), (cause) => ({ kind: "encode-failed", message: errorMessage(cause) }));
102
103
  if (!encoded.ok)
103
104
  return encoded;
104
105
  if (typeof encoded.value !== "string")
@@ -125,21 +126,30 @@ function encodeRequestParams(request) {
125
126
  const params = encodeSqlParams(request.params);
126
127
  if (!params.ok)
127
128
  return params;
129
+ if (params.value === request.params)
130
+ return Result.ok(request);
128
131
  return Result.ok({ ...request, params: params.value });
129
132
  }
130
133
  case "batch": {
131
- const statements = [];
132
- for (const [index, statement] of request.statements.entries()) {
134
+ let changed = false;
135
+ const statements = new Array(request.statements.length);
136
+ for (let index = 0;index < request.statements.length; index += 1) {
137
+ const statement = request.statements[index];
133
138
  if (statement.params === undefined) {
134
- statements.push(statement);
139
+ statements[index] = statement;
135
140
  continue;
136
141
  }
137
142
  const params = encodeSqlParams(statement.params);
138
143
  if (!params.ok)
139
144
  return invalid(`statements[${index}].${params.error.message}`);
140
- statements.push({ ...statement, params: params.value });
145
+ if (params.value === statement.params) {
146
+ statements[index] = statement;
147
+ } else {
148
+ changed = true;
149
+ statements[index] = { ...statement, params: params.value };
150
+ }
141
151
  }
142
- return Result.ok({ ...request, statements });
152
+ return Result.ok(changed ? { ...request, statements } : request);
143
153
  }
144
154
  default:
145
155
  return Result.ok(request);
@@ -150,23 +160,51 @@ function encodeSqlParams(params) {
150
160
  return invalid("params must be an array or an object");
151
161
  const shape = paramsShape(params);
152
162
  if (shape.kind === "positional") {
153
- const values = [];
154
- for (const [index, item] of shape.values.entries()) {
163
+ const items = shape.values;
164
+ let values = null;
165
+ for (let index = 0;index < items.length; index += 1) {
166
+ const item = items[index];
167
+ if (item === null || typeof item === "string" || typeof item === "boolean" || typeof item === "number" && Number.isFinite(item)) {
168
+ if (values !== null)
169
+ values[index] = item;
170
+ continue;
171
+ }
155
172
  const value = encodeParamValue(item);
156
173
  if (!value.ok)
157
174
  return invalid(`params[${index}]: ${value.error.message}`);
158
- values.push(value.value);
175
+ if (values === null) {
176
+ values = new Array(items.length);
177
+ for (let prev = 0;prev < index; prev += 1)
178
+ values[prev] = items[prev];
179
+ }
180
+ values[index] = value.value;
159
181
  }
160
- return Result.ok(values);
182
+ return Result.ok(values ?? items);
161
183
  }
162
- const entries = [];
163
- for (const [name, item] of Object.entries(shape.values)) {
184
+ const fields = shape.values;
185
+ const keys = Object.keys(fields);
186
+ let entries = null;
187
+ for (let index = 0;index < keys.length; index += 1) {
188
+ const name = keys[index];
189
+ const item = fields[name];
190
+ if (item === null || typeof item === "string" || typeof item === "boolean" || typeof item === "number" && Number.isFinite(item)) {
191
+ if (entries !== null)
192
+ entries.push([name, item]);
193
+ continue;
194
+ }
164
195
  const value = encodeParamValue(item);
165
196
  if (!value.ok)
166
197
  return invalid(`params.${name}: ${value.error.message}`);
198
+ if (entries === null) {
199
+ entries = [];
200
+ for (let prev = 0;prev < index; prev += 1) {
201
+ const prevKey = keys[prev];
202
+ entries.push([prevKey, fields[prevKey]]);
203
+ }
204
+ }
167
205
  entries.push([name, value.value]);
168
206
  }
169
- return Result.ok(Object.fromEntries(entries));
207
+ return Result.ok(entries === null ? fields : Object.fromEntries(entries));
170
208
  }
171
209
  function paramsShape(params) {
172
210
  return Array.isArray(params) ? { kind: "positional", values: params } : { kind: "named", values: params };
@@ -230,17 +268,25 @@ function parseWireBigInt(input) {
230
268
  return Result.ok(parsed.value);
231
269
  }
232
270
  function parseWireBlob(input) {
233
- if (typeof input !== "string" || !BASE64.test(input))
271
+ if (typeof input !== "string" || !BASE64.test(input) || !hasCanonicalBase64Padding(input)) {
234
272
  return invalid("$blob must be canonical padded base64");
235
- const decoded = Trust.try(() => {
236
- const bytes = Buffer.from(input, "base64");
237
- return { bytes: new Uint8Array(bytes), canonical: bytes.toString("base64") };
238
- }, (cause) => ({ kind: "invalid", message: `$blob: ${errorMessage(cause)}` }));
273
+ }
274
+ const decoded = Trust.try(() => new Uint8Array(Buffer.from(input, "base64")), (cause) => ({ kind: "invalid", message: `$blob: ${errorMessage(cause)}` }));
239
275
  if (!decoded.ok)
240
276
  return decoded;
241
- if (decoded.value.canonical !== input)
242
- return invalid("$blob must be canonical padded base64");
243
- return Result.ok(decoded.value.bytes);
277
+ return Result.ok(decoded.value);
278
+ }
279
+ function hasCanonicalBase64Padding(input) {
280
+ const length = input.length;
281
+ if (length === 0 || input.charCodeAt(length - 1) !== 61)
282
+ return true;
283
+ if (input.charCodeAt(length - 2) === 61) {
284
+ const c = input.charCodeAt(length - 3);
285
+ return c === 65 || c === 81 || c === 103 || c === 119;
286
+ }
287
+ const c = input.charCodeAt(length - 2);
288
+ const sextet = c >= 65 && c <= 90 ? c - 65 : c >= 97 && c <= 122 ? c - 97 + 26 : c >= 48 && c <= 57 ? c - 48 + 52 : c === 43 ? 62 : 63;
289
+ return (sextet & 3) === 0;
244
290
  }
245
291
  function parseWireInteger(input, at) {
246
292
  if (typeof input === "number" && Number.isSafeInteger(input))
@@ -291,22 +337,22 @@ function parseResponse(input) {
291
337
  const response = { id, ok: false, error: { code: code.value, message: error.message } };
292
338
  return Result.ok(response);
293
339
  }
294
- function parseRow(input) {
295
- const fields = fieldsOf(input);
296
- if (!fields)
297
- return invalid("a row must be an object");
298
- const row = { ...fields };
299
- return Result.ok(row);
300
- }
301
340
  function parseRows(input) {
302
341
  if (!Array.isArray(input))
303
342
  return invalid("rows must be an array");
304
- const rows = [];
305
- for (const [index, item] of input.entries()) {
306
- const row = parseRow(item);
307
- if (!row.ok)
308
- return invalid(`rows[${index}]: ${row.error.message}`);
309
- rows.push(row.value);
343
+ const rows = new Array(input.length);
344
+ for (let index = 0;index < input.length; index += 1) {
345
+ const item = input[index];
346
+ const fields = fieldsOf(item);
347
+ if (!fields)
348
+ return invalid(`rows[${index}]: a row must be an object`);
349
+ const row = item;
350
+ for (const column in fields) {
351
+ const raw = fields[column];
352
+ if (typeof raw === "bigint")
353
+ row[column] = Number(raw);
354
+ }
355
+ rows[index] = row;
310
356
  }
311
357
  return Result.ok(rows);
312
358
  }
@@ -348,20 +394,23 @@ function parseBatchResult(input) {
348
394
  function parseWireRows(input) {
349
395
  if (!Array.isArray(input))
350
396
  return invalid("rows must be an array");
351
- const rows = [];
352
- for (const [index, item] of input.entries()) {
397
+ const rows = new Array(input.length);
398
+ for (let index = 0;index < input.length; index += 1) {
399
+ const item = input[index];
353
400
  const fields = fieldsOf(item);
354
401
  if (!fields)
355
402
  return invalid(`rows[${index}] must be an object`);
356
- const entries = [];
357
- for (const [column, raw] of Object.entries(fields)) {
403
+ const record = item;
404
+ for (const column in fields) {
405
+ const raw = fields[column];
406
+ if (raw === null || typeof raw === "string" || typeof raw === "boolean" || typeof raw === "number" && Number.isFinite(raw))
407
+ continue;
358
408
  const value = parseSqlValue(raw);
359
409
  if (!value.ok)
360
410
  return invalid(`rows[${index}].${column}: ${value.error.message}`);
361
- entries.push([column, value.value]);
411
+ record[column] = value.value;
362
412
  }
363
- const row = Object.fromEntries(entries);
364
- rows.push(row);
413
+ rows[index] = record;
365
414
  }
366
415
  return Result.ok(rows);
367
416
  }
@@ -605,8 +654,7 @@ function resolvePaths(file) {
605
654
  return directory;
606
655
  const derived = Trust.try(() => {
607
656
  const key = createHash("sha1").update(canonical.value).digest("hex").slice(0, 16);
608
- const scope = createHash("sha1").update(directory.value.toLowerCase()).digest("hex").slice(0, 8);
609
- const socket = USES_NAMED_PIPES ? `\\\\.\\pipe\\sqlego-${scope}-${key}` : path2.join(directory.value, `${key}.sock`);
657
+ const socket = USES_NAMED_PIPES ? `\\\\.\\pipe\\sqlego-${createHash("sha1").update(directory.value.toLowerCase()).digest("hex").slice(0, 8)}-${key}` : path2.join(directory.value, `${key}.sock`);
610
658
  return { key, socket, socketBytes: Buffer.byteLength(socket) };
611
659
  }, (cause) => ({ kind: "hash-failed", message: `cannot hash ${canonical.value}: ${errorMessage(cause)}` }));
612
660
  if (!derived.ok)
@@ -679,7 +727,7 @@ import { fileURLToPath } from "node:url";
679
727
  // package.json
680
728
  var package_default = {
681
729
  name: "@noego/sqlego",
682
- version: "0.1.3",
730
+ version: "0.1.4-dev.1",
683
731
  description: "One owner per SQLite file, many files per owner process. Clients (CLI, Node, Bun) pass SQL over a local socket (Unix) or named pipe (Windows); the owner starts on demand and exits when idle.",
684
732
  type: "module",
685
733
  license: "ISC",
@@ -727,14 +775,14 @@ var package_default = {
727
775
  typescript: "^5.6.0"
728
776
  },
729
777
  dependencies: {
730
- "@noego/trust": "^0.5.0"
778
+ "@noego/trust": "^0.5.1"
731
779
  },
732
780
  optionalDependencies: {
733
- "@noego/sqlego-darwin-arm64": "0.1.3",
734
- "@noego/sqlego-darwin-x64": "0.1.3",
735
- "@noego/sqlego-linux-x64": "0.1.3",
736
- "@noego/sqlego-linux-arm64": "0.1.3",
737
- "@noego/sqlego-win32-x64": "0.1.3"
781
+ "@noego/sqlego-darwin-arm64": "0.1.4-dev.1",
782
+ "@noego/sqlego-darwin-x64": "0.1.4-dev.1",
783
+ "@noego/sqlego-linux-x64": "0.1.4-dev.1",
784
+ "@noego/sqlego-linux-arm64": "0.1.4-dev.1",
785
+ "@noego/sqlego-win32-x64": "0.1.4-dev.1"
738
786
  }
739
787
  };
740
788
 
@@ -752,8 +800,8 @@ function sourceBuildId(sourceDirectory) {
752
800
  }, (cause) => ({ kind: "source-unreadable", message: `cannot hash sources in ${sourceDirectory}: ${errorMessage(cause)}` }));
753
801
  }
754
802
  function resolveBuildId() {
755
- if ("3f3144144273".length > 0)
756
- return "3f3144144273";
803
+ if ("ff247411ec41".length > 0)
804
+ return "ff247411ec41";
757
805
  const directory = Trust.try(() => path3.dirname(fileURLToPath(import.meta.url)), (cause) => ({ kind: "module-path", message: errorMessage(cause) }));
758
806
  if (!directory.ok)
759
807
  return decideUnknownBuild(directory.error.kind);
@@ -806,6 +854,8 @@ class SqlegoClient {
806
854
  paths;
807
855
  socket = null;
808
856
  frames = new FrameReader;
857
+ outbound = [];
858
+ flushScheduled = false;
809
859
  nextId = 1;
810
860
  pending = new Map;
811
861
  hello = null;
@@ -1037,13 +1087,13 @@ class SqlegoClient {
1037
1087
  return Result.err({ kind: placed.error.kind, message: `${placed.error.message}${suffix}` });
1038
1088
  }
1039
1089
  }
1040
- while (Date.now() < deadline) {
1090
+ for (let delayMs = 2;Date.now() < deadline; delayMs = Math.min(25, delayMs * 2)) {
1041
1091
  const socket = await tryConnect(this.paths.socket);
1042
1092
  if (socket) {
1043
1093
  this.releaseSpawnLock();
1044
1094
  return Result.ok(socket);
1045
1095
  }
1046
- await sleep(25);
1096
+ await sleep(delayMs);
1047
1097
  }
1048
1098
  this.releaseSpawnLock();
1049
1099
  const cause = this.spawnFailure ? ` (${this.spawnFailure})` : "";
@@ -1112,13 +1162,13 @@ class SqlegoClient {
1112
1162
  const json = text.ok ? fromJson(text.value) : text;
1113
1163
  const meta = json.ok ? parseServerMeta(json.value) : json;
1114
1164
  if (meta.ok) {
1115
- if (meta.value.serverVersion !== VERSION || !isProcessAlive(meta.value.pid))
1165
+ if (meta.value.serverVersion !== VERSION)
1116
1166
  continue;
1117
1167
  const known = byPid.get(meta.value.pid);
1118
1168
  if (known) {
1119
1169
  known.files += 1;
1120
1170
  known.startedAt = Math.min(known.startedAt, meta.value.startedAt);
1121
- } else {
1171
+ } else if (isProcessAlive(meta.value.pid)) {
1122
1172
  byPid.set(meta.value.pid, { pid: meta.value.pid, socket: meta.value.socket, files: 1, startedAt: meta.value.startedAt });
1123
1173
  }
1124
1174
  } else if (meta.error.kind === "invalid") {}
@@ -1135,12 +1185,12 @@ class SqlegoClient {
1135
1185
  this.spawnFailure = `spawn lock not released: ${released.error.message}`;
1136
1186
  }
1137
1187
  async waitForRelease(deadline) {
1138
- while (Date.now() < deadline) {
1188
+ for (let delayMs = 2;Date.now() < deadline; delayMs = Math.min(25, delayMs * 2)) {
1139
1189
  const socket = await tryConnect(this.paths.socket);
1140
1190
  if (!socket)
1141
1191
  return;
1142
1192
  socket.destroy();
1143
- await sleep(25);
1193
+ await sleep(delayMs);
1144
1194
  }
1145
1195
  }
1146
1196
  spawnServer() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noego/sqlego",
3
- "version": "0.1.3",
3
+ "version": "0.1.4-dev.1",
4
4
  "description": "One owner per SQLite file, many files per owner process. Clients (CLI, Node, Bun) pass SQL over a local socket (Unix) or named pipe (Windows); the owner starts on demand and exits when idle.",
5
5
  "type": "module",
6
6
  "license": "ISC",
@@ -48,13 +48,13 @@
48
48
  "typescript": "^5.6.0"
49
49
  },
50
50
  "dependencies": {
51
- "@noego/trust": "^0.5.0"
51
+ "@noego/trust": "^0.5.1"
52
52
  },
53
53
  "optionalDependencies": {
54
- "@noego/sqlego-darwin-arm64": "0.1.3",
55
- "@noego/sqlego-darwin-x64": "0.1.3",
56
- "@noego/sqlego-linux-x64": "0.1.3",
57
- "@noego/sqlego-linux-arm64": "0.1.3",
58
- "@noego/sqlego-win32-x64": "0.1.3"
54
+ "@noego/sqlego-darwin-arm64": "0.1.4-dev.1",
55
+ "@noego/sqlego-darwin-x64": "0.1.4-dev.1",
56
+ "@noego/sqlego-linux-x64": "0.1.4-dev.1",
57
+ "@noego/sqlego-linux-arm64": "0.1.4-dev.1",
58
+ "@noego/sqlego-win32-x64": "0.1.4-dev.1"
59
59
  }
60
60
  }
package/src/client.ts CHANGED
@@ -194,6 +194,9 @@ export class SqlegoClient {
194
194
  private socket: net.Socket | null = null;
195
195
  /** Reply frames from `socket`; the socket decodes UTF-8 itself (`setEncoding`), split characters included. */
196
196
  private readonly frames = new FrameReader();
197
+ /** Request frames queued in this microtask turn, joined and written once before the turn ends. */
198
+ private readonly outbound: string[] = [];
199
+ private flushScheduled = false;
197
200
  private nextId = 1;
198
201
  private readonly pending = new Map<number, Waiter>();
199
202
  private hello: HelloResult | null = null;
@@ -520,13 +523,13 @@ export class SqlegoClient {
520
523
  }
521
524
  }
522
525
  // Claimer or not, the socket appears when the winner is listening.
523
- while (Date.now() < deadline) {
526
+ for (let delayMs = 2; Date.now() < deadline; delayMs = Math.min(25, delayMs * 2)) {
524
527
  const socket = await tryConnect(this.paths.socket);
525
528
  if (socket) {
526
529
  this.releaseSpawnLock();
527
530
  return Result.ok(socket);
528
531
  }
529
- await sleep(25);
532
+ await sleep(delayMs);
530
533
  }
531
534
  this.releaseSpawnLock();
532
535
  const cause = this.spawnFailure ? ` (${this.spawnFailure})` : '';
@@ -618,12 +621,12 @@ export class SqlegoClient {
618
621
  const json = text.ok ? fromJson(text.value) : text;
619
622
  const meta = json.ok ? parseServerMeta(json.value) : json;
620
623
  if (meta.ok) {
621
- if (meta.value.serverVersion !== VERSION || !isProcessAlive(meta.value.pid)) continue;
624
+ if (meta.value.serverVersion !== VERSION) continue;
622
625
  const known = byPid.get(meta.value.pid);
623
626
  if (known) {
624
627
  known.files += 1;
625
628
  known.startedAt = Math.min(known.startedAt, meta.value.startedAt);
626
- } else {
629
+ } else if (isProcessAlive(meta.value.pid)) {
627
630
  byPid.set(meta.value.pid, { pid: meta.value.pid, socket: meta.value.socket, files: 1, startedAt: meta.value.startedAt });
628
631
  }
629
632
  } else if (meta.error.kind === 'invalid') {
@@ -647,11 +650,11 @@ export class SqlegoClient {
647
650
 
648
651
  /** Waits until nothing answers on the file's socket (the old owner released it, its database closed first), or the deadline. */
649
652
  private async waitForRelease(deadline: number): Promise<void> {
650
- while (Date.now() < deadline) {
653
+ for (let delayMs = 2; Date.now() < deadline; delayMs = Math.min(25, delayMs * 2)) {
651
654
  const socket = await tryConnect(this.paths.socket);
652
655
  if (!socket) return;
653
656
  socket.destroy();
654
- await sleep(25);
657
+ await sleep(delayMs);
655
658
  }
656
659
  }
657
660
 
package/src/paths.ts CHANGED
@@ -83,8 +83,9 @@ export function resolvePaths(file: string) {
83
83
  // `\\.\pipe\sqlego-<dir hash>-<key>` — the pipe namespace is flat and
84
84
  // shared machine-wide, so the runtime directory (per user, or per test)
85
85
  // is hashed into the name to keep the isolation the directory gives on Unix.
86
- const scope = createHash('sha1').update(directory.value.toLowerCase()).digest('hex').slice(0, 8);
87
- const socket = USES_NAMED_PIPES ? `\\\\.\\pipe\\sqlego-${scope}-${key}` : path.join(directory.value, `${key}.sock`);
86
+ const socket = USES_NAMED_PIPES
87
+ ? `\\\\.\\pipe\\sqlego-${createHash('sha1').update(directory.value.toLowerCase()).digest('hex').slice(0, 8)}-${key}`
88
+ : path.join(directory.value, `${key}.sock`);
88
89
  return { key, socket, socketBytes: Buffer.byteLength(socket) };
89
90
  },
90
91
  (cause) => ({ kind: 'hash-failed', message: `cannot hash ${canonical.value}: ${errorMessage(cause)}` }),
package/src/protocol.ts CHANGED
@@ -172,10 +172,16 @@ export type Response =
172
172
  * or a `toJSON` that throws; both are this one failure.
173
173
  */
174
174
  export function toJson(value: unknown, indent?: number) {
175
- const encoded = Trust.try(
176
- (): unknown => JSON.stringify(value, replaceBigInt, indent),
175
+ const fast = Trust.try(
176
+ (): unknown => (indent === undefined ? JSON.stringify(value) : JSON.stringify(value, undefined, indent)),
177
177
  (cause) => ({ kind: 'encode-failed' as const, message: errorMessage(cause) }),
178
178
  );
179
+ const encoded = fast.ok
180
+ ? fast
181
+ : Trust.try(
182
+ (): unknown => JSON.stringify(value, replaceBigInt, indent),
183
+ (cause) => ({ kind: 'encode-failed' as const, message: errorMessage(cause) }),
184
+ );
179
185
  if (!encoded.ok) return encoded;
180
186
  if (typeof encoded.value !== 'string') return Result.err({ kind: 'encode-failed', message: `${typeof value} has no JSON form` });
181
187
  return Result.ok(encoded.value);
@@ -210,20 +216,28 @@ function encodeRequestParams(request: Request) {
210
216
  if (request.params === undefined) return Result.ok<unknown>(request);
211
217
  const params = encodeSqlParams(request.params);
212
218
  if (!params.ok) return params;
219
+ if (params.value === request.params) return Result.ok<unknown>(request);
213
220
  return Result.ok<unknown>({ ...request, params: params.value });
214
221
  }
215
222
  case 'batch': {
216
- const statements: unknown[] = [];
217
- for (const [index, statement] of request.statements.entries()) {
223
+ let changed = false;
224
+ const statements: unknown[] = new Array(request.statements.length);
225
+ for (let index = 0; index < request.statements.length; index += 1) {
226
+ const statement = request.statements[index];
218
227
  if (statement.params === undefined) {
219
- statements.push(statement);
228
+ statements[index] = statement;
220
229
  continue;
221
230
  }
222
231
  const params = encodeSqlParams(statement.params);
223
232
  if (!params.ok) return invalid(`statements[${index}].${params.error.message}`);
224
- statements.push({ ...statement, params: params.value });
233
+ if (params.value === statement.params) {
234
+ statements[index] = statement;
235
+ } else {
236
+ changed = true;
237
+ statements[index] = { ...statement, params: params.value };
238
+ }
225
239
  }
226
- return Result.ok<unknown>({ ...request, statements });
240
+ return Result.ok<unknown>(changed ? { ...request, statements } : request);
227
241
  }
228
242
  default:
229
243
  return Result.ok<unknown>(request);
@@ -235,21 +249,46 @@ export function encodeSqlParams(params: SqlParams) {
235
249
  if (typeof params !== 'object' || params === null) return invalid('params must be an array or an object');
236
250
  const shape = paramsShape(params);
237
251
  if (shape.kind === 'positional') {
238
- const values: unknown[] = [];
239
- for (const [index, item] of shape.values.entries()) {
252
+ const items = shape.values;
253
+ let values: unknown[] | null = null;
254
+ for (let index = 0; index < items.length; index += 1) {
255
+ const item = items[index];
256
+ if (item === null || typeof item === 'string' || typeof item === 'boolean' || (typeof item === 'number' && Number.isFinite(item))) {
257
+ if (values !== null) values[index] = item;
258
+ continue;
259
+ }
240
260
  const value = encodeParamValue(item);
241
261
  if (!value.ok) return invalid(`params[${index}]: ${value.error.message}`);
242
- values.push(value.value);
262
+ if (values === null) {
263
+ values = new Array(items.length);
264
+ for (let prev = 0; prev < index; prev += 1) values[prev] = items[prev];
265
+ }
266
+ values[index] = value.value;
243
267
  }
244
- return Result.ok<WireParams>(values);
268
+ return Result.ok<WireParams>(values ?? items);
245
269
  }
246
- const entries: Array<[string, unknown]> = [];
247
- for (const [name, item] of Object.entries(shape.values)) {
270
+ const fields = shape.values;
271
+ const keys = Object.keys(fields);
272
+ let entries: Array<[string, unknown]> | null = null;
273
+ for (let index = 0; index < keys.length; index += 1) {
274
+ const name = keys[index];
275
+ const item = fields[name];
276
+ if (item === null || typeof item === 'string' || typeof item === 'boolean' || (typeof item === 'number' && Number.isFinite(item))) {
277
+ if (entries !== null) entries.push([name, item]);
278
+ continue;
279
+ }
248
280
  const value = encodeParamValue(item);
249
281
  if (!value.ok) return invalid(`params.${name}: ${value.error.message}`);
282
+ if (entries === null) {
283
+ entries = [];
284
+ for (let prev = 0; prev < index; prev += 1) {
285
+ const prevKey = keys[prev];
286
+ entries.push([prevKey, fields[prevKey]]);
287
+ }
288
+ }
250
289
  entries.push([name, value.value]);
251
290
  }
252
- return Result.ok<WireParams>(Object.fromEntries(entries));
291
+ return Result.ok<WireParams>(entries === null ? fields : Object.fromEntries(entries));
253
292
  }
254
293
 
255
294
  /**
@@ -314,20 +353,31 @@ export function encodeResultValue(value: unknown) {
314
353
  }
315
354
 
316
355
  /** Rows as SQLite returned them (`unknown`), in wire form. */
356
+ //trust:validator_function
317
357
  export function encodeResultRows(input: unknown) {
318
358
  if (!Array.isArray(input)) return invalid('rows must be an array');
319
- const rows: WireRow[] = [];
320
- for (const [index, item] of input.entries()) {
359
+ const rows: WireRow[] = new Array(input.length);
360
+ for (let index = 0; index < input.length; index += 1) {
361
+ const item: unknown = input[index];
321
362
  const fields = fieldsOf(item);
322
363
  if (!fields) return invalid(`rows[${index}] must be an object`);
323
- const entries: Array<[string, WireValue]> = [];
324
- for (const [column, raw] of Object.entries(fields)) {
364
+ const record = item as Record<string, WireValue>;
365
+ for (const column in fields) {
366
+ const raw = fields[column];
367
+ if (raw === null || typeof raw === 'string' || typeof raw === 'boolean') continue;
368
+ if (typeof raw === 'number') {
369
+ if (!Number.isFinite(raw)) return invalid(`rows[${index}].${column}: the REAL ${raw} has no JSON form`);
370
+ continue;
371
+ }
372
+ if (typeof raw === 'bigint') {
373
+ record[column] = encodeWireInteger(raw);
374
+ continue;
375
+ }
325
376
  const value = encodeResultValue(raw);
326
377
  if (!value.ok) return invalid(`rows[${index}].${column}: ${value.error.message}`);
327
- entries.push([column, value.value]);
378
+ record[column] = value.value;
328
379
  }
329
- const row: WireRow = Object.fromEntries(entries);
330
- rows.push(row);
380
+ rows[index] = record;
331
381
  }
332
382
  return Result.ok(rows);
333
383
  }
@@ -398,17 +448,36 @@ function parseWireBigInt(input: unknown) {
398
448
  /** Canonical padded base64; the empty string is a zero-length blob. */
399
449
  //trust:validator_function
400
450
  function parseWireBlob(input: unknown) {
401
- if (typeof input !== 'string' || !BASE64.test(input)) return invalid('$blob must be canonical padded base64');
451
+ if (typeof input !== 'string' || !BASE64.test(input) || !hasCanonicalBase64Padding(input)) {
452
+ return invalid('$blob must be canonical padded base64');
453
+ }
402
454
  const decoded = Trust.try(
403
- () => {
404
- const bytes = Buffer.from(input, 'base64');
405
- return { bytes: new Uint8Array(bytes), canonical: bytes.toString('base64') };
406
- },
455
+ () => new Uint8Array(Buffer.from(input, 'base64')),
407
456
  (cause) => ({ kind: 'invalid' as const, message: `$blob: ${errorMessage(cause)}` }),
408
457
  );
409
458
  if (!decoded.ok) return decoded;
410
- if (decoded.value.canonical !== input) return invalid('$blob must be canonical padded base64');
411
- return Result.ok<SqlValue>(decoded.value.bytes);
459
+ return Result.ok<SqlValue>(decoded.value);
460
+ }
461
+
462
+ /**
463
+ * A string matching `BASE64` is canonical unless its padding (`=` or `==`)
464
+ * leaves non-zero unused low bits in the character before `=`.
465
+ */
466
+ function hasCanonicalBase64Padding(input: string): boolean {
467
+ const length = input.length;
468
+ if (length === 0 || input.charCodeAt(length - 1) !== 0x3d) return true;
469
+ if (input.charCodeAt(length - 2) === 0x3d) {
470
+ // 2 padding chars (`==`): 4-bit unused tail of char at length - 3 must be 0 (A, Q, g, w).
471
+ const c = input.charCodeAt(length - 3);
472
+ return c === 0x41 || c === 0x51 || c === 0x67 || c === 0x77;
473
+ }
474
+ // 1 padding char (`=`): 2-bit unused tail of char at length - 2 must be 0 (sextet % 4 === 0).
475
+ const c = input.charCodeAt(length - 2);
476
+ const sextet = c >= 0x41 && c <= 0x5a ? c - 0x41
477
+ : c >= 0x61 && c <= 0x7a ? c - 0x61 + 26
478
+ : c >= 0x30 && c <= 0x39 ? c - 0x30 + 52
479
+ : c === 0x2b ? 62 : 63;
480
+ return (sextet & 3) === 0;
412
481
  }
413
482
 
414
483
  /** An integer result: a JSON number or a `$bigint` tag. */
@@ -426,23 +495,26 @@ function parseWireInteger(input: unknown, at: string) {
426
495
  //trust:validator_function
427
496
  export function parseSqlParams(input: unknown) {
428
497
  if (Array.isArray(input)) {
429
- const values: SqlValue[] = [];
430
- for (const [index, item] of input.entries()) {
498
+ for (let index = 0; index < input.length; index += 1) {
499
+ const item: unknown = input[index];
500
+ if (item === null || typeof item === 'string' || typeof item === 'boolean' || (typeof item === 'number' && Number.isFinite(item))) continue;
431
501
  const value = parseSqlValue(item);
432
502
  if (!value.ok) return invalid(`params[${index}]: ${value.error.message}`);
433
- values.push(value.value);
503
+ input[index] = value.value;
434
504
  }
435
- return Result.ok<SqlParams>(values);
505
+ return Result.ok<SqlParams>(input as SqlValue[]);
436
506
  }
437
507
  const fields = fieldsOf(input);
438
508
  if (!fields) return invalid('params must be an array or an object');
439
- const entries: Array<[string, SqlValue]> = [];
440
- for (const [name, item] of Object.entries(fields)) {
509
+ const record = input as Record<string, SqlValue>;
510
+ for (const name in fields) {
511
+ const item = fields[name];
512
+ if (item === null || typeof item === 'string' || typeof item === 'boolean' || (typeof item === 'number' && Number.isFinite(item))) continue;
441
513
  const value = parseSqlValue(item);
442
514
  if (!value.ok) return invalid(`params.${name}: ${value.error.message}`);
443
- entries.push([name, value.value]);
515
+ record[name] = value.value;
444
516
  }
445
- return Result.ok<SqlParams>(Object.fromEntries(entries));
517
+ return Result.ok<SqlParams>(record);
446
518
  }
447
519
 
448
520
  /** `params` when present; absent (`undefined`) is allowed. */
@@ -586,18 +658,28 @@ export function parseResponse(input: unknown) {
586
658
  export function parseRow(input: unknown) {
587
659
  const fields = fieldsOf(input);
588
660
  if (!fields) return invalid('a row must be an object');
589
- const row: SqlRow = { ...fields };
661
+ const row = input as SqlRow;
662
+ for (const column in fields) {
663
+ const raw = fields[column];
664
+ if (typeof raw === 'bigint') row[column] = Number(raw);
665
+ }
590
666
  return Result.ok(row);
591
667
  }
592
668
 
593
669
  //trust:validator_function
594
670
  export function parseRows(input: unknown) {
595
671
  if (!Array.isArray(input)) return invalid('rows must be an array');
596
- const rows: SqlRow[] = [];
597
- for (const [index, item] of input.entries()) {
598
- const row = parseRow(item);
599
- if (!row.ok) return invalid(`rows[${index}]: ${row.error.message}`);
600
- rows.push(row.value);
672
+ const rows: SqlRow[] = new Array(input.length);
673
+ for (let index = 0; index < input.length; index += 1) {
674
+ const item: unknown = input[index];
675
+ const fields = fieldsOf(item);
676
+ if (!fields) return invalid(`rows[${index}]: a row must be an object`);
677
+ const row = item as SqlRow;
678
+ for (const column in fields) {
679
+ const raw = fields[column];
680
+ if (typeof raw === 'bigint') row[column] = Number(raw);
681
+ }
682
+ rows[index] = row;
601
683
  }
602
684
  return Result.ok(rows);
603
685
  }
@@ -641,19 +723,20 @@ export function parseBatchResult(input: unknown) {
641
723
  //trust:validator_function
642
724
  function parseWireRows(input: unknown) {
643
725
  if (!Array.isArray(input)) return invalid('rows must be an array');
644
- const rows: SqlRow[] = [];
645
- for (const [index, item] of input.entries()) {
726
+ const rows: SqlRow[] = new Array(input.length);
727
+ for (let index = 0; index < input.length; index += 1) {
728
+ const item: unknown = input[index];
646
729
  const fields = fieldsOf(item);
647
730
  if (!fields) return invalid(`rows[${index}] must be an object`);
648
- const entries: Array<[string, SqlValue]> = [];
649
- for (const [column, raw] of Object.entries(fields)) {
731
+ const record = item as SqlRow;
732
+ for (const column in fields) {
733
+ const raw = fields[column];
734
+ if (raw === null || typeof raw === 'string' || typeof raw === 'boolean' || (typeof raw === 'number' && Number.isFinite(raw))) continue;
650
735
  const value = parseSqlValue(raw);
651
736
  if (!value.ok) return invalid(`rows[${index}].${column}: ${value.error.message}`);
652
- entries.push([column, value.value]);
737
+ record[column] = value.value;
653
738
  }
654
- // fromEntries defines own properties, so a column named __proto__ stays a column.
655
- const row: SqlRow = Object.fromEntries(entries);
656
- rows.push(row);
739
+ rows[index] = record;
657
740
  }
658
741
  return Result.ok(rows);
659
742
  }
package/src/server.ts CHANGED
@@ -203,12 +203,32 @@ class StatementCache {
203
203
 
204
204
  /**
205
205
  * `frames` reads the request frames of this socket from its raw bytes (see
206
- * `FrameReader.pushBytes`). `outbound` holds bytes the kernel buffer refused
207
- * (null when there are none). Bun's `socket.write` returns the byte count it
208
- * accepted and drops the rest, so a large result followed by another frame
209
- * corrupts the stream unless the remainder is carried and flushed on `drain`.
206
+ * `FrameReader.pushBytes`). `outbound` holds, in order, the bytes the kernel
207
+ * buffer refused (empty when there are none). Bun's `socket.write` returns
208
+ * the byte count it accepted and drops the rest, so a large result followed
209
+ * by another frame corrupts the stream unless the remainder is carried and
210
+ * flushed on `drain`. It is a list, not one Buffer grown by concatenation:
211
+ * a client that stopped reading while thousands of replies went out (a
212
+ * mass `tx-busy` expiry) made every reply re-copy the whole backlog, and
213
+ * the owner stalled for seconds.
210
214
  */
211
- type Connection = { id: number; frames: FrameReader; outbound: Buffer | null; socket: ServerSocket; detachedPlain: boolean };
215
+ type Connection = {
216
+ id: number;
217
+ frames: FrameReader;
218
+ outbound: Buffer[];
219
+ /**
220
+ * Reply frames not yet handed to the socket. Replies produced in one turn
221
+ * (every request of a pipelined burst, a drained queue) are joined and
222
+ * written once, from a microtask, instead of one write per reply.
223
+ */
224
+ pending: string[];
225
+ flushScheduled: boolean;
226
+ socket: ServerSocket;
227
+ detachedPlain: boolean;
228
+ };
229
+
230
+ /** At most this many bytes of a connection's backlog are joined into one write. */
231
+ const FLUSH_JOIN_BYTES = 64 * 1024;
212
232
 
213
233
  /** Each socket carries its connection in Bun's typed `data` slot: null until `open` assigns it. */
214
234
  type ServerSocket = import('bun').Socket<Connection | null>;
@@ -225,7 +245,13 @@ type OpenTransaction = {
225
245
  };
226
246
 
227
247
  /** A request from another client, held until the open transaction ends (or its wait runs out). */
228
- type QueuedRequest = { connection: Connection; request: Request; timer: ReturnType<typeof setTimeout> };
248
+ type QueuedRequest = {
249
+ connection: Connection;
250
+ request: Request;
251
+ timer: ReturnType<typeof setTimeout>;
252
+ /** Served, expired, or abandoned by its client: then only waiting to be skipped by the drain. */
253
+ settled: boolean;
254
+ };
229
255
 
230
256
  /** How a transaction ended, kept so a late request for it gets a precise answer. */
231
257
  type EndedTransaction = { code: 'tx-expired' | 'tx-invalid'; message: string };
@@ -299,7 +325,17 @@ export class SqlegoServer {
299
325
  private requestsServed = 0;
300
326
  private stopping = false;
301
327
  private transaction: OpenTransaction | null = null;
302
- private readonly queue: QueuedRequest[] = [];
328
+ /**
329
+ * Held requests in arrival order, settled ones included until the drain
330
+ * reaches them: an expiry or a client leaving settles its entries in
331
+ * place, so neither searches nor splices the queue (with tens of thousands
332
+ * waiting, mass expiry was quadratic and froze the owner for seconds).
333
+ * `waiting` counts the unsettled ones.
334
+ */
335
+ private queue: QueuedRequest[] = [];
336
+ private waiting = 0;
337
+ /** Whether `drainQueue` is running, so the drain `serve` asks for inside it is left to the running loop. */
338
+ private draining = false;
303
339
  private readonly ended = new Map<number, EndedTransaction>();
304
340
  private readonly log: NonNullable<ServerOptions['log']>;
305
341
 
@@ -433,8 +469,16 @@ export class SqlegoServer {
433
469
  if (this.idleTimer) clearTimeout(this.idleTimer);
434
470
  if (this.fileCheckTimer) clearTimeout(this.fileCheckTimer);
435
471
  if (this.transaction) this.endTransaction('server stopping', 'tx-expired', true);
436
- for (const queued of this.queue.splice(0)) clearTimeout(queued.timer);
472
+ for (const queued of this.queue) clearTimeout(queued.timer);
473
+ this.queue = [];
474
+ this.waiting = 0;
437
475
  for (const connection of this.connections.values()) {
476
+ // Replies still waiting for their microtask (the reply to this `stop`
477
+ // among them) go out before the socket ends, as they did when every
478
+ // reply was written at once.
479
+ const queued = this.flushPending(connection);
480
+ const flushed = queued.ok ? this.flush(connection) : queued;
481
+ if (!flushed.ok && flushed.error.kind === 'write-failed') this.log('flush before stop failed', { connection: connection.id, error: flushed.error.message });
438
482
  this.reportCleanup('end connection', Trust.try(() => connection.socket.end(), cleanupFailure));
439
483
  }
440
484
  this.closeConnections();
@@ -516,7 +560,7 @@ export class SqlegoServer {
516
560
  idleMs: now - open.lastRequestAt,
517
561
  leaseMs: open.leaseMs,
518
562
  maxDurationMs: this.txMaxDurationMs(),
519
- queued: this.queue.length,
563
+ queued: this.waiting,
520
564
  };
521
565
  }
522
566
 
@@ -543,7 +587,7 @@ export class SqlegoServer {
543
587
  return;
544
588
  }
545
589
  const id = this.nextConnectionId++;
546
- const connection: Connection = { id, frames: new FrameReader(), outbound: null, socket, detachedPlain: false };
590
+ const connection: Connection = { id, frames: new FrameReader(), outbound: [], pending: [], flushScheduled: false, socket, detachedPlain: false };
547
591
  this.connections.set(id, connection);
548
592
  socket.data = connection;
549
593
  this.disarmIdleTimer();
@@ -554,8 +598,10 @@ export class SqlegoServer {
554
598
  if (!connection) return;
555
599
  this.connections.delete(connection.id);
556
600
  // A waiting request from a client that left has nobody to answer.
557
- for (let index = this.queue.length - 1; index >= 0; index -= 1) {
558
- if (this.queue[index].connection === connection) clearTimeout(this.queue.splice(index, 1)[0].timer);
601
+ if (this.waiting > 0) {
602
+ for (const queued of this.queue) {
603
+ if (queued.connection === connection) this.settleQueued(queued);
604
+ }
559
605
  }
560
606
  if (this.transaction && this.transaction.connection === connection) {
561
607
  this.endTransaction(`client ${connection.id} disconnected`, 'tx-expired', true);
@@ -593,8 +639,11 @@ export class SqlegoServer {
593
639
  }
594
640
  }
595
641
  if (this.mustWait(connection, request)) {
596
- const timer = setTimeout(() => this.expireQueued(connection, request), this.txQueueTimeoutMs());
597
- this.queue.push({ connection, request, timer });
642
+ const queued: QueuedRequest = {
643
+ connection, request, settled: false, timer: setTimeout(() => this.expireQueued(queued), this.txQueueTimeoutMs()),
644
+ };
645
+ this.queue.push(queued);
646
+ this.waiting += 1;
598
647
  return;
599
648
  }
600
649
  this.serve(connection, request);
@@ -633,16 +682,13 @@ export class SqlegoServer {
633
682
  if (!connection.detachedPlain) return false;
634
683
  if (request.op !== 'query' && request.op !== 'run' && request.op !== 'statement') return false;
635
684
  if (request.txId !== undefined) return false;
636
- const pieces = splitSqlStatements(request.sql);
637
- if (pieces.length !== 1) return false;
638
- const body = pieces[0].replace(/^(?:\s+|--[^\n]*\n?|\/\*[\s\S]*?\*\/)+/, '');
639
- return /^(SELECT|WITH|VALUES|EXPLAIN)\b/i.test(body);
685
+ return sqlShape(request.sql).detachedRead;
640
686
  }
641
687
 
642
- private expireQueued(connection: Connection, request: Request): void {
643
- const index = this.queue.findIndex((queued) => queued.request === request);
644
- if (index < 0) return;
645
- this.queue.splice(index, 1);
688
+ private expireQueued(queued: QueuedRequest): void {
689
+ if (queued.settled) return;
690
+ this.settleQueued(queued);
691
+ const { connection, request } = queued;
646
692
  const waited = this.txQueueTimeoutMs();
647
693
  this.reply(connection, {
648
694
  id: request.id, ok: false,
@@ -650,13 +696,42 @@ export class SqlegoServer {
650
696
  });
651
697
  }
652
698
 
653
- /** Serves held requests in arrival order until one of them opens a new transaction. */
699
+ /**
700
+ * Takes a held request out of the wait, in place. The settled entries are
701
+ * dropped from the array once none is waiting, or once they are most of a
702
+ * large one, so a queue that keeps expiring behind a long transaction stays
703
+ * bounded by what is actually waiting.
704
+ */
705
+ private settleQueued(queued: QueuedRequest): void {
706
+ if (queued.settled) return;
707
+ queued.settled = true;
708
+ clearTimeout(queued.timer);
709
+ this.waiting -= 1;
710
+ if (this.waiting === 0) this.queue = [];
711
+ else if (this.queue.length > 1_024 && this.waiting * 2 < this.queue.length) this.queue = this.queue.filter((entry) => !entry.settled);
712
+ }
713
+
714
+ /**
715
+ * Serves held requests in arrival order until one of them opens a new
716
+ * transaction. Not re-entrant: `serve` drains after every request, and
717
+ * when that nested drain served the next waiter itself, draining N waiters
718
+ * nested N calls deep — about 5 000 requests queued behind one transaction
719
+ * overflowed the stack, and every waiting client was dropped as
720
+ * "cannot encode response". A nested call returns and the outer loop goes on.
721
+ */
654
722
  private drainQueue(): void {
655
- while (this.queue.length > 0 && this.transaction === null && !this.stopping) {
656
- const next = this.queue.shift();
657
- if (!next) return;
658
- clearTimeout(next.timer);
659
- this.serve(next.connection, next.request);
723
+ if (this.draining) return;
724
+ this.draining = true;
725
+ try {
726
+ while (this.waiting > 0 && this.transaction === null && !this.stopping) {
727
+ const next = this.queue.shift();
728
+ if (!next) return;
729
+ if (next.settled) continue;
730
+ this.settleQueued(next);
731
+ this.serve(next.connection, next.request);
732
+ }
733
+ } finally {
734
+ this.draining = false;
660
735
  }
661
736
  }
662
737
 
@@ -781,7 +856,7 @@ export class SqlegoServer {
781
856
  * as `query`/`run`.
782
857
  */
783
858
  private unifiedStatement(connection: Connection, sql: string, params: SqlParams | undefined, txId: number | undefined, db = this.db) {
784
- const pieces = splitSqlStatements(sql);
859
+ const { pieces } = sqlShape(sql);
785
860
  if (pieces.length === 0) return badRequest('statement needs one SQL statement; the text has none');
786
861
  if (pieces.length > 1) return badRequest(`statement takes one SQL statement, the text has ${pieces.length}: use exec for several`);
787
862
  const piece = pieces[0];
@@ -795,8 +870,8 @@ export class SqlegoServer {
795
870
  * hidden after a harmless first statement is refused just like a leading one.
796
871
  */
797
872
  private exec(connection: Connection, sql: string, txId: number | undefined) {
798
- const pieces = splitSqlStatements(sql);
799
- return this.scoped(connection, 'exec', txId, pieces.map((piece) => transactionControl(piece)), () => this.runScript(pieces));
873
+ const { pieces, controls } = sqlShape(sql);
874
+ return this.scoped(connection, 'exec', txId, controls, () => this.runScript(pieces));
800
875
  }
801
876
 
802
877
  /**
@@ -858,9 +933,11 @@ export class SqlegoServer {
858
933
  () => {
859
934
  const outcome = params === undefined ? statement.run() : statement.run(...bindings(params));
860
935
  // safeIntegers may report either counter as bigint; `run` keeps answering with numbers.
936
+ // Converted here, as the encoder's bigint replacer used to on the wire (the same bytes),
937
+ // so the reply has no bigint left and is encoded without the replacer.
861
938
  const result: RunResult = db === this.reader
862
939
  ? { changes: 0, lastInsertRowid: 0 }
863
- : { changes: Number(outcome.changes), lastInsertRowid: outcome.lastInsertRowid };
940
+ : { changes: Number(outcome.changes), lastInsertRowid: Number(outcome.lastInsertRowid) };
864
941
  return result;
865
942
  },
866
943
  sqliteFailure,
@@ -1150,27 +1227,54 @@ export class SqlegoServer {
1150
1227
  if (frame.error.kind === 'encode-failed') this.dropConnection(connection, `cannot encode response ${response.id}: ${frame.error.message}`);
1151
1228
  return;
1152
1229
  }
1153
- const sent = this.send(connection, frame.value);
1154
- if (!sent.ok && sent.error.kind === 'write-failed') this.dropConnection(connection, sent.error.message);
1230
+ // Written from a microtask (see `send`); a write that fails there drops the connection.
1231
+ this.send(connection, frame.value);
1155
1232
  }
1156
1233
 
1157
1234
  private dropConnection(connection: Connection, why: string): void {
1158
1235
  this.log('dropping connection', { connection: connection.id, error: why });
1159
- connection.outbound = null;
1236
+ connection.outbound = [];
1237
+ connection.pending = [];
1160
1238
  this.reportCleanup('drop connection', Trust.try(() => connection.socket.end(), cleanupFailure));
1161
1239
  }
1162
1240
 
1163
- /** Queues behind any unflushed bytes so frames never interleave. */
1164
- private send(connection: Connection, frame: string) {
1165
- const queued = Trust.try(
1241
+ /**
1242
+ * Queues one frame behind every frame before it, so frames never
1243
+ * interleave, and schedules one write for everything queued this turn.
1244
+ */
1245
+ private send(connection: Connection, frame: string): void {
1246
+ connection.pending.push(frame);
1247
+ if (connection.flushScheduled) return;
1248
+ connection.flushScheduled = true;
1249
+ queueMicrotask(() => {
1250
+ const flushed = this.flushPending(connection);
1251
+ if (!flushed.ok && flushed.error.kind === 'write-failed') this.dropConnection(connection, flushed.error.message);
1252
+ });
1253
+ }
1254
+
1255
+ /**
1256
+ * Hands the queued frames to the socket: behind unflushed bytes when there
1257
+ * are any (they wait for `drain`, which a refused write always brings),
1258
+ * else as one string write, keeping only what the kernel refused.
1259
+ */
1260
+ private flushPending(connection: Connection) {
1261
+ connection.flushScheduled = false;
1262
+ if (connection.pending.length === 0) return Result.ok(undefined);
1263
+ const text = connection.pending.length === 1 ? connection.pending[0] : connection.pending.join('');
1264
+ connection.pending = [];
1265
+ if (!this.connections.has(connection.id)) return Result.ok(undefined);
1266
+ return Trust.try(
1166
1267
  () => {
1167
- const bytes = Buffer.from(frame, 'utf8');
1168
- connection.outbound = connection.outbound === null ? bytes : Buffer.concat([connection.outbound, bytes]);
1268
+ if (connection.outbound.length > 0) {
1269
+ connection.outbound.push(Buffer.from(text, 'utf8'));
1270
+ return;
1271
+ }
1272
+ const written = connection.socket.write(text);
1273
+ const length = Buffer.byteLength(text, 'utf8');
1274
+ if (written < length) connection.outbound.push(Buffer.from(text, 'utf8').subarray(Math.max(written, 0)));
1169
1275
  },
1170
1276
  writeFailure,
1171
1277
  );
1172
- if (!queued.ok) return queued;
1173
- return this.flush(connection);
1174
1278
  }
1175
1279
 
1176
1280
  private onDrain(socket: ServerSocket): void {
@@ -1180,13 +1284,27 @@ export class SqlegoServer {
1180
1284
  if (!flushed.ok && flushed.error.kind === 'write-failed') this.dropConnection(connection, flushed.error.message);
1181
1285
  }
1182
1286
 
1287
+ /**
1288
+ * Writes the unflushed bytes in order until the kernel refuses some. Small
1289
+ * chunks are joined up to `FLUSH_JOIN_BYTES` per write, so each byte is
1290
+ * copied a bounded number of times however long the backlog grew.
1291
+ */
1183
1292
  private flush(connection: Connection) {
1184
1293
  return Trust.try(
1185
1294
  () => {
1186
- const pending = connection.outbound;
1187
- if (pending === null) return;
1188
- const written = connection.socket.write(pending);
1189
- connection.outbound = written >= pending.length ? null : pending.subarray(Math.max(written, 0));
1295
+ const chunks = connection.outbound;
1296
+ while (chunks.length > 0) {
1297
+ let take = 1;
1298
+ let size = chunks[0].length;
1299
+ while (take < chunks.length && size + chunks[take].length <= FLUSH_JOIN_BYTES) size += chunks[take++].length;
1300
+ const bytes = take === 1 ? chunks[0] : Buffer.concat(chunks.slice(0, take), size);
1301
+ const written = Math.max(connection.socket.write(bytes), 0);
1302
+ chunks.splice(0, take);
1303
+ if (written < bytes.length) {
1304
+ chunks.unshift(bytes.subarray(written));
1305
+ return;
1306
+ }
1307
+ }
1190
1308
  },
1191
1309
  writeFailure,
1192
1310
  );
@@ -1296,6 +1414,39 @@ export class SqlegoServer {
1296
1414
  }
1297
1415
  }
1298
1416
 
1417
+ /** How the owner classifies one SQL text: its statements, the transaction control each starts with, and whether it may run detached. */
1418
+ type SqlShape = Readonly<{ pieces: readonly string[]; controls: readonly TxControl[]; detachedRead: boolean }>;
1419
+
1420
+ /** Distinct SQL texts whose shape is remembered; past this, the oldest is forgotten. */
1421
+ const SQL_SHAPE_CACHE_SIZE = 512;
1422
+ /** Longer texts (migrations, scripts) are classified each time and never held. */
1423
+ const SQL_SHAPE_MAX_LENGTH = 4_096;
1424
+ const sqlShapes = new Map<string, SqlShape>();
1425
+
1426
+ /**
1427
+ * The shape of `sql`. It depends only on the text, and applications send the
1428
+ * same few statements over and over, so short texts are classified once and
1429
+ * reused: splitting them was most of the owner's own work per point read.
1430
+ */
1431
+ function sqlShape(sql: string): SqlShape {
1432
+ const cached = sqlShapes.get(sql);
1433
+ if (cached !== undefined) return cached;
1434
+ const pieces = splitSqlStatements(sql);
1435
+ const shape: SqlShape = {
1436
+ pieces,
1437
+ controls: pieces.map((piece) => transactionControl(piece)),
1438
+ detachedRead: pieces.length === 1 && /^(SELECT|WITH|VALUES|EXPLAIN)\b/i.test(pieces[0].replace(/^(?:\s+|--[^\n]*\n?|\/\*[\s\S]*?\*\/)+/, '')),
1439
+ };
1440
+ if (sql.length <= SQL_SHAPE_MAX_LENGTH) {
1441
+ if (sqlShapes.size >= SQL_SHAPE_CACHE_SIZE) {
1442
+ const oldest = sqlShapes.keys().next();
1443
+ if (!oldest.done) sqlShapes.delete(oldest.value);
1444
+ }
1445
+ sqlShapes.set(sql, shape);
1446
+ }
1447
+ return shape;
1448
+ }
1449
+
1299
1450
  /**
1300
1451
  * Refuses transaction-control statements: all of them outside a transaction
1301
1452
  * (a stray `BEGIN` or `SAVEPOINT` would wrap every client's later statements),