SHA256
Исправить восстановление сессии после переподключения WS
This commit is contained in:
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user