@odatano/core 2.0.0-rc.10 → 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.
- package/@cds-models/CardanoODataService/index.d.ts +54 -0
- package/@cds-models/CardanoODataService/index.js +6 -0
- package/@cds-models/odatano/cardano/index.d.ts +54 -0
- package/@cds-models/odatano/cardano/index.js +6 -0
- package/db/schema.cds +1844 -1738
- package/package.json +1 -1
- package/srv/blockchain/backends/blockfrost-backend.js +7 -2
- package/srv/blockchain/backends/cardano-backend.d.ts +22 -0
- package/srv/blockchain/backends/cardano-backend.js +9 -0
- package/srv/blockchain/backends/koios-backend.d.ts +34 -2
- package/srv/blockchain/backends/koios-backend.js +133 -39
- package/srv/blockchain/backends/ogmios-backend.d.ts +6 -1
- package/srv/blockchain/backends/ogmios-backend.js +27 -2
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +77 -0
- package/srv/blockchain/backends/ogmios-frame-guard.js +181 -0
- package/srv/blockchain/cardano-client.d.ts +8 -1
- package/srv/blockchain/cardano-client.js +14 -0
- package/srv/blockchain/cardano-indexer.d.ts +127 -0
- package/srv/blockchain/cardano-indexer.js +345 -3
- package/srv/blockchain/crawler/crawler.d.ts +88 -0
- package/srv/blockchain/crawler/crawler.js +180 -2
- package/srv/cardano-service.cds +10 -0
- package/srv/server.js +26 -1
- package/srv/utils/const.d.ts +1 -1
- package/srv/utils/const.js +1 -1
- package/srv/utils/errors.d.ts +18 -0
- package/srv/utils/errors.js +24 -1
- package/srv/utils/mappers.d.ts +54 -1
- package/srv/utils/mappers.js +111 -0
- package/srv/utils/types.d.ts +27 -0
- package/srv/utils/validators.d.ts +1 -1
- package/srv/utils/validators.js +2 -2
|
@@ -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
|
|
@@ -493,9 +557,12 @@ class CardanoIndexer {
|
|
|
493
557
|
if (epochRows.length)
|
|
494
558
|
await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries(epochRows));
|
|
495
559
|
}
|
|
496
|
-
|
|
497
|
-
//
|
|
560
|
+
// Backfill chain-sync inputs (empty address/amount) from local outputs, then settle
|
|
561
|
+
// the fee of any phase-2 failure. Both run before the block row is written, because a
|
|
562
|
+
// corrected fee changes the block's fee total.
|
|
498
563
|
await this.resolveInputs(tx, txs);
|
|
564
|
+
this.applyCollateralFees(blockData, txs);
|
|
565
|
+
await tx.run(UPSERT.into(CardanoODataService_1.Block).entries((0, mappers_1.mapBlock)(blockData, epoch)));
|
|
499
566
|
// Accumulate rows across the whole block, then one bulk UPSERT per table.
|
|
500
567
|
// NUL safety (PostgreSQL rejects U+0000 in text/JSON) is enforced for every write
|
|
501
568
|
// of this plugin by the db-level hook in srv/utils/db-sanitize.ts, not per call site.
|
|
@@ -505,6 +572,9 @@ class CardanoIndexer {
|
|
|
505
572
|
const outputRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputs)(t.hash, t.outputs ?? []));
|
|
506
573
|
const outputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputAssets)(t.hash, t.outputs ?? []));
|
|
507
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) : [];
|
|
508
578
|
if (txRows.length)
|
|
509
579
|
await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRows));
|
|
510
580
|
if (inputRows.length)
|
|
@@ -517,7 +587,16 @@ class CardanoIndexer {
|
|
|
517
587
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
|
|
518
588
|
if (metadataRows.length)
|
|
519
589
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
|
|
520
|
-
|
|
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`);
|
|
521
600
|
}
|
|
522
601
|
/**
|
|
523
602
|
* Backfill input address/amount for chain-sync transactions whose inputs are bare
|
|
@@ -582,6 +661,269 @@ class CardanoIndexer {
|
|
|
582
661
|
input.amount = amt;
|
|
583
662
|
}
|
|
584
663
|
}
|
|
664
|
+
/**
|
|
665
|
+
* Settle the fee of phase-2-invalid transactions and the block total that follows from it.
|
|
666
|
+
*
|
|
667
|
+
* A failed script phase does not pay the fee declared in the body: the ledger consumes the
|
|
668
|
+
* collateral instead, i.e. the collateral inputs minus the collateral return. The Ogmios
|
|
669
|
+
* mapper already uses the body's `total_collateral` when it declares one; what is left are
|
|
670
|
+
* the transactions without it, and those need the collateral inputs that resolveInputs()
|
|
671
|
+
* has just filled in.
|
|
672
|
+
*
|
|
673
|
+
* A collateral input the crawler cannot resolve — spent from an output produced before the
|
|
674
|
+
* crawl start, so no row exists locally — would make the sum silently too small. The
|
|
675
|
+
* declared fee is kept in that case and the transaction is logged: a value that is wrong in
|
|
676
|
+
* a known, named way beats one that looks derived but is short by an unknown amount.
|
|
677
|
+
*
|
|
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.
|
|
682
|
+
*/
|
|
683
|
+
applyCollateralFees(blockData, txs) {
|
|
684
|
+
const lovelaceOf = (amount) => BigInt(amount?.find(a => a.unit === 'lovelace')?.quantity ?? '0');
|
|
685
|
+
let corrected = false;
|
|
686
|
+
for (const t of txs) {
|
|
687
|
+
// totalCollateral set = the mapper already put the charged amount in `fee`
|
|
688
|
+
if (!t.spendsCollaterals || t.totalCollateral != null)
|
|
689
|
+
continue;
|
|
690
|
+
const collateral = (t.inputs ?? []).filter(i => i.isCollateral);
|
|
691
|
+
if (!collateral.length)
|
|
692
|
+
continue; // nothing to derive from — leave the declared fee
|
|
693
|
+
const unresolved = collateral.find(i => !i.address);
|
|
694
|
+
if (unresolved) {
|
|
695
|
+
logger.warn(`collateral fee for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed ` +
|
|
696
|
+
`— keeping the declared fee ${t.fee}, which understates what the ledger charged`);
|
|
697
|
+
continue;
|
|
698
|
+
}
|
|
699
|
+
const consumed = collateral.reduce((sum, i) => sum + lovelaceOf(i.amount), 0n);
|
|
700
|
+
const returned = (t.outputs ?? [])
|
|
701
|
+
.filter(o => o.isCollateral)
|
|
702
|
+
.reduce((sum, o) => sum + lovelaceOf(o.amount), 0n);
|
|
703
|
+
const charged = consumed - returned;
|
|
704
|
+
if (charged < 0n) {
|
|
705
|
+
logger.warn(`collateral fee for ${t.hash}: return ${returned} exceeds collateral ${consumed} ` +
|
|
706
|
+
`— keeping the declared fee ${t.fee}`);
|
|
707
|
+
continue;
|
|
708
|
+
}
|
|
709
|
+
t.fee = charged.toString();
|
|
710
|
+
corrected = true;
|
|
711
|
+
}
|
|
712
|
+
if (corrected) {
|
|
713
|
+
blockData.fees = txs.reduce((sum, t) => sum + BigInt(t.fee || 0), 0n).toString();
|
|
714
|
+
}
|
|
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
|
+
}
|
|
585
927
|
/**
|
|
586
928
|
* Index & return the epoch information data
|
|
587
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. */
|
|
@@ -71,9 +99,23 @@ export declare class CardanoCrawler {
|
|
|
71
99
|
/** Chain-sync callback promises outlive openChainSync(); stop() explicitly drains them. */
|
|
72
100
|
private readonly inFlightCallbacks;
|
|
73
101
|
private haltPromise;
|
|
102
|
+
/**
|
|
103
|
+
* Set when a chain-sync frame could not be parsed at all. The stream cannot deliver that
|
|
104
|
+
* block, so the ingest loop takes it through the paginating backend and then reopens
|
|
105
|
+
* chain-sync — see runIngestPipeline().
|
|
106
|
+
*/
|
|
107
|
+
private frameFailure;
|
|
108
|
+
/** Resolves the ingest loop's wait for the current chain-sync stream to end. */
|
|
109
|
+
private streamEnded;
|
|
74
110
|
private finalStatus;
|
|
75
111
|
/** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
|
|
76
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;
|
|
77
119
|
private leaseHeld;
|
|
78
120
|
private leaseHeartbeat;
|
|
79
121
|
private leaseWake;
|
|
@@ -118,6 +160,22 @@ export declare class CardanoCrawler {
|
|
|
118
160
|
/** Bound a direct backend call — these bypass the client's timeout/breaker layer. */
|
|
119
161
|
private withTimeout;
|
|
120
162
|
private runChainSync;
|
|
163
|
+
/** Read and clear the pending frame failure, so each stream starts from a clean slate. */
|
|
164
|
+
private takeFrameFailure;
|
|
165
|
+
/**
|
|
166
|
+
* Can this unparseable frame be worked around by fetching the block over HTTP instead?
|
|
167
|
+
*
|
|
168
|
+
* Requires a height to walk to, a paginating backend to walk with, and an operator who has
|
|
169
|
+
* not pinned the source to 'ogmios' — that setting means chain-sync only, and silently
|
|
170
|
+
* degrading to the weaker pagination reorg handling would defeat the point of it.
|
|
171
|
+
*/
|
|
172
|
+
private canDegradeToPagination;
|
|
173
|
+
/**
|
|
174
|
+
* End the chain-sync stream and hand control back to the ingest loop, which continues on
|
|
175
|
+
* pagination past the offending block. Records the error first, so `lastError` names the
|
|
176
|
+
* block rather than leaving the empty status a crashed process used to leave behind.
|
|
177
|
+
*/
|
|
178
|
+
private degradeToPagination;
|
|
121
179
|
/**
|
|
122
180
|
* Candidate intersection points, NEWEST FIRST: the cursor, then an exponentially
|
|
123
181
|
* spaced ladder of our own already-crawled ancestors, then the configured start
|
|
@@ -133,6 +191,12 @@ export declare class CardanoCrawler {
|
|
|
133
191
|
private buildIntersectionPoints;
|
|
134
192
|
/** Track streamed callbacks because closing a socket does not imply DB callbacks finished. */
|
|
135
193
|
private trackCallback;
|
|
194
|
+
/**
|
|
195
|
+
* @param untilHeight when set, return as soon as the cursor has reached it instead of
|
|
196
|
+
* looping forever. Used to walk past a block the chain-sync stream cannot deliver and
|
|
197
|
+
* then hand back to it — pagination is roughly seven times slower, so staying on it
|
|
198
|
+
* for the rest of a backfill would be a poor trade.
|
|
199
|
+
*/
|
|
136
200
|
private runPagination;
|
|
137
201
|
/**
|
|
138
202
|
* Pagination reorg recovery: walk back by height comparing the on-chain block hash with
|
|
@@ -148,6 +212,30 @@ export declare class CardanoCrawler {
|
|
|
148
212
|
* @returns true when the block was persisted, false when the crawler was stopped
|
|
149
213
|
*/
|
|
150
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;
|
|
151
239
|
/**
|
|
152
240
|
* Handle a chain rollback: in one transaction, delete every block after the fork point
|
|
153
241
|
* and exactly the transactions belonging to those blocks (plus their child rows), reset
|