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