gidstorage.js 16.7 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 jIO: true, setTimeout: true, complex_queries: true */
21 22 23 24 25

/**
 * JIO GID Storage. Type = 'gid'.
 * Identifies document with their global identifier représentation
 *
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 48 49
 *
 * 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
 *         }
 *       }
 *     }
 */
(function () {

Tristan Cavelier's avatar
Tristan Cavelier committed
50
  var dcmi_types, metadata_actions, content_type_re;
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
  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 = {
66 67 68
    /**
     * Returns the metadata value
     */
69 70 71
    json: function (value) {
      return value;
    },
72 73 74
    /**
     * Returns the metadata if it is a string
     */
75 76 77 78 79
    string: function (value) {
      if (typeof value === 'string') {
        return value;
      }
    },
80 81 82
    /**
     * Returns the metadata in a array format
     */
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    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;
    },
98 99 100
    /**
     * Returns the metadata if it is a string equal to a DCMIType
     */
101 102 103
    DCMIType: function (value) {
      return dcmi_types[value];
    },
104 105 106
    /**
     * Returns the metadata content type if exist
     */
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
    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];
          }
        }
      }
    }
  };
  content_type_re =
    /^([a-z]+\/[a-zA-Z0-9\+\-\.]+)(?:\s*;\s*charset\s*=\s*([a-zA-Z0-9\-]+))?$/;

128 129 130 131 132 133 134 135
  /**
   * 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
   */
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
  function gidFormat(metadata, constraints) {
    var types, i, meta_key, result = {}, tmp;
    types = ['default', metadata.type];
    for (i = 0; i < types.length; i += 1) {
      for (meta_key in constraints[types[i]]) {
        if (constraints[types[i]].hasOwnProperty(meta_key)) {
          tmp = metadata_actions[
            constraints[types[i]][meta_key]
          ](metadata[meta_key]);
          if (tmp === undefined) {
            return;
          }
          result[meta_key] = tmp;
        }
      }
    }
    return JSON.stringify(result);
  }

155 156 157 158 159 160 161
  /**
   * Convert a gid to a complex query.
   *
   * @param  {Object,String} gid The gid
   * @param  {Object} constraints The constraints
   * @return {Object} A complex serialized object
   */
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
  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
    };
  }

194 195 196 197 198 199 200
  /**
   * 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
   */
201 202 203 204 205 206 207 208 209 210 211 212 213
  function gidParse(gid, constraints) {
    var object;
    try {
      object = JSON.parse(gid);
    } catch (e) {
      return;
    }
    if (gid !== gidFormat(object, constraints)) {
      return;
    }
    return object;
  }

214 215 216 217 218 219 220 221 222 223
  /**
   * 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
   */
224 225
  function gidStorage(spec, my) {
    var that = my.basicStorage(spec, my), priv = {};
226

227 228 229 230 231 232 233 234
    priv.sub_storage = spec.sub_storage;
    priv.constraints = spec.constraints || {
      "default": {
        "identifier": "list",
        "type": "DCMIType"
      }
    };

235 236
    // Overrides

237 238 239 240 241 242 243
    that.specToStore = function () {
      return {
        "sub_storage": priv.sub_storage,
        "constraints": priv.constraints
      };
    };

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    // 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
     */
259
    priv.putOrPost = function (command, method) {
260 261 262 263 264
      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({
265 266 267
            "status": 400,
            "statusText": "Bad Request",
            "error": "bad_request",
268
            "message": "Cannot " + method + " document",
269 270 271 272 273 274 275 276
            "reason": "metadata should respect constraints"
          });
        }
        complex_query = gidToComplexQuery(gid);
        that.addJob('allDocs', priv.sub_storage, {}, {
          "query": complex_query,
          "wildcard_character": null
        }, function (response) {
277
          var update_method = method;
278
          if (response.total_rows !== 0) {
279 280 281 282 283
            if (method === 'post') {
              return that.error({
                "status": 409,
                "statusText": "Conflict",
                "error": "conflict",
284
                "message": "Cannot " + method + " document",
285 286 287
                "reason": "Document already exist"
              });
            }
288 289
            doc = command.cloneDoc();
            doc._id = response.rows[0].id;
290 291 292 293
          } else {
            doc = command.cloneDoc();
            delete doc._id;
            update_method = 'post';
294
          }
295
          that.addJob(update_method, priv.sub_storage, doc, {
296 297 298 299
          }, function (response) {
            response.id = gid;
            that.success(response);
          }, function (err) {
300
            err.message = "Cannot " + method + " document";
301 302 303
            that.error(err);
          });
        }, function (err) {
304
          err.message = "Cannot " + method + " document";
305 306 307 308 309
          that.error(err);
        });
      });
    };

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
    /**
     * 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);
        });
      });
    };

368 369 370 371 372 373
    /**
     * See {{#crossLink "gidStorage/putOrPost:method"}}{{/#crossLink}}.
     *
     * @method post
     * @param  {Command} command The JIO command
     */
