summaryrefslogtreecommitdiffhomepage
path: root/frontend/src/modules/socketio/index.ts
blob: 18934b39a78d055ad39463427f45cc8a772387c9 (plain)
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
import { debounce, forIn, remove, uniq } from "lodash";
import { onlineManager } from "react-query";
import { io, Socket } from "socket.io-client";
import { Environment, isDevEnv } from "../../utilities";
import { ENSURE, GROUP, LOG } from "../../utilities/console";
import { createDefaultReducer } from "./reducer";

class SocketIOClient {
  private socket: Socket;
  private events: SocketIO.Event[];
  private debounceReduce: () => void;

  private reducers: SocketIO.Reducer[];

  constructor() {
    this.socket = io({
      path: `${Environment.baseUrl}/api/socket.io`,
      transports: ["polling", "websocket"],
      upgrade: true,
      rememberUpgrade: true,
      autoConnect: false,
    });

    this.socket.on("connect", this.onConnect.bind(this));
    this.socket.on("disconnect", this.onDisconnect.bind(this));
    this.socket.on("connect_error", this.onConnectError.bind(this));
    this.socket.on("data", this.onEvent.bind(this));

    this.events = [];
    this.debounceReduce = debounce(this.reduce, 20);
    this.reducers = [];

    onlineManager.setOnline(false);

    if (isDevEnv) {
      window.socketIO = {
        dump: () => {
          GROUP("Socket.IO Reducers", (logger) => {
            this.reducers.forEach((reducer) => {
              logger(reducer.key);
            });
          });
        },
        emit: (e) => {
          if (e) {
            this.onEvent(e);
          }
        },
      };
    }
  }

  initialize() {
    LOG("info", "Initializing Socket.IO client...");
    this.reducers.push(...createDefaultReducer());

    window.addEventListener("app-auth-changed", (ev) => {
      const authenticated = ev.detail.authenticated;
      LOG("info", "Authentication status change to", authenticated);
      if (authenticated) {
        this.connect();
      } else {
        this.disconnect();
      }
    });
  }

  connect() {
    LOG("info", "Connecting Socket.IO client...");
    this.socket.connect();
  }

  disconnect() {
    LOG("info", "Disconnecting Socket.IO client...");
    this.socket.disconnect();
  }

  addReducer(reducer: SocketIO.Reducer) {
    this.reducers.push(reducer);
  }

  removeReducer(reducer: SocketIO.Reducer) {
    const removed = remove(this.reducers, (r) => r === reducer);
    ENSURE(removed.length === 0, "Fail to remove reducer", reducer);
  }

  private reduce() {
    const events = [...this.events];
    this.events = [];

    const records: SocketIO.ActionRecord = {};

    events.forEach((e) => {
      if (!(e.type in records)) {
        records[e.type] = {};
      }

      const record = records[e.type];
      if (record === undefined) {
        return;
      }

      if (!(e.action in record)) {
        record[e.action] = [];
      }

      if (e.payload) {
        record[e.action]?.push(e.payload);
      }
    });

    forIn(records, (element, type) => {
      if (element) {
        const handlers = this.reducers.filter((v) => v.key === type);
        if (handlers.length === 0) {
          LOG("warning", "Unhandled SocketIO event", type);
          return;
        }

        handlers.forEach((handler) => {
          const anyAction = handler.any;
          if (anyAction) {
            anyAction();
          }

          forIn(element, (ids, key) => {
            ids = uniq(ids);
            const action = handler[key as SocketIO.ActionType];
            if (action) {
              // FIXME: type
              // eslint-disable-next-line @typescript-eslint/no-explicit-any
              action(ids as any[]);
            } else if (anyAction === undefined) {
              LOG("warning", "Unhandled SocketIO event", key, type);
            }
          });
        });
      }
    });
  }

  private onConnect() {
    LOG("info", "Socket.IO has connected");
    onlineManager.setOnline(true);
    this.onEvent({ type: "connect", action: "update" });
  }

  private onConnectError() {
    LOG("warning", "Socket.IO has error connecting backend");
    onlineManager.setOnline(false);
    this.onEvent({ type: "connect_error", action: "update" });
  }

  private onDisconnect() {
    LOG("warning", "Socket.IO has disconnected");
    onlineManager.setOnline(false);
    this.onEvent({ type: "disconnect", action: "update" });
  }

  private onEvent(event: SocketIO.Event) {
    LOG("info", "Socket.IO receives", event);
    this.events.push(event);
    this.debounceReduce();
  }
}

export default new SocketIOClient();