1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
mod chain_reorg;
mod chains;
mod config;
mod contract_states;
mod contracts;
mod diesels;
mod event_handlers;
pub mod events;
pub mod events_ingester;
mod nodes;
mod pruning;
mod repos;
mod reset_counts;

pub use chain_reorg::{MinConfirmationCount, ReorgedBlock, ReorgedBlocks, UnsavedReorgedBlock};
pub use chains::{Chain, ChainId};
pub use config::{Config, OptimizationConfig};
pub use contract_states::{ContractState, ContractStateMigrations, ContractStates};
pub use contracts::{Contract, ContractAddress, ContractEvent, Contracts, UnsavedContractAddress};
pub use event_handlers::{EventHandler, EventHandlerContext as EventContext, EventHandlers};
pub use events::{Event, EventParam};
pub use events_ingester::Provider as EventsIngesterProvider;
pub use nodes::KeepNodeActiveRequest;
pub use repos::*;
pub use reset_counts::ResetCount;

use config::ConfigError;
use nodes::NodeTasks;
use std::fmt::Debug;
use std::time::Duration;

#[cfg(feature = "postgres")]
pub use repos::{PostgresRepo, PostgresRepoConn, PostgresRepoPool};

#[cfg(feature = "postgres")]
pub type ChaindexingRepo = PostgresRepo;

#[cfg(feature = "postgres")]
pub type ChaindexingRepoPool = PostgresRepoPool;

#[cfg(feature = "postgres")]
pub type ChaindexingRepoConn<'a> = PostgresRepoConn<'a>;

#[cfg(feature = "postgres")]
pub type ChaindexingRepoRawQueryClient = PostgresRepoRawQueryClient;

#[cfg(feature = "postgres")]
pub type ChaindexingRepoRawQueryTxnClient<'a> = PostgresRepoRawQueryTxnClient<'a>;

#[cfg(feature = "postgres")]
pub use repos::PostgresRepoAsyncConnection as ChaindexingRepoAsyncConnection;
use tokio::time;

pub enum ChaindexingError {
    Config(ConfigError),
}

impl From<ConfigError> for ChaindexingError {
    fn from(value: ConfigError) -> Self {
        ChaindexingError::Config(value)
    }
}

impl Debug for ChaindexingError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ChaindexingError::Config(config_error) => {
                write!(f, "Config Error: {:?}", config_error)
            }
        }
    }
}

pub struct Chaindexing;

