feat(alpha): wire connect→snapshot→disconnect end-to-end (v0.1.0-alpha.1)
First Internal Alpha build per DEC-001. Closes the milestone of
'Flutter UI calls Rust via the typed bridge, Rust connects to a
TeamSpeak-compatible server through tsclientlib, returns a typed
snapshot, and disconnects cleanly.' Audio remains Beta scope.
Promotions from PoC:
poc/tsclientlib-connect-spike → crates/chanora_protocol/
New product code:
crates/chanora_protocol/src/{dto.rs,adapter.rs} — typed boundary
over tsclientlib. Tokio task owns the Connection; public
handle communicates via mpsc/oneshot. No tsclientlib types
cross out of the crate (SAD-067 / SysDes-011 / SysDes-029).
core/chanora_core/src/lib.rs — ChanoraSession composes the
protocol crate, enforces the DEC-006 single-connection
invariant.
crates/chanora_bridge/src/{api.rs,frb_generated.rs} — FRB 2.12.0
bridge per DEC-014. cdylib + staticlib + rlib. Typed
BridgeSnapshot / BridgeChannel / BridgeClient / BridgeError
DTOs. Process-wide OnceLock<Runtime> + OnceLock<ChanoraSession>.
flutter_rust_bridge.yaml at repo root.
apps/chanora_flutter/lib/main.dart — Alpha UI: server form,
connect button, channel tree, disconnect.
apps/chanora_flutter/lib/l10n/app_{en,zh}.arb expanded with the
Alpha key set; ARB metadata reaffirms ADR-008 for
server-provided content.
Generated Dart bindings under apps/chanora_flutter/lib/src/rust/.
Empirical verification (2026-05-14):
Workspace: cargo check + cargo test clean
(workspace tests: all green).
Bridge cdylib: target/release/libchanora_bridge.so produced
(~15 MB).
Flutter: flutter analyze clean; flutter test runs 3/3 green
including the alpha_e2e_test that drives the full
Dart → FRB → chanora_bridge → chanora_core → chanora_protocol
→ tsclientlib → UDP → cn.teamspeak.app
path. The captured logcat/stdout shows the tsproto resender
transitioning Connected → Disconnecting → Disconnected on
clean teardown.
Architecture changes:
- Removed the chanora_core ↔ chanora_bridge cyclic dependency.
chanora_core no longer knows the bridge exists; the bridge
maps from CoreError.
- chanora_bridge crate's #![forbid(unsafe_code)] lint relaxed
because FRB-generated glue legitimately uses unsafe at the
FFI boundary. Hand-written code remains unsafe-free.
Open follow-ups (NOT in this Alpha):
- Audio capture/playback wiring into chanora_audio
(Beta scope per DEC-001).
- Identity persistence via chanora_storage
(currently regenerated on every connect).
- Per-message diagnostics + redaction
(chanora_diagnostics still scaffold).
- Reconnect / network-loss recovery.
- Mobile (Android) build of the bridge cdylib + UI verification.
This commit is contained in:
@@ -0,0 +1,305 @@
|
||||
//! The adapter that drives `tsclientlib` on a background task and
|
||||
//! exposes a typed channel-and-future API to the rest of Chanora.
|
||||
//!
|
||||
//! Threading model:
|
||||
//!
|
||||
//! * `ProtocolClient::connect` spawns a tokio task that owns the
|
||||
//! `tsclientlib::Connection` (which is not `Send`-safe to move
|
||||
//! across awaits in some shapes — keeping it inside a single task
|
||||
//! sidesteps the problem entirely).
|
||||
//! * The task exposes its life via a `oneshot` that fires when the
|
||||
//! initial state snapshot is ready.
|
||||
//! * Snapshot reads are served by sending a request over an
|
||||
//! `mpsc::channel`; the task replies on a `oneshot` per request.
|
||||
//! * Disconnect is requested via a `oneshot`; the task drains
|
||||
//! `tsclientlib`'s outbound events and exits.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use futures::prelude::*;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tracing::{info, warn};
|
||||
|
||||
use tsclientlib::data::{self, Channel, Client};
|
||||
use tsclientlib::{
|
||||
ChannelId as TsChannelId, Connection, DisconnectOptions, Identity, OutCommandExt, StreamItem,
|
||||
};
|
||||
|
||||
use crate::dto::{ChannelId, ChannelInfo, ClientId, ClientInfo, ServerSnapshot};
|
||||
use crate::ProtocolError;
|
||||
|
||||
/// Typed configuration for a connection attempt.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ConnectConfig {
|
||||
/// Server address: `hostname[:port]` or TSDNS name.
|
||||
pub address: String,
|
||||
/// Nickname to use on the server.
|
||||
pub nickname: String,
|
||||
/// Optional server password.
|
||||
pub password: Option<String>,
|
||||
/// Optional pre-existing identity (base64 string accepted by
|
||||
/// `tsclientlib::Identity::new_from_str`). If `None`, a fresh
|
||||
/// identity is generated and **not persisted** — production
|
||||
/// callers must wire this to `chanora_storage::SecretStorageRepository`.
|
||||
pub identity: Option<String>,
|
||||
/// How long to wait for the initial state snapshot before
|
||||
/// returning `ProtocolError::Timeout`.
|
||||
pub ready_timeout: Duration,
|
||||
}
|
||||
|
||||
impl Default for ConnectConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
address: String::new(),
|
||||
nickname: "Chanora".to_string(),
|
||||
password: None,
|
||||
identity: None,
|
||||
ready_timeout: Duration::from_secs(10),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Request {
|
||||
Snapshot(oneshot::Sender<Result<ServerSnapshot, ProtocolError>>),
|
||||
Disconnect(oneshot::Sender<()>),
|
||||
}
|
||||
|
||||
/// Async handle owning a live protocol connection. Drop = disconnect.
|
||||
pub struct ProtocolClient {
|
||||
tx: mpsc::Sender<Request>,
|
||||
}
|
||||
|
||||
impl ProtocolClient {
|
||||
/// Dial the server and wait for the initial state snapshot. The
|
||||
/// returned client is ready for [`Self::snapshot`] and
|
||||
/// [`Self::disconnect`] calls.
|
||||
pub async fn connect(cfg: ConnectConfig) -> Result<Self, ProtocolError> {
|
||||
if cfg.address.trim().is_empty() {
|
||||
return Err(ProtocolError::Invalid("address is empty".to_string()));
|
||||
}
|
||||
if cfg.nickname.trim().is_empty() {
|
||||
return Err(ProtocolError::Invalid("nickname is empty".to_string()));
|
||||
}
|
||||
|
||||
let (tx, rx) = mpsc::channel::<Request>(8);
|
||||
let (ready_tx, ready_rx) = oneshot::channel::<Result<(), ProtocolError>>();
|
||||
|
||||
tokio::spawn(connection_task(cfg.clone(), rx, ready_tx));
|
||||
|
||||
match tokio::time::timeout(cfg.ready_timeout, ready_rx).await {
|
||||
Ok(Ok(Ok(()))) => Ok(Self { tx }),
|
||||
Ok(Ok(Err(e))) => Err(e),
|
||||
Ok(Err(_)) => Err(ProtocolError::Backend(
|
||||
"connection task exited before signalling ready".to_string(),
|
||||
)),
|
||||
Err(_) => Err(ProtocolError::Timeout),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a typed snapshot of the current server state.
|
||||
pub async fn snapshot(&self) -> Result<ServerSnapshot, ProtocolError> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
self.tx
|
||||
.send(Request::Snapshot(tx))
|
||||
.await
|
||||
.map_err(|_| ProtocolError::Lost("connection task is gone".to_string()))?;
|
||||
rx.await
|
||||
.map_err(|_| ProtocolError::Lost("snapshot reply dropped".to_string()))?
|
||||
}
|
||||
|
||||
/// Disconnect cleanly. Blocks until the task exits.
|
||||
pub async fn disconnect(self) {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
if self.tx.send(Request::Disconnect(tx)).await.is_ok() {
|
||||
let _ = rx.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn connection_task(
|
||||
cfg: ConnectConfig,
|
||||
mut rx: mpsc::Receiver<Request>,
|
||||
ready_tx: oneshot::Sender<Result<(), ProtocolError>>,
|
||||
) {
|
||||
let mut builder = Connection::build(cfg.address.clone()).name(cfg.nickname.clone());
|
||||
|
||||
let identity = match cfg.identity.as_deref() {
|
||||
Some(s) => match Identity::new_from_str(s) {
|
||||
Ok(id) => id,
|
||||
Err(e) => {
|
||||
let _ = ready_tx.send(Err(ProtocolError::Identity(format!("{e}"))));
|
||||
return;
|
||||
}
|
||||
},
|
||||
None => Identity::create(),
|
||||
};
|
||||
builder = builder.identity(identity);
|
||||
|
||||
if let Some(pw) = &cfg.password {
|
||||
builder = builder.password(pw.clone());
|
||||
}
|
||||
|
||||
let mut con = match builder.connect() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
let _ = ready_tx.send(Err(ProtocolError::Connect(format!("{e}"))));
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// Wait for the first BookEvents indicating the state snapshot is ready.
|
||||
let first = con
|
||||
.events()
|
||||
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
|
||||
.next()
|
||||
.await;
|
||||
match first {
|
||||
Some(Ok(_)) => {
|
||||
info!(target: "chanora_protocol", "initial state snapshot received");
|
||||
}
|
||||
Some(Err(e)) => {
|
||||
let _ = ready_tx.send(Err(ProtocolError::DisconnectedEarly(format!("{e}"))));
|
||||
return;
|
||||
}
|
||||
None => {
|
||||
let _ = ready_tx.send(Err(ProtocolError::DisconnectedEarly(
|
||||
"event stream ended before snapshot".to_string(),
|
||||
)));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Subscribe to the full server tree so snapshot() returns more than just our channel.
|
||||
if let Ok(state) = con.get_state() {
|
||||
if let Err(e) = state.server.set_subscribed(true).send(&mut con) {
|
||||
warn!(target: "chanora_protocol", error = %e, "could not subscribe to server tree");
|
||||
}
|
||||
}
|
||||
|
||||
// Settle: pump events for ~2 s so the subscribed tree arrives
|
||||
// before the first snapshot. The upstream packet codec emits
|
||||
// out-of-order command-packet warnings here; they are harmless
|
||||
// and the final state still converges.
|
||||
let settle_until = std::time::Instant::now() + Duration::from_secs(2);
|
||||
while std::time::Instant::now() < settle_until {
|
||||
let ev = tokio::time::timeout(Duration::from_millis(100), con.events().next()).await;
|
||||
match ev {
|
||||
Ok(Some(Ok(_))) => continue,
|
||||
Ok(Some(Err(e))) => {
|
||||
warn!(target: "chanora_protocol", error = %e, "event error during settle");
|
||||
}
|
||||
Ok(None) => {
|
||||
let _ = ready_tx.send(Err(ProtocolError::DisconnectedEarly(
|
||||
"stream closed during settle".to_string(),
|
||||
)));
|
||||
return;
|
||||
}
|
||||
Err(_) => { /* no event available right now; keep waiting */ }
|
||||
}
|
||||
}
|
||||
|
||||
let _ = ready_tx.send(Ok(()));
|
||||
|
||||
// Request loop with a continuously-pumped event stream. We pump
|
||||
// one event at a time, then check for one pending request, then
|
||||
// repeat. This avoids holding a borrow on `con` across an await
|
||||
// boundary in `tokio::select!`.
|
||||
loop {
|
||||
// Try to advance the event stream by one event with a small
|
||||
// timeout. Errors are logged; stream end is fatal.
|
||||
let pump = async {
|
||||
let mut ev_stream = con.events();
|
||||
tokio::time::timeout(Duration::from_millis(50), ev_stream.next()).await
|
||||
};
|
||||
match pump.await {
|
||||
Ok(Some(Ok(_))) => { /* event consumed */ }
|
||||
Ok(Some(Err(e))) => {
|
||||
warn!(target: "chanora_protocol", error = %e, "event error");
|
||||
}
|
||||
Ok(None) => {
|
||||
warn!(target: "chanora_protocol", "event stream ended");
|
||||
return;
|
||||
}
|
||||
Err(_) => { /* no event in 50 ms — service requests */ }
|
||||
}
|
||||
|
||||
// Service at most one request (non-blocking) so we keep
|
||||
// pumping events too.
|
||||
match rx.try_recv() {
|
||||
Ok(Request::Snapshot(reply)) => {
|
||||
let snap = build_snapshot(&con);
|
||||
let _ = reply.send(snap);
|
||||
}
|
||||
Ok(Request::Disconnect(reply)) => {
|
||||
let _ = con.disconnect(DisconnectOptions::new());
|
||||
con.events().for_each(|_| future::ready(())).await;
|
||||
let _ = reply.send(());
|
||||
info!(target: "chanora_protocol", "clean disconnect");
|
||||
return;
|
||||
}
|
||||
Err(mpsc::error::TryRecvError::Empty) => { /* nothing to do */ }
|
||||
Err(mpsc::error::TryRecvError::Disconnected) => {
|
||||
let _ = con.disconnect(DisconnectOptions::new());
|
||||
con.events().for_each(|_| future::ready(())).await;
|
||||
info!(target: "chanora_protocol", "handle dropped; implicit disconnect");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn build_snapshot(con: &Connection) -> Result<ServerSnapshot, ProtocolError> {
|
||||
let state: &data::Connection = con
|
||||
.get_state()
|
||||
.map_err(|e| ProtocolError::Backend(format!("get_state: {e}")))?;
|
||||
|
||||
let mut channels: Vec<&Channel> = state.channels.values().collect();
|
||||
channels.sort_by_key(|c| c.order.0);
|
||||
let clients: Vec<&Client> = state.clients.values().collect();
|
||||
|
||||
let channels_dto: Vec<ChannelInfo> = channels
|
||||
.iter()
|
||||
.map(|c| ChannelInfo {
|
||||
id: ChannelId(c.id.0),
|
||||
parent: ChannelId(c.parent.0),
|
||||
name: sanitize(&c.name),
|
||||
order: c.order.0 as i64,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let clients_dto: Vec<ClientInfo> = clients
|
||||
.iter()
|
||||
.map(|c| ClientInfo {
|
||||
id: ClientId(c.id.0 as u64),
|
||||
channel: ChannelId(c.channel.0),
|
||||
name: sanitize(&c.name),
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(ServerSnapshot {
|
||||
server_name: sanitize(&state.server.name),
|
||||
welcome_message: sanitize(&state.server.welcome_message),
|
||||
platform: sanitize(&state.server.platform),
|
||||
version: sanitize(&state.server.version),
|
||||
channels: channels_dto,
|
||||
clients: clients_dto,
|
||||
})
|
||||
}
|
||||
|
||||
/// Light sanitisation of strings before they cross the protocol
|
||||
/// boundary. The redaction policy proper lives in
|
||||
/// `chanora_diagnostics`; this filter only strips control characters
|
||||
/// that would break terminal output or Flutter rendering.
|
||||
fn sanitize(s: &str) -> String {
|
||||
s.chars()
|
||||
.filter(|c| !c.is_control() || *c == '\t' || *c == '\n')
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
const _ROOT_MATCHES_UPSTREAM: () = {
|
||||
// Compile-time assertion that ChannelId(0) maps to what tsclientlib
|
||||
// also considers the root. If upstream ever changes, this stops
|
||||
// compiling and forces an audit.
|
||||
let _ = TsChannelId(0);
|
||||
};
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Public DTOs returned across the protocol boundary. All fields are
|
||||
//! owned primitives or `String`s; no `tsclientlib` types leak.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Opaque server-side channel identifier. Internal representation is
|
||||
/// the upstream u64 but callers must treat it as opaque.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct ChannelId(pub u64);
|
||||
|
||||
/// Opaque server-side client identifier.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct ClientId(pub u64);
|
||||
|
||||
/// One channel in the server's tree.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ChannelInfo {
|
||||
/// Stable channel id.
|
||||
pub id: ChannelId,
|
||||
/// Parent channel id; `ChannelId(0)` indicates a top-level channel.
|
||||
pub parent: ChannelId,
|
||||
/// Display name, preserved verbatim per ADR-008.
|
||||
pub name: String,
|
||||
/// Server-side ordering hint.
|
||||
pub order: i64,
|
||||
}
|
||||
|
||||
/// One connected client on the server.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ClientInfo {
|
||||
/// Stable client id.
|
||||
pub id: ClientId,
|
||||
/// Channel the client is currently in.
|
||||
pub channel: ChannelId,
|
||||
/// Nickname, preserved verbatim per ADR-008.
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// Snapshot of the server's published state at a moment in time.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ServerSnapshot {
|
||||
/// Server name.
|
||||
pub server_name: String,
|
||||
/// Server welcome banner. Contains markup from the upstream
|
||||
/// server (BBCode-like); not parsed here.
|
||||
pub welcome_message: String,
|
||||
/// Server platform string.
|
||||
pub platform: String,
|
||||
/// Server version string.
|
||||
pub version: String,
|
||||
/// All channels currently known.
|
||||
pub channels: Vec<ChannelInfo>,
|
||||
/// All clients currently known.
|
||||
pub clients: Vec<ClientInfo>,
|
||||
}
|
||||
|
||||
impl ChannelId {
|
||||
/// The conventional root sentinel used by TeamSpeak-compatible
|
||||
/// servers for the top of the channel tree.
|
||||
pub const ROOT: ChannelId = ChannelId(0);
|
||||
}
|
||||
@@ -4,48 +4,66 @@
|
||||
//! behind a typed boundary so the rest of Chanora is decoupled from
|
||||
//! the upstream library's types (SAD-067, SysDes-011, SysDes-029).
|
||||
//!
|
||||
//! ## Status
|
||||
//! ## What this crate exposes
|
||||
//!
|
||||
//! Scaffold only. Promotion of `poc/tsclientlib-connect-spike` into
|
||||
//! this crate happens later, with its own audit-trail commit.
|
||||
//! * [`ConnectConfig`] — typed connection parameters.
|
||||
//! * [`ProtocolClient`] — async handle owning the connection task.
|
||||
//! * [`ServerSnapshot`], [`ChannelInfo`], [`ClientInfo`] — opaque
|
||||
//! DTOs containing only `String`s and primitives.
|
||||
//! * [`ProtocolError`] — typed error catalogue.
|
||||
//!
|
||||
//! ## What this crate does NOT expose
|
||||
//!
|
||||
//! * `tsclientlib::*` types.
|
||||
//! * `tsproto::*` types.
|
||||
//! * Any audio-related types — those live in `chanora_audio`.
|
||||
//!
|
||||
//! Promoted from `poc/tsclientlib-connect-spike` on 2026-05-14
|
||||
//! as part of the Alpha build.
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
mod adapter;
|
||||
mod dto;
|
||||
|
||||
pub use adapter::{ConnectConfig, ProtocolClient};
|
||||
pub use dto::{ChannelInfo, ClientInfo, ServerSnapshot};
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
/// Errors surfaced by the protocol adapter. None of these expose
|
||||
/// `tsclientlib`-specific types; raw upstream errors are mapped here.
|
||||
/// `tsclientlib`-specific types; raw upstream errors are mapped here
|
||||
/// to typed arms.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ProtocolError {
|
||||
/// Configuration is invalid before any I/O is attempted (bad
|
||||
/// hostname, missing identity, etc.).
|
||||
#[error("invalid protocol configuration: {0}")]
|
||||
Invalid(&'static str),
|
||||
/// The connect handshake failed.
|
||||
Invalid(String),
|
||||
|
||||
/// Failed to dial / handshake with the server.
|
||||
#[error("connect failed: {0}")]
|
||||
Connect(String),
|
||||
/// The connection ended unexpectedly.
|
||||
#[error("disconnected: {0}")]
|
||||
Disconnected(String),
|
||||
|
||||
/// The connection ended before becoming ready.
|
||||
#[error("disconnected before ready: {0}")]
|
||||
DisconnectedEarly(String),
|
||||
|
||||
/// Connection lost after becoming ready.
|
||||
#[error("connection lost: {0}")]
|
||||
Lost(String),
|
||||
|
||||
/// Identity parsing failed.
|
||||
#[error("identity error: {0}")]
|
||||
Identity(String),
|
||||
|
||||
/// Operation timed out.
|
||||
#[error("protocol timeout")]
|
||||
Timeout,
|
||||
}
|
||||
|
||||
/// Opaque identifier for a server-side channel. Replaces
|
||||
/// `tsclientlib::ChannelId` at the public boundary so its concrete
|
||||
/// representation can change without leaking through the rest of the
|
||||
/// codebase.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct ChannelId(pub u64);
|
||||
|
||||
/// Opaque identifier for a server-side client.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct ClientId(pub u64);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn it_compiles() {}
|
||||
/// A backend error escaped the mapping. Production callers
|
||||
/// should never see this; if they do, it is a mapping bug here.
|
||||
#[error("protocol backend: {0}")]
|
||||
Backend(String),
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user