1 /* -----------------------------------------------------------------------
2 * Copyright (C) 2014 Equinox Software, Inc.
3 * Bill Erickson <berick@esilibrary.com>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * ----------------------------------------------------------------------- */
18 * Shared WebSocket communication layer. Each browser tab registers with
19 * this code all inbound / outbound messages are delivered through a
20 * single websocket connection managed within.
22 * Messages take the form : {action : my_action, message : my_message}
23 * actions for tab-generated messages may be "message" or "close".
24 * actions for messages generated within may be "message" or "error"
27 var WEBSOCKET_URL_PATH = '/osrf-websocket-translator';
28 var WEBSOCKET_PORT_SSL = @WS_PORT@;
29 var WEBSOCKET_MAX_THREAD_PORT_CACHE_SIZE = 1000;
32 * Collection of shared ports (browser tabs)
34 var connected_ports = {};
37 * Each port gets a local identifier so we have an easy way to refer to
40 var port_identifier = 0;
42 // maps osrf message threads to a port index in connected_ports.
43 // this is how we know which browser tab to deliver messages to.
44 var thread_port_map = {};
47 * Browser-global, shared websocket connection.
52 * Pending messages awaiting a successful websocket connection
54 * instead of asking the caller to pass messages after a connection
55 * is made, queue the messages for the caller and deliver them
56 * after the connection is established.
58 var pending_ws_messages = [];
61 * Deliver the message blob to the specified port (tab)
63 function send_msg_to_port(ident, msg) {
64 console.debug('sending msg to port ' + ident + ' : ' + msg.action);
66 connected_ports[ident].postMessage(msg);
68 // some browsers (Opera) throw an exception when messaging
69 // a disconnected port.
70 console.debug('unable to send msg to port ' + ident);
71 delete connected_ports[ident];
76 * Send a message blob to all ports (tabs)
78 function broadcast(msg) {
79 for (var ident in connected_ports)
80 send_msg_to_port(ident, msg);
85 * Opens the websocket connection.
87 * If our global socket is already open, use it. Otherwise, queue the
88 * message for delivery after the socket is open.
90 function send_to_websocket(message) {
92 if (websocket && websocket.readyState == websocket.OPEN) {
93 // websocket connection is viable. send our message now.
94 websocket.send(message);
98 // no viable connection. queue our outbound messages for future delivery.
99 pending_ws_messages.push(message);
101 if (websocket && websocket.readyState == websocket.CONNECTING) {
102 // we are already in the middle of a setup call.
103 // our queued message will be delivered after setup completes.
107 // we have no websocket or an invalid websocket. build a new one.
109 // assume SSL at all times
110 var path = 'wss://' + location.host + ':' +
111 WEBSOCKET_PORT_SSL + WEBSOCKET_URL_PATH;
113 console.debug('connecting websocket to ' + path);
116 websocket = new WebSocket(path);
118 console.log('Error creating WebSocket for path ' + path + ' : ' + E);
122 websocket.onopen = function() {
123 console.debug('websocket.onopen()');
124 // deliver any queued messages
126 while ( (msg = pending_ws_messages.shift()) )
131 websocket.onmessage = function(evt) {
132 var message = evt.data;
134 // this is sort of a hack to avoid having to run JSON2js
135 // multiple times on the same message. Hopefully match() is
136 // faster. Note: We can't use JSON_v1 within a shared worker
137 // for marshalling messages, because it has no knowledge of
138 // application-level class hints in this environment.
140 var match = message.match(/"thread":"(.*?)"/);
141 if (!match || !(thread = match[1])) {
142 throw new Error("Websocket message malformed; no thread: " + message);
145 console.debug('websocket received message for thread ' + thread);
147 var port_msg = {action: 'message', message : message};
148 var port_ident = thread_port_map[thread];
151 send_msg_to_port(port_ident, port_msg);
153 // don't know who it's for, broadcast and let the ports
154 // sort it out for themselves.
158 /* poor man's memory management. We are not cleaning up our
159 * thread_port_map as we go, because that would require parsing
160 * and analyzing every message to look for opensrf statuses.
161 * parsing messages adds overhead (see also above comments about
162 * JSON_v1.js). So, instead, after the map has reached a certain
163 * size, clear it. If any pending messages are afield that depend
164 * on the map, they will be broadcast to all ports on arrival
165 * (see above). Only the port expecting a message with the given
166 * thread will honor the message, all other ports will drop it
167 * silently. We could just broadcastfor every messsage, but this
168 * is presumably more efficient.
170 * If for some reason this fails to work as expected, we could add
171 * a new tab->ws message type for marking a thread as complete.
172 * My hunch is this will be faster, since it will require a lot
173 * fewer cross-tab messages overall.
175 if (Object.keys(thread_port_map).length >
176 WEBSOCKET_MAX_THREAD_PORT_CACHE_SIZE) {
177 console.debug('resetting thread_port_map');
178 thread_port_map = {};
183 * Websocket error handler. This type of error indicates a probelem
184 * with the connection. I.e. it's not port-specific.
185 * Broadcast to all ports.
187 websocket.onerror = function(evt) {
188 var err = "WebSocket Error " + evt;
190 broadcast({action : 'event', type : 'onerror', message : err});
191 websocket.close(); // connection is no good; reset.
195 * Called when the websocket connection is closed.
197 * Once a websocket is closed, it will be re-opened the next time
198 * a message delivery attempt is made. Clean up and prepare to reconnect.
200 websocket.onclose = function() {
201 console.debug('closing websocket');
203 thread_port_map = {};
204 broadcast({action : 'event', type : 'onclose'});
209 * New port (tab) opened handler
211 * Apply the port identifier and message handlers.
213 onconnect = function(e) {
214 var port = e.ports[0];
216 // we have no way of identifying ports within the message handler,
217 // so we apply an identifier to each and toss that into a closer.
218 var port_ident = port_identifier++;
219 connected_ports[port_ident] = port;
222 port.addEventListener('message', function(e) {
225 if (data.action == 'message') {
226 thread_port_map[data.thread] = port_ident;
227 send_to_websocket(data.message);
231 if (messsage.action == 'close') {
232 // TODO: all browser tabs need an onunload handler which sends
233 // a action=close message, so that the port may be removed from
234 // the conected_ports collection.
235 delete connected_ports[port_ident];
236 console.debug('closed port ' + port_ident +
237 '; ' + Object.keys(connected_ports).length + ' remaining');
245 console.debug('added port ' + port_ident +
246 '; ' + Object.keys(connected_ports).length + ' total');