gidstorage.js 18.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
 * JIO extension for resource global identifier management.
 * 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/>.
 */

/*jslint indent: 2, maxlen: 80, sloppy: true, nomen: true */
20
/*global define, jIO, setTimeout */
21 22 23

/**
 * JIO GID Storage. Type = 'gid'.
24
 * Identifies document with their global identifier representation
25
 *
26
 * Sub storages must support complex queries and include_docs options.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
 *
 * Storage Description:
 *
 *     {
 *       "type": "gid",
 *       "sub_storage": {<storage description>},
 *       "constraints": {
 *         "default": {
 *           "identifier": "list",    // ['a', 1]
 *           "type": "DCMIType",      // 'Text'
 *           "title": "string"        // 'something blue'
 *         },
 *         "Text": {
 *           "format": "contentType"  // contains 'text/plain;charset=utf-8'
 *         },
 *         "Image": {
 *           "version": "json"        // value as is
 *         }
 *       }
 *     }
 */
48 49 50 51 52 53 54 55 56
// define([module_name], [dependencies], module);
(function (dependencies, module) {
  "use strict";
  if (typeof define === 'function' && define.amd) {
    return define(dependencies, module);
  }
  module(jIO);
}(['jio'], function (jIO) {
  "use strict";
57

Tristan Cavelier's avatar
Tristan Cavelier committed
58
  var dcmi_types, metadata_actions, content_type_re;
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
  dcmi_types = {
    'Collection': 'Collection',
    'Dataset': 'Dataset',
    'Event': 'Event',
    'Image': 'Image',
    'InteractiveResource': 'InteractiveResource',
    'MovingImage': 'MovingImage',
    'PhysicalObject': 'PhysicalObject',
    'Service': 'Service',
    'Software': 'Software',
    'Sound': 'Sound',
    'StillImage': 'StillImage',
    'Text': 'Text'
  };
  metadata_actions = {
74 75 76
    /**
     * Returns the metadata value
     */
77 78 79
    json: function (value) {
      return value;
    },
80
    /**
81
     * Returns the metadata if there is a string
82
     */
83
    string: function (value) {
84 85 86 87
      if (!Array.isArray(value)) {
        if (typeof value === 'object') {
          return value.content;
        }
88 89 90
        return value;
      }
    },
91 92 93
    /**
     * Returns the metadata in a array format
     */
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    list: function (value) {
      var i, new_value = [];
      if (Array.isArray(value)) {
        for (i = 0; i < value.length; i += 1) {
          if (typeof value[i] === 'object') {
            new_value[new_value.length] = value[i].content;
          } else {
            new_value[new_value.length] = value[i];
          }
        }
      } else if (value !== undefined) {
        value = [value];
      }
      return value;
    },
109
    /**
110
     * Returns the metadata if there is a string equal to a DCMIType
111
     */
112
    DCMIType: function (value) {
113 114 115 116 117 118 119
      var i;
      if (!Array.isArray(value)) {
        value = [value];
      }
      for (i = 0; i < value.length; i += 1) {
        if (typeof value[i] === 'object' && dcmi_types[value[i].content]) {
          return value[i].content;
Tristan Cavelier's avatar
Tristan Cavelier committed
120 121
        }
        if (dcmi_types[value[i]]) {
122 123 124
          return value[i];
        }
      }
125
    },
126 127 128
    /**
     * Returns the metadata content type if exist
     */
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    contentType: function (value) {
      var i;
      if (!Array.isArray(value)) {
        value = [value];
      }
      for (i = 0; i < value.length; i += 1) {
        if (value[i] === 'object') {
          if (content_type_re.test(value[i].content)) {
            return value[i].content;
          }
        } else {
          if (content_type_re.test(value[i])) {
            return value[i];
          }
        }
      }
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
    },
    /**
     * Returns the metadata if it is a date
     */
    date: function (value) {
      var d;
      if (!Array.isArray(value)) {
        if (typeof value === 'object') {
          d = new Date(value.content);
          value = value.content;
        } else {
          d = new Date(value);
        }
      }
      if (Object.prototype.toString.call(d) === "[object Date]") {
        if (!isNaN(d.getTime())) {
          return value;
        }
      }
164 165 166 167 168
    }
  };
  content_type_re =
    /^([a-z]+\/[a-zA-Z0-9\+\-\.]+)(?:\s*;\s*charset\s*=\s*([a-zA-Z0-9\-]+))?$/;

169 170 171 172 173 174 175 176
  /**
   * Creates a gid from metadata and constraints.
   *
   * @param  {Object} metadata The metadata to use
   * @param  {Object} constraints The constraints
   * @return {String} The gid or undefined if metadata doesn't respect the
   *   constraints
   */
177
  function gidFormat(metadata, constraints) {
178 179 180
    var types, i, j, meta_key, result = [], tmp, constraint, actions;
    types = (metadata_actions.list(metadata.type) || []).slice();
    types.unshift('default');
181
    for (i = 0; i < types.length; i += 1) {
182 183 184 185 186 187
      constraint = constraints[types[i]];
      for (meta_key in constraint) {
        if (constraint.hasOwnProperty(meta_key)) {
          actions = constraint[meta_key];
          if (!Array.isArray(actions)) {
            actions = [actions];
188
          }
189 190 191 192 193 194 195 196 197
          for (j = 0; j < actions.length; j += 1) {
            tmp = metadata_actions[
              actions[j]
            ](metadata[meta_key]);
            if (tmp === undefined) {
              return;
            }
          }
          result[result.length] = [meta_key, tmp];
198 199 200
        }
      }
    }
201 202 203 204 205 206 207 208 209
    // sort dict keys to make gid universal
    result.sort(function (a, b) {
      return a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0;
    });
    tmp = {};
    for (i = 0; i < result.length; i += 1) {
      tmp[result[i][0]] = result[i][1];
    }
    return JSON.stringify(tmp);
210 211
  }

212 213 214 215 216 217 218
  /**
   * Convert a gid to a complex query.
   *
   * @param  {Object,String} gid The gid
   * @param  {Object} constraints The constraints
   * @return {Object} A complex serialized object
   */
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
  function gidToComplexQuery(gid, contraints) {
    var k, i, result = [], meta, content;
    if (typeof gid === 'string') {
      gid = JSON.parse(gid);
    }
    for (k in gid) {
      if (gid.hasOwnProperty(k)) {
        meta = gid[k];
        if (!Array.isArray(meta)) {
          meta = [meta];
        }
        for (i = 0; i < meta.length; i += 1) {
          content = meta[i];
          if (typeof content === 'object') {
            content = content.content;
          }
          result[result.length] = {
            "type": "simple",
            "operator": "=",
            "key": k,
            "value": content
          };
        }
      }
    }
    return {
      "type": "complex",
      "operator": "AND",
      "query_list": result
    };
  }

251 252 253 254 255 256 257
  /**
   * Parse the gid and returns a metadata object containing gid keys and values.
   *
   * @param  {String} gid The gid to convert
   * @param  {Object} constraints The constraints
   * @return {Object} The gid metadata
   */
258 259 260 261 262 263 264 265 266 267 268 269 270
  function gidParse(gid, constraints) {
    var object;
    try {
      object = JSON.parse(gid);
    } catch (e) {
      return;
    }
    if (gid !== gidFormat(object, constraints)) {
      return;
    }
    return object;
  }

271 272 273 274 275 276 277 278 279 280
  /**
   * The gid storage used by JIO.
   *
   * This storage change the id of a document with its global id. A global id
   * is representation of a document metadata used to define it as uniq. The way
   * to generate global ids can be define in the storage description. It allows
   * us use duplicating storage with different sub storage kind.
   *
   * @class gidStorage
   */
281 282
  function gidStorage(spec, my) {
    var that = my.basicStorage(spec, my), priv = {};
283

284 285 286
    priv.sub_storage = spec.sub_storage;
    priv.constraints = spec.constraints || {
      "default": {
287 288
        "type": "DCMIType",
        "title": "string"
289 290 291
      }
    };

292 293
    // Overrides

294 295 296 297 298 299 300
    that.specToStore = function () {
      return {
        "sub_storage": priv.sub_storage,
        "constraints": priv.constraints
      };
    };

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    // JIO Commands

    /**
     * Generic command for post or put one.
     *
     * This command will check if the document already exist with an allDocs
     * and a complex query. If exist, then post will fail. Put will update the
     * retrieved document thanks to its real id. If no documents are found, post
     * and put will create a new document with the sub storage id generator.
     *
     * @method putOrPost
     * @private
     * @param  {Command} command The JIO command
     * @param  {String} method The command method
     */
316
    priv.putOrPost = function (command, method) {
317 318 319 320 321
      setTimeout(function () {
        var gid, complex_query, doc = command.cloneDoc();
        gid = gidFormat(doc, priv.constraints);
        if (gid === undefined || (doc._id && gid !== doc._id)) {
          return that.error({
322 323 324
            "status": 400,
            "statusText": "Bad Request",
            "error": "bad_request",
325
            "message": "Cannot " + method + " document",
326 327 328 329 330 331 332 333
            "reason": "metadata should respect constraints"
          });
        }
        complex_query = gidToComplexQuery(gid);
        that.addJob('allDocs', priv.sub_storage, {}, {
          "query": complex_query,
          "wildcard_character": null
        }, function (response) {
334
          var update_method = method;
335
          if (response.total_rows !== 0) {
336 337 338 339 340
            if (method === 'post') {
              return that.error({
                "status": 409,
                "statusText": "Conflict",
                "error": "conflict",
341
                "message": "Cannot " + method + " document",
342 343 344
                "reason": "Document already exist"
              });
            }
345 346
            doc = command.cloneDoc();
            doc._id = response.rows[0].id;
347 348 349 350
          } else {
            doc = command.cloneDoc();
            delete doc._id;
            update_method = 'post';
351
          }
352
          that.addJob(update_method, priv.sub_storage, doc, {
353 354 355 356
          }, function (response) {
            response.id = gid;
            that.success(response);
          }, function (err) {
357
            err.message = "Cannot " + method + " document";
358 359 360
            that.error(err);
          });
        }, function (err) {
361
          err.message = "Cannot " + method + " document";
362 363 364 365 366
          that.error(err);
        });
      });
    };

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 420 421 422 423 424
    /**
     * Generic command for putAttachment, getAttachment or removeAttachment.
     *
     * This command will check if the document exist with an allDocs and a
     * complex query. If not exist, then it returns 404. Otherwise the
     * action will be done on the attachment of the found document.
     *
     * @method putGetOrRemoveAttachment
     * @private
     * @param  {Command} command The JIO command
     * @param  {String} method The command method
     */
    priv.putGetOrRemoveAttachment = function (command, method) {
      setTimeout(function () {
        var gid_object, complex_query, doc = command.cloneDoc();
        gid_object = gidParse(doc._id, priv.constraints);
        if (gid_object === undefined) {
          return that.error({
            "status": 400,
            "statusText": "Bad Request",
            "error": "bad_request",
            "message": "Cannot " + method + " attachment",
            "reason": "metadata should respect constraints"
          });
        }
        complex_query = gidToComplexQuery(gid_object);
        that.addJob('allDocs', priv.sub_storage, {}, {
          "query": complex_query,
          "wildcard_character": null
        }, function (response) {
          if (response.total_rows === 0) {
            return that.error({
              "status": 404,
              "statusText": "Not Found",
              "error": "not_found",
              "message": "Cannot " + method + " attachment",
              "reason": "Document already exist"
            });
          }
          gid_object = doc._id;
          doc._id = response.rows[0].id;
          that.addJob(method + "Attachment", priv.sub_storage, doc, {
          }, function (response) {
            if (method !== 'get') {
              response.id = gid_object;
            }
            that.success(response);
          }, function (err) {
            err.message = "Cannot " + method + " attachment";
            that.error(err);
          });
        }, function (err) {
          err.message = "Cannot " + method + " attachment";
          that.error(err);
        });
      });
    };

425 426 427 428 429 430
    /**
     * See {{#crossLink "gidStorage/putOrPost:method"}}{{/#crossLink}}.
     *
     * @method post
     * @param  {Command} command The JIO command
     */
431 432 433 434
    that.post = function (command) {
      priv.putOrPost(command, 'post');
    };

435 436 437 438 439 440
    /**
     * See {{#crossLink "gidStorage/putOrPost:method"}}{{/#crossLink}}.
     *
     * @method put
     * @param  {Command} command The JIO command
     */
441 442 443 444
    that.put = function (command) {
      priv.putOrPost(command, 'put');
    };

445 446 447 448 449 450 451 452
    /**
     * Puts an attachment to a document thank to its gid, a sub allDocs and a
     * complex query.
     *
     * @method putAttachment
     * @param  {Command} command The JIO command
     */
    that.putAttachment = function (command) {
Tristan Cavelier's avatar
Tristan Cavelier committed
453
      priv.putGetOrRemoveAttachment(command, 'put');
454 455
    };

456 457 458 459 460 461
    /**
     * Gets a document thank to its gid, a sub allDocs and a complex query.
     *
     * @method get
     * @param  {Command} command The JIO command
     */
462 463 464
    that.get = function (command) {
      setTimeout(function () {
        var gid_object, complex_query;
465
        gid_object = gidParse(command.getDocId(), priv.constraints);
466 467
        if (gid_object === undefined) {
          return that.error({
468 469 470
            "status": 400,
            "statusText": "Bad Request",
            "error": "bad_request",
471
            "message": "Cannot get document",
472 473 474 475 476 477
            "reason": "metadata should respect constraints"
          });
        }
        complex_query = gidToComplexQuery(gid_object);
        that.addJob('allDocs', priv.sub_storage, {}, {
          "query": complex_query,
478 479
          "wildcard_character": null,
          "include_docs": true
480 481 482 483 484 485 486 487 488 489
        }, function (response) {
          if (response.total_rows === 0) {
            return that.error({
              "status": 404,
              "statusText": "Not Found",
              "error": "not_found",
              "message": "Cannot get document",
              "reason": "missing"
            });
          }
490
          response.rows[0].doc._id = command.getDocId();
491
          return that.success(response.rows[0].doc);
492
        }, function (err) {
493 494 495 496 497 498
          err.message = "Cannot get document";
          return that.error(err);
        });
      });
    };

499 500 501 502 503 504 505 506
    /**
     * Gets an attachment from a document thank to its gid, a sub allDocs and a
     * complex query.
     *
     * @method getAttachment
     * @param  {Command} command The JIO command
     */
    that.getAttachment = function (command) {
Tristan Cavelier's avatar
Tristan Cavelier committed
507
      priv.putGetOrRemoveAttachment(command, 'get');
508 509
    };

510 511 512 513 514 515
    /**
     * Remove a document thank to its gid, sub allDocs and a complex query.
     *
     * @method remove
     * @param  {Command} command The JIO command.
     */
516 517 518 519 520 521
    that.remove = function (command) {
      setTimeout(function () {
        var gid_object, complex_query, doc = command.cloneDoc();
        gid_object = gidParse(doc._id, priv.constraints);
        if (gid_object === undefined) {
          return that.error({
522 523 524
            "status": 400,
            "statusText": "Bad Request",
            "error": "bad_request",
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
            "message": "Cannot remove document",
            "reason": "metadata should respect constraints"
          });
        }
        complex_query = gidToComplexQuery(gid_object);
        that.addJob('allDocs', priv.sub_storage, {}, {
          "query": complex_query,
          "wildcard_character": null
        }, function (response) {
          if (response.total_rows === 0) {
            return that.error({
              "status": 404,
              "statusText": "Not found",
              "error": "not_found",
              "message": "Cannot remove document",
              "reason": "missing"
            });
          }
          gid_object = doc._id;
          doc = {"_id": response.rows[0].id};
          that.addJob('remove', priv.sub_storage, doc, {
          }, function (response) {
            response.id = gid_object;
            that.success(response);
          }, function (err) {
            err.message = "Cannot remove document";
            that.error(err);
          });
        }, function (err) {
          err.message = "Cannot remove document";
          that.error(err);
        });
      });
    };

560 561 562 563 564 565 566 567 568 569 570
    /**
     * Removes an attachment to a document thank to its gid, a sub allDocs and a
     * complex query.
     *
     * @method removeAttachment
     * @param  {Command} command The JIO command
     */
    that.removeAttachment = function (command) {
      priv.putGetOrRemoveAttachment(command, 'remove');
    };

571 572 573 574 575 576
    /**
     * Retrieve a list of document which respect gid constraints.
     *
     * @method allDocs
     * @param  {Command} command The JIO command
     */
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
    that.allDocs = function (command) {
      setTimeout(function () {
        var options = command.cloneOption(), include_docs;
        include_docs = options.include_docs;
        options.include_docs = true;
        that.addJob('allDocs', priv.sub_storage, {
        }, options, function (response) {
          var result = [], doc_gids = {}, i, row, gid;
          while ((row = response.rows.shift()) !== undefined) {
            if ((gid = gidFormat(row.doc, priv.constraints)) !== undefined) {
              if (!doc_gids[gid]) {
                doc_gids[gid] = true;
                row.id = gid;
                delete row.key;
                result[result.length] = row;
                if (include_docs === true) {
                  row.doc._id = gid;
                } else {
                  delete row.doc;
                }
              }
            }
          }
          doc_gids = undefined; // free memory
          row = undefined;
          that.success({"total_rows": result.length, "rows": result});
        }, function (err) {
          err.message = "Cannot get all documents";
          return that.error(err);
606 607 608 609 610 611 612 613 614
        });
      });
    };

    return that;
  }

  jIO.addStorageType('gid', gidStorage);

615
}));