Skip to content

refactor: split files #135

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 6, 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
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

34 changes: 34 additions & 0 deletions src/cloudevents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import * as express from 'express';

/**
* Checks whether the incoming request is a CloudEvents event in binary content
* mode. This is verified by checking the presence of required headers.
*
* @link https://github.com/cloudevents/spec/blob/master/http-transport-binding.md#31-binary-content-mode
*
* @param req Express request object.
* @return True if the request is a CloudEvents event in binary content mode,
* false otherwise.
*/
export function isBinaryCloudEvent(req: express.Request): boolean {
return !!(
req.header('ce-type') &&
req.header('ce-specversion') &&
req.header('ce-source') &&
req.header('ce-id')
);
}
102 changes: 27 additions & 75 deletions src/invoker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ import * as express from 'express';
import * as http from 'http';
import * as onFinished from 'on-finished';

// HTTP header field that is added to Worker response to signalize problems with
// executing the client function.
const FUNCTION_STATUS_HEADER_FIELD = 'X-Google-Status';
import { FUNCTION_STATUS_HEADER_FIELD } from './types';
import { logAndSendError } from './logger';
import { isBinaryCloudEvent } from './cloudevents';

/**
* The Cloud Functions context object for the event.
Expand Down Expand Up @@ -267,34 +267,6 @@ function sendResponse(result: any, err: Error | null, res: express.Response) {
}
}

/**
* Logs an error message and sends back an error response to the incoming
* request.
* @param err Error to be logged and sent.
* @param res Express response object.
* @param callback A function to be called synchronously.
*/
function logAndSendError(
// tslint:disable-next-line:no-any
err: Error | any,
res: express.Response | null,
callback?: Function
) {
console.error(err.stack || err);

// If user function has already sent response headers, the response with
// error message cannot be sent. This check is done inside the callback,
// right before sending the response, to make sure that no concurrent
// execution sends the response between the check and 'send' call below.
if (res && !res.headersSent) {
res.set(FUNCTION_STATUS_HEADER_FIELD, 'crash');
res.send(err.message || err);
}
if (callback) {
callback();
}
}

// Set limit to a value larger than 32MB, which is maximum limit of higher level
// layers anyway.
const requestLimit = '1024mb';
Expand All @@ -315,31 +287,6 @@ function rawBodySaver(
req.rawBody = buf;
}

const defaultBodySavingOptions = {
limit: requestLimit,
verify: rawBodySaver,
};

const cloudEventsBodySavingOptions = {
type: 'application/cloudevents+json',
limit: requestLimit,
verify: rawBodySaver,
};

// The parser will process ALL content types so must come last.
const rawBodySavingOptions = {
limit: requestLimit,
verify: rawBodySaver,
type: '*/*',
};

// Use extended query string parsing for URL-encoded bodies.
const urlEncodedOptions = {
limit: requestLimit,
verify: rawBodySaver,
extended: true,
};

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

/**
* Checks whether the incoming request is a CloudEvents event in binary content
* mode. This is verified by checking the presence of required headers.
*
* @link https://github.com/cloudevents/spec/blob/master/http-transport-binding.md#31-binary-content-mode
*
* @param req Express request object.
* @return True if the request is a CloudEvents event in binary content mode,
* false otherwise.
*/
function isBinaryCloudEvent(req: express.Request): boolean {
return !!(
req.header('ce-type') &&
req.header('ce-specversion') &&
req.header('ce-source') &&
req.header('ce-id')
);
}

/**
* Returns a CloudEvents context from the given CloudEvents request. Context
* attributes are retrieved from request headers.
Expand Down Expand Up @@ -567,6 +495,30 @@ export function getServer(
next();
});

const defaultBodySavingOptions = {
limit: requestLimit,
verify: rawBodySaver,
};
const cloudEventsBodySavingOptions = {
type: 'application/cloudevents+json',
limit: requestLimit,
verify: rawBodySaver,
};

// The parser will process ALL content types so must come last.
const rawBodySavingOptions = {
limit: requestLimit,
verify: rawBodySaver,
type: '*/*',
};

// Use extended query string parsing for URL-encoded bodies.
const urlEncodedOptions = {
limit: requestLimit,
verify: rawBodySaver,
extended: true,
};

app.use(bodyParser.json(cloudEventsBodySavingOptions));
app.use(bodyParser.json(defaultBodySavingOptions));
app.use(bodyParser.text(defaultBodySavingOptions));
Expand Down
44 changes: 44 additions & 0 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import * as express from 'express';
import { FUNCTION_STATUS_HEADER_FIELD } from './types';

/**
* Logs an error message and sends back an error response to the incoming
* request.
* @param err Error to be logged and sent.
* @param res Express response object.
* @param callback A function to be called synchronously.
*/
export function logAndSendError(
// tslint:disable-next-line:no-any
err: Error | any,
res: express.Response | null,
callback?: Function
) {
console.error(err.stack || err);

// If user function has already sent response headers, the response with
// error message cannot be sent. This check is done inside the callback,
// right before sending the response, to make sure that no concurrent
// execution sends the response between the check and 'send' call below.
if (res && !res.headersSent) {
res.set(FUNCTION_STATUS_HEADER_FIELD, 'crash');
res.send(err.message || err);
}
if (callback) {
callback();
}
}
17 changes: 17 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// HTTP header field that is added to Worker response to signalize problems with
// executing the client function.
export const FUNCTION_STATUS_HEADER_FIELD = 'X-Google-Status';