Я пытаюсь создать 1k отчетов с использованием и конечной точки с Express.js, я передаю массив в JSON, API проходит через него и в цикле forEach, затем каждый объект используется для очистки портала , получите ответ и создайте файл PDF ...
Этот подход псевдо работает, но я вполне уверен, что есть некоторые проблемы с параллелизмом ... потому что, если я передам 2 элемента в массиве JSON, API сможет создать 2 файла PDF без проблем, но если я передам 300 API создает случайным образом 50 ... или 60 или 120.
Это мой конфиг jsreport
const jsReportConfig = {
extensions: {
"chrome-pdf": {
launchOptions: {
timeout: 10000,
args: ['--no-sandbox', '--disable-setuid-sandbox'],
},
},
},
tempDirectory: path.resolve(__dirname, './../../temporal/pdfs'),
templatingEngines: {
numberOfWorkers: 4,
timeout: 180000,
strategy: 'http-server',
},
};
Я установил экземпляр jsreport следующим образом
jsreport.use(jsReportChrome());
jsreport.use(jsReportHandlebars());
jsreport.init()
И вот как я отображаю отчеты, функция checkInvoiceStatus
используется в качестве HTTP-вызова, который возвращает HTML-ответ, введенный в шаблон Handlebars.
const renderReports = (reporter, invoices) => new Promise(async (resolve, reject) => {
try {
const templateContent = await readFile(
path.resolve(__dirname, './../templates/hello-world.hbs'),
'utf-8',
);
invoices.forEach(async (invoice) => {
try {
const response = await checkInvoiceStatus(invoice.re, invoice.rr, invoice.id)
const $ = await cheerio.load(response);
const reporterResponse = await reporter.render({
template: {
content: templateContent,
engine: 'handlebars',
recipe: 'chrome-pdf',
name: 'PDF Validation',
chrome: {
displayHeaderFooter: true,
footerTemplate: '<table width=\'100%\' style="font-size: 12px;"><tr><td width=\'33.33%\'>{#pageNum} de {#numPages}</td><td width=\'33.33%\' align=\'center\'></td><td width=\'33.33%\' align=\'right\'></td></tr></table>',
},
},
data: {
taxpayerId: 'CAC070508MY2',
captcha: $('#ctl00_MainContent_ImgCaptcha').attr('src'),
bodyContent: $('#ctl00_MainContent_PnlResultados').html(),
},
});
reporterResponse.result.pipe(fs.createWriteStream(`./temporal/validatedPdfs/${invoice.id}.pdf`));
} catch (err) {
console.error(err);
reject(new Error(JSON.stringify({
code: 'PORTAL-PDFx001',
message: 'The server could not retrieve the PDF from the portal',
})));
}
});
resolve();
} catch (err) {
console.error(err);
reject(new Error(JSON.stringify({
code: 'PORTAL-PDFx001',
message: 'The server could not retrieve the PDF from the portal',
})));
}
});
Я не знаю почему, но эта функция прекращается в 500ms , но файлы создаются через 1 минуту ...
app.post('/pdf-report', async (req, res, next) => {
const { invoices } = req.body;
repository.renderReports(reporter, invoices)
.then(() => res.status(200).send('Ok'))
.catch((err) => {
res.status(500).send(err);
});
});
UPDATE
Помимо кода, представленного @hurricane, мне пришлось изменить конфигурацию jsReport на этот
const jsReportConfig = {
chrome: {
timeout: 180000,
strategy: 'chrome-pool',
numberOfWorkers: 4
},
extensions: {
'chrome-pdf': {
launchOptions: {
timeout: 180000,
args: ['--no-sandbox', '--disable-setuid-sandbox'],
ignoreDefaultArgs: ['--disable-extensions'],
},
},
},
tempDirectory: path.resolve(__dirname, './../../temporal/pdfs'),
templatingEngines: {
numberOfWorkers: 4,
timeout: 180000,
strategy: 'http-server',
},
};