mod client;
mod publish;
mod server;
mod subscribe;
mod web;
use client::*;
use hang::moq_lite;
use publish::*;
use server::*;
use subscribe::*;
use web::*;
use clap::{Parser, Subcommand};
use std::path::PathBuf;
use url::Url;
#[derive(Parser, Clone)]
#[command(version = env!("VERSION"))]
pub struct Cli {
#[command(flatten)]
log: moq_native::Log,
#[command(flatten)]
#[cfg(feature = "iroh")]
iroh: moq_native::IrohEndpointConfig,
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand, Clone)]
pub enum Command {
Serve {
#[command(flatten)]
config: moq_native::ServerConfig,
#[arg(long)]
name: String,
#[arg(long)]
dir: Option<PathBuf>,
#[command(subcommand)]
format: PublishFormat,
},
Publish {
#[command(flatten)]
config: moq_native::ClientConfig,
#[arg(long)]
url: Url,
#[arg(long)]
name: String,
#[command(subcommand)]
format: PublishFormat,
},
Subscribe {
#[command(flatten)]
config: moq_native::ClientConfig,
#[arg(long)]
url: Url,
#[arg(long)]
name: String,
#[command(flatten)]
args: SubscribeArgs,
},
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
rustls::crypto::aws_lc_rs::default_provider()
.install_default()
.expect("failed to install default crypto provider");
let cli = Cli::parse();
cli.log.init();
#[cfg(feature = "iroh")]
let iroh = cli.iroh.bind().await?;
match cli.command {
Command::Serve {
config,
dir,
name,
format,
} => {
let publish = Publish::new(&format)?;
let web_bind = config.bind.clone().unwrap_or_else(|| "[::]:443".to_string());
let server = config.init()?;
#[cfg(feature = "iroh")]
let server = server.with_iroh(iroh);
let web_tls = server.tls_info();
tokio::select! {
res = run_server(server, name, publish.consume()) => res,
res = run_web(&web_bind, web_tls, dir) => res,
res = publish.run() => res,
}
}
Command::Publish {
config,
url,
name,
format,
} => {
let publish = Publish::new(&format)?;
let client = config.init()?;
#[cfg(feature = "iroh")]
let client = client.with_iroh(iroh);
run_client(client, url, name, publish).await
}
Command::Subscribe {
config,
url,
name,
args,
} => {
let client = config.init()?;
#[cfg(feature = "iroh")]
let client = client.with_iroh(iroh);
run_subscribe(client, url, name, args).await
}
}
}
async fn run_subscribe(client: moq_native::Client, url: Url, name: String, args: SubscribeArgs) -> anyhow::Result<()> {
let origin = moq_lite::Origin::random().produce();
let consumer = origin.consume();
tracing::info!(%url, %name, "connecting");
let reconnect = client.with_consume(origin).reconnect(url);
#[cfg(unix)]
let _ = sd_notify::notify(&[sd_notify::NotifyState::Ready]);
let broadcast = consumer
.announced_broadcast(&name)
.await
.ok_or_else(|| anyhow::anyhow!("origin closed before broadcast was announced"))?;
let subscribe = Subscribe::new(broadcast, args);
tokio::select! {
res = subscribe.run() => res,
res = reconnect.closed() => res,
_ = tokio::signal::ctrl_c() => Ok(()),
}
}