-
Notifications
You must be signed in to change notification settings - Fork 1
/
logic.coffee
380 lines (294 loc) · 10.7 KB
/
logic.coffee
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# 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.
DEFAULT_TIMEOUT = 60
TICK = 100
arraySort = require "array-sort"
buffer = (require "buffer").Buffer
httpProxy = require "http-proxy"
restService = require "rest-middleware/server"
uuid = require "uuid"
clone = (obj) ->
JSON.parse(JSON.stringify(obj))
class MockableHttpServer
constructor: (printCallback=console.log,
setIntervalCallback=global.setInterval,
setTimeoutCallback=global.setTimeout,
promiseClassCallback=Promise) ->
opts = {
proxyTimeout: 5 * 60 * 1000,
autoRewrite: true,
forceRewrite: true
}
@proxy = httpProxy.createProxyServer opts
@routes = {}
@loggedRequests = {}
@internalDataForRoutes = {}
@sortedRoutes = []
@areSortedRoutesValid = false
@printCallback = printCallback
@setIntervalCallback = setIntervalCallback
@setTimeoutCallback = setTimeoutCallback
@PromiseClassCallback = promiseClassCallback
uthis = this
printRoutes = () ->
uthis.printCallback ""
uthis.printCallback "We have #{Object.keys(uthis.routes).length} " + \
"routes:"
for key in Object.keys(uthis.routes)
uthis.printCallback "### #{key}"
uthis.printRoute uthis.routes[key]
uthis.printCallback ""
@proxy.on "error", (err, req, res) ->
uthis.printCallback "Error: #{err}"
res.statusCode = 502
res.end()
@setIntervalCallback printRoutes, 60000
sortRoutesIfNeeded: ->
if @areSortedRoutesValid
return null
compareFunction = (left, right) ->
return right.priority - left.priority
values = []
for key in Object.keys(@routes)
value = @routes[key]
nvalue = clone(value)
nvalue.key = key
values.push nvalue
@sortedRoutes = arraySort values, compareFunction
@areSortedRoutesValid = true
null
invalidateSortedRoutes: ->
@areSortedRoutesValid = false
null
validateRoute: (data) ->
if !data?
throw new restService.ServerMethodError 400, "POST", [],
"Invalid route data: empty"
if !data.path? || !data.priority?
throw new restService.ServerMethodError 400, "POST", [],
"Invalid route data: no path or priority"
if data.times?
times = parseInt(data.times)
if isNaN(times) or times <= 0
throw new restService.ServerMethodError 400, "POST", [],
"Invalid route data: times must be a non-negative integer"
if data.method? and data.method != "POST" and data.method != "GET"
throw new restService.ServerMethodError 400, "POST", [],
"Invalid route data: method must be POST or GET"
if data.delay?
if !data.forward?
throw new restService.ServerMethodError 400, "POST", [],
"Invalid route data: delay requires forward"
if data.log?
throw new restService.ServerMethodError 400, "POST", [],
"Invalid route data: delay conflicts with log"
if data.response? or data.log? or data.forward?
if data.response?
if !data.response.code? || !data.response.body?
throw new restService.ServerMethodError 400, "POST", [],
"Invalid route data: response must have code and body"
if data.forward?
if !data.forward.host? or !data.forward.port? or !data.forward.ssl?
throw new restService.ServerMethodError 400, "POST", [],
"Invalid route data: forward must have host, port and ssl"
else
throw new restService.ServerMethodError 400, "POST", [],
"Invalid route data: no action provided"
printRoute: (data) ->
@printCallback " with priority: #{data.priority}"
@printCallback " for URL: #{data.path}"
if data.method?
@printCallback " for method: #{data.method}"
if data.times?
@printCallback " will expire after #{data.times} calls"
if data.response?
@printCallback "Action is to respond"
@printCallback " with code #{data.response.code}"
@printCallback " with body: #{data.response.body}"
if data.forward?
protocol = "http"
if data.forward.ssl
protocol = "https"
@printCallback "Action is to forward all requests to " +
"#{protocol}://#{data.forward.host}:#{data.forward.port}"
if data.delay?
@printCallback " and delay HTTP request by #{data.delay} seconds"
if data.log?
@printCallback "Action is to log all requests"
if data.log.base64?
@printCallback " body will be base64-ed"
findMatchingRoutes: (opts) ->
this.sortRoutesIfNeeded()
matched = []
for route in @sortedRoutes
pathRegexp = @internalDataForRoutes[route.key].pathRegexp
if not pathRegexp.test(opts.path)
continue
if route.method? and opts.method != route.method
continue
matched.push route
return matched
addLoggedRequestForRoute: (id, request) ->
if !@loggedRequests[id]?
@loggedRequests[id] = []
@loggedRequests[id].push request
getLoggedRequestsForRouteIfAny: (id) ->
ret = @loggedRequests[id]
if ret?
delete @loggedRequests[id]
return ret
methodRoutesGet: () ->
return @routes
methodRoutesPost: (data) ->
this.validateRoute data
anId = uuid.v1()
@routes[anId] = data
@internalDataForRoutes[anId] = {pathRegexp: new RegExp(data.path)}
this.invalidateSortedRoutes()
@printCallback "Added new route #{anId}"
this.printRoute data
@printCallback "Now we have #{Object.keys(@routes).length} route(s)."
@printCallback ""
return anId
methodRoutesDelete: () ->
@printCallback "Deleted all routes."
@printCallback ""
@routes = {}
this.invalidateSortedRoutes()
methodRouteGet: (id) ->
if !@routes[id]?
throw new restService.ServerMethodError 404, "GET", [id]
return @routes[id]
methodRoutePost: (id, data) ->
if !@routes[id]?
throw new restService.ServerMethodError 404, "POST", [id]
this.validateRoute data
@routes[id] = data
@internalDataForRoutes[id].pathRegexp = new RegExp(data.path)
this.invalidateSortedRoutes()
@printCallback "Updated route #{id}"
this.printRoute data
@printCallback ""
methodRouteDelete: (id) ->
if !@routes[id]?
throw new restService.ServerMethodError 404, "DELETE", [id]
delete @routes[id]
this.invalidateSortedRoutes()
@printCallback "Deleted route #{id}"
@printCallback ""
methodLogGet: (id, timeout) ->
ret = this.getLoggedRequestsForRouteIfAny id
if !ret?
# We will need to wait for it
if !timeout? || typeof timeout == "object"
timeout = DEFAULT_TIMEOUT
ticks = timeout * 1000 / TICK
timeExpired = 0
@printCallback "Waiting for logs of #{id} up to #{timeout} seconds"
@printCallback ""
uthis = this
promise = new @PromiseClassCallback (resolve, reject) ->
interval = null
intervalFn = () ->
ret = uthis.getLoggedRequestsForRouteIfAny id
if ret?
clearInterval interval
resolve ret
uthis.printCallback "Sent logs for #{id} after " +
"#{timeExpired * 0.001} seconds"
uthis.printCallback ""
else
ticks -= 1
if ticks < 1
clearInterval interval
uthis.printCallback "Timeout while waiting for logs of #{id}"
uthis.printCallback ""
reject "Did not get logs of #{id} after timeout of #{timeout}"
else
timeExpired += TICK
null
interval = uthis.setIntervalCallback intervalFn, TICK
null
return promise
@printCallback "Sent logs of #{id}"
@printCallback ""
return ret
methodLogsGet: () ->
return Object.keys(@loggedRequests)
dispatchNoRoutes: (request, response) ->
response.statusCode = 404
response.statusMessage = "Not found"
response.write "Not found"
response.end()
dispatchInRoute: (request, response, route) ->
uthis = this
if route.log?
buffers = []
request.on "data", (data) ->
buffers.push data
uthis.printCallback "Request more data #{data.length}"
null
request.on "end", () ->
uthis.printCallback "Request end"
encoding = "utf8"
if route.log.base64?
encoding = "base64"
buffer = Buffer.concat(buffers).toString(encoding)
log = {headers: request.headers, method: request.method, \
url: request.url, body: buffer}
uthis.addLoggedRequestForRoute route.key, log
null
if route.times?
route.times -= 1
if route.times <= 0
delete @routes[route.key]
delete @internalDataForRoutes[route.key]
this.invalidateSortedRoutes()
@printCallback "Route #{route.key} expired"
@printCallback ""
if route.response?
response.statusCode = route.response.code
response.write route.response.body
response.end()
else if route.forward?
protocol = "http"
if route.forward.ssl
protocol = "https"
target = "#{protocol}://#{route.forward.host}:#{route.forward.port}"
options = {
target: target
}
@printCallback target
proxyNow = () ->
uthis.printCallback "Forwarding to #{target}"
uthis.proxy.web request, response, options
if route.delay?
@printCallback "Delaying by #{route.delay} seconds"
@setTimeoutCallback proxyNow, (route.delay) * 1000
else
proxyNow()
dispatch: (request, response) ->
path = request.url.substring(1)
@printCallback "Dispatch: #{path}"
matchedRoutes = this.findMatchingRoutes {path: path, \
method: request.method}
if matchedRoutes.length > 0
@printCallback "Matched #{matchedRoutes.length} routes, will dispatch in first one"
for route in matchedRoutes
@printCallback "In route #{route.key}"
this.printRoute route
return this.dispatchInRoute(request, response, route)
@printCallback "No idea how to process the request!"
this.dispatchNoRoutes request, response
null
# eslint no-unused-expressions: "allow"
exports.MockableHttpServer = MockableHttpServer