hopwire 0.1.5 → 0.1.7

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.
@@ -3,12 +3,24 @@ import { INSPECTOR_HEARTBEAT_INTERVAL_MS, ProtocolError, decodeReplayOverrides,
3
3
  import { isRedactedHeader } from './agent/redact.js';
4
4
  import { summarize } from './agent/summary.js';
5
5
  import { InvalidBlockError } from './log.js';
6
+ import { WsReplays, recordedInMessages } from './ws-replay.js';
6
7
  /**
7
8
  * A teammate's log as their coding agents may see it (spec decision 140): only the exchanges the sharer marked with
8
- * agents: true. Any other block is left out as a block that is not an exchange is, so no route can list, find or
9
- * replay it; the browser inspector reads the log itself.
9
+ * agents: true, and the recorded messages of a WebSocket whose handshake is marked. Any other block is left out as a
10
+ * block that is not an exchange is, so no route can list, find or replay it; the browser inspector reads the log
11
+ * itself.
10
12
  */
11
13
  export function agentsOnly(log) {
14
+ /** Handshakes seen marked or not, so the messages that follow them are sorted without a lookup */
15
+ const marked = new Map();
16
+ const isMarked = async (exchangeId) => {
17
+ const known = marked.get(exchangeId);
18
+ if (known !== undefined) {
19
+ return known;
20
+ }
21
+ const found = await log.find(exchangeId).catch(() => null);
22
+ return found?.exchange.agents === true;
23
+ };
12
24
  return {
13
25
  get length() {
14
26
  return log.length;
@@ -31,6 +43,31 @@ export function agentsOnly(log) {
31
43
  }
32
44
  });
33
45
  },
46
+ async wsMessages(exchangeId, handshakeIndex, afterSeq) {
47
+ const handshake = await log.get(handshakeIndex, { wait: false }).catch(() => null);
48
+ if (handshake === null || handshake.id !== exchangeId || handshake.agents !== true) {
49
+ return { blocks: [], more: false };
50
+ }
51
+ return log.wsMessages(exchangeId, handshakeIndex, afterSeq);
52
+ },
53
+ subscribeWsMessages(listener) {
54
+ const endExchanges = log.subscribe((_index, exchange) => {
55
+ if (isWebSocketHandshake(exchange)) {
56
+ marked.set(exchange.id, exchange.agents === true);
57
+ }
58
+ });
59
+ const endMessages = log.subscribeWsMessages((index, block) => {
60
+ void isMarked(block.exchangeId).then((allowed) => {
61
+ if (allowed) {
62
+ listener(index, block);
63
+ }
64
+ });
65
+ });
66
+ return () => {
67
+ endExchanges();
68
+ endMessages();
69
+ };
70
+ },
34
71
  };
35
72
  }
36
73
  /** An answer of the API that is not a success: HTTP status, a stable code and one sentence. */
@@ -47,6 +84,11 @@ export class ApiError extends Error {
47
84
  }
48
85
  const DEFAULT_LIMIT = 100;
49
86
  const MAX_LIMIT = 500;
