77 lines
2.8 KiB
TypeScript
77 lines
2.8 KiB
TypeScript
import { type Logger } from "./logger.ts";
|
|
/**
|
|
* How to fetch and cache a given value, as passed to {@link PollingCachedValue}.
|
|
*/
|
|
export interface PollingCachedValueOptions<ValueType> {
|
|
/** The name of the cached value (for tracing/logs). */
|
|
name: string;
|
|
/** The logger to derive this value's child logger from. */
|
|
logger: Logger;
|
|
/** Fetches a fresh value. Rejections are retried according to the retry policy. */
|
|
fetch: () => Promise<ValueType>;
|
|
/**
|
|
* The default time-to-live before the value gets refreshed, overridable per run
|
|
* via {@link PollingCachedValue.start}.
|
|
* If undefined the value never expires; use {@link PollingCachedValue.refresh} to clear the cache.
|
|
*/
|
|
ttlMillis?: number;
|
|
/** Called when a new value is cached. Use to emit changes if needed. */
|
|
onValueCached?: (value: ValueType) => void;
|
|
/**
|
|
* Determines whether a non-transient error should be cached.
|
|
* By default errors are not cached, i.e. the next attempt retries the fetch.
|
|
*/
|
|
shouldCacheError?: (error: unknown) => boolean;
|
|
}
|
|
/**
|
|
* Defines a generic mechanism to fetch and cache a value, refreshing it periodically.
|
|
*/
|
|
export declare class PollingCachedValue<ValueType> {
|
|
private readonly opts;
|
|
private cached?;
|
|
private fetchPromise?;
|
|
private ttlTimeoutHandle?;
|
|
private isStopped;
|
|
private ttlMillis?;
|
|
private readonly logger;
|
|
/**
|
|
* Build a generic mechanism allowing to fetch and cache a given value.
|
|
* @param opts - Describes what to fetch and how to cache it, see {@link PollingCachedValueOptions}.
|
|
*/
|
|
constructor(opts: PollingCachedValueOptions<ValueType>);
|
|
/**
|
|
* Gets the cached value if any.
|
|
*/
|
|
get(): ValueType | undefined;
|
|
/**
|
|
* Ensures that the value was fetched once before getting the actual cached value.
|
|
*/
|
|
wait(): Promise<ValueType | undefined>;
|
|
/**
|
|
* Call this as early as possible and when the value can already be fetched.
|
|
* @param ttlMillis - The time-to-live before the value gets refreshed, overriding the one
|
|
* given at construction. If omitted the configured default is kept.
|
|
*/
|
|
start(ttlMillis?: number): void;
|
|
/**
|
|
* Call when the client is stopped, or when the cached value is no longer needed.
|
|
*/
|
|
stop(): void;
|
|
/**
|
|
* Force to refresh.
|
|
* @throws
|
|
*/
|
|
refresh(): Promise<ValueType | undefined>;
|
|
/**
|
|
* Internal fetch method
|
|
* @param force - if set to true will force a fetch of the value even if a fetch is already in progress.
|
|
* @private
|
|
*/
|
|
private doFetch;
|
|
/**
|
|
* Gracefully handle transient error retries, respect retry_after_millis for rate limits.
|
|
* @private
|
|
*/
|
|
private fetchWithRetryPolicy;
|
|
}
|
|
//# sourceMappingURL=pollingCachedValue.d.ts.map
|