@eik/sink-file-system 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,6 @@
1
+ # 1.0.0 (2024-07-29)
2
+
3
+
4
+ ### Features
5
+
6
+ * initial release ([1c00ec5](https://github.com/eik-lib/sink-file-system/commit/1c00ec533dbec7d08a05ef1b7f9a3575a34db01a))
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Eik
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,136 @@
1
+ # @eik/sink-file-system
2
+
3
+ Sink implementation that persists files on the local file system.
4
+
5
+ ## Usage
6
+
7
+ ```sh
8
+ npm install @eik/sink-file-system
9
+ ```
10
+
11
+ ```js
12
+ import path from 'node:path';
13
+ import { pipeline } from 'node:stream';
14
+ import Sink from '@eik/sink-file-system';
15
+ import express from 'express';
16
+
17
+ const app = express();
18
+ const sink = new Sink({
19
+ sinkFsRootPath: path.join(process.cwd(), 'eik-files'),
20
+ });
21
+
22
+ app.get('/file.js', async (req, res, next) => {
23
+ try {
24
+ const file = await sink.read('/path/to/file/file.js');
25
+ pipeline(file.stream, res, (error) => {
26
+ if (error) return next(error);
27
+ });
28
+ } catch (error) {
29
+ next(error);
30
+ }
31
+ });
32
+
33
+ app.listen(8000);
34
+ ```
35
+
36
+ ## API
37
+
38
+ The sink instance has the following API:
39
+
40
+ ### .write(filePath, contentType)
41
+
42
+ Method for writing a file to storage.
43
+
44
+ This method takes the following arguments:
45
+
46
+ - `filePath` - String - Path to the file to be stored - Required.
47
+ - `contentType` - String - The content type of the file - Required.
48
+
49
+ Resolves with a writable stream.
50
+
51
+ ```js
52
+ import { pipeline } from 'node:stream';
53
+
54
+ const fromStream = new SomeReadableStream();
55
+ const sink = new Sink({ ... });
56
+
57
+ try {
58
+ const file = await sink.write('/path/to/file/file.js', 'application/javascript');
59
+ pipeline(fromStream, file.stream, (error) => {
60
+ if (error) console.log(error);
61
+ });
62
+ } catch (error) {
63
+ console.log(error);
64
+ }
65
+ ```
66
+
67
+ ### .read(filePath)
68
+
69
+ Method for reading a file from storage.
70
+
71
+ This method takes the following arguments:
72
+
73
+ - `filePath` - String - Path to the file to be read - Required.
74
+
75
+ Resolves with a [ReadFile][read-file] object which holds metadata about
76
+ the file and a readable stream with the byte stream of the file on the
77
+ `.stream` property.
78
+
79
+ ```js
80
+ import { pipeline } from 'node:stream';
81
+
82
+ const toStream = new SomeWritableStream();
83
+ const sink = new Sink({ ... });
84
+
85
+ try {
86
+ const file = await sink.read('/path/to/file/file.js');
87
+ pipeline(file.stream, toStream, (error) => {
88
+ if (error) console.log(error);
89
+ });
90
+ } catch (error) {
91
+ console.log(error);
92
+ }
93
+ ```
94
+
95
+ ### .delete(filePath)
96
+
97
+ Method for deleting a file in storage.
98
+
99
+ This method takes the following arguments:
100
+
101
+ - `filePath` - String - Path to the file to be deleted - Required.
102
+
103
+ Resolves if file is deleted and rejects if file could not be deleted.
104
+
105
+ ```js
106
+ const sink = new Sink({ ... });
107
+
108
+ try {
109
+ await sink.delete('/path/to/file/file.js');
110
+ } catch (error) {
111
+ console.log(error);
112
+ }
113
+ ```
114
+
115
+ ### .exist(filePath)
116
+
117
+ Method for checking if a file exist in the storage.
118
+
119
+ This method takes the following arguments:
120
+
121
+ - `filePath` - String - Path to the file to be checked for existence - Required.
122
+
123
+ Resolves if file exists and rejects if file does not exist.
124
+
125
+ ```js
126
+ const sink = new Sink({ ... });
127
+
128
+ try {
129
+ await sink.exist('/path/to/file/file.js');
130
+ } catch (error) {
131
+ console.log(error);
132
+ }
133
+ ```
134
+
135
+ [eik]: https://github.com/eik-lib
136
+ [read-file]: https://github.com/eik-lib/common/blob/master/lib/classes/read-file.js
package/lib/main.js ADDED
@@ -0,0 +1,337 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { ReadFile } from '@eik/common';
5
+ import Sink from '@eik/sink';
6
+ import Metrics from '@metrics/client';
7
+ import mime from 'mime';
8
+ import { rimraf } from 'rimraf';
9
+
10
+ /**
11
+ * @param {import('node:fs').Stats} stat
12
+ * @returns {string} As etag
13
+ */
14
+ const etagFromFsStat = (stat) => {
15
+ const mtime = stat.mtime.getTime().toString(16);
16
+ const size = stat.size.toString(16);
17
+ return `W/"${size}-${mtime}"`;
18
+ };
19
+
20
+ /**
21
+ * @typedef {object} SinkFileSystemOptions
22
+ * @property {string} [sinkFsRootPath] Default: gets a temporary directory from the OS
23
+ */
24
+
25
+ /**
26
+ * A sink for persisting files to local file system. By default
27
+ * files are stored in a temporary folder on the OS. To ensure
28
+ * the files are persisted over time, provide a `sinkFsRootPath`.
29
+ *
30
+ * @example
31
+ * ```js
32
+ * import path from "node:path";
33
+ * import Sink from "@eik/sink-file-system";
34
+ *
35
+ * const sink = new Sink({
36
+ * sinkFsRootPath: path.join(process.cwd(), "eik-files"),
37
+ * });
38
+ * ```
39
+ */
40
+ export default class SinkFileSystem extends Sink {
41
+ /**
42
+ * @type {Required<SinkFileSystemOptions>}
43
+ */
44
+ _config;
45
+
46
+ /** @type {import('@metrics/client')} */
47
+ _metrics;
48
+
49
+ /**
50
+ * @param {SinkFileSystemOptions} options
51
+ */
52
+ constructor(options = {}) {
53
+ super();
54
+ this._config = {
55
+ sinkFsRootPath: path.join(os.tmpdir(), '/eik-files'),
56
+ ...options,
57
+ };
58
+ this._metrics = new Metrics();
59
+ this._counter = this._metrics.counter({
60
+ name: 'eik_core_sink_fs',
61
+ description:
62
+ 'Counter measuring access to the file system storage sink',
63
+ labels: {
64
+ operation: 'n/a',
65
+ success: false,
66
+ access: false,
67
+ },
68
+ });
69
+ }
70
+
71
+ get metrics() {
72
+ return this._metrics;
73
+ }
74
+
75
+ /**
76
+ * @param {string} filePath
77
+ * @param {string} contentType
78
+ * @returns {Promise<import('node:stream').Writable>}
79
+ */
80
+ write(filePath, contentType) {
81
+ return new Promise((resolve, reject) => {
82
+ const operation = 'write';
83
+
84
+ try {
85
+ Sink.validateFilePath(filePath);
86
+ Sink.validateContentType(contentType);
87
+ } catch (error) {
88
+ this._counter.inc({ labels: { operation } });
89
+ reject(error);
90
+ return;
91
+ }
92
+
93
+ const pathname = path.join(this._config.sinkFsRootPath, filePath);
94
+
95
+ if (pathname.indexOf(this._config.sinkFsRootPath) !== 0) {
96
+ this._counter.inc({ labels: { operation } });
97
+ reject(new Error(`Directory traversal - ${filePath}`));
98
+ return;
99
+ }
100
+
101
+ const dir = path.dirname(pathname);
102
+
103
+ fs.mkdir(
104
+ dir,
105
+ {
106
+ recursive: true,
107
+ },
108
+ (error) => {
109
+ if (error) {
110
+ this._counter.inc({
111
+ labels: { access: true, operation },
112
+ });
113
+ reject(
114
+ new Error(`Could not create directory - ${dir}`),
115
+ );
116
+ return;
117
+ }
118
+
119
+ const stream = fs.createWriteStream(pathname, {
120
+ autoClose: true,
121
+ emitClose: true,
122
+ });
123
+
124
+ this._counter.inc({
125
+ labels: {
126
+ success: true,
127
+ access: true,
128
+ operation,
129
+ },
130
+ });
131
+
132
+ resolve(stream);
133
+ },
134
+ );
135
+ });
136
+ }
137
+
138
+ /**
139
+ * @param {string} filePath
140
+ * @throws {Error} if the file does not exist
141
+ * @returns {Promise<import('@eik/common').ReadFile>}
142
+ */
143
+ read(filePath) {
144
+ return new Promise((resolve, reject) => {
145
+ const operation = 'read';
146
+
147
+ try {
148
+ Sink.validateFilePath(filePath);
149
+ } catch (error) {
150
+ this._counter.inc({ labels: { operation } });
151
+ reject(error);
152
+ return;
153
+ }
154
+
155
+ const pathname = path.join(this._config.sinkFsRootPath, filePath);
156
+
157
+ if (pathname.indexOf(this._config.sinkFsRootPath) !== 0) {
158
+ this._counter.inc({ labels: { operation } });
159
+ reject(new Error(`Directory traversal - ${filePath}`));
160
+ return;
161
+ }
162
+
163
+ const closeFd = (fd) => {
164
+ fs.close(fd, (error) => {
165
+ if (error) {
166
+ this._counter.inc({
167
+ labels: {
168
+ access: true,
169
+ operation,
170
+ },
171
+ });
172
+ return;
173
+ }
174
+ this._counter.inc({
175
+ labels: {
176
+ success: true,
177
+ access: true,
178
+ operation,
179
+ },
180
+ });
181
+ });
182
+ };
183
+
184
+ fs.open(pathname, 'r', (error, fd) => {
185
+ if (error) {
186
+ this._counter.inc({
187
+ labels: {
188
+ access: true,
189
+ operation,
190
+ },
191
+ });
192
+ reject(error);
193
+ return;
194
+ }
195
+
196
+ fs.fstat(fd, (err, stat) => {
197
+ if (err) {
198
+ closeFd(fd);
199
+ reject(err);
200
+ return;
201
+ }
202
+
203
+ if (!stat.isFile()) {
204
+ closeFd(fd);
205
+ reject(new Error(`Not a file - ${pathname}`));
206
+ return;
207
+ }
208
+
209
+ const mimeType =
210
+ mime.getType(pathname) || 'application/octet-stream';
211
+ const etag = etagFromFsStat(stat);
212
+
213
+ const obj = new ReadFile({
214
+ mimeType,
215
+ etag,
216
+ });
217
+
218
+ obj.stream = fs.createReadStream(pathname, {
219
+ autoClose: true,
220
+ fd,
221
+ });
222
+
223
+ obj.stream.on('error', () => {
224
+ this._counter.inc({
225
+ labels: {
226
+ access: true,
227
+ operation,
228
+ },
229
+ });
230
+ });
231
+
232
+ obj.stream.on('end', () => {
233
+ this._counter.inc({
234
+ labels: {
235
+ success: true,
236
+ access: true,
237
+ operation,
238
+ },
239
+ });
240
+ });
241
+
242
+ resolve(obj);
243
+ });
244
+ });
245
+ });
246
+ }
247
+
248
+ /**
249
+ * @param {string} filePath
250
+ * @returns {Promise<void>}
251
+ */
252
+ delete(filePath) {
253
+ return new Promise((resolve, reject) => {
254
+ const operation = 'delete';
255
+
256
+ try {
257
+ Sink.validateFilePath(filePath);
258
+ } catch (error) {
259
+ this._counter.inc({ labels: { operation } });
260
+ reject(error);
261
+ return;
262
+ }
263
+
264
+ const pathname = path.join(this._config.sinkFsRootPath, filePath);
265
+
266
+ if (pathname.indexOf(this._config.sinkFsRootPath) !== 0) {
267
+ this._counter.inc({ labels: { operation } });
268
+ reject(new Error(`Directory traversal - ${filePath}`));
269
+ return;
270
+ }
271
+
272
+ rimraf(pathname)
273
+ .then(() => {
274
+ this._counter.inc({
275
+ labels: {
276
+ success: true,
277
+ access: true,
278
+ operation,
279
+ },
280
+ });
281
+ resolve();
282
+ })
283
+ .catch((error) => {
284
+ this._counter.inc({ labels: { access: true, operation } });
285
+ reject(error);
286
+ });
287
+ });
288
+ }
289
+
290
+ /**
291
+ * @param {string} filePath
292
+ * @throws {Error} if the file does not exist
293
+ * @returns {Promise<void>}
294
+ */
295
+ exist(filePath) {
296
+ return new Promise((resolve, reject) => {
297
+ const operation = 'exist';
298
+
299
+ try {
300
+ Sink.validateFilePath(filePath);
301
+ } catch (error) {
302
+ this._counter.inc({ labels: { operation } });
303
+ reject(error);
304
+ return;
305
+ }
306
+
307
+ const pathname = path.join(this._config.sinkFsRootPath, filePath);
308
+
309
+ if (pathname.indexOf(this._config.sinkFsRootPath) !== 0) {
310
+ this._counter.inc({ labels: { operation } });
311
+ reject(new Error(`Directory traversal - ${filePath}`));
312
+ return;
313
+ }
314
+
315
+ fs.stat(pathname, (error, stat) => {
316
+ this._counter.inc({
317
+ labels: { success: true, access: true, operation },
318
+ });
319
+
320
+ if (stat && stat.isFile()) {
321
+ resolve();
322
+ return;
323
+ }
324
+
325
+ if (error) {
326
+ reject(error);
327
+ return;
328
+ }
329
+ reject();
330
+ });
331
+ });
332
+ }
333
+
334
+ get [Symbol.toStringTag]() {
335
+ return 'SinkFileSystem';
336
+ }
337
+ }
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@eik/sink-file-system",
3
+ "version": "1.0.0",
4
+ "description": "Sink implementation that persists files on the local file system.",
5
+ "main": "lib/main.js",
6
+ "type": "module",
7
+ "files": [
8
+ "CHANGELOG.md",
9
+ "package.json",
10
+ "README.md",
11
+ "lib"
12
+ ],
13
+ "scripts": {
14
+ "lint": "eslint .",
15
+ "lint:fix": "eslint --fix .",
16
+ "test": "run-s test:*",
17
+ "test:unit": "tap --disable-coverage --allow-empty-coverage tests/**/*.js",
18
+ "test:types": "tsc --project tsconfig.test.json",
19
+ "types": "tsc --declaration --emitDeclarationOnly"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+ssh://git@github.com/eik-lib/sink-file-system.git"
24
+ },
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "author": "Trygve Lie",
29
+ "license": "MIT",
30
+ "bugs": {
31
+ "url": "https://github.com/eik-lib/sink-file-system/issues"
32
+ },
33
+ "homepage": "https://github.com/eik-lib/sink-file-system#readme",
34
+ "dependencies": {
35
+ "@eik/common": "3.0.1",
36
+ "@eik/sink": "1.2.5",
37
+ "@metrics/client": "2.5.3",
38
+ "mime": "3.0.0",
39
+ "rimraf": "5.0.8"
40
+ },
41
+ "devDependencies": {
42
+ "@semantic-release/changelog": "6.0.3",
43
+ "@semantic-release/git": "10.0.1",
44
+ "@types/mime": "3.0.4",
45
+ "@types/readable-stream": "4.0.15",
46
+ "eslint": "9.1.1",
47
+ "eslint-config-prettier": "9.1.0",
48
+ "eslint-plugin-prettier": "5.1.3",
49
+ "globals": "15.0.0",
50
+ "npm-run-all": "4.1.5",
51
+ "prettier": "3.3.2",
52
+ "semantic-release": "24.0.0",
53
+ "tap": "18.8.0"
54
+ }
55
+ }