hopwire 0.1.9 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,473 @@
1
+ import { open, readdir, stat } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { LOG_BATCH_INTERVAL_MS, LOG_BATCH_MAX_BYTES, LOG_BATCH_MAX_ENTRIES, LOG_ENTRIES_KIND, LOG_ENTRIES_PER_SECOND, LOG_ENTRY_CAPTURE_LIMIT_BYTES, LOG_ENTRY_IDLE_MS, LOG_ENTRY_MAX_EXCHANGES, LOG_LINK_GRACE_MS, LOG_SOURCE_CAPTURE_LIMIT_BYTES, LOG_SOURCE_NAME_MAX_LENGTH, utf8Length, } from '@hopwire/protocol';
4
+ /**
5
+ * Application log files next to the traffic (phase 15, spec decision 144). A followed file is read from the moment
6
+ * the tunnel starts, never before; its new lines are grouped into entries, each linked to the exchanges of its service
7
+ * that were in flight when it was read, and written to a log in batches. Hopwire never writes to the file.
8
+ */
9
+ /** Ids of exchanges a service has seen in this run; an entry that names one is linked to it alone. */
10
+ const KNOWN_IDS_MAX = 10_000;
11
+ /**
12
+ * The exchanges of one service that are in flight, and the ones that ended a moment ago: an entry read while they
13
+ * were is linked to them. Every interceptor of a service reports to the same one.
14
+ */
15
+ export class InFlightExchanges {
16
+ now;
17
+ graceMs;
18
+ open = new Map();
19
+ ended = [];
20
+ known = new Set();
21
+ constructor(now = Date.now, graceMs = LOG_LINK_GRACE_MS) {
22
+ this.now = now;
23
+ this.graceMs = graceMs;
24
+ }
25
+ /** An exchange began; the function ends it (once). */
26
+ begin(id) {
27
+ this.open.set(id, (this.open.get(id) ?? 0) + 1);
28
+ this.known.delete(id);
29
+ this.known.add(id);
30
+ if (this.known.size > KNOWN_IDS_MAX) {
31
+ const oldest = this.known.values().next().value;
32
+ if (oldest !== undefined) {
33
+ this.known.delete(oldest);
34
+ }
35
+ }
36
+ let done = false;
37
+ return () => {
38
+ if (done) {
39
+ return;
40
+ }
41
+ done = true;
42
+ const count = (this.open.get(id) ?? 1) - 1;
43
+ if (count <= 0) {
44
+ this.open.delete(id);
45
+ this.ended.push({ id, at: this.now() });
46
+ }
47
+ else {
48
+ this.open.set(id, count);
49
+ }
50
+ };
51
+ }
52
+ /**
53
+ * Ids of the exchanges in flight now. When none is, the ones that ended within the grace time: a handler that
54
+ * writes after its response (Laravel's terminating callbacks) is still linked, and a request that follows another
55
+ * at once is not linked to the one before it.
56
+ */
57
+ current() {
58
+ const floor = this.now() - this.graceMs;
59
+ while (this.ended.length > 0 && (this.ended[0]?.at ?? 0) < floor) {
60
+ this.ended.shift();
61
+ }
62
+ if (this.open.size > 0) {
63
+ return [...this.open.keys()];
64
+ }
65
+ return [...new Set(this.ended.map(({ id }) => id))];
66
+ }
67
+ /** Whether an exchange with this id began in this run (among the newest KNOWN_IDS_MAX). */
68
+ knows(id) {
69
+ return this.known.has(id);
70
+ }
71
+ }
72
+ export const LOG_FOLLOW_LIMITS = {
73
+ entryBytes: LOG_ENTRY_CAPTURE_LIMIT_BYTES,
74
+ sourceBytes: LOG_SOURCE_CAPTURE_LIMIT_BYTES,
75
+ entriesPerSecond: LOG_ENTRIES_PER_SECOND,
76
+ batchIntervalMs: LOG_BATCH_INTERVAL_MS,
77
+ batchBytes: LOG_BATCH_MAX_BYTES,
78
+ batchEntries: LOG_BATCH_MAX_ENTRIES,
79
+ idleMs: LOG_ENTRY_IDLE_MS,
80
+ };
81
+ /** How often a followed file is looked at. `fs.watch` misses writes over Docker bind mounts on macOS, so it is polled. */
82
+ export const LOG_POLL_INTERVAL_MS = 100;
83
+ /** Bytes read from a file per look at most; the rest waits for the next one. */
84
+ const READ_PER_TICK_BYTES = 8 * 1024 * 1024;
85
+ const READ_CHUNK_BYTES = 64 * 1024;
86
+ /** A line without its end this long is taken as a line, so one endless line cannot fill the memory. */
87
+ const PARTIAL_LINE_MAX_BYTES = 1024 * 1024;
88
+ /** A file that is away this long is reported as gone once */
89
+ const GONE_NOTICE_AFTER_MS = 1_000;
90
+ /** A line that starts an entry: a timestamp at its start (`[2026-11-30 12:00:00]`, `2026-11-30T12:00:00`, `[30-Nov-2026 ...`) or `{`. */
91
+ const ENTRY_START = [
92
+ /^\[\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}/,
93
+ /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}/,
94
+ /^\[\d{1,2}-[A-Za-z]{3}-\d{4}[ T:]\d{2}:\d{2}/,
95
+ /^\{/,
96
+ ];
97
+ /** An exchange id as the interceptor makes them, for `capture.logRequestId` */
98
+ const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;
99
+ export function isEntryStart(line) {
100
+ return ENTRY_START.some((pattern) => pattern.test(line));
101
+ }
102
+ /** The name of a followed file when none is given: the file name without its extension (and without a `*`). */
103
+ export function defaultLogName(file) {
104
+ const base = path.basename(file);
105
+ const withoutExtension = base.includes('.') && !base.startsWith('.') ? base.slice(0, base.lastIndexOf('.')) : base;
106
+ const name = withoutExtension.replace(/[-_.]*\*[-_.]*/g, '');
107
+ return (name === '' ? 'log' : name).slice(0, LOG_SOURCE_NAME_MAX_LENGTH);
108
+ }
109
+ /** Whether a `*` pattern is only in the last segment of a path. */
110
+ export function isFollowablePath(file) {
111
+ return !path.dirname(file).includes('*');
112
+ }
113
+ /**
114
+ * Follows one log file. Resolves once the file was looked at (opened at its end, or found missing); the returned
115
+ * follower reads on until it is stopped.
116
+ */
117
+ export async function followLogFile(options) {
118
+ const limits = { ...LOG_FOLLOW_LIMITS, ...options.limits };
119
+ const now = options.now ?? Date.now;
120
+ const pattern = path.basename(options.path).includes('*') ? patternOf(path.basename(options.path)) : null;
121
+ const notice = (line) => options.onNotice?.(`${options.name}: ${line}`);
122
+ /** Offsets of the files read in this run, by device and inode: a file seen at the start counts from its end */
123
+ const offsets = new Map();
124
+ let current = null;
125
+ let partial = Buffer.alloc(0);
126
+ let entry = null;
127
+ let sawStart = false;
128
+ let lastBytesAt = 0;
129
+ let goneReported = false;
130
+ let goneSince = null;
131
+ const refused = new Set();
132
+ let seq = 0;
133
+ let pending = [];
134
+ let pendingBytes = 0;
135
+ let pendingSince = null;
136
+ let omitted = { entries: 0, bytes: 0 };
137
+ let capturedTotal = 0;
138
+ let rateSecond = -1;
139
+ let rateCount = 0;
140
+ const limitReported = { source: false, rate: false };
141
+ let writes = Promise.resolve();
142
+ async function resolveTarget() {
143
+ if (pattern === null) {
144
+ const stats = await stat(options.path).catch(() => null);
145
+ return stats === null ? null : { path: options.path, stats };
146
+ }
147
+ const directory = path.dirname(options.path);
148
+ const names = await readdir(directory).catch(() => []);
149
+ let newest = null;
150
+ for (const name of names) {
151
+ if (!pattern.test(name)) {
152
+ continue;
153
+ }
154
+ const file = path.join(directory, name);
155
+ const stats = await stat(file).catch(() => null);
156
+ if (stats === null || !stats.isFile()) {
157
+ continue;
158
+ }
159
+ if (newest === null ||
160
+ stats.mtimeMs > newest.stats.mtimeMs ||
161
+ (stats.mtimeMs === newest.stats.mtimeMs && file > newest.path)) {
162
+ newest = { path: file, stats };
163
+ }
164
+ }
165
+ return newest;
166
+ }
167
+ /** At the start: every file that already exists counts from its end, so nothing written before is read. */
168
+ async function markExisting() {
169
+ const files = pattern === null
170
+ ? [options.path]
171
+ : (await readdir(path.dirname(options.path)).catch(() => []))
172
+ .filter((name) => pattern.test(name))
173
+ .map((name) => path.join(path.dirname(options.path), name));
174
+ for (const file of files) {
175
+ const stats = await stat(file).catch(() => null);
176
+ if (stats?.isFile() === true) {
177
+ offsets.set(fileKey(stats), stats.size);
178
+ }
179
+ }
180
+ }
181
+ async function openTarget(target) {
182
+ const key = fileKey(target.stats);
183
+ if (refused.has(key)) {
184
+ return;
185
+ }
186
+ if (!target.stats.isFile()) {
187
+ refused.add(key);
188
+ notice('is not a regular file; it is not followed');
189
+ return;
190
+ }
191
+ try {
192
+ const handle = await open(target.path, 'r');
193
+ current = {
194
+ path: target.path,
195
+ handle,
196
+ dev: target.stats.dev,
197
+ ino: target.stats.ino,
198
+ offset: Math.min(offsets.get(key) ?? 0, target.stats.size),
199
+ };
200
+ }
201
+ catch (error) {
202
+ refused.add(key);
203
+ notice(`cannot be read (${errorCodeOf(error)}); it is not followed until it is replaced`);
204
+ }
205
+ }
206
+ async function closeCurrent() {
207
+ const file = current;
208
+ if (file === null) {
209
+ return;
210
+ }
211
+ current = null;
212
+ await drain(file);
213
+ takePartialLine();
214
+ closeEntry();
215
+ offsets.set(`${file.dev}:${file.ino}`, file.offset);
216
+ await file.handle.close().catch(() => { });
217
+ }
218
+ /** Reads the new bytes of a file, within the bytes one look reads. */
219
+ async function drain(file) {
220
+ let read = 0;
221
+ const buffer = Buffer.allocUnsafe(READ_CHUNK_BYTES);
222
+ while (read < READ_PER_TICK_BYTES) {
223
+ const { bytesRead } = await file.handle
224
+ .read(buffer, 0, READ_CHUNK_BYTES, file.offset)
225
+ .catch(() => ({ bytesRead: 0 }));
226
+ if (bytesRead === 0) {
227
+ return;
228
+ }
229
+ file.offset += bytesRead;
230
+ read += bytesRead;
231
+ onBytes(buffer.subarray(0, bytesRead));
232
+ }
233
+ }
234
+ function onBytes(chunk) {
235
+ lastBytesAt = now();
236
+ let data = partial.length === 0 ? Buffer.from(chunk) : Buffer.concat([partial, chunk]);
237
+ let newline = data.indexOf(0x0a);
238
+ while (newline !== -1) {
239
+ onLine(decode(data.subarray(0, newline)));
240
+ data = data.subarray(newline + 1);
241
+ newline = data.indexOf(0x0a);
242
+ }
243
+ partial = data.length > PARTIAL_LINE_MAX_BYTES ? (onLine(decode(data)), Buffer.alloc(0)) : Buffer.from(data);
244
+ }
245
+ function takePartialLine() {
246
+ if (partial.length > 0) {
247
+ onLine(decode(partial));
248
+ partial = Buffer.alloc(0);
249
+ }
250
+ }
251
+ function onLine(line) {
252
+ const starts = isEntryStart(line);
253
+ sawStart ||= starts;
254
+ if (entry === null || starts || !sawStart) {
255
+ closeEntry();
256
+ entry = {
257
+ readAt: now(),
258
+ parts: [],
259
+ capturedBytes: 0,
260
+ length: 0,
261
+ truncated: false,
262
+ lines: 0,
263
+ links: options.inFlight.current(),
264
+ };
265
+ }
266
+ const piece = entry.lines === 0 ? line : `\n${line}`;
267
+ entry.lines += 1;
268
+ const bytes = utf8Length(piece);
269
+ entry.length += bytes;
270
+ if (entry.truncated) {
271
+ return;
272
+ }
273
+ if (entry.capturedBytes + bytes <= limits.entryBytes) {
274
+ entry.parts.push(piece);
275
+ entry.capturedBytes += bytes;
276
+ return;
277
+ }
278
+ const cut = cutUtf8(piece, limits.entryBytes - entry.capturedBytes);
279
+ entry.parts.push(cut);
280
+ entry.capturedBytes += utf8Length(cut);
281
+ entry.truncated = true;
282
+ }
283
+ function closeEntry() {
284
+ const closing = entry;
285
+ if (closing === null) {
286
+ return;
287
+ }
288
+ entry = null;
289
+ const text = closing.parts.join('');
290
+ const named = [...new Set(text.match(UUID) ?? [])]
291
+ .map((id) => id.toLowerCase())
292
+ .filter((id) => options.inFlight.knows(id));
293
+ const links = named.length > 0 ? named : closing.links;
294
+ const captured = {
295
+ readAt: closing.readAt,
296
+ text,
297
+ length: closing.length,
298
+ truncated: closing.truncated,
299
+ exchangeIds: links.slice(0, LOG_ENTRY_MAX_EXCHANGES),
300
+ ambiguous: links.length > 1,
301
+ };
302
+ const second = Math.floor(closing.readAt / 1000);
303
+ if (second !== rateSecond) {
304
+ rateSecond = second;
305
+ rateCount = 0;
306
+ }
307
+ rateCount += 1;
308
+ if (rateCount > limits.entriesPerSecond) {
309
+ omit(captured, 'rate');
310
+ }
311
+ else if (capturedTotal + closing.capturedBytes > limits.sourceBytes) {
312
+ omit(captured, 'source');
313
+ }
314
+ else {
315
+ capturedTotal += closing.capturedBytes;
316
+ pending.push(captured);
317
+ pendingBytes += closing.capturedBytes;
318
+ pendingSince ??= now();
319
+ }
320
+ if (pendingBytes >= limits.batchBytes || pending.length >= limits.batchEntries) {
321
+ flush();
322
+ }
323
+ }
324
+ function omit(captured, why) {
325
+ omitted.entries += 1;
326
+ omitted.bytes += captured.length;
327
+ pendingSince ??= now();
328
+ if (!limitReported[why]) {
329
+ limitReported[why] = true;
330
+ notice(why === 'rate'
331
+ ? `more than ${limits.entriesPerSecond} entries in one second; the rest of such a second is counted, not captured`
332
+ : `${Math.round(limits.sourceBytes / (1024 * 1024))} MB captured in this run; further entries are counted, not captured`);
333
+ }
334
+ }
335
+ function flush() {
336
+ if (pending.length === 0 && omitted.entries === 0) {
337
+ return;
338
+ }
339
+ const block = {
340
+ kind: LOG_ENTRIES_KIND,
341
+ serviceName: options.serviceName,
342
+ source: options.name,
343
+ seq: seq++,
344
+ entries: pending,
345
+ ...(omitted.entries > 0 ? { omitted } : {}),
346
+ ...(options.agents === true ? { agents: true } : {}),
347
+ };
348
+ pending = [];
349
+ pendingBytes = 0;
350
+ pendingSince = null;
351
+ omitted = { entries: 0, bytes: 0 };
352
+ writes = writes.then(() => options.append(block)).catch((error) => options.onLogError?.(error));
353
+ }
354
+ async function look() {
355
+ const target = await resolveTarget();
356
+ const reading = current;
357
+ if (target === null) {
358
+ if (reading !== null) {
359
+ // A rotation renames the file and creates it again, and the writer may still finish a line in the
360
+ // renamed one: it stays open and is read on until the new file is there or this one is gone for good
361
+ goneSince ??= now();
362
+ await drain(reading);
363
+ }
364
+ if (goneSince !== null && !goneReported && now() - goneSince >= GONE_NOTICE_AFTER_MS) {
365
+ goneReported = true;
366
+ await closeCurrent();
367
+ notice('the file is gone; waiting for it to come back');
368
+ }
369
+ }
370
+ else {
371
+ goneSince = null;
372
+ goneReported = false;
373
+ if (reading === null ||
374
+ reading.path !== target.path ||
375
+ reading.ino !== target.stats.ino ||
376
+ reading.dev !== target.stats.dev) {
377
+ // Rotated, a newer match of the pattern, or (back) there: the old file is read to its end first
378
+ await closeCurrent();
379
+ await openTarget(target);
380
+ }
381
+ else if (target.stats.size < reading.offset) {
382
+ // Truncated: read again from its start
383
+ takePartialLine();
384
+ closeEntry();
385
+ reading.offset = 0;
386
+ }
387
+ const file = current;
388
+ if (file !== null) {
389
+ await drain(file);
390
+ }
391
+ }
392
+ const time = now();
393
+ if (time - lastBytesAt >= limits.idleMs) {
394
+ takePartialLine();
395
+ closeEntry();
396
+ }
397
+ if (pendingSince !== null && time - pendingSince >= limits.batchIntervalMs) {
398
+ flush();
399
+ }
400
+ }
401
+ await markExisting();
402
+ const first = await resolveTarget();
403
+ const waiting = first === null;
404
+ if (first !== null) {
405
+ await openTarget(first);
406
+ }
407
+ let stopped = false;
408
+ let timer;
409
+ let looking = Promise.resolve();
410
+ const schedule = () => {
411
+ timer = setTimeout(() => {
412
+ looking = look()
413
+ .catch(() => { })
414
+ .finally(() => {
415
+ if (!stopped) {
416
+ schedule();
417
+ }
418
+ });
419
+ }, options.pollIntervalMs ?? LOG_POLL_INTERVAL_MS);
420
+ timer.unref();
421
+ };
422
+ schedule();
423
+ return {
424
+ name: options.name,
425
+ waiting,
426
+ async stop() {
427
+ if (stopped) {
428
+ return;
429
+ }
430
+ stopped = true;
431
+ clearTimeout(timer);
432
+ await looking;
433
+ await closeCurrent();
434
+ takePartialLine();
435
+ closeEntry();
436
+ flush();
437
+ await writes;
438
+ },
439
+ };
440
+ }
441
+ function patternOf(name) {
442
+ const escaped = name
443
+ .split('*')
444
+ .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&'))
445
+ .join('[^/\\\\]*');
446
+ return new RegExp(`^${escaped}$`);
447
+ }
448
+ function fileKey(stats) {
449
+ return `${stats.dev}:${stats.ino}`;
450
+ }
451
+ const decoder = new TextDecoder('utf-8', { fatal: false });
452
+ /** A line as text: bytes that are not UTF-8 become U+FFFD, a CR before the LF is dropped. */
453
+ function decode(bytes) {
454
+ const text = decoder.decode(bytes);
455
+ return text.endsWith('\r') ? text.slice(0, -1) : text;
456
+ }
457
+ /** The longest start of a text that is at most `max` bytes as UTF-8, cut between two characters. */
458
+ export function cutUtf8(text, max) {
459
+ let bytes = 0;
460
+ let end = 0;
461
+ for (const character of text) {
462
+ const size = utf8Length(character);
463
+ if (bytes + size > max) {
464
+ break;
465
+ }
466
+ bytes += size;
467
+ end += character.length;
468
+ }
469
+ return text.slice(0, end);
470
+ }
471
+ function errorCodeOf(error) {
472
+ return typeof error === 'object' && error !== null && 'code' in error ? String(error.code) : 'error';
473
+ }