@kiln-js/cache 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -2
- package/dist/index.d.ts +186 -0
- package/dist/index.js +503 -0
- package/package.json +24 -6
package/README.md
CHANGED
|
@@ -1,3 +1,46 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @kiln-js/cache
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@kiln-js/cache)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
|
|
6
|
+
Part of the Kiln framework.
|
|
7
|
+
|
|
8
|
+
Part of [Kiln](https://github.com/kiln-js/kiln), a file-based server-side rendering framework for React and Vite.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
bun add @kiln-js/cache
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { cachedLoader, revalidateTag } from "@kiln-js/cache";
|
|
20
|
+
|
|
21
|
+
export const loader = cachedLoader(
|
|
22
|
+
async ({ params }) => fetchPost(params.slug),
|
|
23
|
+
{ ttl: 60, tags: ["posts"] }
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
// After a write, invalidate everything tagged "posts".
|
|
27
|
+
await revalidateTag("posts");
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Adapters
|
|
31
|
+
|
|
32
|
+
`MemoryCacheAdapter` is the default. Use `ExternalCacheAdapter` to back the cache with a key-value store, or `TieredCacheAdapter` to layer both.
|
|
33
|
+
Pass an adapter to `configureDataCache` to replace the global cache.
|
|
34
|
+
Concurrent requests for the same key are deduplicated, and `staleWhileRevalidate` is supported.
|
|
35
|
+
|
|
36
|
+
## Documentation
|
|
37
|
+
|
|
38
|
+
See the [Kiln repository](https://github.com/kiln-js/kiln) for the full API reference and guides.
|
|
39
|
+
|
|
40
|
+
## Development
|
|
41
|
+
|
|
42
|
+
This repository is generated from the Kiln monorepo. Make changes there, then run `scripts/publish-repo.ps1` to publish them here. Report issues in this repository, and send pull requests to the monorepo.
|
|
43
|
+
|
|
44
|
+
## License
|
|
45
|
+
|
|
46
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
export interface CacheEntry<T = unknown> {
|
|
2
|
+
key: string;
|
|
3
|
+
value: T;
|
|
4
|
+
tags: string[];
|
|
5
|
+
path?: string;
|
|
6
|
+
createdAt: number;
|
|
7
|
+
expiresAt: number;
|
|
8
|
+
staleUntil?: number;
|
|
9
|
+
hits: number;
|
|
10
|
+
adapter: string;
|
|
11
|
+
}
|
|
12
|
+
export interface CacheSetOptions {
|
|
13
|
+
/** Time-to-live in seconds (default: 60) */
|
|
14
|
+
ttl?: number;
|
|
15
|
+
/** Additional seconds after expiration during which stale data can be served while revalidating in background */
|
|
16
|
+
staleWhileRevalidate?: number;
|
|
17
|
+
/** Cache tags for targeted invalidation via revalidateTag() */
|
|
18
|
+
tags?: string[];
|
|
19
|
+
/** Associated route path for revalidatePath() */
|
|
20
|
+
path?: string;
|
|
21
|
+
}
|
|
22
|
+
export interface CacheStatsSnapshot {
|
|
23
|
+
adapter: string;
|
|
24
|
+
size: number;
|
|
25
|
+
hits: number;
|
|
26
|
+
misses: number;
|
|
27
|
+
dedupedHits: number;
|
|
28
|
+
invalidations: number;
|
|
29
|
+
evictions: number;
|
|
30
|
+
inFlightCount: number;
|
|
31
|
+
tags: Record<string, string[]>;
|
|
32
|
+
}
|
|
33
|
+
export interface CacheAdapter {
|
|
34
|
+
readonly name: string;
|
|
35
|
+
get<T = unknown>(key: string): Promise<CacheEntry<T> | null>;
|
|
36
|
+
set<T = unknown>(key: string, value: T, options?: CacheSetOptions): Promise<CacheEntry<T>>;
|
|
37
|
+
delete(key: string): Promise<boolean>;
|
|
38
|
+
clear(): Promise<void>;
|
|
39
|
+
invalidateTag(tag: string): Promise<string[]>;
|
|
40
|
+
invalidatePath(pathPrefix: string): Promise<string[]>;
|
|
41
|
+
entries(): Promise<CacheEntry[]>;
|
|
42
|
+
stats(): Promise<Omit<CacheStatsSnapshot, "dedupedHits" | "inFlightCount">>;
|
|
43
|
+
}
|
|
44
|
+
export interface MemoryCacheOptions {
|
|
45
|
+
maxEntries?: number;
|
|
46
|
+
defaultTtl?: number;
|
|
47
|
+
}
|
|
48
|
+
export declare class MemoryCacheAdapter implements CacheAdapter {
|
|
49
|
+
readonly name = "memory";
|
|
50
|
+
private store;
|
|
51
|
+
private tagIndex;
|
|
52
|
+
private maxEntries;
|
|
53
|
+
private defaultTtl;
|
|
54
|
+
private hitCount;
|
|
55
|
+
private missCount;
|
|
56
|
+
private invalidationCount;
|
|
57
|
+
private evictionCount;
|
|
58
|
+
constructor(options?: MemoryCacheOptions);
|
|
59
|
+
get<T = unknown>(key: string): Promise<CacheEntry<T> | null>;
|
|
60
|
+
set<T = unknown>(key: string, value: T, options?: CacheSetOptions): Promise<CacheEntry<T>>;
|
|
61
|
+
delete(key: string): Promise<boolean>;
|
|
62
|
+
clear(): Promise<void>;
|
|
63
|
+
invalidateTag(tag: string): Promise<string[]>;
|
|
64
|
+
invalidatePath(pathPrefix: string): Promise<string[]>;
|
|
65
|
+
entries(): Promise<CacheEntry[]>;
|
|
66
|
+
stats(): Promise<{
|
|
67
|
+
adapter: string;
|
|
68
|
+
size: number;
|
|
69
|
+
hits: number;
|
|
70
|
+
misses: number;
|
|
71
|
+
invalidations: number;
|
|
72
|
+
evictions: number;
|
|
73
|
+
tags: Record<string, string[]>;
|
|
74
|
+
}>;
|
|
75
|
+
}
|
|
76
|
+
export interface ExternalKeyValueStore {
|
|
77
|
+
name?: string;
|
|
78
|
+
get(key: string): Promise<string | null>;
|
|
79
|
+
set(key: string, serialized: string, ttlSeconds?: number): Promise<void>;
|
|
80
|
+
del(key: string): Promise<boolean | number>;
|
|
81
|
+
keys?(pattern?: string): Promise<string[]>;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* ExternalCacheAdapter bridges external stores (Redis, Upstash, PostgreSQL KV, Cloudflare KV)
|
|
85
|
+
* to the standard Kiln CacheAdapter interface with full tag and path invalidation support.
|
|
86
|
+
*/
|
|
87
|
+
export declare class ExternalCacheAdapter implements CacheAdapter {
|
|
88
|
+
readonly name: string;
|
|
89
|
+
private store;
|
|
90
|
+
private keyIndex;
|
|
91
|
+
private tagIndex;
|
|
92
|
+
private hitCount;
|
|
93
|
+
private missCount;
|
|
94
|
+
private invalidationCount;
|
|
95
|
+
constructor(store: ExternalKeyValueStore);
|
|
96
|
+
get<T = unknown>(key: string): Promise<CacheEntry<T> | null>;
|
|
97
|
+
set<T = unknown>(key: string, value: T, options?: CacheSetOptions): Promise<CacheEntry<T>>;
|
|
98
|
+
delete(key: string): Promise<boolean>;
|
|
99
|
+
clear(): Promise<void>;
|
|
100
|
+
invalidateTag(tag: string): Promise<string[]>;
|
|
101
|
+
invalidatePath(pathPrefix: string): Promise<string[]>;
|
|
102
|
+
entries(): Promise<CacheEntry[]>;
|
|
103
|
+
stats(): Promise<{
|
|
104
|
+
adapter: string;
|
|
105
|
+
size: number;
|
|
106
|
+
hits: number;
|
|
107
|
+
misses: number;
|
|
108
|
+
invalidations: number;
|
|
109
|
+
evictions: number;
|
|
110
|
+
tags: Record<string, string[]>;
|
|
111
|
+
}>;
|
|
112
|
+
}
|
|
113
|
+
export declare class TieredCacheAdapter implements CacheAdapter {
|
|
114
|
+
private readonly l1;
|
|
115
|
+
private readonly l2;
|
|
116
|
+
readonly name = "tiered(memory+external)";
|
|
117
|
+
constructor(l1: MemoryCacheAdapter, l2: CacheAdapter);
|
|
118
|
+
get<T = unknown>(key: string): Promise<CacheEntry<T> | null>;
|
|
119
|
+
set<T = unknown>(key: string, value: T, options?: CacheSetOptions): Promise<CacheEntry<T>>;
|
|
120
|
+
delete(key: string): Promise<boolean>;
|
|
121
|
+
clear(): Promise<void>;
|
|
122
|
+
invalidateTag(tag: string): Promise<string[]>;
|
|
123
|
+
invalidatePath(pathPrefix: string): Promise<string[]>;
|
|
124
|
+
entries(): Promise<CacheEntry[]>;
|
|
125
|
+
stats(): Promise<{
|
|
126
|
+
adapter: string;
|
|
127
|
+
size: number;
|
|
128
|
+
hits: number;
|
|
129
|
+
misses: number;
|
|
130
|
+
invalidations: number;
|
|
131
|
+
evictions: number;
|
|
132
|
+
tags: Record<string, string[]>;
|
|
133
|
+
}>;
|
|
134
|
+
}
|
|
135
|
+
export interface LoaderCacheResult<T> {
|
|
136
|
+
data: T;
|
|
137
|
+
status: "HIT" | "MISS" | "STALE" | "DEDUPED";
|
|
138
|
+
key: string;
|
|
139
|
+
tags: string[];
|
|
140
|
+
expiresAt: number;
|
|
141
|
+
durationMs: number;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* DataCache coordinates loader caching, request deduplication, time-based expiration,
|
|
145
|
+
* and tag/path invalidation across the Kiln server runtime.
|
|
146
|
+
*/
|
|
147
|
+
export declare class DataCache {
|
|
148
|
+
private adapter;
|
|
149
|
+
private inFlight;
|
|
150
|
+
private dedupedHits;
|
|
151
|
+
constructor(adapter?: CacheAdapter);
|
|
152
|
+
getAdapter(): CacheAdapter;
|
|
153
|
+
setAdapter(adapter: CacheAdapter): void;
|
|
154
|
+
/**
|
|
155
|
+
* Deduplicates concurrent executions for the same key and caches the resolved value.
|
|
156
|
+
*/
|
|
157
|
+
load<T>(key: string, fetcher: () => Promise<T>, options?: CacheSetOptions & {
|
|
158
|
+
forceRefresh?: boolean;
|
|
159
|
+
}): Promise<LoaderCacheResult<T>>;
|
|
160
|
+
private revalidateInBackground;
|
|
161
|
+
revalidateTag(tag: string): Promise<string[]>;
|
|
162
|
+
revalidatePath(pathPrefix: string): Promise<string[]>;
|
|
163
|
+
delete(key: string): Promise<boolean>;
|
|
164
|
+
clear(): Promise<void>;
|
|
165
|
+
entries(): Promise<CacheEntry[]>;
|
|
166
|
+
stats(): Promise<CacheStatsSnapshot>;
|
|
167
|
+
}
|
|
168
|
+
export declare function getGlobalDataCache(): DataCache;
|
|
169
|
+
export declare function configureDataCache(adapter: CacheAdapter): DataCache;
|
|
170
|
+
export declare function createDataCache(adapter?: CacheAdapter): DataCache;
|
|
171
|
+
export declare function revalidateTag(tag: string): Promise<string[]>;
|
|
172
|
+
export declare function revalidatePath(pathPrefix: string): Promise<string[]>;
|
|
173
|
+
export interface CachedLoaderConfig<Ctx = {
|
|
174
|
+
params: Record<string, string>;
|
|
175
|
+
request: Request;
|
|
176
|
+
}> extends CacheSetOptions {
|
|
177
|
+
key?: string | ((ctx: Ctx) => string);
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Wraps any Kiln server loader with automatic caching, TTL expiration,
|
|
181
|
+
* tag registration, and concurrent request deduplication.
|
|
182
|
+
*/
|
|
183
|
+
export declare function cachedLoader<Ctx extends {
|
|
184
|
+
params: Record<string, string>;
|
|
185
|
+
request: Request;
|
|
186
|
+
}, Result>(loaderFn: (ctx: Ctx) => Promise<Result> | Result, config?: CachedLoaderConfig<Ctx>, cacheInstance?: DataCache): (ctx: Ctx) => Promise<Result>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/index.ts
|
|
3
|
+
class MemoryCacheAdapter {
|
|
4
|
+
name = "memory";
|
|
5
|
+
store = new Map;
|
|
6
|
+
tagIndex = new Map;
|
|
7
|
+
maxEntries;
|
|
8
|
+
defaultTtl;
|
|
9
|
+
hitCount = 0;
|
|
10
|
+
missCount = 0;
|
|
11
|
+
invalidationCount = 0;
|
|
12
|
+
evictionCount = 0;
|
|
13
|
+
constructor(options = {}) {
|
|
14
|
+
this.maxEntries = options.maxEntries ?? 500;
|
|
15
|
+
this.defaultTtl = options.defaultTtl ?? 60;
|
|
16
|
+
}
|
|
17
|
+
async get(key) {
|
|
18
|
+
const entry = this.store.get(key);
|
|
19
|
+
if (!entry) {
|
|
20
|
+
this.missCount++;
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
const now = Date.now();
|
|
24
|
+
const hardLimit = entry.staleUntil ?? entry.expiresAt;
|
|
25
|
+
if (now > hardLimit) {
|
|
26
|
+
await this.delete(key);
|
|
27
|
+
this.missCount++;
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
entry.hits++;
|
|
31
|
+
this.hitCount++;
|
|
32
|
+
this.store.delete(key);
|
|
33
|
+
this.store.set(key, entry);
|
|
34
|
+
return entry;
|
|
35
|
+
}
|
|
36
|
+
async set(key, value, options = {}) {
|
|
37
|
+
if (this.store.size >= this.maxEntries && !this.store.has(key)) {
|
|
38
|
+
const oldestKey = this.store.keys().next().value;
|
|
39
|
+
if (oldestKey) {
|
|
40
|
+
await this.delete(oldestKey);
|
|
41
|
+
this.evictionCount++;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const now = Date.now();
|
|
45
|
+
const ttlSeconds = options.ttl ?? this.defaultTtl;
|
|
46
|
+
const expiresAt = now + Math.max(0, ttlSeconds) * 1000;
|
|
47
|
+
const staleUntil = options.staleWhileRevalidate && options.staleWhileRevalidate > 0 ? expiresAt + options.staleWhileRevalidate * 1000 : undefined;
|
|
48
|
+
const tags = Array.from(new Set(options.tags ?? []));
|
|
49
|
+
const entry = {
|
|
50
|
+
key,
|
|
51
|
+
value,
|
|
52
|
+
tags,
|
|
53
|
+
path: options.path,
|
|
54
|
+
createdAt: now,
|
|
55
|
+
expiresAt,
|
|
56
|
+
staleUntil,
|
|
57
|
+
hits: 0,
|
|
58
|
+
adapter: this.name
|
|
59
|
+
};
|
|
60
|
+
this.store.set(key, entry);
|
|
61
|
+
for (const tag of tags) {
|
|
62
|
+
let set = this.tagIndex.get(tag);
|
|
63
|
+
if (!set) {
|
|
64
|
+
set = new Set;
|
|
65
|
+
this.tagIndex.set(tag, set);
|
|
66
|
+
}
|
|
67
|
+
set.add(key);
|
|
68
|
+
}
|
|
69
|
+
return entry;
|
|
70
|
+
}
|
|
71
|
+
async delete(key) {
|
|
72
|
+
const existing = this.store.get(key);
|
|
73
|
+
if (!existing)
|
|
74
|
+
return false;
|
|
75
|
+
this.store.delete(key);
|
|
76
|
+
for (const tag of existing.tags) {
|
|
77
|
+
const set = this.tagIndex.get(tag);
|
|
78
|
+
if (set) {
|
|
79
|
+
set.delete(key);
|
|
80
|
+
if (set.size === 0)
|
|
81
|
+
this.tagIndex.delete(tag);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
async clear() {
|
|
87
|
+
this.store.clear();
|
|
88
|
+
this.tagIndex.clear();
|
|
89
|
+
}
|
|
90
|
+
async invalidateTag(tag) {
|
|
91
|
+
const keys = Array.from(this.tagIndex.get(tag) ?? []);
|
|
92
|
+
for (const key of keys) {
|
|
93
|
+
await this.delete(key);
|
|
94
|
+
}
|
|
95
|
+
this.tagIndex.delete(tag);
|
|
96
|
+
this.invalidationCount += keys.length;
|
|
97
|
+
return keys;
|
|
98
|
+
}
|
|
99
|
+
async invalidatePath(pathPrefix) {
|
|
100
|
+
const removed = [];
|
|
101
|
+
for (const [key, entry] of this.store.entries()) {
|
|
102
|
+
if (entry.path && (entry.path === pathPrefix || entry.path.startsWith(pathPrefix)) || key.startsWith(`path:${pathPrefix}`)) {
|
|
103
|
+
await this.delete(key);
|
|
104
|
+
removed.push(key);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
this.invalidationCount += removed.length;
|
|
108
|
+
return removed;
|
|
109
|
+
}
|
|
110
|
+
async entries() {
|
|
111
|
+
const now = Date.now();
|
|
112
|
+
const valid = [];
|
|
113
|
+
for (const [key, entry] of this.store.entries()) {
|
|
114
|
+
const limit = entry.staleUntil ?? entry.expiresAt;
|
|
115
|
+
if (now <= limit) {
|
|
116
|
+
valid.push(entry);
|
|
117
|
+
} else {
|
|
118
|
+
await this.delete(key);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return valid;
|
|
122
|
+
}
|
|
123
|
+
async stats() {
|
|
124
|
+
const currentEntries = await this.entries();
|
|
125
|
+
const tags = {};
|
|
126
|
+
for (const [tag, keys] of this.tagIndex.entries()) {
|
|
127
|
+
if (keys.size > 0)
|
|
128
|
+
tags[tag] = Array.from(keys);
|
|
129
|
+
}
|
|
130
|
+
return {
|
|
131
|
+
adapter: this.name,
|
|
132
|
+
size: currentEntries.length,
|
|
133
|
+
hits: this.hitCount,
|
|
134
|
+
misses: this.missCount,
|
|
135
|
+
invalidations: this.invalidationCount,
|
|
136
|
+
evictions: this.evictionCount,
|
|
137
|
+
tags
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
class ExternalCacheAdapter {
|
|
143
|
+
name;
|
|
144
|
+
store;
|
|
145
|
+
keyIndex = new Set;
|
|
146
|
+
tagIndex = new Map;
|
|
147
|
+
hitCount = 0;
|
|
148
|
+
missCount = 0;
|
|
149
|
+
invalidationCount = 0;
|
|
150
|
+
constructor(store) {
|
|
151
|
+
this.store = store;
|
|
152
|
+
this.name = store.name ?? "external-kv";
|
|
153
|
+
}
|
|
154
|
+
async get(key) {
|
|
155
|
+
const raw = await this.store.get(key);
|
|
156
|
+
if (!raw) {
|
|
157
|
+
this.missCount++;
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
try {
|
|
161
|
+
const entry = JSON.parse(raw);
|
|
162
|
+
const now = Date.now();
|
|
163
|
+
const hardLimit = entry.staleUntil ?? entry.expiresAt;
|
|
164
|
+
if (now > hardLimit) {
|
|
165
|
+
await this.delete(key);
|
|
166
|
+
this.missCount++;
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
entry.hits = (entry.hits ?? 0) + 1;
|
|
170
|
+
this.hitCount++;
|
|
171
|
+
const remainingSeconds = Math.max(1, Math.ceil((hardLimit - now) / 1000));
|
|
172
|
+
await this.store.set(key, JSON.stringify(entry), remainingSeconds);
|
|
173
|
+
return entry;
|
|
174
|
+
} catch {
|
|
175
|
+
this.missCount++;
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
async set(key, value, options = {}) {
|
|
180
|
+
const now = Date.now();
|
|
181
|
+
const ttlSeconds = options.ttl ?? 60;
|
|
182
|
+
const swrSeconds = options.staleWhileRevalidate ?? 0;
|
|
183
|
+
const expiresAt = now + Math.max(0, ttlSeconds) * 1000;
|
|
184
|
+
const staleUntil = swrSeconds > 0 ? expiresAt + swrSeconds * 1000 : undefined;
|
|
185
|
+
const tags = Array.from(new Set(options.tags ?? []));
|
|
186
|
+
const entry = {
|
|
187
|
+
key,
|
|
188
|
+
value,
|
|
189
|
+
tags,
|
|
190
|
+
path: options.path,
|
|
191
|
+
createdAt: now,
|
|
192
|
+
expiresAt,
|
|
193
|
+
staleUntil,
|
|
194
|
+
hits: 0,
|
|
195
|
+
adapter: this.name
|
|
196
|
+
};
|
|
197
|
+
await this.store.set(key, JSON.stringify(entry), ttlSeconds + swrSeconds);
|
|
198
|
+
this.keyIndex.add(key);
|
|
199
|
+
for (const tag of tags) {
|
|
200
|
+
let set = this.tagIndex.get(tag);
|
|
201
|
+
if (!set) {
|
|
202
|
+
set = new Set;
|
|
203
|
+
this.tagIndex.set(tag, set);
|
|
204
|
+
}
|
|
205
|
+
set.add(key);
|
|
206
|
+
}
|
|
207
|
+
return entry;
|
|
208
|
+
}
|
|
209
|
+
async delete(key) {
|
|
210
|
+
this.keyIndex.delete(key);
|
|
211
|
+
for (const [tag, set] of this.tagIndex.entries()) {
|
|
212
|
+
set.delete(key);
|
|
213
|
+
if (set.size === 0)
|
|
214
|
+
this.tagIndex.delete(tag);
|
|
215
|
+
}
|
|
216
|
+
const res = await this.store.del(key);
|
|
217
|
+
return Boolean(res);
|
|
218
|
+
}
|
|
219
|
+
async clear() {
|
|
220
|
+
const allKeys = this.store.keys ? await this.store.keys() : Array.from(this.keyIndex);
|
|
221
|
+
for (const k of allKeys) {
|
|
222
|
+
await this.store.del(k);
|
|
223
|
+
}
|
|
224
|
+
this.keyIndex.clear();
|
|
225
|
+
this.tagIndex.clear();
|
|
226
|
+
}
|
|
227
|
+
async invalidateTag(tag) {
|
|
228
|
+
const keys = Array.from(this.tagIndex.get(tag) ?? []);
|
|
229
|
+
for (const key of keys) {
|
|
230
|
+
await this.delete(key);
|
|
231
|
+
}
|
|
232
|
+
this.tagIndex.delete(tag);
|
|
233
|
+
this.invalidationCount += keys.length;
|
|
234
|
+
return keys;
|
|
235
|
+
}
|
|
236
|
+
async invalidatePath(pathPrefix) {
|
|
237
|
+
const current = await this.entries();
|
|
238
|
+
const removed = [];
|
|
239
|
+
for (const entry of current) {
|
|
240
|
+
if (entry.path && (entry.path === pathPrefix || entry.path.startsWith(pathPrefix)) || entry.key.startsWith(`path:${pathPrefix}`)) {
|
|
241
|
+
await this.delete(entry.key);
|
|
242
|
+
removed.push(entry.key);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
this.invalidationCount += removed.length;
|
|
246
|
+
return removed;
|
|
247
|
+
}
|
|
248
|
+
async entries() {
|
|
249
|
+
const keys = this.store.keys ? await this.store.keys() : Array.from(this.keyIndex);
|
|
250
|
+
const out = [];
|
|
251
|
+
const now = Date.now();
|
|
252
|
+
for (const key of keys) {
|
|
253
|
+
const raw = await this.store.get(key);
|
|
254
|
+
if (!raw)
|
|
255
|
+
continue;
|
|
256
|
+
try {
|
|
257
|
+
const parsed = JSON.parse(raw);
|
|
258
|
+
const limit = parsed.staleUntil ?? parsed.expiresAt;
|
|
259
|
+
if (now <= limit)
|
|
260
|
+
out.push(parsed);
|
|
261
|
+
} catch {}
|
|
262
|
+
}
|
|
263
|
+
return out;
|
|
264
|
+
}
|
|
265
|
+
async stats() {
|
|
266
|
+
const active = await this.entries();
|
|
267
|
+
const tags = {};
|
|
268
|
+
for (const [tag, keys] of this.tagIndex.entries()) {
|
|
269
|
+
if (keys.size > 0)
|
|
270
|
+
tags[tag] = Array.from(keys);
|
|
271
|
+
}
|
|
272
|
+
return {
|
|
273
|
+
adapter: this.name,
|
|
274
|
+
size: active.length,
|
|
275
|
+
hits: this.hitCount,
|
|
276
|
+
misses: this.missCount,
|
|
277
|
+
invalidations: this.invalidationCount,
|
|
278
|
+
evictions: 0,
|
|
279
|
+
tags
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
class TieredCacheAdapter {
|
|
285
|
+
l1;
|
|
286
|
+
l2;
|
|
287
|
+
name = "tiered(memory+external)";
|
|
288
|
+
constructor(l1, l2) {
|
|
289
|
+
this.l1 = l1;
|
|
290
|
+
this.l2 = l2;
|
|
291
|
+
}
|
|
292
|
+
async get(key) {
|
|
293
|
+
const fromL1 = await this.l1.get(key);
|
|
294
|
+
if (fromL1)
|
|
295
|
+
return fromL1;
|
|
296
|
+
const fromL2 = await this.l2.get(key);
|
|
297
|
+
if (fromL2) {
|
|
298
|
+
const remainingSec = Math.max(1, Math.ceil((fromL2.expiresAt - Date.now()) / 1000));
|
|
299
|
+
await this.l1.set(key, fromL2.value, {
|
|
300
|
+
ttl: remainingSec,
|
|
301
|
+
tags: fromL2.tags,
|
|
302
|
+
path: fromL2.path
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
return fromL2;
|
|
306
|
+
}
|
|
307
|
+
async set(key, value, options) {
|
|
308
|
+
await this.l1.set(key, value, options);
|
|
309
|
+
return this.l2.set(key, value, options);
|
|
310
|
+
}
|
|
311
|
+
async delete(key) {
|
|
312
|
+
await this.l1.delete(key);
|
|
313
|
+
return this.l2.delete(key);
|
|
314
|
+
}
|
|
315
|
+
async clear() {
|
|
316
|
+
await Promise.all([this.l1.clear(), this.l2.clear()]);
|
|
317
|
+
}
|
|
318
|
+
async invalidateTag(tag) {
|
|
319
|
+
const [k1, k2] = await Promise.all([this.l1.invalidateTag(tag), this.l2.invalidateTag(tag)]);
|
|
320
|
+
return Array.from(new Set([...k1, ...k2]));
|
|
321
|
+
}
|
|
322
|
+
async invalidatePath(pathPrefix) {
|
|
323
|
+
const [k1, k2] = await Promise.all([this.l1.invalidatePath(pathPrefix), this.l2.invalidatePath(pathPrefix)]);
|
|
324
|
+
return Array.from(new Set([...k1, ...k2]));
|
|
325
|
+
}
|
|
326
|
+
async entries() {
|
|
327
|
+
return this.l2.entries();
|
|
328
|
+
}
|
|
329
|
+
async stats() {
|
|
330
|
+
const s2 = await this.l2.stats();
|
|
331
|
+
const s1 = await this.l1.stats();
|
|
332
|
+
return {
|
|
333
|
+
adapter: this.name,
|
|
334
|
+
size: s2.size,
|
|
335
|
+
hits: s1.hits + s2.hits,
|
|
336
|
+
misses: s2.misses,
|
|
337
|
+
invalidations: s2.invalidations,
|
|
338
|
+
evictions: s1.evictions + s2.evictions,
|
|
339
|
+
tags: s2.tags
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
class DataCache {
|
|
345
|
+
adapter;
|
|
346
|
+
inFlight = new Map;
|
|
347
|
+
dedupedHits = 0;
|
|
348
|
+
constructor(adapter) {
|
|
349
|
+
this.adapter = adapter ?? new MemoryCacheAdapter;
|
|
350
|
+
}
|
|
351
|
+
getAdapter() {
|
|
352
|
+
return this.adapter;
|
|
353
|
+
}
|
|
354
|
+
setAdapter(adapter) {
|
|
355
|
+
this.adapter = adapter;
|
|
356
|
+
}
|
|
357
|
+
async load(key, fetcher, options = {}) {
|
|
358
|
+
const start = performance.now();
|
|
359
|
+
if (!options.forceRefresh) {
|
|
360
|
+
const cached = await this.adapter.get(key);
|
|
361
|
+
if (cached) {
|
|
362
|
+
const now = Date.now();
|
|
363
|
+
const isStale = now > cached.expiresAt;
|
|
364
|
+
if (isStale && cached.staleUntil && now <= cached.staleUntil) {
|
|
365
|
+
this.revalidateInBackground(key, fetcher, options);
|
|
366
|
+
return {
|
|
367
|
+
data: cached.value,
|
|
368
|
+
status: "STALE",
|
|
369
|
+
key,
|
|
370
|
+
tags: cached.tags,
|
|
371
|
+
expiresAt: cached.expiresAt,
|
|
372
|
+
durationMs: Math.round((performance.now() - start) * 100) / 100
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
return {
|
|
376
|
+
data: cached.value,
|
|
377
|
+
status: "HIT",
|
|
378
|
+
key,
|
|
379
|
+
tags: cached.tags,
|
|
380
|
+
expiresAt: cached.expiresAt,
|
|
381
|
+
durationMs: Math.round((performance.now() - start) * 100) / 100
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
const existingFlight = this.inFlight.get(key);
|
|
386
|
+
if (existingFlight) {
|
|
387
|
+
this.dedupedHits++;
|
|
388
|
+
const entry = await existingFlight;
|
|
389
|
+
return {
|
|
390
|
+
data: entry.value,
|
|
391
|
+
status: "DEDUPED",
|
|
392
|
+
key,
|
|
393
|
+
tags: entry.tags,
|
|
394
|
+
expiresAt: entry.expiresAt,
|
|
395
|
+
durationMs: Math.round((performance.now() - start) * 100) / 100
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
const flightPromise = (async () => {
|
|
399
|
+
try {
|
|
400
|
+
const freshValue = await fetcher();
|
|
401
|
+
return await this.adapter.set(key, freshValue, options);
|
|
402
|
+
} finally {
|
|
403
|
+
this.inFlight.delete(key);
|
|
404
|
+
}
|
|
405
|
+
})();
|
|
406
|
+
this.inFlight.set(key, flightPromise);
|
|
407
|
+
const stored = await flightPromise;
|
|
408
|
+
return {
|
|
409
|
+
data: stored.value,
|
|
410
|
+
status: "MISS",
|
|
411
|
+
key,
|
|
412
|
+
tags: stored.tags,
|
|
413
|
+
expiresAt: stored.expiresAt,
|
|
414
|
+
durationMs: Math.round((performance.now() - start) * 100) / 100
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
async revalidateInBackground(key, fetcher, options) {
|
|
418
|
+
if (this.inFlight.has(key))
|
|
419
|
+
return;
|
|
420
|
+
const p = (async () => {
|
|
421
|
+
try {
|
|
422
|
+
const fresh = await fetcher();
|
|
423
|
+
await this.adapter.set(key, fresh, options);
|
|
424
|
+
} finally {
|
|
425
|
+
this.inFlight.delete(key);
|
|
426
|
+
}
|
|
427
|
+
})();
|
|
428
|
+
this.inFlight.set(key, p);
|
|
429
|
+
await p;
|
|
430
|
+
}
|
|
431
|
+
async revalidateTag(tag) {
|
|
432
|
+
return this.adapter.invalidateTag(tag);
|
|
433
|
+
}
|
|
434
|
+
async revalidatePath(pathPrefix) {
|
|
435
|
+
return this.adapter.invalidatePath(pathPrefix);
|
|
436
|
+
}
|
|
437
|
+
async delete(key) {
|
|
438
|
+
return this.adapter.delete(key);
|
|
439
|
+
}
|
|
440
|
+
async clear() {
|
|
441
|
+
this.inFlight.clear();
|
|
442
|
+
await this.adapter.clear();
|
|
443
|
+
}
|
|
444
|
+
async entries() {
|
|
445
|
+
return this.adapter.entries();
|
|
446
|
+
}
|
|
447
|
+
async stats() {
|
|
448
|
+
const base = await this.adapter.stats();
|
|
449
|
+
return {
|
|
450
|
+
...base,
|
|
451
|
+
dedupedHits: this.dedupedHits,
|
|
452
|
+
inFlightCount: this.inFlight.size
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
var GLOBAL_CACHE_KEY = "__KILN_DATA_CACHE__";
|
|
457
|
+
function getGlobalDataCache() {
|
|
458
|
+
const g = globalThis;
|
|
459
|
+
if (!g[GLOBAL_CACHE_KEY]) {
|
|
460
|
+
g[GLOBAL_CACHE_KEY] = new DataCache(new MemoryCacheAdapter);
|
|
461
|
+
}
|
|
462
|
+
return g[GLOBAL_CACHE_KEY];
|
|
463
|
+
}
|
|
464
|
+
function configureDataCache(adapter) {
|
|
465
|
+
const cache = getGlobalDataCache();
|
|
466
|
+
cache.setAdapter(adapter);
|
|
467
|
+
return cache;
|
|
468
|
+
}
|
|
469
|
+
function createDataCache(adapter) {
|
|
470
|
+
return new DataCache(adapter);
|
|
471
|
+
}
|
|
472
|
+
async function revalidateTag(tag) {
|
|
473
|
+
return getGlobalDataCache().revalidateTag(tag);
|
|
474
|
+
}
|
|
475
|
+
async function revalidatePath(pathPrefix) {
|
|
476
|
+
return getGlobalDataCache().revalidatePath(pathPrefix);
|
|
477
|
+
}
|
|
478
|
+
function cachedLoader(loaderFn, config = {}, cacheInstance) {
|
|
479
|
+
const cache = cacheInstance ?? getGlobalDataCache();
|
|
480
|
+
return async (ctx) => {
|
|
481
|
+
const url = new URL(ctx.request.url);
|
|
482
|
+
const computedKey = typeof config.key === "function" ? config.key(ctx) : config.key ?? `loader:${url.pathname}${url.search}`;
|
|
483
|
+
const res = await cache.load(computedKey, async () => await loaderFn(ctx), {
|
|
484
|
+
ttl: config.ttl ?? 60,
|
|
485
|
+
staleWhileRevalidate: config.staleWhileRevalidate,
|
|
486
|
+
tags: config.tags ?? [],
|
|
487
|
+
path: config.path ?? url.pathname
|
|
488
|
+
});
|
|
489
|
+
return res.data;
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
export {
|
|
493
|
+
DataCache,
|
|
494
|
+
ExternalCacheAdapter,
|
|
495
|
+
MemoryCacheAdapter,
|
|
496
|
+
TieredCacheAdapter,
|
|
497
|
+
cachedLoader,
|
|
498
|
+
configureDataCache,
|
|
499
|
+
createDataCache,
|
|
500
|
+
getGlobalDataCache,
|
|
501
|
+
revalidatePath,
|
|
502
|
+
revalidateTag
|
|
503
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,24 @@
|
|
|
1
|
-
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
"
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@kiln-js/cache",
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"files": [
|
|
6
|
+
"dist"
|
|
7
|
+
],
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"scripts": {
|
|
15
|
+
"build": "bun build ./src/index.ts --outdir ./dist --target bun \u0026\u0026 tsc -p tsconfig.json --emitDeclarationOnly",
|
|
16
|
+
"test": "bun test",
|
|
17
|
+
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
18
|
+
},
|
|
19
|
+
"repository": "github:kiln-js/cache",
|
|
20
|
+
"homepage": "https://kiln-js.vercel.app",
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@kiln-js/core": "^0.4.0"
|
|
23
|
+
}
|
|
24
|
+
}
|