replicaterevisionstorage.js 21.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*jslint indent: 2, maxlen: 80, nomen: true */
/*global jIO: true */
/**
 * JIO Replicate Revision Storage.
 * It manages storages that manage revisions and conflicts.
 * Description:
 * {
 *     "type": "replicaterevision",
 *     "storage_list": [
 *         <sub storage description>,
 *         ...
 *     ]
 * }
 */
jIO.addStorageType('replicaterevision', function (spec, my) {
  "use strict";
  var that, priv = {};
  spec = spec || {};
  that = my.basicStorage(spec, my);

  priv.storage_list_key = "storage_list";
  priv.storage_list = spec[priv.storage_list_key];
  my.env = my.env || spec.env || {};
24
  priv.emptyFunction = function () {};
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

  that.specToStore = function () {
    var o = {};
    o[priv.storage_list_key] = priv.storage_list;
    o.env = my.env;
    return o;
  };

  /**
   * Generate a new uuid
   * @method generateUuid
   * @return {string} The new uuid
   */
  priv.generateUuid = function () {
    var S4 = function () {
      var i, string = Math.floor(
        Math.random() * 0x10000 /* 65536 */
      ).toString(16);
      for (i = string.length; i < 4; i += 1) {
        string = "0" + string;
      }
      return string;
    };
    return S4() + S4() + "-" +
      S4() + "-" +
      S4() + "-" +
      S4() + "-" +
      S4() + S4() + S4();
  };

  /**
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
   * Create an array containing dictionnary keys
   * @method dictKeys2Array
   * @param  {object} dict The object to convert
   * @return {array} The array of keys
   */
  priv.dictKeys2Array = function (dict) {
    var k, newlist = [];
    for (k in dict) {
      if (dict.hasOwnProperty(k)) {
        newlist.push(k);
      }
    }
    return newlist;
  };

  /**
   * Generates the next revision
   * @method generateNextRevision
   * @param  {number|string} previous_revision The previous revision
   * @param  {string} docid The document id
76 77
   * @return {string} The next revision
   */
78
  priv.generateNextRevision = function (previous_revision, docid) {
79
    my.env[docid].id += 1;
80 81 82 83
    if (typeof previous_revision === "string") {
      previous_revision = parseInt(previous_revision.split("-")[0], 10);
    }
    return (previous_revision + 1) + "-" + my.env[docid].id.toString();
84 85 86 87 88 89 90 91 92
  };

  /**
   * Checks a revision format
   * @method checkRevisionFormat
   * @param  {string} revision The revision string
   * @return {boolean} True if ok, else false
   */
  priv.checkRevisionFormat = function (revision) {
93
    return (/^[0-9]+-[0-9a-zA-Z_]+$/.test(revision));
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
  };

  /**
   * Initalize document environment object
   * @method initEnv
   * @param  {string} docid The document id
   * @return {object} The reference to the environment
   */
  priv.initEnv = function (docid) {
    my.env[docid] = {
      "id": 0,
      "distant_revisions": {},
      "my_revisions": {},
      "last_revisions": []
    };
    return my.env[docid];
  };

112 113 114 115 116 117 118 119 120 121 122 123 124
  priv.updateEnv = function (doc_env, doc_env_rev, index, doc_rev) {
    doc_env.last_revisions[index] = doc_rev;
    if (doc_rev !== undefined) {
      if (!doc_env.my_revisions[doc_env_rev]) {
        doc_env.my_revisions[doc_env_rev] = [];
        doc_env.my_revisions[doc_env_rev].length = priv.storage_list.length;
      }
      doc_env.my_revisions[doc_env_rev][index] = doc_rev;
      doc_env.distant_revisions[doc_rev] = doc_env_rev;
    }
  };

  /**
125 126 127 128
   * Clones an object in deep (without functions)
   * @method clone
   * @param  {any} object The object to clone
   * @return {any} The cloned object
129 130 131 132 133 134 135 136 137
   */
  priv.clone = function (object) {
    var tmp = JSON.stringify(object);
    if (tmp === undefined) {
      return undefined;
    }
    return JSON.parse(tmp);
  };

138 139 140 141 142 143 144 145 146 147 148 149 150
  /**
   * Like addJob but also return the method and the index of the storage
   * @method send
   * @param  {string} method The request method
   * @param  {number} index The storage index
   * @param  {object} doc The document object
   * @param  {object} option The request object
   * @param  {function} callback The callback. Parameters:
   * - {string} The request method
   * - {number} The storage index
   * - {object} The error object
   * - {object} The response object
   */
151 152
  priv.send = function (method, index, doc, option, callback) {
    var wrapped_callback_success, wrapped_callback_error;
153
    callback = callback || priv.emptyFunction;
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    wrapped_callback_success = function (response) {
      callback(method, index, undefined, response);
    };
    wrapped_callback_error = function (err) {
      callback(method, index, err, undefined);
    };
    that.addJob(
      method,
      priv.storage_list[index],
      doc,
      option,
      wrapped_callback_success,
      wrapped_callback_error
    );
  };

170 171 172 173 174 175 176 177 178 179 180 181 182
  /**
   * Use "send" method to all sub storages.
   * Calling "callback" for each storage response.
   * @method sendToAll
   * @param  {string} method The request method
   * @param  {object} doc The document object
   * @param  {object} option The request option
   * @param  {function} callback The callback. Parameters:
   * - {string} The request method
   * - {number} The storage index
   * - {object} The error object
   * - {object} The response object
   */
183 184 185 186 187 188 189
  priv.sendToAll = function (method, doc, option, callback) {
    var i;
    for (i = 0; i < priv.storage_list.length; i += 1) {
      priv.send(method, i, doc, option, callback);
    }
  };

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
////////////////////////////////////////////////////////////////////////////////
  that.check = function (command) {
    priv.check(
      command.cloneDoc(),
      command.cloneOption(),
      that.success,
      that.error
    );
  };
  that.repair = function (command) {
    priv.repair(
      command.cloneDoc(),
      command.cloneOption(),
      true,
      that.success,
      that.error
    );
  };
  priv.check = function (doc, option, success, error) {
    priv.repair(doc, option, false, success, error);
  };
  priv.repair = function (doc, option, repair, callback) {
    var functions = {};
    callback = callback || priv.emptyFunction;
    option = option || {};
    functions.begin = function () {
      functions.getAllDocuments(functions.newParam(
        doc,
        option,
        repair
      ));
    };
    functions.newParam = function (doc, option, repair) {
      var param = {
        "doc": doc,
        "option": option,
        "repair": repair,
        "responses": {
          "count": 0,
          "list": [
            // 0: response0
            // 1: response1
            // 2: response2
          ],
          "stats": {
            // responseA: [0, 1]
            // responseB: [2]
          },
          "stats_items": [
            // 0: [responseA, [0, 1]]
            // 1: [responseB, [2]]
          ]
        },
        "conflicts": {
          // revC: true
          // revD: true
        },
        "deal_result_state": "ok",
        "my_rev": undefined
      };
      param.responses.list.length = priv.storage_list.length;
      return param;
    };
    functions.getAllDocuments = function (param) {
      var i, doc = priv.clone(param.doc), option = priv.clone(param.option);
      option.conflicts = true;
      option.revs = true;
      option.revs_info = true;
258
      option.repair = false;
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
      for (i = 0; i < priv.storage_list.length; i += 1) {
        // if the document is not loaded
        priv.send("get", i, doc, option, functions.dealResults(param));
      }
      functions.finished_count += 1;
    };
    functions.dealResults = function (param) {
      return function (method, index, err, response) {
        if (param.deal_result_state !== "ok") {
          // deal result is in a wrong state, exit
          return;
        }
        if (err) {
          if (err.status !== 404) {
            // get document failed, exit
            param.deal_result_state = "error";
            callback({
              "status": 40,
              "statusText": "Check Failed",
              "error": "check_failed",
              "message": "An error occured on the sub storage",
              "reason": err.reason
            });
            return;
          }
        }
        // success to get the document
        // add the response in memory
        param.responses.count += 1;
        param.responses.list[index] = response;

        // add the conflicting revision for other synchronizations
        functions.addConflicts(param, (response || {})._conflicts);
        if (param.responses.count !== param.responses.list.length) {
          // this is not the last response, wait for the next response
          return;
        }

297
        // this is now the last response
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
        functions.makeResponsesStats(param.responses);
        if (param.responses.stats_items.length === 1) {
          // the responses are equals!
          callback(undefined, {
            "ok": true,
            "id": param.doc._id,
            "rev": (typeof param.responses.list[0] === "object" ?
                    param.responses.list[0]._rev : undefined)
          });
          return;
        }
        // the responses are different
        if (param.repair === false) {
          // do not repair
          callback({
            "status": 41,
            "statusText": "Check Not Ok",
            "error": "check_not_ok",
            "message": "Some documents are different in the sub storages",
            "reason": "Storage contents differ"
          });
          return;
        }
        // repair
        functions.synchronizeAllSubStorage(param);
        if (param.option.synchronize_conflicts !== false) {
          functions.synchronizeConflicts(param);
        }
      };
    };
    functions.addConflicts = function (param, list) {
      var i;
      list = list || [];
      for (i = 0; i < list.length; i += 1) {
        param.conflicts[list[i]] = true;
      }
    };
    functions.makeResponsesStats = function (responses) {
      var i, str_response;
      for (i = 0; i < responses.count; i += 1) {
        str_response = JSON.stringify(responses.list[i]);
        if (responses.stats[str_response] === undefined) {
          responses.stats[str_response] = [];
          responses.stats_items.push([
            str_response,
            responses.stats[str_response]
          ]);
        }
        responses.stats[str_response].push(i);
      }
    };
    functions.synchronizeAllSubStorage = function (param) {
      var i, j, len = param.responses.stats_items.length;
      for (i = 0; i < len; i += 1) {
        // browsing responses
        for (j = 0; j < len; j += 1) {
          // browsing storage list
          if (i !== j) {
            functions.synchronizeResponseToSubStorage(
              param,
              param.responses.stats_items[i][0],
              param.responses.stats_items[j][1]
            );
          }
        }
      }
      functions.finished_count -= 1;
    };
    functions.synchronizeResponseToSubStorage = function (
      param,
      response,
      storage_list
    ) {
      var i, new_doc;
      if (response === undefined) {
        // no response to sync
        return;
      }
      for (i = 0; i < storage_list.length; i += 1) {
        new_doc = JSON.parse(response);
        new_doc._revs = new_doc._revisions;
        delete new_doc._rev;
        delete new_doc._revisions;
        delete new_doc._conflicts;
        functions.finished_count += 1;
        priv.send(
          "put",
          storage_list[i],
          new_doc,
          param.option,
          functions.finished
        );
      }
    };
    functions.synchronizeConflicts = function (param) {
      var rev, new_doc, new_option;
      new_option = priv.clone(param.option);
      new_option.synchronize_conflict = false;
      for (rev in param.conflicts) {
        if (param.conflicts.hasOwnProperty(rev)) {
          new_doc = priv.clone(param.doc);
          new_doc._rev = rev;
          // no need to synchronize all the conflicts again, do it once
          functions.getAllDocuments(functions.newParam(
            new_doc,
            new_option,
            param.repair
          ));
        }
      }
    };
    functions.finished_count = 0;
    functions.finished = function () {
      functions.finished_count -= 1;
      if (functions.finished_count === 0) {
        callback(undefined, {"ok": true, "id": doc._id});
      }
    };
    functions.begin();
  };

////////////////////////////////////////////////////////////////////////////////
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
  /**
   * Post the document metadata to all sub storages
   * @method post
   * @param  {object} command The JIO command
   */
  that.post = function (command) {
    var functions = {}, doc_env, revs_info, doc, my_rev;
    functions.begin = function () {
      doc = command.cloneDoc();

      if (typeof doc._rev === "string" && !priv.checkRevisionFormat(doc._rev)) {
        that.error({
          "status": 31,
          "statusText": "Wrong Revision Format",
          "error": "wrong_revision_format",
          "message": "The document previous revision does not match " +
            "^[0-9]+-[0-9a-zA-Z]+$",
          "reason": "Previous revision is wrong"
        });
        return;
      }
      if (typeof doc._id !== "string") {
        doc._id = priv.generateUuid();
      }
444 445
      if (priv.post_allowed === undefined) {
        priv.post_allowed = true;
446 447
      }
      doc_env = my.env[doc._id];
Tristan Cavelier's avatar
Tristan Cavelier committed
448
      if (!doc_env || !doc_env.id) {
449 450
        doc_env = priv.initEnv(doc._id);
      }
451
      my_rev = priv.generateNextRevision(doc._rev || 0, doc._id);
452 453 454
      functions.sendDocument();
    };
    functions.sendDocument = function () {
455
      var i, cloned_doc;
456
      for (i = 0; i < priv.storage_list.length; i += 1) {
457
        cloned_doc = priv.clone(doc);
458 459 460 461 462 463
        if (typeof cloned_doc._rev === "string" &&
            doc_env.my_revisions[cloned_doc._rev] !== undefined) {
          cloned_doc._rev = doc_env.my_revisions[cloned_doc._rev][i];
        }
        priv.send(
          doc_env.last_revisions[i] === "unique_" + i ||
464
            priv.put_only ? "put" : "post",
465
          i,
466 467
          cloned_doc,
          command.cloneOption(),
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
          functions.checkSendResult
        );
      }
    };
    functions.checkSendResult = function (method, index, err, response) {
      if (err) {
        if (err.status === 409) {
          if (method !== "put") {
            functions.sendDocumentIndex(
              "put",
              index,
              functions.checkSendResult
            );
            return;
          }
        }
484
        priv.updateEnv(doc_env, my_rev, index, null);
485 486 487 488
        functions.error(err);
        return;
      }
      // success
489 490 491 492 493 494
      priv.updateEnv(
        doc_env,
        my_rev,
        index,
        response.rev || "unique_" + index
      );
495 496 497
      functions.success({"ok": true, "id": doc._id, "rev": my_rev});
    };
    functions.success = function (response) {
498 499
      // can be called once
      that.success(response);
500
      functions.success = priv.emptyFunction;
501 502 503 504 505 506
    };
    functions.error_count = 0;
    functions.error = function (err) {
      functions.error_count += 1;
      if (functions.error_count === priv.storage_list.length) {
        that.error(err);
507
        functions.error = priv.emptyFunction;
508 509
      }
    };
510 511 512 513
    functions.begin();
  };

  /**
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
   * Put the document metadata to all sub storages
   * @method put
   * @param  {object} command The JIO command
   */
  that.put = function (command) {
    priv.put_only = true;
    that.post(command);
  };

  /**
   * Put an attachment to a document to all sub storages
   * @method putAttachment
   * @param  {object} command The JIO command
   */
  // that.putAttachment = function (command) {

  // };

  /**
   * Get the document or attachment from all sub storages, get the fastest.
534 535 536 537
   * @method get
   * @param  {object} command The JIO command
   */
  that.get = function (command) {
538
    var functions = {}, doc_env, doc, my_rev, revs_array = [];
539
    functions.begin = function () {
540 541
      var i;
      doc = command.cloneDoc();
542

543
      doc_env = my.env[doc._id];
544 545
      if (!doc_env || !doc_env.id) {
        // document environment is not set
546
        doc_env = priv.initEnv(doc._id);
547 548 549
      }
      // document environment is set now
      revs_array.length = priv.storage_list.length;
550
      my_rev = doc._rev;
551 552 553 554 555 556 557
      if (my_rev) {
        functions.update_env = false;
      }
      for (i = 0; i < priv.storage_list.length; i += 1) {
        // request all sub storages
        if (doc_env.my_revisions[my_rev]) {
          // if my_rev exist, convert it to distant revision
558
          doc._rev = doc_env.my_revisions[my_rev][i];
559
        }
560
        priv.send("get", i, doc, command.cloneOption(), functions.callback);
561 562
      }
    };
563
    functions.update_env = true;
564 565
    functions.callback = function (method, index, err, response) {
      if (err) {
566
        revs_array[index] = null;
567 568 569
        functions.error(err);
        return;
      }
570 571 572 573 574 575 576 577 578 579 580
      doc_env.last_revisions[index] = response._rev || "unique_" + index;
      revs_array[index] = response._rev || "unique_" + index;
      if (doc_env.distant_revisions[response._rev || "unique_" + index]) {
        // the document revision is already known
        if (functions.update_env === true) {
          my_rev = doc_env.distant_revisions[response._rev ||
                                             "unique_" + index];
        }
      } else {
        // the document revision is unknown
        if (functions.update_env === true) {
581
          my_rev = priv.generateNextRevision(0, doc._id);
582 583 584 585 586 587
          doc_env.my_revisions[my_rev] = revs_array;
          doc_env.distant_revisions[response._rev || "unique_" + index] =
            my_rev;
        }
        functions.update_env = false;
      }
588 589 590 591
      response._rev = my_rev;
      functions.success(response);
    };
    functions.success = function (response) {
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
      var i, start, tmp, tmp_object;
      functions.success = priv.emptyFunction;
      if (doc_env.my_revisions[my_rev]) {
        // this was not a specific revision
        // we can convert revisions recieved by the sub storage
        if (response._conflicts) {
          // convert conflicting revisions to replicate revisions
          tmp_object = {};
          for (i = 0; i < response._conflicts.length; i += 1) {
            tmp_object[doc_env.distant_revisions[response._conflicts[i]] ||
                       response._conflicts[i]] = true;
          }
          response._conflicts = priv.dictKeys2Array(tmp_object);
        }
        if (response._revisions) {
          // convert revisions history to replicate revisions
          tmp_object = {};
          start = response._revisions.start;
          for (i = 0; i < response._revisions.ids.length; i += 1, start -= 1) {
Tristan Cavelier's avatar
Tristan Cavelier committed
611 612 613
            tmp = doc_env.distant_revisions[
              start + "-" + response._revisions.ids[i]
            ];
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
            if (tmp) {
              response._revisions.ids[i] = tmp.split("-").slice(1).join("-");
            }
          }
        }
        if (response._revs_info) {
          // convert revs info to replicate revisions
          for (i = 0; i < response._revs_info.length; i += 1) {
            tmp = doc_env.distant_revisions[response._revs_info[i].rev];
            if (tmp) {
              response._revs_info[i].rev = tmp;
            }
          }
        }
      }
629
      that.success(response);
630 631 632 633 634
      if (command.getOption("repair") === true) {
        setTimeout(function () {
          priv.repair({"_id": doc._id}, command.cloneOption(), true);
        });
      }
635
    };
636 637 638 639 640
    functions.error_count = 0;
    functions.error = function (err) {
      functions.error_count += 1;
      if (functions.error_count === priv.storage_list.length) {
        that.error(err);
641
        functions.error = priv.emptyFunction;
642 643 644 645 646
      }
    };
    functions.begin();
  };

647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
  /**
   * Remove the document or attachment from all sub storages.
   * @method remove
   * @param  {object} command The JIO command
   */
  that.remove = function (command) {
    var functions = {}, doc_env, revs_info, doc, my_rev;
    functions.begin = function () {
      doc = command.cloneDoc();

      if (typeof doc._rev === "string" && !priv.checkRevisionFormat(doc._rev)) {
        that.error({
          "status": 31,
          "statusText": "Wrong Revision Format",
          "error": "wrong_revision_format",
          "message": "The document previous revision does not match " +
            "^[0-9]+-[0-9a-zA-Z]+$",
          "reason": "Previous revision is wrong"
        });
        return;
      }
      doc_env = my.env[doc._id];
      if (!doc_env || !doc_env.id) {
        doc_env = priv.initEnv(doc._id);
      }
      my_rev = priv.generateNextRevision(doc._rev || 0, doc._id);
      functions.sendDocument();
    };
    functions.sendDocument = function () {
      var i, cloned_doc;
      for (i = 0; i < priv.storage_list.length; i += 1) {
        cloned_doc = priv.clone(doc);
        if (typeof cloned_doc._rev === "string" &&
            doc_env.my_revisions[cloned_doc._rev] !== undefined) {
          cloned_doc._rev = doc_env.my_revisions[cloned_doc._rev][i];
        }
        priv.send(
          "remove",
          i,
          cloned_doc,
          command.cloneOption(),
          functions.checkSendResult
        );
      }
      that.end();
    };
    functions.checkSendResult = function (method, index, err, response) {
      if (err) {
        priv.updateEnv(doc_env, my_rev, index, null);
        functions.error(err);
        return;
      }
      // success
      priv.updateEnv(
        doc_env,
        my_rev,
        index,
        response.rev || "unique_" + index
      );
      functions.success({"ok": true, "id": doc._id, "rev": my_rev});
    };
    functions.success = function (response) {
      // can be called once
      that.success(response);
      functions.success = priv.emptyFunction;
    };
    functions.error_count = 0;
    functions.error = function (err) {
      functions.error_count += 1;
      if (functions.error_count === priv.storage_list.length) {
        that.error(err);
        functions.error = priv.emptyFunction;
      }
    };
    functions.begin();
  };

724 725
  return that;
});