diff --git a/src/server.ts b/src/server.ts index 3b591b5f1..04dc05bcf 100644 --- a/src/server.ts +++ b/src/server.ts @@ -317,21 +317,27 @@ export default { } return runWithHostRuntimeEnv(env, () => runWithHostRuntimeContext(context, () => - withDocsRequestTimings(request, async () => { - const response = finalizeDocsHtmlHeaders( - request, - await server.fetch(request), - ) - if (import.meta.env.PROD && import.meta.env.MODE !== 'staging') { - const scarfRequest = createScarfServerRequest(request, response) - if (scarfRequest) { - scheduleHostRuntimeTask(() => - sendScarfServerRequest(scarfRequest), - ) + withDocsRequestTimings( + request, + async () => { + const response = finalizeDocsHtmlHeaders( + request, + await server.fetch(request), + ) + if (import.meta.env.PROD && import.meta.env.MODE !== 'staging') { + const scarfRequest = createScarfServerRequest(request, response) + if (scarfRequest) { + scheduleHostRuntimeTask(() => + sendScarfServerRequest(scarfRequest), + ) + } } - } - return response - }), + return response + }, + import.meta.env.MODE === 'staging' + ? undefined + : scheduleHostRuntimeTask, + ), ), ) }, diff --git a/src/utils/request-timing.server.ts b/src/utils/request-timing.server.ts index 4ae55047e..9b6d30069 100644 --- a/src/utils/request-timing.server.ts +++ b/src/utils/request-timing.server.ts @@ -40,6 +40,7 @@ export async function timeRequestWork( export async function withDocsRequestTimings( request: Request, work: () => Promise, + scheduleMetricFlush?: (flush: () => Promise) => void, ) { if (!/^\/[^/]+\/[^/]+\/docs\//.test(new URL(request.url).pathname)) return work() @@ -54,6 +55,21 @@ export async function withDocsRequestTimings( return storage.run(timings, async () => { const response = await work() const durationMs = performance.now() - timings.startedAt + if (scheduleMetricFlush && Sentry.isEnabled()) { + Sentry.metrics.distribution( + 'docs.response.headers.duration', + durationMs, + { + unit: 'millisecond', + attributes: { + 'http.response.status_code': response.status, + 'docs.database_used': timings.databaseUsed, + 'docs.first_request_on_worker': docsRequest === 1, + }, + }, + ) + scheduleMetricFlush(() => Sentry.flush(2_000)) + } const totals = new Map() for (const entry of timings.entries) totals.set(entry.name, (totals.get(entry.name) ?? 0) + entry.durationMs) diff --git a/src/utils/stale-app-reload.ts b/src/utils/stale-app-reload.ts index 9a1217f51..cea274490 100644 --- a/src/utils/stale-app-reload.ts +++ b/src/utils/stale-app-reload.ts @@ -1,3 +1,4 @@ +import * as Sentry from '@sentry/tanstackstart-react' import { getSessionStorageItem, setSessionStorageItem, @@ -77,6 +78,10 @@ export function reloadOnStaleAppError(error: unknown) { writeLastReloadAt(now) window.location.reload() markReloadedErrors(error) + if (Sentry.isEnabled()) { + Sentry.metrics.count('app.stale_reload', 1) + void Sentry.flush(2_000) + } return true } diff --git a/tests/request-timing.test.ts b/tests/request-timing.test.ts index 2bb1b7f8d..334e3eb51 100644 --- a/tests/request-timing.test.ts +++ b/tests/request-timing.test.ts @@ -1,5 +1,6 @@ import assert from 'node:assert/strict' import { test } from 'node:test' +import * as Sentry from '@sentry/tanstackstart-react' import { markRequestDatabaseUse, timeRequestWork, @@ -49,3 +50,53 @@ test('non-docs requests have no profiling headers', async () => { ) assert.equal(response.headers.has('Server-Timing'), false) }) + +test('docs response timing is sent through the scheduled Sentry flush', async (t) => { + const metricPayloads: unknown[] = [] + const client = new Sentry.NodeClient({ + dsn: 'https://fixture@example.invalid/1', + integrations: [], + stackParser: Sentry.defaultStackParser, + transport: () => ({ + async send([, items]) { + for (const [header, payload] of items) { + if (header.type === 'trace_metric') metricPayloads.push(payload) + } + return { statusCode: 200 } + }, + flush: async () => true, + }), + }) + t.after(() => client.close(100)) + + await Sentry.withScope(async (scope) => { + scope.setClient(client) + const pending: Array> = [] + const response = await withDocsRequestTimings( + request, + async () => { + markRequestDatabaseUse() + return new Response(null, { status: 503 }) + }, + (flush) => pending.push(flush()), + ) + + assert.equal(response.status, 503) + assert.deepEqual(await Promise.all(pending), [true]) + assert.partialDeepStrictEqual(metricPayloads, [ + { + items: [ + { + name: 'docs.response.headers.duration', + type: 'distribution', + unit: 'millisecond', + attributes: { + 'http.response.status_code': { type: 'integer', value: 503 }, + 'docs.database_used': { type: 'boolean', value: true }, + }, + }, + ], + }, + ]) + }) +}) diff --git a/tests/stale-app-reload.test.ts b/tests/stale-app-reload.test.ts index 92d3092dd..442fcc4a4 100644 --- a/tests/stale-app-reload.test.ts +++ b/tests/stale-app-reload.test.ts @@ -1,6 +1,11 @@ import assert from 'node:assert/strict' import test from 'node:test' -import { BrowserClient, Scope, defaultStackParser } from '@sentry/browser' +import { + BrowserClient, + Scope, + defaultStackParser, + getCurrentScope, +} from '@sentry/browser' import { consumeStaleAppRecovery, reloadOnStaleAppError, @@ -33,14 +38,18 @@ test('Sentry suppresses recovered errors but reports cooldown failures', async ( }) t.mock.method(Date, 'now', () => now) let sent = 0 + let sentMetrics = 0 + const metrics: unknown[] = [] const originals: unknown[] = [] const client = new BrowserClient({ dsn: 'https://fixture@example.invalid/1', integrations: [], stackParser: defaultStackParser, transport: () => ({ - send: async () => { - sent++ + send: async ([, items]) => { + if (items.some(([header]) => header.type === 'trace_metric')) + sentMetrics++ + else sent++ return { statusCode: 200 } }, flush: async () => true, @@ -49,10 +58,22 @@ test('Sentry suppresses recovered errors but reports cooldown failures', async ( originals.push(hint.originalException) return consumeStaleAppRecovery(hint.originalException) ? null : event }, + beforeSendMetric(metric) { + metrics.push({ + name: metric.name, + type: metric.type, + value: metric.value, + }) + return metric + }, }) t.after(() => client.close(100)) const scope = new Scope() scope.setClient(client) + const currentScope = getCurrentScope() + const previousClient = currentScope.getClient() + currentScope.setClient(client) + t.after(() => currentScope.setClient(previousClient)) const first = new Error('Failed to fetch dynamically imported module') assert.equal(reloadOnStaleAppError([first]), true) // The boundary can see the same error again before Sentry processes it. @@ -91,4 +112,7 @@ test('Sentry suppresses recovered errors but reports cooldown failures', async ( const blocked = new Error(first.message) assert.throws(() => reloadOnStaleAppError(blocked), /reload blocked/) assert.equal(consumeStaleAppRecovery(blocked), false) + const reloadMetric = { name: 'app.stale_reload', type: 'counter', value: 1 } + assert.deepEqual(metrics, [reloadMetric, reloadMetric]) + assert.equal(sentMetrics, 2) })