generated from hyper63/adapter-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
adapter.js
483 lines (454 loc) · 12.3 KB
/
adapter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
import { Buffer, crocks, HyperErr, join, R, readAll } from "./deps.js";
import * as lib from "./lib/s3.js";
import { checkName, handleHyperErr, isAwsTokenErr } from "./lib/utils.js";
const { Async } = crocks;
const {
assocPath,
assoc,
dissoc,
keys,
always,
filter,
compose,
pluck,
prop,
propEq,
map,
identity,
path,
has,
ifElse,
isNil,
complement,
defaultTo,
} = R;
const notHas = (prop) => complement(has(prop));
const createPrefix = (bucket, name) => join(bucket, name);
const asyncifyHandle = (fn) =>
Async.fromPromise(
(...args) =>
Promise.resolve(fn(...args))
.catch((err) => {
// Map token errs to a HyperErr
// TODO: emit 'unhealthy' when event listener api is finalized
if (isAwsTokenErr(err)) {
throw HyperErr({ status: 500, msg: "AWS credentials are invalid" });
}
throw err;
}),
);
export const HYPER_BUCKET_PREFIX = "hyper-storage-namespaced";
const [META, CREATED_AT, DELETED_AT, BUCKET_NOT_FOUND_CODE] = [
"meta.json",
"createdAt",
"deletedAt",
"Http404",
];
/**
* @typedef {Object} PutObjectArgs
* @property {string} bucket
* @property {string} object
* @property {any} stream
*
* @typedef {Object} ObjectArgs
* @property {string} bucket
* @property {string} object
*
* @typedef {Object} ListObjectsArgs
* @property {string} bucket
* @property {string} [prefix]
*
* @typedef {Object} Msg
* @property {string} [msg]
*
* @typedef {Object} Buckets
* @property {string[]} buckets
*
* @typedef {Object} Objects
* @property {string[]} objects
*
* @typedef {Object} ResponseOk
* @property {boolean} ok
*
* @typedef {Msg & ResponseOk} ResponseMsg
* @typedef {Buckets & ResponseOk} ResponseBuckets
* @typedef {Objects & ResponseOk} ResponseObjects
*/
/**
* @param {{ s3: any, factory: any, getSignedUrl: any, credentialProvider: any }} aws
* @returns
*/
export default function (bucketPrefix, aws) {
const { s3, getSignedUrl, credentialProvider } = aws;
const getCredentials = Async.fromPromise(credentialProvider.getCredentials);
const client = {
makeBucket: asyncifyHandle(lib.makeBucket(s3)),
headBucket: asyncifyHandle(lib.headBucket(s3)),
listBuckets: asyncifyHandle(lib.listBuckets(s3)),
putObject: asyncifyHandle(lib.putObject(s3)),
removeObject: asyncifyHandle(lib.removeObject(s3)),
removeObjects: asyncifyHandle(lib.removeObjects(s3)),
getObject: asyncifyHandle(lib.getObject(s3)),
getSignedUrl: asyncifyHandle(lib.getSignedUrl({ getSignedUrl })),
listObjects: asyncifyHandle(lib.listObjects(s3)),
};
// The single bucket used for all objects
const namespacedBucket = `${HYPER_BUCKET_PREFIX}-${bucketPrefix}`;
/**
* Check if the bucket exists, and create if not
*/
function findOrCreateBucket() {
return client.headBucket(namespacedBucket)
.bichain(
ifElse(
propEq("code", BUCKET_NOT_FOUND_CODE),
always(Async.Resolved(false)), // bucket does not exist
Async.Rejected, // some unknown err, so bubble
),
always(Async.Resolved(true)),
)
.chain((exists) =>
exists ? Async.Resolved() : client.makeBucket(namespacedBucket)
);
}
/**
* Get the meta.json for the namespaced s3 bucket
* which holds information like namespace names and when they were created
*
* If meta object does not exist, it will be created.
* Otherwise, will reject if an unhandled error is received.
*
* @returns {object}
*/
function getMeta() {
return findOrCreateBucket()
.chain(() =>
client.getObject({ bucket: namespacedBucket, key: META })
/**
* Find or create the meta.json object
*/
.bichain(
(err) => {
return err.message.includes("NoSuchKey")
// Create
? Async.of({ [CREATED_AT]: new Date().toISOString() })
.chain((meta) => saveMeta(meta).map(() => meta))
: Async.Rejected(err); // Some other error
},
// Found
(r) =>
Async.of(r)
.map((r) => JSON.parse(new TextDecoder().decode(r.Body))),
)
);
}
/**
* Save the meta object in the namespaced bucket
* as meta.json
*/
function saveMeta(meta) {
return client.putObject({
bucket: namespacedBucket,
key: META,
body: JSON.stringify(meta),
});
}
/**
* grab a list of objects at the prefix
* remove them
* check if list was truncated, and recurse if so
* when recursing is done, all object under prefix have been removed
*/
function removeObjects(prefix) {
return client.listObjects({
bucket: namespacedBucket,
prefix,
})
.chain(
(data) =>
Async.of(data)
// gather the keys
.map(
compose(
pluck("Key"),
prop("Contents"),
),
)
.chain((keys) =>
keys.length
? client.removeObjects({ bucket: namespacedBucket, keys })
: Async.Resolved()
)
.chain(() =>
// https://doc.deno.land/https://aws-api.deno.dev/v0.3/services/s3.ts?docs=full/~/ListObjectsOutput#IsTruncated
data.isTruncated
? removeObjects(prefix) // recurse to delete more objects
: Async.Resolved()
),
);
}
/**
* check the provided meta object for the existence
* of the provided namespace
*
* the namespace may have been deleted, so we check for if the key exists
* and if so, if the deletedAt key is set
*/
function checkNamespaceExists(meta, name) {
return Async.of(meta)
.map(
compose(
ifElse(
isNil,
always(false), // no namespace key
notHas(DELETED_AT), // set deletedAt means namespace was deleted, so does not exist
),
prop(name),
defaultTo({}),
),
)
.chain(ifElse(
identity,
Async.Resolved,
() =>
Async.Rejected(
HyperErr({ status: 404, msg: "bucket does not exist" }),
),
));
}
function putObjectOrSignedUrl({ bucket, object, stream, useSignedUrl }) {
const key = createPrefix(bucket, object);
if (!useSignedUrl) {
return Async.of(stream)
.chain(Async.fromPromise(readAll))
.chain((arrBuffer) =>
client.putObject({
bucket: namespacedBucket,
key,
body: arrBuffer,
})
)
.map(always({ ok: true }));
}
return Async.of()
.chain(getCredentials)
.chain((credentials) =>
client.getSignedUrl({
bucket: namespacedBucket,
key,
method: "PUT",
credentials,
})
)
.map((url) => ({ ok: true, url }));
}
function getObjectOrSignedUrl({ bucket, object, useSignedUrl }) {
const key = createPrefix(bucket, object);
if (!useSignedUrl) {
return client.getObject({
bucket: namespacedBucket,
key,
})
.map(
path(["Body", "buffer"]),
).map(
(arrayBuffer) => new Buffer(arrayBuffer),
);
}
return Async.of()
.chain(getCredentials)
.chain((credentials) =>
client.getSignedUrl({
bucket: namespacedBucket,
key,
method: "GET",
expires: 10000, // expiration is 1 hour
credentials,
})
)
.map((url) => ({ ok: true, url }));
}
/**
* Create a namespace (prefix/folder) within the s3 bucket
* recording it's existence in the meta file
*
* @param {string} name
* @returns {Promise<ResponseMsg>}
*/
function makeNamespace(name) {
return checkName(name)
.chain(getMeta)
.chain((meta) =>
checkNamespaceExists(meta, name)
.bichain(
/**
* Set a key for the new namespace
* NOTE: this also removes any deletedAt for the namespace
*/
() =>
Async.Resolved(
assoc(name, { [CREATED_AT]: new Date().toISOString() }, meta),
),
// The namespace already exists
() =>
Async.Rejected(
HyperErr({ status: 409, msg: "bucket already exists" }),
),
)
)
.chain(saveMeta)
.bichain(
handleHyperErr,
always(Async.Resolved({ ok: true })),
).toPromise();
}
/**
* Remove a namespace aka. folder/prefix in the bucket
* This is done by simply querying for all of the objects with
* the prefix and deleting them.
*
* If the result isTruncated, then we recurse, until all objects with
* the prefix are deleted, effectively deleting the namespace.
*
* Finally, we remove the bucket from the meta file
*
* @param {string} name
* @returns {Promise<ResponseMsg>}
*/
function removeNamespace(name) {
return Async.of(name)
.chain(checkName)
.chain(getMeta)
.chain((meta) =>
checkNamespaceExists(meta, name)
.bichain(
() =>
Async.Rejected(
HyperErr({ status: 404, msg: "bucket does not exist" }),
),
() => removeObjects(name),
)
.chain(
() =>
Async.of(
assocPath([name, DELETED_AT], new Date().toISOString(), meta),
)
.chain(saveMeta),
)
)
.bichain(
handleHyperErr,
always(Async.Resolved({ ok: true })),
).toPromise();
}
/**
* @returns {Promise<ResponseBuckets>}
*/
function listNamespaces() {
return getMeta()
.map(dissoc(CREATED_AT))
.map(filter(notHas(DELETED_AT)))
.map(keys)
.bichain(
handleHyperErr,
(bucketNamesArr) =>
Async.Resolved({ ok: true, buckets: bucketNamesArr }),
).toPromise();
}
/**
* @param {PutObjectArgs}
* @returns {Promise<ResponseOk>}
*/
function putObject({ bucket, object, stream, useSignedUrl }) {
return checkName(bucket)
.chain(() => checkName(object))
.chain(getMeta)
.chain(
(meta) => checkNamespaceExists(meta, bucket),
)
.chain(() =>
putObjectOrSignedUrl({ bucket, object, stream, useSignedUrl })
)
.bichain(
handleHyperErr,
Async.Resolved,
).toPromise();
}
/**
* @param {ObjectArgs}
* @returns {Promise<ResponseOk>}
*/
function removeObject({ bucket, object }) {
return checkName(bucket)
.chain(() => checkName(object))
.chain(getMeta)
.chain(
(meta) => checkNamespaceExists(meta, bucket),
)
.chain(() =>
client.removeObject({
bucket: namespacedBucket,
key: createPrefix(bucket, object),
})
)
.bichain(
handleHyperErr,
always(Async.Resolved({ ok: true })),
).toPromise();
}
/**
* @param {ObjectArgs}
* @returns {Promise<Buffer>}
*/
function getObject({ bucket, object, useSignedUrl }) {
return checkName(bucket)
.chain(() => checkName(object))
.chain(getMeta)
.chain(
(meta) => checkNamespaceExists(meta, bucket),
)
.chain(() => getObjectOrSignedUrl({ bucket, object, useSignedUrl }))
.bichain(
handleHyperErr,
Async.Resolved,
).toPromise();
}
/**
* @param {ListObjectsArgs}
* @returns {Promise<ResponseObjects>}
*/
function listObjects({ bucket, prefix }) {
return checkName(bucket)
.chain(() => checkName(prefix))
.chain(getMeta)
.chain(
(meta) => checkNamespaceExists(meta, bucket),
)
.chain(() =>
client.listObjects({
bucket: namespacedBucket,
prefix: createPrefix(bucket, prefix),
})
)
.bimap(
identity,
compose(
map(prop("Key")),
prop("Contents"),
),
).bichain(
handleHyperErr,
(objectNamesArr) =>
Async.Resolved({ ok: true, objects: objectNamesArr }),
).toPromise();
}
return Object.freeze({
makeBucket: makeNamespace,
removeBucket: removeNamespace,
listBuckets: listNamespaces,
putObject,
removeObject,
getObject,
listObjects,
});
}