From 2203e8f84062fdeb98e27ee7a926d1a3be2d8b94 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 28 Sep 2026 02:55:29 +0000 Subject: [PATCH] voelinctl, it-smoke: chat history, gateway features and the stream directory through the engine `voelinctl gateway --engine` runs one engine session against a gateway, optionally with voice, and prints every history batch, gateway update and stream event as a line: --chat opens chats (with --db, stored history), --older pages back, --request sends any gateway request as JSON (admin config, permission rules, events, ...), --roundtrip posts, pins, reacts, starts a topic from the post, posts into it and reads it back, --stream-seconds streams synthetic frames (registering in the directory) and --watch-streamer watches a stream once found. it-smoke adds three steps with the gateway running: messages sent while a user is offline reach its stored history on the next connect (the admin sets relay.pinned_channels at runtime for it); the pin/react/topic round trip as a normal user with a permission rule the admin sets; and on TeamSpeak 6 a stream registered in the directory found and watched by a viewer that connects later. The gateway's port can be moved (TSGW_PORT_TS3/TS6), and default builds go to $CARGO_TARGET_DIR. A chat's first stored page is no longer marked complete while its gateway is still connecting. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- crates/voelin-core/src/history.rs | 10 +- crates/voelin-core/src/session.rs | 5 +- scripts/it-smoke.sh | 126 +++++++- tools/voelinctl/src/engine.rs | 500 ++++++++++++++++++++++++++++++ tools/voelinctl/src/gateway.rs | 68 +++- tools/voelinctl/src/main.rs | 5 +- 6 files changed, 701 insertions(+), 13 deletions(-) create mode 100644 tools/voelinctl/src/engine.rs diff --git a/crates/voelin-core/src/history.rs b/crates/voelin-core/src/history.rs index 4af91fa..a9d0397 100644 --- a/crates/voelin-core/src/history.rs +++ b/crates/voelin-core/src/history.rs @@ -564,13 +564,19 @@ pub(crate) fn gateway_history(client: &GatewayClient, target: &ChatTarget) -> bo /// A chat opened (or its session reconnected): the stored page, then what /// the gateway has that we do not. -pub(crate) async fn open_chat(ctx: ChatCtx, target: ChatTarget, gateway: Option) { +pub(crate) async fn open_chat( + ctx: ChatCtx, + target: ChatTarget, + gateway: Option, + gateway_pending: bool, +) { let gateway = gateway.filter(|g| gateway_history(g, &target)); let limit = ctx.page_limit(); let query = PageQuery { limit: limit.map(|l| l as usize), ..Default::default() }; match ctx.history.page(&ctx.server_uid, &target, query, ctx.memory()).await { Ok(local) => { - let complete = gateway.is_none() && limit.is_none_or(|l| local.len() < l as usize); + let short = limit.is_none_or(|l| local.len() < l as usize); + let complete = short && gateway.is_none() && !gateway_pending; ctx.emit_batch(&target, local, HistorySource::Local, complete); } Err(e) => warn!("cannot read chat history: {e}"), diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index 31ec212..6dc83c8 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -521,7 +521,10 @@ impl Session { /// Show a chat's stored messages, then sync it with the gateway. fn open_history(&self, target: &ChatTarget) { if let Some(ctx) = self.chat_ctx() { - tokio::spawn(history::open_chat(ctx, target.clone(), self.gateway_client.clone())); + // A gateway that is still connecting may have more. + let pending = self.gateway.is_some() && self.gateway_client.is_none(); + let gateway = self.gateway_client.clone(); + tokio::spawn(history::open_chat(ctx, target.clone(), gateway, pending)); } } diff --git a/scripts/it-smoke.sh b/scripts/it-smoke.sh index 1b1624d..2441f4a 100755 --- a/scripts/it-smoke.sh +++ b/scripts/it-smoke.sh @@ -11,12 +11,23 @@ # 6. relay chat: a query relay reads channel chat and posts into the channel # 7. gateway (tsgw): login with a TeamSpeak identity, presence, channel chat # both ways, refusal of an identity the server does not know -# 8. stream (TeamSpeak 6 only): a viewer watches a synthetic VP8 + Opus stream -# 9. late stream (TeamSpeak 6 only): a viewer that connects after the stream +# 8. chat history through the engine (voelinctl gateway --engine): an admin +# sets a runtime gateway setting; messages sent while a user is offline +# reach the user's stored history when it connects again +# 9. pins, reactions and topics through the engine: post, pin (allowed by +# a permission rule the admin sets), react, start a topic from the post, +# post into it, read the topic and the pins back +# 10. stream directory (TeamSpeak 6 only): an engine session's stream +# registers itself in the gateway's directory; a viewer that connects +# later finds it there and watches it +# 11. stream (TeamSpeak 6 only): a viewer watches a synthetic VP8 + Opus stream +# 12. late stream (TeamSpeak 6 only): a viewer that connects after the stream # started finds it (requeststreaminfo) and watches it # # Usage: scripts/it-smoke.sh [ts3|ts6]... (default: both) -# Env: VOELINCTL=path/to/voelinctl (default: builds target/debug/voelinctl) +# Env: VOELINCTL=path/to/voelinctl, TSGW=path/to/tsgw (default: builds both +# into $CARGO_TARGET_DIR or target) +# TSGW_PORT_TS3, TSGW_PORT_TS6: gateway ports (default 7787, 7788) # COMPOSE_FILE=dev/docker-compose.yml set -euo pipefail @@ -29,16 +40,17 @@ mkdir -p "$STATE_DIR" # Never leave background clients behind. trap 'kill $(jobs -p) 2>/dev/null || true' EXIT +BUILD_DIR="${CARGO_TARGET_DIR:-target}/debug" if [[ -z "${VOELINCTL:-}" ]]; then cargo build --quiet -p voelinctl -p voelin-gateway - VOELINCTL=target/debug/voelinctl + VOELINCTL=$BUILD_DIR/voelinctl fi -TSGW="${TSGW:-target/debug/tsgw}" +TSGW="${TSGW:-$BUILD_DIR/tsgw}" declare -A PORTS=([ts3]=9987 [ts6]=9988) # ServerQuery transport and address per server (dev/docker-compose.yml). declare -A QUERY=([ts3]="raw 127.0.0.1:10011" [ts6]="ssh 127.0.0.1:10022") -declare -A GATEWAY=([ts3]=7787 [ts6]=7788) +declare -A GATEWAY=([ts3]=${TSGW_PORT_TS3:-7787} [ts6]=${TSGW_PORT_TS6:-7788}) QUERY_SECRET=voelin-dev-admin SERVERS=("$@") [[ ${#SERVERS[@]} -eq 0 ]] && SERVERS=(ts3 ts6) @@ -201,7 +213,8 @@ relay_check() { gateway_check() { local svc=$1 addr=$2 port=${GATEWAY[$svc]} out="$STATE_DIR/gateway.log" local url="ws://127.0.0.1:$port/v1" token="gw-$RANDOM$RANDOM" - "$TSGW" --config "dev/tsgw-$svc.toml" >"$STATE_DIR/tsgw-$svc.log" 2>&1 & + "$TSGW" --config "dev/tsgw-$svc.toml" --set "listen.bind=127.0.0.1:$port" \ + --set "history.path=$STATE_DIR/tsgw-$svc.db" >"$STATE_DIR/tsgw-$svc.log" 2>&1 & local gateway=$! for _ in $(seq 1 40); do grep -q "listening" "$STATE_DIR/tsgw-$svc.log" 2>/dev/null && break @@ -236,10 +249,109 @@ gateway_check() { fi grep -E "presence:|to-gateway-$token" "$out" grep "from-gateway-$token" "$STATE_DIR/gateway-heard.log" + + history_check "$svc" "$addr" "$url" "$user" + features_check "$svc" "$url" "$user" + if [[ $svc == ts6 ]]; then + directory_check "$svc" "$addr" "$url" "$user" + fi kill "$gateway" wait "$gateway" 2>/dev/null || true } +# An engine session through the gateway: voelinctl gateway --engine. +engine() { + local url=$1 identity=$2 + shift 2 + "$VOELINCTL" gateway "$url" --identity "$identity" --engine "$@" +} + +# A gateway request as the server's admin; the answer must contain $expect. +admin_request() { + local svc=$1 url=$2 request=$3 expect=$4 out="$STATE_DIR/admin-request.log" + if ! engine "$url" "$STATE_DIR/$svc-admin.json" --request "$request" --expect "$expect" \ + --seconds 15 >"$out" 2>&1; then + cat "$out" + fail "gateway request $request was not answered with $expect" + fi + grep -F "$expect" "$out" | cut -c1-200 +} + +# Messages sent while a user is offline reach the user's stored history +# through the gateway when the user connects again. +history_check() { + local svc=$1 addr=$2 url=$3 user=$4 token="offline-$RANDOM$RANDOM" + local db="$STATE_DIR/$svc-history-$$.db" out="$STATE_DIR/history.log" + rm -f "$db"* + # The gateway reads channel 1 even while nobody has it open (runtime setting). + admin_request "$svc" "$url" '{"config_set":{"key":"relay.pinned_channels","value":[1]}}' \ + '"config_value":{"entry":{"key":"relay.pinned_channels","value":[1]' + # First visit: the chat is synced and stored. + if ! engine "$url" "$user" --db "$db" --chat channel:1 --expect "history gateway channel:1 batch" \ + --seconds 15 >"$out" 2>&1; then + cat "$out" + fail "first chat history sync failed" + fi + # Away: someone talks in the channel. + sleep 2 + "$VOELINCTL" connect "$addr" --nick history-talker chat channel "$token-1" + "$VOELINCTL" connect "$addr" --nick history-talker chat channel "$token-2" + sleep 1 + # Back: the stored history at once, then what was missed, from the gateway. + if ! engine "$url" "$user" --db "$db" --chat channel:1 --expect "$token-2" \ + --seconds 15 >"$out" 2>&1; then + cat "$out" "$STATE_DIR/tsgw-$svc.log" + fail "messages sent while offline did not arrive" + fi + grep -E "^history gateway channel:1 .*$token-1" "$out" || { cat "$out"; fail "$token-1 not from the gateway"; } + grep -E "^history gateway channel:1 .*$token-2" "$out" || { cat "$out"; fail "$token-2 not from the gateway"; } + # And stored: the next visit shows them from the database first. + if ! engine "$url" "$user" --db "$db" --chat channel:1 --expect "history gateway channel:1 batch" \ + --seconds 15 >"$out" 2>&1; then + cat "$out" + fail "third chat history sync failed" + fi + grep -E "^history local channel:1 .*$token-2" "$out" || { cat "$out"; fail "$token-2 was not stored"; } + admin_request "$svc" "$url" '{"config_reset":{"key":"relay.pinned_channels"}}' '"config_value"' >/dev/null + rm -f "$db"* +} + +# Post, pin, react, topic and topic post through the engine as a normal user; +# pinning is allowed by a permission rule the admin sets for the test. +features_check() { + local svc=$1 url=$2 user=$3 out="$STATE_DIR/roundtrip.log" + admin_request "$svc" "$url" '{"perm_set":{"action":"pin","rule":{"everyone":true}}}' '"perm_rules"' >/dev/null + if ! engine "$url" "$user" --roundtrip channel:1 --seconds 20 >"$out" 2>&1; then + cat "$out" + admin_request "$svc" "$url" '{"perm_reset":{"action":"pin"}}' '"perm_rules"' >/dev/null || true + fail "pin/react/topic round trip failed" + fi + admin_request "$svc" "$url" '{"perm_reset":{"action":"pin"}}' '"perm_rules"' >/dev/null + grep -E "^roundtrip|\"pinned\":\{|\"reaction\":\{" "$out" | cut -c1-160 +} + +# TeamSpeak 6: an engine session streams; its stream registers in the +# gateway's directory; a viewer that connects later finds it and watches it. +directory_check() { + local svc=$1 addr=$2 url=$3 user=$4 streamer="dir-$$-$RANDOM" title="directory-$RANDOM" + local out="$STATE_DIR/directory-stream.log" viewer_out="$STATE_DIR/directory-watch.log" + engine "$url" "$STATE_DIR/$svc-admin.json" --voice "$addr" --nick "$streamer" --loopback \ + --stream-seconds 30 --stream-title "$title" --seconds 45 >"$out" 2>&1 & + local streamer_pid=$! + for _ in $(seq 1 80); do grep -q '"stream_registered"' "$out" 2>/dev/null && break; sleep 0.25; done + grep -q '"stream_registered"' "$out" || { cat "$out"; fail "the stream did not register in the directory"; } + if ! engine "$url" "$user" --voice "$addr" --nick "late-dir-$$" --loopback \ + --watch-streamer "$streamer" --expect-frames 30 --seconds 25 >"$viewer_out" 2>&1; then + cat "$viewer_out" "$out" + fail "late viewer did not watch the stream from the directory" + fi + grep -qF "\"title\":\"$title\"" "$viewer_out" || { cat "$viewer_out"; fail "the directory did not list the stream"; } + kill -INT "$streamer_pid" 2>/dev/null || true + wait "$streamer_pid" 2>/dev/null || true + grep -E '"stream_registered"' "$out" | cut -c1-160 + grep -E "^watching|^received" "$viewer_out" +} + for svc in "${SERVERS[@]}"; do port=${PORTS[$svc]:?unknown server $svc} addr="127.0.0.1:$port" diff --git a/tools/voelinctl/src/engine.rs b/tools/voelinctl/src/engine.rs new file mode 100644 index 0000000..2ba88a5 --- /dev/null +++ b/tools/voelinctl/src/engine.rs @@ -0,0 +1,500 @@ +//! `voelinctl gateway --engine`: one engine session (voelin-core) with the +//! gateway (and optionally voice), for chat history, the gateway's features +//! and the stream directory as the app uses them. +//! +//! Prints one line per event: `history ...` per message +//! of a history batch (then `history batch n=.. complete=..`), +//! `update ` per gateway update, `chat ...` for live messages, +//! `state ...`, `streams ...`, `stream ...`, `watch ...`, `error: ...`. +//! `--expect TEXT` succeeds on the first line containing TEXT. + +use std::collections::HashMap; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result, bail}; +use tokio::sync::broadcast::error::RecvError; +use tokio::time::{Instant as TokioInstant, sleep_until, timeout_at}; +use voelin_core::gateway::{GatewayRequest, GatewayUpdate}; +use voelin_core::history::HistoryMessage; +use voelin_core::settings::Settings; +use voelin_core::stream::{FrameSource, MediaKind, PeerConfig, StreamSetup, SyntheticSource}; +use voelin_core::{ + Command, Engine, Event, History, HistorySource, ObserveState, StreamState, VoiceOptions, + VoiceState, WatchState, +}; +use voelin_model::ChatTarget; + +use crate::gateway::{GatewayArgs, parse_target, target_name}; + +const SESSION: u64 = 1; + +fn message_line(source: HistorySource, target: &ChatTarget, m: &HistoryMessage) -> String { + let reactions: Vec = m + .reactions + .iter() + .map(|r| format!("{}{}{}", r.emoji, r.count, if r.me { "*" } else { "" })) + .collect(); + format!( + "history {} {} id={} remote={} topic={} pinned={} reactions=[{}] {}: {}", + source_name(source), + target_name(target), + m.id, + m.remote_id.map_or("-".into(), |r| r.to_string()), + m.topic_id.map_or("-".into(), |t| t.to_string()), + m.pinned, + reactions.join(","), + m.message.author_name, + m.message.text + ) +} + +fn source_name(source: HistorySource) -> &'static str { + match source { + HistorySource::Local => "local", + HistorySource::Gateway => "gateway", + HistorySource::Live => "live", + } +} + +/// What the run is waiting for. +struct Run { + expect: Option, + /// Lines printed so far that matched. + done: bool, +} + +impl Run { + fn print(&mut self, line: String) { + if self.expect.as_ref().is_some_and(|e| line.contains(e.as_str())) { + self.done = true; + } + println!("{line}"); + } +} + +pub async fn run(args: GatewayArgs) -> Result<()> { + let identity = crate::identity::load(&args.identity)?; + let settings = Settings::in_memory(); + if let Some(e) = settings.apply_overrides(args.set.iter().map(String::as_str)).first() { + bail!("--set: {e}"); + } + let history = match &args.db { + Some(path) => History::open(path).with_context(|| format!("history {}", path.display()))?, + None => History::in_memory(), + }; + let engine = Engine::start_with(settings, history); + let mut events = engine.subscribe(); + let mut frames = engine.subscribe_frames(); + let deadline = TokioInstant::now() + Duration::from_secs(args.seconds); + let mut out = Run { expect: args.expect.clone(), done: false }; + + let chats: Vec = + args.chat.iter().map(|t| parse_target(t)).collect::>()?; + for target in &chats { + engine.send(Command::OpenChat { session: SESSION, target: target.clone() }); + } + let roundtrip = args.roundtrip.as_deref().map(parse_target).transpose()?; + if let Some(target) = &roundtrip { + engine.send(Command::OpenChat { session: SESSION, target: target.clone() }); + } + engine.send(Command::ObserveGateway { + session: SESSION, + url: args.url.clone(), + identity: Box::new(identity.clone()), + }); + if let Some(addr) = &args.voice { + let mut options = VoiceOptions::new(addr, &args.nick); + options.identity = Some(identity); + if args.loopback { + options.stream_peer = PeerConfig::loopback(); + } + engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) }); + } + let requests: Vec = args + .request + .iter() + .map(|r| serde_json::from_str(r).with_context(|| format!("--request {r}"))) + .collect::>()?; + + let mut gateway_up = false; + let mut voice_up = false; + let mut older_left: HashMap = + chats.iter().map(|t| (t.clone(), args.older)).collect(); + // The oldest message shown per chat: (ts_ms, id). + let mut oldest: HashMap = HashMap::new(); + let mut rt = roundtrip.map(Roundtrip::new); + let mut streaming: Option<(Instant, tokio::task::JoinHandle<()>)> = None; + let mut stream_started = false; + let mut watching = false; + let mut nicknames: HashMap = HashMap::new(); + let mut video_frames = 0u64; + + loop { + if out.done && rt.as_ref().is_none_or(|r| r.finished) { + return Ok(()); + } + if let Some(r) = &rt + && let Some(e) = &r.failed + { + bail!("roundtrip failed: {e}"); + } + // Our stream's time is up. + if let Some((until, _)) = &streaming + && Instant::now() >= *until + { + let (_, feeder) = streaming.take().unwrap(); + feeder.abort(); + engine.send(Command::StopStream { session: SESSION }); + } + let wake = streaming + .as_ref() + .map(|(until, _)| TokioInstant::from_std(*until)) + .unwrap_or(deadline) + .min(deadline); + let event = tokio::select! { + e = timeout_at(wake, events.recv()) => match e { + Ok(Ok(e)) => e, + Ok(Err(RecvError::Lagged(_))) => continue, + Ok(Err(RecvError::Closed)) => bail!("engine stopped"), + Err(_) if TokioInstant::now() >= deadline => break, + Err(_) => continue, + }, + f = frames.recv() => { + if let Ok(f) = f && f.frame.kind == MediaKind::Video { + video_frames += 1; + if video_frames == 1 { + out.print(format!("watch {} first video frame", f.stream_id)); + } + if args.expect_frames.is_some_and(|n| video_frames >= n) { + out.print(format!("received {video_frames} video frames")); + return Ok(()); + } + } + continue; + } + }; + match event { + Event::State { session: SESSION, state } => { + out.print(format!( + "state voice={:?} observe={:?} server_uid={}", + state.voice, + state.observe, + state.server_uid.as_deref().unwrap_or("-") + )); + voice_up = state.voice == VoiceState::Connected && state.own_channel.is_some(); + if state.observe == ObserveState::Off && gateway_up { + gateway_up = false; + } + } + Event::Gateway { session: SESSION, update } => { + out.print(format!("update {}", serde_json::to_string(&update)?)); + if let GatewayUpdate::Connected { .. } = &update { + gateway_up = true; + for request in &requests { + engine + .send(Command::Gateway { session: SESSION, request: request.clone() }); + } + } + if let Some(r) = &mut rt { + r.update(&engine, &update); + } + } + Event::ChatHistory { session: SESSION, target, messages, source, complete } => { + for m in &messages { + out.print(message_line(source, &target, m)); + } + out.print(format!( + "history {} {} batch n={} complete={complete}", + source_name(source), + target_name(&target), + messages.len() + )); + if source != HistorySource::Live { + for m in &messages { + let at = (m.message.ts_ms, m.id); + let o = oldest.entry(target.clone()).or_insert(at); + *o = (*o).min(at); + } + } + if let Some(r) = &mut rt { + r.history(&engine, &messages); + } + // Page back after each batch from the gateway. + let left = older_left.get(&target).copied().unwrap_or(0); + if left > 0 && source == HistorySource::Gateway && !complete { + older_left.insert(target.clone(), left - 1); + let before = oldest.get(&target).map(|(_, id)| *id); + engine.send(Command::LoadOlderHistory { session: SESSION, target, before }); + } + } + Event::Chat { session: SESSION, message } => out.print(format!( + "chat {} {}: {}", + target_name(&message.target), + message.author_name, + message.text + )), + Event::Presence { session: SESSION, presence } => { + nicknames = presence.clients.values().map(|c| (c.id, c.nickname.clone())).collect(); + } + Event::ServerInfo { session: SESSION, name, flavor, .. } => { + out.print(format!("server {name:?} {flavor:?}")); + } + Event::StreamsChanged { session: SESSION, streams } => { + for s in &streams { + let nick = nicknames.get(&s.streamer.0).map_or("?", String::as_str); + out.print(format!( + "streams: {} by {nick} ({}) {:?}", + s.id, s.streamer.0, s.name + )); + } + if let Some(wanted) = &args.watch_streamer + && !watching && let Some(s) = streams + .iter() + .find(|s| nicknames.get(&s.streamer.0).is_some_and(|n| n == wanted)) + { + watching = true; + out.print(format!("watching {}", s.id)); + engine.send(Command::WatchStream { session: SESSION, stream_id: s.id.clone() }); + } + } + Event::StreamState { session: SESSION, state } => match state { + StreamState::Starting => out.print("stream starting".into()), + StreamState::Live { id, sink } => { + out.print(format!("stream live {id}")); + let seconds = args.stream_seconds.unwrap_or(0); + let feeder = tokio::spawn(async move { + let mut source = SyntheticSource::new(30, 2000, true); + let mut buf = Vec::new(); + while sink.is_live() { + source.poll_frames(Instant::now(), &mut buf); + for f in buf.drain(..) { + sink.send(f); + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }); + streaming = Some((Instant::now() + Duration::from_secs(seconds), feeder)); + } + StreamState::Ended(reason) => { + out.print(format!("stream ended {reason:?}")); + if args.stream_seconds.is_some() && streaming.is_none() { + // Give the directory update a moment to go out. + sleep_until(TokioInstant::now() + Duration::from_millis(500)).await; + return Ok(()); + } + } + }, + Event::WatchState { session: SESSION, stream_id, state } => { + out.print(format!("watch {stream_id} {state:?}")); + if let WatchState::Ended(reason) = state + && args.expect_frames.is_some() + { + bail!("the stream ended before enough frames arrived: {reason:?}"); + } + } + Event::Error { session: SESSION, message } => out.print(format!("error: {message}")), + _ => {} + } + // Stream once voice (and the gateway, if any) are up. + if args.stream_seconds.is_some() && !stream_started && voice_up && gateway_up { + stream_started = true; + let setup = StreamSetup { name: args.stream_title.clone(), ..Default::default() }; + engine.send(Command::StartStream { session: SESSION, setup, auto_accept: true }); + } + } + if let Some(r) = &rt + && !r.finished + { + bail!("roundtrip did not finish (step {:?})", r.step); + } + if args.expect.is_some() && !out.done { + bail!("expected output did not appear"); + } + if args.expect_frames.is_some() { + bail!("received only {video_frames} video frames"); + } + Ok(()) +} + +/// The steps of `--roundtrip`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Step { + Post, + Pin, + React, + Topic, + TopicPost, + TopicHistory, + Pins, + Done, +} + +/// Post, pin, react, start a topic from the message, post into it, read +/// the topic and the pins; each answer is checked. +struct Roundtrip { + target: ChatTarget, + tag: String, + step: Step, + /// Gateway and local id of our post. + remote: i64, + local: i64, + topic: i64, + pinned_row: bool, + pinned_push: bool, + reacted_row: bool, + started: bool, + finished: bool, + failed: Option, +} + +impl Roundtrip { + fn new(target: ChatTarget) -> Self { + let tag = format!("{}", std::process::id() % 100_000); + Self { + target, + tag, + step: Step::Post, + remote: 0, + local: 0, + topic: 0, + pinned_row: false, + pinned_push: false, + reacted_row: false, + started: false, + finished: false, + failed: None, + } + } + + fn send(&self, engine: &Engine, request: GatewayRequest) { + engine.send(Command::Gateway { session: SESSION, request }); + } + + fn next(&mut self, engine: &Engine, step: Step) { + self.step = step; + println!("roundtrip: {step:?}"); + let target = self.target.clone(); + match step { + Step::Post => self.send( + engine, + GatewayRequest::Post { target, text: format!("rt-{}", self.tag), topic: None }, + ), + Step::Pin => self.send(engine, GatewayRequest::Pin { message_id: self.remote }), + Step::React => self.send( + engine, + GatewayRequest::React { message_id: self.remote, emoji: "👍".into() }, + ), + Step::Topic => self.send( + engine, + GatewayRequest::CreateTopic { + target, + title: format!("rt topic {}", self.tag), + message_id: Some(self.remote), + }, + ), + Step::TopicPost => self.send( + engine, + GatewayRequest::Post { + target, + text: format!("rt-in-topic-{}", self.tag), + topic: Some(self.topic), + }, + ), + Step::TopicHistory => self.send( + engine, + GatewayRequest::TopicHistory { + target, + topic: self.topic, + before: None, + limit: None, + }, + ), + Step::Pins => self.send(engine, GatewayRequest::Pins { target }), + Step::Done => { + self.finished = true; + println!("roundtrip ok"); + } + } + } + + fn update(&mut self, engine: &Engine, update: &GatewayUpdate) { + match update { + GatewayUpdate::Connected { .. } if !self.started => { + self.started = true; + self.next(engine, Step::Post); + } + GatewayUpdate::Failed { request, message, .. } => { + self.failed = Some(format!("{request}: {message}")); + } + GatewayUpdate::Posted { message } if self.step == Step::Post => { + self.remote = message.remote_id.unwrap_or_default(); + self.local = message.id; + self.next(engine, Step::Pin); + } + GatewayUpdate::Pinned { pin, .. } if self.step == Step::Pin => { + self.pinned_push = pin.message.id == self.local; + self.after_pin(engine); + } + GatewayUpdate::Reaction { message_id, added: true, .. } + if self.step == Step::React && *message_id == self.remote => + { + if self.reacted_row { + self.next(engine, Step::Topic); + } + } + GatewayUpdate::Topic { topic } if self.step == Step::Topic => { + if topic.root_message_id != Some(self.remote) { + self.failed = Some(format!("topic from another message: {topic:?}")); + return; + } + self.topic = topic.id; + self.next(engine, Step::TopicPost); + } + GatewayUpdate::Posted { message } if self.step == Step::TopicPost => { + if message.topic_id != Some(self.topic) { + self.failed = Some(format!("posted outside the topic: {message:?}")); + return; + } + self.next(engine, Step::TopicHistory); + } + GatewayUpdate::TopicHistory { messages, .. } if self.step == Step::TopicHistory => { + let text = format!("rt-in-topic-{}", self.tag); + if !messages.iter().any(|m| m.message.text == text) { + self.failed = Some(format!("topic history without {text}")); + return; + } + self.next(engine, Step::Pins); + } + GatewayUpdate::Pins { pins, .. } if self.step == Step::Pins => { + if !pins.iter().any(|p| p.message.id == self.local) { + self.failed = Some("our pin is not listed".into()); + return; + } + self.next(engine, Step::Done); + } + _ => {} + } + } + + fn after_pin(&mut self, engine: &Engine) { + if self.pinned_row && self.pinned_push { + self.next(engine, Step::React); + } + } + + fn history(&mut self, engine: &Engine, messages: &[HistoryMessage]) { + let Some(ours) = messages.iter().find(|m| m.id == self.local && self.local != 0) else { + return; + }; + match self.step { + Step::Pin if ours.pinned => { + self.pinned_row = true; + self.after_pin(engine); + } + Step::React if ours.reactions.iter().any(|r| r.emoji == "👍" && r.me) => { + self.reacted_row = true; + } + _ => {} + } + } +} diff --git a/tools/voelinctl/src/gateway.rs b/tools/voelinctl/src/gateway.rs index c23bf6d..41efa06 100644 --- a/tools/voelinctl/src/gateway.rs +++ b/tools/voelinctl/src/gateway.rs @@ -40,17 +40,81 @@ pub struct GatewayArgs { /// Exit successfully when a client with this nickname is present. #[arg(long)] pub expect_client: Option, + + // Through the engine (voelin-core), as the app uses the gateway. + /// Run an engine session instead of a raw connection: chat history, + /// requests, the stream directory. Prints one line per event. + #[arg(long)] + pub engine: bool, + /// Chat history database (engine; default: in memory). + #[arg(long, requires = "engine")] + pub db: Option, + /// Also connect voice to this server address with the same identity (engine). + #[arg(long, requires = "engine")] + pub voice: Option, + /// Voice nickname (engine). + #[arg(long, default_value = "voelinctl", requires = "engine")] + pub nick: String, + /// Stream media over 127.0.0.1 only (engine, both ends on this machine). + #[arg(long, requires = "engine")] + pub loopback: bool, + /// Open a chat and print its history (engine): `server`, `channel:` + /// or `private:`. Repeatable. + #[arg(long = "chat", requires = "engine")] + pub chat: Vec, + /// Page back this many times in each `--chat` (engine). + #[arg(long, default_value_t = 0, requires = "engine")] + pub older: u32, + /// A gateway request as JSON, sent after login (engine), e.g. + /// `{"config_get":{"key":"relay.pinned_channels"}}`, `"config_list"`, + /// `{"perm_set":{"action":"pin","rule":{"everyone":true}}}`. Repeatable. + #[arg(long = "request", requires = "engine")] + pub request: Vec, + /// Post, pin, react, start a topic from the post, post into it and read + /// it back in this chat, checking each step (engine). + #[arg(long, requires = "engine")] + pub roundtrip: Option, + /// With `--voice` (TeamSpeak 6): stream synthetic frames this long; the + /// stream registers itself in the gateway's directory (engine). + #[arg(long, requires = "voice")] + pub stream_seconds: Option, + /// Title of that stream. + #[arg(long, default_value = "voelinctl", requires = "stream_seconds")] + pub stream_title: String, + /// With `--voice`: watch the stream of this client once it is found + /// (from the server or the gateway's directory) (engine). + #[arg(long, requires = "voice")] + pub watch_streamer: Option, + /// Exit successfully once this many video frames of the watched stream arrived. + #[arg(long, requires = "watch_streamer")] + pub expect_frames: Option, + /// An engine setting, e.g. `chat.history_page=20`. Repeatable. + #[arg(long = "set", value_name = "KEY=VALUE", requires = "engine")] + pub set: Vec, } -fn parse_target(s: &str) -> Result { +pub fn parse_target(s: &str) -> Result { match s.split_once(':') { None if s == "server" => Ok(ChatTarget::Server), Some(("channel", cid)) => Ok(ChatTarget::Channel(cid.parse().context("channel id")?)), - _ => bail!("target must be `server` or `channel:`, got {s:?}"), + Some(("private", uid)) => Ok(ChatTarget::Private(uid.to_owned())), + _ => bail!("target must be `server`, `channel:` or `private:`, got {s:?}"), + } +} + +/// [`parse_target`] back. +pub fn target_name(target: &ChatTarget) -> String { + match target { + ChatTarget::Server => "server".into(), + ChatTarget::Channel(cid) => format!("channel:{cid}"), + ChatTarget::Private(uid) => format!("private:{uid}"), } } pub async fn run(args: GatewayArgs) -> Result<()> { + if args.engine { + return crate::engine::run(args).await; + } let identity = crate::identity::load(&args.identity)?; let mut request = args.url.as_str().into_client_request()?; request diff --git a/tools/voelinctl/src/main.rs b/tools/voelinctl/src/main.rs index 4f57f69..3f9da0f 100644 --- a/tools/voelinctl/src/main.rs +++ b/tools/voelinctl/src/main.rs @@ -1,5 +1,6 @@ //! `voelinctl`: headless TeamSpeak 3/6 client for development and integration tests. +mod engine; mod gateway; mod identity; mod observe; @@ -45,7 +46,9 @@ enum Command { Observe(observe::ObserveArgs), /// Read and write a channel's chat through an invisible query relay. Relay(observe::RelayArgs), - /// Use a tsgw gateway as a user: presence, chat, history. + /// Use a tsgw gateway as a user: presence, chat, history; with + /// `--engine` through the client engine (chat history sync, pins, + /// reactions, topics, events, stream directory, administration). Gateway(gateway::GatewayArgs), /// TeamSpeak 6: probe how a client that arrives after a stream started /// can learn about it; prints every command both clients exchange.