Skip to content
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. 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“.
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“. Ein Backend-Prozess, der startet, während die Datenbank nicht erreichbar ist, wartet bis zu etwa einer Minute auf sie, statt sich zu beenden, und schreibt für jeden neuen Versuch eine Warnung ins Protokoll. Ist die Datenbank danach noch immer nicht erreichbar, schlägt der Start fehl und wird als Fehler gemeldet. Ein falscher Host oder Port in `DATABASE_URL` lässt den Start deshalb erst nach etwa einer Minute fehlschlagen.

Auch eine Anfrage, die ihr Client aufgegeben hat, meldet das Backend nicht. Das passiert etwa, wenn du einen Browser-Tab schließt oder einen Upload abbrichst, während die Daten noch übertragen werden. Die Anfrage erhält den Status `499`, zählt in den Anfragemetriken zu den Clientfehlern und hinterlässt eine einzige Debug-Zeile im Protokoll. Jeder andere Fehler in einer Anfrage, deren Client nicht mehr verbunden ist, wird weiterhin gemeldet. Eine App-Anfrage mit leerem oder abgeschnittenem JSON-Body beantwortet das Backend mit `400 INVALID_JSON`, ohne sie zu melden.

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. 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.
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. A backend process that starts while the database is unreachable waits up to about a minute for it instead of exiting, and logs a warning line for each new attempt. If the database is still unreachable after that, the start fails and is reported as an error. So a wrong host or port in `DATABASE_URL` takes about a minute to fail the start.

The backend does not report a request its client abandoned either, for example when you close a tab or cancel an upload while its body is still arriving. The request is answered with status `499`, counted among the client errors in the request metrics, and logged as a single debug line. Any other error in a request whose client has disconnected is still reported. An app request whose JSON body is empty or cut short is answered with `400 INVALID_JSON` and is not reported.

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. 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.
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. Un processus backend qui démarre pendant que la base est injoignable l’attend jusqu’à une minute environ au lieu de s’arrêter, et écrit un avertissement dans le journal à chaque nouvelle tentative. Si la base reste injoignable au-delà, le démarrage échoue et est signalé comme une erreur. Un hôte ou un port erroné dans `DATABASE_URL` ne fait donc échouer le démarrage qu’au bout d’une minute environ.

Le backend ne signale pas non plus une requête abandonnée par son client, par exemple quand tu fermes un onglet ou annules un téléversement pendant que son corps arrive encore. La requête reçoit le statut `499`, compte parmi les erreurs client dans les métriques de requêtes et laisse une seule ligne de débogage dans le journal. Toute autre erreur survenue dans une requête dont le client s’est déconnecté reste signalée. Une requête de l’application dont le corps JSON est vide ou tronqué reçoit `400 INVALID_JSON` et n’est pas signalée.

Expand Down
52 changes: 52 additions & 0 deletions packages/shared/src/db/retry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,56 @@ describe('withRetry', () => {
).rejects.toThrow();
expect(op).toHaveBeenCalledTimes(3);
});

it('stops doubling the delay at maxDelayMs', async () => {
const sleep = vi.fn(async (_ms: number) => undefined);
const op = vi
.fn()
.mockRejectedValueOnce(connErr('57P03'))
.mockRejectedValueOnce(connErr('57P03'))
.mockRejectedValueOnce(connErr('57P03'))
.mockRejectedValueOnce(connErr('57P03'))
.mockResolvedValueOnce('ok');
expect(
await withRetry(op, {
attempts: 5,
baseDelayMs: 100,
maxDelayMs: 250,
sleep,
}),
).toBe('ok');
expect(sleep.mock.calls.map(([ms]) => ms)).toEqual([100, 200, 250, 250]);
});

