🎥 Make videos programmatically with React
add node leak detection code
Jonny Burgerfbf459d66f5d
diff --git a/packages/lambda/src/shared/stackback.ts b/packages/lambda/src/shared/stackback.tsnew file mode 100644index 0000000000..7140d78c9f--- /dev/null+++ b/packages/lambda/src/shared/stackback.ts@@ -0,0 +1,67 @@+function FormatStackTrace(error: Error, frames: NodeJS.CallSite[]) {+ const lines = [];+ try {+ lines.push(error.toString());+ } catch (e) {+ try {+ lines.push('<error: ' + e + '>');+ } catch (ee) {+ lines.push('<error>');+ }+ }++ for (let i = 0; i < frames.length; i++) {+ const frame = frames[i];+ let line;+ try {+ line = frame.toString();+ } catch (e) {+ try {+ line = '<error: ' + e + '>';+ } catch (ee) {+ // Any code that reaches this point is seriously nasty!+ line = '<error>';+ }+ }++ lines.push(' at ' + line);+ }++ return lines.join('\n');+}++export const stackback = (error: Error): NodeJS.CallSite[] => {+ // save original stacktrace+ const save = Error.prepareStackTrace;++ // replace capture with our function+ Error.prepareStackTrace = function (err, trace) {+ // cache stack frames so we don't have to get them again+ // use a non-enumerable property+ Object.defineProperty(err, '_sb_callsites', {+ value: trace,+ });++ return (save || FormatStackTrace)(err, trace);+ };++ // force capture of the stack frames+ // eslint-disable-next-line no-unused-expressions+ error.stack;++ // someone already asked for the stack so we can't do this trick+ if (!error._sb_callsites) {+ return [];+ }++ // return original capture function+ Error.prepareStackTrace = save;++ return error._sb_callsites as NodeJS.CallSite[];+};++declare global {+ interface Error {+ _sb_callsites: NodeJS.CallSite[];+ }+}diff --git a/packages/lambda/src/shared/why-is-node-running.ts b/packages/lambda/src/shared/why-is-node-running.tsnew file mode 100644index 0000000000..0057bfd896--- /dev/null+++ b/packages/lambda/src/shared/why-is-node-running.ts@@ -0,0 +1,98 @@+import asyncHooks from 'async_hooks';+import fs from 'fs';+import {sep} from 'path';+import {stackback} from './stackback';++type Resource = {+ type: string;+ stacks: NodeJS.CallSite[];+ resource: {+ hasRef?: () => boolean;+ };+};++type NodeIntrospection = {+ hook: asyncHooks.AsyncHook;+ active: Map<number, Resource>;+};++export const enableNodeIntrospection = (): NodeIntrospection => {+ const active = new Map<number, Resource>();+ const hook = asyncHooks.createHook({+ init(asyncId, type, _triggerAsyncId, resource) {+ if (type === 'TIMERWRAP' || type === 'PROMISE') return;+ if (type === 'PerformanceObserver' || type === 'RANDOMBYTESREQUEST')+ return;+ const err = new Error('whatevs');+ const stacks = stackback(err);+ active.set(asyncId, {type, stacks, resource});+ },+ destroy(asyncId) {+ active.delete(asyncId);+ },+ });++ hook.enable();+ return {hook, active};+};++export function whyIsNodeRunning({active, hook}: NodeIntrospection) {+ hook.disable();+ const activeResources = [...active.values()].filter((r) => {+ if (typeof r.resource.hasRef === 'function' && !r.resource.hasRef())+ return false;+ return true;+ });++ console.error(+ 'There are %d handle(s) keeping the process running',+ activeResources.length,+ );++ function printStacks(o: Resource) {+ const stacks = o.stacks.slice(1).filter((s) => {+ const filename = s.getFileName();+ return (+ filename &&+ filename.indexOf(sep) > -1 &&+ filename.indexOf('internal' + sep) !== 0+ );+ });++ console.error('');+ console.error('# %s', o.type);++ if (stacks[0]) {+ let padding = '';+ stacks.forEach((s) => {+ const pad = (s.getFileName() + ':' + s.getLineNumber()).replace(+ /./g,+ ' ',+ );+ if (pad.length > padding.length) padding = pad;+ });+ stacks.forEach((s) => {+ const prefix = s.getFileName() + ':' + s.getLineNumber();+ try {+ const src = fs+ .readFileSync(s.getFileName() as string, 'utf-8')+ .split(/\n|\r\n/);+ console.error(+ prefix ++ padding.slice(prefix.length) ++ ' - ' ++ src[(s.getLineNumber() as number) - 1].trim(),+ );+ } catch (e) {+ console.error(prefix + padding.slice(prefix.length));+ }+ });+ } else {+ console.error('(unknown stack trace)');+ }+ }++ for (const o of activeResources) {+ printStacks(o);+ }+}