dives into publish_result
[myslice.git] / manifold / js / manifold.js
1 // utilities 
2 function debug_dict_keys (msg, o) {
3     var keys=[];
4     for (var k in o) keys.push(k);
5     messages.debug ("debug_dict_keys: " + msg + " keys= " + keys);
6 }
7 function debug_dict (msg, o) {
8     for (var k in o) messages.debug ("debug_dict: " + msg + " [" + k + "]=" + o[k]);
9 }
10 function debug_value (msg, value) {
11     messages.debug ("debug_value: " + msg + " " + value);
12 }
13 function debug_query (msg, query) {
14     if (query === undefined) messages.debug ("debug_query: " + msg + " -> undefined");
15     else if (query == null) messages.debug ("debug_query: " + msg + " -> null");
16     else if ('query_uuid' in query) messages.debug ("debug_query: " + msg + query.__repr());
17     else messages.debug ("debug_query: " + msg + " query= " + query);
18 }
19
20 // http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
21 Object.toType = (function toType(global) {
22   return function(obj) {
23     if (obj === global) {
24       return "global";
25     }
26     return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
27   }
28 })(this);
29
30 /* ------------------------------------------------------------ */
31
32 // Constants that should be somehow moved to a plugin.js file
33 var FILTER_ADDED   = 1;
34 var FILTER_REMOVED = 2;
35 var CLEAR_FILTERS  = 3;
36 var FIELD_ADDED    = 4;
37 var FIELD_REMOVED  = 5;
38 var CLEAR_FIELDS   = 6;
39 var NEW_RECORD     = 7;
40 var CLEAR_RECORDS  = 8;
41 var FIELD_STATE_CHANGED = 9;
42
43 var IN_PROGRESS    = 101;
44 var DONE           = 102;
45
46 /* Update requests related to subqueries */
47 var SET_ADD        = 201;
48 var SET_REMOVED    = 202;
49
50 // request
51 var FIELD_REQUEST_CHANGE  = 301;
52 var FIELD_REQUEST_ADD     = 302;
53 var FIELD_REQUEST_REMOVE  = 303;
54 var FIELD_REQUEST_ADD_RESET = 304;
55 var FIELD_REQUEST_REMOVE_RESET = 305;
56 // status
57 var FIELD_REQUEST_PENDING = 401;
58 var FIELD_REQUEST_SUCCESS = 402;
59 var FIELD_REQUEST_FAILURE = 403;
60
61 /* Query status */
62 var STATUS_NONE               = 500; // Query has not been started yet
63 var STATUS_GET_IN_PROGRESS    = 501; // Query has been sent, no result has been received
64 var STATUS_GET_RECEIVED       = 502; // Success
65 var STATUS_GET_ERROR          = 503; // Error
66 var STATUS_UPDATE_PENDING     = 504;
67 var STATUS_UPDATE_IN_PROGRESS = 505;
68 var STATUS_UPDATE_RECEIVED    = 506;
69 var STATUS_UPDATE_ERROR       = 507;
70
71 /* Requests for query cycle */
72 var RUN_UPDATE     = 601;
73
74 /* MANIFOLD types */
75 var TYPE_VALUE  = 1;
76 var TYPE_RECORD = 2;
77 var TYPE_LIST_OF_VALUES = 3;
78 var TYPE_LIST_OF_RECORDS = 4;
79
80
81 // A structure for storing queries
82
83 function QueryExt(query, parent_query_ext, main_query_ext, update_query_ext, disabled) {
84
85     /* Constructor */
86     if (typeof query == "undefined")
87         throw "Must pass a query in QueryExt constructor";
88     this.query                 = query;
89     this.parent_query_ext      = (typeof parent_query_ext      == "undefined") ? null  : parent_query_ext;
90     this.main_query_ext        = (typeof main_query_ext        == "undefined") ? null  : main_query_ext;
91     this.update_query_ext      = (typeof update_query_ext      == "undefined") ? null  : update_query_ext;
92     this.update_query_orig_ext = (typeof update_query_orig_ext == "undefined") ? null  : update_query_orig_ext;
93     this.disabled              = (typeof update_query_ext      == "undefined") ? false : disabled;
94     
95     this.status       = null;
96     this.results      = null;
97     // update_query null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
98 }
99
100 function QueryStore() {
101
102     this.main_queries     = {};
103     this.analyzed_queries = {};
104
105     /* Insertion */
106
107     this.insert = function(query) {
108         // We expect only main_queries are inserted
109         
110         /* If the query has not been analyzed, then we analyze it */
111         if (query.analyzed_query == null) {
112             query.analyze_subqueries();
113         }
114
115         /* We prepare the update query corresponding to the main query and store both */
116         /* Note: they have the same UUID */
117
118         // XXX query.change_action() should become deprecated
119         update_query = query.clone();
120         update_query.action = 'update';
121         update_query.analyzed_query.action = 'update';
122         update_query.params = {};
123         update_query_ext = new QueryExt(update_query);
124
125         /* We remember the original query to be able to reset it */
126         update_query_orig_ext = new QueryExt(update_query.clone());
127
128
129         /* We store the main query */
130         query_ext = new QueryExt(query, null, null, update_query_ext, update_query_orig_ext, false);
131         manifold.query_store.main_queries[query.query_uuid] = query_ext;
132         /* Note: the update query does not have an entry! */
133
134
135         // The query is disabled; since it is incomplete until we know the content of the set of subqueries
136         // XXX unless we have no subqueries ???
137         // we will complete with params when records are received... this has to be done by the manager
138         // SET_ADD, SET_REMOVE will change the status of the elements of the set
139         // UPDATE will change also, etc.
140         // XXX We need a proper structure to store this information...
141
142         // We also need to insert all queries and subqueries from the analyzed_query
143         // XXX We need the root of all subqueries
144         query.iter_subqueries(function(sq, data, parent_query) {
145             if (parent_query)
146                 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
147             else
148                 parent_query_ext = null;
149             // XXX parent_query_ext == false
150             // XXX main.subqueries = {} # Normal, we need analyzed_query
151             sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
152             manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
153         });
154
155         // XXX We have spurious update queries...
156     }
157
158     /* Searching */
159
160     this.find_query_ext = function(query_uuid) {
161         return this.main_queries[query_uuid];
162     }
163
164     this.find_query = function(query_uuid) {
165         return this.find_query_ext(query_uuid).query;
166     }
167
168     this.find_analyzed_query_ext = function(query_uuid) {
169         return this.analyzed_queries[query_uuid];
170     }
171
172     this.find_analyzed_query = function(query_uuid) {
173         return this.find_analyzed_query_ext(query_uuid).query;
174     }
175 }
176
177 /*!
178  * This namespace holds functions for globally managing query objects
179  * \Class Manifold
180  */
181 var manifold = {
182
183     /************************************************************************** 
184      * Helper functions
185      **************************************************************************/ 
186
187     separator: '__',
188
189     spin_presets: {},
190
191     spin: function(locator, active /*= true */) {
192         active = typeof active !== 'undefined' ? active : true;
193         try {
194             if (active) {
195                 $(locator).spin(manifold.spin_presets);
196             } else {
197                 $(locator).spin(false);
198             }
199         } catch (err) { messages.debug("Cannot turn spins on/off " + err); }
200     },
201
202     get_type: function(variable) {
203         switch(Object.toType(variable)) {
204             case 'number':
205             case 'string':
206                 return TYPE_VALUE;
207             case 'object':
208                 return TYPE_RECORD;
209             case 'array':
210                 if ((variable.length > 0) && (Object.toType(variable[0]) === 'object'))
211                     return TYPE_LIST_OF_RECORDS;
212                 else
213                     return TYPE_LIST_OF_VALUES;
214         }
215     },
216
217     /************************************************************************** 
218      * Metadata management
219      **************************************************************************/ 
220
221      metadata: {
222
223         get_table: function(method) {
224             var table = MANIFOLD_METADATA[method];
225             return (typeof table === 'undefined') ? null : table;
226         },
227
228         get_columns: function(method) {
229             var table = this.get_table(method);
230             if (!table) {
231                 return null;
232             }
233
234             return (typeof table.column === 'undefined') ? null : table.column;
235         },
236
237         get_key: function(method) {
238             var table = this.get_table(method);
239             if (!table)
240                 return null;
241
242             return (typeof table.key === 'undefined') ? null : table.key;
243         },
244
245
246         get_column: function(method, name) {
247             var columns = this.get_columns(method);
248             if (!columns)
249                 return null;
250
251             $.each(columns, function(i, c) {
252                 if (c.name == name)
253                     return c
254             });
255             return null;
256         },
257
258         get_type: function(method, name) {
259             var table = this.get_table(method);
260             if (!table)
261                 return null;
262
263             return (typeof table.type === 'undefined') ? null : table.type;
264         }
265
266      },
267
268     /************************************************************************** 
269      * Query management
270      **************************************************************************/ 
271
272     query_store: new QueryStore(),
273
274     // XXX Remaining functions are deprecated since they are replaced by the query store
275
276     /*!
277      * Associative array storing the set of queries active on the page
278      * \memberof Manifold
279      */
280     all_queries: {},
281
282     /*!
283      * Insert a query in the global hash table associating uuids to queries.
284      * If the query has no been analyzed yet, let's do it.
285      * \fn insert_query(query)
286      * \memberof Manifold
287      * \param ManifoldQuery query Query to be added
288      */
289     insert_query : function (query) { 
290         // NEW API
291         manifold.query_store.insert(query);
292
293         // FORMER API
294         if (query.analyzed_query == null) {
295             query.analyze_subqueries();
296         }
297         manifold.all_queries[query.query_uuid]=query;
298     },
299
300     /*!
301      * Returns the query associated to a UUID
302      * \fn find_query(query_uuid)
303      * \memberof Manifold
304      * \param string query_uuid The UUID of the query to be returned
305      */
306     find_query : function (query_uuid) { 
307         return manifold.all_queries[query_uuid];
308     },
309
310     /************************************************************************** 
311      * Query execution
312      **************************************************************************/ 
313
314     // trigger a query asynchroneously
315     proxy_url : '/manifold/proxy/json/',
316
317     // reasonably low-noise, shows manifold requests coming in and out
318     asynchroneous_debug : true,
319     // print our more details on result publication and related callbacks
320     publish_result_debug : false,
321
322     /**
323      * \brief We use js function closure to be able to pass the query (array)
324      * to the callback function used when data is received
325      */
326     success_closure: function(query, publish_uuid, callback /*domid*/) {
327         return function(data, textStatus) {
328             manifold.asynchroneous_success(data, query, publish_uuid, callback /*domid*/);
329         }
330     },
331
332     run_query: function(query, callback) {
333         // default value for callback = null
334         if (typeof callback === 'undefined')
335             callback = null; 
336
337         var query_json = JSON.stringify(query);
338
339         /* Nothing related to pubsub here... for the moment at least. */
340         //query.iter_subqueries(function (sq) {
341         //    manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
342         //});
343
344         $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, null, callback /*domid*/));
345     },
346
347     // Executes all async. queries
348     // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
349     asynchroneous_exec : function (query_publish_dom_tuples) {
350         // start spinners
351
352         // in case the spin stuff was not loaded, let's make sure we proceed to the exit 
353         //try {
354         //    if (manifold.asynchroneous_debug) 
355         //   messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
356         //    jQuery('.need-spin').spin(manifold.spin_presets);
357         //} catch (err) { messages.debug("Cannot turn on spins " + err); }
358         
359         // Loop through input array, and use publish_uuid to publish back results
360         jQuery.each(query_publish_dom_tuples, function(index, tuple) {
361             var query=manifold.find_query(tuple.query_uuid);
362             var query_json=JSON.stringify (query);
363             var publish_uuid=tuple.publish_uuid;
364             // by default we publish using the same uuid of course
365             if (publish_uuid==undefined) publish_uuid=query.query_uuid;
366             if (manifold.asynchroneous_debug) {
367                 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
368                 messages.debug("... ctd... with actual query= " + query.__repr());
369             }
370
371             query.iter_subqueries(function (sq) {
372                 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
373             });
374
375             // not quite sure what happens if we send a string directly, as POST data is named..
376             // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
377             jQuery.post(manifold.proxy_url, {'json':query_json}, 
378                         manifold.success_closure(query, publish_uuid, tuple.callback /*domid*/));
379         })
380     },
381
382     /**
383      * \brief Forward a query to the manifold backend
384      * \param query (dict) the query to be executed asynchronously
385      * \param callback (function) the function to be called when the query terminates
386      * Deprecated:
387      * \param domid (string) the domid to be notified about the results (null for using the pub/sub system
388      */
389     forward: function(query, callback /*domid*/) {
390         var query_json = JSON.stringify(query);
391         $.post(manifold.proxy_url, {'json': query_json} , 
392                manifold.success_closure(query, query.query_uuid, callback/*domid*/));
393     },
394
395     /*!
396      * Returns whether a query expects a unique results.
397      * This is the case when the filters contain a key of the object
398      * \fn query_expects_unique_result(query)
399      * \memberof Manifold
400      * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
401      */
402     query_expects_unique_result: function(query) {
403         /* XXX we need functions to query metadata */
404         //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
405         /* TODO requires keys in metadata */
406         return true;
407     },
408
409     /*!
410      * Publish result
411      * \fn publish_result(query, results)
412      * \memberof Manifold
413      * \param ManifoldQuery query Query which has received results
414      * \param array results results corresponding to query
415      */
416     publish_result: function(query, result) {
417         if (typeof result === 'undefined')
418             result = [];
419
420         // NEW PLUGIN API
421         manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
422         if (manifold.publish_result_debug) messages.debug(".. publish_result (1) ");
423         var count=0;
424         $.each(result, function(i, record) {
425             manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
426             count += 1;
427         });
428         if (manifold.publish_result_debug) messages.debug(".. publish_result NEW API (2) count=" + count);
429         manifold.raise_record_event(query.query_uuid, DONE);
430
431         // OLD PLUGIN API BELOW
432         /* Publish an update announce */
433         var channel="/results/" + query.query_uuid + "/changed";
434         if (manifold.publish_result_debug) messages.debug(".. publish_result OLD API (3) " + channel);
435         jQuery.publish(channel, [result, query]);
436
437         if (manifold.publish_result_debug) messages.debug(".. publish_result - END (4) q=" + query.__repr());
438     },
439
440     /*!
441      * Recursively publish result
442      * \fn publish_result_rec(query, result)
443      * \memberof Manifold
444      * \param ManifoldQuery query Query which has received result
445      * \param array result result corresponding to query
446      */
447     publish_result_rec: function(query, result) {
448         /* If the result is not unique, only publish the top query;
449          * otherwise, publish the main object as well as subqueries
450          * XXX how much recursive are we ?
451          */
452         if (manifold.publish_result_debug) messages.debug (">>>>> publish_result_rec " + query.object);
453         if (manifold.query_expects_unique_result(query)) {
454             /* Also publish subqueries */
455             jQuery.each(query.subqueries, function(object, subquery) {
456                 manifold.publish_result_rec(subquery, result[0][object]);
457                 /* TODO remove object from result */
458             });
459         }
460         if (manifold.publish_result_debug) messages.debug ("===== publish_result_rec " + query.object);
461         manifold.publish_result(query, result);
462         if (manifold.publish_result_debug) messages.debug ("<<<<< publish_result_rec " + query.object);
463     },
464
465     setup_update_query: function(query, records) {
466         // We don't prepare an update query if the result has more than 1 entry
467         if (records.length != 1)
468             return;
469         var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
470
471         var record = records[0];
472
473         var update_query_ext = query_ext.update_query_ext;
474         var update_query = update_query_ext.query;
475         var update_query_ext = query_ext.update_query_ext;
476         var update_query_orig = query_ext.update_query_orig_ext.query;
477
478         // Testing whether the result has subqueries (one level deep only)
479         // iif the query has subqueries
480         var count = 0;
481         var obj = query.analyzed_query.subqueries;
482         for (method in obj) {
483             if (obj.hasOwnProperty(method)) {
484                 var key = manifold.metadata.get_key(method);
485                 if (!key)
486                     continue;
487                 if (key.length > 1)
488                     continue;
489                 key = key[0];
490                 var sq_keys = [];
491                 var subrecords = record[method];
492                 if (!subrecords)
493                     continue
494                 $.each(subrecords, function (i, subrecord) {
495                     sq_keys.push(subrecord[key]);
496                 });
497                 update_query.params[method] = sq_keys;
498                 update_query_orig.params[method] = sq_keys.slice();
499                 count++;
500             }
501         }
502
503         if (count > 0) {
504             update_query_ext.disabled = false;
505             update_query_orig_ext.disabled = false;
506         }
507     },
508
509     process_get_query_records: function(query, records) {
510         this.setup_update_query(query, records);
511
512         /* Publish full results */
513         tmp_query = manifold.find_query(query.query_uuid);
514         manifold.publish_result_rec(tmp_query.analyzed_query, records);
515     },
516
517     /**
518      * 
519      * What we need to do when receiving results from an update query:
520      * - differences between what we had, what we requested, and what we obtained
521      *    . what we had : update_query_orig (simple fields and set fields managed differently)
522      *    . what we requested : update_query
523      *    . what we received : records
524      * - raise appropriate events
525      *
526      * The normal process is that results similar to Get will be pushed in the
527      * pubsub mechanism, thus repopulating everything while we only need
528      * diff's. This means we need to move the publish functionalities in the
529      * previous 'process_get_query_records' function.
530      */
531     process_update_query_records: function(query, records) {
532         // First issue: we request everything, and not only what we modify, so will will have to ignore some fields
533         var query_uuid        = query.query_uuid;
534         var query_ext         = manifold.query_store.find_analyzed_query_ext(query_uuid);
535         var update_query      = query_ext.main_query_ext.update_query_ext.query;
536         var update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
537         
538         // Since we update objects one at a time, we can get the first record
539         var record = records[0];
540
541         // Let's iterate over the object properties
542         for (var field in record) {
543             switch (this.get_type(record[field])) {
544                 case TYPE_VALUE:
545                     // Did we ask for a change ?
546                     var update_value = update_query[field];
547                     if (!update_value)
548                         // Not requested, if it has changed: OUT OF SYNC
549                         // How we can know ?
550                         // We assume it won't have changed
551                         continue;
552
553                     var result_value = record[field];
554                     if (!result_value)
555                         throw "Internal error";
556
557                     data = {
558                         request: FIELD_REQUEST_CHANGE,
559                         key   : field,
560                         value : update_value,
561                         status: (update_value == result_value) ? FIELD_REQUEST_SUCCESS : FIELD_REQUEST_FAILURE,
562                     }
563                     manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
564
565                     break;
566                 case TYPE_RECORD:
567                     throw "Not implemented";
568                     break;
569
570                 case TYPE_LIST_OF_VALUES:
571                     // Same as list of records, but we don't have to extract keys
572                     var result_keys  = record[field]
573                     
574                     // The rest of exactly the same (XXX factorize)
575                     var update_keys  = update_query_orig.params[field];
576                     var query_keys   = update_query.params[field];
577                     var added_keys   = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
578                     var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
579
580
581                     $.each(added_keys, function(i, key) {
582                         if ($.inArray(key, result_keys) == -1) {
583                             data = {
584                                 request: FIELD_REQUEST_ADD,
585                                 key   : field,
586                                 value : key,
587                                 status: FIELD_REQUEST_FAILURE,
588                             }
589                         } else {
590                             data = {
591                                 request: FIELD_REQUEST_ADD,
592                                 key   : field,
593                                 value : key,
594                                 status: FIELD_REQUEST_SUCCESS,
595                             }
596                         }
597                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
598                     });
599                     $.each(removed_keys, function(i, key) {
600                         if ($.inArray(key, result_keys) == -1) {
601                             data = {
602                                 request: FIELD_REQUEST_REMOVE,
603                                 key   : field,
604                                 value : key,
605                                 status: FIELD_REQUEST_SUCCESS,
606                             }
607                         } else {
608                             data = {
609                                 request: FIELD_REQUEST_REMOVE,
610                                 key   : field,
611                                 value : key,
612                                 status: FIELD_REQUEST_FAILURE,
613                             }
614                         }
615                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
616                     });
617
618
619                     break;
620                 case TYPE_LIST_OF_RECORDS:
621                     // example: slice.resource
622                     //  - update_query_orig.params.resource = resources in slice before update
623                     //  - update_query.params.resource = resource requested in slice
624                     //  - keys from field = resources obtained
625                     var key = manifold.metadata.get_key(field);
626                     if (!key)
627                         continue;
628                     if (key.length > 1) {
629                         throw "Not implemented";
630                         continue;
631                     }
632                     key = key[0];
633
634                     /* XXX should be modified for multiple keys */
635                     var result_keys  = $.map(record[field], function(x) { return x[key]; });
636
637                     var update_keys  = update_query_orig.params[field];
638                     var query_keys   = update_query.params[field];
639                     var added_keys   = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
640                     var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
641
642
643                     $.each(added_keys, function(i, key) {
644                         if ($.inArray(key, result_keys) == -1) {
645                             data = {
646                                 request: FIELD_REQUEST_ADD,
647                                 key   : field,
648                                 value : key,
649                                 status: FIELD_REQUEST_FAILURE,
650                             }
651                         } else {
652                             data = {
653                                 request: FIELD_REQUEST_ADD,
654                                 key   : field,
655                                 value : key,
656                                 status: FIELD_REQUEST_SUCCESS,
657                             }
658                         }
659                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
660                     });
661                     $.each(removed_keys, function(i, key) {
662                         if ($.inArray(key, result_keys) == -1) {
663                             data = {
664                                 request: FIELD_REQUEST_REMOVE,
665                                 key   : field,
666                                 value : key,
667                                 status: FIELD_REQUEST_SUCCESS,
668                             }
669                         } else {
670                             data = {
671                                 request: FIELD_REQUEST_REMOVE,
672                                 key   : field,
673                                 value : key,
674                                 status: FIELD_REQUEST_FAILURE,
675                             }
676                         }
677                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
678                     });
679
680
681                     break;
682             }
683         }
684         
685         // XXX Now we need to adapt 'update' and 'update_orig' queries as if we had done a get
686         this.setup_update_query(query, records);
687     },
688
689     process_query_records: function(query, records) {
690         if (query.action == 'get') {
691             this.process_get_query_records(query, records);
692         } else if (query.action == 'update') {
693             this.process_update_query_records(query, records);
694         }
695     },
696
697     // if set domid allows the result to be directed to just one plugin
698     // most of the time publish_uuid will be query.query_uuid
699     // however in some cases we wish to publish the result under a different uuid
700     // e.g. an updater wants to publish its result as if from the original (get) query
701     asynchroneous_success : function (data, query, publish_uuid, callback /*domid*/) {
702         // xxx should have a nicer declaration of that enum in sync with the python code somehow
703         
704         var start = new Date();
705         if (manifold.asynchroneous_debug)
706             messages.debug(">>>>>>>>>> asynchroneous_success query.object=" + query.object);
707
708         /* If a callback has been specified, we redirect results to it */
709         if (!!callback) { 
710             callback(data); 
711             if (manifold.asynchroneous_debug) {
712                 duration=new Date()-start;
713                 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- callback ended " + duration + " ms");
714             }
715             return; 
716         }
717
718         if (data.code == 2) { // ERROR
719             // We need to make sense of error codes here
720             alert("Your session has expired, please log in again");
721             window.location="/logout/";
722             if (manifold.asynchroneous_debug) {
723                 duration=new Date()-start;
724                 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- error returned - logging out " + duration + " ms");
725             }
726             return;
727         }
728         if (data.code == 1) { // WARNING
729             messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
730             // publish error code and text message on a separate channel for whoever is interested
731             if (publish_uuid)
732                 $.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
733
734             $("#notifications").notify("create", "sticky", {
735               title: 'Warning',
736               text: data.description
737             },{
738               expires: false,
739               speed: 1000
740             });
741             
742         }
743         if (manifold.asynchroneous_debug) 
744             messages.debug ("========== asynchroneous_success " + query.object + " -- before process_query_records");
745
746         // once everything is checked we can use the 'value' part of the manifoldresult
747         var result=data.value;
748         if (result) {
749             /* Eventually update the content of related queries (update, etc) */
750             this.process_query_records(query, result);
751
752             /* Publish results: disabled here, done in the previous call */
753             //tmp_query = manifold.find_query(query.query_uuid);
754             //manifold.publish_result_rec(tmp_query.analyzed_query, result);
755         }
756         if (manifold.asynchroneous_debug) {
757             duration=new Date()-start;
758             messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- done " + duration + " ms");
759         }
760
761     },
762
763     /************************************************************************** 
764      * Plugin API helpers
765      **************************************************************************/ 
766
767     raise_event_handler: function(type, query_uuid, event_type, value) {
768         if ((type != 'query') && (type != 'record'))
769             throw 'Incorrect type for manifold.raise_event()';
770
771         var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
772
773         $.each(channels, function(i, channel) {
774             if (value === undefined) {
775                 $('.plugin').trigger(channel, [event_type]);
776             } else {
777                 $('.plugin').trigger(channel, [event_type, value]);
778             }
779         });
780     },
781
782     raise_query_event: function(query_uuid, event_type, value) {
783         manifold.raise_event_handler('query', query_uuid, event_type, value);
784     },
785
786     raise_record_event: function(query_uuid, event_type, value) {
787         manifold.raise_event_handler('record', query_uuid, event_type, value);
788     },
789
790
791     raise_event: function(query_uuid, event_type, value) {
792         // Query uuid has been updated with the key of a new element
793         query_ext    = manifold.query_store.find_analyzed_query_ext(query_uuid);
794         query = query_ext.query;
795
796         switch(event_type) {
797             case FIELD_STATE_CHANGED:
798                 // value is an object (request, key, value, status)
799                 // update is only possible is the query is not pending, etc
800                 // SET_ADD is on a subquery, FIELD_STATE_CHANGED on the query itself
801                 // we should map SET_ADD on this...
802
803                 // 1. Update internal query store about the change in status
804
805                 // 2. Update the update query
806                 update_query      = query_ext.main_query_ext.update_query_ext.query;
807                 update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
808
809                 switch(value.request) {
810                     case FIELD_REQUEST_CHANGE:
811                         update_query.params[value.key] = value.value;
812                         break;
813                     case FIELD_REQUEST_ADD:
814                         if ($.inArray(value.value, update_query_orig.params[value.key]) != -1)
815                             value.request = FIELD_REQUEST_ADD_RESET;
816                         update_query.params[value.key].push(value.value);
817                         break;
818                     case FIELD_REQUEST_REMOVE:
819                         if ($.inArray(value.value, update_query_orig.params[value.key]) == -1)
820                             value.request = FIELD_REQUEST_REMOVE_RESET;
821
822                         var arr = update_query.params[value.key];
823                         arr = $.grep(arr, function(x) { return x != value.value; });
824                         update_query.params[value.key] = arr;
825
826                         break;
827                     case FIELD_REQUEST_ADD_RESET:
828                     case FIELD_REQUEST_REMOVE_RESET:
829                         // XXX We would need to keep track of the original query
830                         throw "Not implemented";
831                         break;
832                 }
833
834                 // 3. Inform others about the change
835                 // a) the main query...
836                 manifold.raise_record_event(query_uuid, event_type, value);
837
838                 // b) subqueries eventually (dot in the key)
839                 // Let's unfold 
840                 var path_array = value.key.split('.');
841                 var value_key = value.key.split('.');
842
843                 var cur_query = query;
844                 if (cur_query.analyzed_query)
845                     cur_query = cur_query.analyzed_query;
846                 $.each(path_array, function(i, method) {
847                     cur_query = cur_query.subqueries[method];
848                     value_key.shift(); // XXX check that method is indeed shifted
849                 });
850                 value.key = value_key;
851
852                 manifold.raise_record_event(cur_query.query_uuid, event_type, value);
853
854                 // XXX make this DOT a global variable... could be '/'
855                 break;
856
857             case SET_ADD:
858             case SET_REMOVED:
859     
860                 // update is only possible is the query is not pending, etc
861                 // CHECK status !
862
863                 // XXX we can only update subqueries of the main query. Check !
864                 // assert query_ext.parent_query == query_ext.main_query
865                 // old // update_query = query_ext.main_query_ext.update_query_ext.query;
866
867                 // This SET_ADD is called on a subquery, so we have to
868                 // recontruct the path of the key in the main_query
869                 // We then call FIELD_STATE_CHANGED which is the equivalent for the main query
870
871                 var path = "";
872                 var sq = query_ext;
873                 while (sq.parent_query_ext) {
874                     if (path != "")
875                         path = '.' + path;
876                     path = sq.query.object + path;
877                     sq = sq.parent_query_ext;
878                 }
879
880                 main_query = query_ext.main_query_ext.query;
881                 data = {
882                     request: (event_type == SET_ADD) ? FIELD_REQUEST_ADD : FIELD_REQUEST_REMOVE,
883                     key   : path,
884                     value : value,
885                     status: FIELD_REQUEST_PENDING,
886                 };
887                 this.raise_event(main_query.query_uuid, FIELD_STATE_CHANGED, data);
888
889                 // old //update_query.params[path].push(value);
890                 // old // console.log('Updated query params', update_query);
891                 // NOTE: update might modify the fields in Get
892                 // NOTE : we have to modify all child queries
893                 // NOTE : parts of a query might not be started (eg slice.measurements, how to handle ?)
894
895                 // if everything is done right, update_query should not be null. 
896                 // It is updated when we received results from the get query
897                 // object = the same as get
898                 // filter = key : update a single object for now
899                 // fields = the same as get
900                 manifold.raise_query_event(query_uuid, event_type, value);
901
902                 break;
903
904             case RUN_UPDATE:
905                 manifold.run_query(query_ext.main_query_ext.update_query_ext.query);
906                 break;
907
908             case FILTER_ADDED:
909                 manifold.raise_query_event(query_uuid, event_type, value);
910                 break;
911             case FILTER_REMOVED:
912                 manifold.raise_query_event(query_uuid, event_type, value);
913                 break;
914             case FIELD_ADDED:
915                 main_query = query_ext.main_query_ext.query;
916                 main_update_query = query_ext.main_query_ext.update_query;
917                 query.select(value);
918
919                 // Here we need the full path through all subqueries
920                 path = ""
921                 // XXX We might need the query name in the QueryExt structure
922                 main_query.select(value);
923
924                 // XXX When is an update query associated ?
925                 // XXX main_update_query.select(value);
926
927                 manifold.raise_query_event(query_uuid, event_type, value);
928                 break;
929
930             case FIELD_REMOVED:
931                 query = query_ext.query;
932                 main_query = query_ext.main_query_ext.query;
933                 main_update_query = query_ext.main_query_ext.update_query;
934                 query.unselect(value);
935                 main_query.unselect(value);
936
937                 // We need to inform about changes in these queries to the respective plugins
938                 // Note: query & main_query have the same UUID
939                 manifold.raise_query_event(query_uuid, event_type, value);
940                 break;
941         }
942         // We need to inform about changes in these queries to the respective plugins
943         // Note: query, main_query & update_query have the same UUID
944         manifold.raise_query_event(query_uuid, event_type, value);
945         // We are targeting the same object with get and update
946         // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
947         // NOTE: Editing a subquery == editing a local view on the destination
948
949         // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
950         // For the time being, we will collect all columns during the first query
951     },
952
953     /* Publish/subscribe channels for internal use */
954     get_channel: function(type, query_uuid) {
955         if ((type !== 'query') && (type != 'record'))
956             return null;
957         return '/' + type + '/' + query_uuid;
958     },
959
960 }; // manifold object
961 /* ------------------------------------------------------------ */
962
963 (function($) {
964
965     // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
966     // https://gist.github.com/661855
967     var o = $({});
968     $.subscribe = function( channel, selector, data, fn) {
969       /* borrowed from jQuery */
970       if ( data == null && fn == null ) {
971           // ( channel, fn )
972           fn = selector;
973           data = selector = undefined;
974       } else if ( fn == null ) {
975           if ( typeof selector === "string" ) {
976               // ( channel, selector, fn )
977               fn = data;
978               data = undefined;
979           } else {
980               // ( channel, data, fn )
981               fn = data;
982               data = selector;
983               selector = undefined;
984           }
985       }
986       /* </ugly> */
987   
988       /* We use an indirection function that will clone the object passed in
989        * parameter to the subscribe callback 
990        * 
991        * FIXME currently we only clone query objects which are the only ones
992        * supported and editable, we might have the same issue with results but
993        * the page load time will be severely affected...
994        */
995       o.on.apply(o, [channel, selector, data, function() { 
996           for(i = 1; i < arguments.length; i++) {
997               if ( arguments[i].constructor.name == 'ManifoldQuery' )
998                   arguments[i] = arguments[i].clone();
999           }
1000           fn.apply(o, arguments);
1001       }]);
1002     };
1003   
1004     $.unsubscribe = function() {
1005       o.off.apply(o, arguments);
1006     };
1007   
1008     $.publish = function() {
1009       o.trigger.apply(o, arguments);
1010     };
1011   
1012 }(jQuery));
1013
1014 /* ------------------------------------------------------------ */
1015
1016 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
1017 //make sure to expose csrf in our outcoming ajax/post requests
1018 $.ajaxSetup({ 
1019      beforeSend: function(xhr, settings) {
1020          function getCookie(name) {
1021              var cookieValue = null;
1022              if (document.cookie && document.cookie != '') {
1023                  var cookies = document.cookie.split(';');
1024                  for (var i = 0; i < cookies.length; i++) {
1025                      var cookie = jQuery.trim(cookies[i]);
1026                      // Does this cookie string begin with the name we want?
1027                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
1028                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
1029                      break;
1030                  }
1031              }
1032          }
1033          return cookieValue;
1034          }
1035          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
1036              // Only send the token to relative URLs i.e. locally.
1037              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
1038          }
1039      } 
1040 });