@a2alite/sdk
Version:
A Modular SDK (Server & Client) for Agent to Agent (A2A) protocol, with easy task lifecycle management
74 lines (73 loc) • 2.06 kB
JavaScript
/**
* In-memory implementation of IStore<T>
*
* InMemoryStore provides a simple, non-persistent storage implementation
* suitable for development and testing. It supports TTL (time-to-live)
* with automatic cleanup of expired entries.
*
* @template T - The type of values stored in this store
*/
class InMemoryStore {
constructor() {
this.store = new Map();
}
async set(key, value, ttl) {
let expiresAt = undefined;
if (ttl && ttl > 0) {
expiresAt = Date.now() + ttl * 1000;
}
this.store.set(key, { value, expiresAt });
}
async get(key) {
const entry = this.store.get(key);
if (!entry)
return undefined;
if (entry.expiresAt && entry.expiresAt < Date.now()) {
this.store.delete(key);
return undefined;
}
return entry.value;
}
async delete(key) {
return this.store.delete(key);
}
async has(key) {
const entry = this.store.get(key);
if (!entry)
return false;
if (entry.expiresAt && entry.expiresAt < Date.now()) {
this.store.delete(key);
return false;
}
return true;
}
async clear() {
this.store.clear();
}
async keys() {
this.cleanupExpired();
return Array.from(this.store.keys());
}
async values() {
this.cleanupExpired();
return Array.from(this.store.values()).map((e) => e.value);
}
async entries() {
this.cleanupExpired();
return Array.from(this.store.entries()).map(([k, v]) => [k, v.value]);
}
/**
* Remove expired entries from the store
* Called automatically by methods that enumerate the store
* @private
*/
cleanupExpired() {
const now = Date.now();
for (const [key, entry] of this.store.entries()) {
if (entry.expiresAt && entry.expiresAt < now) {
this.store.delete(key);
}
}
}
}
export { InMemoryStore };