From 4fa5fa201430f14148f8f20f17c31e9355a7119a Mon Sep 17 00:00:00 2001 From: whyour Date: Thu, 16 Jan 2025 00:35:47 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=20lock=20=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E5=90=8D=E7=A7=B0=E8=A7=84=E5=88=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- back/shared/utils.ts | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/back/shared/utils.ts b/back/shared/utils.ts index 2753476b..8cd27478 100644 --- a/back/shared/utils.ts +++ b/back/shared/utils.ts @@ -1,27 +1,39 @@ import { lock } from 'proper-lockfile'; +import os from 'os'; +import path from 'path'; import { writeFile, open } from 'fs/promises'; import { fileExist } from '../config/util'; +function getUniqueLockPath(filePath: string) { + const sanitizedPath = filePath + .replace(/[<>:"/\\|?*]/g, '_') + .replace(/^_/, ''); + return path.join(os.tmpdir(), `${sanitizedPath}.ql_lock`); +} + export async function writeFileWithLock( - path: string, + filePath: string, content: string | Buffer, options: Parameters[2] = {}, ) { if (typeof options === 'string') { options = { encoding: options }; } - if (!(await fileExist(path))) { - const fileHandle = await open(path, 'w'); + if (!(await fileExist(filePath))) { + const fileHandle = await open(filePath, 'w'); fileHandle.close(); } - const release = await lock(path, { + const lockfilePath = getUniqueLockPath(filePath); + + const release = await lock(filePath, { retries: { retries: 10, factor: 2, minTimeout: 100, maxTimeout: 3000, }, + lockfilePath, }); - await writeFile(path, content, { encoding: 'utf8', ...options }); + await writeFile(filePath, content, { encoding: 'utf8', ...options }); await release(); }