@defillama/sdk 5.0.244 → 5.0.245

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.
@@ -1,7 +1,12 @@
1
- export declare const ES_INDEX = "adapter-call-stats";
2
- export declare const DEFAULT_MIN_CALLS = 50;
3
- /** a chain bucket is also kept when it has at least this many getLogs requests, however few calls it made */
4
- export declare const DEFAULT_MIN_GET_LOGS = 10;
1
+ /** one doc per (run, chain) */
2
+ export declare const ES_INDEX = "adapter-calls";
3
+ /** one doc per (run, host) */
4
+ export declare const ES_HOST_INDEX = "adapter-call-hosts";
5
+ /** `chain` of the doc counting requests that matched no registered rpc endpoint */
6
+ export declare const OTHER_CHAIN = "_other";
7
+ /** runs with fewer http requests in total are not written at all (env CALL_STATS_MIN_CALLS) */
8
+ export declare const DEFAULT_MIN_CALLS = 1;
9
+ export declare const MAX_HOSTS_PER_RUN = 25;
5
10
  export type CallStatsMeta = {
6
11
  /** 'tvl' | 'dimensions' | ... */
7
12
  application: string;
@@ -24,8 +29,14 @@ export type CallStats = {
24
29
  * every LlamaProvider attempt (`call`, `getLogs`, `getBlock`, ...), starknet `getLogs`, and `indexerGetLogs`
25
30
  */
26
31
  byMethod: Record<string, Record<string, number>>;
32
+ /** log rows fetched over the wire: source ('rpc' | 'indexer') -> chain -> rows, recorded by the SDK (`recordLogs`) */
33
+ logs: Record<LogSource, Record<string, number>>;
34
+ /** set once the run's docs were written (by `run` settling, or earlier by `flushActive`) */
35
+ reported?: boolean;
27
36
  };
28
- export type CallStatsSnapshot = Pick<CallStats, 'total' | 'byChain' | 'byHost' | 'unattributed' | 'byMethod'>;
37
+ export type LogSource = 'rpc' | 'indexer';
38
+ export declare const INDEXER_METHOD = "indexer";
39
+ export type CallStatsSnapshot = Pick<CallStats, 'total' | 'byChain' | 'byHost' | 'unattributed' | 'byMethod'> & Partial<Pick<CallStats, 'logs'>>;
29
40
  /**
30
41
  * Remember that `endpoints` serve `chain`, so requests to them are counted against that chain.
31
42
  * Called by the SDK wherever it resolves rpc urls; adapters can call it for endpoints they manage themselves.
@@ -40,10 +51,12 @@ export declare function ignoreHost(url: string): void;
40
51
  * The http layer already counts the request itself; this adds the method breakdown (getLogs being the one that matters).
41
52
  */
42
53
  export declare function recordMethod(method: string, chain?: string): void;
54
+ /** Count `count` log rows fetched from `source` for `chain` in the current run (rows received, cached reads are not fetched). */
55
+ export declare function recordLogs(source: LogSource, chain: string | undefined, count: number): void;
43
56
  /** Patch the node http layer. Idempotent, shared across sdk copies. Called by `run`. */
44
57
  export declare function install(): void;
45
58
  export type RunOptions = {
46
- /** chain / host buckets below this are dropped, and nothing is written when the total is below it (default 50, env LLAMA_SDK_CALL_STATS_MIN_CALLS) */
59
+ /** nothing is written when the run made fewer http requests in total (default 1, env CALL_STATS_MIN_CALLS) */
47
60
  minCalls?: number;
48
61
  /** print the summary table to the console (always, not only in debug mode) */
49
62
  print?: boolean;
@@ -59,16 +72,52 @@ export declare function mergeSnapshots(snapshots: CallStatsSnapshot[]): CallStat
59
72
  * Nested calls get their own context; calls made by `fn` through any http client are attributed to it.
60
73
  */
61
74
  export declare function run<T>(meta: CallStatsMeta, fn: () => Promise<T>, options?: RunOptions): Promise<T>;
75
+ /**
76
+ * Write the docs of the runs still in flight (all of them, or those whose meta passes `filter`) as failed runs
77
+ * with `interrupted: reason`, and mark them so they are not written again when they eventually settle.
78
+ * For a process that is about to be killed, or a job the caller has given up on: without this the heaviest runs,
79
+ * the ones that hit the timeout, would be exactly the ones never recorded. Returns the number of runs written.
80
+ */
81
+ export declare function flushActive(reason: string, { filter, ...options }?: RunOptions & {
82
+ filter?: (meta: CallStatsMeta) => boolean;
83
+ }): Promise<number>;
62
84
  export declare function getMinCalls(minCalls?: number): number;
63
- /** Elasticsearch documents for a run: one `run` summary, one `chain` doc per chain and one `host` doc per unattributed host at or above `minCalls`. */
64
- export declare function buildDocs(stats: CallStatsSnapshot, meta: CallStatsMeta, { success, runtime, minCalls }?: {
85
+ export type ChainRow = {
86
+ chain: string;
87
+ /** http requests to a registered rpc of the chain (`_other`: requests matching no registered rpc, the indexer included) */
88
+ calls: number;
89
+ /** rpc getLogs attempts */
90
+ getLogs: number;
91
+ /** http requests to the llama indexer for this chain */
92
+ indexerCalls: number;
93
+ /** log rows fetched over the wire, by source and in total */
94
+ logs: number;
95
+ logsRpc: number;
96
+ logsIndexer: number;
97
+ methods: Record<string, number>;
98
+ };
99
+ export type HostRow = {
100
+ host: string;
101
+ calls: number;
102
+ rpc: boolean;
103
+ };
104
+ export type CallStatsDocs = {
105
+ chainDocs: any[];
106
+ hostDocs: any[];
107
+ };
108
+ /**
109
+ * Elasticsearch documents for a run: `chainDocs` for `adapter-calls` (one per chain) and `hostDocs` for
110
+ * `adapter-call-hosts` (one per host). Every doc carries the run meta, totals and the same `runId`, so
111
+ * run-level questions are a `runId` grouping of the same index. Empty when the run is under `minCalls`.
112
+ */
113
+ export type ReportOptions = {
65
114
  success?: boolean;
66
115
  runtime?: number;
67
- minCalls?: number;
68
- }): any[];
116
+ minCalls?: number; /** why the run was written before it settled ('timeout', 'shutdown'...) */
117
+ interrupted?: string;
118
+ };
119
+ export declare function buildDocs(stats: CallStatsSnapshot, meta: CallStatsMeta, { success, runtime, minCalls, interrupted }?: ReportOptions): CallStatsDocs;
69
120
  /** Write the docs for `stats` to elasticsearch (no-op when ELASTICSEARCH_CONFIG is unset) and print the summary in debug mode. */
70
- export declare function report(stats: CallStats | CallStatsSnapshot, { success, runtime, minCalls, print, skipElastic, meta }?: RunOptions & {
71
- success?: boolean;
72
- runtime?: number;
121
+ export declare function report(stats: CallStats | CallStatsSnapshot, { success, runtime, minCalls, interrupted, print, skipElastic, meta }?: RunOptions & ReportOptions & {
73
122
  meta?: CallStatsMeta;
74
123
  }): Promise<void>;
@@ -4,16 +4,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  var _a;
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.DEFAULT_MIN_GET_LOGS = exports.DEFAULT_MIN_CALLS = exports.ES_INDEX = void 0;
7
+ exports.INDEXER_METHOD = exports.MAX_HOSTS_PER_RUN = exports.DEFAULT_MIN_CALLS = exports.OTHER_CHAIN = exports.ES_HOST_INDEX = exports.ES_INDEX = void 0;
8
8
  exports.registerEndpoints = registerEndpoints;
9
9
  exports.resolveChain = resolveChain;
10
10
  exports.ignoreHost = ignoreHost;
11
11
  exports.recordMethod = recordMethod;
12
+ exports.recordLogs = recordLogs;
12
13
  exports.install = install;
13
14
  exports.getCurrent = getCurrent;
14
15
  exports.snapshot = snapshot;
15
16
  exports.mergeSnapshots = mergeSnapshots;
16
17
  exports.run = run;
18
+ exports.flushActive = flushActive;
17
19
  exports.getMinCalls = getMinCalls;
18
20
  exports.buildDocs = buildDocs;
19
21
  exports.report = report;
@@ -21,6 +23,17 @@ exports.report = report;
21
23
  * Per-run counters for every outbound HTTP request a process makes, attributed to a chain
22
24
  * and to the adapter run that made them, and flushed to Elasticsearch when the run ends.
23
25
  *
26
+ * What gets written (see `buildDocs`)
27
+ * - `adapter-calls`: one flat doc per (run, chain) carrying the run's meta (application, name, runType...),
28
+ * `chain`, `calls` (rpc http requests), `getLogs` (rpc getLogs attempts), `indexerCalls` (http requests to
29
+ * the llama indexer for that chain), `logs` / `logsRpc` / `logsIndexer` (log rows fetched over the wire),
30
+ * `methods.*`, the run totals (`runCalls`, `runGetLogs`, `runLogs`), `success`, `runtime` and a shared
31
+ * `runId`. Requests matching no registered rpc go to `chain: "_other"`. Nothing is dropped, so a terms
32
+ * aggregation on `chain` or `name` over any time range is exact.
33
+ * - `adapter-call-hosts`: one doc per (run, host) for the 25 busiest hosts of the run, same base fields
34
+ * plus `host` and `rpc` (true when the host is a registered rpc endpoint).
35
+ * Both carry `@timestamp` (ISO) so Kibana picks it up as the time field with no index template.
36
+ *
24
37
  * How it works
25
38
  * - `install()` wraps `http.request` / `http.get` / `https.request` / `https.get` and subscribes to
26
39
  * the `undici:request:create` diagnostics channel (global `fetch`). That catches axios, ethers,
@@ -36,19 +49,26 @@ exports.report = report;
36
49
  * registry and one context, and nothing is counted twice.
37
50
  */
38
51
  const async_hooks_1 = require("async_hooks");
52
+ const crypto_1 = __importDefault(require("crypto"));
39
53
  const http_1 = __importDefault(require("http"));
40
54
  const https_1 = __importDefault(require("https"));
41
55
  const diagnostics_channel_1 = __importDefault(require("diagnostics_channel"));
42
56
  const elastic_1 = require("./elastic");
43
57
  const debugLog_1 = require("./debugLog");
44
58
  const env_1 = require("./env");
45
- exports.ES_INDEX = 'adapter-call-stats';
46
- exports.DEFAULT_MIN_CALLS = 50;
47
- /** a chain bucket is also kept when it has at least this many getLogs requests, however few calls it made */
48
- exports.DEFAULT_MIN_GET_LOGS = 10;
59
+ /** one doc per (run, chain) */
60
+ exports.ES_INDEX = 'adapter-calls';
61
+ /** one doc per (run, host) */
62
+ exports.ES_HOST_INDEX = 'adapter-call-hosts';
63
+ /** `chain` of the doc counting requests that matched no registered rpc endpoint */
64
+ exports.OTHER_CHAIN = '_other';
65
+ /** runs with fewer http requests in total are not written at all (env CALL_STATS_MIN_CALLS) */
66
+ exports.DEFAULT_MIN_CALLS = 1;
67
+ exports.MAX_HOSTS_PER_RUN = 25;
68
+ exports.INDEXER_METHOD = 'indexer';
49
69
  const STATE_KEY = Symbol.for('@defillama/sdk/callStats');
50
70
  function newStats(meta) {
51
- return { meta, startTime: Date.now(), total: 0, byChain: {}, byHost: {}, unattributed: 0, byMethod: {} };
71
+ return { meta, startTime: Date.now(), total: 0, byChain: {}, byHost: {}, unattributed: 0, byMethod: {}, logs: { rpc: {}, indexer: {} } };
52
72
  }
53
73
  const shared = (_a = globalThis[STATE_KEY]) !== null && _a !== void 0 ? _a : (globalThis[STATE_KEY] = {
54
74
  als: new async_hooks_1.AsyncLocalStorage(),
@@ -57,7 +77,11 @@ const shared = (_a = globalThis[STATE_KEY]) !== null && _a !== void 0 ? _a : (gl
57
77
  global: newStats({ application: 'global', name: '-' }),
58
78
  ignoredHosts: new Set(),
59
79
  registered: new Set(),
80
+ active: new Set(),
60
81
  });
82
+ // the state may have been created by an older sdk copy that did not track active runs
83
+ if (!shared.active)
84
+ shared.active = new Set();
61
85
  // ---------------------------------------------------------------------------
62
86
  // endpoint registry
63
87
  // ---------------------------------------------------------------------------
@@ -141,19 +165,39 @@ function record(url) {
141
165
  * Count a logical rpc request (one attempt, so retries count) against `method` and `chain` in the current run.
142
166
  * The http layer already counts the request itself; this adds the method breakdown (getLogs being the one that matters).
143
167
  */
144
- function recordMethod(method, chain = 'unknown') {
168
+ function recordMethod(method, chain = exports.OTHER_CHAIN) {
145
169
  var _a, _b, _c;
146
170
  const stats = (_a = shared.als.getStore()) !== null && _a !== void 0 ? _a : shared.global;
147
171
  const byChain = (_b = stats.byMethod[method]) !== null && _b !== void 0 ? _b : (stats.byMethod[method] = {});
148
172
  chain = chain.toLowerCase();
149
173
  byChain[chain] = ((_c = byChain[chain]) !== null && _c !== void 0 ? _c : 0) + 1;
150
174
  }
175
+ /** Count `count` log rows fetched from `source` for `chain` in the current run (rows received, cached reads are not fetched). */
176
+ function recordLogs(source, chain = exports.OTHER_CHAIN, count) {
177
+ var _a, _b, _c;
178
+ if (!(count > 0))
179
+ return;
180
+ const stats = (_a = shared.als.getStore()) !== null && _a !== void 0 ? _a : shared.global;
181
+ const byChain = (_b = stats.logs[source]) !== null && _b !== void 0 ? _b : (stats.logs[source] = {});
182
+ chain = chain.toLowerCase();
183
+ byChain[chain] = ((_c = byChain[chain]) !== null && _c !== void 0 ? _c : 0) + count;
184
+ }
185
+ function sumValues(map) {
186
+ return Object.values(map !== null && map !== void 0 ? map : {}).reduce((a, b) => a + b, 0);
187
+ }
151
188
  function getLogsCount(stats, chain) {
152
189
  var _a, _b, _c;
153
190
  const byChain = (_b = (_a = stats.byMethod) === null || _a === void 0 ? void 0 : _a.getLogs) !== null && _b !== void 0 ? _b : {};
154
191
  if (chain)
155
192
  return (_c = byChain[chain]) !== null && _c !== void 0 ? _c : 0;
156
- return Object.values(byChain).reduce((a, b) => a + b, 0);
193
+ return sumValues(byChain);
194
+ }
195
+ function logsFetched(stats, source, chain) {
196
+ var _a, _b, _c;
197
+ const byChain = (_b = (_a = stats.logs) === null || _a === void 0 ? void 0 : _a[source]) !== null && _b !== void 0 ? _b : {};
198
+ if (chain)
199
+ return (_c = byChain[chain]) !== null && _c !== void 0 ? _c : 0;
200
+ return sumValues(byChain);
157
201
  }
158
202
  /** method -> requests across chains */
159
203
  function methodTotals(stats) {
@@ -252,15 +296,29 @@ function getCurrent() {
252
296
  var _a;
253
297
  return (_a = shared.als.getStore()) !== null && _a !== void 0 ? _a : shared.global;
254
298
  }
299
+ function copyNested(map) {
300
+ const out = {};
301
+ for (const [key, byChain] of Object.entries(map !== null && map !== void 0 ? map : {}))
302
+ out[key] = { ...byChain };
303
+ return out;
304
+ }
305
+ function addNested(target, source) {
306
+ var _a, _b;
307
+ for (const [key, byChain] of Object.entries(source !== null && source !== void 0 ? source : {})) {
308
+ const into = (_a = target[key]) !== null && _a !== void 0 ? _a : (target[key] = {});
309
+ for (const [k, v] of Object.entries(byChain))
310
+ into[k] = ((_b = into[k]) !== null && _b !== void 0 ? _b : 0) + v;
311
+ }
312
+ }
255
313
  function snapshot(stats = getCurrent()) {
256
- const byMethod = {};
257
- for (const [method, byChain] of Object.entries(stats.byMethod))
258
- byMethod[method] = { ...byChain };
259
- return { total: stats.total, byChain: { ...stats.byChain }, byHost: { ...stats.byHost }, unattributed: stats.unattributed, byMethod };
314
+ return {
315
+ total: stats.total, byChain: { ...stats.byChain }, byHost: { ...stats.byHost }, unattributed: stats.unattributed,
316
+ byMethod: copyNested(stats.byMethod), logs: copyNested(stats.logs),
317
+ };
260
318
  }
261
319
  function mergeSnapshots(snapshots) {
262
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
263
- const out = { total: 0, byChain: {}, byHost: {}, unattributed: 0, byMethod: {} };
320
+ var _a, _b, _c, _d, _e, _f;
321
+ const out = { total: 0, byChain: {}, byHost: {}, unattributed: 0, byMethod: {}, logs: { rpc: {}, indexer: {} } };
264
322
  for (const s of snapshots) {
265
323
  if (!s)
266
324
  continue;
@@ -270,11 +328,8 @@ function mergeSnapshots(snapshots) {
270
328
  out.byChain[k] = ((_d = out.byChain[k]) !== null && _d !== void 0 ? _d : 0) + v;
271
329
  for (const [k, v] of Object.entries((_e = s.byHost) !== null && _e !== void 0 ? _e : {}))
272
330
  out.byHost[k] = ((_f = out.byHost[k]) !== null && _f !== void 0 ? _f : 0) + v;
273
- for (const [method, byChain] of Object.entries((_g = s.byMethod) !== null && _g !== void 0 ? _g : {})) {
274
- const target = (_h = out.byMethod[method]) !== null && _h !== void 0 ? _h : (out.byMethod[method] = {});
275
- for (const [k, v] of Object.entries(byChain))
276
- target[k] = ((_j = target[k]) !== null && _j !== void 0 ? _j : 0) + v;
277
- }
331
+ addNested(out.byMethod, s.byMethod);
332
+ addNested(out.logs, s.logs);
278
333
  }
279
334
  return out;
280
335
  }
@@ -285,6 +340,7 @@ function mergeSnapshots(snapshots) {
285
340
  async function run(meta, fn, options = {}) {
286
341
  install();
287
342
  const stats = newStats(meta);
343
+ shared.active.add(stats);
288
344
  return shared.als.run(stats, async () => {
289
345
  let success = false;
290
346
  try {
@@ -293,92 +349,136 @@ async function run(meta, fn, options = {}) {
293
349
  return result;
294
350
  }
295
351
  finally {
296
- try {
297
- await report(stats, { success, runtime: (Date.now() - stats.startTime) / 1000, ...options });
298
- }
299
- catch (e) {
300
- (0, debugLog_1.debugLog)('[callStats] failed to report', e === null || e === void 0 ? void 0 : e.message);
352
+ shared.active.delete(stats);
353
+ // already written by flushActive: the run was given up on (timeout / shutdown), its outcome no longer counts
354
+ if (!stats.reported) {
355
+ stats.reported = true;
356
+ try {
357
+ await report(stats, { success, runtime: (Date.now() - stats.startTime) / 1000, ...options });
358
+ }
359
+ catch (e) {
360
+ (0, debugLog_1.debugLog)('[callStats] failed to report', e === null || e === void 0 ? void 0 : e.message);
361
+ }
301
362
  }
302
363
  }
303
364
  });
304
365
  }
366
+ /**
367
+ * Write the docs of the runs still in flight (all of them, or those whose meta passes `filter`) as failed runs
368
+ * with `interrupted: reason`, and mark them so they are not written again when they eventually settle.
369
+ * For a process that is about to be killed, or a job the caller has given up on: without this the heaviest runs,
370
+ * the ones that hit the timeout, would be exactly the ones never recorded. Returns the number of runs written.
371
+ */
372
+ async function flushActive(reason, { filter, ...options } = {}) {
373
+ const runs = [...shared.active].filter(stats => !stats.reported && (!filter || filter(stats.meta)));
374
+ for (const stats of runs)
375
+ stats.reported = true;
376
+ await Promise.all(runs.map(stats => report(stats, { success: false, interrupted: reason, runtime: (Date.now() - stats.startTime) / 1000, ...options })
377
+ .catch(e => (0, debugLog_1.debugLog)('[callStats] failed to flush', e === null || e === void 0 ? void 0 : e.message))));
378
+ return runs.length;
379
+ }
305
380
  // ---------------------------------------------------------------------------
306
381
  // reporting
307
382
  // ---------------------------------------------------------------------------
308
- function sortedEntries(map, minCalls, limit) {
309
- const entries = Object.entries(map).filter(([, calls]) => calls >= minCalls).map(([key, calls]) => ({ key, calls }));
310
- entries.sort((a, b) => b.calls - a.calls);
311
- return limit ? entries.slice(0, limit) : entries;
312
- }
313
383
  function getMinCalls(minCalls) {
314
384
  if (minCalls !== undefined)
315
385
  return minCalls;
316
386
  return +(0, env_1.getEnvValue)('CALL_STATS_MIN_CALLS', String(exports.DEFAULT_MIN_CALLS));
317
387
  }
318
- function getMinGetLogs() {
319
- return +(0, env_1.getEnvValue)('CALL_STATS_MIN_GET_LOGS', String(exports.DEFAULT_MIN_GET_LOGS));
320
- }
321
388
  /**
322
- * Chains worth a row: at least `minCalls` http requests, or at least `minGetLogs` getLogs requests
323
- * (a chain that makes 20 getLogs calls is heavier than one making 50 eth_calls). Most calls first.
389
+ * One row per chain that made an http request, had an rpc method recorded or had logs fetched, plus `_other`
390
+ * for requests matching no registered rpc. Most calls first. Nothing is thresholded away: the long tail of
391
+ * small adapters is exactly what a per-chain sum must include.
324
392
  */
325
- function chainEntries(stats, minCalls) {
393
+ function chainRows(stats) {
326
394
  var _a, _b;
327
- const minGetLogs = getMinGetLogs();
328
- const chains = new Set([...Object.keys(stats.byChain), ...Object.keys((_b = (_a = stats.byMethod) === null || _a === void 0 ? void 0 : _a.getLogs) !== null && _b !== void 0 ? _b : {})]);
329
- const entries = [...chains]
330
- .map(key => { var _a; return ({ key, calls: (_a = stats.byChain[key]) !== null && _a !== void 0 ? _a : 0, getLogs: getLogsCount(stats, key) }); })
331
- .filter(i => i.calls >= minCalls || i.getLogs >= minGetLogs);
332
- entries.sort((a, b) => b.calls - a.calls || b.getLogs - a.getLogs);
333
- return entries;
395
+ const chains = new Set(Object.keys(stats.byChain));
396
+ for (const byChain of Object.values((_a = stats.byMethod) !== null && _a !== void 0 ? _a : {}))
397
+ for (const chain of Object.keys(byChain))
398
+ chains.add(chain);
399
+ for (const byChain of Object.values((_b = stats.logs) !== null && _b !== void 0 ? _b : {}))
400
+ for (const chain of Object.keys(byChain))
401
+ chains.add(chain);
402
+ if (stats.unattributed > 0)
403
+ chains.add(exports.OTHER_CHAIN);
404
+ const rows = [...chains].map(chain => {
405
+ var _a, _b;
406
+ const methods = methodsForChain(stats, chain);
407
+ const logsRpc = logsFetched(stats, 'rpc', chain);
408
+ const logsIndexer = logsFetched(stats, 'indexer', chain);
409
+ return {
410
+ chain,
411
+ calls: chain === exports.OTHER_CHAIN ? stats.unattributed : (_a = stats.byChain[chain]) !== null && _a !== void 0 ? _a : 0,
412
+ getLogs: getLogsCount(stats, chain),
413
+ indexerCalls: (_b = methods[exports.INDEXER_METHOD]) !== null && _b !== void 0 ? _b : 0,
414
+ logs: logsRpc + logsIndexer, logsRpc, logsIndexer,
415
+ methods,
416
+ };
417
+ }).filter(r => r.calls > 0 || r.logs > 0 || Object.keys(r.methods).length > 0);
418
+ rows.sort((a, b) => b.calls - a.calls || b.getLogs - a.getLogs || b.logs - a.logs);
419
+ return rows;
334
420
  }
335
- /** Elasticsearch documents for a run: one `run` summary, one `chain` doc per chain and one `host` doc per unattributed host at or above `minCalls`. */
336
- function buildDocs(stats, meta, { success, runtime, minCalls } = {}) {
337
- minCalls = getMinCalls(minCalls);
338
- const timestamp = Date.now();
339
- const chains = chainEntries(stats, minCalls);
340
- const hosts = sortedEntries(stats.byHost, minCalls, 25);
341
- const rpcCalls = Object.values(stats.byChain).reduce((a, b) => a + b, 0);
342
- const getLogsCalls = getLogsCount(stats);
343
- const unattributedHosts = sortedEntries(Object.fromEntries(Object.entries(stats.byHost).filter(([host]) => !shared.endpoints.has(host))), minCalls);
344
- const docs = [];
345
- if (stats.total < minCalls && getLogsCalls < getMinGetLogs())
346
- return docs;
347
- docs.push({
348
- timestamp, type: 'run', metadata: meta, success, runtime,
349
- calls: stats.total, rpcCalls, otherCalls: stats.unattributed, getLogsCalls,
350
- methods: methodTotals(stats),
351
- chains: chains.map(i => ({ chain: i.key, calls: i.calls, getLogs: i.getLogs })),
352
- hosts: hosts.map(i => ({ host: i.key, calls: i.calls })),
353
- });
354
- for (const i of chains)
355
- docs.push({ timestamp, type: 'chain', metadata: meta, chain: i.key, calls: i.calls, getLogs: i.getLogs, methods: methodsForChain(stats, i.key) });
356
- for (const i of unattributedHosts)
357
- docs.push({ timestamp, type: 'host', metadata: meta, host: i.key, calls: i.calls });
358
- return docs;
421
+ /** The busiest hosts of the run, rpc endpoints included so provider load is visible too. */
422
+ function hostRows(stats) {
423
+ return Object.entries(stats.byHost)
424
+ .map(([host, calls]) => ({ host, calls, rpc: shared.endpoints.has(host) }))
425
+ .sort((a, b) => b.calls - a.calls)
426
+ .slice(0, exports.MAX_HOSTS_PER_RUN);
427
+ }
428
+ /** Scalar meta fields become top-level doc fields; arrays/objects (eg. the list of chains to run) would only bloat the mapping. */
429
+ function flatMeta(meta) {
430
+ const out = {};
431
+ for (const [key, value] of Object.entries(meta))
432
+ if (value !== undefined && value !== null && typeof value !== 'object')
433
+ out[key] = value;
434
+ return out;
435
+ }
436
+ function buildDocs(stats, meta, { success, runtime, minCalls, interrupted } = {}) {
437
+ var _a;
438
+ const rows = stats.total >= getMinCalls(minCalls) ? chainRows(stats) : [];
439
+ if (!rows.length)
440
+ return { chainDocs: [], hostDocs: [] };
441
+ const base = {
442
+ '@timestamp': new Date().toISOString(),
443
+ ...flatMeta(meta),
444
+ runId: crypto_1.default.randomBytes(8).toString('hex'),
445
+ success, runtime, interrupted,
446
+ runCalls: stats.total,
447
+ runGetLogs: getLogsCount(stats),
448
+ runIndexerCalls: sumValues((_a = stats.byMethod) === null || _a === void 0 ? void 0 : _a[exports.INDEXER_METHOD]),
449
+ runLogs: logsFetched(stats, 'rpc') + logsFetched(stats, 'indexer'),
450
+ runChains: rows.filter(r => r.chain !== exports.OTHER_CHAIN).length,
451
+ };
452
+ return {
453
+ chainDocs: rows.map(r => ({ ...base, ...r })),
454
+ hostDocs: hostRows(stats).map(r => ({ ...base, ...r })),
455
+ };
359
456
  }
360
457
  /** Write the docs for `stats` to elasticsearch (no-op when ELASTICSEARCH_CONFIG is unset) and print the summary in debug mode. */
361
- async function report(stats, { success, runtime, minCalls, print, skipElastic, meta } = {}) {
458
+ async function report(stats, { success, runtime, minCalls, interrupted, print, skipElastic, meta } = {}) {
362
459
  var _a;
363
460
  meta = (_a = meta !== null && meta !== void 0 ? meta : stats.meta) !== null && _a !== void 0 ? _a : { application: 'unknown', name: '-' };
364
- minCalls = getMinCalls(minCalls);
365
- const docs = buildDocs(stats, meta, { success, runtime, minCalls });
461
+ const { chainDocs, hostDocs } = buildDocs(stats, meta, { success, runtime, minCalls, interrupted });
366
462
  if (print)
367
- printStats(stats, meta, minCalls, console.log, console.table);
463
+ printStats(stats, meta, console.log, console.table);
368
464
  else
369
- printStats(stats, meta, minCalls, debugLog_1.debugLog, debugLog_1.debugTable);
370
- if (skipElastic || !docs.length)
465
+ printStats(stats, meta, debugLog_1.debugLog, debugLog_1.debugTable);
466
+ if (skipElastic)
371
467
  return;
372
- await Promise.all(docs.map(doc => (0, elastic_1.writeLog)(exports.ES_INDEX, doc)));
468
+ await Promise.all([
469
+ ...chainDocs.map(doc => (0, elastic_1.writeLog)(exports.ES_INDEX, doc)),
470
+ ...hostDocs.map(doc => (0, elastic_1.writeLog)(exports.ES_HOST_INDEX, doc)),
471
+ ]);
373
472
  }
374
- function printStats(stats, meta, minCalls, log, table) {
375
- const getLogsCalls = getLogsCount(stats);
376
- if (stats.total < minCalls && getLogsCalls < getMinGetLogs())
473
+ function printStats(stats, meta, log, table) {
474
+ var _a;
475
+ if (!stats.total)
377
476
  return;
378
- log(`[callStats] ${meta.application}/${meta.name}: ${stats.total} http requests (${stats.unattributed} not matching a known rpc, ${getLogsCalls} getLogs)`);
477
+ const logs = logsFetched(stats, 'rpc') + logsFetched(stats, 'indexer');
478
+ log(`[callStats] ${meta.application}/${meta.name}: ${stats.total} http requests (${stats.unattributed} not matching a known rpc, ${getLogsCount(stats)} getLogs, ${sumValues((_a = stats.byMethod) === null || _a === void 0 ? void 0 : _a[exports.INDEXER_METHOD])} indexer requests, ${logs} logs fetched)`);
379
479
  const rows = [
380
- ...chainEntries(stats, minCalls).map(i => ({ chain: i.key, calls: i.calls, getLogs: i.getLogs })),
381
- ...sortedEntries(Object.fromEntries(Object.entries(stats.byHost).filter(([host]) => !shared.endpoints.has(host))), minCalls).map(i => ({ chain: `host: ${i.key}`, calls: i.calls, getLogs: 0 })),
480
+ ...chainRows(stats).slice(0, 30).map(r => ({ chain: r.chain, calls: r.calls, getLogs: r.getLogs, indexerCalls: r.indexerCalls, logs: r.logs })),
481
+ ...hostRows(stats).filter(h => !h.rpc).slice(0, 10).map(h => ({ chain: `host: ${h.host}`, calls: h.calls, getLogs: 0, indexerCalls: 0, logs: 0 })),
382
482
  ];
383
483
  if (rows.length)
384
484
  table(rows);
@@ -14,6 +14,7 @@ const general_1 = require("../general");
14
14
  const ethers_1 = require("ethers");
15
15
  const common_1 = require("./common");
16
16
  const debugLog_1 = require("./debugLog");
17
+ const callStats_1 = require("./callStats");
17
18
  const promisePool_1 = __importDefault(require("./promisePool"));
18
19
  var blocks_1 = require("./blocks");
19
20
  Object.defineProperty(exports, "getLatestBlock", { enumerable: true, get: function () { return blocks_1.getLatestBlock; } });
@@ -87,6 +88,7 @@ async function _getLogs(params) {
87
88
  };
88
89
  try {
89
90
  const partLogs = await provider.getLogs(logParams);
91
+ (0, callStats_1.recordLogs)('rpc', params.chain, partLogs.length);
90
92
  logs = logs.concat(partLogs);
91
93
  currentBlock = nextBlock;
92
94
  }
@@ -165,6 +165,11 @@ function assertCursorAdvances(next, previous) {
165
165
  if (!advances)
166
166
  throw new Error("Indexer v4 pagination cursor did not advance");
167
167
  }
168
+ // chain of an indexer query, for call stats: every page request is counted against it
169
+ function chainOfParams(params) {
170
+ var _a;
171
+ return (_a = allChainIdChainMapping[params === null || params === void 0 ? void 0 : params.chainId]) !== null && _a !== void 0 ? _a : callStats_1.OTHER_CHAIN;
172
+ }
168
173
  // Translate the public offset/limit contract into keyset pagination. Even all=false
169
174
  // may need several requests: the v4 server caps offsets, not the public SDK API.
170
175
  async function* getV4Pages(path, key, params, limit, offset, all, getCursor) {
@@ -175,8 +180,10 @@ async function* getV4Pages(path, key, params, limit, offset, all, getCursor) {
175
180
  let cursor;
176
181
  let remainingOffset = offset;
177
182
  let remainingLimit = all ? Infinity : limit;
183
+ const chain = chainOfParams(params);
178
184
  while (remainingLimit > 0) {
179
185
  const pageParams = { ...params, limit, offset: 0, includeTotal: false, ...cursor };
186
+ (0, callStats_1.recordMethod)(callStats_1.INDEXER_METHOD, chain);
180
187
  const response = await axiosInstances.v4(path, {
181
188
  params: pageParams,
182
189
  ...(key === "transfers" ? { responseType: "text", transformResponse: (data) => data } : {}),
@@ -186,6 +193,8 @@ async function* getV4Pages(path, key, params, limit, offset, all, getCursor) {
186
193
  const page = data[key];
187
194
  if (!Array.isArray(page))
188
195
  throw new Error(`Indexer v4 returned an invalid ${key} response`);
196
+ if (key === "logs")
197
+ (0, callStats_1.recordLogs)('indexer', chain, page.length);
189
198
  // Capture the cursor before consumers normalize/mutate the raw rows.
190
199
  const next = getCursor(page[page.length - 1]);
191
200
  const result = applyLocalOffset(page, remainingOffset);
@@ -208,10 +217,14 @@ async function* getIndexerPages(version, path, key, params, limit, offset, all,
208
217
  return;
209
218
  }
210
219
  let count = 0;
220
+ const chain = chainOfParams(params);
211
221
  do {
222
+ (0, callStats_1.recordMethod)(callStats_1.INDEXER_METHOD, chain);
212
223
  const { data } = await axiosInstances.v2(path, { params: { ...params, limit, offset } })
213
224
  .catch((e) => { throw (0, common_1.formError)(e); });
214
225
  const rows = data[key];
226
+ if (key === "logs" && Array.isArray(rows))
227
+ (0, callStats_1.recordLogs)('indexer', chain, rows.length);
215
228
  yield rows;
216
229
  count += rows.length;
217
230
  if (!rows.length || rows.length < limit || (key === "logs" && typeof data.totalCount === "number" && data.totalCount <= count))
@@ -231,6 +244,7 @@ async function getChainIndexStatus(version) {
231
244
  return state.chainIndexStatus;
232
245
  state.timestamp = Date.now();
233
246
  state.chainIndexStatus = (async () => {
247
+ (0, callStats_1.recordMethod)(callStats_1.INDEXER_METHOD); // serves every chain: counted under _other
234
248
  const { data: { syncStatus }, } = await axiosInstances[version].get(`/sync`).catch((e) => { throw (0, common_1.formError)(e); });
235
249
  const info = {};
236
250
  syncStatus.forEach((d) => {
@@ -251,10 +265,11 @@ async function getChainIndexStatus(version) {
251
265
  return state.chainIndexStatus;
252
266
  }
253
267
  async function streamLogs(opts) {
254
- const { path, version, onItem, onChunkStats, shouldStop } = opts;
268
+ const { path, version, chain, onItem, onChunkStats, shouldStop } = opts;
255
269
  const controller = new AbortController();
256
270
  let bytesReceived = 0;
257
271
  let itemsProcessed = 0;
272
+ (0, callStats_1.recordMethod)(callStats_1.INDEXER_METHOD, chain);
258
273
  const res = await axiosInstances[version].get(path, {
259
274
  responseType: "stream",
260
275
  timeout: INDEXER_REQUEST_TIMEOUT_MS,
@@ -296,6 +311,9 @@ async function streamLogs(opts) {
296
311
  if (!stopped)
297
312
  throw processingError !== null && processingError !== void 0 ? processingError : e;
298
313
  }
314
+ finally {
315
+ (0, callStats_1.recordLogs)('indexer', chain, itemsProcessed); // rows received, including those of a stream that then failed
316
+ }
299
317
  onChunkStats === null || onChunkStats === void 0 ? void 0 : onChunkStats({ chunkSize: 0, bytesReceived, itemsProcessed });
300
318
  }
301
319
  async function decodeStreamingLogs(logs, transformLog, batchDecoder, onlyArgs) {
@@ -454,6 +472,7 @@ async function getLogs(options) {
454
472
  await streamLogs({
455
473
  path: `/logs?${qs.toString()}`,
456
474
  version: indexerVersion,
475
+ chain,
457
476
  onItem: async (raw) => {
458
477
  var _a, _b, _c;
459
478
  if (stopNow)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defillama/sdk",
3
- "version": "5.0.244",
3
+ "version": "5.0.245",
4
4
  "description": "SDK for calculating TVL",
5
5
  "main": "build/index.js",
6
6
  "scripts": {