Compare commits

..

2 Commits

Author SHA1 Message Date
David Nguyen
9067351f96 fix: demo 2024-04-27 17:19:58 +07:00
David Nguyen
364c499927 fix: increase trpc max duration 2024-04-27 15:21:46 +07:00
4 changed files with 11 additions and 114 deletions

View File

@@ -3,7 +3,7 @@ import { createTrpcContext } from '@documenso/trpc/server/context';
import { appRouter } from '@documenso/trpc/server/router'; import { appRouter } from '@documenso/trpc/server/router';
export const config = { export const config = {
maxDuration: 60, maxDuration: 90,
api: { api: {
bodyParser: { bodyParser: {
sizeLimit: '50mb', sizeLimit: '50mb',

View File

@@ -47,13 +47,7 @@ export const completeDocumentWithToken = async ({
}: CompleteDocumentWithTokenOptions) => { }: CompleteDocumentWithTokenOptions) => {
'use server'; 'use server';
const startTime = Date.now();
console.log('Start:' + startTime);
console.log('getDocumentStart:' + startTime);
const document = await getDocument({ token, documentId }); const document = await getDocument({ token, documentId });
console.log('getDocumentEnd:' + (Date.now() - startTime));
console.log('Acc:' + (Date.now() - startTime));
if (document.status !== DocumentStatus.PENDING) { if (document.status !== DocumentStatus.PENDING) {
throw new Error(`Document ${document.id} must be pending`); throw new Error(`Document ${document.id} must be pending`);
@@ -69,21 +63,24 @@ export const completeDocumentWithToken = async ({
throw new Error(`Recipient ${recipient.id} has already signed`); throw new Error(`Recipient ${recipient.id} has already signed`);
} }
const fieldStartTime = Date.now();
console.log('fieldStart:' + fieldStartTime);
const fields = await prisma.field.findMany({ const fields = await prisma.field.findMany({
where: { where: {
documentId: document.id, documentId: document.id,
recipientId: recipient.id, recipientId: recipient.id,
}, },
}); });
console.log('fieldEnd:' + (Date.now() - fieldStartTime));
console.log('Acc:' + (Date.now() - startTime));
if (fields.some((field) => !field.inserted)) { if (fields.some((field) => !field.inserted)) {
throw new Error(`Recipient ${recipient.id} has unsigned fields`); throw new Error(`Recipient ${recipient.id} has unsigned fields`);
} }
// eslint-disable-next-line no-promise-executor-return
await new Promise<void>((resolve) => setTimeout(() => resolve(), 70000));
if (Date.now() > 0) {
throw new Error('Test');
}
// Document reauth for completing documents is currently not required. // Document reauth for completing documents is currently not required.
// const { derivedRecipientActionAuth } = extractDocumentAuthMethods({ // const { derivedRecipientActionAuth } = extractDocumentAuthMethods({
@@ -103,9 +100,6 @@ export const completeDocumentWithToken = async ({
// throw new AppError(AppErrorCode.UNAUTHORIZED, 'Invalid authentication values'); // throw new AppError(AppErrorCode.UNAUTHORIZED, 'Invalid authentication values');
// } // }
const recipientUpdateStartTime = Date.now();
console.log('recipientUpdateStart:' + recipientUpdateStartTime);
await prisma.$transaction(async (tx) => { await prisma.$transaction(async (tx) => {
await tx.recipient.update({ await tx.recipient.update({
where: { where: {
@@ -137,12 +131,6 @@ export const completeDocumentWithToken = async ({
}); });
}); });
console.log('recipientUpdateEnd:' + (Date.now() - recipientUpdateStartTime));
console.log('Acc:' + (Date.now() - startTime));
const pendingRecipientsStartTime = Date.now();
console.log('pendingRecipientsStart:' + pendingRecipientsStartTime);
const pendingRecipients = await prisma.recipient.count({ const pendingRecipients = await prisma.recipient.count({
where: { where: {
documentId: document.id, documentId: document.id,
@@ -151,16 +139,11 @@ export const completeDocumentWithToken = async ({
}, },
}, },
}); });
console.log('pendingRecipientsEnd:' + (Date.now() - pendingRecipientsStartTime));
console.log('Acc:' + (Date.now() - startTime));
if (pendingRecipients > 0) { if (pendingRecipients > 0) {
await sendPendingEmail({ documentId, recipientId: recipient.id }); await sendPendingEmail({ documentId, recipientId: recipient.id });
} }
const updateDocumentStartTime = Date.now();
console.log('updateDocumentStart:' + updateDocumentStartTime);
const documents = await prisma.document.updateMany({ const documents = await prisma.document.updateMany({
where: { where: {
id: document.id, id: document.id,
@@ -175,26 +158,12 @@ export const completeDocumentWithToken = async ({
completedAt: new Date(), completedAt: new Date(),
}, },
}); });
console.log('updateDocumentEnd:' + (Date.now() - updateDocumentStartTime));
console.log('Acc:' + (Date.now() - startTime));
if (documents.count > 0) { if (documents.count > 0) {
const sealDocumentStartTime = Date.now();
console.log('sealDocumentStart:' + sealDocumentStartTime);
await sealDocument({ documentId: document.id, requestMetadata }); await sealDocument({ documentId: document.id, requestMetadata });
console.log('sealDocumentEnd:' + (Date.now() - sealDocumentStartTime));
console.log('Acc:' + (Date.now() - startTime));
} }
const updateDocumentStartTime2 = Date.now();
console.log('updateDocumentStart2:' + updateDocumentStartTime2);
const updatedDocument = await getDocument({ token, documentId }); const updatedDocument = await getDocument({ token, documentId });
console.log('updateDocumentEnd2:' + (Date.now() - updateDocumentStartTime2));
console.log('Acc:' + (Date.now() - startTime));
const triggerWebhookStartTime = Date.now();
console.log('triggerWebhookStart:' + triggerWebhookStartTime);
await triggerWebhook({ await triggerWebhook({
event: WebhookTriggerEvents.DOCUMENT_SIGNED, event: WebhookTriggerEvents.DOCUMENT_SIGNED,
@@ -202,6 +171,4 @@ export const completeDocumentWithToken = async ({
userId: updatedDocument.userId, userId: updatedDocument.userId,
teamId: updatedDocument.teamId ?? undefined, teamId: updatedDocument.teamId ?? undefined,
}); });
console.log('triggerWebhookEnd:' + (Date.now() - triggerWebhookStartTime));
console.log('Acc:' + (Date.now() - startTime));
}; };

View File

@@ -90,69 +90,41 @@ export const sealDocument = async ({
} }
// !: Need to write the fields onto the document as a hard copy // !: Need to write the fields onto the document as a hard copy
const getFileTime = Date.now();
console.log('getFileStart:' + getFileTime);
const pdfData = await getFile(documentData); const pdfData = await getFile(documentData);
console.log('getFileEnd:' + (Date.now() - getFileTime));
const getCertificatePdfTime = Date.now();
console.log('getCertificatePdfStart:' + getCertificatePdfTime);
const certificate = await getCertificatePdf({ documentId }).then(async (doc) => const certificate = await getCertificatePdf({ documentId }).then(async (doc) =>
PDFDocument.load(doc), PDFDocument.load(doc),
); );
console.log('getCertificatePdfEnd:' + (Date.now() - getCertificatePdfTime));
const loadDoc = Date.now();
console.log('loadDocStart:' + loadDoc);
const doc = await PDFDocument.load(pdfData); const doc = await PDFDocument.load(pdfData);
console.log('loadDocEnd:' + (Date.now() - loadDoc));
// Normalize and flatten layers that could cause issues with the signature // Normalize and flatten layers that could cause issues with the signature
normalizeSignatureAppearances(doc); normalizeSignatureAppearances(doc);
doc.getForm().flatten(); doc.getForm().flatten();
flattenAnnotations(doc); flattenAnnotations(doc);
const certificatePageTime = Date.now();
console.log('certificatePageStart:' + certificatePageTime);
const certificatePages = await doc.copyPages(certificate, certificate.getPageIndices()); const certificatePages = await doc.copyPages(certificate, certificate.getPageIndices());
console.log('certificatePageEnd:' + (Date.now() - certificatePageTime));
certificatePages.forEach((page) => { certificatePages.forEach((page) => {
doc.addPage(page); doc.addPage(page);
}); });
for (const field of fields) { for (const field of fields) {
const insertFIeldTime = Date.now();
console.log('insertFieldStart:' + insertFIeldTime);
await insertFieldInPDF(doc, field); await insertFieldInPDF(doc, field);
console.log('insertFieldEnd:' + (Date.now() - insertFIeldTime));
} }
const docSaveTime = Date.now();
console.log('docSaveStart:' + docSaveTime);
const pdfBytes = await doc.save(); const pdfBytes = await doc.save();
console.log('docSaveEnd:' + (Date.now() - docSaveTime));
const pdfBufferTIme = Date.now();
console.log('pdfBufferStart:' + pdfBufferTIme);
const pdfBuffer = await signPdf({ pdf: Buffer.from(pdfBytes) }); const pdfBuffer = await signPdf({ pdf: Buffer.from(pdfBytes) });
console.log('pdfBufferEnd:' + (Date.now() - pdfBufferTIme));
const { name, ext } = path.parse(document.title); const { name, ext } = path.parse(document.title);
const putFIleTIme = Date.now();
console.log('putFileStart:' + putFIleTIme);
const { data: newData } = await putFile({ const { data: newData } = await putFile({
name: `${name}_signed${ext}`, name: `${name}_signed${ext}`,
type: 'application/pdf', type: 'application/pdf',
arrayBuffer: async () => Promise.resolve(pdfBuffer), arrayBuffer: async () => Promise.resolve(pdfBuffer),
}); });
console.log('putFileEnd:' + (Date.now() - putFIleTIme));
const postHog = PostHogServerClient(); const postHog = PostHogServerClient();
if (postHog) { if (postHog) {
@@ -165,9 +137,6 @@ export const sealDocument = async ({
}); });
} }
const updateDocumentTime = Date.now();
console.log('updateDocumentStart:' + updateDocumentTime);
await prisma.$transaction(async (tx) => { await prisma.$transaction(async (tx) => {
await tx.documentData.update({ await tx.documentData.update({
where: { where: {
@@ -191,18 +160,10 @@ export const sealDocument = async ({
}); });
}); });
console.log('updateDocumentEnd:' + (Date.now() - updateDocumentTime));
if (sendEmail && !isResealing) { if (sendEmail && !isResealing) {
const sendCompleteEmailTime = Date.now();
console.log('sendCompleteEmailStart:' + sendCompleteEmailTime);
await sendCompletedEmail({ documentId, requestMetadata }); await sendCompletedEmail({ documentId, requestMetadata });
console.log('sendCompleteEmailEnd:' + (Date.now() - sendCompleteEmailTime));
} }
const asdfasdfasdf = Date.now();
console.log('updateDocumentStart:' + asdfasdfasdf);
const updatedDocument = await prisma.document.findFirstOrThrow({ const updatedDocument = await prisma.document.findFirstOrThrow({
where: { where: {
id: document.id, id: document.id,
@@ -212,10 +173,6 @@ export const sealDocument = async ({
Recipient: true, Recipient: true,
}, },
}); });
console.log('updateDocumentEnd:' + (Date.now() - asdfasdfasdf));
const triggerWebhookTime = Date.now();
console.log('triggerWebhookStart:' + triggerWebhookTime);
await triggerWebhook({ await triggerWebhook({
event: WebhookTriggerEvents.DOCUMENT_COMPLETED, event: WebhookTriggerEvents.DOCUMENT_COMPLETED,
@@ -223,5 +180,4 @@ export const sealDocument = async ({
userId: document.userId, userId: document.userId,
teamId: document.teamId ?? undefined, teamId: document.teamId ?? undefined,
}); });
console.log('triggerWebhookEnd:' + (Date.now() - triggerWebhookTime));
}; };

View File

@@ -22,9 +22,7 @@ export const getCertificatePdf = async ({ documentId }: GetCertificatePdfOptions
// !: Previously we would have to keep the playwright version in sync with the browserless version to avoid errors. // !: Previously we would have to keep the playwright version in sync with the browserless version to avoid errors.
browser = await chromium.connectOverCDP(process.env.NEXT_PRIVATE_BROWSERLESS_URL); browser = await chromium.connectOverCDP(process.env.NEXT_PRIVATE_BROWSERLESS_URL);
} else { } else {
console.log('here');
browser = await chromium.launch(); browser = await chromium.launch();
console.log('here2');
} }
if (!browser) { if (!browser) {
@@ -33,41 +31,17 @@ export const getCertificatePdf = async ({ documentId }: GetCertificatePdfOptions
); );
} }
console.log('1');
const page = await browser.newPage(); const page = await browser.newPage();
console.log('2');
const domcontentloadedTime = Date.now(); await page.goto(`${NEXT_PUBLIC_WEBAPP_URL()}/__htmltopdf/certificate?d=${encryptedId}`, {
console.log('domcontentloadedTime:' + domcontentloadedTime); waitUntil: 'networkidle',
});
await page
.goto(`${NEXT_PUBLIC_WEBAPP_URL()}/__htmltopdf/certificate?d=${encryptedId}`, {
waitUntil: 'domcontentloaded',
})
.catch((e) => {
console.log(e);
});
console.log('domcontentloadedEnd:' + (Date.now() - domcontentloadedTime));
const networkidleTime = Date.now();
console.log('networkidleTime:' + networkidleTime);
await page
.goto(`${NEXT_PUBLIC_WEBAPP_URL()}/__htmltopdf/certificate?d=${encryptedId}`, {
waitUntil: 'networkidle',
})
.catch((e) => {
console.log(e);
});
console.log('networkidleEnd:' + (Date.now() - networkidleTime));
const result = await page.pdf({ const result = await page.pdf({
format: 'A4', format: 'A4',
}); });
console.log(4);
void browser.close(); void browser.close();
console.log(5);
return result; return result;
}; };