it('retries at the capped delay until the budget runs out', async () => {
let now = 0;
const clock = vi.spyOn(Date, 'now').mockImplementation(() => now);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
const sleep = vi.fn(async (ms: number) => {
now += ms;
});
const op = vi.fn().mockRejectedValue(connErr('57P03'));
try {
await expect(
withRetry(op, {
attempts: Number.POSITIVE_INFINITY,
baseDelayMs: 1000,
maxDelayMs: 1000,
timeoutMs: 3500,
sleep,
}),
).rejects.toThrow('connection error 57P03');
// Attempts at 0, 1, 2 and 3 s; a fourth wait would end past the budget.
expect(op).toHaveBeenCalledTimes(4);
expect(sleep.mock.calls.map(([ms]) => ms)).toEqual([1000, 1000, 1000]);
// An unbounded count names no total it could reach.
expect(warn).toHaveBeenNthCalledWith(
1,
'[db] transient error on attempt 1, retrying in 1000ms: connection error 57P03',
);
} finally {
clock.mockRestore();
warn.mockRestore();
}
});
});
17 changes: 14 additions & 3 deletions packages/shared/src/db/retry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,19 @@ const TRANSIENT_NODE_CODES = new Set([
]);

export interface RetryOptions {
/** Maximum number of attempts (including the first). */
/**
* Maximum number of attempts (including the first). `Infinity` leaves
* `timeoutMs` alone to end the retries.
*/
attempts?: number;
/** Base delay in milliseconds for exponential backoff. */
baseDelayMs?: number;
/**
* Ceiling for one backoff delay, in milliseconds: the delay stops doubling
* there, so a long budget keeps retrying at that interval instead of
* sleeping through most of it. Unbounded by default.
*/
maxDelayMs?: number;
/** Total wall-clock budget in milliseconds across all attempts. */
timeoutMs?: number;
/** Override for the transient-error classifier (primarily for tests). */
Expand Down Expand Up @@ -72,6 +81,7 @@ export async function withRetry<T>(
): Promise<T> {
const attempts = options.attempts ?? 5;
const baseDelayMs = options.baseDelayMs ?? 200;
const maxDelayMs = options.maxDelayMs ?? Number.POSITIVE_INFINITY;
const timeoutMs = options.timeoutMs ?? 30_000;
const isTransient = options.isTransient ?? isTransientDbError;
const sleep = options.sleep ?? defaultSleep;
Expand All @@ -87,12 +97,13 @@ export async function withRetry<T>(
if (!isTransient(error) || attempt === attempts - 1) {
throw error;
}
const delay = baseDelayMs * 2 ** attempt;
const delay = Math.min(baseDelayMs * 2 ** attempt, maxDelayMs);
if (Date.now() + delay > deadline) {
throw error;
}
const of = Number.isFinite(attempts) ? `/${attempts}` : '';
console.warn(
`[db] transient error on attempt ${attempt + 1}/${attempts}, ` +
`[db] transient error on attempt ${attempt + 1}${of}, ` +
`retrying in ${delay}ms: ${error instanceof Error ? error.message : String(error)}`,
);
await sleep(delay);
Expand Down
223 changes: 223 additions & 0 deletions services/platform/backend/db/migrate.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
// @vitest-environment node

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

import { afterEach, describe, expect, it, vi } from 'vitest';

import { runBootMigrations } from './migrate.ts';

/** 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]);
}

const SHUTTING_DOWN = fatal('57P03', 'the database system is shutting down');
const BAD_PASSWORD = fatal(
'28P01',
'password authentication failed for user "tale"',
);

/**
* A server that refuses every connection's startup with `answer()`'s FATAL
* — what PostgreSQL does while it shuts down, or when it rejects the
* credentials — and counts the connections it saw.
*/
async function refusingServer(
answer: () => Buffer,
): Promise<{ url: string; connections: () => number; close: () => void }> {
let connections = 0;
const server: Server = createServer((socket: Socket) => {
connections += 1;
socket.once('data', () => {
socket.end(answer());
});
});
await new Promise<void>((resolve) => {
server.listen(0, '127.0.0.1', resolve);
});
const { port } = server.address() as AddressInfo;
return {
url: `postgres://tale:pw@127.0.0.1:${port}/tale_app`,
connections: () => connections,
close: () => server.close(),
};
}

describe('runBootMigrations, while the database is unavailable', () => {
const closers: (() => void)[] = [];
afterEach(() => {
for (const close of closers.splice(0)) close();
vi.restoreAllMocks();
});

it('waits out a database that is shutting down instead of failing the boot', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => undefined);
// The database refuses as it shuts down until the second pause, then
// answers again — with a refusal no wait can fix, so the step stops
// there and the test needs no server that speaks the whole protocol.
let answer = SHUTTING_DOWN;
const server = await refusingServer(() => answer);
closers.push(server.close);
const sleep = vi.fn(async () => {
if (sleep.mock.calls.length === 2) answer = BAD_PASSWORD;
});

const failure = await runBootMigrations({
databaseUrl: server.url,
log: () => undefined,
sleep,
}).then(
() => new Error('the step was expected to fail'),
(error: unknown) => error,
);

// Two refusals waited out, 1 s then 2 s apart, then the real failure —
// rejected at once, as before.
expect(failure).toMatchObject({ code: '28P01' });
expect(sleep.mock.calls).toEqual([[1000], [2000]]);
// One connection per attempt: a lock never taken is not unlocked over a
// second one.
expect(server.connections()).toBe(3);
});

it('still fails the boot once the outage outlasts the wait', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => undefined);
let now = 0;
const server = await refusingServer(() => SHUTTING_DOWN);
closers.push(server.close);
const sleep = vi.fn(async (ms: number) => {
now += ms;
});

const failure = await runBootMigrations({
databaseUrl: server.url,
log: () => undefined,
databaseWaitMs: 20_000,
sleep,
now: () => now,
}).then(
() => new Error('the step was expected to fail'),
(error: unknown) => error,
);

// Refusals at 0, 1, 3, 7, 12, 17 and 22 s — the pause stops doubling at
// 5 s — and the last one comes after the 20 s wait, so it is what the
// boot reports.
expect(failure).toMatchObject({
code: '57P03',
message: 'the database system is shutting down',
});
expect(sleep.mock.calls).toEqual([
[1000],
[2000],
[4000],
[5000],
[5000],
[5000],
]);
expect(server.connections()).toBe(7);
});

it('times the outage from its first refusal, not from the start of the step', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => undefined);
let now = 0;
// The first refusal arrives 55 s into the step — the time a process can
// spend queued behind another's migration lock before the database goes
// away under both.
let refusals = 0;
const server = await refusingServer(() => {
refusals += 1;
if (refusals === 1) now += 55_000;
return SHUTTING_DOWN;
});
closers.push(server.close);
const sleep = vi.fn(async (ms: number) => {
now += ms;
});

const failure = await runBootMigrations({
databaseUrl: server.url,
log: () => undefined,
databaseWaitMs: 20_000,
sleep,
now: () => now,
}).then(
() => new Error('the step was expected to fail'),
(error: unknown) => error,
);

// The whole 20 s wait, counted from the refusal at 55 s.
expect(failure).toMatchObject({ code: '57P03' });
expect(sleep.mock.calls).toEqual([
[1000],
[2000],
[4000],
[5000],
[5000],
[5000],
]);
expect(server.connections()).toBe(7);
});

