-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathattachment-lifecycle.test.ts
More file actions
340 lines (281 loc) · 12.3 KB
/
Copy pathattachment-lifecycle.test.ts
File metadata and controls
340 lines (281 loc) · 12.3 KB
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
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { describe, it, expect, vi } from 'vitest';
import {
installAttachmentLifecycleHooks,
createSysFileReapGuard,
createUploadSessionReapGuard,
type AttachmentLifecycleEngine,
} from './attachment-lifecycle.js';
const silentLogger = () => ({ info: vi.fn(), warn: vi.fn(), debug: vi.fn() });
/**
* In-memory fake engine: a sys_attachment table + a sys_file table, plus a
* hook registry so tests can drive the engine seams the way the real engine
* does (same HookContext object across beforeDelete → afterDelete).
*/
function fakeEngine(seed: {
attachments?: Array<Record<string, unknown>>;
files?: Array<Record<string, unknown>>;
}) {
const tables: Record<string, Array<Record<string, unknown>>> = {
sys_attachment: [...(seed.attachments ?? [])],
sys_file: [...(seed.files ?? [])],
};
const hooks = new Map<string, Array<(ctx: any) => Promise<void> | void>>();
const updates: Array<{ object: string; data: any }> = [];
const matches = (row: Record<string, unknown>, where: Record<string, unknown>) =>
Object.entries(where).every(([k, v]) => row[k] === v);
const engine: AttachmentLifecycleEngine & {
tables: typeof tables;
updates: typeof updates;
trigger(event: string, ctx: any): Promise<void>;
deleteRows(where: Record<string, unknown>): void;
} = {
registerHook(event, handler, opts) {
expect(opts?.object).toBe('sys_attachment');
const list = hooks.get(event) ?? [];
list.push(handler);
hooks.set(event, list);
},
async find(object, options: any) {
const rows = tables[object].filter((r) => matches(r, options?.where ?? {}));
return typeof options?.limit === 'number' ? rows.slice(0, options.limit) : rows;
},
async findOne(object, options: any) {
return tables[object].find((r) => matches(r, options?.where ?? {})) ?? null;
},
async update(object, data: any, _options) {
updates.push({ object, data });
const row = tables[object].find((r) => r.id === data.id);
if (row) Object.assign(row, data);
return row;
},
tables,
updates,
async trigger(event, ctx) {
for (const h of hooks.get(event) ?? []) await h(ctx);
},
deleteRows(where) {
tables.sys_attachment = tables.sys_attachment.filter((r) => !matches(r, where));
},
};
return engine;
}
/** Drive a full engine-shaped delete: beforeDelete → row removal → afterDelete
* with ONE shared ctx object (mirrors engine.ts delete()). */
async function driveDelete(engine: ReturnType<typeof fakeEngine>, input: any, where: Record<string, unknown>) {
const ctx: any = { object: 'sys_attachment', event: 'beforeDelete', input };
await engine.trigger('beforeDelete', ctx);
engine.deleteRows(where);
ctx.event = 'afterDelete';
await engine.trigger('afterDelete', ctx);
}
const committedFile = (id: string, scope = 'attachments') => ({
id,
key: `attachments/${id}.bin`,
scope,
status: 'committed',
});
describe('installAttachmentLifecycleHooks — tombstoning', () => {
it('tombstones the file when the LAST join row is deleted (by id)', async () => {
const engine = fakeEngine({
attachments: [{ id: 'a1', file_id: 'f1' }],
files: [committedFile('f1')],
});
installAttachmentLifecycleHooks(engine, silentLogger());
await driveDelete(engine, { id: 'a1', options: {} }, { id: 'a1' });
expect(engine.updates).toHaveLength(1);
expect(engine.updates[0].data).toMatchObject({ id: 'f1', status: 'deleted' });
expect(typeof engine.updates[0].data.deleted_at).toBe('string');
});
it('does NOT tombstone while another join row still references the file', async () => {
const engine = fakeEngine({
attachments: [
{ id: 'a1', file_id: 'f1' },
{ id: 'a2', file_id: 'f1' }, // second parent, same file
],
files: [committedFile('f1')],
});
installAttachmentLifecycleHooks(engine, silentLogger());
await driveDelete(engine, { id: 'a1', options: {} }, { id: 'a1' });
expect(engine.updates).toHaveLength(0);
expect(engine.tables.sys_file[0].status).toBe('committed');
});
it('resolves every affected file on a multi-delete (options.where)', async () => {
const engine = fakeEngine({
attachments: [
{ id: 'a1', file_id: 'f1', parent_id: 'p1' },
{ id: 'a2', file_id: 'f2', parent_id: 'p1' },
{ id: 'a3', file_id: 'f2', parent_id: 'p2' }, // f2 keeps a ref
],
files: [committedFile('f1'), committedFile('f2')],
});
installAttachmentLifecycleHooks(engine, silentLogger());
await driveDelete(
engine,
{ id: undefined, options: { where: { parent_id: 'p1' }, multi: true } },
{ parent_id: 'p1' },
);
expect(engine.updates.map((u) => u.data.id)).toEqual(['f1']);
});
it('never tombstones non-attachments scopes (Field.file/avatar protection)', async () => {
const engine = fakeEngine({
attachments: [{ id: 'a1', file_id: 'f1' }],
files: [committedFile('f1', 'user')],
});
installAttachmentLifecycleHooks(engine, silentLogger());
await driveDelete(engine, { id: 'a1', options: {} }, { id: 'a1' });
expect(engine.updates).toHaveLength(0);
});
it('un-tombstones on re-attach (afterInsert)', async () => {
const engine = fakeEngine({
attachments: [],
files: [{ id: 'f1', key: 'attachments/f1.bin', scope: 'attachments', status: 'deleted', deleted_at: '2026-01-01T00:00:00Z' }],
});
installAttachmentLifecycleHooks(engine, silentLogger());
await engine.trigger('afterInsert', {
object: 'sys_attachment',
event: 'afterInsert',
input: { doc: { file_id: 'f1' } },
result: { id: 'a9', file_id: 'f1' },
});
expect(engine.updates).toHaveLength(1);
expect(engine.updates[0].data).toMatchObject({ id: 'f1', status: 'committed', deleted_at: null });
});
it('a failing lookup never blocks the delete (best-effort)', async () => {
const engine = fakeEngine({ attachments: [], files: [] });
engine.findOne = async () => {
throw new Error('driver exploded');
};
const logger = silentLogger();
installAttachmentLifecycleHooks(engine, logger);
await expect(driveDelete(engine, { id: 'a1', options: {} }, { id: 'a1' })).resolves.toBeUndefined();
expect(logger.warn).toHaveBeenCalled();
});
});
describe('createSysFileReapGuard', () => {
const storage = () => ({ delete: vi.fn(async () => {}) }) as any;
it('confirms zero-ref tombstones after deleting the bytes', async () => {
const engine = fakeEngine({ attachments: [], files: [] });
const s = storage();
const guard = createSysFileReapGuard(engine, () => s, silentLogger());
const confirmed = await guard('sys_file', [
{ id: 'f1', key: 'attachments/f1.bin', status: 'deleted' },
]);
expect(s.delete).toHaveBeenCalledWith('attachments/f1.bin');
expect(confirmed).toEqual(['f1']);
});
it('vetoes and un-tombstones a row that regained references (sweep-time re-verification)', async () => {
const engine = fakeEngine({
attachments: [{ id: 'a1', file_id: 'f1' }],
files: [{ id: 'f1', key: 'attachments/f1.bin', scope: 'attachments', status: 'deleted', deleted_at: '2026-01-01T00:00:00Z' }],
});
const s = storage();
const guard = createSysFileReapGuard(engine, () => s, silentLogger());
const confirmed = await guard('sys_file', [
{ id: 'f1', key: 'attachments/f1.bin', status: 'deleted' },
]);
expect(confirmed).toEqual([]);
expect(s.delete).not.toHaveBeenCalled();
expect(engine.updates[0].data).toMatchObject({ id: 'f1', status: 'committed', deleted_at: null });
});
it('a byte-delete failure vetoes the row (retried next sweep, bytes never leaked)', async () => {
const engine = fakeEngine({ attachments: [], files: [] });
const s = { delete: vi.fn(async () => { throw new Error('S3 down'); }) } as any;
const logger = silentLogger();
const guard = createSysFileReapGuard(engine, () => s, logger);
const confirmed = await guard('sys_file', [
{ id: 'f1', key: 'attachments/f1.bin', status: 'deleted' },
]);
expect(confirmed).toEqual([]);
expect(logger.warn).toHaveBeenCalled();
});
it('confirms abandoned pending uploads with best-effort byte cleanup', async () => {
const engine = fakeEngine({ attachments: [], files: [] });
const s = storage();
const guard = createSysFileReapGuard(engine, () => s, silentLogger());
const confirmed = await guard('sys_file', [
{ id: 'p1', key: 'user/p1.bin', status: 'pending' },
]);
expect(s.delete).toHaveBeenCalledWith('user/p1.bin');
expect(confirmed).toEqual(['p1']);
});
it('vetoes rows in any other state (fail toward retention)', async () => {
const engine = fakeEngine({ attachments: [], files: [] });
const guard = createSysFileReapGuard(engine, storage, silentLogger());
const confirmed = await guard('sys_file', [
{ id: 'c1', key: 'attachments/c1.bin', status: 'committed' },
]);
expect(confirmed).toEqual([]);
});
});
describe('createUploadSessionReapGuard', () => {
/** Swappable-style storage fake: `getInner()` exposes an S3-like inner with
* `setUploadKey`; `abortChunkedUpload` is forwarded. */
const s3Storage = (abortImpl?: () => Promise<void>) => {
const inner = {
setUploadKey: vi.fn((_id: string, _key: string) => {}),
};
return {
getInner: () => inner,
abortChunkedUpload: vi.fn(abortImpl ?? (async () => {})),
_inner: inner,
} as any;
};
it('aborts the backend multipart (re-seeding the key) then reaps an abandoned session', async () => {
const s = s3Storage();
const guard = createUploadSessionReapGuard(() => s, silentLogger());
const confirmed = await guard('sys_upload_session', [
{ id: 'u1', backend_upload_id: 'mp-1', key: 'attachments/u1.bin', status: 'in_progress' },
]);
expect(s._inner.setUploadKey).toHaveBeenCalledWith('mp-1', 'attachments/u1.bin');
expect(s.abortChunkedUpload).toHaveBeenCalledWith('mp-1');
expect(confirmed).toEqual(['u1']);
});
it('does NOT abort a completed session (its multipart is already an object) — just reaps the row', async () => {
const s = s3Storage();
const guard = createUploadSessionReapGuard(() => s, silentLogger());
const confirmed = await guard('sys_upload_session', [
{ id: 'u2', backend_upload_id: 'mp-2', key: 'attachments/u2.bin', status: 'completed' },
]);
expect(s.abortChunkedUpload).not.toHaveBeenCalled();
expect(confirmed).toEqual(['u2']);
});
it('reaps a session with no backend_upload_id without calling abort', async () => {
const s = s3Storage();
const guard = createUploadSessionReapGuard(() => s, silentLogger());
const confirmed = await guard('sys_upload_session', [
{ id: 'u3', key: 'attachments/u3.bin', status: 'expired' },
]);
expect(s.abortChunkedUpload).not.toHaveBeenCalled();
expect(confirmed).toEqual(['u3']);
});
it('VETOES on abort failure so backend_upload_id survives for the retry', async () => {
const s = s3Storage(async () => {
throw new Error('S3 abort transient failure');
});
const logger = silentLogger();
const guard = createUploadSessionReapGuard(() => s, logger);
const confirmed = await guard('sys_upload_session', [
{ id: 'u4', backend_upload_id: 'mp-4', key: 'attachments/u4.bin', status: 'failed' },
]);
expect(confirmed).toEqual([]); // kept
expect(logger.warn).toHaveBeenCalled();
});
it('works with a local-style adapter (no setUploadKey / getInner) — aborts by id', async () => {
const local = { abortChunkedUpload: vi.fn(async () => {}) } as any;
const guard = createUploadSessionReapGuard(() => local, silentLogger());
const confirmed = await guard('sys_upload_session', [
{ id: 'u5', backend_upload_id: 'local-5', key: 'attachments/u5.bin', status: 'expired' },
]);
expect(local.abortChunkedUpload).toHaveBeenCalledWith('local-5');
expect(confirmed).toEqual(['u5']);
});
it('reaps the row when the adapter cannot abort at all', async () => {
const noAbort = {} as any;
const guard = createUploadSessionReapGuard(() => noAbort, silentLogger());
const confirmed = await guard('sys_upload_session', [
{ id: 'u6', backend_upload_id: 'mp-6', key: 'k', status: 'in_progress' },
]);
expect(confirmed).toEqual(['u6']);
});
});