@odatano/core 2.0.0-rc.11 → 2.0.0-rc.12

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.
@@ -8,6 +8,9 @@ const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const CardanoODataService_1 = require("#cds-models/CardanoODataService");
9
9
  const CardanoTransactionService_1 = require("#cds-models/CardanoTransactionService");
10
10
  const CardanoSignService_1 = require("#cds-models/CardanoSignService");
11
+ // DB-level entity: the catalogue's existence check must bypass the temporal filter that the
12
+ // service projection carries (see ensureAssetRows).
13
+ const cardano_1 = require("#cds-models/odatano/cardano");
11
14
  const mappers_1 = require("../utils/mappers");
12
15
  const collections_1 = require("../utils/collections");
13
16
  const { UPSERT, INSERT, UPDATE, SELECT, DELETE } = cds_1.default.ql;
@@ -44,6 +47,67 @@ class CardanoIndexer {
44
47
  crawlEpochCache = new Map();
45
48
  crawlEpochCurrent = null;
46
49
  crawlEpochPrevious = null;
50
+ /**
51
+ * Analytics coverage of the crawl path (v2.0, FR "crawler coverage for analytics"). The
52
+ * defaults mirror the crawler config defaults, so an indexer the crawler never configured
53
+ * (unit tests, the lazy-only path) behaves exactly like a configured one.
54
+ */
55
+ crawlAssetHistory = true;
56
+ crawlAssetCatalogue = 'bare';
57
+ /** Units known to have an `Assets` row, so a repeat sighting costs no DB round-trip. */
58
+ static ASSET_MEMO_CAP = 200_000;
59
+ assetMemo = new Set();
60
+ /**
61
+ * Background registry enrichment (`assetCatalogue: 'enrich'`). Bare rows are queued here and
62
+ * resolved at a fixed rate OUTSIDE the block transaction, so a mint storm can slow the queue
63
+ * but never the crawl. Above the cap the oldest entries are dropped: the unit keeps its bare
64
+ * row and is still enriched by the lazy path on its first API read.
65
+ */
66
+ static ENRICH_QUEUE_CAP = 50_000;
67
+ enrichQueue = [];
68
+ enrichTimer = null;
69
+ enrichRate = 2;
70
+ /**
71
+ * Adopt the crawler's coverage settings. Called once from the crawler's start path; the
72
+ * lazy request path never touches these.
73
+ */
74
+ configureCrawlCoverage(coverage) {
75
+ this.crawlAssetHistory = coverage.assetHistory;
76
+ this.crawlAssetCatalogue = coverage.assetCatalogue;
77
+ this.enrichRate = coverage.assetEnrichRate ?? this.enrichRate;
78
+ if (coverage.assetCatalogue !== 'enrich')
79
+ this.stopAssetEnrichment();
80
+ }
81
+ /**
82
+ * Drain the enrichment queue at `enrichRate` units per second, one `indexAsset()` per tick in
83
+ * its own transaction. The timer is unref'd, so it never holds the process open, and a failing
84
+ * unit (404 from every backend, provider outage) is dropped rather than retried — its bare row
85
+ * stays and the lazy path can still enrich it later.
86
+ */
87
+ startAssetEnrichment() {
88
+ if (this.enrichTimer || this.crawlAssetCatalogue !== 'enrich')
89
+ return;
90
+ const intervalMs = Math.max(1, Math.round(1000 / Math.max(1, this.enrichRate)));
91
+ this.enrichTimer = setInterval(() => {
92
+ const unit = this.enrichQueue.shift();
93
+ if (unit === undefined) {
94
+ this.stopAssetEnrichment();
95
+ return;
96
+ }
97
+ void cds_1.default.tx((tx) => this.indexAsset(tx, unit)).catch((err) => {
98
+ logger.debug(`asset enrichment for ${unit} failed (bare row kept):`, err);
99
+ });
100
+ }, intervalMs);
101
+ this.enrichTimer.unref?.();
102
+ }
103
+ /** Stop the enrichment loop and forget what is still queued (shutdown, crawler halt, mode change). */
104
+ stopAssetEnrichment() {
105
+ if (this.enrichTimer) {
106
+ clearInterval(this.enrichTimer);
107
+ this.enrichTimer = null;
108
+ }
109
+ this.enrichQueue = [];
110
+ }
47
111
  /**
48
112
  * Network-only epoch prefetch for the crawler. Call BEFORE opening the per-block
49
113
  * write transaction — the backend round-trip must never run while the DB write
@@ -508,6 +572,9 @@ class CardanoIndexer {
508
572
  const outputRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputs)(t.hash, t.outputs ?? []));
509
573
  const outputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputAssets)(t.hash, t.outputs ?? []));
510
574
  const metadataRows = txs.flatMap(t => (0, mappers_1.mapTransactionMetadata)(t.metadata ?? []));
575
+ // Mint/burn is derived from rows already in hand — keyed (unit, txHash), so a re-crawl is
576
+ // idempotent and a reorg removes these rows with their transactions (crawler handleReorg).
577
+ const assetHistoryRows = this.crawlAssetHistory ? this.buildAssetHistoryRows(blockData, txs) : [];
511
578
  if (txRows.length)
512
579
  await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRows));
513
580
  if (inputRows.length)
@@ -520,7 +587,16 @@ class CardanoIndexer {
520
587
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
521
588
  if (metadataRows.length)
522
589
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
523
- logger.debug(`indexBlockFull: block ${blockData.hash} — ${txs.length} txs, ${outputRows.length} outputs`);
590
+ if (assetHistoryRows.length)
591
+ await tx.run(UPSERT.into(CardanoODataService_1.AssetHistory).entries(assetHistoryRows));
592
+ // Catalogue last: it reads what the block just wrote conceptually, and a block without
593
+ // native assets costs nothing here. Collecting the units is skipped entirely when the
594
+ // catalogue is off — this runs once per block.
595
+ const newAssets = this.crawlAssetCatalogue === 'off'
596
+ ? 0
597
+ : await this.ensureAssetRows(tx, this.collectBlockUnits(txs, assetHistoryRows));
598
+ logger.debug(`indexBlockFull: block ${blockData.hash} — ${txs.length} txs, ${outputRows.length} outputs, ` +
599
+ `${assetHistoryRows.length} mint/burn, ${newAssets} new assets`);
524
600
  }
525
601
  /**
526
602
  * Backfill input address/amount for chain-sync transactions whose inputs are bare
@@ -599,8 +675,10 @@ class CardanoIndexer {
599
675
  * declared fee is kept in that case and the transaction is logged: a value that is wrong in
600
676
  * a known, named way beats one that looks derived but is short by an unknown amount.
601
677
  *
602
- * Only the chain-sync path sets `spendsCollaterals`; Blockfrost and Koios transactions carry
603
- * it as undefined and pass through untouched.
678
+ * Applies to every backend that reports phase-2 validity — the chain-sync path (`spends`)
679
+ * and Blockfrost (`valid_contract`), whose declared `fees` are likewise never collected on a
680
+ * failed script phase. Koios carries `spendsCollaterals` as undefined and passes through
681
+ * untouched.
604
682
  */
605
683
  applyCollateralFees(blockData, txs) {
606
684
  const lovelaceOf = (amount) => BigInt(amount?.find(a => a.unit === 'lovelace')?.quantity ?? '0');
@@ -635,6 +713,217 @@ class CardanoIndexer {
635
713
  blockData.fees = txs.reduce((sum, t) => sum + BigInt(t.fee || 0), 0n).toString();
636
714
  }
637
715
  }
716
+ /**
717
+ * Mint/burn rows for a whole block, as a by-product of data the crawler already holds —
718
+ * no provider round-trip (v2.1 analytics coverage).
719
+ *
720
+ * Two sources, in this order:
721
+ * 1. `t.mint` — the ledger's own mint field, reported natively by Ogmios (`mint`) and
722
+ * Koios (`assets_minted`). Authoritative: it needs no resolved inputs and states the
723
+ * net per unit directly.
724
+ * 2. Σ outputs − Σ inputs per unit, for backends without that field (Blockfrost), whose
725
+ * inputs all carry their full `amount` so the delta is exact.
726
+ *
727
+ * The delta path excludes what the ledger does not consume or produce: reference inputs are
728
+ * read, never spent, and collateral only moves when the script phase failed — which applies
729
+ * no mint at all, so those transactions are skipped outright. Both exclusions rest on
730
+ * `isReference` / `isCollateral` / `spendsCollaterals`, which every backend that can reach
731
+ * this branch has to set — Blockfrost does since rc.12. A transaction with even one
732
+ * unresolvable consumed input (an output created before the crawl start, so no local row) is
733
+ * skipped and logged rather than reported with a delta that is short by an unknown amount —
734
+ * the same discipline as applyCollateralFees() above.
735
+ */
736
+ buildAssetHistoryRows(blockData, txs) {
737
+ const entries = [];
738
+ let skipped = 0;
739
+ for (const t of txs) {
740
+ let net;
741
+ if (t.mint) {
742
+ // A phase-2 failure never reaches here with a mint: the Ogmios mapper reports none.
743
+ net = new Map();
744
+ for (const m of t.mint) {
745
+ if (m.unit === 'lovelace')
746
+ continue;
747
+ net.set(m.unit, (net.get(m.unit) ?? 0n) + BigInt(m.quantity));
748
+ }
749
+ }
750
+ else {
751
+ if (t.spendsCollaterals)
752
+ continue; // no mint is applied when the script phase failed
753
+ const consumed = (t.inputs ?? []).filter(i => !i.isReference && !i.isCollateral);
754
+ const unresolved = consumed.find(i => !i.address);
755
+ if (unresolved) {
756
+ logger.warn(`mint delta for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed ` +
757
+ `— skipping, mint/burn of this transaction is not recorded`);
758
+ skipped++;
759
+ continue;
760
+ }
761
+ net = new Map();
762
+ const add = (amount, sign) => {
763
+ for (const a of amount ?? []) {
764
+ if (a.unit === 'lovelace')
765
+ continue;
766
+ net.set(a.unit, (net.get(a.unit) ?? 0n) + sign * BigInt(a.quantity));
767
+ }
768
+ };
769
+ for (const o of (t.outputs ?? []).filter(o => !o.isCollateral))
770
+ add(o.amount, 1n);
771
+ for (const i of consumed)
772
+ add(i.amount, -1n);
773
+ }
774
+ for (const [unit, quantity] of net) {
775
+ if (quantity === 0n)
776
+ continue;
777
+ entries.push({
778
+ unit,
779
+ txHash: t.hash,
780
+ action: quantity > 0n ? 'mint' : 'burn',
781
+ quantity: (quantity < 0n ? -quantity : quantity).toString(),
782
+ blockTime: blockData.time ?? null,
783
+ blockHeight: blockData.height ?? null,
784
+ });
785
+ }
786
+ }
787
+ if (skipped) {
788
+ logger.warn(`block ${blockData.hash}: mint/burn not recorded for ${skipped} transaction(s) with unresolved inputs`);
789
+ }
790
+ return (0, mappers_1.mapAssetHistory)(entries);
791
+ }
792
+ /**
793
+ * Keep the `Assets` catalogue complete for every unit the crawl meets, from the data already
794
+ * in hand — no provider call (FR "crawler coverage for analytics", variant "bare row").
795
+ *
796
+ * `Assets` is temporal, so its key is `(validFrom, unit)` and a row is a slice. The bare row
797
+ * therefore carries the fixed epoch-zero stamp (`BARE_ASSET_STAMP`), which no wall-clock slice
798
+ * from mapAsset() can ever alias: the write cannot overwrite enriched registry data, and it
799
+ * stays a single idempotent row per unit. That makes UPSERT safe — and safe is what it has to
800
+ * be, because this runs inside the crawler's block transaction, where a unique-key violation
801
+ * from a lazy-path write racing us would take the whole block down with it (and on PostgreSQL
802
+ * poison the transaction beyond any catch).
803
+ *
804
+ * The existence check is then only an optimization — it keeps a settled catalogue from
805
+ * rewriting every unit of every block. It runs against the DB-LEVEL entity on purpose: the
806
+ * service projection carries the temporal filter (`validFrom < $valid.to AND validTo >
807
+ * $valid.from`), which hides precisely the born-expired rows this check is looking for.
808
+ */
809
+ async ensureAssetRows(tx, units) {
810
+ if (this.crawlAssetCatalogue === 'off' || !units.size)
811
+ return 0;
812
+ const unknown = [...units].filter(u => !this.assetMemo.has(u));
813
+ if (!unknown.length)
814
+ return 0;
815
+ const missing = [];
816
+ for (const unitChunk of (0, collections_1.chunk)(unknown, collections_1.IN_CHUNK)) {
817
+ const rows = await tx.run(SELECT.from(cardano_1.Assets).columns('unit').where({ unit: { in: unitChunk } }));
818
+ const known = new Set(rows.map(r => r.unit));
819
+ for (const unit of unitChunk) {
820
+ if (known.has(unit))
821
+ this.noteAssetSeen(unit);
822
+ else
823
+ missing.push(unit);
824
+ }
825
+ }
826
+ if (!missing.length)
827
+ return 0;
828
+ const rows = missing.map(mappers_1.mapBareAsset).filter((r) => r !== null);
829
+ // Chunked like the lookup above: a mint-storm block can carry thousands of fresh units,
830
+ // and one statement per 500 rows keeps every driver's bind-variable cap out of reach.
831
+ for (const rowChunk of (0, collections_1.chunk)(rows, collections_1.IN_CHUNK)) {
832
+ await tx.run(UPSERT.into(cardano_1.Assets).entries(rowChunk));
833
+ }
834
+ // Memoize every unit we looked up, including the ones mapBareAsset rejected — re-deciding
835
+ // that a malformed unit is unmappable on every block would cost a SELECT each time.
836
+ for (const unit of missing)
837
+ this.noteAssetSeen(unit);
838
+ if (this.crawlAssetCatalogue === 'enrich' && rows.length) {
839
+ for (const row of rows) {
840
+ if (this.enrichQueue.length >= CardanoIndexer.ENRICH_QUEUE_CAP)
841
+ this.enrichQueue.shift();
842
+ this.enrichQueue.push(row.unit);
843
+ }
844
+ this.startAssetEnrichment();
845
+ }
846
+ return rows.length;
847
+ }
848
+ /**
849
+ * Remember a unit as present in the catalogue. Insertion-ordered Set → the oldest entries
850
+ * are evicted first once the cap is reached, which keeps a long backfill's memory flat while
851
+ * hot policies stay memoized. Losing an entry costs one SELECT, never a wrong write.
852
+ */
853
+ noteAssetSeen(unit) {
854
+ if (this.assetMemo.has(unit))
855
+ return;
856
+ if (this.assetMemo.size >= CardanoIndexer.ASSET_MEMO_CAP) {
857
+ const oldest = this.assetMemo.values().next();
858
+ if (!oldest.done)
859
+ this.assetMemo.delete(oldest.value);
860
+ }
861
+ this.assetMemo.add(unit);
862
+ }
863
+ /**
864
+ * Snapshot every stake pool and DRep at an epoch boundary (v2.0 analytics coverage).
865
+ *
866
+ * Runs in its OWN transaction, called by the crawler after a block commit — never inside the
867
+ * block's write transaction: a few thousand rows would inflate an otherwise small atomic
868
+ * write, and a snapshot failure would fail the block and burn its persist retries.
869
+ *
870
+ * Writes two things per entity: the dated snapshot row (authoritative, never expires) and a
871
+ * refresh of the live temporal row, so `Pools` / `Dreps` also stop being empty on a crawled
872
+ * instance. Needs an enumerating backend (Koios); without one it is a logged no-op.
873
+ *
874
+ * @param epoch the epoch the snapshot is taken for
875
+ * @param at slot and block time of the block that triggered the boundary
876
+ * @returns counts actually written, for the caller's log
877
+ */
878
+ async snapshotEpoch(epoch, at) {
879
+ const backend = this.client.getEnumeratingBackend();
880
+ if (!backend) {
881
+ logger.warn(`epoch ${epoch} snapshot skipped: no backend can enumerate pools/DReps (Koios required)`);
882
+ return { pools: 0, dreps: 0 };
883
+ }
884
+ // Network first, DB second — the provider round-trips must not run with a write lock held.
885
+ const [poolData, drepData] = await Promise.all([
886
+ backend.getPoolIds().then(ids => backend.getPools(ids)),
887
+ backend.getDrepIds().then(ids => backend.getDreps(ids)),
888
+ ]);
889
+ const poolSnapshots = poolData.map(p => (0, mappers_1.mapPoolSnapshot)(p, epoch, at));
890
+ const drepSnapshots = drepData.map(d => (0, mappers_1.mapDrepSnapshot)(d, epoch, at));
891
+ const poolRows = poolData.map(p => (0, mappers_1.mapPool)(p, this.client.max_age_ms));
892
+ const drepRows = drepData.map(d => (0, mappers_1.mapDrep)(d, this.client.max_age_ms));
893
+ await cds_1.default.tx(async (tx) => {
894
+ // Chunked so a mainnet-sized set cannot exceed a driver's bind-variable cap.
895
+ for (const rows of (0, collections_1.chunk)(poolSnapshots, collections_1.IN_CHUNK))
896
+ await tx.run(UPSERT.into(CardanoODataService_1.PoolEpochSnapshots).entries(rows));
897
+ for (const rows of (0, collections_1.chunk)(drepSnapshots, collections_1.IN_CHUNK))
898
+ await tx.run(UPSERT.into(CardanoODataService_1.DrepEpochSnapshots).entries(rows));
899
+ for (const rows of (0, collections_1.chunk)(poolRows, collections_1.IN_CHUNK))
900
+ await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(rows));
901
+ for (const rows of (0, collections_1.chunk)(drepRows, collections_1.IN_CHUNK))
902
+ await tx.run(UPSERT.into(CardanoODataService_1.Dreps).entries(rows));
903
+ });
904
+ logger.info(`epoch ${epoch} snapshot: ${poolSnapshots.length} pools, ${drepSnapshots.length} DReps`);
905
+ return { pools: poolSnapshots.length, dreps: drepSnapshots.length };
906
+ }
907
+ /** Every native-asset unit a block touches: outputs, consumed inputs and mint/burn rows. */
908
+ collectBlockUnits(txs, assetHistoryRows) {
909
+ const units = new Set();
910
+ for (const t of txs) {
911
+ for (const o of t.outputs ?? []) {
912
+ for (const a of o.amount ?? [])
913
+ if (a.unit !== 'lovelace')
914
+ units.add(a.unit);
915
+ }
916
+ for (const i of t.inputs ?? []) {
917
+ for (const a of i.amount ?? [])
918
+ if (a.unit !== 'lovelace')
919
+ units.add(a.unit);
920
+ }
921
+ }
922
+ for (const row of assetHistoryRows)
923
+ if (row.unit)
924
+ units.add(row.unit);
925
+ return units;
926
+ }
638
927
  /**
639
928
  * Index & return the epoch information data
640
929
  * @param tx CAP transaction object
@@ -16,6 +16,22 @@ export interface CrawlerConfig {
16
16
  confirmationDepth: number;
17
17
  /** Poll cadence when caught up / on transient errors (pagination path). */
