diff --git a/docs/configuration.md b/docs/configuration.md index cf9c5491..a9534727 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -60,9 +60,9 @@ TRAP_TCP_PORTS=9912,8000 vendor/bin/trap | `TRAP_XDEBUG_TRACE_MAX_SIZE` | `256M` | Uncompressed bytes read of an Xdebug trace; a longer one is cut there. | | `TRAP_XDEBUG_TRACE_KEEP` | `20` | Xdebug traces kept on disk; a new one deletes the oldest with its event. | | `TRAP_XDEBUG_*` | | Settings of the [Xdebug debugger](xdebug.md#settings): port, IDE address, mode, eval, agent control, idle timeout. | -| `TRAP_TRACES_MAX_SPANS` | `10000` | Maximum number of kept [OpenTelemetry](opentelemetry.md#memory-limits) spans. | -| `TRAP_TRACES_TTL` | `600` | Seconds an OpenTelemetry trace is kept after its last received span. | -| `TRAP_TELEMETRY_MAX_SPANS` | `10000` | Maximum number of transactions and spans the [Sentry pages](web-ui.md#sentry-pages) of the web UI keep. | +| `TRAP_TRACES_MAX_SPANS` | `10000` | Maximum number of [OpenTelemetry](opentelemetry.md#memory-limits) spans the console keeps to print a trace as a tree. | +| `TRAP_TRACES_TTL` | `600` | Seconds the console keeps an OpenTelemetry trace after its last received span. | +| `TRAP_TELEMETRY_MAX_SPANS` | `10000` | Maximum number of transactions and spans of the traces the [Sentry pages](web-ui.md#sentry-pages) of the web UI and the [MCP tools](mcp.md#traces) read. | | `TRAP_TELEMETRY_MAX_LOGS` | `5000` | Maximum number of log records the Sentry pages of the web UI keep. | | `TRAP_TELEMETRY_MAX_METRICS` | `5000` | Maximum number of metric values the Sentry pages of the web UI keep. | diff --git a/docs/mcp.md b/docs/mcp.md index 98779a75..fea96e39 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17,9 +17,9 @@ Other clients take the same URL with the `http` (Streamable HTTP) transport type ## Tools -The tools read the events Trap has caught, the [traces](#traces) it has received and the call trees of -[Xdebug traces](#xdebug-traces). The events are the ones the -[web UI](web-ui.md) shows, kept with `--mcp` alone too. An event deleted in the UI is gone for the agent. An event +The tools read the events Trap has caught, the Sentry and OpenTelemetry [traces](#traces) it has received, and the +call trees of [Xdebug traces](#xdebug-traces). The events are the ones the [web UI](web-ui.md) shows, kept with +`--mcp` alone too. An event deleted in the UI is gone for the agent. An event the agent deletes is gone from the UI on its next load; a page already open keeps showing it. | Tool | Arguments | Result | @@ -222,14 +222,16 @@ prints it: The body and the other sections are shown as sent. The query is one line of up to 300 characters; the request is at most 16 KB with its body, and the headers past that are left out and counted. - The contexts, such as `runtime`, `os` and `trace` with its IDs, one line each; the latest breadcrumbs, oldest first; - the extra data; the spans of a transaction with their durations. + the extra data. - An envelope of several items shows each of them under `--- Item 2 of 3: attachment ---`: an attachment by its - name, type and size; an item that is not an event, such as `session`, `client_report` or `check_in`, by its - fields in one line. The web UI shows the first item only. A search looks through the first 64 KB of the whole - envelope, so the details of later items may not be found. + name, type and size; a transaction, sent with the error, by its name, duration, number of spans (itself included) + and trace ID, to read with [`get_trace`](#traces), or as an event when it has no trace ID; an item that is not an + event, such as `session`, `client_report` or `check_in`, by its fields in one line. The web UI shows the first + item only. A search looks through the first 64 KB of the whole envelope, so the details of later items may not be + found. The sections come in this order: the metadata, the exception chain, the request, the contexts, the breadcrumbs, the -extra data and the spans. A [search](#filters) looks through the first 64 KB of the text, so the causes that would +extra data. A [search](#filters) looks through the first 64 KB of the text, so the causes that would take the chain past 32 KB are left out and counted; past less than 32 KB when the metadata and the request are large, so that the contexts and the breadcrumbs start within the 64 KB. A thrown exception larger than that is shown without the code and variables of its frames, and then with fewer frame lines; so is the stack trace of an event @@ -247,7 +249,6 @@ Bounds; what is left out is counted, as `… 5 more …`: | Request headers | 15 in 16 KB of the request with its body | | Breadcrumbs | the last 10 | | Tags, user fields, contexts, extra entries | 20 | -| Spans | 20 | | Items of an envelope | 20 | | Characters of an exception value, message, body | 2 000 | | Characters of another value | 300; of a code line, 200 | @@ -290,29 +291,42 @@ Contexts: ### Traces -[OpenTelemetry traces](opentelemetry.md) are not events: the tools read the spans Trap keeps to join the spans of one -trace sent in separate requests, with `--mcp` alone too. The limits of that store, -[`TRAP_TRACES_MAX_SPANS` and `TRAP_TRACES_TTL`](opentelemetry.md#memory-limits), apply. +Traces are not events: [Sentry transactions and spans](sentry.md#what-an-envelope-gives) and +[OpenTelemetry spans](opentelemetry.md) go to the trace store the [Sentry pages](web-ui.md#sentry-pages) of the web +UI show, and the tools read it, with `--mcp` alone too. Its limit, +[`TRAP_TELEMETRY_MAX_SPANS`](web-ui.md#sentry-pages), applies: above it the least recently updated traces are +dropped. Clearing the Sentry pages of the web UI drops their traces for the tools too. -| Tool | Arguments | Result | -| ------------- | --------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -| `list_traces` | `since` (cursor), `limit`, `errors_only`, `from`, `to`, `service`, `name`, `min_duration_ms`, `search`, `regex` | `traces`: `id`, `name`, `service`, `spans`, `duration_ms`, `error`, `updated` each; `cursor`; `has_more` | -| `get_trace` | `id`, `max_length` | The trace as plain text: a header line, then the tree of all its spans as the console prints it | +| Tool | Arguments | Result | +| ------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- | +| `list_traces` | `since` (cursor), `limit`, `project`, `source`, `errors_only`, `from`, `to`, `service`, `name`, `min_duration_ms`, `search`, `regex` | `traces`: `id`, `name`, `service`, `services`, `sources`, `projects`, `spans`, `duration_ms`, `error`, `updated` each; `cursor`; `has_more` | +| `get_trace` | `id`, `max_length` | The trace as plain text: a header line, then the tree of all its spans as the console prints OpenTelemetry traces | - `list_traces` returns the traces updated after `since`, least recently updated first, at most `limit` of them - (20 by default, 100 at most). A trace is updated by every span that arrives for it, and an updated trace is listed - again. When `has_more` is true, call again with the returned `cursor` to get the rest. -- `name` is of the root span; while it has not arrived, of the earliest span whose parent is missing. - `service` is the `service.name` of the resource of that span; when that resource has none, of another span. -- `errors_only` lists only the traces with a span of the error status. + (20 by default, 100 at most). A trace is updated by every span or transaction that arrives for it, and an updated + trace is listed again. When `has_more` is true, call again with the returned `cursor` to get the rest. +- `name` is of the root transaction: a Sentry transaction or the entry span of a service, the one without a parent + first. While no transaction has arrived, it is of the earliest span whose parent is missing. `service` is the + service of that root; when it has none, of another span. `services`, `sources` (`sentry`, `otel`) and `projects` + list those of every part of the trace: a distributed trace may cross several. +- `spans` counts the spans and the transactions. `error` is true when one of them failed: an OpenTelemetry span of + the error status, a Sentry one of `internal_error`, `unknown_error` or `error`. +- `project` is one project or a list, as in [the event filter](#filters): only the part of each trace sent to those + projects is listed and summed up. `source` is `sentry` or `otel`: only the traces with a part from it. +- `errors_only` lists only the traces with a failed span or transaction. - `from` and `to` take the times of [the event filter](#filters) and match the time of the last update. - `service` is one service or a list, and `name` a name; both match in any case, with `*` for any characters. + `service` matches any service of the trace; `*` takes a trace without services too. - `min_duration_ms` lists only the traces that last that long or longer. -- `search` and `regex` match as in [the event filter](#filters), over the spans: their names, status messages, - attributes, and events, such as an exception with its message, and over the attributes of their resources, - one `key=value` line per attribute. +- `search` and `regex` match as in [the event filter](#filters), over the spans: their names (a Sentry span is named + `op: description`), status messages, attributes, and events, such as an exception with its message, and over the + attributes of OpenTelemetry resources, one `key=value` line per attribute. - Slow traces of the last hour: `{"from": "1h", "min_duration_ms": 500}`; failed checkouts: `{"errors_only": true, "name": "POST /checkout*"}`. +- `get_trace` takes the ID of `list_traces`, or the trace ID of a Sentry error from its `trace` context. The header + line holds the number of spans, the services, sources and projects, whether a span failed, and the time of the + last update. A Sentry span shows its op and description as its name, a kind read from its op (`http.server` is + `SERVER`, `http.client` `CLIENT`, `queue.publish` `PRODUCER`, `queue.process` `CONSUMER`, others `INTERNAL`), its `data` as attributes and a failure status as `ERROR`. - `get_trace` cuts a text longer than `max_length` characters, 50 000 by default, and says so. ### Profiles diff --git a/docs/opentelemetry.md b/docs/opentelemetry.md index 55d3f854..4c05fccf 100644 --- a/docs/opentelemetry.md +++ b/docs/opentelemetry.md @@ -49,8 +49,7 @@ The Phar, the standalone binary and the Docker image do not include them, so the ## Memory limits Spans of one trace often arrive in separate requests (a simple span processor exports each span on its own), -so Trap keeps received spans in memory to print them together. With [`--mcp`](mcp.md#traces) the MCP server -keeps a copy of its own for the agents. Each copy is limited by: +so the console keeps the spans it has printed in memory to print a trace as a tree. That buffer is limited by: - `TRAP_TRACES_MAX_SPANS` - the maximum number of kept spans; the least recently updated traces are dropped above it, and a single trace above it keeps only its most recent spans (default: `10000`) @@ -59,7 +58,9 @@ keeps a copy of its own for the agents. Each copy is limited by: The same limits can be set in [`trap.xml`](configuration.md#trapxml): ``. Non-positive or non-numeric values fall back to the defaults. -The web UI keeps its own traces, logs and metrics, see [web UI limits](web-ui.md#sentry-pages). +The web UI and the [MCP server](mcp.md#traces) read one store of traces, logs and metrics, the one of the Sentry +pages, with the [`TRAP_TELEMETRY_*` limits](web-ui.md#sentry-pages). It keeps a trace until the limit pushes it out, +however long ago its last span came. ## Saving to a file @@ -68,7 +69,8 @@ With the [`file` sender](senders.md#file), each export request is saved as one J ## Notes -- Traces are given to AI agents by the [MCP server](mcp.md#traces); logs and metrics are not. +- Traces are given to AI agents by the [MCP server](mcp.md#traces), along with Sentry traces; logs and metrics + are not. - Exporters running in a browser are not supported: Trap does not answer CORS preflight requests. - One export request may carry up to 10 MB (after decompression) and up to 10 000 spans, log records or metric data points; a bigger one gets `413`. SDK batch processors export 512 spans at a time by default. diff --git a/docs/sentry.md b/docs/sentry.md index 77495733..2fd3f992 100644 --- a/docs/sentry.md +++ b/docs/sentry.md @@ -27,14 +27,21 @@ With [`--mcp`](mcp.md#sentry-events), AI agents read the events with their excep | Envelope item | Becomes | |---------------------------------------|-----------------------------------------------------------------------------| | `event`, `feedback` | a `sentry` event: the console, the event feed of the web UI, the MCP server | -| `transaction` | a `sentry` event, and a trace on the Traces page of the web UI | +| `transaction` | a trace: the Traces page of the web UI, the MCP trace tools | +| `transaction` without a trace ID | a `sentry` event, as `event` is: no trace can hold it | | `span`, `spans` (Span v2) | spans of a trace; a segment span is the transaction of its service | | `log` | log records on the Logs page of the web UI | | `trace_metric` | metric values on the Metrics page of the web UI | | sessions, client reports, attachments | nothing | -An envelope of only logs, metrics, spans or SDK bookkeeping makes no event. The [web UI](web-ui.md#sentry-pages) -shows the traces, logs and metrics only while it runs. +The event feed holds the errors. A transaction is a trace, not an event, also when an older SDK sends it to +`…/store/`: the console prints one line for it, with its name, duration, number of spans (the transaction included), +the failed ones and the trace ID, and AI agents read it with [`list_traces` and `get_trace`](mcp.md#traces). Spans +sent without a transaction get the same line, named after their root span. An envelope of an error and the +transaction of its request gives the error event and the trace. A `/store` payload with an exception is an error, +whatever its type. A transaction without a trace ID fits no trace and stays a `sentry` event; the console prints +one line for it too. An envelope of only transactions, logs, metrics, spans or SDK bookkeeping makes no event. Trap +keeps the traces, logs and metrics while the [web UI](web-ui.md#sentry-pages) or the [MCP server](mcp.md) runs. The `X-Buggregator-Project` header puts the event and the data of the request into that project of the web UI; without it they land in `default`. diff --git a/docs/web-ui.md b/docs/web-ui.md index fee7b102..e84f4a8a 100644 --- a/docs/web-ui.md +++ b/docs/web-ui.md @@ -74,9 +74,10 @@ The Sentry section has a page for each kind of data: that service sends its data to Trap too. - Logs and Metrics: Sentry `log` and `trace_metric` items, OTLP logs and metrics. -Traces, logs and metrics make no events in the feed. Trap keeps them in memory while the UI or the -[MCP server](mcp.md) runs, and the UI asks for them by project and period. "Clear all" in the Sentry section -deletes them with the Sentry events. +Traces, logs and metrics make no events in the feed: a Sentry transaction is a trace, and the feed holds the errors. +Trap keeps them in memory while the UI or the [MCP server](mcp.md) runs, and the UI asks for them by project and +period. The MCP tools [`list_traces` and `get_trace`](mcp.md#traces) read the same traces. "Clear all" in the +Sentry section deletes them with the Sentry events. Memory is bounded by these limits; values below 1 fall back to the defaults: @@ -87,5 +88,4 @@ Memory is bounded by these limits; values below 1 fall back to the defaults: | `TRAP_TELEMETRY_MAX_METRICS` | `/trap/telemetry/@maxMetrics`| `5000` | the oldest metric values are dropped | `maxSpans` counts transactions and spans together; a single trace above it keeps its most recent 90%. -These limits are apart from the [OpenTelemetry limits](opentelemetry.md#memory-limits) of the console and the -MCP server. +These limits are apart from the [OpenTelemetry limits](opentelemetry.md#memory-limits) of the console. diff --git a/skills/trap/SKILL.md b/skills/trap/SKILL.md index 7b7365d3..1d7ad41b 100644 --- a/skills/trap/SKILL.md +++ b/skills/trap/SKILL.md @@ -40,7 +40,7 @@ the agent reads back through Trap's MCP tools. | Reference | Read when | | ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | -| [mcp.md](references/mcp.md) | Reading events and OpenTelemetry traces: the tools, filters, the script for agents without MCP | +| [mcp.md](references/mcp.md) | Reading events and traces of Sentry and OpenTelemetry: the tools, filters, the script for agents without MCP | | [dumps-and-logs.md](references/dumps-and-logs.md) | Seeing values or the code path at runtime: `trap()`, `tr()`, `td()`, `dump()`, `trap()::logger()` | | [profiling.md](references/profiling.md) | Finding why code is slow or takes memory: `trap()::profile()`, the profilers, reading a profile; Xdebug function traces | | [xdebug.md](references/xdebug.md) | Stopping at a line or an exception and stepping through PHP code: `--xdebug`, breakpoints, variables, `xdebug_*` tools | diff --git a/skills/trap/references/integrations.md b/skills/trap/references/integrations.md index 895858c1..37fea3cf 100644 --- a/skills/trap/references/integrations.md +++ b/skills/trap/references/integrations.md @@ -14,8 +14,10 @@ SENTRY_DSN=http://sentry@127.0.0.1:8000/1 # Laravel: SENTRY_LARAVEL_DSN The key and the project ID can be anything. Events: `sentry`; `get_event` gives the exception chain with the code around the frames, the request and the breadcrumbs, the fastest way to an exception the application swallowed into -its error reporting. A transaction is a `sentry` event as well; Sentry logs, trace metrics and spans make no event and -show only on the Sentry pages of the web UI. A body over 2 MB gets `413`, and an event Trap can't parse is dropped +its error reporting. The `sentry` events are the errors: a transaction is a trace, read it with `list_traces` and +`get_trace` (in an envelope with an error, the error is still the event; a transaction without a trace ID stays a +`sentry` event). Sentry logs and trace metrics make no event +and show only on the Sentry pages of the web UI. A body over 2 MB gets `413`, and an event Trap can't parse is dropped with a warning in its console. The `X-Buggregator-Project` header sets the `project` of the event. ## Monolog @@ -79,7 +81,7 @@ OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318 OTEL_EXPORTER_OTLP_PROTOCOL=http/json ``` -Read traces with `list_traces` and `get_trace`, not the event tools. Trap takes logs and metrics too +Read traces with `list_traces` and `get_trace`, not the event tools; they list Sentry traces too. Trap takes logs and metrics too (`/v1/logs`, `/v1/metrics`), but shows them only in the console and the web UI: no MCP tool reads them. `http/protobuf` needs `open-telemetry/gen-otlp-protobuf` and `google/protobuf` in the project that runs Trap. The web UI files the data under the project of the path `/api/{project}/integration/otlp/v1/traces` (also `/logs`, `/metrics`), else of the diff --git a/skills/trap/references/mcp.md b/skills/trap/references/mcp.md index e43f5931..c315f7f3 100644 --- a/skills/trap/references/mcp.md +++ b/skills/trap/references/mcp.md @@ -1,8 +1,8 @@ # Reading events Trap's MCP server answers at `http://127.0.0.1:8000/mcp` while Trap runs with `--mcp`. Its tools read the events -Trap has caught, the OpenTelemetry traces it has received and the Xdebug sessions of `--xdebug`. The full reference: -. +Trap has caught, the Sentry and OpenTelemetry traces it has received and the Xdebug sessions of `--xdebug`. The full +reference: . ## Two clients @@ -44,8 +44,8 @@ The argument schema of each tool is in its `inputSchema` (`mcp.php tools ` | `get_event` | One event as plain text: the full dump, log record, exception, mail, request | | `delete_event` | Deletes events by `id` or `ids` | | `clear_events` | Deletes the events matching a filter, or all; pinned ones stay unless `include_pinned: true` | -| `list_traces` | OpenTelemetry traces, with filters by service, name, duration, errors | -| `get_trace` | One trace as a tree of its spans | +| `list_traces` | Sentry and OpenTelemetry traces; filters by project, source, service, name, duration, errors | +| `get_trace` | One trace as a tree of its spans and transactions | | `profile_*` | Analyze a `profiler` event, see [profiling.md](profiling.md#read-the-profile) | | `xdebug_*` | Step debugging with Xdebug, see [xdebug.md](xdebug.md) | | `xdebug_trace_*` | Walk the call tree of an `xdebug-trace` event, see [profiling.md](profiling.md#trace-the-calls) | @@ -97,8 +97,12 @@ values. A field no type has fails the call. An `xdebug-trace` has no fields: `se ## Traces -Traces are not events: `list_traces` takes its own `since` cursor, and `from`, `to`, `service`, `name`, `errors_only`, -`min_duration_ms`, `search`. A trace is listed again with every span that arrives for it. `get_trace` gives the -span tree with durations and attributes. Slow traces of the last hour: `{"from": "1h", "min_duration_ms": 500}`. -A trace is dropped 600 seconds after its last span (`TRAP_TRACES_TTL`), or sooner when the kept spans pass 10 000 -(`TRAP_TRACES_MAX_SPANS`) and it is the least recently updated: read it soon after the run. OpenTelemetry logs and metrics have no MCP tool. +Traces are not events: a Sentry transaction and OpenTelemetry spans are both traces, and `list_traces` lists them +together, each with its `services`, `sources` (`sentry`, `otel`) and `projects`. It takes its own `since` cursor, and +`project`, `source`, `from`, `to`, `service`, `name`, `errors_only`, `min_duration_ms`, `search`; `service: "*"` +takes a trace without services too. A trace is listed again with every span that arrives for it. `get_trace` gives +the span tree with durations and attributes; a Sentry span is named `op: description`. The trace ID of a Sentry +error, in its `trace` context, opens the trace of the failed request. Slow traces of the last hour: +`{"from": "1h", "min_duration_ms": 500}`. The least recently updated traces are dropped once the kept spans and +transactions pass 10 000 (`TRAP_TELEMETRY_MAX_SPANS`), and clearing the Sentry pages of the web UI drops them too. +OpenTelemetry logs and metrics have no MCP tool. diff --git a/skills/trap/references/server.md b/skills/trap/references/server.md index 0dd8d2c7..37a701aa 100644 --- a/skills/trap/references/server.md +++ b/skills/trap/references/server.md @@ -22,8 +22,9 @@ vendor/bin/trap --mcp -s # no console output: the agent reads only throu Run it as a background process and keep it for the session: events live in its memory and a restart drops them. The buffer keeps the last 200 events (`maxEvents` of `trap.xml`); an event pinned in the web UI is pushed out last. -OpenTelemetry traces have limits of their own, see [mcp.md](mcp.md#traces). Keep the process ID to -stop it later: `vendor/bin/trap --mcp & echo $!` and `kill ` in a POSIX shell; in PowerShell see +Sentry and OpenTelemetry traces are kept apart from the events, up to 10 000 spans and transactions +(`TRAP_TELEMETRY_MAX_SPANS`), see [mcp.md](mcp.md#traces). Keep the process ID to stop it later: +`vendor/bin/trap --mcp & echo $!` and `kill ` in a POSIX shell; in PowerShell see [the Windows recipe](#a-trap-of-your-own-in-powershell). Other Traps may run on the machine: stop only yours. `-vv` prints the server's debug messages and errors, such as a port it can't listen on or a profile it can't import. @@ -115,5 +116,6 @@ decoded past it gets `413`), `TRAP_XDEBUG_PATH`, `TRAP_XHPROF_PATH`, `TRAP_SPX_P to pick up), `TRAP_XDEBUG_PORT`, `TRAP_XDEBUG_IDE`, `TRAP_XDEBUG_MODE`, `TRAP_XDEBUG_ALLOW_EVAL`, `TRAP_XDEBUG_ALLOW_CONTROL` (the debugger of `--xdebug`, see [xdebug.md](xdebug.md)), `TRAP_XDEBUG_TRACE_PATH`, `TRAP_XDEBUG_TRACE_MAX_UPLOAD`, `_MAX_SIZE`, `_KEEP` (Xdebug traces, see [profiling.md](profiling.md#trace-the-calls)), -`TRAP_TRACES_MAX_SPANS`, `TRAP_TRACES_TTL` (OpenTelemetry traces of the console and MCP), -`TRAP_TELEMETRY_MAX_SPANS`, `_MAX_LOGS`, `_MAX_METRICS` (the traces, logs and metrics of the web UI's Sentry pages). +`TRAP_TRACES_MAX_SPANS`, `TRAP_TRACES_TTL` (the OpenTelemetry spans the console keeps to print a trace as a tree), +`TRAP_TELEMETRY_MAX_SPANS`, `_MAX_LOGS`, `_MAX_METRICS` (the traces, logs and metrics of the web UI's Sentry pages +and of `list_traces`). diff --git a/src/Module/Mcp/Tool/ListEvents.php b/src/Module/Mcp/Tool/ListEvents.php index 9869be22..690b1d99 100644 --- a/src/Module/Mcp/Tool/ListEvents.php +++ b/src/Module/Mcp/Tool/ListEvents.php @@ -72,7 +72,8 @@ public function description(): string . '`project`, time (`from`, `to`, such as `5m` for the last five minutes), text (`search`, `regex`) ' . 'and fields (`where`). The fields by type: ' . $this->filters->fieldsHelp() . '. `order: newest` ' . 'gives the latest events first. Read an event in full with `get_event`, or get the texts of all the ' - . 'listed ones with `include: text`. ' . self::budgetHelp($this->scan->budget); + . 'listed ones with `include: text`. Traces, Sentry transactions among them, are not events: read ' + . 'them with `list_traces`. ' . self::budgetHelp($this->scan->budget); } #[\Override] diff --git a/src/Module/Mcp/Tool/WaitForEvents.php b/src/Module/Mcp/Tool/WaitForEvents.php index e282bd12..0eeddd8e 100644 --- a/src/Module/Mcp/Tool/WaitForEvents.php +++ b/src/Module/Mcp/Tool/WaitForEvents.php @@ -67,7 +67,8 @@ public function description(): string . 'which is not an error. Without `since` it waits for the events changed after the call starts; ' . 'events the code sends before that are missed, so to be safe take a `cursor` from `list_events` ' . '(or from an earlier wait) before triggering the code, and pass it as `since`. Pass the returned ' - . '`cursor` to the next wait or `list_events` to miss nothing.', + . '`cursor` to the next wait or `list_events` to miss nothing. Traces, Sentry transactions among ' + . 'them, are not events and never arrive here: read them with `list_traces`.', self::DEFAULT_TIMEOUT, self::MAX_TIMEOUT, ); diff --git a/src/Module/Sentry/Console/SentryEnvelope.php b/src/Module/Sentry/Console/SentryEnvelope.php index 8f4f01b4..b750b056 100644 --- a/src/Module/Sentry/Console/SentryEnvelope.php +++ b/src/Module/Sentry/Console/SentryEnvelope.php @@ -45,7 +45,7 @@ public function render(OutputInterface $output, Frame $frame): void } Header::renderMessageHeader($output, $item->payload); - $this->renderItem($output, $item); + TraceLine::render($output, $type, $item->payload) or $this->renderItem($output, $item); } catch (\Throwable $e) { $output->writeln(['Render error', $e->getMessage()]); trap($e); diff --git a/src/Module/Sentry/Console/SentryStore.php b/src/Module/Sentry/Console/SentryStore.php index b465c4c3..0958190d 100644 --- a/src/Module/Sentry/Console/SentryStore.php +++ b/src/Module/Sentry/Console/SentryStore.php @@ -7,6 +7,7 @@ use Buggregator\Trap\Module\Console\Renderer; use Buggregator\Trap\Module\Console\Support\Common; use Buggregator\Trap\Module\Sentry\Frame\SentryStore as SentryStoreFrame; +use Buggregator\Trap\Module\Sentry\Telemetry\ItemReader; use Buggregator\Trap\Server\Proto\Frame; use Symfony\Component\Console\Output\OutputInterface; @@ -32,7 +33,8 @@ public function render(OutputInterface $output, Frame $frame): void try { Header::renderMessageHeader($output, $frame->message + ['timestamp' => $frame->time->format('U.u')]); - Exceptions::render($output, $frame->message['exception']['values'] ?? []); + ItemReader::isTransaction($frame->message) && TraceLine::render($output, 'transaction', $frame->message) + or Exceptions::render($output, $frame->message['exception']['values'] ?? []); } catch (\Throwable $e) { $output->writeln(['Render error', $e->getMessage()]); } diff --git a/src/Module/Sentry/Console/TraceLine.php b/src/Module/Sentry/Console/TraceLine.php new file mode 100644 index 00000000..c607765b --- /dev/null +++ b/src/Module/Sentry/Console/TraceLine.php @@ -0,0 +1,153 @@ + $roots */ + $roots = []; + /** @var array> $spans */ + $spans = []; + foreach ($batch->transactions as $transaction) { + $roots[$transaction->traceId] ??= $transaction; + $spans[$transaction->traceId] ??= []; + } + foreach ($batch->spans as $span) { + $spans[$span->traceId][] = $span; + } + + if ($spans === [] && $type === 'transaction') { + $output->writeln(['', self::untraced($payload)]); + return true; + } + + $output->writeln(''); + $spans === [] and $output->writeln('Spans without a trace ID'); + foreach ($spans as $traceId => $list) { + $output->writeln(self::line((string) $traceId, $roots[$traceId] ?? self::rootSpan($list), $list)); + } + + return true; + } + + /** + * @param Transaction|Span|null $root The transaction, else the root span of the spans. + * @param list $spans + */ + private static function line(string $traceId, Transaction|Span|null $root, array $spans): string + { + $parts = [...$spans]; + $root instanceof Transaction and $parts[] = $root; + $failed = \count(\array_filter($parts, static fn(Transaction|Span $part): bool => $part->isError())); + $name = match (true) { + $root instanceof Transaction => $root->name, + $root instanceof Span => $root->description, + default => '', + }; + $op = $root?->op ?? ''; + $name = \trim($name . ($op === '' ? '' : " ($op)")); + $duration = $root?->durationMs(); + $count = \count($parts); + $line = \array_filter([ + $name === '' ? '' : '' . self::text($name) . '', + $duration === null ? '' : "$duration ms", + // The transaction counts as a span, as in `list_traces`. + $count === 1 ? '1 span' : "$count spans", + $failed === 0 ? '' : "$failed failed", + ], static fn(string $part): bool => $part !== ''); + + return \sprintf('Trace %s: %s', self::text($traceId), \implode(', ', $line)); + } + + /** + * A transaction without a trace ID, a feed event: its spans are counted as the telemetry store would read them. + */ + private static function untraced(array $payload): string + { + /** @var mixed $spans */ + $spans = $payload['spans'] ?? null; + $count = 1; + /** @var mixed $span */ + foreach (\is_array($spans) && \array_is_list($spans) ? $spans : [] as $span) { + \is_array($span) && \is_string($span['span_id'] ?? null) && $span['span_id'] !== '' and ++$count; + } + + /** @var mixed $name */ + $name = $payload['transaction'] ?? ''; + /** @var mixed $context */ + $context = $payload['contexts']['trace'] ?? null; + /** @var mixed $op */ + $op = $payload['op'] ?? (\is_array($context) ? $context['op'] ?? '' : ''); + $name = \trim((\is_string($name) ? $name : '') . (\is_string($op) && $op !== '' ? " ($op)" : '')); + $duration = Span::durationBetween( + ItemReader::time($payload['start_timestamp'] ?? null), + ItemReader::time($payload['timestamp'] ?? null), + ); + $line = \array_filter([ + $name === '' ? '' : '' . self::text($name) . '', + $duration === null ? '' : "$duration ms", + $count === 1 ? '1 span' : "$count spans", + ], static fn(string $part): bool => $part !== ''); + + return 'Transaction without a trace ID: ' . \implode(', ', $line); + } + + /** + * The span without a parent, else the earliest one whose parent is not among them. + * + * @param list $spans + */ + private static function rootSpan(array $spans): ?Span + { + $ids = \array_fill_keys(\array_map(static fn(Span $span): string => $span->spanId, $spans), true); + $root = null; + foreach ($spans as $span) { + if ($span->parentSpanId !== null && isset($ids[$span->parentSpanId])) { + continue; + } + + $rank = [$span->parentSpanId === null ? 0 : 1, $span->start ?? \INF]; + if ($root === null || $rank < $root[0]) { + $root = [$rank, $span]; + } + } + + return $root[1] ?? null; + } + + /** + * Received text without console markup and control characters. + */ + private static function text(string $value): string + { + return OutputFormatter::escape((string) \preg_replace('/[\x00-\x1F\x7F]/', '?', $value)); + } +} diff --git a/src/Module/Sentry/Frontend/EnvelopeMapper.php b/src/Module/Sentry/Frontend/EnvelopeMapper.php index 809c22e3..a4b6eebf 100644 --- a/src/Module/Sentry/Frontend/EnvelopeMapper.php +++ b/src/Module/Sentry/Frontend/EnvelopeMapper.php @@ -15,19 +15,17 @@ /** * Makes the feed event of an envelope from its event item, and puts its transactions, spans, logs and - * trace metrics into the {@see TelemetryStore}. + * trace metrics into the {@see TelemetryStore}: as in buggregator/server, they make no feed event. * - * The feed event is the first `event` item, else the first `transaction` or `feedback` one, else the first - * item that is neither telemetry nor SDK bookkeeping (sessions, client reports, attachments, ...). - * An envelope of only such items makes no event. + * The feed event is the first `event` item, else the first `feedback` one, else the first transaction without + * a trace ID, which no trace can hold, else the first item that is neither telemetry nor SDK bookkeeping + * (sessions, client reports, attachments, ...). An envelope of only such items makes no event. * * @internal */ final class EnvelopeMapper implements EventMapper { - private const EVENT_ITEMS = ['transaction', 'feedback']; - private const NON_FEED_ITEMS = [ - 'span', 'spans', 'log', 'trace_metric', + private const BOOKKEEPING_ITEMS = [ 'session', 'sessions', 'client_report', 'check_in', 'metric_buckets', 'statsd', 'profile', 'profile_chunk', 'user_report', 'attachment', 'replay_event', 'replay_recording', ]; @@ -49,30 +47,33 @@ public function map(Frame $frame): ?Event $batch = new Batch($project); $event = null; - $feed = null; + $feedback = null; + $untraced = null; $fallback = null; foreach ($frame->items as $item) { /** @var mixed $type */ $type = $item->headers['type'] ?? null; $type = \is_string($type) ? $type : ''; - ItemReader::read($batch, $type, $item->payload, $eventId); + $telemetry = ItemReader::read($batch, $type, $item->payload, $eventId); - if (!\is_array($item->payload)) { + if ($telemetry || !\is_array($item->payload)) { continue; } if ($type === 'event') { $event ??= $item->payload; - } elseif (\in_array($type, self::EVENT_ITEMS, true)) { - $feed ??= $item->payload; - } elseif (!\in_array($type, self::NON_FEED_ITEMS, true)) { + } elseif ($type === 'feedback') { + $feedback ??= $item->payload; + } elseif ($type === 'transaction') { + $untraced ??= $item->payload; + } elseif (!\in_array($type, self::BOOKKEEPING_ITEMS, true)) { $fallback ??= $item->payload; } } $this->telemetry->add($batch); - $payload = $event ?? $feed ?? $fallback; + $payload = $event ?? $feedback ?? $untraced ?? $fallback; if ($payload === null) { return null; } diff --git a/src/Module/Sentry/Frontend/StoreMapper.php b/src/Module/Sentry/Frontend/StoreMapper.php index e65b1915..04103582 100644 --- a/src/Module/Sentry/Frontend/StoreMapper.php +++ b/src/Module/Sentry/Frontend/StoreMapper.php @@ -14,7 +14,8 @@ use Buggregator\Trap\Support\Uuid; /** - * A transaction sent to the `store` endpoint goes to the {@see TelemetryStore} as well. + * An error sent to the `store` endpoint makes a feed event; a transaction goes to the {@see TelemetryStore} + * only, as one of an envelope, unless it has no trace ID: then no trace can hold it, and it stays in the feed. * * @internal */ @@ -25,15 +26,17 @@ public function __construct( ) {} #[\Override] - public function map(Frame $frame): Event + public function map(Frame $frame): ?Event { \assert($frame instanceof SentryFrame); $project = $frame->project === null || $frame->project === '' ? Event::DEFAULT_PROJECT : $frame->project; if (ItemReader::isTransaction($frame->message)) { $batch = new Batch($project); - ItemReader::transaction($batch, $frame->message); - $this->telemetry->add($batch); + if (ItemReader::transaction($batch, $frame->message)) { + $this->telemetry->add($batch); + return null; + } } return new Event( diff --git a/src/Module/Sentry/Mcp/SentryText.php b/src/Module/Sentry/Mcp/SentryText.php index bb0c7673..c94dd6e6 100644 --- a/src/Module/Sentry/Mcp/SentryText.php +++ b/src/Module/Sentry/Mcp/SentryText.php @@ -7,7 +7,10 @@ use Buggregator\Trap\Module\Sentry\Frame\EnvelopeItem; use Buggregator\Trap\Module\Sentry\Frame\SentryEnvelope; use Buggregator\Trap\Module\Sentry\Frame\SentryStore; +use Buggregator\Trap\Module\Sentry\Telemetry\ItemReader; +use Buggregator\Trap\Server\Event\Event; use Buggregator\Trap\Server\Event\Record; +use Buggregator\Trap\Server\Telemetry\Batch; use Buggregator\Trap\Support\Json; /** @@ -50,9 +53,6 @@ final class SentryText /** Tags, user fields, contexts, extra entries. */ public const MAX_ENTRIES = 20; - /** Spans of a transaction. */ - public const MAX_SPANS = 20; - /** Characters of a value in a line: a variable, a header, a tag, a context. */ public const MAX_VALUE = 300; @@ -111,7 +111,7 @@ final class SentryText private const MAX_FILTERED_BYTES = 4096; /** Item types whose payload is an event; the payloads of others, as `session` or `client_report`, take a line. */ - private const EVENT_ITEMS = ['event', 'transaction', 'feedback']; + private const EVENT_ITEMS = ['event', 'feedback']; /** * Of a Sentry record: of every item of an envelope, else of the payload. @@ -132,6 +132,10 @@ public static function render(Record $record): string $payload = $items[0]->payload ?? $record->event->payload; /** @var mixed $type */ $type = $items[0]->headers['type'] ?? null; + if (\is_array($payload) && $type === 'transaction' && self::traceId($payload) !== '') { + return self::transactionLine($payload); + } + if (\is_array($payload) && ($type === null || \in_array($type, self::EVENT_ITEMS, true))) { return self::event($payload, $type); } @@ -146,7 +150,9 @@ public static function render(Record $record): string $type = $item->headers['type'] ?? null; $parts[] = \sprintf("--- Item %d of %d: %s ---\n", $i + 1, $count, self::inline($type ?? 'item')) . match (true) { !\is_array($item->payload) => self::attachment($item->headers), - $type === null || \in_array($type, self::EVENT_ITEMS, true) => self::event($item->payload, $type), + $type === 'transaction' && self::traceId($item->payload) !== '' => self::transactionLine($item->payload), + $type === null || $type === 'transaction' || \in_array($type, self::EVENT_ITEMS, true) + => self::event($item->payload, $type), default => self::itemLine($item->payload), }; } @@ -220,7 +226,6 @@ private static function event(array $event, mixed $itemType = null): string self::entries('Contexts', $event['contexts'] ?? null), self::breadcrumbs($event), self::entries('Extra', $event['extra'] ?? null), - self::spans($event), ]; return \implode("\n", \array_filter($sections, static fn(string $section): bool => $section !== '')); @@ -768,32 +773,6 @@ private static function breadcrumb(array $crumb): string return \implode(' ', \array_filter($parts, static fn(string $part): bool => $part !== '')); } - private static function spans(array $event): string - { - $spans = self::arrays($event['spans'] ?? null); - $count = \count($spans); - if ($count === 0) { - return ''; - } - - $result = "Spans ($count):\n"; - foreach (\array_slice($spans, 0, self::MAX_SPANS) as $span) { - $line = self::inline($span['op'] ?? 'span'); - $description = self::inline($span['description'] ?? ''); - $description === '' or $line .= ": $description"; - $duration = self::duration($span); - $duration === '' or $line .= " ($duration)"; - /** @var mixed $status */ - $status = $span['status'] ?? null; - \is_string($status) && $status !== 'ok' and $line .= ", $status"; - $result .= ' ' . self::cut($line, self::MAX_VALUE) . "\n"; - } - - $count > self::MAX_SPANS and $result .= \sprintf(" … %d more …\n", $count - self::MAX_SPANS); - - return $result; - } - private static function attachment(array $headers): string { $parts = []; @@ -808,6 +787,43 @@ private static function attachment(array $headers): string return ($parts === [] ? 'Not an event' : \implode(', ', $parts)) . "\n"; } + /** + * A transaction with a trace ID is a trace, read by the trace tools: its name, duration and trace ID. + * One without is shown as an event: no trace holds it. + */ + private static function transactionLine(array $payload): string + { + $batch = self::readTransaction($payload); + $parts = \array_filter([ + self::inline($payload['transaction'] ?? ''), + self::duration($payload), + // With the transaction itself, as `list_traces` counts. + (\count($batch->spans) + 1) . ' spans', + ], static fn(string $part): bool => $part !== ''); + + return 'Transaction: ' . \implode(', ', $parts) . "\n" + . 'Read it as trace ' . self::traceId($payload) . " with `get_trace`.\n"; + } + + /** + * The trace ID the telemetry store keeps the transaction under; empty when it keeps none. + */ + private static function traceId(array $payload): string + { + return self::inline(self::readTransaction($payload)->transactions[0]->traceId ?? ''); + } + + /** + * The transaction and its spans as the telemetry store reads them. + */ + private static function readTransaction(array $payload): Batch + { + $batch = new Batch(Event::DEFAULT_PROJECT); + ItemReader::transaction($batch, $payload); + + return $batch; + } + /** * The fields of an item that is not an event, as a session or a client report, in one line. */ diff --git a/src/Module/Sentry/Telemetry/ItemReader.php b/src/Module/Sentry/Telemetry/ItemReader.php index e46eb8c8..58c22337 100644 --- a/src/Module/Sentry/Telemetry/ItemReader.php +++ b/src/Module/Sentry/Telemetry/ItemReader.php @@ -31,7 +31,7 @@ final class ItemReader * Reads an item of a telemetry type into the batch; other items are ignored. * * @param non-empty-string|null $eventId The envelope `event_id`, for SDKs that send it there only. - * @return bool Whether the item had a telemetry type. + * @return bool Whether the item had a telemetry type; false for a transaction without a trace ID too. */ public static function read(Batch $batch, string $type, mixed $payload, ?string $eventId = null): bool { @@ -40,29 +40,30 @@ public static function read(Batch $batch, string $type, mixed $payload, ?string } match ($type) { - 'transaction' => self::transaction($batch, $payload, $eventId), 'span', 'spans' => self::spans($batch, self::records($payload)), 'log' => self::logs($batch, self::records($payload)), 'trace_metric' => self::metrics($batch, self::records($payload)), default => null, }; - return \in_array($type, self::TELEMETRY_ITEMS, true); + return $type === 'transaction' + ? self::transaction($batch, $payload, $eventId) + : \in_array($type, self::TELEMETRY_ITEMS, true); } /** - * Whether a payload of the `store` endpoint is a transaction, not an error: it has spans and a start - * and no exception. + * Whether a payload of the `store` endpoint is a transaction, not an error: it has no exception, and + * either the `transaction` type or spans and a start. An exception makes an error of any type, as in + * buggregator/server. */ public static function isTransaction(array $payload): bool { - if (($payload['type'] ?? null) === 'transaction') { - return true; + if (self::exceptions($payload) !== []) { + return false; } - return \array_key_exists('spans', $payload) - && \array_key_exists('start_timestamp', $payload) - && self::exceptions($payload) === []; + return ($payload['type'] ?? null) === 'transaction' + || \array_key_exists('spans', $payload) && \array_key_exists('start_timestamp', $payload); } /** @@ -101,8 +102,9 @@ public static function time(mixed $value): ?float /** * @param non-empty-string|null $eventId The ID when the payload has none. + * @return bool False for a transaction without a trace ID, which is not read. */ - public static function transaction(Batch $batch, array $payload, ?string $eventId = null): void + public static function transaction(Batch $batch, array $payload, ?string $eventId = null): bool { $context = self::map($payload, 'contexts'); $trace = self::map($context, 'trace'); @@ -113,7 +115,7 @@ public static function transaction(Batch $batch, array $payload, ?string $eventI $traceId ??= self::string($span, 'trace_id'); } if ($traceId === null) { - return; + return false; } $data = self::map($trace, 'data'); @@ -166,6 +168,8 @@ public static function transaction(Batch $batch, array $payload, ?string $eventI attributes: $attributes, ); } + + return true; } /** diff --git a/src/Module/Tracing/Config/Traces.php b/src/Module/Tracing/Config/Traces.php index c730d872..3aa4108c 100644 --- a/src/Module/Tracing/Config/Traces.php +++ b/src/Module/Tracing/Config/Traces.php @@ -4,12 +4,13 @@ namespace Buggregator\Trap\Module\Tracing\Config; +use Buggregator\Trap\Module\Tracing\Console\SpanBuffer; use Buggregator\Trap\Server\Application\Config\Internal\Attribute\Env; use Buggregator\Trap\Server\Application\Config\Internal\Attribute\InflectableConfig; use Buggregator\Trap\Server\Application\Config\Internal\Attribute\XPath; /** - * Limits of the in-memory store of received OpenTelemetry spans, + * Limits of the {@see SpanBuffer} of the OpenTelemetry spans the console prints, * which joins spans of one trace exported in separate requests. * * @internal diff --git a/src/Module/Tracing/Console/Renderer.php b/src/Module/Tracing/Console/Renderer.php index fb27cc43..051ae400 100644 --- a/src/Module/Tracing/Console/Renderer.php +++ b/src/Module/Tracing/Console/Renderer.php @@ -10,7 +10,6 @@ use Buggregator\Trap\Module\Tracing\Frame\OtlpTraces; use Buggregator\Trap\Module\Tracing\Frame\Trace\ResourceSpans; use Buggregator\Trap\Module\Tracing\Frame\Trace\Span; -use Buggregator\Trap\Module\Tracing\SpanStore; use Buggregator\Trap\Server\Proto\Frame; use Symfony\Component\Console\Output\OutputInterface; @@ -18,11 +17,9 @@ * Renders received spans grouped by trace, each trace as a {@see TraceTree} of the spans of the frame * among the spans received so far. * - * Every rendered span is added to a {@see SpanStore} of the renderer, so a tree can join spans of separate - * export requests. Not the store of the container: the OTLP middleware fills that one when a request - * arrives, and the console renders frames later, in batches, so it would show spans of later frames. - * With a simple span processor children end before their parents, so each span is printed when it arrives, - * and the root span brings the complete tree. + * Every rendered span is added to a {@see SpanBuffer} of the renderer, so a tree can join spans of separate + * export requests. With a simple span processor children end before their parents, so each span is printed + * when it arrives, and the root span brings the complete tree. * * A frame prints at most {@see self::MAX_SPANS} spans. * @@ -34,12 +31,12 @@ final class Renderer implements RendererInterface { private const MAX_SPANS = 500; - private readonly SpanStore $store; + private readonly SpanBuffer $store; private readonly TraceTree $tree; public function __construct(Traces $config = new Traces()) { - $this->store = new SpanStore($config); + $this->store = new SpanBuffer($config); $this->tree = new TraceTree($this->store); } diff --git a/src/Module/Tracing/SpanStore.php b/src/Module/Tracing/Console/SpanBuffer.php similarity index 61% rename from src/Module/Tracing/SpanStore.php rename to src/Module/Tracing/Console/SpanBuffer.php index 2db3e36e..b6192a3c 100644 --- a/src/Module/Tracing/SpanStore.php +++ b/src/Module/Tracing/Console/SpanBuffer.php @@ -2,40 +2,28 @@ declare(strict_types=1); -namespace Buggregator\Trap\Module\Tracing; +namespace Buggregator\Trap\Module\Tracing\Console; use Buggregator\Trap\Module\Tracing\Config\Traces as Config; -use Buggregator\Trap\Module\Tracing\Frame\OtlpTraces; -use Buggregator\Trap\Module\Tracing\Frame\Trace\Attributes; use Buggregator\Trap\Module\Tracing\Frame\Trace\Span; -use Buggregator\Trap\Module\Tracing\Frame\Trace\StatusCode; /** - * Spans received by the Trap process, kept so that spans of one trace that arrive in separate - * export requests can be put together. + * OTLP spans a {@see TraceTree} prints, kept so that a tree can join spans of one trace that arrive + * in separate export requests. * - * Every stored span gets the next sequence number, and a trace keeps the one of its last span: - * {@see traces()} lists the traces changed after a moment by it. + * Not the {@see \Buggregator\Trap\Server\Telemetry\TelemetryStore}: the console renders frames later than they + * are stored, in batches, so a store filled on arrival would show spans of later frames; it keeps only + * what the web UI shows of a span, without the OTLP kind, events and links in their own fields; and it is + * filled only while the web UI or the MCP server runs. * * Memory is bounded by {@see Config}: a trace is dropped when it has not received a span for `ttl` seconds, - * and the least recently updated traces are dropped while the store holds more than `maxSpans` spans. + * and the least recently updated traces are dropped while the buffer holds more than `maxSpans` spans. * A single trace above `maxSpans` keeps only its most recently received spans, 90% of `maxSpans`. * - * The container keeps one store for the Trap process, filled by the OTLP middleware while the MCP server runs - * and read by the MCP tools. The console renderer keeps a store of its own, filled as it renders. - * * @internal - * - * @psalm-import-type AttributeMap from Attributes */ -final class SpanStore +final class SpanBuffer { - /** - * A random ID of the store, and so of the Trap process: sequence numbers of another process mean nothing here. - * @var non-empty-string - */ - public readonly string $id; - /** * Ordered from the least to the most recently updated trace. * @@ -46,24 +34,6 @@ final class SpanStore /** @var array Trace ID => time of the last added span */ private array $updatedAt = []; - /** - * Unique and growing in the order of {@see $traces}. - * - * @var array> Trace ID => sequence number of its last stored span - */ - private array $changedAt = []; - - /** @var array> Trace ID => span ID => service name */ - private array $services = []; - - /** - * Spans of one export request share the array of their resource: PHP keeps it once. - * - * @var array> Trace ID => span ID => attributes of - * its resource, when not empty - */ - private array $resources = []; - /** @var int<0, max> */ private int $seq = 0; @@ -108,7 +78,6 @@ public function __construct( $this->maxSpans = $maxSpans; $this->ttl = $config->ttl > 0 && \is_finite($config->ttl) ? $config->ttl : $defaults->ttl; $this->clock = $clock ?? static fn(): float => \microtime(true); - $this->id = \bin2hex(\random_bytes(4)); } /** @@ -127,11 +96,7 @@ public function add(Span ...$spans): void // Re-inserting a known span moves it to the end too, so the oldest spans stay first. $old = $trace[$span->spanId] ?? null; if ($old !== null) { - unset( - $trace[$span->spanId], - $this->services[$traceId][$span->spanId], - $this->resources[$traceId][$span->spanId], - ); + unset($trace[$span->spanId]); $this->unindex($old, $span); } else { ++$this->spanCount; @@ -139,69 +104,12 @@ public function add(Span ...$spans): void $trace[$span->spanId] = $span; $this->traces[$traceId] = $trace; $this->updatedAt[$traceId] = $now; - $this->changedAt[$traceId] = ++$this->seq; - $this->index($span, \count($trace) === 1, $this->seq); + $this->index($span, \count($trace) === 1, ++$this->seq); } $this->evict($now); } - /** - * Adds the spans of the frame with the attributes of their resources. The limits apply after each span, - * as for spans added one by one. - */ - public function receive(OtlpTraces $frame): void - { - foreach ($frame->iterateSpans() as [$resource, , $span]) { - $this->add($span); - $service = $resource->getServiceName(); - // The limits never drop the span just added: it is the most recent one. - $service === null or $this->services[$span->traceId][$span->spanId] = $service; - $attributes = $resource->resourceAttributes; - $attributes === [] or $this->resources[$span->traceId][$span->spanId] = $attributes; - } - } - - /** - * The sequence number of the last stored span; 0 before the first one. - * - * @return int<0, max> - */ - public function cursor(): int - { - return $this->seq; - } - - /** - * Summaries of the traces changed after the cursor, from the least recently updated one: the - * {@see TraceSummary::$seq} of a listed trace is a cursor for the traces after it. - * Traces past their TTL are dropped first. - * - * @param int<0, max> $cursor A value of {@see cursor()} or {@see TraceSummary::$seq}; 0 for all the traces. - * - * @return \Generator Computed one by one: stop reading when enough. - */ - public function traces(int $cursor = 0): \Generator - { - $this->evict(($this->clock)()); - - foreach (\array_keys($this->traces) as $traceId) { - // Cast back: PHP would turn an all-digit ID into an int key. - $traceId = (string) $traceId; - $this->changedAt[$traceId] > $cursor and yield $this->summarize($traceId); - } - } - - /** - * @return TraceSummary|null Null for an unknown or expired trace. - */ - public function summary(string $traceId): ?TraceSummary - { - $this->evict(($this->clock)()); - - return $traceId === '' || !isset($this->traces[$traceId]) ? null : $this->summarize($traceId); - } - public function get(string $traceId, string $spanId): ?Span { return $this->traces[$traceId][$spanId] ?? null; @@ -215,19 +123,6 @@ public function getTrace(string $traceId): array return $this->traces[$traceId] ?? []; } - /** - * @return list The distinct attributes of the resources of the spans, without empty ones. - */ - public function getResources(string $traceId): array - { - $result = []; - foreach ($this->resources[$traceId] ?? [] as $attributes) { - \in_array($attributes, $result, true) or $result[] = $attributes; - } - - return $result; - } - /** * @return list Stored spans whose parent is the given span, in the order of arrival. */ @@ -311,48 +206,6 @@ private static function computeBounds(array $trace): array return [$start, $end]; } - /** - * @param non-empty-string $traceId A stored trace. - */ - private function summarize(string $traceId): TraceSummary - { - $trace = $this->traces[$traceId]; - \assert($trace !== []); - $root = null; - $error = false; - foreach ($trace as $span) { - $error = $error || $span->status->code === StatusCode::Error; - $parentId = $span->parentSpanId; - if ($parentId !== null && ($parentId === $span->spanId || isset($trace[$parentId]))) { - continue; - } - - // A span without a parent wins over one whose parent has not arrived, then the earliest one. - $rank = [$parentId === null ? 0 : 1, $span->startTimeUnixNano]; - if ($root === null || $rank < $root[0]) { - $root = [$rank, $span]; - } - } - - $services = $this->services[$traceId] ?? []; - $root = $root[1] ?? null; - $service = $root === null ? null : $services[$root->spanId] ?? null; - $service ??= $services === [] ? null : \reset($services); - [$start, $end] = $this->getTraceBounds($traceId) ?? [0, 0]; - - return new TraceSummary( - traceId: $traceId, - name: $root?->name, - service: $service, - spans: \count($trace), - start: $start, - end: $end, - error: $error, - updatedAt: $this->updatedAt[$traceId], - seq: $this->changedAt[$traceId], - ); - } - /** * When the most recently updated trace alone exceeds the span limit, its oldest spans are dropped. */ @@ -380,9 +233,6 @@ private function evict(float $now): void unset( $this->traces[$traceId], $this->updatedAt[$traceId], - $this->changedAt[$traceId], - $this->services[$traceId], - $this->resources[$traceId], $this->children[$traceId], $this->bounds[$traceId], ); @@ -401,8 +251,6 @@ private function evict(float $now): void $trace = \array_slice($this->traces[$traceId], -$keep, null, true); $this->traces[$traceId] = $trace; $this->spanCount = \count($trace); - $this->services[$traceId] = \array_intersect_key($this->services[$traceId] ?? [], $trace); - $this->resources[$traceId] = \array_intersect_key($this->resources[$traceId] ?? [], $trace); $old = $this->children[$traceId] ?? []; $children = []; diff --git a/src/Module/Tracing/Console/TraceTree.php b/src/Module/Tracing/Console/TraceTree.php index 7b0e27d8..1b3b2058 100644 --- a/src/Module/Tracing/Console/TraceTree.php +++ b/src/Module/Tracing/Console/TraceTree.php @@ -7,7 +7,6 @@ use Buggregator\Trap\Module\Console\Support\Common; use Buggregator\Trap\Module\Tracing\Frame\Trace\Span; use Buggregator\Trap\Module\Tracing\Frame\Trace\StatusCode; -use Buggregator\Trap\Module\Tracing\SpanStore; use Buggregator\Trap\Support\Json; use Symfony\Component\Console\Formatter\OutputFormatter; use Symfony\Component\Console\Output\OutputInterface; @@ -41,7 +40,7 @@ final class TraceTree private int $budget = 0; public function __construct( - private readonly SpanStore $store, + private readonly SpanBuffer $store, ) {} /** diff --git a/src/Module/Tracing/Http/OtlpTrap.php b/src/Module/Tracing/Http/OtlpTrap.php index 3c221450..926e46ec 100644 --- a/src/Module/Tracing/Http/OtlpTrap.php +++ b/src/Module/Tracing/Http/OtlpTrap.php @@ -4,7 +4,6 @@ namespace Buggregator\Trap\Module\Tracing\Http; -use Buggregator\Trap\Module\Mcp\McpStatus; use Buggregator\Trap\Module\Tracing\Frame\OtlpLogs; use Buggregator\Trap\Module\Tracing\Frame\OtlpMetrics; use Buggregator\Trap\Module\Tracing\Frame\OtlpTraces; @@ -16,7 +15,6 @@ use Buggregator\Trap\Module\Tracing\Http\OtlpTrap\ProtobufDecoder; use Buggregator\Trap\Module\Tracing\Http\OtlpTrap\ProtobufTracesDecoder; use Buggregator\Trap\Module\Tracing\Http\OtlpTrap\TracesDecoder; -use Buggregator\Trap\Module\Tracing\SpanStore; use Buggregator\Trap\Server\Handler\Http\Middleware; use Buggregator\Trap\Server\Logger; use Buggregator\Trap\Support\Json; @@ -32,7 +30,6 @@ * * JSON is always decoded. Protobuf is decoded when the suggested protobuf packages are installed, * see {@see ProtobufTracesDecoder}; otherwise it gets 415. - * While the MCP server runs, received spans go to the {@see SpanStore} for its tools here, once per request. * * The project of the data is the `{project}` of `/api/{project}/integration/otlp/...`, else the * `X-Buggregator-Project` header; the default project without either. @@ -66,15 +63,12 @@ final class OtlpTrap implements Middleware /** * @param array|null $tracesDecoders Media type => decoder. * Null registers JSON, and protobuf when its packages are installed; so do the other decoder lists. - * @param SpanStore|null $spans Filled for the MCP tools while the server runs; null keeps no spans. * @param array|null $logsDecoders * @param array|null $metricsDecoders */ public function __construct( private readonly ?Logger $logger = null, ?array $tracesDecoders = null, - private readonly ?SpanStore $spans = null, - private readonly McpStatus $mcp = new McpStatus(), ?array $logsDecoders = null, ?array $metricsDecoders = null, ) { @@ -276,7 +270,6 @@ private function process(ServerRequestInterface $request, string $signal): Respo return $decoder->createSuccessResponse(); } - $frame instanceof OtlpTraces && $this->mcp->isOn() and $this->spans?->receive($frame); \Fiber::suspend($frame); return $decoder->createSuccessResponse(); diff --git a/src/Module/Tracing/Mcp/GetTrace.php b/src/Module/Tracing/Mcp/GetTrace.php index c26bd03a..ad13c1f3 100644 --- a/src/Module/Tracing/Mcp/GetTrace.php +++ b/src/Module/Tracing/Mcp/GetTrace.php @@ -7,21 +7,23 @@ use Buggregator\Trap\Module\Mcp\Tool; use Buggregator\Trap\Module\Mcp\Tool\MaxLength; use Buggregator\Trap\Module\Mcp\Tool\Time; +use Buggregator\Trap\Module\Tracing\Config\Traces; +use Buggregator\Trap\Module\Tracing\Console\SpanBuffer; use Buggregator\Trap\Module\Tracing\Console\TraceTree; -use Buggregator\Trap\Module\Tracing\SpanStore; +use Buggregator\Trap\Server\Telemetry\TelemetryStore; use Symfony\Component\Console\Output\BufferedOutput; use Symfony\Component\Console\Output\OutputInterface; /** - * A stored trace as plain text: a header line, then the tree of all its spans as the console prints it. + * A stored trace of a Sentry SDK or an OTLP exporter as plain text: a header line, then the tree of all its spans + * as the console prints OTLP spans, see {@see TraceSpans}. * * @internal */ final class GetTrace implements Tool { public function __construct( - private readonly SpanStore $store, - private readonly TraceTree $tree, + private readonly TelemetryStore $store, ) {} #[\Override] @@ -39,9 +41,10 @@ public function title(): string #[\Override] public function description(): string { - return 'Shows one OpenTelemetry trace as plain text, as the Trap console prints it: the tree of its ' - . 'spans with kind, duration, offset from the trace start, status, attributes, events and links. ' - . 'Take the ID from `list_traces`.'; + return 'Shows one trace, of Sentry or OpenTelemetry, as plain text, as the Trap console prints ' + . 'OpenTelemetry traces: a header line with its services, sources and projects, then the tree of its ' + . 'spans and transactions with kind, duration, offset from the trace start, status, attributes, events ' + . 'and links. Take the ID from `list_traces`, or from the trace ID of a Sentry error.'; } #[\Override] @@ -80,28 +83,47 @@ public function call(array $arguments): string $id = $arguments['id'] ?? null; \is_string($id) && $id !== '' or throw new \InvalidArgumentException('`id` must be a non-empty string.'); $maxLength = MaxLength::fromArguments($arguments); - $id = \strtolower($id); - $summary = $this->store->summary($id) ?? throw new \InvalidArgumentException( - "No trace with ID `$id`: it may have expired. Call `list_traces` for the current IDs.", + $trace = $this->store->trace($id) ?? $this->store->trace(\strtolower($id)); + $summary = $trace === null ? null : TraceSummary::of($trace); + $summary === null and throw new \InvalidArgumentException( + "No trace with ID `$id`: it may have been dropped. Call `list_traces` for the current IDs.", ); + $config = new Traces(); + $config->maxSpans = $summary->count(); + $buffer = new SpanBuffer($config); + $buffer->add(...TraceSpans::of($summary)); $output = new BufferedOutput(OutputInterface::VERBOSITY_NORMAL, false); - $this->tree->renderStored($output, $id); + (new TraceTree($buffer))->renderStored($output, $summary->trace->id); $text = \sprintf( - "trace %s, %d %s%s%s, updated at %s\n%s", - $summary->traceId, - $summary->spans, - $summary->spans === 1 ? 'span' : 'spans', - $summary->service === null ? '' : ", service $summary->service", + "trace %s, %d %s%s%s%s%s, updated at %s\n%s", + $summary->trace->id, + $summary->count(), + $summary->count() === 1 ? 'span' : 'spans', + self::names('service', $summary->services), + self::names('source', $summary->sources), + self::names('project', $summary->projects), $summary->error ? ', has errors' : '', - Time::format($summary->updatedAt), + Time::format($summary->trace->updatedAt), self::clean($output->fetch()), ); return MaxLength::cut($text, $maxLength); } + /** + * @param list $names + */ + private static function names(string $what, array $names): string + { + return match (\count($names)) { + 0 => '', + 1 => ", $what $names[0]", + default => ", {$what}s " . \implode('/', $names), + }; + } + /** * Drops the blank lines around the tree and the trailing spaces of the header. */ diff --git a/src/Module/Tracing/Mcp/ListTraces.php b/src/Module/Tracing/Mcp/ListTraces.php index 190c02a5..2e865931 100644 --- a/src/Module/Tracing/Mcp/ListTraces.php +++ b/src/Module/Tracing/Mcp/ListTraces.php @@ -8,12 +8,11 @@ use Buggregator\Trap\Module\Mcp\Tool\Arguments; use Buggregator\Trap\Module\Mcp\Tool\Cursor; use Buggregator\Trap\Module\Mcp\Tool\Time; -use Buggregator\Trap\Module\Tracing\SpanStore; -use Buggregator\Trap\Module\Tracing\TraceSummary; +use Buggregator\Trap\Server\Telemetry\TelemetryStore; /** - * The traces updated after a cursor that match a {@see TraceFilter}, the least recently updated first, - * with a summary each. + * The traces of the {@see TelemetryStore} updated after a cursor that match a {@see TraceFilter}, + * the least recently updated first, with a summary each: the traces of Sentry SDKs and of OTLP exporters alike. * * @internal */ @@ -23,7 +22,7 @@ final class ListTraces implements Tool public const MAX_LIMIT = 100; public function __construct( - private readonly SpanStore $store, + private readonly TelemetryStore $store, ) {} #[\Override] @@ -41,15 +40,16 @@ public function title(): string #[\Override] public function description(): string { - return 'Lists the OpenTelemetry traces Trap has received over OTLP: ID, root span name, service, number ' - . 'of spans, duration and whether a span failed. Spans of a trace may arrive in several requests, so ' - . 'a trace is updated as they come, and an updated trace is listed again. Returns the traces updated ' - . 'after the `since` cursor, least recently updated first, and a new opaque `cursor`: to see only ' - . 'the traces of the code you run next, call it once, keep the cursor, run the code, then call it ' - . 'with `since` set to that cursor. When `has_more` is true, call again with the returned cursor ' - . 'to get the rest. Narrow the list by `errors_only`, `service`, `name`, `min_duration_ms`, the time of ' - . 'the last update (`from`, `to`, such as `5m` for the last five minutes) and the text of span names ' - . 'and attributes (`search`). Read a trace as a tree of spans with `get_trace`.'; + return 'Lists the traces Trap has received: Sentry transactions and spans, and OpenTelemetry spans over ' + . 'OTLP. Each trace comes with its ID, name, services, sources, number of spans, duration and whether ' + . 'a span failed. Spans of a trace may arrive in several requests, so a trace is updated as they come, ' + . 'and an updated trace is listed again. Returns the traces updated after the `since` cursor, least ' + . 'recently updated first, and a new opaque `cursor`: to see only the traces of the code you run next, ' + . 'call it once, keep the cursor, run the code, then call it with `since` set to that cursor. When ' + . '`has_more` is true, call again with the returned cursor to get the rest. Narrow the list by `project`, ' + . '`source`, `errors_only`, `service`, `name`, `min_duration_ms`, the time of the last update (`from`, ' + . '`to`, such as `5m` for the last five minutes) and the text of span names and attributes (`search`). ' + . 'Read a trace as a tree of spans with `get_trace`.'; } #[\Override] @@ -79,6 +79,8 @@ public function inputSchema(): array #[\Override] public function outputSchema(): ?array { + $strings = ['type' => 'array', 'items' => ['type' => 'string']]; + return [ 'type' => 'object', 'properties' => [ @@ -91,24 +93,31 @@ public function outputSchema(): ?array 'id' => ['type' => 'string', 'description' => 'The trace ID to pass to `get_trace`.'], 'name' => [ 'type' => ['string', 'null'], - 'description' => 'The root span name; of the earliest span whose parent has not ' - . 'arrived while the root is missing.', + 'description' => 'The name of the root transaction or span; of the earliest span ' + . 'whose parent has not arrived while the root is missing.', ], 'service' => [ 'type' => ['string', 'null'], - 'description' => 'The `service.name` of the resource of the root span; of another ' - . 'span when that resource has none.', + 'description' => 'The service of the root; of another span when the root has none.', + ], + 'services' => $strings + ['description' => 'Every service of the trace.'], + 'sources' => $strings + [ + 'description' => '`sentry` for the parts of Sentry SDKs, `otel` for those of OTLP.', ], - 'spans' => ['type' => 'integer', 'minimum' => 1], + 'projects' => $strings, + 'spans' => ['type' => 'integer', 'minimum' => 1, 'description' => 'Spans and transactions.'], 'duration_ms' => [ 'type' => 'number', 'minimum' => 0, 'description' => 'From the earliest span start to the latest span end.', ], - 'error' => ['type' => 'boolean', 'description' => 'Whether a span has the error status.'], + 'error' => ['type' => 'boolean', 'description' => 'Whether a span or a transaction failed.'], 'updated' => ['type' => 'string', 'description' => 'When the last span arrived, ISO 8601.'], ], - 'required' => ['id', 'name', 'service', 'spans', 'duration_ms', 'error', 'updated'], + 'required' => [ + 'id', 'name', 'service', 'services', 'sources', 'projects', 'spans', 'duration_ms', 'error', + 'updated', + ], 'additionalProperties' => false, ], ], @@ -128,7 +137,18 @@ public function annotations(): array /** * @return array{ - * traces: list, + * traces: list, + * sources: list<'sentry'|'otel'>, + * projects: list, + * spans: int, + * duration_ms: float, + * error: bool, + * updated: string, + * }>, * cursor: non-empty-string, * has_more: bool, * } @@ -144,8 +164,13 @@ public function call(array $arguments): array $traces = []; $hasMore = false; $last = 0; - foreach ($this->store->traces($since) as $trace) { - if (!$filter->matches($trace, $this->store)) { + foreach ($this->store->traces() as $trace) { + if ($trace->seq <= $since) { + continue; + } + + $summary = TraceSummary::of($trace, $filter->projects); + if ($summary === null || !$filter->matches($summary)) { continue; } @@ -157,25 +182,39 @@ public function call(array $arguments): array } $last = $trace->seq; - $traces[] = self::describe($trace); + $traces[] = self::describe($summary); } return ['traces' => $traces, 'cursor' => Cursor::encode($this->store->id, $cursor), 'has_more' => $hasMore]; } /** - * @return array{id: non-empty-string, name: string|null, service: string|null, spans: int, duration_ms: float, error: bool, updated: string} + * @return array{ + * id: non-empty-string, + * name: string|null, + * service: string|null, + * services: list, + * sources: list<'sentry'|'otel'>, + * projects: list, + * spans: int, + * duration_ms: float, + * error: bool, + * updated: string, + * } */ private static function describe(TraceSummary $trace): array { return [ - 'id' => $trace->traceId, + 'id' => $trace->trace->id, 'name' => $trace->name, 'service' => $trace->service, - 'spans' => $trace->spans, - 'duration_ms' => TraceFilter::durationMs($trace), + 'services' => $trace->services, + 'sources' => $trace->sources, + 'projects' => $trace->projects, + 'spans' => $trace->count(), + 'duration_ms' => $trace->durationMs(), 'error' => $trace->error, - 'updated' => Time::format($trace->updatedAt), + 'updated' => Time::format($trace->trace->updatedAt), ]; } } diff --git a/src/Module/Tracing/Mcp/TraceFilter.php b/src/Module/Tracing/Mcp/TraceFilter.php index 56f8ead6..b76fb39a 100644 --- a/src/Module/Tracing/Mcp/TraceFilter.php +++ b/src/Module/Tracing/Mcp/TraceFilter.php @@ -9,23 +9,27 @@ use Buggregator\Trap\Module\Mcp\Tool\Time; use Buggregator\Trap\Module\Mcp\Tool\TimeRange; use Buggregator\Trap\Module\Mcp\Tool\Wildcard; -use Buggregator\Trap\Module\Tracing\Frame\Trace\Span; -use Buggregator\Trap\Module\Tracing\SpanStore; -use Buggregator\Trap\Module\Tracing\TraceSummary; +use Buggregator\Trap\Server\Event\Event; use Buggregator\Trap\Support\Json; /** - * Which traces {@see ListTraces} takes: `errors_only`, `from`, `to`, `service`, `name`, `min_duration_ms`, - * `search` and `regex`. + * Which traces {@see ListTraces} takes: `project`, `source`, `errors_only`, `from`, `to`, `service`, `name`, + * `min_duration_ms`, `search` and `regex`. * * @internal */ final class TraceFilter { + public const SOURCES = ['sentry', 'otel']; + /** + * @param list $projects The parts of a trace sent to these projects are listed; + * every part when empty. * @param list $services Any service when empty. */ private function __construct( + public readonly array $projects, + private readonly ?string $source, private readonly bool $errorsOnly, private readonly TimeRange $time, private readonly array $services, @@ -40,16 +44,32 @@ private function __construct( public static function schema(): array { return [ + 'project' => [ + 'description' => \sprintf( + 'Only the part of every trace sent to this project or to any of these projects; data sent ' + . 'without a project belongs to `%s`. All projects when omitted.', + Event::DEFAULT_PROJECT, + ), + 'anyOf' => [ + ['type' => 'string'], + ['type' => 'array', 'items' => ['type' => 'string'], 'minItems' => 1], + ], + ], + 'source' => [ + 'type' => 'string', + 'enum' => self::SOURCES, + 'description' => 'Only the traces with a part sent by a Sentry SDK (`sentry`) or over OTLP (`otel`).', + ], 'errors_only' => [ 'type' => 'boolean', 'default' => false, - 'description' => 'Only the traces with a span of the error status.', + 'description' => 'Only the traces with a failed span or transaction.', ], 'from' => Time::schema('Only the traces last updated at this time or later.'), 'to' => Time::schema('Only the traces last updated at this time or earlier.'), 'service' => [ - 'description' => 'Only the traces of this service or of any of these services; in any case, ' - . 'with `*` for any characters.', + 'description' => 'Only the traces with a part of this service or of any of these services; in any ' + . 'case, with `*` for any characters. `*` also takes a trace without services.', 'anyOf' => [ ['type' => 'string'], ['type' => 'array', 'items' => ['type' => 'string'], 'minItems' => 1], @@ -84,8 +104,15 @@ public static function fromArguments(array $arguments, float $now): self /** @var mixed $name */ $name = $arguments['name'] ?? null; $name === null || \is_string($name) or throw new \InvalidArgumentException('`name` must be a string.'); + $source = isset($arguments['source']) ? Arguments::choice($arguments, 'source', self::SOURCES) : null; + $projects = \array_map( + static fn(string $project): string => $project === '' ? Event::DEFAULT_PROJECT : $project, + Arguments::strings($arguments, 'project'), + ); return new self( + projects: \array_values(\array_unique($projects)), + source: $source, errorsOnly: Arguments::boolean($arguments, 'errors_only'), time: $time, services: \array_map(Wildcard::compile(...), Arguments::strings($arguments, 'service')), @@ -95,32 +122,28 @@ public static function fromArguments(array $arguments, float $now): self ); } - public static function durationMs(TraceSummary $trace): float - { - return \round((float) Span::elapsed($trace->start, $trace->end) / 1e6, 3); - } - /** * @throws \InvalidArgumentException When the regular expression of the search fails on the trace. */ - public function matches(TraceSummary $trace, SpanStore $store): bool + public function matches(TraceSummary $trace): bool { return (!$this->errorsOnly || $trace->error) - && $this->time->contains($trace->updatedAt) - && ($this->services === [] || $this->matchesService($trace->service)) + && ($this->source === null || \in_array($this->source, $trace->sources, true)) + && $this->time->contains($trace->trace->updatedAt) + && ($this->services === [] || $this->matchesService($trace->services)) && ($this->name === null || $this->name->matches($trace->name ?? '')) - && ($this->minDuration === null || self::durationMs($trace) >= $this->minDuration) - && ($this->search === null || $this->search->matches(self::text($store, $trace->traceId))); + && ($this->minDuration === null || $trace->durationMs() >= $this->minDuration) + && ($this->search === null || $this->search->matches(self::text($trace))); } /** * A line each: the name of a span, its status message, the name of a span event such as `exception`, * and an attribute of a span, a span event or a resource as `key=value`. */ - private static function text(SpanStore $store, string $traceId): string + private static function text(TraceSummary $trace): string { $lines = []; - foreach ($store->getTrace($traceId) as $span) { + foreach (TraceSpans::of($trace) as $span) { $lines[] = $span->name; $span->status->message === '' or $lines[] = $span->status->message; self::attributes($span->attributes, $lines); @@ -130,7 +153,7 @@ private static function text(SpanStore $store, string $traceId): string } } - foreach ($store->getResources($traceId) as $attributes) { + foreach (TraceSpans::resources($trace) as $attributes) { self::attributes($attributes, $lines); } @@ -158,11 +181,18 @@ private static function json(mixed $value): string } } - private function matchesService(?string $service): bool + /** + * A trace without services matches as one of an empty name, so `*` takes every trace. + * + * @param list $services + */ + private function matchesService(array $services): bool { foreach ($this->services as $pattern) { - if ($pattern->matches($service ?? '')) { - return true; + foreach ($services === [] ? [''] : $services as $service) { + if ($pattern->matches($service)) { + return true; + } } } diff --git a/src/Module/Tracing/Mcp/TraceSpans.php b/src/Module/Tracing/Mcp/TraceSpans.php new file mode 100644 index 00000000..c73e4736 --- /dev/null +++ b/src/Module/Tracing/Mcp/TraceSpans.php @@ -0,0 +1,222 @@ + + */ + public static function of(TraceSummary $trace): array + { + $spans = []; + foreach ($trace->transactions as $transaction) { + $spanId = $transaction->spanId; + $spanId === null || $spanId === '' and $spanId = $transaction->id; + $spans[] = self::span( + $transaction, + $spanId, + $transaction->name === '' ? $transaction->op : $transaction->name, + ); + } + + foreach ($trace->spans as $span) { + $name = match (true) { + $span->source === Source::Otel, $span->op === '' => $span->description, + $span->description === '' => $span->op, + default => "$span->op: $span->description", + }; + $spans[] = self::span($span, $span->spanId, $name); + } + + return $spans; + } + + /** + * @return list> The distinct resource attributes of the OTel parts. + */ + public static function resources(TraceSummary $trace): array + { + $result = []; + foreach ([...$trace->transactions, ...$trace->spans] as $part) { + /** @var mixed $resource */ + $resource = $part->attributes['otel.resource'] ?? null; + \is_array($resource) && $resource !== [] && !\in_array($resource, $result, true) and $result[] = $resource; + } + + return $result; + } + + /** + * @param non-empty-string $spanId + */ + private static function span(Span|Transaction $part, string $spanId, string $name): OtlpSpan + { + // OTel values as the decoder gives them, Sentry data as JSON gives it: printed as JSON either way. + /** @var AttributeMap $attributes */ + $attributes = $part->attributes; + $otel = $part->source === Source::Otel; + $start = self::nanos($part->start ?? $part->end); + $end = self::nanos($part->end ?? $part->start); + $parentId = $part->parentSpanId; + + return new OtlpSpan( + traceId: $part->traceId, + spanId: $spanId, + parentSpanId: $parentId === null || $parentId === '' ? null : $parentId, + name: $name, + kind: $otel ? self::otelKind($attributes['otel.kind'] ?? null) : self::sentryKind($part->op), + startTimeUnixNano: $start, + endTimeUnixNano: \max($start, $end), + attributes: $otel ? \array_diff_key($attributes, \array_flip(self::OTEL_KEYS)) : $attributes, + events: $otel ? self::events($attributes['otel.events'] ?? null) : [], + links: $otel ? self::links($attributes['otel.links'] ?? null) : [], + status: $otel ? self::otelStatus($attributes) : self::sentryStatus($part->status), + ); + } + + private static function otelKind(mixed $kind): SpanKind + { + return match ($kind) { + 'server' => SpanKind::Server, + 'client' => SpanKind::Client, + 'producer' => SpanKind::Producer, + 'consumer' => SpanKind::Consumer, + default => SpanKind::Internal, + }; + } + + private static function sentryKind(string $op): SpanKind + { + return match (true) { + $op === 'http.server' => SpanKind::Server, + $op === 'http.client' => SpanKind::Client, + \str_starts_with($op, 'queue.publish') => SpanKind::Producer, + \str_starts_with($op, 'queue.process') => SpanKind::Consumer, + default => SpanKind::Internal, + }; + } + + private static function otelStatus(array $attributes): SpanStatus + { + /** @var mixed $message */ + $message = $attributes['otel.status_description'] ?? ''; + + return new SpanStatus( + match ($attributes['otel.status_code'] ?? null) { + 'ok' => StatusCode::Ok, + 'error' => StatusCode::Error, + default => StatusCode::Unset, + }, + \is_string($message) ? $message : '', + ); + } + + private static function sentryStatus(string $status): SpanStatus + { + return match (true) { + $status === 'ok' => new SpanStatus(StatusCode::Ok), + Span::isErrorStatus($status) => new SpanStatus(StatusCode::Error, $status), + default => new SpanStatus(), + }; + } + + /** + * @return list + */ + private static function events(mixed $events): array + { + $result = []; + foreach (\is_array($events) ? $events : [] as $event) { + if (!\is_array($event)) { + continue; + } + + /** @var mixed $name */ + $name = $event['name'] ?? ''; + /** @var AttributeMap $attributes */ + $attributes = \is_array($event['attributes'] ?? null) ? $event['attributes'] : []; + $result[] = new SpanEvent( + self::isoNanos($event['time'] ?? null), + \is_string($name) ? $name : '', + $attributes, + ); + } + + return $result; + } + + /** + * @return list + */ + private static function links(mixed $links): array + { + $result = []; + /** @var mixed $link */ + foreach (\is_array($links) ? $links : [] as $link) { + /** @var mixed $traceId */ + $traceId = \is_array($link) ? $link['trace_id'] ?? null : null; + /** @var mixed $spanId */ + $spanId = \is_array($link) ? $link['span_id'] ?? null : null; + \is_string($traceId) && $traceId !== '' && \is_string($spanId) && $spanId !== '' + and $result[] = new SpanLink($traceId, $spanId); + } + + return $result; + } + + /** + * @param float|null $seconds Unix seconds. + */ + private static function nanos(?float $seconds): int + { + return $seconds === null || !\is_finite($seconds) || $seconds <= 0.0 || $seconds >= 9.2e9 + ? 0 + : (int) \round($seconds * 1e9); + } + + /** + * @return int Unix nanoseconds of a time the telemetry mapper writes, as `2024-01-01T10:00:00.123456Z`; + * 0 for others. + */ + private static function isoNanos(mixed $time): int + { + $date = \is_string($time) + ? \DateTimeImmutable::createFromFormat('Y-m-d\TH:i:s.u\Z', $time, new \DateTimeZone('UTC')) + : false; + + return $date === false ? 0 : (int) $date->format('U') * 1_000_000_000 + (int) $date->format('u') * 1000; + } +} diff --git a/src/Module/Tracing/Mcp/TraceSummary.php b/src/Module/Tracing/Mcp/TraceSummary.php new file mode 100644 index 00000000..6750f66b --- /dev/null +++ b/src/Module/Tracing/Mcp/TraceSummary.php @@ -0,0 +1,166 @@ + $transactions + * @param list $spans Without the spans of the IDs of the transactions. + * @param string|null $name The name of the root transaction: the one without a parent, else the earliest. + * Without transactions, of the earliest span whose parent has not arrived; null when every span has + * a stored parent, as in a parent cycle. + * @param string|null $service Of the root, else of any part. + * @param list $services + * @param list<'sentry'|'otel'> $sources + * @param list $projects + * @param float|null $start Unix seconds of the earliest start; null when no part has a start. + * @param float|null $end Unix seconds of the latest end. + */ + private function __construct( + public readonly Trace $trace, + public readonly array $transactions, + public readonly array $spans, + public readonly ?string $name, + public readonly ?string $service, + public readonly array $services, + public readonly array $sources, + public readonly array $projects, + public readonly ?float $start, + public readonly ?float $end, + public readonly bool $error, + ) {} + + /** + * @param list $projects The parts of these projects; all of them when empty. + * @return self|null Null when the trace has no part in the projects. + */ + public static function of(Trace $trace, array $projects = []): ?self + { + $in = static fn(Span|Transaction $part): bool => $projects === [] || \in_array($part->project, $projects, true); + $transactions = \array_values(\array_filter($trace->transactions, $in)); + $spans = \array_filter($trace->spans, $in); + // A span and a transaction of one ID are one span, as on the trace page of the UI. + foreach ($transactions as $transaction) { + if ($transaction->spanId !== null) { + unset($spans[$transaction->spanId]); + } + } + $spans = \array_values($spans); + if ($transactions === [] && $spans === []) { + return null; + } + + $root = self::rootTransaction($transactions) ?? self::rootSpan($spans); + $parts = [...$transactions, ...$spans]; + $services = $sources = $projectList = []; + $start = $end = null; + $error = false; + foreach ($parts as $part) { + $part->service === null || $part->service === '' or $services[$part->service] = true; + $sources[$part->source->value] = true; + $projectList[$part->project] = true; + $part->start === null or $start = \min($start ?? \INF, $part->start); + $part->end === null or $end = \max($end ?? -\INF, $part->end); + $error = $error || $part->isError(); + } + + /** @var list $services */ + $services = \array_keys($services); + /** @var list<'sentry'|'otel'> $sources */ + $sources = \array_keys($sources); + /** @var list $projectList */ + $projectList = \array_map('strval', \array_keys($projectList)); + + return new self( + trace: $trace, + transactions: $transactions, + spans: $spans, + name: match (true) { + $root instanceof Transaction => $root->name, + $root instanceof Span => $root->description, + default => null, + }, + service: $root?->service === null || $root->service === '' ? $services[0] ?? null : $root->service, + services: $services, + sources: $sources, + projects: $projectList, + start: $start, + end: $end, + error: $error, + ); + } + + /** + * @return int<1, max> Transactions and spans. + */ + public function count(): int + { + return \max(1, \count($this->transactions) + \count($this->spans)); + } + + /** + * From the earliest start to the latest end, to a microsecond. + */ + public function durationMs(): float + { + return $this->start === null || $this->end === null || $this->end <= $this->start + ? 0.0 + : \round(($this->end - $this->start) * 1000.0, 3); + } + + /** + * @param list $transactions + */ + private static function rootTransaction(array $transactions): ?Transaction + { + $root = null; + foreach ($transactions as $transaction) { + $rank = [$transaction->parentSpanId !== null, $transaction->start ?? \INF, $transaction->id]; + if ($root === null || $rank < $root[0]) { + $root = [$rank, $transaction]; + } + } + + return $root[1] ?? null; + } + + /** + * @param list $spans + */ + private static function rootSpan(array $spans): ?Span + { + $ids = []; + foreach ($spans as $span) { + $ids[$span->spanId] = true; + } + + $root = null; + foreach ($spans as $span) { + $parentId = $span->parentSpanId; + if ($parentId !== null && ($parentId === $span->spanId || isset($ids[$parentId]))) { + continue; + } + + // A span without a parent wins over one whose parent has not arrived, then the earliest one. + $rank = [$parentId === null ? 0 : 1, $span->start ?? \INF]; + if ($root === null || $rank < $root[0]) { + $root = [$rank, $span]; + } + } + + return $root[1] ?? null; + } +} diff --git a/src/Module/Tracing/Module.php b/src/Module/Tracing/Module.php index 33c34de1..fad75af7 100644 --- a/src/Module/Tracing/Module.php +++ b/src/Module/Tracing/Module.php @@ -20,8 +20,8 @@ use Buggregator\Trap\Server\Proto\ProvidesFrameTypes; /** - * The middleware and the tools share the {@see SpanStore} of the container, one for the Trap process: - * the middleware fills it while the MCP server runs, the tools read it. The renderer keeps a store of its own. + * The mapper fills the {@see \Buggregator\Trap\Server\Telemetry\TelemetryStore} the web UI and the MCP tools + * read; the console renderer keeps a {@see Console\SpanBuffer} of its own. * * @internal */ @@ -51,7 +51,7 @@ public function renderers(): array } /** - * OTLP makes no events: the mapper fills the telemetry store of the web UI, the MCP tools read the span store. + * OTLP makes no events: the mapper fills the telemetry store. */ #[\Override] public function eventMappers(): array diff --git a/src/Module/Tracing/TraceSummary.php b/src/Module/Tracing/TraceSummary.php deleted file mode 100644 index 35410cc3..00000000 --- a/src/Module/Tracing/TraceSummary.php +++ /dev/null @@ -1,37 +0,0 @@ - $spans - * @param int $start Unix nanoseconds of the earliest span start. - * @param int $end Unix nanoseconds of the latest span end. - * @param bool $error Whether a span has the error status. - * @param float $updatedAt Unix time of the last received span, in seconds. - * @param int<1, max> $seq The store sequence number of the last stored span of the trace. - */ - public function __construct( - public readonly string $traceId, - public readonly ?string $name, - public readonly ?string $service, - public readonly int $spans, - public readonly int $start, - public readonly int $end, - public readonly bool $error, - public readonly float $updatedAt, - public readonly int $seq, - ) {} -} diff --git a/src/Server/Config/Telemetry.php b/src/Server/Config/Telemetry.php index 31324d82..b3a6c382 100644 --- a/src/Server/Config/Telemetry.php +++ b/src/Server/Config/Telemetry.php @@ -9,7 +9,8 @@ use Buggregator\Trap\Server\Application\Config\Internal\Attribute\XPath; /** - * Limits of the telemetry buffer: the traces, logs and metrics of the Sentry pages of the web UI. + * Limits of the telemetry buffer: the traces, logs and metrics of the Sentry pages of the web UI + * and of the MCP trace tools. * Values below 1 fall back to the defaults. * * @internal diff --git a/src/Server/Telemetry/TelemetryStore.php b/src/Server/Telemetry/TelemetryStore.php index d7988454..b2a0b0b4 100644 --- a/src/Server/Telemetry/TelemetryStore.php +++ b/src/Server/Telemetry/TelemetryStore.php @@ -7,11 +7,14 @@ use Buggregator\Trap\Server\Config\Telemetry as Config; /** - * Traces, logs and metrics of Sentry SDKs and OTLP exporters, the data of the Sentry pages of the web UI. - * Unlike events, they make no feed cards. + * Traces, logs and metrics of Sentry SDKs and OTLP exporters: the data of the Sentry pages of the web UI + * and of the trace tools of the MCP server. Unlike events, they make no feed cards. * * A container singleton, filled by the event mappers of the Sentry and Tracing modules, so only while - * an event consumer runs: the web UI or the MCP server. + * an event consumer runs: the web UI or the MCP server, its only readers. + * + * Every change of a trace gets the next sequence number: a trace keeps the one of its last change, + * and {@see traces()} lists the traces in the order of these numbers. * * Memory is bounded by {@see Config}. Above `maxSpans` the least recently updated traces are dropped, and * a single trace above it keeps its most recent 90%. Above `maxLogs` or `maxMetrics` the oldest 10% go. @@ -20,6 +23,12 @@ */ final class TelemetryStore { + /** + * A random ID of the store, and so of the Trap process: sequence numbers of another process mean nothing here. + * @var non-empty-string + */ + public readonly string $id; + /** * From the least to the most recently updated trace. * @@ -30,6 +39,9 @@ final class TelemetryStore /** @var int<0, max> Transactions and spans of all the traces */ private int $size = 0; + /** @var int<0, max> */ + private int $seq = 0; + /** @var list From the oldest */ private array $logs = []; @@ -48,12 +60,20 @@ final class TelemetryStore /** @var int<1, max> */ private readonly int $maxMetrics; - public function __construct(Config $config = new Config()) + /** @var \Closure(): float */ + private readonly \Closure $clock; + + /** + * @param \Closure(): float|null $clock Current Unix time in seconds. + */ + public function __construct(Config $config = new Config(), ?\Closure $clock = null) { $defaults = new Config(); $this->maxSpans = \max(1, $config->maxSpans >= 1 ? $config->maxSpans : $defaults->maxSpans); $this->maxLogs = \max(1, $config->maxLogs >= 1 ? $config->maxLogs : $defaults->maxLogs); $this->maxMetrics = \max(1, $config->maxMetrics >= 1 ? $config->maxMetrics : $defaults->maxMetrics); + $this->clock = $clock ?? static fn(): float => \microtime(true); + $this->id = \bin2hex(\random_bytes(4)); } public function listen(TelemetryListener $listener): void @@ -67,14 +87,15 @@ public function listen(TelemetryListener $listener): void */ public function add(Batch $batch): void { + $now = ($this->clock)(); foreach ($batch->transactions as $transaction) { - $trace = $this->touch($transaction->traceId); + $trace = $this->touch($transaction->traceId, $now); isset($trace->transactions[$transaction->id]) or ++$this->size; $trace->transactions[$transaction->id] = $transaction; } foreach ($batch->spans as $span) { - $trace = $this->touch($span->traceId); + $trace = $this->touch($span->traceId, $now); isset($trace->spans[$span->spanId]) or ++$this->size; unset($trace->spans[$span->spanId]); $trace->spans[$span->spanId] = $span; @@ -99,7 +120,18 @@ public function add(Batch $batch): void } /** - * @return array From the least to the most recently updated one. + * The sequence number of the last change of a trace; 0 before the first one. + * + * @return int<0, max> + */ + public function cursor(): int + { + return $this->seq; + } + + /** + * @return array From the least to the most recently updated one, so in the order + * of {@see Trace::$seq}. */ public function traces(): array { @@ -170,10 +202,12 @@ private static function trim(array $items, int $max): array * * @param non-empty-string $traceId */ - private function touch(string $traceId): Trace + private function touch(string $traceId, float $now): Trace { $trace = $this->traces[$traceId] ?? new Trace($traceId); unset($this->traces[$traceId]); + $trace->seq = ++$this->seq; + $trace->updatedAt = $now; return $this->traces[$traceId] = $trace; } diff --git a/src/Server/Telemetry/Trace.php b/src/Server/Telemetry/Trace.php index fe6a3d94..0eb56560 100644 --- a/src/Server/Telemetry/Trace.php +++ b/src/Server/Telemetry/Trace.php @@ -19,6 +19,12 @@ final class Trace /** @var array By span ID, an int key for an all-digit one; in the order of arrival */ public array $spans = []; + /** @var int<0, max> The {@see TelemetryStore::cursor()} of its last change */ + public int $seq = 0; + + /** Unix seconds of its last change */ + public float $updatedAt = 0.0; + /** * @param non-empty-string $id */ diff --git a/src/Support/Measure.php b/src/Support/Measure.php index 50b2403e..1de43610 100644 --- a/src/Support/Measure.php +++ b/src/Support/Measure.php @@ -17,7 +17,8 @@ final class Measure public static function memory(int $size): string { $units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB']; - $power = (int) \floor(\log($size, 1024)); + // log(0) is -INF, which no int can hold. + $power = $size === 0 ? 0 : (int) \floor(\log($size, 1024)); $float = $power > 0 ? \round($size / (1024 ** $power), 2) : $size; \assert($power >= 0 && $power <= 6); diff --git a/tests/Acceptance/ServerTest.php b/tests/Acceptance/ServerTest.php index dee4c318..d2421d0d 100644 --- a/tests/Acceptance/ServerTest.php +++ b/tests/Acceptance/ServerTest.php @@ -535,6 +535,9 @@ public function testMcpToolsReadReceivedTraces(): void 'id' => '382bfca057473920912cab0a4ed95abe', 'name' => 'GET /orders', 'service' => 'e2e-app', + 'services' => ['e2e-app'], + 'sources' => ['otel'], + 'projects' => ['default'], 'spans' => 4, 'duration_ms' => 27.691, 'error' => true, @@ -865,8 +868,14 @@ public function testSentryEnvelopeIsCaptured(): void ); Assert::same($envelope['headers']['event_id'], '1c375fcd2f15438f82d8762f083cd8c0'); Assert::notBlank($envelope['items']); - $event = $trap->waitForUiEvent($this->uiPort, 'sentry'); - Assert::string(\json_encode($event['payload']))->contains('1c375fcd2f15438f82d8762f083cd8c0'); + // The envelope holds a transaction: a trace of the Sentry pages, not a card of the feed. + $trace = TrapProcess::waitFor(function (): ?array { + [$status, , $body] = TrapProcess::http($this->uiPort, 'GET', '/api/sentry/traces/93c66872a715428ba1934889bf60dc07'); + return $status === 200 ? self::json($body) : null; + }, 'the trace of the transaction in the web UI'); + Assert::same($trace['transaction']['transaction_name'], 'CallAction'); + [, , $events] = TrapProcess::http($this->uiPort, 'GET', '/api/events'); + Assert::same(self::json($events)['data'], []); } /** diff --git a/tests/Unit/Module/Console/ConsoleSenderTest.php b/tests/Unit/Module/Console/ConsoleSenderTest.php index f6c13fbb..90d3e437 100644 --- a/tests/Unit/Module/Console/ConsoleSenderTest.php +++ b/tests/Unit/Module/Console/ConsoleSenderTest.php @@ -16,7 +16,6 @@ use Buggregator\Trap\Module\Sentry\Console\SentryStore as SentryStoreRenderer; use Buggregator\Trap\Module\Tracing\Console\Renderer as TracingRenderer; use Buggregator\Trap\Module\Tracing\Console\SignalRenderer; -use Buggregator\Trap\Module\Tracing\SpanStore; use Buggregator\Trap\Module\VarDumper\Console\Renderer as VarDumperRenderer; use Buggregator\Trap\Module\XDebugTrace\Console\Renderer as XDebugTraceRenderer; use Buggregator\Trap\Server\Application\Module\Modules; @@ -51,22 +50,6 @@ public function testModuleRenderersInListOrderThenChannelOnesWithPlainLast(): vo ]); } - /** - * The OTLP middleware fills the store of the container before the console renders the frame. - */ - public function testTracingRendererKeepsSpanStoreOfItsOwn(): void - { - $container = new ObjectContainer(); - - $renderers = self::renderers(self::sender($container)); - $tracing = \array_values(\array_filter( - $renderers, - static fn(Renderer $renderer): bool => $renderer instanceof TracingRenderer, - ))[0]; - - Assert::notSame((new \ReflectionProperty(TracingRenderer::class, 'store'))->getValue($tracing), $container->get(SpanStore::class)); - } - private static function sender(ObjectContainer $container): ConsoleSender { return new ConsoleSender(new BufferedOutput(), $container->get(Modules::class), $container); diff --git a/tests/Unit/Module/Mcp/Tool/ListEventsTest.php b/tests/Unit/Module/Mcp/Tool/ListEventsTest.php index 444e8cf7..d1c57dfb 100644 --- a/tests/Unit/Module/Mcp/Tool/ListEventsTest.php +++ b/tests/Unit/Module/Mcp/Tool/ListEventsTest.php @@ -438,7 +438,7 @@ public function testIsReadOnly(): void Assert::same($tool->name(), 'list_events'); Assert::same($tool->title(), 'List events'); Assert::same($tool->annotations(), ['readOnlyHint' => true, 'openWorldHint' => false]); - Assert::string($tool->description())->contains('get_event')->contains('monolog: level, channel'); + Assert::string($tool->description())->contains('get_event')->contains('monolog: level, channel')->contains('list_traces'); } public function testCollectWithAMemoDescribesAnUnchangedEventOnce(): void diff --git a/tests/Unit/Module/Mcp/Tool/WaitForEventsTest.php b/tests/Unit/Module/Mcp/Tool/WaitForEventsTest.php index f9377a5d..3fe02abf 100644 --- a/tests/Unit/Module/Mcp/Tool/WaitForEventsTest.php +++ b/tests/Unit/Module/Mcp/Tool/WaitForEventsTest.php @@ -462,7 +462,8 @@ public function testIsReadOnly(): void Assert::same($tool->annotations(), ['readOnlyHint' => true, 'openWorldHint' => false]); Assert::string($tool->description()) ->contains(\sprintf('(%d by default, %d at most)', WaitForEvents::DEFAULT_TIMEOUT, WaitForEvents::MAX_TIMEOUT)) - ->contains('`list_events`'); + ->contains('`list_events`') + ->contains('`list_traces`'); } public function testSchemaTakesTheListArgumentsWithCountAndTimeout(): void diff --git a/tests/Unit/Module/Sentry/Console/SentryEnvelopeTest.php b/tests/Unit/Module/Sentry/Console/SentryEnvelopeTest.php index 9fc376e1..bc6155e4 100644 --- a/tests/Unit/Module/Sentry/Console/SentryEnvelopeTest.php +++ b/tests/Unit/Module/Sentry/Console/SentryEnvelopeTest.php @@ -6,6 +6,7 @@ use Buggregator\Trap\Module\Monolog\Frame as Monolog; use Buggregator\Trap\Module\Sentry\Console\SentryEnvelope; +use Buggregator\Trap\Module\Sentry\Console\TraceLine; use Buggregator\Trap\Module\Sentry\Frame\EnvelopeItem; use Buggregator\Trap\Module\Sentry\Frame\SentryEnvelope as SentryEnvelopeFrame; use Nyholm\Psr7\Stream; @@ -16,6 +17,7 @@ use Testo\Test; #[Covers(SentryEnvelope::class)] +#[Covers(TraceLine::class)] #[Test] final class SentryEnvelopeTest { @@ -95,6 +97,55 @@ public function testIgnoresMalformedEventException(array $exception): void Assert::string($output)->contains('There is no renderer for this item type.')->notContains('Exceptions')->notContains('Render error'); } + public function testRendersTransactionAsTraceLine(): void + { + $output = $this->render(new SentryEnvelopeFrame(['event_id' => 'abc'], [ + new EnvelopeItem(['type' => 'transaction'], [ + 'transaction' => 'POST /checkout', + 'contexts' => ['trace' => ['trace_id' => 'aaaabbbbccccdddd', 'span_id' => 's0', 'op' => 'http.server']], + 'start_timestamp' => 100.0, + 'timestamp' => 100.25, + 'spans' => [ + ['span_id' => 's1', 'op' => 'db', 'start_timestamp' => 100.0, 'timestamp' => 100.1], + ['span_id' => 's2', 'op' => 'http.client', 'status' => 'internal_error'], + ], + ]), + ])); + + Assert::string($output) + ->contains("Trace aaaabbbbccccdddd: POST /checkout (http.server), 250 ms, 3 spans, 1 failed\n") + ->notContains('There is no renderer for this item type.'); + } + + public function testRendersSpanItemsByTheirRootSpan(): void + { + $output = $this->render(new SentryEnvelopeFrame([], [ + new EnvelopeItem(['type' => 'span'], ['items' => [ + ['trace_id' => 'aaaabbbbccccdddd', 'span_id' => 's1', 'name' => 'query', 'op' => 'db', 'start_timestamp' => 10.0, 'end_timestamp' => 10.1], + ['trace_id' => 'aaaabbbbccccdddd', 'span_id' => 's2', 'parent_span_id' => 's1', 'name' => 'fetch'], + ]]), + ])); + + Assert::string($output)->contains("Trace aaaabbbbccccdddd: query (db), 100 ms, 2 spans\n"); + } + + public function testRendersTransactionWithoutTraceIdAsItsLine(): void + { + $output = $this->render(new SentryEnvelopeFrame([], [ + new EnvelopeItem(['type' => 'transaction'], [ + 'transaction' => 'POST /checkout', + 'op' => 'http.server', + 'start_timestamp' => 100.0, + 'timestamp' => 100.25, + 'spans' => [['span_id' => 's1'], ['op' => 'no ID']], + ]), + ])); + + Assert::string($output) + ->contains("Transaction without a trace ID: POST /checkout (http.server), 250 ms, 2 spans\n") + ->notContains('There is no renderer for this item type.'); + } + public function testRendersAttachmentItemHeader(): void { $output = $this->render(new SentryEnvelopeFrame(['event_id' => 'abc'], [ diff --git a/tests/Unit/Module/Sentry/Console/SentryStoreTest.php b/tests/Unit/Module/Sentry/Console/SentryStoreTest.php new file mode 100644 index 00000000..7d36153a --- /dev/null +++ b/tests/Unit/Module/Sentry/Console/SentryStoreTest.php @@ -0,0 +1,53 @@ + 'transaction', + 'transaction' => 'GET /', + 'contexts' => ['trace' => ['trace_id' => 'aaaabbbbccccdddd']], + 'spans' => [], + ]); + + Assert::string($output)->contains("Trace aaaabbbbccccdddd: GET /, 1 span\n"); + } + + public function testRendersTransactionWithoutTraceIdAsItsLine(): void + { + $output = self::render(['type' => 'transaction', 'transaction' => 'GET /', 'spans' => []]); + + Assert::string($output)->contains("Transaction without a trace ID: GET /, 1 span\n")->notContains('Trace '); + } + + public function testRendersErrorExceptions(): void + { + $output = self::render(['exception' => ['values' => [['type' => 'RuntimeException', 'value' => 'Boom']]]]); + + Assert::string($output)->contains('RuntimeException')->contains('Boom')->notContains('trace ID'); + } + + private static function render(array $message): string + { + $output = new BufferedOutput(); + (new SentryStore())->render($output, new SentryStoreFrame($message)); + + return \str_replace("\r\n", "\n", $output->fetch()); + } +} diff --git a/tests/Unit/Module/Sentry/Frontend/EnvelopeMapperTest.php b/tests/Unit/Module/Sentry/Frontend/EnvelopeMapperTest.php index ad695e92..b72ca3b2 100644 --- a/tests/Unit/Module/Sentry/Frontend/EnvelopeMapperTest.php +++ b/tests/Unit/Module/Sentry/Frontend/EnvelopeMapperTest.php @@ -41,7 +41,7 @@ public function testEventItemMakesTheFeedEventAndTelemetryGoesToTheStore(): void Assert::count($store->metrics(), 1); } - public function testTransactionStaysAFeedEventAndBecomesATrace(): void + public function testTransactionBecomesATraceWithoutAFeedEvent(): void { $store = new TelemetryStore(); $transaction = ['event_id' => 't1', 'contexts' => ['trace' => ['trace_id' => self::TRACE]], 'spans' => []]; @@ -49,21 +49,80 @@ public function testTransactionStaysAFeedEventAndBecomesATrace(): void $event = (new EnvelopeMapper($store))->map($frame); - Assert::same($event?->payload, $transaction); - Assert::same($event?->projectKey(), 'default'); + Assert::null($event); Assert::same(\array_keys($store->trace(self::TRACE)?->transactions ?? []), ['t1']); + Assert::same($store->trace(self::TRACE)?->transactions['t1']->project, 'default'); + } + + public function testTransactionWithoutTraceIdStaysInTheFeed(): void + { + $store = new TelemetryStore(); + $transaction = ['event_id' => 't1', 'transaction' => 'GET /', 'spans' => []]; + $frame = new SentryEnvelope([], [ + new EnvelopeItem(['type' => 'client_report'], ['discarded_events' => []]), + new EnvelopeItem(['type' => 'transaction'], $transaction), + ]); + + $event = (new EnvelopeMapper($store))->map($frame); + + Assert::same($event?->payload, $transaction); + Assert::same($store->traces(), []); + } + + public function testEventWinsTheFeedOverATransactionWithoutTraceId(): void + { + $store = new TelemetryStore(); + $frame = new SentryEnvelope([], [ + new EnvelopeItem(['type' => 'transaction'], ['transaction' => 'GET /', 'spans' => []]), + new EnvelopeItem(['type' => 'event'], ['message' => 'Boom']), + ]); + + $event = (new EnvelopeMapper($store))->map($frame); + + Assert::same($event?->payload, ['message' => 'Boom']); + Assert::same($store->traces(), []); + } + + public function testSpanOnlyEnvelopeMakesNoEvent(): void + { + $store = new TelemetryStore(); + $frame = new SentryEnvelope([], [new EnvelopeItem(['type' => 'span'], [ + 'trace_id' => self::TRACE, + 'span_id' => 'aaaaaaaaaaaaaaaa', + 'name' => 'GET /', + 'is_segment' => true, + 'start_timestamp' => 1, + 'end_timestamp' => 2, + ])]); + + Assert::null((new EnvelopeMapper($store))->map($frame)); + Assert::notBlank($store->trace(self::TRACE)); } - public function testEventItemWinsTheFeedOverAnEarlierTransaction(): void + public function testErrorWithTransactionMakesTheErrorEventAndATrace(): void { + $store = new TelemetryStore(); $frame = new SentryEnvelope([], [ new EnvelopeItem(['type' => 'transaction'], ['contexts' => ['trace' => ['trace_id' => self::TRACE]], 'spans' => []]), new EnvelopeItem(['type' => 'event'], ['message' => 'Boom']), ]); - $event = (new EnvelopeMapper(new TelemetryStore()))->map($frame); + $event = (new EnvelopeMapper($store))->map($frame); Assert::same($event?->payload, ['message' => 'Boom']); + Assert::count($store->trace(self::TRACE)?->transactions ?? [], 1); + } + + public function testFeedbackMakesTheFeedEvent(): void + { + $frame = new SentryEnvelope([], [ + new EnvelopeItem(['type' => 'session'], ['sid' => 'x']), + new EnvelopeItem(['type' => 'feedback'], ['contexts' => ['feedback' => ['message' => 'Nice']]]), + ]); + + $event = (new EnvelopeMapper(new TelemetryStore()))->map($frame); + + Assert::same($event?->payload, ['contexts' => ['feedback' => ['message' => 'Nice']]]); } public function testTelemetryOnlyEnvelopeMakesNoEvent(): void @@ -91,7 +150,7 @@ public function testUnknownItemTypeStillMakesAnEvent(): void Assert::same($event?->payload, ['a' => 1]); } - public function testStoreEndpointTransactionGoesToTheStoreToo(): void + public function testStoreEndpointTransactionGoesToTheStoreOnly(): void { $store = new TelemetryStore(); $payload = [ @@ -103,16 +162,42 @@ public function testStoreEndpointTransactionGoesToTheStoreToo(): void $event = (new StoreMapper($store))->map(new SentryStore($payload, project: 'shop')); - Assert::same($event->projectKey(), 'shop'); + Assert::null($event); Assert::same($store->trace(self::TRACE)?->transactions['x1']->project, 'shop'); } - public function testStoreEndpointErrorStaysOutOfTheStore(): void + public function testStoreEndpointTransactionWithoutTraceIdStaysInTheFeed(): void + { + $store = new TelemetryStore(); + + $event = (new StoreMapper($store))->map(new SentryStore(['type' => 'transaction', 'transaction' => 'GET /'])); + + Assert::same($event?->payload, ['type' => 'transaction', 'transaction' => 'GET /']); + Assert::same($store->traces(), []); + } + + public function testStoreEndpointTransactionWithExceptionIsAnError(): void + { + $store = new TelemetryStore(); + $payload = [ + 'type' => 'transaction', + 'exception' => ['values' => [['type' => 'RuntimeException', 'value' => 'Boom']]], + 'contexts' => ['trace' => ['trace_id' => self::TRACE]], + ]; + + $event = (new StoreMapper($store))->map(new SentryStore($payload)); + + Assert::same($event?->payload, $payload); + Assert::same($store->traces(), []); + } + + public function testStoreEndpointErrorMakesAnEventAndStaysOutOfTheStore(): void { $store = new TelemetryStore(); - (new StoreMapper($store))->map(new SentryStore(['event_id' => 'x1', 'message' => 'Boom'])); + $event = (new StoreMapper($store))->map(new SentryStore(['event_id' => 'x1', 'message' => 'Boom'], project: 'shop')); + Assert::same($event?->projectKey(), 'shop'); Assert::same($store->traces(), []); } } diff --git a/tests/Unit/Module/Sentry/Mcp/SentryViewTest.php b/tests/Unit/Module/Sentry/Mcp/SentryViewTest.php index b18c7856..d7a9dd55 100644 --- a/tests/Unit/Module/Sentry/Mcp/SentryViewTest.php +++ b/tests/Unit/Module/Sentry/Mcp/SentryViewTest.php @@ -70,25 +70,39 @@ public function testShortStoreEventOfTheTestCommand(): void } #[RunInFiber] - public function testEnvelopeOfTheStub(): void + public function testPayloadOfTheStub(): void { $envelope = EnvelopeParser::parse(Stream::create((string) \file_get_contents(Info::TRAP_ROOT . '/tests/Stub/sentry-body.bin'))); - $trap = new Trap(); - $record = $trap->add($envelope); + $payload = $envelope->items[0]->payload; + \assert(\is_array($payload)); - $text = (string) $trap->get(SentryView::class)->text($record); + $text = (string) (new SentryView())->text(new Record(self::event($payload), 1, [])); Assert::string($text) - ->startsWith("Event ID: 1c375fcd2f15438f82d8762f083cd8c0\nType: transaction\nTransaction: CallAction\nDuration: 4065.4 ms\n") + ->startsWith("Event ID: 1c375fcd2f15438f82d8762f083cd8c0\nTransaction: CallAction\nDuration: 4065.4 ms\n") ->contains("Request: POST http://127.0.0.1:8000/\n Headers:\n host: 127.0.0.1:8000\n") ->contains(" Data: {\"action\":\"sentry:report\"}\n") ->contains("Breadcrumbs:\n 14:02:47.525 info navigation route: CallAction\n 14:02:51.580 error default log.error: Something went wrong\n") - ->contains("Spans (2):\n app.bootstrap (7.9 ms)\n") + ->notContains('Spans') ->notContains('cookie') ->notContains('sec-fetch') ->notContains('Item 1'); } + #[RunInFiber] + public function testTransactionItemPointsToTheTraceTools(): void + { + $envelope = EnvelopeParser::parse(Stream::create((string) \file_get_contents(Info::TRAP_ROOT . '/tests/Stub/sentry-body.bin'))); + + $text = (string) (new SentryView())->text(new Record(self::event([]), 1, [$envelope])); + + Assert::same( + $text, + "Transaction: CallAction, 4065.4 ms, 3 spans\n" + . "Read it as trace 93c66872a715428ba1934889bf60dc07 with `get_trace`.\n", + ); + } + public function testChainFromTheThrownExceptionToTheRootCause(): void { $text = self::text(['exception' => ['values' => [ @@ -386,13 +400,11 @@ public function testDurationOfTimestamps(mixed $start, mixed $end): void 'type' => 'transaction', 'start_timestamp' => $start, 'timestamp' => $end, - 'spans' => [['op' => 'db', 'start_timestamp' => $start, 'timestamp' => $end]], 'breadcrumbs' => [['timestamp' => $start, 'message' => 'begin']], ]); Assert::string($text) ->contains("Duration: 500.0 ms\n") - ->contains(" db (500.0 ms)\n") ->contains(" 10:00:00.123 begin\n"); } @@ -700,13 +712,11 @@ public function testValuesThatAreNotTimesAreLeftOut(mixed $time): void 'type' => 'transaction', 'start_timestamp' => 1_704_103_200.0, 'timestamp' => $time, - 'spans' => [['op' => 'db', 'start_timestamp' => $time, 'timestamp' => 1_704_103_200.0]], 'breadcrumbs' => [['timestamp' => $time, 'message' => 'begin']], ]); Assert::string($text) ->notContains('Duration:') - ->contains(" db\n") ->contains("Breadcrumbs:\n begin\n"); } @@ -745,6 +755,29 @@ public function testTypeOfEveryEventItem(): void ->contains("--- Item 2 of 2: feedback ---\nType: feedback\n"); } + public function testTransactionOfAnErrorEnvelopeIsALineOfItsTrace(): void + { + $items = [ + new EnvelopeItem(['type' => 'event'], ['message' => 'Boom']), + new EnvelopeItem(['type' => 'transaction'], [ + 'transaction' => 'GET /', + 'spans' => [['span_id' => 's1', 'trace_id' => 'abc'], ['op' => 'without an ID']], + ]), + // Spans in a map, not a list, are not read: no trace ID, so an event. + new EnvelopeItem(['type' => 'transaction'], [ + 'transaction' => 'POST /', + 'spans' => ['a' => ['span_id' => 's1', 'trace_id' => 'def']], + ]), + ]; + + $text = (string) (new SentryView())->text(new Record(self::event([]), 1, [new SentryEnvelope([], $items)])); + + Assert::string($text) + ->contains("--- Item 2 of 3: transaction ---\nTransaction: GET /, 2 spans\nRead it as trace abc with `get_trace`.\n") + ->contains("--- Item 3 of 3: transaction ---\nType: transaction\nTransaction: POST /\n") + ->notContains('def'); + } + public function testEmptyBreadcrumbsAndMechanismAreLeftOut(): void { $text = self::text([ @@ -923,12 +956,12 @@ public function testDurationTooLongForAFloatIsLeftOut(): void 'type' => 'transaction', 'start_timestamp' => -1e308, 'timestamp' => 1e308, - 'spans' => [['op' => 'db', 'start_timestamp' => -1e308, 'timestamp' => 1e308]], + 'message' => 'done', ]); Assert::string($text) ->notContains('Duration:') - ->contains(" db\n"); + ->contains("Message: done\n"); } #[DataSet(['=?'], 'queries')] diff --git a/tests/Unit/Module/Sentry/Telemetry/ItemReaderTest.php b/tests/Unit/Module/Sentry/Telemetry/ItemReaderTest.php index ccca8b57..5aa70a47 100644 --- a/tests/Unit/Module/Sentry/Telemetry/ItemReaderTest.php +++ b/tests/Unit/Module/Sentry/Telemetry/ItemReaderTest.php @@ -76,7 +76,7 @@ public function testSkipsTransactionWithoutTraceId(): void { $batch = new Batch('default'); - Assert::true(ItemReader::read($batch, 'transaction', ['transaction' => 'x', 'spans' => []])); + Assert::false(ItemReader::read($batch, 'transaction', ['transaction' => 'x', 'spans' => []]), 'Not taken as telemetry: the feed keeps it.'); Assert::same($batch->transactions, []); } @@ -214,6 +214,10 @@ public function testTellsTransactionFromError(): void 'exception' => [['type' => 'E']], ])); Assert::false(ItemReader::isTransaction(['message' => 'x'])); + Assert::false( + ItemReader::isTransaction(['type' => 'transaction', 'exception' => ['values' => [['type' => 'E']]]]), + 'An exception makes an error of any type.', + ); } public function testReadsTimes(): void diff --git a/tests/Unit/Module/Tracing/Config/TracesTest.php b/tests/Unit/Module/Tracing/Config/TracesTest.php index e4902566..26eb62ee 100644 --- a/tests/Unit/Module/Tracing/Config/TracesTest.php +++ b/tests/Unit/Module/Tracing/Config/TracesTest.php @@ -6,9 +6,9 @@ use Buggregator\Trap\Module\Tracing\Config\Traces; use Buggregator\Trap\Module\Tracing\Console\Renderer; +use Buggregator\Trap\Module\Tracing\Console\SpanBuffer; use Buggregator\Trap\Module\Tracing\Frame\Trace\Span; use Buggregator\Trap\Module\Tracing\Frame\Trace\SpanKind; -use Buggregator\Trap\Module\Tracing\SpanStore; use Buggregator\Trap\Server\Bootstrap; use Buggregator\Trap\Server\Info; use Internal\Container\Container; @@ -18,7 +18,7 @@ use Testo\Test; #[Covers(Traces::class)] -#[Covers(SpanStore::class)] +#[Covers(SpanBuffer::class)] #[Test] final class TracesTest { @@ -68,9 +68,9 @@ public function testEnvOverridesXml(): void Assert::same($config->ttl, 30.0); } - public function testSpanStoreFromContainerUsesEnvLimits(): void + public function testSpanBufferFromContainerUsesEnvLimits(): void { - $store = $this->container(['TRAP_TRACES_MAX_SPANS' => '2'])->get(SpanStore::class); + $store = $this->container(['TRAP_TRACES_MAX_SPANS' => '2'])->get(SpanBuffer::class); $store->add(self::span('a')); $store->add(self::span('b')); @@ -84,7 +84,7 @@ public function testRendererFromContainerUsesEnvLimits(): void { $renderer = $this->container(['TRAP_TRACES_MAX_SPANS' => '2'])->make(Renderer::class); $store = (new \ReflectionProperty(Renderer::class, 'store'))->getValue($renderer); - \assert($store instanceof SpanStore); + \assert($store instanceof SpanBuffer); $store->add(self::span('a'), self::span('b'), self::span('c')); @@ -92,10 +92,10 @@ public function testRendererFromContainerUsesEnvLimits(): void } #[DataProvider('provideInvalidEnvValues')] - public function testSpanStoreIgnoresInvalidEnvLimits(string $maxSpans, string $ttl): void + public function testSpanBufferIgnoresInvalidEnvLimits(string $maxSpans, string $ttl): void { $store = $this->container(['TRAP_TRACES_MAX_SPANS' => $maxSpans, 'TRAP_TRACES_TTL' => $ttl]) - ->get(SpanStore::class); + ->get(SpanBuffer::class); foreach (['a', 'b', 'c', 'd'] as $trace) { $store->add(self::span($trace)); diff --git a/tests/Unit/Module/Tracing/Console/RendererSnapshotTest.php b/tests/Unit/Module/Tracing/Console/RendererSnapshotTest.php index 33400647..29aaf967 100644 --- a/tests/Unit/Module/Tracing/Console/RendererSnapshotTest.php +++ b/tests/Unit/Module/Tracing/Console/RendererSnapshotTest.php @@ -6,12 +6,12 @@ use Buggregator\Trap\Module\Tracing\Config\Traces; use Buggregator\Trap\Module\Tracing\Console\Renderer; +use Buggregator\Trap\Module\Tracing\Console\SpanBuffer; use Buggregator\Trap\Module\Tracing\Frame\OtlpTraces as OtlpTracesFrame; use Buggregator\Trap\Module\Tracing\Frame\Trace\ResourceSpans; use Buggregator\Trap\Module\Tracing\Frame\Trace\ScopeSpans; use Buggregator\Trap\Module\Tracing\Frame\Trace\Span; use Buggregator\Trap\Module\Tracing\Frame\Trace\SpanKind; -use Buggregator\Trap\Module\Tracing\SpanStore; use Buggregator\Trap\Server\Info; use Symfony\Component\Console\Output\BufferedOutput; use Testo\Assert; @@ -26,7 +26,7 @@ * Set `TRAP_UPDATE_SNAPSHOTS=1` to write the snapshots from the current renderer. */ #[Covers(Renderer::class)] -#[Covers(SpanStore::class)] +#[Covers(SpanBuffer::class)] #[Test] final class RendererSnapshotTest { diff --git a/tests/Unit/Module/Tracing/SpanStoreTest.php b/tests/Unit/Module/Tracing/Console/SpanBufferTest.php similarity index 65% rename from tests/Unit/Module/Tracing/SpanStoreTest.php rename to tests/Unit/Module/Tracing/Console/SpanBufferTest.php index aacc668c..209cd30c 100644 --- a/tests/Unit/Module/Tracing/SpanStoreTest.php +++ b/tests/Unit/Module/Tracing/Console/SpanBufferTest.php @@ -2,26 +2,20 @@ declare(strict_types=1); -namespace Buggregator\Trap\Tests\Unit\Module\Tracing; +namespace Buggregator\Trap\Tests\Unit\Module\Tracing\Console; use Buggregator\Trap\Module\Tracing\Config\Traces; -use Buggregator\Trap\Module\Tracing\Frame\OtlpTraces; -use Buggregator\Trap\Module\Tracing\Frame\Trace\ResourceSpans; -use Buggregator\Trap\Module\Tracing\Frame\Trace\ScopeSpans; +use Buggregator\Trap\Module\Tracing\Console\SpanBuffer; use Buggregator\Trap\Module\Tracing\Frame\Trace\Span; use Buggregator\Trap\Module\Tracing\Frame\Trace\SpanKind; -use Buggregator\Trap\Module\Tracing\Frame\Trace\SpanStatus; -use Buggregator\Trap\Module\Tracing\Frame\Trace\StatusCode; -use Buggregator\Trap\Module\Tracing\SpanStore; -use Buggregator\Trap\Module\Tracing\TraceSummary; use Testo\Assert; use Testo\Codecov\Covers; use Testo\Lifecycle\BeforeTest; use Testo\Test; -#[Covers(SpanStore::class)] +#[Covers(SpanBuffer::class)] #[Test] -final class SpanStoreTest +final class SpanBufferTest { private float $now = 1000.0; @@ -201,7 +195,7 @@ public function testResentSpanCoveringItsOldTimeKeepsCachedBounds(): void { $store = $this->store(); $traceId = self::traceId('a'); - $cached = static fn(): mixed => (new \ReflectionProperty(SpanStore::class, 'bounds'))->getValue($store)[$traceId]; + $cached = static fn(): mixed => (new \ReflectionProperty(SpanBuffer::class, 'bounds'))->getValue($store)[$traceId]; $store->add(self::timedSpan('a', 1, null, 0, 100), self::timedSpan('a', 2, 1, 10, 20)); $store->add(self::timedSpan('a', 1, null, 0, 120)); @@ -253,164 +247,6 @@ public function testIndexMatchesStoredSpans(): void \mt_srand(); } - public function testEveryStoredSpanTakesNextSequenceNumber(): void - { - $store = $this->store(); - - $store->add(self::span('a', '1'), self::span('b', '2'), self::span('a', '3')); - $store->receive(self::frame('app', self::span('c', '4'), self::span('b', '5', '2'))); - - Assert::same($store->cursor(), 5); - Assert::same( - \array_map(static fn(TraceSummary $trace): int => $trace->seq, \iterator_to_array($store->traces(), false)), - [3, 4, 5], - ); - } - - public function testAddedSpansHaveNoService(): void - { - $store = $this->store(); - $store->receive(self::frame('app', self::span('a', '1'))); - - $store->add(self::span('a', '1'), self::span('b', '2')); - - Assert::null($store->summary(self::traceId('a'))?->service, 'The span sent again replaces its service too.'); - Assert::null($store->summary(self::traceId('b'))?->service); - Assert::same($store->summary(self::traceId('b'))?->name, 'span-2'); - } - - public function testListsTracesFromLeastRecentlyUpdated(): void - { - $store = $this->store(); - $store->add(self::span('a', '1')); - $store->add(self::span('b', '2')); - $store->add(self::span('c', '3')); - $store->add(self::span('a', '4')); - - $all = \iterator_to_array($store->traces(), false); - $since = \iterator_to_array($store->traces(2), false); - - Assert::same( - \array_map(static fn(TraceSummary $trace): string => $trace->traceId, $all), - [self::traceId('b'), self::traceId('c'), self::traceId('a')], - ); - Assert::same(\array_map(static fn(TraceSummary $trace): int => $trace->seq, $all), [2, 3, 4]); - Assert::same( - \array_map(static fn(TraceSummary $trace): string => $trace->traceId, $since), - [self::traceId('c'), self::traceId('a')], - ); - Assert::same(\iterator_to_array($store->traces(4), false), []); - } - - public function testListingDropsExpiredTraces(): void - { - $store = $this->store(ttl: 10.0); - $store->add(self::span('a', '1')); - $this->now += 5; - $store->add(self::span('b', '2')); - $this->now += 6; - - $traces = \iterator_to_array($store->traces(), false); - - Assert::count($traces, 1); - Assert::same($traces[0]->traceId, self::traceId('b')); - } - - public function testSummaryOfExpiredTraceIsNull(): void - { - $store = $this->store(ttl: 10.0); - $store->add(self::span('a', '1')); - $this->now += 11; - - Assert::null($store->summary(self::traceId('a'))); - Assert::same($store->getTrace(self::traceId('a')), []); - } - - public function testSummarizesTrace(): void - { - $store = $this->store(); - $store->receive(self::frame('db', self::timedSpan('a', 2, 1, 20, 30))); - $store->receive(self::frame('web', self::timedSpan('a', 1, null, 10, 50))); - $this->now += 2; - $store->receive(self::frame(null, new Span( - traceId: self::traceId('a'), - spanId: \sprintf('%016x', 3), - parentSpanId: \sprintf('%016x', 1), - name: 'failed', - kind: SpanKind::Client, - startTimeUnixNano: 40, - endTimeUnixNano: 60, - status: new SpanStatus(StatusCode::Error), - ))); - - $summary = $store->summary(self::traceId('a')); - - Assert::equals($summary, new TraceSummary( - traceId: self::traceId('a'), - name: 'span-1', - service: 'web', - spans: 3, - start: 10, - end: 60, - error: true, - updatedAt: 1002.0, - seq: 3, - )); - Assert::null($store->summary(self::traceId('b'))); - } - - public function testRootWithoutParentWinsOverEarlierOrphan(): void - { - $store = $this->store(); - $store->receive(self::frame('worker', self::timedSpan('a', 5, 9, 0, 10))); - $store->receive(self::frame(null, self::timedSpan('a', 1, null, 5, 10))); - - $summary = $store->summary(self::traceId('a')); - - Assert::same($summary?->name, 'span-1'); - Assert::same($summary?->service, 'worker', 'The root has no service: any span gives it.'); - Assert::false($summary?->error); - } - - public function testRootOfTraceWithoutRootSpan(): void - { - $store = $this->store(); - $store->add(self::timedSpan('a', 3, 9, 30, 40), self::timedSpan('a', 2, 8, 20, 40), self::timedSpan('a', 4, 2, 25, 30)); - $store->add(self::timedSpan('b', 1, 2, 0, 1), self::timedSpan('b', 2, 1, 0, 1), self::timedSpan('b', 7, 7, 0, 1)); - - Assert::same($store->summary(self::traceId('a'))?->name, 'span-2', 'The earliest span whose parent is missing.'); - Assert::null($store->summary(self::traceId('b'))?->name, 'A parent cycle and a self parent have no root.'); - Assert::null($store->summary(self::traceId('b'))?->service); - } - - public function testEvictedTraceLeavesNothing(): void - { - $store = $this->store(maxSpans: 2); - $store->receive(self::frame('app', self::span('a', '1'))); - $store->receive(self::frame('app', self::span('b', '2'), self::span('b', '3'))); - - Assert::same( - \array_map(static fn(TraceSummary $trace): string => $trace->traceId, \iterator_to_array($store->traces(), false)), - [self::traceId('b')], - ); - foreach (['services', 'changedAt'] as $property) { - Assert::same(\array_keys((new \ReflectionProperty(SpanStore::class, $property))->getValue($store)), [self::traceId('b')], $property); - } - } - - public function testStoresWithDifferentIds(): void - { - Assert::notSame($this->store()->id, $this->store()->id); - } - - private static function frame(?string $service, Span ...$spans): OtlpTraces - { - return new OtlpTraces([new ResourceSpans( - [new ScopeSpans(\array_values($spans))], - $service === null ? [] : ['service.name' => $service], - )]); - } - /** * @param array $spans * @return list @@ -466,7 +302,7 @@ private static function spanId(string $char): string * @param list $traces Trace ID chars. * @param int<1, max> $maxId Span IDs to look up children for: 1..$maxId. */ - private function assertIndexMatches(SpanStore $store, array $traces, int $maxId, string $case): void + private function assertIndexMatches(SpanBuffer $store, array $traces, int $maxId, string $case): void { $stored = []; foreach ($traces as $char) { @@ -501,8 +337,8 @@ private function assertIndexMatches(SpanStore $store, array $traces, int $maxId, } // Nothing is left in the index for dropped traces and spans, and no list stays empty. - $children = (new \ReflectionProperty(SpanStore::class, 'children'))->getValue($store); - $bounds = (new \ReflectionProperty(SpanStore::class, 'bounds'))->getValue($store); + $children = (new \ReflectionProperty(SpanBuffer::class, 'children'))->getValue($store); + $bounds = (new \ReflectionProperty(SpanBuffer::class, 'bounds'))->getValue($store); Assert::same(\array_diff_key($children, $stored), [], $case); Assert::same(\array_diff_key($bounds, $stored), [], $case); foreach ($children as $traceId => $parents) { @@ -515,12 +351,12 @@ private function assertIndexMatches(SpanStore $store, array $traces, int $maxId, } } - private function store(int $maxSpans = 100, float $ttl = 600.0): SpanStore + private function store(int $maxSpans = 100, float $ttl = 600.0): SpanBuffer { $config = new Traces(); $config->maxSpans = $maxSpans; $config->ttl = $ttl; - return new SpanStore($config, fn(): float => $this->now); + return new SpanBuffer($config, fn(): float => $this->now); } } diff --git a/tests/Unit/Module/Tracing/Console/TraceTreeTest.php b/tests/Unit/Module/Tracing/Console/TraceTreeTest.php index ddcf4826..730ad6c1 100644 --- a/tests/Unit/Module/Tracing/Console/TraceTreeTest.php +++ b/tests/Unit/Module/Tracing/Console/TraceTreeTest.php @@ -5,11 +5,11 @@ namespace Buggregator\Trap\Tests\Unit\Module\Tracing\Console; use Buggregator\Trap\Module\Tracing\Console\Renderer; +use Buggregator\Trap\Module\Tracing\Console\SpanBuffer; use Buggregator\Trap\Module\Tracing\Console\TraceTree; use Buggregator\Trap\Module\Tracing\Frame\Trace\Span; use Buggregator\Trap\Module\Tracing\Frame\Trace\SpanKind; use Buggregator\Trap\Module\Tracing\Http\OtlpTrap\JsonTracesDecoder; -use Buggregator\Trap\Module\Tracing\SpanStore; use Buggregator\Trap\Server\Info; use Symfony\Component\Console\Output\BufferedOutput; use Symfony\Component\Console\Output\OutputInterface; @@ -29,8 +29,10 @@ public function testStoredTraceIsTheTreeTheConsolePrints(): void (string) \file_get_contents(Info::TRAP_ROOT . '/tests/Stub/otlp-traces.json'), new \DateTimeImmutable('2024-01-01 12:00:00'), ); - $store = new SpanStore(); - $store->receive($frame); + $store = new SpanBuffer(); + foreach ($frame->iterateSpans() as [, , $span]) { + $store->add($span); + } $console = new BufferedOutput(OutputInterface::VERBOSITY_NORMAL, true); (new Renderer())->render($console, $frame); $console = $console->fetch(); @@ -46,7 +48,7 @@ public function testStoredTraceIsTheTreeTheConsolePrints(): void public function testStoredTraceShowsEverySpanInFull(): void { - $store = new SpanStore(); + $store = new SpanBuffer(); $leaves = \array_map(static fn(int $i): Span => self::span(100 + $i, 2), \range(0, 29)); $store->add(...$leaves); $store->add(self::span(2, 1), self::span(1, null)); @@ -62,13 +64,13 @@ public function testUnknownTraceRendersNothing(): void { $output = new BufferedOutput(); - $found = (new TraceTree(new SpanStore()))->renderStored($output, self::TRACE); + $found = (new TraceTree(new SpanBuffer()))->renderStored($output, self::TRACE); Assert::false($found); Assert::same($output->fetch(), ''); } - private static function plain(SpanStore $store, string $traceId): string + private static function plain(SpanBuffer $store, string $traceId): string { $output = new BufferedOutput(OutputInterface::VERBOSITY_NORMAL, false); Assert::true((new TraceTree($store))->renderStored($output, $traceId)); diff --git a/tests/Unit/Module/Tracing/Http/OtlpTrapTest.php b/tests/Unit/Module/Tracing/Http/OtlpTrapTest.php index 503793d4..3f79bbd6 100644 --- a/tests/Unit/Module/Tracing/Http/OtlpTrapTest.php +++ b/tests/Unit/Module/Tracing/Http/OtlpTrapTest.php @@ -6,8 +6,6 @@ use Buggregator\Trap\Module\HttpDump\Frame as HttpFrame; use Buggregator\Trap\Module\HttpDump\Http\Dump; -use Buggregator\Trap\Module\Mcp\McpStatus; -use Buggregator\Trap\Module\Mcp\Sender\McpSender; use Buggregator\Trap\Module\Tracing\Frame as TracingFrame; use Buggregator\Trap\Module\Tracing\Frame\OtlpLogs; use Buggregator\Trap\Module\Tracing\Frame\OtlpMetrics; @@ -16,13 +14,10 @@ use Buggregator\Trap\Module\Tracing\Http\OtlpTrap\JsonTracesDecoder; use Buggregator\Trap\Module\Tracing\Http\OtlpTrap\ProtobufTracesDecoder; use Buggregator\Trap\Module\Tracing\Http\OtlpTrap\TracesDecoder; -use Buggregator\Trap\Module\Tracing\SpanStore; -use Buggregator\Trap\Server\Application\Module\Modules; use Buggregator\Trap\Server\Handler\Http\Handler\MiddlewareHandler; use Buggregator\Trap\Server\Info; use Buggregator\Trap\Server\Logger; use Buggregator\Trap\Server\Traffic\StreamClient; -use Internal\Container\ObjectContainer; use Nyholm\Psr7\Response; use Nyholm\Psr7\ServerRequest; use Nyholm\Psr7\Stream; @@ -282,61 +277,6 @@ public function testAcceptsFixtureFromOpenTelemetryPhpExporter(): void Assert::same($frames[0]->countSpans(), 4); } - public function testStoresSpansBeforePassingTheFrame(): void - { - $store = new SpanStore(); - $middleware = new OtlpTrap(spans: $store, mcp: self::mcpOn()); - $request = $this->request(body: \file_get_contents(Info::TRAP_ROOT . '/tests/Stub/otlp-traces.json')); - $fiber = new \Fiber(static fn(): ResponseInterface => $middleware->handle( - $request, - static fn(): ResponseInterface => new Response(500), - )); - - $frame = $fiber->start(); - - Assert::instanceOf($frame, OtlpTraces::class); - Assert::same($store->countSpans(), 4); - Assert::same($store->summary('382bfca057473920912cab0a4ed95abe')?->service, 'e2e-app'); - } - - public function testStoresNoSpansWithoutMcpServer(): void - { - $store = new SpanStore(); - - [, $frames] = $this->handleInFiber($this->request(body: self::PAYLOAD), new OtlpTrap(spans: $store)); - - Assert::count($frames, 1); - Assert::same($store->cursor(), 0); - } - - /** - * The container gives the middleware the status the MCP sender turns on, whichever is created first. - */ - public function testContainerMiddlewareStoresSpansOnceMcpSenderIsCreated(): void - { - $container = new ObjectContainer(); - $container->set(new Modules($container)); - $middleware = $container->get(OtlpTrap::class); - $store = $container->get(SpanStore::class); - - $this->handleInFiber($this->request(body: self::PAYLOAD), $middleware); - $before = $store->countSpans(); - $container->get(McpSender::class); - $this->handleInFiber($this->request(body: self::PAYLOAD), $middleware); - - Assert::same($before, 0); - Assert::same($store->countSpans(), 1); - } - - public function testRejectedRequestStoresNothing(): void - { - $store = new SpanStore(); - - $this->handleInFiber($this->request(body: '{"resourceSpans": ['), new OtlpTrap(spans: $store, mcp: self::mcpOn())); - - Assert::same($store->cursor(), 0); - } - public function testRejectsMalformedJsonWith400(): void { $request = $this->request(body: '{"resourceSpans": ['); @@ -628,14 +568,6 @@ private static function protobufFixture(): string return \file_get_contents(Info::TRAP_ROOT . '/tests/Stub/otlp-traces.pb'); } - private static function mcpOn(): McpStatus - { - $status = new McpStatus(); - $status->turnOn(); - - return $status; - } - /** * @return array{ResponseInterface, list} */ diff --git a/tests/Unit/Module/Tracing/Mcp/GetTraceTest.php b/tests/Unit/Module/Tracing/Mcp/GetTraceTest.php index cf3c25e9..b9aedf3c 100644 --- a/tests/Unit/Module/Tracing/Mcp/GetTraceTest.php +++ b/tests/Unit/Module/Tracing/Mcp/GetTraceTest.php @@ -5,9 +5,13 @@ namespace Buggregator\Trap\Tests\Unit\Module\Tracing\Mcp; use Buggregator\Trap\Module\Mcp\Tools; +use Buggregator\Trap\Module\Sentry\Frame\EnvelopeItem; +use Buggregator\Trap\Module\Sentry\Frame\SentryEnvelope; +use Buggregator\Trap\Module\Sentry\Frontend\EnvelopeMapper; +use Buggregator\Trap\Module\Tracing\Frontend\TelemetryMapper; use Buggregator\Trap\Module\Tracing\Http\OtlpTrap\JsonTracesDecoder; use Buggregator\Trap\Module\Tracing\Mcp\GetTrace; -use Buggregator\Trap\Module\Tracing\SpanStore; +use Buggregator\Trap\Module\Tracing\Mcp\TraceSpans; use Buggregator\Trap\Server\Info; use Buggregator\Trap\Tests\Unit\Module\Mcp\Stub\Trap; use Testo\Assert; @@ -17,9 +21,11 @@ #[Test] #[Covers(GetTrace::class)] +#[Covers(TraceSpans::class)] final class GetTraceTest { private const TRACE = '382bfca057473920912cab0a4ed95abe'; + private const SENTRY_TRACE = '5b8efff798038103d269b633813fc60c'; public function testShowsTraceAsPlainTextTree(): void { @@ -28,11 +34,42 @@ public function testShowsTraceAsPlainTextTree(): void $text = $trap->get(GetTrace::class)->call(['id' => \strtoupper(self::TRACE)]); Assert::string($text)->matchesRegex( - '/^trace ' . self::TRACE . ', 4 spans, service e2e-app, has errors, updated at \d{4}-[^\n]+\n# Trace /', + '/^trace ' . self::TRACE . ', 4 spans, service e2e-app, source otel, project default, has errors, updated at \d{4}-[^\n]+\n# Trace /', ); Assert::string($text)->contains("\nGET /orders SERVER 27.69 ms OK id:286e73f2056fe20e\n")->contains(" └─ template.load INTERNAL 14.46 ms +12.97 ms id:8118bc4ed687fb8d\n template.name: \"orders.twig\"\n")->notContains("\e")->notMatchesRegex('/ $/m'); } + public function testShowsSentryTransactionWithItsSpans(): void + { + $trap = new Trap(); + $trap->get(EnvelopeMapper::class)->map(new SentryEnvelope([], [new EnvelopeItem(['type' => 'transaction'], [ + 'event_id' => 'e1', + 'transaction' => 'POST /checkout', + 'server_name' => 'checkout-api', + 'contexts' => ['trace' => ['trace_id' => self::SENTRY_TRACE, 'span_id' => 'aaaaaaaaaaaaaaaa', 'op' => 'http.server']], + 'start_timestamp' => 1_700_000_000.0, + 'timestamp' => 1_700_000_000.25, + 'spans' => [[ + 'span_id' => 'bbbbbbbbbbbbbbbb', + 'parent_span_id' => 'aaaaaaaaaaaaaaaa', + 'op' => 'http.client', + 'description' => 'POST http://payments/charge', + 'status' => 'internal_error', + 'start_timestamp' => 1_700_000_000.1, + 'timestamp' => 1_700_000_000.2, + 'data' => ['http.response.status_code' => 502], + ]], + ])], project: 'shop')); + + $text = $trap->get(GetTrace::class)->call(['id' => self::SENTRY_TRACE]); + + Assert::string($text) + ->startsWith('trace ' . self::SENTRY_TRACE . ', 2 spans, service checkout-api, source sentry, project shop, has errors, updated at ') + ->contains("\nPOST /checkout SERVER 250.00 ms id:aaaaaaaaaaaaaaaa\n") + ->contains("└─ http.client: POST http://payments/charge CLIENT 100.00 ms ERROR: internal_error +100.00 ms id:bbbbbbbbbbbbbbbb\n") + ->contains(" http.response.status_code: 502\n"); + } + public function testLongTextIsTruncated(): void { $text = self::trap()->get(GetTrace::class)->call(['id' => self::TRACE, 'max_length' => 100]); @@ -71,7 +108,7 @@ public function testIsReadOnlyTextToolOfTheTracingModule(): void private static function trap(): Trap { $trap = new Trap(); - $trap->get(SpanStore::class)->receive((new JsonTracesDecoder())->decode( + $trap->get(TelemetryMapper::class)->map((new JsonTracesDecoder())->decode( (string) \file_get_contents(Info::TRAP_ROOT . '/tests/Stub/otlp-traces.json'), new \DateTimeImmutable(), )); diff --git a/tests/Unit/Module/Tracing/Mcp/ListTracesTest.php b/tests/Unit/Module/Tracing/Mcp/ListTracesTest.php index 32291b22..7b2f2ed5 100644 --- a/tests/Unit/Module/Tracing/Mcp/ListTracesTest.php +++ b/tests/Unit/Module/Tracing/Mcp/ListTracesTest.php @@ -5,6 +5,9 @@ namespace Buggregator\Trap\Tests\Unit\Module\Tracing\Mcp; use Buggregator\Trap\Module\Mcp\Tools; +use Buggregator\Trap\Module\Sentry\Frame\EnvelopeItem; +use Buggregator\Trap\Module\Sentry\Frame\SentryEnvelope; +use Buggregator\Trap\Module\Sentry\Frontend\EnvelopeMapper; use Buggregator\Trap\Module\Tracing\Frame\OtlpTraces; use Buggregator\Trap\Module\Tracing\Frame\Trace\ResourceSpans; use Buggregator\Trap\Module\Tracing\Frame\Trace\ScopeSpans; @@ -13,9 +16,15 @@ use Buggregator\Trap\Module\Tracing\Frame\Trace\SpanKind; use Buggregator\Trap\Module\Tracing\Frame\Trace\SpanStatus; use Buggregator\Trap\Module\Tracing\Frame\Trace\StatusCode; +use Buggregator\Trap\Module\Tracing\Frontend\TelemetryMapper; use Buggregator\Trap\Module\Tracing\Mcp\ListTraces; use Buggregator\Trap\Module\Tracing\Mcp\TraceFilter; -use Buggregator\Trap\Module\Tracing\SpanStore; +use Buggregator\Trap\Module\Tracing\Mcp\TraceSummary; +use Buggregator\Trap\Server\Telemetry\Batch; +use Buggregator\Trap\Server\Telemetry\Source; +use Buggregator\Trap\Server\Telemetry\Span as TelemetrySpan; +use Buggregator\Trap\Server\Telemetry\TelemetryStore; +use Buggregator\Trap\Server\Telemetry\Transaction; use Buggregator\Trap\Tests\Unit\Module\Mcp\Stub\JsonSchema; use Buggregator\Trap\Tests\Unit\Module\Mcp\Stub\Trap; use Testo\Assert; @@ -27,15 +36,19 @@ #[Test] #[Covers(ListTraces::class)] #[Covers(TraceFilter::class)] +#[Covers(TraceSummary::class)] final class ListTracesTest { + /** Unix nanoseconds of the start of the traces: 0 is an unset time in OTLP */ + private const BASE = 1_700_000_000_000_000_000; + public function testListsLeastRecentlyUpdatedFirst(): void { $trap = new Trap(); - $store = $trap->get(SpanStore::class); - $store->receive(self::frame('shop', self::span('a', 1, null, 'GET /cart', 0, 2_500_000))); - $store->receive(self::frame('shop', self::span('b', 2, null, 'GET /orders', 0, 1))); - $store->receive(self::frame('db', self::span('a', 3, 1, 'query', 1_000_000, 4_000_000, StatusCode::Error))); + $store = $trap->get(TelemetryStore::class); + self::receive($trap, self::frame('shop', self::span('a', 1, null, 'GET /cart', 0, 2_500_000))); + self::receive($trap, self::frame('shop', self::span('b', 2, null, 'GET /orders', 0, 1))); + self::receive($trap, self::frame('db', self::span('a', 3, 1, 'query', 1_000_000, 4_000_000, StatusCode::Error))); $result = $trap->get(ListTraces::class)->call([]); @@ -44,6 +57,9 @@ public function testListsLeastRecentlyUpdatedFirst(): void 'id' => self::traceId('a'), 'name' => 'GET /cart', 'service' => 'shop', + 'services' => ['shop', 'db'], + 'sources' => ['otel'], + 'projects' => ['default'], 'spans' => 2, 'duration_ms' => 4.0, 'error' => true, @@ -57,13 +73,13 @@ public function testListsLeastRecentlyUpdatedFirst(): void public function testCursorGivesOnlyUpdatedTraces(): void { $trap = new Trap(); - $store = $trap->get(SpanStore::class); + $store = $trap->get(TelemetryStore::class); $tool = $trap->get(ListTraces::class); - $store->receive(self::frame('app', self::span('a', 1))); - $store->receive(self::frame('app', self::span('b', 2))); + self::receive($trap, self::frame('app', self::span('a', 1))); + self::receive($trap, self::frame('app', self::span('b', 2))); $cursor = $tool->call([])['cursor']; - $store->receive(self::frame('app', self::span('c', 3))); - $store->receive(self::frame('app', self::span('a', 4, 1))); + self::receive($trap, self::frame('app', self::span('c', 3))); + self::receive($trap, self::frame('app', self::span('a', 4, 1))); $result = $tool->call(['since' => $cursor]); @@ -77,7 +93,7 @@ public function testCursorGivesOnlyUpdatedTraces(): void public function testForeignCursorListsEverything(string $since): void { $trap = new Trap(); - $trap->get(SpanStore::class)->receive(self::frame('app', self::span('a', 1))); + self::receive($trap, self::frame('app', self::span('a', 1))); $result = $trap->get(ListTraces::class)->call(['since' => $since]); @@ -87,14 +103,14 @@ public function testForeignCursorListsEverything(string $since): void public function testLimitPagesThroughTraces(): void { $trap = new Trap(); - $store = $trap->get(SpanStore::class); + $store = $trap->get(TelemetryStore::class); $tool = $trap->get(ListTraces::class); foreach (['a', 'b', 'c'] as $i => $char) { - $store->receive(self::frame('app', self::span($char, $i + 1))); + self::receive($trap, self::frame('app', self::span($char, $i + 1))); } $first = $tool->call(['limit' => 2]); - $store->receive(self::frame('app', self::span('a', 4, 1))); + self::receive($trap, self::frame('app', self::span('a', 4, 1))); $second = $tool->call(['limit' => 2, 'since' => $first['cursor']]); Assert::same(self::ids($first), [self::traceId('a'), self::traceId('b')]); @@ -108,10 +124,10 @@ public function testLimitPagesThroughTraces(): void public function testErrorsOnly(): void { $trap = new Trap(); - $store = $trap->get(SpanStore::class); - $store->receive(self::frame('app', self::span('a', 1, status: StatusCode::Error))); - $store->receive(self::frame('app', self::span('b', 2, status: StatusCode::Ok))); - $store->receive(self::frame('app', self::span('c', 3, status: StatusCode::Error))); + $store = $trap->get(TelemetryStore::class); + self::receive($trap, self::frame('app', self::span('a', 1, status: StatusCode::Error))); + self::receive($trap, self::frame('app', self::span('b', 2, status: StatusCode::Ok))); + self::receive($trap, self::frame('app', self::span('c', 3, status: StatusCode::Error))); $result = $trap->get(ListTraces::class)->call(['errors_only' => true, 'limit' => 1]); @@ -136,20 +152,20 @@ public function testErrorsOnly(): void public function testFilters(array $arguments, array $expected): void { $trap = new Trap(); - $store = $trap->get(SpanStore::class); - $store->receive(self::frame('shop', self::span('a', 1, null, 'GET /api/orders', 0, 2_000_000))); - $store->receive(self::frame('db', new Span( + $store = $trap->get(TelemetryStore::class); + self::receive($trap, self::frame('shop', self::span('a', 1, null, 'GET /api/orders', 0, 2_000_000))); + self::receive($trap, self::frame('db', new Span( traceId: self::traceId('b'), spanId: \sprintf('%016x', 2), parentSpanId: null, name: 'GET /api/users', kind: SpanKind::Client, - startTimeUnixNano: 0, - endTimeUnixNano: 1_000_000, + startTimeUnixNano: self::BASE, + endTimeUnixNano: self::BASE + 1_000_000, attributes: ['db.statement' => 'SELECT * FROM users', 'db.rows' => 3], ))); - $store->receive(self::frame('shop', self::span('c', 3, null, 'POST /checkout', 0, 1_000_000))); - $store->receive(self::frame('shop', self::span('c', 4, 3, 'charge card', 0, 3_000_000))); + self::receive($trap, self::frame('shop', self::span('c', 3, null, 'POST /checkout', 0, 1_000_000))); + self::receive($trap, self::frame('shop', self::span('c', 4, 3, 'charge card', 0, 3_000_000))); $result = $trap->get(ListTraces::class)->call($arguments); @@ -164,18 +180,18 @@ public function testFilters(array $arguments, array $expected): void public function testSearchCoversEventsStatusAndResources(string $search, array $expected): void { $trap = new Trap(); - $store = $trap->get(SpanStore::class); - $store->receive(self::frame('shop', new Span( + $store = $trap->get(TelemetryStore::class); + self::receive($trap, self::frame('shop', new Span( traceId: self::traceId('a'), spanId: \sprintf('%016x', 1), parentSpanId: null, name: 'GET /orders', kind: SpanKind::Server, - startTimeUnixNano: 0, - endTimeUnixNano: 1, + startTimeUnixNano: self::BASE, + endTimeUnixNano: self::BASE + 1, events: [new SpanEvent(0, 'exception', ['exception.message' => 'SQLSTATE[HY000] gone away'])], ))); - $store->receive(new OtlpTraces([new ResourceSpans( + self::receive($trap, new OtlpTraces([new ResourceSpans( [new ScopeSpans([self::span('b', 2, status: StatusCode::Error, message: 'card declined')])], ['service.name' => 'billing', 'cloud.region' => 'eu-west-1'], )])); @@ -190,14 +206,14 @@ public function testSearchCoversEventsStatusAndResources(string $search, array $ public function testSearchCoversStructuredAttributes(array $arguments): void { $trap = new Trap(); - $trap->get(SpanStore::class)->receive(self::frame('app', new Span( + self::receive($trap, self::frame('app', new Span( traceId: self::traceId('a'), spanId: \sprintf('%016x', 1), parentSpanId: null, name: 'GET /', kind: SpanKind::Server, - startTimeUnixNano: 0, - endTimeUnixNano: 1, + startTimeUnixNano: self::BASE, + endTimeUnixNano: self::BASE + 1, attributes: ['tags' => ['web', 'eu'], 'ratio' => [\NAN]], ))); @@ -209,7 +225,7 @@ public function testSearchCoversStructuredAttributes(array $arguments): void public function testListedUpdateTimeTakesItsTraceBack(): void { $trap = new Trap(); - $trap->get(SpanStore::class)->receive(self::frame('app', self::span('a', 1))); + self::receive($trap, self::frame('app', self::span('a', 1))); $tool = $trap->get(ListTraces::class); $updated = $tool->call([])['traces'][0]['updated']; @@ -224,16 +240,101 @@ public function testListedUpdateTimeTakesItsTraceBack(): void public function testResultConformsToOutputSchema(array $arguments): void { $trap = new Trap(); - $store = $trap->get(SpanStore::class); + $store = $trap->get(TelemetryStore::class); $tool = $trap->get(ListTraces::class); - $store->receive(self::frame(null, self::span('a', 1, 9))); - $store->receive(self::frame('app', self::span('b', 2))); + self::receive($trap, self::frame(null, self::span('a', 1, 9))); + self::receive($trap, self::frame('app', self::span('b', 2))); $result = $tool->call($arguments); Assert::same(JsonSchema::errors($result, $tool->outputSchema()), []); } + public function testListsSentryTracesWithOpenTelemetryOnes(): void + { + $trap = new Trap(); + self::receive($trap, self::frame('gateway', self::span('a', 1, null, 'GET /orders', 0, 2_000_000))); + self::sentry($trap, 'b', 'shop'); + + $result = $trap->get(ListTraces::class)->call([]); + + Assert::same(self::ids($result), [self::traceId('a'), self::traceId('b')]); + Assert::same(\array_diff_key($result['traces'][1], ['updated' => true]), [ + 'id' => self::traceId('b'), + 'name' => 'POST /checkout', + 'service' => 'checkout-api', + 'services' => ['checkout-api'], + 'sources' => ['sentry'], + 'projects' => ['shop'], + 'spans' => 3, + 'duration_ms' => 250.0, + 'error' => true, + ]); + } + + #[DataSet([['source' => 'sentry'], ['b', 'c']], 'Sentry')] + #[DataSet([['source' => 'otel'], ['a']], 'OpenTelemetry')] + #[DataSet([['project' => 'shop'], ['b']], 'project')] + #[DataSet([['project' => ['', 'billing']], ['a', 'c']], 'projects, the default one by an empty name')] + #[DataSet([['project' => 'none'], []], 'unknown project')] + #[DataSet([['service' => 'checkout-*'], ['b', 'c']], 'service of Sentry')] + #[DataSet([['search' => 'db.query: SELECT'], ['b', 'c']], 'op and description of a Sentry span')] + #[DataSet([['errors_only' => true, 'project' => 'shop'], ['b']], 'Sentry failure')] + public function testFiltersSentryAndOpenTelemetryTraces(array $arguments, array $expected): void + { + $trap = new Trap(); + self::receive($trap, self::frame('gateway', self::span('a', 1, null, 'GET /orders', 0, 2_000_000))); + self::sentry($trap, 'b', 'shop'); + self::sentry($trap, 'c', 'billing'); + + $result = $trap->get(ListTraces::class)->call($arguments); + + Assert::same(self::ids($result), \array_map(self::traceId(...), $expected)); + } + + public function testAnyServiceTakesTraceWithoutService(): void + { + $trap = new Trap(); + self::receive($trap, self::frame(null, self::span('a', 1))); + + $result = $trap->get(ListTraces::class)->call(['service' => '*']); + + Assert::same(self::ids($result), [self::traceId('a')]); + Assert::null($result['traces'][0]['service']); + } + + public function testRootWithEmptyServiceTakesTheServiceOfAnotherPart(): void + { + $trap = new Trap(); + $batch = new Batch('default'); + $batch->transactions[] = new Transaction('t1', 'default', self::traceId('a'), 's0', null, 'GET /', 'http.server', 'ok', 1.0, 2.0, Source::Sentry, ''); + $batch->spans[] = new TelemetrySpan('default', self::traceId('a'), 's1', 's0', 't1', 'db', 'SELECT 1', 'ok', 1.0, 1.5, Source::Sentry, 'db-api'); + $trap->get(TelemetryStore::class)->add($batch); + + $trace = $trap->get(ListTraces::class)->call([])['traces'][0]; + + Assert::same([$trace['name'], $trace['service'], $trace['services']], ['GET /', 'db-api', ['db-api']]); + } + + public function testProjectScopesTheSummary(): void + { + $trap = new Trap(); + self::receive($trap, self::frame('gateway', self::span('a', 1, null, 'GET /orders', 0, 2_000_000))); + $trap->get(TelemetryMapper::class)->map((new OtlpTraces([new ResourceSpans( + [new ScopeSpans([self::span('a', 2, 1, 'charge', 0, 5_000_000)])], + ['service.name' => 'billing'], + )]))->withProject('billing')); + + $all = $trap->get(ListTraces::class)->call([])['traces'][0]; + $billing = $trap->get(ListTraces::class)->call(['project' => 'billing'])['traces'][0]; + + Assert::same([$all['spans'], $all['projects'], $all['services']], [2, ['default', 'billing'], ['gateway', 'billing']]); + Assert::same( + [$billing['name'], $billing['spans'], $billing['projects'], $billing['duration_ms']], + ['charge', 1, ['billing'], 5.0], + ); + } + #[DataSet([['since' => 1], '`since` must be a string.'], 'cursor not a string')] #[DataSet([['limit' => 101], '`limit` must be an integer from 1 to 100.'], 'limit above maximum')] #[DataSet([['errors_only' => 'yes'], '`errors_only` must be a boolean.'], 'flag not a boolean')] @@ -244,6 +345,8 @@ public function testResultConformsToOutputSchema(array $arguments): void #[DataSet([['min_duration_ms' => -1], '`min_duration_ms` must be a number of at least 0.'], 'negative duration')] #[DataSet([['min_duration_ms' => '5'], '`min_duration_ms` must be a number of at least 0.'], 'duration string')] #[DataSet([['from' => '5m', 'to' => '1h'], '`from` is later than `to`.'], 'time range')] + #[DataSet([['source' => 'zipkin'], '`source` must be one of: sentry, otel.'], 'unknown source')] + #[DataSet([['project' => 1], '`project` must be a string or a non-empty list of strings.'], 'project not a string')] #[DataSet([['search' => '[', 'regex' => true], '`search` is not a valid regular expression: Compilation failed: missing terminating ] for character class at offset 1.'], 'regex')] public function testRejectsInvalidArguments(array $arguments, string $message): never { @@ -263,7 +366,10 @@ public function testIsReadOnlyToolOfTheTracingModule(): void Assert::string($tool->description())->contains('get_trace'); Assert::same( \array_keys($tool->inputSchema()['properties']), - ['since', 'limit', 'errors_only', 'from', 'to', 'service', 'name', 'min_duration_ms', 'search', 'regex'], + [ + 'since', 'limit', 'project', 'source', 'errors_only', 'from', 'to', 'service', 'name', + 'min_duration_ms', 'search', 'regex', + ], ); } @@ -275,6 +381,31 @@ private static function ids(array $result): array return \array_column($result['traces'], 'id'); } + private static function receive(Trap $trap, OtlpTraces $frame): void + { + $trap->get(TelemetryMapper::class)->map($frame); + } + + /** + * A Sentry transaction of 250 ms with a query and a failed HTTP call. + */ + private static function sentry(Trap $trap, string $trace, string $project): void + { + $start = (float) (self::BASE / 1_000_000_000); + $trap->get(EnvelopeMapper::class)->map(new SentryEnvelope([], [new EnvelopeItem(['type' => 'transaction'], [ + 'event_id' => "{$trace}1", + 'transaction' => 'POST /checkout', + 'server_name' => 'checkout-api', + 'contexts' => ['trace' => ['trace_id' => self::traceId($trace), 'span_id' => 's0', 'op' => 'http.server']], + 'start_timestamp' => $start, + 'timestamp' => $start + 0.25, + 'spans' => [ + ['span_id' => 's1', 'parent_span_id' => 's0', 'op' => 'db.query', 'description' => 'SELECT 1', 'start_timestamp' => $start, 'timestamp' => $start + 0.1], + ['span_id' => 's2', 'parent_span_id' => 's0', 'op' => 'http.client', 'status' => 'internal_error', 'start_timestamp' => $start + 0.1, 'timestamp' => $start + 0.2], + ], + ])], project: $project)); + } + private static function frame(?string $service, Span ...$spans): OtlpTraces { return new OtlpTraces([new ResourceSpans( @@ -299,8 +430,8 @@ private static function span( parentSpanId: $parent === null ? null : \sprintf('%016x', $parent), name: $name ?? "span-$id", kind: SpanKind::Internal, - startTimeUnixNano: $start, - endTimeUnixNano: $end, + startTimeUnixNano: self::BASE + $start, + endTimeUnixNano: self::BASE + $end, status: new SpanStatus($status, $message), ); } diff --git a/tests/Unit/Server/Telemetry/TelemetryStoreTest.php b/tests/Unit/Server/Telemetry/TelemetryStoreTest.php index 110e5dfa..9518fa5d 100644 --- a/tests/Unit/Server/Telemetry/TelemetryStoreTest.php +++ b/tests/Unit/Server/Telemetry/TelemetryStoreTest.php @@ -134,6 +134,31 @@ public function stored(string $project, array $kinds): void Assert::same($listener->calls, [['shop', ['trace', 'metric']], ['default', ['log']]]); } + public function testEveryChangeOfATraceTakesTheNextSequenceNumber(): void + { + $now = 100.0; + $store = new TelemetryStore(clock: static function () use (&$now): float { + return $now; + }); + + $store->add(self::batch('default', transactions: [self::transaction('t1', 'a')], spans: [self::span('t2', 's1')])); + $now = 105.0; + $store->add(self::batch('default', spans: [self::span('t1', 's2')], logs: [self::log(1)])); + $store->add(self::batch('default', logs: [self::log(2)])); + + Assert::same($store->cursor(), 3); + Assert::same(\array_keys($store->traces()), ['t2', 't1']); + Assert::same($store->trace('t2')?->seq, 2); + Assert::same($store->trace('t2')?->updatedAt, 100.0); + Assert::same($store->trace('t1')?->seq, 3); + Assert::same($store->trace('t1')?->updatedAt, 105.0); + } + + public function testStoresHaveDifferentIds(): void + { + Assert::notSame((new TelemetryStore())->id, (new TelemetryStore())->id); + } + public function testDurationsAreBoundedToAYear(): void { Assert::same(Span::durationBetween(-9e15, 9e15), Span::MAX_DURATION_MS);