@naturalcycles/cloud-storage-lib 1.13.0 → 1.13.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.
@@ -0,0 +1,81 @@
1
+ import type { Storage, StorageOptions } from '@google-cloud/storage';
2
+ import { CommonLogger, LocalTimeInput } from '@naturalcycles/js-lib';
3
+ import type { ReadableBinary, ReadableTyped, WritableBinary } from '@naturalcycles/nodejs-lib';
4
+ import type { CommonStorage, CommonStorageGetOptions, FileEntry } from './commonStorage';
5
+ import type { GCPServiceAccount } from './model';
6
+ export type { Storage, StorageOptions, };
7
+ /**
8
+ * This object is intentionally made to NOT extend StorageOptions,
9
+ * because StorageOptions is complicated and provides just too many ways
10
+ * to configure credentials.
11
+ *
12
+ * Here we define the minimum simple set of credentials needed.
13
+ * All of these properties are available from the "service account" json file
14
+ * (either personal one or non-personal).
15
+ */
16
+ export interface CloudStorageCfg {
17
+ /**
18
+ * Default is console
19
+ */
20
+ logger?: CommonLogger;
21
+ /**
22
+ * Pass true for extra debugging
23
+ */
24
+ debug?: boolean;
25
+ }
26
+ /**
27
+ * CloudStorage implementation of CommonStorage API.
28
+ *
29
+ * API: https://googleapis.dev/nodejs/storage/latest/index.html
30
+ */
31
+ export declare class CloudStorage implements CommonStorage {
32
+ storage: Storage;
33
+ private constructor();
34
+ cfg: CloudStorageCfg & {
35
+ logger: CommonLogger;
36
+ };
37
+ static createFromGCPServiceAccount(credentials?: GCPServiceAccount, cfg?: CloudStorageCfg): CloudStorage;
38
+ static createFromStorageOptions(storageOptions?: StorageOptions, cfg?: CloudStorageCfg): CloudStorage;
39
+ /**
40
+ * Passing the pre-created Storage allows to instantiate it from both
41
+ * GCP Storage and FirebaseStorage.
42
+ */
43
+ static createFromStorage(storage: Storage, cfg?: CloudStorageCfg): CloudStorage;
44
+ ping(bucketName?: string): Promise<void>;
45
+ deletePath(bucketName: string, prefix: string): Promise<void>;
46
+ deletePaths(bucketName: string, prefixes: string[]): Promise<void>;
47
+ fileExists(bucketName: string, filePath: string): Promise<boolean>;
48
+ getFileNames(bucketName: string, opt?: CommonStorageGetOptions): Promise<string[]>;
49
+ getFileNamesStream(bucketName: string, opt?: CommonStorageGetOptions): ReadableTyped<string>;
50
+ getFilesStream(bucketName: string, opt?: CommonStorageGetOptions): ReadableTyped<FileEntry>;
51
+ getFile(bucketName: string, filePath: string): Promise<Buffer | null>;
52
+ /**
53
+ * Returns a Readable that is NOT object mode,
54
+ * so you can e.g pipe it to fs.createWriteStream()
55
+ */
56
+ getFileReadStream(bucketName: string, filePath: string): ReadableBinary;
57
+ saveFile(bucketName: string, filePath: string, content: Buffer): Promise<void>;
58
+ getFileWriteStream(bucketName: string, filePath: string): WritableBinary;
59
+ uploadFile(localFilePath: string, bucketName: string, bucketFilePath: string): Promise<void>;
60
+ setFileVisibility(bucketName: string, filePath: string, isPublic: boolean): Promise<void>;
61
+ getFileVisibility(bucketName: string, filePath: string): Promise<boolean>;
62
+ copyFile(fromBucket: string, fromPath: string, toPath: string, toBucket?: string): Promise<void>;
63
+ moveFile(fromBucket: string, fromPath: string, toPath: string, toBucket?: string): Promise<void>;
64
+ movePath(fromBucket: string, fromPrefix: string, toPrefix: string, toBucket?: string): Promise<void>;
65
+ deleteFiles(bucketName: string, filePaths: string[]): Promise<void>;
66
+ combineFiles(bucketName: string, filePaths: string[], toPath: string, toBucket?: string, currentRecursionDepth?: number): Promise<void>;
67
+ combine(bucketName: string, prefix: string, toPath: string, toBucket?: string): Promise<void>;
68
+ /**
69
+ * Acquires a "signed url", which allows bearer to use it to download ('read') the file.
70
+ *
71
+ * expires: 'v4' supports maximum duration of 7 days from now.
72
+ *
73
+ * @experimental - not tested yet
74
+ */
75
+ getSignedUrl(bucketName: string, filePath: string, expires: LocalTimeInput): Promise<string>;
76
+ /**
77
+ * Returns SKIP if fileName is a folder.
78
+ * If !fullPaths - strip away the folder prefix.
79
+ */
80
+ private normalizeFilename;
81
+ }
@@ -0,0 +1,248 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CloudStorage = void 0;
4
+ const js_lib_1 = require("@naturalcycles/js-lib");
5
+ const MAX_RECURSION_DEPTH = 10;
6
+ const BATCH_SIZE = 32;
7
+ /**
8
+ * CloudStorage implementation of CommonStorage API.
9
+ *
10
+ * API: https://googleapis.dev/nodejs/storage/latest/index.html
11
+ */
12
+ class CloudStorage {
13
+ constructor(storage, cfg = {}) {
14
+ this.storage = storage;
15
+ this.cfg = {
16
+ logger: console,
17
+ ...cfg,
18
+ };
19
+ }
20
+ static createFromGCPServiceAccount(credentials, cfg) {
21
+ const storageLib = require('@google-cloud/storage');
22
+ const storage = new storageLib.Storage({
23
+ credentials,
24
+ // Explicitly passing it here to fix this error:
25
+ // Error: Unable to detect a Project Id in the current environment.
26
+ // To learn more about authentication and Google APIs, visit:
27
+ // https://cloud.google.com/docs/authentication/getting-started
28
+ // at /root/repo/node_modules/google-auth-library/build/src/auth/googleauth.js:95:31
29
+ projectId: credentials?.project_id,
30
+ });
31
+ return new CloudStorage(storage, cfg);
32
+ }
33
+ static createFromStorageOptions(storageOptions, cfg) {
34
+ const storageLib = require('@google-cloud/storage');
35
+ const storage = new storageLib.Storage(storageOptions);
36
+ return new CloudStorage(storage, cfg);
37
+ }
38
+ /**
39
+ * Passing the pre-created Storage allows to instantiate it from both
40
+ * GCP Storage and FirebaseStorage.
41
+ */
42
+ static createFromStorage(storage, cfg) {
43
+ return new CloudStorage(storage, cfg);
44
+ }
45
+ async ping(bucketName) {
46
+ await this.storage.bucket(bucketName || 'non-existing-for-sure').exists();
47
+ }
48
+ async deletePath(bucketName, prefix) {
49
+ await this.deletePaths(bucketName, [prefix]);
50
+ }
51
+ async deletePaths(bucketName, prefixes) {
52
+ const bucket = this.storage.bucket(bucketName);
53
+ await (0, js_lib_1.pMap)(prefixes, async (prefix) => {
54
+ await bucket.deleteFiles({
55
+ prefix,
56
+ // to keep going in case error occurs, similar to THROW_AGGREGATED
57
+ force: true,
58
+ });
59
+ });
60
+ }
61
+ async fileExists(bucketName, filePath) {
62
+ const [exists] = await this.storage.bucket(bucketName).file(filePath).exists();
63
+ return exists;
64
+ }
65
+ async getFileNames(bucketName, opt = {}) {
66
+ const { prefix, fullPaths = true } = opt;
67
+ const [files] = await this.storage.bucket(bucketName).getFiles({
68
+ prefix,
69
+ });
70
+ if (fullPaths) {
71
+ // Paths that end with `/` are "folders", which are "virtual" in CloudStorage
72
+ // It doesn't make sense to return or do anything with them
73
+ return files.map(f => f.name).filter(s => !s.endsWith('/'));
74
+ }
75
+ return files.map(f => (0, js_lib_1._substringAfterLast)(f.name, '/')).filter(Boolean);
76
+ }
77
+ getFileNamesStream(bucketName, opt = {}) {
78
+ const { prefix, fullPaths = true } = opt;
79
+ return this.storage.bucket(bucketName).getFilesStream({
80
+ prefix,
81
+ maxResults: opt.limit || undefined,
82
+ }).flatMap(f => {
83
+ const r = this.normalizeFilename(f.name, fullPaths);
84
+ if (r === js_lib_1.SKIP)
85
+ return [];
86
+ return [r];
87
+ });
88
+ }
89
+ getFilesStream(bucketName, opt = {}) {
90
+ const { prefix, fullPaths = true } = opt;
91
+ return this.storage.bucket(bucketName).getFilesStream({
92
+ prefix,
93
+ maxResults: opt.limit || undefined,
94
+ }).flatMap(async (f) => {
95
+ const filePath = this.normalizeFilename(f.name, fullPaths);
96
+ if (filePath === js_lib_1.SKIP)
97
+ return [];
98
+ const [content] = await f.download();
99
+ return [{ filePath, content }];
100
+ }, {
101
+ concurrency: 16,
102
+ });
103
+ }
104
+ async getFile(bucketName, filePath) {
105
+ const [buf] = await this.storage
106
+ .bucket(bucketName)
107
+ .file(filePath)
108
+ .download()
109
+ .catch(err => {
110
+ if (err?.code === 404)
111
+ return [null]; // file not found
112
+ throw err; // rethrow otherwise
113
+ });
114
+ return buf;
115
+ }
116
+ /**
117
+ * Returns a Readable that is NOT object mode,
118
+ * so you can e.g pipe it to fs.createWriteStream()
119
+ */
120
+ getFileReadStream(bucketName, filePath) {
121
+ return this.storage.bucket(bucketName).file(filePath).createReadStream();
122
+ }
123
+ async saveFile(bucketName, filePath, content) {
124
+ await this.storage.bucket(bucketName).file(filePath).save(content);
125
+ }
126
+ getFileWriteStream(bucketName, filePath) {
127
+ return this.storage.bucket(bucketName).file(filePath).createWriteStream();
128
+ }
129
+ async uploadFile(localFilePath, bucketName, bucketFilePath) {
130
+ await this.storage.bucket(bucketName).upload(localFilePath, {
131
+ destination: bucketFilePath,
132
+ });
133
+ }
134
+ async setFileVisibility(bucketName, filePath, isPublic) {
135
+ await this.storage.bucket(bucketName).file(filePath)[isPublic ? 'makePublic' : 'makePrivate']();
136
+ }
137
+ async getFileVisibility(bucketName, filePath) {
138
+ const [isPublic] = await this.storage.bucket(bucketName).file(filePath).isPublic();
139
+ return isPublic;
140
+ }
141
+ async copyFile(fromBucket, fromPath, toPath, toBucket) {
142
+ await this.storage
143
+ .bucket(fromBucket)
144
+ .file(fromPath)
145
+ .copy(this.storage.bucket(toBucket || fromBucket).file(toPath));
146
+ }
147
+ async moveFile(fromBucket, fromPath, toPath, toBucket) {
148
+ await this.storage
149
+ .bucket(fromBucket)
150
+ .file(fromPath)
151
+ .move(this.storage.bucket(toBucket || fromBucket).file(toPath));
152
+ }
153
+ async movePath(fromBucket, fromPrefix, toPrefix, toBucket) {
154
+ (0, js_lib_1._assert)(fromPrefix.endsWith('/'), 'fromPrefix should end with `/`');
155
+ (0, js_lib_1._assert)(toPrefix.endsWith('/'), 'toPrefix should end with `/`');
156
+ await this.storage
157
+ .bucket(fromBucket)
158
+ .getFilesStream({
159
+ prefix: fromPrefix,
160
+ })
161
+ .forEach(async (file) => {
162
+ const { name } = file;
163
+ const newName = toPrefix + name.slice(fromPrefix.length);
164
+ await file.move(this.storage.bucket(toBucket || fromBucket).file(newName));
165
+ });
166
+ }
167
+ async deleteFiles(bucketName, filePaths) {
168
+ await (0, js_lib_1.pMap)(filePaths, async (filePath) => {
169
+ await this.storage.bucket(bucketName).file(filePath).delete();
170
+ });
171
+ }
172
+ async combineFiles(bucketName, filePaths, toPath, toBucket, currentRecursionDepth = 0) {
173
+ (0, js_lib_1._assert)(currentRecursionDepth <= MAX_RECURSION_DEPTH, `combineFiles reached max recursion depth of ${MAX_RECURSION_DEPTH}`);
174
+ const { logger, debug } = this.cfg;
175
+ if (filePaths.length === 0) {
176
+ if (debug) {
177
+ logger.log(`[${currentRecursionDepth}] Nothing to compose, returning early!`);
178
+ }
179
+ return;
180
+ }
181
+ if (debug) {
182
+ logger.log(`[${currentRecursionDepth}] Will compose ${filePaths.length} files, by batches of ${BATCH_SIZE}`);
183
+ }
184
+ const intermediateFiles = [];
185
+ if (filePaths.length <= BATCH_SIZE) {
186
+ await this.storage
187
+ .bucket(bucketName)
188
+ .combine(filePaths, this.storage.bucket(toBucket || bucketName).file(toPath));
189
+ if (debug) {
190
+ logger.log(`[${currentRecursionDepth}] Composed into ${toPath}!`);
191
+ }
192
+ await this.deleteFiles(bucketName, filePaths);
193
+ return;
194
+ }
195
+ const started = Date.now();
196
+ await (0, js_lib_1.pMap)((0, js_lib_1._chunk)(filePaths, BATCH_SIZE), async (fileBatch, i) => {
197
+ if (debug) {
198
+ logger.log(`[${currentRecursionDepth}] Composing batch ${i + 1}...`);
199
+ }
200
+ const intermediateFile = `temp_${currentRecursionDepth}_${i}`;
201
+ await this.storage
202
+ .bucket(bucketName)
203
+ .combine(fileBatch, this.storage.bucket(toBucket || bucketName).file(intermediateFile));
204
+ intermediateFiles.push(intermediateFile);
205
+ await this.deleteFiles(bucketName, fileBatch);
206
+ });
207
+ if (debug) {
208
+ logger.log(`[${currentRecursionDepth}] Batch composed into ${intermediateFiles.length} files, in ${(0, js_lib_1._since)(started)}`);
209
+ }
210
+ await this.combineFiles(toBucket || bucketName, intermediateFiles, toPath, toBucket, currentRecursionDepth + 1);
211
+ }
212
+ async combine(bucketName, prefix, toPath, toBucket) {
213
+ const filePaths = await this.getFileNames(bucketName, { prefix });
214
+ await this.combineFiles(bucketName, filePaths, toPath, toBucket);
215
+ }
216
+ /**
217
+ * Acquires a "signed url", which allows bearer to use it to download ('read') the file.
218
+ *
219
+ * expires: 'v4' supports maximum duration of 7 days from now.
220
+ *
221
+ * @experimental - not tested yet
222
+ */
223
+ async getSignedUrl(bucketName, filePath, expires) {
224
+ const [url] = await this.storage
225
+ .bucket(bucketName)
226
+ .file(filePath)
227
+ .getSignedUrl({
228
+ action: 'read',
229
+ version: 'v4',
230
+ expires: (0, js_lib_1.localTime)(expires).unixMillis,
231
+ });
232
+ return url;
233
+ }
234
+ /**
235
+ * Returns SKIP if fileName is a folder.
236
+ * If !fullPaths - strip away the folder prefix.
237
+ */
238
+ normalizeFilename(fileName, fullPaths) {
239
+ if (fullPaths) {
240
+ if (fileName.endsWith('/'))
241
+ return js_lib_1.SKIP; // skip folders
242
+ return fileName;
243
+ }
244
+ fileName = (0, js_lib_1._substringAfterLast)(fileName, '/');
245
+ return fileName || js_lib_1.SKIP; // skip folders
246
+ }
247
+ }
248
+ exports.CloudStorage = CloudStorage;
@@ -0,0 +1,110 @@
1
+ import type { LocalTimeInput } from '@naturalcycles/js-lib';
2
+ import type { ReadableBinary, ReadableTyped, WritableBinary } from '@naturalcycles/nodejs-lib';
3
+ export interface FileEntry {
4
+ filePath: string;
5
+ content: Buffer;
6
+ }
7
+ export interface CommonStorageGetOptions {
8
+ /**
9
+ * Will filter resulting files based on `prefix`.
10
+ */
11
+ prefix?: string;
12
+ /**
13
+ * Defaults to true.
14
+ * Set to false to return file names instead of full paths.
15
+ */
16
+ fullPaths?: boolean;
17
+ /**
18
+ * Limits the number of results.
19
+ *
20
+ * By default it's unlimited.
21
+ *
22
+ * 0 is treated as `undefined`.
23
+ */
24
+ limit?: number;
25
+ }
26
+ /**
27
+ * Common denominator interface for File Storage.
28
+ * Modelled after GCP Cloud Storage, Firebase Storage.
29
+ *
30
+ * Uses the concept of Bucket (identified by string name) and Path within the Bucket.
31
+ *
32
+ * Path MUST NOT start with a slash !
33
+ *
34
+ * Similarly to CommonDB, Bucket is like a Table, and Path is like an `id`.
35
+ */
36
+ export interface CommonStorage {
37
+ /**
38
+ * Ensure that the credentials are correct and the connection is working.
39
+ * Idempotent.
40
+ *
41
+ * Pass `bucketName` in case you only have permissions to operate on that bucket.
42
+ */
43
+ ping: (bucketName?: string) => Promise<void>;
44
+ /**
45
+ * Creates a new bucket by given name.
46
+ * todo: check what to do if it already exists
47
+ */
48
+ fileExists: (bucketName: string, filePath: string) => Promise<boolean>;
49
+ getFile: (bucketName: string, filePath: string) => Promise<Buffer | null>;
50
+ saveFile: (bucketName: string, filePath: string, content: Buffer) => Promise<void>;
51
+ /**
52
+ * Should recursively delete all files in a folder, if path is a folder.
53
+ */
54
+ deletePath: (bucketName: string, prefix: string) => Promise<void>;
55
+ deletePaths: (bucketName: string, prefixes: string[]) => Promise<void>;
56
+ /**
57
+ * Should delete all files by their paths.
58
+ */
59
+ deleteFiles: (bucketName: string, filePaths: string[]) => Promise<void>;
60
+ /**
61
+ * Returns an array of strings which are file paths.
62
+ * Files that are not found by the path are not present in the map.
63
+ *
64
+ * Second argument is called `prefix` (same as `path`) to explain how
65
+ * listing works (it filters all files by `startsWith`). Also, to match
66
+ * GCP Cloud Storage API.
67
+ *
68
+ * Important difference between `prefix` and `path` is that `prefix` will
69
+ * return all files from sub-directories too!
70
+ */
71
+ getFileNames: (bucketName: string, opt?: CommonStorageGetOptions) => Promise<string[]>;
72
+ getFileNamesStream: (bucketName: string, opt?: CommonStorageGetOptions) => ReadableTyped<string>;
73
+ getFilesStream: (bucketName: string, opt?: CommonStorageGetOptions) => ReadableTyped<FileEntry>;
74
+ getFileReadStream: (bucketName: string, filePath: string) => ReadableBinary;
75
+ getFileWriteStream: (bucketName: string, filePath: string) => WritableBinary;
76
+ /**
77
+ * Upload local file to the bucket (by streaming it).
78
+ */
79
+ uploadFile: (localFilePath: string, bucketName: string, bucketFilePath: string) => Promise<void>;
80
+ setFileVisibility: (bucketName: string, filePath: string, isPublic: boolean) => Promise<void>;
81
+ getFileVisibility: (bucketName: string, filePath: string) => Promise<boolean>;
82
+ copyFile: (fromBucket: string, fromPath: string, toPath: string, toBucket?: string) => Promise<void>;
83
+ moveFile: (fromBucket: string, fromPath: string, toPath: string, toBucket?: string) => Promise<void>;
84
+ /**
85
+ * Allows to move "directory" with all its contents.
86
+ *
87
+ * Prefixes should end with `/` to work properly,
88
+ * otherwise some folder that starts with the same prefix will be included.
89
+ */
90
+ movePath: (fromBucket: string, fromPrefix: string, toPrefix: string, toBucket?: string) => Promise<void>;
91
+ /**
92
+ * Combine (compose) multiple input files into a single output file.
93
+ * Should support unlimited number of input files, using recursive algorithm if necessary.
94
+ *
95
+ * After the output file is created, all input files should be deleted.
96
+ *
97
+ * @experimental
98
+ */
99
+ combineFiles: (bucketName: string, filePaths: string[], toPath: string, toBucket?: string) => Promise<void>;
100
+ /**
101
+ * Like `combineFiles`, but for a `prefix`.
102
+ */
103
+ combine: (bucketName: string, prefix: string, toPath: string, toBucket?: string) => Promise<void>;
104
+ /**
105
+ * Acquire a "signed url", which allows bearer to use it to download ('read') the file.
106
+ *
107
+ * @experimental
108
+ */
109
+ getSignedUrl: (bucketName: string, filePath: string, expires: LocalTimeInput) => Promise<string>;
110
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,67 @@
1
+ import { Readable, Writable } from 'node:stream';
2
+ import { ReadableTyped } from '@naturalcycles/nodejs-lib';
3
+ import { CommonStorage, CommonStorageGetOptions, FileEntry } from './commonStorage';
4
+ export interface CommonStorageBucketCfg {
5
+ storage: CommonStorage;
6
+ bucketName: string;
7
+ }
8
+ /**
9
+ * Convenience wrapper around CommonStorage for a given Bucket.
10
+ *
11
+ * Similar to what CommonDao is to CommonDB.
12
+ */
13
+ export declare class CommonStorageBucket {
14
+ cfg: CommonStorageBucketCfg;
15
+ constructor(cfg: CommonStorageBucketCfg);
16
+ ping(bucketName?: string): Promise<void>;
17
+ fileExists(filePath: string): Promise<boolean>;
18
+ getFile(filePath: string): Promise<Buffer | null>;
19
+ getFileAsString(filePath: string): Promise<string | null>;
20
+ getFileAsJson<T = any>(filePath: string): Promise<T | null>;
21
+ requireFile(filePath: string): Promise<Buffer>;
22
+ requireFileAsString(filePath: string): Promise<string>;
23
+ requireFileAsJson<T = any>(filePath: string): Promise<T>;
24
+ private throwRequiredError;
25
+ getFileContents(paths: string[]): Promise<Buffer[]>;
26
+ getFileContentsAsJson<T = any>(paths: string[]): Promise<T[]>;
27
+ getFileEntries(paths: string[]): Promise<FileEntry[]>;
28
+ getFileEntriesAsJson<T = any>(paths: string[]): Promise<{
29
+ filePath: string;
30
+ content: T;
31
+ }[]>;
32
+ saveFile(filePath: string, content: Buffer): Promise<void>;
33
+ /**
34
+ * Convenience method that does:
35
+ * await saveFile
36
+ * await setFileVisibility
37
+ */
38
+ savePublicFile(filePath: string, content: Buffer): Promise<void>;
39
+ saveStringFile(filePath: string, content: string): Promise<void>;
40
+ saveJsonFile(filePath: string, content: any): Promise<void>;
41
+ saveFiles(entries: FileEntry[]): Promise<void>;
42
+ /**
43
+ * Should recursively delete all files in a folder, if path is a folder.
44
+ */
45
+ deletePath(prefix: string): Promise<void>;
46
+ deletePaths(prefixes: string[]): Promise<void>;
47
+ /**
48
+ * Returns an array of strings which are file paths.
49
+ * Files that are not found by the path are not present in the map.
50
+ *
51
+ * Second argument is called `prefix` (same as `path`) to explain how
52
+ * listing works (it filters all files by `startsWith`). Also, to match
53
+ * GCP Cloud Storage API.
54
+ *
55
+ * Important difference between `prefix` and `path` is that `prefix` will
56
+ * return all files from sub-directories too!
57
+ */
58
+ getFileNames(opt?: CommonStorageGetOptions): Promise<string[]>;
59
+ getFileNamesStream(opt?: CommonStorageGetOptions): ReadableTyped<string>;
60
+ getFilesStream(opt?: CommonStorageGetOptions): ReadableTyped<FileEntry>;
61
+ getFileReadStream(filePath: string): Readable;
62
+ getFileWriteStream(filePath: string): Writable;
63
+ setFileVisibility(filePath: string, isPublic: boolean): Promise<void>;
64
+ getFileVisibility(filePath: string): Promise<boolean>;
65
+ copyFile(fromPath: string, toPath: string, toBucket?: string): Promise<void>;
66
+ moveFile(fromPath: string, toPath: string, toBucket?: string): Promise<void>;
67
+ }
@@ -0,0 +1,146 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CommonStorageBucket = void 0;
4
+ const js_lib_1 = require("@naturalcycles/js-lib");
5
+ /**
6
+ * Convenience wrapper around CommonStorage for a given Bucket.
7
+ *
8
+ * Similar to what CommonDao is to CommonDB.
9
+ */
10
+ class CommonStorageBucket {
11
+ constructor(cfg) {
12
+ this.cfg = cfg;
13
+ }
14
+ async ping(bucketName) {
15
+ await this.cfg.storage.ping(bucketName);
16
+ }
17
+ async fileExists(filePath) {
18
+ return await this.cfg.storage.fileExists(this.cfg.bucketName, filePath);
19
+ }
20
+ async getFile(filePath) {
21
+ return await this.cfg.storage.getFile(this.cfg.bucketName, filePath);
22
+ }
23
+ async getFileAsString(filePath) {
24
+ const buf = await this.cfg.storage.getFile(this.cfg.bucketName, filePath);
25
+ return buf?.toString() || null;
26
+ }
27
+ async getFileAsJson(filePath) {
28
+ const buf = await this.cfg.storage.getFile(this.cfg.bucketName, filePath);
29
+ if (!buf)
30
+ return null;
31
+ return JSON.parse(buf.toString());
32
+ }
33
+ async requireFile(filePath) {
34
+ const buf = await this.cfg.storage.getFile(this.cfg.bucketName, filePath);
35
+ if (!buf)
36
+ this.throwRequiredError(filePath);
37
+ return buf;
38
+ }
39
+ async requireFileAsString(filePath) {
40
+ const s = await this.getFileAsString(filePath);
41
+ return s ?? this.throwRequiredError(filePath);
42
+ }
43
+ async requireFileAsJson(filePath) {
44
+ const v = await this.getFileAsJson(filePath);
45
+ return v ?? this.throwRequiredError(filePath);
46
+ }
47
+ throwRequiredError(filePath) {
48
+ throw new js_lib_1.AppError(`File required, but not found: ${this.cfg.bucketName}/${filePath}`, {
49
+ code: 'FILE_REQUIRED',
50
+ });
51
+ }
52
+ async getFileContents(paths) {
53
+ return (await (0, js_lib_1.pMap)(paths, async (filePath) => (await this.cfg.storage.getFile(this.cfg.bucketName, filePath)))).filter(Boolean);
54
+ }
55
+ async getFileContentsAsJson(paths) {
56
+ return (await (0, js_lib_1.pMap)(paths, async (filePath) => {
57
+ const buf = await this.cfg.storage.getFile(this.cfg.bucketName, filePath);
58
+ return buf ? JSON.parse(buf.toString()) : null;
59
+ })).filter(Boolean);
60
+ }
61
+ async getFileEntries(paths) {
62
+ return (await (0, js_lib_1.pMap)(paths, async (filePath) => {
63
+ const content = await this.cfg.storage.getFile(this.cfg.bucketName, filePath);
64
+ return { filePath, content: content };
65
+ })).filter(f => f.content);
66
+ }
67
+ async getFileEntriesAsJson(paths) {
68
+ return (await (0, js_lib_1.pMap)(paths, async (filePath) => {
69
+ const buf = await this.cfg.storage.getFile(this.cfg.bucketName, filePath);
70
+ return buf ? { filePath, content: JSON.parse(buf.toString()) } : null;
71
+ })).filter(Boolean);
72
+ }
73
+ async saveFile(filePath, content) {
74
+ await this.cfg.storage.saveFile(this.cfg.bucketName, filePath, content);
75
+ }
76
+ /**
77
+ * Convenience method that does:
78
+ * await saveFile
79
+ * await setFileVisibility
80
+ */
81
+ async savePublicFile(filePath, content) {
82
+ await this.cfg.storage.saveFile(this.cfg.bucketName, filePath, content);
83
+ await this.cfg.storage.setFileVisibility(this.cfg.bucketName, filePath, true);
84
+ }
85
+ async saveStringFile(filePath, content) {
86
+ await this.cfg.storage.saveFile(this.cfg.bucketName, filePath, Buffer.from(content));
87
+ }
88
+ async saveJsonFile(filePath, content) {
89
+ await this.cfg.storage.saveFile(this.cfg.bucketName, filePath, Buffer.from(JSON.stringify(content)));
90
+ }
91
+ async saveFiles(entries) {
92
+ await (0, js_lib_1.pMap)(entries, async (f) => {
93
+ await this.cfg.storage.saveFile(this.cfg.bucketName, f.filePath, f.content);
94
+ });
95
+ }
96
+ /**
97
+ * Should recursively delete all files in a folder, if path is a folder.
98
+ */
99
+ async deletePath(prefix) {
100
+ return await this.cfg.storage.deletePath(this.cfg.bucketName, prefix);
101
+ }
102
+ async deletePaths(prefixes) {
103
+ await (0, js_lib_1.pMap)(prefixes, async (prefix) => {
104
+ return await this.cfg.storage.deletePath(this.cfg.bucketName, prefix);
105
+ });
106
+ }
107
+ /**
108
+ * Returns an array of strings which are file paths.
109
+ * Files that are not found by the path are not present in the map.
110
+ *
111
+ * Second argument is called `prefix` (same as `path`) to explain how
112
+ * listing works (it filters all files by `startsWith`). Also, to match
113
+ * GCP Cloud Storage API.
114
+ *
115
+ * Important difference between `prefix` and `path` is that `prefix` will
116
+ * return all files from sub-directories too!
117
+ */
118
+ async getFileNames(opt) {
119
+ return await this.cfg.storage.getFileNames(this.cfg.bucketName, opt);
120
+ }
121
+ getFileNamesStream(opt) {
122
+ return this.cfg.storage.getFileNamesStream(this.cfg.bucketName, opt);
123
+ }
124
+ getFilesStream(opt) {
125
+ return this.cfg.storage.getFilesStream(this.cfg.bucketName, opt);
126
+ }
127
+ getFileReadStream(filePath) {
128
+ return this.cfg.storage.getFileReadStream(this.cfg.bucketName, filePath);
129
+ }
130
+ getFileWriteStream(filePath) {
131
+ return this.cfg.storage.getFileWriteStream(this.cfg.bucketName, filePath);
132
+ }
133
+ async setFileVisibility(filePath, isPublic) {
134
+ await this.cfg.storage.setFileVisibility(this.cfg.bucketName, filePath, isPublic);
135
+ }
136
+ async getFileVisibility(filePath) {
137
+ return await this.cfg.storage.getFileVisibility(this.cfg.bucketName, filePath);
138
+ }
139
+ async copyFile(fromPath, toPath, toBucket) {
140
+ await this.cfg.storage.copyFile(this.cfg.bucketName, fromPath, toPath, toBucket);
141
+ }
142
+ async moveFile(fromPath, toPath, toBucket) {
143
+ await this.cfg.storage.moveFile(this.cfg.bucketName, fromPath, toPath, toBucket);
144
+ }
145
+ }
146
+ exports.CommonStorageBucket = CommonStorageBucket;
@@ -0,0 +1,39 @@
1
+ import { CommonDBCreateOptions, CommonKeyValueDB, KeyValueDBTuple } from '@naturalcycles/db-lib';
2
+ import { StringMap } from '@naturalcycles/js-lib';
3
+ import { ReadableTyped } from '@naturalcycles/nodejs-lib';
4
+ import { CommonStorage } from './commonStorage';
5
+ export interface CommonStorageKeyValueDBCfg {
6
+ storage: CommonStorage;
7
+ bucketName: string;
8
+ }
9
+ /**
10
+ * CommonKeyValueDB, backed up by a CommonStorage implementation.
11
+ *
12
+ * Each Table is represented as a Folder.
13
+ * Each Item is represented as a File:
14
+ * fileName is ${id} (without extension)
15
+ * file contents is ${v} (Buffer)
16
+ */
17
+ export declare class CommonStorageKeyValueDB implements CommonKeyValueDB {
18
+ cfg: CommonStorageKeyValueDBCfg;
19
+ constructor(cfg: CommonStorageKeyValueDBCfg);
20
+ support: {
21
+ increment: boolean;
22
+ count?: boolean;
23
+ };
24
+ ping(): Promise<void>;
25
+ createTable(_table: string, _opt?: CommonDBCreateOptions): Promise<void>;
26
+ /**
27
+ * Allows to pass `SomeBucket.SomeTable` in `table`, to override a Bucket.
28
+ */
29
+ private getBucketAndPrefix;
30
+ deleteByIds(table: string, ids: string[]): Promise<void>;
31
+ getByIds(table: string, ids: string[]): Promise<KeyValueDBTuple[]>;
32
+ saveBatch(table: string, entries: KeyValueDBTuple[]): Promise<void>;
33
+ streamIds(table: string, limit?: number): ReadableTyped<string>;
34
+ streamValues(table: string, limit?: number): ReadableTyped<Buffer>;
35
+ streamEntries(table: string, limit?: number): ReadableTyped<KeyValueDBTuple>;
36
+ count(table: string): Promise<number>;
37
+ increment(_table: string, _id: string, _by?: number): Promise<number>;
38
+ incrementBatch(_table: string, _incrementMap: StringMap<number>): Promise<StringMap<number>>;
39
+ }
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CommonStorageKeyValueDB = void 0;
4
+ const db_lib_1 = require("@naturalcycles/db-lib");
5
+ const js_lib_1 = require("@naturalcycles/js-lib");
6
+ /**
7
+ * CommonKeyValueDB, backed up by a CommonStorage implementation.
8
+ *
9
+ * Each Table is represented as a Folder.
10
+ * Each Item is represented as a File:
11
+ * fileName is ${id} (without extension)
12
+ * file contents is ${v} (Buffer)
13
+ */
14
+ class CommonStorageKeyValueDB {
15
+ constructor(cfg) {
16
+ this.cfg = cfg;
17
+ this.support = {
18
+ ...db_lib_1.commonKeyValueDBFullSupport,
19
+ increment: false,
20
+ };
21
+ }
22
+ async ping() {
23
+ await this.cfg.storage.ping(this.cfg.bucketName);
24
+ }
25
+ async createTable(_table, _opt) {
26
+ // no-op
27
+ }
28
+ /**
29
+ * Allows to pass `SomeBucket.SomeTable` in `table`, to override a Bucket.
30
+ */
31
+ getBucketAndPrefix(table) {
32
+ const [part1, part2] = table.split('.');
33
+ if (part2) {
34
+ return {
35
+ bucketName: part1,
36
+ prefix: part2,
37
+ };
38
+ }
39
+ // As is
40
+ return {
41
+ bucketName: this.cfg.bucketName,
42
+ prefix: table,
43
+ };
44
+ }
45
+ async deleteByIds(table, ids) {
46
+ const { bucketName, prefix } = this.getBucketAndPrefix(table);
47
+ await (0, js_lib_1.pMap)(ids, async (id) => {
48
+ await this.cfg.storage.deletePath(bucketName, [prefix, id].join('/'));
49
+ });
50
+ }
51
+ async getByIds(table, ids) {
52
+ const { bucketName, prefix } = this.getBucketAndPrefix(table);
53
+ const map = {};
54
+ await (0, js_lib_1.pMap)(ids, async (id) => {
55
+ const buf = await this.cfg.storage.getFile(bucketName, [prefix, id].join('/'));
56
+ if (buf)
57
+ map[id] = buf;
58
+ });
59
+ return ids.map(id => [id, map[id]]).filter(t => t[1]);
60
+ }
61
+ async saveBatch(table, entries) {
62
+ const { bucketName, prefix } = this.getBucketAndPrefix(table);
63
+ await (0, js_lib_1.pMap)(entries, async ([id, content]) => {
64
+ await this.cfg.storage.saveFile(bucketName, [prefix, id].join('/'), content);
65
+ });
66
+ }
67
+ streamIds(table, limit) {
68
+ const { bucketName, prefix } = this.getBucketAndPrefix(table);
69
+ return this.cfg.storage.getFileNamesStream(bucketName, { prefix, limit, fullPaths: false });
70
+ }
71
+ streamValues(table, limit) {
72
+ const { bucketName, prefix } = this.getBucketAndPrefix(table);
73
+ return this.cfg.storage.getFilesStream(bucketName, { prefix, limit }).map(f => f.content);
74
+ }
75
+ streamEntries(table, limit) {
76
+ const { bucketName, prefix } = this.getBucketAndPrefix(table);
77
+ return this.cfg.storage
78
+ .getFilesStream(bucketName, { prefix, limit, fullPaths: false })
79
+ .map(f => [f.filePath, f.content]);
80
+ }
81
+ async count(table) {
82
+ const { bucketName, prefix } = this.getBucketAndPrefix(table);
83
+ return (await this.cfg.storage.getFileNames(bucketName, { prefix })).length;
84
+ }
85
+ async increment(_table, _id, _by) {
86
+ throw new js_lib_1.AppError('CommonStorageKeyValueDB.increment() is not implemented');
87
+ }
88
+ async incrementBatch(_table, _incrementMap) {
89
+ throw new js_lib_1.AppError('CommonStorageKeyValueDB.incrementBatch() is not implemented');
90
+ }
91
+ }
92
+ exports.CommonStorageKeyValueDB = CommonStorageKeyValueDB;
@@ -0,0 +1,33 @@
1
+ import { LocalTimeInput, StringMap } from '@naturalcycles/js-lib';
2
+ import { ReadableBinary, ReadableTyped, WritableBinary } from '@naturalcycles/nodejs-lib';
3
+ import { CommonStorage, CommonStorageGetOptions, FileEntry } from './commonStorage';
4
+ export declare class InMemoryCommonStorage implements CommonStorage {
5
+ /**
6
+ * data[bucketName][filePath] = Buffer
7
+ */
8
+ data: StringMap<StringMap<Buffer>>;
9
+ publicMap: StringMap<StringMap<boolean>>;
10
+ ping(): Promise<void>;
11
+ getBucketNames(): Promise<string[]>;
12
+ getBucketNamesStream(): ReadableTyped<string>;
13
+ fileExists(bucketName: string, filePath: string): Promise<boolean>;
14
+ getFile(bucketName: string, filePath: string): Promise<Buffer | null>;
15
+ saveFile(bucketName: string, filePath: string, content: Buffer): Promise<void>;
16
+ deletePath(bucketName: string, prefix: string): Promise<void>;
17
+ deletePaths(bucketName: string, prefixes: string[]): Promise<void>;
18
+ deleteFiles(bucketName: string, filePaths: string[]): Promise<void>;
19
+ getFileNames(bucketName: string, opt?: CommonStorageGetOptions): Promise<string[]>;
20
+ getFileNamesStream(bucketName: string, opt?: CommonStorageGetOptions): ReadableTyped<string>;
21
+ getFilesStream(bucketName: string, opt?: CommonStorageGetOptions): ReadableTyped<FileEntry>;
22
+ getFileReadStream(bucketName: string, filePath: string): ReadableBinary;
23
+ getFileWriteStream(_bucketName: string, _filePath: string): WritableBinary;
24
+ uploadFile(localFilePath: string, bucketName: string, bucketFilePath: string): Promise<void>;
25
+ setFileVisibility(bucketName: string, filePath: string, isPublic: boolean): Promise<void>;
26
+ getFileVisibility(bucketName: string, filePath: string): Promise<boolean>;
27
+ copyFile(fromBucket: string, fromPath: string, toPath: string, toBucket?: string): Promise<void>;
28
+ moveFile(fromBucket: string, fromPath: string, toPath: string, toBucket?: string): Promise<void>;
29
+ movePath(fromBucket: string, fromPrefix: string, toPrefix: string, toBucket?: string): Promise<void>;
30
+ combine(bucketName: string, prefix: string, toPath: string, toBucket?: string): Promise<void>;
31
+ combineFiles(bucketName: string, filePaths: string[], toPath: string, toBucket?: string): Promise<void>;
32
+ getSignedUrl(bucketName: string, filePath: string, expires: LocalTimeInput): Promise<string>;
33
+ }
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InMemoryCommonStorage = void 0;
4
+ const js_lib_1 = require("@naturalcycles/js-lib");
5
+ const nodejs_lib_1 = require("@naturalcycles/nodejs-lib");
6
+ class InMemoryCommonStorage {
7
+ constructor() {
8
+ /**
9
+ * data[bucketName][filePath] = Buffer
10
+ */
11
+ this.data = {};
12
+ this.publicMap = {};
13
+ }
14
+ async ping() { }
15
+ async getBucketNames() {
16
+ return Object.keys(this.data);
17
+ }
18
+ getBucketNamesStream() {
19
+ return (0, nodejs_lib_1.readableFrom)(Object.keys(this.data));
20
+ }
21
+ async fileExists(bucketName, filePath) {
22
+ return !!this.data[bucketName]?.[filePath];
23
+ }
24
+ async getFile(bucketName, filePath) {
25
+ return this.data[bucketName]?.[filePath] || null;
26
+ }
27
+ async saveFile(bucketName, filePath, content) {
28
+ this.data[bucketName] ||= {};
29
+ this.data[bucketName][filePath] = content;
30
+ }
31
+ async deletePath(bucketName, prefix) {
32
+ await this.deletePaths(bucketName, [prefix]);
33
+ }
34
+ async deletePaths(bucketName, prefixes) {
35
+ Object.keys(this.data[bucketName] || {}).forEach(filePath => {
36
+ if (prefixes.some(prefix => filePath.startsWith(prefix))) {
37
+ delete this.data[bucketName][filePath];
38
+ }
39
+ });
40
+ }
41
+ async deleteFiles(bucketName, filePaths) {
42
+ if (!this.data[bucketName])
43
+ return;
44
+ filePaths.forEach(filePath => delete this.data[bucketName][filePath]);
45
+ }
46
+ async getFileNames(bucketName, opt = {}) {
47
+ const { prefix = '', fullPaths = true } = opt;
48
+ return Object.keys(this.data[bucketName] || {})
49
+ .filter(filePath => filePath.startsWith(prefix))
50
+ .map(f => (fullPaths ? f : (0, js_lib_1._substringAfterLast)(f, '/')));
51
+ }
52
+ getFileNamesStream(bucketName, opt = {}) {
53
+ const { prefix = '', fullPaths = true } = opt;
54
+ return (0, nodejs_lib_1.readableFrom)(Object.keys(this.data[bucketName] || {})
55
+ .filter(filePath => filePath.startsWith(prefix))
56
+ .slice(0, opt.limit)
57
+ .map(n => (fullPaths ? n : (0, js_lib_1._substringAfterLast)(n, '/'))));
58
+ }
59
+ getFilesStream(bucketName, opt = {}) {
60
+ const { prefix = '', fullPaths = true } = opt;
61
+ return (0, nodejs_lib_1.readableFrom)((0, js_lib_1._stringMapEntries)(this.data[bucketName] || {})
62
+ .map(([filePath, content]) => ({
63
+ filePath,
64
+ content,
65
+ }))
66
+ .filter(f => f.filePath.startsWith(prefix))
67
+ .slice(0, opt.limit)
68
+ .map(f => (fullPaths ? f : { ...f, filePath: (0, js_lib_1._substringAfterLast)(f.filePath, '/') })));
69
+ }
70
+ getFileReadStream(bucketName, filePath) {
71
+ return (0, nodejs_lib_1.readableFrom)(this.data[bucketName][filePath]);
72
+ }
73
+ getFileWriteStream(_bucketName, _filePath) {
74
+ throw new Error('Method not implemented.');
75
+ }
76
+ async uploadFile(localFilePath, bucketName, bucketFilePath) {
77
+ this.data[bucketName] ||= {};
78
+ this.data[bucketName][bucketFilePath] = await nodejs_lib_1.fs2.readBufferAsync(localFilePath);
79
+ }
80
+ async setFileVisibility(bucketName, filePath, isPublic) {
81
+ this.publicMap[bucketName] ||= {};
82
+ this.publicMap[bucketName][filePath] = isPublic;
83
+ }
84
+ async getFileVisibility(bucketName, filePath) {
85
+ return !!this.publicMap[bucketName]?.[filePath];
86
+ }
87
+ async copyFile(fromBucket, fromPath, toPath, toBucket) {
88
+ const tob = toBucket || fromBucket;
89
+ this.data[fromBucket] ||= {};
90
+ this.data[tob] ||= {};
91
+ this.data[tob][toPath] = this.data[fromBucket][fromPath];
92
+ }
93
+ async moveFile(fromBucket, fromPath, toPath, toBucket) {
94
+ const tob = toBucket || fromBucket;
95
+ this.data[fromBucket] ||= {};
96
+ this.data[tob] ||= {};
97
+ this.data[tob][toPath] = this.data[fromBucket][fromPath];
98
+ delete this.data[fromBucket][fromPath];
99
+ }
100
+ async movePath(fromBucket, fromPrefix, toPrefix, toBucket) {
101
+ const tob = toBucket || fromBucket;
102
+ this.data[fromBucket] ||= {};
103
+ this.data[tob] ||= {};
104
+ (0, js_lib_1._stringMapEntries)(this.data[fromBucket]).forEach(([filePath, v]) => {
105
+ if (!filePath.startsWith(fromPrefix))
106
+ return;
107
+ this.data[tob][toPrefix + filePath.slice(fromPrefix.length)] = v;
108
+ delete this.data[fromBucket][filePath];
109
+ });
110
+ }
111
+ async combine(bucketName, prefix, toPath, toBucket) {
112
+ const filePaths = await this.getFileNames(bucketName, { prefix });
113
+ await this.combineFiles(bucketName, filePaths, toPath, toBucket);
114
+ }
115
+ async combineFiles(bucketName, filePaths, toPath, toBucket) {
116
+ if (!this.data[bucketName])
117
+ return;
118
+ const tob = toBucket || bucketName;
119
+ this.data[tob] ||= {};
120
+ this.data[tob][toPath] = Buffer.concat(filePaths.map(p => this.data[bucketName][p]).filter(js_lib_1._isTruthy));
121
+ // delete source files
122
+ filePaths.forEach(p => delete this.data[bucketName][p]);
123
+ }
124
+ async getSignedUrl(bucketName, filePath, expires) {
125
+ const buf = this.data[bucketName]?.[filePath];
126
+ (0, js_lib_1._assert)(buf, `getSignedUrl file not found: ${bucketName}/${filePath}`);
127
+ const signature = (0, nodejs_lib_1.md5)(buf);
128
+ return `https://testurl.com/${bucketName}/${filePath}?expires=${(0, js_lib_1.localTime)(expires).unix}&signature=${signature}`;
129
+ }
130
+ }
131
+ exports.InMemoryCommonStorage = InMemoryCommonStorage;
@@ -0,0 +1,7 @@
1
+ export * from './cloudStorage';
2
+ export * from './commonStorage';
3
+ export * from './commonStorageBucket';
4
+ export * from './commonStorageKeyValueDB';
5
+ export * from './inMemoryCommonStorage';
6
+ export * from './model';
7
+ export * from './testing/commonStorageTest';
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./cloudStorage"), exports);
5
+ tslib_1.__exportStar(require("./commonStorage"), exports);
6
+ tslib_1.__exportStar(require("./commonStorageBucket"), exports);
7
+ tslib_1.__exportStar(require("./commonStorageKeyValueDB"), exports);
8
+ tslib_1.__exportStar(require("./inMemoryCommonStorage"), exports);
9
+ tslib_1.__exportStar(require("./model"), exports);
10
+ tslib_1.__exportStar(require("./testing/commonStorageTest"), exports);
@@ -0,0 +1,5 @@
1
+ export interface GCPServiceAccount {
2
+ client_email: string;
3
+ private_key: string;
4
+ project_id: string;
5
+ }
package/dist/model.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,5 @@
1
+ import { CommonStorage } from '../commonStorage';
2
+ /**
3
+ * This test suite must be idempotent.
4
+ */
5
+ export declare function runCommonStorageTest(storage: CommonStorage, bucketName: string): void;
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runCommonStorageTest = runCommonStorageTest;
4
+ const js_lib_1 = require("@naturalcycles/js-lib");
5
+ const TEST_FOLDER = 'test/subdir';
6
+ const TEST_ITEMS = (0, js_lib_1._range)(10).map(n => ({
7
+ id: `id_${n + 1}`,
8
+ n,
9
+ even: n % 2 === 0,
10
+ }));
11
+ const TEST_ITEMS2 = (0, js_lib_1._range)(10).map(n => ({
12
+ fileType: 2,
13
+ id: `id_${n + 1}`,
14
+ n,
15
+ even: n % 2 === 0,
16
+ }));
17
+ const TEST_ITEMS3 = (0, js_lib_1._range)(10).map(n => ({
18
+ fileType: 3,
19
+ id: `id_${n + 1}`,
20
+ n,
21
+ even: n % 2 === 0,
22
+ }));
23
+ const TEST_FILES = [TEST_ITEMS, TEST_ITEMS2, TEST_ITEMS3].map((obj, i) => ({
24
+ filePath: `${TEST_FOLDER}/file_${i + 1}.json`,
25
+ content: Buffer.from(JSON.stringify(obj)),
26
+ }));
27
+ /**
28
+ * This test suite must be idempotent.
29
+ */
30
+ function runCommonStorageTest(storage, bucketName) {
31
+ // test('createBucket', async () => {
32
+ // await storage.createBucket(bucketName)
33
+ // })
34
+ test('ping', async () => {
35
+ await storage.ping(bucketName);
36
+ });
37
+ // test('listBuckets', async () => {
38
+ // const buckets = await storage.getBucketNames()
39
+ // console.log(buckets)
40
+ // })
41
+ //
42
+ // test('streamBuckets', async () => {
43
+ // const buckets = await readableToArray(storage.getBucketNamesStream())
44
+ // console.log(buckets)
45
+ // })
46
+ test('prepare: clear bucket', async () => {
47
+ await (0, js_lib_1.pMap)(TEST_FILES.map(f => f.filePath), async (filePath) => await storage.deletePath(bucketName, filePath));
48
+ });
49
+ // test('listFileNames on root should return empty', async () => {
50
+ // const fileNames = await storage.getFileNames(bucketName)
51
+ // expect(fileNames).toEqual([])
52
+ // })
53
+ test(`listFileNames on ${TEST_FOLDER} should return empty`, async () => {
54
+ const fileNames = await storage.getFileNames(bucketName, { prefix: TEST_FOLDER });
55
+ expect(fileNames).toEqual([]);
56
+ });
57
+ test(`streamFileNames on ${TEST_FOLDER} should return empty`, async () => {
58
+ const fileNames = await storage
59
+ .getFileNamesStream(bucketName, { prefix: TEST_FOLDER })
60
+ .toArray();
61
+ expect(fileNames).toEqual([]);
62
+ });
63
+ test(`exists should return empty array`, async () => {
64
+ await (0, js_lib_1.pMap)(TEST_FILES, async (f) => {
65
+ const exists = await storage.fileExists(bucketName, f.filePath);
66
+ expect(exists).toBe(false);
67
+ });
68
+ });
69
+ test(`saveFiles, then listFileNames, streamFileNames and getFiles should return just saved files`, async () => {
70
+ const testFilesMap = Object.fromEntries(TEST_FILES.map(f => [f.filePath, f.content]));
71
+ // It's done in the same test to ensure "strong consistency"
72
+ await (0, js_lib_1.pMap)(TEST_FILES, async (f) => await storage.saveFile(bucketName, f.filePath, f.content));
73
+ const fileNamesShort = await storage.getFileNames(bucketName, {
74
+ prefix: TEST_FOLDER,
75
+ fullPaths: false,
76
+ });
77
+ expect(fileNamesShort.sort()).toEqual(TEST_FILES.map(f => (0, js_lib_1._substringAfterLast)(f.filePath, '/')).sort());
78
+ const fileNames = await storage.getFileNames(bucketName, { prefix: TEST_FOLDER });
79
+ expect(fileNames.sort()).toEqual(TEST_FILES.map(f => f.filePath).sort());
80
+ const streamedFileNames = await storage
81
+ .getFileNamesStream(bucketName, { prefix: TEST_FOLDER })
82
+ .toArray();
83
+ expect(streamedFileNames.sort()).toEqual(TEST_FILES.map(f => f.filePath).sort());
84
+ const filesMap = {};
85
+ await (0, js_lib_1.pMap)(fileNames, async (filePath) => {
86
+ filesMap[filePath] = (await storage.getFile(bucketName, filePath));
87
+ });
88
+ expect(filesMap).toEqual(testFilesMap);
89
+ await (0, js_lib_1.pMap)(fileNames, async (filePath) => {
90
+ const exists = await storage.fileExists(bucketName, filePath);
91
+ expect(exists).toBe(true);
92
+ });
93
+ });
94
+ test('cleanup', async () => {
95
+ await storage.deletePath(bucketName, TEST_FOLDER);
96
+ });
97
+ // Cannot update access control for an object when uniform bucket-level access is enabled. Read more at https://cloud.google.com/storage/docs/uniform-bucket-level-access
98
+ /*
99
+ test(`get/set FilesVisibility`, async () => {
100
+ const fileNames = TEST_FILES.map(f => f.filePath)
101
+
102
+ let map = await storage.getFilesVisibility(bucketName, fileNames)
103
+ expect(map).toEqual(Object.fromEntries(fileNames.map(f => [f, false])))
104
+
105
+ await storage.setFilesVisibility(bucketName, fileNames, true)
106
+
107
+ map = await storage.getFilesVisibility(bucketName, fileNames)
108
+ expect(map).toEqual(Object.fromEntries(fileNames.map(f => [f, true])))
109
+
110
+ await storage.setFilesVisibility(bucketName, fileNames, false)
111
+
112
+ map = await storage.getFilesVisibility(bucketName, fileNames)
113
+ expect(map).toEqual(Object.fromEntries(fileNames.map(f => [f, false])))
114
+ })
115
+ */
116
+ }
package/package.json CHANGED
@@ -1,7 +1,12 @@
1
1
  {
2
2
  "name": "@naturalcycles/cloud-storage-lib",
3
3
  "scripts": {
4
- "prepare": "husky"
4
+ "prepare": "husky",
5
+ "build": "dev-lib build",
6
+ "test": "dev-lib test",
7
+ "lint": "dev-lib lint",
8
+ "bt": "dev-lib bt",
9
+ "lbt": "dev-lib lbt"
5
10
  },
6
11
  "dependencies": {
7
12
  "@google-cloud/storage": "^7.0.0",
@@ -11,7 +16,7 @@
11
16
  },
12
17
  "devDependencies": {
13
18
  "@naturalcycles/dev-lib": "^15.18.0",
14
- "@types/node": "^20.4.6",
19
+ "@types/node": "^22.7.4",
15
20
  "firebase-admin": "^12.0.0",
16
21
  "jest": "^29.1.2"
17
22
  },
@@ -33,9 +38,9 @@
33
38
  "url": "https://github.com/NaturalCycles/cloud-storage-lib"
34
39
  },
35
40
  "engines": {
36
- "node": ">=18.12.0"
41
+ "node": ">=20.13.0"
37
42
  },
38
- "version": "1.13.0",
43
+ "version": "1.13.2",
39
44
  "description": "CommonStorage implementation based on Google Cloud Storage",
40
45
  "author": "Natural Cycles Team",
41
46
  "license": "MIT"
@@ -1,6 +1,6 @@
1
- // eslint-disable-next-line import/no-duplicates
1
+ // eslint-disable-next-line import-x/no-duplicates
2
2
  import type { File, Storage, StorageOptions } from '@google-cloud/storage'
3
- // eslint-disable-next-line import/no-duplicates
3
+ // eslint-disable-next-line import-x/no-duplicates
4
4
  import type * as StorageLib from '@google-cloud/storage'
5
5
  import {
6
6
  _assert,
@@ -17,10 +17,10 @@ import type { ReadableBinary, ReadableTyped, WritableBinary } from '@naturalcycl
17
17
  import type { CommonStorage, CommonStorageGetOptions, FileEntry } from './commonStorage'
18
18
  import type { GCPServiceAccount } from './model'
19
19
 
20
- export {
20
+ export type {
21
21
  // This is the latest version, to be imported by consumers
22
- type Storage,
23
- type StorageOptions,
22
+ Storage,
23
+ StorageOptions,
24
24
  }
25
25
 
26
26
  const MAX_RECURSION_DEPTH = 10
@@ -1,4 +1,9 @@
1
- import { CommonDBCreateOptions, CommonKeyValueDB, KeyValueDBTuple } from '@naturalcycles/db-lib'
1
+ import {
2
+ CommonDBCreateOptions,
3
+ CommonKeyValueDB,
4
+ commonKeyValueDBFullSupport,
5
+ KeyValueDBTuple,
6
+ } from '@naturalcycles/db-lib'
2
7
  import { AppError, pMap, StringMap } from '@naturalcycles/js-lib'
3
8
  import { ReadableTyped } from '@naturalcycles/nodejs-lib'
4
9
  import { CommonStorage } from './commonStorage'
@@ -19,6 +24,11 @@ export interface CommonStorageKeyValueDBCfg {
19
24
  export class CommonStorageKeyValueDB implements CommonKeyValueDB {
20
25
  constructor(public cfg: CommonStorageKeyValueDBCfg) {}
21
26
 
27
+ support = {
28
+ ...commonKeyValueDBFullSupport,
29
+ increment: false,
30
+ }
31
+
22
32
  async ping(): Promise<void> {
23
33
  await this.cfg.storage.ping(this.cfg.bucketName)
24
34
  }
@@ -104,4 +114,11 @@ export class CommonStorageKeyValueDB implements CommonKeyValueDB {
104
114
  async increment(_table: string, _id: string, _by?: number): Promise<number> {
105
115
  throw new AppError('CommonStorageKeyValueDB.increment() is not implemented')
106
116
  }
117
+
118
+ async incrementBatch(
119
+ _table: string,
120
+ _incrementMap: StringMap<number>,
121
+ ): Promise<StringMap<number>> {
122
+ throw new AppError('CommonStorageKeyValueDB.incrementBatch() is not implemented')
123
+ }
107
124
  }