18
18
  pollIntervalMs: number;
19
+ /**
20
+ * Analytics coverage of the crawl (FR "crawler coverage for analytics"). All three are
21
+ * by-products of blocks the crawler already holds, except `assetCatalogue: 'enrich'` and
22
+ * `epochSnapshots`, which do talk to a provider.
23
+ */
24
+ /** Write mint/burn rows into AssetHistory. Free — no provider call. */
25
+ assetHistory: boolean;
26
+ /**
27
+ * `off` — nothing; `bare` — one Assets row per unit from block data alone (free);
28
+ * `enrich` — additionally resolve supply/registry data in the background, rate limited.
29
+ */
30
+ assetCatalogue: 'off' | 'bare' | 'enrich';
31
+ /** Units per second the background enrichment resolves (`assetCatalogue: 'enrich'` only). */
32
+ assetEnrichRate: number;
33
+ /** Snapshot every pool and DRep at each epoch boundary. Requires an enumerating backend (Koios). */
34
+ epochSnapshots: boolean;
19
35
  }
20
36
  /**
21
37
  * CardanoCrawler — pre-sync engine (v2.0). Streams the chain forward from a configured
@@ -60,6 +76,18 @@ export declare class CardanoCrawler {
60
76
  private static readonly DATA_REJECTION_PATTERNS;
61
77
  /** Timeout for direct backend calls (the crawler bypasses the client's resilience layer). */
