Repository navigation
Expand file tree
/
Copy pathbongo.coffee
More file actions
executable file
·474 lines (389 loc) · 13.9 KB
/
Copy pathbongo.coffee
File metadata and controls
executable file
·474 lines (389 loc) · 13.9 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
'use strict'
###
Bongo.js
Unfancy models for MongoDB
(c) 2011 Koding, Inc.
@module: bongo-client
@author: Christopher Thorn <chris@koding.com>
###
###
@snippet.
@description: feature-detect the browser.
@todo: is there an improvement?
@foo
###
isBrowser = 'undefined' isnt typeof window
###
@class: bongo (client)
@description: client-side bongo.
###
# core
{EventEmitter} = require 'microemitter'
class Bongo extends EventEmitter
[NOTCONNECTED, CONNECTING, CONNECTED, DISCONNECTED] = [0,1,2,3]
BATCH_CHUNK_MS = 300
# bongo = new EventEmitter
# contrib
Traverse = require 'traverse'
createId = @createId = require 'hat'
JsPath = @JsPath = require 'jspath'
@dnodeProtocol = require 'koding-dnode-protocol'
@dnodeProtocol.Scrubber = require './src/scrubber'
{Store, Scrubber} = @dnodeProtocol
@EventEmitter = EventEmitter
Model = @Model = require './src/model'
@ListenerTree = require './src/listenertree'
EventBus = @EventBus = require './src/eventbus'
OpaqueType = require './src/opaquetype'
Signature = require './src/signature'
@promibackify = require './src/promibackify'
# mixin the event emitter for the AMQP broker
Model::mixin require './src/eventemitter/broker'
# need these aliases:
Model::off = Model::removeListener
Model::addGlobalListener = Model::on
{slice} = []
{extend} = require './src/util'
{race, sequence, dash} = require 'sinkrow'
{@daisy, @dash, @sequence, @race} = require 'sinkrow'
@bound = require 'koding-bound'
bound: require 'koding-bound'
createBongoName =(resourceName)->
"#{createId 128}.unknown.bongo-#{resourceName}"
constructor:(options)->
EventEmitter this
{ @mq, @getSessionToken, @getUserArea, @fetchName, @resourceName,
@apiEndpoint, @useWebsockets, @batchRequests, @apiDescriptor } = options
@useWebsockets ?= no
@batchRequests ?= yes
@getUserArea ?= -> # noop
@localStore = new Store
@remoteStore = new Store
@readyState = NOTCONNECTED
@stack = []
@opaqueTypes = {}
@on 'newListener', (event, listener)=>
if event is 'ready' and @readyState is CONNECTED
process.nextTick =>
@emit 'ready'
@off 'ready'
@setOutboundTimer() if @batchRequests
unless @useWebsockets
process.nextTick @bound 'xhrHandshake'
process.nextTick =>
@api = @createRemoteApiShims @apiDescriptor
if @mq?
@eventBus = new EventBus @mq
@mq.on 'disconnected', =>
@disconnectedAt = Date.now()
@emit 'disconnected'
@readyState = DISCONNECTED
isConnected: -> return @readyState is CONNECTED
cacheable: require './src/cacheable'
cacheableAsync: (rest...) ->
new Promise (resolve, reject) =>
@cacheable rest..., (err, model) ->
return reject err if err
resolve model
createRemoteApiShims:(api)->
shimmedApi = {}
for own name, {statik, instance, attributes} of api
shimmedApi[name] = @createConstructor name, statik, instance, attributes
shimmedApi
guardMethod = (signatures, fn) -> (rest...) ->
for signature in signatures when signature.test rest
return fn.apply this, rest
throw new Error "Unrecognized signature!"
wrapStaticMethods:do ->
optimizeThese = ['on','off']
(constructor, constructorName, methods) ->
bongo = this
(Object.keys methods).forEach (method) ->
signatures = methods[method].map Signature
method += '_' if method in optimizeThese
wrapper = guardMethod signatures, (rest...) ->
rpc = {
type: 'static'
constructorName
method
}
bongo.send rpc, rest
wrapper.signatures = signatures
constructor[method] = Bongo.promibackify wrapper
wrapInstanceMethods:do ->
optimizeThese = ['on','addListener','off','removeListener','save']
(constructor, constructorName, methods) ->
bongo = this
(Object.keys methods).forEach (method) ->
signatures = methods[method].map Signature
method += '_' if method in optimizeThese
wrapper = guardMethod signatures, (rest...) ->
id = @getId()
data = @data unless id?
rpc = {
type: 'instance'
constructorName
method
id
data
}
bongo.send rpc, rest
wrapper.signatures = signatures
constructor::[method] = Bongo.promibackify wrapper
registerInstance:(inst)->
inst.on 'listenerRemoved', (event, listener)=>
@eventBus.off inst, event, listener.bind inst
inst.on 'newListener', (event, listener)=>
@eventBus.on inst, event, listener.bind inst
getEventChannelName =(name)-> "event-#{name}"
getRevivingListener =(bongo, ctx, listener)->
(rest...)-> listener.apply ctx, bongo.revive rest
addGlobalListener =(konstructor, event, listener)->
@eventBus.staticOn konstructor, event, (rest...)=>
revived = @revive rest
listener.apply konstructor, revived
reviveType:(type, shouldWrap)->
return @reviveType type[0], yes if Array.isArray type
return type unless 'string' is typeof type
revived = @api[type] ?
window[type] ?
@opaqueTypes[type] ?= new OpaqueType type
if shouldWrap then [revived] else revived
reviveSchema:do->
{keys} = Object
{isArray} = Array
reviveSchemaRecursively = (bongo, schema)->
(keys schema)
.map (slot)->
type = schema[slot]
if (type and 'object' is typeof type) and not isArray type
type = reviveSchemaRecursively bongo, type
[slot, type]
.reduce (acc, [slot, type])->
acc[slot] = bongo.reviveType type
acc
, {}
reviveSchema = (schema)->
reviveSchemaRecursively this, schema
createConstructor:(name, staticMethods, instanceMethods, attributes)->
konstructor = Function('bongo', """
return function #{name} () {
bongo.registerInstance(this);
this.init.apply(this, [].slice.call(arguments));
this.bongo_.constructorName = '#{name}';
}
""") this
EventEmitter konstructor
@wrapStaticMethods konstructor, name, staticMethods
konstructor extends Model
konstructor::updateInstanceChannel = @updateInstanceChannel
konstructor.on 'newListener', addGlobalListener.bind @, konstructor
konstructor.attributes = attributes
@wrapInstanceMethods konstructor, name, instanceMethods
konstructor
getInstancesById:->
getInstanceMethods:-> ['changeLoggedInState','updateSessionToken']
revive:(obj)->
bongo = @
hasEncoder = Encoder?.XSSEncode?
new Traverse(obj).map (node)->
if node?.bongo_?
{constructorName, instanceId} = node.bongo_
instance = bongo.getInstancesById instanceId
return @update instance, yes if instance?
konstructor = bongo.api[node.bongo_.constructorName]
unless konstructor?
@update node
else
@update new konstructor node
else if hasEncoder and 'string' is typeof node
@update Encoder.XSSEncode node
else
@update node
reviveFromSnapshots:do ->
# TODO: fix this properly, but it avoids clobbering the _events property
snapshotReviver =(k, v)->
return if k is '_events'
return v
(instances, callback)->
results = instances.map (instance)=>
revivee = null
try
revivee = JSON.parse instance.snapshot, snapshotReviver if instance.snapshot?
catch e
console.warn "couldn't revive snapshot! #{instance._id}"
revivee = null
return null unless revivee
@revive revivee
results = results.filter Boolean
callback null, results
handleRequest:(message)->
if message?.method is 'defineApi' and not @api?
@defineApi message.arguments[0]
else if message?.method is 'handshakeDone'
@handshakeDone()
else
{method, context} = message
scrubber = new Scrubber @localStore
unscrubbed = scrubber.unscrub message, (callbackId)=>
unless @remoteStore.has(callbackId)
@remoteStore.add callbackId, (args...)=>
@send callbackId, args
@remoteStore.get callbackId
revived = @revive unscrubbed
if method in @getInstanceMethods()
@[method] revived...
else unless isNaN +method
callback = @localStore.get(method)
callback?.apply null, revived
else unless method is 'auth.authOk' # ok to ignore that one
console.warn 'Unhandleable message; dropping it on the floor.'
# console.trace()
# console.log message
# console.log method
reconnectHelper:->
if @api?
@readyState = CONNECTED
@emit 'ready'
connectHelper:(callback)->
@mq.once 'connected', callback.bind @ if callback?
@channelName = createBongoName @resourceName
@channel = @mq.subscribe @channelName, {connectDirectly:yes}
@channel.exchange = @resourceName
@channel.setAuthenticationInfo
serviceType : 'bongo'
name : @resourceName
clientId : @getSessionToken()
@channel.off 'message', @bound 'handleRequest'
@channel.on 'message', @bound 'handleRequest'
@reconnectHelper()
@channel.once 'broker.subscribed', =>
# apply the middleware
@stack.forEach (fn)=> fn.call @
@channel.on 'broker.subscribed', =>
@emit 'connected'
if @disconnectedAt
@emit 'reconnected', disconnectedFor: Date.now() - @disconnectedAt
@disconnectedAt = null
if @lastMessage
@channel.publish @lastMessage
@lastMessage = null
connect:(callback)->
throw new Error "no broker client" unless @mq?
switch @readyState
when CONNECTED, CONNECTING then return "already connected"
when DISCONNECTED
@readyState = CONNECTING
@mq.connect()
if callback?
@mq.on 'connected', -> callback null
else
@readyState = CONNECTING
@connectHelper callback
if @mq.autoReconnect
@mq.once 'disconnected', => @mq.once 'connected', => @reconnectHelper()
disconnect:(shouldReconnect, callback)->
# @channel.close().off() if @channel?
throw new Error "no broker client" unless @mq?
if 'function' is typeof shouldReconnect
callback = shouldReconnect
shouldReconnect = no
return "already disconnected" if @readyState is NOTCONNECTED or @readyState is DISCONNECTED
@mq.once 'disconnected', callback.bind this if callback?
@mq.disconnect shouldReconnect
@readyState = DISCONNECTED
messageFailed:(message)->
console.log 'MESSAGE FAILED', message
getTimeout:(message, clientTimeout=5000)->
setTimeout @messageFailed.bind(this, message), clientTimeout
ping:(callback)->
@send 'ping', callback if @readyState is CONNECTED and @useWebsockets
send:(method, args)->
args = [args] unless Array.isArray args
if @mq? and not @channel
throw new Error 'No channel!'
scrubber = new Scrubber @localStore
scrubber.scrub args, =>
message = scrubber.toDnodeProtocol()
message.method = method
message.sessionToken = @getSessionToken()
message.userArea = @getUserArea()
@sendHelper message
sendHelper: (message) ->
if @useWebsockets
messageString = JSON.stringify message
if @channel.isOpen
@channel.publish messageString
else
@lastMessage = messageString
@connect()
else if @apiEndpoint
konstructor = @api[message.method.constructorName]
if @batchRequests and not konstructor?.attributes.bypassBatch
@enqueueMessage message
else
@sendXhr @apiEndpoint, 'POST', [message]
setOutboundTimer: ->
@outboundQueue = []
@outboundTimer = setInterval =>
if @outboundQueue.length
@sendXhr @apiEndpoint, 'POST', @outboundQueue
@outboundQueue.length = 0
, BATCH_CHUNK_MS
enqueueMessage: (message) ->
@outboundQueue.push message
sendXhr: (url, method, queue) ->
xhr = new XMLHttpRequest
xhr.open method, url
xhr.setRequestHeader "Content-type", "application/json;charset=UTF-8"
xhr.onreadystatechange = =>
if xhr.status is 0
return # TODO: try again with backoff
if xhr.status >= 400
@emit 'error', new Error "XHR Error: #{ xhr.status }"
return if xhr.readyState isnt 4
return if xhr.status not in [200, 304]
requests = JSON.parse xhr.response
@handleRequest request for request in requests when request
messageString = JSON.stringify { @channelName, queue }
xhr.send messageString
authenticateUser:->
clientId = @getSessionToken()
@send 'authenticateUser', [clientId, @bound 'changeLoggedInState']
handshakeDone:->
return if @readyState is CONNECTED
@readyState = CONNECTED
@emit 'ready'
@authenticateUser()
defineApi:(api)->
if api?
@api or= @createRemoteApiShims api
@handshakeDone()
changeLoggedInState:(state)->
@emit 'loggedInStateChanged', state
updateSessionToken:(token)->
@emit 'sessionTokenChanged', token
fetchChannel:(channelName, callback)->
throw new Error "no broker client" unless @mq?
channel = @mq.subscribe channelName
channel.once 'broker.subscribed', -> callback channel
use:(fn)->
@stack.push fn
monitorPresence:(callbacks)-> @send 'monitorPresence', callbacks
subscribe:(name, options={}, callback)->
throw new Error "no broker client" unless @mq?
options.serviceType ?= 'application'
channel = @mq.subscribe name, options
options.name = name
options.clientId = @getSessionToken()
channel.setAuthenticationInfo options
if callback? then channel.once 'broker.subscribed', -> callback channel
return channel
xhrHandshake: -> @send 'xhrHandshake', (api) =>
if @api
then @handshakeDone()
else @defineApi api
if not isBrowser and module
module.exports = Bongo
else if window?
window['Bongo'] = Bongo