File size: 7,424 Bytes
90f0300
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {
  RELAY_PROTOCOL_VERSION,
  jsonMessage,
  logRelayEvent,
  sendWsJson
} from './relay-protocol.js';

const MAX_HEARTBEAT_MISS_CHECK_MS = 10000;
const STALE_SOCKET_TERMINATE_DELAY_MS = 250;

export function createMacConnectionManager({
  createRequestId,
  heartbeatMs,
  idleHeartbeatMs,
  metrics,
  pendingRequests,
  hasActiveBrowserWork,
  broadcastStatus,
  closeRealtimeForEpoch
}) {
  let macSocket = null;
  let macInfo = null;
  let macConnectionEpoch = 0;
  let heartbeatTimer = null;
  let pinnedConnectorInstanceId = '';

  function getSocket() {
    return macSocket;
  }

  function getInfo() {
    return macInfo;
  }

  function getEpoch() {
    return macConnectionEpoch;
  }

  function isConnected() {
    return Boolean(macSocket && macSocket.readyState === macSocket.OPEN);
  }

  function bufferedAmount() {
    return macSocket?.bufferedAmount || 0;
  }

  function assertAvailable(envelope, clientKey = '') {
    if (!isConnected()) {
      throw Object.assign(new Error('mac_offline'), { status: 503 });
    }
    if (macInfo?.localStatus?.reachable === false && envelope.type !== 'auth.validate') {
      throw Object.assign(new Error('mac_local_offline'), { status: 503 });
    }
    pendingRequests.assertCapacity(clientKey);
  }

  function heartbeatInterval() {
    return hasActiveBrowserWork() || pendingRequests.size > 0 ? heartbeatMs : idleHeartbeatMs;
  }

  const hasActiveRelayWork = () => {
    return hasActiveBrowserWork() || pendingRequests.size > 0;
  };

  const closeStaleSocket = (ws, reason) => {
    try {
      ws.close(4000, reason);
      if (typeof ws.terminate === 'function') {
        const terminateTimer = setTimeout(() => {
          if (ws.readyState !== ws.CLOSED) {
            ws.terminate();
          }
        }, STALE_SOCKET_TERMINATE_DELAY_MS);
        terminateTimer.unref?.();
      }
    } catch {
      ws.terminate?.();
    }
  };

  const detachSocket = (ws) => {
    if (ws !== macSocket) {
      return;
    }
    const oldEpoch = macConnectionEpoch;
    macSocket = null;
    if (macInfo) {
      macInfo.lastSeenAt = new Date().toISOString();
    }
    metrics.macDisconnectsTotal += 1;
    pendingRequests.failForEpoch(oldEpoch, 502, 'mac_offline');
    closeRealtimeForEpoch(oldEpoch, 'mac_offline');
    broadcastStatus();
    clearTimeout(heartbeatTimer);
    heartbeatTimer = null;
    logRelayEvent('mac.disconnected', { macConnectionEpoch: oldEpoch });
  };

  const scheduleHeartbeat = () => {
    clearTimeout(heartbeatTimer);
    if (!isConnected()) {
      return;
    }
    heartbeatTimer = setTimeout(() => {
      if (!isConnected()) {
        return;
      }
      const sentAt = Date.now();
      const active = heartbeatInterval() === heartbeatMs;
      if (!sendWsJson(macSocket, { type: 'ping', sentAt, active })) {
        return;
      }
      const socketAtPing = macSocket;
      const missedTimer = setTimeout(() => {
        const socketOpen = socketAtPing === macSocket && socketAtPing.readyState === socketAtPing.OPEN;
        if (socketOpen && Number(socketAtPing.lastPongAt || 0) < sentAt) {
          metrics.macHeartbeatMissesTotal += 1;
          logRelayEvent('mac.heartbeat_missed', { macConnectionEpoch });
          detachSocket(socketAtPing);
          closeStaleSocket(socketAtPing, 'mac_heartbeat_missed');
        }
      }, Math.min(heartbeatMs, MAX_HEARTBEAT_MISS_CHECK_MS));
      missedTimer.unref?.();
      scheduleHeartbeat();
    }, heartbeatInterval());
    heartbeatTimer.unref?.();
  };

  const attachSocket = (ws, hello = {}) => {
    const nextConnectorId = String(hello.connectorInstanceId || '').trim();
    if (!nextConnectorId) {
      ws.close(4002, 'invalid_connector_instance_id');
      logRelayEvent('mac.rejected', { reason: 'invalid_connector_instance_id' }, 'warn');
      return;
    }
    if (pinnedConnectorInstanceId && pinnedConnectorInstanceId !== nextConnectorId) {
      if (isConnected() || hasActiveRelayWork()) {
        metrics.multiMacRejectedTotal += 1;
        ws.close(4009, 'ambiguous_mac_route');
        logRelayEvent('mac.rejected', {
          reason: 'ambiguous_mac_route',
          pinnedConnectorInstanceId,
          rejectedConnectorInstanceId: nextConnectorId
        }, 'warn');
        return;
      }
      logRelayEvent('mac.connector_identity_rotated', {
        previousConnectorInstanceId: pinnedConnectorInstanceId,
        nextConnectorInstanceId: nextConnectorId
      });
      pinnedConnectorInstanceId = nextConnectorId;
    }
    if (isConnected()) {
      if (macInfo?.connectorInstanceId !== nextConnectorId) {
        metrics.multiMacRejectedTotal += 1;
        ws.close(4009, 'ambiguous_mac_route');
        logRelayEvent('mac.rejected', {
          reason: 'ambiguous_mac_route',
          activeConnectorInstanceId: macInfo.connectorInstanceId,
          rejectedConnectorInstanceId: nextConnectorId
        }, 'warn');
        return;
      }
      const oldEpoch = macConnectionEpoch;
      pendingRequests.failForEpoch(oldEpoch, 502, 'mac_reconnected');
      closeRealtimeForEpoch(oldEpoch, 'mac_reconnected');
      try {
        macSocket.close(4000, 'mac_reconnected');
      } catch {
        macSocket.terminate();
      }
    }

    macConnectionEpoch += 1;
    pinnedConnectorInstanceId = pinnedConnectorInstanceId || nextConnectorId;
    macSocket = ws;
    macInfo = {
      connectorInstanceId: nextConnectorId,
      connectionId: createRequestId(),
      deviceName: hello.deviceName || 'Mac',
      clientVersion: hello.clientVersion || '',
      connectedAt: new Date().toISOString(),
      lastSeenAt: new Date().toISOString(),
      localStatus: hello.localStatus || { reachable: false, checkedAt: '' },
      protocolVersion: hello.protocolVersion || RELAY_PROTOCOL_VERSION
    };
    metrics.macConnectsTotal += 1;
    sendWsJson(ws, jsonMessage('relay.hello', {
      connectionId: macInfo.connectionId,
      macConnectionEpoch,
      serverTime: new Date().toISOString(),
      accepted: true
    }));
    broadcastStatus();
    scheduleHeartbeat();
    logRelayEvent('mac.connected', {
      macConnectionEpoch,
      deviceName: macInfo.deviceName,
      connectorInstanceId: macInfo.connectorInstanceId
    });
  };

  function recordPong(ws, sentAt) {
    ws.lastPongAt = Number(sentAt || Date.now());
    if (macInfo) {
      macInfo.lastSeenAt = new Date().toISOString();
    }
  }

  function updateLocalStatus(ws, localStatus) {
    if (ws !== macSocket || !macInfo) {
      return false;
    }
    macInfo.lastSeenAt = new Date().toISOString();
    macInfo.localStatus = localStatus || macInfo.localStatus;
    logRelayEvent('mac.local_status_changed', {
      macConnectionEpoch,
      reachable: Boolean(macInfo.localStatus?.reachable),
      status: macInfo.localStatus?.status || 0
    });
    broadcastStatus();
    return true;
  }

  function acceptSocket(ws, handleMessage) {
    ws.lastPongAt = Date.now();
    ws.on('message', (message) => {
      handleMessage(ws, message).catch((error) => {
        ws.close(4002, error.message || 'invalid_message');
      });
    });
    ws.on('close', () => detachSocket(ws));
    ws.on('error', () => detachSocket(ws));
  }

  return {
    acceptSocket,
    assertAvailable,
    attachSocket,
    bufferedAmount,
    getEpoch,
    getInfo,
    getSocket,
    isConnected,
    recordPong,
    scheduleHeartbeat,
    updateLocalStatus
  };
}