import { logger } from './logger'; import { env } from '$env/dynamic/private'; import { GlideClient, TimeUnit } from '@valkey/valkey-glide'; export const SESSION_STORE = 'atp_sessions:'; export const STATE_STORE = 'atp_states:'; let valKeyClient: Promise | null = null; export const getAValKeyClient = async () => { if (!valKeyClient) { valKeyClient = (async () => { logger.info('Creating valkey client'); const addresses = [ { host: env.REDIS_HOST ?? 'localhost', // @ts-expect-error Going to leave it to the redis client to throw a run time error for this since // it is a run time error to not be able to have redis to connect port: env.REDIS_PORT as number ?? 6379 }, ]; return await GlideClient.createClient({ addresses, credentials: env.REDIS_PASSWORD ? { password: env.REDIS_PASSWORD } : undefined, useTLS: env.REDIS_TLS === 'true', //This may be a bit extreme, will see requestTimeout: 500, // 500ms timeout }); })(); } return valKeyClient; }; export class Cache { valKeyClient: GlideClient; //Set if the cache set should have an expiration expire: number | undefined; cachePrefix: string; constructor(glideClient: GlideClient, cachePrefix: string, expire: number | undefined = undefined) { this.valKeyClient = glideClient; this.expire = expire; this.cachePrefix = cachePrefix; } $key(key: string) { return `${this.cachePrefix}${key}`; } async get(key: string) { const result = await this.valKeyClient.get(this.$key(key)); if(result){ return result.toString(); } return undefined; } async set(key: string, value: string, customExpire?: number) { const expireSeconds = customExpire ?? this.expire; const expiryOptions = expireSeconds ? { expiry: { type: TimeUnit.Seconds, count: expireSeconds } } : undefined; return await this.valKeyClient.set(this.$key(key), value, expiryOptions); } async delete(key: string) { await this.valKeyClient.del([this.$key(key)]); } async refreshExpiry(key: string, seconds: number) { await this.valKeyClient.expire(this.$key(key), seconds); } }