engawa-chat 0.5.0

A peer-to-peer chat lobby for editors and browsers
use std::collections::VecDeque;

use futures_lite::{Stream, StreamExt, stream};
use iroh::{Endpoint, EndpointId, address_lookup::memory::MemoryLookup};
use tokio::sync::mpsc;

use crate::rendezvous;

pub(crate) enum Event {
    Peer(EndpointId),
    Available(bool),
}

/// The session polls both the rendezvous client and its updates. Dropping the
/// stream cancels discovery; an invitation-only session never starts a client.
pub(crate) fn events(
    endpoint: &Endpoint,
    routes: Option<MemoryLookup>,
) -> impl Stream<Item = Event> + use<> {
    let endpoint = endpoint.clone();
    stream::iter(routes).flat_map(move |routes| {
        let (send, mut recv) = mpsc::channel(16);
        let run = rendezvous::run(endpoint.clone(), send);
        let mut known = VecDeque::new();
        let updates = stream::poll_fn(move |cx| {
            recv.poll_recv(cx).map(|event| {
                event.map(|event| match event {
                    rendezvous::Update::Available(available) => Event::Available(available),
                    rendezvous::Update::Peer(addr) => {
                        let id = addr.id;
                        // Gossip accepts endpoint IDs only. Replace stale relay routes
                        // before joining and bound retained routes on a busy public lobby.
                        if routes.set_endpoint_info(addr).is_none() {
                            if known.len() == 128 {
                                routes.remove_endpoint_info(known.pop_front().expect("full cache"));
                            }
                            known.push_back(id);
                        }
                        Event::Peer(id)
                    }
                })
            })
        });
        stream::once_future(async move {
            run.await;
            Event::Available(false)
        })
        .or(updates)
    })
}

pub(crate) fn status(joined: bool, available: Option<bool>) -> &'static str {
    match (joined, available) {
        (true, Some(false)) => "公開の縁側に接続中(公開ピア探索は利用できません。再試行中)",
        (true, _) => "公開の縁側に接続しました",
        (false, Some(false)) => {
            "接続中のピアはいません。公開ピア探索は利用できません。再試行中です(招待で参加できます)"
        }
        (false, _) => "接続中のピアはいません。他の参加者を待っています",
    }
}