it('keeps its clock off the wall clock, so a time step at boot cannot cut the wait short', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => undefined);
// The wall clock leaps an hour on every read — what a host syncing its
// time at boot can do. The wait must not notice.
let wall = 0;
vi.spyOn(Date, 'now').mockImplementation(() => (wall += 3_600_000));
let refusals = 0;
const server = await refusingServer(() => {
refusals += 1;
return refusals <= 3 ? SHUTTING_DOWN : BAD_PASSWORD;
});
closers.push(server.close);
const sleep = vi.fn(async (_ms: number) => undefined);

const failure = await runBootMigrations({
databaseUrl: server.url,
log: () => undefined,
databaseWaitMs: 20_000,
sleep,
}).then(
() => new Error('the step was expected to fail'),
(error: unknown) => error,
);

// All three refusals waited out, then the real failure.
expect(failure).toMatchObject({ code: '28P01' });
expect(sleep.mock.calls).toEqual([[1000], [2000], [4000]]);
});

it('fails at once, over a single connection, on an error a wait cannot fix', async () => {
const server = await refusingServer(() => BAD_PASSWORD);
closers.push(server.close);
const sleep = vi.fn(async () => undefined);

await expect(
runBootMigrations({
databaseUrl: server.url,
log: () => undefined,
sleep,
}),
).rejects.toMatchObject({ code: '28P01' });
expect(sleep).not.toHaveBeenCalled();
expect(server.connections()).toBe(1);
});
});
Loading
Loading