Permalink
Browse files

initial import

  • Loading branch information...
0 parents commit 8a1d9b0962b39aea0421b4438e3dbc79dd853956 @rsms committed Feb 3, 2011
Showing with 360 additions and 0 deletions.
  1. +1 −0 .gitignore
  2. +107 −0 README.md
  3. +37 −0 example.js
  4. +215 −0 fsdocs.js
@@ -0,0 +1 @@
+mydocs
107 README.md
@@ -0,0 +1,107 @@
+# fsdocs
+
+Simple, [ACID](http://en.wikipedia.org/wiki/ACID) and versioned
+file system-based document database for [node.js](http://nodejs.org/).
+
+The idea is that you can use this simple, single-file module for quick hacks
+where installing (and possibly deploying) a full-scale "real" database like CouchDB, MySQL, Redis, MongoDB, etc kills your creativity. Since documents and their different versions are stored as regular JSON files, inspecting and manipulating data while developing is really easy and simple (just remove/edit/add files).
+
+Performance is actually pretty good since the kernel will take care of caching
+the most frequently read documents in memory. Also, even though this is ACID and
+all, a "put" only implies writing a single file. Atomicity and "crashability" is
+acquired through a mix of `link(2)` and `rename(2)` operations.
+
+## Example
+
+```js
+var FSDocs = require('fsdocs').FSDocs
+var docs = new FSDocs('./mydocs')
+
+docs.put('doc1', {title:"Hello"}, function(err, ok) {
+ if (err) throw err
+ console.log(ok? 'stored ok' : 'conflict: version already exist')
+ docs.get('doc1', function(err, document) {
+ if (err) throw err
+ console.log(document)
+ })
+})
+```
+
+## API
+
+### `new FSDocs(location) -> [object FSDocs]`
+
+A document store based in directory at |location|
+
+#### `docs.get(key, [version], [callback(err, document)])`
+
+Retrieve a document. If |version| is omitted or less than 1, the most
+recent version of the document is returned.
+
+#### `docs.getSync(key, [version]) -> document`
+
+Synchronous version of |docs.get|
+
+#### `docs.put(key, document, [callback(err, storedOk)])`
+
+Create or update a document. If |document| does not contain a |_version|
+member or its |_version| member is less than 1, the document is
+considered as "new" and thus if there's already an existing version an
+error will be returned (since the document is effectively version 1). If
+there's a conflict when writing the new version, |storedOk| will be a
+false value. In this case it's up to the client to proceed (e.g. merge,
+discard, retry, etc). |document| must be an object.
+
+#### `docs.putSync(key, document) -> storedOk`
+
+Synchronous version of |docs.put|
+
+
+## Implementation
+
+When writing a new document version to the database, fsdocs takes a rather simplistic approach in order to achieve [ACID](http://en.wikipedia.org/wiki/ACID)-ness:
+
+1. The new document is written to a temporary file. If this operation fails, we remove the temporary file and bail with an error.
+
+2. A (hard) link is created at "key/lock" (unique to the document key, not considering version). If this operation fails, another version is already being written which indicates a conflict and thus we bail with an error.
+
+3. A new link is created for the document data "key/version.json". If this operation fails, the document has already been modified (version exists) and thus we bail with an error.
+
+4. Finally the temporary link is renamed to "key/current.json". Because of the success of 2. and 3. we are guaranteed to upgrade the document to its latest version. We also retain atomicity because of the implementation of rename(), making concurrent reads of the "current" version safe.
+
+We remove the "key/lock" file (unless 2. fails) when done with 3 or 4.
+
+Most file systems are in fact highly optimized "key-value stores", in a way.
+
+
+## Known issues
+
+- If the program crashes during writing a document the lockfile might not get
+ cleaned up, thus causing that document to become read-only (since any put
+ operation will fail to acquire the lockfile). In cases where there's only one
+ process manipulating the documents (or more specifically; only one process
+ manipulating a given key), this could be solved by simply adding the PID as
+ a suffix of the lockfile.
+
+
+## MIT license
+
+Copyright (c) 2011 Rasmus Andersson <http://rsms.me/>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
@@ -0,0 +1,37 @@
+var FSDocs = require('./fsdocs').FSDocs;
+var docs = new FSDocs(__dirname+'/mydocs');
+
+// synchronous API
+console.log(docs.putSync('doc1', {title:'internet', age:35.5}))
+console.log(docs.getSync('doc1'))
+
+// asynchronous API
+docs.put('doc2', {title:'internets', age:35.5}, function(err, ok) {
+ if (err) return console.error('error: '+(err.stack || err));
+ console.log('stored? '+(ok ? 'true':'false'))
+ docs.get('doc2', function(err, document) {
+ if (err) throw err;
+ console.log(document);
+ });
+})
+
+/*
+var t, i, iterations = 1000;
+
+t = new Date; i = iterations;
+while (i--)
+ docs.putSync('doc-'+i, {title:'internet', age:23.9, _version: 1});
+t = (new Date)-t;
+console.log('write performance: %d ms total, %d ms/op, %d ops/second',
+ t, t/iterations, Math.round(1000/(t/iterations)))
+
+t = new Date; i = iterations;
+while (i--) db.getSync('doc-'+i)
+i = iterations;
+while (i--) db.getSync('doc-'+i)
+i = iterations;
+while (i--) db.getSync('doc-'+i)
+t = (new Date)-t;
+console.log('read performance: %d ms total, %d ms/op, %d ops/second',
+ t, t/iterations, Math.round(1000/(t/iterations)))
+*/
215 fsdocs.js
@@ -0,0 +1,215 @@
+/**
+ * Simple but ACID file system-based document database.
+ *
+ * Copyright (c) 2011 Rasmus Andersson <http://rsms.me/>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+var fs = require('fs');
+
+function FSDocs(location) {
+ this.location = require('path').normalize(location);
+ this.prefixLength = 0;
+ // FIXME: move into an open method or something like that
+ try {
+ fs.mkdirSync(this.location, 0700);
+ } catch (e) { if (typeof e !== 'object' || e.errno !== 17) throw e; }
+}
+
+FSDocs.prototype = {
+ entryPath: function(key) {
+ var basename = this.location+'/';
+ if (this.prefixLength && key.length > this.prefixLength) {
+ basename += key.substr(0, this.prefixLength)+'/'+
+ key.substr(this.prefixLength);
+ } else {
+ basename += key;
+ }
+ return basename;
+ },
+
+ mkdirsSync: function(dirname, mode) {
+ var p = 0;
+ dirname = dirname.substr(this.location.length+1) + '/';
+ while ((p = dirname.indexOf('/', ++p)) !== -1) {
+ try {
+ fs.mkdirSync(this.location+'/'+dirname.substr(0, p), mode);
+ } catch (e) { if (typeof e !== 'object' || e.errno !== 17) throw e; }
+ }
+ },
+
+ mkdirs: function(dirname, mode, callback) {
+ var p = 0, location = this.location;
+ dirname = dirname.substr(location.length+1) + '/';
+ var next = function () {
+ p = dirname.indexOf('/', ++p);
+ if (p === -1) return callback();
+ fs.mkdir(location+'/'+dirname.substr(0, p), mode, function (err) {
+ if (err && (typeof err !== 'object' || err.errno !== 17)) {
+ callback(err);
+ } else {
+ next();
+ }
+ });
+ }
+ next();
+ },
+
+ get: function(key, version, callback) {
+ if (typeof version === 'function') { callback = version; version = 0; }
+ var filename = this.entryPath(key)+'/'+
+ ((version && version > 0) ? version : 'current')+'.json';
+ fs.readFile(filename, 'utf8', function(err, data) {
+ if (err) {
+ if (typeof err === 'object' && (err.errno === 9 || err.errno === 2))
+ err = null;
+ return callback && callback(err, null);
+ }
+ try { data = JSON.parse(data); } catch (e) { err = e; data = null; }
+ if (callback) callback(err, data);
+ });
+ },
+
+ getSync: function(key, version) {
+ var filename = this.entryPath(key)+'/'+
+ ((version && version > 0) ? version : 'current')+'.json';
+ try {
+ return JSON.parse(fs.readFileSync(filename));
+ } catch (e) {
+ if (typeof e === 'object' && (e.errno === 9 || e.errno === 2))
+ return null;
+ throw e;
+ }
+ },
+
+ putSync: function(key, document) {
+ return this._put(key, document);
+ },
+
+ put: function(key, document, callback) {
+ return this._put(key, document, callback || function(){});
+ },
+
+ _put: function(key, document, callback) {
+ if (typeof document !== 'object')
+ throw new TypeError('document must be an object');
+ if (typeof document._version !== 'number') document._version = 1;
+ else document._version += 1;
+ var data = JSON.stringify(document);
+ var basename = this.entryPath(key);
+ var dstname = basename+'/current.json';
+ var lockfile = basename+'/lock';
+ var versionname = basename+'/'+document._version+'.json';
+ var tempname = versionname+'.temp-'+process.pid+'-'+(new Date).getTime();
+
+ if (callback) {
+ // async branch
+
+ var main = function() {
+ // write new data
+ fs.writeFile(tempname, data, 'utf8', function(err) {
+ if (err) return callback(err);
+
+ // lock the entry
+ fs.link(tempname, lockfile, function(e) {
+ if (e && typeof e === 'object' && e.errno === 17) {
+ // someone else already has the lock (we where too slow)
+ return fs.unlink(tempname, callback);
+ } else if (e) { return callback(e); }
+
+ // link version
+ fs.link(tempname, versionname, function(e) {
+
+ if (e) {
+ if (typeof e === 'object' && e.errno === 17) {
+ // someone else wrote this version before we did
+ fs.unlink(tempname, callback);
+ } else {
+ callback(e);
+ }
+ fs.unlink(lockfile, callback);
+ return;
+ }
+
+ // update current by renaming temporary hardlink
+ fs.rename(tempname, dstname, function(e1) {
+ fs.unlink(lockfile, function(e2) {
+ callback(e1 || e2, true);
+ });
+ });
+
+ });
+ // END link version
+ });
+ // END lock the entry
+ });
+ // END write new data
+ }
+
+ // make directories if we are writing the first version
+ if (document._version === 1) {
+ this.mkdirs(basename, 0700, function(err) {
+ if (err) return callback(err);
+ main();
+ });
+ } else {
+ main();
+ }
+
+ } else {
+ // sync branch
+
+ // make directories if we are writing the first version
+ if (document._version === 1)
+ this.mkdirsSync(basename, 0700);
+ // write new data
+ fs.writeFileSync(tempname, data, 'utf8');
+ // lock the entry
+ try {
+ fs.linkSync(tempname, lockfile);
+ // link version
+ try {
+ fs.linkSync(tempname, versionname);
+ // update current by renaming temporary hardlink
+ fs.renameSync(tempname, dstname);
+ return true;
+ } catch (e) {
+ // someone else wrote this version before we did
+ if (typeof e === 'object' && e.errno === 17) {
+ fs.unlinkSync(tempname);
+ return false;
+ }
+ throw e;
+ } finally {
+ fs.unlinkSync(lockfile);
+ }
+ } catch (e) {
+ fs.unlinkSync(tempname);
+ // someone else already has the lock (we where too slow)
+ if (typeof e === 'object' && e.errno === 17)
+ return false;
+ throw e;
+ }
+
+ return true;
+ }
+ }
+}
+
+exports.FSDocs = FSDocs;

0 comments on commit 8a1d9b0

Please sign in to comment.