Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions apps/local/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ import {
getConnectionPresentation,
getWorkspaceEmptyState,
type ConnectionState,
pluralize,
} from "@/lib/presentation.ts";
import {
DEFAULT_STREAM_URL,
Expand Down Expand Up @@ -1505,9 +1506,10 @@ export default function App() {
{activeWorkspace.label}
</h1>
<span className="text-xs tabular-nums text-muted-foreground">
{searchedItems.length}{" "}
{activeWorkspace.singularLabel}
{searchedItems.length === 1 ? "" : "s"}
{pluralize(
searchedItems.length,
activeWorkspace.singularLabel,
)}
</span>
</div>
{newItemCount > 0 ? (
Expand All @@ -1521,9 +1523,11 @@ export default function App() {
}
}}
>
View {newItemCount} new{" "}
{activeWorkspace.singularLabel}
{newItemCount === 1 ? "" : "s"}
View{" "}
{pluralize(
newItemCount,
`new ${activeWorkspace.singularLabel}`,
)}
</button>
) : null}
</div>
Expand Down
3 changes: 2 additions & 1 deletion apps/local/src/components/event-filter-controls.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
} from "@/lib/event-filters.ts";
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover.tsx";
import { Button } from "./ui/button.tsx";
import { pluralize } from "@/lib/presentation.ts";
function toggle(values: string[], value: string) {
return values.includes(value)
? values.filter((entry) => entry !== value)
Expand Down Expand Up @@ -154,7 +155,7 @@ export function EventFilterControls({
})
}
>
Clear {count} filter{count === 1 ? "" : "s"}
Clear {pluralize(count, "filter")}
</Button>
) : null}
{count ? (
Expand Down
4 changes: 2 additions & 2 deletions apps/local/src/components/performance-workspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
type VitalName,
} from "@/lib/performance.ts";
import { ResizableWorkspace } from "./resizable-workspace.tsx";
import { pluralize } from "@/lib/presentation.ts";
function ms(value?: number) {
return value === undefined ? "—" : `${value.toFixed(1)} ms`;
}
Expand Down Expand Up @@ -249,8 +250,7 @@ export function WebVitalsWorkspace({
>
<span className="block break-words">{page.name}</span>
<span className="text-xs text-muted-foreground">
{page.visits.length} captured visit
{page.visits.length === 1 ? "" : "s"}
{pluralize(page.visits.length, "captured visit")}
</span>
</button>
</li>
Expand Down
50 changes: 49 additions & 1 deletion apps/local/src/components/trace-waterfall.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -255,13 +255,61 @@ test("sampled profile rows stay folded under their span until shown", () => {
screen.getAllByRole("button", { name: "Inspect span work" }).length,
).toBeGreaterThan(0);
fireEvent.click(
screen.getByRole("button", { name: "Hide sampled functions" }),
screen.getByRole("button", { name: /^Hide sampled functions/ }),
);
expect(
screen.queryAllByRole("button", { name: "Inspect span work" }),
).toEqual([]);
});

test("each sampled-functions toggle names its span", () => {
const trace = buildTraceGroups(profiledRequest())[0]!;
render(<TraceWaterfall trace={trace} onSelectSpan={() => undefined} />);
const toggle = screen.getByRole("button", {
name: /^Show \d+ sampled functions? under GET \/slow$/,
});
fireEvent.click(toggle);
expect(
screen.getByRole("button", {
name: "Hide sampled functions under GET /slow",
}),
).toBeDefined();
});

test("search unfolds sampled rows only when a sampled row matches", () => {
const trace = buildTraceGroups(profiledRequest())[0]!;
render(<TraceWaterfall trace={trace} onSelectSpan={() => undefined} />);
const search = screen.getByLabelText("Search in trace");
fireEvent.change(search, { target: { value: "SELECT" } });
expect(
screen.queryAllByRole("button", { name: "Inspect span work" }),
).toEqual([]);
fireEvent.change(search, { target: { value: "work" } });
expect(
screen.getAllByRole("button", { name: "Inspect span work" }).length,
).toBeGreaterThan(0);
});

test("selecting a sampled row after mount shows its folded siblings", () => {
const trace = buildTraceGroups(profiledRequest())[0]!;
const sampled = trace.spans.find((span) => span.sampled)!;
const { rerender } = render(
<TraceWaterfall trace={trace} onSelectSpan={() => undefined} />,
);
rerender(
<TraceWaterfall
trace={trace}
selectedSpanId={sampled.id}
onSelectSpan={() => undefined}
/>,
);
expect(
screen
.getAllByRole("button", { name: "Inspect span work" })
.some((button) => button.getAttribute("aria-pressed") === "true"),
).toBe(true);
});

test("a selected sampled row stays visible when returning to the trace", () => {
const trace = buildTraceGroups(profiledRequest())[0]!;
const sampled = trace.spans.find((span) => span.sampled)!;
Expand Down
41 changes: 28 additions & 13 deletions apps/local/src/components/trace-waterfall.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,9 @@ function SpanRow({
const position = getSpanPosition(span, trace);
const visualDepth = Math.min(depth, 4);
const failed = isFailingSpan(span);
const samplesLabel = samplesShown
? "Hide sampled functions"
: `Show ${pluralize(sampleCount, "sampled function")}`;
// Guides start under the parent's expand control and end at this row's.
const guideLeft =
CELL_PADDING_REM + (visualDepth - 1) * INDENT_REM + TOGGLE_REM / 2;
Expand Down Expand Up @@ -228,12 +231,11 @@ function SpanRow({
<button
type="button"
aria-expanded={samplesShown}
aria-label={`${samplesLabel} under ${span.description}`}
className="text-xs text-muted-foreground hover:text-primary focus-visible:ring-2 focus-visible:ring-ring outline-none"
onClick={onToggleSamples}
>
{samplesShown
? "Hide sampled functions"
: `Show ${sampleCount} sampled function${sampleCount === 1 ? "" : "s"}`}
{samplesLabel}
</button>
) : null}
</div>
Expand Down Expand Up @@ -284,13 +286,19 @@ export function TraceWaterfall({
const [collapsed, setCollapsed] = useState<Set<string>>(new Set());
const allSpans = useMemo(() => flattenSpans(trace.roots), [trace]);
// Sampled profile rows stay folded under their captured span until shown.
// A selected or revealed sampled row starts with its siblings shown.
const [shownSamples, setShownSamples] = useState<Set<string>>(() => {
const owner = allSpans.find(
({ span }) => span.id === (revealSpanId ?? selectedSpanId),
)?.owner;
return new Set(owner ? [owner] : []);
});
// A selected or revealed sampled row shows its siblings whenever that
// selection changes, starting with the first render so focus can return
// to it. This runs during render: an effect would run after the
// workspace's focus restore and trips react(set-state-in-effect).
const revealedId = revealSpanId ?? selectedSpanId;
const [shownSamples, setShownSamples] = useState<Set<string>>(new Set());
const [seededFor, setSeededFor] = useState<string>();
if (revealedId !== seededFor) {
setSeededFor(revealedId);
const owner = allSpans.find(({ span }) => span.id === revealedId)?.owner;
if (owner && !shownSamples.has(owner))
setShownSamples(new Set(shownSamples).add(owner));
}
const [treeWidth, setTreeWidth] = useState(40);
const sampleCounts = useMemo(() => {
const counts = new Map<string, number>();
Expand Down Expand Up @@ -357,15 +365,22 @@ export function TraceWaterfall({
);
}

// Search shows every sampled row so matches are not hidden.
// Search also unfolds the owners of matching sampled rows.
const searchedOwners = new Set(
query.trim()
? allSpans.flatMap(({ owner, span }) =>
owner && matching.has(span.id) ? [owner] : [],
)
: [],
);
const samplesVisible = (owner: string) =>
Boolean(query.trim()) || shownSamples.has(owner);
shownSamples.has(owner) || searchedOwners.has(owner);
const spans: PositionedSpan[] = [];
let hiddenBelow: number | undefined;
for (const entry of allSpans) {
if (entry.owner && !samplesVisible(entry.owner)) continue;
if (!query.trim()) {
if (hiddenBelow !== undefined && entry.depth > hiddenBelow) continue;
if (entry.owner && !samplesVisible(entry.owner)) continue;
hiddenBelow = collapsed.has(entry.span.id) ? entry.depth : undefined;
}
if (!query.trim() || !onlyMatches || matching.has(entry.span.id))
Expand Down
2 changes: 1 addition & 1 deletion apps/local/src/components/trace-workspace.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ test("returning from a sampled function keeps its row shown and focused", () =>
(document.activeElement as HTMLElement | null)?.dataset["spanId"],
).toBe(id);
fireEvent.click(
screen.getByRole("button", { name: "Hide sampled functions" }),
screen.getByRole("button", { name: /^Hide sampled functions/ }),
);
expect(
screen.queryAllByRole("button", { name: "Inspect span work" }),
Expand Down
56 changes: 56 additions & 0 deletions apps/local/src/lib/trace-model.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1175,6 +1175,62 @@ test.each([
},
);

test.each([
[
"http.server",
"GET",
{
"url.template": "/api/items/{id}",
"url.full": "http://localhost:3000/api/items/7",
},
"GET /api/items/{id}",
],
[
"http.client",
"GET",
{ "url.full": "https://api.stripe.com/v1/charges?limit=1" },
"GET api.stripe.com/v1/charges",
],
["http.server", "get", { "url.path": "/api/edge" }, "get /api/edge"],
[
"http.server",
"GET",
{ "url.full": "/api/edge?x=1", "url.path": "/api/edge" },
"GET /api/edge",
],
[
"resource.script",
"get localhost",
{ "url.full": "http://localhost:5173/src/app.js?v=1" },
"get http://localhost:5173/src/app.js",
],
])(
"a %s span named %o is labeled with its target",
(op, name, attributes, title) => {
const [trace] = buildTraceGroups(
decodeEnvelope(
spanEnvelope([
{
trace_id: "target",
span_id: "segment",
is_segment: true,
name,
start_timestamp: 1,
end_timestamp: 1.1,
attributes: Object.fromEntries(
Object.entries({ "sentry.op": op, ...attributes }).map(
([key, value]) => [key, { type: "string", value }],
),
),
},
]),
"target",
),
);
expect(trace?.title).toBe(title);
},
);

test("span counts leave out the transaction and segment like the tail's [N spans]", () => {
// Django /queries/: the tail printed [7 spans] while the viewer showed 8.
const children = Array.from({ length: 7 }, (_, index) => ({
Expand Down
37 changes: 26 additions & 11 deletions apps/local/src/lib/trace-model.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { parseEventTimestamp } from "../../../../packages/cli/src/commands/local/timestamp.ts";
import { httpTargetAttribute } from "../../../../packages/cli/src/commands/local/http-target.ts";
import {
getEventMetadata,
type EventMetadata,
Expand Down Expand Up @@ -94,6 +95,7 @@ function getPayloadSpan(
operation ??
item.type,
payload,
operation,
);

return withoutUndefined({
Expand Down Expand Up @@ -143,10 +145,18 @@ const HTTP_METHODS = new Set([
* (span v2 attributes or transaction span data).
* Label them with the URL's origin and path so rows can be told apart,
* grouped and searched. The query (cache busters, tokens) and fragment
* stay in the span's attributes. Spans named by method only get the
* route, or else the path, after the method.
* stay in the span's attributes.
*
* Spans named by method only ("GET", any case) get a target after the
* method, read in the CLI's `httpTargetAttribute` order. A server span
* (`http.server`) shows the route or path; any other span keeps the
* host it called, such as `GET api.stripe.com/v1/charges`.
*/
function withCapturedUrl(description: string, payload: unknown): string {
function withCapturedUrl(
description: string,
payload: unknown,
operation: string | undefined,
): string {
const data = spanData(payload);
const url = getString(data["url.full"]);
let parsed: URL | undefined;
Expand All @@ -155,16 +165,19 @@ function withCapturedUrl(description: string, payload: unknown): string {
} catch {
parsed = undefined;
}
// Next.js edge `http.server` segments are named by method only ("GET").
if (HTTP_METHODS.has(description)) {
const path =
getString(data["http.route"]) ??
getString(data["url.path"]) ??
parsed?.pathname;
if (HTTP_METHODS.has(description.toUpperCase())) {
if (operation !== "http.server" && parsed)
return `${description} ${parsed.host}${parsed.pathname}`;
// A `url.full` that isn't an absolute URL has no path to show, so
// skip it and fall through to `url.path`.
const target = httpTargetAttribute((key) =>
key === "url.full" && !parsed ? undefined : getString(data[key]),
);
const path = target?.key === "url.full" ? parsed?.pathname : target?.value;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
return path ? `${description} ${path}` : description;
}
if (!parsed) return description;
const match = description.match(/^([A-Z]+ )?(.*)$/);
const match = description.match(/^([a-z]+ )?(.*)$/i);
const method = match?.[1] ?? "";
const target = match?.[2] ?? description;
return target === parsed.hostname || target === parsed.host
Expand Down Expand Up @@ -201,7 +214,8 @@ function mergeSpan(
].some(
(value) =>
typeof value === "string" &&
withCapturedUrl(value.trim(), span.payload) === description,
withCapturedUrl(value.trim(), span.payload, span.operation) ===
description,
);
return named ? (captured ? 4 : 2) : 0;
};
Expand Down Expand Up @@ -290,6 +304,7 @@ function getChildSpans(payload: unknown, item: LocalFeedItem): TraceSpan[] {
description: withCapturedUrl(
getString(value["description"]) ?? operation ?? id,
value,
operation,
),
startTimestamp,
endTimestamp,
Expand Down
7 changes: 5 additions & 2 deletions docs/cli/local-control-plane.md
Original file line number Diff line number Diff line change
Expand Up @@ -325,8 +325,11 @@ transactions, show their op and transaction name.

A trace's error count is its error events: exceptions and error-level messages.
Failing spans and error-level logs are not counted again. A span or segment
named only by its HTTP method, such as a Next.js edge `GET`, is labeled with its
`http.route`, or else its `url.path` or URL path.
named only by its HTTP method (in any case), such as a Next.js edge `GET`, gets
a target after the method. The viewer and the tail read the same attributes, in
order: `http.route`, `url.template`, `url.full`, then `url.path`. A server span
(`http.server`) shows the route or path; any other span keeps the host it called,
such as `GET api.stripe.com/v1/charges`.

Log inspectors show the message, level, and attributes. Requests summarize useful
metadata and related telemetry. Waterfall spans are keyboard-selectable and open
Expand Down
Loading
Loading