This repository was archived by the owner on Aug 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 604
Expand file tree
/
Copy pathbongo.coffee
More file actions
executable file
·706 lines (533 loc) · 20.2 KB
/
bongo.coffee
File metadata and controls
executable file
·706 lines (533 loc) · 20.2 KB
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
# coffeelint: disable=cyclomatic_complexity
###
Bongo.js
Unfancy models for MongoDB
(c) 2011 Koding, Inc.
@class: bongo
@description: the main klass of the library.
@author: Christopher Thorn <chris@koding.com>
###
{ EventEmitter } = require 'events'
debug = (require 'debug') 'bongo'
module.exports = class Bongo extends EventEmitter
[READY, NOTREADY] = [0, 1]
Promise = require 'bluebird'
# core
url = require 'url'
fs = Promise.promisifyAll require 'fs'
path = require 'path'
require 'colors'
@mongo = require 'mongodb'
{ extend } = require 'underscore'
@JsPath = JsPath = require 'jspath'
@Inflector = require 'inflector'
# lib
# the base klass of the library:
@Base = Base = require './base'
# the model klass of the library:
@Model = Model = require './model'
ModelRegistry = require './modelregistry'
@ModelCursor = require './modelcursor'
# the rest of the basics:
@Subcollection = require './subcollection'
@ObjectId = require './objectid'
@ObjectRef = require './objectref'
@Validator = require './validator'
@Register = require './register'
@util = require './util'
{ daisy, @daisy, @dash, @sequence, @race } = require 'sinkrow'
{ @future } = require 'sinkrow-future'
{ Scrubber, Store } = require 'koding-dnode-protocol'
Traverse = require 'traverse'
EXCHANGE_OPTIONS = {
autoDelete : no
durable : yes
type :'fanout'
}
@signature = require './signature'
@secure = (fn) ->
fn.isSecurityEnabled = yes
fn
{ @asynchronizeOwnMethods } = require './util'
{ BongoError } = require './errortypes'
Client = require './client'
@throwIt = (it) ->
console.error it if it?
process.exit 1
constructor: (options) ->
{ @mq, @mongo, @resourceName, @root, @metrics, @cache
@fetchClient, @verbose, models, @kite, @mqConfig, @redisClient } = options
@setClient @mongo if @mongo
Model.setCache @cache if @cache
@localStore = new Store
@remoteStore = new Store
@clients = {}
@models = {}
@modelFiles = []
@stack = []
@services = {}
if models
models = [models] unless Array.isArray models
@modelPaths = models.map (_path) =>
path.join @root, _path
@modelIndexPaths = models.map (_path) =>
path.join @root, _path, 'models.json'
else
@modelPaths = []
@modelIndexPaths = []
@loadModels()
@on 'error', Bongo.throwIt
@mq?.ready => @mq.connection?.on 'error', (err) ->
if err.code < 500
console.error err
return
console.error 'AMQP error!'
console.error err
process.exit 1
@setMaxListeners 0
@emit 'newInstance', this
@pendingUpdateInstancesMessages = {}
@updateInstancesMessageThrottleMs = 100
bound: require 'koding-bound'
defineModel: (name, model) ->
unless model.addBongo? this
return null
if @models[name]
console.warn "Model #{name} defined multiple times!"
return name
@models[name] = model
@emit 'newModel', name, model
model.on 'needsPopulated', (def, _path) =>
_path = if Array.isArray _path then _path else _path.split '.'
names = JsPath.getAt def, _path
unless Array.isArray names
names = [names]
JsPath.setAt def, _path, names
names.forEach (name, i) =>
if target = @models[name]
JsPath.setAt def, _path.concat(i), target
@on 'newModel', (newName, newModel) ->
if newName in names
JsPath.setAt def, _path.concat(names.indexOf newName), newModel
return name
registerModels: (path) ->
models = []
cons = require path
# means that we've only one possible model candidate
# in provided path, return model definition.
if cons.name? and ('function' is typeof cons)
model = @defineModel cons.name, cons
models.push model if model
else
# there might be multiple models
for own name, konstructor of cons
model = @defineModel name, konstructor
models.push model if model
if models.length > 0
@modelFiles.push path
return models
findCode = (paths) ->
Promise.map paths, (_path) ->
fs.lstatAsync(_path).then (stats) ->
# in the case that this is a directory, recurse into it
if stats.isDirectory()
fs.readdirAsync(_path).map (dir) ->
path.join _path, dir
.then findCode
# otherwise, just collect the path
else [_path]
# flatten the result
.reduce((a, b) -> a.concat b)
# if coffee or js file include it
.filter (_path) -> return /(\.coffee|\.js)$/.test(_path)
# if test file return false and exclude file
.filter (_path) -> return not (/\.test\.coffee$/.test _path)
loadModels: ->
modelPathToLoad = null
Promise.map @modelIndexPaths, (modelPath, index) =>
# just for loggin purposes in catch handler
modelPathToLoad = modelPath.replace @root, ''
# check if model file exists, if not this will throw err here
fs.lstatSync modelPath
# read model data
cache = JSON.parse(fs.readFileSync(modelPath).toString())
debug 'Model list found:', modelPath
debug "Loading #{Object.keys(cache).length} models..."
Object.keys(cache).map (name) =>
debug 'Loading model:', name
@registerModels path.join @modelPaths[index], cache[name]
.catch (err) =>
debug 'Cache not found or corrupted, re-building...'
debug 'Error was:', err.message
if process.env.CI
@emit 'error', \
new Error """
Model file not found! It needs to be under models folder!
Please provide a valid `models.json` under #{modelPathToLoad}
"""
@buildModelIndexes()
.then =>
debug 'Ready!', (Object.keys @models).length
@emit 'apiReady'
buildModelIndexes: ->
debug 'Building index for following paths:', @modelPaths
Promise.map @modelPaths, (_path, index) =>
cache = {}
modelPath = @modelIndexPaths[index]
findCode([_path]).map (codePath) =>
Promise.try =>
models = @registerModels codePath
plainPath = codePath.replace _path, ''
if models and models.length > 0
debug models.join(', '), 'model(s) found under:', plainPath
cache[model] = plainPath for model in models
else
debug 'No model found under:', plainPath
.catch (err) =>
@emit 'error', \
new Error "Error loading a class: #{ codePath } #{ err.message }"
.then ->
debug 'Updating models.json on: ', modelPath
# write down models.json
fs.writeFileSync modelPath, JSON.stringify cache, ' ', 2
.then =>
@emit 'apiReady'
getInstanceRoutingKey = (inst, event) ->
"oid.#{inst.getId()}.event.#{event}"
getStaticRoutingKey = (konstructor, event) ->
"constructor.#{konstructor.name}.event.#{event}"
handleEvent:(type, ctx, event, params) ->
switch type
when 'instance'
payload = JSON.stringify params[0] or null
routingKey = getInstanceRoutingKey ctx, event
@enqueueUpdateInstancesEvent routingKey, payload
when 'static'
if event is 'broadcast'
[secretChannelId, message] = params
@fetchBrokerExchange (brokerExchange) ->
messageStr = JSON.stringify message
brokerExchange.publish secretChannelId, messageStr if messageStr?
else
broadcastable = ctx.getBroadcastable()
if not broadcastable? or broadcastable # TODO: this is insecure by default :(
[data] = params
data = JSON.stringify data
@enqueueUpdateInstancesEvent getStaticRoutingKey(ctx, event), data
enqueueUpdateInstancesEvent: (routingKey, message) ->
unless @pendingUpdateInstancesMessages[routingKey]
@pendingUpdateInstancesMessages[routingKey] = []
len = @pendingUpdateInstancesMessages[routingKey].push message
@triggerUpdateInstancesEvent routingKey if len is 1
return this
triggerUpdateInstancesEvent:(routingKey) ->
setTimeout =>
{ pendingUpdateInstancesMessages } = this
messages = pendingUpdateInstancesMessages[routingKey]
@pendingUpdateInstancesMessages[routingKey] = []
if messages.length > 0
@mq?.emit 'updateInstances', routingKey, JSON.stringify(messages), { autoDelete: no }
, @updateInstancesMessageThrottleMs
return this
publishEventToExchange: (data) ->
return unless @mqConfig
{ exchangeName } = @mqConfig
@mq.connection?.exchange "#{exchangeName}", EXCHANGE_OPTIONS, (exchange) ->
return console.error "Exchange not found!: #{exchangeName}" unless exchange
{ type, message } = data
exchange.publish '', message, { type }
exchange.close()
parseRoutingKey: do ->
getEdgeMeaning = (i) ->
switch i
when 0 then 'origin'
when 1 then 'secretChannelId'
when 2 then 'username'
when 3 then 'service'
when 4 then 'event'
else "additionalProperty#{i - 4}"
parseRoutingKey = (routingKey) ->
routingKey.split('.').reduce (acc, edge, i) ->
acc[getEdgeMeaning i] = edge
acc
, {}
respondToClient:(routingKey, message) ->
message = \
if Buffer.isBuffer(message) or 'string' is typeof message
message
else
JSON.stringify message
@fetchBrokerExchange (brokerExchange) ->
brokerExchange.publish routingKey, message
getBrokerExchangeOptions: ->
type : 'topic'
autoDelete : no
durable : no
fetchBrokerExchange:(callback) ->
if @brokerExchange is null
@once 'brokerExchangeReady', => @fetchBrokerExchange callback
else unless @brokerExchange?
@brokerExchange = null
@mq?.connection.exchange 'broker', @getBrokerExchangeOptions(),
(@brokerExchange) =>
@emit 'brokerExchangeReady'
callback brokerExchange
else callback @brokerExchange
authenticateUser:(clientId, callback) ->
@fetchClient clientId, (client) ->
callback client?.connection?.delegate
createPresenceMemberKey: ->
serviceGenericName = @resourceName
serviceUniqueName = @resourceName #@getRabbitMqResourceName()
"serviceType.bongo.serviceGenericName.#{serviceGenericName}.serviceUniqueName.#{serviceUniqueName}"
connect:(callback = ->) ->
@once 'connected', =>
if @dbClientReady then callback()
else @once 'dbClientReady', callback
@mq?.ready =>
exchangeOptions = { type:'fanout', autoDelete: yes }
@mq.connection.exchange @resourceName, exchangeOptions, (@exchange) =>
@mq.connection.queue @resourceName, (@queue) =>
@emit 'connected'
queue.bind exchange, ''
queue.on 'queueBindOk', =>
queue.subscribe( (message, headers, deliveryInfo) =>
{ routingKey } = deliveryInfo
if routingKey is 'auth.join'
@respondToClient message.routingKey,
method : 'handshakeDone'
arguments : []
callbacks : {}
else if routingKey is 'auth.leave' then # ignore
else
message = if message.data? then "#{message.data}" else message
@handleRequest routingKey, { message }
).addCallback (ok) => @consumerTag = ok.consumerTag
disconnect:(callback) ->
{ queue } = this
return callback new BongoError 'You are not connected!' unless queue?
queue.unsubscribe(@consumerTag).addCallback -> queue.close()
delete @consumerTag
delete @readyState = 0
delete @queue
callback? null
revive:(data) ->
{ models } = this
new Traverse(data).forEach (node) ->
if data?.bongo_?
konstructor = models[data.bongo_.constructorName]
model = \
try new konstructor data
catch e then data
@update model, yes
else
@update node
handleRequest: (secretName, request, callback) ->
{ message, client } = request
@emit 'message', { secretName, message }
unless @dbClientReady
@once 'dbClientReady', => @handleRequest secretName, request
return
{ method, sessionToken, userArea } = message
methodName = if method.constructorName
then "#{method.constructorName}.#{method.method}"
else method
scrubber = new Scrubber @localStore
unscrubbed = scrubber.unscrub message, (callbackId) =>
fn =
if callback?
then (args...) ->
callback secretName, callbackId, args
else (args...) =>
@handleResponse secretName, callbackId, args
fn.autoCull = yes
fn
@invokeMethod method, unscrubbed, userArea, sessionToken, secretName, client
pong: (callback) -> callback? Date.now()
invokeMethod: do ->
###
@helper apply()
@private
@description - apply the method, conditionally currying the "client" object
###
apply = (bongo, ctx, method, args, sessionToken, userArea, client) ->
unless ctx?
bongo.handleUserError "Bad instance! #{method}", args
return
if 'function' is typeof method
fn = method
else if ctx? and 'string' is typeof method
# prefer the method with the trailing dollar, since this should be, by
# convention, the version of the method which implements security for
# a given model, and provides a wrapper for it; otherwise, search for
# the method with the exact name.
fn = ctx["#{method}$"] ? ctx[method]
unless fn?
bongo.handleUserError "Unknown method! #{method}", args
return
if fn.isSecurityEnabled
if client
args = [client].concat args
fn.apply ctx, args
else
bongo.fetchClient sessionToken, userArea, (client) ->
args = [client].concat args
fn.apply ctx, args
else
fn.apply ctx, args
###
@implementation
###
(method, args, userArea, sessionToken, secretName, client) ->
unless method?
@handleUserError 'No such method', args
else if method is 'ping' then @pong args[0]
else if method is 'monitorPresence' then @monitorPresence args[0]
else if method is 'authenticateUser' then @authenticateUser args... # TODO: this doesn't need to be specialcase. C.T.
else if method is 'xhrHandshake' then @xhrHandshake args...
else if method?.method
konstructor = Base.constructors[method.constructorName]
unless konstructor?
@handleUserError "No such constructor! #{method.constructorName}", args
return
[validCall, signatures] = konstructor.testSignature \
method.type, method.method, args
unless validCall
signatures = " Possible signatures are #{JSON.stringify signatures}"
@handleUserError "Unrecognized signature for #{konstructor.name}.#{method.method}#{signatures ? ''}", args
return
switch method.type
when 'static'
if konstructor.hasSharedMethod method.method
apply this, konstructor, method.method, args, sessionToken, userArea, client
else
@handleUserError "No such method! #{JSON.stringify method}", args
when 'instance'
if konstructor::hasSharedMethod method.method
if method.id
unless konstructor.one?
@handleUserError "Constructor #{konstructor.name} has no instance getter!", args
return
konstructor.one? { _id: method.id }, (err, instance) =>
if err
@handleUserError err, args
else unless instance
@handleUserError "#{konstructor.name} instance with id #{method.id} is not found", args
else
apply this, instance, method.method, args, sessionToken, userArea, client
else if method.data
instance = new konstructor method.data
apply this, instance, method.method, args, sessionToken, userArea, client
else
@handleUserError "No such method! #{JSON.stringify method}", args
else
@handleUserError 'Unknown method type!', args
else
if (kallback = @localStore.get method)?
apply this, null, kallback, args, sessionToken, userArea, client
else
@handleUserError 'Unknown method type!', args
handleUserError: (message, args) ->
console.warn '[Bongo:UserError]', message, args
if (Array.isArray args) and args.length > 0
callback = args[args.length - 1]
if 'function' is typeof callback
callback { message }
@emit 'userError', message
detectErrFirst:(cursor) ->
if cursor.path.length is 1 and
cursor.path[0] is '0' and
'string' is typeof cursor.node?.message
# node_ instead of node since traverse strips out Error
@emit 'errFirstDetected', cursor.node_
scrubResponse: (callbackId, args, callback) ->
scrubber = new Scrubber @localStore, @bound 'detectErrFirst'
scrubber.scrub args, ->
message = scrubber.toDnodeProtocol()
message.method = callbackId
callback message
handleResponse: (secretName, callbackId, args) ->
@scrubResponse callbackId, args, (message) =>
@fetchBrokerExchange (brokerExchange) =>
# when internal error send a generic error message to client
if message?.arguments[0]?.internal?
message.arguments[0] = { message:'Something went wrong!' }
brokerExchange.publish secretName, JSON.stringify(message, @replacer)
getMethodDescription:(konstructor) -> konstructor.getSharedMethods()
describeApi:(callback) ->
api = {}
# share the global constructors
for own name, konstructor of Base.globalSharedConstructors
api[name] = @getMethodDescription konstructor
# share the constructors which are specific to this bongo instance
for own name, konstructor of @models when konstructor.isShared
api[name] = @getMethodDescription konstructor
@callMiddleware api, -> callback api
callMiddleware:(api, callback) ->
if @stack.length
queue = @stack.map (fn) => =>
switch fn.length
when 2 then fn.call this, api, -> queue.next() # async style
when 1 then fn.call this, api; queue.next() # sync style
else callback new Error "Arity error! (got #{fn.length}; expected 1 or 2)"
daisy queue, callback
else
callback api
dispatchMethod:(contructorName, method, context, args) ->
# implement dispatch method
getClient: -> Model.getClient()
getCache: -> Model.getCache()
setClient:(rest...) ->
Model.setClient rest...
Model.on 'dbClientReady', =>
@dbClientReady = yes
@emit 'dbClientReady'
.on 'dbClientDown', =>
@dbClientDown = yes
.on 'dbClientUp', =>
@dbClientDown = no
.on 'error', ->
console.error 'Model error!'
console.error err
process.exit 1
use:(fn...) -> @stack.push fn...
expressify: require './expressify'
xhrHandshake: (callback) -> callback()
registerKite: ->
# This one is deprecated for now, will be enabled later ~ GG
return
host = require('os').hostname()
{ name, username, environment, region, version, kontrol, kiteKey, port, prefix } = @kite
SockJsServer = require 'kite.js/lib/kite-server/sockjs/server.js'
SockJs = require 'node-sockjs-client'
BongoKiteServer = require './kite-server'
@kiteServer = new BongoKiteServer {
name
username
environment
region
version
serverClass: SockJsServer
transportClass: SockJs
prefix
}
.on 'method', ({ payload, callback }) =>
token = @kiteServer.getToken()
@kite.fetchClient token.claims.sub, (err, client) =>
return @emit 'error', err if err?
@invokeMethod(
payload.method
[payload.arguments..., callback]
client.context
'n/a'
'kite.js'
client
)
.on 'error', (err) ->
console.error 'Kite server error!'
console.error err
process.exit 1
@kiteServer.listen port
@kiteServer.register
host : host
kiteKey : kiteKey