@odatano/core 1.11.0 → 2.0.0-rc.10

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.
Files changed (133) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +255 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +177 -0
  4. package/@cds-models/CardanoIndexerService/index.js +27 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +693 -2172
  6. package/@cds-models/CardanoODataService/index.js +88 -390
  7. package/@cds-models/CardanoSignService/index.d.ts +448 -1576
  8. package/@cds-models/CardanoSignService/index.js +62 -293
  9. package/@cds-models/CardanoTransactionService/index.d.ts +437 -1494
  10. package/@cds-models/CardanoTransactionService/index.js +60 -271
  11. package/@cds-models/CardanoWorkerService/index.d.ts +224 -0
  12. package/@cds-models/CardanoWorkerService/index.js +32 -0
  13. package/@cds-models/_/index.d.ts +70 -40
  14. package/@cds-models/_/index.js +17 -32
  15. package/@cds-models/cds/outbox/index.d.ts +28 -0
  16. package/@cds-models/index.d.ts +225 -522
  17. package/@cds-models/index.js +35 -218
  18. package/@cds-models/odatano/cardano/index.d.ts +919 -2884
  19. package/@cds-models/odatano/cardano/index.js +115 -536
  20. package/@cds-models/sap/common/index.d.ts +196 -600
  21. package/@cds-models/sap/common/index.js +28 -269
  22. package/README.md +194 -102
  23. package/db/schema.cds +388 -1
  24. package/db/types.cds +48 -0
  25. package/package.json +48 -33
  26. package/src/index.d.ts +7 -1
  27. package/src/index.js +30 -2
  28. package/src/plugin.js +33 -20
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +21 -2
  30. package/srv/blockchain/backends/blockfrost-backend.js +69 -25
  31. package/srv/blockchain/backends/cardano-backend.d.ts +69 -0
  32. package/srv/blockchain/backends/cardano-backend.js +13 -0
  33. package/srv/blockchain/backends/koios-backend.d.ts +26 -2
  34. package/srv/blockchain/backends/koios-backend.js +148 -25
  35. package/srv/blockchain/backends/ogmios-backend.d.ts +60 -9
  36. package/srv/blockchain/backends/ogmios-backend.js +326 -10
  37. package/srv/blockchain/cardano-client.d.ts +19 -0
  38. package/srv/blockchain/cardano-client.js +36 -0
  39. package/srv/blockchain/cardano-indexer.d.ts +50 -1
  40. package/srv/blockchain/cardano-indexer.js +193 -0
  41. package/srv/blockchain/crawler/crawler.d.ts +176 -0
  42. package/srv/blockchain/crawler/crawler.js +744 -0
  43. package/srv/blockchain/crawler/hooks.d.ts +43 -0
  44. package/srv/blockchain/crawler/hooks.js +62 -0
  45. package/srv/blockchain/crawler/index.d.ts +35 -0
  46. package/srv/blockchain/crawler/index.js +168 -0
  47. package/srv/blockchain/crawler/sync-state.d.ts +106 -0
  48. package/srv/blockchain/crawler/sync-state.js +287 -0
  49. package/srv/blockchain/signing/hsm-signer.d.ts +45 -0
  50. package/srv/blockchain/signing/hsm-signer.js +8 -1
  51. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +20 -0
  52. package/srv/blockchain/transaction-building/buildooor-tx.js +104 -20
  53. package/srv/blockchain/wallet-worker/build-request.d.ts +26 -0
  54. package/srv/blockchain/wallet-worker/build-request.js +370 -0
  55. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +117 -0
  56. package/srv/blockchain/wallet-worker/confirmation-tracker.js +290 -0
  57. package/srv/blockchain/wallet-worker/index.d.ts +14 -0
  58. package/srv/blockchain/wallet-worker/index.js +80 -0
  59. package/srv/blockchain/wallet-worker/job-store.d.ts +272 -0
  60. package/srv/blockchain/wallet-worker/job-store.js +597 -0
  61. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +43 -0
  62. package/srv/blockchain/wallet-worker/lease-heartbeat.js +99 -0
  63. package/srv/blockchain/wallet-worker/signers.d.ts +57 -0
  64. package/srv/blockchain/wallet-worker/signers.js +131 -0
  65. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +145 -0
  66. package/srv/blockchain/wallet-worker/wallet-worker.js +542 -0
  67. package/srv/cardano-agent-service.cds +150 -0
  68. package/srv/cardano-agent-service.d.ts +2 -0
  69. package/srv/cardano-agent-service.js +16 -0
  70. package/srv/cardano-indexer-service.cds +106 -0
  71. package/srv/cardano-indexer-service.d.ts +2 -0
  72. package/srv/cardano-indexer-service.js +79 -0
  73. package/srv/cardano-service.js +79 -4
  74. package/srv/cardano-sign-service.cds +200 -180
  75. package/srv/cardano-tx-service.cds +32 -26
  76. package/srv/cardano-tx-service.d.ts +1 -11
  77. package/srv/cardano-tx-service.js +107 -200
  78. package/srv/cardano-worker-service.cds +125 -0
  79. package/srv/cardano-worker-service.d.ts +2 -0
  80. package/srv/cardano-worker-service.js +199 -0
  81. package/srv/server.d.ts +34 -2
  82. package/srv/server.js +246 -36
  83. package/srv/utils/agent-grants-config.d.ts +65 -0
  84. package/srv/utils/agent-grants-config.js +148 -0
  85. package/srv/utils/agent-grants.d.ts +314 -0
  86. package/srv/utils/agent-grants.js +821 -0
  87. package/srv/utils/agent-token-auth.d.ts +19 -0
  88. package/srv/utils/agent-token-auth.js +81 -0
  89. package/srv/utils/collections.d.ts +13 -0
  90. package/srv/utils/collections.js +24 -0
  91. package/srv/utils/crypto.d.ts +16 -0
  92. package/srv/utils/crypto.js +75 -0
  93. package/srv/utils/db-sanitize.d.ts +40 -0
  94. package/srv/utils/db-sanitize.js +98 -0
  95. package/srv/utils/error-codes.d.ts +6 -0
  96. package/srv/utils/error-codes.js +6 -0
  97. package/srv/utils/errors.d.ts +12 -0
  98. package/srv/utils/errors.js +45 -0
  99. package/srv/utils/liveness.d.ts +23 -0
  100. package/srv/utils/liveness.js +49 -0
  101. package/srv/utils/mappers.d.ts +27 -0
  102. package/srv/utils/mappers.js +80 -10
  103. package/srv/utils/rate-limiter.d.ts +57 -0
  104. package/srv/utils/rate-limiter.js +126 -0
  105. package/srv/utils/service-events.d.ts +26 -0
  106. package/srv/utils/service-events.js +46 -0
  107. package/srv/utils/tx-request-parsers.d.ts +71 -0
  108. package/srv/utils/tx-request-parsers.js +202 -0
  109. package/srv/utils/tx-utils.d.ts +2 -1
  110. package/srv/utils/tx-utils.js +3 -2
  111. package/srv/utils/types.d.ts +17 -1
  112. package/@cds-models/CardanoODataService/index.d.ts.map +0 -1
  113. package/@cds-models/CardanoODataService/index.js.map +0 -1
  114. package/@cds-models/CardanoODataService/index.ts +0 -776
  115. package/@cds-models/CardanoSignService/index.d.ts.map +0 -1
  116. package/@cds-models/CardanoSignService/index.js.map +0 -1
  117. package/@cds-models/CardanoSignService/index.ts +0 -569
  118. package/@cds-models/CardanoTransactionService/index.d.ts.map +0 -1
  119. package/@cds-models/CardanoTransactionService/index.js.map +0 -1
  120. package/@cds-models/CardanoTransactionService/index.ts +0 -526
  121. package/@cds-models/_/index.d.ts.map +0 -1
  122. package/@cds-models/_/index.js.map +0 -1
  123. package/@cds-models/_/index.ts +0 -96
  124. package/@cds-models/cds/outbox/index.ts +0 -27
  125. package/@cds-models/index.d.ts.map +0 -1
  126. package/@cds-models/index.js.map +0 -1
  127. package/@cds-models/index.ts +0 -245
  128. package/@cds-models/odatano/cardano/index.d.ts.map +0 -1
  129. package/@cds-models/odatano/cardano/index.js.map +0 -1
  130. package/@cds-models/odatano/cardano/index.ts +0 -789
  131. package/@cds-models/sap/common/index.d.ts.map +0 -1
  132. package/@cds-models/sap/common/index.js.map +0 -1
  133. package/@cds-models/sap/common/index.ts +0 -249
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Crawler event hooks (v2.1).
3
+ *
4
+ * Small listener registry that lets other subsystems (currently the wallet-worker
5
+ * confirmation tracker) observe crawler progress without the crawler importing
6
+ * them (dependency direction stays crawler ← consumer). The crawler emits:
7
+ * - `blockIndexed` after each successfully persisted block (with its tx hashes), and
8
+ * - `reorg` after a completed rollback (with the fork slot).
9
+ *
10
+ * Listener failures are logged and swallowed — a broken consumer must never
11
+ * stop the crawler.
12
+ */
13
+ export interface BlockIndexedEvent {
14
+ hash: string;
15
+ slot: number | null;
16
+ height: number | null;
17
+ txHashes: string[];
18
+ /** Latest known chain tip at the time of indexing (when the source reports one). */
19
+ tipSlot: number | null;
20
+ tipHeight: number | null;
21
+ }
22
+ export interface ReorgEvent {
23
+ /** Absolute slot of the fork point — everything after it was rolled back. */
24
+ forkSlot: number;
25
+ /** How many blocks the rollback removed (0 when the fork was already the tip). */
26
+ blocksRolledBack?: number;
27
+ /**
28
+ * Block height of the fork point, when known. Listeners tracking confirmation
29
+ * depth must clamp their tip to this — the pre-fork tip height no longer exists.
30
+ */
31
+ forkHeight: number | null;
32
+ }
33
+ export type BlockIndexedListener = (event: BlockIndexedEvent) => void;
34
+ export type ReorgListener = (event: ReorgEvent) => void;
35
+ export declare function registerBlockIndexedListener(listener: BlockIndexedListener): void;
36
+ export declare function unregisterBlockIndexedListener(listener: BlockIndexedListener): void;
37
+ export declare function registerReorgListener(listener: ReorgListener): void;
38
+ export declare function unregisterReorgListener(listener: ReorgListener): void;
39
+ /** True when at least one consumer observes crawler progress. */
40
+ export declare function hasBlockIndexedListeners(): boolean;
41
+ export declare function emitBlockIndexed(event: BlockIndexedEvent): void;
42
+ export declare function emitReorg(event: ReorgEvent): void;
43
+ //# sourceMappingURL=hooks.d.ts.map
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.registerBlockIndexedListener = registerBlockIndexedListener;
7
+ exports.unregisterBlockIndexedListener = unregisterBlockIndexedListener;
8
+ exports.registerReorgListener = registerReorgListener;
9
+ exports.unregisterReorgListener = unregisterReorgListener;
10
+ exports.hasBlockIndexedListeners = hasBlockIndexedListeners;
11
+ exports.emitBlockIndexed = emitBlockIndexed;
12
+ exports.emitReorg = emitReorg;
13
+ const cds_1 = __importDefault(require("@sap/cds"));
14
+ const service_events_1 = require("../../utils/service-events");
15
+ const logger = cds_1.default.log('CardanoCrawler');
16
+ const blockListeners = new Set();
17
+ const reorgListeners = new Set();
18
+ function registerBlockIndexedListener(listener) {
19
+ blockListeners.add(listener);
20
+ }
21
+ function unregisterBlockIndexedListener(listener) {
22
+ blockListeners.delete(listener);
23
+ }
24
+ function registerReorgListener(listener) {
25
+ reorgListeners.add(listener);
26
+ }
27
+ function unregisterReorgListener(listener) {
28
+ reorgListeners.delete(listener);
29
+ }
30
+ /** True when at least one consumer observes crawler progress. */
31
+ function hasBlockIndexedListeners() {
32
+ return blockListeners.size > 0;
33
+ }
34
+ function emitBlockIndexed(event) {
35
+ // Mirrored onto the CAP service so external consumers can subscribe; the
36
+ // in-process registry below stays the fast path for our own subsystems.
37
+ (0, service_events_1.emitServiceEvent)('CardanoIndexerService', 'blockIndexed', { ...event });
38
+ for (const listener of blockListeners) {
39
+ try {
40
+ listener(event);
41
+ }
42
+ catch (err) {
43
+ logger.warn('blockIndexed listener failed (ignored):', err);
44
+ }
45
+ }
46
+ }
47
+ function emitReorg(event) {
48
+ (0, service_events_1.emitServiceEvent)('CardanoIndexerService', 'reorg', {
49
+ forkSlot: event.forkSlot,
50
+ forkHeight: event.forkHeight,
51
+ blocksRolledBack: event.blocksRolledBack ?? 0,
52
+ });
53
+ for (const listener of reorgListeners) {
54
+ try {
55
+ listener(event);
56
+ }
57
+ catch (err) {
58
+ logger.warn('reorg listener failed (ignored):', err);
59
+ }
60
+ }
61
+ }
62
+ //# sourceMappingURL=hooks.js.map
@@ -0,0 +1,35 @@
1
+ import type { CardanoClient } from '../cardano-client';
2
+ import type { CardanoIndexer } from '../cardano-indexer';
3
+ import { CardanoCrawler, type CrawlerConfig } from './crawler';
4
+ /**
5
+ * Delay before the next standby start attempt. A healthy standby (a lease loser, or
6
+ * the leader's own no-op tick) retries every 5 s. Only after the crawler in THIS
7
+ * process halted with an error does the shared cursor's consecutiveErrors drive an
8
+ * exponential backoff (5 s, 10 s, 20 s ... capped at 5 min), so a block the crawler
9
+ * cannot persist no longer re-syncs the chain-sync stream every 5 s. A standby that
10
+ * never held the lease is not slowed down by the leader's streak: failover stays 5 s.
11
+ */
12
+ export declare function standbyDelayMs(consecutiveErrors: number): number;
13
+ export interface StartCrawlerDeps {
14
+ client: CardanoClient;
15
+ indexer: CardanoIndexer;
16
+ network: string;
17
+ config: CrawlerConfig;
18
+ }
19
+ /**
20
+ * Start the crawler (idempotent — a no-op if one is already running). Fire-and-forget:
21
+ * returns once the ingest pipeline is launched, not when catch-up completes.
22
+ */
23
+ export declare function startCrawler(deps: StartCrawlerDeps, resumeCluster?: boolean): Promise<void>;
24
+ /**
25
+ * Stop the local crawler. `pauseCluster=true` additionally fences every instance via
26
+ * shared DB intent; ordinary app shutdown leaves the desired state intact for failover.
27
+ */
28
+ export declare function stopCrawler(pauseCluster?: boolean): Promise<void>;
29
+ /** Whether a crawler is currently running. */
30
+ export declare function isCrawlerRunning(): boolean;
31
+ /** The active crawler instance, or null. */
32
+ export declare function getCrawler(): CardanoCrawler | null;
33
+ /** Read the lease in a fresh transaction (control actions must not use a stale request snapshot). */
34
+ export declare function isCrawlerRunningInCluster(): Promise<boolean>;
35
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,168 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.standbyDelayMs = standbyDelayMs;
7
+ exports.startCrawler = startCrawler;
8
+ exports.stopCrawler = stopCrawler;
9
+ exports.isCrawlerRunning = isCrawlerRunning;
10
+ exports.getCrawler = getCrawler;
11
+ exports.isCrawlerRunningInCluster = isCrawlerRunningInCluster;
12
+ const cds_1 = __importDefault(require("@sap/cds"));
13
+ const node_crypto_1 = require("node:crypto");
14
+ const crawler_1 = require("./crawler");
15
+ const sync_state_1 = require("./sync-state");
16
+ const logger = cds_1.default.log('CardanoCrawler');
17
+ /**
18
+ * Module-level singleton lifecycle for the chain crawler. Mirrors NIGHTGATE's
19
+ * srv/crawler/index.ts: one active crawler per process, started fire-and-forget from
20
+ * the server's `served` hook and controlled (pause/resume/status) via the indexer service.
21
+ */
22
+ let active = null;
23
+ let lifecycleQueue = Promise.resolve();
24
+ let standbyDeps = null;
25
+ let standbyTimer = null;
26
+ let standbyGeneration = 0;
27
+ const STANDBY_RETRY_MS = 5_000;
28
+ const STANDBY_MAX_BACKOFF_MS = 5 * 60_000;
29
+ /**
30
+ * Delay before the next standby start attempt. A healthy standby (a lease loser, or
31
+ * the leader's own no-op tick) retries every 5 s. Only after the crawler in THIS
32
+ * process halted with an error does the shared cursor's consecutiveErrors drive an
33
+ * exponential backoff (5 s, 10 s, 20 s ... capped at 5 min), so a block the crawler
34
+ * cannot persist no longer re-syncs the chain-sync stream every 5 s. A standby that
35
+ * never held the lease is not slowed down by the leader's streak: failover stays 5 s.
36
+ */
37
+ function standbyDelayMs(consecutiveErrors) {
38
+ if (!Number.isFinite(consecutiveErrors) || consecutiveErrors <= 1)
39
+ return STANDBY_RETRY_MS;
40
+ return Math.min(STANDBY_MAX_BACKOFF_MS, STANDBY_RETRY_MS * 2 ** Math.min(consecutiveErrors - 1, 10));
41
+ }
42
+ /**
43
+ * Start the crawler (idempotent — a no-op if one is already running). Fire-and-forget:
44
+ * returns once the ingest pipeline is launched, not when catch-up completes.
45
+ */
46
+ async function startCrawler(deps, resumeCluster = false) {
47
+ const generation = ++standbyGeneration;
48
+ standbyDeps = deps;
49
+ if (standbyTimer) {
50
+ clearTimeout(standbyTimer);
51
+ standbyTimer = null;
52
+ }
53
+ scheduleStandby(generation);
54
+ return startCrawlerAttempt(deps, resumeCluster, generation);
55
+ }
56
+ async function startCrawlerAttempt(deps, resumeCluster, generation) {
57
+ return serializeLifecycle(async () => {
58
+ if (generation !== standbyGeneration)
59
+ return;
60
+ if (resumeCluster) {
61
+ await cds_1.default.tx((tx) => (0, sync_state_1.setCrawlerDesiredRunning)(tx, true));
62
+ }
63
+ if (active?.isRunning()) {
64
+ logger.debug('startCrawler: already running');
65
+ return;
66
+ }
67
+ if (active) {
68
+ const previous = active;
69
+ await previous.stop();
70
+ if (active === previous)
71
+ active = null;
72
+ }
73
+ const candidate = new crawler_1.CardanoCrawler(deps.client, deps.indexer, deps.network, deps.config, `${process.pid}:${(0, node_crypto_1.randomUUID)()}`);
74
+ active = candidate;
75
+ try {
76
+ await candidate.start();
77
+ }
78
+ catch (err) {
79
+ if (active === candidate)
80
+ active = null;
81
+ throw err;
82
+ }
83
+ // A lease loser stays in standby, not as a misleading process-local singleton.
84
+ if (!candidate.isRunning() && active === candidate)
85
+ active = null;
86
+ });
87
+ }
88
+ /**
89
+ * Stop the local crawler. `pauseCluster=true` additionally fences every instance via
90
+ * shared DB intent; ordinary app shutdown leaves the desired state intact for failover.
91
+ */
92
+ async function stopCrawler(pauseCluster = false) {
93
+ ++standbyGeneration; // invalidate callbacks that already left the timer queue
94
+ standbyDeps = null;
95
+ if (standbyTimer) {
96
+ clearTimeout(standbyTimer);
97
+ standbyTimer = null;
98
+ }
99
+ return serializeLifecycle(async () => {
100
+ if (pauseCluster) {
101
+ await cds_1.default.tx((tx) => (0, sync_state_1.setCrawlerDesiredRunning)(tx, false));
102
+ }
103
+ const crawler = active;
104
+ if (!crawler)
105
+ return;
106
+ await crawler.stop();
107
+ // A queued/re-entrant start can never be erased by an older stop continuation.
108
+ if (active === crawler)
109
+ active = null;
110
+ });
111
+ }
112
+ /** Whether a crawler is currently running. */
113
+ function isCrawlerRunning() {
114
+ return active?.isRunning() ?? false;
115
+ }
116
+ /** The active crawler instance, or null. */
117
+ function getCrawler() {
118
+ return active;
119
+ }
120
+ /** Read the lease in a fresh transaction (control actions must not use a stale request snapshot). */
121
+ async function isCrawlerRunningInCluster() {
122
+ const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
123
+ return (0, sync_state_1.isCrawlerLeaseActive)(cursor);
124
+ }
125
+ function serializeLifecycle(operation) {
126
+ const result = lifecycleQueue.then(operation, operation);
127
+ lifecycleQueue = result.catch(() => undefined);
128
+ return result;
129
+ }
130
+ /** Keep non-leader instances warm so an expired/released lease fails over automatically. */
131
+ function scheduleStandby(generation, delayMs = STANDBY_RETRY_MS) {
132
+ if (standbyTimer || !standbyDeps)
133
+ return;
134
+ standbyTimer = setTimeout(() => {
135
+ standbyTimer = null;
136
+ if (generation !== standbyGeneration)
137
+ return;
138
+ const deps = standbyDeps;
139
+ if (!deps)
140
+ return;
141
+ // Local evidence only, taken BEFORE the attempt replaces `active`.
142
+ const failedHere = active?.haltedWithError() ?? false;
143
+ void startCrawlerAttempt(deps, false, generation)
144
+ .catch((err) => logger.error('standby lease attempt failed:', err))
145
+ .then(() => nextStandbyDelay(failedHere))
146
+ .then((delay) => {
147
+ if (generation === standbyGeneration)
148
+ scheduleStandby(generation, delay);
149
+ });
150
+ }, delayMs);
151
+ standbyTimer.unref?.();
152
+ }
153
+ /**
154
+ * Backoff from the shared cursor's error streak after a local failure; the base delay
155
+ * otherwise — a healthy tick costs no DB round-trip.
156
+ */
157
+ async function nextStandbyDelay(failedHere) {
158
+ if (!failedHere)
159
+ return STANDBY_RETRY_MS;
160
+ try {
161
+ const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
162
+ return standbyDelayMs(cursor?.consecutiveErrors ?? 0);
163
+ }
164
+ catch {
165
+ return STANDBY_RETRY_MS;
166
+ }
167
+ }
168
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,106 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ /**
3
+ * Chain crawler cursor helpers (v2.0 pre-sync).
4
+ *
5
+ * `CardanoSyncState` is a singleton row (key = SINGLETON_ID) that records how far
6
+ * the crawler has indexed the chain, so a restart resumes instead of re-crawling.
7
+ *
8
+ * NOTE (CAP 10): Integer64 / Decimal columns are read back from SQLite/HANA as
9
+ * STRINGS, not JS numbers — the same change that makes them strings over OData.
10
+ * Every read here therefore coerces numeric fields with `num()`; callers get a
11
+ * clean numeric `SyncCursor` and never have to think about it.
12
+ */
13
+ export declare const SINGLETON_ID = "SINGLETON";
14
+ /** Circuit-breaker threshold: pause crawling after this many back-to-back failures. */
15
+ export declare const MAX_CONSECUTIVE_ERRORS = 10;
16
+ /** A short, renewable DB lease prevents two app instances from advancing one cursor. */
17
+ export declare const CRAWLER_LEASE_TTL_MS = 15000;
18
+ export type CrawlSyncStatusValue = 'stopped' | 'syncing' | 'synced' | 'error';
19
+ /** A chain point the crawler can start from or roll back to. */
20
+ export interface CrawlPoint {
21
+ slot: number;
22
+ hash: string;
23
+ height?: number;
24
+ }
25
+ /** Normalized, number-typed view of the cursor row (numeric fields already coerced). */
26
+ export interface SyncCursor {
27
+ network: string | null;
28
+ startSlot: number | null;
29
+ startBlockHash: string | null;
30
+ lastSlot: number;
31
+ lastBlockHash: string | null;
32
+ lastHeight: number;
33
+ tipSlot: number | null;
34
+ tipHeight: number | null;
35
+ syncStatus: CrawlSyncStatusValue;
36
+ consecutiveErrors: number;
37
+ desiredRunning: boolean;
38
+ leaseOwner: string | null;
39
+ leaseUntil: string | null;
40
+ }
41
+ /**
42
+ * Idempotently ensure the singleton cursor row exists and return it.
43
+ * On first call (fresh DB) the row is created with the configured start point
44
+ * (if given) and status 'stopped'. Subsequent calls just return the current row.
45
+ * Safe to call from both the crawler and the control service.
46
+ */
47
+ export declare function ensureSyncStateSingleton(db: CapTransaction, network: string, start?: CrawlPoint): Promise<SyncCursor>;
48
+ /** Read the current cursor, or null if it has not been initialized yet. */
49
+ export declare function readCursor(db: CapTransaction): Promise<SyncCursor | null>;
50
+ /** Whether the shared lease currently represents a live cluster-wide crawler. */
51
+ export declare function isCrawlerLeaseActive(cursor: SyncCursor | null, now?: Date): boolean;
52
+ /**
53
+ * Atomically acquire an expired/unowned lease with compare-and-swap semantics.
54
+ * The post-update read is intentional: CAP adapters consistently return the row
55
+ * for SELECT, whereas affected-row return shapes differ between SQLite and HANA.
56
+ */
57
+ export declare function tryAcquireCrawlerLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
58
+ /**
59
+ * Renew/fence a lease. Call this inside the same transaction as every crawler write:
60
+ * the conditional UPDATE serializes a former leader against a newly elected one.
61
+ */
62
+ export declare function renewCrawlerLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
63
+ /**
64
+ * Release only the caller's lease; a stale process can never clear a successor.
65
+ *
66
+ * `pauseCluster` clears `desiredRunning`, which no restart undoes — every instance
67
+ * then refuses to start until an operator calls resumeCrawler. Reserve it for
68
+ * failures a restart genuinely cannot fix (misconfiguration, no resume point). A
69
+ * crashed stream, a provider outage or a node restart must NOT latch: those are
70
+ * exactly the cases where coming back up should resume the pre-sync by itself.
71
+ */
72
+ export declare function releaseCrawlerLease(db: CapTransaction, owner: string, status: CrawlSyncStatusValue, pauseCluster?: boolean): Promise<void>;
73
+ /**
74
+ * Persist the pause/resume intent shared by every app instance. Resuming also clears
75
+ * the error streak: the operator says the cause is fixed, and a stale streak would
76
+ * otherwise keep the standby backoff at its cap for the first retry.
77
+ */
78
+ export declare function setCrawlerDesiredRunning(db: CapTransaction, desiredRunning: boolean): Promise<void>;
79
+ /**
80
+ * Latch the cluster off because of a poison block (a block whose data the database
81
+ * deterministically rejects). Deliberately NOT lease-scoped, unlike releaseCrawlerLease:
82
+ * the poison is a property of the block, not of the instance that observed it, and
83
+ * that instance may have lost its lease while the failure was being recorded. Only
84
+ * an operator's resumeCrawler brings the crawler back.
85
+ */
86
+ export declare function latchPoisonBlock(db: CapTransaction, message: string): Promise<void>;
87
+ /**
88
+ * Advance the cursor to a freshly-indexed block. Sets the status (default 'syncing';
89
+ * pass 'synced' when the block is at the tip), clears the error streak, and refreshes
90
+ * lastIndexedAt. Optionally records the latest known tip (for progress).
91
+ */
92
+ export declare function advanceCursor(db: CapTransaction, block: CrawlPoint, tip?: {
93
+ slot: number;
94
+ height?: number;
95
+ }, status?: CrawlSyncStatusValue): Promise<void>;
96
+ /** Reset the cursor to a rollback point (used by reorg handling). */
97
+ export declare function resetCursorTo(db: CapTransaction, point: CrawlPoint): Promise<void>;
98
+ /** Set the crawler status (e.g. 'synced' when caught up, 'stopped' on shutdown). */
99
+ export declare function setSyncStatus(db: CapTransaction, status: CrawlSyncStatusValue, pauseCluster?: boolean): Promise<void>;
100
+ /**
101
+ * Record a crawler error. Increments the consecutive-error counter and flips status
102
+ * to 'error' once the circuit-breaker threshold is reached. Returns the new streak
103
+ * length so the caller can decide whether to back off / stop.
104
+ */
105
+ export declare function recordError(db: CapTransaction, err: unknown, leaseOwner?: string): Promise<number>;
106
+ //# sourceMappingURL=sync-state.d.ts.map