@noego/sqlego 0.1.6-dev.1 → 0.1.6-dev.11

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/src/lease.ts ADDED
@@ -0,0 +1,265 @@
1
+ /**
2
+ * Leases: the runtime directory's mutual exclusion between processes — a
3
+ * file's claim (who places it with an owner, then which owner serves it) and
4
+ * the spawn reservation (who is starting an owner process).
5
+ *
6
+ * A lease at `base` is a chain of generation files `<base>.<g>` (g = 1, 2,
7
+ * …), each created once and never rewritten. The highest generation is the
8
+ * lease's state: `{"holder":<pid>,"token":…}` (held while that process
9
+ * lives) or `{"free":true,"token":…}`. Every change — taking a free lease,
10
+ * reclaiming one whose holder died, handing one to another process,
11
+ * releasing it — creates generation g+1 by `link()`ing a fully written file
12
+ * into place, which fails if g+1 exists. So of all the processes acting on
13
+ * generation g exactly one succeeds: a reclaimer and a handover can never
14
+ * both win, and a release by a process the lease has since moved on from
15
+ * does nothing rather than removing its successor's lease. A generation is
16
+ * never read half-written.
17
+ *
18
+ * Each generation carries a token no other generation shares, and a change
19
+ * names the token of the generation it acts on, checked before and after the
20
+ * link. Generation numbers alone are not enough: if the newest generation
21
+ * file is lost (a temp-directory cleaner, say) the chain starts again at 1,
22
+ * and a process still holding an old generation would otherwise act on the
23
+ * new chain's generation of the same number.
24
+ *
25
+ * Older generations are pruned; the newest never is. An actor that recreates
26
+ * a pruned generation finds a newer one after its link and counts as having
27
+ * lost.
28
+ */
29
+ import { linkSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
30
+ import path from 'node:path';
31
+ import { Result, Trust } from '@noego/trust';
32
+ import { isProcessAlive } from './paths.ts';
33
+ import { errnoCode, errorMessage, fromJson } from './protocol.ts';
34
+
35
+ /** A lease this process holds: generation `generation` (whose token is `token`) of the lease at `base`. */
36
+ export type Lease = Readonly<{ base: string; generation: number; token: string }>;
37
+
38
+ type LeaseFailure = { readonly kind: 'lease-failed'; readonly message: string };
39
+
40
+ const leaseFailure = (cause: unknown): LeaseFailure => ({ kind: 'lease-failed', message: errorMessage(cause) });
41
+
42
+ /** How many times `acquireLease` retries after losing a race on a free or dead lease before reporting it held. */
43
+ const ACQUIRE_ATTEMPTS = 8;
44
+
45
+ /** The runtime directory's spawn reservation: at most one owner process is being started at a time. */
46
+ export function spawnLeaseBase(runtimeDirectory: string): string {
47
+ return path.join(runtimeDirectory, 'spawn.lease');
48
+ }
49
+
50
+ function generationFile(base: string, generation: number): string {
51
+ return `${base}.${generation}`;
52
+ }
53
+
54
+ /** The generation file `lease` names (what a long-lived holder keeps fresh against temp cleaners). */
55
+ export function leaseFile(lease: Lease): string {
56
+ return generationFile(lease.base, lease.generation);
57
+ }
58
+
59
+ /** Tells this process's generations apart from each other's (and its staged files). */
60
+ let created = 0;
61
+
62
+ /** A token no other generation has: this pid, the time, and a count within this process. */
63
+ function newToken(): string {
64
+ created += 1;
65
+ return `${process.pid}.${Date.now().toString(36)}.${created}`;
66
+ }
67
+
68
+ /** `<generation>:<token>`, the form a lease travels in to another process (an environment variable, an `adopt`). */
69
+ export function encodeLease(lease: Lease): string {
70
+ return `${lease.generation}:${lease.token}`;
71
+ }
72
+
73
+ /** The lease `encodeLease` wrote, at `base`; null for anything else. */
74
+ export function decodeLease(base: string, encoded: string | undefined): Lease | null {
75
+ const match = encoded === undefined ? null : /^(\d+):([0-9a-z.]+)$/.exec(encoded);
76
+ if (!match) return null;
77
+ const generation = Number(match[1]);
78
+ return generation > 0 ? { base, generation, token: match[2] } : null;
79
+ }
80
+
81
+ /** The lease's generations present on disk, in no particular order. */
82
+ function generations(base: string) {
83
+ const prefix = `${path.basename(base)}.`;
84
+ const names = Trust.try(() => readdirSync(path.dirname(base)), leaseFailure);
85
+ if (!names.ok) return names;
86
+ const found: number[] = [];
87
+ for (const name of names.value) {
88
+ if (!name.startsWith(prefix)) continue;
89
+ const suffix = name.slice(prefix.length);
90
+ if (/^\d+$/.test(suffix)) found.push(Number(suffix));
91
+ }
92
+ return Result.ok(found);
93
+ }
94
+
95
+ /** The lease's newest generation; 0 when it was never taken. */
96
+ export function leaseHead(base: string) {
97
+ const found = generations(base);
98
+ if (!found.ok) return found;
99
+ return Result.ok(Math.max(0, ...found.value));
100
+ }
101
+
102
+ /**
103
+ * What generation `generation` records: its token and its live holder (null
104
+ * when it is free, its holder is dead, or it is not one of ours). `gone` when
105
+ * the generation file is not there (pruned, or lost).
106
+ */
107
+ function readGeneration(base: string, generation: number) {
108
+ const text = Trust.try(
109
+ () => readFileSync(generationFile(base, generation), 'utf8'),
110
+ (cause) => (errnoCode(cause) === 'ENOENT' ? { kind: 'gone' as const } : leaseFailure(cause)),
111
+ );
112
+ if (!text.ok) return text;
113
+ // A generation that is not JSON is not one of ours (ours are never read half-written): no holder, no token.
114
+ const state = Trust.decide(fromJson(text.value), { invalid: () => null }).value;
115
+ if (typeof state !== 'object' || state === null) return Result.ok({ holder: null, token: null });
116
+ const token = 'token' in state && typeof state.token === 'string' ? state.token : null;
117
+ const holder = 'holder' in state ? state.holder : null;
118
+ const live = typeof holder === 'number' && Number.isInteger(holder) && holder > 0 && isProcessAlive(holder) ? holder : null;
119
+ return Result.ok({ holder: live, token });
120
+ }
121
+
122
+ /** Whether generation `generation` is there and has `token`. */
123
+ function generationIs(base: string, generation: number, token: string | null): Result<boolean, LeaseFailure> {
124
+ if (generation === 0) return Result.ok(true);
125
+ const state = readGeneration(base, generation);
126
+ if (state.ok) return Result.ok(state.value.token === token);
127
+ const failure = state.error;
128
+ if (failure.kind === 'gone') return Result.ok(false);
129
+ return Result.err(failure);
130
+ }
131
+
132
+ /**
133
+ * Creates generation `from + 1` recording `holder` (null: free), acting on
134
+ * generation `from` whose token is `fromToken`. The new generation's token
135
+ * when this call made it and it is the newest generation; null when another
136
+ * process acted on generation `from` first, or `from` is no longer that
137
+ * generation (the chain was lost and started again).
138
+ */
139
+ function advance(base: string, from: number, fromToken: string | null, holder: number | null): Result<string | null, LeaseFailure> {
140
+ const before = generationIs(base, from, fromToken);
141
+ if (!before.ok) return before;
142
+ if (!before.value) return Result.ok(null);
143
+ const next = generationFile(base, from + 1);
144
+ const token = newToken();
145
+ const staged = `${next}.${token}.tmp`;
146
+ const linked = Trust.try(
147
+ () => {
148
+ writeFileSync(staged, holder === null ? `{"free":true,"token":"${token}"}` : `{"holder":${holder},"token":"${token}"}`);
149
+ linkSync(staged, next);
150
+ },
151
+ (cause) => (errnoCode(cause) === 'EEXIST' ? { kind: 'lost' as const } : leaseFailure(cause)),
152
+ );
153
+ const unstaged = Trust.try(() => rmSync(staged, { force: true }), leaseFailure);
154
+ if (!unstaged.ok && unstaged.error.kind === 'lease-failed') {
155
+ // A staged copy left behind is never read: its name is not a generation.
156
+ }
157
+ if (!linked.ok) {
158
+ const failure = linked.error;
159
+ if (failure.kind === 'lost') return Result.ok(null);
160
+ return Result.err(failure);
161
+ }
162
+ const found = generations(base);
163
+ if (!found.ok) return found;
164
+ // A newer generation means `next` had been pruned and this link recreated it: the lease had moved on.
165
+ if (found.value.some((generation) => generation > from + 1)) return Result.ok(null);
166
+ // `from` replaced while this linked (lost and started again): this generation belongs to no chain.
167
+ const after = generationIs(base, from, fromToken);
168
+ if (!after.ok || !after.value) {
169
+ withdraw(base, from + 1, token);
170
+ if (!after.ok) return after;
171
+ return Result.ok(null);
172
+ }
173
+ prune(base, found.value.filter((generation) => generation <= from));
174
+ return Result.ok(token);
175
+ }
176
+
177
+ /** Removes generation `generation` again if it is still this call's own (token `token`). */
178
+ function withdraw(base: string, generation: number, token: string): void {
179
+ // One that cannot be read is left: it names this process or a free lease, and either frees itself.
180
+ if (!Trust.decide(generationIs(base, generation, token), { 'lease-failed': () => false }).value) return;
181
+ const removed = Trust.try(() => rmSync(generationFile(base, generation), { force: true }), leaseFailure);
182
+ if (!removed.ok && removed.error.kind === 'lease-failed') {
183
+ // Left in place it names this process or a free lease: either frees itself.
184
+ }
185
+ }
186
+
187
+ /** Removes superseded generations; one that cannot be removed now is removed by a later change. */
188
+ function prune(base: string, superseded: readonly number[]): void {
189
+ for (const generation of superseded) {
190
+ const removed = Trust.try(() => rmSync(generationFile(base, generation), { force: true }), leaseFailure);
191
+ if (!removed.ok && removed.error.kind === 'lease-failed') {
192
+ // Left for the next change to remove; an old generation is never read as the lease's state.
193
+ }
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Takes the lease for this process if it is free or its holder is dead. Null
199
+ * when a live process holds it (this one included: a lease is not re-entrant).
200
+ */
201
+ export function acquireLease(base: string): Result<Lease | null, LeaseFailure> {
202
+ for (let attempt = 0; attempt < ACQUIRE_ATTEMPTS; attempt += 1) {
203
+ const head = leaseHead(base);
204
+ if (!head.ok) return head;
205
+ let headToken: string | null = null;
206
+ if (head.value > 0) {
207
+ const state = readGeneration(base, head.value);
208
+ if (!state.ok) {
209
+ const failure = state.error;
210
+ if (failure.kind === 'gone') continue;
211
+ return Result.err(failure);
212
+ }
213
+ if (state.value.holder !== null) return Result.ok(null);
214
+ headToken = state.value.token;
215
+ }
216
+ const won = advance(base, head.value, headToken, process.pid);
217
+ if (!won.ok) return won;
218
+ if (won.value !== null) return Result.ok({ base, generation: head.value + 1, token: won.value });
219
+ }
220
+ return Result.ok(null);
221
+ }
222
+
223
+ /**
224
+ * Hands `lease` to process `holder`, in one step that succeeds only if the
225
+ * lease is still that generation: no reclaimer, release or other handover
226
+ * acted on it first. Null when one did.
227
+ */
228
+ export function handOverLease(lease: Lease, holder: number): Result<Lease | null, LeaseFailure> {
229
+ const moved = advance(lease.base, lease.generation, lease.token, holder);
230
+ if (!moved.ok) return moved;
231
+ return Result.ok(moved.value === null ? null : { base: lease.base, generation: lease.generation + 1, token: moved.value });
232
+ }
233
+
234
+ /** Frees the lease if it is still `lease`'s generation; false (and nothing changed) when it had moved on. */
235
+ export function releaseLease(lease: Lease): Result<boolean, LeaseFailure> {
236
+ const released = advance(lease.base, lease.generation, lease.token, null);
237
+ if (!released.ok) return released;
238
+ return Result.ok(released.value !== null);
239
+ }
240
+
241
+ /** The process `lease`'s generation records as its holder, alive or not; null when it records none or is gone. */
242
+ export function recordedHolder(lease: Lease): number | null {
243
+ const text = Trust.decide(
244
+ Trust.try(() => readFileSync(leaseFile(lease), 'utf8'), () => ({ kind: 'unreadable' as const })),
245
+ { unreadable: () => '' },
246
+ ).value;
247
+ const state = Trust.decide(fromJson(text), { invalid: () => null }).value;
248
+ if (typeof state !== 'object' || state === null || !('holder' in state)) return null;
249
+ const holder = state.holder;
250
+ return typeof holder === 'number' && Number.isInteger(holder) && holder > 0 ? holder : null;
251
+ }
252
+
253
+ /** The process holding the lease now, or null when it is free or its holder is dead. */
254
+ export function leaseHolder(base: string): Result<number | null, LeaseFailure> {
255
+ for (;;) {
256
+ const head = leaseHead(base);
257
+ if (!head.ok) return head;
258
+ if (head.value === 0) return Result.ok(null);
259
+ const state = readGeneration(base, head.value);
260
+ if (state.ok) return Result.ok(state.value.holder);
261
+ const failure = state.error;
262
+ // Pruned between the listing and the read: a newer generation exists, so look again.
263
+ if (failure.kind !== 'gone') return Result.err(failure);
264
+ }
265
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * The claim lock of builds before leases (main 1ec410c and earlier):
3
+ * `<key>.lock`, created exclusively, holding the claimer's pid in decimal.
4
+ * Such a build treats it as held while that pid lives and reclaims (removes)
5
+ * it when the pid is dead or unrecorded. It cannot see claim leases, so a
6
+ * process holding a file's claim lease also holds this lock, naming itself:
7
+ * an older client then finds the file claimed and waits for its socket
8
+ * instead of placing it with a second owner. Only the lease holder writes it
9
+ * (the lease serializes processes of this build), and it is always written
10
+ * whole — linked or renamed into place — so a reader never sees it empty.
11
+ */
12
+ import { linkSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
13
+ import { Result, Trust } from '@noego/trust';
14
+ import { isProcessAlive } from './paths.ts';
15
+ import { errnoCode, errorMessage } from './protocol.ts';
16
+
17
+ type LegacyLockFailure = { readonly kind: 'legacy-lock-failed'; readonly message: string };
18
+
19
+ const legacyFailure = (cause: unknown): LegacyLockFailure => ({ kind: 'legacy-lock-failed', message: errorMessage(cause) });
20
+
21
+ let staged = 0;
22
+
23
+ /** A file beside `lock` holding `pid`, ready to be linked or renamed into place. */
24
+ function stage(lock: string, pid: number) {
25
+ staged += 1;
26
+ const file = `${lock}.${process.pid}.${staged}.tmp`;
27
+ return Trust.try(() => {
28
+ writeFileSync(file, String(pid));
29
+ return file;
30
+ }, legacyFailure);
31
+ }
32
+
33
+ function unstage(file: string): void {
34
+ const removed = Trust.try(() => rmSync(file, { force: true }), legacyFailure);
35
+ if (!removed.ok && removed.error.kind === 'legacy-lock-failed') {
36
+ // Never read as a lock: its name is not `<key>.lock`.
37
+ }
38
+ }
39
+
40
+ /** The pid `lock` names; 0 when it names none (empty or not a number, as older builds read it); null when there is no lock. */
41
+ function holderOf(lock: string): Result<number | null, LegacyLockFailure> {
42
+ const text = Trust.try(
43
+ () => readFileSync(lock, 'utf8'),
44
+ (cause) => (errnoCode(cause) === 'ENOENT' ? { kind: 'absent' as const } : legacyFailure(cause)),
45
+ );
46
+ if (!text.ok) {
47
+ const failure = text.error;
48
+ if (failure.kind === 'absent') return Result.ok(null);
49
+ return Result.err(failure);
50
+ }
51
+ const pid = Number(text.value.trim());
52
+ return Result.ok(Number.isInteger(pid) && pid > 0 ? pid : 0);
53
+ }
54
+
55
+ /** Creates `lock` naming `pid`; false when it exists. */
56
+ function create(lock: string, pid: number): Result<boolean, LegacyLockFailure> {
57
+ const file = stage(lock, pid);
58
+ if (!file.ok) return file;
59
+ const linked = Trust.try(
60
+ () => linkSync(file.value, lock),
61
+ (cause) => (errnoCode(cause) === 'EEXIST' ? { kind: 'exists' as const } : legacyFailure(cause)),
62
+ );
63
+ unstage(file.value);
64
+ if (linked.ok) return Result.ok(true);
65
+ const failure = linked.error;
66
+ if (failure.kind === 'exists') return Result.ok(false);
67
+ return Result.err(failure);
68
+ }
69
+
70
+ /** Replaces `lock` with one naming `pid`, in one step. */
71
+ function replace(lock: string, pid: number): Result<boolean, LegacyLockFailure> {
72
+ const file = stage(lock, pid);
73
+ if (!file.ok) return file;
74
+ const renamed = Trust.try(() => renameSync(file.value, lock), legacyFailure);
75
+ if (!renamed.ok) {
76
+ unstage(file.value);
77
+ return renamed;
78
+ }
79
+ return Result.ok(true);
80
+ }
81
+
82
+ /**
83
+ * Takes `lock` for `pid`, as an older build would: created if absent,
84
+ * reclaimed if its holder is dead or unrecorded. False when a live process
85
+ * other than `pid` holds it — an older build's client placing the file.
86
+ */
87
+ export function takeLegacyLock(lock: string, pid: number): Result<boolean, LegacyLockFailure> {
88
+ for (let attempt = 0; attempt < 2; attempt += 1) {
89
+ const created = create(lock, pid);
90
+ if (!created.ok || created.value) return created;
91
+ const holder = holderOf(lock);
92
+ if (!holder.ok) return holder;
93
+ if (holder.value === pid) return Result.ok(true);
94
+ if (holder.value !== null && holder.value > 0 && isProcessAlive(holder.value)) return Result.ok(false);
95
+ // A dead or unrecorded holder (or the lock just went): reclaim it as older builds do, and try again.
96
+ const removed = Trust.try(() => rmSync(lock, { force: true }), legacyFailure);
97
+ if (!removed.ok) return removed;
98
+ }
99
+ return Result.ok(false);
100
+ }
101
+
102
+ /**
103
+ * Moves `lock` from `from` (the process the claim lease was handed over by)
104
+ * to `to`, keeping the file claimed throughout. False when a live process
105
+ * other than these two holds it.
106
+ */
107
+ export function passLegacyLock(lock: string, from: number | null, to: number): Result<boolean, LegacyLockFailure> {
108
+ const holder = holderOf(lock);
109
+ if (!holder.ok) return holder;
110
+ if (holder.value === to) return Result.ok(true);
111
+ if (holder.value !== null && holder.value === from) return replace(lock, to);
112
+ return takeLegacyLock(lock, to);
113
+ }
114
+
115
+ /** Removes `lock` if it names one of `pids`; a lock another process holds is left alone. */
116
+ export function dropLegacyLock(lock: string, pids: readonly number[]): Result<boolean, LegacyLockFailure> {
117
+ const holder = holderOf(lock);
118
+ if (!holder.ok) return holder;
119
+ if (holder.value === null || !pids.includes(holder.value)) return Result.ok(false);
120
+ const removed = Trust.try(() => rmSync(lock, { force: true }), legacyFailure);
121
+ if (!removed.ok) return removed;
122
+ return Result.ok(true);
123
+ }
package/src/paths.ts CHANGED
@@ -52,7 +52,10 @@ export type FilePaths = Readonly<{
52
52
  key: string;
53
53
  /** Unix domain socket path, or a `\\.\pipe\` named pipe on Windows (see `isNamedPipe`). */
54
54
  socket: string;
55
+ /** The claim lock older builds take (a pid in one file); still honoured while its process lives. */
55
56
  lock: string;
57
+ /** The file's claim as a lease (`lease.ts`): held by the client placing the file, then by the owner serving it. */
58
+ lease: string;
56
59
  meta: string;
57
60
  }>;
58
61
 
@@ -104,6 +107,7 @@ export function resolvePaths(file: string) {
104
107
  key,
105
108
  socket,
106
109
  lock: path.join(directory.value, `${key}.lock`),
110
+ lease: path.join(directory.value, `${key}.lease`),
107
111
  meta: path.join(directory.value, `${key}.json`),
108
112
  });
109
113
  return Result.ok(paths);
package/src/protocol.ts CHANGED
@@ -73,10 +73,12 @@ export type Request =
73
73
  | { id: number; op: 'stop' }
74
74
  /**
75
75
  * Asks this owner process to serve one more file: open it with `pragmas`
76
- * (its defaults when absent), listen on that file's own socket, release
77
- * that file's claim lock. The reply names the socket to connect to.
76
+ * (its defaults when absent) and listen on that file's own socket. `claim`
77
+ * is the file's claim lease the asking client holds (`<generation>:<token>`);
78
+ * the owner takes it over before opening the file and refuses if it cannot
79
+ * (`lease.ts`). The reply names the socket to connect to.
78
80
  */
79
- | { id: number; op: 'adopt'; file: string; pragmas?: readonly string[]; idleTimeoutMs?: number };
81
+ | { id: number; op: 'adopt'; file: string; pragmas?: readonly string[]; idleTimeoutMs?: number; claim?: string };
80
82
 
81
83
  export type RunResult = Readonly<{ changes: number; lastInsertRowid: number | bigint }>;
82
84
  export type QueryResult = Readonly<{ rows: SqlRow[] }>;
@@ -639,7 +641,9 @@ export function parseRequest(input: unknown) {
639
641
  }
640
642
  const idleTimeoutMs = fields.idleTimeoutMs;
641
643
  if (idleTimeoutMs !== undefined && (typeof idleTimeoutMs !== 'number' || !(idleTimeoutMs > 0))) return reject(id, 'idleTimeoutMs must be a positive number');
642
- const request: Request = { id, op: 'adopt', file: fields.file, pragmas: pragmas === undefined ? undefined : [...pragmas], idleTimeoutMs };
644
+ const claim = fields.claim;
645
+ if (claim !== undefined && (typeof claim !== 'string' || claim.length === 0)) return reject(id, 'adopt claim must be a non-empty string');
646
+ const request: Request = { id, op: 'adopt', file: fields.file, pragmas: pragmas === undefined ? undefined : [...pragmas], idleTimeoutMs, claim };
643
647
  return Result.ok(request);
644
648
  }
645
649
  default:
@@ -1126,6 +1130,13 @@ export function splitFrames(buffer: string): { frames: string[]; rest: string }
1126
1130
  return { frames: lines.filter((line) => line.length > 0), rest };
1127
1131
  }
1128
1132
 
1133
+ /**
1134
+ * The longest request frame the server reads, in decoded characters (the
1135
+ * newline not counted). A longer one is never complete in memory: the
1136
+ * server drops the connection once an unfinished frame passes it.
1137
+ */
1138
+ export const DEFAULT_MAX_FRAME_LENGTH = 64 * 1024 * 1024;
1139
+
1129
1140
  /**
1130
1141
  * The frames of one socket, read chunk by chunk in work proportional to what
1131
1142
  * arrives, however finely it is chunked: only the new chunk is searched for
@@ -1137,38 +1148,67 @@ export function splitFrames(buffer: string): { frames: string[]; rest: string }
1137
1148
  */
1138
1149
  export class FrameReader {
1139
1150
  private pieces: string[] = [];
1151
+ /** Characters held in `pieces`: the length of the unfinished frame so far. */
1152
+ private held = 0;
1153
+ private overflowed = false;
1140
1154
  private decoder: TextDecoder | null = null;
1141
1155
  private searched = 0;
1142
1156
 
1157
+ /**
1158
+ * `maxFrameLength` bounds one frame in characters (its newline not
1159
+ * counted); unbounded by default, as a client reads replies of any size.
1160
+ */
1161
+ constructor(private readonly maxFrameLength = Number.POSITIVE_INFINITY) {}
1162
+
1143
1163
  /** Characters searched for a newline so far: each one pushed is searched once. */
1144
1164
  get scannedCharacters(): number {
1145
1165
  return this.searched;
1146
1166
  }
1147
1167
 
1168
+ /**
1169
+ * Whether a frame passed `maxFrameLength`. Its pieces were dropped and
1170
+ * nothing more is read until `reset`: the stream has no trustworthy next
1171
+ * frame boundary.
1172
+ */
1173
+ get oversized(): boolean {
1174
+ return this.overflowed;
1175
+ }
1176
+
1148
1177
  /** The frames `chunk` completes, in order; its unterminated tail waits for the next chunk. */
1149
1178
  push(chunk: string): string[] {
1179
+ if (this.overflowed) return [];
1150
1180
  let newline = chunk.indexOf('\n');
1151
1181
  if (newline < 0) {
1152
1182
  this.searched += chunk.length;
1153
- if (chunk.length > 0) this.pieces.push(chunk);
1183
+ if (chunk.length > 0) {
1184
+ this.held += chunk.length;
1185
+ if (this.held > this.maxFrameLength) return this.overflow([]);
1186
+ this.pieces.push(chunk);
1187
+ }
1154
1188
  return [];
1155
1189
  }
1156
1190
  const frames: string[] = [];
1157
1191
  let start = 0;
1158
1192
  while (newline >= 0) {
1159
1193
  this.searched += newline + 1 - start;
1194
+ if (this.held + (newline - start) > this.maxFrameLength) return this.overflow(frames);
1160
1195
  let frame = chunk.slice(start, newline);
1161
1196
  if (this.pieces.length > 0) {
1162
1197
  this.pieces.push(frame);
1163
1198
  frame = this.pieces.join('');
1164
1199
  this.pieces = [];
1165
1200
  }
1201
+ this.held = 0;
1166
1202
  if (frame.length > 0) frames.push(frame);
1167
1203
  start = newline + 1;
1168
1204
  newline = chunk.indexOf('\n', start);
1169
1205
  }
1170
1206
  this.searched += chunk.length - start;
1171
- if (start < chunk.length) this.pieces.push(chunk.slice(start));
1207
+ if (start < chunk.length) {
1208
+ this.held = chunk.length - start;
1209
+ if (this.held > this.maxFrameLength) return this.overflow(frames);
1210
+ this.pieces.push(chunk.slice(start));
1211
+ }
1172
1212
  return frames;
1173
1213
  }
1174
1214
 
@@ -1186,8 +1226,18 @@ export class FrameReader {
1186
1226
  /** Drops an unfinished frame (and a partly received character): the stream is starting over or was given up. */
1187
1227
  reset(): void {
1188
1228
  this.pieces = [];
1229
+ this.held = 0;
1230
+ this.overflowed = false;
1189
1231
  this.decoder = null;
1190
1232
  }
1233
+
1234
+ /** Gives up the unfinished frame; `frames` are the ones completed before it. */
1235
+ private overflow(frames: string[]): string[] {
1236
+ this.pieces = [];
1237
+ this.held = 0;
1238
+ this.overflowed = true;
1239
+ return frames;
1240
+ }
1191
1241
  }
1192
1242
 
1193
1243
  function replaceBigInt(_key: string, value: unknown): unknown {