mobiletto 1.0.2

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/.babelrc ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "presets": [
3
+ "@babel/preset-env"
4
+ ]
5
+ }
package/.eslintrc.js ADDED
@@ -0,0 +1,14 @@
1
+ module.exports = {
2
+ root: true,
3
+ env: {
4
+ browser: true,
5
+ node: true
6
+ },
7
+ parserOptions: {
8
+ parser: '@babel/eslint-parser',
9
+ requireConfigFile: false
10
+ },
11
+ plugins: [],
12
+ // add your custom rules here
13
+ rules: {}
14
+ }
package/LICENSE.txt ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,101 @@
1
+ Mobiletto
2
+ =========
3
+
4
+ Mobiletto is a JavaScript storage abstraction layer.
5
+
6
+ It supports apps that are agnostic to where files are stored.
7
+
8
+ # Using storage services
9
+ const { mobiletto } = require('mobiletto')
10
+
11
+ // general usage
12
+ const api = await mobiletto(driverName, key, secret, opts)
13
+
14
+ // to use 'local' driver:
15
+ // * key: base directory
16
+ // * secret: ignored, can be null
17
+ // * opts object:
18
+ // * mode: optional, filesystem permissions to set when creating new files and directories, default is 0700
19
+ const local = await mobiletto('local', '/home/ubuntu/tmp', null, {mode: '0700'})
20
+
21
+ // to use 's3' driver:
22
+ // * key: AWS access key
23
+ // * secret: AWS secret key
24
+ // * opts object:
25
+ // * bucket: required, name of the S3 bucket
26
+ // * region: optional, the AWS region to communicate with, default is us-east-1
27
+ // * prefix: optional, all read/writes within the S3 bucket will be under this prefix
28
+ // * delimiter: optional, directory delimiter, default is '/'
29
+ const s3 = await mobiletto('s3', aws_key, aws_secret, {bucket: 'bk', region: 'us-east-1'})
30
+
31
+ // list files
32
+ local.list() // --> returns an array of file objects
33
+ s3.list() // --> returns an array of file objects
34
+
35
+ // list files in a directory
36
+ const path = 'some/path'
37
+ local.list(path) // --> returns an array of file objects
38
+ s3.list(path) // --> returns an array of file objects
39
+
40
+ // read metadata for a file
41
+ local.metadata(path)
42
+ s3.metadata(path)
43
+
44
+ // read a file
45
+ // Provide a callback that writes the data someplace
46
+ const callback = (chunk) => { ... write chunk somewhere ... }
47
+ local.read(path, callback)
48
+ s3.read(path, callback)
49
+
50
+ // write a file
51
+ // Provide a generator function that yields chunks of data
52
+ const generator = function* () {
53
+ while ( ... more-data-to-return ... ) {
54
+ data = ... load-data ...
55
+ yield data
56
+ }
57
+ }
58
+ local.write(path, generator)
59
+ s3.write(path, generator)
60
+
61
+ // delete a file
62
+ // Quiet param is optional (default false), when set errors will not be thrown if the path does not exist
63
+ const quiet = true
64
+ local.remove(path, {quiet})
65
+ s3.remove(path, {quiet})
66
+
67
+ // recursively delete a directory
68
+ const recursive = true
69
+ local.remove(path, {recursive, quiet})
70
+ s3.remove(path, {recursive, quiet})
71
+
72
+ # Driver Interface
73
+ A driver is any JS file that exports a 'storageClient' function with this signature:
74
+
75
+ function storageClient (key, secret, opts)
76
+
77
+ * `key`: a string, your API key (for the `local` driver this is the base directory)
78
+ * `secret`: a string, your API secret (can be omitted for the `local` driver)
79
+ * `opts`: an object, the properties are per-driver:
80
+ * For `local`, the `mode` property is the file permissions to set when creating new files and directories
81
+ * For `s3`, the `bucket` property is required. Optional properties are:
82
+ * `region`: the S3 region, default is us-east-1
83
+ * `prefix`: a prefix to prepend to all S3 paths, default is the empty string
84
+ * `delimiter`: the directory delimiter, default is '/'
85
+
86
+ The object that the storageClient function returns must define these functions:
87
+
88
+ // Find DNS records that match the given domain, type (if provided) and name (if provided)
89
+ async list (path) // path may be omitted
90
+
91
+ // Read metadata for a path
92
+ async metadata (path)
93
+
94
+ // Read a file
95
+ async read (path, callback) // callback receives a chunk of data; a null chunk signals end of data
96
+
97
+ // Write a file
98
+ async write (path, readFunc) // readFunc returns the data you want to write, or null to finish
99
+
100
+ // Remove a file, or recursively delete a directory
101
+ async remove (path, {recursive = false, quiet = false})
@@ -0,0 +1,198 @@
1
+ const { dirname } = require('path')
2
+
3
+ const {
4
+ M_FILE, M_DIR, M_LINK, M_SPECIAL,
5
+ MobilettoError, writeStream, closeStream, MobilettoNotFoundError
6
+ } = require('../../index')
7
+
8
+ const fs = require('fs')
9
+
10
+ const DEFAULT_MODE = '0700'
11
+
12
+ class StorageClient {
13
+ baseDir
14
+ mode
15
+ constructor(baseDir, opts) {
16
+ const resolved = this.resolveSymlinks(baseDir)
17
+ if (!resolved.stat.isDirectory()) {
18
+ const dest = resolved.path === baseDir ? null : resolved.path
19
+ throw new MobilettoError(`local.storageClient: not a directory: ${baseDir}${dest ? ` (resolved to ${dest})` : ''}`)
20
+ }
21
+ const dir = resolved.path
22
+ this.baseDir = dir.endsWith('/') ? dir : dir + '/'
23
+ this.mode = opts && opts.mode ? opts.mode : DEFAULT_MODE
24
+ }
25
+ resolveSymlinks (path) {
26
+ let stat = fs.lstatSync(path)
27
+ let symlinksFollowed = false
28
+ while (!stat.isDirectory() && stat.isSymbolicLink()) {
29
+ path = fs.readlinkSync(path)
30
+ if (path.startsWith('private/')) {
31
+ path = '/' + path
32
+ }
33
+ stat = fs.lstatSync(path)
34
+ symlinksFollowed = true
35
+ }
36
+ return { path, stat }
37
+ }
38
+ async testConfig () {
39
+ return await this.list()
40
+ }
41
+ fileType (stat) {
42
+ if (stat.isDirectory()) {
43
+ return M_DIR
44
+ }
45
+ if (stat.isFile()) {
46
+ return M_FILE
47
+ }
48
+ if (stat.isSymbolicLink()) {
49
+ return M_LINK
50
+ }
51
+ return M_SPECIAL
52
+ }
53
+ normalizePath(path) {
54
+ if (path.startsWith('/')) {
55
+ path = path.substring(1)
56
+ }
57
+ return this.baseDir + path
58
+ }
59
+ async list (path = '') {
60
+ const dir = this.normalizePath(path)
61
+ try {
62
+ const files = fs.readdirSync(dir)
63
+ return files.map(f => {
64
+ const stat = fs.lstatSync(dir + '/' + f)
65
+ const type = this.fileType(stat)
66
+ const entry = {
67
+ name: f,
68
+ type
69
+ }
70
+ if (type === M_LINK) {
71
+ const resolved = this.resolveSymlinks(dir + '/' + f)
72
+ entry.link = resolved.path
73
+ }
74
+ return entry
75
+ })
76
+ } catch (err) {
77
+ throw new MobilettoError(`list(${path}) error: ${err}`, err)
78
+ }
79
+ }
80
+ async metadata (path) {
81
+ const file = this.normalizePath(path)
82
+ try {
83
+ const lstat = fs.lstatSync(file)
84
+ if (!lstat) {
85
+ throw new MobilettoError(`metadata: lstat error`)
86
+ }
87
+ return {
88
+ name: file.startsWith(this.baseDir) ? file.substring(this.baseDir.length) : file,
89
+ type: this.fileType(lstat),
90
+ size: lstat.size,
91
+ mtime: lstat.mtimeMs
92
+ }
93
+ } catch (err) {
94
+ if (err.code && err.code === 'ENOENT') {
95
+ throw new MobilettoNotFoundError(path)
96
+ }
97
+ throw new MobilettoError(`metadata(${path}) error: ${err}`, err)
98
+ }
99
+ }
100
+
101
+ mkdirs (path) {
102
+ try {
103
+ // console.log(`mkdirs: creating directory: ${path}`)
104
+ fs.mkdirSync(path, {recursive: true, mode: this.mode})
105
+ } catch (err) {
106
+ throw new MobilettoError(`mkdirs: error creating directory ${path}: ${err}`, err)
107
+ }
108
+ }
109
+
110
+ async write (path, generator) {
111
+ const file = this.normalizePath(path)
112
+
113
+ // console.log(`read: reading path: ${path} - ${file}`)
114
+ const parent = dirname(file)
115
+ let dirStat
116
+ try {
117
+ dirStat = fs.lstatSync(parent)
118
+ } catch (err) {
119
+ if (err.code && err.code === 'ENOENT') {
120
+ this.mkdirs(parent)
121
+ } else {
122
+ throw new MobilettoError(`write: lstat error on ${parent}: ${err}`, err)
123
+ }
124
+ }
125
+ if (typeof dirStat === 'undefined') {
126
+ this.mkdirs(parent)
127
+ } else if (!dirStat.isDirectory()) {
128
+ throw new MobilettoError(`write: not a directory: ${parent} (cannot write file ${file})`)
129
+ }
130
+
131
+ // console.log(`write: writing path ${path} -> ${file}`)
132
+ const stream = fs.createWriteStream(file, {mode: this.mode})
133
+ const writer = writeStream(stream)
134
+ const closer = closeStream(stream)
135
+ let count = 0
136
+ let chunk = generator.next().value
137
+ while (chunk) {
138
+ count += chunk.length
139
+ writer(chunk)
140
+ chunk = generator.next().value
141
+ }
142
+ closer()
143
+ return Promise.resolve(count)
144
+ }
145
+
146
+ async read (path, callback) {
147
+ const file = this.normalizePath(path)
148
+ // console.log(`read: reading path: ${path} - ${file}`)
149
+ try {
150
+ const stream = fs.createReadStream(file)
151
+ let count = 0
152
+ const streamHandler = stream =>
153
+ new Promise((resolve, reject) => {
154
+ stream.on('data', (data) => {
155
+ count += data ? data.length : 0
156
+ callback(data)
157
+ })
158
+ stream.on('error', reject)
159
+ stream.on('end', resolve)
160
+ })
161
+ await streamHandler(stream)
162
+ return count
163
+ } catch (err) {
164
+ if (err.code && err.code === 'ENOENT') {
165
+ throw new MobilettoNotFoundError(path)
166
+ }
167
+ throw new MobilettoError(`read(${path}) error: ${err}`, err)
168
+ }
169
+ }
170
+
171
+ async remove (path, options) {
172
+ const recursive = options && options.recursive ? options.recursive : false
173
+ const quiet = options && options.quiet ? options.quiet : false
174
+ const file = this.normalizePath(path)
175
+ // console.log(`remove: deleting path: ${path} = ${file}`)
176
+ try {
177
+ fs.rmSync(file, {recursive: recursive, force: quiet, maxRetries: 2})
178
+ } catch (err) {
179
+ if (err.code && err.code === 'ENOENT') {
180
+ if (!quiet) {
181
+ throw new MobilettoNotFoundError(path)
182
+ }
183
+ } else {
184
+ throw new MobilettoError(`remove(${path}) error: ${err}`, err)
185
+ }
186
+ }
187
+ return Promise.resolve(true)
188
+ }
189
+ }
190
+
191
+ function storageClient (key, secret, opts) {
192
+ if (!key) {
193
+ throw new MobilettoError('local.storageClient: key is required')
194
+ }
195
+ return new StorageClient(key, opts)
196
+ }
197
+
198
+ module.exports = {storageClient}
@@ -0,0 +1,261 @@
1
+ const { MobilettoError, M_DIR, M_FILE, MobilettoNotFoundError} = require('../../index')
2
+
3
+ const {
4
+ S3Client,
5
+ ListObjectsCommand,
6
+ HeadObjectCommand, GetObjectCommand, DeleteObjectCommand, DeleteObjectsCommand, NoSuchKey
7
+ } = require('@aws-sdk/client-s3')
8
+
9
+ const { Readable } = require('stream')
10
+ const {Upload} = require("@aws-sdk/lib-storage")
11
+
12
+ const DEFAULT_REGION = 'us-east-1'
13
+ const DEFAULT_PREFIX = ''
14
+ const DEFAULT_DELIMITER = '/'
15
+
16
+ const DELETE_OBJECTS_MAX_KEYS = 1000
17
+
18
+ class StorageClient {
19
+ client
20
+ region
21
+ bucket
22
+ prefix
23
+ delimiter
24
+ constructor(key, secret, opts) {
25
+ if (!key || !secret || !opts || !opts.bucket) {
26
+ throw new MobilettoError('key, secret, and opts.bucket are required')
27
+ }
28
+ this.bucket = opts.bucket
29
+ const delim = this.delimiter = opts.delimiter || DEFAULT_DELIMITER
30
+ this.prefix = opts.prefix || DEFAULT_PREFIX
31
+ ? opts.prefix.endsWith(delim)
32
+ ? opts.prefix
33
+ : opts.prefix + delim
34
+ : ''
35
+ this.region = opts.region || DEFAULT_REGION
36
+ const credentials = {
37
+ accessKeyId: key,
38
+ secretAccessKey: secret
39
+ }
40
+ this.client = new S3Client({region: this.region, credentials})
41
+ }
42
+
43
+ async testConfig () {
44
+ return await this._list('', { MaxKeys: 1 })
45
+ }
46
+
47
+ async list (path = '') {
48
+ return (await this._list(path)).map(obj => {
49
+ return {
50
+ name: obj,
51
+ type: obj.endsWith(this.delimiter) ? M_DIR : M_FILE
52
+ }
53
+ })
54
+ }
55
+
56
+ async _list (path, params = {}, recursive = false) {
57
+ const logPrefix = `_list(path=${path}):`
58
+
59
+ // Declare truncated as a flag that the while loop is based on.
60
+ let truncated = true
61
+
62
+ const Prefix = this.prefix +
63
+ (path.startsWith(this.delimiter) ? path.substring(0) : path) +
64
+ (path.length === 0 || path.endsWith(this.delimiter) ? '' : this.delimiter)
65
+ const bucketParams = Object.assign({}, params, {
66
+ Region: this.region,
67
+ Bucket: this.bucket,
68
+ Prefix
69
+ })
70
+ if (!recursive) {
71
+ bucketParams.Delimiter = this.delimiter
72
+ }
73
+ const objects = []
74
+ // console.log(`${logPrefix} bucketParams=${JSON.stringify(bucketParams)}`)
75
+
76
+ // while loop that runs until 'response.truncated' is false.
77
+ while (truncated) {
78
+ try {
79
+ const response = await this.client.send(new ListObjectsCommand(bucketParams))
80
+ if (typeof response.Contents !== 'undefined') {
81
+ response.Contents.forEach((item) => {
82
+ objects.push(item.Key) // todo: transform into standard object
83
+ })
84
+ }
85
+ if (typeof response.CommonPrefixes !== 'undefined') {
86
+ response.CommonPrefixes.forEach((item) => {
87
+ objects.push(item.Prefix) // todo: transform into standard object
88
+ })
89
+ }
90
+ truncated = response.IsTruncated
91
+ // If truncated is true, advance the marker
92
+ if (truncated) {
93
+ bucketParams.Marker = response.NextMarker
94
+ }
95
+ // At end of the list, response.truncated is false, and the function exits the while loop.
96
+ } catch (err) {
97
+ console.log(`${logPrefix} Error: ${err}`)
98
+ truncated = false
99
+ }
100
+ }
101
+ return objects
102
+ }
103
+
104
+ normalizeKey = (path) =>
105
+ path.startsWith(this.prefix)
106
+ ? path
107
+ : this.prefix + (path.startsWith(this.delimiter) ? path.substring(1) : path)
108
+
109
+ s3error (err, key, path, method) {
110
+ return (err instanceof MobilettoError || err instanceof MobilettoNotFoundError)
111
+ ? err
112
+ : (err instanceof NoSuchKey) || (err.name && err.name === 'NotFound')
113
+ ? new MobilettoNotFoundError(key)
114
+ : new MobilettoError(`${method}(${path}) error: ${err}`, err)
115
+ }
116
+
117
+ async metadata (path) {
118
+ const Key = this.normalizeKey(path)
119
+ const bucketParams = {
120
+ Region: this.region,
121
+ Bucket: this.bucket,
122
+ Key,
123
+ Delimiter: this.delimiter
124
+ }
125
+ try {
126
+ const head = await this.client.send(new HeadObjectCommand(bucketParams))
127
+ const meta = {
128
+ name: path,
129
+ size: head.ContentLength
130
+ }
131
+ if (head.LastModified) {
132
+ meta.mtime = Date.parse(head.LastModified)
133
+ }
134
+ return meta
135
+ } catch (err) {
136
+ throw this.s3error(err, Key, path, 'metadata')
137
+ }
138
+ }
139
+
140
+ async write (path, generator) {
141
+ const Key = this.normalizeKey(path)
142
+ const bucketParams = {
143
+ Region: this.region,
144
+ Bucket: this.bucket,
145
+ Key,
146
+ Body: Readable.from(generator),
147
+ Delimiter: this.delimiter
148
+ }
149
+
150
+ const uploader = new Upload({
151
+ client: this.client,
152
+ params: bucketParams,
153
+ queueSize: 1, // optional concurrency configuration
154
+ partSize: 1024 * 1024 * 5, // optional size of each part, in bytes, at least 5MB
155
+ leavePartsOnError: false // optional manually handle dropped parts
156
+ })
157
+ let total = 0
158
+ uploader.on('httpUploadProgress', (progress) => {
159
+ // console.log(`write(${bucketParams.Key}): ${JSON.stringify(progress)}`)
160
+ total += progress.loaded
161
+ })
162
+ const response = await uploader.done()
163
+ if (response.Key !== Key) {
164
+ throw new MobilettoError(`s3.write: after writing, expected Key=${Key} but found response.Key=${response.Key}`)
165
+ }
166
+ return total
167
+ }
168
+
169
+ async read (path, callback) {
170
+ const Key = this.normalizeKey(path)
171
+ // console.log(`read: reading Key: ${path} - ${Key}`)
172
+ const bucketParams = {
173
+ Region: this.region,
174
+ Bucket: this.bucket,
175
+ Key,
176
+ Delimiter: this.delimiter
177
+ }
178
+ try {
179
+ const data = await this.client.send(new GetObjectCommand(bucketParams))
180
+ let count = 0
181
+ const streamHandler = stream =>
182
+ new Promise((resolve, reject) => {
183
+ stream.on('data', (data) => {
184
+ count += data ? data.length : 0
185
+ callback(data)
186
+ })
187
+ stream.on('error', reject)
188
+ stream.on('end', resolve)
189
+ })
190
+ await streamHandler(data.Body)
191
+ return count
192
+ } catch (err) {
193
+ throw this.s3error(err, Key, path, 'read')
194
+ }
195
+ }
196
+
197
+ async remove (path, options = null) {
198
+ const recursive = options && options.recursive
199
+ const quiet = options && options.quiet
200
+ if (recursive) {
201
+ let objects = await this._list(path, { MaxKeys: DELETE_OBJECTS_MAX_KEYS }, true)
202
+ while (objects && objects.length > 0) {
203
+ const Delete = {
204
+ Objects: objects.map(obj => { return {Key: obj} })
205
+ }
206
+ if (quiet) {
207
+ Delete.Quiet = true
208
+ }
209
+ const bucketParams = {
210
+ Region: this.region,
211
+ Bucket: this.bucket,
212
+ Delete
213
+ }
214
+ // console.log(`remove(${path}): deleting objects: ${JSON.stringify(objects)}`)
215
+ const response = await this.client.send(new DeleteObjectsCommand(bucketParams))
216
+ let statusCode = response.$metadata.httpStatusCode
217
+ let statusClass = Math.floor(statusCode / 100)
218
+ if (statusClass !== 2) {
219
+ throw new MobilettoError(`remove(${path}): DeleteObjectsCommand returned HTTP status ${statusCode}`)
220
+ }
221
+ if (!quiet && response.Errors && response.Errors.length > 0) {
222
+ throw new MobilettoError(`remove(${path}): DeleteObjectsCommand returned Errors: ${JSON.stringify(response.Errors)}`)
223
+ }
224
+ objects = await this._list(path, {MaxKeys: DELETE_OBJECTS_MAX_KEYS})
225
+ }
226
+ } else {
227
+ const Key = this.normalizeKey(path)
228
+ const bucketParams = {
229
+ Region: this.region,
230
+ Bucket: this.bucket,
231
+ Key
232
+ }
233
+ try {
234
+ // DeleteObjectCommand silently succeeds and returns HTTP 204 even for non-existent Keys
235
+ // Thus, if quiet is false, we must check metadata explicitly, which will fail with
236
+ // MobilettoNotFoundError, which is the correct behavior
237
+ if (!quiet) {
238
+ await this.metadata(path)
239
+ }
240
+ const response = await this.client.send(new DeleteObjectCommand(bucketParams))
241
+ let statusCode = response.$metadata.httpStatusCode
242
+ let statusClass = Math.floor(statusCode / 100)
243
+ if (statusClass !== 2) {
244
+ throw new MobilettoError(`remove: DeleteObjectCommand returned HTTP status ${statusCode}`)
245
+ }
246
+ } catch (err) {
247
+ throw this.s3error(err, Key, path, 'remove')
248
+ }
249
+ }
250
+ return true
251
+ }
252
+ }
253
+
254
+ function storageClient (key, secret, opts) {
255
+ if (!key || !secret || !opts || !opts.bucket) {
256
+ throw new MobilettoError('key, secret, and opts.bucket are required')
257
+ }
258
+ return new StorageClient(key, secret, opts)
259
+ }
260
+
261
+ module.exports = {storageClient}
package/index.js ADDED
@@ -0,0 +1,75 @@
1
+ // adapted from https://stackoverflow.com/a/27724419
2
+ function MobilettoError (message, err) {
3
+ this.message = `${message}`
4
+ this.err = err
5
+ // Use V8's native method if available, otherwise fallback
6
+ if ('captureStackTrace' in Error) {
7
+ Error.captureStackTrace(this, TypeError)
8
+ } else {
9
+ this.stack = (new Error(this.message)).stack
10
+ }
11
+ }
12
+
13
+ // adapted from https://stackoverflow.com/a/27724419
14
+ function MobilettoNotFoundError (message) {
15
+ this.message = `${message}`
16
+ // Use V8's native method if available, otherwise fallback
17
+ if ('captureStackTrace' in Error) {
18
+ Error.captureStackTrace(this, TypeError)
19
+ } else {
20
+ this.stack = (new Error(this.message)).stack
21
+ }
22
+ }
23
+
24
+ async function mobiletto (driverPath, key, secret, opts) {
25
+ const driver = require(driverPath.includes('/') ? driverPath : `./drivers/${driverPath}/index.js`)
26
+ const client = driver.storageClient(key, secret, opts)
27
+ if (!(await client.testConfig())) {
28
+ throw new MobilettoError(`mobiletti(${driverPath}) error: test API call failed`)
29
+ }
30
+ return client
31
+ }
32
+
33
+ function writeStream (stream) {
34
+ return (chunk) => {
35
+ if (chunk) {
36
+ stream.write(chunk, (err) => {
37
+ if (err) {
38
+ console.log(`writeStream: error writing: ${err}`)
39
+ throw err
40
+ }
41
+ })
42
+ }
43
+ }
44
+ }
45
+
46
+ function closeStream (stream) {
47
+ return () => stream.close((err) => {
48
+ if (err) {
49
+ console.log(`closeStream: error closing: ${err}`)
50
+ throw err
51
+ }
52
+ })
53
+ }
54
+
55
+ function readCloseHandler (promise, closeHandler) {
56
+ return () => {
57
+ if (closeHandler) {
58
+ closeHandler()
59
+ }
60
+ promise.resolve()
61
+ }
62
+ }
63
+
64
+ const M_FILE = 'file'
65
+ const M_DIR = 'dir'
66
+ const M_LINK = 'link'
67
+ const M_SPECIAL = 'special'
68
+
69
+ module.exports = {
70
+ M_FILE, M_DIR, M_LINK, M_SPECIAL,
71
+ mobiletto,
72
+ MobilettoError, MobilettoNotFoundError,
73
+ writeStream, closeStream, readCloseHandler
74
+ }
75
+
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "mobiletto",
3
+ "version": "1.0.2",
4
+ "description": "A storage abstraction layer",
5
+ "main": "index.js",
6
+ "author": "Jonathan Cobb",
7
+ "license": "Apache-2.0",
8
+ "scripts": {
9
+ "test": "mocha --timeout 10000"
10
+ },
11
+ "devDependencies": {
12
+ "@babel/core": "^7.18.10",
13
+ "@babel/node": "^7.18.10",
14
+ "@babel/preset-env": "^7.18.10",
15
+ "chai": "^4.3.6",
16
+ "dotenv": "^16.0.1",
17
+ "mocha": "^10.0.0",
18
+ "randomstring": "^1.2.2"
19
+ },
20
+ "dependencies": {
21
+ "@aws-sdk/client-s3": "^3.150.0",
22
+ "@aws-sdk/lib-storage": "^3.150.0",
23
+ "node-fetch-commonjs": "^3.1.1"
24
+ }
25
+ }
@@ -0,0 +1,238 @@
1
+ // To run the tests, you need a .env file one level above this directory
2
+ // that contains env vars for all the process.env stuff in DRIVER_CONFIG below
3
+ require('dotenv').config()
4
+
5
+ const randomstring = require('randomstring')
6
+
7
+ const { expect, should, assert } = require('chai')
8
+
9
+ const { mobiletto } = require('../index.js')
10
+ const {MobilettoNotFoundError, M_FILE, M_DIR} = require("../index")
11
+
12
+ // chunk size used by generator function, used by driver's 'write' function
13
+ // the temp file is also TEMP_SZ_MULTIPLE of this number
14
+ const READ_SZ = 8 * 1024 // xfer data in 8k chunks
15
+ const TEMP_SZ_MULTIPLE = 3 // temp file will be ~24k (READ_SZ * 3)
16
+
17
+ DRIVER_CONFIG = {
18
+ local: {
19
+ key: '/tmp'
20
+ },
21
+ s3: {
22
+ key: process.env.S3_ACCESS,
23
+ secret: process.env.S3_SECRET,
24
+ opts: {
25
+ bucket: process.env.S3_BUCKET,
26
+ prefix: process.env.S3_PREFIX,
27
+ region: process.env.S3_REGION
28
+ }
29
+ }
30
+ }
31
+
32
+ async function assertMeta (api, name, expectedSize) {
33
+ const meta = await api.metadata(name)
34
+ should().exist(meta, 'expected return value from metadata call')
35
+ expect(meta.size).equals(expectedSize, 'expected size of written file to equal size of randomData')
36
+ expect(meta.name).equals(name, 'expected name of written file to be correct')
37
+ }
38
+
39
+ async function assertMetaFail (api, name) {
40
+ try {
41
+ const meta = await api.metadata(name)
42
+ assert.fail(`loading metadata after deletion, did not expect to get meta: ${meta ? JSON.stringify(meta) : 'null or undefined'}`)
43
+ } catch (err) {
44
+ if (!(err instanceof MobilettoNotFoundError)) {
45
+ // MobilettoNotFoundError is expected
46
+ assert.fail(`loading metadata after deletion, got err: ${err}`)
47
+ }
48
+ }
49
+ }
50
+
51
+ function rand (count) {
52
+ return randomstring.generate(count)
53
+ }
54
+
55
+ // To test a single driver:
56
+ // - Uncomment one of the lines below to set driverName to the one you want to test
57
+ // - Comment out the next `for` line, and its closing curly brace (just before EOF)
58
+
59
+ // const driverName = 'local'
60
+ // const driverName = 's3'
61
+
62
+ // When you're NOT testing a single driver, it's important that *all* tests remain
63
+ // within the singular 'for' loop below. This ensures that all drivers pass exactly
64
+ // the same set of tests, with exactly the same inputs/outputs.
65
+ // This greatly supports developer sanity
66
+
67
+ for (const driverName of Object.keys(DRIVER_CONFIG)) {
68
+ const config = DRIVER_CONFIG[driverName]
69
+ const nonexistentFile = 'random_file_that_does_not_exist_' + rand(100) + '_' + Date.now()
70
+ const tempFilename = (name, i) => name + (i > 0 ? '_' + i : '')
71
+ describe(`${driverName} test`, () => {
72
+ describe(`${driverName} - create api client`, () => {
73
+ it("should validate the config and return an API object", async () => {
74
+ const api = await mobiletto(driverName, config.key, config.secret, config.opts)
75
+ should().exist(api, 'expected API object to exist')
76
+ })
77
+ })
78
+
79
+ describe(`${driverName} - listing with no arguments returns some results`, () => {
80
+ it("should return some results from a default listing", async () => {
81
+ const api = await mobiletto(driverName, config.key, config.secret, config.opts)
82
+ const results = await api.list()
83
+ expect(results).to.have.lengthOf.greaterThan(0, 'expected some results in the default listing')
84
+ })
85
+ })
86
+
87
+ describe(`${driverName} - write a file, read file, read metadata, delete file`, () => {
88
+ // some random data, plus a bit extra
89
+ const size = (READ_SZ * TEMP_SZ_MULTIPLE) + Math.floor(Math.random() * (READ_SZ/2))
90
+ const randomData = rand(size)
91
+ const fileSuffix = '' + Date.now()
92
+ let fixture
93
+ beforeEach((done) => {
94
+ const name = `test_file_${fileSuffix}`
95
+ mobiletto(driverName, config.key, config.secret, config.opts)
96
+ .then(api => { fixture = {api, name, randomData} })
97
+ .finally(done)
98
+ })
99
+ it("should write a file", async () => {
100
+ const data = fixture.randomData
101
+
102
+ function* dataGenerator() {
103
+ // read in 8k chunks
104
+ for (let i = 0; i < data.length; i += READ_SZ) {
105
+ const end = (i + READ_SZ) > data.length ? data.length : (i + READ_SZ)
106
+ yield data.slice(i, end)
107
+ }
108
+ }
109
+
110
+ const response = await fixture.api.write(fixture.name, dataGenerator())
111
+ expect(response).to.equal(data.length, 'expected write API to return correct number of bytes written')
112
+ })
113
+ it("should read the file we just wrote", async () => {
114
+ const chunks = []
115
+ function reader(chunk) {
116
+ if (chunk) {
117
+ chunks.push(chunk)
118
+ }
119
+ }
120
+ const response = await fixture.api.read(fixture.name, reader)
121
+ const data = Buffer.concat(chunks)
122
+ expect(response).is.equal(data.length, 'expected read API to return correct number of bytes read')
123
+ expect(data.toString('utf8')).to.equal(fixture.randomData, 'expected to read back the same data we wrote')
124
+ })
125
+ it("should load metadata on the file we just wrote", async () => {
126
+ await assertMeta (fixture.api, fixture.name, fixture.randomData.length)
127
+ })
128
+ it("should delete the file we just wrote", async () => {
129
+ const removed = await fixture.api.remove(fixture.name)
130
+ expect(removed).to.be.true
131
+ })
132
+ it("loading metadata on the file we wrote now fails", async () => {
133
+ await assertMetaFail(fixture.api, fixture.name)
134
+ })
135
+ })
136
+
137
+ describe(`${driverName} - write files in a new dir, read metadata, recursively delete`, () => {
138
+ // a random directory and file within it
139
+ const randomParent = `random_dir_${rand(10)}`
140
+ const subdirName = `subdir_` + Date.now()
141
+ const randomPath = `${randomParent}/${subdirName}/random_file_${Date.now()}`
142
+ const fileCount = 3 + Math.floor(Math.random() * 10)
143
+ let fixture
144
+ beforeEach((done) => {
145
+ mobiletto(driverName, config.key, config.secret, config.opts)
146
+ .then(api => { fixture = {api, name: randomPath} })
147
+ .finally(done)
148
+ })
149
+ it(`should write ${fileCount} files in a new directory`, async () => {
150
+ function* dataGenerator() {
151
+ // return one chunk of random data
152
+ yield rand(READ_SZ)
153
+ }
154
+ for (let i = 0; i < fileCount; i++) {
155
+ const response = await fixture.api.write(tempFilename(fixture.name, i), dataGenerator())
156
+ expect(response).to.equal(READ_SZ, 'expected write API to return correct number of bytes written')
157
+ }
158
+ })
159
+ it("should load metadata for one of the new files", async () => {
160
+ await assertMeta (fixture.api, fixture.name, READ_SZ)
161
+ })
162
+ it("should see correct types on objects returned from a listing of the new directory", async () => {
163
+ const objects = await fixture.api.list(randomParent)
164
+ expect(objects).to.have.lengthOf(1)
165
+ expect(objects[0]).to.have.property('type', M_DIR, `subdir should have type ${M_DIR}`)
166
+ })
167
+ it("should see correct types on objects returned from a listing of the subdirectory", async () => {
168
+ const objects = await fixture.api.list(`${randomParent}/${subdirName}`)
169
+ expect(objects).to.have.lengthOf(fileCount)
170
+ for (let i = 0; i < fileCount; i++) {
171
+ // we should find all the files, and they should all have the correct type
172
+ expect(objects
173
+ .find(o => (o.type === M_FILE && o.name === tempFilename(fixture.name, i)))
174
+ ).to.not.be.null
175
+ }
176
+ })
177
+ it("should recursively delete the directory and file we just created", async () => {
178
+ const recursive = true
179
+ const removed = await fixture.api.remove(randomParent, {recursive})
180
+ expect(removed).to.be.true
181
+ })
182
+ it("loading metadata on the file we wrote now fails", async () => {
183
+ await assertMetaFail(fixture.api, fixture.name)
184
+ })
185
+ it("loading metadata on the parent dir we wrote now fails", async () => {
186
+ await assertMetaFail(fixture.api, randomParent)
187
+ })
188
+ })
189
+
190
+ describe(`${driverName} - expect MobilettoNotFoundError when reading nonexistent file `, () => {
191
+ it("should throw MobilettoNotFoundError when trying to read a file that does not exist", async () => {
192
+ const api = await mobiletto(driverName, config.key, config.secret, config.opts)
193
+ try {
194
+ await api.read(nonexistentFile, () => {
195
+ assert.fail(`ERROR: reading non-existent file should NOT succeed`)
196
+ })
197
+ } catch (err) {
198
+ expect(err).to.be.instanceof(MobilettoNotFoundError, `expected MobilettoNotFoundError, got: ${err}`)
199
+ }
200
+ })
201
+ })
202
+
203
+ describe(`${driverName} - expect MobilettoNotFoundError when reading metadata for nonexistent file`, () => {
204
+ it("should throw MobilettoNotFoundError when trying to read metadata for a file that does not exist", async () => {
205
+ const api = await mobiletto(driverName, config.key, config.secret, config.opts)
206
+ try {
207
+ const meta = await api.metadata(nonexistentFile)
208
+ assert.fail(`ERROR: reading metadata for non-existent file should NOT succeed, but it returned ${meta ? JSON.stringify(meta) : 'null or undefined'}`)
209
+ } catch (err) {
210
+ expect(err).to.be.instanceof(MobilettoNotFoundError, `expected MobilettoNotFoundError, got: ${err}`)
211
+ }
212
+ })
213
+ })
214
+
215
+ describe(`${driverName} - expect MobilettoNotFoundError when removing non-existent file`, () => {
216
+ it("should throw MobilettoNotFoundError when trying to remove a file that does not exist", async () => {
217
+ const api = await mobiletto(driverName, config.key, config.secret, config.opts)
218
+ try {
219
+ if (await api.remove(nonexistentFile)) {
220
+ assert.fail('ERROR: removing non-existent file should NOT succeed')
221
+ }
222
+ } catch (err) {
223
+ expect(err).to.be.instanceof(MobilettoNotFoundError, `expected MobilettoNotFoundError, got: ${err}`)
224
+ }
225
+ })
226
+ })
227
+
228
+ describe(`${driverName} - quietly removing non-existent file does not throw MobilettoNotFoundError`, () => {
229
+ it("should NOT throw MobilettoNotFoundError when quietly removing a file that does not exist", async () => {
230
+ const api = await mobiletto(driverName, config.key, config.secret, config.opts)
231
+ if (!(await api.remove(nonexistentFile, {quiet: true}))) {
232
+ assert.fail('ERROR: quietly removing non-existent file should still return true')
233
+ }
234
+ })
235
+ })
236
+
237
+ })
238
+ }