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

it('replies 413 with an explanation (not a bare 500) when printing the PDF timed out', () => {
const httpAdapter = { reply: jest.fn() };
const filter = new AllExceptionsFilter(httpAdapter as any);
const response: any = {};

filter.catch(new PdfPrintTimeoutError(30000), buildHost(response));

expect(response.err).toBeUndefined();
expect(httpAdapter.reply).toHaveBeenCalledWith(
response,
expect.objectContaining({ statusCode: 413, code: 'PDF_PRINT_TIMEOUT', message: expect.stringContaining('הדוח גדול מדי') }),
413,
);
});

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
14 changes: 13 additions & 1 deletion utils/logging/all-exceptions.filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +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';
import { PdfPrintTimeoutError, PdfRenderQueueTimeoutError } from '@shared/utils/report/pdf-render.queue';

interface MysqlDriverError {
code?: string;
Expand Down Expand Up @@ -122,6 +122,18 @@ export class AllExceptionsFilter implements ExceptionFilter {
return;
}

if (exception instanceof PdfPrintTimeoutError) {
// The report is too large to print: the user has to narrow it, so say so (413, not a bare 500).
this.logger.warn(exception.message);
const body = {
statusCode: HttpStatus.PAYLOAD_TOO_LARGE,
code: exception.code,
message: 'הדוח גדול מדי להפקה כ-PDF. יש לצמצם את הסינון (למשל לטווח תאריכים קצר יותר) או להוריד אותו כקובץ Excel.',
};
this.httpAdapter.reply(response, body, HttpStatus.PAYLOAD_TOO_LARGE);
return;
}

const isHttpException = exception instanceof HttpException;
const status = isHttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
const body = isHttpException
Expand Down
12 changes: 12 additions & 0 deletions utils/report/__tests__/markup-to-pdf.generator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,18 @@ describe('MarkupToPdfReportGenerator', () => {
expect(mockBrowser.close).toHaveBeenCalled();
});

it('should turn a Page.printToPDF timeout into a PdfPrintTimeoutError without retrying', async () => {
mockPage.pdf.mockRejectedValue(new Error('waiting for Page.printToPDF failed: timeout 30000ms exceeded'));

await expect(generator.convertMarkupToPdf(markup)).rejects.toMatchObject({
name: 'PdfPrintTimeoutError',
code: 'PDF_PRINT_TIMEOUT',
timeoutMs: 30000,
});
expect(puppeteer.launch).toHaveBeenCalledTimes(1);
expect(mockBrowser.close).toHaveBeenCalled();
});

it('should close browser even if PDF generation fails', async () => {
const error = new Error('PDF generation error');
mockPage.pdf.mockRejectedValue(error);
Expand Down
20 changes: 15 additions & 5 deletions utils/report/markup-to-pdf.generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
PUPPETEER_LAUNCH_ARGS,
getPdfRenderBudgetMs,
getPdfRenderScope,
PdfPrintTimeoutError,
releaseBrowserSlot,
} from './pdf-render.queue';

Expand Down Expand Up @@ -112,11 +113,20 @@ export abstract class MarkupToPdfReportGenerator<T = any, U = any> extends BaseR
await page.setContent(markup, { waitUntil: 'domcontentloaded' });
}

return await page.pdf({
format: 'A4',
printBackground: true,
timeout: getPdfPrintTimeoutMs(),
});
const printTimeoutMs = getPdfPrintTimeoutMs();
try {
return await page.pdf({
format: 'A4',
printBackground: true,
timeout: printTimeoutMs,
});
} catch (e) {
// puppeteer: "waiting for Page.printToPDF failed: timeout 30000ms exceeded"
if (e instanceof Error && (e.name === 'TimeoutError' || /printToPDF.*timeout/i.test(e.message))) {
throw new PdfPrintTimeoutError(printTimeoutMs, { cause: e });
}
throw e;
}
} finally {
// Rows of a shared scope browser take their page with them, so a
// many-row report can't pile up open pages; standalone browsers would
Expand Down
15 changes: 15 additions & 0 deletions utils/report/pdf-render.queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,21 @@ export class PdfRenderQueueTimeoutError extends Error {
}
}

export const PDF_PRINT_TIMEOUT_CODE = 'PDF_PRINT_TIMEOUT';

// Page.printToPDF ran out of time: the report is too heavy to print in one go (typically a
// very large export). Retrying the same request cannot help, so unlike a busy queue this is
// reported to the client as a request to narrow the report.
export class PdfPrintTimeoutError extends Error {
readonly code = PDF_PRINT_TIMEOUT_CODE;

constructor(readonly timeoutMs: number, options?: { cause?: unknown }) {
super(`PDF print exceeded ${timeoutMs}ms`);
this.name = 'PdfPrintTimeoutError';
if (options?.cause !== undefined) (this as any).cause = options.cause;
}
}

// ---------------------------------------------------------------- queue ----

let activeBrowserSlots = 0;
Expand Down
Loading