File size: 7,019 Bytes
fcd8223
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { GatewayClientOptions } from "../gateway/client.js";
import { createNodeHostGatewayCandidateConnection } from "./gateway-candidate-connection.js";

const mocks = vi.hoisted(() => ({
  options: [] as GatewayClientOptions[],
  clients: [] as Array<{
    request: ReturnType<typeof vi.fn>;
    start: ReturnType<typeof vi.fn>;
    stop: ReturnType<typeof vi.fn>;
    updateNodeManifest: ReturnType<typeof vi.fn>;
  }>,
}));

vi.mock("../gateway/client.js", () => ({
  GatewayClient: function GatewayClient(options: GatewayClientOptions) {
    const client = {
      request: vi.fn(async () => ({ url: options.url })),
      start: vi.fn(),
      stop: vi.fn(),
      updateNodeManifest: vi.fn(),
    };
    mocks.options.push(options);
    mocks.clients.push(client);
    return client;
  },
}));

const candidates = [
  { host: "192.168.1.20", port: 18789, contextPath: "/openclaw-gw", tls: false },
  { host: "gateway.tailnet.example", port: 443, tls: true },
];

function createConnection(
  cloudflareAccessByCandidate?: Parameters<
    typeof createNodeHostGatewayCandidateConnection
  >[0]["cloudflareAccessByCandidate"],
) {
  const callbacks = {
    onEvent: vi.fn(),
    onHelloOk: vi.fn(),
    onConnectError: vi.fn(),
    onReconnectPaused: vi.fn(),
    onClose: vi.fn(),
    onWinningCandidate: vi.fn(),
  };
  return {
    callbacks,
    connection: createNodeHostGatewayCandidateConnection({
      candidates,
      clientOptions: {},
      cloudflareAccessByCandidate,
      ...callbacks,
    }),
  };
}

describe("gateway candidate connection", () => {
  beforeEach(() => {
    mocks.options.length = 0;
    mocks.clients.length = 0;
    vi.clearAllMocks();
  });

  it("rotates only before hello, fences stale callbacks, and forwards through the winner", async () => {
    const { callbacks, connection } = createConnection();
    connection.start();

    expect(mocks.options[0]?.url).toBe("ws://192.168.1.20:18789/openclaw-gw");
    expect(mocks.clients[0]?.start).toHaveBeenCalledOnce();
    mocks.options[0]?.onClose?.(1006, "transport unavailable", {
      phase: "pre-hello",
      socketOpened: false,
      transportValidated: false,
      connectRequestSent: false,
      transientPreHelloCleanClose: false,
    });
    await vi.waitFor(() => expect(mocks.clients).toHaveLength(2));

    expect(mocks.clients[0]?.stop).toHaveBeenCalledOnce();
    expect(mocks.options[1]?.url).toBe("wss://gateway.tailnet.example:443");
    expect(mocks.clients[1]?.start).toHaveBeenCalledOnce();

    mocks.options[0]?.onEvent?.({ type: "event", event: "stale" });
    mocks.options[0]?.onHelloOk?.({} as never);
    mocks.options[0]?.onClose?.(1006, "stale close", {
      phase: "pre-hello",
      socketOpened: false,
      transportValidated: false,
      connectRequestSent: false,
      transientPreHelloCleanClose: false,
    });
    expect(callbacks.onEvent).not.toHaveBeenCalled();
    expect(callbacks.onHelloOk).not.toHaveBeenCalled();
    expect(callbacks.onWinningCandidate).not.toHaveBeenCalled();
    expect(mocks.clients).toHaveLength(2);

    const activeEvent = { type: "event", event: "active" } as const;
    mocks.options[1]?.onEvent?.(activeEvent);
    mocks.options[1]?.onHelloOk?.({} as never);
    mocks.options[1]?.onHelloOk?.({} as never);
    expect(callbacks.onEvent).toHaveBeenCalledWith(activeEvent);
    expect(callbacks.onWinningCandidate).toHaveBeenCalledOnce();
    expect(callbacks.onWinningCandidate).toHaveBeenCalledWith(candidates[1]);

    await connection.request("node.test", { active: true }, undefined);
    connection.updateNodeManifest({ caps: ["mcp"], commands: ["mcp.tools.call.v1"] });
    expect(mocks.clients[0]?.request).not.toHaveBeenCalled();
    expect(mocks.clients[1]?.request).toHaveBeenCalledWith(
      "node.test",
      { active: true },
      undefined,
    );
    expect(mocks.clients[1]?.updateNodeManifest).toHaveBeenCalledWith({
      caps: ["mcp"],
      commands: ["mcp.tools.call.v1"],
    });
  });

  it("does not rotate after the connect request was sent", async () => {
    createConnection();

    mocks.options[0]?.onClose?.(1008, "connect failed", {
      phase: "pre-hello",
      socketOpened: true,
      transportValidated: true,
      connectRequestSent: true,
      transientPreHelloCleanClose: false,
    });
    await Promise.resolve();

    expect(mocks.clients).toHaveLength(1);
  });

  it("promotes a candidate after hello instead of replaying setup auth on another endpoint", async () => {
    const { callbacks } = createConnection();

    mocks.options[0]?.onHelloOk?.({} as never);
    mocks.options[0]?.onClose?.(1006, "later reconnect transport failure", {
      phase: "pre-hello",
      socketOpened: false,
      transportValidated: false,
      connectRequestSent: false,
      transientPreHelloCleanClose: false,
    });
    await Promise.resolve();

    expect(callbacks.onWinningCandidate).toHaveBeenCalledWith(candidates[0]);
    expect(mocks.clients).toHaveLength(1);
  });

  it("carries a pre-hello manifest update into the next candidate", async () => {
    const { connection } = createConnection();
    const manifest = { caps: ["mcp"], commands: ["mcp.tools.call.v1"] };

    connection.updateNodeManifest(manifest);
    mocks.options[0]?.onClose?.(1006, "transport unavailable", {
      phase: "pre-hello",
      socketOpened: false,
      transportValidated: false,
      connectRequestSent: false,
      transientPreHelloCleanClose: false,
    });
    await vi.waitFor(() => expect(mocks.clients).toHaveLength(2));

    expect(mocks.clients[1]?.updateNodeManifest).toHaveBeenCalledWith(manifest);
  });

  it("does not create the queued candidate after stop", async () => {
    const { connection } = createConnection();

    mocks.options[0]?.onClose?.(1006, "transport unavailable", {
      phase: "pre-hello",
      socketOpened: false,
      transportValidated: false,
      connectRequestSent: false,
      transientPreHelloCleanClose: false,
    });
    connection.stop();
    await Promise.resolve();

    expect(mocks.clients).toHaveLength(1);
  });

  it("never carries origin-bound Access credentials to another candidate host", async () => {
    const credentials = { clientId: "test-key", clientSecret: "test-secret" };
    createConnection(new Map([[candidates[0]!, credentials]]));

    expect(mocks.options[0]?.edgeAuthHeaders).toEqual({
      "CF-Access-Client-Id": credentials.clientId,
      "CF-Access-Client-Secret": credentials.clientSecret,
    });
    mocks.options[0]?.onClose?.(1006, "transport unavailable", {
      phase: "pre-hello",
      socketOpened: false,
      transportValidated: false,
      connectRequestSent: false,
      transientPreHelloCleanClose: false,
    });
    await vi.waitFor(() => expect(mocks.clients).toHaveLength(2));

    expect(mocks.options[1]?.url).toBe("wss://gateway.tailnet.example:443");
    expect(mocks.options[1]?.edgeAuthHeaders).toBeUndefined();
  });
});