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
21 changes: 21 additions & 0 deletions utils/logging/__tests__/all-exceptions.filter.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { BadRequestException } from '@nestjs/common';
import { QueryFailedError } from 'typeorm';
import { AllExceptionsFilter } from '../all-exceptions.filter';
import { PdfRenderQueueTimeoutError } from '../../report/pdf-render.queue';

function buildFkViolation(referencingTable: string) {
const sqlMessage = `Cannot delete or update a parent row: a foreign key constraint fails (\`app_db\`.\`${referencingTable}\`, CONSTRAINT \`FK_x\` FOREIGN KEY (\`teacherReferenceId\`) REFERENCES \`teachers\` (\`id\`))`;
Expand Down Expand Up @@ -29,6 +30,26 @@ function buildHost(response: any) {
}

describe('AllExceptionsFilter', () => {
it('replies 503 with the PDF_RENDER_BUSY code and a Retry-After header when the PDF render queue is full', () => {
const httpAdapter = { reply: jest.fn(), setHeader: jest.fn() };
const filter = new AllExceptionsFilter(httpAdapter as any);
const response: any = {};

filter.catch(new PdfRenderQueueTimeoutError(20000, 2), buildHost(response));

expect(response.err).toBeUndefined();
expect(httpAdapter.setHeader).toHaveBeenCalledWith(response, 'Retry-After', '60');
expect(httpAdapter.reply).toHaveBeenCalledWith(
response,
{
statusCode: 503,
code: 'PDF_RENDER_BUSY',
message: 'PDF generation is busy with other requests. Please try again in a few minutes.',
},
503,
);
});

it('attaches a non-HttpException to response.err (for pino-http to log) and replies 500', () => {
const httpAdapter = { reply: jest.fn() };
const filter = new AllExceptionsFilter(httpAdapter as any);
Expand Down
18 changes: 18 additions & 0 deletions utils/logging/all-exceptions.filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpServer, HttpS
import { snakeCase } from 'change-case';
import { DataSource, QueryFailedError } from 'typeorm';
import { getTranslatedProperty } from '@shared/utils/validation/class-validator-he';
import { PdfRenderQueueTimeoutError } from '@shared/utils/report/pdf-render.queue';

interface MysqlDriverError {
code?: string;
Expand Down Expand Up @@ -49,6 +50,9 @@ function getReferencingTable(exception: QueryFailedError): string | null {
return match?.[1] || null;
}

// Suggested client back-off when the PDF render queue is full.
const PDF_RENDER_BUSY_RETRY_AFTER_SECONDS = 60;

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
private readonly logger = new Logger(AllExceptionsFilter.name);
Expand Down Expand Up @@ -104,6 +108,20 @@ export class AllExceptionsFilter implements ExceptionFilter {
return;
}

if (exception instanceof PdfRenderQueueTimeoutError) {
// Too many PDF renders at once: a temporary overload, not a server bug.
// The client translates `code` into a localized "try again shortly" message.
this.logger.warn(exception.message);
const body = {
statusCode: HttpStatus.SERVICE_UNAVAILABLE,
code: exception.code,
message: 'PDF generation is busy with other requests. Please try again in a few minutes.',
};
this.httpAdapter.setHeader(response, 'Retry-After', String(PDF_RENDER_BUSY_RETRY_AFTER_SECONDS));
this.httpAdapter.reply(response, body, HttpStatus.SERVICE_UNAVAILABLE);
return;
}

const isHttpException = exception instanceof HttpException;
const status = isHttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
const body = isHttpException
Expand Down
6 changes: 6 additions & 0 deletions utils/report/pdf-render.queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,13 @@ export function getPdfRenderBudgetMs(): number {
return Number.isFinite(configured) && configured > 0 ? configured : 45000;
}

export const PDF_RENDER_BUSY_CODE = 'PDF_RENDER_BUSY';

export class PdfRenderQueueTimeoutError extends Error {
// Stable machine-readable code: the HTTP layer sends it to clients, which
// map it to a localized "busy, try again" message.
readonly code = PDF_RENDER_BUSY_CODE;

constructor(allowedWaitMs: number, maxConcurrentBrowsers: number) {
super(`PDF render queue wait exceeded ${allowedWaitMs}ms (max ${maxConcurrentBrowsers} concurrent browsers)`);
this.name = 'PdfRenderQueueTimeoutError';
Expand Down
Loading