fix(lock): 解决解锁时未正确传递 requestId 的问题

在处理 unlock 消息时,缺少了 requestId 参数的传递,
导致无法准确释放对应的读锁或写锁。
同时增加 _releaseReadLocks 方法以支持按 requestId 精确释放读锁。
```
This commit is contained in:
程广 2025-11-18 15:03:57 +08:00
parent b38367f09f
commit 48c66fa72e
1 changed files with 21 additions and 5 deletions

26
lock.js
View File

@ -64,7 +64,7 @@ class LockServer {
this.handleWriteLock(clientId, resource, requestId, lock); this.handleWriteLock(clientId, resource, requestId, lock);
break; break;
case 'unlock': case 'unlock':
this.handleUnlock(clientId, resource, lock); this.handleUnlock(clientId, resource,requestId, lock);
break; break;
default: default:
this.sendError(clientId, `Unknown message type: ${type}`); this.sendError(clientId, `Unknown message type: ${type}`);
@ -122,24 +122,40 @@ class LockServer {
} }
} }
_releaseReadLocks(lock, lockId){
if(lock.readers.has(lockId)){
lock.readers.delete(lockId);
this._logger.debug(`Read lock released by ${lockId} for ${resource}`);
return 1
}
let ret = 0
for(let lockId of lock.readers){
if(lockId.startsWith(lockId)){
lock.readers.delete(lockId)
ret += 1
}
}
return ret
}
/** /**
* 处理解锁请求 * 处理解锁请求
* @param {string} clientId - 客户端标识符 * @param {string} clientId - 客户端标识符
* @param {string} resource - 资源名称 * @param {string} resource - 资源名称
* @param {Object} lock - 锁对象 * @param {Object} lock - 锁对象
*/ */
handleUnlock(clientId, resource, lock) { handleUnlock(clientId, resource, requestId,lock) {
let released = false; let released = false;
// 移除读锁 // 移除读锁
if (lock.readers.has(clientId)) { const lockId = requestId?`${clientId}_${requestId}`:clientId
lock.readers.delete(clientId); if (this._releaseReadLocks(lockId)>0) {
// lock.readers.delete(clientId);
released = true; released = true;
this._logger.debug(`Read lock released by ${clientId} for ${resource}`); this._logger.debug(`Read lock released by ${clientId} for ${resource}`);
} }
// 移除写锁 // 移除写锁
if (lock.writer === clientId) { if (lock.writer === lockId) {
lock.writer = null; lock.writer = null;
released = true; released = true;
this._logger.debug(`Write lock released by ${clientId} for ${resource}`); this._logger.debug(`Write lock released by ${clientId} for ${resource}`);