Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

8.3 KB
Raw Blame
//! CSV to Iggy β€” Rust analogue of the Python `csv_to_kafka` example, targeting
//! Apache Iggy instead of Kafka (Python ships an `iggy` connector with the same
//! shape as its `kafka` one).
//!
//! Reads local CSV files, converts each row to a JSON object (header row as
//! keys), and publishes one Iggy message per row via CocoIndex's declarative
//! `IggyTopicTarget`. Each row is keyed by the first CSV column.
//!
//!   cargo run -- index      # read ./data/*.csv -> send changed rows
//!   cargo run -- consume    # poll and print all messages on the topic
//!
//! Incrementality (two layers):
//!   - `process_csv` is memoized, so unchanged CSV files skip parsing entirely
//!     (each file is its own processing component declaring its rows'
//!     messages, so a removed file takes its messages with it);
//!   - the managed `IggyTopicTarget` only *sends* a message when its value
//!     changed since the last run. Iggy has no tombstone, so a removed row is
//!     represented by a custom deletion value (`{"_deleted":"<key>"}`).
//!
//! Stream/topic are user-managed (CocoIndex never creates/drops them); `index`
//! creates them up front as a convenience.
//!
//! Parallels the Python example:
//!   - target            : `iggy::mount_iggy_topic_target` (cf. `mount_iggy_topic_target`)
//!   - source            : `walk_dir(..).live()` + `ctx.mount_each_live` (cf. `localfs.walk_dir(live=True)` + `coco.mount_each`)
//!   - per-file compute  : `#[cocoindex::function(memo)]` declaring its messages (cf. `@coco.fn(memo=True)`)
//!   - declare a message : `target.declare_message(key, value)` (cf. `topic_target.declare_target_state`)

use cocoindex::Environment;
use cocoindex::connectors::iggy::{self, IggyProducer};

cocoindex::context_key!(static PRODUCER: IggyProducer);
use cocoindex::prelude::*;
use iggy::prelude::{
    CompressionAlgorithm, Consumer, Identifier, IggyExpiry, MaxTopicSize, MessageClient,
    PollingStrategy, StreamClient, SystemClient, TopicClient,
};
use std::sync::Arc;

const PARTITION: u32 = 0; // Iggy partitions are 0-indexed (matches the connector default).

fn connection_string() -> String {
    std::env::var("IGGY_CONNECTION_STRING")
        .unwrap_or_else(|_| "iggy://iggy:iggy@localhost:8090".to_string())
}

fn stream_name() -> String {
    std::env::var("IGGY_STREAM").unwrap_or_else(|_| "cocoindex".to_string())
}

fn topic_name() -> String {
    std::env::var("IGGY_TOPIC").unwrap_or_else(|_| "csv-rows".to_string())
}

/// Parse one CSV file and declare one message per row (cf. Python `process_csv`).
/// Memoized on the file: an unchanged file keeps its messages without re-parsing.
/// The topic target is one per app, so it is not part of the memo key.
#[cocoindex::function(memo, memo_key(target = skip))]
async fn process_csv(ctx: &Ctx, file: &FileEntry, target: &iggy::IggyTopicTarget) -> Result<()> {
    let text = file.read_text().await?;
    let mut reader = csv::Reader::from_reader(text.as_bytes());
    let headers = reader
        .headers()
        .map_err(|e| Error::engine(format!("csv headers: {e}")))?
        .clone();
    if headers.is_empty() {
        return Ok(());
    }
    for record in reader.records() {
        let record = record.map_err(|e| Error::engine(format!("csv record: {e}")))?;
        let Some(key) = record.get(0).filter(|s| !s.is_empty()) else {
            continue;
        };
        let mut row = serde_json::Map::new();
        for (header, field) in headers.iter().zip(record.iter()) {
            row.insert(
                header.to_string(),
                serde_json::Value::String(field.to_string()),
            );
        }
        let value = serde_json::to_string(&row).map_err(|e| Error::engine(format!("json: {e}")))?;
        target.declare_message(ctx, key, value)?;
    }
    Ok(())
}

