ic-db-cli 0.47.0

Local fixture console for IC DB
Documentation
//! Local fixture commands using typed fixture replies.

use super::{
    Action, CallKind, Command, FIXTURE_OUTPUT_BYTES, FixtureCalls, print_schema, print_schema_json,
    print_status,
};
use ic_db_cli::{
    ConsolePage, DisplayPage, QueryRequest, RetainedPhase, RetainedProgress, RetainedSelection,
    lowercase_hex,
};
use ic_host_text::{bordered_table, escape};

async fn count(calls: &mut FixtureCalls<'_>, entity: &str) -> Result<(), String> {
    let count: u64 = calls
        .fallible(CallKind::Query, "cardinality", 148, entity)
        .await?;
    println!("{}", bordered_table(&["count"], &[vec![count.to_string()]]));
    Ok(())
}

async fn schema(
    calls: &mut FixtureCalls<'_>,
    selected: Option<String>,
    json: bool,
) -> Result<(), String> {
    let ic_db_cli::SchemaResponse {
        status,
        entities,
        types,
    } = fetch_schema(calls, &selected).await?;
    if entities.is_empty()
        && let Some(name) = selected
    {
        return Err(format!(
            "Unknown entity '{}'. Use db entities to list entities.",
            escape(&name)
        ));
    }

    if json {
        print_schema_json(status.schema, &entities, &types)?;
    } else {
        print_schema(entities, types);
    }

    Ok(())
}

async fn fetch_schema(
    calls: &mut FixtureCalls<'_>,
    selected: &Option<String>,
) -> Result<ic_db_cli::SchemaResponse, String> {
    calls.framed(CallKind::Query, "schema", 2, selected).await
}

async fn entities(calls: &mut FixtureCalls<'_>, json: bool) -> Result<(), String> {
    let entities = fetch_schema(calls, &None).await?.entities;
    #[derive(serde::Serialize)]
    struct Summary {
        name: String,
        columns: usize,
    }
    let summaries: Vec<_> = entities
        .into_iter()
        .map(|entity| Summary {
            name: entity.name,
            columns: entity.fields.len(),
        })
        .collect();

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&summaries).map_err(|e| e.to_string())?
        );
    } else {
        let rows: Vec<_> = summaries
            .into_iter()
            .map(|s| vec![s.name, s.columns.to_string()])
            .collect();
        println!("{}", bordered_table(&["Entity", "Columns"], &rows));
    }
    Ok(())
}

async fn migration(calls: &mut FixtureCalls<'_>, wasm: &[u8]) -> Result<(), String> {
    let pic = calls.pic;
    let canister = calls.canister;
    use ic_db_cli::MigrationAction;
    let mut step = async |action: MigrationAction| -> Result<(bool, Vec<Vec<String>>), String> {
        calls
            .fallible(CallKind::Update, "migration_demo", 142, &action)
            .await
    };
    let (_, rows) = step(MigrationAction::Seed).await?;
    println!(
        "\nItem — source\n{}",
        bordered_table(&["id", "amount"], &rows)
    );
    println!("\nMigration: console-item-label v1");
    for action in [
        MigrationAction::Freeze,
        MigrationAction::Copy,
        MigrationAction::Validate,
        MigrationAction::Publish,
        MigrationAction::Cleanup,
    ] {
        // Fixture-size bound only; product checkpoints own progress.
        for call in 1..=32 {
            let (complete, rows) = step(action).await?;
            println!(
                "{action:?} {call}: {}",
                if complete { "complete" } else { "in progress" }
            );
            if action == MigrationAction::Copy {
                println!("{}", bordered_table(&["Copied rows"], &rows));
                if call == 1 {
                    ic_db_cli::host::upgrade_stopped(pic, canister, wasm.to_vec(), vec![], None)
                        .await
                        .map_err(|e| format!("{e:?}"))?;
                    println!("Upgrade: complete");
                }
            }
            if complete {
                break;
            }
            if call == 32 {
                return Err(format!("{action:?} exceeded the fixture's 32-call bound"));
            }
        }
    }
    let (_, rows) = step(MigrationAction::ReadTarget).await?;
    println!(
        "\nItem — target (label index)\n{}",
        bordered_table(&["id", "amount", "label"], &rows)
    );
    Ok(())
}

