Debian Codegraph @

closure-library/closure/goog/labs/pubsub/broadcastpubsub.js

raw
1 // Copyright 2014 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 goog.provide('goog.labs.pubsub.BroadcastPubSub');
16
17
18 goog.require('goog.Disposable');
19 goog.require('goog.Timer');
20 goog.require('goog.array');
21 goog.require('goog.async.run');
22 goog.require('goog.events.EventHandler');
23 goog.require('goog.events.EventType');
24 goog.require('goog.log');
25 goog.require('goog.math');
26 goog.require('goog.pubsub.PubSub');
27 goog.require('goog.storage.Storage');
28 goog.require('goog.storage.mechanism.HTML5LocalStorage');
29 goog.require('goog.string');
30 goog.require('goog.userAgent');
31
32
33
34 /**
35 * Topic-based publish/subscribe messaging implementation that provides
36 * communication between browsing contexts that share the same origin.
37 *
38 * Wrapper around PubSub that utilizes localStorage to broadcast publications to
39 * all browser windows with the same origin as the publishing context. This
40 * allows for topic-based publish/subscribe implementation of strings shared by
41 * all browser contexts that share the same origin.
42 *
43 * Delivery is guaranteed on all browsers except IE8 where topics expire after a
44 * timeout. Publishing of a topic within a callback function provides no
45 * guarantee on ordering in that there is a possibility that separate origin
46 * contexts may see topics in a different order.
47 *
48 * This class is not secure and in certain cases (e.g., a browser crash) data
49 * that is published can persist in localStorage indefinitely. Do not use this
50 * class to communicate private or confidential information.
51 *
52 * On IE8, localStorage is shared by the http and https origins. An attacker
53 * could possibly leverage this to publish to the secure origin.
54 *
55 * goog.labs.pubsub.BroadcastPubSub wraps an instance of PubSub rather than
56 * subclassing because the base PubSub class allows publishing of arbitrary
57 * objects.
58 *
59 * Special handling is done for the IE8 browsers. See the IE8_EVENTS_KEY_
60 * constant and the {@code publish} function for more information.
61 *
62 *
63 * @constructor @struct @extends {goog.Disposable}
64 */
65 goog.labs.pubsub.BroadcastPubSub = function() {
66 goog.labs.pubsub.BroadcastPubSub.base(this, 'constructor');
67 goog.labs.pubsub.BroadcastPubSub.instances_.push(this);
68
69 /** @private @const */
70 this.pubSub_ = new goog.pubsub.PubSub();
71 this.registerDisposable(this.pubSub_);
72
73 /** @private @const */
74 this.handler_ = new goog.events.EventHandler(this);
75 this.registerDisposable(this.handler_);
76
77 /** @private @const */
78 this.logger_ = goog.log.getLogger('goog.labs.pubsub.BroadcastPubSub');
79
80 /** @private @const */
81 this.mechanism_ = new goog.storage.mechanism.HTML5LocalStorage();
82
83 /** @private {goog.storage.Storage} */
84 this.storage_ = null;
85
86 /** @private {Object<string, number>} */
87 this.ie8LastEventTimes_ = null;
88
89 /** @private {number} */
90 this.ie8StartupTimestamp_ = goog.now() - 1;
91
92 if (this.mechanism_.isAvailable()) {
93 this.storage_ = new goog.storage.Storage(this.mechanism_);
94
95 var target = window;
96 if (goog.labs.pubsub.BroadcastPubSub.IS_IE8_) {
97 this.ie8LastEventTimes_ = {};
98
99 target = document;
100 }
101 this.handler_.listen(
102 target, goog.events.EventType.STORAGE, this.handleStorageEvent_);
103 }
104 };
105 goog.inherits(goog.labs.pubsub.BroadcastPubSub, goog.Disposable);
106
107
108 /** @private @const {!Array<!goog.labs.pubsub.BroadcastPubSub>} */
109 goog.labs.pubsub.BroadcastPubSub.instances_ = [];
110
111
112 /**
113 * SitePubSub namespace for localStorage.
114 * @private @const
115 */
116 goog.labs.pubsub.BroadcastPubSub.STORAGE_KEY_ = '_closure_bps';
117
118
119 /**
120 * Handle the storage event and possibly dispatch topics.
121 * @param {!goog.events.BrowserEvent} e Event object.
122 * @private
123 */
124 goog.labs.pubsub.BroadcastPubSub.prototype.handleStorageEvent_ = function(e) {
125 if (goog.labs.pubsub.BroadcastPubSub.IS_IE8_) {
126 // Even though we have the event, IE8 doesn't update our localStorage until
127 // after we handle the actual event.
128 goog.async.run(this.handleIe8StorageEvent_, this);
129 return;
130 }
131
132 var browserEvent = e.getBrowserEvent();
133 if (browserEvent.key != goog.labs.pubsub.BroadcastPubSub.STORAGE_KEY_) {
134 return;
135 }
136
137 var data = JSON.parse(browserEvent.newValue);
138 var args = goog.isObject(data) && data['args'];
139 if (goog.isArray(args) && goog.array.every(args, goog.isString)) {
140 this.dispatch_(args);
141 } else {
142 goog.log.warning(this.logger_, 'storage event contained invalid arguments');
143 }
144 };
145
146
147 /**
148 * Dispatches args on the internal pubsub queue.
149 * @param {!Array<string>} args The arguments to publish.
150 * @private
151 */
152 goog.labs.pubsub.BroadcastPubSub.prototype.dispatch_ = function(args) {
153 goog.pubsub.PubSub.prototype.publish.apply(this.pubSub_, args);
154 };
155
156
157 /**
158 * Publishes a message to a topic. Remote subscriptions in other tabs/windows
159 * are dispatched via local storage events. Local subscriptions are called
160 * asynchronously via Timer event in order to simulate remote behavior locally.
161 * @param {string} topic Topic to publish to.
162 * @param {...string} var_args String arguments that are applied to each
163 * subscription function.
164 */
165 goog.labs.pubsub.BroadcastPubSub.prototype.publish = function(topic, var_args) {
166 var args = goog.array.toArray(arguments);
167
168 // Dispatch to localStorage.
169 if (this.storage_) {
170 // Update topics to use the optional prefix.
171 var now = goog.now();
172 var data = {'args': args, 'timestamp': now};
173
174 if (!goog.labs.pubsub.BroadcastPubSub.IS_IE8_) {
175 // Generated events will contain all the data in modern browsers.
176 this.storage_.set(goog.labs.pubsub.BroadcastPubSub.STORAGE_KEY_, data);
177 this.storage_.remove(goog.labs.pubsub.BroadcastPubSub.STORAGE_KEY_);
178 } else {
179 // With IE8 we need to manage our own events queue.
180 var events = null;
181
182 try {
183 events =
184 this.storage_.get(goog.labs.pubsub.BroadcastPubSub.IE8_EVENTS_KEY_);
185 } catch (ex) {
186 goog.log.error(
187 this.logger_, 'publish encountered invalid event queue at ' +
188 goog.labs.pubsub.BroadcastPubSub.IE8_EVENTS_KEY_);
189 }
190 if (!goog.isArray(events)) {
191 events = [];
192 }
193 // Avoid a race condition where we're publishing in the same
194 // millisecond that another event that may be getting
195 // processed. In short, we try go guarantee that whatever event
196 // we put on the event queue has a timestamp that is older than
197 // any other timestamp in the queue.
198 var lastEvent = events[events.length - 1];
199 var lastTimestamp =
200 lastEvent && lastEvent['timestamp'] || this.ie8StartupTimestamp_;
201 if (lastTimestamp >= now) {
202 now = lastTimestamp +
203 goog.labs.pubsub.BroadcastPubSub.IE8_TIMESTAMP_UNIQUE_OFFSET_MS_;
204 data['timestamp'] = now;
205 }
206 events.push(data);
207 this.storage_.set(
208 goog.labs.pubsub.BroadcastPubSub.IE8_EVENTS_KEY_, events);
209
210 // Cleanup this event in IE8_EVENT_LIFETIME_MS_ milliseconds.
211 goog.Timer.callOnce(
212 goog.bind(this.cleanupIe8StorageEvents_, this, now),
213 goog.labs.pubsub.BroadcastPubSub.IE8_EVENT_LIFETIME_MS_);
214 }
215 }
216
217 // W3C spec is to not dispatch the storage event to the same window that
218 // modified localStorage. For conforming browsers we have to manually dispatch
219 // the publish event to subscriptions on instances of BroadcastPubSub in the
220 // current window.
221 if (!goog.userAgent.IE) {
222 // Dispatch the publish event to local instances asynchronously to fix some
223 // quirks with timings. The result is that all subscriptions are dispatched
224 // before any future publishes are processed. The effect is that
225 // subscriptions in the same window are dispatched as if they are the result
226 // of a publish from another tab.
227 goog.array.forEach(
228 goog.labs.pubsub.BroadcastPubSub.instances_, function(instance) {
229 goog.async.run(goog.bind(instance.dispatch_, instance, args));
230 });
231 }
232 };
233
234
235 /**
236 * Unsubscribes a function from a topic. Only deletes the first match found.
237 * Returns a Boolean indicating whether a subscription was removed.
238 * @param {string} topic Topic to unsubscribe from.
239 * @param {Function} fn Function to unsubscribe.
240 * @param {Object=} opt_context Object in whose context the function was to be
241 * called (the global scope if none).
242 * @return {boolean} Whether a matching subscription was removed.
243 */
244 goog.labs.pubsub.BroadcastPubSub.prototype.unsubscribe = function(
245 topic, fn, opt_context) {
246 return this.pubSub_.unsubscribe(topic, fn, opt_context);
247 };
248
249
250 /**
251 * Removes a subscription based on the key returned by {@link #subscribe}. No-op
252 * if no matching subscription is found. Returns a Boolean indicating whether a
253 * subscription was removed.
254 * @param {number} key Subscription key.
255 * @return {boolean} Whether a matching subscription was removed.
256 */
257 goog.labs.pubsub.BroadcastPubSub.prototype.unsubscribeByKey = function(key) {
258 return this.pubSub_.unsubscribeByKey(key);
259 };
260
261
262 /**
263 * Subscribes a function to a topic. The function is invoked as a method on the
264 * given {@code opt_context} object, or in the global scope if no context is
265 * specified. Subscribing the same function to the same topic multiple times
266 * will result in multiple function invocations while publishing. Returns a
267 * subscription key that can be used to unsubscribe the function from the topic
268 * via {@link #unsubscribeByKey}.
269 * @param {string} topic Topic to subscribe to.
270 * @param {Function} fn Function to be invoked when a message is published to
271 * the given topic.
272 * @param {Object=} opt_context Object in whose context the function is to be
273 * called (the global scope if none).
274 * @return {number} Subscription key.
275 */
276 goog.labs.pubsub.BroadcastPubSub.prototype.subscribe = function(
277 topic, fn, opt_context) {
278 return this.pubSub_.subscribe(topic, fn, opt_context);
279 };
280
281
282 /**
283 * Subscribes a single-use function to a topic. The function is invoked as a
284 * method on the given {@code opt_context} object, or in the global scope if no
285 * context is specified, and is then unsubscribed. Returns a subscription key
286 * that can be used to unsubscribe the function from the topic via {@link
287 * #unsubscribeByKey}.
288 * @param {string} topic Topic to subscribe to.
289 * @param {Function} fn Function to be invoked once and then unsubscribed when
290 * a message is published to the given topic.
291 * @param {Object=} opt_context Object in whose context the function is to be
292 * called (the global scope if none).
293 * @return {number} Subscription key.
294 */
295 goog.labs.pubsub.BroadcastPubSub.prototype.subscribeOnce = function(
296 topic, fn, opt_context) {
297 return this.pubSub_.subscribeOnce(topic, fn, opt_context);
298 };
299
300
301 /**
302 * Returns the number of subscriptions to the given topic (or all topics if
303 * unspecified). This number will not change while publishing any messages.
304 * @param {string=} opt_topic The topic (all topics if unspecified).
305 * @return {number} Number of subscriptions to the topic.
306 */
307 goog.labs.pubsub.BroadcastPubSub.prototype.getCount = function(opt_topic) {
308 return this.pubSub_.getCount(opt_topic);
309 };
310
311
312 /**
313 * Clears the subscription list for a topic, or all topics if unspecified.
314 * @param {string=} opt_topic Topic to clear (all topics if unspecified).
315 */
316 goog.labs.pubsub.BroadcastPubSub.prototype.clear = function(opt_topic) {
317 this.pubSub_.clear(opt_topic);
318 };
319
320
321 /** @override */
322 goog.labs.pubsub.BroadcastPubSub.prototype.disposeInternal = function() {
323 goog.array.remove(goog.labs.pubsub.BroadcastPubSub.instances_, this);
324 if (goog.labs.pubsub.BroadcastPubSub.IS_IE8_ &&
325 goog.isDefAndNotNull(this.storage_) &&
326 goog.labs.pubsub.BroadcastPubSub.instances_.length == 0) {
327 this.storage_.remove(goog.labs.pubsub.BroadcastPubSub.IE8_EVENTS_KEY_);
328 }
329 goog.labs.pubsub.BroadcastPubSub.base(this, 'disposeInternal');
330 };
331
332
333 /**
334 * Prefix for IE8 storage event queue keys.
335 * @private @const
336 */
337 goog.labs.pubsub.BroadcastPubSub.IE8_EVENTS_KEY_PREFIX_ = '_closure_bps_ie8evt';
338
339
340 /**
341 * Time (in milliseconds) that IE8 events should live. If they are not
342 * processed by other windows in this time they will be removed.
343 * @private @const
344 */
345 goog.labs.pubsub.BroadcastPubSub.IE8_EVENT_LIFETIME_MS_ = 1000 * 10;
346
347
348 /**
349 * Time (in milliseconds) that the IE8 event queue should live.
350 * @private @const
351 */
352 goog.labs.pubsub.BroadcastPubSub.IE8_QUEUE_LIFETIME_MS_ = 1000 * 30;
353
354
355 /**
356 * Time delta that is used to distinguish between timestamps of events that
357 * happen in the same millisecond.
358 * @private @const
359 */
360 goog.labs.pubsub.BroadcastPubSub.IE8_TIMESTAMP_UNIQUE_OFFSET_MS_ = .01;
361
362
363 /**
364 * Name for this window/tab's storage key that stores its IE8 event queue.
365 *
366 * The browsers storage events are supposed to track the key which was changed,
367 * the previous value for that key, and the new value of that key. Our
368 * implementation is dependent on this information but IE8 doesn't provide it.
369 * We implement our own event queue using local storage to track this
370 * information in IE8. Since all instances share the same localStorage context
371 * in a particular tab, we share the events queue.
372 *
373 * This key is a static member shared by all instances of BroadcastPubSub in the
374 * same Window context. To avoid read-update-write contention, this key is only
375 * written in a single context in the cleanupIe8StorageEvents_ function. Since
376 * instances in other contexts will read this key there is code in the {@code
377 * publish} function to make sure timestamps are unique even within the same
378 * millisecond.
379 *
380 * @private @const {string}
381 */
382 goog.labs.pubsub.BroadcastPubSub.IE8_EVENTS_KEY_ =
383 goog.labs.pubsub.BroadcastPubSub.IE8_EVENTS_KEY_PREFIX_ +
384 goog.math.randomInt(1e9);
385
386
387 /**
388 * All instances of this object should access elements using strings and not
389 * attributes. Since we are communicating across browser tabs we could be
390 * dealing with different versions of javascript and thus may have different
391 * obfuscation in each tab.
392 * @private @typedef {{'timestamp': number, 'args': !Array<string>}}
393 */
394 goog.labs.pubsub.BroadcastPubSub.Ie8Event_;
395
396
397 /** @private @const */
398 goog.labs.pubsub.BroadcastPubSub.IS_IE8_ =
399 goog.userAgent.IE && goog.userAgent.DOCUMENT_MODE == 8;
400
401
402 /**
403 * Validates an event object.
404 * @param {!Object} obj The object to validate as an Event.
405 * @return {?goog.labs.pubsub.BroadcastPubSub.Ie8Event_} A valid
406 * event object or null if the object is invalid.
407 * @private
408 */
409 goog.labs.pubsub.BroadcastPubSub.validateIe8Event_ = function(obj) {
410 if (goog.isObject(obj) && goog.isNumber(obj['timestamp']) &&
411 goog.array.every(obj['args'], goog.isString)) {
412 return {'timestamp': obj['timestamp'], 'args': obj['args']};
413 }
414 return null;
415 };
416
417
418 /**
419 * Returns an array of valid IE8 events.
420 * @param {!Array<!Object>} events Possible IE8 events.
421 * @return {!Array<!goog.labs.pubsub.BroadcastPubSub.Ie8Event_>}
422 * Valid IE8 events.
423 * @private
424 */
425 goog.labs.pubsub.BroadcastPubSub.filterValidIe8Events_ = function(events) {
426 return goog.array.filter(
427 goog.array.map(
428 events, goog.labs.pubsub.BroadcastPubSub.validateIe8Event_),
429 goog.isDefAndNotNull);
430 };
431
432
433 /**
434 * Returns the IE8 events that have a timestamp later than the provided
435 * timestamp.
436 * @param {number} timestamp Expired timestamp.
437 * @param {!Array<!goog.labs.pubsub.BroadcastPubSub.Ie8Event_>} events
438 * Possible IE8 events.
439 * @return {!Array<!goog.labs.pubsub.BroadcastPubSub.Ie8Event_>}
440 * Unexpired IE8 events.
441 * @private
442 */
443 goog.labs.pubsub.BroadcastPubSub.filterNewIe8Events_ = function(
444 timestamp, events) {
445 return goog.array.filter(
446 events, function(event) { return event['timestamp'] > timestamp; });
447 };
448
449
450 /**
451 * Processes the events array for key if all elements are valid IE8 events.
452 * @param {string} key The key in localStorage where the event queue is stored.
453 * @param {!Array<!Object>} events Array of possible events stored at key.
454 * @return {boolean} Return true if all elements in the array are valid
455 * events, false otherwise.
456 * @private
457 */
458 goog.labs.pubsub.BroadcastPubSub.prototype.maybeProcessIe8Events_ = function(
459 key, events) {
460 if (!events.length) {
461 return false;
462 }
463
464 var validEvents =
465 goog.labs.pubsub.BroadcastPubSub.filterValidIe8Events_(events);
466 if (validEvents.length == events.length) {
467 var lastTimestamp = goog.array.peek(validEvents)['timestamp'];
468 var previousTime =
469 this.ie8LastEventTimes_[key] || this.ie8StartupTimestamp_;
470 if (lastTimestamp > previousTime -
471 goog.labs.pubsub.BroadcastPubSub.IE8_QUEUE_LIFETIME_MS_) {
472 this.ie8LastEventTimes_[key] = lastTimestamp;
473 validEvents = goog.labs.pubsub.BroadcastPubSub.filterNewIe8Events_(
474 previousTime, validEvents);
475 for (var i = 0, event; event = validEvents[i]; i++) {
476 this.dispatch_(event['args']);
477 }
478 return true;
479 }
480 } else {
481 goog.log.warning(this.logger_, 'invalid events found in queue ' + key);
482 }
483
484 return false;
485 };
486
487
488 /**
489 * Handle the storage event and possibly dispatch events. Looks through all keys
490 * in localStorage for valid keys.
491 * @private
492 */
493 goog.labs.pubsub.BroadcastPubSub.prototype.handleIe8StorageEvent_ = function() {
494 var numKeys = this.mechanism_.getCount();
495 for (var idx = 0; idx < numKeys; idx++) {
496 var key = this.mechanism_.key(idx);
497 // Don't process events we generated. The W3C standard says that storage
498 // events should be queued by the browser for each window whose document's
499 // storage object is affected by a change in localStorage. Chrome, Firefox,
500 // and modern IE don't dispatch the event to the window which made the
501 // change. This code simulates that behavior in IE8.
502 if (!(goog.isString(key) &&
503 goog.string.startsWith(
504 key, goog.labs.pubsub.BroadcastPubSub.IE8_EVENTS_KEY_PREFIX_))) {
505 continue;
506 }
507
508 var events = null;
509
510 try {
511 events = this.storage_.get(key);
512 } catch (ex) {
513 goog.log.warning(this.logger_, 'invalid remote event queue ' + key);
514 }
515
516 if (!(goog.isArray(events) && this.maybeProcessIe8Events_(key, events))) {
517 // Events is not an array, empty, contains invalid events, or expired.
518 this.storage_.remove(key);
519 }
520 }
521 };
522
523
524 /**
525 * Cleanup our IE8 event queue by removing any events that come at or before the
526 * given timestamp.
527 * @param {number} timestamp Maximum timestamp to remove from the queue.
528 * @private
529 */
530 goog.labs.pubsub.BroadcastPubSub.prototype.cleanupIe8StorageEvents_ = function(
531 timestamp) {
532 var events = null;
533
534 try {
535 events =
536 this.storage_.get(goog.labs.pubsub.BroadcastPubSub.IE8_EVENTS_KEY_);
537 } catch (ex) {
538 goog.log.error(
539 this.logger_, 'cleanup encountered invalid event queue key ' +
540 goog.labs.pubsub.BroadcastPubSub.IE8_EVENTS_KEY_);
541 }
542 if (!goog.isArray(events)) {
543 this.storage_.remove(goog.labs.pubsub.BroadcastPubSub.IE8_EVENTS_KEY_);
544 return;
545 }
546
547 events = goog.labs.pubsub.BroadcastPubSub.filterNewIe8Events_(
548 timestamp,
549 goog.labs.pubsub.BroadcastPubSub.filterValidIe8Events_(events));
550
551 if (events.length > 0) {
552 this.storage_.set(goog.labs.pubsub.BroadcastPubSub.IE8_EVENTS_KEY_, events);
553 } else {
554 this.storage_.remove(goog.labs.pubsub.BroadcastPubSub.IE8_EVENTS_KEY_);
555 }
556 };