Skip to content

Commit f01474f

Browse files
frontendphilclaude
andauthored
perf(watcher): reuse the poll's chain data and proxy cache in every vault read (#49)
Each vault read asked the RPC again for the chain id, the head block and its timestamp, which the search of the poll had just read, and started with an empty cache of the Delay and Roles proxies. In production that was 3 to 5 of the 16 to 23 requests of each read, every minute. - The search hands its chain id, head and head timestamp to the reads of the vaults: one head for the whole poll. - The proxy cache belongs to the network watcher and lives across reads and polls. Proxy code does not change; "other" is still never cached. - A vault that a question of the bot read at a later block than the poll's head reads the head itself, so its state never goes back. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 27eee65 commit f01474f

4 files changed

Lines changed: 62 additions & 13 deletions

File tree

‎watcher/src/all.ts‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ import { BusyError, DryRunStore, FileStore, type Store } from './store.ts';
2323
import type { Email } from './email.ts';
2424
import type { Network, Telegram } from './telegram.ts';
2525
import { ConfigError, type FetchFn, type Log, errText } from './util.ts';
26-
import { Watcher, parseState } from './watcher.ts';
26+
import { type ChainNow, type ProxyKinds, Watcher, parseState } from './watcher.ts';
2727

2828
type Known = {
2929
delay: string;
@@ -117,6 +117,8 @@ export class AllWatcher {
117117
calls: PollCalls = { scan: {}, vaults: {}, read: 0 };
118118
private opts: AllOptions;
119119
private probe: Watcher;
120+
/** Shared by every read of this network, across polls: proxy code does not change. */
121+
private proxyKinds: ProxyKinds = new Map();
120122
private store: Store;
121123
private clock: () => number;
122124

@@ -126,7 +128,7 @@ export class AllWatcher {
126128
this.clock = opts.clock ?? Date.now;
127129
this.store = opts.store ?? (cfg.dryRun ? new DryRunStore(new FileStore(cfg.stateDir)) : new FileStore(cfg.stateDir));
128130
// Reads the chain only. It never loads or saves a state.
129-
this.probe = new Watcher({ ...cfg, dryRun: true }, { fetch: opts.fetch, log: opts.log });
131+
this.probe = new Watcher({ ...cfg, dryRun: true }, { fetch: opts.fetch, log: opts.log, proxyKinds: this.proxyKinds });
130132
this.log = this.probe.log;
131133
}
132134

@@ -287,24 +289,24 @@ export class AllWatcher {
287289
redact(msg: string): string { return this.probe.redact(msg); }
288290

289291
/** The watcher of one vault: the same code as for a single vault. */
290-
private watcherOf(vault: string, known: Known, rpcCounts?: RpcCounts): Watcher {
292+
private watcherOf(vault: string, known: Known, rpcCounts?: RpcCounts, chain?: ChainNow): Watcher {
291293
return new Watcher({ ...this.cfg, chronobox: vault, delay: known.delay }, {
292294
fetch: this.opts.fetch, telegram: this.opts.telegram, email: this.opts.email, store: this.store, key: vault, where: `The state of ${vault}`,
293-
log: (m) => this.log(`${vault.slice(0, 10)}: ${m}`), rpcCounts,
295+
log: (m) => this.log(`${vault.slice(0, 10)}: ${m}`), rpcCounts, chain, proxyKinds: this.proxyKinds,
294296
});
295297
}
296298

297299
/**
298300
* Reads one vault and sends its alerts. False if the chain could not be read. Null if a question of the bot reads
299301
* this vault right now: that read sends its alerts, and this poll goes on with the next vault.
300302
*/
301-
private async look(vault: string, known: Known, calls: PollCalls): Promise<boolean | null> {
303+
private async look(vault: string, known: Known, calls: PollCalls, chain: ChainNow | undefined): Promise<boolean | null> {
302304
// Saved before the read: if the function is killed during it, this vault goes to the back of the line, and it
303305
// cannot block every poll after this one.
304306
known.lookedAt = this.clock();
305307
delete known.waitingSince;
306308
await this.save();
307-
const w = this.watcherOf(vault, known, calls.vaults);
309+
const w = this.watcherOf(vault, known, calls.vaults, chain);
308310
let ok: boolean;
309311
try {
310312
ok = await this.store.lock(`vault:${vault}`, () => { calls.read++; return w.poll(); }, { waitMs: 0 });
@@ -324,7 +326,7 @@ export class AllWatcher {
324326
* and the queue is saved with the new lastBlock before any of them is checked: a search is never done twice, also
325327
* when the function is killed afterwards. Returns the vaults to look at now.
326328
*/
327-
private async scan(probe: Watcher): Promise<{ chainId: number; now: number; touched: Set<string> }> {
329+
private async scan(probe: Watcher): Promise<{ chain: ChainNow; now: number; touched: Set<string> }> {
328330
const s = this.state;
329331
const rpc = probe.rpc;
330332
const chainId = Number(await rpc.call('eth_chainId'));
@@ -377,7 +379,7 @@ export class AllWatcher {
377379
s.chainId = chainId;
378380
s.lastBlock = to;
379381
this.announce();
380-
return { chainId, now, touched };
382+
return { chain: { chainId, head, timestamp: BigInt(block.timestamp) }, now, touched };
381383
}
382384

383385
/**
@@ -441,10 +443,13 @@ export class AllWatcher {
441443
// Counted apart from the bot's questions, which use this.probe at the same time.
442444
const calls: PollCalls = { scan: {}, vaults: {}, read: 0 };
443445
this.calls = calls;
444-
const probe = new Watcher({ ...this.cfg, dryRun: true }, { fetch: this.opts.fetch, log: this.opts.log, rpcCounts: calls.scan });
446+
const probe = new Watcher({ ...this.cfg, dryRun: true }, { fetch: this.opts.fetch, log: this.opts.log, rpcCounts: calls.scan, proxyKinds: this.proxyKinds });
447+
// What the search read of the chain. The reads of the vaults use it: one head for the whole poll.
448+
let chain: ChainNow | undefined;
445449
try {
446450
const r = await this.scan(probe);
447451
now = r.now;
452+
chain = r.chain;
448453
for (const vault of r.touched) s.vaults[vault].active = true;
449454
await this.save();
450455
} catch (e) {
@@ -485,7 +490,7 @@ export class AllWatcher {
485490
// answers anything. Its readers are told (Watcher), and it waits longer each time, while the chain can be read.
486491
let read: boolean | null = false;
487492
try {
488-
read = await this.look(vault, known, calls);
493+
read = await this.look(vault, known, calls, chain);
489494
} catch (e) {
490495
this.log(`${vault}: ${errText(e)}`);
491496
}

‎watcher/src/watcher.ts‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -132,16 +132,26 @@ export type WatcherOptions = {
132132
where?: string;
133133
/** Counts the requests to the RPC here. */
134134
rpcCounts?: RpcCounts;
135+
/** The chain as the poll of the network read it a moment ago. Then a read does not ask for it again. */
136+
chain?: ChainNow;
137+
/** Which addresses are proxies of the Delay or of Roles, kept by the caller across reads. Proxy code does not change. */
138+
proxyKinds?: ProxyKinds;
135139
};
136140

141+
/** The network and its head block, with the time of that block. */
142+
export type ChainNow = { chainId: number; head: number; timestamp: bigint };
143+
144+
export type ProxyKinds = Map<string, 'delay' | 'roles'>;
145+
137146
export class Watcher {
138147
cfg: Config;
139148
rpc: Rpc;
140149
state: State = emptyState();
141150
log: Log;
142151
fetchFn: FetchFn;
143152
private blockTs = new Map<number, bigint>();
144-
private proxyKinds = new Map<string, 'delay' | 'roles'>();
153+
private proxyKinds: ProxyKinds;
154+
private chain?: ChainNow;
145155
private telegram?: Telegram;
146156
private email?: Email;
147157
private store: Store;
@@ -154,6 +164,8 @@ export class Watcher {
154164
this.telegram = opts.telegram;
155165
this.email = opts.email;
156166
this.fetchFn = opts.fetch ?? fetch;
167+
this.proxyKinds = opts.proxyKinds ?? new Map();
168+
this.chain = opts.chain;
157169
this.rpc = new Rpc(cfg.rpcUrls, this.fetchFn, 20000,
158170
cfg.rpcServiceKey ? { host: cfg.rpcServiceHost, key: cfg.rpcServiceKey } : undefined, opts.rpcCounts);
159171
const out = opts.log ?? defaultLog;
@@ -470,11 +482,15 @@ export class Watcher {
470482
private async observe(): Promise<void> {
471483
this.blockTs.clear();
472484
const s = this.state;
473-
const chainId = Number(await this.rpc.call('eth_chainId'));
485+
// The head that the poll of the network read, unless this vault was read at a later block since (a question of the
486+
// bot can read it during the poll): its state must never go back to an older block.
487+
const polled = this.chain && (s.lastBlock === undefined || this.chain.head >= s.lastBlock) ? this.chain : undefined;
488+
const chainId = polled ? polled.chainId : Number(await this.rpc.call('eth_chainId'));
474489
if (s.chainId !== undefined && s.chainId !== chainId) {
475490
throw new ConfigError(`The RPC is on chain ${chainId}, but this watcher watches chain ${s.chainId}. Check RPC_URL.`);
476491
}
477-
const head = Number(await this.rpc.call('eth_blockNumber'));
492+
const head = polled ? polled.head : Number(await this.rpc.call('eth_blockNumber'));
493+
if (polled) this.blockTs.set(head, polled.timestamp);
478494
const now = await this.timestampOf(head);
479495
const tag = hex(head);
480496
const delay = s.delay ?? (await this.resolveDelay(tag));

‎watcher/test/service.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,9 @@ test('a poll counts its requests to the RPC: the search apart from the reads of
149149
assert.equal(calls.read, 1, 'the vault with the new request is read');
150150
assert.ok(calls.scan > 0 && calls.vaults > 0, JSON.stringify(calls));
151151
assert.equal(calls.scan + calls.vaults, rpcSeen.length, 'every request the RPC got is counted, once');
152+
// The read of the vault takes the network and the head from the search of the poll.
153+
assert.equal(rpcSeen.filter((m) => m === 'eth_chainId').length, 1);
154+
assert.equal(rpcSeen.filter((m) => m === 'eth_blockNumber').length, 1);
152155
const line = logs.find((l) => l.includes(': rpc: '));
153156
assert.ok(line, logs.join('\n'));
154157
assert.match(line, new RegExp(`: rpc: ${rpcSeen.length} requests \\(search ${calls.scan}, 1 Chronobox read ${calls.vaults}\\): `));

‎watcher/test/watcher.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,31 @@ test('first start reports Watching and treats queued items as known', async () =
147147
assert.deepEqual(hooks().map((h) => h.json.event), ['ready']);
148148
});
149149

150+
test('a read with the head of the poll does not ask for the chain again, and never goes back to an older block', async () => {
151+
chain.enqueue(OWNER_WALLET, ONE_HALF_ETH);
152+
await watcher().poll();
153+
chain.mine(120n);
154+
const method = (m: string) => chain.calls.filter((c) => c === m).length;
155+
156+
// The head that the poll of the network read: the read takes it, and the time of its block.
157+
chain.calls.length = 0;
158+
const fresh = new Watcher(config(), { log: (m) => logs.push(m), chain: { chainId: 1, head: chain.head, timestamp: chain.now() } });
159+
assert.equal(await fresh.poll(), true);
160+
assert.equal(method('eth_chainId'), 0);
161+
assert.equal(method('eth_blockNumber'), 0);
162+
assert.equal(method('eth_getBlockByNumber'), 0);
163+
assert.equal(fresh.state.lastBlock, chain.head);
164+
165+
// A head from before the last read of this vault (a question of the bot read it during the poll): read again.
166+
const last = chain.head;
167+
chain.mine(120n);
168+
chain.calls.length = 0;
169+
const stale = new Watcher(config(), { log: (m) => logs.push(m), chain: { chainId: 1, head: last - 5, timestamp: chain.ts(last - 5) } });
170+
assert.equal(await stale.poll(), true);
171+
assert.equal(method('eth_blockNumber'), 1);
172+
assert.equal(stale.state.lastBlock, chain.head, 'read at the head of now, not at the older one');
173+
});
174+
150175
test('a queued native withdrawal produces one Queued alert, then Ready once', async () => {
151176
const w = watcher();
152177
await w.poll();

0 commit comments

Comments
 (0)