87
+ /**
88
+ * Blocks one page of the exchange list reads beyond `limit` at most, to step over the blocks of recorded WebSocket
89
+ * messages: a page counts exchanges, and a chatty WebSocket can write many blocks between two of them.
90
+ */
91
+ const LIST_EXTRA_SCAN_BLOCKS = 20_000;
50
92
  /**
51
93
  * Bodies (as Base64) one answer of the exchange list carries per log at most. With the capture limit of 2 MB an
52
94
  * exchange holds up to 5.6 MB of them, so a page of 100 could be more than half a gigabyte in one JSON string.
@@ -81,6 +123,7 @@ const HTTP_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
81
123
  const REQUEST_PATH = /^\/[!-ÿ]*$/;
82
124
  export function createInspectorApi(options) {
83
125
  const streams = new Set();
126
+ const replays = new WsReplays(options.webSocketReplayTimings);
84
127
  function openStream(req, res) {
85
128
  req.socket.setNoDelay(true);
86
129
  res.writeHead(200, {
@@ -101,10 +144,16 @@ export function createInspectorApi(options) {
101
144
  stream.write(chunk);
102
145
  }
103
146
  }
104
- const unsubscribe = options.sources.map(({ origin, log }) => log.subscribe((index, exchange) => {
105
- const record = { index, origin, exchange };
106
- broadcast(`event: exchange\ndata: ${JSON.stringify(record)}\n\n`);
107
- }));
147
+ const unsubscribe = options.sources.flatMap(({ origin, log }) => [
148
+ log.subscribe((index, exchange) => {
149
+ const record = { index, origin, exchange };
150
+ broadcast(`event: exchange\ndata: ${JSON.stringify(record)}\n\n`);
151
+ }),
152
+ log.subscribeWsMessages((index, block) => {
153
+ const record = { index, origin, block };
154
+ broadcast(`event: ws_messages\ndata: ${JSON.stringify(record)}\n\n`);
155
+ }),
156
+ ]);
108
157
  const heartbeat = setInterval(() => broadcast(': heartbeat\n\n'), options.heartbeatIntervalMs ?? INSPECTOR_HEARTBEAT_INTERVAL_MS);
109
158
  heartbeat.unref();
110
159
  let closed = false;
@@ -136,9 +185,13 @@ export function createInspectorApi(options) {
136
185
  }
137
186
  openStream(req, res);
138
187
  }
188
+ else if (first === 'ws-messages' && second !== undefined && second !== '' && more.length === 0) {
189
+ only(method, 'GET');
190
+ sendJson(res, 200, await wsMessagesOf(options.sources, second, params));
191
+ }
139
192
  else if (first === 'replay' && second !== undefined && second !== '' && more.length === 0) {
140
193
  only(method, 'POST');
141
- sendJson(res, 200, await replay(options, second, req, params));
194
+ sendJson(res, 200, await replay(options, replays, second, req, params));
142
195
  }
143
196
  else {
144
197
  throw new ApiError(404, 'not_found', 'The inspector API has no such route');
@@ -147,6 +200,7 @@ export function createInspectorApi(options) {
147
200
  close() {
148
201
  closed = true;
149
202
  clearInterval(heartbeat);
203
+ replays.stop();
150
204
  for (const end of unsubscribe) {
151
205
  end();
152
206
  }
@@ -207,21 +261,22 @@ async function listExchanges(sources, query, bodyBudgetBytes) {
207
261
  return records.slice(0, limit);
208
262
  }
209
263
  /**
210
- * The blocks of one log below `end`, newest first: up to `limit`, and no more than fill the budget for bodies. They
264
+ * The exchanges of one log below `end`, newest first: up to `limit`, and no more than fill the budget for bodies. They
211
265
  * are read a few at a time, so a page of large exchanges is never in memory as a whole, and the run has no gap a
212
266
  * later page would have to fill: paging goes on below its lowest index.
213
267
  */
