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
·350 lines (295 loc) · 10.2 KB
/
Copy pathbongo.coffee
File metadata and controls
executable file
·350 lines (295 loc) · 10.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
'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
# bongo = new EventEmitter
# contrib
Traverse = require 'traverse'
createId = @createId = require 'hat'
JsPath = @JsPath = require 'jspath'
{Store} = require 'koding-dnode-protocol'
Scrubber = require './src/scrubber'
@dnodeProtocol = {Store, Scrubber}
@EventEmitter = EventEmitter
Model = @Model = require './src/model'
@ListenerTree = require './src/listenertree'
EventBus = @EventBus = require './src/eventbus'
OpaqueType = require './src/opaquetype'
# 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
# TODO: temporary hack
# @KDML = require 'kdml'
{slice} = []
{extend} = require './src/util'
{race, sequence, dash} = require 'sinkrow'
{@daisy, @dash, @sequence, @race, @future} = 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} = options
@getUserArea ?= -> # noop
@localStore = new Store
@remoteStore = new Store
@readyState = 0
@stack = []
@eventBus = new EventBus @mq
@mq.on 'message', @bound 'handleRequestString'
@mq.on 'disconnected', @emit.bind this, 'disconnected'
@opaqueTypes = {}
@on 'newListener', (event, listener)=>
if event is 'ready' and @readyState is 1
process.nextTick =>
@emit 'ready'
@removeAllListeners 'ready'
cacheable:require './src/cacheable'
createRemoteApiShims:(api)->
shimmedApi = {}
for own name, {statik, instance, options} of api
shimmedApi[name] = @createConstructor name, statik, instance, options
shimmedApi
wrapStaticMethods:do ->
optimizeThese = ['on','off']
(constructor, constructorName, statik)->
bongo = @
statik.forEach (method)->
method += '_' if method in optimizeThese
constructor[method] =(rest...)->
rpc = {
type: 'static'
constructorName
method
}
bongo.send rpc, rest
wrapInstanceMethods:do ->
optimizeThese = ['on','addListener','off','removeListener','save']
(constructor, constructorName, instance)->
bongo = @
instance.forEach (method)->
method += '_' if method in optimizeThese
constructor::[method] =->
id = @getId()
data = @data unless id?
rpc = {
type: 'instance'
constructorName
method
id
data
}
bongo.send rpc, [].slice.call arguments
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
reviveOption:(option, value)->
switch option
when 'schema' then @reviveSchema value
else value
createConstructor:(name, staticMethods, instanceMethods, options)->
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
process.nextTick =>
for own option of options
konstructor[option] = @reviveOption option, options[option]
@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
handleRequestString:(messageStr)->
@handleRequest \
try JSON.parse messageStr
catch e then messageStr
handleRequest:(message)->
if message?.method is 'defineApi' and not @api?
@defineApi message.arguments[0]
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
console.warn 'Unhandleable message; dropping it on the floor.'
console.trace()
console.log message
console.log method
connectHelper:(callback)->
@mq.once 'connected', callback.bind @ if callback?
@channelName = createBongoName @resourceName
@channel = @mq.subscribe @channelName
@channel.exchange = @resourceName
@channel.setAuthenticationInfo
serviceType : 'bongo'
name : @resourceName
clientId : @getSessionToken()
@channel.off 'message', @bound 'handleRequest'
@channel.on 'message', @bound 'handleRequest'
@readyState = 1
@emit 'ready' if @api?
@channel.once 'broker.subscribed', =>
# apply the middleware
@stack.forEach (fn)=> fn.call @
@emit 'connected'
connect:(callback)->
switch @readyState
when 1
return "already connected"
when 3
@readyState = 0
@mq.connect => @connectHelper callback
else
@connectHelper callback
if @mq.autoReconnect
@mq.once 'disconnected', => @mq.on 'connected', => @connectHelper()
disconnect:(shouldReconnect, callback)->
if 'function' is typeof shouldReconnect
callback = shouldReconnect
shouldReconnect = no
return "already disconnected" if @readyState is 0
@mq.once 'disconnected', callback.bind this if callback?
@mq.disconnect shouldReconnect
@readyState = 3
messageFailed:(message)->
console.log 'MESSAGE FAILED', message
getTimeout:(message, clientTimeout=5000)->
setTimeout @messageFailed.bind(this, message), clientTimeout
ping:(callback)-> @send 'ping', callback
send:(method, args)->
args = [args] unless Array.isArray args
throw new Error 'No channel!' unless @channel
scrubber = new Scrubber @localStore
scrubber.scrub args, =>
message = scrubber.toDnodeProtocol()
message.method = method
message.sessionToken = @getSessionToken()
message.userArea = @getUserArea()
messageString = JSON.stringify message
@channel.publish messageString
authenticateUser:->
clientId = @getSessionToken()
@send 'authenticateUser', [clientId, @bound 'changeLoggedInState']
defineApi:(api)->
@api = @createRemoteApiShims api
@emit 'ready'
@authenticateUser()
changeLoggedInState:(state)->
@emit 'loggedInStateChanged', state
updateSessionToken:(token)->
@emit 'sessionTokenChanged', token
fetchChannel:(channelName, callback)->
channel = @mq.subscribe channelName
channel.on 'broker.subscribed', -> callback channel
use:(fn)->
@stack.push fn
monitorPresence:(callbacks)-> @send 'monitorPresence', callbacks
if not isBrowser and module
module.exports = Bongo
else if window?
window['Bongo'] = Bongo