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
54 changes: 54 additions & 0 deletions apps/local/src/App.capture-lifecycle.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -790,3 +790,57 @@ test("replay recordings show when they were received instead of unknown time", a
expect(row.textContent).not.toContain("unknown time");
expect(row.textContent).toContain(new Date(receivedAt).toLocaleTimeString());
});

test("an untimed item in a trace does not stretch the trace to its receive time", async () => {
// A 400 ms transaction, then a sentry-python cron check-in in the same
// trace that the receiver got 222 s later. Check-ins carry no timestamp.
const uuidv7 = (ms: number) =>
`${ms
.toString(16)
.padStart(12, "0")
.replace(/^(.{8})(.{4})$/, "$1-$2")}-7abc-8def-0123456789ab`;
const finishedAt = 1_794_947_420.913;
const traceId = "8f2a6c1e4b7d4f0a9c3e5b1d7a2f6c8e";
renderCapture({ path: "/traces" });
const source = await openSource();
const send = (lastEventId: string, items: unknown[]) =>
act(async () =>
source.dispatchEvent(
new MessageEvent("application/x-sentry-envelope", {
data: JSON.stringify([{}, items]),
lastEventId,
}),
),
);
await send(uuidv7(finishedAt * 1000 + 50), [
[
{ type: "transaction" },
{
type: "transaction",
transaction: "nightly-report",
start_timestamp: finishedAt - 0.4,
timestamp: finishedAt,
contexts: {
trace: { trace_id: traceId, span_id: "a1b2c3d4e5f60718", op: "task" },
},
},
],
]);
await send(uuidv7(finishedAt * 1000 + 222_000), [
[
{ type: "check_in" },
{
check_in_id: "5f1c0e8a2b9d4c7e8f3a1b6d0c9e2f4a",
monitor_slug: "nightly-report",
status: "ok",
duration: 0.4,
contexts: { trace: { trace_id: traceId, span_id: "a1b2c3d4e5f60718" } },
},
],
]);
const row = await screen.findByRole("button", {
name: "View trace nightly-report",
});
expect(row.textContent).toMatch(/400(\.0+)? ms/);
expect(row.textContent).not.toContain("222");
});
21 changes: 21 additions & 0 deletions apps/local/src/App.sessions.integration.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -729,3 +729,24 @@ test("a new session link in an open tab switches to that run's sessions", async
await second.stop();
}
});

