From dfcd9985d41c54ff352948cfe3734aaa9e8845b2 Mon Sep 17 00:00:00 2001 From: Matchu Date: Fri, 3 Sep 2021 15:43:27 -0700 Subject: [PATCH] Await closing Playwright before finish request I noticed when loading Your Outfits earlier (before I switched it to just use prod images even on dev), that there was a big memory leak slowing down my machine. My hypothesis is that this is because I wasn't _waiting_ for the resources to tear down before finishing the request, so Vercel terminated the request early, and I further hypothesize that terminating a Playwright session partway through isn't guaranteed to clean up the browser. Not sure about that! Could have just been that we spun up a lot at once, and a bunch of things went into swap! (But I thought it generally handles requests in serial in the dev server? So that feels unlikely.) Anyway, I don't feel like extensively testing this again and maybe messing up my computer session again :p Just, when I first wrote this without awaits, I knew that it was a bit risky, but I wanted to _see_ if it was a problem before slowing down individual requests by awaiting. And now, my "it's likely to be a problem" threshold has been reached, lol! So, I'm not _confident_ this is the best play, I don't know the internals well enough; but it seems like a better side to err on than the other, now that I know more! --- api/assetImage.js | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/api/assetImage.js b/api/assetImage.js index 086eafc..ab05e94 100644 --- a/api/assetImage.js +++ b/api/assetImage.js @@ -122,9 +122,18 @@ async function loadAndScreenshotImage(libraryUrl, size) { ); } } finally { - // Tear down our resources when we're done! - page.close(); - browser.close(); + // Tear down our resources when we're done! If it fails, log the error, but + // don't block the success of the image. + try { + await page.close(); + } catch (e) { + console.warn("Error closing page after image finished", e); + } + try { + await browser.close(); + } catch (e) { + console.warn("Error closing browser after image finished", e); + } } }