|
| 1 | +//! Acropolis Asset State module for Caryatid |
| 2 | +//! Accepts native asset mint and burn events |
| 3 | +//! and derives the Asset State in memory |
| 4 | +
|
| 5 | +use acropolis_common::{ |
| 6 | + messages::{CardanoMessage, Message, StateQuery, StateQueryResponse}, |
| 7 | + queries::assets::{AssetsStateQuery, AssetsStateQueryResponse, DEFAULT_ASSETS_QUERY_TOPIC}, |
| 8 | + state_history::{StateHistory, StateHistoryStore}, |
| 9 | + BlockStatus, |
| 10 | +}; |
| 11 | +use anyhow::Result; |
| 12 | +use caryatid_sdk::{module, Context, Module, Subscription}; |
| 13 | +use config::Config; |
| 14 | +use std::sync::Arc; |
| 15 | +use tokio::sync::Mutex; |
| 16 | +use tracing::{error, info, info_span, Instrument}; |
| 17 | + |
| 18 | +use crate::state::{AssetsStorageConfig, State}; |
| 19 | +mod state; |
| 20 | + |
| 21 | +// Subscription topics |
| 22 | +const DEFAULT_ASSET_DELTAS_SUBSCRIBE_TOPIC: (&str, &str) = |
| 23 | + ("asset-deltas-subscribe-topic", "cardano.asset.deltas"); |
| 24 | + |
| 25 | +// Configuration defaults |
| 26 | +const DEFAULT_STORE_INFO: (&str, bool) = ("store-info", false); |
| 27 | +const DEFAULT_STORE_HISTORY: (&str, bool) = ("store-history", false); |
| 28 | +const DEFAULT_STORE_TRANSACTIONS: (&str, bool) = ("store-transactions", false); |
| 29 | +const DEFAULT_STORE_ADDRESSES: (&str, bool) = ("store-addresses", false); |
| 30 | + |
| 31 | +/// Assets State module |
| 32 | +#[module( |
| 33 | + message_type(Message), |
| 34 | + name = "assets-state", |
| 35 | + description = "In-memory Assets State from asset mint and burn events" |
| 36 | +)] |
| 37 | +pub struct AssetsState; |
| 38 | + |
| 39 | +impl AssetsState { |
| 40 | + async fn run( |
| 41 | + history: Arc<Mutex<StateHistory<State>>>, |
| 42 | + mut deltas_subscription: Box<dyn Subscription<Message>>, |
| 43 | + storage_config: AssetsStorageConfig, |
| 44 | + ) -> Result<()> { |
| 45 | + // Main loop of synchronised messages |
| 46 | + loop { |
| 47 | + match deltas_subscription.read().await?.1.as_ref() { |
| 48 | + Message::Cardano((block, CardanoMessage::AssetDeltas(message))) => { |
| 49 | + let span = info_span!("assets_state.handle", epoch = block.epoch); |
| 50 | + async { |
| 51 | + // Get current state and current params |
| 52 | + let mut state = { |
| 53 | + let mut h = history.lock().await; |
| 54 | + h.get_or_init_with(|| State::new(&storage_config)) |
| 55 | + }; |
| 56 | + |
| 57 | + // Handle rollback if needed |
| 58 | + if block.status == BlockStatus::RolledBack { |
| 59 | + state = history.lock().await.get_rolled_back_state(block.epoch); |
| 60 | + } |
| 61 | + |
| 62 | + // Process deltas |
| 63 | + state = match state.handle_deltas(&message.deltas) { |
| 64 | + Ok(new_state) => new_state, |
| 65 | + Err(e) => { |
| 66 | + error!("Asset deltas handling error: {e:#}"); |
| 67 | + state |
| 68 | + } |
| 69 | + }; |
| 70 | + |
| 71 | + // Commit state |
| 72 | + { |
| 73 | + let mut h = history.lock().await; |
| 74 | + h.commit(block.epoch, state); |
| 75 | + } |
| 76 | + |
| 77 | + Ok::<(), anyhow::Error>(()) |
| 78 | + } |
| 79 | + .instrument(span) |
| 80 | + .await?; |
| 81 | + } |
| 82 | + msg => error!("Unexpected message {msg:?} for enact state topic"), |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + pub async fn init(&self, context: Arc<Context<Message>>, config: Arc<Config>) -> Result<()> { |
| 88 | + fn get_bool_flag(config: &Config, key: (&str, bool)) -> bool { |
| 89 | + config.get_bool(key.0).unwrap_or(key.1) |
| 90 | + } |
| 91 | + |
| 92 | + fn get_string_flag(config: &Config, key: (&str, &str)) -> String { |
| 93 | + config.get_string(key.0).unwrap_or_else(|_| key.1.to_string()) |
| 94 | + } |
| 95 | + |
| 96 | + // Get configuration flags and topis |
| 97 | + let storage_config = AssetsStorageConfig { |
| 98 | + _store_info: get_bool_flag(&config, DEFAULT_STORE_INFO), |
| 99 | + _store_history: get_bool_flag(&config, DEFAULT_STORE_HISTORY), |
| 100 | + _store_transactions: get_bool_flag(&config, DEFAULT_STORE_TRANSACTIONS), |
| 101 | + _store_addresses: get_bool_flag(&config, DEFAULT_STORE_ADDRESSES), |
| 102 | + }; |
| 103 | + |
| 104 | + let asset_deltas_subscribe_topic = |
| 105 | + get_string_flag(&config, DEFAULT_ASSET_DELTAS_SUBSCRIBE_TOPIC); |
| 106 | + info!("Creating subscriber on '{asset_deltas_subscribe_topic}'"); |
| 107 | + |
| 108 | + let assets_query_topic = get_string_flag(&config, DEFAULT_ASSETS_QUERY_TOPIC); |
| 109 | + info!("Creating asset query handler on '{assets_query_topic}'"); |
| 110 | + |
| 111 | + // Initalize state history |
| 112 | + let history = Arc::new(Mutex::new(StateHistory::<State>::new( |
| 113 | + "AssetsState", |
| 114 | + StateHistoryStore::default_block_store(), |
| 115 | + ))); |
| 116 | + let history_run = history.clone(); |
| 117 | + let query_history = history.clone(); |
| 118 | + let ticker_history = history.clone(); |
| 119 | + |
| 120 | + // Query handler |
| 121 | + context.handle(&assets_query_topic, move |message| { |
| 122 | + let history = query_history.clone(); |
| 123 | + async move { |
| 124 | + let Message::StateQuery(StateQuery::Assets(query)) = message.as_ref() else { |
| 125 | + return Arc::new(Message::StateQueryResponse(StateQueryResponse::Assets( |
| 126 | + AssetsStateQueryResponse::Error("Invalid message for assets-state".into()), |
| 127 | + ))); |
| 128 | + }; |
| 129 | + |
| 130 | + let state = history.lock().await.get_current_state(); |
| 131 | + |
| 132 | + let response = match query { |
| 133 | + AssetsStateQuery::GetAssetsList => { |
| 134 | + AssetsStateQueryResponse::AssetsList(state.assets) |
| 135 | + } |
| 136 | + _ => AssetsStateQueryResponse::Error(format!( |
| 137 | + "Unimplemented assets query: {query:?}" |
| 138 | + )), |
| 139 | + }; |
| 140 | + Arc::new(Message::StateQueryResponse(StateQueryResponse::Assets( |
| 141 | + response, |
| 142 | + ))) |
| 143 | + } |
| 144 | + }); |
| 145 | + |
| 146 | + // Ticker to log stats |
| 147 | + let mut subscription = context.subscribe("clock.tick").await?; |
| 148 | + context.run(async move { |
| 149 | + loop { |
| 150 | + let Ok((_, message)) = subscription.read().await else { |
| 151 | + return; |
| 152 | + }; |
| 153 | + if let Message::Clock(message) = message.as_ref() { |
| 154 | + if (message.number % 60) == 0 { |
| 155 | + let span = info_span!("assets_state.tick", number = message.number); |
| 156 | + async { |
| 157 | + ticker_history |
| 158 | + .lock() |
| 159 | + .await |
| 160 | + .get_current_state() |
| 161 | + .tick() |
| 162 | + .await |
| 163 | + .inspect_err(|e| error!("Tick error: {e}")) |
| 164 | + .ok(); |
| 165 | + } |
| 166 | + .instrument(span) |
| 167 | + .await; |
| 168 | + } |
| 169 | + } |
| 170 | + } |
| 171 | + }); |
| 172 | + |
| 173 | + // Subscribe to enabled topics |
| 174 | + let deltas_sub = context.subscribe(&asset_deltas_subscribe_topic).await?; |
| 175 | + |
| 176 | + // Start run task |
| 177 | + context.run(async move { |
| 178 | + Self::run(history_run, deltas_sub, storage_config) |
| 179 | + .await |
| 180 | + .unwrap_or_else(|e| error!("Failed: {e}")); |
| 181 | + }); |
| 182 | + |
| 183 | + Ok(()) |
| 184 | + } |
| 185 | +} |
0 commit comments