62
78
  private static readonly CALL_TIMEOUT_MS;
79
+ /**
80
+ * Epoch snapshots are ~100 batched provider requests on mainnet, so they get a wider
81
+ * bound than an ordinary call — still bounded, and cancelled by beginHalt.
82
+ */
83
+ private static readonly SNAPSHOT_TIMEOUT_MS;
84
+ /**
85
+ * Backoff after a failed snapshot attempt, doubling up to the cap. Without it a provider
86
+ * outage would re-trigger a full pool/DRep enumeration on every single block for the rest
87
+ * of the epoch — the marker is only set on success, by design.
88
+ */
89
+ private static readonly SNAPSHOT_RETRY_BASE_MS;
90
+ private static readonly SNAPSHOT_RETRY_MAX_MS;
63
91
  private running;
64
92
  private chainSyncHandle;
65
93
  /** The detached ingest pipeline — awaited by stop() so teardown never races it. */
@@ -82,6 +110,12 @@ export declare class CardanoCrawler {
82
110
  private finalStatus;
83
111
  /** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
84
112
  private latchOnHalt;
113
+ /** Epoch whose pool/DRep snapshot this process has settled, and the in-flight attempt. */
114
+ private snapshotedEpoch;
115
+ private snapshotInFlight;
116
+ /** Consecutive snapshot failures and the earliest time the next attempt may run. */
117
+ private snapshotFailures;
118
+ private snapshotRetryAfter;
85
119
  private leaseHeld;
86
120
  private leaseHeartbeat;
87
121
  private leaseWake;
@@ -178,6 +212,30 @@ export declare class CardanoCrawler {
178
212
  * @returns true when the block was persisted, false when the crawler was stopped
179
213
  */
180
214
  private persistBlock;
215
+ /** Epoch a slot belongs to, from the network's Shelley anchor (same math as the Ogmios mapper). */
216
+ private epochOfSlot;
217
+ /**
218
+ * Take the epoch snapshot of pools and DReps once per epoch, detached from the block that
219
+ * triggered it (v2.0 analytics coverage, opt-in via `epochSnapshots`).
220
+ *
221
+ * ONLY AT THE TIP. The providers that can enumerate the pool and DRep set report their
222
+ * CURRENT state — Koios `/pool_info` and `/drep_info` take no epoch parameter. Snapshotting
223
+ * while the crawl is still backfilling would therefore write today's stake and vote power
224
+ * under every historical epoch number it passes: a table that reads as a time series but is
225
+ * a constant. So the block's epoch must be the epoch the reported tip is in; otherwise the
226
+ * epoch is skipped, permanently and by design. Backfilled ranges have no snapshots, live
227
+ * ones do.
228
+ *
229
+ * Detached on purpose: the snapshot is a few thousand rows plus ~100 provider requests, and
230
+ * the crawl must not wait for it or fail because of it. It is tracked as an in-flight
231
+ * callback, so a shutdown still drains it, and bounded by a timeout that beginHalt cancels.
232
+ *
233
+ * "Once per epoch" survives a restart: the process-local marker only skips work, the
234
+ * authority is a `PoolEpochSnapshots` row for that epoch — so a crawler restarted right
235
+ * after a boundary still records the epoch, and one restarted mid-epoch does not redo it.
236
+ * A failed attempt leaves the marker unset and backs off (see SNAPSHOT_RETRY_BASE_MS).
237
+ */
238
+ private maybeSnapshotEpoch;
181
239
  /**
182
240
  * Handle a chain rollback: in one transaction, delete every block after the fork point
183
241
  * and exactly the transactions belonging to those blocks (plus their child rows), reset
@@ -7,6 +7,7 @@ exports.CardanoCrawler = void 0;
7
7
  const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const errors_1 = require("../../utils/errors");
9
9
  const collections_1 = require("../../utils/collections");
10
+ const const_1 = require("../../utils/const");
10
11
  const hooks_1 = require("./hooks");
11
12
  const cardano_1 = require("#cds-models/odatano/cardano");
12
13
  const sync_state_1 = require("./sync-state");
@@ -71,6 +72,18 @@ class CardanoCrawler {
71
72
  ];
72
73
  /** Timeout for direct backend calls (the crawler bypasses the client's resilience layer). */
73
74
  static CALL_TIMEOUT_MS = 60_000;
75
+ /**
76
+ * Epoch snapshots are ~100 batched provider requests on mainnet, so they get a wider
77
+ * bound than an ordinary call — still bounded, and cancelled by beginHalt.
78
+ */
79
+ static SNAPSHOT_TIMEOUT_MS = 5 * 60_000;
80
+ /**
81
+ * Backoff after a failed snapshot attempt, doubling up to the cap. Without it a provider
82
+ * outage would re-trigger a full pool/DRep enumeration on every single block for the rest
83
+ * of the epoch — the marker is only set on success, by design.
84
+ */
85
+ static SNAPSHOT_RETRY_BASE_MS = 30_000;
86
+ static SNAPSHOT_RETRY_MAX_MS = 10 * 60_000;
74
87
  running = false;
75
88
  chainSyncHandle = null;
76
89
  /** The detached ingest pipeline — awaited by stop() so teardown never races it. */
@@ -93,6 +106,12 @@ class CardanoCrawler {
93
106
  finalStatus = 'stopped';
94
107
  /** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
95
108
  latchOnHalt = false;
109
+ /** Epoch whose pool/DRep snapshot this process has settled, and the in-flight attempt. */
110
+ snapshotedEpoch = null;
111
+ snapshotInFlight = null;
112
+ /** Consecutive snapshot failures and the earliest time the next attempt may run. */
113
+ snapshotFailures = 0;
114
+ snapshotRetryAfter = 0;
96
115
  leaseHeld = false;
97
116
  leaseHeartbeat = null;
98
117
  leaseWake = null;
@@ -141,6 +160,12 @@ class CardanoCrawler {
141
160
  }
142
161
  }
143
162
  this.running = true;
163
+ // Hand the analytics coverage to the indexer before the first block is written.
164
+ this.indexer.configureCrawlCoverage({
165
+ assetHistory: this.config.assetHistory,
166
+ assetCatalogue: this.config.assetCatalogue,
167
+ assetEnrichRate: this.config.assetEnrichRate,
168
+ });
144
169
  this.startLeaseHeartbeat();
145
170
  // A pipeline crash (e.g. chain-sync intersection not found after downtime) must
146
171
  // surface on the cursor — otherwise the crawler looks healthy while doing nothing.
@@ -192,6 +217,8 @@ class CardanoCrawler {
192
217
  if (this.finalStatus !== 'error' || finalStatus === 'error')
193
218
  this.finalStatus = finalStatus;
194
219
  this.running = false;
220
+ // Background asset enrichment belongs to the crawl — it must not outlive it.
221
+ this.indexer.stopAssetEnrichment();
195
222
  this.wake?.(); // cancel a pending poll sleep so the loop exits now
196
223
  this.streamEnded?.(); // release the ingest loop — beginHalt awaits the pipeline below
197
224
  this.leaseWake?.();
@@ -632,6 +659,7 @@ class CardanoCrawler {
632
659
  tipSlot: tip?.slot ?? null,
633
660
  tipHeight: tip?.height ?? null,
634
661
  });
662
+ this.maybeSnapshotEpoch(block, tip);
635
663
  return true;
636
664
  }
637
665
  catch (err) {
@@ -672,6 +700,73 @@ class CardanoCrawler {
672
700
  }
673
701
  }
674
702
  }
