Skip to content

Commit 2cc7ae6

Browse files
authored
Track docs response timing and stale reloads in Sentry (#1537)
Add Sentry Application Metrics for docs and stale reloads
1 parent 53107bd commit 2cc7ae6

5 files changed

Lines changed: 119 additions & 17 deletions

File tree

‎src/server.ts‎

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -317,21 +317,27 @@ export default {
317317
}
318318
return runWithHostRuntimeEnv(env, () =>
319319
runWithHostRuntimeContext(context, () =>
320-
withDocsRequestTimings(request, async () => {
321-
const response = finalizeDocsHtmlHeaders(
322-
request,
323-
await server.fetch(request),
324-
)
325-
if (import.meta.env.PROD && import.meta.env.MODE !== 'staging') {
326-
const scarfRequest = createScarfServerRequest(request, response)
327-
if (scarfRequest) {
328-
scheduleHostRuntimeTask(() =>
329-
sendScarfServerRequest(scarfRequest),
330-
)
320+
withDocsRequestTimings(
321+
request,
322+
async () => {
323+
const response = finalizeDocsHtmlHeaders(
324+
request,
325+
await server.fetch(request),
326+
)
327+
if (import.meta.env.PROD && import.meta.env.MODE !== 'staging') {
328+
const scarfRequest = createScarfServerRequest(request, response)
329+
if (scarfRequest) {
330+
scheduleHostRuntimeTask(() =>
331+
sendScarfServerRequest(scarfRequest),
332+
)
333+
}
331334
}
332-
}
333-
return response
334-
}),
335+
return response
336+
},
337+
import.meta.env.MODE === 'staging'
338+
? undefined
339+
: scheduleHostRuntimeTask,
340+
),
335341
),
336342
)
337343
},

‎src/utils/request-timing.server.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ export async function timeRequestWork<T>(
4040
export async function withDocsRequestTimings(
4141
request: Request,
4242
work: () => Promise<Response>,
43+
scheduleMetricFlush?: (flush: () => Promise<boolean>) => void,
4344
) {
4445
if (!/^\/[^/]+\/[^/]+\/docs\//.test(new URL(request.url).pathname))
4546
return work()
@@ -54,6 +55,21 @@ export async function withDocsRequestTimings(
5455
return storage.run(timings, async () => {
5556
const response = await work()
5657
const durationMs = performance.now() - timings.startedAt
58+
if (scheduleMetricFlush && Sentry.isEnabled()) {
59+
Sentry.metrics.distribution(
60+
'docs.response.headers.duration',
61+
durationMs,
62+
{
63+
unit: 'millisecond',
64+
attributes: {
65+
'http.response.status_code': response.status,
66+
'docs.database_used': timings.databaseUsed,
67+
'docs.first_request_on_worker': docsRequest === 1,
68+
},
69+
},
70+
)
71+
scheduleMetricFlush(() => Sentry.flush(2_000))
72+
}
5773
const totals = new Map<string, number>()
5874
for (const entry of timings.entries)
5975
totals.set(entry.name, (totals.get(entry.name) ?? 0) + entry.durationMs)

‎src/utils/stale-app-reload.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as Sentry from '@sentry/tanstackstart-react'
12
import {
23
getSessionStorageItem,
34
setSessionStorageItem,
@@ -77,6 +78,10 @@ export function reloadOnStaleAppError(error: unknown) {
7778
writeLastReloadAt(now)
7879
window.location.reload()
7980
markReloadedErrors(error)
81+
if (Sentry.isEnabled()) {
82+
Sentry.metrics.count('app.stale_reload', 1)
83+
void Sentry.flush(2_000)
84+
}
8085
return true
8186
}
8287

‎tests/request-timing.test.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import assert from 'node:assert/strict'
22
import { test } from 'node:test'
3+
import * as Sentry from '@sentry/tanstackstart-react'
34
import {
45
markRequestDatabaseUse,
56
timeRequestWork,
@@ -49,3 +50,53 @@ test('non-docs requests have no profiling headers', async () => {
4950
)
5051
assert.equal(response.headers.has('Server-Timing'), false)
5152
})
53+
54+
test('docs response timing is sent through the scheduled Sentry flush', async (t) => {
55+
const metricPayloads: unknown[] = []
56+
const client = new Sentry.NodeClient({
57+
dsn: 'https://fixture@example.invalid/1',
58+
integrations: [],
59+
stackParser: Sentry.defaultStackParser,
60+
transport: () => ({
61+
async send([, items]) {
62+
for (const [header, payload] of items) {
63+
if (header.type === 'trace_metric') metricPayloads.push(payload)
64+
}
65+
return { statusCode: 200 }
66+
},
67+
flush: async () => true,
68+
}),
69+
})
70+
t.after(() => client.close(100))
71+
72+
await Sentry.withScope(async (scope) => {
73+
scope.setClient(client)
74+
const pending: Array<Promise<boolean>> = []
75+
const response = await withDocsRequestTimings(
76+
request,
77+
async () => {
78+
markRequestDatabaseUse()
79+
return new Response(null, { status: 503 })
80+
},
81+
(flush) => pending.push(flush()),
82+
)
83+
84+
assert.equal(response.status, 503)
85+
assert.deepEqual(await Promise.all(pending), [true])
86+
assert.partialDeepStrictEqual(metricPayloads, [
87+
{
88+
items: [
89+
{
90+
name: 'docs.response.headers.duration',
91+
type: 'distribution',
92+
unit: 'millisecond',
93+
attributes: {
94+
'http.response.status_code': { type: 'integer', value: 503 },
95+
'docs.database_used': { type: 'boolean', value: true },
96+
},
97+
},
98+
],
99+
},
100+
])
101+
})
102+
})

‎tests/stale-app-reload.test.ts‎

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
import assert from 'node:assert/strict'
22
import test from 'node:test'
3-
import { BrowserClient, Scope, defaultStackParser } from '@sentry/browser'
3+
import {
4+
BrowserClient,
5+
Scope,
6+
defaultStackParser,
7+
getCurrentScope,
8+
} from '@sentry/browser'
49
import {
510
consumeStaleAppRecovery,
611
reloadOnStaleAppError,
@@ -33,14 +38,18 @@ test('Sentry suppresses recovered errors but reports cooldown failures', async (
3338
})
3439
t.mock.method(Date, 'now', () => now)
3540
let sent = 0
41+
let sentMetrics = 0
42+
const metrics: unknown[] = []
3643
const originals: unknown[] = []
3744
const client = new BrowserClient({
3845
dsn: 'https://fixture@example.invalid/1',
3946
integrations: [],
4047
stackParser: defaultStackParser,
4148
transport: () => ({
42-
send: async () => {
43-
sent++
49+
send: async ([, items]) => {
50+
if (items.some(([header]) => header.type === 'trace_metric'))
51+
sentMetrics++
52+
else sent++
4453
return { statusCode: 200 }
4554
},
4655
flush: async () => true,
@@ -49,10 +58,22 @@ test('Sentry suppresses recovered errors but reports cooldown failures', async (
4958
originals.push(hint.originalException)
5059
return consumeStaleAppRecovery(hint.originalException) ? null : event
5160
},
61+
beforeSendMetric(metric) {
62+
metrics.push({
63+
name: metric.name,
64+
type: metric.type,
65+
value: metric.value,
66+
})
67+
return metric
68+
},
5269
})
5370
t.after(() => client.close(100))
5471
const scope = new Scope()
5572
scope.setClient(client)
73+
const currentScope = getCurrentScope()
74+
const previousClient = currentScope.getClient()
75+
currentScope.setClient(client)
76+
t.after(() => currentScope.setClient(previousClient))
5677
const first = new Error('Failed to fetch dynamically imported module')
5778
assert.equal(reloadOnStaleAppError([first]), true)
5879
// 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 (
91112
const blocked = new Error(first.message)
92113
assert.throws(() => reloadOnStaleAppError(blocked), /reload blocked/)
93114
assert.equal(consumeStaleAppRecovery(blocked), false)
115+
const reloadMetric = { name: 'app.stale_reload', type: 'counter', value: 1 }
116+
assert.deepEqual(metrics, [reloadMetric, reloadMetric])
117+
assert.equal(sentMetrics, 2)
94118
})

0 commit comments

Comments
 (0)