Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Text · 60 lines · 1.9 KiB · at 9ba9e6b

import { Some, None, Ok, Err, type Option, type Result } from "@tsus/runtime";import { fromNullable } from "@tsus/runtime/boundary";export type LoadError = { kind: "load_failed"; reason: string };export type CacheError = { kind: "invalid_ttl" };export type Cache<V> = {  get: (key: string) => Promise<Result<V, LoadError>>;  invalidate: (key: string) => void;};type Entry<V> = { value: V; loadedAt: number };const build = <V>(  loader: (key: string) => Promise<Result<V, LoadError>>,  ttlMs: number,  now: () => number,): Cache<V> => {  const values = new Map<string, Entry<V>>();  const inflight = new Map<string, Promise<Result<V, LoadError>>>();  const finish = (key: string, load: Promise<Result<V, LoadError>>, r: Result<V, LoadError>): Result<V, LoadError> => {    if (inflight.get(key) === load) {      inflight.delete(key);      r.map((value) => values.set(key, { value, loadedAt: now() }));    }    return r;  };  const startLoad = (key: string): Promise<Result<V, LoadError>> => {    const load: Promise<Result<V, LoadError>> = loader(key).then((r) => finish(key, load, r));    inflight.set(key, load);    return load;  };  const get = (key: string): Promise<Result<V, LoadError>> => {    const fresh: Option<Entry<V>> = fromNullable(values.get(key)).andThen((e) => (now() - e.loadedAt < ttlMs ? Some(e) : None));    return match (fresh) {      Some(e) => Promise.resolve(Ok(e.value)),      None => match (fromNullable(inflight.get(key))) {        Some(p) => p,        None => startLoad(key),      },    };  };  const invalidate = (key: string): void => {    values.delete(key);    inflight.delete(key);  };  return { get, invalidate };};export const createCache = <V>(  loader: (key: string) => Promise<Result<V, LoadError>>,  ttlMs: number,  now: () => number,): Result<Cache<V>, CacheError> =>  Number.isInteger(ttlMs) && ttlMs > 0 ? Ok(build(loader, ttlMs, now)) : Err({ kind: "invalid_ttl" });