From b38367f09f58b2670dd945a349ffa1f84c2a875a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E5=B9=BF?= Date: Tue, 18 Nov 2025 14:54:37 +0800 Subject: [PATCH] =?UTF-8?q?feat(lock-client):=20=E9=87=8D=E6=9E=84?= =?UTF-8?q?=E9=94=81=E8=AF=B7=E6=B1=82=E7=AE=A1=E7=90=86=E6=9C=BA=E5=88=B6?= =?UTF-8?q?=E4=BB=A5=E6=94=AF=E6=8C=81=E5=B9=B6=E5=8F=91=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将单一 requestId 字段替换为 Map 类型的 requests 字段,用于存储多个未完成的锁请求及其对应的 resolve 函数。注释掉原有 isLocked 检查逻辑,允许更灵活的锁控制流程。 fix(namedpipe): 修复父类构造函数参数传递错误 在 NamedPipeRWLock 构造函数中调用 super() 时补充缺失的 resource 参数,确保父类正确初始化。 feat(lock-server): 改进读锁客户端标识以增强唯一性 更新 readers 集合中的元素格式,从 clientId 变为 `${clientId}_${requestId}`,提高锁持有者标识的唯一性和可追踪性。 --- lock-client.js | 12 +++++++----- lock-client.namedpipe.js | 2 +- lock.js | 4 ++-- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/lock-client.js b/lock-client.js index 645e020..e593ad1 100644 --- a/lock-client.js +++ b/lock-client.js @@ -33,7 +33,7 @@ class LockClient extends EventEmitter { this.maxRetries = options.maxRetries || 5; this.socket = null; - this.requestId = null; + this.requests = new Map(); this.isLocked = false; this.lockType = null; this.timeoutHandle = null; @@ -74,12 +74,14 @@ class LockClient extends EventEmitter { await this.ensureConnected(); return new Promise((resolve, reject) => { - if (this.isLocked) { - reject(new Error('Lock already held')); - return; - } + // if (this.isLocked) { + // reject(new Error('Lock already held')); + // return; + // } this.requestId = uuidv4(); + this.requests.set(this.requestId, resolve) + this.lockType = type; // 发送锁请求 diff --git a/lock-client.namedpipe.js b/lock-client.namedpipe.js index 78d098a..04ca790 100644 --- a/lock-client.namedpipe.js +++ b/lock-client.namedpipe.js @@ -19,7 +19,7 @@ class NamedPipeRWLock extends LockClient { * @param {number} options.maxRetries - 最大重连次数,默认5 */ constructor(resource, options = {}) { - super(options); + super(resource, options); this.resource = resource; this.pipePath = options.connect.pipePath; } diff --git a/lock.js b/lock.js index abf3958..70ddf1a 100644 --- a/lock.js +++ b/lock.js @@ -82,7 +82,7 @@ class LockServer { handleReadLock(clientId, resource, requestId, lock) { if (!lock.writer) { // 可以立即获取读锁 - lock.readers.add(clientId); + lock.readers.add(`${clientId}_${requestId}`); this.sendToClient(clientId, { type: 'lockGranted', requestId, @@ -108,7 +108,7 @@ class LockServer { if (lock.readers.size === 0 && !lock.writer) { // 可以立即获取写锁 lock.writer = clientId; - this.sendToClient(clientId, { + this.sendToClient(`${clientId}_${requestId}`, { type: 'lockGranted', requestId, resource,