summaryrefslogtreecommitdiffstats
path: root/dom/webgpu/tests/cts/checkout/src/common/internal/websocket_logger.ts
blob: 373378e7c2d9015f4f8cd8aaed0acae372f8a227 (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
import { globalTestConfig } from '../framework/test_config.js';

/**
 * - 'uninitialized' means we haven't tried to connect yet
 * - Promise means it's pending
 * - 'failed' means it failed (this is the most common case, where the logger isn't running)
 * - WebSocket means it succeeded
 */
let connection: Promise<WebSocket | 'failed'> | WebSocket | 'failed' | 'uninitialized' =
  'uninitialized';

/**
 * If the logToWebSocket option is enabled (?log_to_web_socket=1 in browser,
 * --log-to-web-socket on command line, or enable it by default in options.ts),
 * log a string to a websocket at `localhost:59497`. See `tools/websocket-logger`.
 *
 * This does nothing if a logToWebSocket is not enabled, or if a connection
 * couldn't be established on the first call.
 */
export function logToWebSocket(msg: string) {
  if (!globalTestConfig.logToWebSocket || connection === 'failed') {
    return;
  }

  if (connection === 'uninitialized') {
    connection = new Promise(resolve => {
      if (typeof WebSocket === 'undefined') {
        resolve('failed');
        return;
      }

      const ws = new WebSocket('ws://localhost:59497/optional_cts_websocket_logger');
      ws.onopen = () => {
        resolve(ws);
      };
      ws.onerror = () => {
        connection = 'failed';
        resolve('failed');
      };
      ws.onclose = () => {
        connection = 'failed';
        resolve('failed');
      };
    });
    void connection.then(resolved => {
      connection = resolved;
    });
  }

  void (async () => {
    // connection may be a promise or a value here. Either is OK to await.
    const ws = await connection;
    if (ws !== 'failed') {
      ws.send(msg);
    }
  })();
}