aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/frontend/src/xtext/XtextWebSocketClient.ts
blob: 2ce20a54cb2848c868dcd48a08ae183849f09972 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import { nanoid } from 'nanoid';

import { getLogger } from '../utils/logger';
import { PendingTask } from '../utils/PendingTask';
import { Timer } from '../utils/Timer';
import {
  xtextWebErrorResponse,
  XtextWebRequest,
  xtextWebOkResponse,
  xtextWebPushMessage,
  XtextWebPushService,
} from './xtextMessages';
import { pongResult } from './xtextServiceResults';

const XTEXT_SUBPROTOCOL_V1 = 'tools.refinery.language.web.xtext.v1';

const WEBSOCKET_CLOSE_OK = 1000;

const RECONNECT_DELAY_MS = [200, 1000, 5000, 30_000];

const MAX_RECONNECT_DELAY_MS = RECONNECT_DELAY_MS[RECONNECT_DELAY_MS.length - 1];

const BACKGROUND_IDLE_TIMEOUT_MS = 5 * 60 * 1000;

const PING_TIMEOUT_MS = 10 * 1000;

const REQUEST_TIMEOUT_MS = 1000;

const log = getLogger('xtext.XtextWebSocketClient');

export type ReconnectHandler = () => void;

export type PushHandler = (
  resourceId: string,
  stateId: string,
  service: XtextWebPushService,
  data: unknown,
) => void;

enum State {
  Initial,
  Opening,
  TabVisible,
  TabHiddenIdle,
  TabHiddenWaiting,
  Error,
  TimedOut,
}

export class XtextWebSocketClient {
  private nextMessageId = 0;

  private connection!: WebSocket;

  private readonly pendingRequests = new Map<string, PendingTask<unknown>>();

  private readonly onReconnect: ReconnectHandler;

  private readonly onPush: PushHandler;

  private state = State.Initial;

  private reconnectTryCount = 0;

  private readonly idleTimer = new Timer(() => {
    this.handleIdleTimeout();
  }, BACKGROUND_IDLE_TIMEOUT_MS);

  private readonly pingTimer = new Timer(() => {
    this.sendPing();
  }, PING_TIMEOUT_MS);

  private readonly reconnectTimer = new Timer(() => {
    this.handleReconnect();
  });

  constructor(onReconnect: ReconnectHandler, onPush: PushHandler) {
    this.onReconnect = onReconnect;
    this.onPush = onPush;
    document.addEventListener('visibilitychange', () => {
      this.handleVisibilityChange();
    });
    this.reconnect();
  }

  private get isLogicallyClosed(): boolean {
    return this.state === State.Error || this.state === State.TimedOut;
  }

  get isOpen(): boolean {
    return this.state === State.TabVisible
      || this.state === State.TabHiddenIdle
      || this.state === State.TabHiddenWaiting;
  }

  private reconnect() {
    if (this.isOpen || this.state === State.Opening) {
      log.error('Trying to reconnect from', this.state);
      return;
    }
    this.state = State.Opening;
    const webSocketServer = window.origin.replace(/^http/, 'ws');
    const webSocketUrl = `${webSocketServer}/xtext-service`;
    this.connection = new WebSocket(webSocketUrl, XTEXT_SUBPROTOCOL_V1);
    this.connection.addEventListener('open', () => {
      if (this.connection.protocol !== XTEXT_SUBPROTOCOL_V1) {
        log.error('Unknown subprotocol', this.connection.protocol, 'selected by server');
        this.forceReconnectOnError();
      }
      if (document.visibilityState === 'hidden') {
        this.handleTabHidden();
      } else {
        this.handleTabVisibleConnected();
      }
      log.info('Connected to websocket');
      this.nextMessageId = 0;
      this.reconnectTryCount = 0;
      this.pingTimer.schedule();
      this.onReconnect();
    });
    this.connection.addEventListener('error', (event) => {
      log.error('Unexpected websocket error', event);
      this.forceReconnectOnError();
    });
    this.connection.addEventListener('message', (event) => {
      this.handleMessage(event.data);
    });
    this.connection.addEventListener('close', (event) => {
      if (this.isLogicallyClosed && event.code === WEBSOCKET_CLOSE_OK
        && this.pendingRequests.size === 0) {
        log.info('Websocket closed');
        return;
      }
      log.error('Websocket closed unexpectedly', event.code, event.reason);
      this.forceReconnectOnError();
    });
  }

  private handleVisibilityChange() {
    if (document.visibilityState === 'hidden') {
      if (this.state === State.TabVisible) {
        this.handleTabHidden();
      }
      return;
    }
    this.idleTimer.cancel();
    if (this.state === State.TabHiddenIdle || this.state === State.TabHiddenWaiting) {
      this.handleTabVisibleConnected();
      return;
    }
    if (this.state === State.TimedOut) {
      this.reconnect();
    }
  }

  private handleTabHidden() {
    log.debug('Tab hidden while websocket is connected');
    this.state = State.TabHiddenIdle;
    this.idleTimer.schedule();
  }

  private handleTabVisibleConnected() {
    log.debug('Tab visible while websocket is connected');
    this.state = State.TabVisible;
  }

  private handleIdleTimeout() {
    log.trace('Waiting for pending tasks before disconnect');
    if (this.state === State.TabHiddenIdle) {
      this.state = State.TabHiddenWaiting;
      this.handleWaitingForDisconnect();
    }
  }

