mod daemon;
use std::io::IsTerminal;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use clap::{Parser, Subcommand};
use tracing::info;
use tracing_subscriber::EnvFilter;
use turbine_core::config::Config;
use turbine_ipc::{Request, Response};
use turbine_sdk::Turbine;
#[derive(Parser, Debug)]
#[command(
name = "turbine",
version,
about = "TURBINE — ultra-low-latency smart transaction infrastructure on Solana"
)]
struct Cli {
#[arg(short, long, default_value = "turbine.toml", global = true)]
config: PathBuf,
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand, Debug)]
enum Command {
Start {
#[arg(long)]
no_tui: bool,
#[arg(long)]
deshred: bool,
},
Run {
scenario: String,
},
Stop,
Status,
}
fn init_tracing(to_file: bool) -> anyhow::Result<()> {
let filter =
EnvFilter::try_from_env("TURBINE_LOG").unwrap_or_else(|_| EnvFilter::new("info"));
if to_file {
let path = std::env::temp_dir().join("turbine.log");
let file = std::fs::OpenOptions::new().create(true).append(true).open(&path)?;
eprintln!("TURBINE — launching dashboard; logs → {}", path.display());
tracing_subscriber::fmt()
.with_env_filter(filter)
.with_target(false)
.with_ansi(false)
.with_writer(move || file.try_clone().expect("clone log file handle"))
.init();
} else {
tracing_subscriber::fmt()
.with_env_filter(filter)
.with_target(false)
.init();
}
Ok(())
}
async fn run_local_demo(config: &std::path::Path, scenario: &str) -> anyhow::Result<()> {
use turbine_core::tips::TipSnapshot;
use turbine_execute::{ExecutionEngine, TradeIntent};
if let Some(suffix) = scenario.strip_prefix("fail-") {
return run_failure_demo(config, suffix).await;
}
let cfg = Arc::new(Config::load(config)?);
info!(%scenario, dry_run = cfg.execution.dry_run, "Phase 4 local execution demo");
let state = Arc::new(turbine_state::HotState::new(&cfg));
match turbine_ingest::blockhash::fetch_latest_blockhash(&cfg.rpc.http_url).await {
Ok(bh) => {
info!(blockhash = %bh.blockhash, slot = bh.slot, "fetched warm blockhash");
state.set_blockhash(bh);
}
Err(e) => {
tracing::warn!("blockhash fetch failed ({e}); using synthetic placeholder");
state.set_blockhash(turbine_core::blockhash::CachedBlockhash {
blockhash: "11111111111111111111111111111111".into(),
last_valid_block_height: 0,
slot: 0,
fetched_at: std::time::Instant::now(),
});
}
}
match turbine_ingest::tips::fetch_tip_accounts(&cfg.jito.json_rpc_url).await {
Ok(accts) if !accts.is_empty() => {
info!(count = accts.len(), "fetched Jito tip accounts");
state.set_tip_accounts(accts);
}
other => {
if let Err(e) = other {
tracing::warn!("tip account fetch failed ({e}); using a synthetic tip account");
}
state.set_tip_accounts(vec![solana_pubkey::Pubkey::new_from_array([9u8; 32])]);
}
}
match turbine_ingest::tips::fetch_tip_floor(&cfg.jito.tip_floor_url).await {
Ok(t) => {
info!(p50 = t.p50, p95 = t.p95, "fetched tip floor");
state.set_tips(TipSnapshot { p25: t.p25, p50: t.p50, p75: t.p75, p95: t.p95, p99: t.p99 });
}
Err(e) => {
tracing::warn!("tip floor fetch failed ({e}); using synthetic percentiles");
state.set_tips(TipSnapshot { p25: 1_000, p50: 2_000, p75: 5_000, p95: 50_000, p99: 200_000 });
}
}
let slot = 1_000u64;
state.set_slot(slot);
state.set_leader(turbine_core::leader::LeaderView {
next_jito_leader_slot: Some(slot + cfg.strategy.gate_min),
slots_until_leader: Some(cfg.strategy.gate_min),
});
state.set_geyser_healthy(true);
let engine = ExecutionEngine::new(cfg.clone(), state.clone(), None)?;
let report = engine.execute(TradeIntent::mock(scenario)).await?;
info!(
label = %report.label,
congestion = ?report.congestion,
percentile = ?report.percentile,
tip_lamports = report.tip_lamports,
tip_account = %report.tip_account,
tx_count = report.tx_count,
bundle_b64_bytes = report.bundle_b64_bytes,
build_us = report.build_us,
gate = ?report.gate,
submit_us = ?report.submit_us,
bundle_id = ?report.bundle_id,
dry_run = report.dry_run,
"scenario complete",
);
Ok(())
}
async fn run_failure_demo(config: &std::path::Path, class_name: &str) -> anyhow::Result<()> {
use turbine_ai::{AiEngine, Analyst, AnalystVerdict, RetryAdjustments};
use turbine_core::tips::TipSnapshot;
use turbine_core::types::FailureClass;
use turbine_execute::{ExecutionEngine, FailureEvent, RetryCoordinator, TradeIntent};
let class = match class_name {
"blockhash" => FailureClass::BlockhashExpired,
"tip" => FailureClass::TipTooLow,
"auction" => FailureClass::AuctionTimeout,
"dropped" => FailureClass::BundleDropped,
"transient" => FailureClass::Transient,
"slippage" => FailureClass::Slippage,
"account" => FailureClass::AccountInUse,
"sim" => FailureClass::SimulationError,
"custom" => FailureClass::ProgramCustom(6001),
other => {
tracing::warn!(%other, "unknown fail-* scenario; using Unknown");
FailureClass::Unknown
}
};
let mut cfg = Config::load(config)?;
cfg.execution.dry_run = true;
let cfg = Arc::new(cfg);
info!(?class, ai_enabled = cfg.ai.enabled, "Phase 6 autonomous AI retry demo");
let state = Arc::new(turbine_state::HotState::new(&cfg));
state.set_blockhash(turbine_core::blockhash::CachedBlockhash {
blockhash: "11111111111111111111111111111111".into(),
last_valid_block_height: 0,
slot: 0,
fetched_at: std::time::Instant::now(),
});
state.set_tip_accounts(vec![solana_pubkey::Pubkey::new_from_array([9u8; 32])]);
state.set_tips(TipSnapshot { p25: 1_000, p50: 6_700, p75: 20_000, p95: 460_000, p99: 1_800_000 });
let slot = 1_000u64;
state.set_slot(slot);
state.set_leader(turbine_core::leader::LeaderView {
next_jito_leader_slot: Some(slot + cfg.strategy.gate_min),
slots_until_leader: Some(cfg.strategy.gate_min),
});
state.set_geyser_healthy(true);
let engine = Arc::new(ExecutionEngine::new(cfg.clone(), state.clone(), None)?);
let ai = if cfg.ai.enabled {
Arc::new(AiEngine::new(&cfg, state.clone()))
} else {
let verdict = AnalystVerdict {
classification: format!("{class:?}"),
root_cause: format!("demo: synthetic {class_name} failure"),
adjustments: RetryAdjustments {
tip_bump_pct: Some(0.5),
cu_limit: Some(300_000),
fresh_blockhash: true,
rebuild: true,
..Default::default()
},
should_retry: true,
confidence: 0.8,
};
Arc::new(AiEngine::with_analyst(&cfg, state.clone(), Analyst::Mock(Box::new(verdict))))
};
let coordinator =
RetryCoordinator::new(cfg.clone(), engine.clone(), ai, state.clone());
let rep = engine.execute(TradeIntent::mock(format!("demo-{class_name}"))).await?;
info!(tracking_id = rep.tracking_id, attempt = rep.attempt, "original bundle submitted");
coordinator
.on_failure(FailureEvent {
tracking_id: Some(rep.tracking_id),
bundle_id: None,
raw_reason: format!("synthetic {class_name} failure"),
class_hint: class,
logs: vec!["Program log: demo".into()],
})
.await;
for rec in state.ai_audit.snapshot() {
info!(
seq = rec.seq,
attempt = rec.attempt,
outcome = ?rec.outcome,
class = %rec.classification,
fix = %rec.fix,
"AI reasoning: {}", rec.root_cause
);
}
info!(
in_flight = engine.registry().len(),
audit_records = state.ai_audit.len(),
"autonomous retry demo complete"
);
Ok(())
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
let tui_active = matches!(
cli.command,
Command::Start { no_tui: false, .. }
) && std::io::stdout().is_terminal();
init_tracing(tui_active)?;
match cli.command {
Command::Start { deshred, .. } => {
let turbine = Turbine::builder()
.config_path(&cli.config)
.deshred(deshred)
.web(true)
.start()
.await?;
let cfg = turbine.config_arc();
info!(config = %cli.config.display(), "configuration loaded and validated");
info!(
geyser = %cfg.geyser.endpoint,
commitment = %cfg.geyser.commitment,
deshred,
programs = cfg.targets.programs.len(),
watched = cfg.targets.watched_accounts.len(),
socket = %cfg.ipc.socket_path.display(),
studio = %turbine.studio_url(),
tui = tui_active,
"ingestion + processing + execution + AI + IPC running — `turbine stop` or Ctrl-C"
);
let shutdown = turbine.shutdown_notify();
let (cmd_tx, cmd_rx) =
tokio::sync::mpsc::channel::<(Request, tokio::sync::oneshot::Sender<Response>)>(64);
let daemon = Arc::new(daemon::Daemon::new(
cfg.clone(),
turbine.state(),
turbine.engine(),
turbine.fail_tx(),
shutdown.clone(),
turbine.jito_connected(),
));
turbine.spawn_task(tokio::spawn(daemon.run(cmd_rx)));
{
let socket = cfg.ipc.socket_path.clone();
let sd = shutdown.clone();
turbine.spawn_task(tokio::spawn(async move {
if let Err(e) = turbine_ipc::serve(&socket, cmd_tx, sd).await {
tracing::error!("ipc server error: {e}");
}
}));
}
let deshred_boot = turbine.deshred_boot();
if tui_active {
if let Some(notice) = deshred_boot.terminal_notice() {
use std::io::Write;
let mut stderr = std::io::stderr();
let _ = writeln!(stderr);
for line in notice.lines() {
let _ = writeln!(stderr, "{line}");
}
let _ = writeln!(stderr);
let _ = stderr.flush();
}
let stopping = Arc::new(AtomicBool::new(false));
let tui = turbine_tui::spawn_dashboard(
turbine.bus().subscribe(),
turbine.studio_url(),
cfg.execution.dry_run,
shutdown.clone(),
stopping.clone(),
deshred_boot,
);
turbine.wait_shutdown().await;
stopping.store(true, Ordering::Relaxed);
turbine.shutdown();
let _ = tui.await;
info!("dashboard closed; TURBINE stopped");
} else {
if let Some(notice) = deshred_boot.terminal_notice() {
eprintln!();
for line in notice.lines() {
eprintln!("{line}");
}
eprintln!();
}
turbine.wait_shutdown().await;
info!("stop requested; shutting down");
turbine.shutdown();
}
std::process::exit(0);
}
Command::Run { scenario } => {
let cfg = Config::load(&cli.config)?;
match turbine_ipc::request(
&cfg.ipc.socket_path,
Request::RunScenario { scenario: scenario.clone() },
)
.await
{
Ok(resp) => print_response(resp),
Err(e) => {
info!("daemon not reachable ({e}); running in-process demo");
run_local_demo(&cli.config, &scenario).await?;
}
}
}
Command::Stop => {
let cfg = Config::load(&cli.config)?;
match turbine_ipc::request(&cfg.ipc.socket_path, Request::Stop).await {
Ok(resp) => print_response(resp),
Err(e) => info!("could not reach daemon to stop ({e}); is it running?"),
}
}
Command::Status => {
let cfg = Config::load(&cli.config)?;
match turbine_ipc::request(&cfg.ipc.socket_path, Request::Status).await {
Ok(resp) => print_response(resp),
Err(e) => info!(
socket = %cfg.ipc.socket_path.display(),
"daemon not running ({e}); config is valid"
),
}
}
}
Ok(())
}
fn print_response(resp: Response) {
match resp {
Response::Pong => info!("pong"),
Response::Ack { message } => info!("{message}"),
Response::Error { message } => tracing::error!("daemon error: {message}"),
Response::RunResult(r) => info!(
label = %r.label,
tracking_id = r.tracking_id,
gate = %r.gate,
tip_lamports = r.tip_lamports,
tx_count = r.tx_count,
bundle_id = ?r.bundle_id,
submitted = r.submitted,
failure_injected = r.failure_injected,
dry_run = r.dry_run,
"scenario accepted by daemon",
),
Response::Status(s) => info!(
uptime_secs = s.uptime_secs,
slot = s.slot,
geyser_healthy = s.geyser_healthy,
jito_connected = s.jito_connected,
next_jito_leader_slot = ?s.next_jito_leader_slot,
slots_until_leader = ?s.slots_until_leader,
tip_p50 = s.tip_p50,
tip_p95 = s.tip_p95,
in_flight = s.in_flight,
ai_decisions = s.ai_decisions,
submission_killed = s.submission_killed,
dry_run = s.dry_run,
"daemon status",
),
}
}