Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/de/self-hosted/configuration/observability-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ SENTRY_TRACES_SAMPLE_RATE=0.1

Die Abtastrate gilt für Leistungstraces im Browser. Das Backend sendet Fehlerberichte, keine Leistungstraces. In der Entwicklung beträgt die Standardrate für Browsertraces 1.0. Wähle für den Produktivbetrieb einen Wert passend zu deinem Überwachungsbudget. Backend-Ereignisse enthalten nie Cookies oder Inhalte der Anfrage. Autorisierungs-, Cookie-, API-Schlüssel-, Token-, Secret- und Sitzungs-Header, Webhook- und Freigabe-Tokens in URLs sowie Zugangswerte in Abfrageparametern wie OAuth-Codes werden vor dem Senden durch `[Filtered]` ersetzt. Stackframes und Fehlermeldungen werden unverändert übertragen; berücksichtige bei der Zielwahl deine Vorgaben zur Datenverarbeitung.

Ein Neustart der Datenbank gilt nicht als Fehler; ein verwaltetes Upgrade erstellt die Datenbank bei jedem Release neu. Solange sie nicht erreichbar ist, antworten Anfragen mit `503 DATABASE_UNAVAILABLE` und `Retry-After`, Hintergrundjobs schlagen fehl und werden nach der Richtlinie ihrer Warteschlange wiederholt, und offene Live-Update-Streams warten ab und laufen danach weiter. Stattdessen landet jeweils eine Warnung im Protokoll. Bleibt die Datenbank länger als etwa eine Minute unerreichbar, sendet ein API-Prozess mit offenen Live-Update-Streams für diesen Ausfall ein einziges Ereignis der Stufe „warning“.
Ein Neustart der Datenbank gilt nicht als Fehler; ein verwaltetes Upgrade erstellt die Datenbank bei jedem Release neu. Solange sie nicht erreichbar ist, antworten Anfragen mit `503 DATABASE_UNAVAILABLE` und `Retry-After`, Hintergrundjobs schlagen fehl und werden nach der Richtlinie ihrer Warteschlange wiederholt, und offene Live-Update-Streams warten ab und laufen danach weiter. Stattdessen landet jeweils eine Warnung im Protokoll. Die Job-Warteschlange schreibt für den ganzen Ausfall nur eine, nicht eine für jede fehlgeschlagene Abfrage. Bleibt die Datenbank länger als etwa eine Minute unerreichbar, sendet ein API-Prozess mit offenen Live-Update-Streams für diesen Ausfall ein einziges Ereignis der Stufe „warning“.

Fehler, die auf keinen Defekt in Tale hinweisen, meldet der Browser nicht:

Expand Down
2 changes: 1 addition & 1 deletion docs/en/self-hosted/configuration/observability-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ SENTRY_TRACES_SAMPLE_RATE=0.1

The trace sample rate applies to browser performance traces. The backend sends errors, not performance traces. Browser traces default to 1.0 in development; choose a production sample rate that fits your monitoring budget. Backend events never include request cookies or bodies. Authorization, cookie, API-key, token, secret and session headers, webhook and share tokens in URLs, and credential query values such as OAuth codes are replaced with `[Filtered]` before sending. Stack frames and error messages are sent as they are, so choose the destination according to your data-handling requirements.

A database restart is not reported as an error; a managed upgrade recreates the database on every release. While it is unreachable, requests answer `503 DATABASE_UNAVAILABLE` with `Retry-After`, background jobs fail and retry under their queue's policy, and open live-update streams back off and resume. Each logs a warning line instead. When the database stays unreachable for more than about a minute, an API process with live-update streams open sends one warning-level event for that outage.
A database restart is not reported as an error; a managed upgrade recreates the database on every release. While it is unreachable, requests answer `503 DATABASE_UNAVAILABLE` with `Retry-After`, background jobs fail and retry under their queue's policy, and open live-update streams back off and resume. Each logs a warning line instead. The job queue logs one for the whole outage, not one for every failed poll. When the database stays unreachable for more than about a minute, an API process with live-update streams open sends one warning-level event for that outage.

The browser leaves out errors that do not indicate a defect in Tale:

Expand Down
2 changes: 1 addition & 1 deletion docs/fr/self-hosted/configuration/observability-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ SENTRY_TRACES_SAMPLE_RATE=0.1

