multisplitstorage.js 17.4 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 24 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 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 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 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
/*
 * Copyright 2013, Nexedi SA
 * Released under the LGPL license.
 * http://www.gnu.org/licenses/lgpl.html
 */

/*jslint indent:2, maxlen: 80, nomen: true */
/*global jIO, define, Blob */

/**
 * Provides a split storage for JIO. This storage splits data
 * and store them in the sub storages defined on the description.
 *
 *     {
 *       "type": "split",
 *       "storage_list": [<storage description>, ...]
 *     }
 */
// define([dependencies], module);
(function (dependencies, module) {
  "use strict";
  if (typeof define === 'function' && define.amd) {
    return define(dependencies, module);
  }
  module(jIO);
}(['jio'], function (jIO) {
  "use strict";

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

  /**
   * Select a storage to put the document part
   *
   * @method selectStorage
   * @private
   * @return {Object} The selected storage
   */
  function selectStorage(arg, iteration) {
    var step = iteration % arg.length;
    return arg[step];
  }

  /**
   * Class to merge allDocs responses from several sub storages.
   *
   * @class AllDocsResponseMerger
   * @constructor
   */
  function AllDocsResponseMerger() {

    /**
     * A list of allDocs response.
     *
     * @attribute response_list
     * @type {Array} Contains allDocs responses
     * @default []
     */
    this.response_list = [];
  }
  AllDocsResponseMerger.prototype.constructor = AllDocsResponseMerger;

  /**
   * Add an allDocs response to the response list.
   *
   * @method addResponse
   * @param  {Object} response The allDocs response.
   * @return {AllDocsResponseMerger} This
   */
  AllDocsResponseMerger.prototype.addResponse = function (response) {
    this.response_list.push(response);
    return this;
  };

  /**
   * Add several allDocs responses to the response list.
   *
   * @method addResponseList
   * @param  {Array} response_list An array of allDocs responses.
   * @return {AllDocsResponseMerger} This
   */
  AllDocsResponseMerger.prototype.addResponseList = function (response_list) {
    var i;
    for (i = 0; i < response_list.length; i += 1) {
      this.response_list.push(response_list[i]);
    }
    return this;
  };

  /**
   * Merge the response_list to one allDocs response.
   *
   * The merger will find rows with the same id in order to merge them, thanks
   * to the onRowToMerge method. If no row correspond to an id, rows with the
   * same id will be ignored.
   *
   * @method merge
   * @param  {Object} [option={}] The merge options
   * @param  {Boolean} [option.include_docs=false] Tell the merger to also
   *   merge metadata if true.
   * @return {Object} The merged allDocs response.
   */
  AllDocsResponseMerger.prototype.merge = function (option) {
    var result = [], row, to_merge = [], tmp, i;
    if (this.response_list.length === 0) {
      return [];
    }
    /*jslint ass: true */
    while ((row = this.response_list[0].data.rows.shift()) !== undefined) {
      to_merge[0] = row;
      for (i = 1; i < this.response_list.length; i += 1) {
        to_merge[i] = AllDocsResponseMerger.listPopFromRowId(
          this.response_list[i].data.rows,
          row.id
        );
        if (to_merge[i] === undefined) {
          break;
        }
      }
      tmp = this.onRowToMerge(to_merge, option || {});
      if (tmp !== undefined) {
        result[result.length] = tmp;
      }
    }
    this.response_list = [];
    return {"total_rows": result.length, "rows": result};
  };

  /**
   * This method is called when the merger want to merge several rows with the
   * same id.
   *
   * @method onRowToMerge
   * @param  {Array} row_list An array of rows.
   * @param  {Object} [option={}] The merge option.
   * @param  {Boolean} [option.include_docs=false] Also merge the metadata if
   *   true
   * @return {Object} The merged row
   */
  AllDocsResponseMerger.prototype.onRowToMerge = function (row_list, option) {
    var i, k, new_row = {"value": {}}, data = "";
    option = option || {};
    for (i = 0; i < row_list.length; i += 1) {
      new_row.id = row_list[i].id;
      if (row_list[i].key) {
        new_row.key = row_list[i].key;
      }
      if (option.include_docs) {
        new_row.doc = new_row.doc || {};
        for (k in row_list[i].doc) {
          if (row_list[i].doc.hasOwnProperty(k)) {
            if (k[0] === "_") {
              new_row.doc[k] = row_list[i].doc[k];
            }
          }
        }
        data += row_list[i].doc.data;
      }
    }
    if (option.include_docs) {
      try {
        data = JSON.parse(data);
      } catch (e) { return undefined; }
      for (k in data) {
        if (data.hasOwnProperty(k)) {
          new_row.doc[k] = data[k];
        }
      }
    }
    return new_row;
  };

  /**
   * Search for a specific row and pop it. During the search operation, all
   * parsed rows are stored on a dictionnary in order to be found instantly
   * later.
   *
   * @method listPopFromRowId
   * @param  {Array} rows The row list
   * @param  {String} doc_id The document/row id
   * @return {Object/undefined} The poped row
   */
  AllDocsResponseMerger.listPopFromRowId = function (rows, doc_id) {
    var row;
    if (!rows.dict) {
      rows.dict = {};
    }
    if (rows.dict[doc_id]) {
      row = rows.dict[doc_id];
      delete rows.dict[doc_id];
      return row;
    }
    /*jslint ass: true*/
    while ((row = rows.shift()) !== undefined) {
      if (row.id === doc_id) {
        return row;
      }
      rows.dict[row.id] = row;
    }
  };


  /**
   * The split storage class used by JIO.
   *
   * A split storage instance is able to i/o on several sub storages with
   * split documents.
   *
   * @class SplitStorage
   */
  function SplitStorage(spec) {
    var that = this, priv = {};

    /**
     * The list of sub storages we want to use to store part of documents.
     *
     * @attribute storage_list
     * @private
     * @type {Array} Array of storage descriptions
     */
    priv.storage_list = spec.storage_list;

    //////////////////////////////////////////////////////////////////////
    // Tools

    /**
     * Send a command to all sub storages. All the response are returned
     * in a list. The index of the response correspond to the storage_list
     * index. If an error occurs during operation, the callback is called with
     * `callback(err, undefined)`. The response is given with
     * `callback(undefined, response_list)`.
     *
     * `doc` is the document informations but can also be a list of dedicated
     * document informations. In this case, each document is associated to one
     * sub storage.
     *
     * @method send
     * @private
     * @param  {String} method The command method
     * @param  {Object,Array} doc The document information to send to each sub
     *   storages or a list of dedicated document
     * @param  {Object} option The command option
     * @param  {Function} callback Called at the end
     */
    priv.send = function (command, method, doc, option, callback) {
265
      var i, answer_list = [], failed = false, currentServer;
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
      function onEnd() {
        i += 1;
        if (i === priv.storage_list.length) {
          callback(undefined, answer_list);
        }
      }
      function onSuccess(i) {
        return function (response) {
          if (!failed) {
            answer_list[i] = response;
          }
          onEnd();
        };
      }
      function onError(i) {
        return function (err) {
          if (!failed) {
            failed = true;
            err.index = i;
            callback(err, undefined);
          }
        };
      }

      if (!Array.isArray(doc)) {
        for (i = 0; i < doc.length; i += 1) {
292
          currentServer = selectStorage(priv.storage_list, i, doc.length);
293 294 295 296 297 298 299 300 301 302
          if (method === 'allDocs') {
            command.storage(currentServer)[method](option).
              then(onSuccess(i), onError(i));
          } else {
            command.storage(currentServer)[method](doc, option).
              then(onSuccess(i), onError(i));
          }
        }
      } else {
        for (i = 0; i < doc.length; i += 1) {
303
          currentServer = selectStorage(priv.storage_list, i, doc.length);
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
          // we assume that alldocs is not called if the there is several docs
          command.storage(priv.storage_list[i])[method](doc[i], option).
            then(onSuccess(i), onError(i));
        }
      }

      //default splitstorage method
      /*
      if (!Array.isArray(doc)) {
        for (i = 0; i < priv.storage_list.length; i += 1) {
          if (method === 'allDocs') {
            command.storage(priv.storage_list[i])[method](option).
              then(onSuccess(i), onError(i));
          } else {
            command.storage(priv.storage_list[i])[method](doc, option).
              then(onSuccess(i), onError(i));
          }
        }
      } else {
        for (i = 0; i < priv.storage_list.length; i += 1) {
          // we assume that alldocs is not called if the there is several docs
          command.storage(priv.storage_list[i])[method](doc[i], option).
            then(onSuccess(i), onError(i));
        }
      }
      */


      //re-init
      i = 0;
    };

    /**
     * Split document metadata then store them to the sub storages.
     *
     * @method postOrPut
     * @private
     * @param  {Object} doc A serialized document object
     * @param  {Object} option Command option properties
     * @param  {String} method The command method ('post' or 'put')
     */
    priv.postOrPut = function (command, doc, option, method) {
      var i, data, doc_list = [], doc_underscores = {};
      if (!doc._id) {
        doc._id = generateUuid(); // XXX should let gidstorage guess uid
349
        // in the future, complete id with gidstorage
350 351 352 353 354 355 356 357 358 359
      }
      for (i in doc) {
        if (doc.hasOwnProperty(i)) {
          if (i[0] === "_") {
            doc_underscores[i] = doc[i];
            delete doc[i];
          }
        }
      }
      data = JSON.stringify(doc);
360

361 362 363 364 365 366 367 368 369 370 371 372
      //for (i = 0; i < priv.storage_list.length; i += 1) {
        //doc_list[i] = JSON.parse(JSON.stringify(doc_underscores));
        //doc_list[i].data = data.slice(
          //(data.length / priv.storage_list.length) * i,
          //(data.length / priv.storage_list.length) * (i + 1)
        //);
        //console.info('doc_list[i].data');
        //console.log(doc_list[i].data);
      //}

      for (i = 0; i < 100; i += 1) {
        doc_list[i] = JSON.parse(JSON.stringify(doc_underscores));
373
        doc_list[i]._id = doc_list[i]._id + '_' + i;
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 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
        doc_list[i].data = data.slice(
          (data.length / 100) * i,
          (data.length / 100) * (i + 1)
        );
      }

      priv.send(command, method, doc_list, option, function (err) {
        if (err) {
          err.message = "Unable to " + method + " document";
          delete err.index;
          return command.error(err);
        }
        command.success({"id": doc_underscores._id});
      });
    };

    //////////////////////////////////////////////////////////////////////
    // JIO commands

    /**
     * Split document metadata then store them to the sub storages.
     *
     * @method post
     * @param  {Object} command The JIO command
     */
    that.post = function (command, metadata, option) {
      priv.postOrPut(command, metadata, option, 'post');
    };

    /**
     * Split document metadata then store them to the sub storages.
     *
     * @method put
     * @param  {Object} command The JIO command
     */
    that.put = function (command, metadata, option) {
      priv.postOrPut(command, metadata, option, 'put');
    };

    /**
     * Puts an attachment to the sub storages.
     *
     * @method putAttachment
     * @param  {Object} command The JIO command
     */
    that.putAttachment = function (command, param, option) {
      var i, attachment_list = [], data = param._blob;
      for (i = 0; i < priv.storage_list.length; i += 1) {
        attachment_list[i] = jIO.util.deepClone(param);
        attachment_list[i]._blob = data.slice(
          data.size * i / priv.storage_list.length,
          data.size * (i + 1) / priv.storage_list.length,
          data.type
        );
      }
      priv.send(
        command,
        'putAttachment',
        attachment_list,
        option,
        function (err) {
          if (err) {
            err.message = "Unable to put attachment";
            delete err.index;
            return command.error(err);
          }
          command.success();
        }
      );
    };

    /**
     * Gets splited document metadata then returns real document.
     *
     * @method get
     * @param  {Object} command The JIO command
     */
    that.get = function (command, param, option) {
      var doc = param;
      priv.send(command, 'get', doc, option, function (err, response) {
        var i, k;
        if (err) {
          err.message = "Unable to get document";
          delete err.index;
          return command.error(err);
        }
        doc = '';
        for (i = 0; i < response.length; i += 1) {
          response[i] = response[i].data;
          doc += response[i].data;
        }
        doc = JSON.parse(doc);
        for (i = 0; i < response.length; i += 1) {
          for (k in response[i]) {
            if (response[i].hasOwnProperty(k)) {
              if (k[0] === "_") {
                doc[k] = response[i][k];
              }
            }
          }
        }
        delete doc._attachments;
        for (i = 0; i < response.length; i += 1) {
          if (response[i]._attachments) {
            for (k in response[i]._attachments) {
              if (response[i]._attachments.hasOwnProperty(k)) {
                doc._attachments = doc._attachments || {};
                doc._attachments[k] = doc._attachments[k] || {
                  "length": 0,
                  "content_type": ""
                };
                doc._attachments[k].length += response[i]._attachments[k].
                  length;
                // if (response[i]._attachments[k].digest) {
                //   if (doc._attachments[k].digest) {
                //     doc._attachments[k].digest += " " + response[i].
                //       _attachments[k].digest;
                //   } else {
                //     doc._attachments[k].digest = response[i].
                //       _attachments[k].digest;
                //   }
                // }
                doc._attachments[k].content_type = response[i]._attachments[k].
                  content_type;
              }
            }
          }
        }
        command.success({"data": doc});
      });
    };

    /**
     * Gets splited document attachment then returns real attachment data.
     *
     * @method getAttachment
     * @param  {Object} command The JIO command
     */
    that.getAttachment = function (command, param, option) {
      priv.send(command, 'getAttachment', param, option, function (
        err,
        response
      ) {
        if (err) {
          err.message = "Unable to get attachment";
          delete err.index;
          return command.error(err);
        }

        command.success({"data": new Blob(response.map(function (answer) {
          return answer.data;
        }), {"type": response[0].data.type})});
      });
    };

    /**
     * Removes a document from the sub storages.
     *
     * @method remove
     * @param  {Object} command The JIO command
     */
    that.remove = function (command, param, option) {
      priv.send(
        command,
        'remove',
        param,
        option,
        function (err) {
          if (err) {
            err.message = "Unable to remove document";
            delete err.index;
            return command.error(err);
          }
          command.success();
        }
      );
    };

    /**
     * Removes an attachment from the sub storages.
     *
     * @method removeAttachment
     * @param  {Object} command The JIO command
     */
    that.removeAttachment = function (command, param, option) {
      priv.send(
        command,
        'removeAttachment',
        param,
        option,
        function (err) {
          if (err) {
            err.message = "Unable to remove attachment";
            delete err.index;
            return command.error(err);
          }
          command.success();
        }
      );
    };

    /**
     * Retreive a list of all document in the sub storages.
     *
     * If include_docs option is false, then it returns the document list from
     * the first sub storage. Else, it will merge results and return.
     *
     * @method allDocs
     * @param  {Object} command The JIO command
     */
    that.allDocs = function (command, param, option) {
      option = {"include_docs": option.include_docs};
      priv.send(
        command,
        'allDocs',
        param,
        option,
        function (err, response_list) {
          var all_docs_merger;
          if (err) {
            err.message = "Unable to retrieve document list";
            delete err.index;
            return command.error(err);
          }
          all_docs_merger = new AllDocsResponseMerger();
          all_docs_merger.addResponseList(response_list);
          return command.success({"data": all_docs_merger.merge(option)});
        }
      );
    };

  } // end of splitStorage

  jIO.addStorage('split', SplitStorage);
}));