@agrodt/astro-redis-cache-provider 0.1.0 → 0.1.1

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 CHANGED
@@ -1,5 +1,11 @@
1
1
  # @agrodt/astro-redis-cache-provider
2
2
 
3
+ [![CI](https://github.com/AgroDT/astro-redis-cache-provider/actions/workflows/ci.yml/badge.svg)](https://github.com/AgroDT/astro-redis-cache-provider/actions/workflows/ci.yml)
4
+ [![Coverage Status](https://coveralls.io/repos/github/AgroDT/astro-redis-cache-provider/badge.svg?branch=main)](https://coveralls.io/github/AgroDT/astro-redis-cache-provider?branch=main)
5
+ [![npm version](https://img.shields.io/npm/v/@agrodt/astro-redis-cache-provider.svg)](https://www.npmjs.com/package/@agrodt/astro-redis-cache-provider)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE)
7
+ [![npm downloads](https://img.shields.io/npm/dm/@agrodt/astro-redis-cache-provider.svg)](https://www.npmjs.com/package/@agrodt/astro-redis-cache-provider)
8
+
3
9
  Custom Redis cache provider for Astro route caching,
4
10
  powered by [`node-redis`](https://github.com/redis/node-redis).
5
11
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agrodt/astro-redis-cache-provider",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Redis cache provider for Astro route caching using node-redis.",
5
5
  "keywords": [
6
6
  "astro",
@@ -21,6 +21,8 @@
21
21
  "files": [
22
22
  "dist",
23
23
  "!dist/**/*.test.*",
24
+ "src/**/*.ts",
25
+ "!src/**/*.test.ts",
24
26
  "README.md",
25
27
  "LICENSE"
26
28
  ],
package/src/config.ts ADDED
@@ -0,0 +1,18 @@
1
+ import type { CacheProviderConfig } from "astro";
2
+
3
+ import type { RedisCacheProviderOptions } from "./runtime.js";
4
+
5
+ /**
6
+ * Creates Astro cache provider configuration for the Redis runtime provider.
7
+ */
8
+ export function redisCache(
9
+ config: RedisCacheProviderOptions = {},
10
+ ): CacheProviderConfig<RedisCacheProviderOptions> {
11
+ return {
12
+ name: "redis",
13
+ entrypoint: "@agrodt/astro-redis-cache-provider/runtime",
14
+ config,
15
+ };
16
+ }
17
+
18
+ export default redisCache;
package/src/runtime.ts ADDED
@@ -0,0 +1,711 @@
1
+ import { hash as nodeHash } from "node:crypto";
2
+
3
+ import type { CacheProvider } from "astro";
4
+ import picomatch from "picomatch";
5
+ import { createClient, RESP_TYPES } from "redis";
6
+
7
+ import { StoredCacheEntry } from "./schemas.js";
8
+
9
+ export type { RedisCacheProvider, RedisCacheProviderOptions };
10
+ export { createRedisCacheProvider, createRedisCacheProvider as default };
11
+
12
+ const SCHEMA_VERSION = 1;
13
+
14
+ /**
15
+ * Built-in query parameter patterns excluded from cache keys.
16
+ * @internal
17
+ */
18
+ export const DEFAULT_EXCLUDED_PARAMS = [
19
+ "utm_*",
20
+ "fbclid",
21
+ "gclid",
22
+ "gbraid",
23
+ "wbraid",
24
+ "dclid",
25
+ "msclkid",
26
+ "twclid",
27
+ "li_fat_id",
28
+ "mc_cid",
29
+ "mc_eid",
30
+ "_ga",
31
+ "_gl",
32
+ "_hsenc",
33
+ "_hsmi",
34
+ "_ke",
35
+ "oly_anon_id",
36
+ "oly_enc_id",
37
+ "rb_clickid",
38
+ "s_cid",
39
+ "vero_id",
40
+ "wickedid",
41
+ "yclid",
42
+ "__s",
43
+ "ref",
44
+ ] as const;
45
+
46
+ /**
47
+ * Query string normalization settings for cache key generation.
48
+ *
49
+ * `include` and `exclude` are mutually exclusive.
50
+ */
51
+ export interface QueryConfigInput {
52
+ /**
53
+ * Only these query parameter names are included in cache keys.
54
+ * @default undefined
55
+ */
56
+ include?: string[];
57
+
58
+ /**
59
+ * Query parameter names or glob patterns excluded from cache keys.
60
+ * @default {@link DEFAULT_EXCLUDED_PARAMS}
61
+ */
62
+ exclude?: string[];
63
+
64
+ /**
65
+ * Sorts query parameters before key generation for stable cache keys.
66
+ * @default true
67
+ */
68
+ sort?: boolean;
69
+ }
70
+
71
+ interface QueryConfig {
72
+ include: string[] | null;
73
+ excludeMatcher: ((key: string) => boolean) | null;
74
+ sort: boolean;
75
+ }
76
+
77
+ type RedisClient = ReturnType<typeof createClientWithTypeMapping>;
78
+
79
+ /**
80
+ * Configuration for the Redis cache provider.
81
+ */
82
+ interface RedisCacheProviderOptions {
83
+ /**
84
+ * Redis connection URL or runtime resolver for values unavailable at build time.
85
+ * @default undefined
86
+ */
87
+ url?: string | (() => string | undefined);
88
+
89
+ /**
90
+ * Prefix used for all cache keys stored in Redis.
91
+ * @default "astro:cache"
92
+ */
93
+ keyPrefix?: string;
94
+
95
+ /**
96
+ * Query string normalization rules used when building cache keys.
97
+ * @default undefined
98
+ */
99
+ query?: QueryConfigInput;
100
+
101
+ /**
102
+ * Lock TTL in seconds for stale-while-revalidate background refresh.
103
+ * @default 30
104
+ */
105
+ revalidateLockTtl?: number;
106
+
107
+ /**
108
+ * Additional `Vary` header names to ignore during cache key matching.
109
+ * `set-cookie` is always ignored.
110
+ *
111
+ * @default []
112
+ */
113
+ ignoredVaryHeaders?: Iterable<string>;
114
+ }
115
+
116
+ /**
117
+ * Astro cache provider implementation with an explicit shutdown hook.
118
+ */
119
+ interface RedisCacheProvider extends CacheProvider {
120
+ /** Closes the Redis client connection used by the provider instance. */
121
+ close(): Promise<void>;
122
+ }
123
+
124
+ function createClientWithTypeMapping(url: string | undefined) {
125
+ return createClient({ url }).withTypeMapping({
126
+ [RESP_TYPES.BLOB_STRING]: Buffer,
127
+ });
128
+ }
129
+
130
+ function parseCdnCacheControl(header: string | null): {
131
+ maxAge: number;
132
+ swr: number;
133
+ } {
134
+ let maxAge = 0;
135
+ let swr = 0;
136
+ if (!header) {
137
+ return { maxAge, swr };
138
+ }
139
+
140
+ for (const part of header.split(",")) {
141
+ const trimmed = part.trim().toLowerCase();
142
+ if (trimmed.startsWith("max-age=")) {
143
+ maxAge = Number.parseInt(trimmed.slice(8), 10) || 0;
144
+ continue;
145
+ }
146
+ if (trimmed.startsWith("stale-while-revalidate=")) {
147
+ swr = Number.parseInt(trimmed.slice(23), 10) || 0;
148
+ }
149
+ }
150
+
151
+ return { maxAge, swr };
152
+ }
153
+
154
+ function parseCacheTags(header: string | null): string[] {
155
+ const tags = [];
156
+
157
+ if (header) {
158
+ for (let tag of header.split(",")) {
159
+ tag = tag.trim();
160
+ if (tag) {
161
+ tags.push(tag);
162
+ }
163
+ }
164
+ }
165
+
166
+ return tags;
167
+ }
168
+
169
+ function parseVaryHeader(
170
+ response: Response,
171
+ ignoredVaryHeaders: ReadonlySet<string>,
172
+ ): string[] {
173
+ const vary = response.headers.get("Vary");
174
+ if (!vary || vary.trim() === "*") {
175
+ return [];
176
+ }
177
+
178
+ return vary
179
+ .split(",")
180
+ .map((h) => h.trim().toLowerCase())
181
+ .filter((h) => h.length > 0 && !ignoredVaryHeaders.has(h));
182
+ }
183
+
184
+ function matchesVary(request: Request, entry: StoredCacheEntry): boolean {
185
+ if (!entry.vary.length) {
186
+ return true;
187
+ }
188
+ for (const header of entry.vary) {
189
+ const requestValue = request.headers.get(header) ?? "";
190
+ if (requestValue !== entry.varyValues.get(header)) {
191
+ return false;
192
+ }
193
+ }
194
+ return true;
195
+ }
196
+
197
+ function buildVarySuffix(request: Request, varyHeaders: string[]): string {
198
+ if (varyHeaders.length === 0) {
199
+ return "";
200
+ }
201
+ const parts: string[] = [];
202
+ for (const header of varyHeaders) {
203
+ parts.push(`${header}=${request.headers.get(header) ?? ""}`);
204
+ }
205
+ return `\0${parts.join("\0")}`;
206
+ }
207
+
208
+ function encodeVaryHeaders(varyHeaders: string[]): string {
209
+ return varyHeaders.join(",");
210
+ }
211
+
212
+ function decodeVaryHeaders(raw: Buffer): string[] {
213
+ return raw.toString("utf8").split(",");
214
+ }
215
+
216
+ function normalizeQueryConfig({
217
+ include,
218
+ exclude,
219
+ sort = true,
220
+ }: QueryConfigInput = {}): QueryConfig {
221
+ if (include && exclude) {
222
+ throw new Error(
223
+ "`query.include` and `query.exclude` cannot be used together.",
224
+ );
225
+ }
226
+
227
+ const excludePatterns = include
228
+ ? []
229
+ : (exclude ?? [...DEFAULT_EXCLUDED_PARAMS]);
230
+ const excludeMatcher =
231
+ excludePatterns.length > 0
232
+ ? picomatch(excludePatterns, { nocase: true })
233
+ : null;
234
+
235
+ return { include: include ?? null, excludeMatcher, sort };
236
+ }
237
+
238
+ function buildQueryString(url: URL, config: QueryConfig): string {
239
+ const params = new URLSearchParams(url.searchParams);
240
+
241
+ if (config.include) {
242
+ const allowed = new Set(config.include);
243
+ for (const key of Array.from(params.keys())) {
244
+ if (!allowed.has(key)) {
245
+ params.delete(key);
246
+ }
247
+ }
248
+ }
249
+
250
+ if (config.excludeMatcher) {
251
+ for (const key of Array.from(params.keys())) {
252
+ if (config.excludeMatcher(key)) {
253
+ params.delete(key);
254
+ }
255
+ }
256
+ }
257
+
258
+ if (config.sort) {
259
+ params.sort();
260
+ }
261
+
262
+ const queryString = params.toString();
263
+ return queryString ? `?${queryString}` : "";
264
+ }
265
+
266
+ function getCachePrimaryKey(url: URL, queryConfig: QueryConfig): string {
267
+ return `${url.origin}${url.pathname}${buildQueryString(url, queryConfig)}`;
268
+ }
269
+
270
+ function getCachePath(url: URL, queryConfig: QueryConfig): string {
271
+ return `${url.pathname}${buildQueryString(url, queryConfig)}`;
272
+ }
273
+
274
+ function hash(value: string): string {
275
+ return nodeHash("sha256", value, "hex");
276
+ }
277
+
278
+ function normalizeKeyPrefix(value: string | undefined): string {
279
+ const prefix = value?.trim() || "astro:cache";
280
+ return prefix.endsWith(":") ? prefix : `${prefix}:`;
281
+ }
282
+
283
+ function buildEntryKey(prefix: string, cacheKey: string): string {
284
+ return `${prefix}v${SCHEMA_VERSION}:entry:${hash(cacheKey)}`;
285
+ }
286
+
287
+ function buildVaryKey(prefix: string, primaryKey: string): string {
288
+ return `${prefix}v${SCHEMA_VERSION}:vary:${hash(primaryKey)}`;
289
+ }
290
+
291
+ function buildPathIndexKey(prefix: string, path: string): string {
292
+ return `${prefix}v${SCHEMA_VERSION}:idx:path:${hash(path)}`;
293
+ }
294
+
295
+ function buildTagIndexKey(prefix: string, tag: string): string {
296
+ return `${prefix}v${SCHEMA_VERSION}:idx:tag:${hash(tag)}`;
297
+ }
298
+
299
+ function buildRevalidateLockKey(prefix: string, cacheKey: string): string {
300
+ return `${prefix}v${SCHEMA_VERSION}:lock:${hash(cacheKey)}`;
301
+ }
302
+
303
+ function warn(message: string): void {
304
+ console.warn(`[astro:cache:redis] ${message}`);
305
+ }
306
+
307
+ function getCacheFreshness(
308
+ entry: StoredCacheEntry,
309
+ ): "fresh" | "stale" | "expired" {
310
+ const ageSeconds = Math.floor((Date.now() - entry.storedAt.getTime()) / 1000);
311
+ if (ageSeconds <= entry.maxAge) {
312
+ return "fresh";
313
+ }
314
+ if (ageSeconds <= entry.maxAge + entry.swr) {
315
+ return "stale";
316
+ }
317
+ return "expired";
318
+ }
319
+
320
+ function createResponseFromEntry(entry: StoredCacheEntry): Response {
321
+ const headers = new Headers(
322
+ entry.headers as unknown as Record<string, string>,
323
+ );
324
+ const body = Buffer.from(entry.body);
325
+ return new Response(body, {
326
+ status: entry.status,
327
+ headers,
328
+ });
329
+ }
330
+
331
+ function parseStoredEntry(raw: Buffer | null): StoredCacheEntry | null {
332
+ if (!raw) {
333
+ return null;
334
+ }
335
+
336
+ try {
337
+ return StoredCacheEntry.decode(raw);
338
+ } catch {
339
+ return null;
340
+ }
341
+ }
342
+
343
+ async function serializeResponse(
344
+ response: Response,
345
+ request: Request,
346
+ path: string,
347
+ maxAge: number,
348
+ swr: number,
349
+ tags: string[],
350
+ ignoredVaryHeaders: ReadonlySet<string>,
351
+ ): Promise<StoredCacheEntry> {
352
+ const bodyBuffer = await response.arrayBuffer();
353
+ const bodyBytes = new Uint8Array(bodyBuffer);
354
+
355
+ const headers = new Map();
356
+ response.headers.forEach((value, key) => {
357
+ if (key.toLowerCase() !== "set-cookie") {
358
+ headers.set(key, value);
359
+ }
360
+ });
361
+
362
+ const vary = parseVaryHeader(response, ignoredVaryHeaders);
363
+ const varyValues = new Map();
364
+ for (const header of vary) {
365
+ const value = request.headers.get(header) ?? "";
366
+ varyValues.set(header, value);
367
+ }
368
+
369
+ return {
370
+ status: response.status,
371
+ headers,
372
+ body: bodyBytes,
373
+ storedAt: new Date(),
374
+ maxAge,
375
+ swr,
376
+ tags: Array.from(new Set(tags)),
377
+ path,
378
+ vary,
379
+ varyValues,
380
+ };
381
+ }
382
+
383
+ /**
384
+ * Creates a Redis-backed cache provider for Astro route caching.
385
+ */
386
+ function createRedisCacheProvider(
387
+ config: RedisCacheProviderOptions = {},
388
+ ): RedisCacheProvider {
389
+ const keyPrefix = normalizeKeyPrefix(config?.keyPrefix);
390
+ const queryConfig = normalizeQueryConfig(config?.query);
391
+ const lockTtlSeconds = Math.max(5, config?.revalidateLockTtl ?? 30);
392
+ const ignoredVaryHeaders = new Set(["set-cookie"]);
393
+
394
+ const extraIgnoredVaryHeaders = config?.ignoredVaryHeaders;
395
+ if (extraIgnoredVaryHeaders) {
396
+ for (const header of extraIgnoredVaryHeaders) {
397
+ const normalized = header.trim().toLocaleLowerCase();
398
+ if (normalized.length > 0) {
399
+ ignoredVaryHeaders.add(normalized);
400
+ }
401
+ }
402
+ }
403
+
404
+ let clientPromise: Promise<RedisClient> | undefined;
405
+
406
+ const getClient = (): Promise<RedisClient> => {
407
+ if (clientPromise) {
408
+ return clientPromise;
409
+ }
410
+
411
+ let redisUrl = config?.url;
412
+ if (typeof redisUrl === "function") {
413
+ redisUrl = redisUrl();
414
+ }
415
+
416
+ const client = createClientWithTypeMapping(redisUrl);
417
+ client.on("error", (error) => {
418
+ warn(`Redis client error: ${String(error)}`);
419
+ });
420
+
421
+ const pending = client
422
+ .connect()
423
+ .then(() => client)
424
+ .catch((error) => {
425
+ clientPromise = undefined;
426
+ throw error;
427
+ });
428
+ clientPromise = pending;
429
+
430
+ return pending;
431
+ };
432
+
433
+ const deleteEntry = async (
434
+ client: RedisClient,
435
+ key: string,
436
+ ): Promise<void> => {
437
+ const existing = parseStoredEntry(await client.get(key));
438
+ const multi = client.multi();
439
+ multi.del(key);
440
+
441
+ if (existing) {
442
+ multi.sRem(buildPathIndexKey(keyPrefix, existing.path), key);
443
+ for (const tag of existing.tags) {
444
+ multi.sRem(buildTagIndexKey(keyPrefix, tag), key);
445
+ }
446
+ }
447
+
448
+ await multi.exec();
449
+ };
450
+
451
+ const storeEntry = async (
452
+ client: RedisClient,
453
+ key: string,
454
+ primaryKey: string,
455
+ entry: StoredCacheEntry,
456
+ ): Promise<void> => {
457
+ const existing = parseStoredEntry(await client.get(key));
458
+ const ttl = Math.max(1, Math.ceil(entry.maxAge + entry.swr));
459
+ const multi = client.multi();
460
+
461
+ multi.set(key, Buffer.from(StoredCacheEntry.encode(entry)), { EX: ttl });
462
+ const varyKey = buildVaryKey(keyPrefix, primaryKey);
463
+ if (entry.vary.length) {
464
+ multi.set(varyKey, encodeVaryHeaders(entry.vary));
465
+ } else {
466
+ multi.del(varyKey);
467
+ }
468
+
469
+ if (existing) {
470
+ multi.sRem(buildPathIndexKey(keyPrefix, existing.path), key);
471
+ for (const tag of existing.tags) {
472
+ multi.sRem(buildTagIndexKey(keyPrefix, tag), key);
473
+ }
474
+ }
475
+
476
+ const pathIndexKey = buildPathIndexKey(keyPrefix, entry.path);
477
+ multi.sAdd(pathIndexKey, key);
478
+ multi.expire(pathIndexKey, ttl, "NX");
479
+ multi.expire(pathIndexKey, ttl, "GT");
480
+ for (const tag of entry.tags) {
481
+ const tagIndexKey = buildTagIndexKey(keyPrefix, tag);
482
+ multi.sAdd(tagIndexKey, key);
483
+ multi.expire(tagIndexKey, ttl, "NX");
484
+ multi.expire(tagIndexKey, ttl, "GT");
485
+ }
486
+
487
+ await multi.exec();
488
+ };
489
+
490
+ const loadKnownVaryHeaders = async (
491
+ client: RedisClient,
492
+ primaryKey: string,
493
+ ): Promise<string[] | undefined> => {
494
+ const raw = await client.get(buildVaryKey(keyPrefix, primaryKey));
495
+ return raw ? decodeVaryHeaders(raw) : undefined;
496
+ };
497
+
498
+ const maybeStoreResponse = async (
499
+ client: RedisClient,
500
+ response: Response,
501
+ request: Request,
502
+ requestUrl: URL,
503
+ primaryKey: string,
504
+ ): Promise<boolean> => {
505
+ const cdnCacheControl = response.headers.get("CDN-Cache-Control");
506
+ const { maxAge, swr } = parseCdnCacheControl(cdnCacheControl);
507
+ if (maxAge <= 0) {
508
+ return false;
509
+ }
510
+
511
+ if (response.headers.has("set-cookie")) {
512
+ warn(
513
+ `Skipping cache for ${requestUrl.pathname}${requestUrl.search} because response includes Set-Cookie.`,
514
+ );
515
+ return false;
516
+ }
517
+
518
+ const tags = parseCacheTags(response.headers.get("Cache-Tag"));
519
+ const entry = await serializeResponse(
520
+ response,
521
+ request,
522
+ getCachePath(requestUrl, queryConfig),
523
+ maxAge,
524
+ swr,
525
+ tags,
526
+ ignoredVaryHeaders,
527
+ );
528
+
529
+ const key = buildEntryKey(
530
+ keyPrefix,
531
+ primaryKey +
532
+ (entry.vary.length ? buildVarySuffix(request, entry.vary) : ""),
533
+ );
534
+ await storeEntry(client, key, primaryKey, entry);
535
+
536
+ return true;
537
+ };
538
+
539
+ const revalidateInBackground = async (
540
+ client: RedisClient,
541
+ lockKey: string,
542
+ requestUrl: URL,
543
+ request: Request,
544
+ primaryKey: string,
545
+ next: () => Promise<Response>,
546
+ ): Promise<void> => {
547
+ const lock = await client.set(lockKey, "1", {
548
+ NX: true,
549
+ EX: lockTtlSeconds,
550
+ });
551
+ if (lock !== "OK") {
552
+ return;
553
+ }
554
+
555
+ try {
556
+ const freshResponse = await next();
557
+ await maybeStoreResponse(
558
+ client,
559
+ freshResponse,
560
+ request,
561
+ requestUrl,
562
+ primaryKey,
563
+ );
564
+ } catch (error) {
565
+ warn(
566
+ `Background revalidation failed for ${requestUrl.pathname}${requestUrl.search}: ${String(error)}`,
567
+ );
568
+ } finally {
569
+ try {
570
+ await client.del(lockKey);
571
+ } catch {
572
+ // Lock expiration is enough when explicit delete fails.
573
+ }
574
+ }
575
+ };
576
+
577
+ const invalidateByIndex = async (
578
+ client: RedisClient,
579
+ indexKey: string,
580
+ ): Promise<void> => {
581
+ const keys = await client.sMembers(indexKey);
582
+ for (const key of keys) {
583
+ await deleteEntry(client, key.toString("utf8"));
584
+ }
585
+ await client.del(indexKey);
586
+ };
587
+
588
+ return {
589
+ name: "redis",
590
+ async onRequest(context, next) {
591
+ if (context.request.method !== "GET") {
592
+ return next();
593
+ }
594
+
595
+ const requestUrl = new URL(context.request.url);
596
+ const primaryKey = getCachePrimaryKey(requestUrl, queryConfig);
597
+
598
+ let client: RedisClient;
599
+ try {
600
+ client = await getClient();
601
+ } catch (error) {
602
+ warn(`Redis is unavailable, bypassing cache: ${String(error)}`);
603
+ return next();
604
+ }
605
+
606
+ try {
607
+ const knownVary = await loadKnownVaryHeaders(client, primaryKey);
608
+ const lookupKey = buildEntryKey(
609
+ keyPrefix,
610
+ primaryKey +
611
+ (knownVary ? buildVarySuffix(context.request, knownVary) : ""),
612
+ );
613
+
614
+ const cachedEntry = parseStoredEntry(await client.get(lookupKey));
615
+ if (cachedEntry && matchesVary(context.request, cachedEntry)) {
616
+ const freshness = getCacheFreshness(cachedEntry);
617
+
618
+ if (freshness === "fresh") {
619
+ const response = createResponseFromEntry(cachedEntry);
620
+ response.headers.set("X-Astro-Cache", "HIT");
621
+ return response;
622
+ }
623
+
624
+ if (freshness === "stale") {
625
+ const lockKey = buildRevalidateLockKey(keyPrefix, lookupKey);
626
+ const task = revalidateInBackground(
627
+ client,
628
+ lockKey,
629
+ requestUrl,
630
+ context.request,
631
+ primaryKey,
632
+ next,
633
+ );
634
+
635
+ const waitUntil = (
636
+ context as {
637
+ waitUntil?: (promise: Promise<unknown>) => void;
638
+ }
639
+ ).waitUntil;
640
+
641
+ if (typeof waitUntil === "function") {
642
+ waitUntil(task);
643
+ } else {
644
+ void task;
645
+ }
646
+
647
+ const response = createResponseFromEntry(cachedEntry);
648
+ response.headers.set("X-Astro-Cache", "STALE");
649
+ return response;
650
+ }
651
+ }
652
+ } catch (error) {
653
+ warn(`Cache read failed, bypassing cache read path: ${String(error)}`);
654
+ return next();
655
+ }
656
+
657
+ const response = await next();
658
+ try {
659
+ const [forCache, forClient] = [response.clone(), response];
660
+ const stored = await maybeStoreResponse(
661
+ client,
662
+ forCache,
663
+ context.request,
664
+ requestUrl,
665
+ primaryKey,
666
+ );
667
+ if (stored) {
668
+ forClient.headers.set("X-Astro-Cache", "MISS");
669
+ }
670
+ return forClient;
671
+ } catch (error) {
672
+ warn(
673
+ `Cache write failed, returning uncached response: ${String(error)}`,
674
+ );
675
+ return response;
676
+ }
677
+ },
678
+ async invalidate(options) {
679
+ const client = await getClient();
680
+
681
+ if (options.path) {
682
+ await invalidateByIndex(
683
+ client,
684
+ buildPathIndexKey(keyPrefix, options.path),
685
+ );
686
+ }
687
+
688
+ if (options.tags) {
689
+ const tags = Array.isArray(options.tags)
690
+ ? options.tags
691
+ : [options.tags];
692
+ for (const tag of tags) {
693
+ await invalidateByIndex(client, buildTagIndexKey(keyPrefix, tag));
694
+ }
695
+ }
696
+ },
697
+ async close() {
698
+ if (!clientPromise) {
699
+ return;
700
+ }
701
+ try {
702
+ const client = await clientPromise;
703
+ await client.close();
704
+ } catch {
705
+ // Ignore close errors to keep shutdown safe in tests and app exits.
706
+ } finally {
707
+ clientPromise = undefined;
708
+ }
709
+ },
710
+ };
711
+ }
package/src/schemas.ts ADDED
@@ -0,0 +1,174 @@
1
+ //------------------------------------------------------------------------------
2
+ // <auto-generated>
3
+ // This code was generated by a tool.
4
+ //
5
+ //
6
+ // bebopc version:
7
+ // 3.2.3
8
+ //
9
+ //
10
+ // bebopc source:
11
+ // https://github.com/6over3/bebop
12
+ //
13
+ //
14
+ // Changes to this file may cause incorrect behavior and will be lost if
15
+ // the code is regenerated.
16
+ // </auto-generated>
17
+ import { BebopView, type BebopRecord } from "bebop";
18
+
19
+
20
+ export interface StoredCacheEntry {
21
+
22
+ readonly status: number;
23
+
24
+ readonly headers: Map<string, string>;
25
+
26
+ readonly body: Uint8Array;
27
+
28
+ readonly storedAt: Date;
29
+
30
+ readonly maxAge: number;
31
+
32
+ readonly swr: number;
33
+
34
+ readonly tags: string[];
35
+
36
+ readonly path: string;
37
+
38
+ readonly vary: string[];
39
+
40
+ readonly varyValues: Map<string, string>;
41
+ }
42
+
43
+ export const StoredCacheEntry = /*#__PURE__*/ Object.freeze(/*#__PURE__*/ Object.assign(
44
+ // Factory function
45
+ (data: StoredCacheEntry): StoredCacheEntry & BebopRecord => {
46
+ return Object.freeze({
47
+ ...data,
48
+ encode(): Uint8Array {
49
+ return StoredCacheEntry.encode(this);
50
+ }
51
+ });
52
+ },
53
+ // Static methods
54
+ {
55
+ encode(record: StoredCacheEntry): Uint8Array {
56
+ const view = BebopView.getInstance();
57
+ view.startWriting();
58
+ StoredCacheEntry.encodeInto(record, view);
59
+ return view.toArray();
60
+ },
61
+
62
+ encodeInto(record: StoredCacheEntry, view: BebopView): void {
63
+ view.writeUint16(record.status);
64
+ view.writeUint32(record.headers.size);
65
+ for (const [k0, v0] of record.headers) {
66
+ view.writeString(k0);
67
+ view.writeString(v0);
68
+ }
69
+ view.writeBytes(record.body);
70
+ view.writeDate(record.storedAt);
71
+ view.writeUint32(record.maxAge);
72
+ view.writeUint32(record.swr);
73
+ {
74
+ const length0 = record.tags.length;
75
+ view.writeUint32(length0);
76
+ for (let i0 = 0; i0 < length0; i0++) {
77
+ view.writeString(record.tags[i0]);
78
+ }
79
+ }
80
+ view.writeString(record.path);
81
+ {
82
+ const length0 = record.vary.length;
83
+ view.writeUint32(length0);
84
+ for (let i0 = 0; i0 < length0; i0++) {
85
+ view.writeString(record.vary[i0]);
86
+ }
87
+ }
88
+ view.writeUint32(record.varyValues.size);
89
+ for (const [k0, v0] of record.varyValues) {
90
+ view.writeString(k0);
91
+ view.writeString(v0);
92
+ }
93
+ },
94
+
95
+ decode(buffer: Uint8Array): StoredCacheEntry & BebopRecord {
96
+ const view = BebopView.getInstance();
97
+ view.startReading(buffer);
98
+ const decoded = StoredCacheEntry.readFrom(view);
99
+ return StoredCacheEntry(decoded);
100
+ },
101
+
102
+ readFrom(view: BebopView): StoredCacheEntry {
103
+ let field0: number;
104
+ field0 = view.readUint16();
105
+ let field1: Map<string, string>;
106
+ {
107
+ const length0 = view.readUint32();
108
+ field1 = new Map();
109
+ for (let i0 = 0; i0 < length0; i0++) {
110
+ let k0: string;
111
+ let v0: string;
112
+ k0 = view.readString();
113
+ v0 = view.readString();
114
+ field1.set(k0, v0);
115
+ }
116
+ }
117
+ let field2: Uint8Array;
118
+ field2 = view.readBytes();
119
+ let field3: Date;
120
+ field3 = view.readDate();
121
+ let field4: number;
122
+ field4 = view.readUint32();
123
+ let field5: number;
124
+ field5 = view.readUint32();
125
+ let field6: string[];
126
+ {
127
+ const length0 = view.readUint32();
128
+ field6 = [];
129
+ for (let i0 = 0; i0 < length0; i0++) {
130
+ let x0: string;
131
+ x0 = view.readString();
132
+ field6[i0] = x0;
133
+ }
134
+ }
135
+ let field7: string;
136
+ field7 = view.readString();
137
+ let field8: string[];
138
+ {
139
+ const length0 = view.readUint32();
140
+ field8 = [];
141
+ for (let i0 = 0; i0 < length0; i0++) {
142
+ let x0: string;
143
+ x0 = view.readString();
144
+ field8[i0] = x0;
145
+ }
146
+ }
147
+ let field9: Map<string, string>;
148
+ {
149
+ const length0 = view.readUint32();
150
+ field9 = new Map();
151
+ for (let i0 = 0; i0 < length0; i0++) {
152
+ let k0: string;
153
+ let v0: string;
154
+ k0 = view.readString();
155
+ v0 = view.readString();
156
+ field9.set(k0, v0);
157
+ }
158
+ }
159
+ return {
160
+ status: field0,
161
+ headers: field1,
162
+ body: field2,
163
+ storedAt: field3,
164
+ maxAge: field4,
165
+ swr: field5,
166
+ tags: field6,
167
+ path: field7,
168
+ vary: field8,
169
+ varyValues: field9,
170
+ };
171
+ },
172
+ }
173
+ ));
174
+