  private handleWaitingForDisconnect() {
    if (this.state !== State.TabHiddenWaiting) {
      return;
    }
    const pending = this.pendingRequests.size;
    if (pending === 0) {
      log.info('Closing idle websocket');
      this.state = State.TimedOut;
      this.closeConnection(1000, 'idle timeout');
      return;
    }
    log.info('Waiting for', pending, 'pending requests before closing websocket');
  }

  private sendPing() {
    if (!this.isOpen) {
      return;
    }
    const ping = nanoid();
    log.trace('Ping', ping);
    this.send({ ping }).then((result) => {
      const parsedPongResult = pongResult.safeParse(result);
      if (parsedPongResult.success && parsedPongResult.data.pong === ping) {
        log.trace('Pong', ping);
        this.pingTimer.schedule();
      } else {
        log.error('Invalid pong:', parsedPongResult, 'expected:', ping);
        this.forceReconnectOnError();
      }
    }).catch((error) => {
      log.error('Error while waiting for ping', error);
      this.forceReconnectOnError();
    });
  }

  send(request: unknown): Promise<unknown> {
    if (!this.isOpen) {
      throw new Error('Not open');
    }
    const messageId = this.nextMessageId.toString(16);
    if (messageId in this.pendingRequests) {
      log.error('Message id wraparound still pending', messageId);
      this.rejectRequest(messageId, new Error('Message id wraparound'));
    }
    if (this.nextMessageId >= Number.MAX_SAFE_INTEGER) {
      this.nextMessageId = 0;
    } else {
      this.nextMessageId += 1;
    }
    const message = JSON.stringify({
      id: messageId,
      request,
    } as XtextWebRequest);
    log.trace('Sending message', message);
    return new Promise((resolve, reject) => {
      const task = new PendingTask(resolve, reject, REQUEST_TIMEOUT_MS, () => {
        this.removePendingRequest(messageId);
      });
      this.pendingRequests.set(messageId, task);
      this.connection.send(message);
    });
  }

  private handleMessage(messageStr: unknown) {
    if (typeof messageStr !== 'string') {
      log.error('Unexpected binary message', messageStr);
      this.forceReconnectOnError();
      return;
    }
    log.trace('Incoming websocket message', messageStr);
    let message: unknown;
    try {
      message = JSON.parse(messageStr);
    } catch (error) {
      log.error('Json parse error', error);
      this.forceReconnectOnError();
      return;
    }
    const okResponse = xtextWebOkResponse.safeParse(message);
    if (okResponse.success) {
      const { id, response } = okResponse.data;
      this.resolveRequest(id, response);
      return;
    }
    const errorResponse = xtextWebErrorResponse.safeParse(message);
    if (errorResponse.success) {
      const { id, error, message: errorMessage } = errorResponse.data;
      this.rejectRequest(id, new Error(`${error} error: ${errorMessage}`));
      if (error === 'server') {
        log.error('Reconnecting due to server error: ', errorMessage);
        this.forceReconnectOnError();
      }
      return;
    }
    const pushMessage = xtextWebPushMessage.safeParse(message);
    if (pushMessage.success) {
      const {
        resource,
        stateId,
        service,
        push,
      } = pushMessage.data;
      this.onPush(resource, stateId, service, push);
    } else {
      log.error(
        'Unexpected websocket message:',
        message,
        'not ok response because:',
        okResponse.error,
        'not error response because:',
        errorResponse.error,
        'not push message because:',
        pushMessage.error,
      );
      this.forceReconnectOnError();
    }
  }

  private resolveRequest(messageId: string, value: unknown) {
    const pendingRequest = this.pendingRequests.get(messageId);
    if (pendingRequest) {
      pendingRequest.resolve(value);
      this.removePendingRequest(messageId);
      return;
    }
    log.error('Trying to resolve unknown request', messageId, 'with', value);
  }

  private rejectRequest(messageId: string, reason?: unknown) {
    const pendingRequest = this.pendingRequests.get(messageId);
    if (pendingRequest) {
      pendingRequest.reject(reason);
      this.removePendingRequest(messageId);
      return;
    }
    log.error('Trying to reject unknown request', messageId, 'with', reason);
  }

  private removePendingRequest(messageId: string) {
    this.pendingRequests.delete(messageId);
    this.handleWaitingForDisconnect();
  }

  forceReconnectOnError(): void {
    if (this.isLogicallyClosed) {
      return;
    }
    this.abortPendingRequests();
    this.closeConnection(1000, 'reconnecting due to error');
    log.error('Reconnecting after delay due to error');
    this.handleErrorState();
  }

  private abortPendingRequests() {
    this.pendingRequests.forEach((request) => {
      request.reject(new Error('Websocket disconnect'));
    });
    this.pendingRequests.clear();
  }

  private closeConnection(code: number, reason: string) {
    this.pingTimer.cancel();
    const { readyState } = this.connection;
    if (readyState !== WebSocket.CLOSING && readyState !== WebSocket.CLOSED) {
      this.connection.close(code, reason);
    }
  }

  private handleErrorState() {
    this.state = State.Error;
    this.reconnectTryCount += 1;
    const delay = RECONNECT_DELAY_MS[this.reconnectTryCount - 1] || MAX_RECONNECT_DELAY_MS;
    log.info('Reconnecting in', delay, 'ms');
    this.reconnectTimer.schedule(delay);
  }

  private handleReconnect() {
    if (this.state !== State.Error) {
      log.error('Unexpected reconnect in', this.state);
      return;
    }
    if (document.visibilityState === 'hidden') {
      this.state = State.TimedOut;
    } else {
      this.reconnect();
    }
  }
}