-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.ts
299 lines (257 loc) · 7.02 KB
/
index.ts
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
/**
* @packageDocumentation
*
* A Datastore implementation with a file system backend.
*
* @example
*
* ```js
* import { FsDatastore } from 'datastore-fs'
*
* const store = new FsDatastore('path/to/store')
* ```
*/
import fs from 'node:fs/promises'
import path from 'node:path'
import { promisify } from 'util'
import {
BaseDatastore, Errors
} from 'datastore-core'
// @ts-expect-error no types
import fwa from 'fast-write-atomic'
import {
Key, type KeyQuery, type Pair, type Query
} from 'interface-datastore'
import glob from 'it-glob'
import map from 'it-map'
import parallel from 'it-parallel-batch'
import type { AwaitIterable } from 'interface-store'
const writeAtomic = promisify(fwa)
/**
* Write a file atomically
*/
async function writeFile (path: string, contents: Uint8Array): Promise<void> {
try {
await writeAtomic(path, contents)
} catch (err: any) {
if (err.code === 'EPERM' && err.syscall === 'rename') {
// fast-write-atomic writes a file to a temp location before renaming it.
// On Windows, if the final file already exists this error is thrown.
// No such error is thrown on Linux/Mac
// Make sure we can read & write to this file
await fs.access(path, fs.constants.F_OK | fs.constants.W_OK)
// The file was created by another context - this means there were
// attempts to write the same block by two different function calls
return
}
throw err
}
}
export interface FsDatastoreInit {
createIfMissing?: boolean
errorIfExists?: boolean
extension?: string
putManyConcurrency?: number
getManyConcurrency?: number
deleteManyConcurrency?: number
}
/**
* A datastore backed by the file system.
*
* Keys need to be sanitized before use, as they are written
* to the file system as is.
*/
export class FsDatastore extends BaseDatastore {
public path: string
private readonly createIfMissing: boolean
private readonly errorIfExists: boolean
private readonly extension: string
private readonly deleteManyConcurrency: number
private readonly getManyConcurrency: number
private readonly putManyConcurrency: number
constructor (location: string, init: FsDatastoreInit = {}) {
super()
this.path = path.resolve(location)
this.createIfMissing = init.createIfMissing ?? true
this.errorIfExists = init.errorIfExists ?? false
this.extension = init.extension ?? '.data'
this.deleteManyConcurrency = init.deleteManyConcurrency ?? 50
this.getManyConcurrency = init.getManyConcurrency ?? 50
this.putManyConcurrency = init.putManyConcurrency ?? 50
}
async open (): Promise<void> {
try {
await fs.access(this.path, fs.constants.F_OK | fs.constants.W_OK)
if (this.errorIfExists) {
throw Errors.dbOpenFailedError(new Error(`Datastore directory: ${this.path} already exists`))
}
} catch (err: any) {
if (err.code === 'ENOENT') {
if (this.createIfMissing) {
await fs.mkdir(this.path, { recursive: true })
return
} else {
throw Errors.notFoundError(new Error(`Datastore directory: ${this.path} does not exist`))
}
}
throw err
}
}
async close (): Promise<void> {
}
/**
* Calculate the directory and file name for a given key.
*/
_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.extension)
return {
dir,
file
}
}
/**
* Calculate the original key, given the file name.
*/
_decode (file: string): Key {
const ext = this.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)
}
/**
* Store the given value under the key
*/
async put (key: Key, val: Uint8Array): Promise<Key> {
const parts = this._encode(key)
try {
await fs.mkdir(parts.dir, {
recursive: true
})
await writeFile(parts.file, val)
return key
} catch (err: any) {
throw Errors.dbWriteFailedError(err)
}
}
async * putMany (source: AwaitIterable<Pair>): AsyncIterable<Key> {
yield * parallel(
map(source, ({ key, value }) => {
return async () => {
await this.put(key, value)
return key
}
}),
this.putManyConcurrency
)
}
/**
* Read from the file system
*/
async get (key: Key): Promise<Uint8Array> {
const parts = this._encode(key)
let data
try {
data = await fs.readFile(parts.file)
} catch (err: any) {
throw Errors.notFoundError(err)
}
return data
}
async * getMany (source: AwaitIterable<Key>): AsyncIterable<Pair> {
yield * parallel(
map(source, key => {
return async () => {
return {
key,
value: await this.get(key)
}
}
}),
this.getManyConcurrency
)
}
async * deleteMany (source: AwaitIterable<Key>): AsyncIterable<Key> {
yield * parallel(
map(source, key => {
return async () => {
await this.delete(key)
return key
}
}),
this.deleteManyConcurrency
)
}
/**
* Check for the existence of the given key
*/
async has (key: Key): Promise<boolean> {
const parts = this._encode(key)
try {
await fs.access(parts.file)
} catch (err: any) {
return false
}
return true
}
/**
* Delete the record under the given key
*/
async delete (key: Key): Promise<void> {
const parts = this._encode(key)
try {
await fs.unlink(parts.file)
} catch (err: any) {
if (err.code === 'ENOENT') {
return
}
throw Errors.dbDeleteFailedError(err)
}
}
async * _all (q: Query): AsyncIterable<Pair> {
let prefix = q.prefix ?? '**'
// strip leading slashes
prefix = prefix.replace(/^\/+/, '')
const pattern = `${prefix}/*${this.extension}`
.split(path.sep)
.join('/')
const files = glob(this.path, pattern, {
absolute: true
})
for await (const file of files) {
try {
const buf = await fs.readFile(file)
const pair: Pair = {
key: this._decode(file),
value: buf
}
yield pair
} catch (err: any) {
// if keys are removed from the datastore while the query is
// running, we may encounter missing files.
if (err.code !== 'ENOENT') {
throw err
}
}
}
}
async * _allKeys (q: KeyQuery): AsyncIterable<Key> {
let prefix = q.prefix ?? '**'
// strip leading slashes
prefix = prefix.replace(/^\/+/, '')
const pattern = `${prefix}/*${this.extension}`
.split(path.sep)
.join('/')
const files = glob(this.path, pattern, {
absolute: true
})
yield * map(files, f => this._decode(f))
}
}