show: make highlight legible
[debiancodesearch.git] / static / reconnecting-websocket.js
blob4a57b49f5680468c1b2ee07cede2231c0898adbb
1 // MIT License:
2 //
3 // Copyright (c) 2010-2012, Joe Walnes
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to deal
7 // in the Software without restriction, including without limitation the rights
8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 // THE SOFTWARE.
23 /**
24  * This behaves like a WebSocket in every way, except if it fails to connect,
25  * or it gets disconnected, it will repeatedly poll until it successfully connects
26  * again.
27  *
28  * It is API compatible, so when you have:
29  *   ws = new WebSocket('ws://....');
30  * you can replace with:
31  *   ws = new ReconnectingWebSocket('ws://....');
32  *
33  * The event stream will typically look like:
34  *  onconnecting
35  *  onopen
36  *  onmessage
37  *  onmessage
38  *  onclose // lost connection
39  *  onconnecting
40  *  onopen  // sometime later...
41  *  onmessage
42  *  onmessage
43  *  etc... 
44  *
45  * It is API compatible with the standard WebSocket API.
46  *
47  * Latest version: https://github.com/joewalnes/reconnecting-websocket/
48  * - Joe Walnes
49  */
50 (function (global, factory) {
51     if (typeof define === 'function' && define.amd) {
52         define([], factory);
53     } else if (typeof module !== 'undefined' && module.exports){
54         module.exports = factory();
55     } else {
56         global.ReconnectingWebSocket = factory();
57     }
58 })(this, function () {
60     function ReconnectingWebSocket(url, protocols) {
61         protocols = protocols || [];
63         // These can be altered by calling code.
64         this.debug = false;
65         this.reconnectInterval = 1000;
66         this.reconnectDecay = 1.5;
67         this.reconnectAttempts = 0;
68         this.timeoutInterval = 2000;
70         var self = this;
71         var ws;
72         var forcedClose = false;
73         var timedOut = false;
74         
75         this.url = url;
76         this.protocols = protocols;
77         this.readyState = WebSocket.CONNECTING;
78         this.URL = url; // Public API
80         this.onopen = function(event) {
81         };
83         this.onclose = function(event) {
84         };
86         this.onconnecting = function(event) {
87         };
89         this.onmessage = function(event) {
90         };
92         this.onerror = function(event) {
93         };
95         function connect(reconnectAttempt) {
96             ws = new WebSocket(self.url, protocols);
97             
98             if(!reconnectAttempt)
99                 self.onconnecting();
100                 
101             if (self.debug || ReconnectingWebSocket.debugAll) {
102                 console.debug('ReconnectingWebSocket', 'attempt-connect', url);
103             }
104             
105             var localWs = ws;
106             var timeout = setTimeout(function() {
107                 if (self.debug || ReconnectingWebSocket.debugAll) {
108                     console.debug('ReconnectingWebSocket', 'connection-timeout', url);
109                 }
110                 timedOut = true;
111                 localWs.close();
112                 timedOut = false;
113             }, self.timeoutInterval);
114             
115             ws.onopen = function(event) {
116                 clearTimeout(timeout);
117                 if (self.debug || ReconnectingWebSocket.debugAll) {
118                     console.debug('ReconnectingWebSocket', 'onopen', url);
119                 }
120                 self.readyState = WebSocket.OPEN;
121                 reconnectAttempt = false;
122                 self.reconnectAttempts = 0;
123                 self.onopen(event);
124             };
125             
126             ws.onclose = function(event) {
127                 clearTimeout(timeout);
128                 ws = null;
129                 if (forcedClose) {
130                     self.readyState = WebSocket.CLOSED;
131                     self.onclose(event);
132                 } else {
133                     self.readyState = WebSocket.CONNECTING;
134                     self.onconnecting();
135                     if (!reconnectAttempt && !timedOut) {
136                         if (self.debug || ReconnectingWebSocket.debugAll) {
137                             console.debug('ReconnectingWebSocket', 'onclose', url);
138                         }
139                         self.onclose(event);
140                     }
141                     setTimeout(function() {
142                         self.reconnectAttempts++;
143                         connect(true);
144                     }, self.reconnectInterval * Math.pow(self.reconnectDecay, self.reconnectAttempts));
145                 }
146             };
147             ws.onmessage = function(event) {
148                 if (self.debug || ReconnectingWebSocket.debugAll) {
149                     console.debug('ReconnectingWebSocket', 'onmessage', url, event.data);
150                 }
151                 self.onmessage(event);
152             };
153             ws.onerror = function(event) {
154                 if (self.debug || ReconnectingWebSocket.debugAll) {
155                     console.debug('ReconnectingWebSocket', 'onerror', url, event);
156                 }
157                 self.onerror(event);
158             };
159         }
160         connect(false);
162         this.send = function(data) {
163             if (ws) {
164                 if (self.debug || ReconnectingWebSocket.debugAll) {
165                     console.debug('ReconnectingWebSocket', 'send', url, data);
166                 }
167                 return ws.send(data);
168             } else {
169                 throw 'INVALID_STATE_ERR : Pausing to reconnect websocket';
170             }
171         };
173         this.close = function() {
174             forcedClose = true;
175             if (ws) {
176                 ws.close();
177             }
178         };
180         /**
181          * Additional public API method to refresh the connection if still open (close, re-open).
182          * For example, if the app suspects bad data / missed heart beats, it can try to refresh.
183          */
184         this.refresh = function() {
185             if (ws) {
186                 ws.close();
187             }
188         };
189     }
191     /**
192      * Setting this to true is the equivalent of setting all instances of ReconnectingWebSocket.debug to true.
193      */
194     ReconnectingWebSocket.debugAll = false;
196     return ReconnectingWebSocket;