All files / src/utils WebsocketUtils.ts

30.28% Statements 43/142
7.14% Branches 2/28
18.51% Functions 10/54
32.57% Lines 43/132

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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            66x   66x     66x   10x           66x                                                                                                                                                                                                                                                                                                                                                             66x   66x             66x   4x 4x   4x 4x   4x 4x     4x       4x                 4x                                         4x       4x       4x 4x   4x         4x     4x 4x                 4x     4x 2x 2x 2x 2x     4x             4x 2x     4x 2x 2x   2x 1x     1x       4x   4x             2x                
import { getAccessToken } from "./TokenUtils";
import { AttachmentOperation, AttachmentProps } from "@props/RecordProps";
import { fetchConfig } from "@utils/hooks/useConfig";
import { v4 as uuid } from "uuid";
import { WEBSOCKET_SERVER_URL } from "@config/base";
 
const DEFAULT_HEARTBEAT_INTERVAL_IN_SEC = 20;
 
let heartbeatIntervalInSec = DEFAULT_HEARTBEAT_INTERVAL_IN_SEC;
 
// 这里无法直接用 useConfig hook,因为 useConfig 依赖 react,需要在 react component 中调用
fetchConfig("websocket.heartbeatInterval", "int")
  .then((config) => {
    console.log(`websocket.heartbeatInterval: ${config.value}`);
    if (config.value) {
      heartbeatIntervalInSec = config.value as number;
    }
  })
  .catch((error) => {
    console.error(`Failed to fetch config for websocket.heartbeatInterval: ${error}`);
  });
 
export interface AttachmentOperationProps extends AttachmentProps {
  operation: AttachmentOperation; /* 操作类型 */
}
 
/* eslint-disable @typescript-eslint/ban-types */
export interface SocketInterface {
  on: (fn: Function) => void;
  replaceOn: (fn: Function) => void;
  off: (fn: Function) => void;
  onStateChange: (fn: Function) => void;
  close: () => void;
  getClient: () => void;
  isConnected: () => boolean;
  send: (content: string) => void;
  sendFile: (props: AttachmentProps, file: File) => void;
  numberOfMessageListeners: () => number;
}
 
export interface NetworkConnectedEvent {
  type: 'connected';
}
 
export interface NetworkReconnectedEvent {
  type: 'reconnected';
}
 
export interface NetworkClosedEvent {
  type: 'closed';
}
 
export interface NetworkUpstreamMessage<P> {
  msgId?: string;
  topic: string;
  payload: P;
}
 
export interface NetworkDownstreamMessage<P> {
  msgId?: string;
  topic: string;
  payload: P;
}
 
export type NetworkEvent = NetworkConnectedEvent | NetworkReconnectedEvent | NetworkClosedEvent;
 
export type NetworkEventListener = (event: NetworkEvent) => void;
 
export type NetworkMessageListener<P> = (payload: P) => void;
 
export type UnregisterNetworkEventListener = () => void;
 
export class NetworkService {
 
  private readonly url: string;
  private readonly eventListeners: Array<NetworkEventListener> = [];
  private readonly msgListeners: Record<string, Array<NetworkMessageListener<unknown>>> = {};
  private readonly pendingMessagesResolver: Record<string, (payload: unknown) => void> = {};
  private client?: WebSocket;
  private reconnectOnClose = true;
 
  constructor(url: string) {
    this.url = url;
  }
 
  public readonly init = (): Promise<WebSocket> => {
    if (this.client) {
      return Promise.resolve(this.client);
    }
 
    return new Promise((resolve) => {
      const client = new WebSocket(`${this.url}?access_token=${getAccessToken()}`);
 
      client.onopen = () => {
        this.eventListeners.forEach(l => l({ type: 'connected' }));
        this.client = client;
        // heartbeat
        const heartbeatTimeout = setInterval(async () => {
          if (client.readyState === client.CLOSED) {
            clearInterval(heartbeatTimeout);
            return;
          }
          await this.send('heartbeat', 'ping');
        }, heartbeatIntervalInSec * 1000);
        resolve(client);
      };
 
      client.onmessage = (event: MessageEvent<string>) => {
        const msg = JSON.parse(event.data) as NetworkDownstreamMessage<unknown>;
        if (msg.msgId) {
          this.pendingMessagesResolver[msg.msgId]?.(msg.payload);
        }
        this.msgListeners[msg.topic]?.forEach(l => l(msg.payload));
      };
 
      client.onerror = (e) => {
        console.error(e);
      };
 
      client.onclose = () => {
        this.client = undefined;
        this.eventListeners.forEach(l => l({ type: 'closed' }));
        if (this.reconnectOnClose) {
          setTimeout(() => {
            this.init().then(() => {
              this.eventListeners.forEach(l => l({ type: 'reconnected' }));
            });
          }, 1000);
        }
      };
    });
  };
 
  public readonly close = (): void => {
    this.reconnectOnClose = false;
    this.client?.close();
  };
 
