test/integration/allocine_dossier_independant/js/libs/tracemanager.js
branchpopcorn-port
changeset 841 8da49ff273e0
child 899 445631dffdf8
equal deleted inserted replaced
840:ac66e2240e1e 841:8da49ff273e0
       
     1 /*
       
     2  * Modelled Trace API
       
     3  */
       
     4 IriSP.TraceManager = function($) {
       
     5      // If there are more than MAX_FAILURE_COUNT synchronisation
       
     6      // failures, then disable synchronisation
       
     7      MAX_FAILURE_COUNT = 20;
       
     8 
       
     9      // If there are more than MAX_BUFFER_SIZE obsels in the buffer,
       
    10      // then "compress" them as a single "ktbsFullBuffer"
       
    11      MAX_BUFFER_SIZE = 500;
       
    12 
       
    13      var BufferedService_prototype = {
       
    14          /*
       
    15           *  Buffered service for traces
       
    16           */
       
    17          // url: "",
       
    18          // buffer: [],
       
    19          // isReady: false,
       
    20          // timer: null,
       
    21          // failureCount: 0,
       
    22 
       
    23          /* Flush buffer */
       
    24          flush: function() {
       
    25              // FIXME: add mutex on this.buffer
       
    26              if (! this.isReady)
       
    27              {
       
    28                  if (window.console) window.console.log("Sync service not ready");
       
    29              } else if (this.failureCount > MAX_FAILURE_COUNT)
       
    30              {
       
    31                  // Disable synchronisation
       
    32                  this.set_sync_mode('none');
       
    33              } else if (this.buffer.length) {
       
    34                  var temp = this.buffer;
       
    35                  this.buffer = [];
       
    36 
       
    37                  if (this.mode == 'GET')
       
    38                  {
       
    39                      // GET mode: do some data mangline. We mark the
       
    40                      // "compressed" nature of the generated JSON by
       
    41                      // prefixing it with c
       
    42                      var data = 'c' + JSON.stringify(temp.map(function (o) { return o.toCompactJSON(); }));
       
    43                      // Swap " (very frequent, which will be
       
    44                      // serialized into %22) and ; (rather rare), this
       
    45                      // saves some bytes
       
    46                      data = data.replace(/[;"]/g, function(s){ return s == ';' ? '"' : ';'; }).replace(/#/g, '%23');
       
    47                      // FIXME: check data length (< 2K is safe)
       
    48                      var request=$('<img />').error( function() { this.failureCount += 1; })
       
    49                          .load( function() { this.failureCount = 0; })
       
    50                          .attr('src', this.url + 'trace/?data=' + data);
       
    51                  }
       
    52                  else
       
    53                  {
       
    54                      $.ajax({ url: this.url + 'trace/',
       
    55                               type: 'POST',
       
    56                               contentType: 'application/json',
       
    57                               data: JSON.stringify(temp.map(function (o) { return o.toJSON(); })),
       
    58                               processData: false,
       
    59                               // Type of the returned data.
       
    60                               dataType: "html",
       
    61                               error: function(jqXHR, textStatus, errorThrown) {
       
    62                                   if (window.console) window.console.log("Error when sending buffer:", textStatus);
       
    63                                   this.failureCount += 1;
       
    64                               },
       
    65                               success: function(data, textStatus, jqXHR) {
       
    66                                   // Reset failureCount to 0 as soon as there is 1 valid answer
       
    67                                   this.failureCount = 0;
       
    68                               }
       
    69                             });
       
    70                  }
       
    71              }
       
    72          },
       
    73 
       
    74          /* Sync mode: delayed, sync (immediate sync), none (no
       
    75           * synchronisation with server, the trace has to be explicitly saved
       
    76           * if needed */
       
    77          set_sync_mode: function(mode) {
       
    78              this.sync_mode = mode;
       
    79              if (! this.isReady && mode !== "none")
       
    80                  this.init();
       
    81              if (mode == 'delayed') {
       
    82                  this.start_timer();
       
    83              } else {
       
    84                  this.stop_timer();
       
    85              }
       
    86          },
       
    87 
       
    88          /* Enqueue an obsel */
       
    89          enqueue: function(obsel) {
       
    90              if (this.buffer.length > MAX_BUFFER_SIZE)
       
    91              {
       
    92                  obsel = new Obsel('ktbsFullBuffer', this.buffer[0].begin,
       
    93                                    this.buffer[this.buffer.length - 1].end, this.buffer[0].subject);
       
    94                  obsel.trace = this.buffer[0].trace;
       
    95                  this.buffer = [];
       
    96              }
       
    97              this.buffer.push(obsel);
       
    98              if (this.sync_mode === 'sync') {
       
    99                  // Immediate sync of the obsel.
       
   100                  this.flush();
       
   101              }
       
   102          },
       
   103 
       
   104          start_timer: function() {
       
   105              var self = this;
       
   106              if (this.timer === null) {
       
   107                  this.timer = window.setInterval(function() {
       
   108                                                      self.flush();
       
   109                                                  }, this.timeOut);
       
   110              }
       
   111          },
       
   112 
       
   113          stop_timer: function() {
       
   114              if (this.timer !== null) {
       
   115                  window.clearInterval(this.timer);
       
   116                  this.timer = null;
       
   117              }
       
   118          },
       
   119 
       
   120          /*
       
   121           * Initialize the sync service
       
   122           */
       
   123          init: function() {
       
   124              var self = this;
       
   125              if (this.isReady)
       
   126                  /* Already initialized */
       
   127                  return;
       
   128              if (this.mode == 'GET')
       
   129              {
       
   130                  var request=$('<img/>').attr('src', this.url + 'login?userinfo={"name":"ktbs4js"}');
       
   131                  // Do not wait for the return, assume it is
       
   132                  // initialized. This assumption will not work anymore
       
   133                  // if login returns some necessary information
       
   134                  this.isReady = true;
       
   135              }
       
   136              else
       
   137              {
       
   138                  $.ajax({ url: this.url + 'login',
       
   139                           type: 'POST',
       
   140                           data: 'userinfo={"name":"ktbs4js"}',
       
   141                           success: function(data, textStatus, jqXHR) {
       
   142                               self.isReady = true;
       
   143                               if (self.buffer.length) {
       
   144                                   self.flush();
       
   145                               }
       
   146                           }
       
   147                         });
       
   148              }
       
   149          }
       
   150      };
       
   151      var BufferedService = function(url, mode) {
       
   152          this.url = url;
       
   153          this.buffer = [];
       
   154          this.isReady = false;
       
   155          this.timer = null;
       
   156          this.failureCount = 0;
       
   157          // sync_mode is either "none", "sync" or "buffered"
       
   158          this.sync_mode = "none";
       
   159          /* mode can be either POST or GET */
       
   160          if (mode == 'POST' || mode == 'GET')
       
   161              this.mode = mode;
       
   162          else
       
   163              this.mode = 'POST';
       
   164          /* Flush buffer every timeOut ms if the sync_mode is delayed */
       
   165          this.timeOut = 2000;
       
   166      };
       
   167      BufferedService.prototype = BufferedService_prototype;
       
   168 
       
   169      var Trace_prototype = {
       
   170          /* FIXME: We could/should use a sorted list such as
       
   171           http://closure-library.googlecode.com/svn/docs/class_goog_structs_AvlTree.html
       
   172           to speed up queries based on time */
       
   173          obsels: [],
       
   174          /* Trace URI */
       
   175          uri: "",
       
   176          default_subject: "",
       
   177          /* baseuri is used as the base URI to resolve relative
       
   178           * attribute-type names in obsels. Strictly speaking, this
       
   179           * should rather be expressed as a reference to model, or
       
   180           * more generically, as a qname/URI dict */
       
   181          baseuri: "",
       
   182          /* Mapping of obsel type or property name to a compact
       
   183           * representation (shorthands).
       
   184           */
       
   185          shorthands: null,
       
   186          syncservice: null,
       
   187 
       
   188          /* Define the trace URI */
       
   189          set_uri: function(uri) {
       
   190              this.uri = uri;
       
   191          },
       
   192 
       
   193          /* Sync mode: delayed, sync (immediate sync), none (no
       
   194           * synchronisation with server, the trace has to be explicitly saved
       
   195           * if needed */
       
   196          set_sync_mode: function(mode) {
       
   197              if (this.syncservice !== null) {
       
   198                  this.syncservice.set_sync_mode(mode);
       
   199              }
       
   200          },
       
   201 
       
   202          /*
       
   203           * Return a list of the obsels of this trace matching the parameters
       
   204           */
       
   205          list_obsels: function(_begin, _end, _reverse) {
       
   206              var res;
       
   207              if (typeof _begin !== 'undefined' || typeof _end !== 'undefined') {
       
   208                  /*
       
   209                   * Not optimized yet.
       
   210                   */
       
   211                  res = [];
       
   212                  var l = this.obsels.length;
       
   213                  for (var i = 0; i < l; i++) {
       
   214                      var o = this.obsels[i];
       
   215                      if ((typeof _begin !== 'undefined' && o.begin > _begin) && (typeof _end !== 'undefined' && o.end < _end)) {
       
   216                          res.push(o);
       
   217                      }
       
   218                  }
       
   219              }
       
   220 
       
   221              if (typeof _reverse !== 'undefined') {
       
   222                  if (res !== undefined) {
       
   223                      /* Should reverse the whole list. Make a copy. */
       
   224                      res = this.obsels.slice(0);
       
   225                  }
       
   226                  res.sort(function(a, b) { return b.begin - a.begin; });
       
   227                  return res;
       
   228              }
       
   229 
       
   230              if (res === undefined) {
       
   231                  res = this.obsels;
       
   232              }
       
   233              return res;
       
   234 
       
   235          },
       
   236 
       
   237          /*
       
   238           * Return the obsel of this trace identified by the URI, or undefined
       
   239           */
       
   240          get_obsel: function(id) {
       
   241              for (var i = 0; i < this.obsels.length; i++) {
       
   242                  /* FIXME: should check against variations of id/uri, take this.baseuri into account */
       
   243                  if (this.obsels[i].uri === id) {
       
   244                      return this.obsels[i];
       
   245                  }
       
   246              }
       
   247              return undefined;
       
   248          },
       
   249 
       
   250          set_default_subject: function(subject) {
       
   251              this.default_subject = subject;
       
   252          },
       
   253 
       
   254          get_default_subject: function() {
       
   255              return this.default_subject;
       
   256          },
       
   257 
       
   258          /* (type:ObselType, begin:int, end:int?, subject:str?, attributes:[AttributeType=>any]?) */
       
   259          /* Create a new obsel and add it to the trace */
       
   260          create_obsel: function(type, begin, end, subject, _attributes) {
       
   261              var o = new Obsel(type, begin, end, subject);
       
   262              if (typeof _attributes !== 'undefined') {
       
   263                  o.attributes = _attributes;
       
   264              }
       
   265              o.trace = this;
       
   266              this.obsels.push(o);
       
   267              if (this.syncservice !== null)
       
   268                  this.syncservice.enqueue(o);
       
   269          },
       
   270 
       
   271          /* Helper methods */
       
   272 
       
   273          /* Create a new obsel with the given attributes */
       
   274          trace: function(type, _attributes, _begin, _end, _subject) {
       
   275              var t = (new Date()).getTime();
       
   276              if (typeof begin === 'undefined') {
       
   277                  _begin = t;
       
   278              }
       
   279              if (typeof end === 'undefined') {
       
   280                  _end = _begin;
       
   281              }
       
   282              if (typeof subject === 'undefined') {
       
   283                  _subject = this.default_subject;
       
   284              }
       
   285              if (typeof _attributes === 'undefined') {
       
   286                  _attributes = {};
       
   287              }
       
   288              return this.create_obsel(type, _begin, _end, _subject, _attributes);
       
   289          }
       
   290      };
       
   291 
       
   292      var Trace = function(uri, requestmode) {
       
   293          /* FIXME: We could/should use a sorted list such as
       
   294           http://closure-library.googlecode.com/svn/docs/class_goog_structs_AvlTree.html
       
   295           to speed up queries based on time */
       
   296          this.obsels = [];
       
   297          /* Trace URI */
       
   298          if (uri === undefined)
       
   299              uri = "";
       
   300          this.uri = uri;
       
   301          this.sync_mode = "none";
       
   302          this.default_subject = "";
       
   303          this.shorthands = {};
       
   304          /* baseuri is used a the base URI to resolve relative attribute names in obsels */
       
   305          this.baseuri = "";
       
   306 
       
   307          this.syncservice = new BufferedService(uri, requestmode);
       
   308          $(window).unload( function () {
       
   309                                if (this.syncservice && this.sync_mode !== 'none') {
       
   310                                    this.syncservice.flush();
       
   311                                    this.syncservice.stop_timer();
       
   312                                }
       
   313                            });
       
   314      };
       
   315      Trace.prototype = Trace_prototype;
       
   316 
       
   317      var Obsel_prototype = {
       
   318          /* The following attributes are here for documentation
       
   319           * purposes. They MUST be defined in the constructor
       
   320           * function. */
       
   321          trace: undefined,
       
   322          type: undefined,
       
   323          begin: undefined,
       
   324          end: undefined,
       
   325          subject: undefined,
       
   326          /* Dictionary indexed by ObselType URIs */
       
   327          attributes: {},
       
   328 
       
   329          /* Method definitions */
       
   330          get_trace: function() {
       
   331              return this.trace;
       
   332          },
       
   333 
       
   334          get_obsel_type: function() {
       
   335              return this.type;
       
   336          },
       
   337          get_begin: function() {
       
   338              return this.begin;
       
   339          },
       
   340          get_end: function() {
       
   341              return this.end;
       
   342          },
       
   343          get_subject: function() {
       
   344              return this.subject;
       
   345          },
       
   346 
       
   347          list_attribute_types: function() {
       
   348              var result = [];
       
   349              for (var prop in this.attributes) {
       
   350                  if (this.hasOwnProperty(prop))
       
   351                      result.push(prop);
       
   352              }
       
   353              /* FIXME: we return URIs here instead of AttributeType elements */
       
   354              return result;
       
   355          },
       
   356 
       
   357          list_relation_types: function() {
       
   358              /* FIXME: not implemented yet */
       
   359          },
       
   360 
       
   361          list_related_obsels: function (rt) {
       
   362              /* FIXME: not implemented yet */
       
   363          },
       
   364          list_inverse_relation_types: function () {
       
   365              /* FIXME: not implemented yet */
       
   366          },
       
   367          list_relating_obsels: function (rt) {
       
   368              /* FIXME: not implemented yet */
       
   369          },
       
   370          /*
       
   371           * Return the value of the given attribute type for this obsel
       
   372           */
       
   373          get_attribute_value: function(at) {
       
   374              if (typeof at === "string")
       
   375                  /* It is a URI */
       
   376                  return this.attributes[at];
       
   377              else
       
   378                  /* FIXME: check that at is instance of AttributeType */
       
   379                  return this.attributes[at.uri];
       
   380          },
       
   381 
       
   382 
       
   383          /* obsel modification (trace amendment) */
       
   384 
       
   385          set_attribute_value: function(at, value) {
       
   386              if (typeof at === "string")
       
   387                  /* It is a URI */
       
   388                  this.attributes[at] = value;
       
   389              /* FIXME: check that at is instance of AttributeType */
       
   390              else
       
   391                  this.attributes[at.uri] = value;
       
   392          },
       
   393 
       
   394          del_attribute_value: function(at) {
       
   395              if (typeof at === "string")
       
   396                  /* It is a URI */
       
   397                  delete this.attributes[at];
       
   398              /* FIXME: check that at is instance of AttributeType */
       
   399              else
       
   400                  delete this.attributes[at.uri];
       
   401          },
       
   402 
       
   403          add_related_obsel: function(rt, value) {
       
   404              /* FIXME: not implemented yet */
       
   405          },
       
   406 
       
   407          del_related_obsel: function(rt, value) {
       
   408              /* FIXME: not implemented yet */
       
   409          },
       
   410 
       
   411          /*
       
   412           * Return a JSON representation of the obsel
       
   413           */
       
   414          toJSON: function() {
       
   415              var r = {
       
   416                  "@id": this.id,
       
   417                  "@type": this.type,
       
   418                  "begin": this.begin,
       
   419                  "end": this.end,
       
   420                  "subject": this.subject
       
   421              };
       
   422              for (var prop in this.attributes) {
       
   423                  if (this.hasOwnProperty(prop))
       
   424                      r[prop] = this.attributes[prop];
       
   425              }
       
   426              return r;
       
   427          },
       
   428 
       
   429          /*
       
   430           * Return a compact JSON representation of the obsel.
       
   431           * Use predefined + custom shorthands for types/properties
       
   432           */
       
   433          toCompactJSON: function() {
       
   434              var r = {
       
   435                  "@i": this.id,
       
   436                  "@t": (this.trace.shorthands.hasOwnProperty(this.type) ? this.trace.shorthands[this.type] : this.type),
       
   437                  "@b": this.begin,
       
   438                  "@s": this.subject
       
   439              };
       
   440              // Store duration (to save some bytes) and only if it is non-null
       
   441              if (this.begin !== this.end)
       
   442                  r["@d"] = this.end - this.begin;
       
   443 
       
   444              for (var prop in this.attributes) {
       
   445                  if (this.hasOwnProperty(prop))
       
   446                  {
       
   447                      var v = this.attributes[prop];
       
   448                      r[prop] = this.trace.shorthands.hasOwnProperty(v) ? this.trace.shorthands[v] : v;
       
   449                  }
       
   450              }
       
   451              return r;
       
   452          },
       
   453 
       
   454          toJSONstring: function() {
       
   455              return JSON.stringify(this.toJSON());
       
   456          }
       
   457      };
       
   458 
       
   459      var Obsel = function(type, begin, end, subject, attributes) {
       
   460          this.trace = undefined;
       
   461          this.uri = "";
       
   462          this.id = "";
       
   463          this.type = type;
       
   464          this.begin = begin;
       
   465          this.end = end;
       
   466          this.subject = subject;
       
   467          /* Is the obsel synched with the server ? */
       
   468          this.sync_status = false;
       
   469          /* Dictionary indexed by ObselType URIs */
       
   470          this.attributes = {};
       
   471      };
       
   472      Obsel.prototype = Obsel_prototype;
       
   473 
       
   474      var TraceManager_prototype = {
       
   475          traces: [],
       
   476          /*
       
   477           * Return the trace with id name
       
   478           * If it was not registered, return undefined.
       
   479           */
       
   480          get_trace: function(name) {
       
   481              return this.traces[name];
       
   482          },
       
   483 
       
   484          /*
       
   485           * Explicitly create and initialize a new trace with the given name.
       
   486           * The optional uri parameter allows to initialize the trace URI.
       
   487           *
       
   488           * If another existed with the same name before, then it is replaced by a new one.
       
   489           */
       
   490          init_trace: function(name, params)
       
   491          {
       
   492              if (window.console) window.console.log("init_trace", params);
       
   493              url = params.url ? params.url : "";
       
   494              requestmode = params.requestmode ? params.requestmode : "POST";
       
   495              syncmode = params.syncmode ? params.syncmode : "none";
       
   496              default_subject = params.default_subject ? params.default_subject : "default";
       
   497              var t = new Trace(url, requestmode);
       
   498              t.set_sync_mode(syncmode);
       
   499              t.set_default_subject(default_subject);
       
   500              this.traces[name] = t;
       
   501              return t;
       
   502          }
       
   503      };
       
   504 
       
   505      var TraceManager = function() {
       
   506          this.traces = {};
       
   507      };
       
   508      TraceManager.prototype = TraceManager_prototype;
       
   509 
       
   510      var tracemanager  = new TraceManager();
       
   511      return tracemanager;
       
   512  };