impl Chaindexing {
    pub async fn index_states<S: Send + Sync + Clone + Debug + 'static>(
        config: &Config<S>,
    ) -> Result<(), ChaindexingError> {
        config.validate()?;

        let Config { repo, .. } = config;
        let query_client = repo.get_raw_query_client().await;
        let pool = repo.get_pool(1).await;
        let mut conn = ChaindexingRepo::get_conn(&pool).await;

        ChaindexingRepo::migrate(
            &query_client,
            ChaindexingRepo::create_nodes_migration().to_vec(),
        )
        .await;
        ChaindexingRepo::prune_nodes(&query_client, config.max_concurrent_node_count).await;
        let current_node = ChaindexingRepo::create_node(&mut conn).await;

        Self::wait_for_non_leader_nodes_to_abort(config.get_node_election_rate_ms()).await;

        Self::setup(config, &mut conn, &query_client).await?;

        let config = config.clone();
        tokio::spawn(async move {
            let mut interval =
                time::interval(Duration::from_millis(config.get_node_election_rate_ms()));

            let pool = config.repo.get_pool(1).await;
            let mut conn = ChaindexingRepo::get_conn(&pool).await;

            let mut node_tasks = NodeTasks::new(&current_node);

            loop {
                node_tasks.orchestrate(&config, &mut conn).await;

                interval.tick().await;
            }
        });

        Ok(())
    }
    async fn wait_for_non_leader_nodes_to_abort(node_election_rate_ms: u64) {
        time::sleep(Duration::from_millis(node_election_rate_ms)).await;
    }
    pub async fn setup<'a, S: Sync + Send + Clone>(
        config: &Config<S>,
        conn: &mut ChaindexingRepoConn<'a>,
        client: &ChaindexingRepoRawQueryClient,
    ) -> Result<(), ChaindexingError> {
        let Config {
            contracts,
            reset_count,
            reset_queries,
            ..
        } = config;

        Self::run_migrations_for_resets(&client).await;
        Self::maybe_reset(reset_count, reset_queries, contracts, &client, conn).await;
        Self::run_internal_migrations(&client).await;
        Self::run_migrations_for_contract_states(&client, contracts).await;

        let contract_addresses = contracts.clone().into_iter().flat_map(|c| c.addresses).collect();
        ChaindexingRepo::create_contract_addresses(conn, &contract_addresses).await;

        Ok(())
    }
    pub async fn maybe_reset<'a, S: Send + Sync + Clone>(
        reset_count: &u64,
        reset_queries: &Vec<String>,
        contracts: &[Contract<S>],
        client: &ChaindexingRepoRawQueryClient,
        conn: &mut ChaindexingRepoConn<'a>,
    ) {
        let reset_count = *reset_count;
        let previous_reset_count_id = ChaindexingRepo::get_last_reset_count(conn)
            .await
            .map(|rc| rc.get_count())
            .unwrap_or(0);

        if reset_count > previous_reset_count_id {
            Self::reset_internal_migrations(client).await;
            Self::reset_migrations_for_contract_states(client, contracts).await;
            Self::run_user_reset_queries(client, reset_queries).await;
            for _ in previous_reset_count_id..reset_count {
                ChaindexingRepo::create_reset_count(conn).await;
            }
        }
    }

    pub async fn run_migrations_for_resets(client: &ChaindexingRepoRawQueryClient) {
        ChaindexingRepo::migrate(
            client,
            ChaindexingRepo::create_reset_counts_migration().to_vec(),
        )
        .await;
        ChaindexingRepo::prune_reset_counts(&client, reset_counts::MAX_RESET_COUNT).await;
    }
    pub async fn run_internal_migrations(client: &ChaindexingRepoRawQueryClient) {
        ChaindexingRepo::migrate(client, ChaindexingRepo::get_internal_migrations()).await;
    }
    pub async fn reset_internal_migrations(client: &ChaindexingRepoRawQueryClient) {
        ChaindexingRepo::migrate(client, ChaindexingRepo::get_reset_internal_migrations()).await;
    }

    pub async fn run_migrations_for_contract_states<S: Send + Sync + Clone>(
        client: &ChaindexingRepoRawQueryClient,
        contracts: &[Contract<S>],
    ) {
        for state_migration in Contracts::get_state_migrations(contracts) {
            ChaindexingRepo::migrate(client, state_migration.get_migrations()).await;
        }
    }
    pub async fn reset_migrations_for_contract_states<S: Send + Sync + Clone>(
        client: &ChaindexingRepoRawQueryClient,
        contracts: &[Contract<S>],
    ) {
        for state_migration in Contracts::get_state_migrations(contracts) {
            ChaindexingRepo::migrate(client, state_migration.get_reset_migrations()).await;
        }
    }

    async fn run_user_reset_queries(
        client: &ChaindexingRepoRawQueryClient,
        reset_queries: &Vec<String>,
    ) {
        for reset_query in reset_queries {
            ChaindexingRepo::execute_raw_query(client, reset_query).await;
        }
    }
}

pub mod hashes {
    use ethers::types::{H160, H256};

    pub fn h160_to_string(h160: &H160) -> String {
        serde_json::to_value(h160).unwrap().as_str().unwrap().to_string()
    }

    pub fn h256_to_string(h256: &H256) -> String {
        serde_json::to_value(h256).unwrap().as_str().unwrap().to_string()
    }
}
mod utils {
    use ethers::types::H160;

    use crate::hashes;

    pub fn address_to_string(address: &H160) -> String {
        hashes::h160_to_string(address)
    }
}