Skip to content

Commit 6467ddd

Browse files
authored
fix(qqbot): migrate state stores to sqlite kv
Move QQBot credential backups, gateway sessions, known-user records, and ref-index rows into plugin SQLite KV stores. Import shipped JSON/JSONL state files on first use and keep auxiliary known-user/ref-index state best-effort so message delivery is not blocked by cache persistence failures.
1 parent 95880ae commit 6467ddd

14 files changed

Lines changed: 1063 additions & 384 deletions

‎extensions/qqbot/src/bridge/runtime.ts‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,14 @@ import type { GatewayPluginRuntime } from "../engine/gateway/types.js";
44
import { setOpenClawVersion } from "../engine/messaging/sender.js";
55

66
// Single plugin runtime per process — concurrent multi-tenant qqbot runtimes are not supported.
7-
const { setRuntime: _setRuntime, getRuntime: getQQBotRuntime } =
8-
createPluginRuntimeStore<PluginRuntime>({
9-
pluginId: "qqbot",
10-
errorMessage: "QQBot runtime not initialized",
11-
});
7+
const {
8+
setRuntime: _setRuntime,
9+
clearRuntime: resetQQBotRuntimeForTest,
10+
getRuntime: getQQBotRuntime,
11+
} = createPluginRuntimeStore<PluginRuntime>({
12+
pluginId: "qqbot",
13+
errorMessage: "QQBot runtime not initialized",
14+
});
1215

