Исправить восстановление сессии после переподключения WS

This commit is contained in:
AidarKC
2026-11-15 14:35:28 +03:00
parent 70540ff041
commit e01da7ae87
4 changed files with 51 additions and 4 deletions
+32 -3
View File
@@ -64,6 +64,22 @@ export class WsJsonClient {
this.pending = new Map();
this.openPromise = null;
this.eventListeners = new Map();
this.requestGuard = null;
this.connectionGeneration = 0;
this.sessionReadyGeneration = 0;
}
setRequestGuard(guard) {
this.requestGuard = typeof guard === 'function' ? guard : null;
}
markSessionReady() {
this.sessionReadyGeneration = this.connectionGeneration;
}
isSessionReady() {
return this.connectionGeneration > 0
&& this.sessionReadyGeneration === this.connectionGeneration;
}
async open() {
@@ -82,6 +98,7 @@ export class WsJsonClient {
this.openPromise = new Promise((resolve, reject) => {
const ws = new WebSocket(this.url);
this.ws = ws;
this.connectionGeneration += 1;
ws.addEventListener('open', () => {
resolve();
@@ -97,7 +114,10 @@ export class WsJsonClient {
}, { once: true });
ws.addEventListener('close', () => {
this.failPending(t('remaining.websocket.websocket_connection_closed'));
if (this.ws === ws) {
this.ws = null;
this.failPending(t('remaining.websocket.websocket_connection_closed'));
}
});
ws.addEventListener('message', (event) => {
@@ -111,7 +131,14 @@ export class WsJsonClient {
}
async request(op, payload = {}, timeoutMs = DEFAULT_TIMEOUT_MS) {
await this.open();
for (let attempt = 0; attempt < 2; attempt += 1) {
await this.open();
if (this.requestGuard) await this.requestGuard(op);
if (this.ws && this.ws.readyState === WebSocket.OPEN) break;
}
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
throw new Error(t('remaining.websocket.websocket_connection_closed'));
}
const requestId = createRequestId(op);
const body = { op, requestId, payload };
@@ -149,8 +176,10 @@ export class WsJsonClient {
close() {
if (this.ws) {
this.ws.close();
const ws = this.ws;
this.ws = null;
this.failPending(t('remaining.websocket.websocket_connection_closed'));
ws.close();
}
}