🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(file): 文件存储探测移到数据库事务外,避免占用连接时做网络请求 (#22385)
Mochaea1bd10691d6
diff --git a/apps/server/src/routers/lambda/file/upload.globalHash.test.ts b/apps/server/src/routers/lambda/file/upload.globalHash.test.tsnew file mode 100644index 00000000000..3aac3fe4080--- /dev/null+++ b/apps/server/src/routers/lambda/file/upload.globalHash.test.ts@@ -0,0 +1,164 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { uploadRouter } from './upload';++const mocks = vi.hoisted(() => {+ const transaction = {};+ const state = { inTransaction: false };+ return {+ checkHash: vi.fn(),+ create: vi.fn(),+ getFileAccessUrl: vi.fn(),+ getFileMetadata: vi.fn(),+ serverDB: {+ transaction: vi.fn(async (callback: (trx: unknown) => unknown) => {+ state.inTransaction = true;+ try {+ return await callback(transaction);+ } finally {+ state.inTransaction = false;+ }+ }),+ },+ state,+ transaction,+ updateGlobalFile: vi.fn(),+ };+});++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => mocks.serverDB) }));+vi.mock('@/business/server/lambda-routers/file', () => ({+ businessFileUploadCheck: vi.fn(),+}));+vi.mock('@/database/models/asyncTask', () => ({ AsyncTaskModel: vi.fn() }));+vi.mock('@/database/models/chunk', () => ({ ChunkModel: vi.fn() }));+vi.mock('@/database/models/document', () => ({ DocumentModel: vi.fn() }));+vi.mock('@/database/models/knowledgeBase', () => ({ KnowledgeBaseModel: vi.fn() }));+vi.mock('@/database/repositories/knowledge', () => ({ KnowledgeRepo: vi.fn() }));+vi.mock('@/server/services/document', () => ({ DocumentService: vi.fn() }));+vi.mock('@/database/models/file', () => ({+ FileModel: vi.fn(function () {+ return {+ checkHash: mocks.checkHash,+ create: mocks.create,+ updateGlobalFile: mocks.updateGlobalFile,+ };+ }),+}));+vi.mock('@/server/services/file', () => ({+ FileService: vi.fn(function () {+ return {+ getFileAccessUrl: mocks.getFileAccessUrl,+ getFileMetadata: mocks.getFileMetadata,+ };+ }),+}));+vi.mock('@/server/services/fileUpload', () => ({+ FileUploadService: vi.fn(function () {+ return {+ findLatest: vi.fn().mockResolvedValue(undefined),+ hasAnyLiveSession: vi.fn().mockResolvedValue(false),+ };+ }),+}));++const upload = {+ fileType: 'text',+ hash: 'test-hash',+ metadata: { path: 'new/path.txt' },+ name: 'test.txt',+ size: 100,+ url: 'new/path.txt',+};++const caller = () =>+ uploadRouter.createCaller({ userId: 'user-1' } as Parameters<+ typeof uploadRouter.createCaller+ >[0]);++/**+ * An existing hash row whose stored object is gone follows a fresh upload of the same bytes, so+ * dedup checks stop resolving to the dead key. The storage probe deciding that runs before the+ * record transaction, and only applies to the row it probed.+ */+describe('uploadRouter.createFile global hash pointer', () => {+ const probedInTransaction: boolean[] = [];++ beforeEach(() => {+ vi.clearAllMocks();+ probedInTransaction.length = 0;+ mocks.create.mockResolvedValue({ id: 'new-file-id' });+ mocks.getFileAccessUrl.mockImplementation(async ({ id }: { id: string }) => {+ expect(mocks.state.inTransaction).toBe(false);+ return `https://lobehub.com/f/${id}`;+ });+ // The uploaded object itself is present; `old/path.txt` is the hash row's previous object.+ mocks.getFileMetadata.mockImplementation(async (url: string) => {+ if (url !== 'old/path.txt') return { contentLength: 100, contentType: 'text/plain' };+ probedInTransaction.push(mocks.state.inTransaction);+ throw new Error('NoSuchKey');+ });+ vi.spyOn(console, 'error').mockImplementation(() => {});+ });++ afterEach(() => {+ vi.mocked(console.error).mockRestore();+ });++ it('moves the pointer of a missing object to the upload, probing outside the transaction', async () => {+ mocks.checkHash.mockResolvedValue({ isExist: true, url: 'old/path.txt' });++ await caller().createFile(upload);++ expect(probedInTransaction).toEqual([false]);+ expect(mocks.checkHash).toHaveBeenLastCalledWith('test-hash', mocks.transaction);+ expect(mocks.updateGlobalFile).toHaveBeenCalledWith(+ 'test-hash',+ { metadata: { path: 'new/path.txt' }, url: 'new/path.txt' },+ mocks.transaction,+ );+ expect(mocks.create).toHaveBeenCalledWith(+ expect.objectContaining({ fileHash: 'test-hash', url: 'new/path.txt' }),+ false,+ mocks.transaction,+ );+ });++ it('keeps the pointer while its object is still available', async () => {+ mocks.checkHash.mockResolvedValue({ isExist: true, url: 'old/path.txt' });+ mocks.getFileMetadata.mockResolvedValue({ contentLength: 100, contentType: 'text/plain' });++ await caller().createFile(upload);++ expect(mocks.updateGlobalFile).not.toHaveBeenCalled();+ expect(mocks.create).toHaveBeenCalledWith(+ expect.objectContaining({ fileHash: 'test-hash', url: 'new/path.txt' }),+ false,+ mocks.transaction,+ );+ });++ it('does not apply a probe of a pointer that another upload replaced meanwhile', async () => {+ mocks.checkHash+ .mockResolvedValueOnce({ isExist: true, url: 'old/path.txt' })+ .mockResolvedValueOnce({ isExist: true, url: 'other/path.txt' });++ await caller().createFile(upload);++ expect(mocks.updateGlobalFile).not.toHaveBeenCalled();+ expect(mocks.create).toHaveBeenCalledWith(expect.anything(), false, mocks.transaction);+ });++ it('recreates the global row when the probed hash row was removed meanwhile', async () => {+ mocks.checkHash+ .mockResolvedValueOnce({ isExist: true, url: 'old/path.txt' })+ .mockResolvedValueOnce({ isExist: false });++ await caller().createFile(upload);++ expect(mocks.updateGlobalFile).not.toHaveBeenCalled();+ // files.file_hash references global_files, so the row must exist when the file row lands.+ expect(mocks.create).toHaveBeenCalledWith(expect.anything(), true, mocks.transaction);+ });+});diff --git a/apps/server/src/routers/lambda/file/upload.ts b/apps/server/src/routers/lambda/file/upload.tsindex 44c0ae52dd3..f3d974c37f2 100644--- a/apps/server/src/routers/lambda/file/upload.ts+++ b/apps/server/src/routers/lambda/file/upload.ts@@ -253,19 +253,20 @@ export const uploadRouter = router({});}- const { id } = await ctx.serverDB.transaction(async (trx) => {- let shouldRefreshGlobalFile = false;- if (isExist && existingFile.url && existingFile.url !== input.url) {- shouldRefreshGlobalFile = !(await isStoredObjectAvailable(- ctx.fileService,- existingFile.url,- ));- }+ // Storage I/O must finish before the transaction borrows a pooled connection.+ const missingHashUrl =+ isExist &&+ existingFile.url &&+ existingFile.url !== input.url &&+ !(await isStoredObjectAvailable(ctx.fileService, existingFile.url))+ ? existingFile.url+ : undefined;- if (shouldRefreshGlobalFile) {- // A user may re-upload the same bytes after the old object key was- // removed. Keep the global hash pointer on the newly uploaded object so- // future dedup checks do not resolve back to the stale key.+ const { id } = await ctx.serverDB.transaction(async (trx) => {+ // Apply a missing-object probe only to the pointer it observed, and decide whether to+ // insert the global row from the current mapping rather than the pre-transaction read.+ const currentFile = await ctx.fileModel.checkHash(input.hash!, trx);+ if (missingHashUrl && currentFile.isExist && currentFile.url === missingHashUrl) {await ctx.fileModel.updateGlobalFile(input.hash!,{@@ -295,7 +296,7 @@ export const uploadRouter = router({...(resolvedVisibility ? { visibility: resolvedVisibility } : {}),},// if the file is not exist in global file, create a new one- !isExist,+ !currentFile.isExist,trx,);diff --git a/apps/server/src/services/file/__tests__/index.test.ts b/apps/server/src/services/file/__tests__/index.test.tsindex a8e8bc6d802..180ee684949 100644--- a/apps/server/src/services/file/__tests__/index.test.ts+++ b/apps/server/src/services/file/__tests__/index.test.ts@@ -54,7 +54,8 @@ vi.mock('@lobechat/utils', async (importOriginal) => {describe('FileService', () => {let service: FileService;- const mockDb = { transaction: (run: (tx: unknown) => unknown) => run({}) } as any;+ const recordTx = { name: 'record-tx' };+ const mockDb = { transaction: (run: (tx: unknown) => unknown) => run(recordTx) } as any;const mockUserId = 'test-user';let mockFileModel: any;let mockTempManager: any;@@ -389,7 +390,7 @@ describe('FileService', () => {}),}),expect.any(Boolean),- undefined,+ recordTx,);});@@ -417,7 +418,7 @@ describe('FileService', () => {}),}),expect.any(Boolean),- undefined,+ recordTx,);});});@@ -584,7 +585,7 @@ describe('FileService', () => {fileHash: 'new-hash',}),true, // insertToGlobalFiles = true when hash doesn't exist- undefined,+ recordTx,);});@@ -605,7 +606,7 @@ describe('FileService', () => {fileHash: 'existing-hash',}),false, // insertToGlobalFiles = false when hash exists- undefined,+ recordTx,);expect(mockFileModel.updateGlobalFile).not.toHaveBeenCalled();});@@ -631,7 +632,7 @@ describe('FileService', () => {metadata: { dirname: 'new', filename: 'test.txt', path: 'new/path.txt' },url: 'new/path.txt',},- undefined,+ recordTx,);expect(mockFileModel.create).toHaveBeenCalledWith(expect.objectContaining({@@ -639,7 +640,7 @@ describe('FileService', () => {url: 'new/path.txt',}),false,- undefined,+ recordTx,);consoleSpy.mockRestore();});@@ -668,7 +669,7 @@ describe('FileService', () => {url: 'new/path.txt',}),false,- undefined,+ recordTx,);});});diff --git a/apps/server/src/services/file/index.recordTransaction.test.ts b/apps/server/src/services/file/index.recordTransaction.test.tsnew file mode 100644index 00000000000..9147f8ae703--- /dev/null+++ b/apps/server/src/services/file/index.recordTransaction.test.ts@@ -0,0 +1,182 @@+import type { LobeChatDatabase, Transaction } from '@lobechat/database';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { FileService } from './index';++const mocks = vi.hoisted(() => ({+ checkHash: vi.fn(),+ create: vi.fn(),+ deleteFile: vi.fn(),+ getFileMetadata: vi.fn(),+ state: { inTransaction: false },+ transaction: { name: 'record-tx' },+ updateGlobalFile: vi.fn(),+ uploadBuffer: vi.fn(),+}));++vi.mock('@/config/db', () => ({ serverDBEnv: { REMOVE_GLOBAL_FILE: false } }));+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://lobehub.com' } }));+vi.mock('@/database/models/file', () => ({+ FileModel: vi.fn(function () {+ return {+ checkHash: mocks.checkHash,+ create: mocks.create,+ updateGlobalFile: mocks.updateGlobalFile,+ };+ }),+}));+vi.mock('./impls', () => ({+ createFileServiceModule: () => ({+ deleteFile: mocks.deleteFile,+ getFileMetadata: mocks.getFileMetadata,+ uploadBuffer: mocks.uploadBuffer,+ }),+}));++const upload = {+ fileHash: 'existing-hash',+ fileType: 'image/png',+ metadata: { path: 'images/new.png' },+ name: 'new.png',+ size: 5,+ url: 'images/new.png',+};++describe('FileService record transaction', () => {+ let service: FileService;+ const probedInTransaction: boolean[] = [];++ beforeEach(() => {+ vi.resetAllMocks();+ mocks.state.inTransaction = false;+ probedInTransaction.length = 0;+ const db = {+ transaction: async (run: (trx: unknown) => Promise<unknown>) => {+ mocks.state.inTransaction = true;+ try {+ return await run(mocks.transaction);+ } finally {+ mocks.state.inTransaction = false;+ }+ },+ } as unknown as LobeChatDatabase;+ service = new FileService(db, 'user-1');+ mocks.checkHash.mockResolvedValue({ isExist: true, url: 'images/old.png' });+ mocks.create.mockResolvedValue({ id: 'file-id' });+ mocks.uploadBuffer.mockResolvedValue({ key: upload.url });+ mocks.getFileMetadata.mockImplementation(async () => {+ probedInTransaction.push(mocks.state.inTransaction);+ throw new Error('NoSuchKey');+ });+ vi.spyOn(console, 'error').mockImplementation(() => {});+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ const write = (entry: string, beforeRecord?: (trx: Transaction) => Promise<void>) =>+ entry === 'createFileRecord'+ ? service.createFileRecord(upload)+ : service.uploadFromBuffer(Buffer.from('image'), upload.fileType, upload.url, beforeRecord);++ describe.each(['createFileRecord', 'uploadFromBuffer'])('%s', (entry) => {+ it('probes before opening the transaction and writes on one transaction', async () => {+ await write(entry);++ expect(probedInTransaction).toEqual([false]);+ expect(mocks.checkHash).toHaveBeenNthCalledWith(1, expect.any(String));+ expect(mocks.checkHash).toHaveBeenLastCalledWith(expect.any(String), mocks.transaction);+ expect(mocks.updateGlobalFile).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ url: upload.url }),+ mocks.transaction,+ );+ expect(mocks.create).toHaveBeenCalledWith(expect.anything(), false, mocks.transaction);+ });++ it('keeps an available global object', async () => {+ mocks.getFileMetadata.mockResolvedValue({ contentLength: 5 });++ await write(entry);++ expect(mocks.updateGlobalFile).not.toHaveBeenCalled();+ expect(mocks.create).toHaveBeenCalledWith(expect.anything(), false, mocks.transaction);+ });++ it('does not overwrite a hash pointer replaced after the probe', async () => {+ mocks.checkHash+ .mockResolvedValueOnce({ isExist: true, url: 'images/old.png' })+ .mockResolvedValueOnce({ isExist: true, url: 'images/other.png' });++ await write(entry);++ expect(mocks.getFileMetadata).toHaveBeenCalledWith('images/old.png');+ expect(mocks.updateGlobalFile).not.toHaveBeenCalled();+ expect(mocks.create).toHaveBeenCalledWith(expect.anything(), false, mocks.transaction);+ });++ it('recreates a global row removed after the probe', async () => {+ mocks.checkHash+ .mockResolvedValueOnce({ isExist: true, url: 'images/old.png' })+ .mockResolvedValueOnce({ isExist: false });++ await write(entry);++ expect(mocks.updateGlobalFile).not.toHaveBeenCalled();+ expect(mocks.create).toHaveBeenCalledWith(expect.anything(), true, mocks.transaction);+ });++ it('resolves the access URL after the transaction commits', async () => {+ const resolvedInTransaction: boolean[] = [];+ vi.spyOn(service, 'getFileAccessUrl').mockImplementation(async () => {+ resolvedInTransaction.push(mocks.state.inTransaction);+ return 'https://lobehub.com/f/file-id';+ });++ const result = await write(entry);++ expect(resolvedInTransaction).toEqual([false]);+ expect(result).toMatchObject({ fileId: 'file-id', url: 'https://lobehub.com/f/file-id' });+ });+ });++ it('runs the admission check inside the same record transaction', async () => {+ const beforeRecord = vi.fn(async (trx: Transaction) => {+ expect(mocks.state.inTransaction).toBe(true);+ expect(trx).toBe(mocks.transaction);+ expect(mocks.create).not.toHaveBeenCalled();+ });++ await write('uploadFromBuffer', beforeRecord);++ expect(beforeRecord).toHaveBeenCalledTimes(1);+ expect(mocks.create).toHaveBeenCalledWith(expect.anything(), false, mocks.transaction);+ });++ it.each(['admission', 'hash read', 'record write'])(+ 'removes the upload on %s failure',+ async (stage) => {+ const error = new Error(`${stage} failed`);+ const beforeRecord = vi.fn(async () => {+ if (stage === 'admission') throw error;+ });+ if (stage === 'hash read') mocks.checkHash.mockRejectedValueOnce(error);+ if (stage === 'record write') mocks.create.mockRejectedValueOnce(error);++ await expect(write('uploadFromBuffer', beforeRecord)).rejects.toBe(error);++ expect(mocks.deleteFile).toHaveBeenCalledWith(upload.url);+ },+ );++ it('preserves the committed object when access URL generation fails', async () => {+ const error = new Error('URL generation failed');+ vi.spyOn(service, 'getFileAccessUrl').mockRejectedValue(error);++ await expect(write('uploadFromBuffer')).rejects.toBe(error);++ expect(mocks.create).toHaveBeenCalledTimes(1);+ expect(mocks.deleteFile).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/file/index.ts b/apps/server/src/services/file/index.tsindex 6217b2dbbf4..9113df1b248 100644--- a/apps/server/src/services/file/index.ts+++ b/apps/server/src/services/file/index.ts@@ -23,6 +23,18 @@ export interface FileAccessUrlItem {url?: string | null;}+interface FileRecordParams {+ fileHash: string;+ fileType: string;+ id?: string;+ metadata?: Record<string, unknown>;+ name: string;+ size: number;+ source?: FileItem['source'];+ url: string;+ visibility?: FileItem['visibility'];+}+/*** File service class* Provides file operation services using a modular implementation approach@@ -234,65 +246,62 @@ export class FileService {* @returns File record and proxy URL*/public async createFileRecord(- params: {- fileHash: string;- fileType: string;- id?: string;- metadata?: Record<string, unknown>;- name: string;- size: number;- source?: FileItem['source'];- url: string;- visibility?: FileItem['visibility'];- },- trx?: Transaction,+ params: FileRecordParams,): Promise<{ fileId: string; url: string }> {- // Check if hash already exists in globalFiles. Every query here must go through `trx`:- // callers such as `uploadFromBuffer` hold the owner's row lock in that transaction, and- // a read on the shared pool would wait for a connection the lock waiters already hold.- const existingFile = await this.fileModel.checkHash(params.fileHash, trx);- const { isExist } = existingFile;-- let shouldRefreshGlobalFile = false;- if (isExist && existingFile.url && existingFile.url !== params.url) {- shouldRefreshGlobalFile = !(await this.isStoredFileAvailable(existingFile.url));- }+ const id = await this.writeFileRecord(params);++ return {+ fileId: id,+ url: await this.getFileAccessUrl({ id, url: params.url }),+ };+ }- if (shouldRefreshGlobalFile) {- // Keep global hash dedup usable when the same file is uploaded again to a- // fresh object key after the previous storage object has been removed.- await this.fileModel.updateGlobalFile(- params.fileHash,+ /** Probe storage before borrowing a connection; keep all record queries on that transaction. */+ private async writeFileRecord(+ params: FileRecordParams,+ beforeRecord?: (trx: Transaction) => Promise<void>,+ ): Promise<string> {+ const observed = await this.fileModel.checkHash(params.fileHash);+ const missingHashUrl =+ observed.isExist &&+ observed.url &&+ observed.url !== params.url &&+ !(await this.isStoredFileAvailable(observed.url))+ ? observed.url+ : undefined;++ const { id } = await this.db.transaction(async (trx) => {+ await beforeRecord?.(trx);++ // The probe describes only the URL it observed. Re-read on the record transaction so a+ // replaced pointer is preserved and a deleted global row is reinserted before the file row.+ const current = await this.fileModel.checkHash(params.fileHash, trx);+ if (missingHashUrl && current.isExist && current.url === missingHashUrl) {+ await this.fileModel.updateGlobalFile(+ params.fileHash,+ { metadata: params.metadata, url: params.url },+ trx,+ );+ }++ return this.fileModel.create({+ fileHash: params.fileHash,+ fileType: params.fileType,+ id: params.id,metadata: params.metadata,+ name: params.name,+ size: params.size,+ source: params.source,url: params.url,+ visibility: params.visibility,},+ !current.isExist,trx,);- }-- // Create database record- // If hash doesn't exist, also create globalFiles record- const { id } = await this.fileModel.create(- {- fileHash: params.fileHash,- fileType: params.fileType,- id: params.id, // Use custom ID if provided- metadata: params.metadata,- name: params.name,- size: params.size,- source: params.source,- url: params.url,- visibility: params.visibility,- },- !isExist, // insertToGlobalFiles- trx,- );+ });- return {- fileId: id,- url: await this.getFileAccessUrl({ id, url: params.url }),- };+ return id;}/**@@ -468,33 +477,28 @@ export class FileService {const filename = parts.pop() || name;const dirname = parts.join('/');- const { fileId: createdId, url } = await this.db- .transaction(async (trx) => {- await beforeRecord?.(trx);-- return this.createFileRecord(- {- fileHash: hash,- fileType: mimeType,- id: fileId,- metadata: {- date: new Date().toISOString().slice(0, 10),- dirname,- filename,- path: pathname,- },- name,- size,- url: key,- ...recordOptions,- },- trx,- );- })- .catch(async (error) => {- await this.deleteFile(key).catch(() => {});- throw error;- });+ const createdId = await this.writeFileRecord(+ {+ fileHash: hash,+ fileType: mimeType,+ id: fileId,+ metadata: {+ date: new Date().toISOString().slice(0, 10),+ dirname,+ filename,+ path: pathname,+ },+ name,+ size,+ url: key,+ ...recordOptions,+ },+ beforeRecord,+ ).catch(async (error) => {+ await this.deleteFile(key).catch(() => {});+ throw error;+ });+ const url = await this.getFileAccessUrl({ id: createdId, url: key });return { fileId: createdId, key, url };}