File size: 12,456 Bytes
f778c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
// Gateway supervised lock tests cover single-runner locking for supervised gateway starts.
import { createServer } from "node:http";
import { describe, expect, it, vi } from "vitest";
import { resolveGatewayRuntimeConfig } from "../../gateway/server-runtime-config.js";
import { GatewayLockError } from "../../infra/gateway-lock.js";
import { StateDatabaseCoordinatorContentionError } from "../../infra/state-database-coordinator.js";
import { TailscaleRouteOwnershipConflictError } from "../../infra/tailscale-route-ownership-error.js";
import { OpenClawAgentDatabaseMediaMigrationRequiredError } from "../../state/openclaw-agent-db-migration-required.js";
import { testing } from "./run.test-support.js";

const inspectGatewayTlsCertificateMock = vi.hoisted(() =>
  vi.fn<typeof import("../../infra/tls/gateway.js").inspectGatewayTlsCertificate>(async () => ({
    ok: false,
    error: "public certificate missing",
  })),
);

vi.mock("../../infra/tls/gateway.js", () => ({
  inspectGatewayTlsCertificate: inspectGatewayTlsCertificateMock,
}));

function createLogger() {
  return {
    info: vi.fn(),
    warn: vi.fn(),
  };
}

describe("supervised gateway lock recovery", () => {
  it("retries lifecycle contention without treating a healthy port as ownership", async () => {
    const error = new GatewayLockError(
      "failed to acquire gateway state ownership",
      new StateDatabaseCoordinatorContentionError("gateway-lifecycle"),
    );
    const startLoop = vi
      .fn<() => Promise<void>>()
      .mockRejectedValueOnce(error)
      .mockResolvedValueOnce();
    const probeHealth = vi.fn(async () => true);
    let elapsedMs = 0;
    await testing.runGatewayLoopWithSupervisedLockRecovery({
      startLoop,
      supervisor: "systemd",
      port: 18789,
      healthHost: "127.0.0.1",
      log: createLogger(),
      probeHealth,
      now: () => elapsedMs,
      sleep: async (ms) => {
        elapsedMs += ms;
      },
    });
    expect(startLoop).toHaveBeenCalledTimes(2);
    expect(probeHealth).not.toHaveBeenCalled();
  });

  it("spends one budget across supervised retries and lifecycle acquisition", async () => {
    let elapsedMs = 0;
    const error = new GatewayLockError(
      "failed to acquire gateway state ownership; waited 295000ms for gateway-lifecycle ownership",
      new StateDatabaseCoordinatorContentionError("gateway-lifecycle"),
    );
    const budgets: Array<number | undefined> = [];
    const startLoop = vi.fn(async (deadlineMs?: number) => {
      budgets.push(deadlineMs === undefined ? undefined : deadlineMs - elapsedMs);
      if (budgets.length > 1) {
        elapsedMs = deadlineMs ?? elapsedMs;
      }
      throw error;
    });
    const sleep = vi.fn(async (ms: number) => {
      elapsedMs += ms;
    });
    await expect(
      testing.runGatewayLoopWithSupervisedLockRecovery({
        startLoop,
        supervisor: "systemd",
        port: 18789,
        healthHost: "127.0.0.1",
        log: createLogger(),
        now: () => elapsedMs,
        sleep,
      }),
    ).rejects.toBe(error);
    expect(budgets).toEqual([300_000, 295_000]);
    expect(elapsedMs).toBe(300_000);
    expect(sleep).toHaveBeenCalledTimes(1);
  });

  it("uses exit 78 for an ambiguous persistent Tailscale route", () => {
    expect(
      testing.resolveGatewayStartupFailureExitCode(new TailscaleRouteOwnershipConflictError()),
    ).toBe(78);
  });

  it("uses exit 78 for an effective bind/Tailscale config conflict", async () => {
    // Reproduces the reported crash-loop trigger: a persisted gateway.bind=lan
    // combined with a service-level tailscale serve override is only invalid
    // once the two are merged, so only runtime resolution (not static config
    // validation) can detect it.
    const conflict = await resolveGatewayRuntimeConfig({
      cfg: {
        gateway: {
          bind: "lan",
          auth: { mode: "token", token: "test-token-123" },
          tailscale: { mode: "serve" },
        },
      },
      port: 18789,
    }).catch((err: unknown) => err);

    expect(conflict).toBeInstanceOf(Error);
    expect((conflict as Error).message).toBe(
      "tailscale serve/funnel requires gateway bind=loopback (127.0.0.1)",
    );
    expect(testing.resolveGatewayStartupFailureExitCode(conflict)).toBe(78);
  });

  it("uses exit 78 for offline agent database migration requirements", () => {
    expect(
      testing.resolveGatewayStartupFailureExitCode(
        new OpenClawAgentDatabaseMediaMigrationRequiredError("/tmp/openclaw-agent.sqlite", 14),
      ),
    ).toBe(78);
  });

  it("does not retry gateway lock errors outside a supervisor", async () => {
    const err = new GatewayLockError("gateway already running");
    const startLoop = vi.fn(async () => {
      throw err;
    });

    await expect(
      testing.runGatewayLoopWithSupervisedLockRecovery({
        startLoop,
        supervisor: null,
        port: 18789,
        healthHost: "127.0.0.1",
        log: createLogger(),
      }),
    ).rejects.toBe(err);

    expect(startLoop).toHaveBeenCalledTimes(1);
  });

  it("leaves a healthy launchd-supervised gateway in control", async () => {
    const startLoop = vi.fn(async () => {
      throw new GatewayLockError("gateway already running");
    });
    const probeHealth = vi.fn(async () => true);
    const log = createLogger();

    await testing.runGatewayLoopWithSupervisedLockRecovery({
      startLoop,
      supervisor: "launchd",
      port: 18789,
      healthHost: "0.0.0.0",
      log,
      probeHealth,
    });

    expect(startLoop).toHaveBeenCalledTimes(1);
    expect(probeHealth).toHaveBeenCalledWith({ host: "0.0.0.0", port: 18789 });
    expect(log.info).toHaveBeenCalledWith(
      "gateway already running under launchd; existing gateway is healthy, leaving it in control",
    );
    expect(log.warn).not.toHaveBeenCalled();
  });

  it("uses exit 78 semantics for healthy systemd-supervised lock conflicts", async () => {
    const startLoop = vi.fn(async () => {
      throw new GatewayLockError("another gateway instance is already listening");
    });
    const probeHealth = vi.fn(async () => true);

    let failure: unknown;
    try {
      await testing.runGatewayLoopWithSupervisedLockRecovery({
        startLoop,
        supervisor: "systemd",
        port: 18789,
        healthHost: "127.0.0.1",
        log: createLogger(),
        probeHealth,
      });
    } catch (err) {
      failure = err;
    }

    expect(failure).toMatchObject({
      message: expect.stringContaining(
        "exiting with code 78 to prevent a systemd Restart=always loop",
      ),
    });
    expect(startLoop).toHaveBeenCalledTimes(1);
    expect(probeHealth).toHaveBeenCalledWith({ host: "127.0.0.1", port: 18789 });
    expect(testing.resolveGatewayLockErrorExitCode(failure)).toBe(78);
  });

  it("preserves an agent-embedded owner error under a supervisor", async () => {
    const err = new GatewayLockError(
      "another embedded OpenClaw state writer is active (pid 123); lock timeout after 5000ms",
    );
    const startLoop = vi.fn(async () => {
      throw err;
    });
    const probeHealth = vi.fn(async () => true);

    await expect(
      testing.runGatewayLoopWithSupervisedLockRecovery({
        startLoop,
        supervisor: "systemd",
        port: 18789,
        healthHost: "127.0.0.1",
        log: createLogger(),
        probeHealth,
      }),
    ).rejects.toBe(err);

    expect(startLoop).toHaveBeenCalledTimes(1);
    expect(probeHealth).not.toHaveBeenCalled();
  });

  it("bounds supervised retries when the existing gateway stays unhealthy", async () => {
    let now = 0;
    const startLoop = vi.fn(async () => {
      throw new GatewayLockError("gateway already running");
    });
    const sleep = vi.fn(async (ms: number) => {
      now += ms;
    });

    let failure: unknown;
    try {
      await testing.runGatewayLoopWithSupervisedLockRecovery({
        startLoop,
        supervisor: "systemd",
        port: 18789,
        healthHost: "127.0.0.1",
        log: createLogger(),
        probeHealth: vi.fn(async () => false),
        now: () => now,
        sleep,
        retryMs: 5,
        timeoutMs: 12,
      });
    } catch (err) {
      failure = err;
    }

    expect(failure).toMatchObject({
      message:
        "gateway already running under systemd; existing gateway did not become healthy after 12ms",
    });
    expect(testing.resolveGatewayLockErrorExitCode(failure)).toBe(1);
    expect(startLoop).toHaveBeenCalledTimes(4);
    expect(sleep).toHaveBeenNthCalledWith(1, 5);
    expect(sleep).toHaveBeenNthCalledWith(2, 5);
    expect(sleep).toHaveBeenNthCalledWith(3, 2);
  });

  it("bounds supervised retries for EADDRINUSE lock errors", async () => {
    let now = 0;
    const startLoop = vi.fn(async () => {
      throw new GatewayLockError(
        "another gateway instance is already listening on ws://127.0.0.1:18789",
      );
    });
    const sleep = vi.fn(async (ms: number) => {
      now += ms;
    });

    await expect(
      testing.runGatewayLoopWithSupervisedLockRecovery({
        startLoop,
        supervisor: "systemd",
        port: 18789,
        healthHost: "127.0.0.1",
        log: createLogger(),
        probeHealth: vi.fn(async () => false),
        now: () => now,
        sleep,
        retryMs: 5,
        timeoutMs: 12,
      }),
    ).rejects.toThrow(
      "gateway already running under systemd; existing gateway did not become healthy after 12ms",
    );

    expect(startLoop).toHaveBeenCalledTimes(4);
    expect(sleep).toHaveBeenNthCalledWith(1, 5);
    expect(sleep).toHaveBeenNthCalledWith(2, 5);
    expect(sleep).toHaveBeenNthCalledWith(3, 2);
  });

  it.each(["gateway already running", "another gateway instance is already listening"])(
    "uses exit 1 for unmanaged lock errors: %s",
    (message) => {
      expect(testing.resolveGatewayLockErrorExitCode(new GatewayLockError(message))).toBe(1);
    },
  );

  it("retries public certificate inspection while TLS material is unavailable", async () => {
    inspectGatewayTlsCertificateMock.mockClear();
    const probeHealth = testing.createConfiguredGatewayHealthProbe({
      gateway: { tls: { enabled: true, autoGenerate: true } },
    });

    await expect(probeHealth({ host: "127.0.0.1", port: 18789 })).resolves.toBe(false);
    await expect(probeHealth({ host: "127.0.0.1", port: 18789 })).resolves.toBe(false);

    expect(inspectGatewayTlsCertificateMock).toHaveBeenCalledTimes(2);
    expect(inspectGatewayTlsCertificateMock).toHaveBeenCalledWith({
      enabled: true,
      autoGenerate: true,
    });
  });

  it("recognizes only the OpenClaw health response", () => {
    expect(
      testing.isGatewayHealthzResponse(200, JSON.stringify({ ok: true, status: "live" })),
    ).toBe(true);
    expect(
      testing.isGatewayHealthzResponse(200, JSON.stringify({ ok: true, status: "ready" })),
    ).toBe(false);
    expect(testing.isGatewayHealthzResponse(404, "not found")).toBe(false);
    expect(testing.isGatewayHealthzResponse(200, "not json")).toBe(false);
  });

  it("bounds slow health responses with an absolute deadline", async () => {
    const server = createServer((_req, res) => {
      res.writeHead(200, { "content-type": "application/json" });
      const interval = setInterval(() => {
        res.write(" ");
      }, 10);
      res.once("close", () => clearInterval(interval));
    });
    await new Promise<void>((resolve) => {
      server.listen(0, "127.0.0.1", () => resolve());
    });

    try {
      const address = server.address();
      if (!address || typeof address === "string") {
        throw new Error("expected TCP server address");
      }
      const startedAt = Date.now();
      await expect(
        testing.probeGatewayHealthz({
          host: "127.0.0.1",
          port: address.port,
          timeoutMs: 50,
        }),
      ).resolves.toBe(false);
      expect(Date.now() - startedAt).toBeLessThan(500);
    } finally {
      await new Promise<void>((resolve, reject) => {
        server.close((err) => (err ? reject(err) : resolve()));
      });
    }
  });

  it("normalizes wildcard bind hosts for local health probes", () => {
    expect(testing.normalizeGatewayHealthProbeHost("0.0.0.0")).toBe("127.0.0.1");
    expect(testing.normalizeGatewayHealthProbeHost("::")).toBe("127.0.0.1");
    expect(testing.normalizeGatewayHealthProbeHost("127.0.0.1")).toBe("127.0.0.1");
  });
});