bufferedchannel.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. // Copyright 2010 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. * @fileoverview A wrapper for asynchronous message-passing channels that buffer
  16. * their output until both ends of the channel are connected.
  17. *
  18. */
  19. goog.provide('goog.messaging.BufferedChannel');
  20. goog.require('goog.Disposable');
  21. goog.require('goog.Timer');
  22. goog.require('goog.events');
  23. goog.require('goog.log');
  24. goog.require('goog.messaging.MessageChannel');
  25. goog.require('goog.messaging.MultiChannel');
  26. /**
  27. * Creates a new BufferedChannel, which operates like its underlying channel
  28. * except that it buffers calls to send until it receives a message from its
  29. * peer claiming that the peer is ready to receive. The peer is also expected
  30. * to be a BufferedChannel, though this is not enforced.
  31. *
  32. * @param {!goog.messaging.MessageChannel} messageChannel The MessageChannel
  33. * we're wrapping.
  34. * @param {number=} opt_interval Polling interval for sending ready
  35. * notifications to peer, in ms. Default is 50.
  36. * @constructor
  37. * @extends {goog.Disposable}
  38. * @implements {goog.messaging.MessageChannel};
  39. * @final
  40. */
  41. goog.messaging.BufferedChannel = function(messageChannel, opt_interval) {
  42. goog.Disposable.call(this);
  43. /**
  44. * Buffer of messages to be sent when the channel's peer is ready.
  45. *
  46. * @type {Array<Object>}
  47. * @private
  48. */
  49. this.buffer_ = [];
  50. /**
  51. * Channel dispatcher wrapping the underlying delegate channel.
  52. *
  53. * @type {!goog.messaging.MultiChannel}
  54. * @private
  55. */
  56. this.multiChannel_ = new goog.messaging.MultiChannel(messageChannel);
  57. /**
  58. * Virtual channel for carrying the user's messages.
  59. *
  60. * @type {!goog.messaging.MessageChannel}
  61. * @private
  62. */
  63. this.userChannel_ = this.multiChannel_.createVirtualChannel(
  64. goog.messaging.BufferedChannel.USER_CHANNEL_NAME_);
  65. /**
  66. * Virtual channel for carrying control messages for BufferedChannel.
  67. *
  68. * @type {!goog.messaging.MessageChannel}
  69. * @private
  70. */
  71. this.controlChannel_ = this.multiChannel_.createVirtualChannel(
  72. goog.messaging.BufferedChannel.CONTROL_CHANNEL_NAME_);
  73. /**
  74. * Timer for the peer ready ping loop.
  75. *
  76. * @type {goog.Timer}
  77. * @private
  78. */
  79. this.timer_ = new goog.Timer(
  80. opt_interval || goog.messaging.BufferedChannel.DEFAULT_INTERVAL_MILLIS_);
  81. this.timer_.start();
  82. goog.events.listen(
  83. this.timer_, goog.Timer.TICK, this.sendReadyPing_, false, this);
  84. this.controlChannel_.registerService(
  85. goog.messaging.BufferedChannel.PEER_READY_SERVICE_NAME_,
  86. goog.bind(this.setPeerReady_, this));
  87. };
  88. goog.inherits(goog.messaging.BufferedChannel, goog.Disposable);
  89. /**
  90. * Default polling interval (in ms) for setPeerReady_ notifications.
  91. *
  92. * @type {number}
  93. * @const
  94. * @private
  95. */
  96. goog.messaging.BufferedChannel.DEFAULT_INTERVAL_MILLIS_ = 50;
  97. /**
  98. * The name of the private service which handles peer ready pings. The
  99. * service registered with this name is bound to this.setPeerReady_, an internal
  100. * part of BufferedChannel's implementation that clients should not send to
  101. * directly.
  102. *
  103. * @type {string}
  104. * @const
  105. * @private
  106. */
  107. goog.messaging.BufferedChannel.PEER_READY_SERVICE_NAME_ = 'setPeerReady_';
  108. /**
  109. * The name of the virtual channel along which user messages are sent.
  110. *
  111. * @type {string}
  112. * @const
  113. * @private
  114. */
  115. goog.messaging.BufferedChannel.USER_CHANNEL_NAME_ = 'user';
  116. /**
  117. * The name of the virtual channel along which internal control messages are
  118. * sent.
  119. *
  120. * @type {string}
  121. * @const
  122. * @private
  123. */
  124. goog.messaging.BufferedChannel.CONTROL_CHANNEL_NAME_ = 'control';
  125. /** @override */
  126. goog.messaging.BufferedChannel.prototype.connect = function(opt_connectCb) {
  127. if (opt_connectCb) {
  128. opt_connectCb();
  129. }
  130. };
  131. /** @override */
  132. goog.messaging.BufferedChannel.prototype.isConnected = function() {
  133. return true;
  134. };
  135. /**
  136. * @return {boolean} Whether the channel's peer is ready.
  137. */
  138. goog.messaging.BufferedChannel.prototype.isPeerReady = function() {
  139. return this.peerReady_;
  140. };
  141. /**
  142. * Logger.
  143. *
  144. * @type {goog.log.Logger}
  145. * @const
  146. * @private
  147. */
  148. goog.messaging.BufferedChannel.prototype.logger_ =
  149. goog.log.getLogger('goog.messaging.bufferedchannel');
  150. /**
  151. * Handles one tick of our peer ready notification loop. This entails sending a
  152. * ready ping to the peer and shutting down the loop if we've received a ping
  153. * ourselves.
  154. *
  155. * @private
  156. */
  157. goog.messaging.BufferedChannel.prototype.sendReadyPing_ = function() {
  158. try {
  159. this.controlChannel_.send(
  160. goog.messaging.BufferedChannel.PEER_READY_SERVICE_NAME_,
  161. /* payload */ this.isPeerReady() ? '1' : '');
  162. } catch (e) {
  163. this.timer_.stop(); // So we don't keep calling send and re-throwing.
  164. throw e;
  165. }
  166. };
  167. /**
  168. * Whether or not the peer channel is ready to receive messages.
  169. *
  170. * @type {boolean}
  171. * @private
  172. */
  173. goog.messaging.BufferedChannel.prototype.peerReady_;
  174. /** @override */
  175. goog.messaging.BufferedChannel.prototype.registerService = function(
  176. serviceName, callback, opt_objectPayload) {
  177. this.userChannel_.registerService(serviceName, callback, opt_objectPayload);
  178. };
  179. /** @override */
  180. goog.messaging.BufferedChannel.prototype.registerDefaultService = function(
  181. callback) {
  182. this.userChannel_.registerDefaultService(callback);
  183. };
  184. /**
  185. * Send a message over the channel. If the peer is not ready, the message will
  186. * be buffered and sent once we've received a ready message from our peer.
  187. *
  188. * @param {string} serviceName The name of the service this message should be
  189. * delivered to.
  190. * @param {string|!Object} payload The value of the message. If this is an
  191. * Object, it is serialized to JSON before sending. It's the responsibility
  192. * of implementors of this class to perform the serialization.
  193. * @see goog.net.xpc.BufferedChannel.send
  194. * @override
  195. */
  196. goog.messaging.BufferedChannel.prototype.send = function(serviceName, payload) {
  197. if (this.isPeerReady()) {
  198. this.userChannel_.send(serviceName, payload);
  199. } else {
  200. goog.log.fine(
  201. goog.messaging.BufferedChannel.prototype.logger_,
  202. 'buffering message ' + serviceName);
  203. this.buffer_.push({serviceName: serviceName, payload: payload});
  204. }
  205. };
  206. /**
  207. * Marks the channel's peer as ready, then sends buffered messages and nulls the
  208. * buffer. Subsequent calls to setPeerReady_ have no effect.
  209. *
  210. * @param {(!Object|string)} peerKnowsWeKnowItsReady Passed by the peer to
  211. * indicate whether it knows that we've received its ping and that it's
  212. * ready. Non-empty if true, empty if false.
  213. * @private
  214. */
  215. goog.messaging.BufferedChannel.prototype.setPeerReady_ = function(
  216. peerKnowsWeKnowItsReady) {
  217. if (peerKnowsWeKnowItsReady) {
  218. this.timer_.stop();
  219. } else {
  220. // Our peer doesn't know we're ready, so restart (or continue) pinging.
  221. // Restarting may be needed if the peer iframe was reloaded after the
  222. // connection was first established.
  223. this.timer_.start();
  224. }
  225. if (this.peerReady_) {
  226. return;
  227. }
  228. this.peerReady_ = true;
  229. // Send one last ping so that the peer knows we know it's ready.
  230. this.sendReadyPing_();
  231. for (var i = 0; i < this.buffer_.length; i++) {
  232. var message = this.buffer_[i];
  233. goog.log.fine(
  234. goog.messaging.BufferedChannel.prototype.logger_,
  235. 'sending buffered message ' + message.serviceName);
  236. this.userChannel_.send(message.serviceName, message.payload);
  237. }
  238. this.buffer_ = null;
  239. };
  240. /** @override */
  241. goog.messaging.BufferedChannel.prototype.disposeInternal = function() {
  242. goog.dispose(this.multiChannel_);
  243. goog.dispose(this.timer_);
  244. goog.messaging.BufferedChannel.base(this, 'disposeInternal');
  245. };