This repository was archived by the owner on Aug 15, 2022. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathbongo.coffee
More file actions
executable file
·404 lines (357 loc) · 13.2 KB
/
Copy pathbongo.coffee
File metadata and controls
executable file
·404 lines (357 loc) · 13.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
###
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'
module.exports = class Bongo extends EventEmitter
[READY, NOTREADY] = [0,1]
# core
url = require 'url'
fs = require 'fs'
nodePath = require 'path'
# bongo = new EventEmitter
# client-side boilerplate
#@client = bongoClient = require 'bongo-client'
# dnode = require 'koding-dnode'
# contrib
@mongo = require 'mongoskin'
{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'
@Plugin = require './plugin'
@Register = require './register'
@util = require './util'
{daisy, @daisy, @dash, @sequence, @race, @future} = require 'sinkrow'
{Scrubber, Store} = require 'koding-dnode-protocol'
Traverse = require 'traverse'
@secure =(fn)->
fn.isSecurityEnabled = yes
fn
{@asynchronizeOwnMethods} = require './util'
{BongoError} = require './errortypes'
Client = require './client'
@throwIt =(it)-> throw it if it?
constructor:(options)->
{@mq, @mongo, @resourceName, @root, @fetchClient, models} = options
@setClient @mongo
@localStore = new Store
@remoteStore = new Store
@clients = {}
@models = {}
@stack = []
@services = {}
#@initBlacklist options.blacklist
@loadModels models
@on 'error', Bongo.throwIt
@setMaxListeners 0
initBlacklist:do ->
blacklister = (k, v)->
return if k in @blacklist
return v
(@blacklist=[])->
if blacklist.length
@blacklisting = yes
@replacer = blacklister.bind @
defineModel:(name, model)->
@models[name] = model
model.addBongo @
@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
listModels=(root="", modelPath, acc={})->
path = nodePath.join root, modelPath
stat = fs.statSync path
if stat.isDirectory()
names = fs.readdirSync path
for name in names
listModels root, nodePath.join(modelPath, name), acc
else if /(\.coffee|\.js)$/.test path
acc[path] = NOTREADY
return acc
createModelRegistry:(modelPath)->
acc = {}
if Array.isArray modelPath
listModels @root, item, acc for item in modelPath
else
listModels @root, modelPath, acc
new ModelRegistry acc
loadModels:(modelPath)->
@registry = @createModelRegistry(modelPath)
@registry.forEach (path)=>
try model = require path
catch e then return @emit 'error', e
if model.name? and ('function' is typeof model)
@defineModel model.name, model
else
@defineModel name, konstructor for own name, konstructor of model
@registry.setState path, READY
@emit 'ready'
getInstanceRoutingKey =(inst, event)->
"oid.#{inst.getId()}.event.#{event}"
getStaticRoutingKey =(konstructor, event)->
"constructor.#{konstructor.name}.event.#{event}"
handleEvent:(type, ctx, event, rest)->
switch type
when 'instance'
@mq.emit 'updateInstances', getInstanceRoutingKey(ctx, event), rest[0], autoDelete: no
when 'static'
if event is 'global-listener-added'
[actualEvent, listener] = rest
#@mq.on 'event-'+ctx.name, actualEvent, listener
else
[data] = rest
@mq.emit 'updateInstances', getStaticRoutingKey(ctx, event), data, autoDelete: no
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)=>
@emit 'authenticateUser', client, callback
createPresenceMemberKey:->
serviceGenericName = @resourceName
serviceUniqueName = @resourceName #@getRabbitMqResourceName()
"serviceType.bongo.serviceGenericName.#{serviceGenericName}.serviceUniqueName.#{serviceUniqueName}"
createPresence:->
Presence = require 'koding-rabbit-presence'
new Presence {
connection : @mq.connection
member : @createPresenceMemberKey()
exchange : 'services-presence'
}
establishPresence:->
return if @presence?
@presence = @createPresence()
@presence.announce()
@presence.listen()
@presence.on 'join', (serviceKey)=> @services[serviceKey] = 1
@presence.on 'leave', (serviceKey)=> delete @services[serviceKey]
monitorPresence:(callbacks)->
return unless @presence?
callbacks.join serviceKey for serviceKey in Object.keys @services
@presence.on 'join', callbacks.join if callbacks.join?
@presence.on 'leave', callbacks.leave if callbacks.leave?
connect:(callback=->)->
@once 'connected', callback
@mq.ready =>
@establishPresence()
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'
@describeApi (api)=>
response =
method : 'defineApi'
arguments : [api]
callbacks : {}
@respondToClient message.routingKey, response
@handleAuth message.routingKey
else if routingKey is 'auth.leave'
console.log 'got an auth.leave message'
else
@handleRequest routingKey,
if message.data? then "#{message.data}"
else 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
handleAuth:(secretName, sessionToken)->
@fetchBrokerExchange (brokerExchange)->
brokerExchange.publish
# @emit 'auth', secretName, sessionToken
handleRequest:(secretName, message)->
message =\
try JSON.parse message
catch e then message
{method, sessionToken, userArea} = message
scrubber = new Scrubber @localStore
unscrubbed = scrubber.unscrub message, (callbackId)=>
storeKey = secretName+callbackId
unless @remoteStore.has storeKey
@remoteStore.add storeKey, (args...)=>
@handleResponse secretName, callbackId, args
@remoteStore.get storeKey
@invokeMethod method, unscrubbed, secretName, sessionToken, userArea
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)->
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]
return unless fn?
if fn.isSecurityEnabled
bongo.fetchClient sessionToken, userArea, (client)->
args = [client].concat args
fn.apply ctx, args
else
fn.apply ctx, args
###
@implementation
###
(method, args, secretName, sessionToken, userArea)->
unless method?
@handleError 'No such method'
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?.method
konstructor = Base.constructors[method.constructorName]
switch method.type
when 'static'
if konstructor.hasSharedMethod method.method
apply @, konstructor, method.method, args, sessionToken, userArea
else
@handleError "No such method! #{JSON.stringify method} #{args} #{secretName}"
when 'instance'
if konstructor::hasSharedMethod method.method
if method.id
konstructor.one? _id: method.id, (err, instance)=>
if err
@handleError err
else
apply @, instance, method.method, args, sessionToken, userArea
else if method.data
instance = new konstructor data
apply @, instance, method.method, args, sessionToken, userArea
else
@handleError "No such method! #{JSON.stringify method} #{args} #{secretName}"
else
@handleError 'Unknown method type!'
else
kallback = @localStore.get method
if kallback?
apply @, null, kallback, args, sessionToken, userArea
else
@handleError 'Unknown method type!'
handleError:(message)->
@emit 'error',
if message?.message then {message: message.message}
else {message}
handleResponse:(secretName, callbackId, args)->
scrubber = new Scrubber @localStore
scrubber.scrub args, =>
message = scrubber.toDnodeProtocol()
message.method = callbackId
@fetchBrokerExchange (brokerExchange)=>
brokerExchange.publish secretName, JSON.stringify(message, @replacer)
getMethodDescription:(name, konstructor)->
description = konstructor.getSharedMethods()
description.options =
broadcastable : konstructor.getBroadcastable?()
slugTemplate : konstructor.slugTemplate
schema : konstructor.describeSchema?()
pid : process.pid
description
describeApi:(callback)->
api = {}
# share the global constructors
for own name, konstructor of Base.globalSharedConstructors
api[name] = @getMethodDescription name, konstructor
# share the constructors which are specific to this bongo instance
for own name, konstructor of @models when konstructor.isShared
api[name] = @getMethodDescription name, konstructor
@callMiddleware api, -> callback api
callMiddleware:(api, callback)->
if @stack.length
queue = @stack.map (fn)=>=>
switch fn.length
when 2 then fn.call @, api, -> queue.next() # async style
when 1 then fn.call @, 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
setClient:(rest...)-> Model.setClient rest...
use:(fn...)-> @stack.push fn...