@openclaw/nostr 2026.1.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +51 -0
- package/README.md +136 -0
- package/index.ts +69 -0
- package/openclaw.plugin.json +11 -0
- package/package.json +31 -0
- package/src/channel.test.ts +141 -0
- package/src/channel.ts +342 -0
- package/src/config-schema.ts +90 -0
- package/src/metrics.ts +464 -0
- package/src/nostr-bus.fuzz.test.ts +544 -0
- package/src/nostr-bus.integration.test.ts +452 -0
- package/src/nostr-bus.test.ts +199 -0
- package/src/nostr-bus.ts +741 -0
- package/src/nostr-profile-http.test.ts +378 -0
- package/src/nostr-profile-http.ts +500 -0
- package/src/nostr-profile-import.test.ts +120 -0
- package/src/nostr-profile-import.ts +259 -0
- package/src/nostr-profile.fuzz.test.ts +479 -0
- package/src/nostr-profile.test.ts +410 -0
- package/src/nostr-profile.ts +242 -0
- package/src/nostr-state-store.test.ts +129 -0
- package/src/nostr-state-store.ts +226 -0
- package/src/runtime.ts +14 -0
- package/src/seen-tracker.ts +271 -0
- package/src/types.test.ts +161 -0
- package/src/types.ts +99 -0
- package/test/setup.ts +5 -0
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
import { describe, expect, it } from "vitest";
|
|
6
|
+
import type { PluginRuntime } from "openclaw/plugin-sdk";
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
readNostrBusState,
|
|
10
|
+
writeNostrBusState,
|
|
11
|
+
computeSinceTimestamp,
|
|
12
|
+
} from "./nostr-state-store.js";
|
|
13
|
+
import { setNostrRuntime } from "./runtime.js";
|
|
14
|
+
|
|
15
|
+
async function withTempStateDir<T>(fn: (dir: string) => Promise<T>) {
|
|
16
|
+
const previous = process.env.OPENCLAW_STATE_DIR;
|
|
17
|
+
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-nostr-"));
|
|
18
|
+
process.env.OPENCLAW_STATE_DIR = dir;
|
|
19
|
+
setNostrRuntime({
|
|
20
|
+
state: {
|
|
21
|
+
resolveStateDir: (env, homedir) => {
|
|
22
|
+
const override =
|
|
23
|
+
env.OPENCLAW_STATE_DIR?.trim() || env.OPENCLAW_STATE_DIR?.trim();
|
|
24
|
+
if (override) return override;
|
|
25
|
+
return path.join(homedir(), ".openclaw");
|
|
26
|
+
},
|
|
27
|
+
},
|
|
28
|
+
} as PluginRuntime);
|
|
29
|
+
try {
|
|
30
|
+
return await fn(dir);
|
|
31
|
+
} finally {
|
|
32
|
+
if (previous === undefined) delete process.env.OPENCLAW_STATE_DIR;
|
|
33
|
+
else process.env.OPENCLAW_STATE_DIR = previous;
|
|
34
|
+
await fs.rm(dir, { recursive: true, force: true });
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
describe("nostr bus state store", () => {
|
|
39
|
+
it("persists and reloads state across restarts", async () => {
|
|
40
|
+
await withTempStateDir(async () => {
|
|
41
|
+
// Fresh start - no state
|
|
42
|
+
expect(await readNostrBusState({ accountId: "test-bot" })).toBeNull();
|
|
43
|
+
|
|
44
|
+
// Write state
|
|
45
|
+
await writeNostrBusState({
|
|
46
|
+
accountId: "test-bot",
|
|
47
|
+
lastProcessedAt: 1700000000,
|
|
48
|
+
gatewayStartedAt: 1700000100,
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
// Read it back
|
|
52
|
+
const state = await readNostrBusState({ accountId: "test-bot" });
|
|
53
|
+
expect(state).toEqual({
|
|
54
|
+
version: 2,
|
|
55
|
+
lastProcessedAt: 1700000000,
|
|
56
|
+
gatewayStartedAt: 1700000100,
|
|
57
|
+
recentEventIds: [],
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it("isolates state by accountId", async () => {
|
|
63
|
+
await withTempStateDir(async () => {
|
|
64
|
+
await writeNostrBusState({
|
|
65
|
+
accountId: "bot-a",
|
|
66
|
+
lastProcessedAt: 1000,
|
|
67
|
+
gatewayStartedAt: 1000,
|
|
68
|
+
});
|
|
69
|
+
await writeNostrBusState({
|
|
70
|
+
accountId: "bot-b",
|
|
71
|
+
lastProcessedAt: 2000,
|
|
72
|
+
gatewayStartedAt: 2000,
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
const stateA = await readNostrBusState({ accountId: "bot-a" });
|
|
76
|
+
const stateB = await readNostrBusState({ accountId: "bot-b" });
|
|
77
|
+
|
|
78
|
+
expect(stateA?.lastProcessedAt).toBe(1000);
|
|
79
|
+
expect(stateB?.lastProcessedAt).toBe(2000);
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
describe("computeSinceTimestamp", () => {
|
|
85
|
+
it("returns now for null state (fresh start)", () => {
|
|
86
|
+
const now = 1700000000;
|
|
87
|
+
expect(computeSinceTimestamp(null, now)).toBe(now);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it("uses lastProcessedAt when available", () => {
|
|
91
|
+
const state = {
|
|
92
|
+
version: 2,
|
|
93
|
+
lastProcessedAt: 1699999000,
|
|
94
|
+
gatewayStartedAt: null,
|
|
95
|
+
recentEventIds: [],
|
|
96
|
+
};
|
|
97
|
+
expect(computeSinceTimestamp(state, 1700000000)).toBe(1699999000);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("uses gatewayStartedAt when lastProcessedAt is null", () => {
|
|
101
|
+
const state = {
|
|
102
|
+
version: 2,
|
|
103
|
+
lastProcessedAt: null,
|
|
104
|
+
gatewayStartedAt: 1699998000,
|
|
105
|
+
recentEventIds: [],
|
|
106
|
+
};
|
|
107
|
+
expect(computeSinceTimestamp(state, 1700000000)).toBe(1699998000);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it("uses the max of both timestamps", () => {
|
|
111
|
+
const state = {
|
|
112
|
+
version: 2,
|
|
113
|
+
lastProcessedAt: 1699999000,
|
|
114
|
+
gatewayStartedAt: 1699998000,
|
|
115
|
+
recentEventIds: [],
|
|
116
|
+
};
|
|
117
|
+
expect(computeSinceTimestamp(state, 1700000000)).toBe(1699999000);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it("falls back to now if both are null", () => {
|
|
121
|
+
const state = {
|
|
122
|
+
version: 2,
|
|
123
|
+
lastProcessedAt: null,
|
|
124
|
+
gatewayStartedAt: null,
|
|
125
|
+
recentEventIds: [],
|
|
126
|
+
};
|
|
127
|
+
expect(computeSinceTimestamp(state, 1700000000)).toBe(1700000000);
|
|
128
|
+
});
|
|
129
|
+
});
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
import { getNostrRuntime } from "./runtime.js";
|
|
7
|
+
|
|
8
|
+
const STORE_VERSION = 2;
|
|
9
|
+
const PROFILE_STATE_VERSION = 1;
|
|
10
|
+
|
|
11
|
+
type NostrBusStateV1 = {
|
|
12
|
+
version: 1;
|
|
13
|
+
/** Unix timestamp (seconds) of the last processed event */
|
|
14
|
+
lastProcessedAt: number | null;
|
|
15
|
+
/** Gateway startup timestamp (seconds) - events before this are old */
|
|
16
|
+
gatewayStartedAt: number | null;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
type NostrBusState = {
|
|
20
|
+
version: 2;
|
|
21
|
+
/** Unix timestamp (seconds) of the last processed event */
|
|
22
|
+
lastProcessedAt: number | null;
|
|
23
|
+
/** Gateway startup timestamp (seconds) - events before this are old */
|
|
24
|
+
gatewayStartedAt: number | null;
|
|
25
|
+
/** Recent processed event IDs for overlap dedupe across restarts */
|
|
26
|
+
recentEventIds: string[];
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/** Profile publish state (separate from bus state) */
|
|
30
|
+
export type NostrProfileState = {
|
|
31
|
+
version: 1;
|
|
32
|
+
/** Unix timestamp (seconds) of last successful profile publish */
|
|
33
|
+
lastPublishedAt: number | null;
|
|
34
|
+
/** Event ID of the last published profile */
|
|
35
|
+
lastPublishedEventId: string | null;
|
|
36
|
+
/** Per-relay publish results from last attempt */
|
|
37
|
+
lastPublishResults: Record<string, "ok" | "failed" | "timeout"> | null;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
function normalizeAccountId(accountId?: string): string {
|
|
41
|
+
const trimmed = accountId?.trim();
|
|
42
|
+
if (!trimmed) return "default";
|
|
43
|
+
return trimmed.replace(/[^a-z0-9._-]+/gi, "_");
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function resolveNostrStatePath(
|
|
47
|
+
accountId?: string,
|
|
48
|
+
env: NodeJS.ProcessEnv = process.env
|
|
49
|
+
): string {
|
|
50
|
+
const stateDir = getNostrRuntime().state.resolveStateDir(env, os.homedir);
|
|
51
|
+
const normalized = normalizeAccountId(accountId);
|
|
52
|
+
return path.join(stateDir, "nostr", `bus-state-${normalized}.json`);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function resolveNostrProfileStatePath(
|
|
56
|
+
accountId?: string,
|
|
57
|
+
env: NodeJS.ProcessEnv = process.env
|
|
58
|
+
): string {
|
|
59
|
+
const stateDir = getNostrRuntime().state.resolveStateDir(env, os.homedir);
|
|
60
|
+
const normalized = normalizeAccountId(accountId);
|
|
61
|
+
return path.join(stateDir, "nostr", `profile-state-${normalized}.json`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function safeParseState(raw: string): NostrBusState | null {
|
|
65
|
+
try {
|
|
66
|
+
const parsed = JSON.parse(raw) as Partial<NostrBusState> & Partial<NostrBusStateV1>;
|
|
67
|
+
|
|
68
|
+
if (parsed?.version === 2) {
|
|
69
|
+
return {
|
|
70
|
+
version: 2,
|
|
71
|
+
lastProcessedAt: typeof parsed.lastProcessedAt === "number" ? parsed.lastProcessedAt : null,
|
|
72
|
+
gatewayStartedAt: typeof parsed.gatewayStartedAt === "number" ? parsed.gatewayStartedAt : null,
|
|
73
|
+
recentEventIds: Array.isArray(parsed.recentEventIds)
|
|
74
|
+
? parsed.recentEventIds.filter((x): x is string => typeof x === "string")
|
|
75
|
+
: [],
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Back-compat: v1 state files
|
|
80
|
+
if (parsed?.version === 1) {
|
|
81
|
+
return {
|
|
82
|
+
version: 2,
|
|
83
|
+
lastProcessedAt: typeof parsed.lastProcessedAt === "number" ? parsed.lastProcessedAt : null,
|
|
84
|
+
gatewayStartedAt: typeof parsed.gatewayStartedAt === "number" ? parsed.gatewayStartedAt : null,
|
|
85
|
+
recentEventIds: [],
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return null;
|
|
90
|
+
} catch {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function readNostrBusState(params: {
|
|
96
|
+
accountId?: string;
|
|
97
|
+
env?: NodeJS.ProcessEnv;
|
|
98
|
+
}): Promise<NostrBusState | null> {
|
|
99
|
+
const filePath = resolveNostrStatePath(params.accountId, params.env);
|
|
100
|
+
try {
|
|
101
|
+
const raw = await fs.readFile(filePath, "utf-8");
|
|
102
|
+
return safeParseState(raw);
|
|
103
|
+
} catch (err) {
|
|
104
|
+
const code = (err as { code?: string }).code;
|
|
105
|
+
if (code === "ENOENT") return null;
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export async function writeNostrBusState(params: {
|
|
111
|
+
accountId?: string;
|
|
112
|
+
lastProcessedAt: number;
|
|
113
|
+
gatewayStartedAt: number;
|
|
114
|
+
recentEventIds?: string[];
|
|
115
|
+
env?: NodeJS.ProcessEnv;
|
|
116
|
+
}): Promise<void> {
|
|
117
|
+
const filePath = resolveNostrStatePath(params.accountId, params.env);
|
|
118
|
+
const dir = path.dirname(filePath);
|
|
119
|
+
await fs.mkdir(dir, { recursive: true, mode: 0o700 });
|
|
120
|
+
const tmp = path.join(
|
|
121
|
+
dir,
|
|
122
|
+
`${path.basename(filePath)}.${crypto.randomUUID()}.tmp`
|
|
123
|
+
);
|
|
124
|
+
const payload: NostrBusState = {
|
|
125
|
+
version: STORE_VERSION,
|
|
126
|
+
lastProcessedAt: params.lastProcessedAt,
|
|
127
|
+
gatewayStartedAt: params.gatewayStartedAt,
|
|
128
|
+
recentEventIds: (params.recentEventIds ?? []).filter((x): x is string => typeof x === "string"),
|
|
129
|
+
};
|
|
130
|
+
await fs.writeFile(tmp, `${JSON.stringify(payload, null, 2)}\n`, {
|
|
131
|
+
encoding: "utf-8",
|
|
132
|
+
});
|
|
133
|
+
await fs.chmod(tmp, 0o600);
|
|
134
|
+
await fs.rename(tmp, filePath);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Determine the `since` timestamp for subscription.
|
|
139
|
+
* Returns the later of: lastProcessedAt or gatewayStartedAt (both from disk),
|
|
140
|
+
* falling back to `now` for fresh starts.
|
|
141
|
+
*/
|
|
142
|
+
export function computeSinceTimestamp(
|
|
143
|
+
state: NostrBusState | null,
|
|
144
|
+
nowSec: number = Math.floor(Date.now() / 1000)
|
|
145
|
+
): number {
|
|
146
|
+
if (!state) return nowSec;
|
|
147
|
+
|
|
148
|
+
// Use the most recent timestamp we have
|
|
149
|
+
const candidates = [
|
|
150
|
+
state.lastProcessedAt,
|
|
151
|
+
state.gatewayStartedAt,
|
|
152
|
+
].filter((t): t is number => t !== null && t > 0);
|
|
153
|
+
|
|
154
|
+
if (candidates.length === 0) return nowSec;
|
|
155
|
+
return Math.max(...candidates);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// ============================================================================
|
|
159
|
+
// Profile State Management
|
|
160
|
+
// ============================================================================
|
|
161
|
+
|
|
162
|
+
function safeParseProfileState(raw: string): NostrProfileState | null {
|
|
163
|
+
try {
|
|
164
|
+
const parsed = JSON.parse(raw) as Partial<NostrProfileState>;
|
|
165
|
+
|
|
166
|
+
if (parsed?.version === 1) {
|
|
167
|
+
return {
|
|
168
|
+
version: 1,
|
|
169
|
+
lastPublishedAt:
|
|
170
|
+
typeof parsed.lastPublishedAt === "number" ? parsed.lastPublishedAt : null,
|
|
171
|
+
lastPublishedEventId:
|
|
172
|
+
typeof parsed.lastPublishedEventId === "string" ? parsed.lastPublishedEventId : null,
|
|
173
|
+
lastPublishResults:
|
|
174
|
+
parsed.lastPublishResults && typeof parsed.lastPublishResults === "object"
|
|
175
|
+
? (parsed.lastPublishResults as Record<string, "ok" | "failed" | "timeout">)
|
|
176
|
+
: null,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
return null;
|
|
181
|
+
} catch {
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export async function readNostrProfileState(params: {
|
|
187
|
+
accountId?: string;
|
|
188
|
+
env?: NodeJS.ProcessEnv;
|
|
189
|
+
}): Promise<NostrProfileState | null> {
|
|
190
|
+
const filePath = resolveNostrProfileStatePath(params.accountId, params.env);
|
|
191
|
+
try {
|
|
192
|
+
const raw = await fs.readFile(filePath, "utf-8");
|
|
193
|
+
return safeParseProfileState(raw);
|
|
194
|
+
} catch (err) {
|
|
195
|
+
const code = (err as { code?: string }).code;
|
|
196
|
+
if (code === "ENOENT") return null;
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export async function writeNostrProfileState(params: {
|
|
202
|
+
accountId?: string;
|
|
203
|
+
lastPublishedAt: number;
|
|
204
|
+
lastPublishedEventId: string;
|
|
205
|
+
lastPublishResults: Record<string, "ok" | "failed" | "timeout">;
|
|
206
|
+
env?: NodeJS.ProcessEnv;
|
|
207
|
+
}): Promise<void> {
|
|
208
|
+
const filePath = resolveNostrProfileStatePath(params.accountId, params.env);
|
|
209
|
+
const dir = path.dirname(filePath);
|
|
210
|
+
await fs.mkdir(dir, { recursive: true, mode: 0o700 });
|
|
211
|
+
const tmp = path.join(
|
|
212
|
+
dir,
|
|
213
|
+
`${path.basename(filePath)}.${crypto.randomUUID()}.tmp`
|
|
214
|
+
);
|
|
215
|
+
const payload: NostrProfileState = {
|
|
216
|
+
version: PROFILE_STATE_VERSION,
|
|
217
|
+
lastPublishedAt: params.lastPublishedAt,
|
|
218
|
+
lastPublishedEventId: params.lastPublishedEventId,
|
|
219
|
+
lastPublishResults: params.lastPublishResults,
|
|
220
|
+
};
|
|
221
|
+
await fs.writeFile(tmp, `${JSON.stringify(payload, null, 2)}\n`, {
|
|
222
|
+
encoding: "utf-8",
|
|
223
|
+
});
|
|
224
|
+
await fs.chmod(tmp, 0o600);
|
|
225
|
+
await fs.rename(tmp, filePath);
|
|
226
|
+
}
|
package/src/runtime.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { PluginRuntime } from "openclaw/plugin-sdk";
|
|
2
|
+
|
|
3
|
+
let runtime: PluginRuntime | null = null;
|
|
4
|
+
|
|
5
|
+
export function setNostrRuntime(next: PluginRuntime): void {
|
|
6
|
+
runtime = next;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function getNostrRuntime(): PluginRuntime {
|
|
10
|
+
if (!runtime) {
|
|
11
|
+
throw new Error("Nostr runtime not initialized");
|
|
12
|
+
}
|
|
13
|
+
return runtime;
|
|
14
|
+
}
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LRU-based seen event tracker with TTL support.
|
|
3
|
+
* Prevents unbounded memory growth under high load or abuse.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export interface SeenTrackerOptions {
|
|
7
|
+
/** Maximum number of entries to track (default: 100,000) */
|
|
8
|
+
maxEntries?: number;
|
|
9
|
+
/** TTL in milliseconds (default: 1 hour) */
|
|
10
|
+
ttlMs?: number;
|
|
11
|
+
/** Prune interval in milliseconds (default: 10 minutes) */
|
|
12
|
+
pruneIntervalMs?: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface SeenTracker {
|
|
16
|
+
/** Check if an ID has been seen (also marks it as seen if not) */
|
|
17
|
+
has: (id: string) => boolean;
|
|
18
|
+
/** Mark an ID as seen */
|
|
19
|
+
add: (id: string) => void;
|
|
20
|
+
/** Check if ID exists without marking */
|
|
21
|
+
peek: (id: string) => boolean;
|
|
22
|
+
/** Delete an ID */
|
|
23
|
+
delete: (id: string) => void;
|
|
24
|
+
/** Clear all entries */
|
|
25
|
+
clear: () => void;
|
|
26
|
+
/** Get current size */
|
|
27
|
+
size: () => number;
|
|
28
|
+
/** Stop the pruning timer */
|
|
29
|
+
stop: () => void;
|
|
30
|
+
/** Pre-seed with IDs (useful for restart recovery) */
|
|
31
|
+
seed: (ids: string[]) => void;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
interface Entry {
|
|
35
|
+
seenAt: number;
|
|
36
|
+
// For LRU: track order via doubly-linked list
|
|
37
|
+
prev: string | null;
|
|
38
|
+
next: string | null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Create a new seen tracker with LRU eviction and TTL expiration.
|
|
43
|
+
*/
|
|
44
|
+
export function createSeenTracker(options?: SeenTrackerOptions): SeenTracker {
|
|
45
|
+
const maxEntries = options?.maxEntries ?? 100_000;
|
|
46
|
+
const ttlMs = options?.ttlMs ?? 60 * 60 * 1000; // 1 hour
|
|
47
|
+
const pruneIntervalMs = options?.pruneIntervalMs ?? 10 * 60 * 1000; // 10 minutes
|
|
48
|
+
|
|
49
|
+
// Main storage
|
|
50
|
+
const entries = new Map<string, Entry>();
|
|
51
|
+
|
|
52
|
+
// LRU tracking: head = most recent, tail = least recent
|
|
53
|
+
let head: string | null = null;
|
|
54
|
+
let tail: string | null = null;
|
|
55
|
+
|
|
56
|
+
// Move an entry to the front (most recently used)
|
|
57
|
+
function moveToFront(id: string): void {
|
|
58
|
+
const entry = entries.get(id);
|
|
59
|
+
if (!entry) return;
|
|
60
|
+
|
|
61
|
+
// Already at front
|
|
62
|
+
if (head === id) return;
|
|
63
|
+
|
|
64
|
+
// Remove from current position
|
|
65
|
+
if (entry.prev) {
|
|
66
|
+
const prevEntry = entries.get(entry.prev);
|
|
67
|
+
if (prevEntry) prevEntry.next = entry.next;
|
|
68
|
+
}
|
|
69
|
+
if (entry.next) {
|
|
70
|
+
const nextEntry = entries.get(entry.next);
|
|
71
|
+
if (nextEntry) nextEntry.prev = entry.prev;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Update tail if this was the tail
|
|
75
|
+
if (tail === id) {
|
|
76
|
+
tail = entry.prev;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Move to front
|
|
80
|
+
entry.prev = null;
|
|
81
|
+
entry.next = head;
|
|
82
|
+
if (head) {
|
|
83
|
+
const headEntry = entries.get(head);
|
|
84
|
+
if (headEntry) headEntry.prev = id;
|
|
85
|
+
}
|
|
86
|
+
head = id;
|
|
87
|
+
|
|
88
|
+
// If no tail, this is also the tail
|
|
89
|
+
if (!tail) tail = id;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Remove an entry from the linked list
|
|
93
|
+
function removeFromList(id: string): void {
|
|
94
|
+
const entry = entries.get(id);
|
|
95
|
+
if (!entry) return;
|
|
96
|
+
|
|
97
|
+
if (entry.prev) {
|
|
98
|
+
const prevEntry = entries.get(entry.prev);
|
|
99
|
+
if (prevEntry) prevEntry.next = entry.next;
|
|
100
|
+
} else {
|
|
101
|
+
head = entry.next;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (entry.next) {
|
|
105
|
+
const nextEntry = entries.get(entry.next);
|
|
106
|
+
if (nextEntry) nextEntry.prev = entry.prev;
|
|
107
|
+
} else {
|
|
108
|
+
tail = entry.prev;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Evict the least recently used entry
|
|
113
|
+
function evictLRU(): void {
|
|
114
|
+
if (!tail) return;
|
|
115
|
+
const idToEvict = tail;
|
|
116
|
+
removeFromList(idToEvict);
|
|
117
|
+
entries.delete(idToEvict);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Prune expired entries
|
|
121
|
+
function pruneExpired(): void {
|
|
122
|
+
const now = Date.now();
|
|
123
|
+
const toDelete: string[] = [];
|
|
124
|
+
|
|
125
|
+
for (const [id, entry] of entries) {
|
|
126
|
+
if (now - entry.seenAt > ttlMs) {
|
|
127
|
+
toDelete.push(id);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
for (const id of toDelete) {
|
|
132
|
+
removeFromList(id);
|
|
133
|
+
entries.delete(id);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Start pruning timer
|
|
138
|
+
let pruneTimer: ReturnType<typeof setInterval> | undefined;
|
|
139
|
+
if (pruneIntervalMs > 0) {
|
|
140
|
+
pruneTimer = setInterval(pruneExpired, pruneIntervalMs);
|
|
141
|
+
// Don't keep process alive just for pruning
|
|
142
|
+
if (pruneTimer.unref) pruneTimer.unref();
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function add(id: string): void {
|
|
146
|
+
const now = Date.now();
|
|
147
|
+
|
|
148
|
+
// If already exists, update and move to front
|
|
149
|
+
const existing = entries.get(id);
|
|
150
|
+
if (existing) {
|
|
151
|
+
existing.seenAt = now;
|
|
152
|
+
moveToFront(id);
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Evict if at capacity
|
|
157
|
+
while (entries.size >= maxEntries) {
|
|
158
|
+
evictLRU();
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Add new entry at front
|
|
162
|
+
const newEntry: Entry = {
|
|
163
|
+
seenAt: now,
|
|
164
|
+
prev: null,
|
|
165
|
+
next: head,
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
if (head) {
|
|
169
|
+
const headEntry = entries.get(head);
|
|
170
|
+
if (headEntry) headEntry.prev = id;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
entries.set(id, newEntry);
|
|
174
|
+
head = id;
|
|
175
|
+
if (!tail) tail = id;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function has(id: string): boolean {
|
|
179
|
+
const entry = entries.get(id);
|
|
180
|
+
if (!entry) {
|
|
181
|
+
add(id);
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// Check if expired
|
|
186
|
+
if (Date.now() - entry.seenAt > ttlMs) {
|
|
187
|
+
removeFromList(id);
|
|
188
|
+
entries.delete(id);
|
|
189
|
+
add(id);
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Mark as recently used
|
|
194
|
+
entry.seenAt = Date.now();
|
|
195
|
+
moveToFront(id);
|
|
196
|
+
return true;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function peek(id: string): boolean {
|
|
200
|
+
const entry = entries.get(id);
|
|
201
|
+
if (!entry) return false;
|
|
202
|
+
|
|
203
|
+
// Check if expired
|
|
204
|
+
if (Date.now() - entry.seenAt > ttlMs) {
|
|
205
|
+
removeFromList(id);
|
|
206
|
+
entries.delete(id);
|
|
207
|
+
return false;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function deleteEntry(id: string): void {
|
|
214
|
+
if (entries.has(id)) {
|
|
215
|
+
removeFromList(id);
|
|
216
|
+
entries.delete(id);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function clear(): void {
|
|
221
|
+
entries.clear();
|
|
222
|
+
head = null;
|
|
223
|
+
tail = null;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function size(): number {
|
|
227
|
+
return entries.size;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function stop(): void {
|
|
231
|
+
if (pruneTimer) {
|
|
232
|
+
clearInterval(pruneTimer);
|
|
233
|
+
pruneTimer = undefined;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function seed(ids: string[]): void {
|
|
238
|
+
const now = Date.now();
|
|
239
|
+
// Seed in reverse order so first IDs end up at front
|
|
240
|
+
for (let i = ids.length - 1; i >= 0; i--) {
|
|
241
|
+
const id = ids[i];
|
|
242
|
+
if (!entries.has(id) && entries.size < maxEntries) {
|
|
243
|
+
const newEntry: Entry = {
|
|
244
|
+
seenAt: now,
|
|
245
|
+
prev: null,
|
|
246
|
+
next: head,
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
if (head) {
|
|
250
|
+
const headEntry = entries.get(head);
|
|
251
|
+
if (headEntry) headEntry.prev = id;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
entries.set(id, newEntry);
|
|
255
|
+
head = id;
|
|
256
|
+
if (!tail) tail = id;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
return {
|
|
262
|
+
has,
|
|
263
|
+
add,
|
|
264
|
+
peek,
|
|
265
|
+
delete: deleteEntry,
|
|
266
|
+
clear,
|
|
267
|
+
size,
|
|
268
|
+
stop,
|
|
269
|
+
seed,
|
|
270
|
+
};
|
|
271
|
+
}
|