-
Notifications
You must be signed in to change notification settings - Fork 1
/
wakeful.coffee
282 lines (215 loc) · 10.7 KB
/
wakeful.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
if window?
# we're running in a browser
$ = window.$
_ = window._
Backbone = window.Backbone
Drowsy = window.Drowsy
Faye = window.Faye
else
# we're running in node
$ = require 'jquery'
_ = require 'underscore'
Backbone = require 'backbone'
Backbone.$ = $
{Drowsy} = require './backbone.drowsy'
Faye = require 'faye'
global.window = {} # backbone 1.0.0 expects 'window' to be defined
# calls the given val if it's a function, or just returns it as is otherwise
readVal = (context, val) ->
if _.isFunction(val)
val.call context
else
val
# FIXME: under Firefox, Faye seems to occassionally use JSONP instead of WebSockets
# which makes Mocha complain about globals being introduced inside code (_jsonp_ vars)
class Wakeful
# mixin Backbone's Events module to allow Wakeful (itself) to handle events
_.extend this, Backbone.Events;
if Faye?
@Faye = Faye
unless Wakeful.fayeClients?
Wakeful.fayeClients = {}
# A list of all Faye.Subscriptions crated by Wakeful objects.
# We keep this list in order to close all subs at the end of each
# test/spec.
@subs: []
@sync: (method, obj, options) ->
deferredSync = $.Deferred()
data = obj.toJSON()
if method is 'read'
Backbone.sync(method, obj, options)
.fail (xhr) ->
console.error("ERROR",xhr.responseText)
obj.trigger('sync:error', obj, xhr, options)
# TOOO: parse JSON responseText
err = new Error(xhr.status+": "+xhr.responseText)
deferredSync.reject(err)
.done ->
obj.dirty = {}
deferredSync.resolve()
else
# TODO: figure out how to support delete
switch method
when 'create', 'update'
obj.broadcast(method, data)
when 'patch'
changed = obj.dirtyAttributes()
#unless _.isEmpty(changedJSON) # don't broadcast when there are no changes
# FIXME: hacky and inefficent way to make sure changed attributes are JSONified correctly
temp = new Drowsy.Document(changed)
changedJSON = temp.toJSON()
delete changedJSON._id # id can't change
obj.broadcast(method, changedJSON)
# FIXME: maybe don't resolve and trigger until .broadcast() resolves?
obj.dirty = {}
obj.trigger('sync', obj, changed ? data, options)
deferredSync.resolve()
return deferredSync
@wake: (obj, fayeUrl, options = {}) ->
if obj.fayeUrl? and obj.fayeUrl is fayeUrl
console.log obj,"is already awake... skipping"
return
throw new Error("Must provide a fayeUrl") unless fayeUrl?
obj.fayeUrl = fayeUrl
obj.broadcastEchoQueue = []
# FIXME: Not really sure what's going on here... the original intention was not to re-use
# faye clients, but Faye 1.0 seems to discourage the way we were doing it, and this
# does seem to work as is. The part I don't get is why tests start failing if we
# set the client directly on obj.faye?
Wakeful.fayeClients[fayeUrl] = new Wakeful.Faye.Client(fayeUrl, timeout: 35) # WakefulWeasel timeout is 30 seconds, so +5 here... see http://faye.jcoglan.com/browser.html
obj.faye = Wakeful.fayeClients[fayeUrl]
obj.sync = Wakeful.sync
obj = _.extend obj,
subscriptionUrl: ->
drowsyUrl = readVal(this, @url)
# This regex matches Drowsy urls like
# http://drowsy.example.com/my-database/my-collection
# http://localhost/mydb/some_collection/13ad6a54cb08c806f8f00000
# https://drowsy.foo.com/example-database/some.collection
rx = /[a-z]+:\/\/[^\/]+\/([^\/\.]+)\/(\w[^\/\$]*)(?:\/([0-9a-f]{24}))?/
parsedUrl = drowsyUrl.match(rx)
unless parsedUrl?
console.error drowsyUrl, "is not a valid Drowsy URL usable with WakefulWeasel"
throw new Error('Invalid Drowsy URL', drowsyUrl)
[url, db, coll, id] = parsedUrl
if id?
"/#{db}/#{coll}/#{id}"
else
"/#{db}/#{coll}/*"
tunein: ->
# baseRx = "^wss?://[^/]+"
# fullRx = "#{baseRx}/\\w+/\\w+(/[0-9a-f]+)?"
# if fayeUrl.match(new RegExp("#{baseRx}/?$"))
# @fayeUrl = readVal(this, @url).replace(new RegExp("[a-z]+://[^/]+/?"), fayeUrl+"/")
# else if fayeUrl.match(new RegExp(fullRx))
# @fayeUrl = fayeUrl
# else
# console.error fayeUrl, "is not a valid WakefulWeasel WebSocket URL!"
# throw "Invalid WakefulWeasel WebSocket URL!"
if this instanceof Drowsy.Document and !@has('_id')
console.error "Wakeful cannot tunein for this object because it does not yet been assigned an id!", this
throw new Error("Cannot call tunein() on Drowsy.Document because it has not yet been assigned an id", this)
deferredSub = $.Deferred()
@sub = @faye.subscribe @subscriptionUrl(), _.bind(@receiveBroadcast, this)
@sub.callback ->
deferredSub.resolve()
@sub.errback (err) ->
deferredSub.reject(err)
Wakeful.subs.push @sub
return deferredSub
tuneout: ->
sub.cancel()
delete @sub
broadcast: (action, data) ->
deferredPub = $.Deferred()
# bid = broadcast id
# we're just using the Mongo ObjectId as a pseudo-unique string;
# the method call has nothing to do with MongoDB
bid = Drowsy.generateMongoObjectId()
# don't need to stringify data... Faye does it for us
#data = JSON.stringify(data) unless typeof data is 'string'
# make sure that we always have an id attached so that
# we can identify who this data refers to
if not data._id? and @id?
data._id = @id
unless data._id?
console.warn("Cannot broadcast data for a Drowsy.Document without an id!", data, this)
deferredPub.reject('missing_id')
return deferredPub
bcast =
action: action
data: data
bid: bid
@broadcastEchoQueue.push(deferredPub)
toChannel = @subscriptionUrl()
if this instanceof Drowsy.Collection
toChannel = toChannel.replace(/\*$/,'~') # hack to get channel subscription to hear its own broadcasts
pub = @faye.publish toChannel, bcast
@trigger 'wakeful:broadcast:sent', bcast
deferredPub.notify 'sent'
pub.callback =>
# NOTE: Usually this will get executed AFTER deferredPub.
# ... not sure why, but Faye seems to execute this callback
# some time after broadcasting the pub.
# As a consequence, a .progress() handler bound to
# deferredPub for 'confirmed' doesn't normally get triggered,
# since it will have resolved already.
@trigger 'wakeful:broadcast:confirmed', bcast
deferredPub.notify 'confirmed'
pub.errback (err) =>
console.warn "Broadcast ##{bid} failed!", err, bcast
@trigger 'wakeful:broadcast:error', bcast, err
deferredPub.reject err
deferredPub.pub = pub
deferredPub.bid = bid
return deferredPub
receiveBroadcast: (bcast) ->
echoOf = _.find @broadcastEchoQueue, (defPub) -> defPub.bid is bcast.bid
if echoOf?
echoIndex = _.indexOf @broadcastEchoQueue, echoOf
@broadcastEchoQueue.splice(echoIndex, 1) # remove echoOf
@trigger 'wakeful:broadcast:echo', bcast
echoOf.resolve()
return
@trigger 'wakeful:broadcast:received', bcast
switch bcast.action
when 'update','patch','create'
if this instanceof Drowsy.Document
@set @parse(bcast.data)
else
# this is a collection
if _.isArray(bcast.data)
docs = bcast.data
if bcast.action is 'patch' and not bcast.data?
console.error "PATCH received by collection will be ignored because the broadcast data did not include a document id (_id)", bcast
return
else
docs = [bcast.data]
docs = docs.map (doc) => @model::parse(doc)
@set docs, remove: false
else
console.warn "Don't know how to handle broadcast with action", bcast.action
obj.faye.bind 'transport:up', =>
@trigger 'transport:up'
Wakeful.trigger 'transport:up', obj
obj.faye.bind 'transport:down', =>
@trigger 'transport:down'
Wakeful.trigger 'transport:down', obj
unless options.tunein is false
obj.tunein()
# returns a jQuery.Deferred, so you can call .done() or .then() on the result
# to wait until the script has been loaded
@loadFayeClient: (fayeUrl) ->
deferredLoad = $.Deferred()
$.getScript "#{fayeUrl}/client.js", (script) ->
# CoffeeScript prevents us from using late-loaded globals in our code so
# have to load it into Wakeful instead
Wakeful.Faye = window.Faye
deferredLoad.resolve()
deferredLoad
Drowsy.Document::wake = (fayeUrl, options = {}) ->
Wakeful.wake(this, fayeUrl, options)
Drowsy.Collection::wake = (fayeUrl, options = {}) ->
Wakeful.wake(this, fayeUrl, options)
root = exports ? this
root.Wakeful = Wakeful