1316
/** Set the QQBot runtime and inject the framework version into the User-Agent. */
1417
function setQQBotRuntime(runtime: PluginRuntime): void {
@@ -17,7 +20,7 @@ function setQQBotRuntime(runtime: PluginRuntime): void {
1720
setOpenClawVersion(runtime.version);
1821
}
1922

20-
export { getQQBotRuntime, setQQBotRuntime };
23+
export { getQQBotRuntime, resetQQBotRuntimeForTest, setQQBotRuntime };
2124

2225
/** Type-narrowed getter for engine/ modules that need GatewayPluginRuntime. */
2326
export function getQQBotRuntimeForEngine(): GatewayPluginRuntime {
Lines changed: 155 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -1,88 +1,174 @@
11
import fs from "node:fs";
2-
import { afterEach, beforeEach, describe, expect, it } from "vitest";
3-
import { getCredentialBackupFile, getLegacyCredentialBackupFile } from "../utils/data-paths.js";
4-
import { loadCredentialBackup, saveCredentialBackup } from "./credential-backup.js";
5-
6-
/**
7-
* These tests write to `~/.openclaw/qqbot/data` under a test-specific
8-
* accountId prefix and clean up after themselves. Mirrors the approach
9-
* used by `platform.test.ts` in the same package.
10-
*/
2+
import os from "node:os";
3+
import path from "node:path";
4+
import {
5+
createPluginStateSyncKeyedStoreForTests,
6+
resetPluginStateStoreForTests,
7+
} from "openclaw/plugin-sdk/plugin-state-test-runtime";
8+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
9+
import {
10+
installQQBotRuntimeForStateTests,
11+
resetQQBotStateTestRuntime,
12+
} from "../../test-support/runtime.js";
13+
14+
type CredentialBackup = {
15+
accountId: string;
16+
appId: string;
17+
clientSecret: string;
18+
savedAt: string;
19+
};
20+
21+
const createdDirs: string[] = [];
22+
23+
function createTempDir(prefix: string): string {
24+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
25+
createdDirs.push(dir);
26+
return dir;
27+
}
28+
29+
async function useMockHome(homeDir: string): Promise<void> {
30+
vi.doMock("node:os", async (importOriginal) => {
31+
const actual = await importOriginal<typeof import("node:os")>();
32+
return {
33+
...actual,
34+
default: { ...actual, homedir: () => homeDir },
35+
homedir: () => homeDir,
36+
};
37+
});
38+
}
39+
40+
function useStateDir(stateDir: string): void {
41+
vi.stubEnv("OPENCLAW_STATE_DIR", stateDir);
42+
installQQBotRuntimeForStateTests(stateDir);
43+
}
44+
45+
function legacyOsHomeBackupPath(homeDir: string, accountId = "default"): string {
46+
return path.join(homeDir, ".openclaw", "qqbot", "data", `credential-backup-${accountId}.json`);
47+
}
48+
49+
function writeJson(filePath: string, value: unknown): void {
50+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
51+
fs.writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`);
52+
}
53+
54+
function readCredentialRows(stateDir: string): CredentialBackup[] {
55+
const store = createPluginStateSyncKeyedStoreForTests<CredentialBackup>("qqbot", {
56+
namespace: "credential-backups",
57+
maxEntries: 1000,
58+
env: { ...process.env, OPENCLAW_STATE_DIR: stateDir },
59+
});
60+
return store.entries().map((entry) => entry.value);
61+
}
62+
1163
describe("engine/config/credential-backup", () => {
12-
const acct = `test-cb-${process.pid}-${Date.now()}`;
13-
const legacyPath = getLegacyCredentialBackupFile();
14-
let legacyBackup: string | null = null;
15-
16-
beforeEach(() => {
17-
// Preserve any legacy backup that might happen to live in the user's
18-
// real home so we can restore it after the test.
19-
legacyBackup = null;
20-
if (fs.existsSync(legacyPath)) {
21-
legacyBackup = fs.readFileSync(legacyPath, "utf8");
22-
fs.unlinkSync(legacyPath);
23-
}
64+
beforeEach(async () => {
65+
vi.resetModules();
66+
const stateDir = createTempDir("qqbot-state-");
67+
const homeDir = createTempDir("qqbot-home-");
68+
vi.stubEnv("HOME", homeDir);
69+
await useMockHome(homeDir);
70+
useStateDir(stateDir);
2471
});
2572

2673
afterEach(() => {
27-
try {
28-
fs.unlinkSync(getCredentialBackupFile(acct));
29-
} catch {
30-
/* ignore */
31-
}
32-
if (fs.existsSync(legacyPath)) {
33-
fs.unlinkSync(legacyPath);
34-
}
35-
if (legacyBackup != null) {
36-
fs.writeFileSync(legacyPath, legacyBackup);
74+
resetQQBotStateTestRuntime();
75+
resetPluginStateStoreForTests();
76+
vi.doUnmock("node:os");
77+
vi.resetModules();
78+
vi.unstubAllEnvs();
79+
for (const dir of createdDirs.splice(0)) {
80+
fs.rmSync(dir, { recursive: true, force: true });
3781
}
3882
});
3983

40-
it("round-trips a credential snapshot", () => {
41-
saveCredentialBackup(acct, "app-1", "secret-1");
42-
const loaded = loadCredentialBackup(acct);
43-
expect(loaded?.appId).toBe("app-1");
44-
expect(loaded?.clientSecret).toBe("secret-1");
45-
expect(loaded?.accountId).toBe(acct);
46-
expect(fs.existsSync(getCredentialBackupFile(acct))).toBe(true);
84+
it("round-trips a credential snapshot through SQLite without writing JSON", async () => {
85+
const { getCredentialBackupFile } = await import("../utils/data-paths.js");
86+
const { loadCredentialBackup, saveCredentialBackup } = await import("./credential-backup.js");
87+
const stateDir = process.env.OPENCLAW_STATE_DIR!;
88+
89+
saveCredentialBackup("default", "app-1", "secret-1");
90+
91+
const loaded = loadCredentialBackup("default");
92+
expect(loaded).toMatchObject({
93+
accountId: "default",
94+
appId: "app-1",
95+
clientSecret: "secret-1",
96+
});
97+
expect(fs.existsSync(getCredentialBackupFile("default"))).toBe(false);
98+
expect(readCredentialRows(stateDir)).toHaveLength(1);
4799
});
48100

49-
it("returns null when no backup exists", () => {
50-
expect(loadCredentialBackup(acct)).toBeNull();
101+
it("keeps same account IDs isolated across state directories", async () => {
102+
const { loadCredentialBackup, saveCredentialBackup } = await import("./credential-backup.js");
103+
const stateDirA = process.env.OPENCLAW_STATE_DIR!;
104+
saveCredentialBackup("default", "app-a", "secret-a");
105+
106+
const stateDirB = createTempDir("qqbot-state-b-");
107+
useStateDir(stateDirB);
108+
expect(loadCredentialBackup("default")).toBeNull();
109+
saveCredentialBackup("default", "app-b", "secret-b");
110+
111+
useStateDir(stateDirA);
112+
expect(loadCredentialBackup("default")?.appId).toBe("app-a");
113+
114+
useStateDir(stateDirB);
115+
expect(loadCredentialBackup("default")?.appId).toBe("app-b");
51116
});
52117

53-
it("returns null when legacy backup belongs to a different accountId", () => {
54-
fs.writeFileSync(
55-
legacyPath,
56-
JSON.stringify({
57-
accountId: "other-acct",
58-
appId: "app-old",
59-
clientSecret: "secret-old",
60-
savedAt: new Date().toISOString(),
61-
}),
62-
);
63-
expect(loadCredentialBackup(acct)).toBeNull();
118+
it("imports the state-dir legacy per-account JSON backup once", async () => {
119+
const { getCredentialBackupFile } = await import("../utils/data-paths.js");
120+
const { loadCredentialBackup } = await import("./credential-backup.js");
121+
writeJson(getCredentialBackupFile("default"), {
122+
accountId: "default",
123+
appId: "app-old",
124+
clientSecret: "secret-old",
125+
savedAt: new Date().toISOString(),
126+
});
127+
128+
const loaded = loadCredentialBackup("default");
129+
130+
expect(loaded?.appId).toBe("app-old");
131+
expect(fs.existsSync(getCredentialBackupFile("default"))).toBe(false);
132+
expect(loadCredentialBackup("default")?.clientSecret).toBe("secret-old");
64133
});
65134

66-
it("migrates legacy single-file backup to per-account path on load", () => {
67-
fs.writeFileSync(
68-
legacyPath,
69-
JSON.stringify({
70-
accountId: acct,
71-
appId: "app-1",
72-
clientSecret: "secret-1",
73-
savedAt: new Date().toISOString(),
74-
}),
75-
);
76-
77-
const loaded = loadCredentialBackup(acct);
78-
expect(loaded?.appId).toBe("app-1");
135+
it("imports the old OS-home JSON backup once", async () => {
136+
const { loadCredentialBackup } = await import("./credential-backup.js");
137+
const legacyPath = legacyOsHomeBackupPath(process.env.HOME!);
138+
writeJson(legacyPath, {
139+
accountId: "default",
140+
appId: "app-home",
141+
clientSecret: "secret-home",
142+
savedAt: new Date().toISOString(),
143+
});
144+
145+
const loaded = loadCredentialBackup("default");
146+
147+
expect(loaded?.appId).toBe("app-home");
79148
expect(fs.existsSync(legacyPath)).toBe(false);
80-
expect(fs.existsSync(getCredentialBackupFile(acct))).toBe(true);
149+
expect(loadCredentialBackup("default")?.clientSecret).toBe("secret-home");
150+
});
151+
152+
it("returns null when the legacy single-file backup belongs to a different accountId", async () => {
153+
const { getLegacyCredentialBackupFile } = await import("../utils/data-paths.js");
154+
const { loadCredentialBackup } = await import("./credential-backup.js");
155+
writeJson(getLegacyCredentialBackupFile(), {
156+
accountId: "other-acct",
157+
appId: "app-old",
158+
clientSecret: "secret-old",
159+
savedAt: new Date().toISOString(),
160+
});
161+
162+
expect(loadCredentialBackup("default")).toBeNull();
163+
expect(fs.existsSync(getLegacyCredentialBackupFile())).toBe(true);
81164
});
82165

83-
it("ignores empty appId/clientSecret on save", () => {
84-
saveCredentialBackup(acct, "", "secret");
85-
saveCredentialBackup(acct, "app", "");
86-
expect(fs.existsSync(getCredentialBackupFile(acct))).toBe(false);
166+
it("ignores empty appId/clientSecret on save", async () => {
167+
const { loadCredentialBackup, saveCredentialBackup } = await import("./credential-backup.js");
168+
saveCredentialBackup("default", "", "secret");
169+
saveCredentialBackup("default", "app", "");
170+
171+
expect(loadCredentialBackup("default")).toBeNull();
172+
expect(readCredentialRows(process.env.OPENCLAW_STATE_DIR!)).toHaveLength(0);
87173
});
88174
});

0 commit comments

Comments
 (0)