test("a pasted link with a stream the viewer refuses still leaves the address bar", async () => {
const daemon = await startDaemon();
try {
const web = await daemon.create("web");
await daemon.ingest(web, "/first-run");
renderSession(web);
await screen.findAllByText("/first-run");
await act(async () => {
window.location.hash = new URLSearchParams({
stream: "https://collector.example.com/stream",
directory: web.directoryUrl,
}).toString();
});
await waitFor(() => expect(window.location.hash).toBe(""));
expect(screen.getAllByText("/first-run").length).toBeGreaterThan(0);
} finally {
cleanup();
await daemon.stop();
}
});
34 changes: 18 additions & 16 deletions apps/local/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@ import {
DEFAULT_STREAM_URL,
decodeEnvelope,
getStreamUrlFromHash,
itemTime,
readConnectionLink,
parseStreamEndpoint,
isLoopbackHost,
REMOTE_STREAM_STORAGE_KEY,
Expand Down Expand Up @@ -261,7 +263,7 @@ function EventEntry({
) : null}
{columns.includes("time") ? (
<time className="shrink-0 font-mono text-xs tabular-nums text-muted-foreground">
{formatTimestamp(item.timestamp)}
{formatTimestamp(itemTime(item))}
</time>
) : null}
</button>
Expand Down Expand Up @@ -710,18 +712,22 @@ export default function App() {
});
useEffect(() => {
const onHashChange = () => {
const link = readConnectionLink(window.location.hash);
if (!link.present) return;
const linkedStreamUrl = getStreamUrlFromHash(window.location.hash);
if (!linkedStreamUrl) return;
const directory = parseSessionDirectoryUrl(
new URLSearchParams(window.location.hash.slice(1)).get("directory"),
linkedStreamUrl,
);
connectToEndpointRef.current(linkedStreamUrl);
if (directory) {
saveSessionDirectory(directory);
setDirectoryUrl(directory);
if (linkedStreamUrl) {
connectToEndpointRef.current(linkedStreamUrl);
const directory = parseSessionDirectoryUrl(
link.directory,
linkedStreamUrl,
);
if (directory) {
saveSessionDirectory(directory);
setDirectoryUrl(directory);
}
}
// The link carries capabilities; keep them out of the address bar.
// The link carries capabilities, even a refused one; keep them out of
// the address bar.
void navigate(
{ pathname: window.location.pathname, search: window.location.search },
{ replace: true },
Expand Down Expand Up @@ -935,11 +941,7 @@ export default function App() {
envelopeReceivedAt(eventId) ??
(Number.isNaN(sentAtMs) ? Date.now() : sentAtMs);
// Items with no SDK time, such as replay recordings, show when they arrived.
items = items?.map((item) =>
item.timestamp === undefined
? { ...item, timestamp: receivedAt / 1000 }
: item,
);
items = items?.map((item) => ({ ...item, receivedAt }));
const itemTypes = [...new Set(items?.map((item) => item.type))];
setLatestEventTime((latest) =>
latest === undefined ? receivedAt : Math.max(latest, receivedAt),
Expand Down
4 changes: 2 additions & 2 deletions apps/local/src/components/event-detail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
type DetailField,
} from "./inspector-data.ts";
import type { LocalFeedItem } from "@/lib/spotlight.ts";
import { getEventMetadata } from "@/lib/spotlight.ts";
import { getEventMetadata, itemTime } from "@/lib/spotlight.ts";
import { formatTimestamp } from "@/lib/presentation.ts";
import { getEventExceptions } from "@/lib/exceptions.ts";
import type { TraceGroup } from "@/lib/trace-model.ts";
Expand Down Expand Up @@ -213,7 +213,7 @@ export function EventDetail({
</Button>
) : null}
<time className="shrink-0 font-mono text-xs tabular-nums text-muted-foreground">
{formatTimestamp(item.timestamp)}
{formatTimestamp(itemTime(item))}
</time>
</header>
<InspectorTabs
Expand Down
15 changes: 15 additions & 0 deletions apps/local/src/components/inspector-data.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { expect, test } from "vitest";
import { attributeFields } from "./inspector-data.ts";

test("attribute values hide terminal colour codes in nested strings too", () => {
// uvicorn's logging record, kept as breadcrumb data by sentry-python.
const [field] = attributeFields({
record: {
color_message: "Started server process [\u001b[36m%d\u001b[0m]",
args: ["\u001b[1m41234\u001b[0m"],
},
});
expect(field?.value).toBe(
'{"color_message":"Started server process [%d]","args":["41234"]}',
);
});
11 changes: 7 additions & 4 deletions apps/local/src/components/inspector-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,16 @@ export function attributeFields(value: unknown): DetailField[] {
return Object.entries(detailRecord(value)).map(([label, attribute]) => {
const record = detailRecord(attribute);
const content = "value" in record ? record["value"] : attribute;
const serialized = JSON.stringify(content) as string | undefined;
const serialized = JSON.stringify(content, (_key, nested: unknown) =>
typeof nested === "string" ? stripAnsi(nested) : nested,
) as string | undefined;
return {
label,
// Display only: the JSON tab keeps SDK text exactly as captured.
value: stripAnsi(
typeof content === "string" ? content : (serialized ?? String(content)),
),
value:
typeof content === "string"
? stripAnsi(content)
: (serialized ?? String(content)),
code: true,
};
});
Expand Down
56 changes: 53 additions & 3 deletions apps/local/src/components/span-detail.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import {
cleanup,
fireEvent,
render,
screen,
within,
} from "@testing-library/react";
import { afterEach, expect, test, vi } from "vitest";
import { formatDateTime } from "@/lib/presentation.ts";
import { decodeEnvelope } from "@/lib/spotlight.ts";
import { buildTraceGroups } from "@/lib/trace-model.ts";
import { SpanDetail } from "./span-detail.tsx";
Expand Down Expand Up @@ -99,6 +106,49 @@ test("span start and end times use local time, not raw epoch seconds", () => {
const details =
screen.getByRole("table", { name: "Span details" }).textContent ?? "";
expect(details).not.toContain("1795010400.538");
expect(details).toContain(new Date(1795010400538).toLocaleTimeString());
expect(details).toContain(new Date(1795010400650).toLocaleTimeString());
expect(details).toContain(
formatDateTime(1795010400.538, { milliseconds: true }),
);
expect(details).toContain(
formatDateTime(1795010400.65, { milliseconds: true }),
);
});

test("span times keep milliseconds and show the date when it is not today", () => {
// A 40 ms span from an earlier day.
const [trace] = buildTraceGroups(
decodeEnvelope(
JSON.stringify([
{},
[
[
{ type: "transaction" },
{
transaction: "GET /orders",
start_timestamp: 1_700_000_000.538,
timestamp: 1_700_000_000.578,
contexts: { trace: { trace_id: "trace", span_id: "root" } },
},
],
],
]),
"fixture",
),
);
const span = trace?.spans.find((entry) => entry.id === "root");
if (!trace || !span) throw new Error("Expected trace span");
render(<SpanDetail trace={trace} span={span} />);
const details = screen.getByRole("table", { name: "Span details" });
const time = (ms: number) =>
new Date(ms).toLocaleTimeString(undefined, {
hour: "numeric",
minute: "2-digit",
second: "2-digit",
fractionalSecondDigits: 3,
});
const start = within(details).getByRole("row", { name: /Start timestamp/ });
const end = within(details).getByRole("row", { name: /End timestamp/ });
const day = new Date(1_700_000_000_538).toLocaleDateString();
expect(start.textContent).toContain(`${day} ${time(1_700_000_000_538)}`);
expect(end.textContent).toContain(`${day} ${time(1_700_000_000_578)}`);
});
6 changes: 3 additions & 3 deletions apps/local/src/components/span-detail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Check, Copy, ChevronLeft } from "lucide-react";
import { type KeyboardEvent, type ReactNode, useId, useState } from "react";
import type { LocalFeedItem } from "@/lib/spotlight.ts";
import type { TraceGroup, TraceSpan } from "@/lib/trace-model.ts";
import { formatTimestamp } from "@/lib/presentation.ts";
import { formatDateTime } from "@/lib/presentation.ts";
import { isErrorEvent } from "@/lib/workspace.ts";
import { jsonText } from "@/lib/objects.ts";
import { JsonView } from "./json-view.tsx";
Expand Down Expand Up @@ -219,7 +219,7 @@ export function SpanDetail({
: [
{
label: "Start timestamp",
value: formatTimestamp(span.startTimestamp),
value: formatDateTime(span.startTimestamp, { milliseconds: true }),
code: true,
},
]),
Expand All @@ -228,7 +228,7 @@ export function SpanDetail({
: [
{
label: "End timestamp",
value: formatTimestamp(span.endTimestamp),
value: formatDateTime(span.endTimestamp, { milliseconds: true }),
code: true,
},
]),
Expand Down
4 changes: 2 additions & 2 deletions apps/local/src/lib/event-filters.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { parseEventTimestamp } from "../../../../packages/cli/src/commands/local/timestamp.ts";
import type { LocalFeedItem } from "./spotlight.ts";
import { itemTime, type LocalFeedItem } from "./spotlight.ts";
import { spanData, text } from "./inspection.ts";
export type EventColumn = "time" | "type" | "level" | "logger" | "duration";
export type EventFilters = {
Expand All @@ -18,7 +18,7 @@ export function loggerForItem(item: LocalFeedItem): string | undefined {
return text(spanData(item.payload)["sentry.logger.name"]);
}
function timestamp(item: LocalFeedItem): number {
const value = parseEventTimestamp(item.timestamp);
const value = parseEventTimestamp(itemTime(item));
if (value === undefined) return -Infinity;
return value < 1e12 ? value * 1000 : value;
}
Expand Down
4 changes: 2 additions & 2 deletions apps/local/src/lib/inspection.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { classifyEvent } from "../../../../packages/cli/src/commands/local/event-kind.ts";
import { jsonText } from "./objects.ts";
import { getEventMetadata, type LocalFeedItem } from "./spotlight.ts";
import { getEventMetadata, itemTime, type LocalFeedItem } from "./spotlight.ts";
import { getEventExceptions, formatExceptionTitle } from "./exceptions.ts";

export function record(value: unknown): Record<string, unknown> {
Expand Down Expand Up @@ -258,7 +258,7 @@ export function sdkInventory(items: readonly LocalFeedItem[]): SdkEntry[] {
key = `${name}@${version}`;
const previous = entries.get(key);
const lastSeen =
item.timestamp ??
itemTime(item) ??
text(item.envelopeHeader?.["sent_at"]) ??
previous?.lastSeen;
entries.set(key, {
Expand Down
24 changes: 20 additions & 4 deletions apps/local/src/lib/presentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,27 @@ export function formatTimestamp(
return toDate(timestamp)?.toLocaleTimeString() ?? String(timestamp);
}

/** Like formatTimestamp, with the local date added when it is not today. */
export function formatDateTime(timestamp: number | string): string {
const TIME_WITH_MILLISECONDS: Intl.DateTimeFormatOptions = {
hour: "numeric",
minute: "2-digit",
second: "2-digit",
fractionalSecondDigits: 3,
};

/**
* Like formatTimestamp, with the local date added when it is not today. Pass
* `milliseconds` where events can be closer together than a second.
*/
export function formatDateTime(
timestamp: number | string,
{ milliseconds = false }: { milliseconds?: boolean } = {},
): string {
const date = toDate(timestamp);
if (!date) return String(timestamp);
const time = milliseconds
? date.toLocaleTimeString(undefined, TIME_WITH_MILLISECONDS)
: date.toLocaleTimeString();
return date.toDateString() === new Date().toDateString()
? date.toLocaleTimeString()
: `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
? time
: `${date.toLocaleDateString()} ${time}`;
}
12 changes: 8 additions & 4 deletions apps/local/src/lib/session-directory.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { isLoopbackHost, parseStreamEndpoint } from "./spotlight.ts";
import {
isLoopbackHost,
parseStreamEndpoint,
readConnectionLink,
} from "./spotlight.ts";

const DIRECTORY_STORAGE_KEY = "sentry.local.session-directory";
export type ViewerSession = {
Expand Down Expand Up @@ -39,20 +43,20 @@ export function parseSessionDirectoryUrl(
export function getInitialSessionDirectory(
streamUrl: string,
): string | undefined {
const fragment = new URLSearchParams(window.location.hash.slice(1));
const link = readConnectionLink(window.location.hash);
let saved: string | null = null;
try {
saved = window.sessionStorage.getItem(DIRECTORY_STORAGE_KEY);
} catch {
/* Storage may be disabled. */
}
const directory = parseSessionDirectoryUrl(
fragment.has("directory") ? fragment.get("directory") : saved,
link.directory ?? saved,
streamUrl,
);
// The startup effect removes the fragment before discovery can finish. Save
// its validated capability now so an early reload cannot lose the picker.
if (directory && fragment.has("directory")) saveSessionDirectory(directory);
if (directory && link.directory !== null) saveSessionDirectory(directory);
return directory;
}

Expand Down
Loading
Loading