/// Create the (user-managed) stream + single-partition topic if they don't exist.
async fn ensure_stream_topic(producer: &IggyProducer, stream: &str, topic: &str) -> Result<()> {
    let client = producer.client();
    // create_* error if the stream/topic already exists; that's fine.
    let _ = client.create_stream(stream).await;
    let stream_id = Identifier::from_str_value(stream)
        .map_err(|e| Error::engine(format!("iggy stream id: {e}")))?;
    let _ = client
        .create_topic(
            &stream_id,
            topic,
            1,
            CompressionAlgorithm::None,
            None,
            IggyExpiry::NeverExpire,
            MaxTopicSize::ServerDefault,
        )
        .await;
    Ok(())
}

async fn index(producer: IggyProducer, stream: String, topic: String) -> Result<()> {
    ensure_stream_topic(&producer, &stream, &topic).await?;

    // The producer is provided under a `ContextKey`; the target names the key.
    let app = Environment::builder()
        .db_path(std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(".cocoindex_db"))
        .provide_key(&PRODUCER, producer)
        .build()
        .await?
        .app("CsvToIggyRust")
        .await?;

    let stats = app
        .run(move |ctx| {
            let stream = stream.clone();
            let topic = topic.clone();
            async move {
                let options = iggy::IggyTopicOptions {
                    partition: PARTITION,
                    // Iggy has no tombstone; emit a delete marker for removed rows.
                    deletion_value_fn: Some(Arc::new(|key: &[u8]| {
                        format!("{{\"_deleted\":\"{}\"}}", String::from_utf8_lossy(key))
                            .into_bytes()
                    })),
                };
                let target =
                    iggy::mount_iggy_topic_target(&ctx, &PRODUCER, stream, topic, options).await?;

                // The source supports live watch (cf. Python `localfs.walk_dir(live=True)`).
                let files = walk_dir("./data")
                    .path_matcher(PatternFilePathMatcher::include(["**/*.csv"])?)
                    .live();
                // One processing component per file: each file's messages sync and
                // clean up with that file (cf. Python `coco.mount_each(process_csv, files.items(), topic_target)`).
                ctx.mount_each_live(&"process_csv", files, move |ctx, file: FileEntry| {
                    let target = target.clone();
                    async move { process_csv(&ctx, &file, &target).await }
                })
                .await
            }
        })
        .await?;
    println!("{stats}");
    Ok(())
}

async fn consume(producer: &IggyProducer, stream: &str, topic: &str) -> Result<()> {
    let stream_id = Identifier::from_str_value(stream)
        .map_err(|e| Error::engine(format!("iggy stream id: {e}")))?;
    let topic_id = Identifier::from_str_value(topic)
        .map_err(|e| Error::engine(format!("iggy topic id: {e}")))?;
    let consumer = Consumer::new(
        Identifier::numeric(1).map_err(|e| Error::engine(format!("iggy consumer id: {e}")))?,
    );
    let polled = producer
        .client()
        .poll_messages(
            &stream_id,
            &topic_id,
            Some(PARTITION),
            &consumer,
            &PollingStrategy::offset(0),
            10_000,
            false,
        )
        .await
        .map_err(|e| Error::engine(format!("iggy poll: {e}")))?;

    println!("Messages on {stream}/{topic} (partition {PARTITION}):");
    println!("{}", "-".repeat(60));
    for m in &polled.messages {
        println!("  {}", String::from_utf8_lossy(&m.payload));
    }
    println!("{}", "-".repeat(60));
    println!("{} message(s)", polled.messages.len());
    Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
    dotenvy::dotenv().ok();
    let cmd = std::env::args()
        .nth(1)
        .unwrap_or_else(|| "index".to_string());
    let conn = connection_string();
    let stream = stream_name();
    let topic = topic_name();

    let producer = IggyProducer::connect(&conn).await?;
    // Ensure we're logged in / reachable before doing work.
    producer
        .client()
        .ping()
        .await
        .map_err(|e| Error::engine(format!("iggy ping: {e}")))?;

    match cmd.as_str() {
        "consume" => consume(&producer, &stream, &topic).await?,
        "index" => index(producer, stream, topic).await?,
        other => {
            eprintln!("unknown command {other:?}; use `index` or `consume`");
            std::process::exit(2);
        }
    }
    Ok(())
}