forked from Be-FaaS/BeFaaS-lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serverless.js
229 lines (205 loc) · 7.09 KB
/
serverless.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
const _ = require('lodash')
const serverless = require('serverless-http')
const azure = require('@bittrance/azure-function-express')
const Koa = require('koa')
const Router = require('@koa/router')
const bodyParser = require('koa-bodyparser')
const qs = require('qs')
const log = require('./log')
const helper = require('./helper')
const performance = require('./performance')
const call = require('./call')
const db = require('./db')
function createContext (contextId, xPair, dbBindToMeasure) {
const measurement = m => {
performance.mark(`${log.fnName}:${contextId}:${xPair}:start:${m}`)
return () => {
performance.mark(`${log.fnName}:${contextId}:${xPair}:end:${m}`)
performance.measure(
`${log.fnName}:${contextId}:${xPair}:measure:${m}`,
`${log.fnName}:${contextId}:${xPair}:start:${m}`,
`${log.fnName}:${contextId}:${xPair}:end:${m}`
)
}
}
return {
log: e => log(Object.assign({ contextId }, e || {})),
call: async (f, payload) => {
const xPair = `${contextId}-${helper.generateRandomID()}`
const end = measurement(`rpcOut:${f}:${xPair}`)
const res = await call(f, contextId, xPair, payload)
end()
return res
},
mark: m => performance.mark(`${log.fnName}:${contextId}:${m}`),
measure: measurement,
db: dbBindToMeasure(measurement),
contextId,
xPair
}
}
function logRequestAndAttachContext (ctx, dbBindToMeasure) {
const contextId = ctx.request.get('x-context') || helper.generateRandomID()
const xPair = ctx.request.get('x-pair') || 'undefined-x-pair'
log({
contextId,
xPair,
request: _.pick(ctx, ['method', 'originalUrl', 'headers'])
})
ctx.contextId = contextId
ctx.xPair = xPair
ctx.lib = createContext(contextId, xPair, dbBindToMeasure)
ctx.db = ctx.lib.db
}
async function handleErrors (ctx, next) {
try {
await next()
} catch (e) {
console.log(e.toString())
ctx.body = { error: e.toString() }
ctx.status = 502
}
}
function hybridBodyParser () {
// console.log('in body parser')
const bp = bodyParser()
return async (ctx, next) => {
if (
helper.isAzure &&
ctx.request.is('application/x-www-form-urlencoded') &&
ctx.req.body
) {
// console.log('will set req.body')
ctx.req.body = qs.parse(ctx.req.body, { allowDots: true })
}
ctx.request.body =
helper.isGoogle ||
helper.isAzure ||
helper.isTinyfaas ||
helper.isOpenfaas
? ctx.req.body
: ctx.request.body
// console.log('ctx.request.body is ' + JSON.stringify(ctx.request.body))
return bp(ctx, next)
}
}
function serverlessRouter (options, routerFn) {
// console.log('router: ' + JSON.stringify(routerFn))
// console.log('options: ' + JSON.stringify(options))
if (_.isFunction(options) && _.isUndefined(routerFn)) {
routerFn = options
options = {}
}
const app = new Koa()
const router = new Router({
prefix: helper.prefix()
})
// console.log('app and router initialized.')
let dbBindToMeasure = () => undefined
if (options.db) dbBindToMeasure = db.connect(options.db)
// console.log('will use hybrifBodyParser.')
router.use(handleErrors, hybridBodyParser())
// console.log('done.')
// m - method, e.g., "post"
// r - route, e.g., "/"
// h - handler, see return
const wrapHandler = (m, r, h) =>
router[m](r, async (ctx, next) => {
logRequestAndAttachContext(ctx, dbBindToMeasure)
const end = ctx.lib.measure(`${m}:${r}`)
// console.log('will call handler with:')
// console.log('r: ' + JSON.stringify(r))
// console.log('m: ' + JSON.stringify(m))
// console.log('h: ' + JSON.stringify(h))
await h(ctx, next)
end()
})
routerFn({
get: (r, h) => wrapHandler('get', r, h),
post: (r, h) => wrapHandler('post', r, h),
put: (r, h) => wrapHandler('put', r, h),
patch: (r, h) => wrapHandler('patch', r, h),
del: (r, h) => wrapHandler('del', r, h),
all: (r, h) => wrapHandler('all', r, h),
addRpcHandler: handler =>
router.post('/call', async (ctx, next) => {
logRequestAndAttachContext(ctx, dbBindToMeasure)
const end = ctx.lib.measure('rpcIn')
ctx.body = await handler(ctx.request.body, ctx.lib)
end()
})
})
// console.log('will use routes and methods.')
app.use(router.routes())
app.use(router.allowedMethods())
return {
tinyfaasHandler: app.callback(),
openfaasHandler: app.callback(),
openwhiskHandler: app.callback(),
lambdaHandler: serverless(app),
googleHandler: app.callback(),
azureHandler: azure.createHandler(app.callback())
}
}
module.exports.router = serverlessRouter
module.exports.rpcHandler = (options, handler) => {
if (_.isUndefined(handler))
return serverlessRouter(r => r.addRpcHandler(options))
return serverlessRouter(options, r => r.addRpcHandler(handler))
}
module.exports.msgHandler = (options, handler) => {
if (_.isFunction(options) && _.isUndefined(handler)) {
handler = options
options = {}
}
let dbBindToMeasure = () => undefined
if (options.db) dbBindToMeasure = db.connect(options.db)
return {
lambdaHandler: async (event, ctx) => {
// console.log('ctxEntry: ' + JSON.stringify(ctx))
// console.log('eventEntry: ' + JSON.stringify(event))
const contextId =
event.Records[0].Sns.MessageAttributes.contextId.Value ||
helper.generateRandomID()
const xPair =
event.Records[0].Sns.MessageAttributes.xPair.Value || 'undefined-x-pair'
ctx.contextId = contextId
ctx.xPair = xPair
ctx.lib = createContext(contextId, xPair, dbBindToMeasure)
const end = ctx.lib.measure(`msg`)
await handler(JSON.parse(event.Records[0].Sns.Message), ctx.lib)
end()
},
googleHandler: async (event, ctx) => {
// console.log('ctxEntry: ' + JSON.stringify(ctx))
// console.log('eventEntry: ' + JSON.stringify(event))
const msg = event.data
? Buffer.from(event.data, 'base64').toString()
: 'no data'
// console.log('Message: ' + msg)
const contextId = event.attributes.contextId || helper.generateRandomID()
const xPair = event.attributes.xPair || 'undefined-x-pair'
ctx.contextId = contextId
ctx.xPair = xPair
ctx.lib = createContext(contextId, xPair, dbBindToMeasure)
const end = ctx.lib.measure(`msg`)
await handler(JSON.parse(msg), ctx.lib)
end()
},
azureHandler: async (ctx, event) => {
// console.log('ctxEntry: ' + JSON.stringify(ctx))
// console.log('eventEntry: ' + JSON.stringify(event))
const contextId = event.data.contextId || helper.generateRandomID()
const xPair = event.data.xPair || 'undefined-x-pair'
ctx.contextId = contextId
ctx.xPair = xPair
ctx.lib = createContext(contextId, xPair, dbBindToMeasure)
const end = ctx.lib.measure(`msg`)
await handler(JSON.parse(event.data.event), ctx.lib)
end()
},
tinyfaasHandler: _.isUndefined(handler)
? serverlessRouter(r => r.addRpcHandler(options)).tinyfaasHandler
: serverlessRouter(options, r => r.addRpcHandler(handler)).tinyfaasHandler
}
}