alondra 0.0.3

Sign up to get free protection for your applications and to get access to all the features.
Files changed (117) hide show
  1. data/.gitignore +9 -0
  2. data/Gemfile +22 -0
  3. data/Gemfile.lock +166 -0
  4. data/MIT-LICENSE +20 -0
  5. data/README.md +177 -0
  6. data/Rakefile +34 -0
  7. data/alondra.gemspec +23 -0
  8. data/app/assets/javascripts/alondra-client.js.coffee.erb +71 -0
  9. data/app/assets/javascripts/moz_websocket.js +5 -0
  10. data/app/assets/javascripts/vendor/jquery.json-2.2.js +178 -0
  11. data/app/assets/javascripts/vendor/json2.js +480 -0
  12. data/app/assets/javascripts/vendor/swfobject.js +4 -0
  13. data/app/assets/javascripts/vendor/web_socket.js +379 -0
  14. data/app/assets/swf/WebSocketMain.swf +0 -0
  15. data/app/helpers/alondra_helper.rb +24 -0
  16. data/lib/alondra/changes_callbacks.rb +52 -0
  17. data/lib/alondra/changes_push.rb +23 -0
  18. data/lib/alondra/channel.rb +84 -0
  19. data/lib/alondra/command.rb +38 -0
  20. data/lib/alondra/command_dispatcher.rb +22 -0
  21. data/lib/alondra/connection.rb +52 -0
  22. data/lib/alondra/event.rb +74 -0
  23. data/lib/alondra/event_listener.rb +86 -0
  24. data/lib/alondra/event_router.rb +27 -0
  25. data/lib/alondra/listener_callback.rb +37 -0
  26. data/lib/alondra/message.rb +35 -0
  27. data/lib/alondra/message_queue.rb +70 -0
  28. data/lib/alondra/message_queue_client.rb +71 -0
  29. data/lib/alondra/push_controller.rb +53 -0
  30. data/lib/alondra/pushing.rb +14 -0
  31. data/lib/alondra/server.rb +44 -0
  32. data/lib/alondra/session_parser.rb +57 -0
  33. data/lib/alondra.rb +80 -0
  34. data/lib/generators/alondra/USAGE +8 -0
  35. data/lib/generators/alondra/alondra_generator.rb +7 -0
  36. data/lib/generators/alondra/templates/alondra +33 -0
  37. data/lib/tasks/alondra_tasks.rake +4 -0
  38. data/script/rails +6 -0
  39. data/test/dummy/Rakefile +7 -0
  40. data/test/dummy/app/assets/javascripts/application.js +9 -0
  41. data/test/dummy/app/assets/stylesheets/application.css +7 -0
  42. data/test/dummy/app/controllers/application_controller.rb +14 -0
  43. data/test/dummy/app/controllers/chats_controller.rb +85 -0
  44. data/test/dummy/app/controllers/messages_controller.rb +12 -0
  45. data/test/dummy/app/controllers/sessions_controller.rb +20 -0
  46. data/test/dummy/app/controllers/users_controller.rb +30 -0
  47. data/test/dummy/app/helpers/application_helper.rb +2 -0
  48. data/test/dummy/app/helpers/chats_helper.rb +6 -0
  49. data/test/dummy/app/helpers/error_messages_helper.rb +23 -0
  50. data/test/dummy/app/helpers/layout_helper.rb +22 -0
  51. data/test/dummy/app/mailers/.gitkeep +0 -0
  52. data/test/dummy/app/models/.gitkeep +0 -0
  53. data/test/dummy/app/models/chat.rb +5 -0
  54. data/test/dummy/app/models/message.rb +4 -0
  55. data/test/dummy/app/models/user.rb +37 -0
  56. data/test/dummy/app/views/chats/_form.html.erb +21 -0
  57. data/test/dummy/app/views/chats/edit.html.erb +6 -0
  58. data/test/dummy/app/views/chats/index.html.erb +23 -0
  59. data/test/dummy/app/views/chats/new.html.erb +5 -0
  60. data/test/dummy/app/views/chats/show.html.erb +49 -0
  61. data/test/dummy/app/views/layouts/application.html.erb +19 -0
  62. data/test/dummy/app/views/sessions/new.html.erb +15 -0
  63. data/test/dummy/app/views/shared/_message.js.erb +1 -0
  64. data/test/dummy/app/views/users/_form.html.erb +20 -0
  65. data/test/dummy/app/views/users/edit.html.erb +3 -0
  66. data/test/dummy/app/views/users/index.html.erb +25 -0
  67. data/test/dummy/app/views/users/new.html.erb +5 -0
  68. data/test/dummy/app/views/users/show.html.erb +15 -0
  69. data/test/dummy/config/application.rb +42 -0
  70. data/test/dummy/config/boot.rb +10 -0
  71. data/test/dummy/config/database.yml +31 -0
  72. data/test/dummy/config/environment.rb +5 -0
  73. data/test/dummy/config/environments/development.rb +27 -0
  74. data/test/dummy/config/environments/production.rb +54 -0
  75. data/test/dummy/config/environments/test.rb +39 -0
  76. data/test/dummy/config/initializers/backtrace_silencers.rb +7 -0
  77. data/test/dummy/config/initializers/inflections.rb +10 -0
  78. data/test/dummy/config/initializers/mime_types.rb +5 -0
  79. data/test/dummy/config/initializers/secret_token.rb +7 -0
  80. data/test/dummy/config/initializers/session_store.rb +9 -0
  81. data/test/dummy/config/initializers/wrap_parameters.rb +12 -0
  82. data/test/dummy/config/locales/en.yml +5 -0
  83. data/test/dummy/config/routes.rb +19 -0
  84. data/test/dummy/config.ru +4 -0
  85. data/test/dummy/db/migrate/20110719090458_create_chats.rb +9 -0
  86. data/test/dummy/db/migrate/20110719090538_create_messages.rb +10 -0
  87. data/test/dummy/db/migrate/20110720193249_create_users.rb +16 -0
  88. data/test/dummy/db/schema.rb +38 -0
  89. data/test/dummy/lib/controller_authentication.rb +48 -0
  90. data/test/dummy/log/.gitkeep +0 -0
  91. data/test/dummy/public/404.html +26 -0
  92. data/test/dummy/public/422.html +26 -0
  93. data/test/dummy/public/500.html +26 -0
  94. data/test/dummy/public/favicon.ico +0 -0
  95. data/test/dummy/public/stylesheets/application.css +75 -0
  96. data/test/dummy/script/rails +6 -0
  97. data/test/integration/push_changes_test.rb +41 -0
  98. data/test/integration/push_messages_test.rb +40 -0
  99. data/test/models/channel_test.rb +49 -0
  100. data/test/models/command_test.rb +29 -0
  101. data/test/models/configuration_test.rb +22 -0
  102. data/test/models/connection_test.rb +18 -0
  103. data/test/models/event_listener_test.rb +217 -0
  104. data/test/models/event_router_test.rb +7 -0
  105. data/test/models/message_queue_client_test.rb +26 -0
  106. data/test/models/message_queue_test.rb +70 -0
  107. data/test/models/pushing_test.rb +34 -0
  108. data/test/performance/message_queue_performance.rb +66 -0
  109. data/test/support/factories.rb +19 -0
  110. data/test/support/integration_helper.rb +18 -0
  111. data/test/support/integration_test.rb +6 -0
  112. data/test/support/mocks/bogus_event.rb +15 -0
  113. data/test/support/mocks/mock_connection.rb +24 -0
  114. data/test/support/mocks/mock_event_router.rb +12 -0
  115. data/test/support/mocks/mock_listener.rb +9 -0
  116. data/test/test_helper.rb +14 -0
  117. metadata +316 -0
