Files
Gabriel20xx 8701874efb feat(logshipper): support dynamic OmniLogger credentials
- Add per-service OmniLogger credentials to core config and update subscriptions.
- Follow config pushes and enforce entry and request size limits.
- Requeue batches after transient send failures.
2026-11-20 21:45:45 +01:00

545 lines
18 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { createServer } from 'node:http';
import { createLogShipperFromEnv, LogShipper, mirrorConsole } from '../src/logshipper.js';
// startSink runs a local stand-in for OmniLogger that records every request it receives. The first
// requests get the answers in `statuses`, in order: a status code, or null to drop the connection
// without answering. Later requests get `status`. When `gate` is given, each answer waits for it.
async function startSink({ status = 202, statuses = [], gate } = {}) {
const requests = [];
const server = createServer((req, res) => {
const chunks = [];
req.on('data', (chunk) => chunks.push(chunk));
req.on('end', async () => {
const answer = statuses.length > 0 ? statuses.shift() : status;
requests.push({
method: req.method,
path: req.url,
authorization: req.headers.authorization,
contentType: req.headers['content-type'],
status: answer,
accepted: answer >= 200 && answer < 300,
body: JSON.parse(Buffer.concat(chunks).toString('utf8')),
});
await gate;
if (answer === null) {
req.socket.destroy();
return;
}
res.writeHead(answer, { 'Content-Type': 'text/plain' });
res.end('ok');
});
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
return {
url: `http://127.0.0.1:${server.address().port}`,
requests,
// entries returns what OmniLogger accepted, in the order it was sent.
entries: () => requests.filter((request) => request.accepted).flatMap((request) => request.body),
close: async () => {
server.closeAllConnections();
await new Promise((resolve) => server.close(resolve));
},
};
}
async function waitFor(check) {
const deadline = Date.now() + 5000;
while (!check()) {
if (Date.now() > deadline) assert.fail('condition not met within 5s');
await new Promise((resolve) => setTimeout(resolve, 10));
}
}
function shipperFor(sink, options = {}) {
return new LogShipper({
baseUrl: sink.url,
ingestToken: 'secret',
service: 'svc',
flushIntervalMs: 60_000,
onWarning: () => {},
...options,
});
}
test('shipping is disabled unless both OMNILOGGER_URL and OMNILOGGER_INGEST_TOKEN are non-empty', async (t) => {
const sink = await startSink();
t.after(() => sink.close());
const envs = [
{},
{ OMNILOGGER_URL: sink.url },
{ OMNILOGGER_INGEST_TOKEN: 'secret' },
{ OMNILOGGER_URL: '', OMNILOGGER_INGEST_TOKEN: 'secret' },
{ OMNILOGGER_URL: sink.url, OMNILOGGER_INGEST_TOKEN: ' ' },
];
for (const env of envs) {
assert.equal(createLogShipperFromEnv('svc', { env }), null, JSON.stringify(env));
}
});
test('a disabled service makes no calls and prints nothing extra', async (t) => {
const sink = await startSink();
t.after(() => sink.close());
const local = [];
const target = { log: (...args) => local.push(args) };
const shipper = createLogShipperFromEnv('svc', { env: { OMNILOGGER_URL: sink.url } });
if (shipper) mirrorConsole(shipper, target);
target.log('still local');
await new Promise((resolve) => setTimeout(resolve, 20));
assert.equal(shipper, null);
assert.deepEqual(local, [['still local']]);
assert.equal(sink.requests.length, 0);
});
test('createLogShipperFromEnv ships to the trimmed URL with the token and service name', async (t) => {
const sink = await startSink();
const shipper = createLogShipperFromEnv('mediadesktop', {
env: { OMNILOGGER_URL: ` ${sink.url}/ `, OMNILOGGER_INGEST_TOKEN: ' secret-token ' },
flushIntervalMs: 60_000,
onWarning: () => {},
});
t.after(async () => {
await shipper.close();
await sink.close();
});
assert.ok(shipper instanceof LogShipper);
shipper.info('from env');
await shipper.flush();
assert.equal(sink.requests.length, 1);
assert.equal(sink.requests[0].authorization, 'Bearer secret-token');
assert.equal(sink.requests[0].body[0].service, 'mediadesktop');
});
test('posts to /api/logs with the ingest token as a bearer credential', async (t) => {
const sink = await startSink();
const shipper = shipperFor(sink, { baseUrl: `${sink.url}///`, ingestToken: 'secret-token' });
t.after(async () => {
await shipper.close();
await sink.close();
});
shipper.warn('hello');
await shipper.flush();
const [request] = sink.requests;
assert.equal(request.method, 'POST');
assert.equal(request.path, '/api/logs');
assert.equal(request.authorization, 'Bearer secret-token');
assert.equal(request.contentType, 'application/json');
});
test('every entry carries the service name, a level and an RFC 3339 UTC timestamp', async (t) => {
const sink = await startSink();
const shipper = shipperFor(sink, { service: 'mediadesktop', level: 'debug' });
t.after(async () => {
await shipper.close();
await sink.close();
});
shipper.debug('d');
shipper.critical('c');
await shipper.flush();
const entries = sink.entries();
assert.deepEqual(
entries.map((e) => [e.service, e.level]),
[
['mediadesktop', 'debug'],
['mediadesktop', 'critical'],
],
);
for (const entry of entries) {
assert.match(entry.occurred_at, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/);
}
});
test('flush sends everything buffered in one request, in order', async (t) => {
const sink = await startSink();
const shipper = shipperFor(sink);
t.after(async () => {
await shipper.close();
await sink.close();
});
shipper.info('one');
shipper.info('two');
shipper.info('three');
await shipper.flush();
await shipper.flush(); // nothing left, so no second request
assert.equal(sink.requests.length, 1);
assert.deepEqual(
sink.requests[0].body.map((e) => e.message),
['one', 'two', 'three'],
);
});
test('the periodic interval sends entries without an explicit flush', async (t) => {
const sink = await startSink();
const shipper = shipperFor(sink, { flushIntervalMs: 20 });
t.after(async () => {
await shipper.close();
await sink.close();
});
shipper.info('tick');
await waitFor(() => sink.entries().length === 1);
assert.equal(sink.entries()[0].message, 'tick');
});
test('reaching the batch size flushes ahead of the interval', async (t) => {
const sink = await startSink();
const shipper = shipperFor(sink, { maxBatchSize: 3 });
t.after(async () => {
await shipper.close();
await sink.close();
});
shipper.info('a');
shipper.info('b');
await new Promise((resolve) => setTimeout(resolve, 50));
assert.equal(sink.requests.length, 0, 'two entries are below the batch size');
shipper.info('c');
await waitFor(() => sink.requests.length === 1);
assert.deepEqual(
sink.requests[0].body.map((e) => e.message),
['a', 'b', 'c'],
);
});
test('a backlog larger than one batch is split into requests of at most the batch size', async (t) => {
const sink = await startSink();
const shipper = shipperFor(sink, { maxBatchSize: 2 });
t.after(async () => {
await shipper.close();
await sink.close();
});
for (let i = 0; i < 5; i += 1) shipper.info(`m${i}`);
await shipper.flush();
assert.ok(sink.requests.every((request) => request.body.length <= 2));
assert.deepEqual(
sink.entries().map((e) => e.message),
['m0', 'm1', 'm2', 'm3', 'm4'],
);
});
test('the level threshold gates entries, and its aliases and unknown names resolve', async (t) => {
const sink = await startSink();
t.after(() => sink.close());
const cases = [
{ service: 'warning-alias', level: 'warning', kept: ['warn', 'error', 'critical'] },
{ service: 'silent-alias', level: 'off', kept: [] },
{ service: 'unknown-name', level: 'bogus', kept: ['info', 'warn', 'error', 'critical'] },
];
for (const { service, level, kept } of cases) {
const shipper = shipperFor(sink, { service, level });
shipper.debug('debug');
shipper.info('info');
shipper.warn('warn');
shipper.error('error');
shipper.critical('critical');
await shipper.close();
const messages = sink
.entries()
.filter((e) => e.service === service)
.map((e) => e.message);
assert.deepEqual(messages, kept, `level ${level}`);
}
});
test('console calls are mirrored at their levels and still printed locally', async (t) => {
const sink = await startSink();
const shipper = shipperFor(sink, { level: 'debug' });
t.after(async () => {
await shipper.close();
await sink.close();
});
const local = [];
const target = {};
for (const method of ['debug', 'log', 'info', 'warn', 'error']) {
target[method] = (...args) => local.push([method, ...args]);
}
const originals = { ...target };
const restore = mirrorConsole(shipper, target);
target.debug('d');
target.log('l', 1);
target.info('i');
target.warn('w');
target.error('e', { a: 1 });
restore();
assert.deepEqual(target, originals, 'restore puts the original methods back');
await shipper.flush();
assert.deepEqual(local, [
['debug', 'd'],
['log', 'l', 1],
['info', 'i'],
['warn', 'w'],
['error', 'e', { a: 1 }],
]);
assert.deepEqual(
sink.entries().map((e) => [e.level, e.message]),
[
['debug', 'd'],
['info', 'l 1'],
['info', 'i'],
['warn', 'w'],
['error', 'e { a: 1 }'],
],
);
});
test('a message over 8192 bytes is cut on a character boundary and marked', async (t) => {
const sink = await startSink();
const shipper = shipperFor(sink);
t.after(async () => {
await shipper.close();
await sink.close();
});
// Four-byte characters after one ASCII byte: the cut position falls inside a character.
const long = `a${'\u{1F600}'.repeat(3000)}`;
shipper.info(long);
shipper.info('short');
await shipper.flush();
const [clamped, short] = sink.entries().map((e) => e.message);
assert.ok(Buffer.byteLength(clamped, 'utf8') <= 8192);
assert.ok(clamped.endsWith(' [truncated]'));
assert.ok(!clamped.includes('�'), 'the cut split a character');
assert.ok(long.startsWith(clamped.slice(0, -' [truncated]'.length)));
assert.equal(short, 'short');
});
test('an oversized context or one with a NUL escape is replaced by the dropped marker', async (t) => {
const sink = await startSink();
const shipper = shipperFor(sink);
t.after(async () => {
await shipper.close();
await sink.close();
});
const fits = { blob: 'x'.repeat(16 * 1024 - JSON.stringify({ blob: '' }).length) };
shipper.log('info', 'fits', fits);
shipper.log('info', 'too big', { blob: 'x'.repeat(16 * 1024) });
shipper.log('info', 'nul', { s: 'a\u0000b' });
shipper.log('info', 'small', { ok: true, n: 1 });
shipper.log('info', 'no context');
await shipper.flush();
const [a, b, c, d, e] = sink.entries();
assert.deepEqual(a.context, fits);
assert.deepEqual(b.context, { context_dropped: true });
assert.deepEqual(c.context, { context_dropped: true });
assert.deepEqual(d.context, { ok: true, n: 1 });
assert.equal('context' in e, false);
assert.equal(b.message, 'too big');
});
test('a full buffer drops new entries with one warning instead of blocking', async (t) => {
const sink = await startSink();
const warnings = [];
const shipper = shipperFor(sink, { bufferCapacity: 3, onWarning: (text) => warnings.push(text) });
t.after(async () => {
await shipper.close();
await sink.close();
});
for (let i = 0; i < 10; i += 1) shipper.info(`m${i}`);
await shipper.flush();
assert.deepEqual(
sink.entries().map((e) => e.message),
['m0', 'm1', 'm2'],
);
assert.equal(warnings.length, 1);
assert.match(warnings[0], /buffer full/);
});
test('a 503 on the first send is retried, and each entry arrives exactly once and in order', async (t) => {
const sink = await startSink({ statuses: [503] });
const shipper = shipperFor(sink);
t.after(async () => {
await shipper.close();
await sink.close();
});
shipper.info('a');
shipper.info('b');
await shipper.flush(); // refused with 503, so both entries stay buffered
await shipper.flush(); // accepted
await shipper.flush(); // nothing left to send
assert.deepEqual(
sink.requests.map((request) => request.status),
[503, 202],
);
assert.deepEqual(
sink.entries().map((e) => e.message),
['a', 'b'],
);
});
test('a dropped connection is retried like a server error', async (t) => {
const sink = await startSink({ statuses: [null] });
const shipper = shipperFor(sink);
t.after(async () => {
await shipper.close();
await sink.close();
});
shipper.info('a');
await shipper.flush(); // no response at all, so the entry stays buffered
await shipper.flush();
assert.deepEqual(
sink.requests.map((request) => request.status),
[null, 202],
);
assert.deepEqual(
sink.entries().map((e) => e.message),
['a'],
);
});
test('a 400 is dropped and not retried', async (t) => {
const sink = await startSink({ statuses: [400] });
const warnings = [];
const shipper = shipperFor(sink, { onWarning: (text) => warnings.push(text) });
t.after(async () => {
await shipper.close();
await sink.close();
});
shipper.info('rejected');
await shipper.flush();
await shipper.flush(); // nothing was kept, so nothing is sent again
shipper.info('next');
await shipper.flush();
assert.deepEqual(
sink.requests.map((request) => request.status),
[400, 202],
);
assert.deepEqual(
sink.entries().map((e) => e.message),
['next'],
);
assert.equal(warnings.length, 1);
assert.match(warnings[0], /rejected 1 entries: HTTP 400/);
});
test('a failed batch holds back the rest of its flush, and they are sent again in order', async (t) => {
const sink = await startSink({ statuses: [202, 503] });
const shipper = shipperFor(sink, { maxBatchSize: 2 });
t.after(async () => {
await shipper.close();
await sink.close();
});
for (let i = 0; i < 5; i += 1) shipper.info(`m${i}`);
// Reaching the batch size starts a background flush of all five entries: [m0, m1] is accepted,
// [m2, m3] is refused, and [m4] must not be attempted.
await waitFor(() => sink.requests.length === 2);
await new Promise((resolve) => setTimeout(resolve, 50));
assert.equal(sink.requests.length, 2, 'm4 waits for the next flush');
await shipper.flush(); // [m2, m3], then [m4]
assert.deepEqual(
sink.requests.map((request) => request.status),
[202, 503, 202, 202],
);
assert.deepEqual(
sink.entries().map((e) => e.message),
['m0', 'm1', 'm2', 'm3', 'm4'],
);
});
test('during an outage the buffer holds at most its capacity, keeping the oldest entries', async (t) => {
const sink = await startSink({ statuses: [503, 503] });
const shipper = shipperFor(sink, { bufferCapacity: 3 });
t.after(async () => {
await shipper.close();
await sink.close();
});
for (const m of ['a', 'b', 'c']) shipper.info(m);
await shipper.flush(); // refused, so a, b and c stay buffered
for (const m of ['d', 'e']) shipper.info(m); // the buffer is full, so these are dropped
await shipper.flush(); // still refused
await shipper.flush(); // the outage is over
assert.ok(sink.requests.every((request) => request.body.length <= 3));
assert.deepEqual(
sink.requests.map((request) => request.status),
[503, 503, 202],
);
assert.deepEqual(
sink.entries().map((e) => e.message),
['a', 'b', 'c'],
);
});
test('a retry that does not fit beside new entries drops the newest ones', async (t) => {
let release;
const gate = new Promise((resolve) => {
release = resolve;
});
const sink = await startSink({ statuses: [503], gate });
const shipper = shipperFor(sink, { bufferCapacity: 3 });
t.after(async () => {
release();
await shipper.close();
await sink.close();
});
shipper.info('a');
shipper.info('b');
const sending = shipper.flush();
await waitFor(() => sink.requests.length === 1);
// While a and b are in flight, x, y and z fill the buffer. When the refusal arrives, a and b go back
// in front of them, so only a, b and x fit and y and z are dropped.
for (const m of ['x', 'y', 'z']) shipper.info(m);
release();
await sending;
await shipper.flush();
assert.deepEqual(
sink.entries().map((e) => e.message),
['a', 'b', 'x'],
);
});
test('a rejecting or unreachable OmniLogger never throws, and warnings are rate-limited', async (t) => {
const rejecting = await startSink({ status: 400 });
const warnings = [];
const shipper = shipperFor(rejecting, { onWarning: (text) => warnings.push(text) });
t.after(async () => {
await shipper.close();
await rejecting.close();
});
shipper.info('one');
await shipper.flush();
shipper.info('two');
await shipper.flush();
assert.equal(warnings.filter((text) => text.includes('rejected')).length, 1);
const unreachable = shipperFor({ url: 'http://127.0.0.1:1' }, { onWarning: (text) => warnings.push(text) });
unreachable.info('lost');
await unreachable.flush();
await unreachable.close();
assert.ok(warnings.some((text) => text.includes('send 1 entries')));
const malformed = shipperFor({ url: 'not a url' }, { onWarning: (text) => warnings.push(text) });
malformed.info('lost');
await malformed.flush();
await malformed.close();
});
test('close sends what is left, and entries logged after it are dropped', async (t) => {
const sink = await startSink();
t.after(() => sink.close());
const shipper = shipperFor(sink);
shipper.info('last');
await shipper.close();
assert.deepEqual(
sink.entries().map((e) => e.message),
['last'],
);
shipper.info('after close');
await shipper.flush();
await shipper.close();
assert.equal(sink.entries().length, 1);
});
test('the periodic flush timer does not keep the process alive', () => {
const moduleUrl = new URL('../src/logshipper.js', import.meta.url).href;
const script = `
import { LogShipper } from ${JSON.stringify(moduleUrl)};
new LogShipper({ baseUrl: 'http://127.0.0.1:1', ingestToken: 't', service: 's', flushIntervalMs: 3600000 });
`;
const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], {
encoding: 'utf8',
timeout: 10_000,
});
assert.equal(result.signal, null, 'the process was kept alive by the timer');
assert.equal(result.status, 0, result.stderr);
});