374 375 376 377
    that.post = function (command) {
      priv.putOrPost(command, 'post');
    };

378 379 380 381 382 383
    /**
     * See {{#crossLink "gidStorage/putOrPost:method"}}{{/#crossLink}}.
     *
     * @method put
     * @param  {Command} command The JIO command
     */
384 385 386 387
    that.put = function (command) {
      priv.putOrPost(command, 'put');
    };

388 389 390 391 392 393 394 395
    /**
     * 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
396
      priv.putGetOrRemoveAttachment(command, 'put');
397 398
    };

399 400 401 402 403 404
    /**
     * Gets a document thank to its gid, a sub allDocs and a complex query.
     *
     * @method get
     * @param  {Command} command The JIO command
     */
405 406 407
    that.get = function (command) {
      setTimeout(function () {
        var gid_object, complex_query;
408
        gid_object = gidParse(command.getDocId(), priv.constraints);
409 410
        if (gid_object === undefined) {
          return that.error({
411 412 413
            "status": 400,
            "statusText": "Bad Request",
            "error": "bad_request",
414
            "message": "Cannot get document",
415 416 417 418 419 420
            "reason": "metadata should respect constraints"
          });
        }
        complex_query = gidToComplexQuery(gid_object);
        that.addJob('allDocs', priv.sub_storage, {}, {
          "query": complex_query,
421 422
          "wildcard_character": null,
          "include_docs": true
423 424 425 426 427 428 429 430 431 432
        }, function (response) {
          if (response.total_rows === 0) {
            return that.error({
              "status": 404,
              "statusText": "Not Found",
              "error": "not_found",
              "message": "Cannot get document",
              "reason": "missing"
            });
          }
433
          response.rows[0].doc._id = command.getDocId();
434
          return that.success(response.rows[0].doc);
435
        }, function (err) {
436 437 438 439 440 441
          err.message = "Cannot get document";
          return that.error(err);
        });
      });
    };

442 443 444 445 446 447 448 449
    /**
     * 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
450
      priv.putGetOrRemoveAttachment(command, 'get');
451 452
    };

453 454 455 456 457 458
    /**
     * Remove a document thank to its gid, sub allDocs and a complex query.
     *
     * @method remove
     * @param  {Command} command The JIO command.
     */
459 460 461 462 463 464
    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({
465 466 467
            "status": 400,
            "statusText": "Bad Request",
            "error": "bad_request",
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
            "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);
        });
      });
    };

503 504 505 506 507 508 509 510 511 512 513
    /**
     * 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');
    };

514 515 516 517 518 519
    /**
     * Retrieve a list of document which respect gid constraints.
     *
     * @method allDocs
     * @param  {Command} command The JIO command
     */
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
    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);
549 550 551 552 553 554 555 556 557 558
        });
      });
    };

    return that;
  }

  jIO.addStorageType('gid', gidStorage);

}());