|
| 1 | +// Copyright 2021 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +// eslint-disable-next-line node/no-deprecated-api |
| 16 | +import * as domain from 'domain'; |
| 17 | +import {Request, Response, RequestHandler} from 'express'; |
| 18 | +import {sendCrashResponse} from './logger'; |
| 19 | +import {sendResponse} from './invoker'; |
| 20 | +import {isBinaryCloudEvent, getBinaryCloudEventContext} from './cloudevents'; |
| 21 | +import { |
| 22 | + HttpFunction, |
| 23 | + EventFunction, |
| 24 | + EventFunctionWithCallback, |
| 25 | + Context, |
| 26 | + CloudEventFunction, |
| 27 | + CloudEventFunctionWithCallback, |
| 28 | + CloudEventsContext, |
| 29 | + HandlerFunction, |
| 30 | +} from './functions'; |
| 31 | +import {SignatureType} from './types'; |
| 32 | + |
| 33 | +/** |
| 34 | + * The handler function used to signal completion of event functions. |
| 35 | + */ |
| 36 | +// eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 37 | +type OnDoneCallback = (err: Error | null, result: any) => void; |
| 38 | + |
| 39 | +/** |
| 40 | + * Get a completion handler that can be used to signal completion of an event function. |
| 41 | + * @param res the response object of the request the completion handler is for. |
| 42 | + * @returns an OnDoneCallback for the provided request. |
| 43 | + */ |
| 44 | +const getOnDoneCallback = (res: Response): OnDoneCallback => { |
| 45 | + return process.domain.bind<OnDoneCallback>((err, result) => { |
| 46 | + if (res.locals.functionExecutionFinished) { |
| 47 | + console.log('Ignoring extra callback call'); |
| 48 | + } else { |
| 49 | + res.locals.functionExecutionFinished = true; |
| 50 | + if (err) { |
| 51 | + console.error(err.stack); |
| 52 | + } |
| 53 | + sendResponse(result, err, res); |
| 54 | + } |
| 55 | + }); |
| 56 | +}; |
| 57 | + |
| 58 | +/** |
| 59 | + * Helper function to parse a cloudevent object from an HTTP request. |
| 60 | + * @param req an Express HTTP request |
| 61 | + * @returns a cloudevent parsed from the request |
| 62 | + */ |
| 63 | +const parseCloudEventRequest = (req: Request): CloudEventsContext => { |
| 64 | + let cloudevent = req.body; |
| 65 | + if (isBinaryCloudEvent(req)) { |
| 66 | + cloudevent = getBinaryCloudEventContext(req); |
| 67 | + cloudevent.data = req.body; |
| 68 | + } |
| 69 | + return cloudevent; |
| 70 | +}; |
| 71 | + |
| 72 | +/** |
| 73 | + * Helper function to background event context and data payload object from an HTTP |
| 74 | + * request. |
| 75 | + * @param req an Express HTTP request |
| 76 | + * @returns the data playload and event context parsed from the request |
| 77 | + */ |
| 78 | +const parseBackgroundEvent = (req: Request): {data: {}; context: Context} => { |
| 79 | + const event = req.body; |
| 80 | + const data = event.data; |
| 81 | + let context = event.context; |
| 82 | + if (context === undefined) { |
| 83 | + // Support legacy events and CloudEvents in structured content mode, with |
| 84 | + // context properties represented as event top-level properties. |
| 85 | + // Context is everything but data. |
| 86 | + context = event; |
| 87 | + // Clear the property before removing field so the data object |
| 88 | + // is not deleted. |
| 89 | + context.data = undefined; |
| 90 | + delete context.data; |
| 91 | + } |
| 92 | + return {data, context}; |
| 93 | +}; |
| 94 | + |
| 95 | +/** |
| 96 | + * Wraps the provided function into an Express handler function with additional |
| 97 | + * instrumentation logic. |
| 98 | + * @param execute Runs user's function. |
| 99 | + * @return An Express handler function. |
| 100 | + */ |
| 101 | +const wrapHttpFunction = (execute: HttpFunction): RequestHandler => { |
| 102 | + return (req: Request, res: Response) => { |
| 103 | + const d = domain.create(); |
| 104 | + // Catch unhandled errors originating from this request. |
| 105 | + d.on('error', err => { |
| 106 | + if (res.locals.functionExecutionFinished) { |
| 107 | + console.error(`Exception from a finished function: ${err}`); |
| 108 | + } else { |
| 109 | + res.locals.functionExecutionFinished = true; |
| 110 | + sendCrashResponse({err, res}); |
| 111 | + } |
| 112 | + }); |
| 113 | + d.run(() => { |
| 114 | + process.nextTick(() => { |
| 115 | + execute(req, res); |
| 116 | + }); |
| 117 | + }); |
| 118 | + }; |
| 119 | +}; |
| 120 | + |
| 121 | +/** |
| 122 | + * Wraps an async cloudevent function in an express RequestHandler. |
| 123 | + * @param userFunction User's function. |
| 124 | + * @return An Express hander function that invokes the user function. |
| 125 | + */ |
| 126 | +const wrapCloudEventFunction = ( |
| 127 | + userFunction: CloudEventFunction |
| 128 | +): RequestHandler => { |
| 129 | + const httpHandler = (req: Request, res: Response) => { |
| 130 | + const callback = getOnDoneCallback(res); |
| 131 | + const cloudevent = parseCloudEventRequest(req); |
| 132 | + Promise.resolve() |
| 133 | + .then(() => userFunction(cloudevent)) |
| 134 | + .then( |
| 135 | + result => callback(null, result), |
| 136 | + err => callback(err, undefined) |
| 137 | + ); |
| 138 | + }; |
| 139 | + return wrapHttpFunction(httpHandler); |
| 140 | +}; |
| 141 | + |
| 142 | +/** |
| 143 | + * Wraps callback style cloudevent function in an express RequestHandler. |
| 144 | + * @param userFunction User's function. |
| 145 | + * @return An Express hander function that invokes the user function. |
| 146 | + */ |
| 147 | +const wrapCloudEventFunctionWithCallback = ( |
| 148 | + userFunction: CloudEventFunctionWithCallback |
| 149 | +): RequestHandler => { |
| 150 | + const httpHandler = (req: Request, res: Response) => { |
| 151 | + const callback = getOnDoneCallback(res); |
| 152 | + const cloudevent = parseCloudEventRequest(req); |
| 153 | + return userFunction(cloudevent, callback); |
| 154 | + }; |
| 155 | + return wrapHttpFunction(httpHandler); |
| 156 | +}; |
| 157 | + |
| 158 | +/** |
| 159 | + * Wraps an async event function in an express RequestHandler. |
| 160 | + * @param userFunction User's function. |
| 161 | + * @return An Express hander function that invokes the user function. |
| 162 | + */ |
| 163 | +const wrapEventFunction = (userFunction: EventFunction): RequestHandler => { |
| 164 | + const httpHandler = (req: Request, res: Response) => { |
| 165 | + const callback = getOnDoneCallback(res); |
| 166 | + const {data, context} = parseBackgroundEvent(req); |
| 167 | + Promise.resolve() |
| 168 | + .then(() => userFunction(data, context)) |
| 169 | + .then( |
| 170 | + result => callback(null, result), |
| 171 | + err => callback(err, undefined) |
| 172 | + ); |
| 173 | + }; |
| 174 | + return wrapHttpFunction(httpHandler); |
| 175 | +}; |
| 176 | + |
| 177 | +/** |
| 178 | + * Wraps an callback style event function in an express RequestHandler. |
| 179 | + * @param userFunction User's function. |
| 180 | + * @return An Express hander function that invokes the user function. |
| 181 | + */ |
| 182 | +const wrapEventFunctionWithCallback = ( |
| 183 | + userFunction: EventFunctionWithCallback |
| 184 | +): RequestHandler => { |
| 185 | + const httpHandler = (req: Request, res: Response) => { |
| 186 | + const callback = getOnDoneCallback(res); |
| 187 | + const {data, context} = parseBackgroundEvent(req); |
| 188 | + return userFunction(data, context, callback); |
| 189 | + }; |
| 190 | + return wrapHttpFunction(httpHandler); |
| 191 | +}; |
| 192 | + |
| 193 | +/** |
| 194 | + * Wraps a user function with the provided signature type in an express |
| 195 | + * RequestHandler. |
| 196 | + * @param userFunction User's function. |
| 197 | + * @return An Express hander function that invokes the user function. |
| 198 | + */ |
| 199 | +export const wrapUserFunction = ( |
| 200 | + userFunction: HandlerFunction, |
| 201 | + signatureType: SignatureType |
| 202 | +): RequestHandler => { |
| 203 | + switch (signatureType) { |
| 204 | + case 'http': |
| 205 | + return wrapHttpFunction(userFunction as HttpFunction); |
| 206 | + case 'event': |
| 207 | + // Callback style if user function has more than 2 arguments. |
| 208 | + if (userFunction!.length > 2) { |
| 209 | + return wrapEventFunctionWithCallback( |
| 210 | + userFunction as EventFunctionWithCallback |
| 211 | + ); |
| 212 | + } |
| 213 | + return wrapEventFunction(userFunction as EventFunction); |
| 214 | + case 'cloudevent': |
| 215 | + if (userFunction!.length > 1) { |
| 216 | + // Callback style if user function has more than 1 argument. |
| 217 | + return wrapCloudEventFunctionWithCallback( |
| 218 | + userFunction as CloudEventFunctionWithCallback |
| 219 | + ); |
| 220 | + } |
| 221 | + return wrapCloudEventFunction(userFunction as CloudEventFunction); |
| 222 | + } |
| 223 | +}; |
0 commit comments