UNPKG

@mastra/core

Version:

Mastra is a framework for building AI-powered applications and agents with a modern TypeScript stack.

134 lines 4.76 kB
import type { MastraServerCache } from '../cache/base.js'; import type { IMastraLogger } from '../logger/index.js'; import { PubSub } from './pubsub.js'; import type { Event, EventCallback, SubscribeOptions } from './types.js'; /** * Options for CachingPubSub */ export interface CachingPubSubOptions { /** * Optional prefix for cache keys to namespace events. * Defaults to 'pubsub:'. */ keyPrefix?: string; /** * Optional logger for structured logging. * Falls back to console.error if not provided. */ logger?: IMastraLogger; } /** * A PubSub decorator that adds event caching and replay capabilities. * * Wraps any PubSub implementation and uses MastraServerCache to: * - Cache all published events per topic * - Enable replay of cached events for late subscribers * * This enables resumable streams - clients can disconnect and reconnect * without missing events. * * @example * ```typescript * import { EventEmitterPubSub, CachingPubSub } from '@mastra/core/events'; * import { InMemoryServerCache } from '@mastra/core/cache'; * * const cache = new InMemoryServerCache(); * const pubsub = new CachingPubSub(new EventEmitterPubSub(), cache); * * // Subscribe with replay - receives cached events first, then live * await pubsub.subscribeWithReplay('my-topic', (event) => { * console.log(event); * }); * ``` */ export declare class CachingPubSub extends PubSub { private readonly inner; private readonly cache; private readonly keyPrefix; private readonly logger?; /** Maps original callbacks to their wrapped versions for proper unsubscribe */ private callbackMap; constructor(inner: PubSub, cache: MastraServerCache, options?: CachingPubSubOptions); /** * Log an error message using the configured logger or console.error. */ private logError; /** * Get the cache key for a topic's event list */ private getCacheKey; /** * Get the cache key for a topic's index counter */ private getCounterKey; /** * Publish an event to a topic. * The event is cached with a sequential index before being published to the inner PubSub. * * Uses atomic increment for index assignment to prevent race conditions * when multiple events are published concurrently. */ publish(topic: string, event: Omit<Event, 'id' | 'createdAt' | 'index'>): Promise<void>; /** * Subscribe to live events on a topic (no replay). */ subscribe(topic: string, cb: EventCallback, options?: SubscribeOptions): Promise<void>; /** * Subscribe to a topic with automatic replay of cached events. * * Order of operations: * 1. Subscribe to live events FIRST (to avoid missing events during replay) * 2. Fetch and replay cached history * 3. Deduplicate events at the boundary using event IDs * * Each subscriber gets its own deduplication set to ensure * multiple subscribers can independently receive all events. */ subscribeWithReplay(topic: string, cb: EventCallback): Promise<void>; /** * Subscribe to a topic with replay starting from a specific index. * More efficient than full replay when the client knows their last position. * * @param topic - The topic to subscribe to * @param offset - Start replaying from this index (0-based) * @param cb - Callback invoked for each event */ subscribeFromOffset(topic: string, offset: number, cb: EventCallback): Promise<void>; /** * Unsubscribe from a topic. */ unsubscribe(topic: string, cb: EventCallback): Promise<void>; /** * Get historical events for a topic from cache. */ getHistory(topic: string, offset?: number): Promise<Event[]>; /** * Flush any pending operations. */ flush(): Promise<void>; /** * Clear cached events for a specific topic. * Call this when a stream completes to free memory. * Also clears the index counter. */ clearTopic(topic: string): Promise<void>; /** * Get the inner PubSub instance. * Useful for accessing implementation-specific methods like close(). */ getInner(): PubSub; } /** * Factory function to wrap a PubSub with caching capabilities. * * @example * ```typescript * import { withCaching, EventEmitterPubSub } from '@mastra/core/events'; * import { InMemoryServerCache } from '@mastra/core/cache'; * * const cache = new InMemoryServerCache(); * const pubsub = withCaching(new EventEmitterPubSub(), cache); * ``` */ export declare function withCaching(pubsub: PubSub, cache: MastraServerCache, options?: CachingPubSubOptions): CachingPubSub; //# sourceMappingURL=caching-pubsub.d.ts.map