Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
fix(file-bucket): keep version deletions retryable
  • Loading branch information
ikenyal committed Nov 2, 2026
commit 46fdd5acf869b0f48da0bf22909f39132f2b010c
2 changes: 2 additions & 0 deletions .changeset/file-bucket-current-version-deletion.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@
---

Fix local FileBucket version deletion so removing the newest stored data version updates the current body and metadata from the next stored data version, or removes the current copies when none remain. Active delete-marker flags and older-version deletion behavior are preserved. Document that historical delete markers discarded by a subsequent upload are not reconstructed, so deletion across re-uploads still differs from S3.

Ignore nested-key directories when reading version history. Retain the target version body until current-copy reconciliation and version-sidecar removal succeed, allowing filesystem failures to be retried with the same version ID.
2 changes: 2 additions & 0 deletions packages/bb-file-bucket/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,12 +128,14 @@ Creates a single S3 bucket (plus a dedicated log bucket when `accessLogging` is
- Object keys are validated identically on the mock and the AWS runtime via the shared, filesystem-independent `assertValidKey` (`validation.ts`), called from every key-accepting method on both layers. It rejects (`ValidationFailed`) an empty/non-string key, a leading slash, an empty path segment (interior `a//b` or trailing `a/`, which the mock's `path.join` would otherwise collapse while S3 keeps literal), ASCII control characters, and a `..`/`.` path segment. The mock additionally applies a filesystem realpath/symlink containment guard (`assertContainedPath`) as local-only defense. `deleteBatch` validates every key up front on both layers, so a mixed valid/invalid batch deletes nothing.
- Basic versioning: each `put` writes to `versions/{key}/v{n}` and removes any active `__deleted__` sentinel; delete without `versionId` places that sentinel, `listVersions` reads stored data versions, and `restoreVersion` copies an old version via `put`. Historical delete markers are not retained.
- Deleting the newest stored data version updates the current `content/` and `meta/` copies from the next stored data version, including its original modification time, without creating a new version or removing an active delete-marker flag. Deleting the last stored data version removes the current copies. Deleting older or unknown versions leaves the current copies unchanged. The synchronous version reader is shared with `listVersions()`, so selection follows the same newest-first ordering and deletion does not yield between reading and reconciling the version history. This reconciles current copies with the data versions the mock retains; it does not reconstruct discarded delete-marker history.
- The shared version reader considers only regular files, excluding directories that belong to nested object keys. Current-copy updates or removal complete before the target version is unlinked; missing copies and sidecars are tolerated, but other filesystem errors propagate so callers can retry the same deletion. The version body is removed last, after its metadata sidecar.

### Mock vs AWS Behavior Differences

| Behavior Difference | Impact | Mitigation |
|------------|--------|------------|
| Historical delete markers are not retained | The mock has one `__deleted__` flag, removed by the next `put()`, rather than delete markers ordered among data versions. For `put(old)` → `delete()` → `put(replacement)` → permanent deletion of the replacement version, the mock exposes `old`, includes the key in `scan()`, and marks the older data version current in `listVersions()`. S3 instead makes the earlier delete marker current, so a read without a version ID treats the key as deleted. | Do not use the local mock to assert S3 deletion-history behavior across re-uploads; exercise that case in a sandbox. Correct historical promotion needs a model that retains ordered delete markers and defines compatibility with existing local data. Current-copy reconciliation alone does not address it. |
| Non-atomic version deletion | Current body, metadata, and version history are separate filesystem writes. An I/O failure or process interruption can leave partially updated current copies until deletion is retried; this is not an atomic S3 operation or a rollback guarantee. | The target version body remains until current-copy reconciliation and version-sidecar removal succeed. After resolving the I/O error, retry deletion with the same version ID to finish reconciliation. |
| No lifecycle rules | Objects never expire or transition locally | No mitigation — lifecycle rules are a background S3 process |
| No CORS enforcement | Browser requests succeed regardless of origin locally; a missing `corsRules` only fails after deploy | CORS is enforced by the browser + S3, not the mock. The README's "Browser Uploads and Downloads (CORS)" section documents that `corsRules` is required for deployed browser access |
| No storage classes | Transition rules have no effect locally | No mitigation — storage classes are a cost optimization |
Expand Down
100 changes: 98 additions & 2 deletions packages/bb-file-bucket/src/current-version-deletion.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@

import { test, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert/strict';
import { existsSync, readFileSync, rmSync, statSync, utimesSync } from 'node:fs';
import { existsSync, mkdirSync, readFileSync, rmSync, statSync, utimesSync } from 'node:fs';
import { join } from 'node:path';
import { Scope } from '@aws-blocks/core';
import { FileBucket } from './index.mock.js';
import { contentPath, metaPath, deleteMarkerPath, versionContentPath } from './paths.js';
import { contentPath, metaPath, deleteMarkerPath, versionContentPath, versionMetaPath } from './paths.js';

const scope = new Scope('version-delete');
const bucketId = 'files';
Expand Down Expand Up @@ -159,3 +159,99 @@ test('non-versioned deletion still removes the object', async () => {
assert.equal(await bucket.get(key), null);
assert.deepEqual(await scanFiles(bucket), []);
});

test('version history ignores directories belonging to nested keys', async () => {
const bucket = new FileBucket(scope, bucketId);
await bucket.put('docs/readme.txt', 'nested');
await bucket.put('docs/v999', 'numeric-looking key');
assert.deepEqual(await bucket.listVersions('docs'), []);
assert.equal((await bucket.listVersions('docs/readme.txt')).length, 1);
assert.equal((await bucket.listVersions('docs/v999')).length, 1);
});

test('deleting a directory-shaped version ID leaves nested keys untouched', async () => {
const bucket = new FileBucket(scope, bucketId);
for (const child of ['readme.txt', 'v999']) {
await bucket.put(`docs/${child}`, 'nested');
await bucket.delete('docs', { versionId: child });
assert.equal((await bucket.get(`docs/${child}`))?.body.toString(), 'nested');
assert.equal((await bucket.listVersions(`docs/${child}`)).length, 1);
}
});

for (const [name, pathFor] of [['body', contentPath], ['metadata', metaPath]] as const) {
test(`failed promotion ${name} write preserves version history for a retry`, async () => {
const bucket = new FileBucket(scope, bucketId);
const [latest, previous] = await putVersions(bucket);
const obstruction = pathFor(dataDir, key);
rmSync(obstruction);
mkdirSync(obstruction);

await assert.rejects(bucket.delete(key, { versionId: latest.versionId }));
assert.equal(existsSync(versionContentPath(dataDir, key, latest.versionId)), true);
assert.equal(existsSync(versionMetaPath(dataDir, key, latest.versionId)), true);
assert.deepEqual((await bucket.listVersions(key)).map(version => version.versionId), [
latest.versionId, previous.versionId,
]);

rmSync(obstruction, { recursive: true });
const reopened = new FileBucket(scope, bucketId);
await reopened.delete(key, { versionId: latest.versionId });
const file = await reopened.get(key);
assert.equal(file?.body.toString(), 'old');
assert.equal(file?.contentType, 'text/plain');
assert.deepEqual(file?.metadata, { revision: 'old' });
assert.equal(JSON.parse(readFileSync(metaPath(dataDir, key), 'utf8')).cacheControl, 'max-age=60');
assert.equal(await reopened.get(key, { versionId: latest.versionId }), null);
assert.equal((await reopened.listVersions(key))[0].versionId, previous.versionId);
});

test(`failed last-version ${name} cleanup preserves the version for a retry`, async () => {
const bucket = new FileBucket(scope, bucketId);
await bucket.put(key, 'only');
const [latest] = await bucket.listVersions(key);
const obstruction = pathFor(dataDir, key);
rmSync(obstruction);
mkdirSync(obstruction);

await assert.rejects(bucket.delete(key, { versionId: latest.versionId }));
assert.equal(existsSync(versionContentPath(dataDir, key, latest.versionId)), true);
assert.equal(existsSync(versionMetaPath(dataDir, key, latest.versionId)), true);
rmSync(obstruction, { recursive: true });

await bucket.delete(key, { versionId: latest.versionId });
assert.equal(await bucket.get(key), null);
assert.deepEqual(await bucket.listVersions(key), []);
assert.deepEqual(await scanFiles(bucket), []);
assert.equal(existsSync(contentPath(dataDir, key)), false);
assert.equal(existsSync(metaPath(dataDir, key)), false);
});
}

test('failed version metadata cleanup preserves its body for a retry', async () => {
const bucket = new FileBucket(scope, bucketId);
const [latest, previous] = await putVersions(bucket);
const obstruction = versionMetaPath(dataDir, key, latest.versionId);
rmSync(obstruction);
mkdirSync(obstruction);

await assert.rejects(bucket.delete(key, { versionId: latest.versionId }));
assert.equal(existsSync(versionContentPath(dataDir, key, latest.versionId)), true);
rmSync(obstruction, { recursive: true });
await bucket.delete(key, { versionId: latest.versionId });
assert.equal((await bucket.get(key))?.body.toString(), 'old');
assert.equal((await bucket.get(key))?.contentType, 'text/plain');
assert.equal((await bucket.listVersions(key))[0].versionId, previous.versionId);
});

test('deleting the last version tolerates missing current copies and version metadata', async () => {
const bucket = new FileBucket(scope, bucketId);
await bucket.put(key, 'only');
const [latest] = await bucket.listVersions(key);
for (const file of [contentPath(dataDir, key), metaPath(dataDir, key), versionMetaPath(dataDir, key, latest.versionId)]) {
rmSync(file);
}
await bucket.delete(key, { versionId: latest.versionId });
assert.equal(await bucket.get(key), null);
assert.deepEqual(await bucket.listVersions(key), []);
});
46 changes: 25 additions & 21 deletions packages/bb-file-bucket/src/index.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import { getMockDataDir, assertNotMockInDeployedEnv } from '@aws-blocks/core/bb-utils';
import type { ScopeParent } from '@aws-blocks/core';
import {
existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, readdirSync, statSync, copyFileSync, utimesSync,
existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, readdirSync, statSync, copyFileSync, utimesSync, rmSync,
} from 'node:fs';
import { dirname, join, relative } from 'node:path';
import { assertContainedPath } from './mock-utils.js';
Expand Down Expand Up @@ -207,6 +207,8 @@
* On non-versioned buckets, permanently removes the file.
* On versioned buckets without `versionId`, places a delete marker (file appears deleted
* but previous versions are preserved). With `versionId`, permanently removes that version.
* Deleting the newest stored data version promotes the next stored data version, if any,
* without creating a new version. An active local delete marker continues to hide the key.
*
* No-op if the file does not exist (matches S3 behavior).
*
Expand All @@ -224,26 +226,26 @@
if (this.versioned && versionId) {
const versions = this.readVersions(path);
if (!versions.some(version => version.versionId === versionId)) return;
unlinkSync(versionContentPath(this.dataDir, path, versionId));
try { unlinkSync(versionMetaPath(this.dataDir, path, versionId)); } catch {}
if (versions[0].versionId !== versionId) return;

// The current copy is also read by scan() and the dev file-server.
// Promote the next version without put(), which would create a new version
// and remove any existing delete marker.
const next = versions[1];
if (next) {
const filePath = contentPath(this.dataDir, path);
const source = versionContentPath(this.dataDir, path, next.versionId);
const stat = statSync(source);
mkdirSync(dirname(filePath), { recursive: true });
copyFileSync(source, filePath);
utimesSync(filePath, stat.atime, stat.mtime);
this.writeMeta(path, this.readVersionMeta(path, next.versionId));
} else {
try { unlinkSync(contentPath(this.dataDir, path)); } catch {}
try { unlinkSync(metaPath(this.dataDir, path)); } catch {}
if (versions[0].versionId === versionId) {
// The current copy is also read by scan() and the dev file-server.
// Promote without put(), which would create a version and clear the marker.
// Keep the target version until reconciliation succeeds so failures are retryable.
const next = versions[1];
if (next) {
const filePath = contentPath(this.dataDir, path);
const source = versionContentPath(this.dataDir, path, next.versionId);
const stat = statSync(source);
mkdirSync(dirname(filePath), { recursive: true });
copyFileSync(source, filePath);
utimesSync(filePath, stat.atime, stat.mtime);
this.writeMeta(path, this.readVersionMeta(path, next.versionId));
} else {
rmSync(contentPath(this.dataDir, path), { force: true });
rmSync(metaPath(this.dataDir, path), { force: true });
}
}
rmSync(versionMetaPath(this.dataDir, path, versionId), { force: true });
unlinkSync(versionContentPath(this.dataDir, path, versionId));
return;
}
if (this.versioned) {
Expand Down Expand Up @@ -514,7 +516,9 @@
private readVersions(path: string): FileVersionInfo[] {
const versionsDir = versionsDirFor(this.dataDir, path);
if (!existsSync(versionsDir)) return [];
const entries = readdirSync(versionsDir).filter(isVersionEntry);
const entries = readdirSync(versionsDir, { withFileTypes: true })
.filter(entry => entry.isFile() && isVersionEntry(entry.name))
.map(entry => entry.name);
if (entries.length === 0) return [];

const hasDeleteMarker = existsSync(deleteMarkerPath(this.dataDir, path));
Expand Down Expand Up @@ -595,7 +599,7 @@
const existing = readdirSync(dir)
.filter(f => f.startsWith('v') && !f.includes('.'))
.map(f => parseInt(f.slice(1), 10))
.filter(n => !isNaN(n));

Check warning on line 602 in packages/bb-file-bucket/src/index.mock.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/suspicious/noGlobalIsNan

isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.
return `v${(existing.length > 0 ? Math.max(...existing) : 0) + 1}`;
}
}
17 changes: 17 additions & 0 deletions test-apps/comprehensive/test/file-bucket.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,23 @@ export function fileBucketTests(getApi: () => typeof apiType) {
// ── Versioned FileBucket ──────────────────────────────────────────────

describe('Versioned', () => {
test('deleting a version of a prefix key does not delete nested objects', async () => {
const api = getApi();
const prefix = `v/prefix-delete-${crypto.randomUUID()}`;
const children = ['readme.txt', 'v999'];
try {
for (const child of children) {
await api.vFilePut(`${prefix}/${child}`, 'nested');
await api.vFileDelete(prefix, child);
assert.strictEqual((await api.vFileGet(`${prefix}/${child}`))?.body, 'nested');
assert.strictEqual((await api.vFileListVersions(`${prefix}/${child}`)).length, 1);
}
assert.deepStrictEqual(await api.vFileListVersions(prefix), []);
} finally {
for (const child of children) await api.vFilePurge(`${prefix}/${child}`);
}
});

test('deleting the current version promotes the previous version through the API', async () => {
const api = getApi();
const path = `v/delete-current-${crypto.randomUUID()}.txt`;
Expand Down
Loading