Compare commits
8 Commits
5fbbdd199c
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| b270649f21 | |||
| 8b26919790 | |||
| 4adb187331 | |||
| 8824e768fb | |||
| 57b53fc122 | |||
| 7cdda2e335 | |||
| b10ebc541e | |||
| 9fd9b50842 |
@@ -5,6 +5,9 @@
|
||||
"description": "Yonexus.Client OpenClaw plugin scaffold",
|
||||
"type": "module",
|
||||
"main": "dist/plugin/index.js",
|
||||
"openclaw": {
|
||||
"extensions": ["./dist/Yonexus.Client/plugin/index.js"]
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"plugin",
|
||||
|
||||
@@ -32,25 +32,25 @@ export function validateYonexusClientConfig(raw: unknown): YonexusClientConfig {
|
||||
const source = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
|
||||
const issues: string[] = [];
|
||||
|
||||
const mainHost = source.mainHost;
|
||||
if (!isNonEmptyString(mainHost)) {
|
||||
const rawMainHost = source.mainHost;
|
||||
if (!isNonEmptyString(rawMainHost)) {
|
||||
issues.push("mainHost is required");
|
||||
} else if (!isValidWsUrl(mainHost.trim())) {
|
||||
} else if (!isValidWsUrl(rawMainHost.trim())) {
|
||||
issues.push("mainHost must be a valid ws:// or wss:// URL");
|
||||
}
|
||||
|
||||
const identifier = source.identifier;
|
||||
if (!isNonEmptyString(identifier)) {
|
||||
const rawIdentifier = source.identifier;
|
||||
if (!isNonEmptyString(rawIdentifier)) {
|
||||
issues.push("identifier is required");
|
||||
}
|
||||
|
||||
const notifyBotToken = source.notifyBotToken;
|
||||
if (!isNonEmptyString(notifyBotToken)) {
|
||||
const rawNotifyBotToken = source.notifyBotToken;
|
||||
if (!isNonEmptyString(rawNotifyBotToken)) {
|
||||
issues.push("notifyBotToken is required");
|
||||
}
|
||||
|
||||
const adminUserId = source.adminUserId;
|
||||
if (!isNonEmptyString(adminUserId)) {
|
||||
const rawAdminUserId = source.adminUserId;
|
||||
if (!isNonEmptyString(rawAdminUserId)) {
|
||||
issues.push("adminUserId is required");
|
||||
}
|
||||
|
||||
@@ -58,10 +58,15 @@ export function validateYonexusClientConfig(raw: unknown): YonexusClientConfig {
|
||||
throw new YonexusClientConfigError(issues);
|
||||
}
|
||||
|
||||
const mainHost = (rawMainHost as string).trim();
|
||||
const identifier = (rawIdentifier as string).trim();
|
||||
const notifyBotToken = (rawNotifyBotToken as string).trim();
|
||||
const adminUserId = (rawAdminUserId as string).trim();
|
||||
|
||||
return {
|
||||
mainHost: mainHost.trim(),
|
||||
identifier: identifier.trim(),
|
||||
notifyBotToken: notifyBotToken.trim(),
|
||||
adminUserId: adminUserId.trim()
|
||||
mainHost,
|
||||
identifier,
|
||||
notifyBotToken,
|
||||
adminUserId
|
||||
};
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
} from "./state.js";
|
||||
import { generateNonce, signMessage } from "../crypto/keypair.js";
|
||||
import type { ClientConnectionState, ClientTransport } from "./transport.js";
|
||||
import type { ClientRuleRegistry } from "./rules.js";
|
||||
|
||||
export type YonexusClientPhase =
|
||||
| "idle"
|
||||
@@ -44,6 +45,8 @@ export interface YonexusClientRuntimeOptions {
|
||||
config: YonexusClientConfig;
|
||||
transport: ClientTransport;
|
||||
stateStore: YonexusClientStateStore;
|
||||
ruleRegistry?: ClientRuleRegistry;
|
||||
onAuthenticated?: () => void;
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
@@ -118,6 +121,7 @@ export class YonexusClientRuntime {
|
||||
}
|
||||
|
||||
if (!isBuiltinMessage(raw)) {
|
||||
this.options.ruleRegistry?.dispatch(raw);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -159,6 +163,7 @@ export class YonexusClientRuntime {
|
||||
};
|
||||
await this.options.stateStore.save(this.clientState);
|
||||
this.phase = "authenticated";
|
||||
this.options.onAuthenticated?.();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -177,7 +182,17 @@ export class YonexusClientRuntime {
|
||||
|
||||
handleTransportStateChange(state: ClientConnectionState): void {
|
||||
if (state === "connected") {
|
||||
this.sendHello();
|
||||
// Reload state from disk before hello so that any secret written by an
|
||||
// external process (e.g. a pairing script) is picked up on reconnect.
|
||||
this.options.stateStore.load(this.options.config.identifier).then((fresh) => {
|
||||
if (fresh) {
|
||||
this.clientState = { ...this.clientState, ...fresh };
|
||||
}
|
||||
this.sendHello();
|
||||
}).catch(() => {
|
||||
// If reload fails, proceed with in-memory state
|
||||
this.sendHello();
|
||||
});
|
||||
}
|
||||
|
||||
if (state === "disconnected") {
|
||||
@@ -259,7 +274,10 @@ export class YonexusClientRuntime {
|
||||
adminNotification: payload.adminNotification
|
||||
};
|
||||
this.lastPairingFailure = undefined;
|
||||
this.phase = payload.adminNotification === "sent" ? "waiting_pair_confirm" : "pair_required";
|
||||
// Always wait for the pairing code regardless of notification status.
|
||||
// When adminNotification is "failed", the admin can retrieve the code
|
||||
// via the server CLI command and deliver it through an alternate channel.
|
||||
this.phase = "waiting_pair_confirm";
|
||||
}
|
||||
|
||||
private async handlePairSuccess(envelope: TypedBuiltinEnvelope<"pair_success">): Promise<void> {
|
||||
@@ -316,6 +334,12 @@ export class YonexusClientRuntime {
|
||||
}
|
||||
|
||||
this.lastPairingFailure = payload.reason;
|
||||
// If the server lost our session (race condition), re-announce via hello
|
||||
// so the server creates a new session and we can retry auth.
|
||||
if (payload.reason === "not_paired" && hasClientSecret(this.clientState)) {
|
||||
this.sendHello();
|
||||
return;
|
||||
}
|
||||
this.phase = "auth_required";
|
||||
}
|
||||
|
||||
|
||||
@@ -181,7 +181,8 @@ function assertClientStateShape(
|
||||
);
|
||||
}
|
||||
|
||||
if (!Number.isInteger(candidate.updatedAt) || candidate.updatedAt < 0) {
|
||||
const updatedAt = candidate.updatedAt;
|
||||
if (typeof updatedAt !== "number" || !Number.isInteger(updatedAt) || updatedAt < 0) {
|
||||
throw new YonexusClientStateCorruptionError(
|
||||
`Client state file has invalid updatedAt value: ${filePath}`
|
||||
);
|
||||
|
||||
@@ -39,30 +39,95 @@ export {
|
||||
type ClientRuleProcessor
|
||||
} from "./core/rules.js";
|
||||
|
||||
import path from "node:path";
|
||||
import { validateYonexusClientConfig } from "./core/config.js";
|
||||
import { createYonexusClientStateStore } from "./core/state.js";
|
||||
import { createClientTransport } from "./core/transport.js";
|
||||
import { createYonexusClientRuntime, type YonexusClientRuntime } from "./core/runtime.js";
|
||||
import { createClientRuleRegistry, YonexusClientRuleRegistry } from "./core/rules.js";
|
||||
|
||||
const _G = globalThis as Record<string, unknown>;
|
||||
const _STARTED_KEY = "_yonexusClientStarted";
|
||||
const _RUNTIME_KEY = "_yonexusClientRuntime";
|
||||
const _REGISTRY_KEY = "_yonexusClientRegistry";
|
||||
const _CALLBACKS_KEY = "_yonexusClientOnAuthCallbacks";
|
||||
|
||||
export interface YonexusClientPluginManifest {
|
||||
readonly name: "Yonexus.Client";
|
||||
readonly version: string;
|
||||
readonly description: string;
|
||||
}
|
||||
|
||||
export interface YonexusClientPluginRuntime {
|
||||
readonly hooks: readonly [];
|
||||
readonly commands: readonly [];
|
||||
readonly tools: readonly [];
|
||||
}
|
||||
|
||||
const manifest: YonexusClientPluginManifest = {
|
||||
name: "Yonexus.Client",
|
||||
version: "0.1.0",
|
||||
description: "Yonexus client plugin for cross-instance OpenClaw communication"
|
||||
};
|
||||
|
||||
export function createYonexusClientPlugin(): YonexusClientPluginRuntime {
|
||||
return {
|
||||
hooks: [],
|
||||
commands: [],
|
||||
tools: []
|
||||
export function createYonexusClientPlugin(api: { rootDir: string; pluginConfig: unknown }): void {
|
||||
// 1. Ensure shared state survives hot-reload — only initialise when absent
|
||||
if (!(_G[_REGISTRY_KEY] instanceof YonexusClientRuleRegistry)) {
|
||||
_G[_REGISTRY_KEY] = createClientRuleRegistry();
|
||||
}
|
||||
if (!Array.isArray(_G[_CALLBACKS_KEY])) {
|
||||
_G[_CALLBACKS_KEY] = [];
|
||||
}
|
||||
|
||||
const ruleRegistry = _G[_REGISTRY_KEY] as YonexusClientRuleRegistry;
|
||||
const onAuthenticatedCallbacks = _G[_CALLBACKS_KEY] as Array<() => void>;
|
||||
|
||||
// 2. Refresh the cross-plugin API object every call so that sendRule / submitPairingCode
|
||||
// closures always read the live runtime from globalThis.
|
||||
_G["__yonexusClient"] = {
|
||||
ruleRegistry,
|
||||
sendRule: (ruleId: string, content: string): boolean =>
|
||||
(_G[_RUNTIME_KEY] as YonexusClientRuntime | undefined)?.sendRuleMessage(ruleId, content) ?? false,
|
||||
submitPairingCode: (code: string): boolean =>
|
||||
(_G[_RUNTIME_KEY] as YonexusClientRuntime | undefined)?.submitPairingCode(code) ?? false,
|
||||
onAuthenticated: onAuthenticatedCallbacks
|
||||
};
|
||||
|
||||
// 3. Start the runtime only once — the globalThis flag survives hot-reload
|
||||
if (_G[_STARTED_KEY]) return;
|
||||
_G[_STARTED_KEY] = true;
|
||||
|
||||
const config = validateYonexusClientConfig(api.pluginConfig);
|
||||
const stateStore = createYonexusClientStateStore(path.join(api.rootDir, "state.json"));
|
||||
|
||||
const transport = createClientTransport({
|
||||
config,
|
||||
onMessage: (msg) => {
|
||||
(_G[_RUNTIME_KEY] as YonexusClientRuntime | undefined)?.handleMessage(msg).catch((err: unknown) => {
|
||||
console.error("[yonexus-client] message handler error:", err);
|
||||
});
|
||||
},
|
||||
onStateChange: (state) => {
|
||||
(_G[_RUNTIME_KEY] as YonexusClientRuntime | undefined)?.handleTransportStateChange(state);
|
||||
}
|
||||
});
|
||||
|
||||
const runtime = createYonexusClientRuntime({
|
||||
config,
|
||||
transport,
|
||||
stateStore,
|
||||
ruleRegistry,
|
||||
onAuthenticated: () => {
|
||||
for (const cb of onAuthenticatedCallbacks) cb();
|
||||
}
|
||||
});
|
||||
_G[_RUNTIME_KEY] = runtime;
|
||||
|
||||
const shutdown = (): void => {
|
||||
runtime.stop().catch((err: unknown) => {
|
||||
console.error("[yonexus-client] shutdown error:", err);
|
||||
});
|
||||
};
|
||||
process.once("SIGTERM", shutdown);
|
||||
process.once("SIGINT", shutdown);
|
||||
|
||||
runtime.start().catch((err: unknown) => {
|
||||
console.error("[yonexus-client] failed to start:", err);
|
||||
});
|
||||
}
|
||||
|
||||
export default createYonexusClientPlugin;
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
{
|
||||
"id": "yonexus-client",
|
||||
"name": "Yonexus.Client",
|
||||
"version": "0.1.0",
|
||||
"description": "Yonexus client plugin for cross-instance OpenClaw communication",
|
||||
"entry": "dist/plugin/index.js",
|
||||
"entry": "./dist/Yonexus.Client/plugin/index.js",
|
||||
"permissions": [],
|
||||
"config": {
|
||||
"mainHost": "",
|
||||
"identifier": "",
|
||||
"notifyBotToken": "",
|
||||
"adminUserId": ""
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"mainHost": { "type": "string" },
|
||||
"identifier": { "type": "string" },
|
||||
"notifyBotToken": { "type": "string" },
|
||||
"adminUserId": { "type": "string" }
|
||||
},
|
||||
"required": ["mainHost", "identifier", "notifyBotToken", "adminUserId"]
|
||||
}
|
||||
}
|
||||
|
||||
24
plugin/types/ws.d.ts
vendored
Normal file
24
plugin/types/ws.d.ts
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
declare module "ws" {
|
||||
export type RawData = Buffer | ArrayBuffer | Buffer[] | string;
|
||||
|
||||
export class WebSocket {
|
||||
static readonly OPEN: number;
|
||||
constructor(url: string);
|
||||
readonly readyState: number;
|
||||
send(data: string): void;
|
||||
close(code?: number, reason?: string): void;
|
||||
terminate(): void;
|
||||
on(event: "open", listener: () => void): this;
|
||||
on(event: "message", listener: (data: RawData) => void): this;
|
||||
on(event: "close", listener: (code: number, reason: Buffer) => void): this;
|
||||
on(event: "error", listener: (error: Error) => void): this;
|
||||
once(event: "open", listener: () => void): this;
|
||||
once(event: "error", listener: (error: Error) => void): this;
|
||||
off(event: "error", listener: (error: Error) => void): this;
|
||||
removeAllListeners?(event?: string): this;
|
||||
}
|
||||
|
||||
export class WebSocketServer {
|
||||
constructor(options: { host?: string; port: number });
|
||||
}
|
||||
}
|
||||
2
protocol
2
protocol
Submodule protocol updated: 9232aa7c17...2611304084
@@ -29,6 +29,7 @@ if (mode === "install") {
|
||||
fs.rmSync(targetDir, { recursive: true, force: true });
|
||||
fs.cpSync(sourceDist, path.join(targetDir, "dist"), { recursive: true });
|
||||
fs.copyFileSync(path.join(repoRoot, "plugin", "openclaw.plugin.json"), path.join(targetDir, "openclaw.plugin.json"));
|
||||
fs.copyFileSync(path.join(repoRoot, "package.json"), path.join(targetDir, "package.json"));
|
||||
console.log(`Installed ${pluginName} to ${targetDir}`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
@@ -121,6 +121,53 @@ describe("Yonexus.Client runtime flow", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("SR-04: first run without credentials enters pair flow and does not require manual state bootstrap", async () => {
|
||||
const storeState = createMockStateStore({
|
||||
identifier: "client-a",
|
||||
updatedAt: 1_710_000_000
|
||||
});
|
||||
const transportState = createMockTransport();
|
||||
const runtime = createYonexusClientRuntime({
|
||||
config: {
|
||||
mainHost: "ws://localhost:8787",
|
||||
identifier: "client-a",
|
||||
notifyBotToken: "stub-token",
|
||||
adminUserId: "admin-user"
|
||||
},
|
||||
transport: transportState.transport,
|
||||
stateStore: storeState.store,
|
||||
now: () => 1_710_000_000
|
||||
});
|
||||
|
||||
await runtime.start();
|
||||
runtime.handleTransportStateChange("connected");
|
||||
|
||||
const hello = decodeBuiltin(transportState.sent[0]);
|
||||
expect(hello.type).toBe("hello");
|
||||
expect(hello.payload).toMatchObject({
|
||||
identifier: "client-a",
|
||||
hasSecret: false,
|
||||
hasKeyPair: true
|
||||
});
|
||||
|
||||
await runtime.handleMessage(
|
||||
encodeBuiltin(
|
||||
buildHelloAck(
|
||||
{
|
||||
identifier: "client-a",
|
||||
nextAction: "pair_required"
|
||||
},
|
||||
{ requestId: "req-first-run", timestamp: 1_710_000_000 }
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
expect(runtime.state.phase).toBe("pair_required");
|
||||
expect(runtime.state.clientState.secret).toBeUndefined();
|
||||
expect(runtime.state.clientState.privateKey).toBeTypeOf("string");
|
||||
expect(runtime.state.clientState.publicKey).toBeTypeOf("string");
|
||||
});
|
||||
|
||||
it("handles pair request, submits code, stores secret, and authenticates", async () => {
|
||||
let now = 1_710_000_000;
|
||||
const storeState = createMockStateStore();
|
||||
@@ -432,4 +479,114 @@ describe("Yonexus.Client runtime flow", () => {
|
||||
expect(runtime.state.pendingPairing).toBeDefined();
|
||||
expect(runtime.state.lastPairingFailure).toBe("invalid_code");
|
||||
});
|
||||
|
||||
it("PF-10: restart during pending pairing resumes waiting for out-of-band code", async () => {
|
||||
const now = 1_710_000_000;
|
||||
const storeState = createMockStateStore({
|
||||
identifier: "client-a",
|
||||
updatedAt: now
|
||||
});
|
||||
|
||||
const firstTransportState = createMockTransport();
|
||||
const firstRuntime = createYonexusClientRuntime({
|
||||
config: {
|
||||
mainHost: "ws://localhost:8787",
|
||||
identifier: "client-a",
|
||||
notifyBotToken: "stub-token",
|
||||
adminUserId: "admin-user"
|
||||
},
|
||||
transport: firstTransportState.transport,
|
||||
stateStore: storeState.store,
|
||||
now: () => now
|
||||
});
|
||||
|
||||
await firstRuntime.start();
|
||||
firstRuntime.handleTransportStateChange("connected");
|
||||
await firstRuntime.handleMessage(
|
||||
encodeBuiltin(
|
||||
buildPairRequest(
|
||||
{
|
||||
identifier: "client-a",
|
||||
expiresAt: now + 300,
|
||||
ttlSeconds: 300,
|
||||
adminNotification: "sent",
|
||||
codeDelivery: "out_of_band"
|
||||
},
|
||||
{ requestId: "req-pair", timestamp: now }
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
expect(firstRuntime.state.phase).toBe("waiting_pair_confirm");
|
||||
expect(firstRuntime.state.pendingPairing).toMatchObject({
|
||||
expiresAt: now + 300,
|
||||
ttlSeconds: 300,
|
||||
adminNotification: "sent"
|
||||
});
|
||||
|
||||
await firstRuntime.stop();
|
||||
|
||||
const secondTransportState = createMockTransport();
|
||||
const secondRuntime = createYonexusClientRuntime({
|
||||
config: {
|
||||
mainHost: "ws://localhost:8787",
|
||||
identifier: "client-a",
|
||||
notifyBotToken: "stub-token",
|
||||
adminUserId: "admin-user"
|
||||
},
|
||||
transport: secondTransportState.transport,
|
||||
stateStore: storeState.store,
|
||||
now: () => now + 5
|
||||
});
|
||||
|
||||
await secondRuntime.start();
|
||||
secondRuntime.handleTransportStateChange("connected");
|
||||
|
||||
const hello = decodeBuiltin(secondTransportState.sent[0]);
|
||||
expect(hello.type).toBe("hello");
|
||||
expect(hello.payload).toMatchObject({
|
||||
identifier: "client-a",
|
||||
hasSecret: false,
|
||||
hasKeyPair: true
|
||||
});
|
||||
|
||||
await secondRuntime.handleMessage(
|
||||
encodeBuiltin(
|
||||
buildHelloAck(
|
||||
{
|
||||
identifier: "client-a",
|
||||
nextAction: "waiting_pair_confirm"
|
||||
},
|
||||
{ requestId: "req-hello-resume", timestamp: now + 5 }
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
await secondRuntime.handleMessage(
|
||||
encodeBuiltin(
|
||||
buildPairRequest(
|
||||
{
|
||||
identifier: "client-a",
|
||||
expiresAt: now + 300,
|
||||
ttlSeconds: 295,
|
||||
adminNotification: "sent",
|
||||
codeDelivery: "out_of_band"
|
||||
},
|
||||
{ requestId: "req-pair-resume", timestamp: now + 5 }
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
expect(secondRuntime.state.phase).toBe("waiting_pair_confirm");
|
||||
expect(secondRuntime.state.pendingPairing).toMatchObject({
|
||||
expiresAt: now + 300,
|
||||
ttlSeconds: 295,
|
||||
adminNotification: "sent"
|
||||
});
|
||||
expect(secondRuntime.submitPairingCode("PAIR-CODE-123", "req-pair-resume")).toBe(true);
|
||||
|
||||
const pairConfirm = decodeBuiltin(secondTransportState.sent.at(-1)!);
|
||||
expect(pairConfirm.type).toBe("pair_confirm");
|
||||
expect((pairConfirm.payload as PairConfirmPayload).pairingCode).toBe("PAIR-CODE-123");
|
||||
});
|
||||
});
|
||||
|
||||
163
tests/transport-reconnect.test.ts
Normal file
163
tests/transport-reconnect.test.ts
Normal file
@@ -0,0 +1,163 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
type EventName = "open" | "close" | "error" | "message";
|
||||
type EventHandler = (...args: any[]) => void;
|
||||
|
||||
const socketInstances: MockWebSocket[] = [];
|
||||
const pendingBehaviors: Array<"open" | "error"> = [];
|
||||
|
||||
class MockWebSocket {
|
||||
static readonly OPEN = 1;
|
||||
static readonly CLOSED = 3;
|
||||
|
||||
readyState = 0;
|
||||
sent: string[] = [];
|
||||
private readonly handlers = new Map<EventName, EventHandler[]>();
|
||||
|
||||
constructor(public readonly url: string) {
|
||||
socketInstances.push(this);
|
||||
const behavior = pendingBehaviors.shift() ?? "open";
|
||||
|
||||
queueMicrotask(() => {
|
||||
if (behavior === "open") {
|
||||
this.readyState = MockWebSocket.OPEN;
|
||||
this.emit("open");
|
||||
return;
|
||||
}
|
||||
|
||||
const error = new Error(`mock connect failure for ${url}`);
|
||||
this.emit("error", error);
|
||||
this.emit("close", 1006, Buffer.from("connect failed"));
|
||||
this.readyState = MockWebSocket.CLOSED;
|
||||
});
|
||||
}
|
||||
|
||||
once(event: EventName, handler: EventHandler): this {
|
||||
const onceHandler: EventHandler = (...args: any[]) => {
|
||||
this.off(event, onceHandler);
|
||||
handler(...args);
|
||||
};
|
||||
return this.on(event, onceHandler);
|
||||
}
|
||||
|
||||
on(event: EventName, handler: EventHandler): this {
|
||||
const existing = this.handlers.get(event) ?? [];
|
||||
existing.push(handler);
|
||||
this.handlers.set(event, existing);
|
||||
return this;
|
||||
}
|
||||
|
||||
off(event: EventName, handler: EventHandler): this {
|
||||
const existing = this.handlers.get(event) ?? [];
|
||||
this.handlers.set(
|
||||
event,
|
||||
existing.filter((candidate) => candidate !== handler)
|
||||
);
|
||||
return this;
|
||||
}
|
||||
|
||||
send(message: string): void {
|
||||
this.sent.push(message);
|
||||
}
|
||||
|
||||
close(code = 1000, reason = ""):
|
||||
void {
|
||||
this.readyState = MockWebSocket.CLOSED;
|
||||
this.emit("close", code, Buffer.from(reason));
|
||||
}
|
||||
|
||||
emit(event: EventName, ...args: any[]): void {
|
||||
for (const handler of [...(this.handlers.get(event) ?? [])]) {
|
||||
handler(...args);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
vi.mock("ws", () => ({
|
||||
WebSocket: MockWebSocket
|
||||
}));
|
||||
|
||||
describe("Yonexus.Client transport reconnect behavior", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
socketInstances.length = 0;
|
||||
pendingBehaviors.length = 0;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("CF-02: retries initial connect with exponential backoff when server is unreachable", async () => {
|
||||
const { createClientTransport } = await import("../plugin/core/transport.js");
|
||||
const onStateChange = vi.fn();
|
||||
const onError = vi.fn();
|
||||
|
||||
pendingBehaviors.push("error", "error", "open");
|
||||
|
||||
const transport = createClientTransport({
|
||||
config: {
|
||||
mainHost: "ws://localhost:8787",
|
||||
identifier: "client-a",
|
||||
notifyBotToken: "stub-token",
|
||||
adminUserId: "admin-user"
|
||||
},
|
||||
onMessage: vi.fn(),
|
||||
onStateChange,
|
||||
onError
|
||||
});
|
||||
|
||||
await expect(transport.connect()).rejects.toThrow("mock connect failure");
|
||||
expect(socketInstances).toHaveLength(1);
|
||||
expect(transport.state).toBe("disconnected");
|
||||
|
||||
await vi.advanceTimersByTimeAsync(999);
|
||||
expect(socketInstances).toHaveLength(1);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(socketInstances).toHaveLength(2);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1_999);
|
||||
expect(socketInstances).toHaveLength(2);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(socketInstances).toHaveLength(3);
|
||||
expect(transport.state).toBe("connected");
|
||||
expect(onError.mock.calls.length).toBeGreaterThanOrEqual(2);
|
||||
expect(onStateChange).toHaveBeenCalledWith("connecting");
|
||||
expect(onStateChange).toHaveBeenCalledWith("connected");
|
||||
});
|
||||
|
||||
it("CF-01: reconnects with backoff after network partition closes an established connection", async () => {
|
||||
const { createClientTransport } = await import("../plugin/core/transport.js");
|
||||
|
||||
pendingBehaviors.push("open", "open");
|
||||
|
||||
const transport = createClientTransport({
|
||||
config: {
|
||||
mainHost: "ws://localhost:8787",
|
||||
identifier: "client-a",
|
||||
notifyBotToken: "stub-token",
|
||||
adminUserId: "admin-user"
|
||||
},
|
||||
onMessage: vi.fn(),
|
||||
onStateChange: vi.fn(),
|
||||
onError: vi.fn()
|
||||
});
|
||||
|
||||
await transport.connect();
|
||||
expect(socketInstances).toHaveLength(1);
|
||||
expect(transport.state).toBe("connected");
|
||||
|
||||
socketInstances[0].emit("close", 1006, Buffer.from("network partition"));
|
||||
expect(transport.state).toBe("disconnected");
|
||||
|
||||
await vi.advanceTimersByTimeAsync(999);
|
||||
expect(socketInstances).toHaveLength(1);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(socketInstances).toHaveLength(2);
|
||||
expect(transport.state).toBe("connected");
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,7 @@
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"outDir": "dist",
|
||||
"rootDir": ".",
|
||||
"rootDir": "..",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
@@ -15,7 +15,9 @@
|
||||
},
|
||||
"include": [
|
||||
"plugin/**/*.ts",
|
||||
"servers/**/*.ts"
|
||||
"plugin/**/*.d.ts",
|
||||
"servers/**/*.ts",
|
||||
"../Yonexus.Protocol/src/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"dist",
|
||||
|
||||
Reference in New Issue
Block a user