Unverified Commit 25cfbd6a authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

Fix telemetry delivery on Node.js 24 (#99842)

### Why?

Telemetry fails on Node.js 24 with this error before any HTTP request is
sent:

```text
TypeError: RequestInit: Expected signal ("AbortSignal {}") to be an instance of AbortSignal.
```

Native `fetch` checks that `RequestInit.signal` is an instance of Node's
native `AbortSignal`. The Edge Runtime ponyfill creates its own
`AbortSignal` class: the name is the same, but the constructor is
different, so the signal fails the instance check.

The telemetry transport retries once and suppresses the final error, so
the CLI can exit successfully without delivering events.

The controller was introduced when Next.js supported Node.js 14.6.
Next.js now requires Node.js 20.9 or later, where native
`AbortController` is available on all supported versions.

### How?

Use Node's native `AbortController` so its signal matches `fetch`,
preserving the existing timeout.

Verified real SDK HTTP delivery on Node.js 20.9, 22.6, and 24.1, and the
five-second cancellation deadline. The patched CLI received HTTP 204 for
all three upgrade lifecycle events; Snowflake persistence is not yet
verified. The full repository build and test suite were not run.

<!-- NEXT_JS_LLM -->
parent 4141a0a5
import { createServer } from 'http'
import type { AddressInfo } from 'net'
import { postNextTelemetryPayload } from './post-telemetry-payload'
import { Telemetry } from './storage'
// Keep identifiers and metadata local while exercising the real delivery path.
jest.mock('next/dist/compiled/conf', () =>
jest.fn().mockImplementation(() => ({
get: jest.fn((_key: string, fallback: unknown) => fallback),
set: jest.fn(),
}))
)
jest.mock('./project-id', () => ({
getRawProjectId: async () => 'test-project',
}))
jest.mock('./anonymous-meta', () => ({
getAnonymousMeta: async () => ({}),
}))
describe('postNextTelemetryPayload', () => {
let originalFetch: typeof fetch
......@@ -87,3 +104,86 @@ describe('postNextTelemetryPayload', () => {
expect(mockFetch).toHaveBeenCalledTimes(2) // Initial try + 1 retry
})
})
describe('Telemetry delivery', () => {
const originalEnv = process.env
let originalFetch: typeof fetch
beforeEach(() => {
originalFetch = global.fetch
process.env = { ...originalEnv }
delete process.env.NEXT_TELEMETRY_DISABLED
delete process.env.NEXT_TELEMETRY_DEBUG
})
afterEach(() => {
global.fetch = originalFetch
process.env = originalEnv
})
it('delivers recorded telemetry over HTTP', async () => {
const requests: Array<{
method: string | undefined
contentType: string | undefined
body: string
}> = []
const server = createServer((request, response) => {
let body = ''
request.on('data', (chunk) => {
body += chunk
})
request.on('end', () => {
requests.push({
method: request.method,
contentType: request.headers['content-type'],
body,
})
response.writeHead(204)
response.end()
})
})
await new Promise<void>((resolve, reject) => {
server.once('error', reject)
server.listen(0, '127.0.0.1', resolve)
})
try {
// Redirect only the destination; native fetch still validates and sends.
const address = server.address() as AddressInfo
const mockFetch = jest.fn((_input, init) =>
originalFetch('http://127.0.0.1:' + address.port, init)
)
global.fetch = mockFetch
const telemetry = new Telemetry({ distDir: '.next', skipNotify: true })
const event = { eventName: 'test-event', payload: { foo: 'bar' } }
telemetry.record(event)
await telemetry.flush()
expect(requests).toHaveLength(1)
expect(requests[0]).toMatchObject({
method: 'POST',
contentType: 'application/json',
})
expect(JSON.parse(requests[0].body).events).toEqual([
{ eventName: event.eventName, fields: event.payload },
])
expect(mockFetch).toHaveBeenCalledTimes(1)
expect(mockFetch).toHaveBeenCalledWith(
'https://telemetry.nextjs.org/api/v1/record',
expect.objectContaining({ signal: expect.any(AbortSignal) })
)
} finally {
server.closeAllConnections()
await new Promise<void>((resolve, reject) => {
server.close((error) => {
if (error) {
reject(error)
return
}
resolve()
})
})
}
})
})
......@@ -9,7 +9,6 @@ import { getAnonymousMeta } from './anonymous-meta'
import * as ciEnvironment from '../server/ci-info'
import { postNextTelemetryPayload } from './post-telemetry-payload'
import { getRawProjectId } from './project-id'
import { AbortController } from 'next/dist/compiled/@edge-runtime/ponyfill'
import fs from 'fs'
// This is the key that stores whether or not telemetry is enabled or disabled.
......
......@@ -163,15 +163,6 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/cli/next-test.js",
"/node_modules/next/dist/client/*",
"/node_modules/next/dist/compiled/@edge-runtime/cookies/index.js",
"/node_modules/next/dist/compiled/@edge-runtime/ponyfill/index.js",
"/node_modules/next/dist/compiled/@edge-runtime/primitives/abort-controller.js.text.js",
"/node_modules/next/dist/compiled/@edge-runtime/primitives/console.js.text.js",
"/node_modules/next/dist/compiled/@edge-runtime/primitives/events.js.text.js",
"/node_modules/next/dist/compiled/@edge-runtime/primitives/index.js",
"/node_modules/next/dist/compiled/@edge-runtime/primitives/load.js",
"/node_modules/next/dist/compiled/@edge-runtime/primitives/stream.js",
"/node_modules/next/dist/compiled/@edge-runtime/primitives/timers.js.text.js",
"/node_modules/next/dist/compiled/@edge-runtime/primitives/url.js.text.js",
"/node_modules/next/dist/compiled/@hapi/accept/index.js",
"/node_modules/next/dist/compiled/@mswjs/interceptors/ClientRequest/index.js",
"/node_modules/next/dist/compiled/@napi-rs/triples/index.js",
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment