Skip to content

fix(twilio-run): fix global scope in forked process #270

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 20, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 15 additions & 9 deletions packages/twilio-run/src/runtime/internal/functionRunner.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { isTwiml } from '../route';
import { Response } from './response';
import { serializeError } from 'serialize-error';
import { ServerlessCallback } from '@twilio-labs/serverless-runtime-types/types';
import { constructGlobalScope, constructContext } from '../route';
import { serializeError } from 'serialize-error';
import { getRouteMap } from '../internal/route-cache';
import { constructContext, constructGlobalScope, isTwiml } from '../route';
import { Response } from './response';

const sendDebugMessage = (debugMessage: string, ...debugArgs: any) => {
process.send && process.send({ debugMessage, debugArgs });
Expand Down Expand Up @@ -50,7 +49,6 @@ const handleSuccess = (responseObject?: string | number | boolean | object) => {
};

process.on('message', async ({ functionPath, event, config, path }) => {
const { handler } = require(functionPath);
try {
await getRouteMap(config);
constructGlobalScope(config);
Expand All @@ -66,10 +64,12 @@ process.on('message', async ({ functionPath, event, config, path }) => {
run_timings.end = process.hrtime();
sendDebugMessage('Function execution %s finished', path);
sendDebugMessage(
`(Estimated) Total Execution Time: ${(run_timings.end[0] * 1e9 +
run_timings.end[1] -
(run_timings.start[0] * 1e9 + run_timings.start[1])) /
1e6}ms`
`(Estimated) Total Execution Time: ${
(run_timings.end[0] * 1e9 +
run_timings.end[1] -
(run_timings.start[0] * 1e9 + run_timings.start[1])) /
1e6
}ms`
);
if (err) {
handleError(err);
Expand All @@ -80,6 +80,12 @@ process.on('message', async ({ functionPath, event, config, path }) => {

sendDebugMessage('Calling function for %s', path);
run_timings.start = process.hrtime();
const { handler } = require(functionPath);
if (typeof handler !== 'function') {
throw new Error(
`Could not find a "handler" function in file ${functionPath}`
);
}
handler(context, event, callback);
} catch (err) {
if (process.send) {
Expand Down
29 changes: 14 additions & 15 deletions packages/twilio-run/src/runtime/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,10 @@ import { wrapErrorInHtml } from '../utils/error-html';
import { getDebugFunction } from '../utils/logger';
import { createLogger } from './internal/request-logger';
import { getRouteMap } from './internal/route-cache';

import {
constructGlobalScope,
functionToRoute,
functionPathToRoute,
functionToRoute,
} from './route';

const debug = getDebugFunction('twilio-run:server');
Expand All @@ -39,7 +38,7 @@ function requireCacheCleaner(
next: NextFunction
) {
debug('Deleting require cache');
Object.keys(require.cache).forEach(key => {
Object.keys(require.cache).forEach((key) => {
// Entries in the cache that end with .node are compiled binaries, deleting
// those has unspecified results, so we keep them.
// Entries in the cache that include "twilio-run" are part of this module
Expand Down Expand Up @@ -118,11 +117,11 @@ export async function createServer(
const debouncedReloadRoutes = debounce(reloadRoutes, RELOAD_DEBOUNCE_MS);

watcher
.on('add', path => {
.on('add', (path) => {
debug(`Reloading Routes: add @ ${path}`);
debouncedReloadRoutes();
})
.on('unlink', path => {
.on('unlink', (path) => {
debug(`Reloading Routes: unlink @ ${path}`);
debouncedReloadRoutes();
});
Expand Down Expand Up @@ -168,18 +167,18 @@ export async function createServer(
throw new Error('Missing function path');
}

debug('Load & route to function at "%s"', functionPath);
const twilioFunction = loadTwilioFunction(functionPath);
if (typeof twilioFunction !== 'function') {
return res
.status(404)
.send(
`Could not find a "handler" function in file ${functionPath}`
);
}
if (config.forkProcess) {
functionPathToRoute(functionPath, config)(req, res, next);
} else {
debug('Load & route to function at "%s"', functionPath);
const twilioFunction = loadTwilioFunction(functionPath);
if (typeof twilioFunction !== 'function') {
return res
.status(404)
.send(
`Could not find a "handler" function in file ${functionPath}`
);
}
functionToRoute(twilioFunction, config, functionPath)(
req,
res,
Expand Down Expand Up @@ -217,7 +216,7 @@ export async function runServer(
config: StartCliConfig
): Promise<Express> {
const app = await createServer(port, config);
return new Promise(resolve => {
return new Promise((resolve) => {
app.listen(port);
resolve(app);
});
Expand Down