pub(super) async fn execute(
    calls: &mut FixtureCalls<'_>,
    command: Action,
    wasm: &[u8],
) -> Result<(), String> {
    match command {
        Action::Local(Command::Explorer { .. }) => {
            return Err("Run db explorer from the application checkout in your shell".into());
        }
        Action::Local(Command::Quit) => {}
        Action::Local(Command::MigrationDemo) => migration(calls, wasm).await?,
        Action::Aggregate {
            selection,
            work,
            page_size,
        } => aggregate(calls, selection, work, page_size).await?,
        Action::Local(Command::Count { entity }) => count(calls, &entity).await?,
        Action::Local(Command::Schema { entity, json }) => schema(calls, entity, json).await?,
        Action::Local(Command::Entities { json }) => entities(calls, json).await?,
        Action::Local(Command::Status) => {
            print_status(calls.framed(CallKind::Query, "inspect", 1, &()).await?)
        }
        Action::Query(request) => query(calls, request).await?,
    }

    Ok(())
}

async fn query(calls: &mut FixtureCalls<'_>, request: QueryRequest) -> Result<(), String> {
    let ConsolePage {
        page: DisplayPage {
            columns,
            rows,
            next,
        },
        examined,
        fetched,
        output_bytes: bytes,
    } = calls
        .fallible(CallKind::Query, "query", 3, &request)
        .await?;
    let count = rows.len();
    println!("\n{}\n{}", request.entity, bordered_table(&columns, &rows));
    let noun = if count == 1 { "row" } else { "rows" };
    println!("{count} {noun}; {examined} examined; {fetched} fetched; {bytes} encoded bytes.");
    println!(
        "Next cursor: {}",
        next.map_or_else(|| "none".into(), |c| lowercase_hex(&c, ""))
    );
    Ok(())
}

async fn aggregate(
    calls: &mut FixtureCalls<'_>,
    selection: RetainedSelection,
    work: u32,
    page_size: u32,
) -> Result<(), String> {
    let handle = calls
        .fallible::<Vec<u8>>(CallKind::Update, "aggregate_start", 120, &selection)
        .await?;
    println!("\n{} — {}", selection.entity, selection.select);
    let mut request = ic_db_cli::RetainedResume {
        selection,
        handle,
        sequence: 0,
        work,
        bytes: FIXTURE_OUTPUT_BYTES,
        page_size,
        after: None,
    };
    let run = resume(calls, &mut request).await;
    // Cleanup also runs after an output/resource refusal. No automatic
    // restart, lost cursor, or client-side aggregation is hidden here.
    let cleanup = calls
        .fallible::<()>(CallKind::Update, "aggregate_cancel", 122, &request.handle)
        .await;

    match (run, cleanup) {
        (Ok(()), result) | (result, Ok(())) => result,
        (Err(error), Err(cleanup)) => Err(format!("{error}; cleanup: {cleanup}")),
    }
}

async fn resume(
    calls: &mut FixtureCalls<'_>,
    request: &mut ic_db_cli::RetainedResume,
) -> Result<(), String> {
    // At most six rows per entity and two groups. A finite host bound
    // prevents transport/progress regressions from looping forever.
    for call in 1..=32 {
        let RetainedProgress {
            sequence: saved,
            phase,
            examined,
            input_bytes,
            output_bytes,
        } = calls
            .fallible(CallKind::Update, "aggregate_resume", 121, request)
            .await?;
        let label = phase.label();
        println!(
            "Call {call}: {label}; sequence {saved}; {examined} examined; {input_bytes} input bytes; {output_bytes} output bytes."
        );
        request.sequence = saved;

        match phase {
            RetainedPhase::Running => {}
            RetainedPhase::Complete(DisplayPage {
                columns,
                rows,
                next,
            }) => {
                println!("{}", bordered_table(&columns, &rows));
                if next.is_none() {
                    return Ok(());
                }
                request.after = next;
            }
            RetainedPhase::Expired | RetainedPhase::Invalidated => {
                return Err(format!("aggregate {label}"));
            }
        }
    }

    Err("aggregate exceeded the fixture's 32-call bound".into())
}