  public readonly onEvent = (listener: NetworkEventListener): UnregisterNetworkEventListener => {
    this.eventListeners.push(listener);
    return () => {
      this.eventListeners.filter(l => l !== listener);
    };
  };
 
  public readonly subscribe = <T>(topic: string, listener: NetworkMessageListener<T>): UnregisterNetworkEventListener => {
    if (!this.msgListeners[topic]) {
      this.msgListeners[topic] = [];
    }
    this.msgListeners[topic].push(listener as NetworkMessageListener<unknown>);
    return () => {
      this.msgListeners[topic].filter(l => l !== listener);
    };
  };
 
  public readonly send = <P, R>(topic: string, payload: P, timeout?: number): Promise<R> => {
    const msgId = uuid();
    const upstreamMsg: NetworkUpstreamMessage<P> = {
      msgId,
      topic,
      payload
    };
    return new Promise<R>((resolve, reject) => {
      let timeoutId: NodeJS.Timeout | undefined = undefined;
      if (timeout) {
        timeoutId = setTimeout(() => {
          reject(new Error(`Timeout after ${timeout} ms`));
        }, timeout);
      }
      this.init().then((client) => {
        client.send(JSON.stringify(upstreamMsg));
        this.pendingMessagesResolver[msgId] = (payload: unknown) => {
          if (timeoutId) {
            clearTimeout(timeoutId);
          }
          resolve(payload as R);
        };
      });
    });
  };
 
  public readonly sendOneWay = <P>(msgType: string, payload: P): void => {
    const upstreamMsg: NetworkUpstreamMessage<P> = {
      msgId: uuid(),
      topic: msgType,
      payload
    };
    this.init().then((client) => {
      client.send(JSON.stringify(upstreamMsg));
    });
  };
 
}
 
let networkService: NetworkService | undefined = undefined;
 
export const getNetworkService = (): NetworkService => {
  if (!networkService) {
    networkService = new NetworkService(`${WEBSOCKET_SERVER_URL}/websocket/route`);
  }
  return networkService;
};
 
const ReconnectableSocket = (url: string): SocketInterface => {
  let client: WebSocket;
  let isConnected = false;
  let reconnectOnClose = true;
 
  let messageListeners: Array<Function> = [];
  let stateChangeListeners: Array<Function> = [];
 
  const on = (fn: Function): void => {
    messageListeners.push(fn);
  };
 
  const replaceOn = (fn: Function): void => {
    messageListeners = [fn];
  };
 
  const send = (content: string): void => {
    client.send(content);
  };
 
  /**
   * 通过 Websocket 发送文件到后台
   * 先发送文件的元数据,包括文件名,文件大小等
   * 然后发送文件的内容
   */
  const sendFile = (props: AttachmentProps, file: File): void => {
    const {
      id, uid, ownerId, ownerClass, columnNameInOwnerClass, multiple
    } = props;
    const fileMetaData = {
      lastModified: file.lastModified,
      name: file.name,
      type: file.type,
      size: file.size,
      uid: uid,
      ownerId: ownerId ?? undefined,
      ownerClass: ownerClass,
      id: id ?? undefined,
      columnNameInOwnerClass,
      operation: "upload",
      multiple
    };
    client.send(JSON.stringify(fileMetaData));
    client.send(file);
  };
 
  const off = (fn: Function): void => {
    messageListeners = messageListeners.filter(l => l !== fn);
  };
 
  const onStateChange = (fn: Function): void => {
    stateChangeListeners = [fn];
  };
 
  const start = (): void => {
    client = new WebSocket(`${url}?access_token=${getAccessToken()}`);
 
    client.onopen = () => {
      isConnected = true;
      stateChangeListeners.forEach(fn => fn(true));
    };
 
    const { close } = client;
 
    // heartbeat
    const heartbeat = (): void => {
      setTimeout(() => {
        if (client.readyState === client.CLOSED) {
          return;
        }
        send("ping");
        heartbeat();
      }, heartbeatIntervalInSec * 1000);
    };
 
    heartbeat();
 
    // Close without reconnecting;
    client.close = () => {
      reconnectOnClose = false;
      messageListeners = [];
      stateChangeListeners = [];
      close.call(client);
    };
 
    client.onmessage = (event) => {
      if (event.data === "pong") {
        return;
      }
      messageListeners.forEach(fn => fn(event.data));
    };
 
    client.onerror = (e) => {
      console.error(e);
    };
 
    client.onclose = () => {
      isConnected = false;
      stateChangeListeners.forEach(fn => fn(false));
 
      if (!reconnectOnClose) {
        return;
      }
 
      setTimeout(start, 1000 * 10);
    };
  };
 
  start();
 
  return {
    on,
    replaceOn,
    off,
    send,
    sendFile,
    onStateChange,
    close: () => client.close(),
    getClient: () => client,
    isConnected: () => isConnected,
    numberOfMessageListeners: () => messageListeners.length,
  };
};
 
export default ReconnectableSocket;