214
268
  async function newestBelow(source, end, limit, bodyBudgetBytes) {
215
269
  const records = [];
216
- const start = Math.max(0, end - limit);
270
+ // A page counts exchanges: blocks of recorded WebSocket messages between them are stepped over, within a bound
271
+ const floor = Math.max(0, end - limit - LIST_EXTRA_SCAN_BLOCKS);
217
272
  let bodyBytes = 0;
218
273
  const reader = batchReader(source);
219
- for (let top = end; top > start && bodyBytes < bodyBudgetBytes; top -= LIST_READ_BATCH) {
220
- for (const record of await reader(top, Math.max(start, top - LIST_READ_BATCH))) {
274
+ for (let top = end; top > floor && records.length < limit && bodyBytes < bodyBudgetBytes; top -= LIST_READ_BATCH) {
275
+ for (const record of await reader(top, Math.max(floor, top - LIST_READ_BATCH))) {
221
276
  if (record === null) {
222
277
  continue;
223
278
  }
224
- if (bodyBytes >= bodyBudgetBytes) {
279
+ if (bodyBytes >= bodyBudgetBytes || records.length >= limit) {
225
280
  break;
226
281
  }
227
282
  records.push(record);
@@ -409,27 +464,34 @@ function integerParameter(query, name, min, max) {
409
464
  * carry this id: an id is chosen by whoever wrote the log, so a teammate's log can hold it more than once, and the
410
465
  * caller names the block it was shown instead of leaving the choice to the lookup.
411
466
  */
412
- async function replay(options, id, req, query) {
467
+ async function replay(options, replays, id, req, query) {
413
468
  const overrides = await readOverrides(req);
414
469
  const origin = originParameter(query);
415
470
  const index = integerParameter(query, 'index', 0, Number.MAX_SAFE_INTEGER);
416
471
  if ((origin === undefined) !== (index === undefined)) {
417
472
  throw new ApiError(400, 'invalid_request', 'origin and index have to be given together');
418
473
  }
419
- const original = origin === undefined || index === undefined
474
+ const found = origin === undefined || index === undefined
420
475
  ? await findExchange(options.sources, id)
421
476
  : await exchangeAt(options.sources, origin, index, id);
422
- if (original === null) {
477
+ if (found === null) {
423
478
  throw new ApiError(404, 'unknown_exchange', 'No exchange with this id is in the log');
424
479
  }
425
- if (isWebSocketHandshake(original)) {
426
- // The log has the handshake and none of the messages, so there is nothing a replay could repeat
427
- throw new ApiError(422, 'websocket_handshake', 'A WebSocket handshake cannot be replayed: the messages of the connection are not recorded');
480
+ const original = found.exchange;
481
+ const handshake = isWebSocketHandshake(original);
482
+ if (handshake && (overrides.method !== undefined || overrides.bodyBase64 !== undefined)) {
483
+ throw new ApiError(400, 'invalid_request', 'A WebSocket is replayed with path, headers, messages and timing; method and bodyBase64 do not apply');
484
+ }
485
+ if (!handshake && (overrides.messages !== undefined || overrides.timing !== undefined)) {
486
+ throw new ApiError(400, 'invalid_request', 'messages and timing only apply to the handshake of a WebSocket');
428
487
  }
429
488
  const interceptor = options.replayThrough(original);
430
489
  if (interceptor === null) {
431
490
  throw new ApiError(409, 'no_replay_target', 'There is no replay target for this exchange');
432
491
  }
492
+ if (handshake) {
493
+ return replayWebSocket(replays, interceptor, found, overrides);
494
+ }
433
495
  const stored = original.request;
434
496
  if (overrides.bodyBase64 === undefined && stored.bodyTruncated) {
435
497
  throw new ApiError(422, 'body_truncated', 'The stored body was truncated; supply a body with Edit & Replay to send this request');
@@ -500,17 +562,80 @@ async function exchangeAt(sources, origin, index, id) {
500
562
  if (exchange.id !== id) {
501
563
  throw new ApiError(409, 'exchange_mismatch', 'The log holds another exchange at this place than the one that was shown; nothing was sent');
502
564
  }
503
- return exchange;
565
+ return { exchange, log: source.log, index };
504
566
  }
505
567
  async function findExchange(sources, id) {
506
568
  for (const { log } of sources) {
507
569
  const found = await log.find(id);
508
570
  if (found !== null) {
509
- return found.exchange;
571
+ return { exchange: found.exchange, log, index: found.index };
510
572
  }
511
573
  }
512
574
  return null;
513
575
  }
576
+ /** Every recorded message of one WebSocket, page by page. */
577
+ async function allMessages({ exchange, log, index }) {
578
+ const messages = [];
579
+ let after = -1;
580
+ for (;;) {
581
+ const page = await log.wsMessages(exchange.id, index, after);
582
+ for (const block of page.blocks) {
583
+ messages.push(...block.messages);
584
+ after = block.seq;
585
+ }
586
+ if (!page.more || page.blocks.length === 0) {
587
+ return messages;
588
+ }
589
+ }
590
+ }
591
+ /**
592
+ * The replay of a WebSocket handshake: a new WebSocket with the recorded (or edited) path, headers and client
593
+ * messages. Answers with the new 101 exchange once the handshake is done; the messages follow on the stream.
594
+ */
595
+ async function replayWebSocket(replays, interceptor, found, overrides) {
596
+ const stored = found.exchange.request;
597
+ let messages = overrides.messages;
598
+ if (messages === undefined) {
599
+ const recorded = (await allMessages(found)).filter((message) => message.direction === 'in');
600
+ if (recorded.some((message) => message.truncated)) {
601
+ throw new ApiError(409, 'message_truncated', 'A message was captured only in part; replace or remove it with Edit & Replay to send this WebSocket');
602
+ }
603
+ messages = recordedInMessages(recorded);
604
+ }
605
+ const requestPath = overrides.path ?? stored.path;
606
+ const headers = overrides.headers ?? stored.headers;
607
+ assertSendable('GET', requestPath, headers);
608
+ const exchange = await replays.start({
609
+ interceptor,
610
+ replayOf: found.exchange.id,
611
+ path: requestPath,
612
+ headers,
613
+ messages,
614
+ timing: overrides.timing ?? 'recorded',
615
+ });
616
+ if (exchange === null) {
617
+ throw new ApiError(500, 'log_failed', 'The replay was sent but could not be written to the traffic log');
618
+ }
619
+ return exchange;
620
+ }
621
+ /**
622
+ * `GET /api/ws-messages/<exchangeId>`: the blocks of recorded messages of one WebSocket after `after` (a seq), from
623
+ * the log `origin` names or the first log that holds the handshake.
624
+ */
625
+ async function wsMessagesOf(sources, id, query) {
626
+ const origin = originParameter(query);
627
+ const after = integerParameter(query, 'after', 0, Number.MAX_SAFE_INTEGER);
628
+ for (const source of sources) {
629
+ if (origin !== undefined && source.origin !== origin) {
630
+ continue;
631
+ }
632
+ const found = await source.log.find(id);
633
+ if (found !== null && isWebSocketHandshake(found.exchange)) {
634
+ return source.log.wsMessages(id, found.index, after ?? -1);
635
+ }
636
+ }
637
+ throw new ApiError(404, 'not_found', 'No WebSocket handshake with this id is in the log');
638
+ }
514
639
  /** The body of a replay is known in full, so Content-Length is set to what is really sent. */
515
640
  function replayHeaders(headers, body) {
516
641
  const hadLength = headers.some(([name]) => name.toLowerCase() === 'content-length');
@@ -5,6 +5,7 @@ import { WebSocket } from 'ws';
5
5
  import { BODY_CAPTURE_LIMIT_BYTES, WS_MESSAGE_MAX_BYTES, getHeader, headerListFromRaw, headerListToRaw, offeredSubprotocols, withoutHandshakeHeaders, withoutHopByHopHeaders, } from '@hopwire/protocol';
6
6
  import { BodyCapture } from './body-capture.js';
7
7
  import { WS_CLOSE_TIMEOUT_MS } from './websocket.js';
8
+ import { NO_WS_CAPTURE, captureWebSocket } from './ws-capture.js';
8
9
  /** Thrown by `forward` when the signal of the request fired before the local service had answered. */
9
10
  export class RequestAbandonedError extends Error {
10
11
  constructor() {
@@ -27,6 +28,8 @@ export function createInterceptor(options) {
27
28
  }
28
29
  /** What every exchange starts with: the clock, the two capped copies and the way into the log. */
29
30
  const begin = (request) => {
31
+ // Known ahead, so the messages of a WebSocket can name their handshake before it is in the log
32
+ const id = randomUUID();
30
33
  const timestamp = Date.now();
31
34
  const startedAt = performance.now();
32
35
  const requestCapture = new BodyCapture(limit);
@@ -40,7 +43,7 @@ export function createInterceptor(options) {
40
43
  const durationMs = Math.round(performance.now() - startedAt);
41
44
  const requestBodyWhole = await requestBodyRead;
42
45
  const exchange = {
43
- id: randomUUID(),
46
+ id,
44
47
  timestamp,
45
48
  serviceName,
46
49
  source: request.source,
@@ -73,7 +76,7 @@ export function createInterceptor(options) {
73
76
  options.onExchange?.(exchange);
74
77
  settle(exchange);
75
78
  };
76
- return { requestCapture, responseCapture, completed, settle, record };
79
+ return { id, requestCapture, responseCapture, completed, settle, record };
77
80
  };
78
81
  return {
79
82
  async forward(request) {
@@ -138,7 +141,7 @@ export function createInterceptor(options) {
138
141
  return { status, headers, body: body(), completed };
139
142
  },
140
143
  async upgrade(request) {
141
- const { responseCapture, completed, settle, record: recordAfter } = begin({ ...request, method: 'GET' });
144
+ const { id, responseCapture, completed, settle, record: recordAfter } = begin({ ...request, method: 'GET' });
142
145
  // An upgrade request has no body
143
146
  const record = (status, headers) => recordAfter(status, headers, Promise.resolve(true));
144
147
  let answer;
@@ -167,12 +170,23 @@ export function createInterceptor(options) {
167
170
  // Logged as the service answered, with its Upgrade and handshake headers. Not awaited: the client
168
171
  // has its WebSocket while the entry is written
169
172
  void record(101, withoutHopByHopHeaders(answered, [], true)).catch(() => settle(null));
173
+ const capture = options.captureWebSocketMessages === false
174
+ ? NO_WS_CAPTURE
175
+ : captureWebSocket({
176
+ socket: answer.socket,
177
+ exchangeId: id,
178
+ handshake: completed,
179
+ append: (block) => log.append(block),
180
+ onLogError: options.onLogError,
181
+ limits: options.webSocketCaptureLimits,
182
+ });
170
183
  return {
171
184
  accepted: true,
172
185
  socket: answer.socket,
173
186
  protocol: answer.socket.protocol === '' ? null : answer.socket.protocol,
174
187
  headers: withoutHandshakeHeaders(answered),
175
188
  completed,
189
+ capture,
176
190
  };
177
191
  }
178
192
  // Any other answer is an ordinary response: passed on, captured and logged like one
package/dist/log.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { chmod, mkdir } from 'node:fs/promises';
2
2
  import Corestore from 'corestore';
3
- import { isCapturedExchange } from '@hopwire/protocol';
3
+ import { isCapturedExchange, isCapturedWsMessages, } from '@hopwire/protocol';
4
+ /** Blocks of recorded messages one answer of `wsMessages` holds at most. */
5
+ export const WS_MESSAGES_PAGE_BLOCKS = 50;
4
6
  /** How long a read waits for a block of a teammate's log that is not on this machine yet. */
5
7
  const REMOTE_BLOCK_TIMEOUT_MS = 5_000;
6
8
  /** How long `follow` waits for a connected peer to report the length of the log. */
@@ -17,8 +19,9 @@ const BLOCK_OVERHEAD_BYTES = 1024;
17
19
  /** How many of the newest blocks of a teammate's log a lookup by id walks through at most. */
18
20
  const REMOTE_LOOKUP_BLOCKS = 100_000;
19
21
  /**
20
- * A block that is not a captured exchange. In a teammate's log only a changed client writes one; in this machine's
21
- * own log a newer CLI that ran on the same data directory may have (WebSocket messages, spec decision 135).
22
+ * A block that is not a captured exchange: a block of recorded WebSocket messages (spec decision 135), or one this
23
+ * CLI does not know. In a teammate's log only a changed client writes the latter; in this machine's own log a newer
24
+ * CLI that ran on the same data directory may have.
22
25
  */
23
26
  export class InvalidBlockError extends Error {
24
27
  index;
@@ -29,7 +32,7 @@ export class InvalidBlockError extends Error {
29
32
  }
30
33
  /**
31
34
  * The traffic log: an append-only Hypercore holding one CapturedExchange per
32
- * block. The core lives in a Corestore under a fixed name, so the same storage
35
+ * block, and the blocks of recorded WebSocket messages after their 101 exchange. The core lives in a Corestore under a fixed name, so the same storage
33
36
  * directory always reopens the same log (and the same key). A teammate's log
34
37
  * is opened by its key in the same Corestore and can only be read. Every
35
38
  * block is checked before it is used, in both logs, and a block that is not a
@@ -43,6 +46,7 @@ export class ExchangeLog {
43
46
  ownsStore;
44
47
  limits;
45
48
  listeners = new Set();
49
+ wsListeners = new Set();
46
50
  /** Blocks below this index were handed to the listeners or appended before anyone listened */
47
51
  delivered = 0;
48
52
  delivering = Promise.resolve();
@@ -57,8 +61,14 @@ export class ExchangeLog {
57
61
  unread = new Set();
58
62
  /** Lookups extend the id index one after the other; two at once would mix up the cursors */
59
63
  indexing = Promise.resolve();
60
- /** Blocks found not to be captured exchanges; a teammate's are not fetched again */
64
+ /** Blocks found to be neither an exchange nor recorded messages; a teammate's are not fetched again */
61
65
  invalid = new Set();
66
+ /** Blocks of recorded messages that were read or written, by index: the id of their 101 exchange */
67
+ messageBlocks = new Map();
68
+ /** The WebSockets whose messages were asked for, by the id of their 101 exchange */
69
+ sessions = new Map();
70
+ /** Reads for `wsMessages` run one after the other; two at once would read the same blocks twice */
71
+ scanning = Promise.resolve();
62
72
  /** What `follow` fetches ahead; null when it does not */
63
73
  following = null;
64
74
  /** Bytes of a teammate's log that arrived from peers in this run */
@@ -84,7 +94,7 @@ export class ExchangeLog {
84
94
  }
85
95
  };
86
96
  onAppend = () => {
87
- if (this.listeners.size === 0) {
97
+ if (this.listeners.size === 0 && this.wsListeners.size === 0) {
88
98
  return;
89
99
  }
90
100
  this.delivering = this.delivering.then(() => this.deliver());
@@ -92,7 +102,7 @@ export class ExchangeLog {
92
102
  constructor(
93
103
  /** The Corestore behind the log. Replicating it replicates every log opened in it. */
94
104
  store,
95
- /** Typed as the log's content; that only holds after `isCapturedExchange` */
105
+ /** Typed as the log's content; that only holds after `isCapturedExchange` or `isCapturedWsMessages` */
96
106
  core, ownsStore, limits = {}) {
97
107
  this.store = store;
98
108
  this.core = core;
@@ -151,8 +161,14 @@ export class ExchangeLog {
151
161
  get writable() {
152
162
  return this.core.writable;
153
163
  }
154
- async append(exchange) {
155
- const written = this.core.append(exchange).then(() => { });
164
+ /** Appends an exchange or a block of recorded WebSocket messages. */
165
+ async append(block) {
166
+ const written = this.core.append(block).then(({ length }) => {
167
+ if (isCapturedWsMessages(block)) {
168
+ // Known without reading it back: lists skip it, the messages of its WebSocket find it
169
+ this.messageBlocks.set(length - 1, block.exchangeId);
170
+ }
171
+ });
156
172
  this.appending.add(written);
157
173
  try {
158
174
  await written;
@@ -169,7 +185,7 @@ export class ExchangeLog {
169
185
  * that is not on this machine rejects at once.
170
186
  */
171
187
  async get(index, options = {}) {
172
- if (this.invalid.has(index)) {
188
+ if (this.invalid.has(index) || this.messageBlocks.has(index)) {
173
189
  // Not read again: it was looked at and left out
174
190
  throw new InvalidBlockError(index);
175
191
  }
@@ -187,11 +203,104 @@ export class ExchangeLog {
187
203
  block = await this.core.get(index, { timeout: REMOTE_BLOCK_TIMEOUT_MS });
188
204
  }
189
205
  if (!isCapturedExchange(block)) {
190
- this.discard(index);
206
+ this.sortOut(index, block);
191
207
  throw new InvalidBlockError(index);
192
208
  }
193
209
  return block;
194
210
  }
211
+ /**
212
+ * The blocks of recorded messages of one WebSocket, in seq order: the ones with a seq above `afterSeq`, at most
213
+ * WS_MESSAGES_PAGE_BLOCKS. `handshakeIndex` is the place of its 101 exchange; its blocks follow it. The log is
214
+ * read forward from there once, up to the block with the close, and what was read is remembered. In a teammate's
215
+ * log a block that does not arrive ends the read for this time; a later call goes on from there.
216
+ */
217
+ async wsMessages(exchangeId, handshakeIndex, afterSeq = -1) {
218
+ const scanned = this.scanning.then(() => this.scanSession(exchangeId, handshakeIndex));
219
+ // A read that failed (the core was closed) must not fail the ones after it
220
+ this.scanning = scanned.then(() => { }, () => { });
221
+ const session = await scanned;
222
+ const blocks = [];
223
+ for (const index of session.indexes) {
224
+ const block = await this.messageBlock(index);
225
+ if (block === null || block.exchangeId !== exchangeId || block.seq <= afterSeq) {
226
+ continue;
227
+ }
228
+ if (blocks.length === WS_MESSAGES_PAGE_BLOCKS) {
229
+ return { blocks, more: true };
230
+ }
231
+ blocks.push(block);
232
+ }
233
+ return { blocks, more: false };
234
+ }
235
+ async scanSession(exchangeId, handshakeIndex) {
236
+ let session = this.sessions.get(exchangeId);
237
+ if (session === undefined || session.scannedTo <= handshakeIndex) {
238
+ session = { indexes: [], scannedTo: handshakeIndex + 1, closed: false };
239
+ this.sessions.set(exchangeId, session);
240
+ }
241
+ const length = this.core.length;
242
+ while (!session.closed && session.scannedTo < length) {
243
+ const index = session.scannedTo;
244
+ let owner = this.messageBlocks.get(index);
245
+ if (owner === undefined && !this.invalid.has(index)) {
246
+ const block = await this.readStored(index);
247
+ if (block === undefined) {
248
+ // Not on this machine and did not arrive: read on from here next time
249
+ break;
250
+ }
251
+ if (isCapturedWsMessages(block)) {
252
+ owner = block.exchangeId;
253
+ }
254
+ else if (!isCapturedExchange(block)) {
255
+ this.sortOut(index, block);
256
+ }
257
+ }
258
+ if (owner === exchangeId) {
259
+ const block = await this.messageBlock(index);
260
+ if (block !== null) {
261
+ session.indexes.push(index);
262
+ session.closed = block.close !== undefined;
263
+ }
264
+ }
265
+ session.scannedTo = index + 1;
266
+ }
267
+ return session;
268
+ }
269
+ /** One block of recorded messages; null when the block is no such block or cannot be read. */
270
+ async messageBlock(index) {
271
+ const block = await this.readStored(index);
272
+ if (!isCapturedWsMessages(block)) {
273
+ return null;
274
+ }
275
+ this.messageBlocks.set(index, block.exchangeId);
276
+ return block;
277
+ }
278
+ /**
279
+ * A block as stored, whatever its kind. In a teammate's log a block that is not on this machine is waited for a
280
+ * few seconds; undefined when it does not arrive or cannot be decoded.
281
+ */
282
+ async readStored(index) {
283
+ try {
284
+ return this.core.writable
285
+ ? await this.core.get(index)
286
+ : await this.core.get(index, { timeout: REMOTE_BLOCK_TIMEOUT_MS });
287
+ }
288
+ catch (error) {
289
+ if (this.closed) {
290
+ throw error;
291
+ }
292
+ return undefined;
293
+ }
294
+ }
295
+ /** Remembers what a block that is no exchange is: recorded messages, or a block that is used nowhere. */
296
+ sortOut(index, block) {
297
+ if (isCapturedWsMessages(block)) {
298
+ this.messageBlocks.set(index, block.exchangeId);
299
+ }
300
+ else {
301
+ this.discard(index);
302
+ }
303
+ }
195
304
  /**
196
305
  * Reads one block of this machine's own log as it is stored, whatever its
197
306
  * kind: what `hopwire rotate` copies, so that blocks a newer CLI wrote
@@ -210,7 +319,7 @@ export class ExchangeLog {
210
319
  }
211
320
  /** Appends a block as it was read with `block`; for `hopwire rotate` only. */
212
321
  async appendBlock(block) {
213
- // The core is typed with the exchange shape; a copied block of another kind is stored as it came
322
+ // The core is typed with the shapes this CLI knows; a copied block of another kind is stored as it came
214
323
  await this.append(block);
215
324
  }
216
325
  /**
@@ -321,7 +430,7 @@ export class ExchangeLog {
321
430
  /** Puts the id of one block into the index. Never waits for a peer and never fails on what a block holds. */
322
431
  async index(index) {
323
432
  let block;
324
- if (this.invalid.has(index)) {
433
+ if (this.invalid.has(index) || this.messageBlocks.has(index)) {
325
434
  return;
326
435
  }
327
436
  else if (this.core.writable) {
@@ -345,7 +454,7 @@ export class ExchangeLog {
345
454
  this.ids.set(block.id, index);
346
455
  }
347
456
  else {
348
- this.discard(index);
457
+ this.sortOut(index, block);
349
458
  }
350
459
  }
351
460
  /**
@@ -366,19 +475,31 @@ export class ExchangeLog {
366
475
  * function that ends the subscription.
367
476
  */
368
477
  subscribe(listener) {
369
- if (this.listeners.size === 0) {
370
- this.delivered = this.core.length;
371
- }
478
+ this.startDelivering();
372
479
  this.listeners.add(listener);
373
480
  return () => {
374
481
  this.listeners.delete(listener);
375
482
  };
376
483
  }
484
+ /** Like `subscribe`, for the blocks of recorded WebSocket messages. */
485
+ subscribeWsMessages(listener) {
486
+ this.startDelivering();
487
+ this.wsListeners.add(listener);
488
+ return () => {
489
+ this.wsListeners.delete(listener);
490
+ };
491
+ }
492
+ startDelivering() {
493
+ if (this.listeners.size === 0 && this.wsListeners.size === 0) {
494
+ this.delivered = this.core.length;
495
+ }
496
+ }
377
497
  async close() {
378
498
  // An exchange that was answered and is on its way into the log is written before the log closes
379
499
  await Promise.allSettled([...this.appending]);
380
500
  this.closed = true;
381
501
  this.listeners.clear();
502
+ this.wsListeners.clear();
382
503
  this.core.off('append', this.onAppend);
383
504
  this.core.off('download', this.onDownload);
384
505
  this.following?.destroy();
@@ -392,7 +513,10 @@ export class ExchangeLog {
392
513
  }
393
514
  async deliver() {
394
515
  // A teammate's log past its budget is not fetched any more, block by block for the listeners neither
395
- while (!this.closed && !this.overBudget && this.listeners.size > 0 && this.delivered < this.core.length) {
516
+ while (!this.closed &&
517
+ !this.overBudget &&
518
+ (this.listeners.size > 0 || this.wsListeners.size > 0) &&
519
+ this.delivered < this.core.length) {
396
520
  const index = this.delivered;
397
521
  let block;
398
522
  try {
@@ -407,6 +531,18 @@ export class ExchangeLog {
407
531
  block = null;
408
532
  }
409
533
  this.delivered = index + 1;
534
+ if (isCapturedWsMessages(block)) {
535
+ this.messageBlocks.set(index, block.exchangeId);
536
+ for (const listener of this.wsListeners) {
537
+ try {
538
+ listener(index, block);
539
+ }
540
+ catch {
541
+ // One failing listener must not keep the block from the others
542
+ }
543
+ }
544
+ continue;
545
+ }
410
546
  if (!this.usable(block)) {
411
547
  this.discard(index);
412
548
  continue;