-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathcommon.ts
More file actions
70 lines (64 loc) · 2.05 KB
/
Copy pathcommon.ts
File metadata and controls
70 lines (64 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { type Exception, ValueType } from "../../deps.ts";
import { tracer } from "../../observability/otel/config.ts";
import { meter } from "../../observability/otel/metrics.ts";
import {
ATTR_DECO_CACHE_ENGINE,
ATTR_DECO_CACHE_STATUS,
METRIC_DECO_CACHE_REQUESTS,
} from "../../observability/otel/conventions.ts";
import { inFuture } from "./utils.ts";
export interface CacheMetrics {
engine: string;
total: number;
hits: number;
}
// Single cache counter; `deco.cache.status` carries the outcome.
const cacheRequests = meter.createCounter(METRIC_DECO_CACHE_REQUESTS, {
unit: "{request}",
valueType: ValueType.DOUBLE,
});
const getCacheStatus = (
isMatch: Response | undefined,
): "miss" | "stale" | "hit" => {
if (!isMatch) return "miss";
const expires = isMatch.headers.get("expires");
const isStale = expires ? !inFuture(expires) : false;
return isStale ? "stale" : "hit";
};
export const withInstrumentation = (
cache: CacheStorage,
engine: string,
): CacheStorage => {
return {
...cache,
open: async (cacheName) => {
const cacheImpl = await cache.open(cacheName);
return {
...cacheImpl,
delete: cacheImpl.delete.bind(cacheImpl),
put: cacheImpl.put.bind(cacheImpl),
match: async (req, opts) => {
const span = tracer.startSpan("cache-match", {
attributes: { [ATTR_DECO_CACHE_ENGINE]: engine },
});
try {
const isMatch = await cacheImpl.match(req, opts);
//there is an edge case where there is no expires header, but technically our loader always sets it
const result = getCacheStatus(isMatch);
span.setAttribute(ATTR_DECO_CACHE_STATUS, result);
cacheRequests.add(1, {
[ATTR_DECO_CACHE_STATUS]: result,
[ATTR_DECO_CACHE_ENGINE]: engine,
});
return isMatch;
} catch (err) {
span.recordException(err as Exception);
throw err;
} finally {
span.end();
}
},
};
},
};
};