Repository navigation
Expand file tree
/
Copy pathcache-rules.ts
More file actions
232 lines (205 loc) · 8.02 KB
/
Copy pathcache-rules.ts
File metadata and controls
232 lines (205 loc) · 8.02 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import { parseQuantity } from "./rpc.js";
export interface CacheRuleContext {
/** Highest block number known across the pool; null when unknown. */
chainHead: number | null;
shortTtlMs: number;
pendingTtlMs: number;
/** Fallback TTL for reorg-validated entries below finalityDepth. */
unfinalizedTtlMs: number;
finalityDepth: number;
}
export const LONG_TTL_MS = 60 * 60 * 1000; // chain id, client version, etc.
/**
* Request-stage cache policy.
* - cacheable: false -> never touch the cache
* - ttlMs: number | null -> store response with this TTL (null = no expiry)
* - ttlMs: "by-response" -> TTL decided from the response via responseTtl()
* - stampHeight: number -> store wrapped via wrapValidatedEntry with
* this height + the canonical hash at write
* time, for read-time reorg validation
*/
export type RequestPolicy =
| { cacheable: false }
| { cacheable: true; ttlMs: number | null | "by-response"; stampHeight?: number };
const NOT_CACHEABLE: RequestPolicy = { cacheable: false };
const BLOCK_TAGS = new Set(["latest", "earliest", "pending", "safe", "finalized"]);
/** Methods whose params locate data by an immutable hash (block hash, tx hash). */
const HASH_KEYED_METHODS = new Set([
"eth_getBlockByHash",
"eth_getTransactionByHash",
"eth_getBlockTransactionCountByHash",
"eth_getTransactionByBlockHashAndIndex",
"eth_getUncleByBlockHashAndIndex",
"eth_getUncleCountByBlockHash",
]);
/** Methods whose first param is a block number/tag and whose result is immutable once finalized. */
const NUMBER_KEYED_METHODS = new Set([
"eth_getBlockByNumber",
"eth_getBlockTransactionCountByNumber",
"eth_getTransactionByBlockNumberAndIndex",
"eth_getUncleByBlockNumberAndIndex",
"eth_getUncleCountByBlockNumber",
]);
/**
* The seven methods using plain-text cache keys (params embedded, not
* hashed) and read-time reorg validation. Number-keyed entries below
* finalityDepth are stamped with the canonical hash at write time; mined
* tx-hash entries validate from their own blockNumber/blockHash payload.
*/
export const RAW_KEY_METHODS = new Set([
...NUMBER_KEYED_METHODS,
"eth_getTransactionByHash",
"eth_getTransactionReceipt",
]);
/** Per-method param kinds for raw-key normalization: q = quantity, d = data, x = leave as-is. */
const RAW_KEY_PARAM_KINDS: Record<string, ("q" | "d" | "x")[]> = {
eth_getBlockByNumber: ["q", "x"],
eth_getBlockTransactionCountByNumber: ["q"],
eth_getTransactionByBlockNumberAndIndex: ["q", "q"],
eth_getUncleByBlockNumberAndIndex: ["q", "q"],
eth_getUncleCountByBlockNumber: ["q"],
eth_getTransactionByHash: ["d"],
eth_getTransactionReceipt: ["d"],
};
/** Canonical quantity form: lowercase minimal hex ("0x03E9" -> "0x3e9"); non-quantities untouched. */
function normalizeQuantity(value: unknown): unknown {
if (typeof value !== "string") return value;
const n = parseQuantity(value);
return n === null ? value : `0x${n.toString(16)}`;
}
/**
* Normalize params for raw-key construction so semantically equal calls map
* to one key (and external tooling has a single canonical form to build).
*/
export function normalizeRawKeyParams(method: string, params: unknown[]): unknown[] {
const kinds = RAW_KEY_PARAM_KINDS[method];
if (kinds === undefined) return params;
return params.map((p, i) => {
const kind = kinds[i];
if (kind === "q") return normalizeQuantity(p);
if (kind === "d") return typeof p === "string" ? p.toLowerCase() : p;
return p;
});
}
/** State queries: method -> index of the block tag param. */
const STATE_METHOD_TAG_INDEX: Record<string, number> = {
eth_call: 1,
eth_estimateGas: 1,
eth_getBalance: 1,
eth_getCode: 1,
eth_getTransactionCount: 1,
eth_getStorageAt: 2,
eth_getProof: 2,
};
const SHORT_TTL_METHODS = new Set([
"eth_blockNumber",
"eth_gasPrice",
"eth_maxPriorityFeePerGas",
"eth_syncing",
]);
const LONG_TTL_METHODS = new Set([
"eth_chainId",
"net_version",
"web3_clientVersion",
"eth_protocolVersion",
]);
function isFinalized(blockNumber: number, ctx: CacheRuleContext): boolean {
if (ctx.chainHead === null) return false;
return blockNumber <= ctx.chainHead - ctx.finalityDepth;
}
/**
* Policy for a request that carries a block number/tag in `tag`.
* "pending" and blocks beyond the known head are never cacheable;
* deep-enough blocks are permanent; anything near the head is short-TTL —
* or, with `nearHead: "stamped"` (the number-keyed raw-key methods), gets
* the unfinalized TTL plus a validation stamp for read-time reorg checks.
*/
function blockTagPolicy(
tag: unknown,
ctx: CacheRuleContext,
nearHead: "short" | "stamped" = "short",
): RequestPolicy {
if (tag === undefined) return { cacheable: true, ttlMs: ctx.shortTtlMs }; // defaults to "latest"
if (typeof tag === "string" && BLOCK_TAGS.has(tag)) {
if (tag === "pending") return NOT_CACHEABLE;
if (tag === "earliest") return { cacheable: true, ttlMs: null }; // genesis is immutable
return { cacheable: true, ttlMs: ctx.shortTtlMs };
}
const n = parseQuantity(tag);
if (n === null) return NOT_CACHEABLE;
if (ctx.chainHead !== null && n > ctx.chainHead) return NOT_CACHEABLE; // future block
if (isFinalized(n, ctx)) return { cacheable: true, ttlMs: null };
if (nearHead === "stamped") {
return { cacheable: true, ttlMs: ctx.unfinalizedTtlMs, stampHeight: n };
}
return { cacheable: true, ttlMs: ctx.shortTtlMs };
}
function logsPolicy(params: unknown[], ctx: CacheRuleContext): RequestPolicy {
const filter = params[0];
if (typeof filter !== "object" || filter === null) return NOT_CACHEABLE;
const { fromBlock, toBlock } = filter as Record<string, unknown>;
if (fromBlock === "pending" || toBlock === "pending") return NOT_CACHEABLE;
const from = fromBlock === undefined ? null : parseQuantity(fromBlock);
const to = toBlock === undefined ? null : parseQuantity(toBlock);
if (from === null || to === null) {
// "latest"/"earliest"/missing bounds: near-head, short TTL
return { cacheable: true, ttlMs: ctx.shortTtlMs };
}
return isFinalized(to, ctx)
? { cacheable: true, ttlMs: null }
: { cacheable: true, ttlMs: ctx.shortTtlMs };
}
export function requestPolicy(
method: string,
params: unknown[],
ctx: CacheRuleContext,
): RequestPolicy {
if (HASH_KEYED_METHODS.has(method)) {
// Hash-keyed data is immutable, but a null result may just mean the node
// is behind / the tx is not mined yet — decide from the response.
return { cacheable: true, ttlMs: "by-response" };
}
if (method === "eth_getTransactionReceipt") {
return { cacheable: true, ttlMs: "by-response" };
}
if (NUMBER_KEYED_METHODS.has(method)) {
return blockTagPolicy(params[0], ctx, "stamped");
}
if (method in STATE_METHOD_TAG_INDEX) {
return blockTagPolicy(params[STATE_METHOD_TAG_INDEX[method]!], ctx);
}
if (method === "eth_getLogs") {
return logsPolicy(params, ctx);
}
if (method === "eth_feeHistory") {
return { cacheable: true, ttlMs: ctx.shortTtlMs };
}
if (SHORT_TTL_METHODS.has(method)) {
return { cacheable: true, ttlMs: ctx.shortTtlMs };
}
if (LONG_TTL_METHODS.has(method)) {
return { cacheable: true, ttlMs: LONG_TTL_MS };
}
// Unknown, write/stateful or admin/debug methods: fail safe, never cache.
return NOT_CACHEABLE;
}
/**
* Response-stage TTL for "by-response" policies.
* Returns the TTL in ms, null for no expiry, or false to skip storing.
*/
export function responseTtl(
method: string,
result: unknown,
ctx: CacheRuleContext,
): number | null | false {
if (method === "eth_getTransactionReceipt") {
if (result === null || result === undefined) return ctx.pendingTtlMs;
const blockHash = (result as Record<string, unknown>).blockHash;
return typeof blockHash === "string" && blockHash.length > 0
? null // mined: immutable
: ctx.pendingTtlMs;
}
// Hash-keyed lookups: real data is immutable; null may become available later.
if (result === null || result === undefined) return ctx.pendingTtlMs;
return null;
}