@@ -0,0 +1,379 @@
1
+ // Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
2
+ // License: New BSD License
3
+ // Reference: http://dev.w3.org/html5/websockets/
4
+ // Reference: http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10
5
+
6
+ (function() {
7
+
8
+ if (window.WebSocket && !window.WEB_SOCKET_FORCE_FLASH) return;
9
+
10
+ var logger;
11
+ if (window.WEB_SOCKET_LOGGER) {
12
+ logger = WEB_SOCKET_LOGGER;
13
+ } else if (window.console && window.console.log && window.console.error) {
14
+ // In some environment, console is defined but console.log or console.error is missing.
15
+ logger = window.console;
16
+ } else {
17
+ logger = {log: function(){ }, error: function(){ }};
18
+ }
19
+
20
+ // swfobject.hasFlashPlayerVersion("10.0.0") doesn't work with Gnash.
21
+ if (swfobject.getFlashPlayerVersion().major < 10) {
22
+ logger.error("Flash Player >= 10.0.0 is required.");
23
+ return;
24
+ }
25
+ if (location.protocol == "file:") {
26
+ logger.error(
27
+ "WARNING: web-socket-js doesn't work in file:///... URL " +
28
+ "unless you set Flash Security Settings properly. " +
29
+ "Open the page via Web server i.e. http://...");
30
+ }
31
+
32
+ /**
33
+ * This class represents a faux web socket.
34
+ * @param {string} url
35
+ * @param {array or string} protocols
36
+ * @param {string} proxyHost
37
+ * @param {int} proxyPort
38
+ * @param {string} headers
39
+ */
40
+ WebSocket = function(url, protocols, proxyHost, proxyPort, headers) {
41
+ var self = this;
42
+ self.__id = WebSocket.__nextId++;
43
+ WebSocket.__instances[self.__id] = self;
44
+ self.readyState = WebSocket.CONNECTING;
45
+ self.bufferedAmount = 0;
46
+ self.__events = {};
47
+ if (!protocols) {
48
+ protocols = [];
49
+ } else if (typeof protocols == "string") {
50
+ protocols = [protocols];
51
+ }
52
+ // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
53
+ // Otherwise, when onopen fires immediately, onopen is called before it is set.
54
+ self.__createTask = setTimeout(function() {
55
+ WebSocket.__addTask(function() {
56
+ self.__createTask = null;
57
+ WebSocket.__flash.create(
58
+ self.__id, url, protocols, proxyHost || null, proxyPort || 0, headers || null);
59
+ });
60
+ }, 0);
61
+ };
62
+
63
+ /**
64
+ * Send data to the web socket.
65
+ * @param {string} data The data to send to the socket.
66
+ * @return {boolean} True for success, false for failure.
67
+ */
68
+ WebSocket.prototype.send = function(data) {
69
+ if (this.readyState == WebSocket.CONNECTING) {
70
+ throw "INVALID_STATE_ERR: Web Socket connection has not been established";
71
+ }
72
+ // We use encodeURIComponent() here, because FABridge doesn't work if
73
+ // the argument includes some characters. We don't use escape() here
74
+ // because of this:
75
+ // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
76
+ // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
77
+ // preserve all Unicode characters either e.g. "\uffff" in Firefox.
78
+ // Note by wtritch: Hopefully this will not be necessary using ExternalInterface. Will require
79
+ // additional testing.
80
+ var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data));
81
+ if (result < 0) { // success
82
+ return true;
83
+ } else {
84
+ this.bufferedAmount += result;
85
+ return false;
86
+ }
87
+ };
88
+
89
+ /**
90
+ * Close this web socket gracefully.
91
+ */
92
+ WebSocket.prototype.close = function() {
93
+ if (this.__createTask) {
94
+ clearTimeout(this.__createTask);
95
+ this.__createTask = null;
96
+ this.readyState = WebSocket.CLOSED;
97
+ return;
98
+ }
99
+ if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) {
100
+ return;
101
+ }
102
+ this.readyState = WebSocket.CLOSING;
103
+ WebSocket.__flash.close(this.__id);
104
+ };
105
+
106
+ /**
107
+ * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
108
+ *
109
+ * @param {string} type
110
+ * @param {function} listener
111
+ * @param {boolean} useCapture
112
+ * @return void
113
+ */
114
+ WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
115
+ if (!(type in this.__events)) {
116
+ this.__events[type] = [];
117
+ }
118
+ this.__events[type].push(listener);
119
+ };
120
+
121
+ /**
122
+ * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
123
+ *
124
+ * @param {string} type
125
+ * @param {function} listener
126
+ * @param {boolean} useCapture
127
+ * @return void
128
+ */
129
+ WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
130
+ if (!(type in this.__events)) return;
131
+ var events = this.__events[type];
132
+ for (var i = events.length - 1; i >= 0; --i) {
133
+ if (events[i] === listener) {
134
+ events.splice(i, 1);
135
+ break;
136
+ }
137
+ }
138
+ };
139
+
140
+ /**
141
+ * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
142
+ *
143
+ * @param {Event} event
144
+ * @return void
145
+ */
146
+ WebSocket.prototype.dispatchEvent = function(event) {
147
+ var events = this.__events[event.type] || [];
148
+ for (var i = 0; i < events.length; ++i) {
149
+ events[i](event);
150
+ }
151
+ var handler = this["on" + event.type];
152
+ if (handler) handler.apply(this, [event]);
153
+ };
154
+
155
+ /**
156
+ * Handles an event from Flash.
157
+ * @param {Object} flashEvent
158
+ */
159
+ WebSocket.prototype.__handleEvent = function(flashEvent) {
160
+
161
+ if ("readyState" in flashEvent) {
162
+ this.readyState = flashEvent.readyState;
163
+ }
164
+ if ("protocol" in flashEvent) {
165
+ this.protocol = flashEvent.protocol;
166
+ }
167
+
168
+ var jsEvent;
169
+ if (flashEvent.type == "open" || flashEvent.type == "error") {
170
+ jsEvent = this.__createSimpleEvent(flashEvent.type);
171
+ } else if (flashEvent.type == "close") {
172
+ jsEvent = this.__createSimpleEvent("close");
173
+ jsEvent.wasClean = flashEvent.wasClean ? true : false;
174
+ jsEvent.code = flashEvent.code;
175
+ jsEvent.reason = flashEvent.reason;
176
+ } else if (flashEvent.type == "message") {
177
+ var data = decodeURIComponent(flashEvent.message);
178
+ jsEvent = this.__createMessageEvent("message", data);
179
+ } else {
180
+ throw "unknown event type: " + flashEvent.type;
181
+ }
182
+
183
+ this.dispatchEvent(jsEvent);
184
+
185
+ };
186
+
187
+ WebSocket.prototype.__createSimpleEvent = function(type) {
188
+ if (document.createEvent && window.Event) {
189
+ var event = document.createEvent("Event");
190
+ event.initEvent(type, false, false);
191
+ return event;
192
+ } else {
193
+ return {type: type, bubbles: false, cancelable: false};
194
+ }
195
+ };
196
+
197
+ WebSocket.prototype.__createMessageEvent = function(type, data) {
198
+ if (document.createEvent && window.MessageEvent && !window.opera) {
199
+ var event = document.createEvent("MessageEvent");
200
+ event.initMessageEvent("message", false, false, data, null, null, window, null);
201
+ return event;
202
+ } else {
203
+ // IE and Opera, the latter one truncates the data parameter after any 0x00 bytes.
204
+ return {type: type, data: data, bubbles: false, cancelable: false};
205
+ }
206
+ };
207
+
208
+ /**
209
+ * Define the WebSocket readyState enumeration.
210
+ */
211
+ WebSocket.CONNECTING = 0;
212
+ WebSocket.OPEN = 1;
213
+ WebSocket.CLOSING = 2;
214
+ WebSocket.CLOSED = 3;
215
+
216
+ WebSocket.__flash = null;
217
+ WebSocket.__instances = {};
218
+ WebSocket.__tasks = [];
219
+ WebSocket.__nextId = 0;
220
+
221
+ /**
222
+ * Load a new flash security policy file.
223
+ * @param {string} url
224
+ */
225
+ WebSocket.loadFlashPolicyFile = function(url){
226
+ WebSocket.__addTask(function() {
227
+ WebSocket.__flash.loadManualPolicyFile(url);
228
+ });
229
+ };
230
+
231
+ /**
232
+ * Loads WebSocketMain.swf and creates WebSocketMain object in Flash.
233
+ */
234
+ WebSocket.__initialize = function() {
235
+ if (WebSocket.__flash) return;
236
+
237
+ if (WebSocket.__swfLocation) {
238
+ // For backword compatibility.
239
+ window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
240
+ }
241
+ if (!window.WEB_SOCKET_SWF_LOCATION) {
242
+ logger.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
243
+ return;
244
+ }
245
+ if (!window.WEB_SOCKET_SUPPRESS_CROSS_DOMAIN_SWF_ERROR &&
246
+ !WEB_SOCKET_SWF_LOCATION.match(/(^|\/)WebSocketMainInsecure\.swf(\?.*)?$/) &&
247
+ WEB_SOCKET_SWF_LOCATION.match(/^\w+:\/\/([^\/]+)/)) {
248
+ var swfHost = RegExp.$1;
249
+ if (location.host != swfHost) {
250
+ logger.error(
251
+ "[WebSocket] You must host HTML and WebSocketMain.swf in the same host " +
252
+ "('" + location.host + "' != '" + swfHost + "'). " +
253
+ "See also 'How to host HTML file and SWF file in different domains' section " +
254
+ "in README.md. If you use WebSocketMainInsecure.swf, you can suppress this message " +
255
+ "by WEB_SOCKET_SUPPRESS_CROSS_DOMAIN_SWF_ERROR = true;");
256
+ }
257
+ }
258
+ var container = document.createElement("div");
259
+ container.id = "webSocketContainer";
260
+ // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
261
+ // Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
262
+ // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
263
+ // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
264
+ // the best we can do as far as we know now.
265
+ container.style.position = "absolute";
266
+ if (WebSocket.__isFlashLite()) {
267
+ container.style.left = "0px";
268
+ container.style.top = "0px";
269
+ } else {
270
+ container.style.left = "-100px";
271
+ container.style.top = "-100px";
272
+ }
273
+ var holder = document.createElement("div");
274
+ holder.id = "webSocketFlash";
275
+ container.appendChild(holder);
276
+ document.body.appendChild(container);
277
+ // See this article for hasPriority:
278
+ // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
279
+ swfobject.embedSWF(
280
+ WEB_SOCKET_SWF_LOCATION,
281
+ "webSocketFlash",
282
+ "1" /* width */,
283
+ "1" /* height */,
284
+ "10.0.0" /* SWF version */,
285
+ null,
286
+ null,
287
+ {hasPriority: true, swliveconnect : true, allowScriptAccess: "always"},
288
+ null,
289
+ function(e) {
290
+ if (!e.success) {
291
+ logger.error("[WebSocket] swfobject.embedSWF failed");
292
+ }
293
+ });
294
+ };
295
+
296
+ /**
297
+ * Called by Flash to notify JS that it's fully loaded and ready
298
+ * for communication.
299
+ */
300
+ WebSocket.__onFlashInitialized = function() {
301
+ // We need to set a timeout here to avoid round-trip calls
302
+ // to flash during the initialization process.
303
+ setTimeout(function() {
304
+ WebSocket.__flash = document.getElementById("webSocketFlash");
305
+ WebSocket.__flash.setCallerUrl(location.href);
306
+ WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
307
+ for (var i = 0; i < WebSocket.__tasks.length; ++i) {
308
+ WebSocket.__tasks[i]();
309
+ }
310
+ WebSocket.__tasks = [];
311
+ }, 0);
312
+ };
313
+
314
+ /**
315
+ * Called by Flash to notify WebSockets events are fired.
316
+ */
317
+ WebSocket.__onFlashEvent = function() {
318
+ setTimeout(function() {
319
+ try {
320
+ // Gets events using receiveEvents() instead of getting it from event object
321
+ // of Flash event. This is to make sure to keep message order.
322
+ // It seems sometimes Flash events don't arrive in the same order as they are sent.
323
+ var events = WebSocket.__flash.receiveEvents();
324
+ for (var i = 0; i < events.length; ++i) {
325
+ WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]);
326
+ }
327
+ } catch (e) {
328
+ logger.error(e);
329
+ }
330
+ }, 0);
331
+ return true;
332
+ };
333
+
334
+ // Called by Flash.
335
+ WebSocket.__log = function(message) {
336
+ logger.log(decodeURIComponent(message));
337
+ };
338
+
339
+ // Called by Flash.
340
+ WebSocket.__error = function(message) {
341
+ logger.error(decodeURIComponent(message));
342
+ };
343
+
344
+ WebSocket.__addTask = function(task) {
345
+ if (WebSocket.__flash) {
346
+ task();
347
+ } else {
348
+ WebSocket.__tasks.push(task);
349
+ }
350
+ };
351
+
352
+ /**
353
+ * Test if the browser is running flash lite.
354
+ * @return {boolean} True if flash lite is running, false otherwise.
355
+ */
356
+ WebSocket.__isFlashLite = function() {
357
+ if (!window.navigator || !window.navigator.mimeTypes) {
358
+ return false;
359
+ }
360
+ var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
361
+ if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) {
362
+ return false;
363
+ }
364
+ return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
365
+ };
366
+
367
+ if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
368
+ if (window.addEventListener) {
369
+ window.addEventListener("load", function(){
370
+ WebSocket.__initialize();
371
+ }, false);
372
+ } else {
373
+ window.attachEvent("onload", function(){
374
+ WebSocket.__initialize();
375
+ });
376
+ }
377
+ }
378
+
379
+ })();
Binary file
@@ -0,0 +1,24 @@
1
+ module AlondraHelper
2
+
3
+ def alondra_subscribe_tag(resources)
4
+ javascript_tag do
5
+ %Q{
6
+ $(function(){
7
+ #{alondra_subscribe(resources)}
8
+ });
9
+ }
10
+ end
11
+ end
12
+
13
+ def alondra_subscribe(resources)
14
+ resources = [resources] unless Enumerable === resources
15
+ resources_paths = resources.collect { |r| "'#{polymorphic_path(r)}'" }.join(', ')
16
+
17
+ "new AlondraClient('#{Alondra::Alondra.config.host}', #{Alondra::Alondra.config.port}, [#{resources_paths}]);"
18
+ end
19
+
20
+ def encrypted_token
21
+ token = {:user_id => current_user.id, :valid_until => 5.minutes.from_now}.to_json
22
+ Alondra::SessionParser.verifier.generate(token)
23
+ end
24
+ end
@@ -0,0 +1,52 @@
1
+ module Alondra
2
+ module ChangesCallbacks
3
+ extend self
4
+
5
+ def push_updates(klass, options)
6
+ klass.class_eval do
7
+ after_update do |record|
8
+ ChangesCallbacks.push_event :updated, record, options
9
+ end
10
+ end
11
+ end
12
+
13
+ def push_creations(klass, options)
14
+ klass.class_eval do
15
+ after_create do |record|
16
+ ChangesCallbacks.push_event :created, record, options
17
+ end
18
+ end
19
+ end
20
+
21
+ def push_destroys(klass, options)
22
+ klass.class_eval do
23
+ after_destroy do |record|
24
+ ChangesCallbacks.push_event :destroyed, record, options
25
+ end
26
+ end
27
+ end
28
+
29
+ def push_event(type, record, options)
30
+ channels = channel_names_from(type, record, options)
31
+
32
+ channels.each do |channel|
33
+ event = Event.new(:event => type, :resource => record,
34
+ :resource_type => record.class.name, :channel => channel)
35
+
36
+ MessageQueueClient.push event
37
+ end
38
+ end
39
+
40
+ def channel_names_from(type, record, options)
41
+ case options[:to]
42
+ when String then
43
+ [options[:to]]
44
+ when Symbol then
45
+ records = record.send options[:to]
46
+ Channel.names_for(records)
47
+ else
48
+ [Channel.default_name_for(record)]
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,23 @@
1
+ module Alondra
2
+ module ChangesPush
3
+ def push(*args)
4
+ last_arg = args.last
5
+ options = Hash === last_arg ? args.delete(last_arg) : {}
6
+
7
+ args.each do |event_type|
8
+ case event_type
9
+ when :changes then
10
+ ChangesCallbacks.push_updates(self, options)
11
+ ChangesCallbacks.push_creations(self, options)
12
+ ChangesCallbacks.push_destroys(self, options)
13
+ when :updates then
14
+ ChangesCallbacks.push_updates(self, options)
15
+ when :creations then
16
+ ChangesCallbacks.push_creations(self, options)
17
+ when :destroys then
18
+ ChangesCallbacks.push_destroys(self, options)
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,84 @@
1
+ module Alondra
2
+ class Channel
3
+ attr_reader :name
4
+ attr_reader :em_channel
5
+ attr_reader :connections
6
+
7
+ class << self
8
+ def list
9
+ @channel_list ||= {}
10
+ end
11
+
12
+ def [](name)
13
+ list[name] ||= Channel.new(name)
14
+ end
15
+
16
+ def for(records)
17
+ names_for(records).collect { |name| Channel[name] }
18
+ end
19
+
20
+ def names_for(records)
21
+ case records
22
+ when String
23
+ [records]
24
+ when Enumerable then
25
+ records.collect { |r| Channel.default_name_for(r) }
26
+ else
27
+ [Channel.default_name_for(records)]
28
+ end
29
+ end
30
+
31
+ def default_name_for(resource_or_class, type = :member)
32
+
33
+ if resource_or_class.kind_of?(Class)
34
+ resource_name = resource_or_class.name.pluralize.underscore
35
+ else
36
+ resource = resource_or_class
37
+ resource_name = resource.class.name.pluralize.underscore
38
+ end
39
+
40
+ case type
41
+ when :member then
42
+ "/#{resource_name}/#{resource.id}"
43
+ when :collection then
44
+ "/#{resource_name}/"
45
+ end
46
+ end
47
+ end
48
+
49
+ def initialize(name)
50
+ @name = name
51
+ @em_channel = EM::Channel.new
52
+ @connections = {}
53
+ end
54
+
55
+ def subscribe(connection)
56
+ sid = em_channel.subscribe do |event_or_message|
57
+ connection.receive event_or_message
58
+ end
59
+
60
+ connection.channels << self
61
+ connections[connection] = sid
62
+ end
63
+
64
+ def unsubscribe(connection)
65
+ em_channel.unsubscribe connections[connection]
66
+
67
+ connection.channels.delete self
68
+ connections.delete connection
69
+
70
+ event_hash = { :event => :unsubscribed,
71
+ :resource => connection.session,
72
+ :resource_type => connection.session.class.name,
73
+ :channel => name }
74
+
75
+
76
+ event = Event.new(event_hash, nil, connection)
77
+ event.fire!
78
+ end
79
+
80
+ def receive(event_or_message)
81
+ em_channel << event_or_message
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,38 @@
1
+ module Alondra
2
+ class Command
3
+ attr_reader :name
4
+ attr_reader :connection
5
+ attr_reader :channel_name
6
+
7
+ def initialize(connection, command_hash)
8
+ @connection = connection
9
+
10
+ @name = command_hash[:command].to_sym
11
+ @channel_name = command_hash[:channel]
12
+ end
13
+
14
+ def channel
15
+ @channel ||= Channel[channel_name]
16
+ end
17
+
18
+ def execute!
19
+ case name
20
+ when :subscribe then
21
+ channel.subscribe @connection
22
+ fire_event :subscribed
23
+ when :unsubscribe then
24
+ channel.unsubscribe @connection
25
+ fire_event :unsubscribed
26
+ end
27
+ end
28
+
29
+ def fire_event(event_type)
30
+ event_hash = {:event => event_type,
31
+ :resource => @connection.session,
32
+ :resource_type => @connection.session.class.name,
33
+ :channel => @channel_name}
34
+
35
+ Event.new(event_hash, nil, connection).fire!
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,22 @@
1
+ module Alondra
2
+
3
+ class NotRecognizedCommand < StandardError; end
4
+
5
+ module CommandDispatcher
6
+ extend self
7
+
8
+ def dispatch(input, connection)
9
+ msg = parse(input)
10
+
11
+ unless msg.kind_of?(Hash) && msg[:command].present?
12
+ raise NotRecognizedCommand.new("Unrecognized command: #{input}")
13
+ end
14
+
15
+ Command.new(connection, msg).execute!
16
+ end
17
+
18
+ def parse(string)
19
+ msg = ActiveSupport::JSON.decode(string).symbolize_keys
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,52 @@
1
+ require 'uuidtools'
2
+
3
+ module Alondra
4
+ module Connections
5
+ extend self
6
+
7
+ def connections
8
+ @connections ||= {}
9
+ end
10
+
11
+ def [](websocket)
12
+ connections[websocket]
13
+ end
14
+
15
+ def []=(websocket, connection)
16
+ connections[websocket] = connection
17
+ end
18
+
19
+ def delete(websocket)
20
+ connections.delete websocket
21
+ end
22
+ end
23
+
24
+ class Connection
25
+ attr_reader :uuid
26
+ attr_reader :websocket
27
+ attr_reader :session
28
+ attr_reader :channels
29
+
30
+ def initialize(websocket, session = {})
31
+ @session = session.symbolize_keys
32
+ @websocket = websocket
33
+ @uuid = UUIDTools::UUID.random_create
34
+
35
+ Connections[websocket] = self
36
+ end
37
+
38
+ def channels
39
+ @channels ||= []
40
+ end
41
+
42
+ def receive(event_or_message)
43
+ Rails.logger.debug "sending: #{event_or_message.to_json}"
44
+ websocket.send event_or_message.to_json
45
+ end
46
+
47
+ def destroy!
48
+ channels.each { |c| c.unsubscribe self }
49
+ Connections.delete self.websocket
50
+ end
51
+ end
52
+ end