bentocache
Version:
Multi-tier cache module for Node.js. Redis, Upstash, CloudfareKV, File, in-memory and others drivers
1,127 lines (1,109 loc) • 32.2 kB
TypeScript
import { Exception } from '@poppinss/exception';
import { Transport } from '@boringnode/bus/types/main';
import { Logger as Logger$1, LogObject } from '@julr/utils/logger';
export { Logger } from '@julr/utils/logger';
import { Knex } from 'knex';
import { Kysely } from 'kysely';
import { DynamoDBClientConfig } from '@aws-sdk/client-dynamodb';
import { DbResult, DefaultColumnTypes, DefaultSchemaConfig } from 'orchid-orm';
import { Redis, Cluster, RedisOptions } from 'ioredis';
/**
* Thrown when a factory has timed out after waiting for soft timeout
*/
declare class FactorySoftTimeout extends Exception {
static code: string;
static message: string;
key: string;
constructor(key: string);
}
/**
* Thrown when a factory has timed out after waiting for hard timeout
*/
declare class FactoryHardTimeout extends Exception {
static code: string;
static message: string;
key: string;
constructor(key: string);
}
/**
* Thrown when a factory has thrown an error. Original error is available as `cause`
*/
declare class FactoryError extends Exception {
static code: string;
static message: string;
/**
* The key for which the factory was called
*/
key: string;
/**
* If the error was thrown by a factory
* running in the background
*/
isBackgroundFactory: boolean;
constructor(key: string, cause: any, isBackground?: boolean);
}
/**
* Thrown when a `undefined` value is about to be set
* in the cache. You can't set `undefined` values.
*/
declare class UndefinedValueError extends Exception {
static code: string;
constructor(key: string);
}
/**
* Thrown when a L2 Cache operation fail
*/
declare class L2CacheError extends Exception {
static code: string;
static message: string;
constructor(cause: any);
}
declare const errors: {
E_FACTORY_ERROR: typeof FactoryError;
E_FACTORY_SOFT_TIMEOUT: typeof FactorySoftTimeout;
E_FACTORY_HARD_TIMEOUT: typeof FactoryHardTimeout;
E_UNDEFINED_VALUE: typeof UndefinedValueError;
E_L2_CACHE_ERROR: typeof L2CacheError;
};
type PromiseOr<T, Async extends boolean> = Async extends true ? Promise<T> : T;
interface CacheDriver<Async extends boolean = true> {
/**
* Returns a new instance of the driver namespace
*/
namespace(namespace: string): CacheDriver<Async>;
/**
* Get a value from the cache
*/
get(key: string): PromiseOr<string | undefined, Async>;
/**
* Get the value of a key and delete it
*
* Returns the value if the key exists, undefined otherwise
*/
pull(key: string): PromiseOr<string | undefined, Async>;
/**
* Put a value in the cache.
* If `ttl` is not defined, the value will be stored forever
* Returns true if the value was set, false otherwise
*/
set(key: string, value: string, ttl?: number): PromiseOr<boolean, Async>;
/**
* Remove all items from the cache
*/
clear(): PromiseOr<void, Async>;
/**
* Delete a key from the cache
* Returns true if the key was deleted, false otherwise
*/
delete(key: string): PromiseOr<boolean, Async>;
/**
* Delete multiple keys from the cache
*/
deleteMany(keys: string[]): PromiseOr<boolean, Async>;
/**
* Closes the connection to the cache.
* Some drivers may not need this
*/
disconnect(): PromiseOr<void, Async>;
/**
* Manually prune expired cache entries
*
* For drivers with native TTL support, this is typically a noop
* For drivers without native TTL (PostgreSQL, File), this will remove expired entries
*/
prune?(): PromiseOr<void, Async>;
}
/**
* Interface for a DatabaseAdapter that can be used with the DatabaseDriver
*/
interface DatabaseAdapter {
/**
* Set the table name for the adapter
*/
setTableName(tableName: string): void;
/**
* Get an entry from the database
*/
get(key: string): Promise<{
value: any;
expiresAt: number | null;
} | undefined>;
/**
* Delete an entry from the database
*
* You should return true if the entry was deleted, false otherwise
*/
delete(key: string): Promise<boolean>;
/**
* Delete multiple entries from the database
*
* Should return the number of entries deleted
*/
deleteMany(keys: string[]): Promise<number>;
/**
* Disconnect from the database
*/
disconnect(): Promise<void>;
/**
* Create the cache table if it doesn't exist
*
* This method is responsible for checking it the table
* exists before creating it
*/
createTableIfNotExists(): Promise<void>;
/**
* Remove expired entries from the cache table
*/
pruneExpiredEntries(): Promise<void>;
/**
* Clear all entries from the cache table
*/
clear(prefix: string): Promise<void>;
/**
* Set a value in the cache
* You should also make sure to not create duplicate entries for the same key.
* Make sure to use `ON CONFLICT` or similar
*/
set(row: {
key: string;
value: any;
expiresAt: Date | null;
}): Promise<void>;
}
/**
* A Duration can be a number in milliseconds or a string formatted as a duration
*
* Formats accepted are :
* - Simple number in milliseconds
* - String formatted as a duration. Uses https://github.com/lukeed/ms under the hood
*/
type Duration = number | string | null;
/**
* A Factory is basically just a function that returns a value
*/
type Factory<T = any> = T | (() => T) | Promise<T> | (() => Promise<T>);
type GetSetFactoryContext = {
/**
* Dynamically set the TTL
* @see https://bentocache.dev/docs/adaptive-caching
*
* @deprecated use `setOptions` instead
*/
setTtl: (ttl: Duration) => void;
/**
* Set the options for the current factory
*/
setOptions: (options: {
ttl?: Duration;
skipBusNotify?: boolean;
skipL2Write?: boolean;
}) => void;
/**
* Set the tags for the current factory
*/
setTags: (tags: string[]) => void;
/**
* Make the factory fail with a custom error.
* Nothing will be cached and if a graced value is available, it will be returned
*/
fail: (message?: string) => void;
/**
* Make the factory do not cache anything. **If a graced value is available,
* it will not be used**
*/
skip: () => undefined;
/**
* Graced entry if available
*/
gracedEntry: {
value: any;
} | undefined;
};
/**
* GetOrSet Factory
*/
type GetSetFactory<T = any> = (options: GetSetFactoryContext) => T | Promise<T>;
/**
* Interface for the bus driver
*/
type BusDriver = Transport;
/**
* Message sent over the cache bus
*/
type CacheBusMessage = {
keys: string[];
type: CacheBusMessageType;
namespace?: string;
};
declare const CacheBusMessageType: {
/**
* An item was set in the cache
*/
Set: string;
/**
* Whole cache was cleared
*/
Clear: string;
/**
* An item was deleted from the cache
*/
Delete: string;
/**
* An item was logically expired
*/
Expire: string;
};
type CacheBusMessageType = (typeof CacheBusMessageType)[keyof typeof CacheBusMessageType];
type BusOptions = {
/**
* Configuration for the bus retry queue
*/
retryQueue?: {
/**
* If we should retry sending messages that failed to be sent
*/
enabled?: boolean;
/**
* Maximum number of messages to keep in the retry queue. Older
* messages will be discarded when the queue is full.
*/
maxSize?: number;
/**
* The interval between each retry attempt
*
* @default '2s'
*/
retryInterval?: Duration | false;
};
};
declare const busEvents: {
messagePublished(message: CacheBusMessage): {
name: string;
data: {
message: {
keys: string[];
type: string;
};
};
};
messageReceived(message: CacheBusMessage): {
name: string;
data: {
message: {
keys: string[];
type: string;
};
};
};
};
declare const cacheEvents: {
cleared(store: string): {
name: "cache:cleared";
data: {
store: string;
};
};
deleted(key: string, store: string): {
name: "cache:deleted";
data: {
key: string;
store: string;
};
};
hit(key: string, value: any, store: string, layer?: "l1" | "l2", graced?: boolean): {
name: "cache:hit";
data: {
key: string;
value: any;
store: string;
layer: "l1" | "l2";
graced: boolean;
};
};
miss(key: string, store: string): {
name: "cache:miss";
data: {
key: string;
store: string;
};
};
written(key: string, value: any, store: string): {
name: "cache:written";
data: {
key: string;
value: any;
store: string;
};
};
expire(key: string, store: string): {
name: "cache:expire";
data: {
key: string;
store: string;
};
};
};
/**
* Shape of the emitter accepted by BentoCache
* Should be compatible with node's EventEmitter and Emittery
*/
interface Emitter {
on: (event: string, callback: (...values: any[]) => void) => void;
once: (event: string, callback: (...values: any[]) => void) => void;
off: (event: string, callback: (...values: any[]) => void) => void;
emit: (event: string, ...values: any[]) => void;
}
/**
* Name/payload of the events emitted by the cache emitter
*/
type CacheEvents = {
'cache:cleared': ReturnType<typeof cacheEvents.cleared>['data'];
'cache:deleted': ReturnType<typeof cacheEvents.deleted>['data'];
'cache:hit': ReturnType<typeof cacheEvents.hit>['data'];
'cache:miss': ReturnType<typeof cacheEvents.miss>['data'];
'cache:expire': ReturnType<typeof cacheEvents.expire>['data'];
'cache:written': ReturnType<typeof cacheEvents.written>['data'];
'bus:message:published': ReturnType<typeof busEvents.messagePublished>['data'];
'bus:message:received': ReturnType<typeof busEvents.messageReceived>['data'];
};
/**
* A cache event
*/
interface CacheEvent {
name: keyof CacheEvents;
data: Record<string, any>;
}
/**
* A cache provider is a class that wraps an underlying cache driver
* to provide additional features.
*/
interface CacheProvider {
/**
* Set a value in the cache
* Returns true if the value was set, false otherwise
*/
set(options: SetOptions): Promise<boolean>;
/**
* Set a value in the cache forever
*/
setForever(options: SetOptions): Promise<boolean>;
/**
* Get a value from the cache, fallback to a default value
* and set options
*/
get<T = any>(options: GetOptions<T>): Promise<T>;
/**
* Get or set a value in the cache
*/
getOrSet<T>(options: GetOrSetOptions<T>): Promise<T>;
/**
* Get or set a value in the cache forever
*/
getOrSetForever<T>(options: GetOrSetForeverOptions<T>): Promise<T>;
/**
* Check if a key exists in the cache
*/
has(options: HasOptions): Promise<boolean>;
/**
* Check if a key is missing from the cache
*/
missing(options: HasOptions): Promise<boolean>;
/**
* Get the value of a key and delete it
*
* Returns the value if the key exists, undefined otherwise
*/
pull<T = any>(key: string): Promise<T | undefined | null>;
/**
* Delete a key from the cache
* Returns true if the key was deleted, false otherwise
*/
delete(options: DeleteOptions): Promise<boolean>;
/**
* Delete multiple keys from the cache
*/
deleteMany(options: DeleteManyOptions): Promise<boolean>;
/**
* Delete all keys with a specific tag
*/
deleteByTag(options: DeleteByTagOptions): Promise<boolean>;
/**
* Expire a key from the cache.
* Entry will not be fully deleted but expired and
* retained for the grace period if enabled.
*/
expire(options: DeleteOptions): Promise<boolean>;
/**
* Remove all items from the cache
*/
clear(options?: ClearOptions): Promise<void>;
/**
* Manually prune expired cache entries
*
* For drivers with native TTL support, this is typically a noop
* For drivers without native TTL (PostgreSQL, File), this will remove expired entries
*/
prune(): Promise<void>;
/**
* Returns a new instance of the driver namespaced
*/
namespace(namespace: string): CacheProvider;
/**
* Closes the connection to the cache
*/
disconnect(): Promise<void>;
}
/**
* These options are common to :
* - BentoCache global options
* - Driver options
* - Core methods
*/
type RawCommonOptions = {
/**
* Forces executing the factory even if a valid value is found in cache.
* Can be useful for debugging or when you want to force a refresh
* @default false
*/
forceFresh?: boolean;
/**
* The soft timeout. Once this timeout is reached,
* the factory will try to return a graced value
* if available
*
* @default 0 Means, if a graced value is available, it will be returned
* immediately and the factory will be refreshed in the background
*/
timeout?: Duration;
/**
* The hard timeout. Once this timeout is reached,
* the factory will just throw an error that will
* bubble up. You will need to handle this error
*
* @default null Means, no hard timeout
*/
hardTimeout?: Duration;
/**
* The duration for which the entry will be
* considered valid
*/
ttl?: Duration;
/**
* Grace period options
*/
grace?: false | Duration;
graceBackoff?: Duration;
/**
* Whether to suppress errors that occur when
* trying to fetch from remote (l2) cache
*/
suppressL2Errors?: boolean;
/**
* Maximum time for which a lock can try to be acquired
* before running a factory
*/
lockTimeout?: Duration;
/**
* A handler that will be called when a factory
* throws an error
*/
onFactoryError?: (error: FactoryError) => void;
/**
* Should the cache entry be written to the L2 cache
* @default false
*/
skipL2Write?: boolean;
/**
* Should the bus be used for cache invalidation
* @default false
*/
skipBusNotify?: boolean;
/**
* Duration for the circuit breaker to stay open
* if l2 cache fails
*
* @default null Means, no circuit breaker
*/
l2CircuitBreakerDuration?: Duration;
/**
* Tags that will be associated with the cache entry
*/
tags?: string[];
};
/**
* Options accepted by Bentocache
*/
type RawBentoCacheOptions = {
prefix?: string;
/**
* A logger instance that will be used to log
* multiple events occurring in the cache
*
* Pino is compatible out of the box
*/
logger?: Logger$1;
/**
* An emitter instance that will be used to
* emit multiple events occurring in the cache
*
* Emittery and node EventEmitter are compatible
* out of the box
*/
emitter?: Emitter;
/**
* Custom serializer
*/
serializer?: CacheSerializer;
} & Omit<RawCommonOptions, 'tags' | 'skipBusNotify' | 'skipL2Write'>;
/**
* The options that can be passed when creating
* a cache driver like `memoryDriver({ ... })
*/
type CacheDriverOptions = {
prefix?: string;
} & RawCommonOptions;
type CacheEntryOptions = ReturnType<typeof createCacheEntryOptions>;
/**
* Cache Entry Options. Define how a cache operation should behave
*
* Yes, this is a fake class. Initially, this was a class, but
* since CacheEntryOptions is initialized each time a cache
* operation is performed, it was converted to this
* fake class to have way better performance.
*/
declare function createCacheEntryOptions(newOptions?: RawCommonOptions, defaults?: Partial<RawCommonOptions>): {
/**
* Unique identifier that will be used when logging
* debug information.
*/
id: string;
/**
* Resolved grace period options
*/
grace: number;
graceBackoff: number;
/**
* Logical TTL is when the value is considered expired
* but still can be in the cache ( Grace period )
*/
getLogicalTtl(): number | undefined;
/**
* Physical TTL is the time when value will be automatically
* removed from the cache. This is the Grace period
* duration
*/
getPhysicalTtl(): number | undefined;
/**
* Determine if the gracing system is enabled
*/
isGraceEnabled(): boolean;
/**
* Timeouts for the cache operations
*/
timeout: number | undefined;
hardTimeout: number | undefined;
/**
* Tags to associate with the cache entry
*/
tags: string[];
/**
* Skip options
*/
skipL2Write: boolean;
skipBusNotify: boolean;
/**
* Max time to wait for the lock to be acquired
*/
lockTimeout: number | undefined;
onFactoryError: ((error: FactoryError) => void) | undefined;
suppressL2Errors: boolean | undefined;
/**
* Force fresh option
*/
forceFresh: boolean;
/**
* Returns a new instance of `CacheItemOptions` with the same
* options as the current instance, but with any provided
* options overriding the current
*
* For performance reasons, if no options are provided, the
* current instance is returned
*/
cloneWith(newOptions?: Partial<RawCommonOptions>): /*elided*/ any;
/**
* Set a new logical TTL
*/
setLogicalTtl(newTtl: Duration): /*elided*/ any;
/**
* Compute the logical TTL timestamp from now
*/
logicalTtlFromNow(): number | undefined;
/**
* Compute the physical TTL timestamp from now
*/
physicalTtlFromNow(): number | undefined;
/**
* Compute the lock timeout we should use for the
* factory
*/
factoryTimeout(hasFallbackValue: boolean): {
type: string;
duration: number;
exception: typeof FactorySoftTimeout;
} | undefined;
/**
* Determine if we should use the SWR strategy
*/
shouldSwr(hasFallback: boolean): boolean;
/**
* Compute the maximum time we should wait for the
* lock to be acquired
*/
getApplicableLockTimeout(hasFallbackValue: boolean): number | undefined;
};
declare class Logger {
internalLogger: Logger$1;
constructor(internalLogger: Logger$1);
child(obj: LogObject): Logger;
trace(msg: any, obj?: any): void;
debug(msg: any, obj?: any): void;
warn(msg: any, obj?: any): void;
error(msg: any, obj?: any): void;
fatal(msg: any, obj?: any): void;
info(msg: any, obj?: any): void;
logMethod(options: {
cacheName: string;
options: CacheEntryOptions;
key?: string | string[];
tags?: string[];
method: string;
}): void;
logL1Hit(options: {
cacheName: string;
key: string;
options: CacheEntryOptions;
graced?: boolean;
}): void;
logL2Hit(options: {
cacheName: string;
key: string;
options: CacheEntryOptions;
graced?: boolean;
}): void;
}
/**
* Options that are common to all drivers
*
* Some of theses options may be also defined in
* the BentoCache options. Setting them specifically
* for a driver will override the BentoCache options.
*/
type DriverCommonOptions = {
prefix?: string;
};
type DriverCommonInternalOptions = {
logger?: Logger;
};
/**
* Options for DynamoDB driver
*/
type DynamoDBConfig = {
/**
* DynamoDB table name to use.
*/
table: {
name: string;
};
/**
* AWS credentials
*/
credentials?: DynamoDBClientConfig['credentials'];
/**
* Region of your DynamoDB instance
*/
region: DynamoDBClientConfig['region'];
/**
* Endpoint to your DynamoDB instance
*/
endpoint: DynamoDBClientConfig['endpoint'];
} & DriverCommonOptions;
/**
* A number of bytes
* Can be represented as a number or a string
* e.g. '1kb', '1mb', '1gb'
* We use https://www.npmjs.com/package/bytes under the hood
*/
type Bytes = number | string;
/**
* Options for Memory driver
*/
type MemoryConfig = {
/**
* Maximum number of items to store in the cache.
*
* Note that fewer items may be stored if you
* are also using `maxSize` and the cache is full.
*
* @default 1000
*/
maxItems?: number;
/**
* Maximum size of the cache in bytes.
*/
maxSize?: Bytes;
/**
* Maximum size of one entry in bytes.
*
* If an entry is larger than this value,
* it will NOT be stored
*/
maxEntrySize?: Bytes;
/**
* Should the entries be serialized before storing
* them in the cache.
*
* Note that, if unset, you cannot use maxSize or maxEntrySize
* since the size of deserialized objects cannot be calculated.
*
* **Also make sure to read the below documentation. This option
* can cause issues if not used correctly.**
*
* @see http://bentocache.dev/docs/cache-drivers#serialize-option
* @default true
*/
serialize?: boolean;
} & DriverCommonOptions;
/**
* Options for Redis driver
*/
type RedisConfig = {
/**
* A IoRedis connection instance (Redis or Cluster) or connection options
*/
connection: Redis | Cluster | RedisOptions;
} & DriverCommonOptions;
/**
* Options for File driver
*/
type FileConfig = {
/**
* Directory where the cache files will be stored
*/
directory: string;
/**
* The interval between each expired entry pruning
* Can be set to `false` to disable pruning.
*
* @default false
*/
pruneInterval?: Duration | false;
} & DriverCommonOptions;
/**
* Common options for database drivers
*/
interface DatabaseConfig extends DriverCommonOptions {
/**
* Table name to use
*/
tableName?: string;
/**
* Should the driver automatically create the table
* @default true
*/
autoCreateTable?: boolean;
/**
* The interval between each expired entry pruning
* run. Can be set to `false` to disable pruning.
*
* @default false
*/
pruneInterval?: Duration | false;
}
/**
* Configuration accepted by the Knex adapter
*/
interface KnexConfig extends DatabaseConfig {
/**
* The Knex instance
*/
connection: Knex;
}
/**
* Configuration accepted by the Kysely adapter
*/
interface KyselyConfig extends DatabaseConfig {
/**
* The Kysely instance
*/
connection: Kysely<any>;
}
/**
* Configuration accepted by the Orchid ORM adapter
*/
interface OrchidConfig extends DatabaseConfig {
/**
* The Orchid ORM instance
*/
connection: DbResult<DefaultColumnTypes<DefaultSchemaConfig>>;
}
/**
* Options accepted by the `getOrSet` method
*/
type SetCommonOptions = Pick<RawCommonOptions, 'grace' | 'graceBackoff' | 'suppressL2Errors' | 'lockTimeout' | 'ttl' | 'timeout' | 'hardTimeout' | 'skipBusNotify' | 'skipL2Write' | 'onFactoryError' | 'tags'>;
/**
* Options accepted by the `getOrSet` method
*/
type GetOrSetOptions<T> = {
key: string;
factory: GetSetFactory<T>;
} & SetCommonOptions & Pick<RawCommonOptions, 'forceFresh'>;
/**
* Options accepted by the `getOrSetForever` method
*/
type GetOrSetForeverOptions<T> = {
key: string;
factory: GetSetFactory<T>;
} & Omit<SetCommonOptions, 'ttl'>;
/**
* Options accepted by the `set` method
*/
type SetOptions = {
key: string;
value: any;
} & SetCommonOptions;
/**
* Options accepted by the `get` method
*/
type GetOptions<T> = {
key: string;
defaultValue?: Factory<T>;
} & Pick<RawCommonOptions, 'grace' | 'graceBackoff' | 'suppressL2Errors'>;
/**
* Options accepted by the `delete` method
*/
type DeleteOptions = {
key: string;
} & Pick<RawCommonOptions, 'suppressL2Errors'>;
type DeleteManyOptions = {
keys: string[];
} & Pick<RawCommonOptions, 'suppressL2Errors'>;
/**
* Options accepted by the `deleteByTag` method
*/
type DeleteByTagOptions = {
tags: string[];
} & Pick<RawCommonOptions, 'suppressL2Errors'>;
/**
* Options accepted by the `expire` method
*/
type ExpireOptions = {
key: string;
} & Pick<RawCommonOptions, 'suppressL2Errors'>;
/**
* Options accepted by the `has` method
*/
type HasOptions = {
key: string;
} & Pick<RawCommonOptions, 'suppressL2Errors'>;
/**
* Options accepted by the `clear` method
*/
type ClearOptions = Pick<RawCommonOptions, 'suppressL2Errors'>;
/**
* Interface for a L1 cache driver. Probably a memory driver
*/
interface L1CacheDriver extends CacheDriver<false> {
type: 'l1';
getRemainingTtl(key: string): number | undefined;
}
/**
* Interface for a L2, distributed cache driver.
*/
interface L2CacheDriver extends CacheDriver<true> {
type: 'l2';
}
/**
* Factory result for a cache driver
*/
interface CreateDriverResult<T extends L1CacheDriver | L2CacheDriver> {
options: Record<string, any>;
factory: (config: any) => T;
}
/**
* Contract for a bus driver factory
*/
interface CreateBusDriverResult {
options: BusOptions;
factory: (config: any) => BusDriver;
}
/**
* Cache serializer contract
*/
interface CacheSerializer {
serialize: (value: any) => string;
deserialize: (value: any) => any;
}
/**
* Stack of cache drivers
*/
interface CacheStackDrivers {
l1Driver?: L1CacheDriver;
l2Driver?: L2CacheDriver;
busDriver?: BusDriver;
busOptions?: BusOptions;
}
/**
* A Bentocache Plugin
*/
interface BentoCachePlugin {
register(bentocache: BentoCache<any>): void;
}
/**
* Dialect available for the SQL driver
*/
type DialectName = 'pg' | 'mysql2' | 'better-sqlite3' | 'sqlite3';
/**
* Create a new store
*/
declare function bentostore(options?: RawCommonOptions & {
prefix?: string;
}): BentoStore;
declare class BentoStore {
#private;
constructor(baseOptions?: RawCommonOptions & {
prefix?: string;
});
/**
* Add a L1 layer to your store. This is usually a memory driver
* for fast access purposes.
*/
useL1Layer(driver: CreateDriverResult<L1CacheDriver>): this;
/**
* Add a L2 layer to your store. This is usually something
* distributed like Redis, DynamoDB, Sql database, etc.
*/
useL2Layer(driver: CreateDriverResult<L2CacheDriver>): this;
/**
* Add a bus to your store. It will be used to synchronize L1 layers between
* different instances of your application.
*/
useBus(bus: CreateBusDriverResult): this;
get entry(): {
options: RawCommonOptions & {
prefix?: string;
};
l1: CreateDriverResult<L1CacheDriver> | undefined;
l2: CreateDriverResult<L2CacheDriver> | undefined;
bus: CreateBusDriverResult | undefined;
};
}
declare class BentoCache<KnownCaches extends Record<string, BentoStore>> implements CacheProvider {
#private;
constructor(config: RawBentoCacheOptions & {
default: keyof KnownCaches;
stores: KnownCaches;
plugins?: BentoCachePlugin[];
});
get defaultStoreName(): string;
/**
* Use a registered cache driver
*/
use<CacheName extends keyof KnownCaches>(cache?: CacheName): CacheProvider;
/**
* Subscribe to a given cache event
*/
on<Event extends keyof CacheEvents>(event: Event, callback: (arg: CacheEvents[Event]) => void): this;
/**
* Subscribe to a given cache event only once
*/
once<Event extends keyof CacheEvents>(event: Event, callback: (arg: CacheEvents[Event]) => void): this;
/**
* Unsubscribe the callback from the given event
*/
off<Event extends keyof CacheEvents>(event: Event, callback: (arg: CacheEvents[Event]) => void): this;
/**
* Returns a new instance of the driver namespaced
*/
namespace(namespace: string): CacheProvider;
/**
* Get a value from the cache
*/
get<T = any>(options: GetOptions<T>): Promise<T>;
/**
* Put a value in the cache
* Returns true if the value was set, false otherwise
*/
set(options: SetOptions): Promise<boolean>;
/**
* Put a value in the cache forever
* Returns true if the value was set, false otherwise
*/
setForever(options: SetOptions): Promise<boolean>;
/**
* Retrieve an item from the cache if it exists, otherwise store the value
* provided by the factory and return it
*/
getOrSet<T>(options: GetOrSetOptions<T>): Promise<T>;
/**
* Retrieve an item from the cache if it exists, otherwise store the value
* provided by the factory forever and return it
*/
getOrSetForever<T>(options: GetOrSetForeverOptions<T>): Promise<T>;
/**
* Check if a key exists in the cache
*/
has(options: HasOptions): Promise<boolean>;
/**
* Check if key is missing in the cache
*/
missing(options: HasOptions): Promise<boolean>;
/**
* Get the value of a key and delete it
*
* Returns the value if the key exists, undefined otherwise
*/
pull<T = any>(key: string): Promise<T | null | undefined>;
/**
* Delete a key from the cache
* Returns true if the key was deleted, false otherwise
*/
delete(keyOrOptions: DeleteOptions): Promise<boolean>;
/**
* Delete multiple keys from the cache
*/
deleteMany(options: DeleteManyOptions): Promise<boolean>;
/**
* Delete all keys with a specific tag
*/
deleteByTag(options: DeleteByTagOptions): Promise<boolean>;
/**
* Expire a key from the cache.
* Entry will not be fully deleted but expired and
* retained for the grace period if enabled.
*/
expire(options: ExpireOptions): Promise<boolean>;
/**
* Remove all items from the cache
*/
clear(options?: ClearOptions): Promise<void>;
/**
* Manually prune expired cache entries
*
* For drivers with native TTL support, this is typically a noop
* For drivers without native TTL (PostgreSQL, File), this will remove expired entries
*/
prune(): Promise<void>;
/**
* Remove all items from all caches
*/
clearAll(options?: ClearOptions): Promise<void>;
/**
* Closes the connection to the cache
*/
disconnect(): Promise<void>;
/**
* Disconnect all cache connections created by the manager
*/
disconnectAll(): Promise<void>;
}
export { BentoCache as B, type BentoCachePlugin, type BusDriver, type BusOptions, type Bytes, type CacheBusMessage, CacheBusMessageType, type CacheDriver, type CacheDriverOptions, type CacheEvent, type CacheEvents, type CacheProvider, type CacheSerializer, type CacheStackDrivers, type ClearOptions, type CreateBusDriverResult, type CreateDriverResult, type DatabaseAdapter, type DatabaseConfig, type DeleteByTagOptions, type DeleteManyOptions, type DeleteOptions, type DialectName, type DriverCommonInternalOptions, type DriverCommonOptions, type Duration, type DynamoDBConfig, type Emitter, type ExpireOptions, type Factory, type FileConfig, type GetOptions, type GetOrSetForeverOptions, type GetOrSetOptions, type GetSetFactory, type GetSetFactoryContext, type HasOptions, type KnexConfig, type KyselyConfig, type L1CacheDriver, type L2CacheDriver, type MemoryConfig, type OrchidConfig, type RawBentoCacheOptions, type RawCommonOptions, type RedisConfig, type SetCommonOptions, type SetOptions, BentoStore as a, bentostore as b, errors as e };