use std::{str::FromStr, thread};
use anyhow::Context;
use orchestra_toolkit::*;
fn sync_world(session: Session, entity: Entity, auth: Token) {
let outlet = session
.create_outlet(String255::unchecked("Test outlet sync"), auth)
.call()
.expect("Sync: Failed to create outlet");
session
.subscribe_event(entity, outlet, auth)
.call()
.expect("Sync: Failed to subscribe outlet to entity");
for i in 0..4 {
let res = session.wait_event(outlet, auth).call();
match res {
Ok(event) => println!(" Sync event #{i}: Received event with name: {}", event.name),
Err(e) => println!(" Sync event #{i}: Error {}", e),
}
}
}
fn asynchronous_world(session: Session, entity: Entity, auth: Token) {
session.run_async(|session| _asynchronous_world(session, entity, auth))
}
async fn _asynchronous_world(session: &SessionAsync, entity: Entity, auth: Token) {
let outlet = session
.create_outlet(String255::unchecked("Test outlet sync"), auth)
.await
.expect("Sync: Failed to create outlet");
session
.subscribe_event(entity, outlet, auth)
.await
.expect("Sync: Failed to subscribe outlet to entity");
for i in 0..4 {
let res = session.wait_event(outlet, auth).await;
match res {
Ok(event) => println!("Async event #{i}: Received event with name: {}", event.name),
Err(e) => println!("Async event #{i}: Error {}", e),
}
}
}
fn main() -> anyhow::Result<()> {
dotenv::dotenv().ok();
let mut config = SessionConfig::default();
if let Ok(host) = std::env::var("AVESTERRA_HOST") {
config.address = host;
}
if let Ok(port_str) = std::env::var("AVESTERRA_PORT") {
config.port = u16::from_str(&port_str).context("Parsing `AVESTERRA_PORT`")?;
}
if let Ok(cert_dir_path) = std::env::var("AVESTERRA_CERTIFICATE_DIR_PATH") {
config.pem_filepath = (cert_dir_path + "/avesterra.pem").try_into()?;
}
let auth = if let Ok(auth_str) = std::env::var("AVESTERRA_AUTH") {
Token::from_str(&auth_str).context("Parsing authorization token given from env")?
} else {
Token::NULL
};
let session = Session::initialize(config)?;
let entity = session
.create_entity(String255::unchecked("Test entity"), auth)
.call()?;
let s1 = session.clone();
let s2 = session.clone();
let s3 = session.clone();
let t1 = thread::spawn(move || sync_world(s1, entity, auth));
let t2 = thread::spawn(move || asynchronous_world(s2, entity, auth));
let t3 = thread::spawn(move || {
for i in 0..16 {
let name = format!("Test event #{i}");
let res = s3
.publish_event(entity, Event::Null, auth)
.with_name(String255::unchecked(&name))
.call();
match res {
Ok(_) => println!("Published event #{i}: {}. Maybe someone heard me", name),
Err(e) => println!("Error publishing event #{i}: {}", e),
}
}
});
t1.join().unwrap();
t2.join().unwrap();
t3.join().unwrap();
session.finalize();
Ok(())
}