@pi-r/gcp 0.0.1
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/LICENSE +7 -0
- package/README.md +5 -0
- package/client/index.js +830 -0
- package/download/index.js +82 -0
- package/package.json +29 -0
- package/upload/index.js +230 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
Copyright 2023 An Pham
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
4
|
+
|
|
5
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/client/index.js
ADDED
|
@@ -0,0 +1,830 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getProjectId = exports.createBucketRequest = exports.setPredefinedAcl = exports.setPublicRead = exports.executeBatchQuery = exports.executeQuery = exports.deleteObjectsV2 = exports.deleteObjects = exports.setBucketWebsite = exports.setBucketPolicy = exports.createBucketV2 = exports.createBucket = exports.createDatabaseClient = exports.createStorageClient = exports.validateDatabase = exports.validateStorage = exports.isFirebaseApp = void 0;
|
|
4
|
+
const path = require("path");
|
|
5
|
+
const util_1 = require("@e-mc/cloud/util");
|
|
6
|
+
const types_1 = require("@e-mc/types");
|
|
7
|
+
const Module = require("@e-mc/module");
|
|
8
|
+
const Cloud = require("@e-mc/cloud");
|
|
9
|
+
const FIREBASE_DB = {};
|
|
10
|
+
const FIREBASE_STORAGE = {};
|
|
11
|
+
const ADMIN_DB = {};
|
|
12
|
+
const ADMIN_STORAGE = {};
|
|
13
|
+
function getApp(credential, isDB) {
|
|
14
|
+
var _a, _b;
|
|
15
|
+
const { projectId, databaseURL, storageBucket, apiKey, authDomain } = credential;
|
|
16
|
+
if (apiKey && authDomain) {
|
|
17
|
+
const { getApps, initializeApp } = require('@firebase/app');
|
|
18
|
+
let app;
|
|
19
|
+
for (const item of getApps()) {
|
|
20
|
+
const options = item.options;
|
|
21
|
+
if (projectId === options.projectId && apiKey === options.apiKey && authDomain === options.authDomain && (!isDB || isDB && databaseURL === options.databaseURL)) {
|
|
22
|
+
app = item;
|
|
23
|
+
break;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
if (!app) {
|
|
27
|
+
const firebaseKey = (projectId || '') + '_' + apiKey + '_' + authDomain + (isDB ? '_' + databaseURL : '');
|
|
28
|
+
app = isDB ? FIREBASE_DB[firebaseKey] || (FIREBASE_DB[firebaseKey] = initializeApp({ ...credential, databaseURL }, firebaseKey)) : FIREBASE_STORAGE[firebaseKey] || (FIREBASE_STORAGE[firebaseKey] = initializeApp({ ...credential, storageBucket }, firebaseKey));
|
|
29
|
+
}
|
|
30
|
+
if (isDB) {
|
|
31
|
+
const { getDatabase, goOnline } = require('@firebase/database');
|
|
32
|
+
const db = getDatabase(app);
|
|
33
|
+
goOnline(db);
|
|
34
|
+
return db;
|
|
35
|
+
}
|
|
36
|
+
const { getStorage } = require('@firebase/storage');
|
|
37
|
+
return getStorage(app);
|
|
38
|
+
}
|
|
39
|
+
{
|
|
40
|
+
const { getApps, initializeApp, applicationDefault } = require('firebase-admin/app');
|
|
41
|
+
let app;
|
|
42
|
+
for (const item of getApps()) {
|
|
43
|
+
if (!isDB && storageBucket && item.name === storageBucket || isDB && databaseURL && item.name === databaseURL) {
|
|
44
|
+
app = item;
|
|
45
|
+
break;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (!app) {
|
|
49
|
+
app = isDB ? ADMIN_DB[_a = databaseURL || '[DEFAULT]'] || (ADMIN_DB[_a] = initializeApp({ credential: applicationDefault(), databaseURL }, databaseURL)) : ADMIN_STORAGE[_b = storageBucket || '[DEFAULT]'] || (ADMIN_STORAGE[_b] = initializeApp({ credential: applicationDefault(), storageBucket }, storageBucket));
|
|
50
|
+
}
|
|
51
|
+
credential.admin = true;
|
|
52
|
+
if (isDB) {
|
|
53
|
+
const { getDatabase } = require('firebase-admin/database');
|
|
54
|
+
return getDatabase(app);
|
|
55
|
+
}
|
|
56
|
+
const { getStorage } = require('firebase-admin/storage');
|
|
57
|
+
return getStorage(app);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
async function hasBucket(client) {
|
|
61
|
+
const [exists] = await client.exists().catch(err => isErrorConflict(err) ? [true] : [false]);
|
|
62
|
+
return exists;
|
|
63
|
+
}
|
|
64
|
+
function updatePredefinedAcl(acl, values, metadata) {
|
|
65
|
+
const { generation, userProject } = metadata;
|
|
66
|
+
const items = [];
|
|
67
|
+
for (const target of acl.default ? [acl, acl.default] : [acl]) {
|
|
68
|
+
items.push(...values.map(async (value) => {
|
|
69
|
+
if (generation !== undefined) {
|
|
70
|
+
value.generation ?? (value.generation = +generation);
|
|
71
|
+
}
|
|
72
|
+
if (userProject) {
|
|
73
|
+
value.userProject || (value.userProject = userProject);
|
|
74
|
+
}
|
|
75
|
+
const entity = await target.get({ entity: value.entity }).catch(() => null);
|
|
76
|
+
if (entity) {
|
|
77
|
+
return (0, types_1.isString)(value.role) ? target.update(value) : target.delete(value);
|
|
78
|
+
}
|
|
79
|
+
if ((0, types_1.isString)(value.role)) {
|
|
80
|
+
return target.add(value);
|
|
81
|
+
}
|
|
82
|
+
}));
|
|
83
|
+
}
|
|
84
|
+
return Promise.allSettled(items)
|
|
85
|
+
.then(result => {
|
|
86
|
+
const errors = [];
|
|
87
|
+
for (const item of result) {
|
|
88
|
+
if (item.status === 'rejected') {
|
|
89
|
+
errors.push(item.reason);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return errors;
|
|
93
|
+
})
|
|
94
|
+
.catch(err => [err]);
|
|
95
|
+
}
|
|
96
|
+
function setUniformBucketLevel(bucket, enabled) {
|
|
97
|
+
return bucket.setMetadata({ iamConfiguration: { uniformBucketLevelAccess: { enabled } } });
|
|
98
|
+
}
|
|
99
|
+
const getFirebasePackageName = (credential) => credential.apiKey && credential.authDomain ? 'firebase' : 'firebase-admin';
|
|
100
|
+
const hasKeyFile = (credential) => !!(credential.keyFile || credential.keyFilename || process.env.GOOGLE_APPLICATION_CREDENTIALS);
|
|
101
|
+
const isErrorConflict = (err) => (err instanceof Error) && err.code === 409;
|
|
102
|
+
function isFirebaseApp(credential, storage, admin) {
|
|
103
|
+
return !!(credential.apiKey && credential.authDomain && (storage || credential.databaseURL) || credential.product === 'firebase' && process.env.GOOGLE_APPLICATION_CREDENTIALS) && (!admin || !credential.admin);
|
|
104
|
+
}
|
|
105
|
+
exports.isFirebaseApp = isFirebaseApp;
|
|
106
|
+
function validateStorage(credential) {
|
|
107
|
+
return hasKeyFile(credential) || isFirebaseApp(credential, true);
|
|
108
|
+
}
|
|
109
|
+
exports.validateStorage = validateStorage;
|
|
110
|
+
function validateDatabase(credential, data) {
|
|
111
|
+
return hasKeyFile(credential) && !!(data.table || data.query || data.keys || data.product || data.database) || isFirebaseApp(credential);
|
|
112
|
+
}
|
|
113
|
+
exports.validateDatabase = validateDatabase;
|
|
114
|
+
function createStorageClient(credential, bucket) {
|
|
115
|
+
let packageName = '';
|
|
116
|
+
try {
|
|
117
|
+
if (isFirebaseApp(credential, true)) {
|
|
118
|
+
if (bucket) {
|
|
119
|
+
credential.storageBucket = bucket;
|
|
120
|
+
}
|
|
121
|
+
packageName = getFirebasePackageName(credential);
|
|
122
|
+
return getApp(credential, false);
|
|
123
|
+
}
|
|
124
|
+
credential.projectId || (credential.projectId = getProjectId(credential));
|
|
125
|
+
const { Storage } = require(packageName = '@google-cloud/storage');
|
|
126
|
+
return new Storage(credential);
|
|
127
|
+
}
|
|
128
|
+
catch (err) {
|
|
129
|
+
this.checkPackage(err, packageName, { passThrough: true });
|
|
130
|
+
throw err;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
exports.createStorageClient = createStorageClient;
|
|
134
|
+
function createDatabaseClient(credential, data) {
|
|
135
|
+
let packageName = '';
|
|
136
|
+
try {
|
|
137
|
+
const product = data?.product;
|
|
138
|
+
if (product === 'firebase' || isFirebaseApp(credential)) {
|
|
139
|
+
packageName = getFirebasePackageName(credential);
|
|
140
|
+
return getApp(credential, true);
|
|
141
|
+
}
|
|
142
|
+
credential.projectId || (credential.projectId = getProjectId(credential));
|
|
143
|
+
if (data) {
|
|
144
|
+
if (product === 'spanner' || !product && data.name && data.database) {
|
|
145
|
+
const { Spanner } = require(packageName = '@google-cloud/spanner');
|
|
146
|
+
return new Spanner(credential);
|
|
147
|
+
}
|
|
148
|
+
if (product === 'bigtable' || !product && data.name && data.table) {
|
|
149
|
+
const { Bigtable } = require(packageName = '@google-cloud/bigtable');
|
|
150
|
+
return new Bigtable(credential);
|
|
151
|
+
}
|
|
152
|
+
if (product === 'bigquery' || !product && !data.table && typeof data.query === 'string') {
|
|
153
|
+
const { BigQuery } = require(packageName = '@google-cloud/bigquery');
|
|
154
|
+
return new BigQuery(credential);
|
|
155
|
+
}
|
|
156
|
+
if (product === 'datastore' || !product && !data.table && (data.keys || data.query)) {
|
|
157
|
+
const { Datastore } = require(packageName = '@google-cloud/datastore');
|
|
158
|
+
return new Datastore(credential);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const { Firestore } = require(packageName = '@google-cloud/firestore');
|
|
162
|
+
return new Firestore(credential);
|
|
163
|
+
}
|
|
164
|
+
catch (err) {
|
|
165
|
+
this.checkPackage(err, packageName, { passThrough: true });
|
|
166
|
+
throw err;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
exports.createDatabaseClient = createDatabaseClient;
|
|
170
|
+
async function createBucket(credential, bucket, publicRead, service = 'gcp') {
|
|
171
|
+
return createBucketV2.call(this, credential, bucket, publicRead ? 'publicRead' : undefined, createBucketRequest(credential), service);
|
|
172
|
+
}
|
|
173
|
+
exports.createBucket = createBucket;
|
|
174
|
+
async function createBucketV2(credential, bucket, acl, options, service = 'gcp') {
|
|
175
|
+
if (isFirebaseApp(credential, true, true)) {
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
const storage = createStorageClient.call(this, credential, bucket);
|
|
179
|
+
if (await hasBucket(storage.bucket(bucket))) {
|
|
180
|
+
if (acl) {
|
|
181
|
+
await setBucketPolicy.call(this, credential, bucket, { acl }, service);
|
|
182
|
+
}
|
|
183
|
+
return true;
|
|
184
|
+
}
|
|
185
|
+
return storage.createBucket(bucket, options)
|
|
186
|
+
.then(async ([target]) => {
|
|
187
|
+
this.formatMessage(64 /* LOG_TYPE.CLOUD */, service, ["Bucket created" /* VAL_CLOUD.CREATE_BUCKET */, bucket], '', { ...Cloud.LOG_CLOUD_COMMAND });
|
|
188
|
+
if (acl) {
|
|
189
|
+
await setBucketPolicy.call(this, credential, bucket, { acl, bucket: target }, service);
|
|
190
|
+
}
|
|
191
|
+
return true;
|
|
192
|
+
})
|
|
193
|
+
.catch(async (err) => {
|
|
194
|
+
if (isErrorConflict(err)) {
|
|
195
|
+
return acl ? await setBucketPolicy.call(this, credential, bucket, { acl }, service) : true;
|
|
196
|
+
}
|
|
197
|
+
this.formatFail(64 /* LOG_TYPE.CLOUD */, service, ["Unable to create bucket" /* ERR_CLOUD.CREATE_BUCKET */, bucket], err, { ...Cloud.LOG_CLOUD_FAIL });
|
|
198
|
+
return false;
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
exports.createBucketV2 = createBucketV2;
|
|
202
|
+
async function setBucketPolicy(credential, bucket, options, service = 'gcp') {
|
|
203
|
+
if (isFirebaseApp(credential, true, true)) {
|
|
204
|
+
return false;
|
|
205
|
+
}
|
|
206
|
+
const client = createStorageClient.call(this, credential, bucket).bucket(bucket);
|
|
207
|
+
if (!await hasBucket(client)) {
|
|
208
|
+
this.formatFail(64 /* LOG_TYPE.CLOUD */, service, ["Bucket does not exist" /* ERR_CLOUD.EXISTS_BUCKET */, bucket], (0, util_1.formatError)(service, "Bucket does not exist" /* ERR_CLOUD.EXISTS_BUCKET */), { ...Cloud.LOG_CLOUD_FAIL, fatal: false });
|
|
209
|
+
return false;
|
|
210
|
+
}
|
|
211
|
+
const errors = [];
|
|
212
|
+
const acl = options.acl;
|
|
213
|
+
if (!Array.isArray(options.acl)) {
|
|
214
|
+
options.acl = undefined;
|
|
215
|
+
switch (acl) {
|
|
216
|
+
case 'private':
|
|
217
|
+
case 'projectPrivate':
|
|
218
|
+
await client.makePrivate(options).catch(err => !isErrorConflict(err) && errors.push(err));
|
|
219
|
+
await setPredefinedAcl.call(this, client.acl, acl, client, '', options.bucket?.metadata);
|
|
220
|
+
break;
|
|
221
|
+
case 'authenticatedRead':
|
|
222
|
+
await client.makePublic(options).catch(err => !isErrorConflict(err) && errors.push(err));
|
|
223
|
+
options = { ...options };
|
|
224
|
+
options.acl = [{ entity: 'allUsers' }, { entity: 'allAuthenticatedUsers', role: 'READER' }];
|
|
225
|
+
break;
|
|
226
|
+
case 'publicReadWrite':
|
|
227
|
+
await client.makePublic(options).catch(err => !isErrorConflict(err) && errors.push(err));
|
|
228
|
+
options = { ...options };
|
|
229
|
+
options.acl = [{ entity: 'allUsers', role: 'WRITER' }];
|
|
230
|
+
break;
|
|
231
|
+
case 'publicRead':
|
|
232
|
+
await client.makePublic(options).catch(err => !isErrorConflict(err) && errors.push(err));
|
|
233
|
+
break;
|
|
234
|
+
case 'bucketAccessUniform':
|
|
235
|
+
await setUniformBucketLevel(client, true).catch(err => errors.push(err));
|
|
236
|
+
break;
|
|
237
|
+
case 'bucketAccessACL':
|
|
238
|
+
await setUniformBucketLevel(client, false).catch(err => errors.push(err));
|
|
239
|
+
break;
|
|
240
|
+
default:
|
|
241
|
+
errors.push((0, types_1.errorValue)('Invalid ACL', Module.asString(acl) || 'empty'));
|
|
242
|
+
break;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
if (options.acl && (options.acl = options.acl.filter(user => (0, types_1.isString)(user.entity))).length) {
|
|
246
|
+
errors.push(...await updatePredefinedAcl(client.acl, options.acl, options));
|
|
247
|
+
}
|
|
248
|
+
if (errors.length) {
|
|
249
|
+
this.formatFail(64 /* LOG_TYPE.CLOUD */, service, ["Unable to update bucket policy" /* ERR_CLOUD.POLICY_BUCKET */, bucket], errors[0], { ...Cloud.LOG_CLOUD_FAIL, fatal: false });
|
|
250
|
+
return false;
|
|
251
|
+
}
|
|
252
|
+
this.formatMessage(64 /* LOG_TYPE.CLOUD */, service, ["Bucket ACL configured" /* VAL_CLOUD.ACL_BUCKET */, bucket], (0, types_1.isString)(acl) ? acl : '', { ...Cloud.LOG_CLOUD_COMMAND });
|
|
253
|
+
return true;
|
|
254
|
+
}
|
|
255
|
+
exports.setBucketPolicy = setBucketPolicy;
|
|
256
|
+
function setBucketWebsite(credential, bucket, options, service = 'gcp') {
|
|
257
|
+
if (isFirebaseApp(credential, true, true)) {
|
|
258
|
+
return Promise.resolve(false);
|
|
259
|
+
}
|
|
260
|
+
const website = {};
|
|
261
|
+
if ((0, types_1.isString)(options.indexPage)) {
|
|
262
|
+
website.mainPageSuffix = options.indexPage;
|
|
263
|
+
}
|
|
264
|
+
if ((0, types_1.isString)(options.errorPage)) {
|
|
265
|
+
website.notFoundPage = options.errorPage;
|
|
266
|
+
}
|
|
267
|
+
return createStorageClient.call(this, credential, bucket).bucket(bucket).setMetadata({ website })
|
|
268
|
+
.then(() => {
|
|
269
|
+
this.formatMessage(64 /* LOG_TYPE.CLOUD */, service, ["Bucket configured" /* VAL_CLOUD.CONFIGURE_BUCKET */, bucket], website, { ...Cloud.LOG_CLOUD_COMMAND });
|
|
270
|
+
return true;
|
|
271
|
+
})
|
|
272
|
+
.catch(err => {
|
|
273
|
+
this.formatFail(64 /* LOG_TYPE.CLOUD */, service, ["Unable to configure bucket" /* ERR_CLOUD.CONFIGURE_BUCKET */, bucket], err, { ...Cloud.LOG_CLOUD_FAIL, fatal: false });
|
|
274
|
+
return false;
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
exports.setBucketWebsite = setBucketWebsite;
|
|
278
|
+
function deleteObjects(credential, Bucket, service) {
|
|
279
|
+
return deleteObjectsV2.call(this, credential, Bucket, true, service);
|
|
280
|
+
}
|
|
281
|
+
exports.deleteObjects = deleteObjects;
|
|
282
|
+
async function deleteObjectsV2(credential, bucket, recursive = true, service = 'gcp') {
|
|
283
|
+
const storage = createStorageClient.call(this, credential, bucket);
|
|
284
|
+
const errors = [];
|
|
285
|
+
let promise;
|
|
286
|
+
if (isFirebaseApp(credential, true, true)) {
|
|
287
|
+
const { ref, listAll, deleteObject } = require('@firebase/storage');
|
|
288
|
+
const files = [];
|
|
289
|
+
await (async function recurse(prefix) {
|
|
290
|
+
try {
|
|
291
|
+
const { items, prefixes } = await listAll(ref(storage, prefix));
|
|
292
|
+
if (items.length) {
|
|
293
|
+
files.push(...items.map(value => value.fullPath));
|
|
294
|
+
}
|
|
295
|
+
if (recursive && prefixes.length) {
|
|
296
|
+
for (const { name } of prefixes) {
|
|
297
|
+
await recurse(Module.joinPath(prefix, name));
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
catch (err) {
|
|
302
|
+
errors.push(err);
|
|
303
|
+
}
|
|
304
|
+
})('');
|
|
305
|
+
if (files.length) {
|
|
306
|
+
promise = Promise.allSettled(files.map(value => deleteObject(ref(storage, value))));
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
else {
|
|
310
|
+
const client = storage.bucket(bucket);
|
|
311
|
+
if (await hasBucket(client)) {
|
|
312
|
+
if (recursive) {
|
|
313
|
+
return client.deleteFiles({ force: true }).then(() => this.formatMessage(64 /* LOG_TYPE.CLOUD */, service, "Bucket emptied" /* VAL_CLOUD.EMPTY_BUCKET */ + ' (recursive)', bucket, { ...Cloud.LOG_CLOUD_COMMAND }));
|
|
314
|
+
}
|
|
315
|
+
const tasks = [];
|
|
316
|
+
try {
|
|
317
|
+
const result = await client.getFiles();
|
|
318
|
+
for (const { name } of result[0]) {
|
|
319
|
+
if (name.indexOf('/') === -1) {
|
|
320
|
+
tasks.push(client.file(name).delete({ ignoreNotFound: true }).catch(err => this.formatFail(64 /* LOG_TYPE.CLOUD */, service, ["Delete failed" /* ERR_CLOUD.DELETE_FAIL */, name], err, { ...Cloud.LOG_CLOUD_FAIL, fatal: false })));
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
catch (err) {
|
|
325
|
+
errors.push(err);
|
|
326
|
+
}
|
|
327
|
+
if (tasks.length) {
|
|
328
|
+
promise = Promise.allSettled(tasks);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
const checkErrors = () => {
|
|
333
|
+
if (errors.length) {
|
|
334
|
+
this.formatFail(64 /* LOG_TYPE.CLOUD */, service, ["Unable to empty bucket" /* ERR_CLOUD.DELETE_BUCKET */ + (recursive ? ' (recursive)' : ''), errors.length + ' errors'], errors[0], { ...Cloud.LOG_CLOUD_FAIL, fatal: false });
|
|
335
|
+
return true;
|
|
336
|
+
}
|
|
337
|
+
return false;
|
|
338
|
+
};
|
|
339
|
+
if (promise) {
|
|
340
|
+
return promise.then(result => {
|
|
341
|
+
errors.push(...result.filter(item => item.status === 'rejected').map((item) => item.reason));
|
|
342
|
+
if (!checkErrors()) {
|
|
343
|
+
const files = result.length + ' files';
|
|
344
|
+
this.formatMessage(64 /* LOG_TYPE.CLOUD */, service, ["Bucket emptied" /* VAL_CLOUD.EMPTY_BUCKET */ + ` (${recursive ? 'recursive' : files})`, bucket], recursive ? files : '', { ...Cloud.LOG_CLOUD_COMMAND });
|
|
345
|
+
}
|
|
346
|
+
})
|
|
347
|
+
.catch(err => {
|
|
348
|
+
errors.push(err);
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
checkErrors();
|
|
352
|
+
}
|
|
353
|
+
exports.deleteObjectsV2 = deleteObjectsV2;
|
|
354
|
+
async function executeQuery(credential, data, sessionKey) {
|
|
355
|
+
return (await executeBatchQuery.call(this, credential, [data], sessionKey))[0] || [];
|
|
356
|
+
}
|
|
357
|
+
exports.executeQuery = executeQuery;
|
|
358
|
+
async function executeBatchQuery(credential, batch, sessionKey) {
|
|
359
|
+
const length = batch.length;
|
|
360
|
+
const result = new Array(length);
|
|
361
|
+
const clients = [];
|
|
362
|
+
const caching = length > 0 && this.hasCache(batch[0].service, sessionKey);
|
|
363
|
+
const cacheValue = { value: this.valueOfKey(credential, 'cache'), sessionKey };
|
|
364
|
+
const authItems = [];
|
|
365
|
+
const createClient = (data, type) => {
|
|
366
|
+
const client = clients[type];
|
|
367
|
+
if (client) {
|
|
368
|
+
return client;
|
|
369
|
+
}
|
|
370
|
+
const item = length === 1 ? credential : { ...credential };
|
|
371
|
+
authItems.push(item);
|
|
372
|
+
return (clients[type] = createDatabaseClient.call(this, item, data));
|
|
373
|
+
};
|
|
374
|
+
const closeClient = () => {
|
|
375
|
+
const fs = clients[3 /* DB.FIRESTORE */];
|
|
376
|
+
if (fs) {
|
|
377
|
+
fs.terminate();
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
const getFamily = (data, row, family) => {
|
|
381
|
+
const familyData = data[family];
|
|
382
|
+
for (const qualifier of Object.keys(familyData)) {
|
|
383
|
+
const items = familyData[qualifier];
|
|
384
|
+
row[qualifier] = items.length === 1 ? items[0].value : items.map(col => col.value);
|
|
385
|
+
}
|
|
386
|
+
return row;
|
|
387
|
+
};
|
|
388
|
+
const getRowData = (rowId, data) => {
|
|
389
|
+
const families = Object.keys(data);
|
|
390
|
+
const row = { '__id__': rowId };
|
|
391
|
+
if (families.length === 1) {
|
|
392
|
+
return getFamily(data, row, families[0]);
|
|
393
|
+
}
|
|
394
|
+
for (const family of families) {
|
|
395
|
+
row[family] = getFamily(data, {}, family);
|
|
396
|
+
}
|
|
397
|
+
return row;
|
|
398
|
+
};
|
|
399
|
+
for (let i = 0; i < length; ++i) {
|
|
400
|
+
const item = batch[i];
|
|
401
|
+
const { service, product, name, database, table, id, query, orderBy, keys, limit = 0, update, ignoreCache } = item;
|
|
402
|
+
const renewCache = ignoreCache === 0;
|
|
403
|
+
const cached = caching && ignoreCache !== true || ignoreCache === false || ignoreCache === 1 || renewCache;
|
|
404
|
+
const getCache = (value) => {
|
|
405
|
+
if (ignoreCache === 1) {
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
cacheValue.renewCache = renewCache;
|
|
409
|
+
return this.getQueryResult(service, credential, value, cacheValue);
|
|
410
|
+
};
|
|
411
|
+
let rows, queryString = '';
|
|
412
|
+
if (product === 'bigtable' || !product && name && table && !database) {
|
|
413
|
+
const { columns, options = {} } = item;
|
|
414
|
+
if ((0, types_1.isObject)(query)) {
|
|
415
|
+
options.filter = query;
|
|
416
|
+
}
|
|
417
|
+
if (!id && limit > 0) {
|
|
418
|
+
(options.gaxOptions || (options.gaxOptions = {})).maxResults = limit;
|
|
419
|
+
}
|
|
420
|
+
if (cached && (rows = getCache(queryString = name + '_' + table + '_' + (id ? id + ((0, types_1.isArray)(columns) ? '_' + Module.asString(columns, true) : '') : '') + Module.asString(options, true)))) {
|
|
421
|
+
result[i] = rows;
|
|
422
|
+
continue;
|
|
423
|
+
}
|
|
424
|
+
const db = createClient(item, 4 /* DB.BIGTABLE */).instance(name).table(table);
|
|
425
|
+
if (id) {
|
|
426
|
+
const row = db.row(id);
|
|
427
|
+
if (Array.isArray(columns)) {
|
|
428
|
+
const [data] = await row.get(columns, options);
|
|
429
|
+
rows = [getRowData(id, data)];
|
|
430
|
+
}
|
|
431
|
+
else {
|
|
432
|
+
const [response] = await row.get(options);
|
|
433
|
+
rows = [getRowData(response.id, response.data)];
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
else {
|
|
437
|
+
rows = [];
|
|
438
|
+
await new Promise((resolve, reject) => {
|
|
439
|
+
db.createReadStream(options)
|
|
440
|
+
.on('data', row => rows.push(getRowData(row.id, row.data)))
|
|
441
|
+
.on('error', reject)
|
|
442
|
+
.on('end', resolve);
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
else if (product === 'spanner' || !product && name && database && (query || table)) {
|
|
447
|
+
const columns = (0, types_1.isPlainObject)(query) && query.columns || item.columns;
|
|
448
|
+
if (!(query || table && columns)) {
|
|
449
|
+
closeClient();
|
|
450
|
+
throw (0, util_1.formatError)(item, "Missing database query" /* ERR_DB.QUERY */);
|
|
451
|
+
}
|
|
452
|
+
if (!name || !database) {
|
|
453
|
+
closeClient();
|
|
454
|
+
throw (0, util_1.formatError)(item, !name ? "Missing instance name" /* ERR_DB.INSTANCE */ : "Missing database name" /* ERR_DB.NAME */);
|
|
455
|
+
}
|
|
456
|
+
const { updateType, options = {} } = item;
|
|
457
|
+
if (cached) {
|
|
458
|
+
queryString = name + '_' + database + '_' + (table ? table + Module.asString(columns, true) : '') + Module.asString(query, true) + limit;
|
|
459
|
+
if (!update && (rows = getCache(queryString))) {
|
|
460
|
+
result[i] = rows;
|
|
461
|
+
continue;
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
const db = createClient(item, 5 /* DB.SPANNER */).instance(name).database(database, options.databasePool, options.databaseQuery);
|
|
465
|
+
if (table) {
|
|
466
|
+
if ((0, types_1.isPlainObject)(update)) {
|
|
467
|
+
await db.table(table)[updateType === 1 ? 'insert' : updateType === 2 ? 'replace' : 'update'](update, options.tableUpdate);
|
|
468
|
+
}
|
|
469
|
+
const request = (0, types_1.isPlainObject)(query) ? query : { columns };
|
|
470
|
+
request.json = true;
|
|
471
|
+
request.columns || (request.columns = item.columns);
|
|
472
|
+
request.keySet = { all: true };
|
|
473
|
+
if (limit > 0) {
|
|
474
|
+
request.limit = limit;
|
|
475
|
+
}
|
|
476
|
+
[rows] = await db.table(table).read(request, options.tableRead);
|
|
477
|
+
}
|
|
478
|
+
else {
|
|
479
|
+
if ((0, types_1.isString)(update) || (0, types_1.isPlainObject)(update) && (0, types_1.isString)(update.sql)) {
|
|
480
|
+
await new Promise((resolve, reject) => {
|
|
481
|
+
db.runTransaction((err, transaction) => {
|
|
482
|
+
if (err || !transaction) {
|
|
483
|
+
reject(err || new Error("Unknown" /* ERR_MESSAGE.UNKNOWN */));
|
|
484
|
+
}
|
|
485
|
+
else {
|
|
486
|
+
transaction.runUpdate(update)
|
|
487
|
+
.then(() => transaction.commit().then(() => resolve()).catch(error => reject(error)))
|
|
488
|
+
.catch(error => reject(error));
|
|
489
|
+
}
|
|
490
|
+
});
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
const request = (0, types_1.isPlainObject)(query) ? query : { sql: query };
|
|
494
|
+
request.json = true;
|
|
495
|
+
if (limit > 0) {
|
|
496
|
+
(request.gaxOptions || (request.gaxOptions = {})).maxResults = limit;
|
|
497
|
+
}
|
|
498
|
+
[rows] = await db.run(request);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
else if (product === 'firebase' || product === 'bigquery' || !product && !table && typeof query === 'string') {
|
|
502
|
+
if (!(0, types_1.isString)(query)) {
|
|
503
|
+
closeClient();
|
|
504
|
+
throw (0, util_1.formatError)(item, "Missing database query" /* ERR_DB.QUERY */);
|
|
505
|
+
}
|
|
506
|
+
const firebaseApp = product === 'firebase' || isFirebaseApp(credential);
|
|
507
|
+
if (cached) {
|
|
508
|
+
queryString = query + (firebaseApp ? Module.asString(orderBy, true) : Module.asString(item.params, true) + Module.asString(item.options, true) + limit);
|
|
509
|
+
if ((product === 'bigquery' || !update) && (rows = getCache(queryString))) {
|
|
510
|
+
result[i] = rows;
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
if (firebaseApp) {
|
|
515
|
+
const { ref, get, child, query: queryDB, update: updateDB } = require('@firebase/database');
|
|
516
|
+
const constraints = [];
|
|
517
|
+
let limiter = 0;
|
|
518
|
+
if ((0, types_1.isArray)(orderBy)) {
|
|
519
|
+
const sort = require('@firebase/database');
|
|
520
|
+
for (const items of orderBy) {
|
|
521
|
+
if ((0, types_1.isArray)(items)) {
|
|
522
|
+
const method = items[0];
|
|
523
|
+
switch (method) {
|
|
524
|
+
case 'orderByChild':
|
|
525
|
+
constraints.push(sort.orderByChild(items[1]));
|
|
526
|
+
break;
|
|
527
|
+
case 'orderByKey':
|
|
528
|
+
case 'orderByValue':
|
|
529
|
+
case 'orderByPriority':
|
|
530
|
+
constraints.push(sort[method]());
|
|
531
|
+
break;
|
|
532
|
+
case 'limitToFirst':
|
|
533
|
+
case 'limitToLast':
|
|
534
|
+
constraints.push(sort[method](limiter = +items[1]));
|
|
535
|
+
break;
|
|
536
|
+
case 'startAt':
|
|
537
|
+
case 'startAfter':
|
|
538
|
+
case 'endAt':
|
|
539
|
+
case 'endBefore':
|
|
540
|
+
case 'equalTo':
|
|
541
|
+
constraints.push(sort[method](items[1], items[2]));
|
|
542
|
+
break;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
const db = createClient(item, 0 /* DB.FIREBASE */);
|
|
548
|
+
if ((0, types_1.isPlainObject)(update)) {
|
|
549
|
+
await updateDB(ref(db, query), update);
|
|
550
|
+
}
|
|
551
|
+
const snapshot = await (constraints.length ? get(queryDB(ref(db, query), ...constraints)) : get(child(ref(db), query)));
|
|
552
|
+
if (snapshot.exists()) {
|
|
553
|
+
const val = snapshot.val();
|
|
554
|
+
const group = limiter === 1 && Object.keys(val);
|
|
555
|
+
rows = [group && (0, types_1.isObject)(val) && (0, types_1.isObject)(val[group[0]]) ? val[group[0]] : val];
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
else {
|
|
559
|
+
const { options = {} } = item;
|
|
560
|
+
options.query = query;
|
|
561
|
+
options.params || (options.params = item.params);
|
|
562
|
+
if (limit > 0) {
|
|
563
|
+
options.maxResults = limit;
|
|
564
|
+
}
|
|
565
|
+
const [job] = await createClient(item, 1 /* DB.BIGQUERY */).createQueryJob(options);
|
|
566
|
+
[rows] = await job.getQueryResults();
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
else if (product === 'datastore' || !product && !table && (keys || query)) {
|
|
570
|
+
if (!keys && !Array.isArray(query)) {
|
|
571
|
+
closeClient();
|
|
572
|
+
throw (0, util_1.formatError)(item, "Missing database query" /* ERR_DB.QUERY */);
|
|
573
|
+
}
|
|
574
|
+
if (cached && (rows = getCache(queryString = Module.asString(keys || query, true) + Module.asString(item.options, true) + limit))) {
|
|
575
|
+
result[i] = rows;
|
|
576
|
+
continue;
|
|
577
|
+
}
|
|
578
|
+
const db = createClient(item, 2 /* DB.DATASTORE */);
|
|
579
|
+
if (keys) {
|
|
580
|
+
const items = !Array.isArray(keys) ? db.key(keys) : keys.map((key) => db.key(key));
|
|
581
|
+
rows = await db.get(items, item.options);
|
|
582
|
+
if (rows.length > limit) {
|
|
583
|
+
rows = rows.slice(0, limit);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
else {
|
|
587
|
+
const task = db.createQuery(item.kind);
|
|
588
|
+
for (const args of query) {
|
|
589
|
+
if ((0, types_1.isArray)(args)) {
|
|
590
|
+
const method = args[0];
|
|
591
|
+
switch (method) {
|
|
592
|
+
case 'end':
|
|
593
|
+
case 'filter':
|
|
594
|
+
case 'groupBy':
|
|
595
|
+
case 'hasAncestor':
|
|
596
|
+
case 'limit':
|
|
597
|
+
case 'offset':
|
|
598
|
+
case 'order':
|
|
599
|
+
case 'select':
|
|
600
|
+
case 'start':
|
|
601
|
+
task[method].apply(task, args.slice(1)); // eslint-disable-line prefer-spread
|
|
602
|
+
break;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
if (limit > 0) {
|
|
607
|
+
task.limit(limit);
|
|
608
|
+
}
|
|
609
|
+
[rows] = await db.runQuery(task, item.options);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
else if (product === 'firestore' || !product && table) {
|
|
613
|
+
if (!table) {
|
|
614
|
+
closeClient();
|
|
615
|
+
throw (0, util_1.formatError)(item, "Missing database table" /* ERR_DB.TABLE */);
|
|
616
|
+
}
|
|
617
|
+
if (cached) {
|
|
618
|
+
queryString = table + '_';
|
|
619
|
+
}
|
|
620
|
+
if (id) {
|
|
621
|
+
if (cached) {
|
|
622
|
+
queryString += id;
|
|
623
|
+
if (!update && (rows = getCache(queryString))) {
|
|
624
|
+
result[i] = rows;
|
|
625
|
+
continue;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
const db = createClient(item, 3 /* DB.FIRESTORE */).collection(table).doc(id);
|
|
629
|
+
if ((0, types_1.isPlainObject)(update)) {
|
|
630
|
+
await db.update(update, { exists: true });
|
|
631
|
+
}
|
|
632
|
+
const data = (await db.get()).data();
|
|
633
|
+
if (data) {
|
|
634
|
+
rows = [data];
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
else if (Array.isArray(query)) {
|
|
638
|
+
if (cached && (rows = getCache(queryString += Module.asString(query, true) + Module.asString(orderBy, true) + limit))) {
|
|
639
|
+
result[i] = rows;
|
|
640
|
+
continue;
|
|
641
|
+
}
|
|
642
|
+
let db = createClient(item, 3 /* DB.FIRESTORE */).collection(table);
|
|
643
|
+
for (const args of query) {
|
|
644
|
+
if ((0, types_1.isArray)(args)) {
|
|
645
|
+
const method = args[0];
|
|
646
|
+
switch (method) {
|
|
647
|
+
case 'endAt':
|
|
648
|
+
case 'endBefore':
|
|
649
|
+
case 'limit':
|
|
650
|
+
case 'limitToLast':
|
|
651
|
+
case 'offset':
|
|
652
|
+
case 'orderBy':
|
|
653
|
+
case 'select':
|
|
654
|
+
case 'startAfter':
|
|
655
|
+
case 'startAt':
|
|
656
|
+
case 'where':
|
|
657
|
+
case 'withConverter':
|
|
658
|
+
db = db[method].apply(db, args.slice(1)); // eslint-disable-line prefer-spread
|
|
659
|
+
break;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
if ((0, types_1.isArray)(orderBy)) {
|
|
664
|
+
for (const order of orderBy) {
|
|
665
|
+
if ((0, types_1.isArray)(order)) {
|
|
666
|
+
db = db.orderBy(order[0], order[1]);
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
if (limit > 0) {
|
|
671
|
+
db = db.limit(limit);
|
|
672
|
+
}
|
|
673
|
+
rows = (await db.get()).docs.map(doc => doc.data());
|
|
674
|
+
}
|
|
675
|
+
else {
|
|
676
|
+
closeClient();
|
|
677
|
+
throw (0, util_1.formatError)(item, "Missing database query" /* ERR_DB.QUERY */);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
else {
|
|
681
|
+
closeClient();
|
|
682
|
+
throw (0, util_1.formatError)(item, "Missing database product" /* ERR_DB.PRODUCT */);
|
|
683
|
+
}
|
|
684
|
+
result[i] = this.setQueryResult(service, credential, queryString, rows, cacheValue);
|
|
685
|
+
}
|
|
686
|
+
closeClient();
|
|
687
|
+
return result;
|
|
688
|
+
}
|
|
689
|
+
exports.executeBatchQuery = executeBatchQuery;
|
|
690
|
+
function setPublicRead(acl, pathname, requested, service = 'gcp') {
|
|
691
|
+
acl.add({ entity: 'allUsers', role: 'READER' })
|
|
692
|
+
.then(() => {
|
|
693
|
+
if (requested) {
|
|
694
|
+
this.formatMessage(64 /* LOG_TYPE.CLOUD */, service, "Grant public-read" /* VAL_CLOUD.PUBLIC_READ */, pathname, { ...Cloud.LOG_CLOUD_COMMAND });
|
|
695
|
+
}
|
|
696
|
+
})
|
|
697
|
+
.catch(err => {
|
|
698
|
+
if (requested) {
|
|
699
|
+
this.formatMessage(64 /* LOG_TYPE.CLOUD */, service, ["Unable to grant public-read" /* ERR_CLOUD.PUBLIC_READ */, pathname], err, { ...Cloud.LOG_CLOUD_WARN });
|
|
700
|
+
}
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
exports.setPublicRead = setPublicRead;
|
|
704
|
+
async function setPredefinedAcl(target, value, bucket, pathname = '', metadata = {}, requested = true, service = 'gcp') {
|
|
705
|
+
let revoke;
|
|
706
|
+
if (metadata === true) {
|
|
707
|
+
revoke = true;
|
|
708
|
+
metadata = {};
|
|
709
|
+
}
|
|
710
|
+
let items;
|
|
711
|
+
switch (value) {
|
|
712
|
+
case 'publicRead':
|
|
713
|
+
items = [{ entity: 'allUsers', role: revoke ? undefined : 'READER' }];
|
|
714
|
+
break;
|
|
715
|
+
case 'authenticatedRead':
|
|
716
|
+
items = [{ entity: 'allUsers' }, { entity: 'allAuthenticatedUsers', role: revoke ? undefined : 'READER' }];
|
|
717
|
+
break;
|
|
718
|
+
default: {
|
|
719
|
+
const owner = metadata.owner?.entity;
|
|
720
|
+
let acl = metadata.acl;
|
|
721
|
+
if ((0, types_1.isArray)(acl)) {
|
|
722
|
+
items = [];
|
|
723
|
+
}
|
|
724
|
+
else {
|
|
725
|
+
if (bucket) {
|
|
726
|
+
const [users] = await bucket.acl.get().catch(() => [[]]);
|
|
727
|
+
acl = Array.isArray(users) ? users : [users];
|
|
728
|
+
}
|
|
729
|
+
else {
|
|
730
|
+
acl = [];
|
|
731
|
+
}
|
|
732
|
+
items = [{ entity: 'allUsers' }, { entity: 'allAuthenticatedUsers' }];
|
|
733
|
+
}
|
|
734
|
+
switch (value) {
|
|
735
|
+
case 'private': {
|
|
736
|
+
const owners = new Set(acl.filter(item => item.role === 'OWNER').map(item => item.entity));
|
|
737
|
+
if (owner) {
|
|
738
|
+
owners.add(owner);
|
|
739
|
+
}
|
|
740
|
+
if (owners.size) {
|
|
741
|
+
for (const user of acl) {
|
|
742
|
+
const entity = user.entity;
|
|
743
|
+
if (!owners.has(entity)) {
|
|
744
|
+
items.push({ entity });
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
break;
|
|
749
|
+
}
|
|
750
|
+
case 'projectPrivate':
|
|
751
|
+
for (const user of acl) {
|
|
752
|
+
const entity = user.entity;
|
|
753
|
+
if (entity.startsWith('project-')) {
|
|
754
|
+
items.push({ ...user, role: entity.startsWith('project-editors-') || entity.startsWith('project-owners-') ? 'OWNER' : 'READER' });
|
|
755
|
+
}
|
|
756
|
+
else {
|
|
757
|
+
items.push({ ...user, role: undefined });
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
break;
|
|
761
|
+
case 'bucketOwnerRead':
|
|
762
|
+
if (bucket && owner) {
|
|
763
|
+
for (const user of acl) {
|
|
764
|
+
if (user.entity !== owner) {
|
|
765
|
+
items.push({ entity: user.entity, role: 'READER' });
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
case 'bucketOwnerFullControl':
|
|
770
|
+
if (bucket && owner) {
|
|
771
|
+
items.push({ entity: owner, role: 'OWNER' });
|
|
772
|
+
}
|
|
773
|
+
break;
|
|
774
|
+
default:
|
|
775
|
+
return Promise.resolve();
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
return updatePredefinedAcl(target, items, metadata).then(errors => {
|
|
780
|
+
if (errors.length) {
|
|
781
|
+
this.formatMessage(64 /* LOG_TYPE.CLOUD */, service, [`Unable to ${revoke ? 'revoke' : 'grant'} ` + value, bucket && pathname ? bucket.name + '/' + pathname : bucket ? bucket.name : pathname], errors[0], { ...Cloud.LOG_CLOUD_WARN });
|
|
782
|
+
}
|
|
783
|
+
else if (requested && (bucket || pathname)) {
|
|
784
|
+
this.formatMessage(64 /* LOG_TYPE.CLOUD */, service, [(revoke ? 'Revoke' : 'Grant') + ' ' + value, bucket?.name], pathname, { ...Cloud.LOG_CLOUD_COMMAND });
|
|
785
|
+
}
|
|
786
|
+
});
|
|
787
|
+
}
|
|
788
|
+
exports.setPredefinedAcl = setPredefinedAcl;
|
|
789
|
+
function createBucketRequest(credential) {
|
|
790
|
+
const options = {};
|
|
791
|
+
for (const attr in credential) {
|
|
792
|
+
switch (attr) {
|
|
793
|
+
case 'archive':
|
|
794
|
+
case 'coldline':
|
|
795
|
+
case 'cors':
|
|
796
|
+
case 'customPlacementConfig':
|
|
797
|
+
case 'dra':
|
|
798
|
+
case 'location':
|
|
799
|
+
case 'multiRegional':
|
|
800
|
+
case 'nearline':
|
|
801
|
+
case 'regional':
|
|
802
|
+
case 'requesterPays':
|
|
803
|
+
case 'retentionPolicy':
|
|
804
|
+
case 'rpo':
|
|
805
|
+
case 'standard':
|
|
806
|
+
case 'storageClass':
|
|
807
|
+
case 'userProject':
|
|
808
|
+
case 'versioning':
|
|
809
|
+
options[attr] = credential[attr];
|
|
810
|
+
break;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
return options;
|
|
814
|
+
}
|
|
815
|
+
exports.createBucketRequest = createBucketRequest;
|
|
816
|
+
function getProjectId(credential) {
|
|
817
|
+
try {
|
|
818
|
+
let pathname = credential.keyFilename || credential.keyFile;
|
|
819
|
+
if (pathname && Module.isPath(pathname = path.resolve(pathname)) || (pathname = process.env.GOOGLE_APPLICATION_CREDENTIALS) && Module.isPath(pathname = path.resolve(pathname))) {
|
|
820
|
+
const projectId = require(pathname).project_id;
|
|
821
|
+
if ((0, types_1.isString)(projectId)) {
|
|
822
|
+
return projectId;
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
catch {
|
|
827
|
+
}
|
|
828
|
+
return '';
|
|
829
|
+
}
|
|
830
|
+
exports.getProjectId = getProjectId;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const path = require("path");
|
|
4
|
+
const fs = require("fs");
|
|
5
|
+
const https = require("https");
|
|
6
|
+
const client_1 = require("../client");
|
|
7
|
+
const types_1 = require("@e-mc/types");
|
|
8
|
+
const Module = require("@e-mc/module");
|
|
9
|
+
const Cloud = require("@e-mc/cloud");
|
|
10
|
+
function download(credential, service = 'gcp') {
|
|
11
|
+
const storage = client_1.createStorageClient.call(this, credential);
|
|
12
|
+
return (data, callback) => {
|
|
13
|
+
const { bucket: Bucket, download: target } = data;
|
|
14
|
+
const Key = target.filename;
|
|
15
|
+
const firebase = (0, client_1.isFirebaseApp)(credential, true, true);
|
|
16
|
+
let tempDir;
|
|
17
|
+
const downloadResponse = (err, url) => {
|
|
18
|
+
callback(err, url);
|
|
19
|
+
if (tempDir) {
|
|
20
|
+
queueMicrotask(() => Module.removeDir(tempDir));
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
if (!Bucket || !Key) {
|
|
24
|
+
downloadResponse((0, types_1.errorValue)('Missing property', !Bucket ? 'Bucket' : 'Key'));
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
if (!(tempDir = this.getTempDir({ uuidDir: true }))) {
|
|
28
|
+
downloadResponse(new Error("Unable to create temp directory" /* ERR_CLOUD.TEMP_DIR */));
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
const location = Module.joinPath(Bucket, Key);
|
|
32
|
+
const destination = path.join(tempDir, path.basename(Key));
|
|
33
|
+
const deleteMessage = () => this.formatMessage(64 /* LOG_TYPE.CLOUD */, service, "Delete success" /* VAL_CLOUD.DELETE_FILE */, location, { ...Cloud.LOG_CLOUD_DELETE });
|
|
34
|
+
if (firebase) {
|
|
35
|
+
const { ref, getDownloadURL, deleteObject } = require('@firebase/storage');
|
|
36
|
+
const objectRef = ref(storage, Key);
|
|
37
|
+
getDownloadURL(objectRef).then(url => {
|
|
38
|
+
https.get(url, res => {
|
|
39
|
+
const statusCode = res.statusCode;
|
|
40
|
+
if (statusCode >= 200 && statusCode < 300) {
|
|
41
|
+
res.on('error', err => downloadResponse(err));
|
|
42
|
+
res.pipe(fs.createWriteStream(destination)
|
|
43
|
+
.on('finish', () => {
|
|
44
|
+
downloadResponse(null, destination);
|
|
45
|
+
if (target.deleteObject) {
|
|
46
|
+
deleteObject(objectRef)
|
|
47
|
+
.then(() => deleteMessage())
|
|
48
|
+
.catch(err => this.formatFail(64 /* LOG_TYPE.CLOUD */, service, ["Delete failed" /* ERR_CLOUD.DELETE_FAIL */, location], err, { ...Cloud.LOG_CLOUD_FAIL, fatal: !!target.active }));
|
|
49
|
+
}
|
|
50
|
+
})
|
|
51
|
+
.on('error', err => downloadResponse(err)));
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
downloadResponse((0, types_1.errorMessage)(statusCode, 'Invalid HTTP request', location));
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
const bucket = storage.bucket(Bucket);
|
|
61
|
+
const file = bucket.file(Key, { generation: target.versionId });
|
|
62
|
+
file.download({ destination })
|
|
63
|
+
.then(() => {
|
|
64
|
+
downloadResponse(null, destination);
|
|
65
|
+
const deleteObject = target.deleteObject;
|
|
66
|
+
if (deleteObject) {
|
|
67
|
+
file.delete((0, types_1.isPlainObject)(deleteObject) ? deleteObject : { ignoreNotFound: true }, err => {
|
|
68
|
+
if (!err) {
|
|
69
|
+
deleteMessage();
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
this.formatFail(64 /* LOG_TYPE.CLOUD */, service, ["Delete failed" /* ERR_CLOUD.DELETE_FAIL */, location], err, { ...Cloud.LOG_CLOUD_FAIL, fatal: !!target.active });
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
})
|
|
77
|
+
.catch(err => downloadResponse(err));
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
module.exports = download;
|
package/package.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@pi-r/gcp",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Google (GCP) cloud functions for E-mc.",
|
|
5
|
+
"main": "client/index.js",
|
|
6
|
+
"publishConfig": {
|
|
7
|
+
"access": "public"
|
|
8
|
+
},
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "https://github.com/anpham6/pi-r.git",
|
|
12
|
+
"directory": "src/cloud/gcp"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"squared",
|
|
16
|
+
"e-mc",
|
|
17
|
+
"squared-functions"
|
|
18
|
+
],
|
|
19
|
+
"author": "An Pham <anpham6@gmail.com>",
|
|
20
|
+
"license": "MIT",
|
|
21
|
+
"homepage": "https://github.com/anpham6/pi-r#readme",
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"@e-mc/cloud": "^0.4.0",
|
|
24
|
+
"@e-mc/module": "^0.4.0",
|
|
25
|
+
"@e-mc/types": "^0.4.0",
|
|
26
|
+
"@google-cloud/firestore": "^6.5.0",
|
|
27
|
+
"@google-cloud/storage": "^6.9.4"
|
|
28
|
+
}
|
|
29
|
+
}
|
package/upload/index.js
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const path = require("path");
|
|
4
|
+
const fs = require("fs");
|
|
5
|
+
const client_1 = require("../client");
|
|
6
|
+
const util_1 = require("@e-mc/cloud/util");
|
|
7
|
+
const types_1 = require("@e-mc/types");
|
|
8
|
+
const Module = require("@e-mc/module");
|
|
9
|
+
const Cloud = require("@e-mc/cloud");
|
|
10
|
+
const BUCKET_SESSION = new Set();
|
|
11
|
+
const BUCKET_RESPONSE = {};
|
|
12
|
+
const getBucketKey = (credential, bucket, acl = '') => Module.asString(credential, true) + bucket + '_' + acl;
|
|
13
|
+
function upload(credential, service = 'gcp') {
|
|
14
|
+
const storage = client_1.createStorageClient.call(this, credential);
|
|
15
|
+
return async (data, callback) => {
|
|
16
|
+
var _a;
|
|
17
|
+
const firebase = (0, client_1.isFirebaseApp)(credential, true, true);
|
|
18
|
+
const { bucket, localUri } = data;
|
|
19
|
+
const { pathname = '', fileGroup, contentType, metadata, endpoint, active, publicRead, acl, admin = {}, overwrite, options } = data.upload;
|
|
20
|
+
let filename = data.upload.filename || path.basename(localUri), bucketClient, bucketKey, listFiles;
|
|
21
|
+
const uploadResponse = (err, url) => {
|
|
22
|
+
if (!firebase) {
|
|
23
|
+
BUCKET_SESSION.delete(bucket);
|
|
24
|
+
if (bucketKey) {
|
|
25
|
+
delete BUCKET_RESPONSE[bucketKey];
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
callback(err, url);
|
|
29
|
+
};
|
|
30
|
+
if (firebase) {
|
|
31
|
+
const { ref, listAll } = require('@firebase/storage');
|
|
32
|
+
bucketClient = ref(storage, bucket);
|
|
33
|
+
if (!overwrite) {
|
|
34
|
+
try {
|
|
35
|
+
listFiles = (await listAll(bucketClient)).items.map(item => item.fullPath);
|
|
36
|
+
}
|
|
37
|
+
catch (err) {
|
|
38
|
+
uploadResponse(err);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
if (!BUCKET_SESSION.has(bucket)) {
|
|
45
|
+
const bucketAcl = admin.publicRead ? 'publicRead' : admin.acl;
|
|
46
|
+
const response = BUCKET_RESPONSE[_a = bucketKey = getBucketKey(credential, bucket, bucketAcl)] || (BUCKET_RESPONSE[_a] = client_1.createBucketV2.call(this, credential, bucket, bucketAcl, admin.configBucket?.create || (0, client_1.createBucketRequest)(credential)));
|
|
47
|
+
if (!await response) {
|
|
48
|
+
uploadResponse(null);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
BUCKET_SESSION.add(bucket);
|
|
52
|
+
}
|
|
53
|
+
bucketClient = storage.bucket(bucket);
|
|
54
|
+
}
|
|
55
|
+
if (!overwrite && (!listFiles || listFiles.length)) {
|
|
56
|
+
const current = filename;
|
|
57
|
+
const next = (0, util_1.generateFilename)(filename);
|
|
58
|
+
let i = 0, exists;
|
|
59
|
+
do {
|
|
60
|
+
if (i > 0) {
|
|
61
|
+
[filename, exists] = next(i);
|
|
62
|
+
if (!exists) {
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const name = pathname ? Module.joinPath(pathname, filename) : filename;
|
|
67
|
+
if (firebase) {
|
|
68
|
+
exists = listFiles.includes(name);
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
[exists] = await bucketClient.file(name).exists();
|
|
72
|
+
}
|
|
73
|
+
} while (exists && ++i);
|
|
74
|
+
if (i > 0) {
|
|
75
|
+
this.formatMessage(64 /* LOG_TYPE.CLOUD */, service, ["File renamed" /* VAL_CLOUD.RENAME_FILE */, current], filename, { ...Cloud.LOG_CLOUD_WARN });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const Key = [filename];
|
|
79
|
+
const Body = [data.buffer];
|
|
80
|
+
const ContentType = [contentType];
|
|
81
|
+
const getURL = (value) => endpoint ? Module.joinPath(endpoint, value) : Module.joinPath("https://storage.googleapis.com" /* STRINGS.BASE_URL */, bucket, value);
|
|
82
|
+
const addLog = (err) => err instanceof Error && this.addLog(this.statusType.WARN, err.message, service + ': ' + bucket);
|
|
83
|
+
if (fileGroup) {
|
|
84
|
+
for (const [content, ext, localFile] of fileGroup) {
|
|
85
|
+
Key.push(ext === '.map' && localFile ? path.basename(localFile) : filename + ext);
|
|
86
|
+
Body.push(content);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
for (let i = 0; i < Key.length; ++i) {
|
|
90
|
+
const first = i === 0;
|
|
91
|
+
if (this.aborted) {
|
|
92
|
+
if (first) {
|
|
93
|
+
uploadResponse((0, types_1.createAbortError)());
|
|
94
|
+
}
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
if (firebase) {
|
|
98
|
+
const { ref, uploadBytes } = require('@firebase/storage');
|
|
99
|
+
if (!Buffer.isBuffer(Body[i])) {
|
|
100
|
+
try {
|
|
101
|
+
Body[i] = fs.readFileSync(Body[i]);
|
|
102
|
+
}
|
|
103
|
+
catch (err) {
|
|
104
|
+
if (first) {
|
|
105
|
+
uploadResponse(err);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
addLog(err);
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const params = { ...options };
|
|
113
|
+
if (first) {
|
|
114
|
+
params.contentType || (params.contentType = ContentType[i]);
|
|
115
|
+
if (metadata) {
|
|
116
|
+
params.customMetadata = metadata;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
params.contentType = ContentType[i];
|
|
121
|
+
}
|
|
122
|
+
const destination = pathname ? Module.joinPath(pathname, Key[i]) : Key[i];
|
|
123
|
+
uploadBytes(ref(bucketClient, destination), Body[i], params)
|
|
124
|
+
.then(() => {
|
|
125
|
+
const url = getURL(destination);
|
|
126
|
+
this.formatMessage(64 /* LOG_TYPE.CLOUD */, service, "Upload success" /* VAL_CLOUD.UPLOAD_FILE */, url, { ...Cloud.LOG_CLOUD_UPLOAD });
|
|
127
|
+
if (first) {
|
|
128
|
+
uploadResponse(null, url);
|
|
129
|
+
}
|
|
130
|
+
})
|
|
131
|
+
.catch(err => {
|
|
132
|
+
if (first) {
|
|
133
|
+
uploadResponse(err);
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
addLog(err);
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
let outputUri, tempDir;
|
|
142
|
+
try {
|
|
143
|
+
const output = Body[i];
|
|
144
|
+
if (Buffer.isBuffer(output) || path.basename(output) !== Key[i]) {
|
|
145
|
+
if (!(tempDir = this.getTempDir({ uuidDir: true }))) {
|
|
146
|
+
throw new Error("Unable to create temp directory" /* ERR_CLOUD.TEMP_DIR */);
|
|
147
|
+
}
|
|
148
|
+
outputUri = path.join(tempDir, Key[i]);
|
|
149
|
+
if (typeof output === 'string') {
|
|
150
|
+
fs.copyFileSync(output, outputUri);
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
fs.writeFileSync(outputUri, output);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
outputUri = output;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
catch (err) {
|
|
161
|
+
if (first) {
|
|
162
|
+
uploadResponse(err);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
addLog(err);
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
const params = { ...options };
|
|
169
|
+
const readable = publicRead || active && publicRead !== false && publicRead !== 0 && !acl;
|
|
170
|
+
let ACL, revoke, predefined;
|
|
171
|
+
if (first) {
|
|
172
|
+
params.contentType || (params.contentType = ContentType[i]);
|
|
173
|
+
if (readable) {
|
|
174
|
+
ACL = 'publicRead';
|
|
175
|
+
}
|
|
176
|
+
else {
|
|
177
|
+
predefined = true;
|
|
178
|
+
}
|
|
179
|
+
if (metadata) {
|
|
180
|
+
params.metadata = metadata;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
params.contentType = ContentType[i];
|
|
185
|
+
if (!params.predefinedAcl) {
|
|
186
|
+
if (readable) {
|
|
187
|
+
ACL = 'publicRead';
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
predefined = true;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (predefined) {
|
|
195
|
+
if (publicRead === 0) {
|
|
196
|
+
ACL = 'publicRead';
|
|
197
|
+
revoke = true;
|
|
198
|
+
}
|
|
199
|
+
if (acl && (!revoke || acl !== ACL)) {
|
|
200
|
+
params.predefinedAcl = acl;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
params.destination = pathname ? Module.joinPath(pathname, path.basename(outputUri)) : undefined;
|
|
204
|
+
bucketClient.upload(outputUri, params, (err, file) => {
|
|
205
|
+
if (file) {
|
|
206
|
+
const url = getURL(file.name);
|
|
207
|
+
this.formatMessage(64 /* LOG_TYPE.CLOUD */, service, "Upload success" /* VAL_CLOUD.UPLOAD_FILE */, url, { ...Cloud.LOG_CLOUD_UPLOAD });
|
|
208
|
+
if (first) {
|
|
209
|
+
uploadResponse(null, url);
|
|
210
|
+
}
|
|
211
|
+
if (ACL) {
|
|
212
|
+
client_1.setPredefinedAcl.call(this, file.acl, ACL, file.bucket, file.name, revoke || file.metadata, true);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
else if (first) {
|
|
216
|
+
uploadResponse(err);
|
|
217
|
+
}
|
|
218
|
+
else {
|
|
219
|
+
addLog(err);
|
|
220
|
+
}
|
|
221
|
+
if (tempDir) {
|
|
222
|
+
queueMicrotask(() => Module.removeDir(tempDir));
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
module.exports = upload;
|