envio 3.12.1 → 3.13.0-alpha.0
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/package.json +6 -6
- package/src/BatchProcessing.res +9 -9
- package/src/BatchProcessing.res.mjs +5 -5
- package/src/Bin.res +24 -17
- package/src/Bin.res.mjs +5 -0
- package/src/ChainFetching.res +24 -10
- package/src/ChainFetching.res.mjs +8 -3
- package/src/ChainState.res +43 -0
- package/src/ChainState.res.mjs +43 -0
- package/src/ChainState.resi +2 -0
- package/src/Config.res +35 -0
- package/src/Config.res.mjs +39 -0
- package/src/Core.res +4 -0
- package/src/Core.res.mjs +4 -0
- package/src/CrossChainState.res +60 -3
- package/src/CrossChainState.res.mjs +38 -4
- package/src/CrossChainState.resi +10 -1
- package/src/Env.res +4 -0
- package/src/IndexerLoop.res +2 -0
- package/src/IndexerLoop.res.mjs +1 -0
- package/src/IndexerState.res +41 -1
- package/src/IndexerState.res.mjs +43 -4
- package/src/IndexerState.resi +10 -0
- package/src/Logging.res +38 -6
- package/src/Logging.res.mjs +32 -5
- package/src/Main.res +131 -268
- package/src/Main.res.mjs +28 -152
- package/src/Metrics.res +263 -102
- package/src/Metrics.res.mjs +227 -48
- package/src/Persistence.res +27 -2
- package/src/Persistence.res.mjs +9 -2
- package/src/PgStorage.res +17 -9
- package/src/PgStorage.res.mjs +11 -8
- package/src/Server.res +181 -0
- package/src/Server.res.mjs +143 -0
- package/src/Supervisor.res +415 -0
- package/src/Supervisor.res.mjs +325 -0
- package/src/TestIndexer.res.mjs +1 -1
- package/src/Worker.res +95 -0
- package/src/Worker.res.mjs +80 -0
- package/src/bindings/NodeJs.res +41 -0
- package/src/db/InternalTable.res +8 -1
- package/src/db/InternalTable.res.mjs +5 -1
- package/src/tui/Tui.res +24 -0
- package/src/tui/Tui.res.mjs +18 -0
- package/src/tui/components/SyncETA.res +12 -6
- package/src/tui/components/SyncETA.res.mjs +12 -8
package/src/Main.res
CHANGED
|
@@ -1,80 +1,3 @@
|
|
|
1
|
-
// The public console/state chain shape. Kept to exactly this field set for
|
|
2
|
-
// backward compatibility with consumers like RACE — new metric fields stay off
|
|
3
|
-
// the HTTP response.
|
|
4
|
-
type chainData = {
|
|
5
|
-
chainId: ChainId.t,
|
|
6
|
-
poweredByHyperSync: bool,
|
|
7
|
-
firstEventBlockNumber: option<int>,
|
|
8
|
-
latestProcessedBlock: option<int>,
|
|
9
|
-
timestampCaughtUpToHeadOrEndblock: option<Date.t>,
|
|
10
|
-
numEventsProcessed: float,
|
|
11
|
-
latestFetchedBlockNumber: int,
|
|
12
|
-
// Need this for API backwards compatibility
|
|
13
|
-
@as("currentBlockHeight")
|
|
14
|
-
knownHeight: int,
|
|
15
|
-
numBatchesFetched: int,
|
|
16
|
-
startBlock: int,
|
|
17
|
-
endBlock: option<int>,
|
|
18
|
-
numAddresses: int,
|
|
19
|
-
}
|
|
20
|
-
@tag("status")
|
|
21
|
-
type state =
|
|
22
|
-
| @as("disabled") Disabled({})
|
|
23
|
-
| @as("initializing") Initializing({})
|
|
24
|
-
| @as("active")
|
|
25
|
-
Active({
|
|
26
|
-
envioVersion: string,
|
|
27
|
-
chains: array<chainData>,
|
|
28
|
-
indexerStartTime: Date.t,
|
|
29
|
-
isPreRegisteringDynamicContracts: bool,
|
|
30
|
-
rollbackOnReorg: bool,
|
|
31
|
-
})
|
|
32
|
-
|
|
33
|
-
let toChainData = (m: Metrics.chainMetrics): chainData => {
|
|
34
|
-
chainId: m.chainId,
|
|
35
|
-
poweredByHyperSync: m.poweredByHyperSync,
|
|
36
|
-
firstEventBlockNumber: m.firstEventBlockNumber,
|
|
37
|
-
latestProcessedBlock: m.latestProcessedBlock,
|
|
38
|
-
timestampCaughtUpToHeadOrEndblock: m.timestampCaughtUpToHeadOrEndblock,
|
|
39
|
-
numEventsProcessed: m.numEventsProcessed,
|
|
40
|
-
latestFetchedBlockNumber: m.latestFetchedBlockNumber,
|
|
41
|
-
knownHeight: m.knownHeight,
|
|
42
|
-
numBatchesFetched: m.numBatchesFetched,
|
|
43
|
-
startBlock: m.startBlock,
|
|
44
|
-
endBlock: m.endBlock,
|
|
45
|
-
numAddresses: m.numAddresses,
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
let chainDataSchema = S.schema((s): chainData => {
|
|
49
|
-
chainId: s.matches(ChainId.schema),
|
|
50
|
-
poweredByHyperSync: s.matches(S.bool),
|
|
51
|
-
firstEventBlockNumber: s.matches(S.option(S.int)),
|
|
52
|
-
latestProcessedBlock: s.matches(S.option(S.int)),
|
|
53
|
-
timestampCaughtUpToHeadOrEndblock: s.matches(S.option(S.datetime(S.string))),
|
|
54
|
-
numEventsProcessed: s.matches(S.float),
|
|
55
|
-
latestFetchedBlockNumber: s.matches(S.int),
|
|
56
|
-
knownHeight: s.matches(S.int),
|
|
57
|
-
numBatchesFetched: s.matches(S.int),
|
|
58
|
-
startBlock: s.matches(S.int),
|
|
59
|
-
endBlock: s.matches(S.option(S.int)),
|
|
60
|
-
numAddresses: s.matches(S.int),
|
|
61
|
-
})
|
|
62
|
-
let stateSchema = S.union([
|
|
63
|
-
S.literal(Disabled({})),
|
|
64
|
-
S.literal(Initializing({})),
|
|
65
|
-
S.schema(s => Active({
|
|
66
|
-
envioVersion: s.matches(S.string),
|
|
67
|
-
chains: s.matches(S.array(chainDataSchema)),
|
|
68
|
-
indexerStartTime: s.matches(S.datetime(S.string)),
|
|
69
|
-
// Keep the field, since Dev Console expects it to be present
|
|
70
|
-
isPreRegisteringDynamicContracts: false,
|
|
71
|
-
rollbackOnReorg: s.matches(S.bool),
|
|
72
|
-
})),
|
|
73
|
-
])
|
|
74
|
-
|
|
75
|
-
// Runtime state lives in the process-wide `EnvioGlobal` record (shared
|
|
76
|
-
// across duplicate envio module instances); the slots are opaque there, so
|
|
77
|
-
// cast them to the real types here.
|
|
78
1
|
let getIndexerState = () =>
|
|
79
2
|
EnvioGlobal.value.indexerState->(Utils.magic: option<unknown> => option<IndexerState.t>)
|
|
80
3
|
let setIndexerState = (state: IndexerState.t) =>
|
|
@@ -488,111 +411,8 @@ let getGlobalIndexer = (): 'indexer => {
|
|
|
488
411
|
Utils.Proxy.make(Utils.Object.createNullObject(), traps)->(Utils.magic: {..} => 'indexer)
|
|
489
412
|
}
|
|
490
413
|
|
|
491
|
-
let startServer = (
|
|
492
|
-
~getMetrics: unit => option<Metrics.t>,
|
|
493
|
-
~envioVersion: string,
|
|
494
|
-
~persistence: Persistence.t,
|
|
495
|
-
~isDevelopmentMode: bool,
|
|
496
|
-
) => {
|
|
497
|
-
open Express
|
|
498
|
-
|
|
499
|
-
let app = make()
|
|
500
|
-
|
|
501
|
-
let consoleCorsMiddleware = (req, res, next) => {
|
|
502
|
-
switch req.headers->Dict.get("origin") {
|
|
503
|
-
| Some(origin) if origin === Env.prodEnvioAppUrl || origin === Env.envioAppUrl =>
|
|
504
|
-
res->setHeader("Access-Control-Allow-Origin", origin)
|
|
505
|
-
| _ => ()
|
|
506
|
-
}
|
|
507
|
-
|
|
508
|
-
res->setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
|
509
|
-
res->setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
|
|
510
|
-
|
|
511
|
-
if req.method === Rest.Options {
|
|
512
|
-
res->sendStatus(200)
|
|
513
|
-
} else {
|
|
514
|
-
next()
|
|
515
|
-
}
|
|
516
|
-
}
|
|
517
|
-
app->useFor("/console", consoleCorsMiddleware)
|
|
518
|
-
app->useFor("/metrics", consoleCorsMiddleware)
|
|
519
|
-
app->useFor("/metrics/runtime", consoleCorsMiddleware)
|
|
520
|
-
|
|
521
|
-
app->get("/healthz", (_req, res) => {
|
|
522
|
-
// this is the machine readable port used in kubernetes to check the health of this service.
|
|
523
|
-
// aditional health information could be added in the future (info about errors, back-offs, etc).
|
|
524
|
-
res->sendStatus(200)
|
|
525
|
-
})
|
|
526
|
-
|
|
527
|
-
app->get("/console/state", (_req, res) => {
|
|
528
|
-
let state = if !isDevelopmentMode {
|
|
529
|
-
Disabled({})
|
|
530
|
-
} else {
|
|
531
|
-
switch getMetrics() {
|
|
532
|
-
| None => Initializing({})
|
|
533
|
-
| Some(metrics) =>
|
|
534
|
-
Active({
|
|
535
|
-
envioVersion,
|
|
536
|
-
chains: metrics.chains->Array.map(toChainData),
|
|
537
|
-
indexerStartTime: metrics.startTime,
|
|
538
|
-
isPreRegisteringDynamicContracts: false,
|
|
539
|
-
rollbackOnReorg: metrics.rollbackEnabled,
|
|
540
|
-
})
|
|
541
|
-
}
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
res->json(state->S.reverseConvertToJsonOrThrow(stateSchema))
|
|
545
|
-
})
|
|
546
|
-
|
|
547
|
-
app->post("/console/syncCache", (_req, res) => {
|
|
548
|
-
if isDevelopmentMode {
|
|
549
|
-
(persistence->Persistence.getInitializedStorageOrThrow).dumpEffectCache()
|
|
550
|
-
->Promise.thenResolve(_ => res->json(Boolean(true)))
|
|
551
|
-
->Promise.ignore
|
|
552
|
-
} else {
|
|
553
|
-
res->json(Boolean(false))
|
|
554
|
-
}
|
|
555
|
-
})
|
|
556
|
-
|
|
557
|
-
Metrics.startRuntimeCollectors()
|
|
558
|
-
|
|
559
|
-
app->get("/metrics", (_req, res) => {
|
|
560
|
-
res->set("Content-Type", Metrics.contentType)
|
|
561
|
-
let _ = res->endWithData(Metrics.collect(~metrics=getMetrics()))
|
|
562
|
-
})
|
|
563
|
-
|
|
564
|
-
app->get("/metrics/runtime", (_req, res) => {
|
|
565
|
-
res->set("Content-Type", Metrics.contentType)
|
|
566
|
-
let _ = res->endWithData(Metrics.collectRuntime())
|
|
567
|
-
})
|
|
568
|
-
|
|
569
|
-
let server = app->listen(Env.serverPort)
|
|
570
|
-
server->Express.onError(err => {
|
|
571
|
-
let code = (err->(Utils.magic: JsExn.t => {..}))["code"]
|
|
572
|
-
if code === "EADDRINUSE" {
|
|
573
|
-
Logging.error(
|
|
574
|
-
`Port ${Env.serverPort->Int.toString} is already in use. To fix this either:` ++
|
|
575
|
-
`\n 1. Kill the process using the port: lsof -ti :${Env.serverPort->Int.toString} | xargs kill -9` ++ `\n 2. Use a different port by setting the ENVIO_INDEXER_PORT environment variable: ENVIO_INDEXER_PORT=9899 envio start`,
|
|
576
|
-
)
|
|
577
|
-
} else {
|
|
578
|
-
Logging.errorWithExn(err, "Failed to start indexer server")
|
|
579
|
-
}
|
|
580
|
-
NodeJs.process->NodeJs.exitWithCode(Failure)
|
|
581
|
-
})
|
|
582
|
-
}
|
|
583
|
-
|
|
584
|
-
type args = {@as("tui-off") tuiOff?: bool}
|
|
585
|
-
|
|
586
|
-
type process
|
|
587
|
-
@val external process: process = "process"
|
|
588
|
-
@get external argv: process => 'a = "argv"
|
|
589
|
-
|
|
590
|
-
type mainArgs = Yargs.parsedArgs<args>
|
|
591
|
-
|
|
592
414
|
// The RPC-stripped public config that the storage layer persists in
|
|
593
415
|
// `envio_info` (on initialize) and validates against (on resume).
|
|
594
|
-
let getEnvioInfo = () => Config.getPublicConfigJson()->Config.stripSensitiveData
|
|
595
|
-
|
|
596
416
|
let migrate = async (~reset) => {
|
|
597
417
|
let config = Config.load()
|
|
598
418
|
let persistence = PgStorage.makePersistenceFromConfig(~config)
|
|
@@ -600,7 +420,7 @@ let migrate = async (~reset) => {
|
|
|
600
420
|
~reset,
|
|
601
421
|
~chainConfigs=config.chainMap->ChainMap.values,
|
|
602
422
|
~contractMapping=config.contractMapping,
|
|
603
|
-
~envioInfo=
|
|
423
|
+
~envioInfo=Config.envioInfo(),
|
|
604
424
|
~resetCommand="envio local db-migrate setup",
|
|
605
425
|
~runCommand=None,
|
|
606
426
|
~lowercaseAddresses=config.lowercaseAddresses,
|
|
@@ -622,6 +442,118 @@ let dropSchema = async () => {
|
|
|
622
442
|
// context, so callers should act on it (exit / re-throw) without logging again.
|
|
623
443
|
exception FatalError(exn)
|
|
624
444
|
|
|
445
|
+
%%private(
|
|
446
|
+
let startIndexer = async (
|
|
447
|
+
~config: Config.t,
|
|
448
|
+
~persistence: option<Persistence.t>=?,
|
|
449
|
+
~reset=false,
|
|
450
|
+
~isTest=false,
|
|
451
|
+
~exitAfterFirstEventBlock=false,
|
|
452
|
+
~patchConfig: option<(Config.t, HandlerRegister.registrationsByChainId) => Config.t>=?,
|
|
453
|
+
) => {
|
|
454
|
+
// A worker reports to its supervisor, which draws for the whole run.
|
|
455
|
+
let shouldUseTui = Tui.shouldUse(~suppressed=isTest || Worker.isEnabled)
|
|
456
|
+
// In per-chain mode every line this process writes belongs to the chains it
|
|
457
|
+
// drives, whether or not a supervisor split the run across processes.
|
|
458
|
+
config->Config.logContext->Option.forEach(Logging.setContext)
|
|
459
|
+
// isDevelopmentMode controls whether the indexer stays alive after all
|
|
460
|
+
// chains finish (keepProcessAlive) and whether the console API is exposed.
|
|
461
|
+
// Set by `envio dev` via the public config's `isDev` field; `envio start`
|
|
462
|
+
// leaves it false so the process exits cleanly when indexing completes.
|
|
463
|
+
let isDevelopmentMode = !isTest && config.isDev
|
|
464
|
+
// Initialized first so the exported indexer value contains state from the
|
|
465
|
+
// database when handler files are loaded (they may access the indexer at
|
|
466
|
+
// module top level).
|
|
467
|
+
let persistence = switch persistence {
|
|
468
|
+
| Some(p) => p
|
|
469
|
+
| None => PgStorage.makePersistenceFromConfig(~config)
|
|
470
|
+
}
|
|
471
|
+
setGlobalPersistence(persistence)
|
|
472
|
+
await persistence->Persistence.initForRun(
|
|
473
|
+
~config,
|
|
474
|
+
~reset,
|
|
475
|
+
~isDevelopmentMode,
|
|
476
|
+
~requireInitialized=config.isolated,
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
// Loads user handler files, which register handler/contractRegister/where
|
|
480
|
+
// state into the global `HandlerRegister` registry as a side effect; this
|
|
481
|
+
// returns that state resolved into per-chain registrations. `config` itself
|
|
482
|
+
// is never mutated by registration — it holds only event definitions.
|
|
483
|
+
let registrationsByChainId = await HandlerLoader.registerAllHandlers(~config)
|
|
484
|
+
let config = if isTest {
|
|
485
|
+
{...config, shouldRollbackOnReorg: false}
|
|
486
|
+
} else {
|
|
487
|
+
config
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
let config = switch patchConfig {
|
|
491
|
+
| Some(patchConfig) => patchConfig(config, registrationsByChainId)
|
|
492
|
+
| None => config
|
|
493
|
+
}
|
|
494
|
+
// The single fatal-error handler, invoked once via IndexerState.errorExit.
|
|
495
|
+
// It logs the failure once (with chain context) and rejects the run wrapped in
|
|
496
|
+
// `FatalError` so callers know it's already logged — `Bin.res` just exits, the
|
|
497
|
+
// test worker unwraps and re-throws it to the parent thread. `runUntilFatalError`
|
|
498
|
+
// only ever rejects: on a clean run it stays pending and the process exits via
|
|
499
|
+
// ExitOnCaughtUp / when the indexer loop drains.
|
|
500
|
+
let onErrorReject = ref(None)
|
|
501
|
+
let runUntilFatalError: promise<unit> = Promise.make((_resolve, reject) =>
|
|
502
|
+
onErrorReject := Some(reject)
|
|
503
|
+
)
|
|
504
|
+
// `onErrorReject` is filled synchronously by `Promise.make` above, before the
|
|
505
|
+
// indexer can run and call `onError`, so it's always present here.
|
|
506
|
+
let onError = (errHandler: ErrorHandling.t) => {
|
|
507
|
+
errHandler->ErrorHandling.log
|
|
508
|
+
(onErrorReject.contents->Option.getUnsafe)(FatalError(errHandler.exn->Utils.prettifyExn))
|
|
509
|
+
}
|
|
510
|
+
let envioVersion = Utils.EnvioPackage.value.version
|
|
511
|
+
|
|
512
|
+
let getMetrics = () => getIndexerState()->Option.map(IndexerState.toMetrics)
|
|
513
|
+
let dumpEffectCache = () =>
|
|
514
|
+
(persistence->Persistence.getInitializedStorageOrThrow).dumpEffectCache()
|
|
515
|
+
|
|
516
|
+
// A worker reports through its supervisor, which owns the one server and the
|
|
517
|
+
// one display the run has.
|
|
518
|
+
if !isTest && !Worker.isEnabled {
|
|
519
|
+
Metrics.startRuntimeCollectors()
|
|
520
|
+
Server.startServer(
|
|
521
|
+
~onSyncCache=() => dumpEffectCache()->Promise.thenResolve(ignore),
|
|
522
|
+
~collectRuntime=Metrics.collectRuntime,
|
|
523
|
+
~isDevelopmentMode,
|
|
524
|
+
~envioVersion,
|
|
525
|
+
~getMetrics,
|
|
526
|
+
)
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
let state = IndexerState.makeFromDbState(
|
|
530
|
+
~config,
|
|
531
|
+
~persistence,
|
|
532
|
+
~initialState=persistence->Persistence.getInitializedState,
|
|
533
|
+
~registrationsByChainId,
|
|
534
|
+
~isDevelopmentMode,
|
|
535
|
+
~shouldUseTui,
|
|
536
|
+
~exitAfterFirstEventBlock,
|
|
537
|
+
~holdRealtime=Worker.config->Option.mapOr(false, worker => worker.holdRealtime),
|
|
538
|
+
~onError,
|
|
539
|
+
)
|
|
540
|
+
if shouldUseTui {
|
|
541
|
+
let _rerender = Tui.start(~config, ~getMetrics=() => state->IndexerState.toMetrics)
|
|
542
|
+
}
|
|
543
|
+
Worker.bindRun(
|
|
544
|
+
~getMetrics=() => state->IndexerState.toMetrics,
|
|
545
|
+
~onReleaseRealtime=() => state->IndexerState.releaseRealtime,
|
|
546
|
+
)
|
|
547
|
+
setIndexerState(state)
|
|
548
|
+
state->IndexerLoop.start
|
|
549
|
+
await runUntilFatalError
|
|
550
|
+
}
|
|
551
|
+
)
|
|
552
|
+
|
|
553
|
+
// Starts this process's part of a run: the group's supervisor when the budget
|
|
554
|
+
// and the schema afford splitting the chains across processes, and the indexer
|
|
555
|
+
// itself otherwise. A worker is already one process's part, so it never splits
|
|
556
|
+
// again — `planForRun` refuses an isolated config.
|
|
625
557
|
let start = async (
|
|
626
558
|
~persistence: option<Persistence.t>=?,
|
|
627
559
|
~reset=false,
|
|
@@ -629,93 +561,24 @@ let start = async (
|
|
|
629
561
|
~exitAfterFirstEventBlock=false,
|
|
630
562
|
~patchConfig: option<(Config.t, HandlerRegister.registrationsByChainId) => Config.t>=?,
|
|
631
563
|
) => {
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
}
|
|
637
|
-
|
|
638
|
-
| (true, _) => false
|
|
639
|
-
| (_, Some(tui)) => tui
|
|
640
|
-
| (_, None) => !Envio.isNonInteractive()
|
|
641
|
-
}
|
|
642
|
-
// Initialize persistence first so the exported indexer value contains state from the database
|
|
643
|
-
// when handler files are loaded (they may access the indexer at module top level).
|
|
644
|
-
let config = Config.load()
|
|
645
|
-
// isDevelopmentMode controls whether the indexer stays alive after all
|
|
646
|
-
// chains finish (keepProcessAlive) and whether the console API is exposed.
|
|
647
|
-
// Set by `envio dev` via the public config's `isDev` field; `envio start`
|
|
648
|
-
// leaves it false so the process exits cleanly when indexing completes.
|
|
649
|
-
let isDevelopmentMode = !isTest && config.isDev
|
|
650
|
-
let persistence = switch persistence {
|
|
651
|
-
| Some(p) => p
|
|
652
|
-
| None => PgStorage.makePersistenceFromConfig(~config)
|
|
653
|
-
}
|
|
654
|
-
setGlobalPersistence(persistence)
|
|
655
|
-
await persistence->Persistence.init(
|
|
656
|
-
~reset,
|
|
657
|
-
~chainConfigs=config.chainMap->ChainMap.values,
|
|
658
|
-
~contractMapping=config.contractMapping,
|
|
659
|
-
~envioInfo=getEnvioInfo(),
|
|
660
|
-
~resetCommand=isDevelopmentMode ? "envio dev -r" : "envio start -r",
|
|
661
|
-
~runCommand=Some(isDevelopmentMode ? "envio dev" : "envio start"),
|
|
662
|
-
~lowercaseAddresses=config.lowercaseAddresses,
|
|
663
|
-
~requireInitialized=config.isolated,
|
|
564
|
+
// A worker parses the same config its supervisor did and narrows it to the
|
|
565
|
+
// chains it was handed, rather than being told what to index: the storage it
|
|
566
|
+
// resumes refuses a config that disagrees with the one the run was created
|
|
567
|
+
// from, which is a stronger guarantee than a handover could give.
|
|
568
|
+
Worker.config->Option.forEach(({chainIds}) =>
|
|
569
|
+
Config.prime(Config.getPublicConfigJson()->Config.withIsolatedChains(~chainIds))
|
|
664
570
|
)
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
let config = switch patchConfig {
|
|
678
|
-
| Some(patchConfig) => patchConfig(config, registrationsByChainId)
|
|
679
|
-
| None => config
|
|
680
|
-
}
|
|
681
|
-
// The single fatal-error handler, invoked once via IndexerState.errorExit.
|
|
682
|
-
// It logs the failure once (with chain context) and rejects the run wrapped in
|
|
683
|
-
// `FatalError` so callers know it's already logged — `Bin.res` just exits, the
|
|
684
|
-
// test worker unwraps and re-throws it to the parent thread. `runUntilFatalError`
|
|
685
|
-
// only ever rejects: on a clean run it stays pending and the process exits via
|
|
686
|
-
// ExitOnCaughtUp / when the indexer loop drains.
|
|
687
|
-
let onErrorReject = ref(None)
|
|
688
|
-
let runUntilFatalError: promise<unit> = Promise.make((_resolve, reject) =>
|
|
689
|
-
onErrorReject := Some(reject)
|
|
690
|
-
)
|
|
691
|
-
// `onErrorReject` is filled synchronously by `Promise.make` above, before the
|
|
692
|
-
// indexer can run and call `onError`, so it's always present here.
|
|
693
|
-
let onError = (errHandler: ErrorHandling.t) => {
|
|
694
|
-
errHandler->ErrorHandling.log
|
|
695
|
-
(onErrorReject.contents->Option.getUnsafe)(FatalError(errHandler.exn->Utils.prettifyExn))
|
|
696
|
-
}
|
|
697
|
-
let envioVersion = Utils.EnvioPackage.value.version
|
|
698
|
-
|
|
699
|
-
let getMetrics = () => getIndexerState()->Option.map(IndexerState.toMetrics)
|
|
700
|
-
|
|
701
|
-
if !isTest {
|
|
702
|
-
startServer(~persistence, ~isDevelopmentMode, ~envioVersion, ~getMetrics)
|
|
703
|
-
}
|
|
704
|
-
|
|
705
|
-
let state = IndexerState.makeFromDbState(
|
|
706
|
-
~config,
|
|
707
|
-
~persistence,
|
|
708
|
-
~initialState=persistence->Persistence.getInitializedState,
|
|
709
|
-
~registrationsByChainId,
|
|
710
|
-
~isDevelopmentMode,
|
|
711
|
-
~shouldUseTui,
|
|
712
|
-
~exitAfterFirstEventBlock,
|
|
713
|
-
~onError,
|
|
714
|
-
)
|
|
715
|
-
if shouldUseTui {
|
|
716
|
-
let _rerender = Tui.start(~config, ~getMetrics=() => state->IndexerState.toMetrics)
|
|
571
|
+
let config = Config.load()
|
|
572
|
+
switch isTest ? None : Supervisor.planForRun(~config) {
|
|
573
|
+
| Some(workers) => await Supervisor.run(~config, ~workers, ~reset)
|
|
574
|
+
| None =>
|
|
575
|
+
await startIndexer(
|
|
576
|
+
~config,
|
|
577
|
+
~persistence?,
|
|
578
|
+
~reset,
|
|
579
|
+
~isTest,
|
|
580
|
+
~exitAfterFirstEventBlock,
|
|
581
|
+
~patchConfig?,
|
|
582
|
+
)
|
|
717
583
|
}
|
|
718
|
-
setIndexerState(state)
|
|
719
|
-
state->IndexerLoop.start
|
|
720
|
-
await runUntilFatalError
|
|
721
584
|
}
|
package/src/Main.res.mjs
CHANGED
|
@@ -1,85 +1,32 @@
|
|
|
1
1
|
// Generated by ReScript, PLEASE EDIT WITH CARE
|
|
2
2
|
|
|
3
|
-
import * as Env from "./Env.res.mjs";
|
|
4
3
|
import * as Tui from "./tui/Tui.res.mjs";
|
|
5
|
-
import * as Envio from "./Envio.res.mjs";
|
|
6
4
|
import * as Utils from "./Utils.res.mjs";
|
|
7
5
|
import * as Config from "./Config.res.mjs";
|
|
6
|
+
import * as Server from "./Server.res.mjs";
|
|
7
|
+
import * as Worker from "./Worker.res.mjs";
|
|
8
8
|
import * as ChainId from "./ChainId.res.mjs";
|
|
9
9
|
import * as Logging from "./Logging.res.mjs";
|
|
10
10
|
import * as Metrics from "./Metrics.res.mjs";
|
|
11
|
-
import Express from "express";
|
|
12
|
-
import * as Process from "process";
|
|
13
11
|
import * as ChainMap from "./ChainMap.res.mjs";
|
|
14
12
|
import * as PgStorage from "./PgStorage.res.mjs";
|
|
15
13
|
import * as ChainState from "./ChainState.res.mjs";
|
|
14
|
+
import * as Supervisor from "./Supervisor.res.mjs";
|
|
16
15
|
import * as AddressRows from "./AddressRows.res.mjs";
|
|
17
16
|
import * as EnvioGlobal from "./EnvioGlobal.res.mjs";
|
|
18
17
|
import * as IndexerLoop from "./IndexerLoop.res.mjs";
|
|
19
18
|
import * as Persistence from "./Persistence.res.mjs";
|
|
20
|
-
import Yargs from "yargs/yargs";
|
|
21
19
|
import * as IndexerState from "./IndexerState.res.mjs";
|
|
22
20
|
import * as ErrorHandling from "./ErrorHandling.res.mjs";
|
|
23
21
|
import * as HandlerLoader from "./HandlerLoader.res.mjs";
|
|
24
22
|
import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.js";
|
|
25
|
-
import * as Helpers from "yargs/helpers";
|
|
26
23
|
import * as RollbackCommit from "./RollbackCommit.res.mjs";
|
|
27
24
|
import * as Stdlib_JsError from "@rescript/runtime/lib/es6/Stdlib_JsError.js";
|
|
28
25
|
import * as ContractMapping from "./ContractMapping.res.mjs";
|
|
29
26
|
import * as HandlerRegister from "./HandlerRegister.res.mjs";
|
|
30
27
|
import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.js";
|
|
31
|
-
import * as S$RescriptSchema from "rescript-schema/src/S.res.mjs";
|
|
32
28
|
import * as Primitive_exceptions from "@rescript/runtime/lib/es6/Primitive_exceptions.js";
|
|
33
29
|
|
|
34
|
-
function toChainData(m) {
|
|
35
|
-
return {
|
|
36
|
-
chainId: m.chainId,
|
|
37
|
-
poweredByHyperSync: m.poweredByHyperSync,
|
|
38
|
-
firstEventBlockNumber: m.firstEventBlockNumber,
|
|
39
|
-
latestProcessedBlock: m.latestProcessedBlock,
|
|
40
|
-
timestampCaughtUpToHeadOrEndblock: m.timestampCaughtUpToHeadOrEndblock,
|
|
41
|
-
numEventsProcessed: m.numEventsProcessed,
|
|
42
|
-
latestFetchedBlockNumber: m.latestFetchedBlockNumber,
|
|
43
|
-
currentBlockHeight: m.knownHeight,
|
|
44
|
-
numBatchesFetched: m.numBatchesFetched,
|
|
45
|
-
startBlock: m.startBlock,
|
|
46
|
-
endBlock: m.endBlock,
|
|
47
|
-
numAddresses: m.numAddresses
|
|
48
|
-
};
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
let chainDataSchema = S$RescriptSchema.schema(s => ({
|
|
52
|
-
chainId: s.m(ChainId.schema),
|
|
53
|
-
poweredByHyperSync: s.m(S$RescriptSchema.bool),
|
|
54
|
-
firstEventBlockNumber: s.m(S$RescriptSchema.option(S$RescriptSchema.int)),
|
|
55
|
-
latestProcessedBlock: s.m(S$RescriptSchema.option(S$RescriptSchema.int)),
|
|
56
|
-
timestampCaughtUpToHeadOrEndblock: s.m(S$RescriptSchema.option(S$RescriptSchema.datetime(S$RescriptSchema.string, undefined))),
|
|
57
|
-
numEventsProcessed: s.m(S$RescriptSchema.float),
|
|
58
|
-
latestFetchedBlockNumber: s.m(S$RescriptSchema.int),
|
|
59
|
-
currentBlockHeight: s.m(S$RescriptSchema.int),
|
|
60
|
-
numBatchesFetched: s.m(S$RescriptSchema.int),
|
|
61
|
-
startBlock: s.m(S$RescriptSchema.int),
|
|
62
|
-
endBlock: s.m(S$RescriptSchema.option(S$RescriptSchema.int)),
|
|
63
|
-
numAddresses: s.m(S$RescriptSchema.int)
|
|
64
|
-
}));
|
|
65
|
-
|
|
66
|
-
let stateSchema = S$RescriptSchema.union([
|
|
67
|
-
S$RescriptSchema.literal({
|
|
68
|
-
status: "disabled"
|
|
69
|
-
}),
|
|
70
|
-
S$RescriptSchema.literal({
|
|
71
|
-
status: "initializing"
|
|
72
|
-
}),
|
|
73
|
-
S$RescriptSchema.schema(s => ({
|
|
74
|
-
status: "active",
|
|
75
|
-
envioVersion: s.m(S$RescriptSchema.string),
|
|
76
|
-
chains: s.m(S$RescriptSchema.array(chainDataSchema)),
|
|
77
|
-
indexerStartTime: s.m(S$RescriptSchema.datetime(S$RescriptSchema.string, undefined)),
|
|
78
|
-
isPreRegisteringDynamicContracts: false,
|
|
79
|
-
rollbackOnReorg: s.m(S$RescriptSchema.bool)
|
|
80
|
-
}))
|
|
81
|
-
]);
|
|
82
|
-
|
|
83
30
|
function getIndexerState() {
|
|
84
31
|
return EnvioGlobal.value.indexerState;
|
|
85
32
|
}
|
|
@@ -402,87 +349,10 @@ function getGlobalIndexer() {
|
|
|
402
349
|
return new Proxy(Object.create(null), traps);
|
|
403
350
|
}
|
|
404
351
|
|
|
405
|
-
function startServer(getMetrics, envioVersion, persistence, isDevelopmentMode) {
|
|
406
|
-
let app = Express();
|
|
407
|
-
let consoleCorsMiddleware = (req, res, next) => {
|
|
408
|
-
let origin = req.headers["origin"];
|
|
409
|
-
if (origin !== undefined && (origin === Env.prodEnvioAppUrl || origin === Env.envioAppUrl)) {
|
|
410
|
-
res.setHeader("Access-Control-Allow-Origin", origin);
|
|
411
|
-
}
|
|
412
|
-
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
|
|
413
|
-
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
|
|
414
|
-
if (req.method === "OPTIONS") {
|
|
415
|
-
res.sendStatus(200);
|
|
416
|
-
return;
|
|
417
|
-
} else {
|
|
418
|
-
return next();
|
|
419
|
-
}
|
|
420
|
-
};
|
|
421
|
-
app.use("/console", consoleCorsMiddleware);
|
|
422
|
-
app.use("/metrics", consoleCorsMiddleware);
|
|
423
|
-
app.use("/metrics/runtime", consoleCorsMiddleware);
|
|
424
|
-
app.get("/healthz", (_req, res) => {
|
|
425
|
-
res.sendStatus(200);
|
|
426
|
-
});
|
|
427
|
-
app.get("/console/state", (_req, res) => {
|
|
428
|
-
let state;
|
|
429
|
-
if (isDevelopmentMode) {
|
|
430
|
-
let metrics = getMetrics();
|
|
431
|
-
state = metrics !== undefined ? ({
|
|
432
|
-
status: "active",
|
|
433
|
-
envioVersion: envioVersion,
|
|
434
|
-
chains: metrics.chains.map(toChainData),
|
|
435
|
-
indexerStartTime: metrics.startTime,
|
|
436
|
-
isPreRegisteringDynamicContracts: false,
|
|
437
|
-
rollbackOnReorg: metrics.rollbackEnabled
|
|
438
|
-
}) : ({
|
|
439
|
-
status: "initializing"
|
|
440
|
-
});
|
|
441
|
-
} else {
|
|
442
|
-
state = {
|
|
443
|
-
status: "disabled"
|
|
444
|
-
};
|
|
445
|
-
}
|
|
446
|
-
res.json(S$RescriptSchema.reverseConvertToJsonOrThrow(state, stateSchema));
|
|
447
|
-
});
|
|
448
|
-
app.post("/console/syncCache", (_req, res) => {
|
|
449
|
-
if (isDevelopmentMode) {
|
|
450
|
-
Persistence.getInitializedStorageOrThrow(persistence).dumpEffectCache().then(() => {
|
|
451
|
-
res.json(true);
|
|
452
|
-
});
|
|
453
|
-
} else {
|
|
454
|
-
res.json(false);
|
|
455
|
-
}
|
|
456
|
-
});
|
|
457
|
-
Metrics.startRuntimeCollectors();
|
|
458
|
-
app.get("/metrics", (_req, res) => {
|
|
459
|
-
res.set("Content-Type", Metrics.contentType);
|
|
460
|
-
res.end(Metrics.collect(getMetrics()));
|
|
461
|
-
});
|
|
462
|
-
app.get("/metrics/runtime", (_req, res) => {
|
|
463
|
-
res.set("Content-Type", Metrics.contentType);
|
|
464
|
-
res.end(Metrics.collectRuntime());
|
|
465
|
-
});
|
|
466
|
-
let server = app.listen(Env.serverPort);
|
|
467
|
-
server.on("error", err => {
|
|
468
|
-
let code = err.code;
|
|
469
|
-
if (code === "EADDRINUSE") {
|
|
470
|
-
Logging.error(`Port ` + Env.serverPort.toString() + ` is already in use. To fix this either:` + (`\n 1. Kill the process using the port: lsof -ti :` + Env.serverPort.toString() + ` | xargs kill -9`) + `\n 2. Use a different port by setting the ENVIO_INDEXER_PORT environment variable: ENVIO_INDEXER_PORT=9899 envio start`);
|
|
471
|
-
} else {
|
|
472
|
-
Logging.errorWithExn(err, "Failed to start indexer server");
|
|
473
|
-
}
|
|
474
|
-
Process.exit(1);
|
|
475
|
-
});
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
function getEnvioInfo() {
|
|
479
|
-
return Config.stripSensitiveData(Config.getPublicConfigJson());
|
|
480
|
-
}
|
|
481
|
-
|
|
482
352
|
async function migrate(reset) {
|
|
483
353
|
let config = Config.load();
|
|
484
354
|
let persistence = PgStorage.makePersistenceFromConfig(config, undefined);
|
|
485
|
-
await Persistence.init(persistence, ChainMap.values(config.chainMap), config.contractMapping, Config.
|
|
355
|
+
await Persistence.init(persistence, ChainMap.values(config.chainMap), config.contractMapping, Config.envioInfo(), "envio local db-migrate setup", undefined, reset, config.lowercaseAddresses, undefined, "Once");
|
|
486
356
|
return await persistence.storage.close();
|
|
487
357
|
}
|
|
488
358
|
|
|
@@ -495,21 +365,16 @@ async function dropSchema() {
|
|
|
495
365
|
|
|
496
366
|
let FatalError = /* @__PURE__ */Primitive_exceptions.create("Main.FatalError");
|
|
497
367
|
|
|
498
|
-
async function
|
|
368
|
+
async function startIndexer(config, persistence, resetOpt, isTestOpt, exitAfterFirstEventBlockOpt, patchConfig) {
|
|
499
369
|
let reset = resetOpt !== undefined ? resetOpt : false;
|
|
500
370
|
let isTest = isTestOpt !== undefined ? isTestOpt : false;
|
|
501
371
|
let exitAfterFirstEventBlock = exitAfterFirstEventBlockOpt !== undefined ? exitAfterFirstEventBlockOpt : false;
|
|
502
|
-
let
|
|
503
|
-
|
|
504
|
-
let explicitTui = off !== undefined ? !off : Env.tuiEnvVar;
|
|
505
|
-
let shouldUseTui = isTest ? false : (
|
|
506
|
-
explicitTui !== undefined ? explicitTui : !Envio.isNonInteractive()
|
|
507
|
-
);
|
|
508
|
-
let config = Config.load();
|
|
372
|
+
let shouldUseTui = Tui.shouldUse(isTest || Worker.isEnabled);
|
|
373
|
+
Stdlib_Option.forEach(Config.logContext(config), Logging.setContext);
|
|
509
374
|
let isDevelopmentMode = !isTest && config.isDev;
|
|
510
375
|
let persistence$1 = persistence !== undefined ? persistence : PgStorage.makePersistenceFromConfig(config, undefined);
|
|
511
376
|
EnvioGlobal.value.persistence = Primitive_option.some(persistence$1);
|
|
512
|
-
await Persistence.
|
|
377
|
+
await Persistence.initForRun(persistence$1, config, reset, isDevelopmentMode, config.isolated);
|
|
513
378
|
let registrationsByChainId = await HandlerLoader.registerAllHandlers(config);
|
|
514
379
|
let config$1;
|
|
515
380
|
if (isTest) {
|
|
@@ -535,22 +400,35 @@ async function start(persistence, resetOpt, isTestOpt, exitAfterFirstEventBlockO
|
|
|
535
400
|
};
|
|
536
401
|
let envioVersion = Utils.EnvioPackage.value.version;
|
|
537
402
|
let getMetrics = () => Stdlib_Option.map(EnvioGlobal.value.indexerState, IndexerState.toMetrics);
|
|
538
|
-
if (!isTest) {
|
|
539
|
-
|
|
403
|
+
if (!isTest && !Worker.isEnabled) {
|
|
404
|
+
Metrics.startRuntimeCollectors();
|
|
405
|
+
Server.startServer(getMetrics, envioVersion, () => Persistence.getInitializedStorageOrThrow(persistence$1).dumpEffectCache().then(prim => {}), Metrics.collectRuntime, isDevelopmentMode);
|
|
540
406
|
}
|
|
541
|
-
let state = IndexerState.makeFromDbState(config$2, persistence$1, Persistence.getInitializedState(persistence$1), registrationsByChainId, isDevelopmentMode, shouldUseTui, exitAfterFirstEventBlock, undefined, undefined, onError, undefined);
|
|
407
|
+
let state = IndexerState.makeFromDbState(config$2, persistence$1, Persistence.getInitializedState(persistence$1), registrationsByChainId, isDevelopmentMode, shouldUseTui, exitAfterFirstEventBlock, undefined, undefined, Stdlib_Option.mapOr(Worker.config, false, worker => worker.holdRealtime), onError, undefined);
|
|
542
408
|
if (shouldUseTui) {
|
|
543
409
|
Tui.start(config$2, () => IndexerState.toMetrics(state));
|
|
544
410
|
}
|
|
411
|
+
Worker.bindRun(() => IndexerState.toMetrics(state), () => IndexerState.releaseRealtime(state));
|
|
545
412
|
EnvioGlobal.value.indexerState = Primitive_option.some(state);
|
|
546
413
|
IndexerLoop.start(state);
|
|
547
414
|
return await runUntilFatalError;
|
|
548
415
|
}
|
|
549
416
|
|
|
417
|
+
async function start(persistence, resetOpt, isTestOpt, exitAfterFirstEventBlockOpt, patchConfig) {
|
|
418
|
+
let reset = resetOpt !== undefined ? resetOpt : false;
|
|
419
|
+
let isTest = isTestOpt !== undefined ? isTestOpt : false;
|
|
420
|
+
let exitAfterFirstEventBlock = exitAfterFirstEventBlockOpt !== undefined ? exitAfterFirstEventBlockOpt : false;
|
|
421
|
+
Stdlib_Option.forEach(Worker.config, param => Config.prime(Config.withIsolatedChains(Config.getPublicConfigJson(), param.chainIds)));
|
|
422
|
+
let config = Config.load();
|
|
423
|
+
let workers = isTest ? undefined : Supervisor.planForRun(config, undefined);
|
|
424
|
+
if (workers !== undefined) {
|
|
425
|
+
return await Supervisor.run(config, workers, reset);
|
|
426
|
+
} else {
|
|
427
|
+
return await startIndexer(config, persistence, reset, isTest, exitAfterFirstEventBlock, patchConfig);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
550
431
|
export {
|
|
551
|
-
toChainData,
|
|
552
|
-
chainDataSchema,
|
|
553
|
-
stateSchema,
|
|
554
432
|
getIndexerState,
|
|
555
433
|
setIndexerState,
|
|
556
434
|
getGlobalPersistence,
|
|
@@ -559,11 +437,9 @@ export {
|
|
|
559
437
|
getInitialChainState,
|
|
560
438
|
buildChainsObject,
|
|
561
439
|
getGlobalIndexer,
|
|
562
|
-
startServer,
|
|
563
|
-
getEnvioInfo,
|
|
564
440
|
migrate,
|
|
565
441
|
dropSchema,
|
|
566
442
|
FatalError,
|
|
567
443
|
start,
|
|
568
444
|
}
|
|
569
|
-
/*
|
|
445
|
+
/* Tui Not a pure module */
|