@byline/storage-local 6.11.0 → 6.12.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.
@@ -9,6 +9,7 @@ import { randomBytes } from 'node:crypto';
9
9
  import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
  import { pipeline } from 'node:stream/promises';
12
+ import { ERR_STORAGE, ERR_STORAGE_PRECONDITION, isSameStorageValidator } from '@byline/core';
12
13
  import { v4 as uuidv4 } from 'uuid';
13
14
  // ---------------------------------------------------------------------------
14
15
  // Helpers
@@ -54,6 +55,32 @@ function randomSuffix(length = 6) {
54
55
  * safety net for direct callers) and the entropy rides as a short suffix
55
56
  * before the extension — friendly to download as, browse, and log.
56
57
  */
58
+ /** Validator kind issued by this provider. */
59
+ const LOCAL_VALIDATOR_KIND = 'local-stat';
60
+ /**
61
+ * `local-stat` validator: device, inode, nanosecond modification time and
62
+ * size. Every Byline write creates a new file and renames it into place, so a
63
+ * replacement always yields a new inode and therefore a new validator.
64
+ */
65
+ function statValidator(stats) {
66
+ return {
67
+ kind: LOCAL_VALIDATOR_KIND,
68
+ value: `${stats.dev}:${stats.ino}:${stats.mtimeNs}:${stats.size}`,
69
+ };
70
+ }
71
+ /** Sibling temporary path in the destination directory (same filesystem, so rename is atomic). */
72
+ function temporarySibling(absolutePath) {
73
+ return `${absolutePath}.${randomSuffix(10)}.tmp`;
74
+ }
75
+ function isNotFound(err) {
76
+ return err.code === 'ENOENT';
77
+ }
78
+ function preconditionFailed(reason, storagePath, expect, actual) {
79
+ return ERR_STORAGE_PRECONDITION({
80
+ message: `Storage precondition failed for '${storagePath}' (${reason}).`,
81
+ details: { reason, storagePath, expect, ...(actual && { actual }) },
82
+ });
83
+ }
57
84
  function buildStoragePath(scope, filename, suffix) {
58
85
  const safe = sanitiseFilename(filename);
59
86
  const ext = path.extname(safe);
@@ -77,18 +104,33 @@ class LocalStorageProvider {
77
104
  const absolutePath = path.join(this.uploadDir, storagePath);
78
105
  // Ensure the target directory exists.
79
106
  fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
80
- if (Buffer.isBuffer(stream)) {
81
- await fs.promises.writeFile(absolutePath, stream);
107
+ // Write a new file beside the destination and rename it into place. A
108
+ // reader never sees a partial file, and a reader that already has the old
109
+ // file open keeps reading the old inode.
110
+ const temporaryPath = temporarySibling(absolutePath);
111
+ try {
112
+ if (Buffer.isBuffer(stream)) {
113
+ await fs.promises.writeFile(temporaryPath, stream, { flag: 'wx' });
114
+ }
115
+ else {
116
+ const writeStream = fs.createWriteStream(temporaryPath, { flags: 'wx' });
117
+ await pipeline(stream, writeStream);
118
+ }
119
+ // The temporary name is private to this call, so a path stat cannot
120
+ // observe another writer. Rename preserves the inode and timestamps.
121
+ const stats = await fs.promises.stat(temporaryPath, { bigint: true });
122
+ await fs.promises.rename(temporaryPath, absolutePath);
123
+ return {
124
+ storageProvider: this.providerName,
125
+ storagePath: storagePath,
126
+ storageUrl: this.getUrl(storagePath),
127
+ storageValidator: statValidator(stats),
128
+ };
82
129
  }
83
- else {
84
- const writeStream = fs.createWriteStream(absolutePath);
85
- await pipeline(stream, writeStream);
130
+ catch (err) {
131
+ await fs.promises.rm(temporaryPath, { force: true });
132
+ throw err;
86
133
  }
87
- return {
88
- storageProvider: this.providerName,
89
- storagePath: storagePath,
90
- storageUrl: this.getUrl(storagePath),
91
- };
92
134
  }
93
135
  /**
94
136
  * Pick an unclaimed storage path: compose the friendly key, verify it is
@@ -122,25 +164,187 @@ class LocalStorageProvider {
122
164
  const toAbsolute = path.join(this.uploadDir, toPath);
123
165
  // Ensure the target directory exists.
124
166
  fs.mkdirSync(path.dirname(toAbsolute), { recursive: true });
167
+ const location = (validator) => ({
168
+ storageProvider: this.providerName,
169
+ storagePath: toPath,
170
+ storageUrl: this.getUrl(toPath),
171
+ storageValidator: validator,
172
+ });
173
+ // Claim the source first: an atomic rename to a private name in the
174
+ // source directory takes exactly the file at `fromPath` now, even if a
175
+ // Byline upload replaces `fromPath` a moment later. Everything after this
176
+ // works on the private name, so the validator always describes the file
177
+ // that reaches the destination, and a later source never gets removed.
178
+ const claimedPath = temporarySibling(fromAbsolute);
179
+ await fs.promises.rename(fromAbsolute, claimedPath);
180
+ // From here until the destination is committed, every failure goes
181
+ // through `restoreClaimedSource`, so the source is put back or the error
182
+ // names where the content is.
183
+ let claimedValidator;
125
184
  try {
126
- await fs.promises.rename(fromAbsolute, toAbsolute);
185
+ // The claimed name is private, so a path stat cannot observe another writer.
186
+ claimedValidator = statValidator(await fs.promises.stat(claimedPath, { bigint: true }));
127
187
  }
128
188
  catch (err) {
129
- // `rename` fails with EXDEV when uploadDir spans filesystems (e.g. a
130
- // mounted volume boundary). Fall back to copy + unlink.
131
- if (err.code === 'EXDEV') {
132
- await fs.promises.copyFile(fromAbsolute, toAbsolute);
133
- await fs.promises.unlink(fromAbsolute);
189
+ throw await this.restoreClaimedSource(claimedPath, fromAbsolute, fromPath, err);
190
+ }
191
+ // Same filesystem: a rename moves the inode, so the validator is preserved.
192
+ try {
193
+ await fs.promises.rename(claimedPath, toAbsolute);
194
+ return location(claimedValidator);
195
+ }
196
+ catch (err) {
197
+ if (err.code !== 'EXDEV') {
198
+ throw await this.restoreClaimedSource(claimedPath, fromAbsolute, fromPath, err);
134
199
  }
135
- else {
200
+ }
201
+ // Across filesystems (`EXDEV`, e.g. a mounted volume boundary): never copy
202
+ // onto the destination in place, which would change an inode a reader may
203
+ // have open. Copy to a temporary sibling, rename it into place, then
204
+ // remove the claimed source. The destination gets a new inode and validator.
205
+ const temporaryPath = temporarySibling(toAbsolute);
206
+ let validator;
207
+ try {
208
+ await fs.promises.copyFile(claimedPath, temporaryPath, fs.constants.COPYFILE_EXCL);
209
+ validator = statValidator(await fs.promises.stat(temporaryPath, { bigint: true }));
210
+ await fs.promises.rename(temporaryPath, toAbsolute);
211
+ }
212
+ catch (err) {
213
+ // Cleanup must not bypass restoration or replace the primary error.
214
+ let temporaryRetained = false;
215
+ try {
216
+ await fs.promises.rm(temporaryPath, { force: true });
217
+ }
218
+ catch {
219
+ temporaryRetained = true;
220
+ }
221
+ throw await this.restoreClaimedSource(claimedPath, fromAbsolute, fromPath, err, temporaryRetained ? temporaryPath : undefined);
222
+ }
223
+ try {
224
+ await fs.promises.unlink(claimedPath);
225
+ }
226
+ catch (err) {
227
+ throw ERR_STORAGE({
228
+ message: `Moved '${fromPath}' to '${toPath}', but could not remove the claimed source copy. ` +
229
+ 'The destination is committed; record it and retry removing the claimed copy.',
230
+ details: {
231
+ reason: 'source-not-removed',
232
+ destinationCommitted: true,
233
+ fromPath,
234
+ claimedPath: path.relative(this.uploadDir, claimedPath),
235
+ location: location(validator),
236
+ },
237
+ cause: err,
238
+ });
239
+ }
240
+ return location(validator);
241
+ }
242
+ /**
243
+ * Put a claimed source back after a failed move, without overwriting a
244
+ * file that has since been written at the source path (`link` refuses an
245
+ * existing destination). Returns the error the caller should throw: the
246
+ * primary failure when everything was put back cleanly, otherwise an
247
+ * `ERR_STORAGE` that keeps the primary failure as its cause and names any
248
+ * path still holding content (`claimedPath`, `temporaryPath`).
249
+ */
250
+ async restoreClaimedSource(claimedPath, fromAbsolute, fromPath, cause, retainedTemporaryPath) {
251
+ const retained = retainedTemporaryPath
252
+ ? { temporaryPath: path.relative(this.uploadDir, retainedTemporaryPath) }
253
+ : {};
254
+ try {
255
+ await fs.promises.link(claimedPath, fromAbsolute);
256
+ }
257
+ catch (restoreErr) {
258
+ return ERR_STORAGE({
259
+ message: `Move from '${fromPath}' failed and the source could not be put back; ` +
260
+ 'its content remains at the claimed path.',
261
+ details: {
262
+ reason: 'source-not-restored',
263
+ destinationCommitted: false,
264
+ fromPath,
265
+ claimedPath: path.relative(this.uploadDir, claimedPath),
266
+ restoreError: restoreErr.code,
267
+ ...retained,
268
+ },
269
+ cause,
270
+ });
271
+ }
272
+ // The source is back at `fromPath`; the claimed name is now a second link.
273
+ let claimRetained = false;
274
+ try {
275
+ await fs.promises.unlink(claimedPath);
276
+ }
277
+ catch {
278
+ claimRetained = true;
279
+ }
280
+ if (!claimRetained && !retainedTemporaryPath)
281
+ return cause;
282
+ return ERR_STORAGE({
283
+ message: `Move from '${fromPath}' failed. The source was restored, but a private ` +
284
+ 'copy could not be removed.',
285
+ details: {
286
+ reason: 'move-failed',
287
+ destinationCommitted: false,
288
+ sourceRestored: true,
289
+ fromPath,
290
+ ...(claimRetained && { claimedPath: path.relative(this.uploadDir, claimedPath) }),
291
+ ...retained,
292
+ },
293
+ cause,
294
+ });
295
+ }
296
+ async download(storagePath, options) {
297
+ const expect = options?.expect;
298
+ if (expect && expect.kind !== LOCAL_VALIDATOR_KIND) {
299
+ throw preconditionFailed('unsupported-kind', storagePath, expect);
300
+ }
301
+ options?.signal?.throwIfAborted();
302
+ const absolutePath = path.join(this.uploadDir, storagePath);
303
+ let handle;
304
+ try {
305
+ handle = await fs.promises.open(absolutePath, 'r');
306
+ }
307
+ catch (err) {
308
+ if (!isNotFound(err))
136
309
  throw err;
310
+ if (expect)
311
+ throw preconditionFailed('missing', storagePath, expect);
312
+ return null;
313
+ }
314
+ // The validator comes from the open handle, so it describes exactly the
315
+ // inode the body streams from, even if the path is replaced meanwhile.
316
+ let validator;
317
+ let size;
318
+ try {
319
+ const stats = await handle.stat({ bigint: true });
320
+ validator = statValidator(stats);
321
+ size = Number(stats.size);
322
+ if (expect && !isSameStorageValidator(expect, validator)) {
323
+ throw preconditionFailed('changed', storagePath, expect, validator);
137
324
  }
325
+ options?.signal?.throwIfAborted();
326
+ }
327
+ catch (err) {
328
+ await handle.close();
329
+ throw err;
330
+ }
331
+ const body = handle.createReadStream({
332
+ autoClose: true,
333
+ ...(options?.signal && { signal: options.signal }),
334
+ });
335
+ return { body, validator, size };
336
+ }
337
+ async head(storagePath) {
338
+ const absolutePath = path.join(this.uploadDir, storagePath);
339
+ try {
340
+ const stats = await fs.promises.stat(absolutePath, { bigint: true });
341
+ return { validator: statValidator(stats), size: Number(stats.size) };
342
+ }
343
+ catch (err) {
344
+ if (isNotFound(err))
345
+ return null;
346
+ throw err;
138
347
  }
139
- return {
140
- storageProvider: this.providerName,
141
- storagePath: toPath,
142
- storageUrl: this.getUrl(toPath),
143
- };
144
348
  }
145
349
  async exists(storagePath) {
146
350
  const absolutePath = path.join(this.uploadDir, storagePath);
@@ -0,0 +1,8 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ export {};
@@ -0,0 +1,387 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { ErrorCodes } from '@byline/core';
12
+ import { runStorageProviderConformanceSuite } from '@byline/storage-conformance';
13
+ import { afterAll, describe, expect, it, vi } from 'vitest';
14
+ import { localStorageProvider } from './local-storage-provider.js';
15
+ const roots = [];
16
+ function freshProvider() {
17
+ const uploadDir = fs.mkdtempSync(path.join(os.tmpdir(), 'byline-storage-local-'));
18
+ roots.push(uploadDir);
19
+ return { provider: localStorageProvider({ uploadDir, baseUrl: '/uploads' }), uploadDir };
20
+ }
21
+ afterAll(() => {
22
+ for (const root of roots)
23
+ fs.rmSync(root, { recursive: true, force: true });
24
+ });
25
+ /**
26
+ * Makes the next `rename` onto a public path (not a private `.tmp` name) fail
27
+ * with EXDEV — in a move, that is the final rename onto the destination.
28
+ */
29
+ function forceExdevOnce() {
30
+ const realRename = fs.promises.rename.bind(fs.promises);
31
+ let armed = true;
32
+ return vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
33
+ if (armed && !String(to).endsWith('.tmp')) {
34
+ armed = false;
35
+ const err = new Error('EXDEV: cross-device link not permitted');
36
+ err.code = 'EXDEV';
37
+ throw err;
38
+ }
39
+ return realRename(from, to);
40
+ });
41
+ }
42
+ runStorageProviderConformanceSuite({
43
+ name: 'storage-local',
44
+ createProvider: () => freshProvider().provider,
45
+ validatorKinds: ['local-stat'],
46
+ extraReplacers: [
47
+ {
48
+ name: 'cross-filesystem move',
49
+ replace: async (provider, storagePath, bytes) => {
50
+ const staging = `conformance/staging-exdev-${Date.now()}.bin`;
51
+ await provider.upload(bytes, {
52
+ filename: 'staging.bin',
53
+ mimeType: 'application/octet-stream',
54
+ size: bytes.length,
55
+ targetStoragePath: staging,
56
+ });
57
+ const spy = forceExdevOnce();
58
+ try {
59
+ await provider.move?.(staging, storagePath);
60
+ }
61
+ finally {
62
+ spy.mockRestore();
63
+ }
64
+ },
65
+ },
66
+ ],
67
+ });
68
+ describe('storage-local writes', () => {
69
+ it('leaves no temporary files behind after uploads and moves', async () => {
70
+ const { provider, uploadDir } = freshProvider();
71
+ const bytes = Buffer.from('content');
72
+ const opts = { filename: 'a.txt', mimeType: 'text/plain', size: bytes.length };
73
+ await provider.upload(bytes, { ...opts, targetStoragePath: 'media/a.txt' });
74
+ await provider.upload(bytes, { ...opts, targetStoragePath: 'media/a.txt' });
75
+ await provider.upload(bytes, { ...opts, targetStoragePath: 'media/b.txt' });
76
+ await provider.move?.('media/b.txt', 'media/c.txt');
77
+ expect(fs.readdirSync(path.join(uploadDir, 'media')).sort()).toEqual(['a.txt', 'c.txt']);
78
+ });
79
+ it('keeps the validator across a same-filesystem move', async () => {
80
+ const { provider } = freshProvider();
81
+ const bytes = Buffer.from('moved');
82
+ const uploaded = await provider.upload(bytes, {
83
+ filename: 'm.txt',
84
+ mimeType: 'text/plain',
85
+ size: bytes.length,
86
+ targetStoragePath: 'media/m.txt',
87
+ });
88
+ const moved = await provider.move?.('media/m.txt', 'archive/m.txt');
89
+ expect(moved?.storageValidator).toEqual(uploaded.storageValidator);
90
+ expect((await provider.head?.('archive/m.txt'))?.validator).toEqual(uploaded.storageValidator);
91
+ });
92
+ it('gives a cross-filesystem move a new validator and removes the source', async () => {
93
+ const { provider, uploadDir } = freshProvider();
94
+ const bytes = Buffer.from('exdev');
95
+ const uploaded = await provider.upload(bytes, {
96
+ filename: 'x.txt',
97
+ mimeType: 'text/plain',
98
+ size: bytes.length,
99
+ targetStoragePath: 'media/x.txt',
100
+ });
101
+ const spy = forceExdevOnce();
102
+ let moved;
103
+ try {
104
+ moved = await provider.move?.('media/x.txt', 'archive/x.txt');
105
+ }
106
+ finally {
107
+ spy.mockRestore();
108
+ }
109
+ expect(moved?.storageValidator).not.toEqual(uploaded.storageValidator);
110
+ expect(fs.existsSync(path.join(uploadDir, 'media/x.txt'))).toBe(false);
111
+ expect(fs.readFileSync(path.join(uploadDir, 'archive/x.txt'), 'utf8')).toBe('exdev');
112
+ });
113
+ it('reports a committed destination when the source cannot be removed after EXDEV', async () => {
114
+ const { provider, uploadDir } = freshProvider();
115
+ const bytes = Buffer.from('stuck');
116
+ await provider.upload(bytes, {
117
+ filename: 's.txt',
118
+ mimeType: 'text/plain',
119
+ size: bytes.length,
120
+ targetStoragePath: 'media/s.txt',
121
+ });
122
+ const renameSpy = forceExdevOnce();
123
+ const unlinkSpy = vi
124
+ .spyOn(fs.promises, 'unlink')
125
+ .mockRejectedValueOnce(Object.assign(new Error('EBUSY'), { code: 'EBUSY' }));
126
+ let error;
127
+ try {
128
+ await provider.move?.('media/s.txt', 'archive/s.txt');
129
+ }
130
+ catch (err) {
131
+ error = err;
132
+ }
133
+ finally {
134
+ renameSpy.mockRestore();
135
+ unlinkSpy.mockRestore();
136
+ }
137
+ expect(error).toMatchObject({
138
+ code: ErrorCodes.STORAGE,
139
+ details: expect.objectContaining({
140
+ reason: 'source-not-removed',
141
+ destinationCommitted: true,
142
+ location: expect.objectContaining({
143
+ storagePath: 'archive/s.txt',
144
+ storageValidator: expect.objectContaining({ kind: 'local-stat' }),
145
+ }),
146
+ }),
147
+ });
148
+ expect(fs.readFileSync(path.join(uploadDir, 'archive/s.txt'), 'utf8')).toBe('stuck');
149
+ });
150
+ it('leaves the destination untouched when the cross-filesystem copy fails', async () => {
151
+ const { provider, uploadDir } = freshProvider();
152
+ const opts = { filename: 'd.txt', mimeType: 'text/plain' };
153
+ await provider.upload(Buffer.from('src'), {
154
+ ...opts,
155
+ size: 3,
156
+ targetStoragePath: 'media/d.txt',
157
+ });
158
+ await provider.upload(Buffer.from('dest'), {
159
+ ...opts,
160
+ size: 4,
161
+ targetStoragePath: 'archive/d.txt',
162
+ });
163
+ const renameSpy = forceExdevOnce();
164
+ const copySpy = vi
165
+ .spyOn(fs.promises, 'copyFile')
166
+ .mockRejectedValueOnce(Object.assign(new Error('ENOSPC'), { code: 'ENOSPC' }));
167
+ try {
168
+ await expect(provider.move?.('media/d.txt', 'archive/d.txt')).rejects.toMatchObject({
169
+ code: 'ENOSPC',
170
+ });
171
+ }
172
+ finally {
173
+ renameSpy.mockRestore();
174
+ copySpy.mockRestore();
175
+ }
176
+ expect(fs.readFileSync(path.join(uploadDir, 'archive/d.txt'), 'utf8')).toBe('dest');
177
+ expect(fs.readFileSync(path.join(uploadDir, 'media/d.txt'), 'utf8')).toBe('src');
178
+ expect(fs.readdirSync(path.join(uploadDir, 'archive'))).toEqual(['d.txt']);
179
+ // The claimed source was put back; no private copy is left behind.
180
+ expect(fs.readdirSync(path.join(uploadDir, 'media'))).toEqual(['d.txt']);
181
+ });
182
+ describe('move with a concurrent upload to the source path', () => {
183
+ const text = (s) => Buffer.from(s);
184
+ const opts = (size, targetStoragePath) => ({
185
+ filename: 'f.txt',
186
+ mimeType: 'text/plain',
187
+ size,
188
+ targetStoragePath,
189
+ });
190
+ /**
191
+ * Runs `replace` once, just before the first `fs.promises[method]` call
192
+ * that matches `when`, then lets that call proceed.
193
+ */
194
+ function interceptOnce(method, when, replace) {
195
+ const real = fs.promises[method].bind(fs.promises);
196
+ let armed = true;
197
+ return vi.spyOn(fs.promises, method).mockImplementation((async (from, to, ...rest) => {
198
+ if (armed && when(String(from), String(to))) {
199
+ armed = false;
200
+ await replace();
201
+ }
202
+ return real(from, to, ...rest);
203
+ }));
204
+ }
205
+ it('moves whatever the claim took and returns that file’s validator', async () => {
206
+ const { provider, uploadDir } = freshProvider();
207
+ await provider.upload(text('old'), opts(3, 'media/src.txt'));
208
+ // A Byline upload replaces the source just before the claim.
209
+ const spy = interceptOnce('rename', (from) => from === path.join(uploadDir, 'media/src.txt'), () => provider.upload(text('replacement'), opts(11, 'media/src.txt')));
210
+ let moved;
211
+ try {
212
+ moved = await provider.move?.('media/src.txt', 'archive/dst.txt');
213
+ }
214
+ finally {
215
+ spy.mockRestore();
216
+ }
217
+ expect(fs.readFileSync(path.join(uploadDir, 'archive/dst.txt'), 'utf8')).toBe('replacement');
218
+ expect(moved?.storageValidator).toEqual((await provider.head?.('archive/dst.txt'))?.validator);
219
+ });
220
+ it('keeps a source written after the claim and binds the validator to the moved file', async () => {
221
+ const { provider, uploadDir } = freshProvider();
222
+ await provider.upload(text('old'), opts(3, 'media/src.txt'));
223
+ // A Byline upload writes a new source after the claim, before the final rename.
224
+ const spy = interceptOnce('rename', (from, to) => from.endsWith('.tmp') && to === path.join(uploadDir, 'archive/dst.txt'), () => provider.upload(text('newer'), opts(5, 'media/src.txt')));
225
+ let moved;
226
+ try {
227
+ moved = await provider.move?.('media/src.txt', 'archive/dst.txt');
228
+ }
229
+ finally {
230
+ spy.mockRestore();
231
+ }
232
+ expect(fs.readFileSync(path.join(uploadDir, 'archive/dst.txt'), 'utf8')).toBe('old');
233
+ expect(moved?.storageValidator).toEqual((await provider.head?.('archive/dst.txt'))?.validator);
234
+ expect(fs.readFileSync(path.join(uploadDir, 'media/src.txt'), 'utf8')).toBe('newer');
235
+ });
236
+ it('never removes a source written during a cross-filesystem move', async () => {
237
+ const { provider, uploadDir } = freshProvider();
238
+ await provider.upload(text('old'), opts(3, 'media/src.txt'));
239
+ const exdev = forceExdevOnce();
240
+ const copy = interceptOnce('copyFile', () => true, () => provider.upload(text('newer'), opts(5, 'media/src.txt')));
241
+ let moved;
242
+ try {
243
+ moved = await provider.move?.('media/src.txt', 'archive/dst.txt');
244
+ }
245
+ finally {
246
+ exdev.mockRestore();
247
+ copy.mockRestore();
248
+ }
249
+ expect(fs.readFileSync(path.join(uploadDir, 'archive/dst.txt'), 'utf8')).toBe('old');
250
+ expect(moved?.storageValidator).toEqual((await provider.head?.('archive/dst.txt'))?.validator);
251
+ expect(fs.readFileSync(path.join(uploadDir, 'media/src.txt'), 'utf8')).toBe('newer');
252
+ expect(fs.readdirSync(path.join(uploadDir, 'media'))).toEqual(['src.txt']);
253
+ });
254
+ });
255
+ it('closes the file handle when an expectation fails', async () => {
256
+ const { provider } = freshProvider();
257
+ const bytes = Buffer.from('handle');
258
+ await provider.upload(bytes, {
259
+ filename: 'h.txt',
260
+ mimeType: 'text/plain',
261
+ size: bytes.length,
262
+ targetStoragePath: 'media/h.txt',
263
+ });
264
+ const closeSpy = vi.fn();
265
+ const realOpen = fs.promises.open.bind(fs.promises);
266
+ const openSpy = vi.spyOn(fs.promises, 'open').mockImplementation(async (...args) => {
267
+ const handle = await realOpen(...args);
268
+ const realClose = handle.close.bind(handle);
269
+ handle.close = async () => {
270
+ closeSpy();
271
+ return realClose();
272
+ };
273
+ return handle;
274
+ });
275
+ try {
276
+ await expect(provider.download?.('media/h.txt', { expect: { kind: 'local-stat', value: 'stale' } })).rejects.toMatchObject({ details: expect.objectContaining({ reason: 'changed' }) });
277
+ }
278
+ finally {
279
+ openSpy.mockRestore();
280
+ }
281
+ expect(closeSpy).toHaveBeenCalledOnce();
282
+ });
283
+ describe('move recovery after the source is claimed', () => {
284
+ const text = (s) => Buffer.from(s);
285
+ const opts = (size, targetStoragePath) => ({
286
+ filename: 'f.txt',
287
+ mimeType: 'text/plain',
288
+ size,
289
+ targetStoragePath,
290
+ });
291
+ const fsError = (code) => Object.assign(new Error(code), { code });
292
+ it('restores the source when stating the claimed file fails', async () => {
293
+ const { provider, uploadDir } = freshProvider();
294
+ await provider.upload(text('old'), opts(3, 'media/src.txt'));
295
+ const realStat = fs.promises.stat.bind(fs.promises);
296
+ const statSpy = vi.spyOn(fs.promises, 'stat').mockImplementation((async (target, options) => {
297
+ const p = String(target);
298
+ if (p.startsWith(path.join(uploadDir, 'media/src.txt.')) && p.endsWith('.tmp')) {
299
+ throw fsError('EIO');
300
+ }
301
+ return realStat(target, options);
302
+ }));
303
+ try {
304
+ await expect(provider.move?.('media/src.txt', 'archive/dst.txt')).rejects.toMatchObject({
305
+ code: 'EIO',
306
+ });
307
+ }
308
+ finally {
309
+ statSpy.mockRestore();
310
+ }
311
+ expect(fs.readFileSync(path.join(uploadDir, 'media/src.txt'), 'utf8')).toBe('old');
312
+ expect(fs.existsSync(path.join(uploadDir, 'archive/dst.txt'))).toBe(false);
313
+ expect(fs.readdirSync(path.join(uploadDir, 'media'))).toEqual(['src.txt']);
314
+ });
315
+ it('still restores the source and names the retained temp when EXDEV cleanup fails', async () => {
316
+ const { provider, uploadDir } = freshProvider();
317
+ await provider.upload(text('old'), opts(3, 'media/src.txt'));
318
+ const exdev = forceExdevOnce();
319
+ const copy = vi.spyOn(fs.promises, 'copyFile').mockRejectedValueOnce(fsError('ENOSPC'));
320
+ const rm = vi.spyOn(fs.promises, 'rm').mockRejectedValueOnce(fsError('EBUSY'));
321
+ let error;
322
+ try {
323
+ await provider.move?.('media/src.txt', 'archive/dst.txt');
324
+ }
325
+ catch (err) {
326
+ error = err;
327
+ }
328
+ finally {
329
+ exdev.mockRestore();
330
+ copy.mockRestore();
331
+ rm.mockRestore();
332
+ }
333
+ expect(error).toMatchObject({
334
+ code: ErrorCodes.STORAGE,
335
+ details: expect.objectContaining({
336
+ reason: 'move-failed',
337
+ destinationCommitted: false,
338
+ sourceRestored: true,
339
+ temporaryPath: expect.stringMatching(/^archive\/dst\.txt\..+\.tmp$/),
340
+ }),
341
+ });
342
+ expect(error.cause?.code).toBe('ENOSPC');
343
+ expect(fs.readFileSync(path.join(uploadDir, 'media/src.txt'), 'utf8')).toBe('old');
344
+ expect(fs.readdirSync(path.join(uploadDir, 'media'))).toEqual(['src.txt']);
345
+ });
346
+ it('refuses to overwrite a source written meanwhile and names the claimed copy', async () => {
347
+ const { provider, uploadDir } = freshProvider();
348
+ await provider.upload(text('old'), opts(3, 'media/src.txt'));
349
+ const destination = path.join(uploadDir, 'archive/dst.txt');
350
+ // The final rename fails, and a Byline upload writes a new source first.
351
+ const realRename = fs.promises.rename.bind(fs.promises);
352
+ let armed = true;
353
+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation((async (from, to) => {
354
+ if (armed && String(from).endsWith('.tmp') && String(to) === destination) {
355
+ armed = false;
356
+ renameSpy.mockRestore();
357
+ await provider.upload(text('newer'), opts(5, 'media/src.txt'));
358
+ throw fsError('EACCES');
359
+ }
360
+ return realRename(from, to);
361
+ }));
362
+ let error;
363
+ try {
364
+ await provider.move?.('media/src.txt', 'archive/dst.txt');
365
+ }
366
+ catch (err) {
367
+ error = err;
368
+ }
369
+ finally {
370
+ renameSpy.mockRestore();
371
+ }
372
+ expect(error).toMatchObject({
373
+ code: ErrorCodes.STORAGE,
374
+ details: expect.objectContaining({
375
+ reason: 'source-not-restored',
376
+ destinationCommitted: false,
377
+ restoreError: 'EEXIST',
378
+ }),
379
+ });
380
+ expect(error.cause?.code).toBe('EACCES');
381
+ const claimedPath = error.details.claimedPath;
382
+ expect(fs.readFileSync(path.join(uploadDir, claimedPath), 'utf8')).toBe('old');
383
+ expect(fs.readFileSync(path.join(uploadDir, 'media/src.txt'), 'utf8')).toBe('newer');
384
+ expect(fs.existsSync(destination)).toBe(false);
385
+ });
386
+ });
387
+ });
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@byline/storage-local",
3
3
  "private": false,
4
4
  "license": "MPL-2.0",
5
- "version": "6.11.0",
5
+ "version": "6.12.1",
6
6
  "engines": {
7
7
  "node": ">=22.22.2"
8
8
  },
@@ -38,18 +38,20 @@
38
38
  "dist"
39
39
  ],
40
40
  "dependencies": {
41
- "@byline/core": "6.11.0",
41
+ "@byline/core": "6.12.1",
42
42
  "uuid": "^14.0.3"
43
43
  },
44
44
  "devDependencies": {
45
- "@biomejs/biome": "2.6.2",
46
- "@types/node": "^26.6.5",
45
+ "@biomejs/biome": "2.6.4",
46
+ "@byline/storage-conformance": "0.0.0",
47
+ "@types/node": "^26.6.6",
47
48
  "chokidar": "^6.0.0",
48
49
  "chokidar-cli": "^3.0.0",
49
50
  "npm-run-all": "^4.1.5",
50
- "tsc-alias": "^1.9.8",
51
+ "tsc-alias": "^1.9.10",
51
52
  "tsx": "^4.23.15",
52
- "typescript": "^7.0.2"
53
+ "typescript": "^7.0.2",
54
+ "vitest": "^5.0.5"
53
55
  },
54
56
  "publishConfig": {
55
57
  "access": "public"
@@ -60,6 +62,7 @@
60
62
  "clean": "node scripts/clean.js node_modules dist build .turbo",
61
63
  "lint": "biome check --write --unsafe --diagnostic-level=error",
62
64
  "skip": "tsx ./scripts/task-watch.js",
63
- "typecheck": "tsc --noEmit"
65
+ "typecheck": "tsc --noEmit",
66
+ "test": "vitest run --mode=node"
64
67
  }
65
68
  }