703
+ /** Epoch a slot belongs to, from the network's Shelley anchor (same math as the Ogmios mapper). */
704
+ epochOfSlot(slot) {
705
+ const cfg = const_1.EPOCH_CONFIG_BY_NETWORK[this.network]
706
+ ?? const_1.EPOCH_CONFIG_BY_NETWORK.preview;
707
+ return cfg.shelleyStartEpoch + Math.floor((slot - cfg.shelleyStartSlot) / cfg.slotsPerEpoch);
708
+ }
709
+ /**
710
+ * Take the epoch snapshot of pools and DReps once per epoch, detached from the block that
711
+ * triggered it (v2.0 analytics coverage, opt-in via `epochSnapshots`).
712
+ *
713
+ * ONLY AT THE TIP. The providers that can enumerate the pool and DRep set report their
714
+ * CURRENT state — Koios `/pool_info` and `/drep_info` take no epoch parameter. Snapshotting
715
+ * while the crawl is still backfilling would therefore write today's stake and vote power
716
+ * under every historical epoch number it passes: a table that reads as a time series but is
717
+ * a constant. So the block's epoch must be the epoch the reported tip is in; otherwise the
718
+ * epoch is skipped, permanently and by design. Backfilled ranges have no snapshots, live
719
+ * ones do.
720
+ *
721
+ * Detached on purpose: the snapshot is a few thousand rows plus ~100 provider requests, and
722
+ * the crawl must not wait for it or fail because of it. It is tracked as an in-flight
723
+ * callback, so a shutdown still drains it, and bounded by a timeout that beginHalt cancels.
724
+ *
725
+ * "Once per epoch" survives a restart: the process-local marker only skips work, the
726
+ * authority is a `PoolEpochSnapshots` row for that epoch — so a crawler restarted right
727
+ * after a boundary still records the epoch, and one restarted mid-epoch does not redo it.
728
+ * A failed attempt leaves the marker unset and backs off (see SNAPSHOT_RETRY_BASE_MS).
729
+ */
730
+ maybeSnapshotEpoch(block, tip) {
731
+ if (!this.config.epochSnapshots || block.epoch == null)
732
+ return;
733
+ if (this.snapshotedEpoch === block.epoch || this.snapshotInFlight)
734
+ return;
735
+ // No tip reported = we cannot prove we are live, so we do not pretend to be.
736
+ if (tip == null) {
737
+ logger.debug(`epoch ${block.epoch} snapshot skipped: no chain tip reported for this block`);
738
+ return;
739
+ }
740
+ const tipEpoch = this.epochOfSlot(tip.slot);
741
+ if (block.epoch !== tipEpoch) {
742
+ logger.debug(`epoch ${block.epoch} snapshot skipped: still backfilling (tip is in epoch ${tipEpoch}) — ` +
743
+ `the pool/DRep set can only be observed as it is now, never as it was`);
744
+ return;
745
+ }
746
+ if (Date.now() < this.snapshotRetryAfter)
747
+ return;
748
+ const epoch = block.epoch;
749
+ const at = { slot: block.slot ?? 0, time: block.time ?? 0 };
750
+ this.snapshotInFlight = this.trackCallback(async () => {
751
+ const existing = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.PoolEpochSnapshots).columns('epoch').where({ epoch })));
752
+ if (!existing) {
753
+ await this.withTimeout(this.indexer.snapshotEpoch(epoch, at), `snapshotEpoch(${epoch})`, CardanoCrawler.SNAPSHOT_TIMEOUT_MS);
754
+ }
755
+ this.snapshotedEpoch = epoch;
756
+ this.snapshotFailures = 0;
757
+ this.snapshotRetryAfter = 0;
758
+ })
759
+ .catch((err) => {
760
+ // Never fatal: the crawl keeps its data, the epoch is retried on a later block —
761
+ // but not on the very next one, or an outage would re-enumerate per block.
762
+ this.snapshotFailures++;
763
+ const backoff = Math.min(CardanoCrawler.SNAPSHOT_RETRY_BASE_MS * 2 ** (this.snapshotFailures - 1), CardanoCrawler.SNAPSHOT_RETRY_MAX_MS);
764
+ this.snapshotRetryAfter = Date.now() + backoff;
765
+ if (this.running)
766
+ logger.error(`epoch ${epoch} snapshot failed (retry in ${backoff} ms):`, err);
767
+ })
768
+ .finally(() => { this.snapshotInFlight = null; });
769
+ }
675
770
  /**
676
771
  * Handle a chain rollback: in one transaction, delete every block after the fork point
677
772
  * and exactly the transactions belonging to those blocks (plus their child rows), reset
@@ -62,6 +62,16 @@ service CardanoODataService @(impl: './cardano-service') {
62
62
  @description: 'Projection for Dreps'
63
63
  entity Dreps as projection on db.Dreps;
64
64
 
65
+ @readonly
66
+ @title : 'Pool Epoch Snapshots'
67
+ @description: 'Projection for per-epoch stake-pool snapshots written by the chain crawler'
68
+ entity PoolEpochSnapshots as projection on db.PoolEpochSnapshots;
69
+
70
+ @readonly
71
+ @title : 'DRep Epoch Snapshots'
72
+ @description: 'Projection for per-epoch DRep snapshots written by the chain crawler'
73
+ entity DrepEpochSnapshots as projection on db.DrepEpochSnapshots;
74
+
65
75
  @readonly
66
76
  @title : 'Assets'
67
77
  @description: 'Projection for Native-Asset Information'
package/srv/server.js CHANGED
@@ -39,7 +39,19 @@ const CRAWLER_LIMITS = {
39
39
  batchSize: { min: 1, max: 100 },
40
40
  confirmationDepth: { min: 0, max: 2160 },
41
41
  pollIntervalMs: { min: 1000, max: 3_600_000 },
42
+ assetEnrichRate: { min: 1, max: 20 },
42
43
  };
44
+ const VALID_ASSET_CATALOGUE_MODES = ['off', 'bare', 'enrich'];
45
+ /** Parse a boolean crawler flag that defaults to `fallback` when unset. */
46
+ function crawlerBoolean(raw, name, fallback) {
47
+ if (raw === undefined || raw === null)
48
+ return fallback;
49
+ if (raw === true || raw === 'true')
50
+ return true;
51
+ if (raw === false || raw === 'false')
52
+ return false;
53
+ throw new errors_1.ConfigError(`Invalid ${name} "${String(raw)}". Must be true or false.`);
54
+ }
43
55
  /** Parse an integer without allowing JavaScript's lossy/implicit coercions. */
