diff --git a/utils/logging/__tests__/all-exceptions.filter.spec.ts b/utils/logging/__tests__/all-exceptions.filter.spec.ts index a9fd97b..02e761e 100644 --- a/utils/logging/__tests__/all-exceptions.filter.spec.ts +++ b/utils/logging/__tests__/all-exceptions.filter.spec.ts @@ -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\`))`; @@ -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); diff --git a/utils/logging/all-exceptions.filter.ts b/utils/logging/all-exceptions.filter.ts index 96dd12c..072212d 100644 --- a/utils/logging/all-exceptions.filter.ts +++ b/utils/logging/all-exceptions.filter.ts @@ -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; @@ -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 diff --git a/utils/report/__tests__/markup-to-pdf.generator.spec.ts b/utils/report/__tests__/markup-to-pdf.generator.spec.ts index 27fda7d..6f1e589 100644 --- a/utils/report/__tests__/markup-to-pdf.generator.spec.ts +++ b/utils/report/__tests__/markup-to-pdf.generator.spec.ts @@ -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); diff --git a/utils/report/markup-to-pdf.generator.ts b/utils/report/markup-to-pdf.generator.ts index b2311db..be961a0 100644 --- a/utils/report/markup-to-pdf.generator.ts +++ b/utils/report/markup-to-pdf.generator.ts @@ -7,6 +7,7 @@ import { PUPPETEER_LAUNCH_ARGS, getPdfRenderBudgetMs, getPdfRenderScope, + PdfPrintTimeoutError, releaseBrowserSlot, } from './pdf-render.queue'; @@ -112,11 +113,20 @@ export abstract class MarkupToPdfReportGenerator 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 diff --git a/utils/report/pdf-render.queue.ts b/utils/report/pdf-render.queue.ts index d2a71f9..e36eeda 100644 --- a/utils/report/pdf-render.queue.ts +++ b/utils/report/pdf-render.queue.ts @@ -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;