Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use remove() for rmdir() #1014

Merged
merged 2 commits into from
Oct 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 56 additions & 52 deletions packages/helix-shared-storage/src/storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -400,42 +400,74 @@ class Bucket {
* Remove object(s)
*
* @param {string|string[]} path source key(s)
* @param {string} [sourceInfo] informational message of the source
* @param {boolean} [stopOnError]
* @returns result obtained from S3
*/
async remove(path) {
async remove(path, sourceInfo = '', stopOnError = false) {
const { log, bucket } = this;

if (Array.isArray(path)) {
const input = {
Bucket: this.bucket,
Delete: {
Objects: path.map((p) => ({ Key: sanitizeKey(p) })),
},
// slice into chunks of MAX_DELETE_OBJECTS at most
const chunks = Array.from({
length: Math.ceil(path.length / MAX_DELETE_OBJECTS),
}, (v, i) => path.slice(i * MAX_DELETE_OBJECTS, i * MAX_DELETE_OBJECTS + MAX_DELETE_OBJECTS));

let oks = 0;
let errors = 0;
const result = {
Deleted: [],
Errors: [],
};
// delete on s3 and r2 (mirror) in parallel
try {
const result = await this.sendToS3andR2(DeleteObjectsCommand, input);
this.log.info(`${result.Deleted.length} objects deleted from bucket ${input.Bucket}.`);
return result;
} catch (e) {
const msg = `removing ${input.Delete.length} objects from bucket ${input.Bucket} failed: ${e.message}`;
this.log.error(msg);
const e2 = new Error(msg);
e2.status = e.$metadata.httpStatusCode;
throw e2;
}
await processQueue(chunks, async (chunk) => {
log.debug(`deleting ${chunk.length} from ${bucket}`);
const input = {
Bucket: bucket,
Delete: {
Objects: chunk.map((p) => ({ Key: sanitizeKey(p) })),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

when passing through rmdir to remove, the paths are already sanitized, but eventually removing a leading / is probably not that expensive

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes. I thought so, too.

},
};

try {
// delete on s3 and r2 (mirror) in parallel
const res = await this.sendToS3andR2(DeleteObjectsCommand, input);
if (res.Deleted) {
result.Deleted.push(...res.Deleted);
oks += res.Deleted.length;
}
if (res.Errors) {
result.Errors.push(...res.Errors);
errors += res.Errors.length;
}
} catch (e) {
// at least 1 cmd failed
log.warn(`error while deleting ${chunk.length} from ${bucket}/${sourceInfo}: ${e.message} (${e.$metadata.httpStatusCode})`);
errors += chunk.length;
if (stopOnError) {
const msg = `removing ${input.Delete.Objects.length} objects from bucket ${input.Bucket} failed: ${e.message}`;
this.log.error(msg);
const e2 = new Error(msg);
e2.status = e.$metadata.httpStatusCode;
throw e2;
}
}
}, 2);
log.info(`deleted ${oks} files (${errors} errors)`);
return result;
}

const input = {
Bucket: this.bucket,
Bucket: bucket,
Key: sanitizeKey(path),
};
// delete on s3 and r2 (mirror) in parallel
try {
const result = await this.sendToS3andR2(DeleteObjectCommand, input);
this.log.info(`object deleted: ${input.Bucket}/${input.Key}`);
log.info(`object deleted: ${bucket}/${input.Key}`);
return result;
} catch (e) {
const msg = `removing ${input.Bucket}/${input.Key} from storage failed: ${e.message}`;
this.log.error(msg);
const msg = `removing ${bucket}/${input.Key} from storage failed: ${e.message}`;
log.error(msg);
const e2 = new Error(msg);
e2.status = e.$metadata.httpStatusCode;
throw e2;
Expand Down Expand Up @@ -562,38 +594,10 @@ class Bucket {
}

async rmdir(src) {
const { bucket, log } = this;
src = sanitizeKey(src);
log.info(`fetching list of files to delete from ${bucket}/${src}`);
this.log.info(`fetching list of files to delete from ${this.bucket}/${src}`);
const items = await this.list(src);

// slice into chunks of MAX_DELETE_OBJECTS at most
const chunks = Array.from({
length: Math.ceil(items.length / MAX_DELETE_OBJECTS),
}, (v, i) => items.slice(i * MAX_DELETE_OBJECTS, i * MAX_DELETE_OBJECTS + MAX_DELETE_OBJECTS));

let oks = 0;
let errors = 0;
await processQueue(chunks, async (chunk) => {
log.debug(`deleting ${chunk.length} from ${bucket}`);
const input = {
Bucket: bucket,
Delete: {
Objects: chunk.map((item) => ({ Key: item.key })),
},
};

try {
// delete on s3 and r2 (mirror) in parallel
await this.sendToS3andR2(DeleteObjectsCommand, input);
oks += chunk.length;
} catch (e) {
// at least 1 cmd failed
log.warn(`error while deleting ${chunk.length} from ${bucket}/${src}: ${e.message} (${e.$metadata.httpStatusCode})`);
errors += chunk.length;
}
}, 2);
log.info(`deleted ${oks} files (${errors} errors)`);
return this.remove(items.map((item) => item.key), src);
}
}

Expand Down
11 changes: 8 additions & 3 deletions packages/helix-shared-storage/test/storage.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,7 @@ describe('Storage test', () => {
await assert.rejects(async () => bus.remove('/does-not-exist'));
});

it('remove objects can fail', async () => {
it('remove objects can report error', async () => {
nock('https://helix-code-bus.s3.fake.amazonaws.com')
.post('/?delete=')
.reply(404);
Expand All @@ -433,7 +433,7 @@ describe('Storage test', () => {
.reply(404);

const bus = storage.codeBus();
await assert.rejects(async () => bus.remove(['/foo', '/bar']));
await assert.rejects(async () => bus.remove(['/foo', '/bar'], '', true));
});

it('can remove objects', async () => {
Expand All @@ -446,7 +446,12 @@ describe('Storage test', () => {
headers: Object.fromEntries(Object.entries(this.req.headers)
.filter(([key]) => TEST_HEADERS.indexOf(key) >= 0)),
};
return [200, '<?xml version="1.0" encoding="UTF-8"?>\n<DeleteResult><Deleted><Key>/foo</Key></Deleted><Deleted><Key>/bar</Key></Deleted></DeleteResult>'];
return [200, '<?xml version="1.0" encoding="UTF-8"?>'
+ '<DeleteResult>'
+ '<Deleted><Key>/foo</Key></Deleted>'
+ '<Deleted><Key>/bar</Key></Deleted>'
+ '<Error><Code>kaputt</Code></Error>'
+ '</DeleteResult>'];
});
nock(`https://helix-code-bus.${CLOUDFLARE_ACCOUNT_ID}.r2.cloudflarestorage.com`)
.post('/?delete=')
Expand Down
Loading