use super::*;
use crate::store::chat_rename::{Command, Decision, Delivery};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
pub(super) const ALPN: &[u8] = b"gent/chat-rename/1";
const FRAME: usize = 2048;
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Reply {
id: Uuid,
decision: Decision,
}
pub(super) async fn serve(conn: &Connection, store: SharedStore) -> Result<()> {
loop {
let (mut send, mut recv) =
tokio::time::timeout(Duration::from_secs(30), conn.accept_bi()).await??;
tokio::time::timeout(OPERATION, async {
let mut hello = [0];
recv.read_exact(&mut hello).await?;
ensure!(hello == [1], "unknown rename session");
let endpoint = conn.remote_id();
local(store.clone(), move |s| s.direct_allowed(endpoint)).await?;
send.write_all(&[1]).await?;
let command: Command = serde_json::from_slice(&recv.read_to_end(FRAME).await?)?;
let id = command.id;
let decision =
local(store.clone(), move |s| s.serve_rename(endpoint, &command)).await?;
send.write_all(&serde_json::to_vec(&Reply { id, decision })?)
.await?;
send.finish()?;
Ok::<_, anyhow::Error>(())
})
.await??;
}
}
impl Direct {
pub(crate) async fn send_rename(&self, store: SharedStore, work: Delivery) -> Result<()> {
let endpoint = work.address.id;
tokio::time::timeout(OPERATION, async {
let conn = self
.primary_pull_connection(&self.renames, work.address, ALPN, 4)
.await
.context("rename carrier unavailable")?;
let (mut send, mut recv) = conn.open_bi().await?;
send.write_all(&[1]).await?;
let mut ready = [0];
recv.read_exact(&mut ready).await?;
ensure!(ready == [1], "rename carrier did not confirm support");
let bytes = serde_json::to_vec(&work.command)?;
ensure!(bytes.len() <= FRAME, "rename command too large");
let command = work.command.clone();
local(store.clone(), move |s| {
s.dispatch_rename(endpoint, &command)
})
.await?;
send.write_all(&bytes).await?;
send.finish()?;
let reply: Reply = serde_json::from_slice(&recv.read_to_end(256).await?)?;
ensure!(reply.id == work.command.id, "rename receipt mismatch");
local(store, move |s| {
s.finish_rename(endpoint, &work.command, reply.decision)
})
.await
})
.await?
}
pub(in crate::sync) async fn rename_worker(&self, store: SharedStore, wakeup: Arc<Notify>) {
loop {
if let Ok(Some(work)) = local(store.clone(), |s| s.next_rename()).await {
let _ = self.send_rename(store.clone(), work).await;
continue;
}
let wait = local(store.clone(), |s| s.rename_retry_delay())
.await
.unwrap_or(Some(Duration::from_secs(15)));
if let Some(delay) = wait {
tokio::select! { _=wakeup.notified()=>{}, _=tokio::time::sleep(delay)=>{} }
} else {
wakeup.notified().await;
}
}
}
}