44
56
  function crawlerInteger(raw, name, min, max, defaultValue) {
45
57
  if (raw == null)
@@ -406,7 +418,20 @@ function loadCrawlerConfigFromEnv() {
406
418
  if (!['ogmios', 'pagination', 'auto'].includes(source)) {
407
419
  throw new errors_1.ConfigError(`Invalid CRAWLER_SOURCE "${source}". Must be one of: ogmios, pagination, auto.`);
408
420
  }
409
- return { enabled, startSlot, startBlockHash, startHeight, source, batchSize, confirmationDepth, pollIntervalMs };
421
+ // Analytics coverage. Mint/burn and the bare catalogue are on by default: both are
422
+ // by-products of a block the crawler already holds and add no provider traffic. The two
423
+ // that do cost network — background enrichment and the epoch snapshots — are opt-in.
424
+ const assetHistory = crawlerBoolean(c.assetHistory ?? process_1.env.CRAWLER_ASSET_HISTORY, 'CRAWLER_ASSET_HISTORY', true);
425
+ const assetCatalogue = (c.assetCatalogue ?? process_1.env.CRAWLER_ASSET_CATALOGUE ?? 'bare');
426
+ if (!VALID_ASSET_CATALOGUE_MODES.includes(assetCatalogue)) {
427
+ throw new errors_1.ConfigError(`Invalid CRAWLER_ASSET_CATALOGUE "${assetCatalogue}". Must be one of: ${VALID_ASSET_CATALOGUE_MODES.join(', ')}.`);
428
+ }
429
+ const assetEnrichRate = crawlerInteger(c.assetEnrichRate ?? process_1.env.CRAWLER_ASSET_ENRICH_RATE, 'CRAWLER_ASSET_ENRICH_RATE', CRAWLER_LIMITS.assetEnrichRate.min, CRAWLER_LIMITS.assetEnrichRate.max, 2);
430
+ const epochSnapshots = crawlerBoolean(c.epochSnapshots ?? process_1.env.CRAWLER_EPOCH_SNAPSHOTS, 'CRAWLER_EPOCH_SNAPSHOTS', false);
431
+ return {
432
+ enabled, startSlot, startBlockHash, startHeight, source, batchSize, confirmationDepth, pollIntervalMs,
433
+ assetHistory, assetCatalogue, assetEnrichRate, epochSnapshots,
434
+ };
410
435
  }
411
436
  /**
412
437
  * Start the chain crawler if it is enabled and the app context is ready. Never throws
@@ -169,7 +169,7 @@ export declare const HEX_56_REGEX: RegExp;
169
169
  */
170
170
  export declare const TX_HASH_REGEX: RegExp;
171
171
  /**
172
- * Asset unit Regex - policy ID (56 hex chars) + asset name (0-128 hex chars)
172
+ * Asset unit Regex - policy ID (56 hex chars) + asset name (0-64 hex chars)
173
173
  */
174
174
  export declare const ASSET_UNIT_REGEX: RegExp;
175
175
  /**
@@ -139,7 +139,7 @@ exports.HEX_56_REGEX = /^[a-f0-9]{56}$/;
139
139
  */
140
140
  exports.TX_HASH_REGEX = /^[a-f0-9]{64}$/;
141
141
  /**
142
- * Asset unit Regex - policy ID (56 hex chars) + asset name (0-128 hex chars)
142
+ * Asset unit Regex - policy ID (56 hex chars) + asset name (0-64 hex chars)
143
143
  */
144
144
  exports.ASSET_UNIT_REGEX = /^[a-f0-9]{56}([a-f0-9]{2}){0,32}$/; // policy ID (56) + asset name (0-32 bytes per ledger rules -> 0-64 hex chars, even length; total ≤ 120 = String(120) key column)
145
145
  /**