UNPKG

@mastra/core

Version:
298 lines • 13 kB
import type { MastraServerCache } from '../cache/base.js'; import type { IMastraLogger } from '../logger/index.js'; import { PubSub } from './pubsub.js'; import type { LeaseProvider } 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; /** * Use Redis Cluster hash tags for replay keys. Opt in only for new logs or * after existing logs have expired; the default preserves legacy keys. */ keyFormat?: 'redis-cluster'; /** * Optional per-topic caching policy. Defaults to caching every topic. * * Returning `false` takes the same path as a `localOnly` publish: no list * entry, no index, no counter allocation — the event is handed straight to * the inner PubSub and still delivered live. * * This exists because `localOnly` is not always visible here. When a caller * wraps a PubSub that itself decides `localOnly` (e.g. the `mastra.pubsub` * proxy), the cache runs *above* that decision and never sees the flag, so * the policy has to be supplied at construction time instead. */ shouldCache?: (topic: string) => boolean; /** * Only append to topics whose log this cache already holds. A publish to a * topic with no log is delivered live and unnumbered, and `onUnlogged` is * called with the topic. * * A process-local cache can only number a topic's frames consistently in the * process that started its log. Another process numbering the same topic * from 0 in its own cache would produce indices that observers drop as * duplicates. * * @internal */ extendExistingLogsOnly?: boolean; /** * Called when `extendExistingLogsOnly` leaves a publish unnumbered. * * @internal */ onUnlogged?: (topic: string) => void; /** * @deprecated No longer used. Evented steps now cache their frames when they * publish, so nothing needs to be copied in from another PubSub. Accepted and * ignored for compatibility. */ source?: PubSub; } /** * 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. * * ## One append path * * Every cached publish goes through {@link MastraServerCache.listPushIndexed}, * which allocates the frame's index and appends it. The cache list is * therefore the run's log, and the transport only carries the * live tail of that log. Subscribers hold a single integer cursor and backfill * any gap they observe from the log rather than relying on transport replay. * * A list position is not necessarily its index: a cache whose append is not * atomic can allocate an index and then fail to push the frame, leaving a hole * that shifts every later frame to a lower position. Reads go through * `readLogFrom`, which uses the counter minus the list length to find where * index `from` can start, and returns entries in index order. A frame whose * cache write failed is not recoverable. * * Limitation: a non-atomic append (the default * {@link MastraServerCache.listPushIndexed}, or Redis after its CROSSSLOT * fallback) can also let concurrent publishes store frames out of order. An * entry that lands below the computed start position is then missed, e.g. * the log `[0, 2, 1, 3]` read from index 2 loses index 2. Removing that needs * an atomic append. * * If caching a frame fails, it is published without an index and delivered * live only. * * ## Batching * * `CachingPubSub` is transparent to `options.batch`: `subscribe()` forwards * the option to the inner PubSub, and `supportsNativeBatching` mirrors the * inner's value. Wrapping a non-native inner with `{ batch: {...} }` results * in unbatched delivery — use an inner that returns * `supportsNativeBatching === true` (e.g. `EventEmitterPubSub`) if you need * batched delivery. * * @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 keyFormat; private readonly logger?; private readonly shouldCache?; private readonly extendExistingLogsOnly; private readonly onUnlogged?; /** Maps original callbacks to their wrapped versions for proper unsubscribe */ private callbackMap; /** * Log indices per topic that were appended to the cache but whose live * publish threw. The frame stays in the log (late subscribers still replay * it), but the transport never carried it, so readers must not wait for it * to arrive. */ private undeliveredIndices; constructor(inner: PubSub, cache: MastraServerCache, options?: CachingPubSubOptions); /** * @deprecated No longer used; see {@link CachingPubSubOptions.source}. Kept as * a no-op for compatibility. */ __setSource(_source: PubSub | undefined): void; /** Unwrap to the inner transport so capability checks see through this decorator. */ __rawBus(): PubSub; get supportsNativeBatching(): boolean; get supportsOffsets(): boolean; get redeliversUnacked(): boolean; /** * Topics `shouldCache` leaves out only reach the inner transport. With * `extendExistingLogsOnly`, a process that doesn't hold a run's log * publishes it live only; that setup is already warned about (`onUnlogged`) * and its replays miss those frames whatever they carry, so it still counts * as kept. */ __replaysTopic(topic: string): boolean; /** * Log an error message using the configured logger or console.error. */ private logError; /** * Log a warning using the configured logger or console.warn. */ private logWarn; /** Get the cache key for a topic's event list. */ private getCacheKey; /** Get the cache key for a topic's index counter in the same Redis slot. */ private getCounterKey; /** * Read the log entries for `topic` whose index is `from` or later. * * Each hole left by an allocated-but-unpushed index moves later entries one * position below their index, so slicing at `from` would skip them. The * counter minus the list length is the number of holes; start that many * positions earlier and filter by index. When either value is unavailable * (a failed read, or a cache whose `get` does not return counters), read * the whole log instead. * * Numbered entries are returned in index order, followed by unnumbered * ones, because a non-atomic append can store frames out of order. */ private readLogFrom; publish(topic: string, event: Omit<Event, 'id' | 'createdAt' | 'index'>, options?: { localOnly?: boolean; }): Promise<void>; private hasLog; /** * Log indices this instance cached for `topic` but failed to publish to the * inner transport. Readers exclude them when waiting for the log to reach * them: those frames are replayed to late subscribers, but the live * subscription will never deliver them. * * Only the publishing process knows these indices. A reader in another * process sharing the cache still waits out its pending-frame deadline for * a frame a remote publisher could not send. */ getUndeliveredIndices(topic: string): ReadonlySet<number>; /** * 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. * Delegates to {@link subscribeFromOffset} with offset 0. */ subscribeWithReplay(topic: string, cb: EventCallback): Promise<void>; /** * Subscribe to a topic with replay starting at a specific index. * * The subscriber keeps one cursor, `next`, and every frame it receives is * reconciled against it: * - `index < next` — already delivered (transport replay, retry, or a * duplicate) → dropped. * - `index === next` — the next frame in the log → delivered. * - `index > next` — frames arrived out of order. Because a frame is appended * to the log before it is published, the missing frames are already in the * log, so they are read back in order and delivered before this one. That * holds even when the transport replays nothing at all. * * One exception to the first rule: a frame numbered `0` whose counter shows * the log restarted. That means the retained log expired or was cleared and * a new run segment began numbering at 0; the cursor resyncs and the frame is * delivered, instead of silently dropping the whole new segment. Nack * redeliveries (`deliveryAttempt > 1`) also bypass reconciliation, since a * retry of an already-cursor-advanced frame still has to reach the consumer. * * When the log no longer holds the missing range (no shared cache, or the * TTL lapsed) there is nothing to replay; the cursor resynchronises to the * frame in hand so live delivery continues. * * @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, from index `offset` on. */ getHistory(topic: string, offset?: number): Promise<Event[]>; /** * Flush any pending operations on the inner PubSub. */ flush(): Promise<void>; /** * Expose the inner's {@link LeaseProvider} when it has one, otherwise * `undefined`. Leasing is a capability of the underlying backend * (e.g. Redis), not of the caching decorator itself — so rather than * unconditionally declaring lease methods (which would make * {@link isLeaseProvider} report `true` even when the inner can't * coordinate a lock), we surface the inner's capability directly. The * signals runtime unwraps this so wrapping with caching preserves real * distributed lease semantics without faking them. */ getLeaseProvider(): LeaseProvider | undefined; /** * Clear cached events for a specific topic (and the index counter), and * forward the clear to the inner transport. * * Call this when a stream completes to free memory. The forward matters for * persistent inner transports (e.g. Redis Streams): without it, wrapping a * pubsub in `CachingPubSub` silently turns `clearTopic` into a cache-only * no-op and the inner stream leaks forever. */ clearTopic(topic: string): Promise<void>; /** Forward run trims to the inner transport; the per-process cache is left to its own bounds. */ trimTopic(topic: string, options: { runId: string; producedBefore?: number; retainTerminalEvents?: boolean; }): Promise<void>; /** * Get the inner PubSub instance. * Useful for accessing implementation-specific methods like close(). */ getInner(): PubSub; /** The cache holding this bus's retained frames. */ getCache(): MastraServerCache; } /** * 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