Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 40 additions & 15 deletions watcher/src/all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
// work at the same time, in different places.
import {
MASTER_COPY, MODULE_PROXY_FACTORY, RevertError, TOPIC_DISABLED_MODULE, TOPIC_ENABLED_MODULE, TOPIC_MODULE_PROXY_CREATION, TOPIC_TRANSACTION_ADDED,
encAddr, hex, strip, toAddr,
type RpcCounts, callsByMethod, encAddr, hex, strip, toAddr, totalCalls,
} from './chain.ts';
import { predictRecoveryDelay } from './guardian.ts';
import type { Config } from './config.ts';
Expand Down Expand Up @@ -84,6 +84,14 @@ export type PollReport = {
failing: number;
};

/** The requests to the RPC in the last poll: for the search and the new Delays, and for the reads of the vaults. */
export type PollCalls = {
scan: RpcCounts;
vaults: RpcCounts;
/** Vaults that the poll read. */
read: number;
};

export type PollOptions = {
/** A time (ms since 1970). After it, the poll reads no further vault. They are read on the next poll. */
deadline?: number;
Expand All @@ -105,6 +113,8 @@ export class AllWatcher {
log: Log;
/** Set by each poll. */
report: PollReport = { late: 0, overdueSeconds: 0, queued: 0, failing: 0 };
/** Set by each poll. A question of the bot that reads a vault is not in it. */
calls: PollCalls = { scan: {}, vaults: {}, read: 0 };
private opts: AllOptions;
private probe: Watcher;
private store: Store;
Expand Down Expand Up @@ -277,27 +287,27 @@ export class AllWatcher {
redact(msg: string): string { return this.probe.redact(msg); }

/** The watcher of one vault: the same code as for a single vault. */
private watcherOf(vault: string, known: Known): Watcher {
private watcherOf(vault: string, known: Known, rpcCounts?: RpcCounts): Watcher {
return new Watcher({ ...this.cfg, chronobox: vault, delay: known.delay }, {
fetch: this.opts.fetch, telegram: this.opts.telegram, email: this.opts.email, store: this.store, key: vault, where: `The state of ${vault}`,
log: (m) => this.log(`${vault.slice(0, 10)}: ${m}`),
log: (m) => this.log(`${vault.slice(0, 10)}: ${m}`), rpcCounts,
});
}

/**
* Reads one vault and sends its alerts. False if the chain could not be read. Null if a question of the bot reads
* this vault right now: that read sends its alerts, and this poll goes on with the next vault.
*/
private async look(vault: string, known: Known): Promise<boolean | null> {
private async look(vault: string, known: Known, calls: PollCalls): Promise<boolean | null> {
// Saved before the read: if the function is killed during it, this vault goes to the back of the line, and it
// cannot block every poll after this one.
known.lookedAt = this.clock();
delete known.waitingSince;
await this.save();
const w = this.watcherOf(vault, known);
const w = this.watcherOf(vault, known, calls.vaults);
let ok: boolean;
try {
ok = await this.store.lock(`vault:${vault}`, () => w.poll(), { waitMs: 0 });
ok = await this.store.lock(`vault:${vault}`, () => { calls.read++; return w.poll(); }, { waitMs: 0 });
} catch (e) {
if (e instanceof BusyError) return null;
throw e;
Expand All @@ -314,9 +324,9 @@ export class AllWatcher {
* and the queue is saved with the new lastBlock before any of them is checked: a search is never done twice, also
* when the function is killed afterwards. Returns the vaults to look at now.
*/
private async scan(): Promise<{ chainId: number; now: number; touched: Set<string> }> {
private async scan(probe: Watcher): Promise<{ chainId: number; now: number; touched: Set<string> }> {
const s = this.state;
const rpc = this.probe.rpc;
const rpc = probe.rpc;
const chainId = Number(await rpc.call('eth_chainId'));
if (this.cfg.chainId !== undefined && chainId !== this.cfg.chainId) {
throw new ConfigError(`The RPC of chain ${this.cfg.chainId} is on chain ${chainId}. Check RPC_URL_${this.cfg.chainId}.`);
Expand All @@ -341,7 +351,7 @@ export class AllWatcher {
for (const vault of Object.keys(s.vaults)) watched.set(predictRecoveryDelay(vault), vault);
const all = [...watched.keys()];
for (let i = 0; i < all.length; i += ADDRESSES_PER_QUERY) {
for (const l of await this.probe.getLogs(from, to, [[TOPIC_TRANSACTION_ADDED, TOPIC_ENABLED_MODULE, TOPIC_DISABLED_MODULE]], all.slice(i, i + ADDRESSES_PER_QUERY))) {
for (const l of await probe.getLogs(from, to, [[TOPIC_TRANSACTION_ADDED, TOPIC_ENABLED_MODULE, TOPIC_DISABLED_MODULE]], all.slice(i, i + ADDRESSES_PER_QUERY))) {
const vault = watched.get(String(l.address).toLowerCase());
if (vault) touched.add(vault);
}
Expand All @@ -350,7 +360,7 @@ export class AllWatcher {
const queue = s.queue ?? [];
const waiting = new Set(queue);
let dropped = 0;
const created = await this.probe.getLogs(from, to, [TOPIC_MODULE_PROXY_CREATION, null, '0x' + encAddr(MASTER_COPY.delay)], MODULE_PROXY_FACTORY);
const created = await probe.getLogs(from, to, [TOPIC_MODULE_PROXY_CREATION, null, '0x' + encAddr(MASTER_COPY.delay)], MODULE_PROXY_FACTORY);
for (const l of created) {
if (String(l.address).toLowerCase() !== MODULE_PROXY_FACTORY || toAddr(strip(l.topics[2] ?? '')) !== MASTER_COPY.delay) continue;
const delay = toAddr(strip(l.topics[1]));
Expand All @@ -376,7 +386,7 @@ export class AllWatcher {
* chain could be read in this poll: then a check that fails is a problem of that Delay (anybody can deploy a Delay
* whose Safe answers anything). It goes to the back of the queue, and after CHECK_TRIES it is dropped.
*/
private async check(deadline: number | undefined): Promise<number> {
private async check(probe: Watcher, deadline: number | undefined): Promise<number> {
const s = this.state;
let found = 0;
let turns = (s.queue ?? []).length;
Expand All @@ -386,7 +396,7 @@ export class AllWatcher {
first = false;
const batch = s.queue!.slice(0, Math.min(CHECK_PARALLEL, turns));
turns -= batch.length;
const results = await Promise.allSettled(batch.map((delay) => this.probe.chronoboxOf(delay, 'latest')));
const results = await Promise.allSettled(batch.map((delay) => probe.chronoboxOf(delay, 'latest')));
const again: string[] = [];
results.forEach((r, i) => {
const delay = batch[i];
Expand Down Expand Up @@ -428,8 +438,12 @@ export class AllWatcher {
const s = this.state;
let ok = true;
let now = Math.floor(Date.now() / 1000);
// Counted apart from the bot's questions, which use this.probe at the same time.
const calls: PollCalls = { scan: {}, vaults: {}, read: 0 };
this.calls = calls;
const probe = new Watcher({ ...this.cfg, dryRun: true }, { fetch: this.opts.fetch, log: this.opts.log, rpcCounts: calls.scan });
try {
const r = await this.scan();
const r = await this.scan(probe);
now = r.now;
for (const vault of r.touched) s.vaults[vault].active = true;
await this.save();
Expand All @@ -444,7 +458,7 @@ export class AllWatcher {
// batch always), so that a flood of Delays cannot take the time of the Chronoboxes that are known.
const started = this.clock();
// Only when the chain could be read: else a failed check says nothing about the Delay.
if (ok) await this.check(opts.deadline === undefined ? undefined : started + Math.max(0, opts.deadline - started) / 4);
if (ok) await this.check(probe, opts.deadline === undefined ? undefined : started + Math.max(0, opts.deadline - started) / 4);
await this.opts.telegram?.ready();
const beat = this.cfg.heartbeatHours * 3600;
const chainId = s.chainId;
Expand All @@ -471,7 +485,7 @@ export class AllWatcher {
// answers anything. Its readers are told (Watcher), and it waits longer each time, while the chain can be read.
let read: boolean | null = false;
try {
read = await this.look(vault, known);
read = await this.look(vault, known, calls);
} catch (e) {
this.log(`${vault}: ${errText(e)}`);
}
Expand All @@ -491,10 +505,21 @@ export class AllWatcher {
if (failing) this.log(`${failing} Chronobox${failing === 1 ? '' : 'es'} could not be read`);
if (late) this.log(`out of time: ${late} Chronobox${late === 1 ? '' : 'es'} will be read on the next poll (the oldest waits ${this.report.overdueSeconds}s)`);
this.report.queued = (s.queue ?? []).length;
this.logCalls(calls);
await this.save();
// Stops that the other followers were not told of yet, because one was told in the last hour.
await this.opts.telegram?.sendNotices().catch((e) => this.log(`telegram: could not send the notices of stops: ${errText(e)}`));
await this.opts.email?.sendNotices().catch((e) => this.log(`email: could not send the notices of stops: ${errText(e)}`));
return ok;
}

/** One line per poll: how many requests went to the RPC, and for what. */
private logCalls(calls: PollCalls): void {
const scan = totalCalls(calls.scan);
const vaults = totalCalls(calls.vaults);
const by: RpcCounts = { ...calls.scan };
for (const [m, n] of Object.entries(calls.vaults)) by[m] = (by[m] ?? 0) + n;
this.log(`rpc: ${scan + vaults} requests (search ${scan}, ${calls.read} Chronobox${calls.read === 1 ? '' : 'es'} read ${vaults})` +
(scan + vaults ? `: ${callsByMethod(by)}` : ''));
}
}
16 changes: 15 additions & 1 deletion watcher/src/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,23 +229,37 @@ export class RevertError extends Error {}
*/
export class BadAnswerError extends RevertError {}

/** Requests sent to the RPC, by method. Each try counts, also one that failed and went on to the next endpoint. */
export type RpcCounts = Record<string, number>;

/** All requests in `counts`. */
export const totalCalls = (counts: RpcCounts) => Object.values(counts).reduce((a, b) => a + b, 0);

/** "eth_call 20, eth_getLogs 4": the methods, most requests first. */
export const callsByMethod = (counts: RpcCounts) =>
Object.entries(counts).sort(([a, x], [b, y]) => y - x || a.localeCompare(b)).map(([m, n]) => `${m} ${n}`).join(', ');

export class Rpc {
urls: string[];
idx = 0;
id = 0;
timeoutMs: number;
fetchFn: FetchFn;
auth?: RpcAuth;
constructor(urls: string[], fetchFn: FetchFn = fetch, timeoutMs = 20000, auth?: RpcAuth) {
/** Where the requests are counted, if anywhere. */
counts?: RpcCounts;
constructor(urls: string[], fetchFn: FetchFn = fetch, timeoutMs = 20000, auth?: RpcAuth, counts?: RpcCounts) {
this.urls = urls;
this.auth = auth;
this.fetchFn = fetchFn;
this.timeoutMs = timeoutMs;
this.counts = counts;
}
async call(method: string, params: unknown[] = []): Promise<any> {
let lastErr = 'no RPC configured';
for (let i = 0; i < this.urls.length; i++) {
const k = (this.idx + i) % this.urls.length;
if (this.counts) this.counts[method] = (this.counts[method] ?? 0) + 1;
try {
const res = await this.fetchFn(this.urls[k], {
method: 'POST',
Expand Down
6 changes: 5 additions & 1 deletion watcher/src/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
// them into Vercel functions.
import * as crypto from 'node:crypto';
import { AllWatcher } from './all.ts';
import { totalCalls } from './chain.ts';
import { type Config, parseConfig } from './config.ts';
import { DEFAULT_POLL_BUDGET_SECONDS, LOCK_TTL_MS } from './limits.ts';
import { EMAIL_PATH, Email, PAGE_HEADERS } from './email.ts';
Expand Down Expand Up @@ -192,6 +193,8 @@ export type NetworkResult = {
queued?: number;
/** Vaults that could not be read while the chain could. A problem of those vaults; their readers are told. */
failing?: number;
/** Requests to the RPC in this poll: for the search and the new Delays, and for the reads of the vaults. */
rpc?: { scan: number; vaults: number; read: number };
};

/** The note of the last poll, or null if there is none or it cannot be read. */
Expand Down Expand Up @@ -225,8 +228,9 @@ export async function poll(env: Env, req: Request, deps: Deps = {}): Promise<Rep
try {
const ok = await w.poll({ deadline });
const { late, overdueSeconds, queued, failing } = w.report;
const rpc = { scan: totalCalls(w.calls.scan), vaults: totalCalls(w.calls.vaults), read: w.calls.read };
const observedAt = new Date().toISOString();
return { chainId, ok, observedAt, ...(late ? { late, overdueSeconds } : {}), ...(queued ? { queued } : {}), ...(failing ? { failing } : {}) };
return { chainId, ok, observedAt, ...(late ? { late, overdueSeconds } : {}), ...(queued ? { queued } : {}), ...(failing ? { failing } : {}), rpc };
} catch (e) {
// The poll before this one still runs. It does this work. Until it ends, the time of the last poll that ended stays.
if (e instanceof BusyError) {
Expand Down
6 changes: 4 additions & 2 deletions watcher/src/watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// The CLI runs it for one vault. --all and the service run one for each vault that something waits in.
import * as path from 'node:path';
import {
BURN_ADDRESS, MASTER_COPY, RevertError, Rpc, SAFE_GUARD_SLOT, SENTINEL, SEL, TOPIC_SAFE_MODULE_TRANSACTION, TOPIC_TRANSACTION_ADDED,
BURN_ADDRESS, MASTER_COPY, RevertError, Rpc, type RpcCounts, SAFE_GUARD_SLOT, SENTINEL, SEL, TOPIC_SAFE_MODULE_TRANSACTION, TOPIC_TRANSACTION_ADDED,
TOPIC_MODULE_FAILURE, TOPIC_MODULE_SUCCESS, ZERO_ADDRESS, addressWord, cleanSymbol, decodeAbiString, decodeAddressArray, decodeAddresses, decodeModuleTransaction, strip,
decodeAddress, decodeTransactionAdded, decodeUint, encAddr, encUint, hex, proxyCode, toAddr, toBig, word,
} from './chain.ts';
Expand Down Expand Up @@ -130,6 +130,8 @@ export type WatcherOptions = {
key?: string;
/** Names the state in an error message. */
where?: string;
/** Counts the requests to the RPC here. */
rpcCounts?: RpcCounts;
};

export class Watcher {
Expand All @@ -153,7 +155,7 @@ export class Watcher {
this.email = opts.email;
this.fetchFn = opts.fetch ?? fetch;
this.rpc = new Rpc(cfg.rpcUrls, this.fetchFn, 20000,
cfg.rpcServiceKey ? { host: cfg.rpcServiceHost, key: cfg.rpcServiceKey } : undefined);
cfg.rpcServiceKey ? { host: cfg.rpcServiceHost, key: cfg.rpcServiceKey } : undefined, opts.rpcCounts);
const out = opts.log ?? defaultLog;
this.log = (m: string) => out(this.redact(m));
this.store = opts.store ?? (cfg.dryRun ? new DryRunStore(stateFileStore(cfg.stateFile)) : stateFileStore(cfg.stateFile));
Expand Down
29 changes: 27 additions & 2 deletions watcher/test/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ const ONE_ETH = 10n ** 18n;

let chain: MockChain;
let rpcDelayMs = 0;
/** The methods of the requests that the RPC got. */
let rpcSeen: string[] = [];
let rpc: { url: string; close: () => Promise<void> };
let redis: FakeRedis;
let redisServer: { url: string; close: () => Promise<void> };
Expand All @@ -35,6 +37,7 @@ before(async () => {
rpc = await startServer(async (_req, body, res) => {
if (rpcDelayMs) await new Promise((r) => setTimeout(r, rpcDelayMs));
const msg = JSON.parse(body);
rpcSeen.push(msg.method);
res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ jsonrpc: '2.0', id: msg.id, ...handle(chain, msg.method, msg.params ?? []) }));
});
redis = new FakeRedis(REDIS_TOKEN);
Expand All @@ -60,6 +63,7 @@ after(async () => { await rpc.close(); await redisServer.close(); await tg.close
beforeEach(() => {
chain = new MockChain();
rpcDelayMs = 0;
rpcSeen = [];
redis.data.clear();
redis.commands = [];
said = [];
Expand Down Expand Up @@ -123,13 +127,34 @@ test('settings of the service', () => {
assert.throws(() => serviceConfig(env({ TELEGRAM_KEY: 'too-short' })), ConfigError);
});

/** The result of a network without the time of its last full poll, which only has to be there. */
/** The result of a network without the time of its last full poll and its count of RPC requests, which only have to be there. */
const net = (n: any) => {
const { observedAt, ...rest } = n;
const { observedAt, rpc: calls, ...rest } = n;
assert.ok(!Number.isNaN(Date.parse(observedAt)), `observedAt: ${observedAt}`);
if (n.ok && !n.skipped) for (const k of ['scan', 'vaults', 'read']) assert.ok(Number.isInteger(calls?.[k]), `rpc.${k}: ${calls?.[k]}`);
return rest;
};

test('a poll counts its requests to the RPC: the search apart from the reads of the vaults', async () => {
chain.withCancel();
await poll(env(), cron(), deps);
chain.create();
await poll(env(), cron(), deps);
chain.mine(12n);
chain.enqueue(OWNER_WALLET, ONE_ETH);
rpcSeen = [];
logs.length = 0;
const r = await poll(env(), cron(), deps);
const calls = (r.body as any).networks[0].rpc;
assert.equal(calls.read, 1, 'the vault with the new request is read');
assert.ok(calls.scan > 0 && calls.vaults > 0, JSON.stringify(calls));
assert.equal(calls.scan + calls.vaults, rpcSeen.length, 'every request the RPC got is counted, once');
const line = logs.find((l) => l.includes(': rpc: '));
assert.ok(line, logs.join('\n'));
assert.match(line, new RegExp(`: rpc: ${rpcSeen.length} requests \\(search ${calls.scan}, 1 Chronobox read ${calls.vaults}\\): `));
assert.match(line, new RegExp(`eth_call ${rpcSeen.filter((m) => m === 'eth_call').length}\\b`));
});

test('only Vercel Cron starts a poll', async () => {
assert.equal((await poll(env(), cron('wrong-secret-of-the-same-size'), deps)).status, 401);
assert.equal((await poll(env(), { method: 'GET', headers: {}, body: '' }, deps)).status, 401);
Expand Down
Loading