replicatestorage.js 16.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * JIO extension for resource replication.
 * Copyright (C) 2013  Nexedi SA
 *
 *   This library is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This library is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
Tristan Cavelier's avatar
Tristan Cavelier committed
18

19 20
/*jslint indent: 2, maxlen: 80, nomen: true */
/*global define, module, require, jIO, RSVP */
Tristan Cavelier's avatar
Tristan Cavelier committed
21

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
(function (root, dependencies, factory) {
  "use strict";
  if (typeof define === 'function' && define.amd) {
    return define(dependencies, function () {
      return factory(require);
    });
  }
  if (typeof require === 'function') {
    module.exports = factory(require);
    return;
  }
  root.replicate_storage = factory(function (name) {
    return {
      "jio": jIO,
      "rsvp": RSVP
    }[name];
  });
}(this, ['jio', 'rsvp'], function (require) {
  "use strict";
Tristan Cavelier's avatar
Tristan Cavelier committed
41

42 43
  var Promise = require('rsvp').Promise,
    all = require('rsvp').all,
44 45
    addStorageFunction = require('jio').addStorage,
    uniqueJSONStringify = require('jio').util.uniqueJSONStringify;
46

47 48 49 50 51 52 53
  /**
   * Test if the a value is a date
   *
   * @param  {String,Number,Date} date The date to test
   * @return {Boolean} true if success, else false
   */
  function isDate(date) {
Tristan Cavelier's avatar
Tristan Cavelier committed
54
    return !isNaN((new Date(date === null ? undefined : date)).getTime());
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
  }

  /**
   * Executes a sequence of *then* callbacks. It acts like
   * `smth().then(callback).then(callback)...`. The first callback is called
   * with no parameter.
   *
   * Elements of `then_list` array can be a function or an array contaning at
   * most three *then* callbacks: *onFulfilled*, *onRejected*, *onNotified*.
   *
   * When `cancel()` is executed, each then promises are cancelled at the same
   * time.
   *
   *     sequence(then_list): Promise
   *
   * @param  {Array} then_list An array of *then* callbacks
   * @return {Promise} A new promise
   */
  function sequence(then_list) {
    var promise_list = [];
    return new Promise(function (resolve, reject, notify) {
      var i, length = then_list.length;
      promise_list[0] = new Promise(function (resolve) {
        resolve();
      });
      for (i = 0; i < length; i += 1) {
        if (Array.isArray(then_list[i])) {
          promise_list[i + 1] = promise_list[i].
            then(then_list[i][0], then_list[i][1], then_list[i][2]);
        } else {
          promise_list[i + 1] = promise_list[i].then(then_list[i]);
        }
      }
      promise_list[i].then(resolve, reject, notify);
    }, function () {
      var i, length = promise_list.length;
      for (i = 0; i < length; i += 1) {
        promise_list[i].cancel();
      }
    });
  }

  function success(promise) {
    return new Promise(function (resolve, reject, notify) {
      /*jslint unparam: true*/
      promise.then(resolve, resolve, notify);
    }, function () {
      promise.cancel();
    });
  }

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
  // /**
  //  * Awaits for an answer from one promise only. Promises are cancelled only
  //  * by calling `first(promise_list).cancel()`.
  //  *
  //  *     first(promise_list): Promise
  //  *
  //  * @param  {Array} promise_list An array of promises
  //  * @return {Promise} A new promise
  //  */
  // function first(promise_list) {
  //   var length = promise_list.length;
  //   promise_list = promise_list.slice();
  //   return new Promise(function (resolve, reject, notify) {
  //     var index, count = 0;
  //     function rejecter(answer) {
  //       count += 1;
  //       if (count === length) {
  //         return reject(answer);
  //       }
  //     }
  //     function notifier(index) {
  //       return function (notification) {
  //         notify({
  //           "index": index,
  //           "value": notification
  //         });
  //       };
  //     }
  //     for (index = 0; index < length; index += 1) {
  //       promise_list[index].then(resolve, rejecter, notifier(index));
  //     }
  //   }, function () {
  //     var index;
  //     for (index = 0; index < length; index += 1) {
  //       promise_list[index].cancel();
  //     }
  //   });
  // }
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 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 258 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 297 298 299 300 301 302 303 304 305 306

  /**
   * Responds with the last resolved promise answer recieved. If all promises
   * are rejected, it returns the latest rejected promise answer
   * received. Promises are cancelled only by calling
   * `last(promise_list).cancel()`.
   *
   *     last(promise_list): Promise
   *
   * @param  {Array} promise_list An array of promises
   * @return {Promise} A new promise
   */
  function last(promise_list) {
    var length = promise_list.length;
    promise_list = promise_list.slice();
    return new Promise(function (resolve, reject, notify) {
      var index, last_answer, count = 0, error_count = 0;
      function resolver() {
        return function (answer) {
          count += 1;
          if (count === length) {
            return resolve(answer);
          }
          last_answer = answer;
        };
      }
      function rejecter() {
        return function (answer) {
          error_count += 1;
          if (error_count === length) {
            return reject(answer);
          }
          count += 1;
          if (count === length) {
            return resolve(last_answer);
          }
        };
      }
      function notifier(index) {
        return function (notification) {
          notify({
            "index": index,
            "value": notification
          });
        };
      }
      for (index = 0; index < length; index += 1) {
        promise_list[index].then(resolver(), rejecter(), notifier(index));
      }
    }, function () {
      var index;
      for (index = 0; index < length; index += 1) {
        promise_list[index].cancel();
      }
    });
  }

  /**
   * Responds with the last modified document recieved. If all promises are
   * rejected, it returns the latest rejected promise answer received. Promises
   * are cancelled only by calling `lastModified(promise_list).cancel()`. USE
   * THIS FUNCTION ONLY FOR GET METHOD!
   *
   *     lastModified(promise_list): Promise
   *
   * @param  {Array} promise_list An array of promises
   * @return {Promise} A new promise
   */
  function lastModified(promise_list) {
    var length = promise_list.length;
    promise_list = promise_list.slice();
    return new Promise(function (resolve, reject, notify) {
      var index, last_good_answer, last_answer, count = 0, error_count = 0;
      function resolver(answer) {
        last_answer = answer;
        if (last_good_answer === undefined) {
          if (isDate(answer.data.modified)) {
            last_good_answer = answer;
          }
        } else {
          if (isDate(answer.data.modified)) {
            if (new Date(last_good_answer.data.modified) <
                new Date(answer.data.modified)) {
              last_good_answer = answer;
            }
          }
        }
        count += 1;
        if (count === length) {
          return resolve(last_good_answer);
        }
      }
      function rejecter(answer) {
        error_count += 1;
        if (error_count === length) {
          return reject(answer);
        }
        count += 1;
        if (count === length) {
          return resolve(last_good_answer || last_answer);
        }
      }
      function notifier(index) {
        return function (notification) {
          notify({
            "index": index,
            "value": notification
          });
        };
      }
      for (index = 0; index < length; index += 1) {
        promise_list[index].then(resolver, rejecter, notifier(index));
      }
    }, function () {
      var index;
      for (index = 0; index < length; index += 1) {
        promise_list[index].cancel();
      }
    });
  }

  // /**
  //  * An Universal Unique ID generator
  //  *
  //  * @return {String} The new UUID.
  //  */
  // function generateUuid() {
  //   function S4() {
  //     return ('0000' + Math.floor(
  //       Math.random() * 0x10000 /* 65536 */
  //     ).toString(16)).slice(-4);
  //   }
  //   return S4() + S4() + "-" +
  //     S4() + "-" +
  //     S4() + "-" +
  //     S4() + "-" +
  //     S4() + S4() + S4();
  // }

  function ReplicateStorage(spec) {
    if (!Array.isArray(spec.storage_list)) {
      throw new TypeError("ReplicateStorage(): " +
                          "storage_list is not of type array");
    }
    this._storage_list = spec.storage_list;
  }

  ReplicateStorage.prototype.post = function (command, metadata, option) {
    var promise_list = [], index, length = this._storage_list.length;
    if (!isDate(metadata.modified)) {
      command.error(
        409,
        "invalid 'modified' metadata",
        "The metadata 'modified' should be a valid date string or date object"
      );
      return;
    }
    for (index = 0; index < length; index += 1) {
      promise_list[index] = success(
        command.storage(this._storage_list[index]).post(metadata, option)
      );
    }
    sequence([function () {
307
      return last(promise_list);
308
    }, [command.success, command.error]]);
309
  };
Tristan Cavelier's avatar
Tristan Cavelier committed
310

311 312 313 314 315 316 317 318 319
  ReplicateStorage.prototype.put = function (command, metadata, option) {
    var promise_list = [], index, length = this._storage_list.length;
    if (!isDate(metadata.modified)) {
      command.error(
        409,
        "invalid 'modified' metadata",
        "The metadata 'modified' should be a valid date string or date object"
      );
      return;
320
    }
321 322 323 324 325
    for (index = 0; index < length; index += 1) {
      promise_list[index] =
        command.storage(this._storage_list[index]).put(metadata, option);
    }
    sequence([function () {
326
      return last(promise_list);
327
    }, [command.success, command.error]]);
328
  };
Tristan Cavelier's avatar
Tristan Cavelier committed
329

330 331 332 333 334 335 336 337 338 339
  ReplicateStorage.prototype.putAttachment = function (command, param, option) {
    var promise_list = [], index, length = this._storage_list.length;
    for (index = 0; index < length; index += 1) {
      promise_list[index] = success(
        command.storage(this._storage_list[index]).putAttachment(param, option)
      );
    }
    sequence([function () {
      return last(promise_list);
    }, [command.success, command.error]]);
340 341
  };

342 343 344 345 346 347
  ReplicateStorage.prototype.remove = function (command, param, option) {
    var promise_list = [], index, length = this._storage_list.length;
    for (index = 0; index < length; index += 1) {
      promise_list[index] = success(
        command.storage(this._storage_list[index]).remove(param, option)
      );
348
    }
349
    sequence([function () {
350
      return last(promise_list);
351
    }, [command.success, command.error]]);
352
  };
Tristan Cavelier's avatar
Tristan Cavelier committed
353

354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
  ReplicateStorage.prototype.removeAttachment = function (
    command,
    param,
    option
  ) {
    var promise_list = [], index, length = this._storage_list.length;
    for (index = 0; index < length; index += 1) {
      promise_list[index] = success(
        command.storage(this._storage_list[index]).
          removeAttachment(param, option)
      );
    }
    sequence([function () {
      return last(promise_list);
    }, [command.success, command.error]]);
369
  };
Tristan Cavelier's avatar
Tristan Cavelier committed
370

371 372 373 374 375 376 377 378 379
  ReplicateStorage.prototype.get = function (command, param, option) {
    var promise_list = [], index, length = this._storage_list.length;
    for (index = 0; index < length; index += 1) {
      promise_list[index] =
        command.storage(this._storage_list[index]).get(param, option);
    }
    sequence([function () {
      return lastModified(promise_list);
    }, [command.success, command.error]]);
380
  };
Tristan Cavelier's avatar
Tristan Cavelier committed
381

382 383 384 385 386 387 388 389 390 391
  ReplicateStorage.prototype.getAttachment = function (command, param, option) {
    var promise_list = [], index, length = this._storage_list.length;
    for (index = 0; index < length; index += 1) {
      promise_list[index] = success(
        command.storage(this._storage_list[index]).getAttachment(param, option)
      );
    }
    sequence([function () {
      return last(promise_list);
    }, [command.success, command.error]]);
392
  };
Tristan Cavelier's avatar
Tristan Cavelier committed
393

394
  ReplicateStorage.prototype.allDocs = function (command, param, option) {
395
    /*jslint unparam: true */
396 397 398
    var promise_list = [], index, length = this._storage_list.length;
    for (index = 0; index < length; index += 1) {
      promise_list[index] =
399
        success(command.storage(this._storage_list[index]).allDocs(option));
400 401
    }
    sequence([function () {
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
      return all(promise_list);
    }, function (answers) {
      // merge responses
      var i, j, k, found, rows;
      // browsing answers
      for (i = 0; i < answers.length; i += 1) {
        if (answers[i].result === "success") {
          if (!rows) {
            rows = answers[i].data.rows;
          } else {
            // browsing answer rows
            for (j = 0; j < answers[i].data.rows.length; j += 1) {
              found = false;
              // browsing result rows
              for (k = 0; k < rows.length; k += 1) {
                if (rows[k].id === answers[i].data.rows[j].id) {
                  found = true;
                  break;
                }
              }
              if (!found) {
                rows.push(answers[i].data.rows[j]);
              }
            }
          }
        }
      }
      return {"data": {"total_rows": (rows || []).length, "rows": rows || []}};
430
    }, [command.success, command.error]]);
431
  };
Tristan Cavelier's avatar
Tristan Cavelier committed
432

433 434 435
  ReplicateStorage.prototype.check = function (command, param, option) {
    var promise_list = [], index, length = this._storage_list.length;
    for (index = 0; index < length; index += 1) {
436 437
      promise_list[index] =
        command.storage(this._storage_list[index]).check(param, option);
438
    }
439 440 441
    return all(promise_list).
      then(function () { return; }).
      then(command.success, command.error, command.notify);
442
  };
Tristan Cavelier's avatar
Tristan Cavelier committed
443

444 445 446
  ReplicateStorage.prototype.repair = function (command, param, option) {
    var storage_list = this._storage_list, length = storage_list.length;

447
    if (typeof param._id !== 'string' || !param._id) {
448
      command.error("bad_request");
449 450
      return;
    }
451 452 453 454 455 456 457 458 459 460 461

    storage_list = storage_list.map(function (description) {
      return command.storage(description);
    });

    function repairSubStorages() {
      var promise_list = [], i;
      for (i = 0; i < length; i += 1) {
        promise_list[i] = storage_list[i].repair(param, option);
      }
      return all(promise_list);
462
    }
463 464 465 466 467 468

    function getSubStoragesDocument() {
      var promise_list = [], i;
      for (i = 0; i < length; i += 1) {
        promise_list[i] = success(storage_list[i].get(param));
      }
469
      return all(promise_list);
470 471 472 473 474
    }

    function synchronizeDocument(answers) {
      var i, tmp, winner, winner_str, promise_list = [],
        metadata_dict = {}, not_found_dict = {}, modified_list = [];
475
      for (i = 0; i < answers.length; i += 1) {
476 477 478 479 480 481 482 483
        if (answers[i].result !== "success") {
          not_found_dict[i] = true;
        } else {
          metadata_dict[i] = answers[i].data;
          tmp = metadata_dict[i].modified;
          tmp = new Date(tmp === undefined ? NaN : tmp);
          tmp.index = i;
          modified_list.push(tmp);
484 485
        }
      }
486 487 488 489 490
      modified_list.sort();

      if (modified_list.length === 0) {
        // do nothing because no document was found
        return [];
491
      }
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508

      tmp = modified_list.pop();
      winner = metadata_dict[tmp.index];
      winner_str = uniqueJSONStringify(winner);
      tmp = tmp.index;

      // if no document has valid modified metadata
      // just take the first one and replicate to the other one

      for (i = 0; i < length; i += 1) {
        if (i !== tmp && winner_str !== uniqueJSONStringify(metadata_dict[i])) {
          // console.log("Synchronizing document `" + winner_str +
          //             "` into storage number " + i + " by doing a `" +
          //             (not_found_dict[i] ? "post" : "put") + "`. ");
          promise_list.push(
            storage_list[i][not_found_dict[i] ? "post" : "put"](winner)
          );
509
        }
510 511 512 513 514
      }
      return all(promise_list);
    }

    function checkAnswers(answers) {
515 516 517
      var i;
      for (i = 0; i < answers.length; i += 1) {
        if (answers[i].result !== "success") {
518
          throw answers[i];
519 520
        }
      }
521 522 523 524 525 526 527
    }

    return repairSubStorages().
      then(getSubStoragesDocument).
      then(synchronizeDocument).
      then(checkAnswers).
      then(command.success, command.error, command.notify);
528 529 530 531 532
  };

  addStorageFunction('replicate', ReplicateStorage);

}));