parent
37a5e008f5
commit
bc4466942d
@ -0,0 +1,81 @@
|
||||
import {
|
||||
CACHE_DECISION_ACTION_DELETE_AND_FETCH,
|
||||
CACHE_DECISION_ACTION_SERVE,
|
||||
CACHE_DECISION_ACTION_SERVE_AND_REFRESH,
|
||||
CACHE_DECISION_REASON_CACHE_MISS,
|
||||
CACHE_EVENT_HIT,
|
||||
CACHE_EVENT_MISS,
|
||||
CACHE_EVENT_SCHEMA_MISMATCH,
|
||||
CACHE_EVENT_STALE_HIT
|
||||
} from './consts.ts';
|
||||
import type { ResolvedCacheContext } from './runtime-context.ts';
|
||||
import type { CacheRuntimeDelete } from './runtime-delete.ts';
|
||||
import type {
|
||||
CacheAdapter,
|
||||
CacheDecision,
|
||||
CacheEnvelope,
|
||||
CacheEvent,
|
||||
CacheEventType,
|
||||
CacheKey,
|
||||
GetOptions
|
||||
} from './types.ts';
|
||||
|
||||
interface CacheRuntimeGetInput {
|
||||
readonly adapter: CacheAdapter;
|
||||
readonly deletion: CacheRuntimeDelete;
|
||||
contextFor(input: {
|
||||
readonly key: CacheKey;
|
||||
readonly scope?: GetOptions['scope'];
|
||||
readonly policy?: GetOptions['policy'];
|
||||
readonly mode?: GetOptions['mode'];
|
||||
readonly schemaVersion?: GetOptions['schemaVersion'];
|
||||
}): Promise<ResolvedCacheContext>;
|
||||
evaluate<T>(entry: CacheEnvelope<T>, ctx: ResolvedCacheContext): Promise<CacheDecision>;
|
||||
emitForContext(
|
||||
type: CacheEventType,
|
||||
ctx: ResolvedCacheContext,
|
||||
patch?: Partial<CacheEvent>
|
||||
): void;
|
||||
}
|
||||
|
||||
export function createCacheRuntimeGet(runtime: CacheRuntimeGetInput) {
|
||||
return async function get<T>(key: CacheKey, options: GetOptions): Promise<T | undefined> {
|
||||
const ctx = await runtime.contextFor({
|
||||
key,
|
||||
scope: options.scope,
|
||||
policy: options.policy,
|
||||
mode: options.mode,
|
||||
schemaVersion: options.schemaVersion
|
||||
});
|
||||
|
||||
const cached = await runtime.adapter.get<T>(ctx.fullKey);
|
||||
if (!cached) {
|
||||
runtime.emitForContext(CACHE_EVENT_MISS, ctx, {
|
||||
reason: CACHE_DECISION_REASON_CACHE_MISS
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const decision = await runtime.evaluate(cached, ctx);
|
||||
if (decision.action === CACHE_DECISION_ACTION_DELETE_AND_FETCH) {
|
||||
runtime.emitForContext(CACHE_EVENT_SCHEMA_MISMATCH, ctx, { reason: decision.reason });
|
||||
await runtime.deletion.safeDelete(ctx.fullKey, ctx.keyHash);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (
|
||||
decision.action === CACHE_DECISION_ACTION_SERVE ||
|
||||
decision.action === CACHE_DECISION_ACTION_SERVE_AND_REFRESH
|
||||
) {
|
||||
runtime.emitForContext(
|
||||
decision.action === CACHE_DECISION_ACTION_SERVE ? CACHE_EVENT_HIT : CACHE_EVENT_STALE_HIT,
|
||||
ctx,
|
||||
{ reason: decision.reason }
|
||||
);
|
||||
return cached.value;
|
||||
}
|
||||
|
||||
runtime.emitForContext(CACHE_EVENT_MISS, ctx, { reason: decision.reason });
|
||||
return undefined;
|
||||
};
|
||||
}
|
||||
Loading…
Reference in new issue