-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathdriver.ts
More file actions
423 lines (379 loc) · 12.2 KB
/
Copy pathdriver.ts
File metadata and controls
423 lines (379 loc) · 12.2 KB
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
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
/*
* flydrive
*
* (c) FlyDrive
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import etag from 'etag'
import mimeTypes from 'mime-types'
import * as fsp from 'node:fs/promises'
import { fileURLToPath } from 'node:url'
import { type Readable } from 'node:stream'
import string from '@poppinss/utils/string'
import { Retrier } from '@humanwhocodes/retry'
import { dirname, join, relative } from 'node:path'
import { RuntimeException } from '@poppinss/utils/exception'
import { existsSync, rmSync, createReadStream, type Dirent } from 'node:fs'
import debug from './debug.js'
import type { FSDriverOptions } from './types.js'
import { DriveFile } from '../../src/driver_file.js'
import { DriveDirectory } from '../../src/drive_directory.js'
import type {
WriteOptions,
ObjectMetaData,
DriverContract,
ObjectVisibility,
SignedURLOptions,
UploadSignedURLOptions,
} from '../../src/types.js'
/**
* The error codes on which we want to retry fs
* operations
*/
const RETRY_ERROR_CODES = new Set(['ENFILE', 'EMFILE'])
/**
* Implementation of FlyDrive driver that uses the local filesystem
* to persist and read files.
*/
export class FSDriver implements DriverContract {
/**
* The root directory for the driver
*/
#rootUrl: string
/**
* Retrier is used to retry file system operations
* when certain errors are raised.
*/
#retrier = new Retrier(
(error: NodeJS.ErrnoException) => error.code && RETRY_ERROR_CODES.has(error.code)
)
constructor(public options: FSDriverOptions) {
this.#rootUrl =
typeof options.location === 'string' ? options.location : fileURLToPath(options.location)
debug('driver config %O', options)
}
/**
* Reads the file for the provided path
*/
#read(key: string): Promise<Buffer> {
const location = join(this.#rootUrl, key)
return this.#retrier.retry(() => fsp.readFile(location))
}
/**
* Reads dir and ignores non-existing errors
*/
async #readDir(location: string, recursive: boolean): Promise<Dirent[]> {
try {
return await fsp.readdir(location, {
recursive,
withFileTypes: true,
})
} catch (error) {
if (error.code !== 'ENOENT') {
throw error
}
return []
}
}
/**
* Generic implementation to write a file
*/
#write(
key: string,
contents: string | Readable | Uint8Array,
options?: { signal?: AbortSignal }
) {
const location = join(this.#rootUrl, key)
return this.#retrier.retry(async () => {
await fsp.mkdir(dirname(location), { recursive: true })
await fsp.writeFile(location, contents, options)
})
}
/**
* Synchronously check if a file exists
*/
existsSync(key: string): boolean {
debug('checking if file exists %s:%s', this.#rootUrl, key)
const location = join(this.#rootUrl, key)
return existsSync(location)
}
/**
* Returns a boolean indicating if the file exists or not.
*/
async exists(key: string): Promise<boolean> {
debug('checking if file exists %s:%s', this.#rootUrl, key)
const location = join(this.#rootUrl, key)
try {
const object = await fsp.stat(location)
return object.isFile()
} catch (error) {
if (error.code === 'ENOENT') {
return false
}
throw error
}
}
/**
* Returns the contents of the file as a UTF-8 string. An
* exception is thrown when the file is missing.
*/
async get(key: string): Promise<string> {
debug('reading file contents %s:%s', this.#rootUrl, key)
return this.#read(key).then((value) => value.toString('utf-8'))
}
/**
* Returns the contents of the file as a stream. An
* exception is thrown when the file is missing.
*/
async getStream(key: string): Promise<Readable> {
debug('reading file contents as a stream %s:%s', this.#rootUrl, key)
const location = join(this.#rootUrl, key)
return createReadStream(location)
}
/**
* Returns the contents of the file as an Uint8Array. An
* exception is thrown when the file is missing.
*/
async getBytes(key: string): Promise<Uint8Array> {
debug('reading file contents as array buffer %s:%s', this.#rootUrl, key)
return this.#read(key).then((value) => new Uint8Array(value.buffer))
}
/**
* Returns the metadata of a file.
*/
async getMetaData(key: string): Promise<ObjectMetaData> {
debug('fetching file metadata %s:%s', this.#rootUrl, key)
const location = join(this.#rootUrl, key)
const stats = await fsp.stat(location)
if (stats.isDirectory()) {
throw new RuntimeException(`Cannot get metadata of a directory "${key}"`)
}
return {
contentLength: stats.size,
contentType: mimeTypes.lookup(key) || undefined,
etag: etag(stats),
lastModified: stats.mtime,
}
}
/**
* Returns the file visibility from the pre-defined config
* value
*/
async getVisibility(_: string): Promise<ObjectVisibility> {
return this.options.visibility
}
/**
* Returns the public URL of the file. This method does not check
* if the file exists or not.
*/
async getUrl(key: string): Promise<string> {
const location = join(this.#rootUrl, key)
const generateURL = this.options.urlBuilder?.generateURL
if (generateURL) {
debug('generating public URL %s:%s', this.#rootUrl, key)
return generateURL(key, location)
}
throw new RuntimeException('Cannot generate URL. The "fs" driver does not support it')
}
/**
* Returns the signed/temporary URL of the file. By default, the signed URLs
* expire in 30mins, but a custom expiry can be defined using
* "options.expiresIn" property.
*/
async getSignedUrl(key: string, options?: SignedURLOptions): Promise<string> {
const location = join(this.#rootUrl, key)
const normalizedOptions = Object.assign(
{
expiresIn: '30 mins',
},
options
)
/**
* Use custom implementation when exists.
*/
const generateSignedURL = this.options.urlBuilder?.generateSignedURL
if (generateSignedURL) {
debug('generating signed URL %s:%s', this.#rootUrl, key)
return generateSignedURL(key, location, normalizedOptions)
}
throw new RuntimeException('Cannot generate signed URL. The "fs" driver does not support it')
}
/**
* Returns the signed/temporary URL that can be used to directly upload the file.
* By default, the signed URLs expire in 30mins, but a custom expiry can be
* defined using "options.expiresIn" property.
*/
async getSignedUploadUrl(key: string, options?: UploadSignedURLOptions): Promise<string> {
const location = join(this.#rootUrl, key)
const normalizedOptions = Object.assign(
{
expiresIn: '30 mins',
},
options
)
/**
* Use custom implementation when exists.
*/
const generateSignedUploadURL = this.options.urlBuilder?.generateSignedUploadURL
if (generateSignedUploadURL) {
debug('generating signed upload URL %s:%s', this.#rootUrl, key)
return generateSignedUploadURL(key, location, normalizedOptions)
}
/**
* Not supported by default
*/
throw new RuntimeException(
'Cannot generate signed upload URL. The "fs" driver does not support it'
)
}
/**
* Results in noop, since the local filesystem cannot have per
* object visibility.
*/
async setVisibility(_: string, __: ObjectVisibility): Promise<void> {}
/**
* Writes a file to the destination with the provided contents.
*
* - Missing directories will be created recursively.
* - Existing file will be overwritten.
*/
put(key: string, contents: string | Uint8Array, options?: WriteOptions): Promise<void> {
debug('creating/updating file %s:%s', this.#rootUrl, key)
return this.#write(key, contents, { signal: options?.signal })
}
/**
* Writes a file to the destination with the provided contents
* as a readable stream.
*
* - Missing directories will be created recursively.
* - Existing file will be overwritten.
*/
putStream(key: string, contents: Readable, options?: WriteOptions): Promise<void> {
debug('creating/updating file using readable stream %s:%s', this.#rootUrl, key)
return new Promise((resolve, reject) => {
contents.once('error', (error) => reject(error))
return this.#write(key, contents, { signal: options?.signal }).then(resolve).catch(reject)
})
}
/**
* Copies the source file to the destination. Both paths must
* be within the root location.
*/
copy(source: string, destination: string): Promise<void> {
debug('copying file from %s to %s', source, destination)
const sourceLocation = join(this.#rootUrl, source)
const destinationLocation = join(this.#rootUrl, destination)
return this.#retrier.retry(async () => {
await fsp.mkdir(dirname(destinationLocation), { recursive: true })
await fsp.copyFile(sourceLocation, destinationLocation)
})
}
/**
* Moves the source file to the destination. Both paths must
* be within the root location.
*/
move(source: string, destination: string): Promise<void> {
debug('moving file from %s to %s', source, destination)
const sourceLocation = join(this.#rootUrl, source)
const destinationLocation = join(this.#rootUrl, destination)
return this.#retrier.retry(async () => {
await fsp.mkdir(dirname(destinationLocation), { recursive: true })
await fsp.copyFile(sourceLocation, destinationLocation)
await fsp.unlink(sourceLocation)
})
}
/**
* Deletes a file within the root location of the filesystem.
* Attempting to delete a non-existing file will result in
* a noop.
*/
delete(key: string): Promise<void> {
debug('deleting file %s:%s', this.#rootUrl, key)
const location = join(this.#rootUrl, key)
return this.#retrier.retry(async () => {
try {
await fsp.unlink(location)
} catch (error) {
if (error.code !== 'ENOENT') {
throw error
}
}
})
}
/**
* Deletes the files and directories matching the provided
* prefix. The method is same as running "rm -rf" unix
* command
*/
deleteAll(prefix: string): Promise<void> {
debug('deleting all files in folder %s:%s', this.#rootUrl, prefix)
const location = join(this.#rootUrl, prefix)
return this.#retrier.retry(async () => {
return fsp.rm(location, { recursive: true, force: true })
})
}
/**
* Synchronously delete all files from the root location
*/
clearSync() {
rmSync(this.#rootUrl, { recursive: true, force: true })
}
/**
* Returns a list of files. The pagination properties are ignored
* by the fs driver, since it does not support pagination.
*/
async listAll(
prefix: string,
options?: {
recursive?: boolean
paginationToken?: string
}
): Promise<{
paginationToken?: string
objects: Iterable<DriveFile | DriveDirectory>
}> {
const self = this
const location = join(this.#rootUrl, prefix)
const { recursive } = Object.assign({ recursive: false }, options)
debug('listing files from folder %s:%s %O', this.#rootUrl, prefix, options)
/**
* Reading files with their types.
*/
const files = await this.#readDir(location, recursive)
/**
* The generator is used to lazily iterate over files and
* convert them into DriveFile or DriveDirectory instances
*/
function* filesGenerator(): Iterator<
DriveFile | { isFile: false; isDirectory: true; prefix: string; name: string }
> {
for (const file of files) {
const relativeName = string.toUnixSlash(
relative(
self.#rootUrl,
join(file.parentPath ?? ('path' in file ? file.path : ''), file.name)
)
)
if (file.isFile()) {
yield new DriveFile(relativeName, self)
} else if (!recursive) {
yield new DriveDirectory(relativeName)
}
}
}
return {
paginationToken: undefined,
objects: {
[Symbol.iterator]: filesGenerator,
},
}
}
/**
* Switch bucket at runtime if supported.
*/
bucket(_bucket: string): FSDriver {
throw new RuntimeException('Cannot switch bucket. The "fs" driver does not support it.')
}
}