chore: Add a local telemetry listener for development (no-changelog) (#41990)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Miguel Ángel MorenoandClaude Opus 5.5 authored and GitHub committed 2026-10-28 17:00:57 +00:00
1 parent 5d640a22b8
commit 5df3c06050
9 files changed
+495 -1

No files matched your search

+2
View File
@@ -65,6 +65,8 @@ Do not retype event-name literals in tests:
- In frontend transport tests, expect `window.rudderanalytics.track` to receive `entry.name` and the augmented payload.
- In backend transport tests, expect the RudderStack payload's `event` field to equal `entry.name` and its `properties` to include the event payload.
To check by hand that an event arrives, run `pnpm telemetry:sink` (add `--grep <event name>` to filter) and start the backend with `pnpm dev:be:telemetry`. Backend and editor events appear on screen and in `.output/telemetry.ndjson`, one per line.
## Related
Experiment exposure and metric events follow `n8n:experiments` (`.agents/skills/experiments/SKILL.md`).
+1 -1
View File
@@ -6,7 +6,7 @@
},
"packageManager": "pnpm@12.4.2",
"scripts": {
"test": "node --test --experimental-test-module-mocks ./*.test.mjs ./docker/*.test.mjs ./owners/*.test.mjs ./quality/*.test.mjs ./slack/*.test.mjs ./stale/*.test.mjs ../../scripts/*.test.mjs ../../scripts/codespace-preview/*.test.mjs ../../scripts/licenses/*.test.mjs ../../scripts/mutation-health/*.test.mjs ../../.devcontainer/codespaces/*.test.mjs",
"test": "node --test --experimental-test-module-mocks ./*.test.mjs ./docker/*.test.mjs ./owners/*.test.mjs ./quality/*.test.mjs ./slack/*.test.mjs ./stale/*.test.mjs ../../scripts/*.test.mjs ../../scripts/codespace-preview/*.test.mjs ../../scripts/telemetry/*.test.mjs ../../scripts/licenses/*.test.mjs ../../scripts/mutation-health/*.test.mjs ../../.devcontainer/codespaces/*.test.mjs",
"generate-sbom": "FETCH_LICENSE=true cdxgen -t pnpm --no-install-deps --profile license-compliance --spec-version 1.6 -o ../../sbom-source.cdx.json ../../compiled/",
"enrich-sbom": "node ../../scripts/licenses/enrich-sbom.mjs ../../sbom-source.cdx.json --nested-sbom-root=../../compiled/node_modules",
"render-licenses-md": "node ../../scripts/licenses/render-licenses-md.mjs ../../sbom-source.cdx.json ../../packages/cli/THIRD_PARTY_LICENSES.md ../../compiled/node_modules",
+1
View File
@@ -144,6 +144,7 @@ jobs:
scripts/codespace-preview/**
scripts/licenses/**
scripts/mutation-health/**
scripts/telemetry/**
cubic.yaml
.agents/review-rules/**
e2e-performance:
+2
View File
@@ -101,3 +101,5 @@ stryker.log
# Generated migration indexes (scripts/generate-migration-index.mjs)
packages/@n8n/db/src/migrations/sqlite/index.ts
packages/@n8n/db/src/migrations/postgresdb/index.ts
# Files that local dev tools generate, such as `pnpm telemetry:sink`
.output/
+1
View File
@@ -376,6 +376,7 @@ extends one of those layers):
| Run backend with PostgreSQL, Redis, email, and proxy services | `pnpm --filter n8n-containers services --services postgres,redis,mailpit,proxy`, then `pnpm dev:be` |
| Add editor hot reload | `pnpm dev:fe:editor` |
| Start a Codespace backend and share its port | `pnpm dev:up` |
| See the telemetry events of a local instance | `pnpm telemetry:sink`, then `pnpm dev:be:telemetry` |
The root `pnpm dev` command does not start a server. See the
[Playwright guide](packages/quality/testing/playwright/README.md) and the
+16
View File
@@ -239,6 +239,22 @@ N8N_PORT=5699 pnpm dev:be
N8N_PORT=5699 N8N_EDITOR_PORT=8082 pnpm dev:fe:editor
```
### See telemetry events locally
To see the telemetry events that your instance sends, start a local listener in
one terminal and the backend in another. The listener shows one line for each
event, from the backend and from the editor, and writes each event to
`.output/telemetry.ndjson`. Run `pnpm telemetry:sink --help` for its options.
`pnpm dev:be:telemetry` loads `.env.local` and `.env` when they exist, like
`dotenvx` in the examples above. It always points the diagnostics settings at the
listener, also when those files set them to other values.
```bash
pnpm telemetry:sink
pnpm dev:be:telemetry
```
### Basic Development Workflow Example (most used within n8n)
If you're working on API and FE, a lot of team members run the following steps:
+2
View File
@@ -42,6 +42,8 @@
"format": "turbo run format && node scripts/format.mjs",
"grind": "node scripts/grind.mjs",
"inspect:activity": "node scripts/instance-seeding/inspectActivity.mjs",
"telemetry:sink": "node scripts/telemetry/sink.mjs",
"dev:be:telemetry": "cross-env N8N_DIAGNOSTICS_ENABLED=true N8N_DIAGNOSTICS_CONFIG_BACKEND=\"local;http://127.0.0.1:9999\" N8N_DIAGNOSTICS_CONFIG_FRONTEND=\"local;http://127.0.0.1:9999\" N8N_DIAGNOSTICS_POSTHOG_API_HOST=http://127.0.0.1:9999 N8N_DIAGNOSTICS_POSTHOG_API_KEY=local dotenvx run -f .env.local -f .env --ignore=MISSING_ENV_FILE -- pnpm dev:be",
"seed:account": "node scripts/instance-seeding/seedInstance.mjs",
"seed:history": "node scripts/instance-seeding/seedHistory.mjs",
"seed:preference": "cross-env PROFILE=preference pnpm seed:account && pnpm seed:history",
+265
View File
@@ -0,0 +1,265 @@
#!/usr/bin/env node
// A local listener for the telemetry of a development instance.
//
// The backend sends its own events, and proxies the events of the editor and of
// PostHog, to the diagnostics targets. Point those targets here to see each event
// as one line on screen and as one JSON line in a file.
//
// Events carry user and agent ids, so it binds loopback only. Do not tunnel it.
import { createWriteStream, mkdirSync, realpathSync } from 'node:fs';
import http from 'node:http';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseArgs } from 'node:util';
import { gunzipSync } from 'node:zlib';
const HOST = '127.0.0.1';
const DEFAULT_PORT = 9999;
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const MAX_VALUE_LENGTH = 60;
const EDITOR_PATHS = new Set(['/v1/track', '/v1/identify', '/v1/page']);
/** Environment for a backend that sends its telemetry to this listener. */
export function diagnosticsEnv(port) {
// Not `localhost`: it can resolve to the IPv6 address, and the listener binds IPv4 loopback only.
const target = `http://${HOST}:${port}`;
return {
N8N_DIAGNOSTICS_ENABLED: 'true',
N8N_DIAGNOSTICS_CONFIG_BACKEND: `local;${target}`,
N8N_DIAGNOSTICS_CONFIG_FRONTEND: `local;${target}`,
N8N_DIAGNOSTICS_POSTHOG_API_HOST: target,
N8N_DIAGNOSTICS_POSTHOG_API_KEY: 'local',
};
}
/**
* Turns a request body into a value. PostHog can send gzip, or a form with a
* base64 `data` field. Returns `undefined` for an empty body.
*/
export function decodeBody(buffer, { contentEncoding = '', query = new URLSearchParams() } = {}) {
if (buffer.length === 0) {
return undefined;
}
let bytes = buffer;
if (contentEncoding.includes('gzip') || query.get('compression') === 'gzip-js') {
bytes = gunzipSync(bytes);
}
const text = bytes.toString('utf8');
const trimmed = text.trimStart();
const isJson = trimmed.startsWith('{') || trimmed.startsWith('[');
const formData = isJson ? null : new URLSearchParams(text).get('data');
const json = formData ? Buffer.from(formData, 'base64').toString('utf8') : text;
try {
return JSON.parse(json);
} catch {
return { unparsed: text };
}
}
function toRecord(source, path, receivedAt, item) {
return {
receivedAt,
source,
path,
type: item.type,
event: item.event ?? item.type,
userId: item.userId ?? item.distinct_id,
properties: item.properties ?? item.traits ?? {},
};
}
/** Turns one decoded request into one record for each event it carries. */
export function toRecords(path, body, receivedAt = new Date().toISOString()) {
if (!body || typeof body !== 'object') {
return [];
}
if (path === '/v1/batch' && Array.isArray(body.batch)) {
return body.batch.map((item) => toRecord('backend', path, receivedAt, item));
}
if (EDITOR_PATHS.has(path)) {
return [toRecord('editor', path, receivedAt, body)];
}
let posthogItems = [body];
if (Array.isArray(body)) {
posthogItems = body;
} else if (Array.isArray(body.batch)) {
posthogItems = body.batch;
}
return posthogItems
.filter((item) => item && typeof item === 'object' && typeof item.event === 'string')
.map((item) => toRecord('posthog', path, receivedAt, item));
}
function shortValue(value) {
const text = typeof value === 'string' ? value : JSON.stringify(value);
return text.length > MAX_VALUE_LENGTH ? `${text.slice(0, MAX_VALUE_LENGTH)}…` : text;
}
/** One short line for the screen. */
export function formatLine(record) {
const time = new Date(record.receivedAt).toLocaleTimeString('en-GB');
const properties = Object.entries(record.properties)
.map(([key, value]) => `${key}=${shortValue(value)}`)
.join(' ');
return `${time} ${record.source.padEnd(7)} ${record.event} ${properties}`.trimEnd();
}
/** Starts the listener. Resolves to the server once it accepts connections. */
export async function startSink({
port,
out,
grep,
raw = false,
posthog = false,
log = console.log,
}) {
mkdirSync(path.dirname(out), { recursive: true });
const file = createWriteStream(out, { flags: 'a' });
const filter = grep ? new RegExp(grep, 'i') : undefined;
let received = 0;
const server = http.createServer((req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', '*');
if (req.method === 'OPTIONS') {
res.writeHead(204).end();
return;
}
const chunks = [];
req.on('data', (chunk) => chunks.push(chunk));
req.on('end', () => {
const url = new URL(req.url ?? '/', `http://${HOST}`);
let records = [];
try {
const body = decodeBody(Buffer.concat(chunks), {
contentEncoding: req.headers['content-encoding'],
query: url.searchParams,
});
records = toRecords(url.pathname, body);
} catch (error) {
log(`Could not read a request to ${url.pathname}: ${error.message}`);
}
if (records.length === 0 && raw) {
log(`${new Date().toLocaleTimeString('en-GB')} request ${req.method} ${url.pathname}`);
}
for (const record of records) {
if (filter && !filter.test(record.event ?? '')) {
continue;
}
received++;
file.write(`${JSON.stringify(record)}\n`);
// Most PostHog events copy a RudderStack event, so the screen hides them.
// The file keeps them, because some events, such as experiment exposures, exist only in PostHog.
if (record.source !== 'posthog' || posthog) {
log(formatLine(record));
}
}
// PostHog reads flags from some answers, and an empty object means no flags.
res.writeHead(200, { 'Content-Type': 'application/json' }).end('{}');
});
});
await new Promise((resolve) => server.listen(port, HOST, resolve));
server.receivedCount = () => received;
/** Closes the server, then waits until every event is in the file. */
server.stop = () =>
new Promise((resolve) => {
server.close(() => file.end(resolve));
});
return server;
}
const HELP = `Usage: pnpm telemetry:sink [options]
Listens for the telemetry of a local n8n instance. Shows one line for each
event, and writes each event as one JSON line to a file.
Options:
--port <port> Port to listen on (default: ${DEFAULT_PORT})
--out <file> File for the events (default: .output/telemetry.ndjson in the repo root)
--grep <regex> Show and write only the events whose name matches (case-insensitive)
--raw Also show requests that carry no event, such as PostHog flag requests
--posthog Also show PostHog events on screen. Hidden by default, because most
of them copy a RudderStack event. The file always keeps them.
-h, --help Show this help
Start the backend with \`pnpm dev:be:telemetry\` to send its telemetry to the default port.
Example: grep '"Agent run used knowledge"' .output/telemetry.ndjson | tail -1 | jq .properties`;
function parseOptions(args) {
// Accept `pnpm telemetry:sink -- --port 9998`, and `-help`, which parseArgs does not know.
const normalizedArgs = args
.filter((arg) => arg !== '--')
.map((arg) => (arg === '-help' ? '--help' : arg));
return parseArgs({
args: normalizedArgs,
options: {
port: { type: 'string', default: String(DEFAULT_PORT) },
out: { type: 'string', default: path.join(ROOT, '.output', 'telemetry.ndjson') },
grep: { type: 'string' },
raw: { type: 'boolean', default: false },
posthog: { type: 'boolean', default: false },
help: { type: 'boolean', short: 'h', default: false },
},
}).values;
}
async function main() {
let values;
try {
values = parseOptions(process.argv.slice(2));
} catch (error) {
console.error(`${error.message}\n\n${HELP}`);
process.exit(1);
}
if (values.help) {
console.log(HELP);
return;
}
const port = Number(values.port);
const server = await startSink({
port,
out: values.out,
grep: values.grep,
raw: values.raw,
posthog: values.posthog,
});
console.log(`Telemetry listener on http://${HOST}:${port}`);
console.log(`Writing events to ${values.out}`);
// `pnpm dev:be:telemetry` points the backend at the default port only.
if (port === DEFAULT_PORT) {
console.log('Start the backend with `pnpm dev:be:telemetry`, or with this environment:');
} else {
console.log('Start the backend with this environment:');
}
for (const [key, value] of Object.entries(diagnosticsEnv(port))) {
console.log(` ${key}=${value}`);
}
process.on('SIGINT', () => {
console.log(`\nReceived ${server.receivedCount()} events.`);
void server.stop().then(() => process.exit(0));
});
}
if (process.argv[1] && fileURLToPath(import.meta.url) === realpathSync(process.argv[1])) {
await main();
}
+205
View File
@@ -0,0 +1,205 @@
import assert from 'node:assert/strict';
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, it } from 'node:test';
import { gzipSync } from 'node:zlib';
import { decodeBody, formatLine, startSink, toRecords } from './sink.mjs';
const receivedAt = '2026-10-23T10:17:08.000Z';
describe('decodeBody', () => {
it('reads a JSON body', () => {
assert.deepEqual(decodeBody(Buffer.from('{"event":"a"}')), { event: 'a' });
});
it('reads a gzip body', () => {
const buffer = gzipSync(Buffer.from('[{"event":"a"}]'));
assert.deepEqual(decodeBody(buffer, { contentEncoding: 'gzip' }), [{ event: 'a' }]);
assert.deepEqual(decodeBody(buffer, { query: new URLSearchParams('compression=gzip-js') }), [
{ event: 'a' },
]);
});
it('reads a form body with a base64 data field', () => {
const data = Buffer.from('{"event":"a"}').toString('base64');
assert.deepEqual(decodeBody(Buffer.from(`data=${encodeURIComponent(data)}`)), { event: 'a' });
});
it('keeps a body that is not JSON as text', () => {
assert.deepEqual(decodeBody(Buffer.from('not json')), { unparsed: 'not json' });
});
it('returns nothing for an empty body', () => {
assert.equal(decodeBody(Buffer.alloc(0)), undefined);
});
});
describe('toRecords', () => {
it('gives one record for each event of a backend batch', () => {
const records = toRecords(
'/v1/batch',
{
batch: [
{ type: 'track', event: 'First', userId: 'u1', properties: { a: 1 } },
{ type: 'track', event: 'Second', userId: 'u1', properties: { b: 2 } },
],
},
receivedAt,
);
assert.deepEqual(
records.map(({ source, event, properties }) => ({ source, event, properties })),
[
{ source: 'backend', event: 'First', properties: { a: 1 } },
{ source: 'backend', event: 'Second', properties: { b: 2 } },
],
);
});
it('gives one record for an editor track request', () => {
const [record] = toRecords(
'/v1/track',
{ type: 'track', event: 'User opened agent knowledge tab', properties: { agent_id: 'a1' } },
receivedAt,
);
assert.equal(record.source, 'editor');
assert.equal(record.event, 'User opened agent knowledge tab');
});
it('names an editor identify request by its type', () => {
const [record] = toRecords(
'/v1/identify',
{ type: 'identify', userId: 'u1', traits: { instance_id: 'i1' } },
receivedAt,
);
assert.equal(record.event, 'identify');
assert.deepEqual(record.properties, { instance_id: 'i1' });
});
it('gives one record for each event of a PostHog batch', () => {
const records = toRecords(
'/e/',
[
{ event: '$pageview', distinct_id: 'u1', properties: {} },
{ event: '$autocapture', distinct_id: 'u1', properties: {} },
],
receivedAt,
);
assert.deepEqual(
records.map(({ source, event, userId }) => ({ source, event, userId })),
[
{ source: 'posthog', event: '$pageview', userId: 'u1' },
{ source: 'posthog', event: '$autocapture', userId: 'u1' },
],
);
});
it('gives no record for a request without events', () => {
assert.deepEqual(toRecords('/decide/', { token: 'local' }, receivedAt), []);
assert.deepEqual(toRecords('/v1/batch', undefined, receivedAt), []);
});
});
describe('formatLine', () => {
it('shows the time, the source, the event and short properties', () => {
const line = formatLine({
receivedAt,
source: 'backend',
event: 'Agent run used knowledge',
properties: { file_read_count: 2, run_id: 'r'.repeat(80) },
});
const localTime = new Date(receivedAt).toLocaleTimeString('en-GB');
assert.equal(
line,
`${localTime} backend Agent run used knowledge file_read_count=2 run_id=${'r'.repeat(60)}…`,
);
});
});
/** Starts a sink on a free port, sends one request, and returns what it showed and wrote. */
async function sendToSink(options, path, body) {
const directory = mkdtempSync(join(tmpdir(), 'telemetry-sink-'));
const out = join(directory, 'telemetry.ndjson');
const lines = [];
const server = await startSink({ port: 0, out, log: (line) => lines.push(line), ...options });
try {
const { port } = server.address();
await fetch(`http://127.0.0.1:${port}${path}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
await server.stop();
const written = readFileSync(out, 'utf8').trim().split('\n').filter(Boolean);
return { lines, written: written.map((line) => JSON.parse(line)) };
} finally {
rmSync(directory, { recursive: true, force: true });
}
}
describe('startSink', () => {
const posthogBatch = [{ event: 'Agent run used knowledge', distinct_id: 'u1', properties: {} }];
it('hides PostHog events on screen by default, but writes them to the file', async () => {
const { lines, written } = await sendToSink({}, '/batch/', posthogBatch);
assert.deepEqual(lines, []);
assert.deepEqual(
written.map(({ source, event }) => ({ source, event })),
[{ source: 'posthog', event: 'Agent run used knowledge' }],
);
});
it('shows PostHog events on screen with the posthog option', async () => {
const { lines } = await sendToSink({ posthog: true }, '/batch/', posthogBatch);
assert.equal(lines.length, 1);
assert.match(lines[0], /posthog\s+Agent run used knowledge/);
});
it('answers a backend batch and writes one line for each event', async () => {
const directory = mkdtempSync(join(tmpdir(), 'telemetry-sink-'));
const out = join(directory, 'telemetry.ndjson');
const lines = [];
const server = await startSink({ port: 0, out, log: (line) => lines.push(line) });
try {
const { port } = server.address();
const response = await fetch(`http://127.0.0.1:${port}/v1/batch`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
batch: [
{ type: 'track', event: 'First', properties: {} },
{ type: 'track', event: 'Second', properties: {} },
],
}),
});
assert.equal(response.status, 200);
assert.equal(lines.length, 2);
} finally {
await server.stop();
}
try {
const written = readFileSync(out, 'utf8')
.trim()
.split('\n')
.map((line) => JSON.parse(line));
assert.deepEqual(
written.map(({ event }) => event),
['First', 'Second'],
);
} finally {
rmSync(directory, { recursive: true, force: true });
}
});
});