mirror of
https://github.com/certd/certd.git
synced 2025-11-25 09:10:11 +08:00
perf: 优化宝塔网站证书在并发部署时导致nginx配置文件错乱的问题
This commit is contained in:
@@ -17,6 +17,7 @@
|
||||
"compile": "tsc --skipLibCheck --watch"
|
||||
},
|
||||
"dependencies": {
|
||||
"async-lock": "^1.4.1",
|
||||
"axios": "^1.7.2",
|
||||
"dayjs": "^1.11.7",
|
||||
"http-proxy-agent": "^7.0.2",
|
||||
|
||||
@@ -1,46 +1,17 @@
|
||||
import { logger, utils } from './index.js';
|
||||
import { logger } from "./index.js";
|
||||
// @ts-ignore
|
||||
import AsyncLock from "async-lock";
|
||||
|
||||
export class Locker {
|
||||
locked: Record<string, any> = {};
|
||||
private asyncLocker: AsyncLock;
|
||||
|
||||
async execute(lockStr: string, callback: any) {
|
||||
await this.lock(lockStr);
|
||||
const timeoutId = setTimeout(() => {
|
||||
logger.warn('Lock timeout,自动解锁', lockStr);
|
||||
this.unlock(lockStr);
|
||||
}, 20000);
|
||||
try {
|
||||
return await callback();
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
this.unlock(lockStr);
|
||||
}
|
||||
constructor() {
|
||||
this.asyncLocker = new AsyncLock();
|
||||
}
|
||||
|
||||
async lock(str: string) {
|
||||
const isLocked = this.isLocked(str);
|
||||
if (isLocked) {
|
||||
let count = 0;
|
||||
while (true) {
|
||||
await utils.sleep(100);
|
||||
if (!this.isLocked(str)) {
|
||||
break;
|
||||
}
|
||||
count++;
|
||||
if (count > 20) {
|
||||
throw new Error('Lock timeout');
|
||||
}
|
||||
}
|
||||
}
|
||||
this.locked[str] = true;
|
||||
}
|
||||
|
||||
unlock(str: string) {
|
||||
delete this.locked[str];
|
||||
}
|
||||
|
||||
isLocked(str: string) {
|
||||
return this.locked[str] ?? false;
|
||||
async execute(lockStr: string, callback: any, options?: { timeout?: number }) {
|
||||
const timeout = options?.timeout ?? 20000;
|
||||
return this.asyncLocker.acquire(lockStr, callback, { timeout });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
14
packages/core/basic/test.mjs
Normal file
14
packages/core/basic/test.mjs
Normal file
@@ -0,0 +1,14 @@
|
||||
import { random } from "lodash-es";
|
||||
import { locker } from "./dist/utils/util.lock.js";
|
||||
|
||||
async function testLocker() {
|
||||
for (let i = 0; i < 10; i++) {
|
||||
await locker.execute("test", async () => {
|
||||
console.log("test", i);
|
||||
await new Promise(resolve => setTimeout(resolve, Math.random() * 1000));
|
||||
throw new Error("test error");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await testLocker();
|
||||
Reference in New Issue
Block a user