]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/javascript/opensrf.js
LP#1268619: websockets: auto-upgrade to shared workers; SSL-always
[OpenSRF.git] / src / javascript / opensrf.js
1 /* -----------------------------------------------------------------------
2  * Copyright (C) 2008  Georgia Public Library Service
3  * Bill Erickson <erickson@esilibrary.com>
4  *  
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.
9  * 
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  * ----------------------------------------------------------------------- */
15
16 /* session states */
17 var OSRF_APP_SESSION_CONNECTED = 0;
18 var OSRF_APP_SESSION_CONNECTING = 1;
19 var OSRF_APP_SESSION_DISCONNECTED = 2;
20
21 /* types of transport layers */
22 var OSRF_TRANSPORT_TYPE_XHR = 1;
23 var OSRF_TRANSPORT_TYPE_XMPP = 2;
24 var OSRF_TRANSPORT_TYPE_WS = 3;
25 var OSRF_TRANSPORT_TYPE_WS_SHARED = 4;
26
27 /* message types */
28 var OSRF_MESSAGE_TYPE_REQUEST = 'REQUEST';
29 var OSRF_MESSAGE_TYPE_STATUS = 'STATUS';
30 var OSRF_MESSAGE_TYPE_RESULT = 'RESULT';
31 var OSRF_MESSAGE_TYPE_CONNECT = 'CONNECT';
32 var OSRF_MESSAGE_TYPE_DISCONNECT = 'DISCONNECT';
33
34 /* message statuses */
35 var OSRF_STATUS_CONTINUE = 100;
36 var OSRF_STATUS_OK = 200;
37 var OSRF_STATUS_ACCEPTED = 202;
38 var OSRF_STATUS_COMPLETE = 205;
39 var OSRF_STATUS_REDIRECTED = 307;
40 var OSRF_STATUS_BADREQUEST = 400;
41 var OSRF_STATUS_UNAUTHORIZED = 401;
42 var OSRF_STATUS_FORBIDDEN = 403;
43 var OSRF_STATUS_NOTFOUND = 404;
44 var OSRF_STATUS_NOTALLOWED = 405;
45 var OSRF_STATUS_TIMEOUT = 408;
46 var OSRF_STATUS_EXPFAILED = 417;
47 var OSRF_STATUS_INTERNALSERVERERROR = 500;
48 var OSRF_STATUS_NOTIMPLEMENTED = 501;
49 var OSRF_STATUS_VERSIONNOTSUPPORTED = 505;
50
51 // TODO: get path from ./configure prefix
52 var SHARED_WORKER_LIB = '/js/dojo/opensrf/opensrf_ws_shared.js'; 
53
54 /* The following classes map directly to network-serializable opensrf objects */
55
56 function osrfMessage(hash) {
57     this.hash = hash;
58     if(!this.hash.locale)
59         this.hash.locale = OpenSRF.locale || 'en-US';
60     this._encodehash = true;
61 }
62 osrfMessage.prototype.threadTrace = function(d) { 
63     if(arguments.length == 1) 
64         this.hash.threadTrace = d; 
65     return this.hash.threadTrace; 
66 };
67 osrfMessage.prototype.type = function(d) { 
68     if(arguments.length == 1) 
69         this.hash.type = d; 
70     return this.hash.type; 
71 };
72 osrfMessage.prototype.payload = function(d) { 
73     if(arguments.length == 1) 
74         this.hash.payload = d; 
75     return this.hash.payload; 
76 };
77 osrfMessage.prototype.locale = function(d) { 
78     if(arguments.length == 1) 
79         this.hash.locale = d; 
80     return this.hash.locale; 
81 };
82 osrfMessage.prototype.api_level = function(d) { 
83     if(arguments.length == 1) 
84         this.hash.api_level = d; 
85     return this.hash.api_level; 
86 };
87 osrfMessage.prototype.serialize = function() {
88     return {
89         "__c":"osrfMessage",
90         "__p": {
91             'threadTrace' : this.hash.threadTrace,
92             'type' : this.hash.type,
93             'payload' : (this.hash.payload) ? this.hash.payload.serialize() : 'null',
94             'locale' : this.hash.locale,
95             'api_level' : this.hash.api_level
96         }
97     };
98 };
99
100 function osrfMethod(hash) {
101     this.hash = hash;
102     this._encodehash = true;
103 }
104 osrfMethod.prototype.method = function(d) {
105     if(arguments.length == 1) 
106         this.hash.method = d; 
107     return this.hash.method; 
108 };
109 osrfMethod.prototype.params = function(d) {
110     if(arguments.length == 1) 
111         this.hash.params = d; 
112     return this.hash.params; 
113 };
114 osrfMethod.prototype.serialize = function() {
115     return {
116         "__c":"osrfMethod",
117         "__p": {
118             'method' : this.hash.method,
119             'params' : this.hash.params
120         }
121     };
122 };
123
124 function osrfMethodException(hash) {
125     this.hash = hash;
126     this._encodehash = true;
127 }
128 osrfMethodException.prototype.status = function(d) {
129     if(arguments.length == 1) 
130         this.hash.status = d; 
131     return this.hash.status; 
132 };
133 osrfMethodException.prototype.statusCode = function(d) {
134     if(arguments.length == 1) 
135         this.hash.statusCode = d; 
136     return this.hash.statusCode; 
137 };
138 function osrfConnectStatus(hash) { 
139     this.hash = hash;
140     this._encodehash = true;
141 }
142 osrfConnectStatus.prototype.status = function(d) {
143     if(arguments.length == 1) 
144         this.hash.status = d; 
145     return this.hash.status; 
146 };
147 osrfConnectStatus.prototype.statusCode = function(d) {
148     if(arguments.length == 1) 
149         this.hash.statusCode = d; 
150     return this.hash.statusCode; 
151 };
152 function osrfResult(hash) {
153     this.hash = hash;
154     this._encodehash = true;
155 }
156 osrfResult.prototype.status = function(d) {
157     if(arguments.length == 1) 
158         this.hash.status = d; 
159     return this.hash.status; 
160 };
161 osrfResult.prototype.statusCode = function(d) {
162     if(arguments.length == 1) 
163         this.hash.statusCode = d; 
164     return this.hash.statusCode; 
165 };
166 osrfResult.prototype.content = function(d) {
167     if(arguments.length == 1) 
168         this.hash.content = d; 
169     return this.hash.content; 
170 };
171 function osrfServerError(hash) { 
172     this.hash = hash;
173     this._encodehash = true;
174 }
175 osrfServerError.prototype.status = function(d) {
176     if(arguments.length == 1) 
177         this.hash.status = d; 
178     return this.hash.status; 
179 };
180 osrfServerError.prototype.statusCode = function(d) {
181     if(arguments.length == 1) 
182         this.hash.statusCode = d; 
183     return this.hash.statusCode; 
184 };
185 function osrfContinueStatus(hash) { 
186     this.hash = hash;
187     this._encodehash = true;
188 }
189 osrfContinueStatus.prototype.status = function(d) {
190     if(arguments.length == 1) 
191         this.hash.status = d; 
192     return this.hash.status; 
193 };
194 osrfContinueStatus.prototype.statusCode = function(d) {
195     if(arguments.length == 1) 
196         this.hash.statusCode = d; 
197     return this.hash.statusCode; 
198 };
199
200 OpenSRF = {};
201 OpenSRF.locale = null;
202 OpenSRF.api_level = 1;
203
204 /* makes cls a subclass of pcls */
205 OpenSRF.set_subclass = function(cls, pcls) {
206     var str = cls+'.prototype = new '+pcls+'();';
207     str += cls+'.prototype.constructor = '+cls+';';
208     str += cls+'.baseClass = '+pcls+'.prototype.constructor;';
209     str += cls+'.prototype["super"] = '+pcls+'.prototype;';
210     eval(str);
211 };
212
213
214 /* general session superclass */
215 OpenSRF.Session = function() {
216     this.remote_id = null;
217     this.state = OSRF_APP_SESSION_DISCONNECTED;
218 };
219
220 OpenSRF.Session.transport = OSRF_TRANSPORT_TYPE_XHR;
221 OpenSRF.Session.cache = {};
222
223 OpenSRF.Session.find_session = function(thread_trace) {
224     return OpenSRF.Session.cache[thread_trace];
225 };
226 OpenSRF.Session.prototype.cleanup = function() {
227     delete OpenSRF.Session.cache[this.thread];
228 };
229
230 OpenSRF.Session.prototype.send = function(osrf_msg, args) {
231     args = (args) ? args : {};
232     switch(OpenSRF.Session.transport) {
233         case OSRF_TRANSPORT_TYPE_WS:
234             return this.send_ws(osrf_msg);
235         case OSRF_TRANSPORT_TYPE_WS_SHARED:
236             return this.send_ws_shared(osrf_msg);
237         case OSRF_TRANSPORT_TYPE_XHR:
238             return this.send_xhr(osrf_msg, args);
239         case OSRF_TRANSPORT_TYPE_XMPP:
240             return this.send_xmpp(osrf_msg, args);
241     }
242 };
243
244 OpenSRF.Session.prototype.send_xhr = function(osrf_msg, args) {
245     args.thread = this.thread;
246     args.rcpt = this.remote_id;
247     args.rcpt_service = this.service;
248     new OpenSRF.XHRequest(osrf_msg, args).send();
249 };
250
251 OpenSRF.Session.prototype.send_ws = function(osrf_msg) {
252
253     if (typeof SharedWorker == 'function') {
254         // vanilla websockets requested, but this browser supports
255         // shared workers, so use those instead.
256         return this.send_ws_shared(osrf_msg);
257     }
258
259     // otherwise, use a per-tab connection
260
261     if (!OpenSRF.websocketConnection) {
262         this.setup_single_ws();
263     }
264
265     var json = js2JSON({
266         service : this.service,
267         thread : this.thread,
268         osrf_msg : [message.serialize()]
269     });
270
271     OpenSRF.websocketConnection.send(json);
272 };
273
274 OpenSRF.Session.prototype.setup_single_ws = function() {
275     OpenSRF.websocketConnection = new OpenSRF.WebSocket();
276
277     OpenSRF.websocketConnection.onmessage = function(msg) {
278         try {
279             var msg = JSON2js(msg);
280         } catch(E) {
281             console.error(
282                 "Error parsing JSON in shared WS response: " + msg);
283             throw E;
284         }
285         OpenSRF.Stack.push(                                                        
286             new OpenSRF.NetMessage(                                                
287                null, null, msg.thread, null, msg.osrf_msg)                        
288         ); 
289
290         return;
291     }
292 }
293
294 OpenSRF.Session.setup_shared_ws = function() {
295     OpenSRF.Session.transport = OSRF_TRANSPORT_TYPE_WS_SHARED;
296
297     OpenSRF.sharedWSWorker = new SharedWorker(SHARED_WORKER_LIB);
298
299     OpenSRF.sharedWSWorker.port.addEventListener('message', function(e) {                          
300         var data = e.data;
301         console.debug('sharedWSWorker received message of type: ' + data.action);
302
303         if (data.action == 'message') {
304             // pass all inbound message up the opensrf stack
305
306             var msg;
307             try {
308                 msg = JSON2js(data.message);
309             } catch(E) {
310                 console.error(
311                     "Error parsing JSON in shared WS response: " + msg);
312                 throw E;
313             }
314             OpenSRF.Stack.push(                                                        
315                 new OpenSRF.NetMessage(                                                
316                    null, null, msg.thread, null, msg.osrf_msg)                        
317             ); 
318
319             return;
320         }
321
322         if (data.action == 'error') {
323             throw new Error(data.message);
324         }
325     });
326
327     OpenSRF.sharedWSWorker.port.start();   
328 }
329
330 OpenSRF.Session.prototype.send_ws_shared = function(message) {
331
332     if (!OpenSRF.sharedWSWorker) 
333         OpenSRF.Session.setup_shared_ws();
334
335     var json = js2JSON({
336         service : this.service,
337         thread : this.thread,
338         osrf_msg : [message.serialize()]
339     });
340
341     OpenSRF.sharedWSWorker.port.postMessage({
342         action : 'message', 
343         // pass the thread additionally as a stand-alone value so the
344         // worker can more efficiently inspect it.
345         thread : this.thread,
346         message : json
347     });
348 }
349
350
351 OpenSRF.Session.prototype.send_xmpp = function(osrf_msg, args) {
352     alert('xmpp transport not implemented');
353 };
354
355
356 /* client sessions make requests */
357 OpenSRF.ClientSession = function(service) {
358     this.service = service;
359     this.remote_id = null;
360     this.locale = OpenSRF.locale || 'en-US';
361     this.last_id = 0;
362     this.requests = [];
363     this.onconnect = null;
364     this.thread = Math.random() + '' + new Date().getTime();
365     OpenSRF.Session.cache[this.thread] = this;
366 };
367 OpenSRF.set_subclass('OpenSRF.ClientSession', 'OpenSRF.Session');
368
369
370 OpenSRF.ClientSession.prototype.connect = function(args) {
371     args = (args) ? args : {};
372     this.remote_id = null;
373
374     if (this.state == OSRF_APP_SESSION_CONNECTED) {
375         if (args.onconnect) args.onconnect();
376         return true;
377     }
378
379     if(args.onconnect) {
380         this.onconnect = args.onconnect;
381
382     } else {
383         /* if no handler is provided, make this a synchronous call */
384         this.timeout = (args.timeout) ? args.timeout : 5;
385     }
386
387     message = new osrfMessage({
388         'threadTrace' : this.last_id++, 
389         'type' : OSRF_MESSAGE_TYPE_CONNECT
390     });
391
392     this.send(message, {'timeout' : this.timeout});
393
394     if(this.onconnect || this.state == OSRF_APP_SESSION_CONNECTED)
395         return true;
396
397     return false;
398 };
399
400 OpenSRF.ClientSession.prototype.disconnect = function(args) {
401
402     if (this.state == OSRF_APP_SESSION_CONNECTED) {
403         this.send(
404             new osrfMessage({
405                 'threadTrace' : this.last_id++,
406                 'type' : OSRF_MESSAGE_TYPE_DISCONNECT
407             })
408         );
409     }
410
411     this.remote_id = null;
412     this.state = OSRF_APP_SESSION_DISCONNECTED;
413 };
414
415
416 OpenSRF.ClientSession.prototype.request = function(args) {
417     
418     if(this.state != OSRF_APP_SESSION_CONNECTED)
419         this.remote_id = null;
420         
421     if(typeof args == 'string') { 
422         params = [];
423         for(var i = 1; i < arguments.length; i++)
424             params.push(arguments[i]);
425
426         args = {
427             method : args, 
428             params : params
429         };
430     } else {
431         if(typeof args == 'undefined')
432             args = {};
433     }
434
435     var req = new OpenSRF.Request(this, this.last_id++, args);
436     this.requests.push(req);
437     return req;
438 };
439
440 OpenSRF.ClientSession.prototype.find_request = function(reqid) {
441     for(var i = 0; i < this.requests.length; i++) {
442         var req = this.requests[i];
443         if(req.reqid == reqid)
444             return req;
445     }
446     return null;
447 };
448
449 OpenSRF.Request = function(session, reqid, args) {
450     this.session = session;
451     this.reqid = reqid;
452
453     /* callbacks */
454     this.onresponse = args.onresponse;
455     this.oncomplete = args.oncomplete;
456     this.onerror = args.onerror;
457     this.onmethoderror = args.onmethoderror;
458     this.ontransporterror = args.ontransporterror;
459
460     this.method = args.method;
461     this.params = args.params;
462     this.timeout = args.timeout;
463     this.api_level = args.api_level || OpenSRF.api_level;
464     this.response_queue = [];
465     this.complete = false;
466 };
467
468 OpenSRF.Request.prototype.peek_last = function(timeout) {
469     if(this.response_queue.length > 0) {
470         var x = this.response_queue.pop();
471         this.response_queue.push(x);
472         return x;
473     }
474     return null;
475 };
476
477 OpenSRF.Request.prototype.peek = function(timeout) {
478     if(this.response_queue.length > 0)
479         return this.response_queue[0];
480     return null;
481 };
482
483 OpenSRF.Request.prototype.recv = function(timeout) {
484     if(this.response_queue.length > 0)
485         return this.response_queue.shift();
486     return null;
487 };
488
489 OpenSRF.Request.prototype.send = function() {
490     method = new osrfMethod({'method':this.method, 'params':this.params});
491     message = new osrfMessage({
492         'threadTrace' : this.reqid, 
493         'type' : OSRF_MESSAGE_TYPE_REQUEST, 
494         'payload' : method, 
495         'locale' : this.session.locale,
496         'api_level' : this.api_level
497     });
498
499     this.session.send(message, {
500         'timeout' : this.timeout,
501         'onresponse' : this.onresponse,
502         'oncomplete' : this.oncomplete,
503         'onerror' : this.onerror,
504         'onmethoderror' : this.onmethoderror,
505         'ontransporterror' : this.ontransporterror
506     });
507 };
508
509 OpenSRF.NetMessage = function(to, from, thread, body, osrf_msg) {
510     this.to = to;
511     this.from = from;
512     this.thread = thread;
513     this.body = body;
514     this.osrf_msg = osrf_msg;
515 };
516
517 OpenSRF.Stack = function() {
518 };
519
520 // global inbound message queue
521 OpenSRF.Stack.queue = [];
522
523 // XXX testing
524 function log(msg) {
525     try {
526         dump(msg + '\n'); // xulrunner
527     } catch(E) {
528         console.log(msg);
529     }
530 }
531
532 // ses may be passed to us by the network handler
533 OpenSRF.Stack.push = function(net_msg, callbacks) {
534     var ses = OpenSRF.Session.find_session(net_msg.thread); 
535     if (!ses) return;
536     ses.remote_id = net_msg.from;
537
538     // NetMessage's from websocket connections are parsed before they get here
539     osrf_msgs = net_msg.osrf_msg;
540
541     if (!osrf_msgs) {
542
543         try {
544             osrf_msgs = JSON2js(net_msg.body);
545
546             // TODO: pretty sure we don't need this..
547             if (OpenSRF.Session.transport == OSRF_TRANSPORT_TYPE_WS) {
548                 // WebSocketRequests wrap the content
549                 osrf_msgs = osrf_msgs.osrf_msg;
550             }
551
552         } catch(E) {
553             log('Error parsing OpenSRF message body as JSON: ' + net_msg.body + '\n' + E);
554
555             /** UGH
556               * For unknown reasons, the Content-Type header will occasionally
557               * be included in the XHR.responseText for multipart/mixed messages.
558               * When this happens, strip the header and newlines from the message
559               * body and re-parse.
560               */
561             net_msg.body = net_msg.body.replace(/^.*\n\n/, '');
562             log('Cleaning up and retrying...');
563
564             try {
565                 osrf_msgs = JSON2js(net_msg.body);
566             } catch(E2) {
567                 log('Unable to clean up message, giving up: ' + net_msg.body);
568                 return;
569             }
570         }
571     }
572
573     // push the latest responses onto the end of the inbound message queue
574     for(var i = 0; i < osrf_msgs.length; i++)
575         OpenSRF.Stack.queue.push({msg : osrf_msgs[i], ses : ses});
576
577     // continue processing responses, oldest to newest
578     while(OpenSRF.Stack.queue.length) {
579         var data = OpenSRF.Stack.queue.shift();
580         OpenSRF.Stack.handle_message(data.ses, data.msg);
581     }
582 };
583
584 OpenSRF.Stack.handle_message = function(ses, osrf_msg) {
585     
586     var req = ses.find_request(osrf_msg.threadTrace());
587
588     if(osrf_msg.type() == OSRF_MESSAGE_TYPE_STATUS) {
589
590         var payload = osrf_msg.payload();
591         var status = payload.statusCode();
592         var status_text = payload.status();
593
594         if(status == OSRF_STATUS_COMPLETE) {
595             if(req) {
596                 req.complete = true;
597                 if(req.oncomplete && !req.oncomplete_called) {
598                     req.oncomplete_called = true;
599                     return req.oncomplete(req);
600                 }
601             }
602         }
603
604         if(status == OSRF_STATUS_OK) {
605             ses.state = OSRF_APP_SESSION_CONNECTED;
606
607             /* call the connect callback */
608             if(ses.onconnect && !ses.onconnect_called) {
609                 ses.onconnect_called = true;
610                 return ses.onconnect();
611             }
612         }
613
614         if(status == OSRF_STATUS_NOTFOUND || status == OSRF_STATUS_INTERNALSERVERERROR) {
615             if(req && req.onmethoderror) 
616                 return req.onmethoderror(req, status, status_text);
617         }
618     }
619
620     if(osrf_msg.type() == OSRF_MESSAGE_TYPE_RESULT) {
621         if(req) {
622             req.response_queue.push(osrf_msg.payload());
623             if(req.onresponse) {
624                 return req.onresponse(req);
625             }
626         }
627     }
628 };
629
630