Le taux d’échantillonnage concerne les traces de performance du navigateur. Le backend envoie des erreurs, pas de traces de performance. Le taux par défaut des traces du navigateur est de 1.0 en développement. Choisis un taux adapté à ton budget de supervision en production. Les événements du backend n’incluent jamais les cookies ni le corps des requêtes. Les en-têtes d’autorisation, de cookie, de clé d’API, de jeton, de secret et de session, les jetons de webhook et de partage dans les URL ainsi que les valeurs d’identification des paramètres de requête, comme les codes OAuth, sont remplacés par `[Filtered]` avant l’envoi. Les cadres de pile et les messages d’erreur sont envoyés tels quels ; choisis la destination selon tes exigences de traitement des données.

Un redémarrage de la base de données n’est pas signalé comme une erreur : une mise à niveau gérée recrée la base à chaque version. Tant qu’elle est injoignable, les requêtes répondent `503 DATABASE_UNAVAILABLE` avec `Retry-After`, les tâches d’arrière-plan échouent puis sont relancées selon la politique de leur file, et les flux de mise à jour en direct ouverts patientent puis reprennent. Chacun écrit un avertissement dans le journal à la place. Si la base reste injoignable plus d’une minute environ, un processus API ayant des flux ouverts envoie un seul événement de niveau « warning » pour cette panne.
Un redémarrage de la base de données n’est pas signalé comme une erreur : une mise à niveau gérée recrée la base à chaque version. Tant qu’elle est injoignable, les requêtes répondent `503 DATABASE_UNAVAILABLE` avec `Retry-After`, les tâches d’arrière-plan échouent puis sont relancées selon la politique de leur file, et les flux de mise à jour en direct ouverts patientent puis reprennent. Chacun écrit un avertissement dans le journal à la place. La file des tâches n’en écrit qu’un pour toute la panne, et non un à chaque interrogation échouée. Si la base reste injoignable plus d’une minute environ, un processus API ayant des flux ouverts envoie un seul événement de niveau « warning » pour cette panne.

Le navigateur ne signale pas les erreurs qui ne révèlent aucun défaut de Tale :

Expand Down
12 changes: 12 additions & 0 deletions services/platform/backend/db/unavailable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,18 @@ describe('describeDatabaseError', () => {
).toBe('connect ECONNREFUSED 10.0.0.5:5432');
expect(describeDatabaseError('plain')).toBe('plain');
});

it('reads a plain copy of an error’s fields, as pg-boss re-emits one', () => {
expect(
describeDatabaseError({
code: '57P01',
message: 'terminating connection due to administrator command',
queue: 'rag.index_file',
}),
).toBe('57P01 terminating connection due to administrator command');
expect(describeDatabaseError({ code: '57P01' })).toBe('57P01');
expect(describeDatabaseError({})).toBe('');
});
});

