diff --git a/src/services/drive/drive-file.service.ts b/src/services/drive/drive-file.service.ts index 638daaae..fdaab15e 100644 --- a/src/services/drive/drive-file.service.ts +++ b/src/services/drive/drive-file.service.ts @@ -15,7 +15,7 @@ export class DriveFileService { itemType: 'file', name: payload.plainName, uuid: driveFile.uuid, - size: driveFile.size, + size: DriveUtils.parseFileSize(driveFile.size), bucket: driveFile.bucket, createdAt: new Date(driveFile.createdAt), updatedAt: new Date(driveFile.updatedAt), @@ -41,7 +41,7 @@ export class DriveFileService { itemType: 'file', name: driveFile.plainName ?? '', uuid: driveFile.uuid, - size: driveFile.size, + size: DriveUtils.parseFileSize(driveFile.size), bucket: driveFile.bucket, createdAt: new Date(driveFile.createdAt), updatedAt: new Date(driveFile.updatedAt), @@ -66,7 +66,8 @@ export class DriveFileService { filesList: [file], }); - const existentFile = existentFiles[0]; + // The duplicate check can match a file with the same name but a different extension + const existentFile = existentFiles.find((existent) => (existent.type ?? '') === (file.type ?? '')); if (!existentFile) return undefined; return { diff --git a/src/services/drive/drive-item.service.ts b/src/services/drive/drive-item.service.ts index 030d4af0..e1a642d4 100644 --- a/src/services/drive/drive-item.service.ts +++ b/src/services/drive/drive-item.service.ts @@ -1,3 +1,4 @@ +import path from 'node:path'; import { DriveItemRepository } from '../database/drive-item/drive-item.repository'; import { DriveFileItem, DriveFolderItem } from '../../types/drive.types'; import { ErrorUtils } from '../../utils/errors.utils'; @@ -6,9 +7,60 @@ import { DriveFileService } from './drive-file.service'; import { DriveFolderService } from './drive-folder.service'; import { DriveItemBD } from '../database/drive-item/drive-item.domain'; +const RECENT_WRITE_TRUST_MS = 10_000; + export class DriveItemService { static readonly instance = new DriveItemService(); + private readonly recentFileWrites = new Map(); + + /** The API reads from replicas that can lag a moment behind a write, so a file this server + * just created can briefly look missing; remember it so that 404 is not trusted. */ + public rememberFileWrite = (path: string, item: DriveFileItem): void => { + const now = Date.now(); + for (const [writtenPath, write] of this.recentFileWrites) { + if (write.expiresAt <= now) this.recentFileWrites.delete(writtenPath); + } + this.recentFileWrites.set(path, { item, expiresAt: now + RECENT_WRITE_TRUST_MS }); + }; + + public moveFileWrite = (fromPath: string, toPath: string): void => { + const write = this.recentFileWrites.get(fromPath); + if (!write) return; + this.recentFileWrites.delete(fromPath); + const { name, ext } = path.parse(toPath); + this.recentFileWrites.set(toPath, { ...write, item: { ...write.item, name, type: ext.replace('.', '') } }); + }; + + public forgetFileWrite = (itemPath: string, uuid: string): void => { + if (this.recentFileWrites.get(itemPath)?.item.uuid === uuid) this.recentFileWrites.delete(itemPath); + }; + + /** Forgets writes at this path and, for a folder, everything under it. */ + public forgetFileWrites = (itemPath: string): void => { + const folderPrefix = itemPath.endsWith('/') ? itemPath : `${itemPath}/`; + for (const writtenPath of this.recentFileWrites.keys()) { + if (writtenPath === itemPath || writtenPath.startsWith(folderPrefix)) this.recentFileWrites.delete(writtenPath); + } + }; + + /** Only while the path cache still maps to the written uuid: our own DELETE and MOVE clear it. */ + private readonly getRecentFileWrite = ( + cached: DriveItemBD | undefined, + path: string, + error: unknown, + ): DriveFileItem | undefined => { + if (!cached || !ErrorUtils.isNotFoundError(error)) return; + + const write = this.recentFileWrites.get(path); + if (!write || write.expiresAt <= Date.now() || write.item.uuid !== cached.uuid) return; + + webdavLogger.info(`[LOOKUP] '${path}' was written moments ago, ignoring the API's not found`, { + uuid: cached.uuid, + }); + return write.item; + }; + /** Only drop the cached uuid when the API confirms the item is gone; evicting on a timeout * pushes every later request onto the slow path lookup. */ private readonly dropCacheIfGone = async (uuid: string, error: unknown): Promise => { @@ -30,6 +82,9 @@ export class DriveItemService { ]); return item; } catch (error) { + const recentWrite = this.getRecentFileWrite(cached, path, error); + if (recentWrite) return recentWrite; + webdavLogger.warn(ErrorUtils.withRequestId('File metadata by uuid failed, falling back to path lookup', error), { path, uuid: cached.uuid, @@ -84,6 +139,9 @@ export class DriveItemService { ]); return item; } catch (error) { + const recentWrite = this.getRecentFileWrite(cached, path, error); + if (recentWrite) return recentWrite; + ErrorUtils.logIfUnexpected(webdavLogger, 'File lookup by path failed', error, { path }); throw ErrorUtils.toLookupError('file', path, error); } diff --git a/src/utils/errors.utils.ts b/src/utils/errors.utils.ts index 3ae395f8..b35cdb22 100644 --- a/src/utils/errors.utils.ts +++ b/src/utils/errors.utils.ts @@ -9,6 +9,8 @@ export const DEFAULT_RETRY_AFTER_SECONDS = 5; export const CLIENT_VERSION_UNSUPPORTED = 'CLIENT_VERSION_UNSUPPORTED'; +export const FILE_NOT_REPLACEABLE = 'FILE_NOT_REPLACEABLE'; + export class ErrorUtils { static readonly isError = (error: unknown): error is Error => { return typeof Error.isError === 'function' @@ -38,6 +40,10 @@ export class ErrorUtils { ); }; + static readonly isApiConflict = (error: unknown): boolean => { + return this.getStatusCode(error, 'status') === 409; + }; + static readonly isFileNotFoundError = (error: unknown): error is NodeJS.ErrnoException => { return this.isError(error) && 'code' in error && error.code === 'ENOENT'; }; @@ -93,6 +99,10 @@ export class ErrorUtils { return this.getResponseBody(error)?.errorCode === CLIENT_VERSION_UNSUPPORTED; }; + static readonly isFileNotReplaceable = (error: unknown): boolean => { + return this.getResponseBody(error)?.errorCode === FILE_NOT_REPLACEABLE; + }; + static readonly toClientVersionUnsupportedError = (error: unknown): ClientVersionUnsupportedError => { if (error instanceof ClientVersionUnsupportedError) return error; diff --git a/src/webdav/handlers/DELETE.handler.ts b/src/webdav/handlers/DELETE.handler.ts index e7411079..12540552 100644 --- a/src/webdav/handlers/DELETE.handler.ts +++ b/src/webdav/handlers/DELETE.handler.ts @@ -3,6 +3,7 @@ import { WebDavMethodHandler } from '../../types/webdav.types'; import { WebDavUtils } from '../../utils/webdav.utils'; import { webdavLogger } from '../../utils/logger.utils'; import { NotFoundError } from '../../utils/errors.utils'; +import { DriveItemService } from '../../services/drive/drive-item.service'; export class DELETERequestHandler implements WebDavMethodHandler { handle = async (req: Request, res: Response) => { @@ -16,6 +17,7 @@ export class DELETERequestHandler implements WebDavMethodHandler { } await WebDavUtils.deleteOrTrashItem(driveItem); + DriveItemService.instance.forgetFileWrites(resource.url); res.status(204).send(); }; diff --git a/src/webdav/handlers/MOVE.handler.ts b/src/webdav/handlers/MOVE.handler.ts index bb8671eb..5f2d1beb 100644 --- a/src/webdav/handlers/MOVE.handler.ts +++ b/src/webdav/handlers/MOVE.handler.ts @@ -7,6 +7,7 @@ import { NotFoundError, PreconditionFailedError } from '../../utils/errors.utils import { webdavLogger } from '../../utils/logger.utils'; import { WebDavUtils } from '../../utils/webdav.utils'; import { WebDavFolderService } from '../../services/webdav/webdav-folder.service'; +import { DriveItemService } from '../../services/drive/drive-item.service'; export class MOVERequestHandler implements WebDavMethodHandler { handle = async (req: Request, res: Response) => { @@ -44,6 +45,7 @@ export class MOVERequestHandler implements WebDavMethodHandler { isOverwrite = true; webdavLogger.info(`[MOVE] Destination '${destinationResource.url}' already exists, overwriting it`); await WebDavUtils.deleteOrTrashItem(destinationDriveItem); + DriveItemService.instance.forgetFileWrites(destinationResource.url); } if (destinationResource.path.dir === resource.path.dir) { @@ -107,6 +109,12 @@ export class MOVERequestHandler implements WebDavMethodHandler { }, ]); + if (originalDriveItem.itemType === 'file') { + DriveItemService.instance.moveFileWrite(resource.url, destinationResource.url); + } else { + DriveItemService.instance.forgetFileWrites(resource.url); + } + const statusCode = isOverwrite ? 204 : 201; res.status(statusCode).send(); }; diff --git a/src/webdav/handlers/PUT.handler.ts b/src/webdav/handlers/PUT.handler.ts index 80455081..6d7d2240 100644 --- a/src/webdav/handlers/PUT.handler.ts +++ b/src/webdav/handlers/PUT.handler.ts @@ -1,9 +1,10 @@ import { Request, Response } from 'express'; import { DriveFileService } from '../../services/drive/drive-file.service'; import { DriveItemRepository } from '../../services/database/drive-item/drive-item.repository'; +import { DriveItemService } from '../../services/drive/drive-item.service'; import { AuthService } from '../../services/auth.service'; import { WebDavMethodHandler } from '../../types/webdav.types'; -import { ConflictError, ErrorUtils } from '../../utils/errors.utils'; +import { ConflictError, ErrorUtils, ServiceUnavailableError } from '../../utils/errors.utils'; import { WebDavUtils } from '../../utils/webdav.utils'; import { webdavLogger } from '../../utils/logger.utils'; import { EncryptionVersion } from '@internxt/sdk/dist/drive/storage/types'; @@ -12,6 +13,7 @@ import { WebDavFolderService } from '../../services/webdav/webdav-folder.service import { ThumbnailService } from '../../services/thumbnail.service'; import { FormatUtils } from '../../utils/format.utils'; import { UploadUtils } from '../../utils/upload.utils'; +import { DriveFileItem } from '../../types/drive.types'; export class PUTRequestHandler implements WebDavMethodHandler { handle = async (req: Request, res: Response) => { @@ -109,24 +111,22 @@ export class PUTRequestHandler implements WebDavMethodHandler { }; let file; - if (driveFileItem?.itemType === 'file') { + if (isReplacement && driveFileItem) { try { file = await DriveFileService.instance.replaceFile(driveFileItem.uuid, filePayload); } catch (error) { - if (ErrorUtils.isClientVersionUnsupported(error)) throw error; - webdavLogger.warn( - ErrorUtils.withRequestId( - `[PUT] File replace failed for '${resource.url}', falling back to delete and create: ${ - error instanceof Error ? error.message : String(error) - }`, - error, - ), - ); - await WebDavUtils.deleteOrTrashItem(driveFileItem); - file = await DriveFileService.instance.createFile(filePayload); + if (!ErrorUtils.isNotFoundError(error) && !ErrorUtils.isFileNotReplaceable(error)) throw error; + // The lookup came from a lagging replica; the primary says this file is gone, so PUT creates it + webdavLogger.info(`[PUT] '${resource.url}' is no longer replaceable, creating it instead`, { + uuid: driveFileItem.uuid, + }); + await DriveItemRepository.instance.delete([driveFileItem.uuid]); + DriveItemService.instance.forgetFileWrite(resource.url, driveFileItem.uuid); + isReplacement = false; + file = await this.createFileOrRetryLater(resource.url, filePayload); } } else { - file = await DriveFileService.instance.createFile(filePayload); + file = await this.createFileOrRetryLater(resource.url, filePayload, driveFileItem?.uuid); } timings.driveUpload = driveTimer.stop(); @@ -139,6 +139,7 @@ export class PUTRequestHandler implements WebDavMethodHandler { updatedAt: new Date(), }, ]); + DriveItemService.instance.rememberFileWrite(resource.url, file); const thumbnailTimer = CLIUtils.timer(); await ThumbnailService.instance.tryUploadThumbnail({ @@ -168,4 +169,29 @@ export class PUTRequestHandler implements WebDavMethodHandler { res.header('ETag', WebDavUtils.getItemETag(file)); res.status(statusCode).send(); }; + + private readonly createFileOrRetryLater = async ( + url: string, + payload: Parameters[0], + staleUuid?: string, + ): Promise => { + try { + return await DriveFileService.instance.createFile(payload); + } catch (error) { + // POST /files only returns 409 when a live file with this name exists + if (!ErrorUtils.isApiConflict(error)) throw error; + + webdavLogger.warn( + ErrorUtils.withRequestId( + `[PUT] '${url}' conflicts on the API, asking to retry: ${ErrorUtils.getResponseMessage(error) ?? 'no message'}`, + error, + ), + ); + if (staleUuid) { + await DriveItemRepository.instance.delete([staleUuid]); + DriveItemService.instance.forgetFileWrite(url, staleUuid); + } + throw new ServiceUnavailableError(`File '${url}' already exists but could not be found yet, retry later`); + } + }; } diff --git a/test/services/drive/drive-file.service.test.ts b/test/services/drive/drive-file.service.test.ts index 7ceda6a0..c47d4209 100644 --- a/test/services/drive/drive-file.service.test.ts +++ b/test/services/drive/drive-file.service.test.ts @@ -50,6 +50,28 @@ describe('Drive file Service', () => { expect(result.folderUuid).to.be.equal(payload.folderUuid); }); + test('when the API returns the size as a string, then created and replaced files carry it as a number', async () => { + const payload: Storage.FileEntryByUuid = { + plainName: 'example', + type: 'txt', + size: 1024, + folderUuid: 'folder_uuid', + fileId: 'fileId_123456', + bucket: 'bucket123', + encryptVersion: EncryptionVersion.Aes03, + }; + const apiFile = { uuid: 'example-uuid', size: '1024', createdAt: new Date(), updatedAt: new Date() }; + const storageClientMock: Partial = { + createFileEntryByUuid: vi.fn().mockResolvedValue(apiFile), + replaceFile: vi.fn().mockResolvedValue(apiFile), + }; + // @ts-expect-error - We only stub the methods we need to test + vi.spyOn(SdkManager.instance, 'getStorage').mockReturnValue(storageClientMock); + + expect((await sut.createFile(payload)).size).toBe(1024); + expect((await sut.replaceFile('example-uuid', payload)).size).toBe(1024); + }); + test('when file metadata is requested, then it is returned successfully', async () => { const fakeFileData: DriveFileData = { uuid: randomUUID(), @@ -120,4 +142,51 @@ describe('Drive file Service', () => { await expect(sut.getFileMetadata(randomUUID())).rejects.toBeInstanceOf(ServiceUnavailableError); }); + + describe('findExistentFile', () => { + const existent = (type: string | null) => ({ + uuid: randomUUID(), + plainName: 'report', + type, + size: '1', + bucket: 'bucket', + fileId: 'file-id', + folderUuid: 'folder-uuid', + status: 'EXISTS', + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }); + + const mockDuplicates = (existentFiles: ReturnType[]) => { + const storageClientMock: Partial = { + checkDuplicatedFiles: vi.fn().mockResolvedValue({ existentFiles }), + }; + // @ts-expect-error - We only stub the method we need to test + vi.spyOn(SdkManager.instance, 'getStorage').mockReturnValue(storageClientMock); + }; + + test('when the only duplicate has another extension, then no file is returned', async () => { + mockDuplicates([existent('txt')]); + + await expect(sut.findExistentFile('folder-uuid', { plainName: 'report', type: 'pdf' })).resolves.toBeUndefined(); + }); + + test('when several duplicates are returned, then the one with the same extension is picked', async () => { + const match = existent('pdf'); + mockDuplicates([existent('txt'), match]); + + const result = await sut.findExistentFile('folder-uuid', { plainName: 'report', type: 'pdf' }); + + expect(result?.uuid).toBe(match.uuid); + }); + + test('when the file has no extension, then a duplicate without one matches', async () => { + const match = existent(null); + mockDuplicates([existent('txt'), match]); + + const result = await sut.findExistentFile('folder-uuid', { plainName: 'report', type: '' }); + + expect(result?.uuid).toBe(match.uuid); + }); + }); }); diff --git a/test/services/drive/drive-item.service.test.ts b/test/services/drive/drive-item.service.test.ts index a91ee778..e56d472b 100644 --- a/test/services/drive/drive-item.service.test.ts +++ b/test/services/drive/drive-item.service.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test, vi } from 'vitest'; +import { afterEach, describe, expect, test, vi } from 'vitest'; import { DriveItemService } from '../../../src/services/drive/drive-item.service'; import { DriveItemRepository } from '../../../src/services/database/drive-item/drive-item.repository'; import { DriveItemBD } from '../../../src/services/database/drive-item/drive-item.domain'; @@ -215,6 +215,142 @@ describe('Drive Item Service', () => { }); }); + describe('trusting a file this server just wrote', () => { + const cacheEntry = (path: string, uuid: string) => + new DriveItemBD({ uuid, path, type: 'file', createdAt: new Date(), updatedAt: new Date() }); + + afterEach(() => { + vi.useRealTimers(); + }); + + test('when the API says a just-written file is missing, then the written file is returned and kept in cache', async () => { + const path = '/recent/just-written.txt'; + const written = newFileItem({ uuid: 'written-uuid' }); + sut.rememberFileWrite(path, written); + vi.spyOn(DriveItemRepository.instance, 'getByPath').mockResolvedValue(cacheEntry(path, written.uuid)); + vi.spyOn(DriveFileService.instance, 'getFileMetadata').mockRejectedValue(newApiError(404)); + const pathLookupSpy = vi.spyOn(DriveFileService.instance, 'getFileMetadataByPath'); + const deleteSpy = vi.spyOn(DriveItemRepository.instance, 'delete').mockResolvedValue(undefined); + + const result = await sut.getFileByPath(path); + + expect(result).toBe(written); + expect(pathLookupSpy).not.toHaveBeenCalled(); + expect(deleteSpy).not.toHaveBeenCalled(); + }); + + test('when the API finds a just-written file, then the API answer is returned', async () => { + const path = '/recent/found.txt'; + const written = newFileItem({ uuid: 'found-uuid' }); + const fromApi = newFileItem({ uuid: 'found-uuid' }); + sut.rememberFileWrite(path, written); + vi.spyOn(DriveItemRepository.instance, 'getByPath').mockResolvedValue(cacheEntry(path, written.uuid)); + vi.spyOn(DriveFileService.instance, 'getFileMetadata').mockResolvedValue(fromApi); + vi.spyOn(DriveItemRepository.instance, 'createOrUpdate').mockResolvedValue(undefined); + + const result = await sut.getFileByPath(path); + + expect(result).toBe(fromApi); + }); + + test('when the uuid lookup fails transiently and the path lookup says missing, then the written file is returned', async () => { + const path = '/recent/transient.txt'; + const written = newFileItem({ uuid: 'transient-uuid' }); + sut.rememberFileWrite(path, written); + vi.spyOn(DriveItemRepository.instance, 'getByPath').mockResolvedValue(cacheEntry(path, written.uuid)); + vi.spyOn(DriveFileService.instance, 'getFileMetadata').mockRejectedValue(newApiError(504)); + vi.spyOn(DriveFileService.instance, 'getFileMetadataByPath').mockRejectedValue(newApiError(404)); + + const result = await sut.getFileByPath(path); + + expect(result).toBe(written); + }); + + test('when the write is older than the trust window, then the not found is reported', async () => { + vi.useFakeTimers(); + const path = '/recent/expired.txt'; + const written = newFileItem({ uuid: 'expired-uuid' }); + sut.rememberFileWrite(path, written); + vi.advanceTimersByTime(10_001); + vi.spyOn(DriveItemRepository.instance, 'getByPath').mockResolvedValue(cacheEntry(path, written.uuid)); + vi.spyOn(DriveFileService.instance, 'getFileMetadata').mockRejectedValue(newApiError(404)); + vi.spyOn(DriveFileService.instance, 'getFileMetadataByPath').mockRejectedValue(newApiError(404)); + vi.spyOn(DriveItemRepository.instance, 'delete').mockResolvedValue(undefined); + + await expect(sut.getFileByPath(path)).rejects.toBeInstanceOf(NotFoundError); + }); + + test('when the path no longer maps to the written file, then the not found is reported', async () => { + const path = '/recent/replaced-elsewhere.txt'; + sut.rememberFileWrite(path, newFileItem({ uuid: 'old-uuid' })); + vi.spyOn(DriveItemRepository.instance, 'getByPath').mockResolvedValue(cacheEntry(path, 'other-uuid')); + vi.spyOn(DriveFileService.instance, 'getFileMetadata').mockRejectedValue(newApiError(404)); + vi.spyOn(DriveFileService.instance, 'getFileMetadataByPath').mockRejectedValue(newApiError(404)); + vi.spyOn(DriveItemRepository.instance, 'delete').mockResolvedValue(undefined); + + await expect(sut.getFileByPath(path)).rejects.toBeInstanceOf(NotFoundError); + }); + + test('when the written file was deleted through this server, then the not found is reported', async () => { + const path = '/recent/deleted.txt'; + sut.rememberFileWrite(path, newFileItem({ uuid: 'deleted-uuid' })); + vi.spyOn(DriveItemRepository.instance, 'getByPath').mockResolvedValue(undefined); + vi.spyOn(DriveFileService.instance, 'getFileMetadataByPath').mockRejectedValue(newApiError(404)); + + await expect(sut.getFileByPath(path)).rejects.toBeInstanceOf(NotFoundError); + }); + + test('when a just-written file is moved, then the destination keeps the protection with its new name', async () => { + const written = newFileItem({ uuid: 'moved-uuid', name: 'backup', type: 'temp' }); + sut.rememberFileWrite('/recent/backup.temp', written); + sut.moveFileWrite('/recent/backup.temp', '/recent/backup.dat'); + vi.spyOn(DriveItemRepository.instance, 'getByPath').mockImplementation(async (path) => + cacheEntry(path, written.uuid), + ); + vi.spyOn(DriveFileService.instance, 'getFileMetadata').mockRejectedValue(newApiError(404)); + vi.spyOn(DriveFileService.instance, 'getFileMetadataByPath').mockRejectedValue(newApiError(404)); + vi.spyOn(DriveItemRepository.instance, 'delete').mockResolvedValue(undefined); + + const result = await sut.getFileByPath('/recent/backup.dat'); + + expect(result).toMatchObject({ uuid: written.uuid, name: 'backup', type: 'dat' }); + await expect(sut.getFileByPath('/recent/backup.temp')).rejects.toBeInstanceOf(NotFoundError); + }); + + test('when a write is forgotten by uuid, then only a write of that uuid is dropped', async () => { + const path = '/forget/by-uuid.txt'; + const newer = newFileItem({ uuid: 'newer-uuid' }); + sut.rememberFileWrite(path, newer); + sut.forgetFileWrite(path, 'older-uuid'); + vi.spyOn(DriveItemRepository.instance, 'getByPath').mockResolvedValue(cacheEntry(path, newer.uuid)); + vi.spyOn(DriveFileService.instance, 'getFileMetadata').mockRejectedValue(newApiError(404)); + vi.spyOn(DriveFileService.instance, 'getFileMetadataByPath').mockRejectedValue(newApiError(404)); + vi.spyOn(DriveItemRepository.instance, 'delete').mockResolvedValue(undefined); + + await expect(sut.getFileByPath(path)).resolves.toBe(newer); + + sut.forgetFileWrite(path, newer.uuid); + await expect(sut.getFileByPath(path)).rejects.toBeInstanceOf(NotFoundError); + }); + + test('when a folder is forgotten, then the writes under it are forgotten and siblings are kept', async () => { + const inside = newFileItem({ uuid: 'inside-uuid' }); + const sibling = newFileItem({ uuid: 'sibling-uuid' }); + sut.rememberFileWrite('/forget/folder/file.txt', inside); + sut.rememberFileWrite('/forget/folder-2/file.txt', sibling); + sut.forgetFileWrites('/forget/folder'); + vi.spyOn(DriveItemRepository.instance, 'getByPath').mockImplementation(async (path) => + cacheEntry(path, path.startsWith('/forget/folder/') ? inside.uuid : sibling.uuid), + ); + vi.spyOn(DriveFileService.instance, 'getFileMetadata').mockRejectedValue(newApiError(404)); + vi.spyOn(DriveFileService.instance, 'getFileMetadataByPath').mockRejectedValue(newApiError(404)); + vi.spyOn(DriveItemRepository.instance, 'delete').mockResolvedValue(undefined); + + await expect(sut.getFileByPath('/forget/folder/file.txt')).rejects.toBeInstanceOf(NotFoundError); + await expect(sut.getFileByPath('/forget/folder-2/file.txt')).resolves.toBe(sibling); + }); + }); + describe('getting a folder by path', () => { test('when the folder is in cache and the API responds, then the cached folder is returned', async () => { const path = '/test/folder/'; diff --git a/test/utils/errors.utils.test.ts b/test/utils/errors.utils.test.ts index a7c8a805..441e807a 100644 --- a/test/utils/errors.utils.test.ts +++ b/test/utils/errors.utils.test.ts @@ -277,6 +277,34 @@ describe('Errors Utils', () => { }); }); + describe('isApiConflict', () => { + test('when the API answers 409, then it is a conflict whatever the message', () => { + expect(ErrorUtils.isApiConflict(newApiError(409, { data: { message: 'File already exists' } }))).toBe(true); + expect(ErrorUtils.isApiConflict(newApiError(409))).toBe(true); + }); + + test('when the error is another status or carries none, then it is not a conflict', () => { + expect(ErrorUtils.isApiConflict(newApiError(400))).toBe(false); + expect(ErrorUtils.isApiConflict(newNetworkError())).toBe(false); + expect(ErrorUtils.isApiConflict(new Error('File already exists'))).toBe(false); + }); + }); + + describe('isFileNotReplaceable', () => { + test('when the API rejects a replace with its error code, then it is detected', () => { + const error = newApiError(400, { data: { errorCode: 'FILE_NOT_REPLACEABLE' } }); + expect(ErrorUtils.isFileNotReplaceable(error)).toBe(true); + }); + + test('when the 400 carries another error code or none, then it is not detected', () => { + expect(ErrorUtils.isFileNotReplaceable(newApiError(400))).toBe(false); + expect( + ErrorUtils.isFileNotReplaceable(newApiError(400, { data: { errorCode: 'EMPTY_FILES_LIMIT_REACHED' } })), + ).toBe(false); + expect(ErrorUtils.isFileNotReplaceable(new Error('TRASHED files can not be replaced'))).toBe(false); + }); + }); + describe('toClientVersionUnsupportedError', () => { afterEach(() => { vi.unstubAllEnvs(); diff --git a/test/webdav/handlers/DELETE.handler.test.ts b/test/webdav/handlers/DELETE.handler.test.ts index f66b24a0..7feddb28 100644 --- a/test/webdav/handlers/DELETE.handler.test.ts +++ b/test/webdav/handlers/DELETE.handler.test.ts @@ -10,6 +10,7 @@ import { } from '../../fixtures/webdav.fixture'; import { NotFoundError } from '../../../src/utils/errors.utils'; import { WebDavUtils } from '../../../src/utils/webdav.utils'; +import { DriveItemService } from '../../../src/services/drive/drive-item.service'; import { newFileItem, newFolderItem } from '../../fixtures/drive.fixture'; import { WebDavRequestedResource } from '../../../src/types/webdav.types'; import { AuthService } from '../../../src/services/auth.service'; @@ -100,11 +101,13 @@ describe('DELETE request handler', () => { .spyOn(WebDavUtils, 'getDriveItemFromResource') .mockResolvedValue(mockFolder); const removeItemsStub = vi.spyOn(WebDavUtils, 'deleteOrTrashItem').mockResolvedValue(); + const forgetFileWritesSpy = vi.spyOn(DriveItemService.instance, 'forgetFileWrites'); await requestHandler.handle(request, response); expect(response.status).toHaveBeenCalledWith(204); expect(getRequestedResourceStub).toHaveBeenCalledOnce(); expect(getAndSearchItemFromResourceStub).toHaveBeenCalledOnce(); expect(removeItemsStub).toHaveBeenCalledWith(mockFolder); + expect(forgetFileWritesSpy).toHaveBeenCalledWith(requestedFolderResource.url); }); }); diff --git a/test/webdav/handlers/MOVE.handler.test.ts b/test/webdav/handlers/MOVE.handler.test.ts index 2f3badb7..5e60917e 100644 --- a/test/webdav/handlers/MOVE.handler.test.ts +++ b/test/webdav/handlers/MOVE.handler.test.ts @@ -13,6 +13,7 @@ import { DriveFileService } from '../../../src/services/drive/drive-file.service import { WebDavFolderService } from '../../../src/services/webdav/webdav-folder.service'; import { DriveItemRepository } from '../../../src/services/database/drive-item/drive-item.repository'; import { newFolderItem, newFileItem } from '../../fixtures/drive.fixture'; +import { DriveItemService } from '../../../src/services/drive/drive-item.service'; describe('MOVE request handler', () => { let sut: MOVERequestHandler; @@ -66,9 +67,11 @@ describe('MOVE request handler', () => { const renameFolderStub = vi.spyOn(DriveFolderService.instance, 'renameFolder').mockResolvedValue(undefined); const deleteSpy = vi.spyOn(DriveItemRepository.instance, 'delete').mockResolvedValue(undefined); const createOrUpdateSpy = vi.spyOn(DriveItemRepository.instance, 'createOrUpdate').mockResolvedValue(undefined); + const forgetFileWritesSpy = vi.spyOn(DriveItemService.instance, 'forgetFileWrites'); await sut.handle(request, response); + expect(forgetFileWritesSpy).toHaveBeenCalledWith('/source/folder/'); expect(renameFolderStub).toHaveBeenCalledWith({ folderUuid: 'folder-uuid', name: 'renamed' }); expect(deleteSpy).toHaveBeenCalledWith(['folder-uuid']); expect(createOrUpdateSpy).toHaveBeenCalled(); @@ -96,9 +99,11 @@ describe('MOVE request handler', () => { const renameFileStub = vi.spyOn(DriveFileService.instance, 'renameFile').mockResolvedValue(undefined); const deleteSpy = vi.spyOn(DriveItemRepository.instance, 'delete').mockResolvedValue(undefined); const createOrUpdateSpy = vi.spyOn(DriveItemRepository.instance, 'createOrUpdate').mockResolvedValue(undefined); + const moveFileWriteSpy = vi.spyOn(DriveItemService.instance, 'moveFileWrite'); await sut.handle(request, response); + expect(moveFileWriteSpy).toHaveBeenCalledWith('/source/file.txt', '/source/renamed.txt'); expect(renameFileStub).toHaveBeenCalledWith('file-uuid', { plainName: 'renamed', type: 'txt' }); expect(deleteSpy).toHaveBeenCalledWith(['file-uuid']); expect(createOrUpdateSpy).toHaveBeenCalled(); diff --git a/test/webdav/handlers/PUT.handler.test.ts b/test/webdav/handlers/PUT.handler.test.ts index 456db80d..781c2739 100644 --- a/test/webdav/handlers/PUT.handler.test.ts +++ b/test/webdav/handlers/PUT.handler.test.ts @@ -8,6 +8,7 @@ import { getRequestedFolderResource, } from '../../fixtures/webdav.fixture'; import { DriveFileService } from '../../../src/services/drive/drive-file.service'; +import { DriveItemService } from '../../../src/services/drive/drive-item.service'; import { AuthService } from '../../../src/services/auth.service'; import { NetworkFacade } from '../../../src/services/network/network-facade.service'; import { PUTRequestHandler } from '../../../src/webdav/handlers/PUT.handler'; @@ -15,11 +16,13 @@ import { WebDavRequestedResource } from '../../../src/types/webdav.types'; import { WebDavUtils } from '../../../src/utils/webdav.utils'; import { newFileItem, newFolderItem } from '../../fixtures/drive.fixture'; import { UserCredentialsFixture } from '../../fixtures/login.fixture'; -import { newClientVersionUnsupportedError } from '../../fixtures/errors.fixture'; +import { FileStatus } from '@internxt/sdk/dist/drive/storage/types'; import { CLIUtils } from '../../../src/utils/cli.utils'; import { UsageService } from '../../../src/services/usage.service'; -import { webdavLogger } from '../../../src/utils/logger.utils'; -import { AxiosResponseError } from '@internxt/sdk/dist/shared/types/errors'; +import { DriveItemRepository } from '../../../src/services/database/drive-item/drive-item.repository'; +import { newApiError, newClientVersionUnsupportedError } from '../../fixtures/errors.fixture'; +import { ServiceUnavailableError } from '../../../src/utils/errors.utils'; +import { DriveItemBD } from '../../../src/services/database/drive-item/drive-item.domain'; describe('PUT request handler', () => { let networkFacade: NetworkFacade; @@ -183,6 +186,7 @@ describe('PUT request handler', () => { const uploadStub = vi.spyOn(networkFacade, 'uploadFile').mockResolvedValue('uploaded-file-id'); const createDriveFileStub = vi.spyOn(DriveFileService.instance, 'createFile').mockResolvedValue(fileFixture); const replaceDriveFileStub = vi.spyOn(DriveFileService.instance, 'replaceFile').mockResolvedValue(fileFixture); + const rememberFileWriteStub = vi.spyOn(DriveItemService.instance, 'rememberFileWrite'); await sut.handle(request, response); expect(response.status).toHaveBeenCalledWith(204); @@ -203,67 +207,173 @@ describe('PUT request handler', () => { ); expect(createDriveFileStub).not.toHaveBeenCalled(); expect(deleteDriveFileStub).not.toHaveBeenCalled(); + expect(rememberFileWriteStub).toHaveBeenCalledWith(requestedFileResource.url, fileFixture); }); - test('when replacing an existing file fails, then the request id is logged and the file is deleted and created', async () => { - const requestedFileResource: WebDavRequestedResource = getRequestedFileResource(); - const requestedParentFolderResource: WebDavRequestedResource = getRequestedFolderResource({ - parentFolder: '/', - folderName: '', + test.each([ + ['an API error', () => newApiError(500)], + ['an unsupported client version', () => newClientVersionUnsupportedError()], + ])( + 'when replacing an existing file fails with %s, then the error passes through and nothing is created', + async (_, newError) => { + const requestedFileResource: WebDavRequestedResource = getRequestedFileResource(); + const requestedParentFolderResource: WebDavRequestedResource = getRequestedFolderResource({ + parentFolder: '/', + folderName: '', + }); + const folderFixture = newFolderItem({ name: requestedParentFolderResource.name }); + const fileFixture = newFileItem({ folderUuid: folderFixture.uuid, size: 0, fileId: undefined }); + const request = createWebDavRequestFixture({ + method: 'PUT', + url: requestedFileResource.url, + headers: { 'content-length': '0' }, + }); + const response = createWebDavResponseFixture({ + status: vi.fn().mockReturnValue({ send: vi.fn() }), + }); + const replaceError = newError(); + + vi.spyOn(WebDavUtils, 'getRequestedResource') + .mockResolvedValueOnce(requestedFileResource) + .mockResolvedValueOnce(requestedParentFolderResource); + vi.spyOn(WebDavUtils, 'getDriveItemFromResource').mockResolvedValueOnce(fileFixture); + vi.spyOn(WebDavUtils, 'getDriveFolderFromResource').mockResolvedValue(folderFixture); + vi.spyOn(AuthService.instance, 'getAuthDetails').mockResolvedValue(UserCredentialsFixture); + const deleteDriveFileStub = vi.spyOn(WebDavUtils, 'deleteOrTrashItem').mockResolvedValue(); + vi.spyOn(DriveFileService.instance, 'replaceFile').mockRejectedValue(replaceError); + const createDriveFileStub = vi.spyOn(DriveFileService.instance, 'createFile').mockResolvedValue(fileFixture); + + await expect(sut.handle(request, response)).rejects.toBe(replaceError); + + expect(deleteDriveFileStub).not.toHaveBeenCalled(); + expect(createDriveFileStub).not.toHaveBeenCalled(); + expect(response.status).not.toHaveBeenCalled(); + }, + ); + + describe('when the replace says the file is no longer replaceable', () => { + const setupStaleReplace = (replaceError: unknown) => { + const requestedFileResource: WebDavRequestedResource = getRequestedFileResource(); + const requestedParentFolderResource: WebDavRequestedResource = getRequestedFolderResource({ + parentFolder: '/', + folderName: '', + }); + const folderFixture = newFolderItem({ name: requestedParentFolderResource.name }); + const staleFile = newFileItem({ folderUuid: folderFixture.uuid }); + const createdFile = newFileItem({ folderUuid: folderFixture.uuid }); + const request = createWebDavRequestFixture({ + method: 'PUT', + url: requestedFileResource.url, + headers: { 'content-length': '100' }, + }); + const response = createWebDavResponseFixture({ + status: vi.fn().mockReturnValue({ send: vi.fn() }), + }); + + vi.spyOn(WebDavUtils, 'getRequestedResource') + .mockResolvedValueOnce(requestedFileResource) + .mockResolvedValueOnce(requestedParentFolderResource); + vi.spyOn(WebDavUtils, 'getDriveItemFromResource').mockResolvedValueOnce(staleFile); + vi.spyOn(WebDavUtils, 'getDriveFolderFromResource').mockResolvedValue(folderFixture); + vi.spyOn(AuthService.instance, 'getAuthDetails').mockResolvedValue(UserCredentialsFixture); + const uploadStub = vi.spyOn(networkFacade, 'uploadFile').mockResolvedValue('uploaded-file-id'); + const deleteDriveFileStub = vi.spyOn(WebDavUtils, 'deleteOrTrashItem').mockResolvedValue(); + const dropCacheStub = vi.spyOn(DriveItemRepository.instance, 'delete').mockResolvedValue(undefined); + vi.spyOn(DriveItemRepository.instance, 'createOrUpdate').mockResolvedValue(undefined); + vi.spyOn(DriveFileService.instance, 'replaceFile').mockRejectedValue(replaceError); + const createDriveFileStub = vi.spyOn(DriveFileService.instance, 'createFile').mockResolvedValue(createdFile); + + return { + request, + response, + staleFile, + createdFile, + uploadStub, + deleteDriveFileStub, + dropCacheStub, + createDriveFileStub, + }; + }; + + test('when the replace returns 404, then the cached uuid is dropped and the file is created with the same upload', async () => { + const { request, response, staleFile, uploadStub, deleteDriveFileStub, dropCacheStub, createDriveFileStub } = + setupStaleReplace(newApiError(404)); + + await sut.handle(request, response); + + expect(uploadStub).toHaveBeenCalledOnce(); + expect(dropCacheStub).toHaveBeenCalledWith([staleFile.uuid]); + expect(createDriveFileStub).toHaveBeenCalledOnce(); + expect(createDriveFileStub).toHaveBeenCalledWith(expect.objectContaining({ fileId: 'uploaded-file-id' })); + expect(deleteDriveFileStub).not.toHaveBeenCalled(); + expect(response.status).toHaveBeenCalledWith(201); }); - const folderFixture = newFolderItem({ name: requestedParentFolderResource.name }); - const fileFixture = newFileItem({ folderUuid: folderFixture.uuid, size: 0, fileId: undefined }); - const request = createWebDavRequestFixture({ - method: 'PUT', - url: requestedFileResource.url, - headers: { - 'content-length': '0', - }, + test('when the replace returns FILE_NOT_REPLACEABLE, then the file is created', async () => { + const { request, response, staleFile, dropCacheStub, createDriveFileStub } = setupStaleReplace( + newApiError(400, { data: { errorCode: 'FILE_NOT_REPLACEABLE' } }), + ); + + await sut.handle(request, response); + + expect(dropCacheStub).toHaveBeenCalledWith([staleFile.uuid]); + expect(createDriveFileStub).toHaveBeenCalledOnce(); + expect(response.status).toHaveBeenCalledWith(201); }); - const response = createWebDavResponseFixture({ - status: vi.fn().mockReturnValue({ send: vi.fn() }), + test('when the create that follows says the file already exists, then the client is asked to retry', async () => { + const { request, response, staleFile, dropCacheStub, createDriveFileStub } = setupStaleReplace( + newApiError(400, { data: { errorCode: 'FILE_NOT_REPLACEABLE' } }), + ); + createDriveFileStub.mockRejectedValue(newApiError(409, { data: { message: 'File already exists' } })); + const forgetFileWriteSpy = vi.spyOn(DriveItemService.instance, 'forgetFileWrite'); + + await expect(sut.handle(request, response)).rejects.toBeInstanceOf(ServiceUnavailableError); + + expect(createDriveFileStub).toHaveBeenCalledOnce(); + expect(dropCacheStub).toHaveBeenCalledExactlyOnceWith([staleFile.uuid]); + expect(forgetFileWriteSpy).toHaveBeenCalledExactlyOnceWith(request.url, staleFile.uuid); + expect(response.status).not.toHaveBeenCalled(); }); - const replaceError = new AxiosResponseError('Request failed with status code 500', 'PUT /files/uuid', { - status: 500, - data: {}, - headers: { 'x-request-id': 'req-123' }, - statusText: 'Internal Server Error', - // @ts-expect-error partial AxiosResponse fixture, only the fields read by AxiosResponseError are needed - config: {}, + test('when the create that follows fails with another error, then the gone file is no longer remembered', async () => { + const createError = newApiError(500); + const { request, response, staleFile, createDriveFileStub } = setupStaleReplace(newApiError(404)); + createDriveFileStub.mockRejectedValue(createError); + DriveItemService.instance.rememberFileWrite(request.url, staleFile); + const forgetFileWriteSpy = vi.spyOn(DriveItemService.instance, 'forgetFileWrite'); + + await expect(sut.handle(request, response)).rejects.toBe(createError); + + expect(forgetFileWriteSpy).toHaveBeenCalledWith(request.url, staleFile.uuid); }); - vi.spyOn(WebDavUtils, 'getRequestedResource') - .mockResolvedValueOnce(requestedFileResource) - .mockResolvedValueOnce(requestedParentFolderResource); - vi.spyOn(WebDavUtils, 'getDriveItemFromResource').mockResolvedValueOnce(fileFixture); - vi.spyOn(WebDavUtils, 'getDriveFolderFromResource').mockResolvedValue(folderFixture); - vi.spyOn(AuthService.instance, 'getAuthDetails').mockResolvedValue(UserCredentialsFixture); - const deleteDriveFileStub = vi.spyOn(WebDavUtils, 'deleteOrTrashItem').mockResolvedValue(); - const replaceDriveFileStub = vi.spyOn(DriveFileService.instance, 'replaceFile').mockRejectedValue(replaceError); - const createDriveFileStub = vi.spyOn(DriveFileService.instance, 'createFile').mockResolvedValue(fileFixture); + test('when the replace fails with a 400 with another error code, then no file is created', async () => { + const limitError = newApiError(400, { data: { errorCode: 'EMPTY_FILES_LIMIT_REACHED' } }); + const { request, response, dropCacheStub, createDriveFileStub } = setupStaleReplace(limitError); - await sut.handle(request, response); + await expect(sut.handle(request, response)).rejects.toBe(limitError); - expect(response.status).toHaveBeenCalledWith(204); - expect(replaceDriveFileStub).toHaveBeenCalledOnce(); - expect(webdavLogger.warn).toHaveBeenCalledWith( - expect.stringContaining('Request failed with status code 500 (requestId: req-123)'), - ); - expect(deleteDriveFileStub).toHaveBeenCalledWith(fileFixture); - expect(createDriveFileStub).toHaveBeenCalledOnce(); + expect(dropCacheStub).not.toHaveBeenCalled(); + expect(createDriveFileStub).not.toHaveBeenCalled(); + expect(response.status).not.toHaveBeenCalled(); + }); }); - test('when replacing an existing file is blocked for the CLI version, then the existing file is left untouched', async () => { + test('when the file found at the destination is trashed, then the server creates a new one', async () => { const requestedFileResource: WebDavRequestedResource = getRequestedFileResource(); const requestedParentFolderResource: WebDavRequestedResource = getRequestedFolderResource({ parentFolder: '/', folderName: '', }); const folderFixture = newFolderItem({ name: requestedParentFolderResource.name }); - const fileFixture = newFileItem({ folderUuid: folderFixture.uuid, size: 0, fileId: undefined }); + const trashedFile = newFileItem({ + folderUuid: folderFixture.uuid, + size: 0, + fileId: undefined, + status: FileStatus.TRASHED, + }); + const createdFile = newFileItem({ folderUuid: folderFixture.uuid, size: 0, fileId: undefined }); const request = createWebDavRequestFixture({ method: 'PUT', url: requestedFileResource.url, @@ -272,21 +382,100 @@ describe('PUT request handler', () => { const response = createWebDavResponseFixture({ status: vi.fn().mockReturnValue({ send: vi.fn() }), }); - const versionError = newClientVersionUnsupportedError(); vi.spyOn(WebDavUtils, 'getRequestedResource') .mockResolvedValueOnce(requestedFileResource) .mockResolvedValueOnce(requestedParentFolderResource); - vi.spyOn(WebDavUtils, 'getDriveItemFromResource').mockResolvedValueOnce(fileFixture); + vi.spyOn(WebDavUtils, 'getDriveItemFromResource').mockResolvedValueOnce(trashedFile); vi.spyOn(WebDavUtils, 'getDriveFolderFromResource').mockResolvedValue(folderFixture); vi.spyOn(AuthService.instance, 'getAuthDetails').mockResolvedValue(UserCredentialsFixture); - const deleteDriveFileStub = vi.spyOn(WebDavUtils, 'deleteOrTrashItem').mockResolvedValue(); - vi.spyOn(DriveFileService.instance, 'replaceFile').mockRejectedValue(versionError); - const createDriveFileStub = vi.spyOn(DriveFileService.instance, 'createFile').mockResolvedValue(fileFixture); + const replaceDriveFileStub = vi.spyOn(DriveFileService.instance, 'replaceFile'); + const createDriveFileStub = vi.spyOn(DriveFileService.instance, 'createFile').mockResolvedValue(createdFile); - await expect(sut.handle(request, response)).rejects.toBe(versionError); + await sut.handle(request, response); - expect(deleteDriveFileStub).not.toHaveBeenCalled(); - expect(createDriveFileStub).not.toHaveBeenCalled(); + expect(replaceDriveFileStub).not.toHaveBeenCalled(); + expect(createDriveFileStub).toHaveBeenCalledOnce(); + expect(response.status).toHaveBeenCalledWith(201); + }); + + describe('when creating a new file conflicts', () => { + const setupCreateConflict = (createError: unknown, existing?: ReturnType) => { + const requestedFileResource: WebDavRequestedResource = getRequestedFileResource(); + const requestedParentFolderResource: WebDavRequestedResource = getRequestedFolderResource({ + parentFolder: '/', + folderName: '', + }); + const folderFixture = newFolderItem({ name: requestedParentFolderResource.name }); + const request = createWebDavRequestFixture({ + method: 'PUT', + url: requestedFileResource.url, + headers: { 'content-length': '0' }, + }); + const response = createWebDavResponseFixture({ + status: vi.fn().mockReturnValue({ send: vi.fn() }), + }); + + vi.spyOn(WebDavUtils, 'getRequestedResource') + .mockResolvedValueOnce(requestedFileResource) + .mockResolvedValueOnce(requestedParentFolderResource); + vi.spyOn(WebDavUtils, 'getDriveItemFromResource').mockResolvedValueOnce(existing); + vi.spyOn(WebDavUtils, 'getDriveFolderFromResource').mockResolvedValue(folderFixture); + vi.spyOn(AuthService.instance, 'getAuthDetails').mockResolvedValue(UserCredentialsFixture); + const dropCacheStub = vi.spyOn(DriveItemRepository.instance, 'delete').mockResolvedValue(undefined); + const forgetFileWriteSpy = vi.spyOn(DriveItemService.instance, 'forgetFileWrite'); + vi.spyOn(DriveFileService.instance, 'createFile').mockRejectedValue(createError); + + return { request, response, requestedFileResource, dropCacheStub, forgetFileWriteSpy }; + }; + + test('when the file found was trashed and the create conflicts, then its uuid is dropped and the client is asked to retry', async () => { + const trashed = newFileItem({ uuid: 'trashed-uuid', status: FileStatus.TRASHED }); + const { request, response, requestedFileResource, dropCacheStub, forgetFileWriteSpy } = setupCreateConflict( + newApiError(409, { data: { message: 'A file with this name already exists in this location' } }), + trashed, + ); + + await expect(sut.handle(request, response)).rejects.toBeInstanceOf(ServiceUnavailableError); + + expect(dropCacheStub).toHaveBeenCalledExactlyOnceWith(['trashed-uuid']); + expect(forgetFileWriteSpy).toHaveBeenCalledExactlyOnceWith(requestedFileResource.url, 'trashed-uuid'); + expect(response.status).not.toHaveBeenCalled(); + }); + + test('when a concurrent PUT wrote the file first, then its cache row and remembered write survive the 409', async () => { + const { request, response, requestedFileResource, dropCacheStub } = setupCreateConflict(newApiError(409)); + const winner = newFileItem({ uuid: 'winner-uuid' }); + DriveItemService.instance.rememberFileWrite(requestedFileResource.url, winner); + + await expect(sut.handle(request, response)).rejects.toBeInstanceOf(ServiceUnavailableError); + + expect(dropCacheStub).not.toHaveBeenCalled(); + vi.spyOn(DriveItemRepository.instance, 'getByPath').mockResolvedValue( + new DriveItemBD({ + uuid: winner.uuid, + path: requestedFileResource.url, + type: 'file', + createdAt: new Date(), + updatedAt: new Date(), + }), + ); + vi.spyOn(DriveFileService.instance, 'getFileMetadata').mockRejectedValue(newApiError(404)); + vi.spyOn(DriveFileService.instance, 'getFileMetadataByPath').mockRejectedValue(newApiError(404)); + await expect(DriveItemService.instance.getFileByPath(requestedFileResource.url)).resolves.toBe(winner); + }); + + test.each([404, 500])( + 'when the create fails with %i, then it passes through and the cache is kept', + async (status) => { + const createError = newApiError(status); + const { request, response, dropCacheStub, forgetFileWriteSpy } = setupCreateConflict(createError); + + await expect(sut.handle(request, response)).rejects.toBe(createError); + + expect(dropCacheStub).not.toHaveBeenCalled(); + expect(forgetFileWriteSpy).not.toHaveBeenCalled(); + }, + ); }); });