1+ import { createHash } from "node:crypto" ;
12import fs from "node:fs" ;
23import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts" ;
4+ import type { PluginStateSyncKeyedStore } from "openclaw/plugin-sdk/plugin-state-runtime" ;
35import { logVerbose } from "openclaw/plugin-sdk/runtime-env" ;
4- import { replaceFileAtomicSync } from "openclaw/plugin-sdk/security-runtime" ;
56import { resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime" ;
7+ import { getTelegramRuntime } from "./runtime.js" ;
68
79const TTL_MS = 24 * 60 * 60 * 1000 ;
10+ export const TELEGRAM_POLL_CONTEXT_NAMESPACE = "telegram.poll-context" ;
11+ export const TELEGRAM_POLL_CONTEXT_MAX_ENTRIES = 10_000 ;
812const TELEGRAM_POLL_CONTEXT_STATE_KEY = Symbol . for ( "openclaw.telegramPollContextState" ) ;
13+ const TELEGRAM_POLL_CONTEXT_STORE_FOR_TEST_KEY = Symbol . for (
14+ "openclaw.telegramPollContextStoreForTest" ,
15+ ) ;
916
1017export type TelegramPollContext = {
1118 accountId : string ;
@@ -16,42 +23,82 @@ export type TelegramPollContext = {
1623 updatedAt : number ;
1724} ;
1825
19- type PollContextStore = Map < string , TelegramPollContext > ;
26+ type StoredTelegramPollContext = TelegramPollContext & {
27+ pollId : string ;
28+ scopeKey : string ;
29+ } ;
30+
31+ type PollContextStore = Map < string , StoredTelegramPollContext > ;
32+ type PollContextPersistentStore = PluginStateSyncKeyedStore < StoredTelegramPollContext > ;
2033
2134type PollContextBucket = {
22- persistedPath : string ;
35+ scopeKey : string ;
2336 store : PollContextStore ;
2437} ;
2538
2639type PollContextState = {
27- bucketsByPath : Map < string , PollContextBucket > ;
40+ bucketsByScope : Map < string , PollContextBucket > ;
2841} ;
2942
43+ let pollContextStoreForTest : PollContextPersistentStore | undefined ;
44+
45+ function getPollContextStoreForTest ( ) : PollContextPersistentStore | undefined {
46+ const globalStore = globalThis as Record < PropertyKey , unknown > ;
47+ return (
48+ pollContextStoreForTest ??
49+ ( globalStore [ TELEGRAM_POLL_CONTEXT_STORE_FOR_TEST_KEY ] as
50+ | PollContextPersistentStore
51+ | undefined )
52+ ) ;
53+ }
54+
3055function getPollContextState ( ) : PollContextState {
3156 const globalStore = globalThis as Record < PropertyKey , unknown > ;
3257 const existing = globalStore [ TELEGRAM_POLL_CONTEXT_STATE_KEY ] as PollContextState | undefined ;
3358 if ( existing ) {
3459 return existing ;
3560 }
3661 const state : PollContextState = {
37- bucketsByPath : new Map ( ) ,
62+ bucketsByScope : new Map ( ) ,
3863 } ;
3964 globalStore [ TELEGRAM_POLL_CONTEXT_STATE_KEY ] = state ;
4065 return state ;
4166}
4267
4368function createPollContextStore ( ) : PollContextStore {
44- return new Map < string , TelegramPollContext > ( ) ;
69+ return new Map < string , StoredTelegramPollContext > ( ) ;
4570}
4671
4772function resolvePollContextStorePath ( cfg ?: Pick < OpenClawConfig , "session" > ) : string {
4873 return `${ resolveStorePath ( cfg ?. session ?. store ) } .telegram-poll-context.json` ;
4974}
5075
76+ function resolvePollContextScopeKey ( cfg ?: Pick < OpenClawConfig , "session" > ) : string {
77+ const storePath = resolveStorePath ( cfg ?. session ?. store ) ;
78+ return createHash ( "sha256" ) . update ( storePath , "utf8" ) . digest ( "hex" ) . slice ( 0 , 24 ) ;
79+ }
80+
5181function buildContextKey ( accountId : string , pollId : string ) : string {
5282 return `${ accountId } :${ pollId } ` ;
5383}
5484
85+ function pollContextEntryKey ( scopeKey : string , accountId : string , pollId : string ) : string {
86+ return createHash ( "sha256" )
87+ . update ( `${ scopeKey } \0${ accountId } \0${ pollId } ` , "utf8" )
88+ . digest ( "hex" )
89+ . slice ( 0 , 32 ) ;
90+ }
91+
92+ function openPollContextStore ( ) : PollContextPersistentStore {
93+ return (
94+ getPollContextStoreForTest ( ) ??
95+ getTelegramRuntime ( ) . state . openSyncKeyedStore < StoredTelegramPollContext > ( {
96+ namespace : TELEGRAM_POLL_CONTEXT_NAMESPACE ,
97+ maxEntries : TELEGRAM_POLL_CONTEXT_MAX_ENTRIES ,
98+ } )
99+ ) ;
100+ }
101+
55102function cleanupExpired ( store : PollContextStore , now : number ) : void {
56103 for ( const [ key , entry ] of store ) {
57104 if ( now - entry . updatedAt > TTL_MS ) {
@@ -76,7 +123,7 @@ function isTelegramPollContext(value: unknown): value is TelegramPollContext {
76123 ) ;
77124}
78125
79- function readPersistedPollContexts ( filePath : string ) : PollContextStore {
126+ function readLegacyPollContexts ( filePath : string ) : PollContextStore {
80127 if ( ! fs . existsSync ( filePath ) ) {
81128 return createPollContextStore ( ) ;
82129 }
@@ -89,47 +136,100 @@ function readPersistedPollContexts(filePath: string): PollContextStore {
89136 if ( ! isTelegramPollContext ( value ) ) {
90137 continue ;
91138 }
92- if ( now - value . updatedAt > TTL_MS ) {
139+ const pollId = key . split ( ":" ) . slice ( 1 ) . join ( ":" ) . trim ( ) ;
140+ if ( ! pollId || now - value . updatedAt > TTL_MS ) {
93141 continue ;
94142 }
95- store . set ( key , value ) ;
143+ store . set ( key , {
144+ ...value ,
145+ pollId,
146+ } ) ;
96147 }
97148 return store ;
98149 } catch ( error ) {
99- logVerbose ( `telegram: failed to read poll-context cache: ${ String ( error ) } ` ) ;
150+ logVerbose ( `telegram: failed to read legacy poll-context cache: ${ String ( error ) } ` ) ;
100151 return createPollContextStore ( ) ;
101152 }
102153}
103154
155+ function readPersistedPollContexts ( scopeKey : string ) : PollContextStore {
156+ const now = Date . now ( ) ;
157+ const store = createPollContextStore ( ) ;
158+ try {
159+ for ( const entry of openPollContextStore ( ) . entries ( ) ) {
160+ if ( entry . value . scopeKey !== scopeKey || now - entry . value . updatedAt > TTL_MS ) {
161+ continue ;
162+ }
163+ store . set ( buildContextKey ( entry . value . accountId , entry . value . pollId ) , entry . value ) ;
164+ }
165+ } catch ( error ) {
166+ logVerbose ( `telegram: failed to read poll-context store: ${ String ( error ) } ` ) ;
167+ }
168+ return store ;
169+ }
170+
171+ function persistPollContexts ( bucket : PollContextBucket ) : void {
172+ const { store, scopeKey } = bucket ;
173+ const now = Date . now ( ) ;
174+ cleanupExpired ( store , now ) ;
175+ for ( const entry of store . values ( ) ) {
176+ const ttlMs = TTL_MS - Math . max ( 0 , now - entry . updatedAt ) ;
177+ if ( ttlMs <= 0 ) {
178+ continue ;
179+ }
180+ openPollContextStore ( ) . register (
181+ pollContextEntryKey ( scopeKey , entry . accountId , entry . pollId ) ,
182+ entry ,
183+ { ttlMs } ,
184+ ) ;
185+ }
186+ }
187+
188+ function migrateLegacyPollContexts (
189+ bucket : PollContextBucket ,
190+ cfg ?: Pick < OpenClawConfig , "session" > ,
191+ ) : void {
192+ const legacyPath = resolvePollContextStorePath ( cfg ) ;
193+ if ( ! fs . existsSync ( legacyPath ) ) {
194+ return ;
195+ }
196+ const legacyStore = readLegacyPollContexts ( legacyPath ) ;
197+ if ( legacyStore . size === 0 ) {
198+ fs . rmSync ( legacyPath , { force : true } ) ;
199+ return ;
200+ }
201+ for ( const [ key , entry ] of legacyStore ) {
202+ if ( ! bucket . store . has ( key ) ) {
203+ bucket . store . set ( key , {
204+ ...entry ,
205+ scopeKey : bucket . scopeKey ,
206+ } ) ;
207+ }
208+ }
209+ try {
210+ persistPollContexts ( bucket ) ;
211+ fs . rmSync ( legacyPath , { force : true } ) ;
212+ } catch ( error ) {
213+ logVerbose ( `telegram: failed to migrate legacy poll-context cache: ${ String ( error ) } ` ) ;
214+ }
215+ }
216+
104217function getPollContextBucket ( cfg ?: Pick < OpenClawConfig , "session" > ) : PollContextBucket {
105218 const state = getPollContextState ( ) ;
106- const persistedPath = resolvePollContextStorePath ( cfg ) ;
107- const existing = state . bucketsByPath . get ( persistedPath ) ;
219+ const scopeKey = resolvePollContextScopeKey ( cfg ) ;
220+ const existing = state . bucketsByScope . get ( scopeKey ) ;
108221 if ( existing ) {
109222 return existing ;
110223 }
111224 const bucket = {
112- persistedPath ,
113- store : readPersistedPollContexts ( persistedPath ) ,
225+ scopeKey ,
226+ store : readPersistedPollContexts ( scopeKey ) ,
114227 } ;
115- state . bucketsByPath . set ( persistedPath , bucket ) ;
228+ migrateLegacyPollContexts ( bucket , cfg ) ;
229+ state . bucketsByScope . set ( scopeKey , bucket ) ;
116230 return bucket ;
117231}
118232
119- function persistPollContexts ( bucket : PollContextBucket ) : void {
120- const { store, persistedPath } = bucket ;
121- cleanupExpired ( store , Date . now ( ) ) ;
122- if ( store . size === 0 ) {
123- fs . rmSync ( persistedPath , { force : true } ) ;
124- return ;
125- }
126- replaceFileAtomicSync ( {
127- filePath : persistedPath ,
128- content : JSON . stringify ( Object . fromEntries ( store ) ) ,
129- tempPrefix : ".telegram-poll-context" ,
130- } ) ;
131- }
132-
133233export function recordTelegramPollContext (
134234 pollId : string ,
135235 params : {
@@ -147,6 +247,8 @@ export function recordTelegramPollContext(
147247 }
148248 const bucket = getPollContextBucket ( cfg ) ;
149249 bucket . store . set ( buildContextKey ( params . accountId , normalizedPollId ) , {
250+ scopeKey : bucket . scopeKey ,
251+ pollId : normalizedPollId ,
150252 accountId : params . accountId ,
151253 chatId : String ( params . chatId ) ,
152254 question : params . question ,
@@ -157,7 +259,7 @@ export function recordTelegramPollContext(
157259 try {
158260 persistPollContexts ( bucket ) ;
159261 } catch ( error ) {
160- logVerbose ( `telegram: failed to persist poll-context cache : ${ String ( error ) } ` ) ;
262+ logVerbose ( `telegram: failed to persist poll-context store : ${ String ( error ) } ` ) ;
161263 }
162264}
163265
@@ -172,18 +274,35 @@ export function getTelegramPollContext(
172274 }
173275 const bucket = getPollContextBucket ( cfg ) ;
174276 cleanupExpired ( bucket . store , Date . now ( ) ) ;
175- return bucket . store . get ( buildContextKey ( accountId , normalizedPollId ) ) ;
277+ const entry = bucket . store . get ( buildContextKey ( accountId , normalizedPollId ) ) ;
278+ if ( ! entry ) {
279+ return undefined ;
280+ }
281+ const { pollId : _pollId , scopeKey : _scopeKey , ...context } = entry ;
282+ return context ;
176283}
177284
178285export function clearTelegramPollContextCache ( ) : void {
179286 const state = getPollContextState ( ) ;
180- for ( const bucket of state . bucketsByPath . values ( ) ) {
287+ for ( const bucket of state . bucketsByScope . values ( ) ) {
181288 bucket . store . clear ( ) ;
182- fs . rmSync ( bucket . persistedPath , { force : true } ) ;
183289 }
184- state . bucketsByPath . clear ( ) ;
290+ state . bucketsByScope . clear ( ) ;
291+ openPollContextStore ( ) . clear ( ) ;
185292}
186293
187294export function resetTelegramPollContextCacheForTest ( ) : void {
188- getPollContextState ( ) . bucketsByPath . clear ( ) ;
295+ getPollContextState ( ) . bucketsByScope . clear ( ) ;
296+ }
297+
298+ export function setTelegramPollContextStoreForTest (
299+ store : PollContextPersistentStore | undefined ,
300+ ) : void {
301+ pollContextStoreForTest = store ;
302+ const globalStore = globalThis as Record < PropertyKey , unknown > ;
303+ if ( store ) {
304+ globalStore [ TELEGRAM_POLL_CONTEXT_STORE_FOR_TEST_KEY ] = store ;
305+ } else {
306+ delete globalStore [ TELEGRAM_POLL_CONTEXT_STORE_FOR_TEST_KEY ] ;
307+ }
189308}
0 commit comments