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