This repository has been archived by the owner on Mar 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathindex.js
343 lines (309 loc) · 7.87 KB
/
index.js
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
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
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
/* @flow */
'use strict'
/* :: import type {Batch, Query, QueryResult, Callback} from 'interface-datastore' */
const fs = require('graceful-fs')
const pull = require('pull-stream')
const glob = require('glob')
const setImmediate = require('async/setImmediate')
const waterfall = require('async/series')
const each = require('async/each')
const mkdirp = require('mkdirp')
const writeFile = require('write-file-atomic')
const path = require('path')
const asyncFilter = require('interface-datastore').utils.asyncFilter
const asyncSort = require('interface-datastore').utils.asyncSort
const IDatastore = require('interface-datastore')
const Key = IDatastore.Key
const Errors = IDatastore.Errors
/* :: export type FsInputOptions = {
createIfMissing?: bool,
errorIfExists?: bool,
extension?: string
}
type FsOptions = {
createIfMissing: bool,
errorIfExists: bool,
extension: string
}
*/
/**
* A datastore backed by the file system.
*
* Keys need to be sanitized before use, as they are written
* to the file system as is.
*/
class FsDatastore {
/* :: path: string */
/* :: opts: FsOptions */
constructor (location /* : string */, opts /* : ?FsInputOptions */) {
this.path = path.resolve(location)
this.opts = Object.assign({}, {
createIfMissing: true,
errorIfExists: false,
extension: '.data'
}, opts)
if (this.opts.createIfMissing) {
this._openOrCreate()
} else {
this._open()
}
}
open (callback /* : Callback<void> */) /* : void */ {
this._openOrCreate()
setImmediate(callback)
}
/**
* Check if the path actually exists.
* @private
* @returns {void}
*/
_open () {
if (!fs.existsSync(this.path)) {
throw new Error(`Datastore directory: ${this.path} does not exist`)
}
if (this.opts.errorIfExists) {
throw new Error(`Datastore directory: ${this.path} already exists`)
}
}
/**
* Create the directory to hold our data.
*
* @private
* @returns {void}
*/
_create () {
mkdirp.sync(this.path, { fs: fs })
}
/**
* Tries to open, and creates if the open fails.
*
* @private
* @returns {void}
*/
_openOrCreate () {
try {
this._open()
} catch (err) {
if (err.message.match('does not exist')) {
this._create()
return
}
throw err
}
}
/**
* Calculate the directory and file name for a given key.
*
* @private
* @param {Key} key
* @returns {{string, string}}
*/
_encode (key /* : Key */) /* : {dir: string, file: string} */ {
const parent = key.parent().toString()
const dir = path.join(this.path, parent)
const name = key.toString().slice(parent.length)
const file = path.join(dir, name + this.opts.extension)
return {
dir: dir,
file: file
}
}
/**
* Calculate the original key, given the file name.
*
* @private
* @param {string} file
* @returns {Key}
*/
_decode (file /* : string */) /* : Key */ {
const ext = this.opts.extension
if (path.extname(file) !== ext) {
throw new Error(`Invalid extension: ${path.extname(file)}`)
}
const keyname = file
.slice(this.path.length, -ext.length)
.split(path.sep)
.join('/')
return new Key(keyname)
}
/**
* Write to the file system without extension.
*
* @param {Key} key
* @param {Buffer} val
* @param {function(Error)} callback
* @returns {void}
*/
putRaw (key /* : Key */, val /* : Buffer */, callback /* : Callback<void> */) /* : void */ {
const parts = this._encode(key)
const file = parts.file.slice(0, -this.opts.extension.length)
waterfall([
(cb) => mkdirp(parts.dir, { fs: fs }, cb),
(cb) => writeFile(file, val, cb)
], (err) => callback(err))
}
/**
* Store the given value under the key.
*
* @param {Key} key
* @param {Buffer} val
* @param {function(Error)} callback
* @returns {void}
*/
put (key /* : Key */, val /* : Buffer */, callback /* : Callback<void> */) /* : void */ {
const parts = this._encode(key)
waterfall([
(cb) => mkdirp(parts.dir, { fs: fs }, cb),
(cb) => writeFile(parts.file, val, cb)
], (err) => {
if (err) {
return callback(Errors.dbWriteFailedError(err))
}
callback()
})
}
/**
* Read from the file system without extension.
*
* @param {Key} key
* @param {function(Error, Buffer)} callback
* @returns {void}
*/
getRaw (key /* : Key */, callback /* : Callback<Buffer> */) /* : void */ {
const parts = this._encode(key)
let file = parts.file
file = file.slice(0, -this.opts.extension.length)
fs.readFile(file, (err, data) => {
if (err) {
return callback(Errors.notFoundError(err))
}
callback(null, data)
})
}
/**
* Read from the file system.
*
* @param {Key} key
* @param {function(Error, Buffer)} callback
* @returns {void}
*/
get (key /* : Key */, callback /* : Callback<Buffer> */) /* : void */ {
const parts = this._encode(key)
fs.readFile(parts.file, (err, data) => {
if (err) {
return callback(Errors.notFoundError(err))
}
callback(null, data)
})
}
/**
* Check for the existence of the given key.
*
* @param {Key} key
* @param {function(Error, bool)} callback
* @returns {void}
*/
has (key /* : Key */, callback /* : Callback<bool> */) /* : void */ {
const parts = this._encode(key)
fs.access(parts.file, err => {
callback(null, !err)
})
}
/**
* Delete the record under the given key.
*
* @param {Key} key
* @param {function(Error)} callback
* @returns {void}
*/
delete (key /* : Key */, callback /* : Callback<void> */) /* : void */ {
const parts = this._encode(key)
fs.unlink(parts.file, (err) => {
if (err) {
return callback(Errors.dbDeleteFailedError(err))
}
callback()
})
}
/**
* Create a new batch object.
*
* @returns {Batch}
*/
batch () /* : Batch<Buffer> */ {
const puts = []
const deletes = []
return {
put (key /* : Key */, value /* : Buffer */) /* : void */ {
puts.push({ key: key, value: value })
},
delete (key /* : Key */) /* : void */ {
deletes.push(key)
},
commit: (callback /* : (err: ?Error) => void */) => {
waterfall([
(cb) => each(puts, (p, cb) => {
this.put(p.key, p.value, cb)
}, cb),
(cb) => each(deletes, (k, cb) => {
this.delete(k, cb)
}, cb)
], (err) => callback(err))
}
}
}
/**
* Query the store.
*
* @param {Object} q
* @returns {PullStream}
*/
query (q /* : Query<Buffer> */) /* : QueryResult<Buffer> */ {
// glob expects a POSIX path
let prefix = q.prefix || '**'
let pattern = path
.join(this.path, prefix, '*' + this.opts.extension)
.split(path.sep)
.join('/')
let tasks = [pull.values(glob.sync(pattern))]
if (!q.keysOnly) {
tasks.push(pull.asyncMap((f, cb) => {
fs.readFile(f, (err, buf) => {
if (err) {
return cb(err)
}
cb(null, {
key: this._decode(f),
value: buf
})
})
}))
} else {
tasks.push(pull.map(f => ({ key: this._decode(f) })))
}
if (q.filters != null) {
tasks = tasks.concat(q.filters.map(asyncFilter))
}
if (q.orders != null) {
tasks = tasks.concat(q.orders.map(asyncSort))
}
if (q.offset != null) {
let i = 0
tasks.push(pull.filter(() => i++ >= q.offset))
}
if (q.limit != null) {
tasks.push(pull.take(q.limit))
}
return pull.apply(null, tasks)
}
/**
* Close the store.
*
* @param {function(Error)} callback
* @returns {void}
*/
close (callback /* : (err: ?Error) => void */) /* : void */ {
setImmediate(callback)
}
}
module.exports = FsDatastore