diff --git a/README.md b/README.md index 98b68474..97cc54e5 100644 --- a/README.md +++ b/README.md @@ -437,6 +437,7 @@ The daemon routes `POST /tool/:name` requests through the registry, applies Zod | `mock_network` | Adds, clears, lists, and inspects targeted Playwright network mocks on the active browser context. Unmatched same-origin requests are continued unchanged. A rule with `record` and no `response` records the real request and forwards it unchanged. Rules can opt in to record request bodies and headers (redacted). | | `events` | Bookmarks or clears the session event buffer that `mm logs` and `mm network` read: `mark` returns the current cursor (one cursor for both) and `summary.startedAt`; `clear` empties it without resetting the cursor. The buffer starts with a browser session and keeps the newest 1000 console and 2000 network records. Browser only. | | `logs` | Read-only. Console errors and uncaught exceptions of every page and the Extension service worker, from the session event buffer: `{ records, cursor, hasMore, gap, summary }`, oldest first, with `cursor`/`since`/`limit`/`grep`. Records `error` only by default; `configure` widens the levels for the session (`warn` is accepted as `warning`). Object and array arguments are rendered from their CDP preview (a sensitive property name prints `[REDACTED]`), and a leading format string fills its `%s`/`%d`/`%o` specifiers. URLs in the text and the values of sensitive object fields (`privateKey`, `mnemonic`, `password`, …) are redacted; plain string contents are not scanned (JWTs and `Bearer` tokens excepted). Text is cut at 2000 characters. Browser only. | +| `network` | Read-only, passive. HTTP(S) requests of every page and the Extension service worker, from the session event buffer: one record per request with method, redacted URL, type, status, duration (`ms`), `failure`, JSON-RPC `rpcMethods` and, after `configure` with `rpcErrors`, the JSON-RPC `rpcError`. Filters: `cursor`, `since`, `limit`, `url` (glob or text), `errors`, `settled`; a filtered or `settled` read returns settled requests only, ordered by `settledSeq`. Never routes or changes a request; no bodies are stored. Browser only. | | `cdp` | Sends a raw Chrome DevTools Protocol command, dispatched through the active platform driver. **Browser:** targets the active page (`target: "page"`, default) or the Extension service worker (`target: "sw"`) on a persistent CDP session shared across calls, so enabled domains and listeners survive; `fresh: true` uses a one-shot session. Full Runtime/DOM/Network/Page surface; destructive methods (`Browser.close`, `Target.closeTarget`, etc.) are blocked. **Mobile (iOS/Android):** targets the app's React Native Hermes JS runtime via Metro's inspector proxy (delegates to `@metamask/device-mcp`, needs a DEBUG build with Metro running); only the JS-engine subset exists (`Runtime`, `Debugger`, `Log`, `HeapProfiler` — no DOM/Page/Network) and `Runtime.terminateExecution` / `Inspector.detached` are blocked. Optional `metroPort` / `appId` are mobile-only (ignored on browser). Categorized as `cdp`: no observation is collected and refs are not refreshed, so run `describe_screen` after a call that changes state. See [Browser vs Mobile CDP](#browser-vs-mobile-hermes-cdp). | | **Hermes (mobile only)** | | | `hermes_targets` | Lists and diagnoses the debuggable Hermes targets Metro exposes (iOS and Android), reporting which target would be chosen or why selection is ambiguous. Use to confirm Metro is running and the app is registered. Pass `all` to bypass the appId filter and discover the real appId. Mobile only — there is no browser equivalent. | @@ -681,17 +682,19 @@ mm describe-screen ### Advanced -| Command | Description | -| ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `mm mock-network add ''` | Adds targeted route mocks during an active session. Pass either a single rule, an array of rules, or an object with a `routes` array. Add `"record":{"body":true}` to a rule to record the bodies of the requests it matches. A rule with `record` and no `response` forwards the real request unchanged. | -| `mm mock-network clear` | Clears route mocks and recorded requests. | -| `mm mock-network list` | Lists active route mocks. | -| `mm mock-network requests [--limit ] [--url ] [--bodies]` | Shows recorded matched and missed requests. `--url` keeps only matching URLs. `--bodies` adds the recorded (redacted) request bodies and headers. | -| `mm events mark` | Returns the current cursor of the session event buffer and `summary.startedAt`. Take it at the start of a flow and pass it to `mm logs` / `mm network` at the end. Browser only. | -| `mm events clear [--kind console\|network]` | Empties the session event buffer (one kind or all). The cursor keeps counting, so older cursors stay valid. | -| `mm logs [--cursor \| --since ] [--limit ] [--grep ]` | Console errors and uncaught exceptions of every page and the Extension service worker since the cursor. Read again with the returned `cursor` while `hasMore`; `gap: true` also means the cursor is from an earlier session (the read restarts from the oldest record). `--grep` is a case-sensitive JavaScript regex of at most 256 characters; the pattern runs in the daemon, so avoid nested quantifiers such as `(a+)+`; a value that starts with `--` must be escaped (`--grep '\-\-x'`). Browser only. | -| `mm logs configure --levels ` | Changes the recorded console levels for the session (default `error`; `warn` is accepted as `warning`). Only `--levels ` is accepted; any other flag or a second `--levels` is a usage error. | -| `mm cdp [params-json] [--timeout ] [--target page\|sw\|hermes\|android-webview] [--fresh] [--metro-port

] [--app-id ]` | Sends a raw Chrome DevTools Protocol command against the active session. Escape hatch for when structured tools are insufficient. Works on both browser and mobile — the target runtime and blocked methods differ by platform (see below). Browser targets are the active page (`page`, default) and the Extension service worker (`sw`); `--fresh` uses a one-shot session. On mobile the session keeps the `--metro-port` given to `mm launch`, so later calls use it; a per-call `--metro-port` is only an override. | +| Command | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `mm mock-network add ''` | Adds targeted route mocks during an active session. Pass either a single rule, an array of rules, or an object with a `routes` array. Add `"record":{"body":true}` to a rule to record the bodies of the requests it matches. A rule with `record` and no `response` forwards the real request unchanged. | +| `mm mock-network clear` | Clears route mocks and recorded requests. | +| `mm mock-network list` | Lists active route mocks. | +| `mm mock-network requests [--limit ] [--url ] [--bodies]` | Shows recorded matched and missed requests. `--url` keeps only matching URLs. `--bodies` adds the recorded (redacted) request bodies and headers. | +| `mm events mark` | Returns the current cursor of the session event buffer and `summary.startedAt`. Take it at the start of a flow and pass it to `mm logs` / `mm network` at the end. Browser only. | +| `mm events clear [--kind console\|network]` | Empties the session event buffer (one kind or all). The cursor keeps counting, so older cursors stay valid. | +| `mm logs [--cursor \| --since ] [--limit ] [--grep ]` | Console errors and uncaught exceptions of every page and the Extension service worker since the cursor. Read again with the returned `cursor` while `hasMore`; `gap: true` also means the cursor is from an earlier session (the read restarts from the oldest record). `--grep` is a case-sensitive JavaScript regex of at most 256 characters; the pattern runs in the daemon, so avoid nested quantifiers such as `(a+)+`; a value that starts with `--` must be escaped (`--grep '\-\-x'`). Browser only. | +| `mm logs configure --levels ` | Changes the recorded console levels for the session (default `error`; `warn` is accepted as `warning`). Only `--levels ` is accepted; any other flag or a second `--levels` is a usage error. | +| `mm network [--cursor \| --since ] [--limit ] [--url ] [--errors] [--settled]` | HTTP(S) requests of every page and the Extension service worker since the cursor: status, `ms`, `failure`, `rpcMethods`. `--errors` keeps status >= 400, failures and `rpcError`. An unfiltered read returns every record in start order, pending requests included. A filtered read (`--url`, `--errors`) returns only settled requests, in `settledSeq` order, so a request that becomes a match when it ends is returned once by the next read, even when it started before the cursor; `--settled` does the same without a filter, for the end of a step. `--since` compares the request start (`t`). A request whose page or worker goes away is finalized with `failure: "target closed"`; one dropped from the pending limit as `"abandoned"`. Requests during `mm launch` are not recorded. Browser only. | +| `mm network configure --rpc-errors \| --no-rpc-errors` | Reads JSON-RPC response bodies (up to 64 KiB decoded, 8 at a time) and records their `error` as `rpcError`. Off by default. | +| `mm cdp [params-json] [--timeout ] [--target page\|sw\|hermes\|android-webview] [--fresh] [--metro-port

] [--app-id ]` | Sends a raw Chrome DevTools Protocol command against the active session. Escape hatch for when structured tools are insufficient. Works on both browser and mobile — the target runtime and blocked methods differ by platform (see below). Browser targets are the active page (`page`, default) and the Extension service worker (`sw`); `--fresh` uses a one-shot session. On mobile the session keeps the `--metro-port` given to `mm launch`, so later calls use it; a per-call `--metro-port` is only an override. | ```bash mm cdp Runtime.evaluate '{"expression":"document.title"}' diff --git a/SKILL.md b/SKILL.md index f7d3c490..c4a83a15 100644 --- a/SKILL.md +++ b/SKILL.md @@ -42,7 +42,7 @@ The default depends on the tool's category: | Category | Examples | Default `observe` | | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | | **Mutating** | click, type, navigate, reload, launch, cleanup, build, clipboard, mock_network, scroll_to_element, device_swipe, long_press, tap_coordinates, dismiss_keyboard, dismiss_alert, open_app, close_app, press_button, device_context, device_clipboard | `diff` | -| **Read-only** | get_state, get_text, inspect, get_context, set_context, events, logs, get_alert_text, screen_recording, device_logs, generate_locators, hermes_targets | `none` | +| **Read-only** | get_state, get_text, inspect, get_context, set_context, events, logs, network, get_alert_text, screen_recording, device_logs, generate_locators, hermes_targets | `none` | | **Discovery** | describe_screen, list_testids, accessibility_snapshot, screenshot (data is already in `result`) | `none` | | **CDP** | cdp | `none` | | **Batch** | run_steps | `diff` | @@ -759,7 +759,7 @@ Returns `{ cursor, summary }`. Take it at the start of a flow. Empties the buffer (one kind or all). The cursor keeps counting, so older cursors stay valid. -`summary` is `{ startedAt, seq, counts: { console, network }, dropped: { console, network }, captureErrors, lastCaptureError? }`. `startedAt` (epoch ms) changes when the session is relaunched; `seq` then starts at 1 again. The buffer keeps the newest 1000 console and 2000 network records; older ones are dropped and counted. `captureErrors` counts the times the session could not listen to a page or the service worker (for example a target that did not answer within 5 s, or a domain that could not be enabled); `lastCaptureError` is the newest one, redacted. When it grows during a flow, events of that target can be missing. A call that starts the recording waits at most 5 s for a target that does not answer. +`summary` is `{ startedAt, seq, counts: { console, network }, dropped: { console, network }, captureErrors, lastCaptureError? }`. `startedAt` (epoch ms) changes when the session is relaunched; `seq` then starts at 1 again. Every appended record and every settled network request (a request that ended) takes the next `seq`, so `seq` can skip values. The buffer keeps the newest 1000 console and 2000 network records; older ones are dropped and counted. `captureErrors` counts the times the session could not listen to a page or the service worker (for example a target that did not answer within 5 s, or a domain that could not be enabled); `lastCaptureError` is the newest one, redacted. When it grows during a flow, events of that target can be missing. A call that starts the recording waits at most 5 s for a target that does not answer. #### `mm logs [--cursor | --since ] [--limit ] [--grep ]` @@ -784,6 +784,62 @@ Console errors and uncaught exceptions of every page and the Extension service w Only `error` (including `console.assert` and uncaught exceptions) is recorded by default. `mm logs configure --levels error,warning` records more levels from then on, for this session (`warn` is accepted as `warning`). Non-error objects and arrays are rendered from their CDP preview (`{message: 'User rejected', chainId: 1}`, `[1, 2]`); a named property of an array prints as `name: value`, and a sensitive property name prints `[REDACTED]`. A leading format string fills `%s`, `%d`, `%i`, `%f`, `%o`, `%O`, `%c` from its arguments. `mm logs configure` accepts only `--levels `: any other flag or a second `--levels` is a usage error. +#### `mm network [--cursor | --since ] [--limit ] [--url ] [--errors] [--settled]` + +HTTP(S) requests of every page and the Extension service worker (gas, security alerts, bridge, RPC: most Extension traffic comes from the worker). It only listens: it never mocks, blocks or changes a request, and it stores no bodies (use `mm mock-network` for that). One record per request, created when it starts and updated in place when it ends; it keeps its first `seq` and gets a `settledSeq` when it ends. Same paging as `mm logs`, plus `stats: { pending, ignored, rpcErrorsSkipped }`. A request whose page or worker goes away before it ends is finalized with `failure: "target closed"`; one dropped from the pending limit is finalized with `failure: "abandoned"`. + +```json +{ + "seq": 6, + "settledSeq": 11, + "t": 1795430400608, + "target": { + "kind": "sw", + "id": "A51F9577…", + "url": "chrome-extension://…/scripts/app-init.js" + }, + "method": "POST", + "url": "https://mainnet.infura.io/v3/[REDACTED]", + "type": "fetch", + "status": 200, + "ms": 42, + "rpcMethods": ["eth_call"], + "rpcError": { "code": -32000, "message": "execution reverted" } +} +``` + +| Field | Description | +| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `settledSeq` | Position when the request became final: it ended, with its `rpcError` read when configured. Absent while pending | +| `t` | Request start, epoch ms | +| `url` | Redacted: API keys in the host or path (such as Infura IDs), credentials, and `key`/`token`/`apiKey`-like params | +| `type` | `fetch`, `xhr`, `document`, `script`, … | +| `status` | HTTP status. Absent while pending and when the request failed before a response; a request that fails after its response keeps it | +| `ms` | Start to end of the response or the failure. Absent while pending | +| `failure` | Set when the request fails, before or after its response: for example `net::ERR_ABORTED`, `net::ERR_NAME_NOT_RESOLVED`, `net::ERR_FAILED (cors: …)`, `target closed`, or `abandoned` | +| `rpcMethods` | JSON-RPC methods of the request body; always an array (a batch lists its methods in order) | +| `rpcError` | `{ code, message }` of a JSON-RPC error response. Only after `mm network configure --rpc-errors` | + +`--url` takes a glob (`*`, `**`) or plain text the URL must contain. `--errors` keeps status >= 400, `failure` and `rpcError`. Only `http(s)` requests are recorded (`stats.ignored` counts the rest). A redirect gives one record per hop. + +An unfiltered read returns every record in start order (`seq`), pending requests included, and the cursor moves past all of them. A filtered read (`--url`, `--errors`) returns only **settled** requests, in `settledSeq` order: a request may become a match only when it ends (a 404, a failure, an `rpcError`), so it is returned by the read that follows its end, once, even when it started before the cursor. `--settled` asks for that same settle-order read without a filter: at the end of a step, read `--settled --cursor ` to get the final status of every request that finished since the mark, including ones started earlier; requests still open are not returned yet. An unsettled request is never returned by a filtered or `--settled` read, so a request that never ends never matches one. In every case `--since` compares the request start (`t`), not when it ended. A cursor from a filtered or `--settled` read continues reads of the same mode; for an unfiltered read, use a cursor from `mm events mark` or an unfiltered read. + +`mm network configure --rpc-errors` reads the body of each JSON-RPC response (up to 64 KiB decoded, at most 8 at a time) and records its `error`; `stats.rpcErrorsSkipped` counts the bodies that were too large, too many at once or gone. The decoded size comes from `Network.dataReceived` when Chrome reports it; without those events the compressed `encodedDataLength` is used, which can undercount. `Network.enable` gets small response-buffer limits, since no bodies are kept otherwise. `--no-rpc-errors` turns it off. + +The session holds `Network` and `Runtime` enabled on every page and on the service worker from `mm launch` on. `mm cdp Network.enable` (no params) still succeeds and sends nothing; `mm cdp Network.disable`, or a `Network.enable` with other params, is refused with `MM_CDP_BLOCKED`, because it would stop or change what `mm network` records. Use `--fresh` for those. + +#### Per-flow recipe + +```bash +mm events mark # {"cursor":120,"summary":{"startedAt":1795430400000,...}} +# ...run the flow... +mm network --settled --cursor 120 # final status of every request that ended since the mark +mm network --cursor 120 # repeat with the returned cursor while hasMore is true +mm logs --cursor 120 +``` + +Compare `summary.startedAt` of each read with the one from `mark`. If it changed, the session was relaunched: read again from `--cursor 0` and record a capture gap for the flow. Also record a gap when a read returns `gap: true`. Requests sent during `mm launch` itself are not recorded. + ### Mobile device actions (iOS/Android only) These commands require a mobile session (`mm launch --platform ios|android`). On a browser diff --git a/src/cli/mm.test.ts b/src/cli/mm.test.ts index 99098bbf..9b85c258 100644 --- a/src/cli/mm.test.ts +++ b/src/cli/mm.test.ts @@ -1059,6 +1059,7 @@ describe('printHelp', () => { expect(output).toContain('MM_PRETTY'); expect(output).toContain('mm events mark'); expect(output).toContain('mm logs configure --levels'); + expect(output).toContain('mm network configure --rpc-errors'); }); }); @@ -3236,6 +3237,7 @@ describe('routeCommand', () => { [['--grep', '--cursor', '1']], [['--grap', 'x']], [['--levels', 'warning']], + [['--error']], [['configure']], [['configure', '--levels', ',']], [['configure', '--levels', 'warning', '--cursor', '1']], @@ -3249,6 +3251,74 @@ describe('routeCommand', () => { expectFailure(expect.stringContaining('Usage: mm logs'), 2); }); + it('routes network with read flags', async () => { + await routeCommand( + 'network', + [ + '--cursor', + '3', + '--url', + 'https://*.api.cx.metamask.io/**', + '--errors', + '--settled', + '--since', + '1700000000000', + ], + 3000, + ); + expect(globalThis.fetch).toHaveBeenLastCalledWith( + 'http://127.0.0.1:3000/tool/network', + expect.objectContaining({ + body: JSON.stringify({ + cursor: 3, + url: 'https://*.api.cx.metamask.io/**', + errors: true, + settled: true, + since: '1700000000000', + }), + }), + ); + await routeCommand('network', [], 3000); + expect(globalThis.fetch).toHaveBeenLastCalledWith( + 'http://127.0.0.1:3000/tool/network', + expect.objectContaining({ body: JSON.stringify({}) }), + ); + }); + + it('routes network configure', async () => { + await routeCommand('network', ['configure', '--rpc-errors'], 3000); + expect(globalThis.fetch).toHaveBeenLastCalledWith( + 'http://127.0.0.1:3000/tool/network', + expect.objectContaining({ + body: JSON.stringify({ action: 'configure', rpcErrors: true }), + }), + ); + await routeCommand('network', ['configure', '--no-rpc-errors'], 3000); + expect(globalThis.fetch).toHaveBeenLastCalledWith( + 'http://127.0.0.1:3000/tool/network', + expect.objectContaining({ + body: JSON.stringify({ action: 'configure', rpcErrors: false }), + }), + ); + }); + + it.each([ + [['--url']], + [['--cursor', 'abc']], + [['--error']], + [['--errors', 'true']], + [['--settled', 'true']], + [['configure']], + [['configure', '--rpc-errors', '--no-rpc-errors']], + [['configure', '--rpc-errors', 'extra']], + [['requests']], + ])('exits on bad network arguments %j', async (args) => { + await expect(routeCommand('network', args, 3000)).rejects.toThrowError( + 'process.exit', + ); + expectFailure(expect.stringContaining('Usage: mm network'), 2); + }); + it('exits when mock-network has an unknown action', async () => { await expect( routeCommand('mock-network', ['unknown'], 3000), diff --git a/src/cli/mm.ts b/src/cli/mm.ts index a43456bd..3af9f996 100644 --- a/src/cli/mm.ts +++ b/src/cli/mm.ts @@ -1019,6 +1019,10 @@ export async function routeCommand( await routeLogsCommand(args, daemon); break; } + case 'network': { + await routeNetworkCommand(args, daemon); + break; + } case 'cdp': { const cdpMethod = args[0]; if (!cdpMethod) { @@ -1372,28 +1376,38 @@ const LOGS_USAGE = ' mm logs configure --levels '; /** - * Parses the read flags shared by `mm logs` and `mm network`. + * Parses the read flags shared by `mm logs` and `mm network`. Unknown flags, + * missing values and stray arguments are usage errors. * * @param args - CLI arguments. * @param usage - The usage text to print on a bad flag. * @param stringFlags - Extra flags that take a string value. + * @param booleanFlags - Extra flags that take no value. * @returns The read options for the tool. */ export function parseEventReadArgs( args: string[], usage: string, stringFlags: readonly string[] = [], + booleanFlags: readonly string[] = [], ): Record { const integerFlags = new Set(['--cursor', '--limit']); const textFlags = new Set(['--since', ...stringFlags]); + const booleans = new Set(booleanFlags); const options: Record = {}; - // Every flag takes one value, so the arguments come in flag/value pairs. - // Reject anything else: a mistyped flag must not be silently ignored. - for (let index = 0; index < args.length; index += 2) { + // Every flag takes one value, or none for a boolean flag. Reject anything + // else: a mistyped flag must not be silently ignored. + for (let index = 0; index < args.length; index += 1) { const flag = args[index]; + if (flag === undefined) { + failUsage(usage); + } + if (booleans.has(flag)) { + options[flag.slice(2)] = true; + continue; + } const value = args[index + 1]; if ( - flag === undefined || (!integerFlags.has(flag) && !textFlags.has(flag)) || value === undefined || value.startsWith('--') @@ -1410,6 +1424,7 @@ export function parseEventReadArgs( } else { options[flag.slice(2)] = value; } + index += 1; } return options; } @@ -1458,6 +1473,49 @@ export async function routeLogsCommand( ); } +const NETWORK_USAGE = + 'Usage: mm network [--cursor | --since ] [--limit ] [--url ] [--errors] [--settled]\n' + + ' mm network configure --rpc-errors | --no-rpc-errors'; + +/** + * Routes `mm network` to the daemon. + * + * @param args - CLI arguments after `network`. + * @param daemon - The daemon endpoint (a port or the daemon state). + */ +export async function routeNetworkCommand( + args: string[], + daemon: DaemonEndpoint, +): Promise { + if (args[0] === 'configure') { + const rest = args.slice(1); + const on = rest.length === 1 && rest[0] === '--rpc-errors'; + const off = rest.length === 1 && rest[0] === '--no-rpc-errors'; + if (on === off) { + failUsage(NETWORK_USAGE); + } + await sendRequest(daemon, 'POST', '/tool/network', { + action: 'configure', + rpcErrors: on, + }); + return; + } + if (args[0] !== undefined && !args[0].startsWith('--')) { + failUsage(NETWORK_USAGE); + } + await sendRequest( + daemon, + 'POST', + '/tool/network', + parseEventReadArgs( + args, + NETWORK_USAGE, + ['--url'], + ['--errors', '--settled'], + ), + ); +} + /** * Checks whether a failed request is safe to send again: only a refused * connection (`ECONNREFUSED`), because the daemon never accepted the request. @@ -2361,6 +2419,14 @@ Session events (browser only; recorded from launch on, not during it): again with the returned cursor while hasMore. mm logs configure --levels Levels to record from now on (default: error). + mm network [--cursor | --since ] [--limit ] [--url ] [--errors] [--settled] + HTTP(S) requests of every page and the Extension + service worker: status, ms, failure, rpcMethods. + --errors: status >= 400, failure or rpcError. + --settled: only requests that ended after the cursor, + in settle order (no filter needed). + mm network configure --rpc-errors | --no-rpc-errors + Read JSON-RPC response bodies for rpcError (off). Mobile (iOS/Android only): mm device-swipe [--startX ] [--startY ] [--distance ] diff --git a/src/events/console-source.test.ts b/src/events/console-source.test.ts index e8d7c05e..13a0fff6 100644 --- a/src/events/console-source.test.ts +++ b/src/events/console-source.test.ts @@ -594,7 +594,7 @@ describe('ConsoleSource', () => { 'a1', ]); - events.config = { consoleLevels: ['error', 'warning'] }; + events.config = { consoleLevels: ['error', 'warning'], rpcErrors: false }; emit( consoleEvent('warning', [{ type: 'string', value: 'w2' }], { timestamp: now + 1, diff --git a/src/events/event-buffer.test.ts b/src/events/event-buffer.test.ts index 6577226a..0511b22d 100644 --- a/src/events/event-buffer.test.ts +++ b/src/events/event-buffer.test.ts @@ -221,6 +221,289 @@ describe('EventBuffer', () => { expect(firstPage.cursor).toBe(1); }); + it('returns a record that settled after the cursor even when it started before it', () => { + const buffer = new EventBuffer(); + const old = add(buffer, 'network', 'old'); // seq 1 + const recent = add(buffer, 'network', 'recent'); // seq 2 + buffer.settle('network', recent); // settledSeq 3 + + const first = buffer.read({ + kind: 'network', + settled: true, + limit: 10, + }); + expect(first.records.map((record) => record.name)).toStrictEqual([ + 'recent', + ]); + expect(first.cursor).toBe(3); + + // The older record ends late: it settles above the returned cursor and + // is returned by the next read, once. + old.status = 500; + buffer.settle('network', old); // settledSeq 4 + buffer.settle('network', old); + const second = buffer.read({ + kind: 'network', + settled: true, + cursor: first.cursor, + limit: 10, + }); + expect( + second.records.map((record) => [record.name, record.status]), + ).toStrictEqual([['old', 500]]); + expect(second.cursor).toBe(4); + + expect( + buffer.read({ + kind: 'network', + settled: true, + cursor: second.cursor, + limit: 10, + }).records, + ).toStrictEqual([]); + }); + + it('reads settled records in settle order, not start order', () => { + const buffer = new EventBuffer(); + const a = add(buffer, 'network', 'a'); // seq 1 + const b = add(buffer, 'network', 'b'); // seq 2 + const c = add(buffer, 'network', 'c'); // seq 3 + buffer.settle('network', c); // settledSeq 4 + buffer.settle('network', b); // settledSeq 5 + buffer.settle('network', a); // settledSeq 6 + + const page = buffer.read({ + kind: 'network', + settled: true, + limit: 10, + }); + expect(page.records.map((record) => record.name)).toStrictEqual([ + 'c', + 'b', + 'a', + ]); + expect( + page.records.map( + (record) => (record as TestRecord & { settledSeq?: number }).settledSeq, + ), + ).toStrictEqual([4, 5, 6]); + }); + + it('pages a settled read by settle position', () => { + const buffer = new EventBuffer(); + const a = add(buffer, 'network', 'a'); + const b = add(buffer, 'network', 'b'); + const c = add(buffer, 'network', 'c'); + buffer.settle('network', b); // settledSeq 4 + buffer.settle('network', c); // settledSeq 5 + buffer.settle('network', a); // settledSeq 6 + + const first = buffer.read({ + kind: 'network', + settled: true, + limit: 2, + }); + expect(first.records.map((record) => record.name)).toStrictEqual([ + 'b', + 'c', + ]); + expect(first).toMatchObject({ cursor: 5, hasMore: true }); + + const second = buffer.read({ + kind: 'network', + settled: true, + cursor: first.cursor, + limit: 2, + }); + expect(second.records.map((record) => record.name)).toStrictEqual(['a']); + expect(second).toMatchObject({ cursor: 6, hasMore: false }); + + // `limit` is clamped the same way. + const clamped = buffer.read({ + kind: 'network', + settled: true, + limit: 0, + }); + expect(clamped.records).toHaveLength(1); + expect(clamped.hasMore).toBe(true); + }); + + it('reports a gap for a settled read only when a settled record after the cursor was dropped', () => { + const buffer = new EventBuffer({ capacity: { network: 1 } }); + const a = add(buffer, 'network', 'a'); // seq 1 + buffer.settle('network', a); // settledSeq 2 + const b = add(buffer, 'network', 'b'); // seq 3, drops a + + const fromStart = buffer.read({ + kind: 'network', + settled: true, + limit: 10, + }); + expect(fromStart.records).toStrictEqual([]); + expect(fromStart.gap).toBe(true); + + // A cursor at or above the dropped settle position is not a gap. + expect( + buffer.read({ + kind: 'network', + settled: true, + cursor: 2, + limit: 10, + }).gap, + ).toBe(false); + + buffer.settle('network', b); // settledSeq 4 + const next = buffer.read({ + kind: 'network', + settled: true, + cursor: 3, + limit: 10, + }); + expect(next.records.map((record) => record.name)).toStrictEqual(['b']); + expect(next.gap).toBe(false); + }); + + it('reports a gap for a settled read when an unsettled record was dropped', () => { + const buffer = new EventBuffer({ capacity: { network: 1 } }); + add(buffer, 'network', 'open'); // seq 1, never settles + const kept = add(buffer, 'network', 'kept'); // seq 2, drops the open one + + const page = buffer.read({ + kind: 'network', + settled: true, + limit: 10, + }); + expect(page.records).toStrictEqual([]); + // The open record could have matched once settled, so it is a gap. + expect(page.gap).toBe(true); + + buffer.settle('network', kept); // settledSeq 3 + const next = buffer.read({ + kind: 'network', + settled: true, + cursor: 2, + limit: 10, + }); + expect(next.records.map((record) => record.name)).toStrictEqual(['kept']); + expect(next.gap).toBe(false); + }); + + it('does not report a settled gap for a dropped record before since', () => { + const buffer = new EventBuffer({ capacity: { network: 2 } }); + const first = add(buffer, 'network', 'first', 0); + const second = add(buffer, 'network', 'second', 1); + buffer.settle('network', first); + buffer.settle('network', second); + add(buffer, 'network', 'third', 2); // seq 5, drops `first` + + // `first` (t=0) was dropped; a read from t=100 cannot see it anyway. + const since = buffer.read({ + kind: 'network', + settled: true, + since: 100, + limit: 10, + }); + expect(since.records).toStrictEqual([]); + expect(since.gap).toBe(false); + + const all = buffer.read({ + kind: 'network', + settled: true, + limit: 10, + }); + expect(all.gap).toBe(true); + }); + + it('does not settle a record the buffer dropped or cleared', () => { + const buffer = new EventBuffer({ capacity: { network: 1 } }); + const dropped = add(buffer, 'network', 'dropped'); // seq 1 + const kept = add(buffer, 'network', 'kept'); // seq 2, drops the first + buffer.settle('network', dropped); + expect( + (dropped as TestRecord & { settledSeq?: number }).settledSeq, + ).toBeUndefined(); + + // No position is burnt for the dropped record. + buffer.settle('network', kept); + expect((kept as TestRecord & { settledSeq?: number }).settledSeq).toBe(3); + + const cleared = add(buffer, 'network', 'cleared'); // seq 4, drops kept + buffer.clear('network'); + buffer.settle('network', cleared); + expect( + (cleared as TestRecord & { settledSeq?: number }).settledSeq, + ).toBeUndefined(); + }); + + it('reads settled records from a stale cursor with a gap', () => { + const buffer = new EventBuffer(); + const a = add(buffer, 'network', 'a'); // seq 1 + buffer.settle('network', a); // settledSeq 2 + + const page = buffer.read({ + kind: 'network', + settled: true, + cursor: 50, + limit: 10, + }); + expect(page.records.map((record) => record.name)).toStrictEqual(['a']); + expect(page.gap).toBe(true); + expect(page.cursor).toBe(2); + }); + + it('filters a settled read by t, the request start', () => { + const buffer = new EventBuffer(); + const a = add(buffer, 'network', 'a', 100); + buffer.settle('network', a); // settledSeq 2 + + expect( + buffer.read({ + kind: 'network', + settled: true, + since: 200, + limit: 10, + }).records, + ).toStrictEqual([]); + expect( + buffer + .read({ + kind: 'network', + settled: true, + since: 100, + limit: 10, + }) + .records.map((record) => record.name), + ).toStrictEqual(['a']); + }); + + it('keeps one cursor across kinds, so a mark continues a settled read', () => { + const buffer = new EventBuffer(); + const log = add(buffer, 'console', 'log'); // seq 1 + const request = add(buffer, 'network', 'request'); // seq 2 + buffer.settle('network', request); // settledSeq 3 + + // A cursor taken before the request settled (`mm events mark`). + const page = buffer.read({ + kind: 'network', + settled: true, + cursor: log.seq, + limit: 10, + }); + expect(page.records.map((record) => record.name)).toStrictEqual([ + 'request', + ]); + + // Its cursor is a buffer position, valid for another kind too. + const later = add(buffer, 'console', 'later'); // seq 4 + const logs = buffer.read({ + kind: 'console', + cursor: page.cursor, + limit: 10, + }); + expect(logs.records.map((record) => record.name)).toStrictEqual(['later']); + expect(later.seq).toBe(4); + }); + it('clamps a limit below one to one record', () => { const buffer = new EventBuffer(); add(buffer, 'console', 'a'); diff --git a/src/events/event-buffer.ts b/src/events/event-buffer.ts index 62e49537..4ae7821e 100644 --- a/src/events/event-buffer.ts +++ b/src/events/event-buffer.ts @@ -16,7 +16,7 @@ export const EVENT_KINDS: readonly EventKind[] = ['console', 'network']; /** Options for {@link EventBuffer.read}. */ export type EventReadOptions = { kind: EventKind; - /** Only records with a `seq` above this (from `mark` or an earlier read). */ + /** Only records with a position above this (from `mark` or an earlier read). */ cursor?: number; /** Only records with `t` at or after this, epoch ms. */ since?: number; @@ -24,6 +24,14 @@ export type EventReadOptions = { limit: number; /** Only records this returns true for. */ filter?: (record: RecordType) => boolean; + /** + * Only records the source has settled (no field changes any more), in + * settle order; `cursor` is then a settle position. A record that + * settles after a read is returned by a later read, also when it started + * before the cursor. Used by `mm network` with a filter, where a request + * may become a match only when it ends. + */ + settled?: boolean; }; type KindState = { @@ -34,8 +42,15 @@ type KindState = { lastDroppedSeq: number; /** Largest `t` of a dropped record, 0 when none. */ lastDroppedT: number; + /** `settledSeq` of the newest dropped settled record, 0 when none. */ + lastDroppedSettledSeq: number; + /** Records this kind dropped: settling one would only burn a position. */ + evicted: WeakSet; }; +/** A record a `settled` read can see. */ +type SettledRecord = EventRecordBase & { settledSeq: number }; + let lastStartedAt = 0; /** @@ -50,13 +65,27 @@ function nextStartedAt(now: number): number { return lastStartedAt; } +/** + * Reads the settle position of a record. + * + * @param record - The record. + * @returns Its `settledSeq`, or undefined when it is not settled. + */ +function settledSeqOf(record: EventRecordBase): number | undefined { + return (record as EventRecordBase & { settledSeq?: number }).settledSeq; +} + /** * The event buffer of one session: one bounded list per record kind, and - * one `seq` shared by all kinds, so one cursor covers every kind. + * one position shared by all kinds, so one cursor covers every kind. * - * A record keeps the `seq` it got when it was appended, also when its - * source updates it in place later (a network request that finishes), so a - * read after a cursor never returns it again. + * A position is taken by an appended record and by a settled one. A record + * keeps the `seq` it got when it was appended, also when its source updates + * it in place later (a network request that ends), and gets a `settledSeq` + * when it is settled, that is, when no field of it changes any more. A + * filtered network read reads settled records in `settledSeq` order, so a + * request that ends late is returned once, after it settles; an unfiltered + * read returns every record in `seq` order. */ export class EventBuffer { readonly startedAt: number; @@ -88,20 +117,23 @@ export class EventBuffer { dropped: 0, lastDroppedSeq: 0, lastDroppedT: 0, + lastDroppedSettledSeq: 0, + evicted: new WeakSet(), }); this.#kinds = { console: state('console'), network: state('network') }; } /** - * @returns The newest `seq` given out (0 before the first record). + * @returns The newest position given out (0 before the first record). */ get seq(): number { return this.#seq; } /** - * Appends a record and gives it the next `seq`. The returned object is the - * stored record: a source may update its fields in place later. + * Appends a record and gives it the next position as its `seq`. The + * returned object is the stored record: a source may update its fields in + * place later, then settle it. * * @param kind - The record kind. * @param record - The record without its `seq`. @@ -120,25 +152,62 @@ export class EventBuffer { state.dropped += 1; state.lastDroppedSeq = dropped.seq; state.lastDroppedT = Math.max(state.lastDroppedT, dropped.t); + state.evicted.add(dropped); + const settledSeq = settledSeqOf(dropped); + // An unsettled record dropped now can never settle, so a filtered read + // cannot see it: count it as a settle position lost at the current + // position, or a filtered read would report no gap for a record it + // would have returned. + state.lastDroppedSettledSeq = Math.max( + state.lastDroppedSettledSeq, + settledSeq ?? this.#seq, + ); } return stored; } + /** + * Marks a record final: no field of it changes any more. A settled record + * gets the next position as its `settledSeq` and becomes visible to a + * `settled` read. Settling twice does nothing, and a record the buffer has + * dropped (capacity or `clear`) is not settled: no read can see it. + * + * @param kind - The record kind. + * @param record - The record to settle. + */ + settle(kind: EventKind, record: EventRecordBase): void { + const state = this.#kinds[kind]; + if (settledSeqOf(record) !== undefined || state.evicted.has(record)) { + return; + } + this.#seq += 1; + (record as EventRecordBase & { settledSeq?: number }).settledSeq = + this.#seq; + } + /** * Reads records of one kind, oldest first. * * The returned `cursor` continues the read without duplicates or holes: * the `seq` of the last returned record when `hasMore`, else the newest - * `seq` of the buffer (records of other kinds and records the filter + * position of the buffer (records of other kinds and records the filter * skipped are behind it). `gap` is true when a record after `cursor` (and * at or after `since`) was dropped because the buffer was full. When * `cursor` and `since` are both given, `gap` is approximate: a record * dropped after `cursor` but before `since` is not distinguished. * - * A `cursor` above the newest `seq` (from an earlier session: `seq` starts - * at 1 per session) is stale. The read then starts from the oldest record - * and reports `gap: true`, so a client that only compares cursors notices - * the records are not the ones it asked for. + * A `cursor` above the newest position (from an earlier session: `seq` + * starts at 1 per session) is stale. The read then starts from the oldest + * record and reports `gap: true`, so a client that only compares cursors + * notices the records are not the ones it asked for. + * + * With `settled`, only settled records are read, in `settledSeq` order, + * and `cursor` is a settle position: a record that settles after the read + * gets a position above the returned cursor, so a later read sees it even + * when it started before the cursor. `gap` then means a record after + * `cursor` was dropped before a read could see it, settled or not; with + * `since`, a dropped record after `cursor` but before `since` is not + * counted, as in an unfiltered read. * * `limit` is clamped to at least 1. * @@ -148,6 +217,9 @@ export class EventBuffer { read( options: EventReadOptions, ): EventPage { + if (options.settled === true) { + return this.#readSettled(options); + } const { kind, since, limit, filter } = options; const requestedCursor = options.cursor ?? 0; const staleCursor = requestedCursor > this.#seq; @@ -186,8 +258,67 @@ export class EventBuffer { } /** - * Empties the buffer of one kind, or of every kind. `seq` keeps counting, - * so older cursors stay valid. Cleared records are not a gap. + * Reads settled records in settle order. + * + * `since` compares `t`, which for a request is when it started, not when + * it settled. + * + * @param options - What to read. + * @returns The page. + */ + #readSettled( + options: EventReadOptions, + ): EventPage { + const { kind, since, limit, filter } = options; + const requestedCursor = options.cursor ?? 0; + const staleCursor = requestedCursor > this.#seq; + const cursor = staleCursor ? 0 : requestedCursor; + const maxRecords = + Number.isFinite(limit) && limit >= 1 ? Math.floor(limit) : 1; + const state = this.#kinds[kind]; + const settled = (state.records as RecordType[]) + .filter((record) => { + const settledSeq = settledSeqOf(record); + return settledSeq !== undefined && settledSeq > cursor; + }) + .sort( + (left, right) => + (settledSeqOf(left) as number) - (settledSeqOf(right) as number), + ); + const records: RecordType[] = []; + let hasMore = false; + for (const record of settled) { + if ( + (since !== undefined && record.t < since) || + (filter !== undefined && !filter(record)) + ) { + continue; + } + if (records.length === maxRecords) { + hasMore = true; + break; + } + records.push({ ...record }); + } + const last = records.at(-1) as SettledRecord | undefined; + return { + records, + cursor: + hasMore && last !== undefined + ? last.settledSeq + : Math.max(cursor, this.#seq), + hasMore, + gap: + staleCursor || + (state.lastDroppedSettledSeq > cursor && + (since === undefined || state.lastDroppedT >= since)), + summary: this.summary(), + }; + } + + /** + * Empties the buffer of one kind, or of every kind. Positions keep + * counting, so older cursors stay valid. Cleared records are not a gap. * * @param kind - The kind to clear; every kind when undefined. * @returns The kinds cleared. @@ -195,7 +326,11 @@ export class EventBuffer { clear(kind?: EventKind): EventKind[] { const kinds = kind === undefined ? [...EVENT_KINDS] : [kind]; for (const each of kinds) { - this.#kinds[each].records.length = 0; + const state = this.#kinds[each]; + for (const record of state.records) { + state.evicted.add(record); + } + state.records.length = 0; } return kinds; } diff --git a/src/events/json-rpc.test.ts b/src/events/json-rpc.test.ts new file mode 100644 index 00000000..3cb3efcc --- /dev/null +++ b/src/events/json-rpc.test.ts @@ -0,0 +1,104 @@ +import { describe, expect, it } from 'vitest'; + +import { + MAX_RPC_BATCH_METHODS, + MAX_RPC_METHOD_NAME_LENGTH, + MAX_RPC_REQUEST_BYTES, + parseRpcError, + parseRpcMethods, +} from './json-rpc.js'; + +describe('parseRpcMethods', () => { + it('reads a single call as a one-item array', () => { + expect( + parseRpcMethods('{"jsonrpc":"2.0","id":1,"method":"eth_call"}'), + ).toStrictEqual(['eth_call']); + expect(parseRpcMethods(' {"id":1,"method":"eth_chainId"}')).toStrictEqual([ + 'eth_chainId', + ]); + expect( + parseRpcMethods('{"method":"eth_blockNumber","params":[]}'), + ).toStrictEqual(['eth_blockNumber']); + }); + + it('reads a batch in order and caps it', () => { + expect( + parseRpcMethods( + JSON.stringify([ + { jsonrpc: '2.0', id: 2, method: 'eth_chainId' }, + { foo: 1 }, + { jsonrpc: '2.0', id: 3, method: 'eth_blockNumber' }, + ]), + ), + ).toStrictEqual(['eth_chainId', 'eth_blockNumber']); + const big = Array.from({ length: MAX_RPC_BATCH_METHODS + 5 }, (_, id) => ({ + id, + method: `m${id}`, + })); + expect(parseRpcMethods(JSON.stringify(big))).toHaveLength( + MAX_RPC_BATCH_METHODS, + ); + }); + + it('caps a method name', () => { + const method = `m${'x'.repeat(200)}`; + expect(parseRpcMethods(JSON.stringify({ id: 1, method }))).toStrictEqual([ + method.slice(0, MAX_RPC_METHOD_NAME_LENGTH), + ]); + }); + + it('returns undefined for non-JSON-RPC bodies', () => { + expect(parseRpcMethods(undefined)).toBeUndefined(); + expect(parseRpcMethods('a=1&b=2')).toBeUndefined(); + expect(parseRpcMethods('{not json')).toBeUndefined(); + expect(parseRpcMethods('{"method":"x"}')).toBeUndefined(); + expect(parseRpcMethods('{"id":1,"method":5}')).toBeUndefined(); + expect(parseRpcMethods('[1,null,"x"]')).toBeUndefined(); + expect( + parseRpcMethods( + `{"id":1,"method":"eth_call","p":"${'x'.repeat(MAX_RPC_REQUEST_BYTES)}"}`, + ), + ).toBeUndefined(); + }); +}); + +describe('parseRpcError', () => { + it('reads the error of a single response', () => { + expect( + parseRpcError( + '{"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"execution reverted"}}', + ), + ).toStrictEqual({ code: -32000, message: 'execution reverted' }); + }); + + it('reads the first error of a batch', () => { + expect( + parseRpcError( + JSON.stringify([ + { id: 1, result: '0x1' }, + { + id: 2, + error: { code: 'x', message: 'see https://a.example/?key=s' }, + }, + { id: 3, error: { code: 3, message: 'second' } }, + ]), + ), + ).toStrictEqual({ message: 'see https://a.example/?key=[REDACTED]' }); + }); + + it('cuts a long message and names a missing one', () => { + const long = parseRpcError( + JSON.stringify({ error: { code: 1, message: 'm'.repeat(400) } }), + ); + expect(long?.message).toHaveLength(301); + expect(parseRpcError('{"error":{}}')).toStrictEqual({ + message: 'unknown error', + }); + }); + + it('returns undefined without an error', () => { + expect(parseRpcError('{"id":1,"result":"0x1"}')).toBeUndefined(); + expect(parseRpcError('[null, 1]')).toBeUndefined(); + expect(parseRpcError('not json')).toBeUndefined(); + }); +}); diff --git a/src/events/json-rpc.ts b/src/events/json-rpc.ts new file mode 100644 index 00000000..017a14c1 --- /dev/null +++ b/src/events/json-rpc.ts @@ -0,0 +1,104 @@ +import { redactUrlsInText, truncateText } from './redact.js'; +import type { RpcError } from '../tools/types/events.js'; + +/** Request bodies larger than this are not parsed for JSON-RPC methods. */ +export const MAX_RPC_REQUEST_BYTES = 64 * 1024; + +/** Methods kept from one batch. */ +export const MAX_RPC_BATCH_METHODS = 50; + +/** Longest JSON-RPC method name kept. */ +export const MAX_RPC_METHOD_NAME_LENGTH = 128; + +const MAX_RPC_ERROR_MESSAGE_LENGTH = 300; + +/** + * Returns the method of a JSON-RPC call object, cut to + * {@link MAX_RPC_METHOD_NAME_LENGTH}. + * + * @param call - A parsed JSON value. + * @returns The method, or undefined when the value is not a JSON-RPC call. + */ +function getRpcCallMethod(call: unknown): string | undefined { + if (typeof call !== 'object' || call === null) { + return undefined; + } + const { method } = call as { method?: unknown }; + if ( + typeof method !== 'string' || + !('jsonrpc' in call || 'id' in call || 'params' in call) + ) { + return undefined; + } + return method.length > MAX_RPC_METHOD_NAME_LENGTH + ? method.slice(0, MAX_RPC_METHOD_NAME_LENGTH) + : method; +} + +/** + * Reads the JSON-RPC methods of a request body: one for a single call, the + * methods in order for a batch (at most {@link MAX_RPC_BATCH_METHODS}). + * + * @param body - The request body text. + * @returns The methods, or undefined when the body is not JSON-RPC. + */ +export function parseRpcMethods( + body: string | undefined, +): string[] | undefined { + if (body === undefined || body.length > MAX_RPC_REQUEST_BYTES) { + return undefined; + } + const text = body.trimStart(); + if (!text.startsWith('{') && !text.startsWith('[')) { + return undefined; + } + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + return undefined; + } + const calls = Array.isArray(parsed) ? parsed : [parsed]; + const methods = calls + .map(getRpcCallMethod) + .filter((method): method is string => method !== undefined) + .slice(0, MAX_RPC_BATCH_METHODS); + return methods.length === 0 ? undefined : methods; +} + +/** + * Returns the JSON-RPC error of a response body: the `error` of a single + * response, or the first error of a batch. + * + * @param body - The response body text. + * @returns The error with its message redacted, or undefined. + */ +export function parseRpcError(body: string): RpcError | undefined { + let parsed: unknown; + try { + parsed = JSON.parse(body); + } catch { + return undefined; + } + const responses = Array.isArray(parsed) ? parsed : [parsed]; + for (const response of responses) { + const error = + typeof response === 'object' && response !== null + ? (response as { error?: unknown }).error + : undefined; + if (typeof error !== 'object' || error === null) { + continue; + } + const { code, message } = error as { code?: unknown; message?: unknown }; + return { + ...(typeof code === 'number' ? { code } : {}), + message: truncateText( + redactUrlsInText( + typeof message === 'string' ? message : 'unknown error', + ), + MAX_RPC_ERROR_MESSAGE_LENGTH, + ), + }; + } + return undefined; +} diff --git a/src/events/network-source.test.ts b/src/events/network-source.test.ts new file mode 100644 index 00000000..99be992e --- /dev/null +++ b/src/events/network-source.test.ts @@ -0,0 +1,764 @@ +import type { BrowserContext } from '@playwright/test'; +import { describe, expect, it, vi } from 'vitest'; + +import { MAX_RPC_REQUEST_BYTES } from './json-rpc.js'; +import { + MAX_CONCURRENT_RPC_READS, + MAX_PENDING_REQUESTS, + MAX_RESOURCE_BUFFER_BYTES, + MAX_RPC_RESPONSE_BYTES, + MAX_TOTAL_BUFFER_BYTES, + NETWORK_EVENTS, + NetworkSource, + RPC_RESPONSE_READ_TIMEOUT_MS, +} from './network-source.js'; +import { SessionEvents } from './session-events.js'; +import type { + CdpEvent, + CdpEventTarget, + CdpManager, + CdpSubscribeOptions, + CdpSubscription, + CdpTargetLifecycleEvent, +} from '../platform/cdp-manager.js'; +import type { NetworkRecord } from '../tools/types/events.js'; + +const INFURA_KEY = '0123456789abcdef0123456789abcdef'; +const SW: CdpEventTarget = { + kind: 'sw', + targetId: 'W1', + url: 'chrome-extension://abcdefghijklmnopabcdefghijklmnop/bg.js', +}; +const PAGE: CdpEventTarget = { + kind: 'page', + targetId: 'P1', + url: 'https://dapp.example/', +}; + +/** + * Starts a network source on a fake manager. + * + * @param sendToEventTarget - Answers `Network.getResponseBody`. + * @returns The session events, an emitter and the subscribe options. + */ +async function startSource( + sendToEventTarget: CdpManager['sendToEventTarget'] = vi.fn(), +): Promise<{ + events: SessionEvents; + emit: ( + method: string, + params: Record, + target?: CdpEventTarget, + ) => void; + detach: (event: CdpTargetLifecycleEvent) => void; + options: CdpSubscribeOptions; + source: NetworkSource; + manager: CdpManager; + subscription: CdpSubscription; +}> { + let options: CdpSubscribeOptions | undefined; + const listeners = new Set<(event: CdpTargetLifecycleEvent) => void>(); + const manager = { + subscribe: vi.fn(async (subscribeOptions: CdpSubscribeOptions) => { + options = subscribeOptions; + return { unsubscribe: vi.fn() }; + }), + sendToEventTarget, + on: vi.fn( + (_event: string, listener: (event: CdpTargetLifecycleEvent) => void) => { + listeners.add(listener); + }, + ), + off: vi.fn( + (_event: string, listener: (event: CdpTargetLifecycleEvent) => void) => { + listeners.delete(listener); + }, + ), + } as unknown as CdpManager; + const events = new SessionEvents({} as BrowserContext, []); + const source = new NetworkSource(); + const subscription = await source.start(manager, events); + const subscribed = options as CdpSubscribeOptions; + return { + events, + source, + manager, + subscription, + options: subscribed, + emit: (method, params, target = SW): void => + subscribed.onEvent({ target, method, params, t: 9999 } as CdpEvent), + detach: (event): void => { + for (const listener of [...listeners]) { + listener(event); + } + }, + }; +} + +/** + * Reads every network record. + * + * @param events - The session events. + * @returns The records. + */ +function readAll(events: SessionEvents): NetworkRecord[] { + return events.buffer.read({ kind: 'network', limit: 5000 }) + .records; +} + +/** + * Reads every settled network record (what a filtered `mm network` does). + * + * @param events - The session events. + * @returns The records. + */ +function settledReadAll(events: SessionEvents): NetworkRecord[] { + return events.buffer.read({ + kind: 'network', + settled: true, + limit: 5000, + }).records; +} + +/** + * Builds `Network.requestWillBeSent` parameters. + * + * @param requestId - The request ID. + * @param url - The URL. + * @param extra - Other parameters. + * @returns The parameters. + */ +function willBeSent( + requestId: string, + url: string, + extra: Record = {}, +): Record { + const { request, ...rest } = extra as { + request?: Record; + }; + return { + requestId, + request: { url, method: 'GET', ...request }, + timestamp: 100, + wallTime: 1_700_000_000.123, + type: 'Fetch', + ...rest, + }; +} + +describe('NetworkSource', () => { + it('subscribes to the Network events with body buffer limits', async () => { + const { options } = await startSource(); + expect(options.events).toStrictEqual(NETWORK_EVENTS); + expect(options.enable).toStrictEqual({ + Network: { + maxPostDataSize: MAX_RPC_REQUEST_BYTES, + maxResourceBufferSize: MAX_RESOURCE_BUFFER_BYTES, + maxTotalBufferSize: MAX_TOTAL_BUFFER_BYTES, + }, + }); + }); + + it('records subscription errors in the buffer summary', async () => { + const { events, options } = await startSource(); + + options.onError?.( + new Error( + 'Network.enable parameters {"maxPostDataSize":65536} were not applied on page https://dapp.example/', + ), + ); + + expect(events.buffer.summary()).toMatchObject({ + captureErrors: 1, + lastCaptureError: + 'Network.enable parameters {"maxPostDataSize":65536} were not applied on page https://dapp.example/', + }); + }); + + it('stops listening for target detaches when unsubscribed', async () => { + const { subscription, detach, emit, events } = await startSource(); + emit('Network.requestWillBeSent', willBeSent('1', 'https://a/'), PAGE); + await subscription.unsubscribe(); + detach({ kind: 'page', targetId: PAGE.targetId }); + expect(events.networkStats.pending).toBe(1); + }); + + it('records one request, updated in place with status and ms', async () => { + const { events, emit } = await startSource(); + emit( + 'Network.requestWillBeSent', + willBeSent('1', `https://mainnet.infura.io/v3/${INFURA_KEY}?apiKey=s`), + ); + expect(events.networkStats.pending).toBe(1); + const read = events.buffer.read({ + kind: 'network', + limit: 10, + }); + expect(read.records).toStrictEqual([ + { + seq: 1, + t: 1_700_000_000_123, + target: { kind: 'sw', id: 'W1', url: SW.url }, + method: 'GET', + url: 'https://mainnet.infura.io/v3/[REDACTED]?apiKey=[REDACTED]', + type: 'fetch', + }, + ]); + + emit('Network.responseReceived', { + requestId: '1', + response: { status: 200 }, + }); + emit('Network.loadingFinished', { requestId: '1', timestamp: 100.1234 }); + + expect(readAll(events)).toStrictEqual([ + expect.objectContaining({ seq: 1, status: 200, ms: 123 }), + ]); + expect(events.networkStats.pending).toBe(0); + // Already read past it: the update is not returned again. + expect( + events.buffer.read({ + kind: 'network', + cursor: read.cursor, + limit: 10, + }).records, + ).toStrictEqual([]); + }); + + it('records a failure with its duration, redacted', async () => { + const { events, emit } = await startSource(); + emit( + 'Network.requestWillBeSent', + willBeSent('2', 'https://a.example/slow'), + ); + emit('Network.loadingFailed', { + requestId: '2', + timestamp: 100.05, + errorText: 'net::ERR_ABORTED', + }); + emit('Network.requestWillBeSent', willBeSent('3', 'https://a.example/b')); + emit('Network.loadingFailed', { + requestId: '3', + blockedReason: 'mixed-content', + }); + + expect(readAll(events)).toStrictEqual([ + expect.objectContaining({ ms: 50, failure: 'net::ERR_ABORTED' }), + expect.objectContaining({ + failure: 'failed (blocked: mixed-content)', + }), + ]); + expect(readAll(events)[1]?.ms).toBeUndefined(); + }); + + it('includes the CORS reason in a failure', async () => { + const { events, emit } = await startSource(); + emit( + 'Network.requestWillBeSent', + willBeSent('c1', 'https://a.example/cors'), + ); + emit('Network.loadingFailed', { + requestId: 'c1', + errorText: 'net::ERR_FAILED', + corsErrorStatus: { + corsError: 'MissingAllowOriginHeader', + failedParameter: 'Access-Control-Allow-Origin', + }, + }); + + expect(readAll(events)[0]?.failure).toBe( + 'net::ERR_FAILED (cors: MissingAllowOriginHeader)', + ); + }); + + it('uses the delivery time and defaults when CDP leaves fields out', async () => { + const { events, emit } = await startSource(); + emit('Network.requestWillBeSent', { + requestId: '4', + request: { url: 'https://a.example/' }, + }); + emit('Network.responseReceived', { requestId: '4', response: {} }); + emit('Network.loadingFinished', { requestId: '4' }); + + expect(readAll(events)).toStrictEqual([ + { + seq: 1, + settledSeq: 2, + t: 9999, + target: { kind: 'sw', id: 'W1', url: SW.url }, + method: 'GET', + url: 'https://a.example/', + type: 'other', + }, + ]); + }); + + it('counts non-http URLs as ignored and ignores events without a request ID', async () => { + const { events, emit } = await startSource(); + emit( + 'Network.requestWillBeSent', + willBeSent( + '5', + 'chrome-extension://abcdefghijklmnopabcdefghijklmnop/x.js', + ), + ); + emit('Network.requestWillBeSent', willBeSent('6', 'data:text/plain,hi')); + emit('Network.requestWillBeSent', { request: { url: 'https://a/' } }); + emit('Network.requestWillBeSent', { requestId: '7' }); + emit('Network.loadingFinished', { requestId: 'unknown' }); + emit('Network.loadingFailed', { requestId: 'unknown' }); + emit('Network.responseReceived', { requestId: 'unknown' }); + + expect(readAll(events)).toStrictEqual([]); + expect(events.networkStats.ignored).toBe(3); + }); + + it('settles a failed request so a filtered read sees its final state', async () => { + const { events, emit } = await startSource(); + emit('Network.requestWillBeSent', willBeSent('f1', 'https://a.example/')); + expect(settledReadAll(events)).toStrictEqual([]); + + emit('Network.loadingFailed', { + requestId: 'f1', + timestamp: 100.05, + errorText: 'net::ERR_ABORTED', + }); + + expect(settledReadAll(events)).toStrictEqual([ + expect.objectContaining({ + seq: 1, + settledSeq: 2, + failure: 'net::ERR_ABORTED', + }), + ]); + }); + + it('settles each redirect hop when the next one starts', async () => { + const { events, emit } = await startSource(); + emit('Network.requestWillBeSent', willBeSent('r1', 'http://a.example/old')); + expect(settledReadAll(events)).toStrictEqual([]); + + emit( + 'Network.requestWillBeSent', + willBeSent('r1', 'https://a.example/new', { + timestamp: 100.02, + redirectResponse: { status: 301 }, + }), + ); + // The first hop is final; the new hop is still pending and has no + // settle position yet. + expect(settledReadAll(events)).toStrictEqual([ + expect.objectContaining({ + seq: 1, + settledSeq: 2, + url: 'http://a.example/old', + status: 301, + }), + ]); + + emit('Network.loadingFinished', { requestId: 'r1', timestamp: 100.05 }); + expect(settledReadAll(events).map((record) => record.seq)).toStrictEqual([ + 1, 3, + ]); + }); + + it('settles every pending request when it starts again on a new manager', async () => { + const { events, emit, source, manager } = await startSource(); + emit('Network.requestWillBeSent', willBeSent('1', 'https://a/')); + expect(settledReadAll(events)).toStrictEqual([]); + + await source.start(manager, events); + + expect(settledReadAll(events)).toStrictEqual([ + expect.objectContaining({ seq: 1, settledSeq: 2 }), + ]); + }); + + it('keys requests by target, so equal request IDs do not mix', async () => { + const { events, emit } = await startSource(); + emit('Network.requestWillBeSent', willBeSent('1', 'https://a.example/sw')); + emit( + 'Network.requestWillBeSent', + willBeSent('1', 'https://a.example/page'), + PAGE, + ); + emit( + 'Network.responseReceived', + { requestId: '1', response: { status: 404 } }, + PAGE, + ); + emit('Network.responseReceived', { + requestId: '1', + response: { status: 200 }, + }); + + expect( + readAll(events).map((record) => [record.target.kind, record.status]), + ).toStrictEqual([ + ['sw', 200], + ['page', 404], + ]); + }); + + it('ends a redirect hop and starts a new record for the next URL', async () => { + const { events, emit } = await startSource(); + emit('Network.requestWillBeSent', willBeSent('8', 'http://a.example/old')); + emit( + 'Network.requestWillBeSent', + willBeSent('8', 'https://a.example/new', { + timestamp: 100.02, + redirectResponse: { status: 301 }, + }), + ); + emit('Network.responseReceived', { + requestId: '8', + response: { status: 200 }, + }); + emit('Network.loadingFinished', { requestId: '8', timestamp: 100.05 }); + + expect( + readAll(events).map(({ url, status, ms }) => ({ url, status, ms })), + ).toStrictEqual([ + { url: 'http://a.example/old', status: 301, ms: 20 }, + { url: 'https://a.example/new', status: 200, ms: 30 }, + ]); + }); + + it('keeps a redirect hop without a status or time as is', async () => { + const { events, emit } = await startSource(); + emit('Network.requestWillBeSent', { + requestId: '9', + request: { url: 'https://a.example/1' }, + }); + emit('Network.requestWillBeSent', { + requestId: '9', + request: { url: 'https://a.example/2' }, + redirectResponse: {}, + }); + expect(readAll(events)[0]).not.toHaveProperty('status'); + expect(readAll(events)[0]).not.toHaveProperty('ms'); + }); + + it('reads rpcMethods from postData and postDataEntries', async () => { + const { events, emit } = await startSource(); + emit( + 'Network.requestWillBeSent', + willBeSent('10', 'https://rpc.example/', { + request: { + method: 'POST', + postData: '{"jsonrpc":"2.0","id":1,"method":"eth_call"}', + }, + }), + ); + const batch = JSON.stringify([ + { jsonrpc: '2.0', id: 2, method: 'eth_chainId' }, + { jsonrpc: '2.0', id: 3, method: 'eth_blockNumber' }, + ]); + emit( + 'Network.requestWillBeSent', + willBeSent('11', 'https://rpc.example/', { + request: { + method: 'POST', + postDataEntries: [ + { bytes: Buffer.from(batch.slice(0, 10)).toString('base64') }, + { bytes: Buffer.from(batch.slice(10)).toString('base64') }, + {}, + ], + }, + }), + ); + emit( + 'Network.requestWillBeSent', + willBeSent('12', 'https://rpc.example/', { + request: { method: 'POST', postDataEntries: [] }, + }), + ); + emit( + 'Network.requestWillBeSent', + willBeSent('13', 'https://rpc.example/', { + request: { + method: 'POST', + postDataEntries: [ + { bytes: Buffer.alloc(70 * 1024, 'a').toString('base64') }, + ], + }, + }), + ); + emit( + 'Network.requestWillBeSent', + willBeSent('14', 'https://rpc.example/', { + request: { method: 'GET', postData: '{"id":1,"method":"eth_call"}' }, + }), + ); + + expect(readAll(events).map((record) => record.rpcMethods)).toStrictEqual([ + ['eth_call'], + ['eth_chainId', 'eth_blockNumber'], + undefined, + undefined, + undefined, + ]); + }); + + it('forgets the oldest pending request past the limit as abandoned', async () => { + const { events, emit } = await startSource(); + // The record and the pending entry are both full at the limit, so the + // abandoned record is already out of the buffer: keep the objects the + // source appends to inspect it. + const appended: NetworkRecord[] = []; + const append = events.buffer.append.bind(events.buffer); + vi.spyOn(events.buffer, 'append').mockImplementation((( + kind: 'network', + record: Omit, + ) => { + const stored = append(kind, record); + appended.push(stored); + return stored; + }) as typeof events.buffer.append); + for (let index = 0; index <= MAX_PENDING_REQUESTS; index++) { + emit('Network.requestWillBeSent', willBeSent(`p${index}`, 'https://a/')); + } + expect(events.networkStats.pending).toBe(MAX_PENDING_REQUESTS); + expect(appended[0]).toMatchObject({ failure: 'abandoned' }); + emit('Network.loadingFinished', { requestId: 'p0', timestamp: 101 }); + expect(readAll(events)[0]?.ms).toBeUndefined(); + }); + + it('clears pending requests when it starts on a new manager', async () => { + const { events, emit, source, manager } = await startSource(); + emit('Network.requestWillBeSent', willBeSent('1', 'https://a/')); + await source.start(manager, events); + expect(events.networkStats.pending).toBe(0); + expect(settledReadAll(events)).toStrictEqual([ + expect.objectContaining({ seq: 1, failure: 'target closed' }), + ]); + }); + + it('finalizes the pending requests of a target that detaches', async () => { + const { events, emit, detach } = await startSource(); + emit('Network.requestWillBeSent', willBeSent('1', 'https://a/'), PAGE); + emit('Network.requestWillBeSent', willBeSent('2', 'https://a/'), PAGE); + emit('Network.requestWillBeSent', willBeSent('3', 'https://a/')); + + // A detach without a target ID cannot be matched safely: leave it. + detach({ kind: 'page' }); + expect(events.networkStats.pending).toBe(3); + + detach({ kind: 'page', targetId: PAGE.targetId }); + expect(events.networkStats.pending).toBe(1); + expect(readAll(events)).toStrictEqual([ + expect.objectContaining({ seq: 1, failure: 'target closed' }), + expect.objectContaining({ seq: 2, failure: 'target closed' }), + expect.objectContaining({ seq: 3 }), + ]); + expect(readAll(events)[2]).not.toHaveProperty('failure'); + // The finalized requests are settled; the one of the live worker is not. + expect(settledReadAll(events).map((record) => record.seq)).toStrictEqual([ + 1, 2, + ]); + }); + + describe('rpcError', () => { + /** + * Sends one finished JSON-RPC request through a source. + * + * @param emit - The source emitter. + * @param requestId - The request ID. + * @param finished - Extra `loadingFinished` parameters. + */ + function rpcRequest( + emit: (method: string, params: Record) => void, + requestId: string, + finished: Record = {}, + ): void { + emit( + 'Network.requestWillBeSent', + willBeSent(requestId, 'https://rpc.example/', { + request: { + method: 'POST', + postData: '{"jsonrpc":"2.0","id":1,"method":"eth_call"}', + }, + }), + ); + emit('Network.loadingFinished', { requestId, ...finished }); + } + + it('is not read by default', async () => { + const send = vi.fn(); + const { emit } = await startSource(send); + rpcRequest(emit, '1'); + expect(send).not.toHaveBeenCalled(); + }); + + it('reads JSON-RPC bodies when configured, plain and base64', async () => { + const body = JSON.stringify({ + jsonrpc: '2.0', + id: 1, + error: { code: -32000, message: 'execution reverted' }, + }); + const send = vi + .fn() + .mockResolvedValueOnce({ body }) + .mockResolvedValueOnce({ + body: Buffer.from(body).toString('base64'), + base64Encoded: true, + }) + .mockResolvedValueOnce({ body: '{"result":"0x1"}' }) + .mockResolvedValueOnce({}); + const { events, emit } = await startSource(send); + events.config = { ...events.config, rpcErrors: true }; + + rpcRequest(emit, '1'); + rpcRequest(emit, '2'); + rpcRequest(emit, '3'); + rpcRequest(emit, '4'); + // Not JSON-RPC: never read. + emit('Network.requestWillBeSent', willBeSent('5', 'https://a/')); + emit('Network.loadingFinished', { requestId: '5' }); + await vi.waitFor(() => + expect(readAll(events)[1]?.rpcError).toBeDefined(), + ); + + expect(send).toHaveBeenCalledTimes(4); + expect(send).toHaveBeenCalledWith( + SW, + 'Network.getResponseBody', + { requestId: '1' }, + { timeoutMs: RPC_RESPONSE_READ_TIMEOUT_MS }, + ); + expect(readAll(events).map((record) => record.rpcError)).toStrictEqual([ + { code: -32000, message: 'execution reverted' }, + { code: -32000, message: 'execution reverted' }, + undefined, + undefined, + undefined, + ]); + expect(events.networkStats.rpcErrorsSkipped).toBe(0); + }); + + it('settles the record after its rpcError read, not before', async () => { + let resolveRead!: (value: unknown) => void; + const send = vi.fn( + async () => + new Promise((resolve) => { + resolveRead = resolve; + }), + ); + const { events, emit } = await startSource(send); + events.config = { ...events.config, rpcErrors: true }; + + rpcRequest(emit, '1'); + expect(readAll(events)[0]?.settledSeq).toBeUndefined(); + // A filtered read (settled) leaves the record out until its final + // rpcError is known. + expect(settledReadAll(events)).toStrictEqual([]); + + resolveRead({ body: '{"error":{"code":-1,"message":"boom"}}' }); + await vi.waitFor(() => + expect(readAll(events)[0]?.settledSeq).toBeDefined(), + ); + expect(readAll(events)[0]?.rpcError).toStrictEqual({ + code: -1, + message: 'boom', + }); + expect(settledReadAll(events)).toStrictEqual([ + expect.objectContaining({ + seq: 1, + rpcError: { code: -1, message: 'boom' }, + }), + ]); + }); + + it('settles a record whose rpcError read is skipped', async () => { + const send = vi.fn(); + const { events, emit } = await startSource(send); + events.config = { ...events.config, rpcErrors: true }; + + rpcRequest(emit, '1', { encodedDataLength: MAX_RPC_RESPONSE_BYTES + 1 }); + + expect(send).not.toHaveBeenCalled(); + expect(events.networkStats.rpcErrorsSkipped).toBe(1); + expect(settledReadAll(events)).toStrictEqual([ + expect.objectContaining({ seq: 1, settledSeq: 2 }), + ]); + }); + + it('bounds the body by decoded bytes, not the encoded length', async () => { + const send = vi.fn().mockResolvedValue({ body: '{"result":"0x1"}' }); + const { events, emit } = await startSource(send); + events.config = { ...events.config, rpcErrors: true }; + const postData = '{"jsonrpc":"2.0","id":1,"method":"eth_call"}'; + const start = (requestId: string): void => { + emit( + 'Network.requestWillBeSent', + willBeSent(requestId, 'https://rpc.example/', { + request: { method: 'POST', postData }, + }), + ); + }; + + start('big'); + emit('Network.dataReceived', { + requestId: 'big', + dataLength: MAX_RPC_RESPONSE_BYTES + 1, + }); + emit('Network.loadingFinished', { + requestId: 'big', + encodedDataLength: 1, + }); + + start('compressed'); + emit('Network.dataReceived', { requestId: 'compressed', dataLength: 10 }); + emit('Network.loadingFinished', { + requestId: 'compressed', + encodedDataLength: MAX_RPC_RESPONSE_BYTES + 1, + }); + + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1)); + expect(send).toHaveBeenCalledWith( + SW, + 'Network.getResponseBody', + { requestId: 'compressed' }, + { timeoutMs: RPC_RESPONSE_READ_TIMEOUT_MS }, + ); + expect(events.networkStats.rpcErrorsSkipped).toBe(1); + }); + + it('skips large, failing and concurrent reads and counts them', async () => { + const resolvers: ((value: unknown) => void)[] = []; + const send = vi.fn( + async () => + new Promise((resolve) => { + resolvers.push(resolve); + }), + ); + const { events, emit } = await startSource(send); + events.config = { ...events.config, rpcErrors: true }; + + rpcRequest(emit, 'big', { + encodedDataLength: MAX_RPC_RESPONSE_BYTES + 1, + }); + for (let index = 0; index < MAX_CONCURRENT_RPC_READS + 1; index++) { + rpcRequest(emit, `c${index}`); + } + expect(send).toHaveBeenCalledTimes(MAX_CONCURRENT_RPC_READS); + expect(events.networkStats.rpcErrorsSkipped).toBe(2); + + resolvers[0]?.({ body: 'x'.repeat(MAX_RPC_RESPONSE_BYTES + 1) }); + for (const resolve of resolvers.slice(1)) { + resolve({ body: '{}' }); + } + await vi.waitFor(() => + expect(events.networkStats.rpcErrorsSkipped).toBe(3), + ); + + send.mockRejectedValueOnce( + new Error('No resource with given identifier'), + ); + rpcRequest(emit, 'gone'); + await vi.waitFor(() => + expect(events.networkStats.rpcErrorsSkipped).toBe(4), + ); + }); + }); +}); diff --git a/src/events/network-source.ts b/src/events/network-source.ts new file mode 100644 index 00000000..512958d7 --- /dev/null +++ b/src/events/network-source.ts @@ -0,0 +1,516 @@ +import { + MAX_RPC_REQUEST_BYTES, + parseRpcError, + parseRpcMethods, +} from './json-rpc.js'; +import { toRecordTarget } from './read-options.js'; +import { redactText, redactUrl } from './redact.js'; +import type { SessionEventSource, SessionEvents } from './session-events.js'; +import type { + CdpEvent, + CdpEventTarget, + CdpManager, + CdpSubscription, + CdpTargetLifecycleEvent, +} from '../platform/cdp-manager.js'; +import type { NetworkRecord } from '../tools/types/events.js'; +import { debugWarn } from '../utils'; + +export const NETWORK_EVENTS = [ + 'Network.requestWillBeSent', + 'Network.responseReceived', + 'Network.dataReceived', + 'Network.loadingFinished', + 'Network.loadingFailed', +] as const; + +/** JSON-RPC response bodies larger than this are not read for `rpcError`. */ +export const MAX_RPC_RESPONSE_BYTES = 64 * 1024; + +/** Response bodies read at the same time for `rpcError`. */ +export const MAX_CONCURRENT_RPC_READS = 8; + +/** How long one response body read may take. */ +export const RPC_RESPONSE_READ_TIMEOUT_MS = 2_000; + +/** + * Per-response network buffer, in bytes. Twice the largest JSON-RPC body that + * is read, so headers and framing fit too. + */ +export const MAX_RESOURCE_BUFFER_BYTES = MAX_RPC_RESPONSE_BYTES * 2; + +/** + * Total network buffer, in bytes: room for the concurrent JSON-RPC body + * reads. No bodies are kept otherwise. + */ +export const MAX_TOTAL_BUFFER_BYTES = + MAX_RESOURCE_BUFFER_BYTES * MAX_CONCURRENT_RPC_READS; + +/** + * Requests remembered while they run. Requests that never end (a worker + * that stopped mid-request, a stream) are forgotten oldest first past it; + * their record is settled as it stands, so a filtered read sees it once. + */ +export const MAX_PENDING_REQUESTS = 2_000; + +const RECORDED_PROTOCOLS = /^https?:/iu; + +type CdpRequest = { + url?: string; + method?: string; + postData?: string; + postDataEntries?: { bytes?: string }[]; +}; + +type RequestWillBeSentParams = { + requestId?: string; + request?: CdpRequest; + timestamp?: number; + wallTime?: number; + type?: string; + redirectResponse?: { status?: number }; +}; + +type ResponseReceivedParams = { + requestId?: string; + response?: { status?: number }; +}; + +type LoadingFinishedParams = { + requestId?: string; + timestamp?: number; + encodedDataLength?: number; +}; + +type DataReceivedParams = { + requestId?: string; + dataLength?: number; +}; + +type LoadingFailedParams = { + requestId?: string; + timestamp?: number; + errorText?: string; + blockedReason?: string; + corsErrorStatus?: { corsError?: string; failedParameter?: string }; +}; + +type PendingRequest = { + record: NetworkRecord; + target: CdpEventTarget; + requestId: string; + /** CDP monotonic time of the start, in seconds. */ + startedAt?: number; + /** + * Body bytes received before decoding (`Network.dataReceived` lengths), + * undefined when Chrome sent no data event. + */ + decodedBytes?: number; +}; + +/** + * Reads the request body of a `Network.requestWillBeSent` request. + * + * @param request - The CDP request. + * @returns The body text, or undefined when Chrome sent none. + */ +function readPostData(request: CdpRequest): string | undefined { + if (request.postData !== undefined) { + return request.postData; + } + if (!request.postDataEntries?.length) { + return undefined; + } + const chunks = request.postDataEntries.map((entry) => + Buffer.from(entry.bytes ?? '', 'base64'), + ); + const size = chunks.reduce((total, chunk) => total + chunk.length, 0); + return size > MAX_RPC_REQUEST_BYTES + ? undefined + : Buffer.concat(chunks).toString('utf8'); +} + +/** + * Milliseconds between two CDP monotonic times (seconds). + * + * @param start - The start time. + * @param end - The end time. + * @returns The rounded duration, or undefined when a time is missing. + */ +function elapsedMs( + start: number | undefined, + end: number | undefined, +): number | undefined { + if (start === undefined || end === undefined) { + return undefined; + } + return Math.max(Math.round((end - start) * 1000), 0); +} + +/** + * Records the HTTP(S) requests of every page and the Extension service + * worker: one record per request, created when it starts and updated in + * place when it gets a response and when it ends. A redirect ends the + * record of the hop with the redirect status and starts a new record for + * the next URL, as DevTools shows it. Every record is settled when no field + * of it can change any more, so a filtered `mm network` read returns it + * once, after it ended. + */ +export class NetworkSource implements SessionEventSource { + readonly #pending = new Map(); + + #rpcReads = 0; + + /** + * @param manager - The session's CDP manager. + * @param events - The session's events. + * @returns The subscription. + */ + async start( + manager: CdpManager, + events: SessionEvents, + ): Promise { + // A request still pending when the source starts again (the CDP manager + // was replaced) can never finish: settle its record as it stands, so a + // filtered read can see it. + for (const pending of this.#pending.values()) { + pending.record.failure = 'target closed'; + events.buffer.settle('network', pending.record); + } + this.#pending.clear(); + events.networkStats.pending = 0; + const subscription = await manager.subscribe({ + events: NETWORK_EVENTS, + enable: { + Network: { + maxPostDataSize: MAX_RPC_REQUEST_BYTES, + maxResourceBufferSize: MAX_RESOURCE_BUFFER_BYTES, + maxTotalBufferSize: MAX_TOTAL_BUFFER_BYTES, + }, + }, + onEvent: (event) => this.#onEvent(event, manager, events), + onError: events.reportError, + }); + const onDetached = (event: CdpTargetLifecycleEvent): void => + this.#onTargetDetached(event, events); + manager.on('targetDetached', onDetached); + return { + unsubscribe: async (): Promise => { + manager.off('targetDetached', onDetached); + await subscription.unsubscribe(); + }, + }; + } + + /** + * Dispatches one CDP event. + * + * @param event - The CDP event. + * @param manager - The session's CDP manager. + * @param events - The session's events. + */ + #onEvent(event: CdpEvent, manager: CdpManager, events: SessionEvents): void { + const { requestId } = event.params as { requestId?: unknown }; + if (typeof requestId !== 'string') { + return; + } + const key = `${event.target.kind}\u0000${event.target.targetId}\u0000${requestId}`; + switch (event.method) { + case 'Network.requestWillBeSent': + this.#onRequest( + key, + requestId, + event, + event.params as RequestWillBeSentParams, + events, + ); + break; + case 'Network.responseReceived': { + const pending = this.#pending.get(key); + const status = (event.params as ResponseReceivedParams).response + ?.status; + if (pending && typeof status === 'number') { + pending.record.status = status; + } + break; + } + case 'Network.dataReceived': { + const pending = this.#pending.get(key); + const length = (event.params as DataReceivedParams).dataLength; + if (pending && typeof length === 'number' && length > 0) { + pending.decodedBytes = (pending.decodedBytes ?? 0) + length; + } + break; + } + case 'Network.loadingFinished': + this.#onFinished( + key, + event.params as LoadingFinishedParams, + manager, + events, + ); + break; + case 'Network.loadingFailed': + this.#onFailed(key, event.params as LoadingFailedParams, events); + break; + default: + break; + } + } + + /** + * Starts the record of a request (or of the next hop of a redirect). + * + * @param key - The request key (target kind, target ID, request ID). + * @param requestId - The CDP request ID. + * @param event - The CDP event. + * @param params - Its parameters. + * @param events - The session's events. + */ + #onRequest( + key: string, + requestId: string, + event: CdpEvent, + params: RequestWillBeSentParams, + events: SessionEvents, + ): void { + const previous = this.#pending.get(key); + if (previous && params.redirectResponse) { + if (typeof params.redirectResponse.status === 'number') { + previous.record.status = params.redirectResponse.status; + } + const ms = elapsedMs(previous.startedAt, params.timestamp); + if (ms !== undefined) { + previous.record.ms = ms; + } + } + // A new request with the same ID is not a leftover of a detached target: + // `CdpManager.#detach` emits `targetDetached`, which settles and forgets + // the target's pending requests, before it re-attaches. So this is a + // redirect hop, or an ID Chrome reused on a live target. + this.#forget(key, events); + + const request = params.request ?? {}; + const url = request.url ?? ''; + if (!RECORDED_PROTOCOLS.test(url)) { + events.networkStats.ignored += 1; + return; + } + const method = request.method ?? 'GET'; + const rpcMethods = + method === 'POST' ? parseRpcMethods(readPostData(request)) : undefined; + const record = events.buffer.append('network', { + t: + typeof params.wallTime === 'number' + ? Math.round(params.wallTime * 1000) + : event.t, + target: toRecordTarget(event.target), + method, + url: redactUrl(url), + type: (params.type ?? 'other').toLowerCase(), + ...(rpcMethods === undefined ? {} : { rpcMethods }), + }); + this.#pending.set(key, { + record, + target: event.target, + requestId, + startedAt: params.timestamp, + }); + events.networkStats.pending = this.#pending.size; + if (this.#pending.size > MAX_PENDING_REQUESTS) { + const [oldest] = this.#pending.keys(); + const abandoned = this.#pending.get(oldest); + if (abandoned) { + // The request never ends here: say so instead of looking pending. + abandoned.record.failure = 'abandoned'; + } + this.#forget(oldest, events); + } + } + + /** + * Ends a request that finished loading, and reads its JSON-RPC error when + * the session asks for it. + * + * @param key - The request key. + * @param params - The `Network.loadingFinished` parameters. + * @param manager - The session's CDP manager. + * @param events - The session's events. + */ + #onFinished( + key: string, + params: LoadingFinishedParams, + manager: CdpManager, + events: SessionEvents, + ): void { + const known = this.#pending.get(key); + const readError = + known !== undefined && + events.config.rpcErrors && + known.record.rpcMethods !== undefined; + // Keep the record unsettled while its rpcError is read, so a filtered + // read returns it with the final rpcError. + const pending = this.#forget(key, events, readError); + if (!pending) { + return; + } + const ms = elapsedMs(pending.startedAt, params.timestamp); + if (ms !== undefined) { + pending.record.ms = ms; + } + if (readError) { + this.#readRpcError(pending, params, manager, events).catch( + (error: unknown) => debugWarn('network-source.rpc-error', error), + ); + } + } + + /** + * Ends a request that failed. + * + * @param key - The request key. + * @param params - The `Network.loadingFailed` parameters. + * @param events - The session's events. + */ + #onFailed( + key: string, + params: LoadingFailedParams, + events: SessionEvents, + ): void { + const pending = this.#forget(key, events); + if (!pending) { + return; + } + const ms = elapsedMs(pending.startedAt, params.timestamp); + if (ms !== undefined) { + pending.record.ms = ms; + } + const reasons: string[] = []; + if (params.blockedReason) { + reasons.push(`blocked: ${params.blockedReason}`); + } + if (params.corsErrorStatus?.corsError) { + reasons.push(`cors: ${params.corsErrorStatus.corsError}`); + } + const reason = reasons.length === 0 ? '' : ` (${reasons.join('; ')})`; + pending.record.failure = redactText( + `${params.errorText ?? 'failed'}${reason}`, + ); + } + + /** + * Reads a JSON-RPC response body and records its error, bounded in size, + * time and concurrent reads. Skipped reads are counted. + * + * The size bound uses the decoded body bytes reported by + * `Network.dataReceived` when Chrome sent them; without those events it + * falls back to `encodedDataLength`, which is the compressed size and can + * undercount. The body text is checked again by UTF-8 byte length. + * + * The record stays unsettled until the read settles (or is skipped), so a + * filtered read returns it once, with its final `rpcError`. + * + * @param pending - The finished request. + * @param params - The `Network.loadingFinished` parameters. + * @param manager - The session's CDP manager. + * @param events - The session's events. + */ + async #readRpcError( + pending: PendingRequest, + params: LoadingFinishedParams, + manager: CdpManager, + events: SessionEvents, + ): Promise { + try { + const received = pending.decodedBytes ?? params.encodedDataLength ?? 0; + if ( + this.#rpcReads >= MAX_CONCURRENT_RPC_READS || + received > MAX_RPC_RESPONSE_BYTES + ) { + events.networkStats.rpcErrorsSkipped += 1; + return; + } + this.#rpcReads += 1; + try { + const { body, base64Encoded } = (await manager.sendToEventTarget( + pending.target, + 'Network.getResponseBody', + { requestId: pending.requestId }, + { timeoutMs: RPC_RESPONSE_READ_TIMEOUT_MS }, + )) as { body?: string; base64Encoded?: boolean }; + const text = base64Encoded + ? Buffer.from(body ?? '', 'base64').toString('utf8') + : (body ?? ''); + if (Buffer.byteLength(text, 'utf8') > MAX_RPC_RESPONSE_BYTES) { + events.networkStats.rpcErrorsSkipped += 1; + return; + } + const rpcError = parseRpcError(text); + if (rpcError) { + // The record object is created once and only its fields change; the + // pending entry may be gone, but the buffered record is the same. + // eslint-disable-next-line require-atomic-updates + pending.record.rpcError = rpcError; + } + } catch { + events.networkStats.rpcErrorsSkipped += 1; + } finally { + this.#rpcReads -= 1; + } + } finally { + // Whether the body was read, skipped or failed, the record is final. + events.buffer.settle('network', pending.record); + } + } + + /** + * Ends the requests of a target that detached (a page closed, the worker + * stopped, its session was lost): they can never finish, so they stop + * counting as pending and carry a `target closed` failure. + * + * @param event - The detached target. + * @param events - The session's events. + */ + #onTargetDetached( + event: CdpTargetLifecycleEvent, + events: SessionEvents, + ): void { + const { targetId } = event; + if (targetId === undefined) { + return; + } + for (const [key, pending] of this.#pending) { + if ( + pending.target.kind === event.kind && + pending.target.targetId === targetId + ) { + pending.record.failure = 'target closed'; + this.#forget(key, events); + } + } + } + + /** + * Stops tracking a request and settles its record, unless the caller keeps + * it open for a JSON-RPC error read. + * + * @param key - The request key. + * @param events - The session's events. + * @param keepOpen - Whether the record may still change (an `rpcError` + * read follows). + * @returns The request, when it was tracked. + */ + #forget( + key: string, + events: SessionEvents, + keepOpen = false, + ): PendingRequest | undefined { + const pending = this.#pending.get(key); + this.#pending.delete(key); + if (pending && !keepOpen) { + events.buffer.settle('network', pending.record); + } + events.networkStats.pending = this.#pending.size; + return pending; + } +} diff --git a/src/events/session-events.ts b/src/events/session-events.ts index e06332d2..73be9a66 100644 --- a/src/events/session-events.ts +++ b/src/events/session-events.ts @@ -2,10 +2,11 @@ import type { BrowserContext } from '@playwright/test'; import { ConsoleSource, DEFAULT_CONSOLE_LEVELS } from './console-source.js'; import { EventBuffer } from './event-buffer.js'; +import { NetworkSource } from './network-source.js'; import { redactText, truncateText } from './redact.js'; import type { CdpManager, CdpSubscription } from '../platform/cdp-manager.js'; import { getCdpManager } from '../platform/cdp-manager.js'; -import type { EventConfig } from '../tools/types/events.js'; +import type { EventConfig, NetworkStats } from '../tools/types/events.js'; import { debugWarn, extractErrorMessage } from '../utils'; /** @@ -42,7 +43,17 @@ export class SessionEvents { readonly context: BrowserContext; /** What the sources record. Sources read it for each event. */ - config: EventConfig = { consoleLevels: [...DEFAULT_CONSOLE_LEVELS] }; + config: EventConfig = { + consoleLevels: [...DEFAULT_CONSOLE_LEVELS], + rpcErrors: false, + }; + + /** Counters of the network source. */ + readonly networkStats: NetworkStats = { + pending: 0, + ignored: 0, + rpcErrorsSkipped: 0, + }; readonly #sources: SessionEventSource[]; @@ -158,7 +169,7 @@ export class SessionEvents { * @returns The sources. */ function createSources(): SessionEventSource[] { - return [new ConsoleSource()]; + return [new ConsoleSource(), new NetworkSource()]; } const sessions = new WeakMap(); diff --git a/src/platform/cdp-manager.test.ts b/src/platform/cdp-manager.test.ts index 45cfccb9..d8d18c90 100644 --- a/src/platform/cdp-manager.test.ts +++ b/src/platform/cdp-manager.test.ts @@ -3255,3 +3255,173 @@ describe('CdpManager subscribe without onError', () => { } }); }); + +describe('CdpManager sendToEventTarget', () => { + it('sends on the persistent session of an attached page or worker', async () => { + const page = createEventPage(); + const other = createEventPage('https://dapp.test/'); + const fake = createContext({ + pages: [other, page], + swReply: (method) => ({ result: { body: `sw:${method}` } }), + }); + const otherSession = createEventSession('page-0'); + const pageSession = createEventSession('page-1', (method) => ({ + body: `page:${method}`, + })); + fake.newCDPSession.mockImplementation(async (target: Page) => + target === page ? pageSession : otherSession, + ); + const manager = new CdpManager(fake.context); + await manager.subscribe({ events: NET_EVENTS, onEvent: vi.fn() }); + + expect( + await manager.sendToEventTarget( + { kind: 'page', targetId: 'page-1', url: PAGE_URL }, + 'Network.getResponseBody', + { requestId: 'r1' }, + ), + ).toStrictEqual({ body: 'page:Network.getResponseBody' }); + expect(pageSession.send).toHaveBeenCalledWith('Network.getResponseBody', { + requestId: 'r1', + }); + expect( + await manager.sendToEventTarget( + { kind: 'sw', targetId: TARGET_ID, url: SW_URL }, + 'Network.getResponseBody', + ), + ).toStrictEqual({ body: 'sw:Network.getResponseBody' }); + expect(fake.newCDPSession).toHaveBeenCalledTimes(2); + }); + + it('reports the target ID on targetDetached', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + const session = createEventSession('page-1'); + fake.newCDPSession.mockResolvedValueOnce(session); + const manager = new CdpManager(fake.context); + const detached = vi.fn(); + manager.on('targetDetached', detached); + + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn() }); + page.setClosed(true); + page.emitter.emit('close', page); + await flush(); + + expect(detached).toHaveBeenCalledWith({ + kind: 'page', + target: page, + targetId: 'page-1', + }); + }); + + it('reports the worker target ID on targetDetached', async () => { + const fake = createContext(); + const manager = new CdpManager(fake.context); + const detached = vi.fn(); + manager.on('targetDetached', detached); + + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn() }); + fake.browserEmitter.emit('Target.targetDestroyed', { targetId: TARGET_ID }); + await flush(); + + expect(detached).toHaveBeenCalledWith( + expect.objectContaining({ kind: 'sw', targetId: TARGET_ID }), + ); + }); + + it('times out a command whose target lookup hangs', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + const session = createEventSession('page-1'); + let resolveInfo!: (value: unknown) => void; + session.send.mockImplementation(async (method: string) => + method === 'Target.getTargetInfo' + ? new Promise((resolve) => { + resolveInfo = resolve; + }) + : {}, + ); + fake.newCDPSession.mockResolvedValueOnce(session); + const manager = new CdpManager(fake.context); + const subscribing = manager.subscribe({ + events: LOG_EVENTS, + onEvent: vi.fn(), + }); + await vi.waitFor(() => + expect(session.send).toHaveBeenCalledWith('Target.getTargetInfo', {}), + ); + + await expect( + manager.sendToEventTarget( + { kind: 'page', targetId: 'page-1', url: PAGE_URL }, + 'Network.getResponseBody', + {}, + { timeoutMs: 5 }, + ), + ).rejects.toThrowError( + 'CDP call "Network.getResponseBody" timed out after 5ms', + ); + + resolveInfo({ targetInfo: { targetId: 'page-1' } }); + await subscribing; + }); + + it('fails at once for a target that is not attached', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + const session = createEventSession('page-1'); + session.send.mockImplementation(async (method: string) => { + if (method === 'Target.getTargetInfo') { + throw new Error('Target closed'); + } + return {}; + }); + fake.newCDPSession.mockResolvedValueOnce(session); + const manager = new CdpManager(fake.context); + + await expect( + manager.sendToEventTarget( + { kind: 'sw', targetId: TARGET_ID, url: SW_URL }, + 'Network.getResponseBody', + ), + ).rejects.toThrowError(`CDP target ${TARGET_ID} is not attached`); + + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn() }); + await expect( + manager.sendToEventTarget( + { kind: 'page', targetId: 'page-1', url: PAGE_URL }, + 'Network.getResponseBody', + ), + ).rejects.toThrowError('CDP target page-1 is not attached'); + + await manager.dispose(); + await expect( + manager.sendToEventTarget( + { kind: 'page', targetId: 'page-1', url: PAGE_URL }, + 'Network.getResponseBody', + ), + ).rejects.toThrowError('CDP manager is disposed'); + }); + + it('times out a slow command', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + const session = createEventSession('page-1', async (method) => + method === 'Network.getResponseBody' ? new Promise(() => undefined) : {}, + ); + fake.newCDPSession.mockResolvedValueOnce(session); + const manager = new CdpManager(fake.context); + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn() }); + + await expect( + manager.sendToEventTarget( + { kind: 'page', targetId: 'page-1', url: PAGE_URL }, + 'Network.getResponseBody', + {}, + { timeoutMs: 5 }, + ), + ).rejects.toThrowError( + 'CDP call "Network.getResponseBody" timed out after 5ms', + ); + }); +}); diff --git a/src/platform/cdp-manager.ts b/src/platform/cdp-manager.ts index def59fea..69d11781 100644 --- a/src/platform/cdp-manager.ts +++ b/src/platform/cdp-manager.ts @@ -42,6 +42,11 @@ export type CdpSession = { */ export type CdpTargetLifecycleEvent = { kind: CdpTargetKind; + /** + * The CDP target ID. Always set for the Extension service worker; set for + * a page once the manager resolved it (the first event from the page). + */ + targetId?: string; /** * The page of a page target, or the worker of a service worker target when * Playwright reported one. The service worker is identified by its CDP @@ -610,7 +615,11 @@ type CdpEntryBase = { dropped?: boolean; }; -type PageEntry = CdpEntryBase & { page: Page }; +type PageEntry = CdpEntryBase & { + page: Page; + /** The CDP target ID, once the manager resolved it. */ + targetId?: string; +}; type ServiceWorkerEntry = CdpEntryBase & { /** The CDP target ID; a restarted worker has a new one. */ @@ -931,6 +940,71 @@ export class CdpManager { throw new CdpDomainInUseError(method, domain); } + /** + * Sends one command to the target a subscribed event came from, on its + * persistent session (for example `Network.getResponseBody` for a + * request). Only targets that are attached now are reached: a closed page + * or a stopped worker fails at once instead of being attached again. + * + * @param target - The target of a delivered {@link CdpEvent}. + * @param method - The CDP method. + * @param params - The CDP method parameters. + * @param options - Timeout and abort signal. + * @returns The raw CDP result. + */ + async sendToEventTarget( + target: CdpEventTarget, + method: string, + params: Record = {}, + options: CdpAttachOptions = {}, + ): Promise { + this.#assertLive(); + // The timeout covers the target lookup too: a hanging target-info call + // must not hold the caller longer than the timeout. + return this.#race( + this.#sendToAttachedTarget(target, method, params), + `CDP call "${method}"`, + options, + ); + } + + /** + * Finds the attached session of an event target and sends one command on + * it. + * + * @param target - The target of a delivered {@link CdpEvent}. + * @param method - The CDP method. + * @param params - The CDP method parameters. + * @returns The raw CDP result. + */ + async #sendToAttachedTarget( + target: CdpEventTarget, + method: string, + params: Record, + ): Promise { + let session: EventCdpSession | undefined; + if (target.kind === 'sw') { + session = this.#workerEntries.get(target.targetId)?.session; + } else { + for (const entry of this.#entries) { + if (!('page' in entry) || !entry.session) { + continue; + } + const targetId = await this.#sessionStates + .get(entry.session) + ?.targetId?.catch(() => undefined); + if (targetId === target.targetId) { + session = entry.session; + break; + } + } + } + if (!session) { + throw new Error(`CDP target ${target.targetId} is not attached`); + } + return session.send(method, params); + } + /** * Subscribes to a target event. * @@ -1625,6 +1699,8 @@ export class CdpManager { } const targetId = await state.targetId; const { page } = entry; + entry.targetId = targetId; + entry.event.targetId = targetId; return () => ({ kind: 'page', targetId, url: page.url() }); } @@ -1886,7 +1962,7 @@ export class CdpManager { targetId: target.targetId, url: target.url, worker, - event: { kind: 'sw', target: worker }, + event: { kind: 'sw', targetId: target.targetId, target: worker }, }; this.#workerEntries.set(target.targetId, entry); this.#entries.add(entry); diff --git a/src/tools/network.test.ts b/src/tools/network.test.ts new file mode 100644 index 00000000..2e5aa078 --- /dev/null +++ b/src/tools/network.test.ts @@ -0,0 +1,408 @@ +import type { BrowserContext } from '@playwright/test'; +import { describe, expect, it, vi } from 'vitest'; + +import { isErrorRequest, networkTool } from './network.js'; +import { createMockSessionManager } from './test-utils/mock-factories.js'; +import { ErrorCodes } from './types/errors.js'; +import type { NetworkRecord } from './types/events.js'; +import { getSessionEvents } from '../events/session-events.js'; +import type { ToolContext } from '../types/http.js'; + +vi.mock('../platform/cdp-manager.js', () => ({ + getCdpManager: vi.fn().mockReturnValue({ + subscribe: vi.fn().mockResolvedValue({ unsubscribe: vi.fn() }), + on: vi.fn(), + off: vi.fn(), + }), +})); + +const TARGET = { + kind: 'sw' as const, + id: 'W', + url: 'chrome-extension://x/bg.js', +}; + +/** + * Builds a tool context around a fake browser context. + * + * @param hasActive - Whether a session is active. + * @returns The context and its browser context. + */ +function createContext(hasActive = true): { + context: ToolContext; + browserContext: BrowserContext; +} { + const browserContext = {} as BrowserContext; + const sessionManager = createMockSessionManager({ hasActive }); + sessionManager.getContext.mockReturnValue(browserContext); + return { + context: { sessionManager } as unknown as ToolContext, + browserContext, + }; +} + +/** + * Appends a network record. + * + * @param browserContext - The browser context of the session. + * @param fields - Record fields. + * @returns The stored record. + */ +function addRequest( + browserContext: BrowserContext, + fields: Partial & { url: string }, +): NetworkRecord { + return getSessionEvents(browserContext).buffer.append( + 'network', + { + t: 100, + target: TARGET, + method: 'GET', + type: 'fetch', + ...fields, + }, + ); +} + +/** + * Marks a request final. + * + * @param browserContext - The browser context of the session. + * @param record - The request record. + * @returns The record. + */ +function settleRequest( + browserContext: BrowserContext, + record: NetworkRecord, +): NetworkRecord { + getSessionEvents(browserContext).buffer.settle('network', record); + return record; +} + +describe('isErrorRequest', () => { + it.each([ + [{ status: 200 }, false], + [{}, false], + [{ status: 404 }, true], + [{ failure: 'net::ERR_ABORTED' }, true], + [{ status: 200, rpcError: { message: 'x' } }, true], + ])('%j → %s', (fields, expected) => { + expect( + isErrorRequest({ + seq: 1, + t: 1, + target: TARGET, + method: 'GET', + url: 'u', + type: 'fetch', + ...fields, + }), + ).toBe(expected); + }); +}); + +describe('networkTool', () => { + it('fails without a session', async () => { + const { context } = createContext(false); + expect(await networkTool({}, context)).toMatchObject({ + ok: false, + error: { code: ErrorCodes.MM_NO_ACTIVE_SESSION }, + }); + }); + + it('reads requests with filters, paging and stats', async () => { + const { context, browserContext } = createContext(); + const first = addRequest(browserContext, { + url: 'https://gas.api.cx.metamask.io/a', + status: 200, + }); + const second = addRequest(browserContext, { + url: 'https://mainnet.infura.io/v3/x', + status: 404, + }); + const third = addRequest(browserContext, { + url: 'https://gas.api.cx.metamask.io/b', + failure: 'net::ERR_ABORTED', + }); + settleRequest(browserContext, first); + settleRequest(browserContext, second); + settleRequest(browserContext, third); + + const all = await networkTool({}, context); + expect(all).toMatchObject({ + ok: true, + result: { + cursor: 6, + hasMore: false, + gap: false, + stats: { pending: 0, ignored: 0, rpcErrorsSkipped: 0 }, + }, + }); + expect( + all.ok && 'records' in all.result && all.result.records, + ).toHaveLength(3); + + // Filtered reads are in settle order and page by settle position. + const errors = await networkTool({ errors: true, limit: 1 }, context); + expect(errors).toMatchObject({ + ok: true, + result: { records: [{ seq: 2 }], hasMore: true, cursor: 5 }, + }); + const errorsNext = await networkTool( + { errors: true, limit: 1, cursor: 5 }, + context, + ); + expect(errorsNext).toMatchObject({ + ok: true, + result: { records: [{ seq: 3 }], hasMore: false, cursor: 6 }, + }); + + const url = await networkTool( + { url: 'https://gas.api.cx.metamask.io/**', cursor: 4 }, + context, + ); + expect(url).toMatchObject({ ok: true, result: { records: [{ seq: 3 }] } }); + + const both = await networkTool( + { url: 'gas.api', errors: true, since: 50, action: 'read' }, + context, + ); + expect(both).toMatchObject({ ok: true, result: { records: [{ seq: 3 }] } }); + }); + + it('returns a request that ends after a filtered read, even when it started before the cursor', async () => { + const { context, browserContext } = createContext(); + const events = getSessionEvents(browserContext); + await events.ensureStarted(); + const pending = addRequest(browserContext, { + url: 'https://gas.api.cx.metamask.io/pending', + }); + + const first = await networkTool({ errors: true }, context); + expect(first).toMatchObject({ + ok: true, + result: { records: [], cursor: pending.seq, hasMore: false }, + }); + + pending.failure = 'net::ERR_ABORTED'; + settleRequest(browserContext, pending); + const second = await networkTool( + { errors: true, cursor: pending.seq }, + context, + ); + expect(second).toMatchObject({ + ok: true, + result: { + records: [{ seq: pending.seq, failure: 'net::ERR_ABORTED' }], + cursor: pending.seq + 1, + }, + }); + + const third = await networkTool( + { errors: true, cursor: pending.seq + 1 }, + context, + ); + expect(third).toMatchObject({ ok: true, result: { records: [] } }); + }); + + it('returns an open request after a stale cursor read', async () => { + const { context, browserContext } = createContext(); + const events = getSessionEvents(browserContext); + await events.ensureStarted(); + const pending = addRequest(browserContext, { + url: 'https://gas.api.cx.metamask.io/pending', + }); + + // A cursor from an earlier session reads from the start, reports the + // gap, and returns the newest position: the request is still open, so + // it is not returned, but its late failure stays after that position. + const first = await networkTool({ errors: true, cursor: 5 }, context); + expect(first).toMatchObject({ + ok: true, + result: { records: [], cursor: pending.seq, gap: true }, + }); + + pending.failure = 'net::ERR_ABORTED'; + settleRequest(browserContext, pending); + const second = await networkTool( + { errors: true, cursor: pending.seq }, + context, + ); + expect(second).toMatchObject({ + ok: true, + result: { + records: [{ seq: pending.seq, failure: 'net::ERR_ABORTED' }], + cursor: pending.seq + 1, + }, + }); + }); + + it('returns an older request that ends after a filtered read, once', async () => { + const { context, browserContext } = createContext(); + const events = getSessionEvents(browserContext); + await events.ensureStarted(); + const open = addRequest(browserContext, { + url: 'https://gas.api.cx.metamask.io/slow', + }); + settleRequest( + browserContext, + addRequest(browserContext, { + url: 'https://mainnet.infura.io/v3/x', + status: 500, + }), + ); + + const first = await networkTool({ errors: true }, context); + expect(first).toMatchObject({ + ok: true, + result: { records: [{ seq: 2 }], cursor: 3 }, + }); + + // The older record settles after the read: its settle position is + // above the returned cursor, so the next read returns it once. + open.failure = 'net::ERR_ABORTED'; + settleRequest(browserContext, open); + const second = await networkTool({ errors: true, cursor: 3 }, context); + expect(second).toMatchObject({ + ok: true, + result: { + records: [{ seq: 1, failure: 'net::ERR_ABORTED' }], + cursor: 4, + }, + }); + const third = await networkTool({ errors: true, cursor: 4 }, context); + expect(third).toMatchObject({ ok: true, result: { records: [] } }); + }); + + it('pages late failures with limit 1', async () => { + const { context, browserContext } = createContext(); + const events = getSessionEvents(browserContext); + await events.ensureStarted(); + const first = addRequest(browserContext, { + url: 'https://gas.api.cx.metamask.io/1', + }); + const second = addRequest(browserContext, { + url: 'https://mainnet.infura.io/v3/x', + }); + const third = addRequest(browserContext, { + url: 'https://gas.api.cx.metamask.io/3', + }); + second.status = 500; + settleRequest(browserContext, second); + first.failure = 'net::ERR_FAILED'; + settleRequest(browserContext, first); + third.failure = 'net::ERR_ABORTED'; + settleRequest(browserContext, third); + + const page1 = await networkTool({ errors: true, limit: 1 }, context); + expect(page1).toMatchObject({ + ok: true, + result: { records: [{ seq: 2 }], cursor: 4, hasMore: true }, + }); + const page2 = await networkTool( + { errors: true, limit: 1, cursor: 4 }, + context, + ); + expect(page2).toMatchObject({ + ok: true, + result: { records: [{ seq: 1 }], cursor: 5, hasMore: true }, + }); + const page3 = await networkTool( + { errors: true, limit: 1, cursor: 5 }, + context, + ); + expect(page3).toMatchObject({ + ok: true, + result: { records: [{ seq: 3 }], cursor: 6, hasMore: false }, + }); + }); + + it('reads settled requests in settle order with settled: true', async () => { + const { context, browserContext } = createContext(); + const events = getSessionEvents(browserContext); + await events.ensureStarted(); + const started = addRequest(browserContext, { + url: 'https://gas.api.cx.metamask.io/started-before-mark', + }); + addRequest(browserContext, { + url: 'https://gas.api.cx.metamask.io/still-open', + }); + + // At the mark, nothing has settled. + const mark = await networkTool({ settled: true }, context); + expect(mark).toMatchObject({ + ok: true, + result: { records: [], cursor: 2, gap: false }, + }); + const markCursor = (mark as { result: { cursor: number } }).result.cursor; + + // The request started before the mark ends after it: a settled read + // from the mark returns it, with its final status. + started.status = 200; + settleRequest(browserContext, started); + const afterEnd = await networkTool( + { settled: true, cursor: markCursor }, + context, + ); + expect(afterEnd).toMatchObject({ + ok: true, + result: { + records: [{ seq: 1, status: 200 }], + hasMore: false, + cursor: 3, + }, + }); + + // The other request is still open, and a repeated read with the returned + // cursor returns neither record again. + const repeat = await networkTool({ settled: true, cursor: 3 }, context); + expect(repeat).toMatchObject({ ok: true, result: { records: [] } }); + }); + + it('keeps unfiltered reads on start order and pending records', async () => { + const { context, browserContext } = createContext(); + const events = getSessionEvents(browserContext); + await events.ensureStarted(); + const pending = addRequest(browserContext, { + url: 'https://gas.api.cx.metamask.io/pending', + }); + settleRequest( + browserContext, + addRequest(browserContext, { + url: 'https://gas.api.cx.metamask.io/done', + status: 200, + }), + ); + + const first = await networkTool({}, context); + expect(first).toMatchObject({ + ok: true, + result: { records: [{ seq: 1 }, { seq: 2 }], cursor: 3 }, + }); + + // A record updated in place keeps its seq: an unfiltered read past it + // never returns it again, unlike a filtered read (which uses settle + // positions). + pending.failure = 'net::ERR_ABORTED'; + settleRequest(browserContext, pending); + const again = await networkTool({ cursor: 3 }, context); + expect(again).toMatchObject({ ok: true, result: { records: [] } }); + }); + + it('configure turns rpcErrors on and off', async () => { + const { context, browserContext } = createContext(); + const events = getSessionEvents(browserContext); + + expect( + await networkTool({ action: 'configure', rpcErrors: true }, context), + ).toMatchObject({ + ok: true, + result: { action: 'configure', config: { rpcErrors: true } }, + }); + expect(events.config.rpcErrors).toBe(true); + expect(events.config.consoleLevels).toStrictEqual(['error']); + + await networkTool({ action: 'configure', rpcErrors: false }, context); + expect(events.config.rpcErrors).toBe(false); + }); +}); diff --git a/src/tools/network.ts b/src/tools/network.ts new file mode 100644 index 00000000..5db89d3e --- /dev/null +++ b/src/tools/network.ts @@ -0,0 +1,82 @@ +import { matchesUrlFilter } from './mock-network.js'; +import type { NetworkInput, NetworkRecord, NetworkResult } from './types'; +import { createToolSuccess, requireActiveSession } from './utils.js'; +import { + DEFAULT_EVENT_READ_LIMIT, + parseSince, +} from '../events/read-options.js'; +import { getSessionEvents } from '../events/session-events.js'; +import type { ToolContext, ToolResponse } from '../types/http.js'; + +/** + * Checks whether a request is an error: HTTP status 400 or more, a + * failure, or a JSON-RPC error. + * + * @param record - The request. + * @returns True for an error. + */ +export function isErrorRequest(record: NetworkRecord): boolean { + return ( + record.failure !== undefined || + (record.status !== undefined && record.status >= 400) || + record.rpcError !== undefined + ); +} + +/** + * Reads the HTTP(S) requests of every page and the Extension service worker + * (`mm network`), or turns JSON-RPC error reading on or off + * (`mm network configure`). + * + * An unfiltered read returns every record in start order and advances past + * every record, pending or not. A read with `url` or `errors` returns only + * settled requests, in settle order: a request may become a match only when + * it ends (a 404, a failure, a `rpcError`), so it is returned by the read + * that follows its end, once, also when it started long before the cursor. + * An unsettled request is never returned by a filtered read, and a request + * that never ends therefore never matches one. `settled: true` asks for the + * same settle-order read without a filter, so a consumer can read the final + * status of every request that ended after the cursor, including ones it + * started earlier. `since` compares the request start time (`t`). + * + * @param input - Read options, or the `configure` action. + * @param context - The tool execution context. + * @returns A page of network records, or the new config. + */ +export async function networkTool( + input: NetworkInput, + context: ToolContext, +): Promise> { + const missingSession = requireActiveSession(context); + if (missingSession) { + return missingSession; + } + + const events = getSessionEvents(context.sessionManager.getContext()); + await events.ensureStarted(); + + if (input.action === 'configure') { + events.config = { ...events.config, rpcErrors: input.rpcErrors }; + return createToolSuccess({ + action: 'configure', + config: { rpcErrors: events.config.rpcErrors }, + summary: events.buffer.summary(), + }); + } + + const { url, errors } = input; + const filtered = url !== undefined || errors === true; + const page = events.buffer.read({ + kind: 'network', + cursor: input.cursor, + since: parseSince(input.since), + limit: input.limit ?? DEFAULT_EVENT_READ_LIMIT, + settled: filtered || input.settled === true, + filter: filtered + ? (record): boolean => + (url === undefined || matchesUrlFilter(url, record.url)) && + (errors !== true || isErrorRequest(record)) + : undefined, + }); + return createToolSuccess({ ...page, stats: { ...events.networkStats } }); +} diff --git a/src/tools/platform-gating.test.ts b/src/tools/platform-gating.test.ts index cac2c162..f832aa66 100644 --- a/src/tools/platform-gating.test.ts +++ b/src/tools/platform-gating.test.ts @@ -16,6 +16,7 @@ describe('isBrowserOnlyTool', () => { expect(isBrowserOnlyTool('mock_network')).toBe(true); expect(isBrowserOnlyTool('events')).toBe(true); expect(isBrowserOnlyTool('logs')).toBe(true); + expect(isBrowserOnlyTool('network')).toBe(true); expect(isBrowserOnlyTool('reload')).toBe(true); expect(isBrowserOnlyTool('build')).toBe(true); expect(isBrowserOnlyTool('inspect')).toBe(true); diff --git a/src/tools/registry.test.ts b/src/tools/registry.test.ts index 665ec2df..6bed796e 100644 --- a/src/tools/registry.test.ts +++ b/src/tools/registry.test.ts @@ -24,6 +24,7 @@ describe('toolRegistry', () => { 'mock_network', 'events', 'logs', + 'network', 'run_steps', 'cdp', 'hermes_targets', @@ -43,7 +44,7 @@ describe('toolRegistry', () => { }); it('has the expected number of entries', () => { - expect(toolRegistry.size).toBe(51); + expect(toolRegistry.size).toBe(52); }); it('stores only functions as values', () => { @@ -97,7 +98,7 @@ describe('TOOL_CATEGORIES and getToolCategory', () => { }, ); - it.each(['events', 'logs'])( + it.each(['events', 'logs', 'network'])( 'getToolCategory returns readonly for %s', (toolName) => { expect(getToolCategory(toolName)).toBe('readonly'); @@ -135,6 +136,7 @@ describe('isBrowserOnlyTool', () => { 'mock_network', 'events', 'logs', + 'network', 'reload', 'build', 'inspect', diff --git a/src/tools/registry.ts b/src/tools/registry.ts index ce2250b5..e7d15572 100644 --- a/src/tools/registry.ts +++ b/src/tools/registry.ts @@ -48,6 +48,7 @@ import { switchToTabTool, waitForNotificationTool, } from './navigation.js'; +import { networkTool } from './network.js'; import { screenshotTool } from './screenshot.js'; import { getContractAddressTool, @@ -102,6 +103,7 @@ export const toolRegistry = new Map>([ ['mock_network', mockNetworkTool], ['events', eventsTool], ['logs', logsTool], + ['network', networkTool], ['scroll_to_element', scrollToElementTool], ['device_swipe', deviceSwipeTool], ['long_press', longPressTool], @@ -169,7 +171,7 @@ export const TOOL_CATEGORIES: Record = { press_button: 'mutating', device_context: 'mutating', device_clipboard: 'mutating', - // READONLY (15) + // READONLY (16) hermes_targets: 'readonly', get_window_size: 'readonly', get_alert_text: 'readonly', @@ -189,6 +191,7 @@ export const TOOL_CATEGORIES: Record = { // `events clear` empties the session event buffer; it never touches the UI. events: 'readonly', logs: 'readonly', + network: 'readonly', // DISCOVERY (4) describe_screen: 'discovery', list_testids: 'discovery', @@ -221,6 +224,7 @@ const BROWSER_ONLY_TOOLS = new Set([ 'mock_network', 'events', 'logs', + 'network', 'reload', 'build', 'inspect', diff --git a/src/tools/types/events.ts b/src/tools/types/events.ts index 2a6b0221..f0b7e6f8 100644 --- a/src/tools/types/events.ts +++ b/src/tools/types/events.ts @@ -87,4 +87,55 @@ export type ConsoleRecord = EventRecordBase & { export type EventConfig = { /** Console levels to record. Default `['error']`. */ consoleLevels: ConsoleLevel[]; + /** Read JSON-RPC response bodies for `rpcError`. Default false. */ + rpcErrors: boolean; +}; + +/** The JSON-RPC error of a response (`mm network configure --rpc-errors`). */ +export type RpcError = { + /** The JSON-RPC error code, when it is a number. */ + code?: number; + /** The error message, redacted and cut at 300 characters. */ + message: string; +}; + +/** + * One HTTP(S) request of a page or the Extension service worker + * (`mm network`). Created when the request starts and updated in place as + * it ends; it keeps its first `seq` and gets a `settledSeq` when it ends + * (or its JSON-RPC error is read). + */ +export type NetworkRecord = EventRecordBase & { + /** + * Position of the request when it settled, that is, when no field of it + * changed any more. Absent while pending. A filtered `mm network` read + * returns settled records in this order. + */ + settledSeq?: number; + /** HTTP method. */ + method: string; + /** The URL, redacted. */ + url: string; + /** Lowercase CDP resource type, for example `fetch`, `xhr`, `document`. */ + type: string; + /** HTTP status. Absent while pending and for a request that failed before a response. */ + status?: number; + /** Duration from start to the end of the response or the failure. Absent while pending. */ + ms?: number; + /** Failure text, for example `net::ERR_ABORTED`. */ + failure?: string; + /** JSON-RPC methods of the request body (one for a single call, in order for a batch). */ + rpcMethods?: string[]; + /** JSON-RPC error of the response. Only with `mm network configure --rpc-errors`. */ + rpcError?: RpcError; +}; + +/** Counters of the network source, returned by `mm network`. */ +export type NetworkStats = { + /** Requests started and not finished yet. */ + pending: number; + /** Requests not recorded because their URL is not http(s) (extension files, `data:`). */ + ignored: number; + /** JSON-RPC responses not read for `rpcError` (too large, too many at once, timeout). */ + rpcErrorsSkipped: number; }; diff --git a/src/tools/types/tool-inputs.ts b/src/tools/types/tool-inputs.ts index 685fcbf0..41026a6e 100644 --- a/src/tools/types/tool-inputs.ts +++ b/src/tools/types/tool-inputs.ts @@ -334,6 +334,32 @@ export type LogsInput = } & EventReadInput) | { action: 'configure'; levels: ConsoleLevel[] }; +export type NetworkInput = + | ({ + action?: 'read'; + /** + * URL glob (`*`, `**`) or, without `*`, text the URL must contain. A + * filtered read returns only settled requests, so a request that + * matches when it ends is returned by the read that follows its end. + */ + url?: string; + /** + * Only errors: HTTP status >= 400, `failure`, or `rpcError`. A + * filtered read returns only settled requests, so a request that + * becomes an error when it ends is returned by the read that follows + * its end. + */ + errors?: boolean; + /** + * Return only settled requests, in settle order, without needing a + * filter: at the end of a step, read the final status of every request + * that ended after the cursor, including ones started earlier. + * Requests still open are not returned yet. + */ + settled?: boolean; + } & EventReadInput) + | { action: 'configure'; rpcErrors: boolean }; + export type EventsInput = | { action: 'mark' } | { action: 'clear'; kind?: EventKind }; diff --git a/src/tools/types/tool-outputs.ts b/src/tools/types/tool-outputs.ts index 6cc1532e..1d4c4419 100644 --- a/src/tools/types/tool-outputs.ts +++ b/src/tools/types/tool-outputs.ts @@ -5,6 +5,8 @@ import type { EventKind, EventPage, EventSummary, + NetworkRecord, + NetworkStats, } from './events.js'; import type { NetworkMockRequestRecord, @@ -313,6 +315,14 @@ export type LogsResult = summary: EventSummary; }; +export type NetworkResult = + | (EventPage & { stats: NetworkStats }) + | { + action: 'configure'; + config: { rpcErrors: boolean }; + summary: EventSummary; + }; + export type SetContextResult = { previousContext: 'e2e' | 'prod'; newContext: 'e2e' | 'prod'; diff --git a/src/validation/schemas.test.ts b/src/validation/schemas.test.ts index 4ac93cca..6bf92d15 100644 --- a/src/validation/schemas.test.ts +++ b/src/validation/schemas.test.ts @@ -21,6 +21,7 @@ import { mockNetworkInputSchema, eventsInputSchema, logsInputSchema, + networkInputSchema, launchInputSchema, scrollToElementInputSchema, clickInputSchema, @@ -622,6 +623,36 @@ describe('logsInputSchema', () => { }); }); +describe('networkInputSchema', () => { + it('accepts reads and configure', () => { + expect(networkInputSchema.safeParse({}).success).toBe(true); + expect( + networkInputSchema.safeParse({ + cursor: 4, + limit: 10, + url: '**infura**', + errors: true, + settled: true, + }).success, + ).toBe(true); + expect( + networkInputSchema.safeParse({ action: 'configure', rpcErrors: true }) + .success, + ).toBe(true); + }); + + it('rejects unknown fields and a configure without rpcErrors', () => { + expect(networkInputSchema.safeParse({ grep: 'x' }).success).toBe(false); + expect(networkInputSchema.safeParse({ url: '' }).success).toBe(false); + expect(networkInputSchema.safeParse({ action: 'configure' }).success).toBe( + false, + ); + expect(networkInputSchema.safeParse({ settled: 'true' }).success).toBe( + false, + ); + }); +}); + describe('launchInputSchema', () => { it('preserves platform field', () => { const input = { platform: 'ios' }; diff --git a/src/validation/schemas.ts b/src/validation/schemas.ts index 3132fd33..295f4eeb 100644 --- a/src/validation/schemas.ts +++ b/src/validation/schemas.ts @@ -942,6 +942,44 @@ export const logsInputSchema = z.union([ .strict(), ]); +export const networkInputSchema = z.union([ + z + .object({ + action: z.literal('read').optional(), + ...eventReadFields, + url: z + .string() + .min(1) + .describe( + 'Only requests whose URL matches this glob (* and **) or, without *, contains this text', + ) + .optional(), + errors: z + .boolean() + .describe('Only errors: HTTP status >= 400, failure, or rpcError') + .optional(), + settled: z + .boolean() + .describe( + 'Return only settled requests, in settle order, without a filter: ' + + 'every request that ended after the cursor, including ones ' + + 'started earlier. Requests still open are not returned', + ) + .optional(), + }) + .strict(), + z + .object({ + action: z.literal('configure'), + rpcErrors: z + .boolean() + .describe( + 'Read JSON-RPC response bodies (up to 64 KiB) and record their error as rpcError. Default false', + ), + }) + .strict(), +]); + export const cdpInputSchema = z.object({ method: z .string() @@ -1201,6 +1239,7 @@ export type HermesTargetsInputZ = z.infer; export type MockNetworkInputZ = z.infer; export type EventsInputZ = z.infer; export type LogsInputZ = z.infer; +export type NetworkInputZ = z.infer; export type ScrollToElementInputZ = z.infer; export type DeviceSwipeInputZ = z.infer; export type LongPressInputZ = z.infer; @@ -1256,6 +1295,7 @@ export const toolSchemas = { mock_network: withObserve(mockNetworkInputSchema), events: withObserve(eventsInputSchema), logs: withObserve(logsInputSchema), + network: withObserve(networkInputSchema), scroll_to_element: withObserve(scrollToElementInputSchema), device_swipe: withObserve(deviceSwipeInputSchema), long_press: withObserve(longPressInputSchema),