Skip to content

refactor: extract cloudevents functions, privateize file-global identifiers #138

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 2 commits into from
May 12, 2020
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
21 changes: 21 additions & 0 deletions src/cloudevents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
// limitations under the License.

import * as express from 'express';
import { CloudEventsContext } from './functions';

/**
* Checks whether the incoming request is a CloudEvents event in binary content
Expand All @@ -32,3 +33,23 @@ export function isBinaryCloudEvent(req: express.Request): boolean {
req.header('ce-id')
);
}

/**
* Returns a CloudEvents context from the given CloudEvents request. Context
* attributes are retrieved from request headers.
*
* @param req Express request object.
* @return CloudEvents context.
*/
export function getBinaryCloudEventContext(
req: express.Request
): CloudEventsContext {
const context: CloudEventsContext = {};
for (const name in req.headers) {
if (name.startsWith('ce-')) {
const attributeName = name.substr('ce-'.length);
context[attributeName] = req.header(name);
}
}
return context;
}
75 changes: 26 additions & 49 deletions src/invoker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,12 @@ import * as onFinished from 'on-finished';

import { FUNCTION_STATUS_HEADER_FIELD } from './types';
import { logAndSendError } from './logger';
import { isBinaryCloudEvent } from './cloudevents';
import { isBinaryCloudEvent, getBinaryCloudEventContext } from './cloudevents';
import {
HttpFunction,
EventFunction,
EventFunctionWithCallback,
HandlerFunction,
CloudFunctionsContext,
CloudEventsContext,
} from './functions';

// We optionally annotate the express Request with a rawBody field.
Expand Down Expand Up @@ -106,26 +104,6 @@ function sendResponse(result: any, err: Error | null, res: express.Response) {
}
}

// Set limit to a value larger than 32MB, which is maximum limit of higher level
// layers anyway.
const requestLimit = '1024mb';

/**
* Retains a reference to the raw body buffer to allow access to the raw body
* for things like request signature validation. This is used as the "verify"
* function in body-parser options.
* @param req Express request object.
* @param res Express response object.
* @param buf Buffer to be saved.
*/
function rawBodySaver(
req: express.Request,
res: express.Response,
buf: Buffer
) {
req.rawBody = buf;
}

/**
* Wraps the provided function into an Express handler function with additional
* instrumentation logic.
Expand All @@ -152,24 +130,6 @@ function makeHttpHandler(execute: HttpFunction): express.RequestHandler {
};
}

/**
* Returns a CloudEvents context from the given CloudEvents request. Context
* attributes are retrieved from request headers.
*
* @param req Express request object.
* @return CloudEvents context.
*/
function getBinaryCloudEventContext(req: express.Request): CloudEventsContext {
const context: CloudEventsContext = {};
for (const name in req.headers) {
if (name.startsWith('ce-')) {
const attributeName = name.substr('ce-'.length);
context[attributeName] = req.header(name);
}
}
return context;
}

/**
* Wraps event function (or event function with callback) in HTTP function
* signature.
Expand Down Expand Up @@ -327,13 +287,34 @@ export function getServer(
// App to use for function executions.
const app = express();

// Express middleware

// Set request-specific values in the very first middleware.
app.use('/*', (req, res, next) => {
latestRes = res;
res.locals.functionExecutionFinished = false;
next();
});

/**
* Retains a reference to the raw body buffer to allow access to the raw body
* for things like request signature validation. This is used as the "verify"
* function in body-parser options.
* @param req Express request object.
* @param res Express response object.
* @param buf Buffer to be saved.
*/
function rawBodySaver(
req: express.Request,
res: express.Response,
buf: Buffer
) {
req.rawBody = buf;
}

// Set limit to a value larger than 32MB, which is maximum limit of higher level
// layers anyway.
const requestLimit = '1024mb';
const defaultBodySavingOptions = {
limit: requestLimit,
verify: rawBodySaver,
Expand All @@ -343,8 +324,6 @@ export function getServer(
limit: requestLimit,
verify: rawBodySaver,
};

// The parser will process ALL content types so must come last.
const rawBodySavingOptions = {
limit: requestLimit,
verify: rawBodySaver,
Expand All @@ -358,18 +337,16 @@ export function getServer(
extended: true,
};

// Apply middleware
app.use(bodyParser.json(cloudEventsBodySavingOptions));
app.use(bodyParser.json(defaultBodySavingOptions));
app.use(bodyParser.text(defaultBodySavingOptions));
app.use(bodyParser.urlencoded(urlEncodedOptions));

// MUST be last in the list of body parsers as subsequent parsers will be
// skipped when one is matched.
// The parser will process ALL content types so MUST come last.
// Subsequent parsers will be skipped when one is matched.
app.use(bodyParser.raw(rawBodySavingOptions));

registerFunctionRoutes(app, userFunction, functionSignatureType);

app.enable('trust proxy'); // To respect X-Forwarded-For header.

registerFunctionRoutes(app, userFunction, functionSignatureType);
return http.createServer(app);
}