describe('a database error a library swallowed', () => {
Expand Down
15 changes: 9 additions & 6 deletions services/platform/backend/db/unavailable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import { AsyncLocalStorage } from 'node:async_hooks';
* restart, so this is an operational event, not a defect: a request answers
* a retryable 503 (`error-reporting.ts`), the `/events` stream backs off
* (`realtime/sse.ts`), a job fails for pg-boss to retry (`jobs/runner.ts`),
* and none of them reports an error.
* pg-boss's failing polls log one line per outage (`jobs/boss.ts`), and none
* of them reports an error.
*
* Deliberately narrower than its two neighbours. `isTransientDbError`
* (`@tale/shared/db/retry`) decides whether to rerun an operation in place
Expand Down Expand Up @@ -111,13 +112,15 @@ function stampedByPostgresJs(error: object): boolean {
}

/** One line for a log: the code, when the message does not already name
* it, then the message. */
* it, then the message. Reads any object that carries a message — pg-boss
* re-emits an error as a plain copy of its fields (`jobs/boss.ts`). */
export function describeDatabaseError(error: unknown): string {
if (!(error instanceof Error)) return String(error);
if (error === null || typeof error !== 'object') return String(error);
const rawMessage: unknown = Reflect.get(error, 'message');
const message = typeof rawMessage === 'string' ? rawMessage : '';
const code: unknown = Reflect.get(error, 'code');
return typeof code === 'string' && !error.message.includes(code)
? `${code} ${error.message}`
: error.message;
if (typeof code !== 'string' || message.includes(code)) return message;
return message === '' ? code : `${code} ${message}`;
}

/**
Expand Down
277 changes: 277 additions & 0 deletions services/platform/backend/jobs/boss.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,277 @@
// @vitest-environment node

import {
createServer,
type AddressInfo,
type Server,
type Socket,
} from 'node:net';

import pg from 'pg';
import type { PgBoss, WipData } from 'pg-boss';
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';

import { createBoss } from './boss.ts';

/** A local server; `answer` gets each connection. */
async function listen(
answer: (socket: Socket) => void,
): Promise<{ server: Server; port: number }> {
const server = createServer(answer);
await new Promise<void>((resolve) => {
server.listen(0, '127.0.0.1', resolve);
});
const { port } = server.address() as AddressInfo;
return { server, port };
}

/** A FATAL ErrorResponse, as PostgreSQL sends one before it hangs up. */
function fatal(code: string, message: string): Buffer {
const fields = Buffer.concat([
...[
['S', 'FATAL'],
['V', 'FATAL'],
['C', code],
['M', message],
].map(([key, value]) => Buffer.from(`${key}${value}\0`)),
Buffer.from([0]),
]);
const header = Buffer.alloc(5);
header.write('E', 0);
header.writeInt32BE(fields.length + 4, 1);
return Buffer.concat([header, fields]);
}

/** What node-postgres — pg-boss's driver — rejects a connection with. */
async function connectError(port: number): Promise<Error> {
const client = new pg.Client({
connectionString: `postgres://tale:pw@127.0.0.1:${port}/tale`,
});
try {
await client.connect();
} catch (error) {
if (error instanceof Error) return error;
throw error;
}
await client.end();
throw new Error('the connection was expected to fail');
}

/**
* What a pg-boss 12 worker emits for a failed poll: it appends its queue and
* id to the error's message, then re-emits a plain copy of the error's own
* fields with `queue` and `worker` beside them (`pg-boss/dist/worker.js`,
* `manager.js`).
*/
function failedPoll(error: Error, queue: string): object {
const worker = `worker-${queue}`;
return {
...copy(error),
message: `${error.message} (Queue: ${queue}, Worker: ${worker})`,
stack: error.stack,
queue,
worker,
};
}

/** An error's own enumerable fields — what pg-boss's `{ ...error }` keeps:
* `code` and the rest, never the prototype or `cause`. */
function copy(error: Error): Record<string, unknown> {
return Object.fromEntries(Object.entries(error));
}

/** Emit what pg-boss emits. Its event map types the `error` event as an
* `Error`, yet a worker's failed poll arrives as a plain copy of one. */
function emitError(boss: PgBoss, failure: object): void {
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- pg-boss's event map calls its plain copies Error
boss.emit('error', failure as Error);
}

/** One pg-boss worker as `getWipData` reports it. */
function wipWorker(lastFetchedOn: number | null): WipData {
return {
id: 'worker-1',
workId: 'worker-1',
name: '__pgboss__send-it',
options: {},
state: 'active',
count: 0,
createdOn: 0,
lastFetchedOn,
lastJobStartedOn: null,
lastJobEndedOn: null,
lastJobDuration: null,
lastError: null,
lastErrorOn: null,
};
}

const OUTAGE_LINE =
'[backend] pg-boss: database unavailable, polls fail quietly until one succeeds:';

/** What a restart says, in turn: the server is going away, it is gone, a
* connection dropped mid-handshake, it is starting up. */
interface Restart {
shutdown: Error;
refused: Error;
hungUp: Error;
startingUp: Error;
}

describe('createBoss error log', () => {
let restart: Restart;
let closedPort: number;

beforeAll(async () => {
const startingUp = await listen((socket) => {
socket.once('data', () => {
socket.end(fatal('57P03', 'the database system is starting up'));
});
});
const hangUp = await listen((socket) => {
socket.end();
});
const startingUpError = await connectError(startingUp.port);
const hungUpError = await connectError(hangUp.port);
startingUp.server.close();
hangUp.server.close();
closedPort = hangUp.port;
const shutdown = new pg.DatabaseError(
'terminating connection due to administrator command',
0,
'error',
);
shutdown.code = '57P01';
restart = {
shutdown,
refused: await connectError(closedPort),
hungUp: hungUpError,
startingUp: startingUpError,
};
});

afterEach(() => {
vi.restoreAllMocks();
vi.useRealTimers();
});

function bossWithSpies() {
// Constructing pg-boss opens nothing; `start` would.
const boss: PgBoss = createBoss(
`postgres://tale:pw@127.0.0.1:${closedPort}/tale`,
{ supervise: false },
);
const wip = vi.spyOn(boss, 'getWipData').mockReturnValue([]);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
return { boss, warn, error, wip };
}

it('logs a restart’s burst of failed polls as one warning, then any other error in full', () => {
const { boss, warn, error } = bossWithSpies();

// The pool's idle clients hear the shutdown first, and pass it on as is.
emitError(boss, restart.shutdown);
// Then ten rounds of sixty queues' workers polling a database that is
// going, gone and coming back: a 20 s restart.
const kinds = [
restart.shutdown,
restart.refused,
restart.hungUp,
restart.startingUp,
];
for (let round = 0; round < 10; round++) {
for (let queue = 0; queue < 60; queue++) {
const kind = kinds[(round + queue) % kinds.length] ?? restart.refused;
emitError(boss, failedPoll(kind, `queue-${queue}`));
}
}
// The queue cache's refresh re-emits a copy with no queue.
emitError(boss, {
...copy(restart.refused),
message: restart.refused.message,
stack: restart.refused.stack,
});

expect(warn).toHaveBeenCalledTimes(1);
expect(warn).toHaveBeenCalledWith(
`${OUTAGE_LINE} 57P01 terminating connection due to administrator command`,
);
expect(error).not.toHaveBeenCalled();

const missingTable = new pg.DatabaseError(
'relation "pgboss.job" does not exist',
0,
'error',
);
missingTable.code = '42P01';
const failure = failedPoll(missingTable, 'queue-0');
emitError(boss, failure);

expect(error).toHaveBeenCalledTimes(1);
expect(error).toHaveBeenCalledWith('[backend] pg-boss error:', failure);
expect(warn).toHaveBeenCalledTimes(1);
});

it('reads node-postgres’s code-less hang-up through the worker’s suffix', () => {
const { boss, warn, error } = bossWithSpies();

emitError(boss, failedPoll(restart.hungUp, 'queue-0'));

expect(error).not.toHaveBeenCalled();
expect(warn).toHaveBeenCalledWith(
`${OUTAGE_LINE} Connection terminated unexpectedly`,
);
});

it('keeps logging in full what is not an unavailable database', () => {
const { boss, warn, error } = bossWithSpies();
// A pool with no free client is capacity, and rejected credentials are
// an operator's to fix — neither is a restart.
const exhausted = failedPoll(
new Error('timeout exceeded when trying to connect'),
'queue-0',
);
const rejected = failedPoll(
Object.assign(new Error('password authentication failed'), {
code: '28P01',
}),
'queue-1',
);

emitError(boss, exhausted);
emitError(boss, rejected);

expect(warn).not.toHaveBeenCalled();
expect(error.mock.calls).toEqual([
['[backend] pg-boss error:', exhausted],
['[backend] pg-boss error:', rejected],
]);
});

it('is re-armed once a poll succeeds, so the next outage logs again', () => {
vi.useFakeTimers({ toFake: ['Date'], now: 1_000_000 });
const { boss, warn, wip } = bossWithSpies();
const fail = () => {
emitError(boss, failedPoll(restart.refused, 'queue-0'));
};

fail();
expect(warn).toHaveBeenCalledTimes(1);

// Polls that last succeeded before the outage do not end it.
wip.mockReturnValue([wipWorker(null), wipWorker(999_000)]);
vi.advanceTimersByTime(30_000);
fail();
expect(warn).toHaveBeenCalledTimes(1);
// The api role runs no queue's worker; the cron clock's is internal.
expect(wip).toHaveBeenCalledWith({ includeInternal: true });

// The database is back: a poll succeeds.
wip.mockReturnValue([wipWorker(Date.now())]);
vi.advanceTimersByTime(60_000);
fail();
fail();
expect(warn).toHaveBeenCalledTimes(2);
});
});
Loading
Loading