vercel/next.js · #102018
Share trace-style truncation and gzip the Request Insights journal
packages/next/src/lib/rotating-file.tsadded70 + / 0 −
@@ -0,0 +1,70 @@+import fs from 'fs'+import path from 'path'++/**+ * Synchronous diagnostic output. Callers buffer complete records and choose when+ * to rotate, so a file boundary never silently changes their serialization state.+ * Flushed bytes survive process.exit(); this does not fsync against power loss.+ */+export class RotatingFile {+ private fd: number | undefined+ // Callers recovering an existing file can seed this before writing.+ size = 0++ constructor(+ readonly file: string,+ private readonly sizeLimit: number+ ) {}++ wouldExceed(bytes: number): boolean {+ return this.size + bytes > this.sizeLimit+ }++ /**+ * Open lazily: opening before dev-server cleanup would leave writes going to+ * an unlinked inode. The mode only applies when opening a new descriptor.+ */+ open(mode: 'a' | 'w' = 'a'): number {+ if (this.fd === undefined) {+ fs.mkdirSync(path.dirname(this.file), { recursive: true })+ const flags =+ fs.constants.O_WRONLY |+ fs.constants.O_CREAT |+ fs.constants.O_NOFOLLOW |+ (mode === 'a' ? fs.constants.O_APPEND : fs.constants.O_TRUNC)+ this.fd = fs.openSync(this.file, flags)+ }+ return this.fd+ }++ /** Discard the old contents when the size limit is reached. */+ rotate(): void {+ this.close()+ this.open('w')+ this.size = 0+ }++ write(data: Buffer, mode: 'a' | 'w' = 'a'): void {+ let offset = 0+ try {+ const fd = this.open(mode)+ // writeSync can write fewer than all the bytes.+ while (offset < data.length) {+ offset += fs.writeSync(fd, data, offset)+ }+ } finally {+ // Account for a partial write even if the caller handles an I/O error.+ this.size += offset+ }+ }++ close(): void {+ if (this.fd === undefined) return+ try {+ fs.closeSync(this.fd)+ } catch {+ // Nothing useful to do if the descriptor is already gone.+ }+ this.fd = undefined+ }+}packages/next/src/server/lib/router-server.ts1 + / 0 −
@@ -532,6 +532,7 @@ export async function initialize(opts: { requestId, kind, limit: 1,+ indexedOnly: true, }) res.statusCode = request ? 200 : 404 res.end(packages/next/src/server/lib/trace/request-insights-journal.ts347 + / 210 −
@@ -1,7 +1,11 @@ import { createReadStream } from 'fs'-import { appendFile, mkdir, stat, writeFile } from 'fs/promises'+import { stat } from 'fs/promises'+import { RotatingFile } from '../../../lib/rotating-file' import path from 'path' import { createInterface } from 'readline'+import { pipeline } from 'stream/promises'+import { promisify } from 'util'+import { createGunzip, gzip } from 'zlib' import { getRequestInsightKey, getRequestInsightKind,@@ -21,9 +25,12 @@ import { type RequestInsightSummary, } from '../../../shared/lib/request-insights-summary' +// History scans must stay bounded regardless of the journal's compression ratio.+const HISTORY_ENTRY_LIMIT = 1000 const JOURNAL_SIZE_LIMIT = 50 * 1024 * 1024 const JOURNAL_WRITE_BATCH_BYTES = 64 * 1024-const JOURNAL_FILENAME = 'request-insights.ndjson'+const JOURNAL_FILENAME = 'request-insights.ndjson.gz'+const compress = promisify(gzip) const REQUEST_INSIGHTS_JOURNAL_KEY = Symbol.for( `@next/request-insights-journal@${process.env.__NEXT_VERSION}` )@@ -38,6 +45,7 @@ type JournalFilter = { htmlRequestId?: string kind?: RequestInsight['kind'] limit?: number+ indexedOnly?: boolean } type HistoryFilter = {@@ -55,16 +63,48 @@ type IndexedSummary = { type PendingAppend = { line: string- byteLength: number key: string summary: RequestInsightSummary } type AppendBatch = {+ kind: 'append' records: PendingAppend[] byteLength: number } +type UpdateInput =+ | { kind: 'live'; request: RequestInsight }+ | { kind: 'archived' }++type PendingUpdate = {+ identity: Pick<RequestInsight, 'requestId' | 'kind'>+ key: string+ update: RequestInsightUpdate+} & (+ | {+ kind: 'live'+ request: RequestInsight+ spanCount: number+ fetchCount: number+ }+ | { kind: 'archived' }+)++type ArchivedUpdateBatch = {+ kind: 'archived-batch'+ key: string+ updates: Array<Extract<PendingUpdate, { kind: 'archived' }>>+ byteLength: number+}++type PendingWrite = AppendBatch | PendingUpdate | ArchivedUpdateBatch++type ArchivedRequest = {+ loaded: boolean+ request: RequestInsight | undefined+}+ type JournalCursor = { sessionId: string generation: number@@ -73,16 +113,19 @@ type JournalCursor = { class RequestInsightsJournal { private writes = Promise.resolve()- private pendingAppends: AppendBatch | undefined- private size = 0+ private pending: AppendBatch | ArchivedUpdateBatch | undefined+ private needsReset = false+ private readonly writer: RotatingFile private sequence = 0 private summaries = new Map<string, IndexedSummary>() private pendingRequests = new Set<string>() private sessionId = createSessionId() private generation = 0 private truncated = false - constructor(readonly file: string) {}+ constructor(readonly file: string) {+ this.writer = new RotatingFile(file, JOURNAL_SIZE_LIMIT)+ } append(request: RequestInsight): void { let line: string@@ -96,60 +139,80 @@ class RequestInsightsJournal { const summary = summarizeRequestInsight(request) const key = getRequestInsightKey(request) this.pendingRequests.add(key)- let batch = this.pendingAppends- if (!batch || batch.byteLength + byteLength > JOURNAL_WRITE_BATCH_BYTES) {- batch = { records: [], byteLength: 0 }- this.pendingAppends = batch- const queuedBatch = batch- this.writes = this.writes- .then(async () => {- if (this.pendingAppends === queuedBatch)- this.pendingAppends = undefined- await this.appendRequests(queuedBatch.records)- })- .catch((error) => {- console.warn('Failed to write Request Insights journal', error)- })- .finally(() => {- for (const record of queuedBatch.records) {- this.pendingRequests.delete(record.key)- }- })+ let batch = this.pending+ if (+ batch?.kind !== 'append' ||+ batch.byteLength + byteLength > JOURNAL_WRITE_BATCH_BYTES+ ) {+ batch = { kind: 'append', records: [], byteLength: 0 }+ this.enqueue(batch) }- batch.records.push({ line, byteLength, key, summary })+ batch.records.push({ line, key, summary }) batch.byteLength += byteLength } - private async appendRequests(records: PendingAppend[]): Promise<void> {- await this.ensureDirectory()- let index = 0- while (index < records.length) {- if (- this.size > 0 &&- this.size + records[index].byteLength > JOURNAL_SIZE_LIMIT- ) {- await this.rotate()- }- const start = index- let byteLength = 0- let lines = ''- do {- const record = records[index++]- lines += record.line- byteLength += record.byteLength- } while (- index < records.length &&- this.size + byteLength + records[index].byteLength <= JOURNAL_SIZE_LIMIT- )- await appendFile(this.file, lines, 'utf8')- this.size += byteLength- for (let i = start; i < index; i++) {- const record = records[i]- this.summaries.set(record.key, {- sequence: ++this.sequence,- request: record.summary,- })+ private enqueue(batch: PendingWrite): void {+ this.pending =+ batch.kind === 'append' || batch.kind === 'archived-batch'+ ? batch+ : undefined+ this.writes = this.writes.then(async () => {+ if (this.pending === batch) this.pending = undefined+ try {+ // Never prepare journal-only deltas against bytes damaged by a failed+ // member. A failed reset skips this batch and remains retryable.+ if (this.needsReset) {+ this.rotate()+ this.needsReset = false+ }+ if (batch.kind === 'append') {+ // Only completed requests share a gzip dictionary.+ this.write(+ await compress(batch.records.map(({ line }) => line).join(''))+ )+ for (const record of batch.records) {+ this.indexSummary(record.key, {+ sequence: ++this.sequence,+ request: record.summary,+ })+ }+ } else {+ // Share lazy replay, not compression: each late delta stays a member.+ const archive: ArchivedRequest = { loaded: false, request: undefined }+ const updates =+ batch.kind === 'archived-batch' ? batch.updates : [batch]+ for (const update of updates) {+ const prepared = await this.prepareUpdate(update, archive)+ if (!prepared) continue+ this.write(prepared.data)+ this.indexSummary(update.key, {+ sequence:+ this.summaries.get(update.key)?.sequence ?? ++this.sequence,+ request: prepared.summary,+ })+ }+ }+ } catch (error) {+ console.warn('Failed to write Request Insights journal', error)+ } finally {+ if (batch.kind === 'append') {+ for (const record of batch.records)+ this.pendingRequests.delete(record.key)+ } }+ })+ }++ private write(data: Buffer): void {+ try {+ if (this.writer.size > 0 && this.writer.wouldExceed(data.length))+ this.rotate()+ this.writer.write(data)+ } catch (error) {+ // Even an exception after a short write can leave a torn gzip member.+ // Do not index it or append another member until the file is reset.+ this.needsReset = true+ throw error } } @@ -161,159 +224,230 @@ class RequestInsightsJournal { if (!this.summaries.has(key) && !this.pendingRequests.has(key)) { return false }- this.appendUpdate(identity, update)+ this.appendUpdate(identity, update, { kind: 'archived' }) return true } appendUpdate( identity: Pick<RequestInsight, 'requestId' | 'kind'>, update: RequestInsightUpdate,- request?: RequestInsight+ source: UpdateInput ): void {- this.pendingAppends = undefined const key = getRequestInsightKey(identity)- // The live arrays keep growing while writes wait, so capture their lengths.- const snapshot = request && { ...request }- const filter = {- requestId: identity.requestId,- kind: getRequestInsightKind(identity),+ if (source.kind === 'live') {+ const { request } = source+ this.enqueue({+ kind: 'live',+ identity,+ key,+ update,+ request: { ...request },+ // Live arrays grow while queued writes wait; retain exact boundaries.+ spanCount: request.spans.length,+ fetchCount: request.fetches.length,+ })+ } else {+ let byteLength: number+ try {+ // Include framing overhead so even empty updates consume the budget.+ byteLength = Buffer.byteLength(JSON.stringify(update)) + 64+ } catch {+ return+ }+ let batch = this.pending+ if (+ batch?.kind !== 'archived-batch' ||+ batch.key !== key ||+ batch.byteLength + byteLength > JOURNAL_WRITE_BATCH_BYTES+ ) {+ batch = { kind: 'archived-batch', key, updates: [], byteLength: 0 }+ this.enqueue(batch)+ }+ batch.updates.push({ kind: 'archived', identity, key, update })+ batch.byteLength += byteLength }- const spanCount = request?.spans.length- const fetchCount = request?.fetches.length- this.writes = this.writes- .then(async () => {- const previous = this.summaries.get(key)?.request- if (!previous && !snapshot) {- return- }- const { span } = update- let { fetch } = update- let archived: RequestInsight | undefined- if (!snapshot && fetch) {- archived = (await readJournalFile(this.file, filter))[0]- if (!archived) return- if (- archived.fetches.some((existing) =>- isSameRequestInsightFetch(existing, fetch!)- )- ) {- fetch = undefined- }- }- if (!span && !fetch) return+ } - const metadata = getRequestMetadata(snapshot ?? previous!)- if (span?.status === 'error') metadata.status = 'error'- else if (metadata.status !== 'error' && span?.status === 'ok')- metadata.status = 'ok'- const summary = summarizeRequestInsight({- ...metadata,- spans: span ? [span] : [],- fetches: fetch ? [fetch] : [],- })- let line = `${JSON.stringify({ version: 2, request: metadata, span, fetch } satisfies JournalRecord)}\n`- let updatedSummary: RequestInsightSummary = {- ...summary,- spanCount: spanCount ?? (previous?.spanCount ?? 0) + (span ? 1 : 0),- fetchCount:- fetchCount ?? (previous?.fetchCount ?? 0) + (fetch ? 1 : 0),- statusCode: previous?.statusCode ?? summary.statusCode,- isRsc: previous?.isRsc ?? summary.isRsc,- hasError: !!previous?.hasError || summary.hasError,- hasProxyActivity:- !!previous?.hasProxyActivity || summary.hasProxyActivity,- cacheStatuses: [- ...new Set([- ...(previous?.cacheStatuses ?? []),- ...summary.cacheStatuses,- ]),- ],- }- if (- span?.attributes?.['next.span_type'] ===- REQUEST_INSIGHT_REQUEST_SPAN_TYPE- ) {- archived ??= snapshot ?? (await readJournalFile(this.file, filter))[0]- if (!archived) return- const canonicalSummary = summarizeRequestInsight({- ...metadata,- spans: snapshot- ? snapshot.spans.slice(0, spanCount)- : [...archived.spans, span],- fetches: [],+ private async prepareUpdate(+ batch: PendingUpdate,+ archive: ArchivedRequest+ ): Promise<{ data: Buffer; summary: RequestInsightSummary } | undefined> {+ const previous = this.summaries.get(batch.key)?.request+ const request = batch.kind === 'live' ? batch.request : previous+ // Truncation (including error recovery) discards journal-only delta bases.+ if (!request) return+ const { span } = batch.update+ let { fetch } = batch.update+ const loadArchived = async () => {+ if (!archive.loaded) {+ archive.request = (+ await readJournalFile(this.file, {+ requestId: batch.identity.requestId,+ kind: getRequestInsightKind(batch.identity), })- updatedSummary.statusCode = canonicalSummary.statusCode- updatedSummary.isRsc = canonicalSummary.isRsc- }- if (- !previous ||- this.size + Buffer.byteLength(line, 'utf8') > JOURNAL_SIZE_LIMIT- ) {- let fullRequest: RequestInsight- if (snapshot) {- fullRequest = {- ...snapshot,- spans: snapshot.spans.slice(0, spanCount),- fetches: snapshot.fetches.slice(0, fetchCount),- }- } else {- archived ??= (await readJournalFile(this.file, filter))[0]- if (!archived) return- fullRequest = { ...archived, ...metadata }- if (span) fullRequest.spans.push(span)- if (fetch) fullRequest.fetches.push(fetch)- }- line = `${JSON.stringify({ version: 1, request: fullRequest } satisfies JournalRecord)}\n`- updatedSummary = summarizeRequestInsight(fullRequest)+ )[0]+ archive.loaded = true+ }+ return archive.request+ }+ if (batch.kind === 'archived' && fetch) {+ const stored = await loadArchived()+ if (!stored) return+ const candidate = fetch+ if (+ stored.fetches.some((existing) =>+ isSameRequestInsightFetch(existing, candidate)+ )+ )+ fetch = undefined+ }+ if (!span && !fetch) return+ let canonicalSpans: RequestInsight['spans'] | undefined+ if (+ span?.attributes?.['next.span_type'] === REQUEST_INSIGHT_REQUEST_SPAN_TYPE+ ) {+ if (batch.kind === 'live') {+ canonicalSpans = batch.request.spans.slice(0, batch.spanCount)+ } else {+ const stored = await loadArchived()+ if (!stored) return+ canonicalSpans = [...stored.spans, span]+ }+ }+ const metadata = getRequestMetadata(request)+ if (span?.status === 'error') metadata.status = 'error'+ else if (metadata.status !== 'error' && span?.status === 'ok')+ metadata.status = 'ok'+ const delta = summarizeRequestInsight({+ ...metadata,+ spans: span ? [span] : [],+ fetches: fetch ? [fetch] : [],+ })+ let summary: RequestInsightSummary = {+ ...delta,+ spanCount:+ batch.kind === 'live'+ ? batch.spanCount+ : (previous?.spanCount ?? 0) + (span ? 1 : 0),+ fetchCount:+ batch.kind === 'live'+ ? batch.fetchCount+ : (previous?.fetchCount ?? 0) + (fetch ? 1 : 0),+ statusCode: previous?.statusCode ?? delta.statusCode,+ isRsc: previous?.isRsc ?? delta.isRsc,+ hasError: !!previous?.hasError || delta.hasError,+ hasProxyActivity: !!previous?.hasProxyActivity || delta.hasProxyActivity,+ cacheStatuses: [+ ...new Set([+ ...(previous?.cacheStatuses ?? []),+ ...delta.cacheStatuses,+ ]),+ ],+ }+ if (canonicalSpans) {+ const canonical = summarizeRequestInsight({+ ...metadata,+ spans: canonicalSpans,+ fetches: [],+ })+ summary.statusCode = canonical.statusCode+ summary.isRsc = canonical.isRsc+ }+ let data = await compress(+ `${JSON.stringify({ version: 2, request: metadata, span, fetch } satisfies JournalRecord)}\n`+ )+ if (!previous || this.writer.wouldExceed(data.length)) {+ let fullRequest: RequestInsight+ if (batch.kind === 'live') {+ fullRequest = {+ ...batch.request,+ ...metadata,+ spans: batch.request.spans.slice(0, batch.spanCount),+ fetches: batch.request.fetches.slice(0, batch.fetchCount), }- const byteLength = Buffer.byteLength(line, 'utf8')- await this.ensureDirectory()- if (this.size > 0 && this.size + byteLength > JOURNAL_SIZE_LIMIT) {- await this.rotate()+ } else {+ const stored = await loadArchived()+ if (!stored) return+ fullRequest = {+ ...stored,+ ...metadata,+ spans: span ? [...stored.spans, span] : stored.spans,+ fetches: fetch ? [...stored.fetches, fetch] : stored.fetches, }- await appendFile(this.file, line, 'utf8')- this.size += byteLength- this.summaries.set(key, {- sequence: this.summaries.get(key)?.sequence ?? ++this.sequence,- request: updatedSummary,- })- })- .catch((error) => {- console.warn('Failed to write Request Insights journal', error)- })+ }+ data = await compress(+ `${JSON.stringify({ version: 1, request: fullRequest } satisfies JournalRecord)}\n`+ )+ summary = summarizeRequestInsight(fullRequest)+ }+ // Earlier span-only updates are on disk before the first replay. Once+ // loaded, keep the shared record current for deduplication and rotation.+ if (archive.request) {+ Object.assign(archive.request, metadata)+ if (span) archive.request.spans.push(span)+ if (fetch) archive.request.fetches.push(fetch)+ }+ return { data, summary } } - private async rotate(): Promise<void> {- await writeFile(this.file, '')- this.size = 0+ private indexSummary(key: string, summary: IndexedSummary): void {+ this.summaries.set(key, summary)+ if (this.summaries.size > HISTORY_ENTRY_LIMIT) {+ // Map insertion order preserves the oldest entry even when late updates+ // replace its summary. Internal requests count toward the same budget.+ this.summaries.delete(this.summaries.keys().next().value!)+ this.truncated = true+ }+ }++ private rotate(): void {+ this.writer.rotate() this.summaries.clear() this.generation++ this.truncated = true } async initialize(): Promise<void> { await this.flush()- await this.ensureDirectory()- await writeFile(this.file, '')- this.size = 0+ this.writer.rotate()+ this.writer.close() this.sequence = 0 this.summaries.clear() this.sessionId = createSessionId() this.generation = 0 this.truncated = false+ this.needsReset = false } async configure(): Promise<void> {- await this.ensureDirectory()+ await this.flush()+ this.writer.close()+ this.writer.size = 0 try {- this.size = (await stat(this.file)).size+ this.writer.size = (await stat(this.file)).size } catch (error: any) { if (error.code !== 'ENOENT') { throw error } } } + async read(filter: JournalFilter): Promise<RequestInsight[]> {+ await this.flush()+ if (filter.indexedOnly) {+ const { requestId } = filter+ if (requestId === undefined) return []+ const kind = getRequestInsightKind(filter)+ // Detail misses must not replay the journal. Internal readers can still+ // access disk records whose summaries were evicted from the index.+ if (!this.summaries.has(getRequestInsightKey({ requestId, kind }))) {+ return []+ }+ filter = { ...filter, kind }+ }+ return readJournalFile(this.file, filter)+ }+ async getHistory( filter: HistoryFilter = {} ): Promise<RequestInsightsHistoryPage> {@@ -397,12 +531,13 @@ class RequestInsightsJournal { } flush(): Promise<void> {- this.pendingAppends = undefined+ this.pending = undefined return this.writes } - private async ensureDirectory(): Promise<void> {- await mkdir(path.dirname(this.file), { recursive: true })+ async close(): Promise<void> {+ await this.flush()+ this.writer.close() } } @@ -423,7 +558,10 @@ export function appendRequestInsightUpdateToJournal( request: RequestInsight, update: RequestInsightUpdate ): void {- getJournalRegistry().configured?.appendUpdate(request, update, request)+ getJournalRegistry().configured?.appendUpdate(request, update, {+ kind: 'live',+ request,+ }) } export function appendArchivedRequestInsightUpdateToJournal(@@ -447,9 +585,7 @@ export async function readRequestInsightsJournal( distDir: string, filter: JournalFilter = {} ): Promise<RequestInsight[]> {- const journal = getOrCreateRequestInsightsJournal(distDir)- await journal.flush()- return readJournalFile(journal.file, filter)+ return getOrCreateRequestInsightsJournal(distDir).read(filter) } async function readJournalFile(@@ -459,41 +595,42 @@ async function readJournalFile( if (filter.limit !== undefined && filter.limit <= 0) return [] const matches = new Map<string, RequestInsight>() try {- const lines = createInterface({- input: createReadStream(file, { encoding: 'utf8' }),- crlfDelay: Infinity,- })-- for await (const line of lines) {- const record = parseJournalLine(line)- if (!record) continue- const request = record.request- if (- (filter.requestId !== undefined &&- request.requestId !== filter.requestId) ||- (filter.htmlRequestId !== undefined &&- request.htmlRequestId !== filter.htmlRequestId) ||- (filter.kind !== undefined &&- getRequestInsightKind(request) !== filter.kind)- ) {- continue- }-- const key = getRequestInsightKey(request)- if (record.version === 1) {- matches.set(key, record.request)- if (filter.limit !== undefined && matches.size > filter.limit) {- matches.delete(matches.keys().next().value!)+ // Initialization leaves an empty file until the first completed record.+ if ((await stat(file)).size === 0) return []+ const input = createGunzip()+ await pipeline(createReadStream(file), input, async () => {+ const lines = createInterface({ input, crlfDelay: Infinity })+ for await (const line of lines) {+ const record = parseJournalLine(line)+ if (!record) continue+ const request = record.request+ if (+ (filter.requestId !== undefined &&+ request.requestId !== filter.requestId) ||+ (filter.htmlRequestId !== undefined &&+ request.htmlRequestId !== filter.htmlRequestId) ||+ (filter.kind !== undefined &&+ getRequestInsightKind(request) !== filter.kind)+ ) {+ continue }- } else {- const stored = matches.get(key)- if (stored) {- Object.assign(stored, request)- if (record.span) stored.spans.push(record.span)- if (record.fetch) stored.fetches.push(record.fetch)++ const key = getRequestInsightKey(request)+ if (record.version === 1) {+ matches.set(key, record.request)+ if (filter.limit !== undefined && matches.size > filter.limit) {+ matches.delete(matches.keys().next().value!)+ }+ } else {+ const stored = matches.get(key)+ if (stored) {+ Object.assign(stored, request)+ if (record.span) stored.spans.push(record.span)+ if (record.fetch) stored.fetches.push(record.fetch)+ } } }- }+ }) } catch (error: any) { if (error.code !== 'ENOENT') { console.warn('Failed to read Request Insights journal', error)@@ -510,7 +647,7 @@ export async function resetRequestInsightsJournalForTest(): Promise<void> { export async function closeRequestInsightsJournal(): Promise<void> { const registry = getJournalRegistry() await Promise.all(- [...registry.journals.values()].map((journal) => journal.flush())+ [...registry.journals.values()].map((journal) => journal.close()) ) // TODO(as-any): pre-existing cast, not yet reviewed // eslint-disable-next-line @next/internal/no-as-anypackages/next/src/server/lib/trace/request-insights.test.ts478 + / 83 −
@@ -28,7 +28,8 @@ import { resolveRequestInsightsIdentity, runWithRequestInsightsIdentity, } from './request-insights-identity'-import { mkdtemp, readFile, rm } from 'fs/promises'+import { mkdtemp, readFile, rm, symlink, writeFile } from 'fs/promises'+import { gunzipSync, gzipSync } from 'zlib' import { tmpdir } from 'os' import path from 'path' import { MAX_LIVE_COMPLETED_REQUEST_INSIGHTS } from '../../../shared/lib/request-insights'@@ -583,9 +584,10 @@ describe('request insights', () => { }) clearRequestInsightsForTest()- expect(- await readRequestInsightsJournal(distDir, { requestId: 'journaled' })- ).toEqual([+ const persisted = await readRequestInsightsJournal(distDir, {+ requestId: 'journaled',+ })+ expect(persisted).toEqual([ expect.objectContaining({ requestId: 'journaled', htmlRequestId: 'document',@@ -738,7 +740,7 @@ describe('request insights', () => { const fs = require('fs/promises') as typeof import('fs/promises') const currentStat = await fs.stat(- path.join(distDir, 'request-insights.ndjson')+ path.join(distDir, 'request-insights.ndjson.gz') ) const stat = jest.spyOn(fs, 'stat') stat.mockResolvedValueOnce({ ...currentStat, size: 50 * 1024 * 1024 })@@ -774,6 +776,180 @@ describe('request insights', () => { } ) + it('shares one journal replay across a burst of archived fetch updates', async () => {+ process.env.__NEXT_REQUEST_INSIGHTS = 'true'+ const distDir = await mkdtemp(path.join(tmpdir(), 'request-insights-'))+ const fs = require('fs') as typeof import('fs')+ try {+ await initializeRequestInsightsJournal(distDir)+ configureJournalProvider(distDir)+ startRequestInsight({ requestId: 'archived-burst' })+ recordSpan({ name: 'original', requestId: 'archived-burst' })+ const fetch = { url: 'https://example.com/data', index: 0 }+ recordRequestInsightFetch({ requestId: 'archived-burst' }, fetch)+ completeRequestInsight({ requestId: 'archived-burst' })+ await getRequestInsightsHistory(distDir)+ clearRequestInsightsForTest()++ const createReadStream = jest.spyOn(fs, 'createReadStream')+ const write = jest.spyOn(fs, 'writeSync')+ try {+ // A span before the first lazy replay is already on disk when it loads.+ recordSpan({ name: 'before fetches', requestId: 'archived-burst' })+ for (let index = 0; index < 16; index++) {+ const lateFetch = { ...fetch, index }+ recordRequestInsightFetch({ requestId: 'archived-burst' }, lateFetch)+ recordRequestInsightFetch({ requestId: 'archived-burst' }, lateFetch)+ }+ recordSpan({ name: 'after fetches', requestId: 'archived-burst' })+ recordSpan({+ name: 'GET /',+ requestId: 'archived-burst',+ attributes: {+ 'next.span_type': 'BaseServer.handleRequest',+ 'http.status_code': 200,+ },+ })+ const history = await getRequestInsightsHistory(distDir)+ expect(history.requests[0]).toMatchObject({+ fetchCount: 16,+ spanCount: 4,+ statusCode: 200,+ })+ expect(createReadStream).toHaveBeenCalledTimes(1)+ // Accepted late updates still have independent compressed writes.+ expect(write).toHaveBeenCalledTimes(18)+ } finally {+ createReadStream.mockRestore()+ write.mockRestore()+ }+ const [stored] = await readRequestInsightsJournal(distDir, {+ requestId: 'archived-burst',+ })+ expect(stored.fetches).toEqual(+ Array.from({ length: 16 }, (_, index) => ({ ...fetch, index }))+ )+ expect(stored.spans.map(({ name }) => name)).toEqual([+ 'original',+ 'before fetches',+ 'after fetches',+ 'GET /',+ ])+ } finally {+ await resetRequestInsightsJournalForTest()+ await rm(distDir, { recursive: true, force: true })+ }+ })++ it.each(['bytes', 'identity'] as const)(+ 'bounds archived replay sharing across %s boundaries',+ async (boundary) => {+ process.env.__NEXT_REQUEST_INSIGHTS = 'true'+ startRequestInsight({ requestId: 'bounded-burst' })+ recordSpan({ name: 'original', requestId: 'bounded-burst' })+ const request = getRequestInsightsSnapshot().requests[0]+ const other = {+ ...request,+ requestId: 'other',+ kind: 'instant-insights' as const,+ }+ const fetch = (index: number) => ({+ url: 'https://example.com/data',+ index,+ cacheReason: boundary === 'bytes' ? 'x'.repeat(17 * 1024) : '',+ })+ const append = (index: number, identity = request) => {+ expect(+ appendArchivedRequestInsightUpdateToJournal(identity, {+ fetch: fetch(index),+ })+ ).toBe(true)+ }+ const distDir = await mkdtemp(path.join(tmpdir(), 'request-insights-'))+ const fs = require('fs') as typeof import('fs')+ try {+ await initializeRequestInsightsJournal(distDir)+ appendRequestInsightToJournal(request)+ if (boundary === 'identity') appendRequestInsightToJournal(other)+ await getRequestInsightsHistory(distDir)+ const createReadStream = jest.spyOn(fs, 'createReadStream')+ try {+ append(0)+ append(1)+ if (boundary === 'identity') append(0, other)+ append(2)+ append(3)+ await getRequestInsightsHistory(distDir)+ expect(createReadStream).toHaveBeenCalledTimes(+ boundary === 'identity' ? 3 : 2+ )+ } finally {+ createReadStream.mockRestore()+ }+ const [stored] = await readRequestInsightsJournal(distDir, {+ requestId: request.requestId,+ kind: 'request',+ })+ expect(stored.fetches).toEqual([fetch(0), fetch(1), fetch(2), fetch(3)])+ } finally {+ await resetRequestInsightsJournalForTest()+ await rm(distDir, { recursive: true, force: true })+ }+ }+ )++ it('discards shared archived state after a torn update write', async () => {+ process.env.__NEXT_REQUEST_INSIGHTS = 'true'+ startRequestInsight({ requestId: 'torn-burst' })+ recordSpan({ name: 'original', requestId: 'torn-burst' })+ const request = getRequestInsightsSnapshot().requests[0]+ const distDir = await mkdtemp(path.join(tmpdir(), 'request-insights-'))+ const fs = require('fs') as typeof import('fs')+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ await initializeRequestInsightsJournal(distDir)+ appendRequestInsightToJournal(request)+ await getRequestInsightsHistory(distDir)+ const originalWrite = fs.writeSync+ const write = jest+ .spyOn(fs, 'writeSync')+ .mockImplementationOnce(originalWrite)+ .mockImplementationOnce((fd, data) => {+ if (!Buffer.isBuffer(data)) throw new Error('expected a gzip buffer')+ originalWrite(fd, data, 0, 16)+ throw new Error('simulated torn archived update')+ })+ const append = (index: number) => {+ expect(+ appendArchivedRequestInsightUpdateToJournal(request, {+ fetch: { url: 'https://example.com/data', index },+ })+ ).toBe(true)+ }+ try {+ append(0)+ append(1)+ append(2)+ appendRequestInsightToJournal({ ...request, requestId: 'healthy' })+ append(3)+ const history = await getRequestInsightsHistory(distDir)+ expect(history.requests.map(({ requestId }) => requestId)).toEqual([+ 'healthy',+ ])+ expect(warn).toHaveBeenCalledTimes(1)+ } finally {+ write.mockRestore()+ }+ expect(await readRequestInsightsJournal(distDir)).toEqual([+ { ...request, requestId: 'healthy' },+ ])+ } finally {+ warn.mockRestore()+ await resetRequestInsightsJournalForTest()+ await rm(distDir, { recursive: true, force: true })+ }+ })+ it('writes late spans without serializing previously stored spans again', async () => { process.env.__NEXT_REQUEST_INSIGHTS = 'true' startRequestInsight({ requestId: 'delta' })@@ -788,108 +964,271 @@ describe('request insights', () => { completeRequestInsight({ requestId: 'delta' }) await getRequestInsightsHistory(distDir) serialize.mockClear()- for (let i = 0; i < 10; i++) {+ const updateCount = 3+ for (let i = 0; i < updateCount; i++) { recordSpan({ name: 'late work', requestId: 'delta' }) } expect( (await readRequestInsightsJournal(distDir, { requestId: 'delta' }))[0] .spans- ).toHaveLength(11)+ ).toHaveLength(updateCount + 1) expect( (await getRequestInsightsHistory(distDir)).requests[0].spanCount- ).toBe(11)+ ).toBe(updateCount + 1) expect(serialize).not.toHaveBeenCalled() await resetRequestInsightsJournalForTest() await rm(distDir, { recursive: true, force: true }) }) - it('batches completed requests without moving them across a late update', async () => {+ it.each([false, true])(+ 'truncates only before a whole compressed batch, exceeds: %s',+ async (exceeds) => {+ process.env.__NEXT_REQUEST_INSIGHTS = 'true'+ startRequestInsight({ requestId: 'seed' })+ recordSpan({ name: 'render', requestId: 'seed' })+ const request = getRequestInsightsSnapshot().requests[0]+ const records = ['one', 'two', 'tri'].map((requestId) => ({+ ...request,+ requestId,+ }))+ const batch = gzipSync(+ records+ .map((entry) => JSON.stringify({ version: 1, request: entry }) + '\n')+ .join('')+ )+ const distDir = await mkdtemp(+ path.join(tmpdir(), 'request-insights-batch-')+ )+ const fs = require('fs/promises') as typeof import('fs/promises')+ await initializeRequestInsightsJournal(distDir)+ const currentStat = await fs.stat(+ path.join(distDir, 'request-insights.ndjson.gz')+ )+ const stat = jest.spyOn(fs, 'stat').mockResolvedValueOnce({+ ...currentStat,+ size: 50 * 1024 * 1024 - batch.length + (exceeds ? 1 : 0),+ })+ try {+ await configureRequestInsightsJournal(distDir)+ stat.mockRestore()+ for (const record of records) appendRequestInsightToJournal(record)++ const history = await getRequestInsightsHistory(distDir)+ expect(history.truncated).toBe(exceeds)+ expect(history.requests.map((entry) => entry.requestId)).toEqual([+ 'tri',+ 'two',+ 'one',+ ])+ expect(+ (await readRequestInsightsJournal(distDir)).map(+ (entry) => entry.requestId+ )+ ).toEqual(['one', 'two', 'tri'])+ // A completed batch is one compressed write, never split at the limit.+ expect(+ await readFile(path.join(distDir, 'request-insights.ndjson.gz'))+ ).toEqual(batch)+ } finally {+ stat.mockRestore()+ await resetRequestInsightsJournalForTest()+ await rm(distDir, { recursive: true, force: true })+ }+ }+ )++ it('does not replay the journal for an indexed detail miss', async () => { process.env.__NEXT_REQUEST_INSIGHTS = 'true'- const distDir = await mkdtemp(- path.join(tmpdir(), 'request-insights-batch-')- )- await initializeRequestInsightsJournal(distDir)- configureJournalProvider(distDir)- const fs = require('fs/promises') as typeof import('fs/promises')- const append = jest.spyOn(fs, 'appendFile')+ startRequestInsight({ requestId: 'indexed' })+ recordSpan({ name: 'render', requestId: 'indexed' })+ const request = getRequestInsightsSnapshot().requests[0]+ const distDir = await mkdtemp(path.join(tmpdir(), 'request-insights-'))+ const fs = require('fs') as typeof import('fs') try {- for (let i = 0; i < 8; i++) {- const identity = { requestId: `batch-${i}` }- startRequestInsight(identity)- recordSpan({ name: 'render', requestId: identity.requestId })- completeRequestInsight(identity)+ await initializeRequestInsightsJournal(distDir)+ appendRequestInsightToJournal(request)+ await getRequestInsightsHistory(distDir)+ const createReadStream = jest.spyOn(fs, 'createReadStream')+ try {+ await expect(+ readRequestInsightsJournal(distDir, {+ requestId: 'missing',+ indexedOnly: true,+ })+ ).resolves.toEqual([])+ expect(createReadStream).not.toHaveBeenCalled()+ } finally {+ createReadStream.mockRestore() }- recordSpan({ name: 'late work', requestId: 'batch-0' })- startRequestInsight({ requestId: 'last' })- recordSpan({ name: 'render', requestId: 'last' })- completeRequestInsight({ requestId: 'last' })- await closeRequestInsightsJournal()-- expect(append).toHaveBeenCalledTimes(3)- const records = (- await readFile(path.join(distDir, 'request-insights.ndjson'), 'utf8')- )- .trim()- .split('\n')- .map((line) => JSON.parse(line))- expect(records.map((record) => record.request.requestId)).toEqual([- ...Array.from({ length: 8 }, (_, i) => `batch-${i}`),- 'batch-0',- 'last',- ])- expect(- (await readRequestInsightsJournal(distDir, { requestId: 'batch-0' }))[0]- .spans- ).toHaveLength(2) } finally {- append.mockRestore() await resetRequestInsightsJournalForTest() await rm(distDir, { recursive: true, force: true }) } }) - it('rotates between records inside a completed-request batch', async () => {+ it.each(['queued', 'live', 'archived', 'reset failure', 'initialize'])(+ 'recovers from a torn gzip write before the next batch: %s',+ async (resume) => {+ process.env.__NEXT_REQUEST_INSIGHTS = 'true'+ startRequestInsight({ requestId: 'seed' })+ recordSpan({ name: 'original', requestId: 'seed' })+ const request = getRequestInsightsSnapshot().requests[0]+ const distDir = await mkdtemp(path.join(tmpdir(), 'request-insights-'))+ const fs = require('fs') as typeof import('fs')+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ await initializeRequestInsightsJournal(distDir)+ appendRequestInsightToJournal(request)+ appendRequestInsightToJournal({ ...request, requestId: 'older' })+ const before = await getRequestInsightsHistory(distDir, { limit: 1 })+ expect(before.nextCursor).toBeDefined()++ const originalWrite = fs.writeSync+ const write = jest+ .spyOn(fs, 'writeSync')+ .mockImplementationOnce((fd, data) => {+ if (!Buffer.isBuffer(data))+ throw new Error('expected a gzip buffer')+ originalWrite(fd, data, 0, 16)+ throw new Error('simulated disk full after a partial write')+ })+ try {+ appendRequestInsightToJournal({ ...request, requestId: 'failed' })+ const failedFlush = getRequestInsightsHistory(distDir)+ if (resume === 'queued') {+ appendRequestInsightToJournal({ ...request, requestId: 'healthy' })+ }+ const afterFailure = await failedFlush+ expect(+ afterFailure.requests.map(({ requestId }) => requestId)+ ).not.toContain('failed')+ } finally {+ write.mockRestore()+ }+ expect(warn).toHaveBeenCalledTimes(1)+ const late = { ...request.spans[0], name: 'late' }+ const updated = { ...request, spans: [...request.spans, late] }+ if (resume === 'reset failure') {+ const open = jest.spyOn(fs, 'openSync').mockImplementationOnce(() => {+ throw new Error('simulated reset failure')+ })+ try {+ appendRequestInsightToJournal({ ...request, requestId: 'skipped' })+ await getRequestInsightsHistory(distDir)+ } finally {+ open.mockRestore()+ }+ expect(warn).toHaveBeenCalledTimes(2)+ expect(+ appendArchivedRequestInsightUpdateToJournal(+ { requestId: 'skipped' },+ { span: late }+ )+ ).toBe(false)+ }+ if (resume === 'initialize')+ await initializeRequestInsightsJournal(distDir)+ if (resume === 'live') {+ appendRequestInsightUpdateToJournal(updated, { span: late })+ } else {+ if (resume === 'archived') {+ expect(+ appendArchivedRequestInsightUpdateToJournal(request, {+ span: late,+ })+ ).toBe(true)+ }+ if (resume !== 'queued')+ appendRequestInsightToJournal({ ...request, requestId: 'healthy' })+ }+ const history = await getRequestInsightsHistory(distDir)+ expect(history.truncated).toBe(resume !== 'initialize')+ const expected =+ resume === 'live' ? updated : { ...request, requestId: 'healthy' }+ expect(history.requests.map(({ requestId }) => requestId)).toEqual([+ expected.requestId,+ ])+ await expect(+ readRequestInsightsJournal(distDir, {+ requestId: expected.requestId,+ indexedOnly: true,+ })+ ).resolves.toEqual([expected])+ // Independently decode the entire file, not just an indexed match.+ expect(+ gunzipSync(+ await readFile(path.join(distDir, 'request-insights.ndjson.gz'))+ ).toString()+ ).toContain(expected.requestId)+ await expect(+ getRequestInsightsHistory(distDir, { cursor: before.nextCursor })+ ).rejects.toBeInstanceOf(StaleRequestInsightsHistoryCursorError)+ } finally {+ warn.mockRestore()+ await resetRequestInsightsJournalForTest()+ await rm(distDir, { recursive: true, force: true })+ }+ }+ )++ // @force-gate !windows+ it('does not follow a symlink while recovering a failed open', async () => { process.env.__NEXT_REQUEST_INSIGHTS = 'true' startRequestInsight({ requestId: 'seed' })- recordSpan({ name: 'render', requestId: 'seed' })+ recordSpan({ name: 'original', requestId: 'seed' }) const request = getRequestInsightsSnapshot().requests[0]- const records = ['one', 'two', 'tri'].map((requestId) => ({- ...request,- requestId,- }))- const firstLineBytes = Buffer.byteLength(- JSON.stringify({ version: 1, request: records[0] }) + '\n'- )- const distDir = await mkdtemp(- path.join(tmpdir(), 'request-insights-batch-')- )- const fs = require('fs/promises') as typeof import('fs/promises')- await initializeRequestInsightsJournal(distDir)- const currentStat = await fs.stat(- path.join(distDir, 'request-insights.ndjson')- )- const stat = jest.spyOn(fs, 'stat').mockResolvedValueOnce({- ...currentStat,- size: 50 * 1024 * 1024 - firstLineBytes,- })+ const distDir = await mkdtemp(path.join(tmpdir(), 'request-insights-'))+ const journal = path.join(distDir, 'request-insights.ndjson.gz')+ const target = path.join(distDir, 'target')+ const contents = 'must not be truncated'+ const fs = require('fs') as typeof import('fs')+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}) try {- await configureRequestInsightsJournal(distDir)- stat.mockRestore()- for (const record of records) appendRequestInsightToJournal(record)+ await initializeRequestInsightsJournal(distDir)+ await rm(journal)+ await writeFile(target, contents) - const history = await getRequestInsightsHistory(distDir)- expect(history.truncated).toBe(true)- expect(history.requests.map((entry) => entry.requestId)).toEqual([- 'tri',- 'two',- ])- expect(- (await readRequestInsightsJournal(distDir)).map(- (entry) => entry.requestId- )- ).toEqual(['two', 'tri'])+ const open = jest.spyOn(fs, 'openSync').mockImplementationOnce(() => {+ throw new Error('simulated open failure')+ })+ try {+ appendRequestInsightToJournal(request)+ await getRequestInsightsHistory(distDir)+ } finally {+ open.mockRestore()+ }++ await symlink(target, journal)+ appendRequestInsightToJournal({ ...request, requestId: 'next' })+ await getRequestInsightsHistory(distDir)++ expect(await readFile(target, 'utf8')).toBe(contents) } finally {- stat.mockRestore()+ warn.mockRestore()+ await resetRequestInsightsJournalForTest()+ await rm(distDir, { recursive: true, force: true })+ }+ })++ it('handles missing, empty and damaged gzip journals without rejecting reads', async () => {+ const distDir = await mkdtemp(path.join(tmpdir(), 'request-insights-'))+ const file = path.join(distDir, 'request-insights.ndjson.gz')+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ await expect(readRequestInsightsJournal(distDir)).resolves.toEqual([])+ await writeFile(file, '')+ await expect(readRequestInsightsJournal(distDir)).resolves.toEqual([])+ expect(warn).not.toHaveBeenCalled()+ for (const data of [+ Buffer.from('not gzip'),+ gzipSync('not a record\n').subarray(0, -4),+ ]) {+ await writeFile(file, data)+ await expect(readRequestInsightsJournal(distDir)).resolves.toEqual([])+ }+ expect(warn).toHaveBeenCalledTimes(2)+ } finally {+ warn.mockRestore() await resetRequestInsightsJournalForTest() await rm(distDir, { recursive: true, force: true }) }@@ -910,7 +1249,7 @@ describe('request insights', () => { const fs = require('fs/promises') as typeof import('fs/promises') const currentStat = await fs.stat(- path.join(distDir, 'request-insights.ndjson')+ path.join(distDir, 'request-insights.ndjson.gz') ) const stat = jest.spyOn(fs, 'stat') stat.mockResolvedValueOnce({ ...currentStat, size: 50 * 1024 * 1024 })@@ -974,12 +1313,14 @@ describe('request insights', () => { await rm(distDir, { recursive: true, force: true }) }) - it('resets session history on initialization and stores the journal directly in distDir', async () => {+ it('resets session history and recreates the journal after startup cleanup', async () => { process.env.__NEXT_REQUEST_INSIGHTS = 'true' startRequestInsight({ requestId: 'history' }) const distDir = await mkdtemp(path.join(tmpdir(), 'request-insights-')) await initializeRequestInsightsJournal(distDir) configureJournalProvider(distDir)+ // The bundler cleans its output after journal initialization.+ await rm(path.join(distDir, 'request-insights.ndjson.gz')) recordSpan({ name: 'GET /history',@@ -995,7 +1336,9 @@ describe('request insights', () => { }) ) expect(- await readFile(path.join(distDir, 'request-insights.ndjson'), 'utf8')+ gunzipSync(+ await readFile(path.join(distDir, 'request-insights.ndjson.gz'))+ ).toString('utf8') ).toContain('"requestId":"history"') await initializeRequestInsightsJournal(distDir)@@ -1075,6 +1418,58 @@ describe('request insights', () => { await rm(distDir, { recursive: true, force: true }) }) + it('bounds history across append and update insertions', async () => {+ process.env.__NEXT_REQUEST_INSIGHTS = 'true'+ startRequestInsight({ requestId: 'seed' })+ recordSpan({ name: 'render', requestId: 'seed' })+ const seed = getRequestInsightsSnapshot().requests[0]+ const request = (index: number) => ({+ ...seed,+ requestId: `bounded-${index}`,+ kind: index % 2 ? ('instant-insights' as const) : ('request' as const),+ })+ const append = (index: number) => {+ const entry = request(index)+ if (index % 2)+ appendRequestInsightUpdateToJournal(entry, { span: entry.spans[0] })+ else appendRequestInsightToJournal(entry)+ }+ const distDir = await mkdtemp(path.join(tmpdir(), 'request-insights-'))+ try {+ await initializeRequestInsightsJournal(distDir)+ for (let index = 0; index < 1000; index++) append(index)+ expect(+ await getRequestInsightsHistory(distDir, { showInternal: true })+ ).toMatchObject({ totalRequestCount: 1000, truncated: false })++ // Late updates must not pin the oldest summary in the index.+ appendRequestInsightUpdateToJournal(request(0), { span: seed.spans[0] })+ append(1000)+ const history = await getRequestInsightsHistory(distDir, {+ showInternal: true,+ })+ expect(history.totalRequestCount).toBe(1000)+ expect(history.truncated).toBe(true)+ expect(history.requests[0].requestId).toBe('bounded-1000')+ expect(+ appendArchivedRequestInsightUpdateToJournal(request(0), {+ span: seed.spans[0],+ })+ ).toBe(false)++ // A live update can reintroduce an evicted entry without growing the index.+ appendRequestInsightUpdateToJournal(request(0), { span: seed.spans[0] })+ const reintroduced = await getRequestInsightsHistory(distDir, {+ showInternal: true,+ })+ expect(reintroduced.totalRequestCount).toBe(1000)+ expect(reintroduced.requests[0].requestId).toBe('bounded-0')+ } finally {+ await resetRequestInsightsJournalForTest()+ await rm(distDir, { recursive: true, force: true })+ }+ })+ it('classifies framework request sources without letting the root span erase a specific source', () => { process.env.__NEXT_REQUEST_INSIGHTS = 'true' startRequestInsight({ requestId: 'req_source' })packages/next/src/server/lib/trace/request-insights.ts1 + / 0 −
@@ -65,6 +65,7 @@ export type RequestInsightsJournalQuery = { htmlRequestId?: string kind?: RequestInsight['kind'] limit?: number+ indexedOnly?: boolean } export type RequestInsightsHistoryProvider = {packages/next/src/trace/report/to-json.ts15 + / 67 −
@@ -1,6 +1,6 @@ import { traceGlobals, traceId } from '../shared'-import fs from 'fs' import path from 'path'+import { RotatingFile } from '../../lib/rotating-file' import { PHASE_DEVELOPMENT_SERVER } from '../../shared/lib/constants' import type { TraceEvent } from '../types' import type { Reporter } from './types'@@ -23,50 +23,18 @@ const MAX_UTF8_CHAR_BYTES = 4 * exists for callers that must then act on the file itself. */ class RotatingWriteStream {- readonly file: string- // Undefined until the first write; see `open()`.- private fd: number | undefined+ private readonly writer: RotatingFile private readonly buffer = Buffer.allocUnsafe(BUFFER_SIZE) // Bytes of event data in `buffer`, excluding the terminator written at // flush time. 0 means nothing is pending. private buffered: number = 0- private size: number = 0- private readonly sizeLimit: number-- constructor(file: string, sizeLimit: number) {- this.file = file- this.sizeLimit = sizeLimit- // TODO: opening a file in append mode like we do in dev should seed the- // size from the current file size.- this.size = 0- } - /**- * Open on first write rather than up front. The dev server records spans- * before it cleans its dist dir, and a descriptor opened that early would be- * unlinked by the clean -- writes to the orphaned inode still succeed, so- * the trace would silently never appear on disk.- */- private open(): number {- if (this.fd === undefined) {- fs.mkdirSync(path.dirname(this.file), { recursive: true })- // In dev, append so traces accumulate across sessions. In production,- // truncate so each build starts with a fresh trace file.- this.fd = fs.openSync(- this.file,- traceGlobals.get('phase') === PHASE_DEVELOPMENT_SERVER ? 'a' : 'w'- )- }- return this.fd- }-- // Recreate the file- private rotate() {- this.closeFd()- fs.mkdirSync(path.dirname(this.file), { recursive: true })- // Opening in 'w' mode truncates the file, discarding what rotated out.- this.fd = fs.openSync(this.file, 'w')- this.size = 0+ constructor(+ readonly file: string,+ sizeLimit: number+ ) {+ this.writer = new RotatingFile(file, sizeLimit)+ // TODO: opening in append mode in dev should seed the existing file size. } /**@@ -125,38 +93,18 @@ class RotatingWriteStream { } private writeToFile(data: Buffer): void {- let offset = 0 try {- if (this.size + data.length > this.sizeLimit) {- this.rotate()- }- const fd = this.open()- // writeSync can write fewer than all the bytes- while (offset < data.length) {- offset += fs.writeSync(fd, data, offset)- }+ if (this.writer.wouldExceed(data.length)) this.writer.rotate()+ // In dev, append across sessions. Each production build starts fresh.+ this.writer.write(+ data,+ traceGlobals.get('phase') === PHASE_DEVELOPMENT_SERVER ? 'a' : 'w'+ ) } catch (err) { // Tracing is diagnostic, so a failed write should not fail the build. // N.B. This is incredibly rare and a torn write means the data may be corrupted on disk. console.log(err) }- this.size += offset- }-- /**- * Release the descriptor without flushing. Callers that want the buffered- * tail on disk flush first; `rotate` deliberately does not.- */- private closeFd(): void {- if (this.fd === undefined) {- return- }- try {- fs.closeSync(this.fd)- } catch {- // Nothing useful to do if the descriptor is already gone.- }- this.fd = undefined } /**@@ -167,7 +115,7 @@ class RotatingWriteStream { */ close(): void { this.flush()- this.closeFd()+ this.writer.close() } } test/development/app-dir/request-insights/request-insights.test.ts9 + / 0 −
@@ -218,6 +218,15 @@ describe('request insights', () => { ) const summary = history.requests[0]+ for (const kind of ['request', 'instant-insights']) {+ const missing = await next.fetch(+ `/_next/development/request-insights?view=detail&requestId=missing-detail-id&kind=${kind}`+ )+ expect(missing.status).toBe(404)+ expect(await missing.json()).toEqual({+ error: 'Request insight not found',+ })+ } const detailResponse = await next.fetch( `/_next/development/request-insights?view=detail&requestId=${encodeURIComponent(summary.requestId)}&kind=${summary.kind ?? 'request'}` )test/development/lockfile/lockfile.test.ts10 + / 6 −
@@ -4,6 +4,7 @@ import fs from 'fs' import path from 'path' import stripAnsi from 'strip-ansi' import { retry } from 'next-test-utils'+import { gunzipSync } from 'zlib' describe('lockfile', () => { const { next, isTurbopack, isRspack } = nextTestSetup({@@ -31,11 +32,16 @@ describe('lockfile', () => { startedAt: expect.any(Number), }) - const journalPath = path.join(distDir, 'request-insights.ndjson')+ const journalPath = path.join(distDir, 'request-insights.ndjson.gz')+ const readJournal = () =>+ gunzipSync(fs.readFileSync(journalPath)).toString('utf8') await retry(() => {- expect(fs.readFileSync(journalPath, 'utf-8').length).toBeGreaterThan(0)+ expect(readJournal().length).toBeGreaterThan(0) })- const recordedHistory = fs.readFileSync(journalPath, 'utf-8')+ const recordedHistory = readJournal()+ expect(fs.existsSync(path.join(distDir, 'request-insights.ndjson'))).toBe(+ false+ ) // Try to start another dev server - should fail with helpful error const { stdout, stderr, exitCode } = await execa(@@ -71,9 +77,7 @@ describe('lockfile', () => { ) expect(output).toMatch(errorPattern) expect(exitCode).toBe(1)- expect(- fs.readFileSync(journalPath, 'utf-8').startsWith(recordedHistory)- ).toBe(true)+ expect(readJournal().startsWith(recordedHistory)).toBe(true) // Make sure the other instance of `next dev` didn't mess anything up await browser.refresh()test/production/next-server-nft/next-server-nft.test.ts1 + / 0 −
@@ -326,6 +326,7 @@ async function readNormalizedNFT(next, name) { "/node_modules/next/dist/lib/require-instrumentation-client.js", "/node_modules/next/dist/lib/resolve-build-paths.js", "/node_modules/next/dist/lib/resolve-from.js",+ "/node_modules/next/dist/lib/rotating-file.js", "/node_modules/next/dist/lib/route-pattern-normalizer.js", "/node_modules/next/dist/lib/scheduler.js", "/node_modules/next/dist/lib/server-external-packages.jsonc",