Skip to content

Commit

Permalink
Merge branch 'main' into SyncV1ServicesDeprecationWarning
Browse files Browse the repository at this point in the history
  • Loading branch information
victoray authored Mar 26, 2024
2 parents 36e0b08 + 3868a78 commit 6fbb501
Show file tree
Hide file tree
Showing 10 changed files with 129 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/forty-snails-rescue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@twilio/runtime-handler': patch
---

Fix error messages in local development
5 changes: 5 additions & 0 deletions .changeset/friendly-turtles-pretend.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@twilio/runtime-handler': patch
---

Don't check for exact Content-Type matches
6 changes: 6 additions & 0 deletions .changeset/warm-moles-learn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'twilio-run': patch
'@twilio-labs/plugin-serverless': patch
---

Fix of debug/inspect mode by disabling fork process
Original file line number Diff line number Diff line change
Expand Up @@ -292,3 +292,21 @@ test('serializes a response with content type set to application/json', () => {
'Set-Cookie': [],
});
});

test('serializes a response with content type set to application/json with a charset', () => {
const response = new Response();
response.setBody({ url: 'https://dkundel.com' });
response.setStatusCode(200);
response.appendHeader('Content-Type', 'application/json; charset=UTF-8');

const serialized = response.serialize();

expect(serialized.body).toEqual(
JSON.stringify({ url: 'https://dkundel.com' })
);
expect(serialized.statusCode).toEqual(200);
expect(serialized.headers).toEqual({
'Content-Type': 'application/json; charset=UTF-8',
'Set-Cookie': [],
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { LoggerInstance } from '../types';

export class CrossForkLogger implements LoggerInstance {
constructor() {}

debug(msg: string) {
this.sendLog('debug', msg);
}

info(msg: string) {
this.sendLog('info', msg);
}

warn(msg: string, title: string = '') {
this.sendLog('warn', msg, title);
}

error(msg: string, title: string = '') {
this.sendLog('error', msg, title);
}

log(msg: string, level: number) {
this.sendLog('log', msg, level);
}

private sendLog(level: keyof LoggerInstance, ...args: (string | number)[]) {
process.send &&
process.send({
crossForkLogMessage: {
level,
args: args,
},
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
isTwiml,
} from '../route';
import { ServerConfig, Headers } from '../types';
import { CrossForkLogger } from './crossForkLogger';
import { Response } from './response';
import { setRoutes } from './route-cache';

Expand Down Expand Up @@ -61,12 +62,19 @@ const handleSuccess = (responseObject?: string | number | boolean | object) => {
}
};

process.on('uncaughtException', (err, origin) => {
if (process.send) {
process.send({ err: serializeError(err) });
}
});

process.on(
'message',
({ functionPath, event, config, path }: FunctionRunnerOptions) => {
try {
setRoutes(config.routes);
constructGlobalScope(config);
config.logger = new CrossForkLogger();
let context = constructContext(config, path);
sendDebugMessage('Context for %s: %p', path, context);
context = augmentContextWithOptionals(config, context);
Expand Down
15 changes: 10 additions & 5 deletions packages/runtime-handler/src/dev-runtime/internal/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export class Response implements TwilioResponse {
this.headers[COOKIE_HEADER] = newHeaderValue;
}
} else {
this.headers[COOKIE_HEADER] = Array.isArray(value) ? value: [value];
this.headers[COOKIE_HEADER] = Array.isArray(value) ? value : [value];
}
} else {
const existingValue = this.headers[key];
Expand Down Expand Up @@ -133,12 +133,17 @@ export class Response implements TwilioResponse {
}

serialize() {
const contentType = this.headers['Content-Type'];
let body = this.body;
if (
typeof contentType === 'string' &&
contentType.startsWith('application/json')
) {
body = JSON.stringify(body);
}
return {
statusCode: this.statusCode,
body:
this.headers['Content-Type'] === 'application/json'
? JSON.stringify(this.body)
: this.body,
body: body,
headers: this.headers,
};
}
Expand Down
23 changes: 22 additions & 1 deletion packages/runtime-handler/src/dev-runtime/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import {
import { Reply } from './internal/functionRunner';
import { Response } from './internal/response';
import * as Runtime from './internal/runtime';
import { ServerConfig } from './types';
import { LoggerInstance, ServerConfig } from './types';
import debug from './utils/debug';
import { wrapErrorInHtml } from './utils/error-html';
import { getCodeLocation } from './utils/getCodeLocation';
Expand Down Expand Up @@ -303,25 +303,46 @@ export function functionPathToRoute(
reply,
debugMessage,
debugArgs = [],
crossForkLogMessage,
}: {
err?: Error | number | string;
reply?: Reply;
debugMessage?: string;
debugArgs?: any[];
crossForkLogMessage?: {
level: keyof LoggerInstance;
args: [string] | [string, number] | [string, string];
};
}) => {
if (debugMessage) {
log(debugMessage, ...debugArgs);
return;
}

if (crossForkLogMessage) {
if (
config.logger &&
typeof config.logger[crossForkLogMessage.level] === 'function'
) {
config.logger[crossForkLogMessage.level](
// @ts-ignore
...crossForkLogMessage.args
);
}
return;
}

if (err) {
const error = deserializeError(err);
handleError(error, req, res, functionPath);
}

if (reply) {
res.status(reply.statusCode);
res.set(reply.headers);
res.send(reply.body);
}

forked.kill();
}
);
Expand Down
14 changes: 14 additions & 0 deletions packages/twilio-run/__tests__/config/start.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -285,4 +285,18 @@ describe('getConfigFromCli', () => {
expect(startConfig.baseDir).toEqual(path.resolve(config.cwd));
}
});

test('turns off fork process if inspect is enabled', async () => {
require('../../src/config/utils/package-json').__setPackageJson({});
const config = {
dir: './other_dir',
inspect: '',
} as unknown as StartCliFlags;
if (config.dir) {
const startConfig = await getConfigFromCli(config);
expect(startConfig.baseDir).toEqual(path.resolve(config.dir));
expect(startConfig.forkProcess).toEqual(false);
expect(startConfig.inspect).not.toEqual(undefined);
}
});
});
6 changes: 6 additions & 0 deletions packages/twilio-run/src/config/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,12 @@ export async function getConfigFromCli(
config.assetsFolderName = cli.assetsFolder;
config.functionsFolderName = cli.functionsFolder;
config.forkProcess = cli.forkProcess;

if (typeof config.inspect !== 'undefined') {
debug('Disabling fork-process in inspect mode.');
config.forkProcess = false;
}

config.pkgJson = pkgJson;

return config;
Expand Down

0 comments on commit 6fbb501

Please sign in to comment.