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.
This commit is contained in:
1 parent
76bf5916fe
commit
8701874efb
20 files changed
+4908
-61
No files matched your search
@@ -7,7 +7,8 @@ Shared Node.js backend infrastructure for services that use PostgreSQL:
|
||||
- PBKDF2 password hashing (`verifyAndUpgradePasswordAsync` returns a current-scheme hash for a login to store) and secure session-token helpers;
|
||||
- short-lived, one-time admin reset codes printed to the server console;
|
||||
- common account/session persistence;
|
||||
- transaction-locked ordered migrations.
|
||||
- transaction-locked ordered migrations;
|
||||
- OmniLogger log shipping: `createLogShipperFromEnv` (off unless `OMNILOGGER_URL` and `OMNILOGGER_INGEST_TOKEN` are both set), `LogShipper`, and `mirrorConsole`.
|
||||
|
||||
The package does not depend on Express. Each service keeps its own routes,
|
||||
cookies, roles, validation policy, and domain repositories. Existing
|
||||
|
||||
@@ -36,6 +36,7 @@ export {
|
||||
verifyTotpStep,
|
||||
} from './totp.js';
|
||||
export { runMigrations } from './migrate.js';
|
||||
export { LOG_LEVELS, LogShipper, createLogShipperFromEnv, mirrorConsole } from './logshipper.js';
|
||||
export { APIError, AuthClient, InvalidSessionError, createAuthClient } from './authclient.js';
|
||||
export {
|
||||
EXAMPLE_INTERNAL_SECRETS,
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
// logshipper.js is the Node equivalent of shared/backend/logshipper (Go) and follows the same
|
||||
// OmniLogger contract: it batches log entries and POSTs them to OmniLogger's /api/logs with the
|
||||
// service's ingest token, so a service's existing logs also reach the central sink.
|
||||
//
|
||||
// It is a sink, not a logger. It never writes to the console itself: callers keep their
|
||||
// console.* lines exactly as they are, and mirrorConsole() forwards each of those lines here as
|
||||
// well. Shipping is off unless both OMNILOGGER_URL and OMNILOGGER_INGEST_TOKEN are set;
|
||||
// createLogShipperFromEnv returns null otherwise, and nothing here ever throws into the caller.
|
||||
|
||||
import { format } from 'node:util';
|
||||
|
||||
export const LOG_LEVELS = Object.freeze(['debug', 'info', 'warn', 'error', 'critical']);
|
||||
|
||||
// Thresholds use the same numeric scale as internal/logging in the Go services.
|
||||
const LEVEL_RANK = new Map([
|
||||
['debug', 10],
|
||||
['info', 20],
|
||||
['warn', 30],
|
||||
['error', 40],
|
||||
['critical', 50],
|
||||
['silent', 100],
|
||||
]);
|
||||
const LEVEL_ALIASES = new Map([
|
||||
['warning', 'warn'],
|
||||
['none', 'silent'],
|
||||
['off', 'silent'],
|
||||
]);
|
||||
|
||||
const DEFAULT_FLUSH_INTERVAL_MS = 2000;
|
||||
const DEFAULT_MAX_BATCH_SIZE = 100;
|
||||
const DEFAULT_BUFFER_CAPACITY = 2000;
|
||||
const DEFAULT_TIMEOUT_MS = 5000;
|
||||
const DEFAULT_WARN_INTERVAL_MS = 60_000;
|
||||
|
||||
// OmniLogger rejects a whole batch when any entry breaks a limit, so each entry is clamped before
|
||||
// it is buffered. It also caps a batch at 1000 entries and a request body under 2 MiB.
|
||||
const MAX_MESSAGE_BYTES = 8 * 1024;
|
||||
const MAX_CONTEXT_BYTES = 16 * 1024;
|
||||
const MAX_BATCH_ENTRIES = 1000;
|
||||
const MAX_BODY_BYTES = 1024 * 1024; // packing budget, well under OmniLogger's 2 MiB limit
|
||||
const TRUNCATED_MARKER = ' [truncated]';
|
||||
const DROPPED_CONTEXT = '{"context_dropped":true}';
|
||||
|
||||
// The console methods that are mirrored, and the level each one ships at. console.log has no level
|
||||
// of its own, so it ships at info.
|
||||
const CONSOLE_LEVELS = [
|
||||
['debug', 'debug'],
|
||||
['log', 'info'],
|
||||
['info', 'info'],
|
||||
['warn', 'warn'],
|
||||
['error', 'error'],
|
||||
];
|
||||
|
||||
function canonicalLevel(name) {
|
||||
const key = String(name ?? '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
return LEVEL_ALIASES.get(key) ?? key;
|
||||
}
|
||||
|
||||
function positiveOr(value, fallback) {
|
||||
return Number.isFinite(value) && value > 0 ? value : fallback;
|
||||
}
|
||||
|
||||
function clampMessage(message) {
|
||||
if (Buffer.byteLength(message, 'utf8') <= MAX_MESSAGE_BYTES) return message;
|
||||
const bytes = Buffer.from(message, 'utf8');
|
||||
let cut = MAX_MESSAGE_BYTES - Buffer.byteLength(TRUNCATED_MARKER);
|
||||
// Cut on a UTF-8 character boundary: a continuation byte (10xxxxxx) starts no character.
|
||||
while (cut > 0 && (bytes[cut] & 0xc0) === 0x80) cut -= 1;
|
||||
return bytes.subarray(0, cut).toString('utf8') + TRUNCATED_MARKER;
|
||||
}
|
||||
|
||||
// serializeContext returns the context as JSON text, or undefined when there is none to send.
|
||||
// A context that cannot be serialized is omitted; one that breaks a limit is replaced by a marker,
|
||||
// so the entry itself still reaches OmniLogger.
|
||||
function serializeContext(context) {
|
||||
if (Object.prototype.toString.call(context) !== '[object Object]') return undefined;
|
||||
let json;
|
||||
try {
|
||||
json = JSON.stringify(context);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
if (json === undefined) return undefined;
|
||||
if (Buffer.byteLength(json, 'utf8') > MAX_CONTEXT_BYTES || json.includes('\\u0000')) return DROPPED_CONTEXT;
|
||||
return json;
|
||||
}
|
||||
|
||||
// packBatches splits serialized entries into request bodies of at most maxEntries entries and
|
||||
// MAX_BODY_BYTES bytes each. A flush can hold more than one batch's worth of entries when
|
||||
// OmniLogger was slow, so the split keeps every request inside OmniLogger's limits.
|
||||
function packBatches(entries, maxEntries) {
|
||||
const batches = [];
|
||||
let batch = [];
|
||||
let bytes = 2; // the enclosing brackets
|
||||
for (const entry of entries) {
|
||||
const entryBytes = Buffer.byteLength(entry, 'utf8');
|
||||
const separator = batch.length === 0 ? 0 : 1;
|
||||
if (batch.length > 0 && (batch.length >= maxEntries || bytes + separator + entryBytes > MAX_BODY_BYTES)) {
|
||||
batches.push(batch);
|
||||
batch = [];
|
||||
bytes = 2;
|
||||
}
|
||||
bytes += (batch.length === 0 ? 0 : 1) + entryBytes;
|
||||
batch.push(entry);
|
||||
}
|
||||
if (batch.length > 0) batches.push(batch);
|
||||
return batches;
|
||||
}
|
||||
|
||||
function defaultWarning(text) {
|
||||
process.stderr.write(`[${new Date().toISOString()}] ${text}\n`);
|
||||
}
|
||||
|
||||
// LogShipper batches entries in memory and sends them to OmniLogger in the background. Its methods
|
||||
// never throw and never wait on the network, and it never prints anything itself except a
|
||||
// rate-limited warning when OmniLogger cannot be reached.
|
||||
export class LogShipper {
|
||||
#service;
|
||||
#url;
|
||||
#token;
|
||||
#threshold;
|
||||
#flushIntervalMs;
|
||||
#maxBatchSize;
|
||||
#bufferCapacity;
|
||||
#timeoutMs;
|
||||
#warnIntervalMs;
|
||||
#onWarning;
|
||||
|
||||
#buffer = []; // serialized wire entries, oldest first
|
||||
#timer;
|
||||
#chain = Promise.resolve(); // sends run one at a time, in the order they were requested
|
||||
#flushRequested = false;
|
||||
#closed = false;
|
||||
#lastWarnAt = null;
|
||||
|
||||
constructor({
|
||||
baseUrl = '',
|
||||
ingestToken = '',
|
||||
service = '',
|
||||
level = 'info',
|
||||
flushIntervalMs = DEFAULT_FLUSH_INTERVAL_MS,
|
||||
maxBatchSize = DEFAULT_MAX_BATCH_SIZE,
|
||||
bufferCapacity = DEFAULT_BUFFER_CAPACITY,
|
||||
timeoutMs = DEFAULT_TIMEOUT_MS,
|
||||
warnIntervalMs = DEFAULT_WARN_INTERVAL_MS,
|
||||
onWarning = defaultWarning,
|
||||
} = {}) {
|
||||
this.#service = String(service);
|
||||
this.#url = `${String(baseUrl).replace(/\/+$/, '')}/api/logs`;
|
||||
this.#token = String(ingestToken);
|
||||
this.#threshold = LEVEL_RANK.get(canonicalLevel(level)) ?? LEVEL_RANK.get('info');
|
||||
this.#flushIntervalMs = positiveOr(flushIntervalMs, DEFAULT_FLUSH_INTERVAL_MS);
|
||||
this.#maxBatchSize = Math.min(
|
||||
MAX_BATCH_ENTRIES,
|
||||
Math.max(1, Math.floor(positiveOr(maxBatchSize, DEFAULT_MAX_BATCH_SIZE))),
|
||||
);
|
||||
this.#bufferCapacity = Math.max(1, Math.floor(positiveOr(bufferCapacity, DEFAULT_BUFFER_CAPACITY)));
|
||||
this.#timeoutMs = positiveOr(timeoutMs, DEFAULT_TIMEOUT_MS);
|
||||
this.#warnIntervalMs = positiveOr(warnIntervalMs, DEFAULT_WARN_INTERVAL_MS);
|
||||
this.#onWarning = typeof onWarning === 'function' ? onWarning : defaultWarning;
|
||||
|
||||
this.#timer = setInterval(() => this.#requestFlush(), this.#flushIntervalMs);
|
||||
this.#timer.unref();
|
||||
}
|
||||
|
||||
debug(...args) {
|
||||
this.#emit('debug', args);
|
||||
}
|
||||
|
||||
info(...args) {
|
||||
this.#emit('info', args);
|
||||
}
|
||||
|
||||
warn(...args) {
|
||||
this.#emit('warn', args);
|
||||
}
|
||||
|
||||
error(...args) {
|
||||
this.#emit('error', args);
|
||||
}
|
||||
|
||||
critical(...args) {
|
||||
this.#emit('critical', args);
|
||||
}
|
||||
|
||||
// log queues one entry. An optional context object is sent as the entry's context.
|
||||
log(level, message, context) {
|
||||
try {
|
||||
this.#record(level, String(message), context);
|
||||
} catch {
|
||||
// Shipping must never fail the caller.
|
||||
}
|
||||
}
|
||||
|
||||
// flush sends everything buffered so far. It resolves once those sends have finished, and it
|
||||
// never rejects.
|
||||
flush() {
|
||||
return this.#send();
|
||||
}
|
||||
|
||||
// close drains the buffer and stops the periodic flush. Entries logged after close are dropped.
|
||||
async close() {
|
||||
this.#closed = true;
|
||||
clearInterval(this.#timer);
|
||||
await this.#send();
|
||||
}
|
||||
|
||||
#emit(level, args) {
|
||||
try {
|
||||
this.#record(level, format(...args));
|
||||
} catch {
|
||||
// Shipping must never fail the caller.
|
||||
}
|
||||
}
|
||||
|
||||
#record(level, message, context) {
|
||||
if (this.#closed) return;
|
||||
const name = LOG_LEVELS.includes(canonicalLevel(level)) ? canonicalLevel(level) : 'info';
|
||||
if (LEVEL_RANK.get(name) < this.#threshold) return;
|
||||
|
||||
if (this.#buffer.length >= this.#bufferCapacity) {
|
||||
this.#warnOnce(`buffer full (cap=${this.#bufferCapacity}), dropping log entries for service "${this.#service}"`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Each field is serialized on its own so the context can be spliced in as raw JSON.
|
||||
const fields = [
|
||||
`"service":${JSON.stringify(this.#service)}`,
|
||||
`"level":${JSON.stringify(name)}`,
|
||||
`"message":${JSON.stringify(clampMessage(message))}`,
|
||||
];
|
||||
const contextJson = serializeContext(context);
|
||||
if (contextJson !== undefined) fields.push(`"context":${contextJson}`);
|
||||
fields.push(`"occurred_at":${JSON.stringify(new Date().toISOString())}`);
|
||||
this.#buffer.push(`{${fields.join(',')}}`);
|
||||
|
||||
if (this.#buffer.length >= this.#maxBatchSize) this.#requestFlush();
|
||||
}
|
||||
|
||||
// requestFlush asks for a flush without waiting for it. A request made while one is already
|
||||
// pending is dropped, so a burst of log calls queues at most one extra send.
|
||||
#requestFlush() {
|
||||
if (this.#flushRequested) return;
|
||||
this.#flushRequested = true;
|
||||
void this.#send();
|
||||
}
|
||||
|
||||
#send() {
|
||||
this.#chain = this.#chain.then(() => this.#sendBuffered()).catch(() => {});
|
||||
return this.#chain;
|
||||
}
|
||||
|
||||
async #sendBuffered() {
|
||||
this.#flushRequested = false;
|
||||
if (this.#buffer.length === 0) return;
|
||||
const entries = this.#buffer;
|
||||
this.#buffer = [];
|
||||
|
||||
let settled = 0; // entries of this flush that were sent or dropped
|
||||
for (const batch of packBatches(entries, this.#maxBatchSize)) {
|
||||
const retry = await this.#post(batch);
|
||||
// A batch that may pass on a later attempt keeps itself and every later entry for the next
|
||||
// flush. The rest of this flush is not sent now, so the entries still go out in order.
|
||||
if (retry) {
|
||||
this.#requeue(entries.slice(settled));
|
||||
return;
|
||||
}
|
||||
settled += batch.length;
|
||||
}
|
||||
}
|
||||
|
||||
// requeue puts entries that failed to send back at the front of the buffer, so the next flush
|
||||
// sends them before anything logged since. The buffer never grows past its capacity: when the
|
||||
// waiting entries and the buffer do not all fit, the newest entries are dropped.
|
||||
#requeue(entries) {
|
||||
const combined = [...entries, ...this.#buffer];
|
||||
const dropped = Math.max(0, combined.length - this.#bufferCapacity);
|
||||
this.#buffer = combined.slice(0, this.#bufferCapacity);
|
||||
if (dropped > 0) {
|
||||
this.#warnOnce(`buffer full while retrying, dropping ${dropped} log entries for service "${this.#service}"`);
|
||||
}
|
||||
}
|
||||
|
||||
// post sends one batch and reports whether it must be sent again. That is true when no HTTP
|
||||
// response came back, or the response was 429 or 5xx: those failures may pass. Any other non-2xx
|
||||
// response is OmniLogger rejecting the batch, which a retry would not change, so it is warned
|
||||
// about and dropped.
|
||||
async #post(batch) {
|
||||
const count = batch.length;
|
||||
let response;
|
||||
try {
|
||||
response = await globalThis.fetch(this.#url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${this.#token}`,
|
||||
},
|
||||
body: `[${batch.join(',')}]`,
|
||||
signal: AbortSignal.timeout(this.#timeoutMs),
|
||||
});
|
||||
} catch (err) {
|
||||
const detail = err?.cause?.code ?? err?.message ?? String(err);
|
||||
this.#warnOnce(`send ${count} entries to ${this.#url}, will retry: ${detail}`);
|
||||
return true;
|
||||
}
|
||||
// Read the body so the connection can be reused. A failure here does not change the outcome.
|
||||
await response.arrayBuffer().catch(() => {});
|
||||
const { status } = response;
|
||||
if (status >= 200 && status < 300) return false;
|
||||
if (status === 429 || status >= 500) {
|
||||
this.#warnOnce(`OmniLogger answered HTTP ${status} for ${count} entries, will retry`);
|
||||
return true;
|
||||
}
|
||||
this.#warnOnce(`OmniLogger rejected ${count} entries: HTTP ${status}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
#warnOnce(text) {
|
||||
const now = Date.now();
|
||||
if (this.#lastWarnAt !== null && now - this.#lastWarnAt < this.#warnIntervalMs) return;
|
||||
this.#lastWarnAt = now;
|
||||
try {
|
||||
this.#onWarning(`[logshipper] ${text}`);
|
||||
} catch {
|
||||
// A broken warning sink must not fail the caller either.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// createLogShipperFromEnv returns a LogShipper for service when both OMNILOGGER_URL and
|
||||
// OMNILOGGER_INGEST_TOKEN are set and non-empty, and null otherwise. A null result means shipping
|
||||
// is disabled: no shipper, no network calls, and no extra output. Options other than env are passed
|
||||
// to the LogShipper constructor.
|
||||
export function createLogShipperFromEnv(service, { env = process.env, ...options } = {}) {
|
||||
const baseUrl = String(env.OMNILOGGER_URL ?? '').trim();
|
||||
const ingestToken = String(env.OMNILOGGER_INGEST_TOKEN ?? '').trim();
|
||||
if (!baseUrl || !ingestToken) return null;
|
||||
return new LogShipper({ ...options, baseUrl, ingestToken, service });
|
||||
}
|
||||
|
||||
// mirrorConsole forwards each console.debug/log/info/warn/error call to the shipper at its level,
|
||||
// after printing the line exactly as before. It returns a function that restores the original
|
||||
// console methods. Call it once per shipper, or lines ship twice.
|
||||
export function mirrorConsole(shipper, target = globalThis.console) {
|
||||
const originals = new Map();
|
||||
for (const [method, level] of CONSOLE_LEVELS) {
|
||||
const original = target[method];
|
||||
if (typeof original !== 'function') continue;
|
||||
originals.set(method, original);
|
||||
target[method] = function mirrored(...args) {
|
||||
const result = original.apply(target, args);
|
||||
shipper[level](...args);
|
||||
return result;
|
||||
};
|
||||
}
|
||||
return function restoreConsole() {
|
||||
for (const [method, original] of originals) target[method] = original;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,544 @@
|
||||
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);
|
||||
});
|
||||
Reference in new issue
Block a user