Merge chat history and the gateway's features in the engine

Chats show their stored history at once and sync what the gateway kept
while we were away; messages seen over voice and the gateway are
stored once. Pins, reactions, topics, events, the stream directory,
activity and gateway administration are engine commands and events.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-28 12:37:29 +00:00
commit 897eec031d
20 files changed
+4933 -218

No files matched your search

+1 -1
View File
@@ -43,7 +43,7 @@ tsclientlib = { path = "../proto/tsclientlib" }
tsproto-packets = { path = "../proto/tsproto-packets" }
[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt-multi-thread", "test-util"] }
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "test-util"] }
[lints]
workspace = true
+648 -26
View File
@@ -1,22 +1,59 @@
//! The gateway source: presence and relayed chat through `tsgw`, and the
//! typed client for everything else a gateway offers (pins, reactions,
//! topics, events, the stream directory, the activity feed,
//! administration).
//! The gateway source: presence and relayed chat through `tsgw`, and
//! everything else a gateway offers (history, pins, reactions, topics,
//! events, the stream directory, the activity feed, administration).
//!
//! [`GatewayClient`] (from `voelin-gateway-proto`, feature `client`) has one
//! async method per request and delivers pushes as [`Push`];
//! [`GatewayClient::capabilities`] says which features the gateway and user
//! have, so the UI can hide the rest. The data types (`HistoryQuery`,
//! `PinInfo`, `EventSpec`, `StreamEntry`, …) are in `voelin_gateway_proto`.
//! [`connect`] logs in with the user's TeamSpeak identity. The engine uses
//! [`run`] for presence and chat.
//! have. The data types (`HistoryQuery`, `PinInfo`, `EventSpec`,
//! `StreamEntry`, …) are in `voelin_gateway_proto`. [`connect`] logs in
//! with the user's TeamSpeak identity.
//!
//! # In the engine
//!
//! [`crate::Command::ObserveGateway`] starts a session's gateway: invisible
//! presence, relayed chat, chat history ([`crate::history`]). The session
//! then takes [`crate::Command::Gateway`] with a [`GatewayRequest`] and
//! reports answers and pushes as [`crate::Event::Gateway`] with a
//! [`GatewayUpdate`]:
//!
//! - [`GatewayUpdate::Connected`] after login, with the capabilities
//! ([`voelin_gateway_proto::feature`]; hide what is missing);
//! [`GatewayUpdate::Capabilities`] when they change;
//! [`GatewayUpdate::Disconnected`] when the gateway is gone.
//! - Each request is answered with its update (e.g. `Pins` for
//! [`GatewayRequest::Pins`]), [`GatewayUpdate::Done`] for requests without
//! data, or [`GatewayUpdate::Failed`] (gateway error code and message).
//! - Pushes: pins, reactions and topic changes of open chats, event
//! changes and reminders, stream directory and activity changes. The
//! engine subscribes to events, streams and activity when the gateway
//! has them (the `Subscribe*` requests turn that off and on).
//! - Messages the gateway returns (posts, pins, topic history) and message
//! changes (pins, reactions) are stored and also emitted as
//! [`crate::Event::ChatHistory`], so the chat view updates by local id.
//! Message ids in requests are the gateway's
//! ([`crate::history::HistoryMessage::remote_id`]).
//! - Our own stream (TeamSpeak 6) registers itself in the directory when it
//! goes live and the gateway has `streams` ([`GatewayUpdate::StreamRegistered`]),
//! and is removed when it ends. The directory is also where the session's
//! streams look for streams that started before we joined, next to the
//! server's `requeststreaminfo`.
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;
use tracing::info;
use voelin_gateway_proto::client::Login;
pub use voelin_gateway_proto::client::{ClientError, GatewayClient, Push};
use voelin_gateway_proto::{ClientMsg, ErrorCode};
use voelin_model::{ChatMessage, ChatTarget, Presence};
use voelin_gateway_proto::{
Action, ActivityEntry, ClientMsg, ConfigEntry, ErrorCode, EventInfo, EventQuery, EventSpec,
HistoryEntry, HistoryQuery, PermRule, PermRuleInfo, PinInfo, RsvpStatus, StreamEntry,
StreamSpec, TopicInfo, UserRef,
};
use voelin_model::{ChannelId, ChatTarget, Presence};
use voelin_store::WriteOutcome;
use crate::Event;
use crate::history::{ChatCtx, HistoryMessage, HistorySource, gateway_message, store_target};
pub(crate) enum GatewayCmd {
OpenChat(ChatTarget),
@@ -26,10 +63,11 @@ pub(crate) enum GatewayCmd {
}
pub(crate) enum GatewayEvent {
Connected,
/// Logged in; requests go through `client`.
Connected(GatewayClient),
Presence(Presence),
Chat(ChatMessage),
Error(String),
/// A push other than presence.
Push(Box<Push>),
Disconnected(Option<String>),
}
@@ -54,6 +92,14 @@ pub(crate) async fn run(
let _ = events.send(GatewayEvent::Disconnected(reason));
}
/// Features whose pushes for open chats need [`ClientMsg::Enable`].
const CHAT_EXTENSIONS: [&str; 4] = [
voelin_gateway_proto::feature::HISTORY,
voelin_gateway_proto::feature::PINS,
voelin_gateway_proto::feature::REACTIONS,
voelin_gateway_proto::feature::TOPICS,
];
async fn run_inner(
url: &str,
identity: &tsclientlib::Identity,
@@ -63,13 +109,19 @@ async fn run_inner(
let (client, mut pushes) = match connect(url, identity).await {
Ok(connected) => connected,
Err(ClientError::Gateway { code, message }) => {
let _ = events.send(GatewayEvent::Error(format!("{code:?}: {message}")));
let _ = events
.send(GatewayEvent::Push(Box::new(Push::Error { code, message: message.clone() })));
anyhow::bail!("gateway refused login: {message}");
}
Err(e) => return Err(e.into()),
};
info!(server_name = %client.info().server_name, capabilities = ?client.capabilities(), "gateway connected");
let _ = events.send(GatewayEvent::Connected);
// Messages with their gateway ids, pins, reactions and topics of open
// chats (older gateways answer `unknown_type` as a push; ignored).
if CHAT_EXTENSIONS.iter().any(|f| client.has(f)) {
client.send(ClientMsg::Enable { features: Vec::new() })?;
}
let _ = events.send(GatewayEvent::Connected(client.clone()));
client.subscribe_presence()?;
let mut presence = Presence::default();
@@ -86,19 +138,18 @@ async fn run_inner(
presence.apply(&delta);
let _ = events.send(GatewayEvent::Presence(presence.clone()));
}
Some(Push::Chat { message, .. }) => {
let _ = events.send(GatewayEvent::Chat(message));
// Answers to requests sent without waiting.
Some(Push::Other(_) | Push::Error { code: ErrorCode::UnknownType, .. }) => {}
Some(Push::Error { code: ErrorCode::NotAuthenticated, message }) => {
let _ = events.send(GatewayEvent::Push(Box::new(Push::Error {
code: ErrorCode::NotAuthenticated,
message: message.clone(),
})));
anyhow::bail!("gateway session lost: {message}");
}
Some(Push::Message(entry)) => {
let _ = events.send(GatewayEvent::Chat(entry.message));
Some(push) => {
let _ = events.send(GatewayEvent::Push(Box::new(push)));
}
Some(Push::Error { code, message }) => {
let _ = events.send(GatewayEvent::Error(format!("{code:?}: {message}")));
if code == ErrorCode::NotAuthenticated {
anyhow::bail!("gateway session lost: {message}");
}
}
Some(_) => {}
},
cmd = commands.recv() => match cmd {
None | Some(GatewayCmd::Stop) => return Ok(()),
@@ -111,3 +162,574 @@ async fn run_inner(
}
}
}
/// Something to ask a session's gateway ([`crate::Command::Gateway`]).
/// Message ids are the gateway's. Serialized in snake case, e.g.
/// `{"pin":{"message_id":7}}`, `"config_list"`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GatewayRequest {
/// Report the capabilities again ([`GatewayUpdate::Capabilities`]).
Capabilities,
/// What the user may do, server-wide or in `channel`
/// ([`GatewayUpdate::Permissions`]).
Permissions {
#[serde(default)]
channel: Option<ChannelId>,
},
/// Post into a chat, optionally into a topic ([`GatewayUpdate::Posted`]).
Post {
target: ChatTarget,
text: String,
#[serde(default)]
topic: Option<i64>,
},
Pin {
message_id: i64,
},
Unpin {
message_id: i64,
},
/// [`GatewayUpdate::Pins`].
Pins {
target: ChatTarget,
},
React {
message_id: i64,
emoji: String,
},
Unreact {
message_id: i64,
emoji: String,
},
/// Who reacted with `emoji` ([`GatewayUpdate::Reactors`]).
Reactors {
message_id: i64,
emoji: String,
},
/// Start a topic, from a message or standalone ([`GatewayUpdate::Topic`]).
CreateTopic {
target: ChatTarget,
title: String,
#[serde(default)]
message_id: Option<i64>,
},
/// Rename or (un)archive a topic ([`GatewayUpdate::Topic`]).
UpdateTopic {
topic_id: i64,
#[serde(default)]
title: Option<String>,
#[serde(default)]
archived: Option<bool>,
},
/// [`GatewayUpdate::Topics`], most recently active first.
Topics {
target: ChatTarget,
#[serde(default)]
include_archived: bool,
},
/// A topic's messages before gateway message `before` (the latest
/// without), `limit` of them (`chat.history_page` without)
/// ([`GatewayUpdate::TopicHistory`]).
TopicHistory {
target: ChatTarget,
topic: i64,
#[serde(default)]
before: Option<i64>,
#[serde(default)]
limit: Option<u32>,
},
/// [`GatewayUpdate::Event`].
CreateEvent {
event: EventSpec,
},
/// [`GatewayUpdate::Event`].
UpdateEvent {
id: i64,
event: EventSpec,
},
DeleteEvent {
id: i64,
},
/// One event with its attendees ([`GatewayUpdate::Event`]).
GetEvent {
id: i64,
},
/// [`GatewayUpdate::Events`], by start time.
Events {
#[serde(default)]
query: EventQuery,
},
/// Answer an invitation; `None` withdraws the answer ([`GatewayUpdate::Event`]).
Rsvp {
event_id: i64,
#[serde(default)]
status: Option<RsvpStatus>,
},
/// Event changes and reminders as pushes (on by default).
SubscribeEvents {
on: bool,
},
/// The stream directory ([`GatewayUpdate::Streams`]).
Streams,
/// Directory changes as pushes (on by default).
SubscribeStreams {
on: bool,
},
/// Add a stream to the directory (our own stream registers itself;
/// [`GatewayUpdate::StreamRegistered`]).
RegisterStream {
stream: StreamSpec,
},
UpdateStream {
stream_id: String,
#[serde(default)]
title: Option<String>,
#[serde(default)]
viewers: Option<u32>,
},
UnregisterStream {
stream_id: String,
},
/// Newest first, entries with an id below `before` ([`GatewayUpdate::Activity`]).
Activity {
#[serde(default)]
before: Option<i64>,
#[serde(default)]
limit: Option<u32>,
},
/// New activity as pushes (on by default).
SubscribeActivity {
on: bool,
},
/// Administration (capability `admin`): [`GatewayUpdate::Config`].
ConfigList,
/// [`GatewayUpdate::ConfigValue`].
ConfigGet {
key: String,
},
/// Store a runtime value at the gateway ([`GatewayUpdate::ConfigValue`]).
ConfigSet {
key: String,
value: serde_json::Value,
},
/// Drop the runtime value ([`GatewayUpdate::ConfigValue`]).
ConfigReset {
key: String,
},
/// Read the gateway's file again ([`GatewayUpdate::Config`]).
ConfigReload,
/// [`GatewayUpdate::PermRules`].
PermList,
PermSet {
action: Action,
rule: PermRule,
},
PermReset {
action: Action,
},
}
impl GatewayRequest {
/// The request's name, as in [`GatewayUpdate::Done`] and [`GatewayUpdate::Failed`].
pub fn name(&self) -> &'static str {
match self {
GatewayRequest::Capabilities => "capabilities",
GatewayRequest::Permissions { .. } => "permissions",
GatewayRequest::Post { .. } => "post",
GatewayRequest::Pin { .. } => "pin",
GatewayRequest::Unpin { .. } => "unpin",
GatewayRequest::Pins { .. } => "pins",
GatewayRequest::React { .. } => "react",
GatewayRequest::Unreact { .. } => "unreact",
GatewayRequest::Reactors { .. } => "reactors",
GatewayRequest::CreateTopic { .. } => "create_topic",
GatewayRequest::UpdateTopic { .. } => "update_topic",
GatewayRequest::Topics { .. } => "topics",
GatewayRequest::TopicHistory { .. } => "topic_history",
GatewayRequest::CreateEvent { .. } => "create_event",
GatewayRequest::UpdateEvent { .. } => "update_event",
GatewayRequest::DeleteEvent { .. } => "delete_event",
GatewayRequest::GetEvent { .. } => "get_event",
GatewayRequest::Events { .. } => "events",
GatewayRequest::Rsvp { .. } => "rsvp",
GatewayRequest::SubscribeEvents { .. } => "subscribe_events",
GatewayRequest::Streams => "streams",
GatewayRequest::SubscribeStreams { .. } => "subscribe_streams",
GatewayRequest::RegisterStream { .. } => "register_stream",
GatewayRequest::UpdateStream { .. } => "update_stream",
GatewayRequest::UnregisterStream { .. } => "unregister_stream",
GatewayRequest::Activity { .. } => "activity",
GatewayRequest::SubscribeActivity { .. } => "subscribe_activity",
GatewayRequest::ConfigList => "config_list",
GatewayRequest::ConfigGet { .. } => "config_get",
GatewayRequest::ConfigSet { .. } => "config_set",
GatewayRequest::ConfigReset { .. } => "config_reset",
GatewayRequest::ConfigReload => "config_reload",
GatewayRequest::PermList => "perm_list",
GatewayRequest::PermSet { .. } => "perm_set",
GatewayRequest::PermReset { .. } => "perm_reset",
}
}
}
/// A pinned message.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Pin {
/// The message as stored ([`HistoryMessage::id`] is the local id).
pub message: HistoryMessage,
pub by: UserRef,
pub ts_ms: i64,
}
/// What a session's gateway reports ([`crate::Event::Gateway`]).
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum GatewayUpdate {
/// Logged in.
Connected {
gateway_id: String,
server_uid: String,
server_name: String,
/// Our unique id on the server.
uid: String,
/// See [`voelin_gateway_proto::feature`].
capabilities: Vec<String>,
},
/// The features available to us changed.
Capabilities {
capabilities: Vec<String>,
},
/// The gateway connection ended (nothing of it is available).
Disconnected {
reason: Option<String>,
},
/// A request without data succeeded (e.g. `pin`, `react`, `subscribe_*`).
Done {
request: String,
},
/// A request failed; `code` is the gateway's (`None`: not connected,
/// connection lost, unexpected answer).
Failed {
request: String,
code: Option<ErrorCode>,
message: String,
},
Permissions {
channel: Option<ChannelId>,
actions: Vec<Action>,
},
/// Our post, as stored.
Posted {
message: HistoryMessage,
},
Pins {
target: ChatTarget,
pins: Vec<Pin>,
},
/// Push (chat open) or our pin.
Pinned {
target: ChatTarget,
pin: Pin,
},
/// Push (chat open).
Unpinned {
target: ChatTarget,
message_id: i64,
by: UserRef,
},
/// Push (chat open): `user` added or removed `emoji`; `count` is the new total.
Reaction {
target: ChatTarget,
message_id: i64,
emoji: String,
user: UserRef,
added: bool,
count: u32,
},
Reactors {
message_id: i64,
emoji: String,
users: Vec<UserRef>,
},
/// A topic: created, changed (also as a push), or new activity.
Topic {
topic: TopicInfo,
},
Topics {
target: ChatTarget,
topics: Vec<TopicInfo>,
},
/// A page of a topic's messages, oldest first, stored.
TopicHistory {
target: ChatTarget,
topic: i64,
messages: Vec<HistoryMessage>,
has_more: bool,
},
/// An event: the answer to create, update, get and rsvp, or a push
/// (created or changed, RSVP counts, going live).
Event {
event: EventInfo,
},
Events {
events: Vec<EventInfo>,
},
/// Push.
EventDeleted {
id: i64,
},
/// Push at the gateway's reminder times before an event starts (0: it starts).
EventReminder {
event: EventInfo,
starts_in_ms: i64,
},
/// The whole directory (answer to `streams`, and after subscribing).
Streams {
streams: Vec<StreamEntry>,
},
/// Push.
StreamStarted {
stream: StreamEntry,
},
/// Push.
StreamUpdated {
stream: StreamEntry,
},
/// Push.
StreamEnded {
id: String,
reason: String,
},
/// A stream we registered (our own stream when it goes live).
StreamRegistered {
stream: StreamEntry,
},
/// Newest first.
Activity {
entries: Vec<ActivityEntry>,
has_more: bool,
},
/// Push.
ActivityAdded {
entry: ActivityEntry,
},
Config {
entries: Vec<ConfigEntry>,
},
ConfigValue {
entry: ConfigEntry,
},
PermRules {
rules: Vec<PermRuleInfo>,
},
}
/// Carry out a request and report the answer.
pub(crate) async fn execute(ctx: ChatCtx, client: GatewayClient, request: GatewayRequest) {
let name = request.name();
let update = match answer(&ctx, &client, request).await {
Ok(Some(update)) => update,
Ok(None) => GatewayUpdate::Done { request: name.into() },
Err(e) => {
GatewayUpdate::Failed { request: name.into(), code: e.code(), message: e.to_string() }
}
};
ctx.emit(Event::Gateway { session: ctx.session, update });
}
/// Store gateway messages; as stored (local id 0 if storing failed).
async fn stored(ctx: &ChatCtx, entries: &[HistoryEntry]) -> Vec<HistoryMessage> {
match ctx.store_entries(entries).await {
Ok(written) => written.into_iter().map(|w| w.message.into()).collect(),
Err(e) => {
tracing::warn!("cannot store gateway messages: {e}");
entries.iter().map(HistoryMessage::unstored).collect()
}
}
}
async fn answer(
ctx: &ChatCtx,
client: &GatewayClient,
request: GatewayRequest,
) -> Result<Option<GatewayUpdate>, ClientError> {
use GatewayRequest as R;
use GatewayUpdate as U;
Ok(Some(match request {
R::Capabilities => U::Capabilities { capabilities: client.capabilities() },
R::Permissions { channel } => {
U::Permissions { channel, actions: client.permissions(channel).await? }
}
R::Post { target, text, topic } => {
let entry = client.post(target.clone(), text, topic).await?;
let message = stored(ctx, std::slice::from_ref(&entry)).await.remove(0);
ctx.emit_batch(&target, vec![message.clone()], HistorySource::Live, false);
U::Posted { message }
}
R::Pin { message_id } => return client.pin(message_id).await.map(|()| None),
R::Unpin { message_id } => return client.unpin(message_id).await.map(|()| None),
R::Pins { target } => {
let pins = client.pins(target.clone()).await?;
let entries: Vec<HistoryEntry> = pins.iter().map(|p| p.entry.clone()).collect();
let messages = stored(ctx, &entries).await;
let pins = pins
.into_iter()
.zip(messages)
.map(|(p, message)| Pin { message, by: p.by, ts_ms: p.ts_ms })
.collect();
U::Pins { target, pins }
}
R::React { message_id, emoji } => {
return client.react(message_id, emoji).await.map(|()| None);
}
R::Unreact { message_id, emoji } => {
return client.unreact(message_id, emoji).await.map(|()| None);
}
R::Reactors { message_id, emoji } => {
let users = client.reactors(message_id, emoji.clone()).await?;
U::Reactors { message_id, emoji, users }
}
R::CreateTopic { target, title, message_id } => {
U::Topic { topic: client.create_topic(target, title, message_id).await? }
}
R::UpdateTopic { topic_id, title, archived } => {
U::Topic { topic: client.update_topic(topic_id, title, archived).await? }
}
R::Topics { target, include_archived } => {
let topics = client.topics(target.clone(), include_archived).await?;
U::Topics { target, topics }
}
R::TopicHistory { target, topic, before, limit } => {
let mut query = HistoryQuery::latest(target.clone(), limit.or(ctx.page_limit()));
query.before = before;
query.topic = Some(topic);
let page = client.history(query).await?;
let messages = stored(ctx, &page.messages).await;
U::TopicHistory { target, topic, messages, has_more: page.has_more }
}
R::CreateEvent { event } => U::Event { event: client.create_event(event).await? },
R::UpdateEvent { id, event } => U::Event { event: client.update_event(id, event).await? },
R::DeleteEvent { id } => return client.delete_event(id).await.map(|()| None),
R::GetEvent { id } => U::Event { event: client.event(id).await? },
R::Events { query } => U::Events { events: client.events(query).await? },
R::Rsvp { event_id, status } => U::Event { event: client.rsvp(event_id, status).await? },
R::SubscribeEvents { on: true } => return client.subscribe_events().await.map(|()| None),
R::SubscribeEvents { on: false } => {
return client.unsubscribe_events().await.map(|()| None);
}
R::Streams => U::Streams { streams: client.streams().await? },
R::SubscribeStreams { on: true } => {
U::Streams { streams: client.subscribe_streams().await? }
}
R::SubscribeStreams { on: false } => {
return client.unsubscribe_streams().await.map(|()| None);
}
R::RegisterStream { stream } => {
U::StreamRegistered { stream: client.register_stream(stream).await? }
}
R::UpdateStream { stream_id, title, viewers } => {
U::StreamUpdated { stream: client.update_stream(stream_id, title, viewers).await? }
}
R::UnregisterStream { stream_id } => {
return client.unregister_stream(stream_id).await.map(|()| None);
}
R::Activity { before, limit } => {
let (entries, has_more) = client.activity(before, limit).await?;
U::Activity { entries, has_more }
}
R::SubscribeActivity { on: true } => {
return client.subscribe_activity().await.map(|()| None);
}
R::SubscribeActivity { on: false } => {
return client.unsubscribe_activity().await.map(|()| None);
}
R::ConfigList => U::Config { entries: client.config_list().await? },
R::ConfigGet { key } => U::ConfigValue { entry: client.config_get(key).await? },
R::ConfigSet { key, value } => {
U::ConfigValue { entry: client.config_set(key, value).await? }
}
R::ConfigReset { key } => U::ConfigValue { entry: client.config_reset(key).await? },
R::ConfigReload => U::Config { entries: client.config_reload().await? },
R::PermList => U::PermRules { rules: client.perm_list().await? },
R::PermSet { action, rule } => U::PermRules { rules: client.perm_set(action, rule).await? },
R::PermReset { action } => U::PermRules { rules: client.perm_reset(action).await? },
}))
}
/// Pushes about messages of open chats: stored, then reported, in the
/// order they arrived (the writer thread runs jobs in order).
impl ChatCtx {
pub(crate) fn pinned(&self, target: ChatTarget, pin: PinInfo) {
let mut entry = pin.entry.clone();
entry.pinned = true;
let ctx = self.clone();
self.history.write(
self.memory(),
vec![gateway_message(&self.server_uid, &entry)],
self.tolerance_ms(),
move |result| {
let message = match result.ok().and_then(|mut w| w.pop()) {
Some(w) => {
let changed = w.outcome != WriteOutcome::Unchanged;
let message = HistoryMessage::from(w.message);
if changed {
ctx.emit_batch(
&target,
vec![message.clone()],
HistorySource::Live,
false,
);
}
message
}
None => HistoryMessage::unstored(&entry),
};
let pin = Pin { message, by: pin.by, ts_ms: pin.ts_ms };
let update = GatewayUpdate::Pinned { target, pin };
ctx.emit(Event::Gateway { session: ctx.session, update });
},
);
}
pub(crate) fn unpinned(&self, target: ChatTarget, message_id: i64, by: UserRef) {
let (uid, key, ctx) = (self.server_uid.clone(), store_target(&target), self.clone());
self.history.run_then(
self.memory(),
move |s| s.set_pinned(&uid, &key, message_id, false),
move |result| {
ctx.emit_changed(result.ok().flatten());
let update = GatewayUpdate::Unpinned { target, message_id, by };
ctx.emit(Event::Gateway { session: ctx.session, update });
},
);
}
/// A reaction push; `own_uid` tells whether it was ours.
pub(crate) fn reaction(&self, push: ReactionPush, own_uid: Option<&str>) {
let ReactionPush { target, message_id, emoji, user, added, count } = push;
let me = (own_uid == Some(user.uid.as_str())).then_some(added);
let (uid, key, ctx) = (self.server_uid.clone(), store_target(&target), self.clone());
let e = emoji.clone();
self.history.run_then(
self.memory(),
move |s| s.set_reaction(&uid, &key, message_id, &e, count, me),
move |result| {
ctx.emit_changed(result.ok().flatten());
let update =
GatewayUpdate::Reaction { target, message_id, emoji, user, added, count };
ctx.emit(Event::Gateway { session: ctx.session, update });
},
);
}
}
/// The fields of [`Push::Reaction`].
pub(crate) struct ReactionPush {
pub target: ChatTarget,
pub message_id: i64,
pub emoji: String,
pub user: UserRef,
pub added: bool,
pub count: u32,
}
+812
View File
@@ -0,0 +1,812 @@
//! Chat history: every chat message a session sees is stored, and opening a
//! chat shows what is stored, then what the gateway has that we missed.
//!
//! # Contract for the UI
//!
//! A chat's messages are [`HistoryMessage`]s, keyed by
//! [`HistoryMessage::id`] (the local id, stable on this device) and ordered
//! by `(message.ts_ms, id)`. Every [`Event::ChatHistory`] is an upsert of
//! messages into that list:
//!
//! - [`crate::Command::OpenChat`] (and every (re)connect of a source that
//! tells the server's unique id) emits the newest `chat.history_page`
//! stored messages at once, [`HistorySource::Local`]. If the session has
//! a gateway that keeps history (capability `history`), the gateway's
//! messages we do not have yet follow: everything newer than the chat's
//! sync cursor (the latest page when the chat was never synced), stored
//! and emitted in batches of `chat.history_page`, [`HistorySource::Gateway`].
//! A last `Gateway` batch, possibly empty, says the chat is in sync.
//! Until one arrives the list holds only what this device saw: label it
//! so ("only messages seen by this device").
//! - [`crate::Command::LoadOlderHistory`] emits the page before a message:
//! the gateway's page for that time range is fetched and merged first when
//! the session has one (`Gateway`), else the stored one (`Local`).
//! - Live messages (voice, gateway pushes, query relays, our own sends) are
//! stored and emitted one by one as [`HistorySource::Live`]; so are
//! changes of stored messages (pins, reactions, the gateway id arriving
//! for a message seen over voice). A copy of a message that is already
//! there (it arrived over voice and from the gateway) is merged into the
//! existing row: same id, no second message.
//! - `complete: true`: nothing older than the batch exists as far as the
//! engine can tell; stop offering to load older messages.
//!
//! [`Event::Chat`] still reports each live message as before (without ids).
//!
//! Merging copies ("dedupe") is described in [`voelin_store::chat`]: the
//! gateway id when known, else the same text (without a relay's `[nick] `
//! prefix), author and time within `chat.dedupe_tolerance_ms`, from
//! different sources.
//!
//! # Storage
//!
//! [`History`] owns a database connection on a writer thread: writes are
//! batched into one transaction per wake-up, statements are cached, and the
//! engine's tasks never wait on the disk. `chat.store_history` (read on
//! every write) off keeps messages in memory for this run only; their ids
//! are negative. `chat.retention_days` prunes old messages (pinned ones
//! stay). Without [`crate::Command::AttachHistory`] the engine keeps its
//! history in memory.
use std::collections::VecDeque;
use std::path::Path;
use std::sync::mpsc as std_mpsc;
use std::sync::{Arc, Mutex, PoisonError, RwLock};
use std::thread::JoinHandle;
use serde::Serialize;
use tokio::sync::{broadcast, oneshot};
use tracing::warn;
use voelin_gateway_proto::{HistoryEntry, HistoryQuery, ReactionCount, feature};
use voelin_model::{ChatMessage, ChatTarget};
pub use voelin_store::MessageSource;
use voelin_store::{ChatCursor, WriteOutcome};
use voelin_store::{NewMessage, PageQuery, Reaction, RemoteInfo, Store, StoredMessage, Written};
use crate::gateway::{GatewayClient, GatewayUpdate};
use crate::settings::{CHAT_DEDUPE_TOLERANCE_MS, CHAT_HISTORY_PAGE, CHAT_STORE_HISTORY, Settings};
use crate::{Event, SessionId};
/// A chat message with what the engine knows about it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct HistoryMessage {
/// Local id, stable on this device (negative: kept in memory only).
pub id: i64,
pub message: ChatMessage,
/// What delivered it first.
pub source: MessageSource,
/// The gateway's id: pin, react and start topics with it.
pub remote_id: Option<i64>,
/// The gateway topic the message belongs to.
pub topic_id: Option<i64>,
/// In order of the first reaction.
pub reactions: Vec<ReactionCount>,
pub pinned: bool,
/// Gateway revision of the last change (0 without a gateway copy).
pub rev: i64,
}
/// Where the messages of an [`Event::ChatHistory`] come from.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum HistorySource {
/// Stored on this device: only what it saw (or fetched before).
Local,
/// Fetched from the session's gateway (and stored).
Gateway,
/// New or changed just now.
Live,
}
pub(crate) fn store_target(target: &ChatTarget) -> voelin_store::ChatTarget {
match target {
ChatTarget::Server => voelin_store::ChatTarget::Server,
ChatTarget::Channel(cid) => voelin_store::ChatTarget::Channel(*cid),
ChatTarget::Private(uid) => voelin_store::ChatTarget::Private(uid.clone()),
}
}
fn model_target(target: &voelin_store::ChatTarget) -> ChatTarget {
match target {
voelin_store::ChatTarget::Server => ChatTarget::Server,
voelin_store::ChatTarget::Channel(cid) => ChatTarget::Channel(*cid),
voelin_store::ChatTarget::Private(uid) => ChatTarget::Private(uid.clone()),
}
}
impl From<StoredMessage> for HistoryMessage {
fn from(m: StoredMessage) -> Self {
Self {
id: m.id,
message: ChatMessage {
target: model_target(&m.target),
author_name: m.author_name,
author_uid: m.author_uid,
author_id: m.author_id,
text: m.text,
ts_ms: m.ts_ms,
via_relay: m.via_relay,
},
source: m.source,
remote_id: m.remote_id,
topic_id: m.topic_id,
reactions: m
.reactions
.into_iter()
.map(|r| ReactionCount { emoji: r.emoji, count: r.count, me: r.me })
.collect(),
pinned: m.pinned,
rev: m.rev,
}
}
}
impl HistoryMessage {
/// A gateway message that could not be stored (local id 0).
pub(crate) fn unstored(entry: &HistoryEntry) -> Self {
Self {
id: 0,
message: entry.message.clone(),
source: MessageSource::Gateway,
remote_id: Some(entry.id),
topic_id: entry.topic_id,
reactions: entry.reactions.clone(),
pinned: entry.pinned,
rev: entry.rev,
}
}
}
/// A live message (voice, query relay, our own) to store.
pub(crate) fn new_message(
server_uid: &str,
msg: &ChatMessage,
source: MessageSource,
) -> NewMessage {
NewMessage {
server_uid: server_uid.to_owned(),
target: store_target(&msg.target),
ts_ms: msg.ts_ms,
author_uid: msg.author_uid.clone(),
author_name: msg.author_name.clone(),
author_id: msg.author_id,
via_relay: msg.via_relay,
text: msg.text.clone(),
source,
remote: None,
}
}
/// A gateway message to store.
pub(crate) fn gateway_message(server_uid: &str, entry: &HistoryEntry) -> NewMessage {
let mut m = new_message(server_uid, &entry.message, MessageSource::Gateway);
m.remote = Some(RemoteInfo {
id: entry.id,
rev: entry.rev,
topic_id: entry.topic_id,
reactions: entry
.reactions
.iter()
.map(|r| Reaction { emoji: r.emoji.clone(), count: r.count, me: r.me })
.collect(),
pinned: entry.pinned,
});
m
}
type Done<T> = Box<dyn FnOnce(Result<T, String>) + Send>;
enum Job {
Write { memory: bool, messages: Vec<NewMessage>, tolerance_ms: i64, done: Done<Vec<Written>> },
Run { memory: bool, f: Box<dyn FnOnce(&mut Store) + Send> },
Flush(std_mpsc::Sender<()>),
}
struct Inner {
jobs: Mutex<Option<std_mpsc::Sender<Job>>>,
thread: Mutex<Option<JoinHandle<()>>>,
persistent: bool,
}
impl Drop for Inner {
fn drop(&mut self) {
// Closing the queue ends the writer after the pending jobs.
self.jobs.get_mut().unwrap_or_else(PoisonError::into_inner).take();
if let Some(thread) = self.thread.get_mut().unwrap_or_else(PoisonError::into_inner).take()
// The last handle may go with a job's callback, on the writer
// itself: it ends on its own once the queue is empty.
&& thread.thread().id() != std::thread::current().id()
{
let _ = thread.join();
}
}
}
/// The chat history database; see the [module docs](self). Cheap to clone.
#[derive(Clone)]
pub struct History {
inner: Arc<Inner>,
}
impl std::fmt::Debug for History {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("History").field("persistent", &self.inner.persistent).finish()
}
}
impl Default for History {
fn default() -> Self {
Self::in_memory()
}
}
/// First id of messages kept in memory only (`chat.store_history` off):
/// negative, so they never collide with stored ones.
const MEMORY_IDS: i64 = -(1 << 62);
impl History {
/// History in the client database at `path` (its own connection).
pub fn open(path: &Path) -> Result<Self, voelin_store::Error> {
Ok(Self::start(Store::open(path)?, true))
}
/// History kept in memory for this run.
pub fn in_memory() -> Self {
let store =
Store::open_in_memory().and_then(|s| s.start_message_ids_at(MEMORY_IDS).map(|()| s));
Self::start(store.expect("in-memory database"), false)
}
/// History in `store`, which moves to the writer thread.
pub fn with_store(store: Store) -> Self {
Self::start(store, true)
}
fn start(store: Store, persistent: bool) -> Self {
let (tx, rx) = std_mpsc::channel();
let thread = std::thread::Builder::new()
.name("chat-history".into())
.spawn(move || writer(store, persistent, rx))
.expect("history thread");
Self {
inner: Arc::new(Inner {
jobs: Mutex::new(Some(tx)),
thread: Mutex::new(Some(thread)),
persistent,
}),
}
}
/// Whether messages go to a database file (else memory).
pub fn is_persistent(&self) -> bool {
self.inner.persistent
}
fn send(&self, job: Job) {
let jobs = self.inner.jobs.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(tx) = jobs.as_ref() {
let _ = tx.send(job);
}
}
/// Wait until everything queued so far is done (blocking).
pub fn flush(&self) {
let (tx, rx) = std_mpsc::channel();
self.send(Job::Flush(tx));
let _ = rx.recv();
}
/// Queue messages; `done` runs on the writer thread after they are stored.
pub(crate) fn write(
&self,
memory: bool,
messages: Vec<NewMessage>,
tolerance_ms: i64,
done: impl FnOnce(Result<Vec<Written>, String>) + Send + 'static,
) {
self.send(Job::Write { memory, messages, tolerance_ms, done: Box::new(done) });
}
pub(crate) async fn write_async(
&self,
memory: bool,
messages: Vec<NewMessage>,
tolerance_ms: i64,
) -> Result<Vec<Written>, String> {
let (tx, rx) = oneshot::channel();
self.write(memory, messages, tolerance_ms, move |r| {
let _ = tx.send(r);
});
rx.await.map_err(|_| "chat history stopped".to_string())?
}
/// Run `f` on the writer thread, after the jobs queued before.
pub(crate) async fn run<T: Send + 'static>(
&self,
memory: bool,
f: impl FnOnce(&mut Store) -> voelin_store::Result<T> + Send + 'static,
) -> Result<T, String> {
let (tx, rx) = oneshot::channel();
self.send(Job::Run {
memory,
f: Box::new(move |store| {
let _ = tx.send(f(store).map_err(|e| e.to_string()));
}),
});
rx.await.map_err(|_| "chat history stopped".to_string())?
}
/// Run `f` on the writer thread, then `then` with its result (there too).
pub(crate) fn run_then<T: Send + 'static>(
&self,
memory: bool,
f: impl FnOnce(&mut Store) -> voelin_store::Result<T> + Send + 'static,
then: impl FnOnce(Result<T, String>) + Send + 'static,
) {
self.send(Job::Run {
memory,
f: Box::new(move |store| then(f(store).map_err(|e| e.to_string()))),
});
}
/// Stored messages of a chat, oldest first (from the database; with
/// `memory`, from what was kept in memory while `chat.store_history`
/// was off).
pub async fn page(
&self,
server_uid: &str,
target: &ChatTarget,
query: PageQuery,
memory: bool,
) -> Result<Vec<HistoryMessage>, String> {
let (uid, target) = (server_uid.to_owned(), store_target(target));
let rows = self.run(memory, move |s| s.messages(&uid, &target, query)).await?;
Ok(rows.into_iter().map(HistoryMessage::from).collect())
}
/// Delete messages older than `before_ms` (pinned ones stay).
pub(crate) fn prune(&self, before_ms: i64) {
self.send(Job::Run {
memory: false,
f: Box::new(move |store| {
if let Err(e) = store.prune_messages(before_ms) {
warn!("cannot prune chat history: {e}");
}
}),
});
}
}
/// The writer thread: runs jobs in order; consecutive writes to the same
/// database go into one transaction.
fn writer(store: Store, persistent: bool, rx: std_mpsc::Receiver<Job>) {
let mut main = store;
// For `chat.store_history` off while the main store is a file.
let mut ephemeral: Option<Store> = None;
while let Ok(first) = rx.recv() {
let mut queue: VecDeque<Job> = std::iter::once(first).chain(rx.try_iter()).collect();
while let Some(job) = queue.pop_front() {
match job {
Job::Write { memory, messages, tolerance_ms, done } => {
let mut batch = vec![(messages, done)];
while let Some(Job::Write { memory: m, tolerance_ms: t, .. }) = queue.front()
&& *m == memory && *t == tolerance_ms
{
let Some(Job::Write { messages, done, .. }) = queue.pop_front() else {
unreachable!()
};
batch.push((messages, done));
}
let store = pick(&mut main, &mut ephemeral, persistent, memory);
let all: Vec<NewMessage> =
batch.iter().flat_map(|(m, _)| m.iter().cloned()).collect();
match store.write_messages(&all, tolerance_ms) {
Ok(written) => {
let mut written = written.into_iter();
for (messages, done) in batch {
done(Ok(written.by_ref().take(messages.len()).collect()));
}
}
Err(e) => {
warn!("cannot store chat messages: {e}");
for (_, done) in batch {
done(Err(e.to_string()));
}
}
}
}
Job::Run { memory, f } => f(pick(&mut main, &mut ephemeral, persistent, memory)),
Job::Flush(done) => {
let _ = done.send(());
}
}
}
}
}
/// The store a job uses: the main one, or with `memory` while the main one
/// is a file, one in memory.
fn pick<'a>(
main: &'a mut Store,
ephemeral: &'a mut Option<Store>,
persistent: bool,
memory: bool,
) -> &'a mut Store {
if !(memory && persistent) {
return main;
}
ephemeral.get_or_insert_with(|| {
let store = Store::open_in_memory().expect("in-memory database");
if let Err(e) = store.start_message_ids_at(MEMORY_IDS) {
warn!("in-memory chat ids: {e}");
}
store
})
}
/// The engine's history: one [`History`] that
/// [`crate::Command::AttachHistory`] can replace, shared by the sessions.
#[derive(Clone, Debug, Default)]
pub(crate) struct SharedHistory(Arc<RwLock<History>>);
impl SharedHistory {
pub fn new(history: History) -> Self {
Self(Arc::new(RwLock::new(history)))
}
pub fn current(&self) -> History {
self.0.read().unwrap_or_else(PoisonError::into_inner).clone()
}
pub fn replace(&self, history: History) {
*self.0.write().unwrap_or_else(PoisonError::into_inner) = history;
}
}
/// What the chat history flows of one session need.
#[derive(Clone)]
pub(crate) struct ChatCtx {
pub session: SessionId,
pub events: broadcast::Sender<Event>,
pub history: History,
pub settings: Settings,
/// The key of the server's history.
pub server_uid: String,
}
impl ChatCtx {
/// `chat.store_history` off: memory only.
pub fn memory(&self) -> bool {
!self.settings.get(&CHAT_STORE_HISTORY)
}
/// `chat.history_page`; `None`: no limit.
pub fn page_limit(&self) -> Option<u32> {
Some(self.settings.get(&CHAT_HISTORY_PAGE)).filter(|n| *n > 0)
}
pub fn tolerance_ms(&self) -> i64 {
self.settings.get(&CHAT_DEDUPE_TOLERANCE_MS).min(i64::MAX as u64) as i64
}
pub fn emit(&self, event: Event) {
let _ = self.events.send(event);
}
pub fn emit_batch(
&self,
target: &ChatTarget,
messages: Vec<HistoryMessage>,
source: HistorySource,
complete: bool,
) {
self.emit(Event::ChatHistory {
session: self.session,
target: target.clone(),
messages,
source,
complete,
});
}
fn gateway_failed(&self, request: &str, error: &crate::gateway::ClientError) {
self.emit(Event::Gateway {
session: self.session,
update: GatewayUpdate::Failed {
request: request.to_owned(),
code: error.code(),
message: error.to_string(),
},
});
}
/// Store live messages; each new or changed one is emitted as
/// [`HistorySource::Live`] from the writer thread.
pub fn store_live(&self, messages: Vec<NewMessage>) {
let (session, events) = (self.session, self.events.clone());
self.history.write(self.memory(), messages, self.tolerance_ms(), move |result| {
for w in result.unwrap_or_default() {
if w.outcome == WriteOutcome::Unchanged {
continue;
}
let message = HistoryMessage::from(w.message);
let _ = events.send(Event::ChatHistory {
session,
target: message.message.target.clone(),
messages: vec![message],
source: HistorySource::Live,
complete: false,
});
}
});
}
/// Store gateway entries; returns the stored rows in input order.
pub async fn store_entries(&self, entries: &[HistoryEntry]) -> Result<Vec<Written>, String> {
let messages = entries.iter().map(|e| gateway_message(&self.server_uid, e)).collect();
self.history.write_async(self.memory(), messages, self.tolerance_ms()).await
}
/// Emit a stored message that changed (e.g. its pin), as `Live`.
pub fn emit_changed(&self, message: Option<StoredMessage>) {
if let Some(m) = message {
let m = HistoryMessage::from(m);
let target = m.message.target.clone();
self.emit_batch(&target, vec![m], HistorySource::Live, false);
}
}
}
/// Whether a gateway keeps the history of `target` (it relays server and
/// channel chat, not private chat).
pub(crate) fn gateway_history(client: &GatewayClient, target: &ChatTarget) -> bool {
!matches!(target, ChatTarget::Private(_)) && client.has(feature::HISTORY)
}
/// 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<GatewayClient>,
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 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}"),
}
if let Some(client) = gateway {
sync_chat(&ctx, &client, &target).await;
}
}
/// Fetch what the gateway has for `target` beyond the chat's cursor.
async fn sync_chat(ctx: &ChatCtx, client: &GatewayClient, target: &ChatTarget) {
let (memory, uid, key) = (ctx.memory(), ctx.server_uid.clone(), store_target(target));
let gateway_id = client.info().gateway_id.clone();
let cursor = {
let (uid, key) = (uid.clone(), key.clone());
ctx.history.run(memory, move |s| s.chat_cursor(&uid, &key)).await.ok().flatten()
};
let mut cursor = match cursor {
Some(c) if c.gateway_id == gateway_id => Some(c),
// Another gateway numbers messages differently.
Some(_) => {
let (uid, key) = (uid.clone(), key.clone());
let _ = ctx.history.run(memory, move |s| s.forget_remote_ids(&uid, &key)).await;
None
}
None => None,
};
let limit = ctx.page_limit();
let save = |cursor: ChatCursor| {
let (uid, key) = (uid.clone(), key.clone());
ctx.history.run(memory, move |s| s.set_chat_cursor(&uid, &key, &cursor))
};
let mut complete = cursor.as_ref().is_some_and(|c| c.complete);
if cursor.is_none() {
// Never synced: the latest page; older ones when scrolling back.
let page = match client.history(HistoryQuery::latest(target.clone(), limit)).await {
Ok(page) => page,
Err(e) => return ctx.gateway_failed("history", &e),
};
complete = !page.has_more;
let rev = page.messages.iter().map(|e| e.rev).max().unwrap_or(0);
match ctx.store_entries(&page.messages).await {
Ok(written) => {
let messages = written.into_iter().map(|w| w.message.into()).collect();
ctx.emit_batch(target, messages, HistorySource::Gateway, complete);
}
Err(e) => return warn!("cannot store chat history: {e}"),
}
let c = ChatCursor { gateway_id: gateway_id.clone(), rev, complete, updated_ms: now_ms() };
let _ = save(c.clone()).await;
cursor = Some(c);
}
let mut rev = cursor.map_or(0, |c| c.rev);
loop {
let (entries, next, has_more) = match client.sync(target.clone(), rev, limit).await {
Ok(page) => page,
Err(e) => return ctx.gateway_failed("sync", &e),
};
let changed: Vec<HistoryMessage> = match ctx.store_entries(&entries).await {
Ok(written) => written
.into_iter()
.filter(|w| w.outcome != WriteOutcome::Unchanged)
.map(|w| w.message.into())
.collect(),
Err(e) => return warn!("cannot store chat history: {e}"),
};
rev = rev.max(next);
let c = ChatCursor { gateway_id: gateway_id.clone(), rev, complete, updated_ms: now_ms() };
let _ = save(c).await;
if !has_more || entries.is_empty() {
// The last batch, possibly empty: in sync.
return ctx.emit_batch(target, changed, HistorySource::Gateway, complete);
}
if !changed.is_empty() {
ctx.emit_batch(target, changed, HistorySource::Gateway, false);
}
}
}
/// The page before the message with local id `before` (the newest page
/// without it): the gateway's page for that range merged in first.
pub(crate) async fn load_older(
ctx: ChatCtx,
target: ChatTarget,
before: Option<i64>,
gateway: Option<GatewayClient>,
) {
let gateway = gateway.filter(|g| gateway_history(g, &target));
let (memory, uid, key) = (ctx.memory(), ctx.server_uid.clone(), store_target(&target));
let anchor = match before {
Some(id) => ctx
.history
.run(memory, move |s| s.message(id))
.await
.ok()
.flatten()
.map(|m| (m.ts_ms, m.id)),
None => None,
};
let limit = ctx.page_limit();
// Whether the gateway has nothing older (None: not asked).
let mut gateway_complete = None;
if let Some(client) = &gateway {
let gateway_id = client.info().gateway_id.clone();
let (cursor, oldest) = {
let (uid, key) = (uid.clone(), key.clone());
ctx.history
.run(memory, move |s| {
Ok((s.chat_cursor(&uid, &key)?, s.oldest_remote_ts(&uid, &key)?))
})
.await
.unwrap_or((None, None))
};
let cursor = cursor.filter(|c| c.gateway_id == gateway_id);
let known_complete = cursor.as_ref().is_some_and(|c| c.complete)
&& anchor.is_some_and(|(ts, _)| oldest.is_some_and(|o| ts <= o));
if known_complete {
gateway_complete = Some(true);
} else {
let mut query = HistoryQuery::latest(target.clone(), limit);
// Up to and including the anchor's millisecond (copies merge).
query.before_ms = anchor.map(|(ts, _)| ts.saturating_add(1));
match client.history(query).await {
Ok(page) => {
if let Err(e) = ctx.store_entries(&page.messages).await {
warn!("cannot store chat history: {e}");
}
gateway_complete = Some(!page.has_more);
// The gateway's oldest message is stored now.
if let Some(mut c) = cursor.filter(|_| !page.has_more) {
c.complete = true;
let (uid, key) = (uid.clone(), key.clone());
let _ = ctx
.history
.run(memory, move |s| s.set_chat_cursor(&uid, &key, &c))
.await;
}
}
Err(e) => ctx.gateway_failed("history", &e),
}
}
}
let query = PageQuery { before: anchor, after: None, limit: limit.map(|l| l as usize) };
match ctx.history.page(&uid, &target, query, memory).await {
Ok(local) => {
let short = limit.is_none_or(|l| local.len() < l as usize);
let complete = short && gateway_complete.unwrap_or(gateway.is_none());
let source = if gateway_complete.is_some() {
HistorySource::Gateway
} else {
HistorySource::Local
};
ctx.emit_batch(&target, local, source, complete);
}
Err(e) => warn!("cannot read chat history: {e}"),
}
}
pub(crate) fn now_ms() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use std::sync::mpsc as std_mpsc;
use super::*;
fn live(text: &str, ts_ms: i64) -> NewMessage {
let msg = ChatMessage {
target: ChatTarget::Channel(1),
author_name: "a".into(),
author_uid: Some("uid-a".into()),
author_id: None,
text: text.into(),
ts_ms,
via_relay: false,
};
new_message("srv", &msg, MessageSource::Voice)
}
/// Writes queued together run in one batch, each answered with its own
/// rows, in order; reads see them.
#[tokio::test]
async fn writes_are_batched_and_answered_in_order() {
let path = std::env::temp_dir()
.join(format!("voelin-history-{}", std::process::id()))
.join("client.db");
let _ = std::fs::remove_dir_all(path.parent().unwrap());
let history = History::open(&path).unwrap();
let (tx, rx) = std_mpsc::channel();
for i in 0..50 {
let tx = tx.clone();
let batch = vec![live(&format!("m{i}"), i), live(&format!("n{i}"), i)];
history.write(false, batch, 5000, move |r| {
let texts: Vec<String> = r.unwrap().into_iter().map(|w| w.message.text).collect();
tx.send((i, texts)).unwrap();
});
}
history.flush();
let answers: Vec<_> = rx.try_iter().collect();
assert_eq!(answers.len(), 50);
for (n, (i, texts)) in answers.into_iter().enumerate() {
assert_eq!(i, n as i64);
assert_eq!(texts, [format!("m{i}"), format!("n{i}")]);
}
let page = history
.page(
"srv",
&ChatTarget::Channel(1),
PageQuery { limit: Some(2), ..Default::default() },
false,
)
.await
.unwrap();
assert_eq!(
page.iter().map(|m| m.message.text.as_str()).collect::<Vec<_>>(),
["m49", "n49"]
);
assert!(page[0].id > 0);
// Kept in memory only: negative ids, not in the file.
let kept = history.write_async(true, vec![live("secret", 99)], 5000).await.unwrap();
assert!(kept[0].message.id < 0);
let stored =
history.page("srv", &ChatTarget::Channel(1), PageQuery::default(), false).await;
assert_eq!(stored.unwrap().len(), 100);
drop(history);
std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
}
}
+116 -5
View File
@@ -23,9 +23,19 @@
//! and defaults. The engine reads its own keys from it (e.g. who may watch
//! our stream), takes [`Command::SetSetting`] / [`Command::ResetSetting`],
//! and reports every change as [`Event::SettingChanged`].
//!
//! Chat history: every message a session sees is stored under the server's
//! unique id ([`history`], the client database with
//! [`Command::AttachHistory`]). Opening a chat emits the stored messages,
//! then, with a gateway, what we missed ([`Event::ChatHistory`]);
//! [`Command::LoadOlderHistory`] pages back. The gateway's other features
//! (pins, reactions, topics, events, stream directory, activity,
//! administration) are [`Command::Gateway`] requests and
//! [`Event::Gateway`] updates ([`gateway`]).
mod audio;
mod gateway;
pub mod gateway;
pub mod history;
#[cfg(feature = "media")]
pub mod media;
mod query;
@@ -44,6 +54,9 @@ pub use voelin_audio::{AudioSettings, ProcessingSettings, VadSettings};
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
use crate::audio::{AudioEvent, AudioHandle, AudioIn};
pub use gateway::{GatewayRequest, GatewayUpdate};
use history::SharedHistory;
pub use history::{History, HistoryMessage, HistorySource};
pub use route::{ChatRoute, Dedup, route_chat};
use settings::{SettingChange, Settings, SharedSettings};
pub use stream::{StreamFrame, StreamSink, StreamState, WatchState};
@@ -91,6 +104,21 @@ pub enum Command {
target: ChatTarget,
text: String,
},
/// The history page before the message with local id `before`
/// ([`HistoryMessage::id`]; the newest page without it), answered with
/// [`Event::ChatHistory`]. With a gateway, its page for that time is
/// fetched and merged first.
LoadOlderHistory {
session: SessionId,
target: ChatTarget,
before: Option<i64>,
},
/// A request to the session's gateway, answered with [`Event::Gateway`]
/// (see [`gateway`]).
Gateway {
session: SessionId,
request: GatewayRequest,
},
MoveToChannel {
session: SessionId,
channel: ChannelId,
@@ -213,6 +241,10 @@ pub enum Command {
/// Use these settings from now on (e.g. the ones of the client database,
/// for an engine started without).
AttachSettings(Settings),
/// Keep chat history here from now on (e.g. [`History::open`] on the
/// client database; without it, history lives in memory). Chats opened
/// later read from it.
AttachHistory(History),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -252,6 +284,9 @@ pub struct SessionState {
pub input_muted: bool,
pub output_muted: bool,
pub transmitting: bool,
/// The server's unique id once a source told it (the key of its chat
/// history; for query-only sessions the query address).
pub server_uid: Option<String>,
}
/// What the engine reports.
@@ -272,10 +307,29 @@ pub enum Event {
session: SessionId,
presence: Arc<Presence>,
},
/// A live message, as it arrives (without ids; see [`Event::ChatHistory`]).
Chat {
session: SessionId,
message: ChatMessage,
},
/// Messages of a chat to add to or update in its list, by
/// [`HistoryMessage::id`], ordered by `(ts_ms, id)`: stored ones when a
/// chat opens, the gateway's, older pages, and live messages and changes.
/// See [`history`] for when each comes.
ChatHistory {
session: SessionId,
target: ChatTarget,
/// Oldest first.
messages: Vec<HistoryMessage>,
source: HistorySource,
/// Nothing older exists as far as the engine can tell.
complete: bool,
},
/// An answer or push of the session's gateway (see [`gateway`]).
Gateway {
session: SessionId,
update: GatewayUpdate,
},
/// A client in the session started or stopped talking (voice only).
Talking {
session: SessionId,
@@ -360,6 +414,7 @@ pub struct Engine {
frames: broadcast::Sender<StreamFrame>,
runtime: tokio::runtime::Handle,
settings: SharedSettings,
history: SharedHistory,
}
impl Engine {
@@ -371,13 +426,33 @@ impl Engine {
/// Start the engine on the current tokio runtime with `settings`.
pub fn start_with_settings(settings: Settings) -> Self {
Self::start_with(settings, History::in_memory())
}
/// Start the engine on the current tokio runtime with `settings` and
/// chat `history`.
pub fn start_with(settings: Settings, history: History) -> Self {
let (commands, rx) = mpsc::unbounded_channel();
let (events, _) = broadcast::channel(4096);
// About a minute of one watched stream.
let (frames, _) = broadcast::channel(4096);
let settings = SharedSettings::new(settings);
tokio::spawn(run(rx, events.clone(), frames.clone(), settings.clone()));
Self { commands, events, frames, runtime: tokio::runtime::Handle::current(), settings }
let history = SharedHistory::new(history);
let shared = Shared { settings: settings.clone(), history: history.clone() };
tokio::spawn(run(rx, events.clone(), frames.clone(), shared));
Self {
commands,
events,
frames,
runtime: tokio::runtime::Handle::current(),
settings,
history,
}
}
/// The chat history the engine uses.
pub fn history(&self) -> History {
self.history.current()
}
/// The settings the engine uses (read, watch or change them directly;
@@ -412,6 +487,22 @@ enum Input {
Setting(SettingChange),
/// Changes were missed: the engine re-reads what it uses.
SettingsLagged,
/// Time to delete chat history past `chat.retention_days`.
Prune,
}
/// What the engine and its sessions share and commands can replace.
struct Shared {
settings: SharedSettings,
history: SharedHistory,
}
/// Delete chat history past `chat.retention_days` (0: keep everything).
fn prune_history(settings: &Settings, history: &History) {
let days = settings.get(&settings::CHAT_RETENTION_DAYS);
if days > 0 {
history.prune(history::now_ms().saturating_sub(i64::from(days) * 86_400_000));
}
}
/// A command that applies the stored audio settings if they differ from
@@ -425,10 +516,13 @@ async fn run(
mut commands: mpsc::UnboundedReceiver<Command>,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
shared: SharedSettings,
shared: Shared,
) {
let Shared { settings: shared, history } = shared;
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
let mut current = shared.current();
// Pruning: at start, then hourly (and when the setting changes).
let mut prune = tokio::time::interval(std::time::Duration::from_secs(3600));
let mut changes = current.subscribe();
let mut settings = AudioSettings::default();
let mut srtp_profiles: Option<Vec<SrtpProfile>> = None;
@@ -445,10 +539,18 @@ async fn run(
// Not while `current` holds the settings.
Err(broadcast::error::RecvError::Closed) => continue,
},
_ = prune.tick() => Input::Prune,
};
let command = match input {
Input::Command(command) => command,
Input::Prune => {
prune_history(&current, &history.current());
continue;
}
Input::Setting(change) => {
if change.key == settings::CHAT_RETENTION_DAYS.name() {
prune_history(&current, &history.current());
}
let audio = change.key == settings::AUDIO.name();
let _ = events.send(Event::SettingChanged { key: change.key });
match audio.then(|| stored_audio(&current, &settings)).flatten() {
@@ -501,6 +603,11 @@ async fn run(
current = new;
continue;
}
Command::AttachHistory(new) => {
history.replace(new.clone());
prune_history(&current, &new);
continue;
}
ref command => command_session(command),
};
if matches!(command, Command::CloseSession { .. }) {
@@ -518,6 +625,7 @@ async fn run(
frames.clone(),
settings.clone(),
shared.clone(),
history.clone(),
);
if let Some(profiles) = &srtp_profiles {
s.send(Command::SetSrtpProfiles(profiles.clone()));
@@ -558,6 +666,8 @@ fn command_session(command: &Command) -> SessionId {
| Command::OpenChat { session, .. }
| Command::CloseChat { session, .. }
| Command::SendChat { session, .. }
| Command::LoadOlderHistory { session, .. }
| Command::Gateway { session, .. }
| Command::MoveToChannel { session, .. }
| Command::SetInputMuted { session, .. }
| Command::SetOutputMuted { session, .. }
@@ -580,7 +690,8 @@ fn command_session(command: &Command) -> SessionId {
| Command::TestMicrophone { .. }
| Command::SetSetting { .. }
| Command::ResetSetting { .. }
| Command::AttachSettings(_) => {
| Command::AttachSettings(_)
| Command::AttachHistory(_) => {
unreachable!("engine-wide commands have no session")
}
}
+495 -28
View File
@@ -1,4 +1,10 @@
//! One server session: merges its sources and routes commands.
//!
//! Chat messages from every source are stored under the server's unique id
//! ([`crate::history`]); the id comes from the voice connection or the
//! gateway, or, before they connect, from what the database remembers for
//! the address (`voice:<address>`, `gateway:<url>`). The gateway's features
//! are driven through its client ([`crate::gateway`]).
use std::collections::{BTreeMap, HashSet};
use std::sync::Arc;
@@ -7,15 +13,23 @@ use tokio::sync::{broadcast, mpsc};
use tracing::debug;
use tsclientlib::ClientId;
use voelin_audio::AudioSettings;
use voelin_gateway_proto::{HistoryEntry, StreamEntry, StreamSpec, feature};
use voelin_model::{ChatMessage, ChatTarget, Presence};
use voelin_stream::ClientState;
use crate::audio::{self, AudioEvent, AudioHandle, AudioIn};
use crate::gateway::{self, GatewayCmd, GatewayEvent};
use crate::gateway::{
self, ClientError, GatewayClient, GatewayCmd, GatewayEvent, GatewayRequest, GatewayUpdate,
Push, ReactionPush,
};
use crate::history::{self, ChatCtx, HistoryMessage, MessageSource, SharedHistory};
use crate::query::{self, QueryCmd, QueryEvent};
use crate::route::{ChatRoute, Dedup, route_chat};
use crate::settings::SharedSettings;
use crate::stream::{LayerSpec, PeerConfig, SrtpProfile, StreamFrame, StreamHandle, StreamInput};
use crate::stream::{
LayerSpec, OwnStreamEvent, PeerConfig, SrtpProfile, StreamFrame, StreamHandle, StreamInfo,
StreamInput, StreamKind, kind_name, parse_kind,
};
use crate::voice::{self, VoiceCmd, VoiceEvent};
use crate::{Command, Event, ObserveState, SessionId, SessionState, Source, VoiceState};
@@ -30,9 +44,10 @@ impl SessionHandle {
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
settings: SharedSettings,
history: SharedHistory,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
tokio::spawn(Session::new(id, events, frames, audio_settings, settings).run(rx));
tokio::spawn(Session::new(id, events, frames, audio_settings, settings, history).run(rx));
Self { tx }
}
@@ -49,6 +64,21 @@ enum SourceEvent {
Query(u64, QueryEvent),
AudioOut(u64, tsproto_packets::packets::OutPacket),
Audio(u64, AudioEvent),
/// Our own stream (from the stream task of that voice connection).
OwnStream(u64, OwnStreamEvent),
/// The gateway's stream directory after subscribing.
Directory(u64, Result<Vec<StreamEntry>, ClientError>),
/// The server's unique id the database remembers for an address.
KnownServer(String),
}
/// Our live stream, for the gateway's directory.
struct OwnStream {
id: String,
title: String,
kind: StreamKind,
/// Registered in the directory of the connected gateway.
registered: bool,
}
struct Session {
@@ -61,11 +91,19 @@ struct Session {
nickname: String,
gateway: Option<(u64, mpsc::UnboundedSender<GatewayCmd>)>,
gateway_presence: Option<Presence>,
/// The logged-in gateway, for requests.
gateway_client: Option<GatewayClient>,
query: Option<(u64, mpsc::UnboundedSender<QueryCmd>)>,
query_presence: Option<Presence>,
audio: Option<AudioHandle>,
audio_settings: AudioSettings,
settings: SharedSettings,
history: SharedHistory,
/// Our unique id on the server, for the messages we send.
own_uid: Option<String>,
/// Other names of this server (`voice:<address>`, `gateway:<url>`),
/// remembered with its unique id once a source tells it.
aliases: Vec<String>,
/// Streams of the voice connection (TeamSpeak 6 only).
streams: Option<StreamHandle>,
stream_peer: PeerConfig,
@@ -78,6 +116,9 @@ struct Session {
/// Channel and `client_is_streaming` of the voice presence, as last told
/// to the streams.
streaming_clients: BTreeMap<u16, ClientState>,
/// The gateway's stream directory, by id.
directory: BTreeMap<String, StreamEntry>,
own_stream: Option<OwnStream>,
open_chats: HashSet<ChatTarget>,
dedup: Dedup,
sources_tx: mpsc::UnboundedSender<SourceEvent>,
@@ -91,6 +132,7 @@ impl Session {
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
settings: SharedSettings,
history: SharedHistory,
) -> Self {
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
Self {
@@ -103,17 +145,23 @@ impl Session {
nickname: String::new(),
gateway: None,
gateway_presence: None,
gateway_client: None,
query: None,
query_presence: None,
audio: None,
audio_settings,
settings,
history,
own_uid: None,
aliases: Vec::new(),
streams: None,
stream_peer: PeerConfig::default(),
stream_layers: Vec::new(),
srtp_profiles: None,
frames,
streaming_clients: BTreeMap::new(),
directory: BTreeMap::new(),
own_stream: None,
open_chats: HashSet::new(),
dedup: Dedup::default(),
sources_tx,
@@ -133,6 +181,10 @@ impl Session {
self.emit(Event::State { session: self.id, state: self.state.clone() });
}
fn gateway_update(&self, update: GatewayUpdate) {
self.emit(Event::Gateway { session: self.id, update });
}
async fn run(mut self, mut commands: mpsc::UnboundedReceiver<Command>) {
let mut sources = self.sources_rx.take().expect("receiver");
loop {
@@ -181,6 +233,7 @@ impl Session {
if let Some(profiles) = &self.srtp_profiles {
self.stream_peer.srtp_profiles = profiles.clone();
}
self.known_server(format!("voice:{}", options.address));
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (ev_tx, ev_rx) = mpsc::unbounded_channel();
self.audio = None;
@@ -205,6 +258,7 @@ impl Session {
Command::ObserveGateway { url, identity, .. } => {
self.stop_observing();
let generation = self.next_generation();
self.known_server(format!("gateway:{url}"));
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (ev_tx, ev_rx) = mpsc::unbounded_channel();
tokio::spawn(gateway::run(url, *identity, cmd_rx, ev_tx));
@@ -217,6 +271,13 @@ impl Session {
Command::ObserveQuery { connect, .. } => {
self.stop_observing();
let generation = self.next_generation();
// Queries do not tell the server's unique id: without another
// source, the history is kept under the query address.
if self.state.server_uid.is_none() {
let port = connect.server_port.map(|p| format!("/{p}")).unwrap_or_default();
self.learn_server_uid(format!("query:{}{port}", connect.addr), Source::Query);
self.open_histories();
}
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (ev_tx, ev_rx) = mpsc::unbounded_channel();
tokio::spawn(query::run(*connect, cmd_rx, ev_tx));
@@ -233,6 +294,7 @@ impl Session {
Command::OpenChat { target, .. } => {
self.open_chats.insert(target.clone());
self.open_relay(&target);
self.open_history(&target);
}
Command::CloseChat { target, .. } => {
self.open_chats.remove(&target);
@@ -243,25 +305,42 @@ impl Session {
let _ = tx.send(QueryCmd::CloseChat(target));
}
}
Command::SendChat { target, text, .. } => match self.route(&target) {
ChatRoute::Voice => self.voice_cmd(VoiceCmd::SendChat(target, text)),
ChatRoute::Gateway => {
if let Some((_, tx)) = &self.gateway {
let _ = tx.send(GatewayCmd::SendChat(target, text));
}
Command::SendChat { target, text, .. } => {
let route = self.route(&target);
if !matches!(route, ChatRoute::Unavailable(_)) {
self.store_own(&target, &text, &route);
}
ChatRoute::Query => {
if let Some((_, tx)) = &self.query {
let nick = if self.nickname.is_empty() {
"user".into()
} else {
self.nickname.clone()
};
let _ = tx.send(QueryCmd::SendChat { target, nick, text });
match route {
ChatRoute::Voice => self.voice_cmd(VoiceCmd::SendChat(target, text)),
ChatRoute::Gateway => {
if let Some((_, tx)) = &self.gateway {
let _ = tx.send(GatewayCmd::SendChat(target, text));
}
}
ChatRoute::Query => {
if let Some((_, tx)) = &self.query {
let nick = self.relay_nick();
let _ = tx.send(QueryCmd::SendChat { target, nick, text });
}
}
ChatRoute::Unavailable(reason) => self.error(reason),
}
ChatRoute::Unavailable(reason) => self.error(reason),
}
Command::LoadOlderHistory { target, before, .. } => match self.chat_ctx() {
Some(ctx) => {
let gateway = self.gateway_client.clone();
tokio::spawn(history::load_older(ctx, target, before, gateway));
}
// Nothing is known about the server yet: nothing stored.
None => self.emit(Event::ChatHistory {
session: self.id,
target,
messages: Vec::new(),
source: history::HistorySource::Local,
complete: true,
}),
},
Command::Gateway { request, .. } => self.gateway_request(request),
Command::MoveToChannel { channel, password, .. } => {
self.voice_cmd(VoiceCmd::Move(channel, password));
}
@@ -353,7 +432,8 @@ impl Session {
| Command::TestMicrophone { .. }
| Command::SetSetting { .. }
| Command::ResetSetting { .. }
| Command::AttachSettings(_) => {}
| Command::AttachSettings(_)
| Command::AttachHistory(_) => {}
}
}
@@ -372,6 +452,8 @@ impl Session {
s.send(StreamInput::Shutdown(reason.into()));
}
self.streaming_clients.clear();
// The stream task's report comes from a replaced source.
self.own_stream_ended();
}
fn voice_cmd(&self, cmd: VoiceCmd) {
@@ -389,6 +471,11 @@ impl Session {
route_chat(target, voice_channel, self.gateway.is_some(), self.query.is_some())
}
/// The nickname relays post our messages under.
fn relay_nick(&self) -> String {
if self.nickname.is_empty() { "user".into() } else { self.nickname.clone() }
}
/// Chats that are not covered by the voice connection need a relay.
fn open_relay(&self, target: &ChatTarget) {
match self.route(target) {
@@ -412,6 +499,235 @@ impl Session {
}
}
// Chat history
/// What the history flows need; `None` until the server's unique id is known.
fn chat_ctx(&self) -> Option<ChatCtx> {
Some(ChatCtx {
session: self.id,
events: self.events.clone(),
history: self.history.current(),
settings: self.settings.current(),
server_uid: self.state.server_uid.clone()?,
})
}
/// `chat.store_history` off: the history (and what it remembers about
/// servers) stays in memory.
fn memory(&self) -> bool {
!self.settings.current().get(&crate::settings::CHAT_STORE_HISTORY)
}
/// 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() {
// 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));
}
}
fn open_histories(&self) {
for target in &self.open_chats {
self.open_history(target);
}
}
/// Look up the server's unique id remembered for `alias`, and remember
/// it under `alias` once a source tells it.
fn known_server(&mut self, alias: String) {
if !self.aliases.contains(&alias) {
self.aliases.push(alias.clone());
}
if self.state.server_uid.is_some() {
return;
}
let tx = self.sources_tx.clone();
self.history.current().run_then(
self.memory(),
move |s| s.server_alias(&alias),
move |uid| {
if let Ok(Some(uid)) = uid {
let _ = tx.send(SourceEvent::KnownServer(uid));
}
},
);
}
/// A source told the server's unique id. The gateway's wins: its
/// history is the one synced. `true` if the history key changed.
fn learn_server_uid(&mut self, uid: String, from: Source) -> bool {
let gateway_key = self.state.server_uid.clone().filter(|_| self.gateway_client.is_some());
let keep = from != Source::Gateway && gateway_key.is_some();
if from != Source::Query {
let aliases = self.aliases.clone();
let key = gateway_key.filter(|_| keep).unwrap_or_else(|| uid.clone());
self.history.current().run_then(
self.memory(),
move |s| aliases.iter().try_for_each(|a| s.set_server_alias(a, &key)),
|r| {
if let Err(e) = r {
debug!("cannot remember the server's aliases: {e}");
}
},
);
}
if keep || self.state.server_uid.as_deref() == Some(uid.as_str()) {
return false;
}
self.state.server_uid = Some(uid);
self.emit_state();
true
}
/// Store a message we send, at once (the copy that comes back is merged).
fn store_own(&self, target: &ChatTarget, text: &str, route: &ChatRoute) {
let Some(ctx) = self.chat_ctx() else { return };
let msg = ChatMessage {
target: target.clone(),
author_name: self.relay_nick(),
author_uid: self.own_uid.clone(),
author_id: self.state.own_client.filter(|_| *route == ChatRoute::Voice),
text: text.to_owned(),
ts_ms: history::now_ms(),
via_relay: *route != ChatRoute::Voice,
};
ctx.store_live(vec![history::new_message(&ctx.server_uid, &msg, MessageSource::Local)]);
}
// Gateway
fn gateway_request(&mut self, request: GatewayRequest) {
let (Some(client), Some(ctx)) = (self.gateway_client.clone(), self.chat_ctx()) else {
self.gateway_update(GatewayUpdate::Failed {
request: request.name().into(),
code: None,
message: "not connected to a gateway".into(),
});
return;
};
match request {
// The session keeps the directory.
GatewayRequest::SubscribeStreams { on: true } => self.subscribe_streams(&client),
request => {
tokio::spawn(gateway::execute(ctx, client, request));
}
}
}
fn subscribe_streams(&self, client: &GatewayClient) {
let Some((generation, _)) = self.gateway else { return };
let (client, tx) = (client.clone(), self.sources_tx.clone());
tokio::spawn(async move {
let result = client.subscribe_streams().await;
let _ = tx.send(SourceEvent::Directory(generation, result));
});
}
/// Subscribe to what the gateway pushes (errors are reported).
fn subscribe_gateway(&self, client: &GatewayClient) {
if client.has(feature::STREAMS) {
self.subscribe_streams(client);
}
let ctx = self.chat_ctx();
for (feature, request) in [
(feature::EVENTS, GatewayRequest::SubscribeEvents { on: true }),
(feature::ACTIVITY, GatewayRequest::SubscribeActivity { on: true }),
] {
if let Some(ctx) = ctx.clone().filter(|_| client.has(feature)) {
tokio::spawn(gateway::execute(ctx, client.clone(), request));
}
}
}
/// The registered streams of the directory, for the stream task.
fn feed_directory(&self) {
let Some(streams) = &self.streams else { return };
let entries = self
.directory
.values()
.filter_map(|e| {
Some(StreamInfo {
id: e.stream_id.clone()?,
streamer: ClientId(e.client_id?),
name: e.title.clone(),
kind: parse_kind(&e.kind),
// Not in the directory; the stream's offer tells.
bitrate: 0,
viewer_limit: 0,
audio: true,
})
})
.collect();
streams.send(StreamInput::Directory(entries));
}
fn register_own_stream(&mut self) {
let Some(client) = self.gateway_client.clone().filter(|c| c.has(feature::STREAMS)) else {
return;
};
let Some(own) = self.own_stream.as_mut().filter(|s| !s.registered) else { return };
own.registered = true;
let spec = StreamSpec {
stream_id: own.id.clone(),
client_id: self.state.own_client,
channel: self.state.own_channel,
title: own.title.clone(),
kind: kind_name(own.kind),
viewers: None,
};
let (session, events) = (self.id, self.events.clone());
tokio::spawn(async move {
let update = match client.register_stream(spec).await {
Ok(stream) => GatewayUpdate::StreamRegistered { stream },
Err(e) => GatewayUpdate::Failed {
request: "register_stream".into(),
code: e.code(),
message: e.to_string(),
},
};
let _ = events.send(Event::Gateway { session, update });
});
}
fn own_stream_ended(&mut self) {
let Some(own) = self.own_stream.take() else { return };
if let Some(client) = self.gateway_client.clone().filter(|_| own.registered) {
tokio::spawn(async move {
if let Err(e) = client.unregister_stream(own.id).await {
debug!("cannot unregister our stream: {e}");
}
});
}
}
fn own_stream_event(&mut self, e: OwnStreamEvent) {
match e {
OwnStreamEvent::Live { id, title, kind } => {
self.own_stream_ended();
self.own_stream = Some(OwnStream { id, title, kind, registered: false });
self.register_own_stream();
}
OwnStreamEvent::Viewers(n) => {
let registered = self.own_stream.as_ref().filter(|s| s.registered);
if let (Some(own), Some(client)) = (registered, self.gateway_client.clone()) {
let id = own.id.clone();
tokio::spawn(async move {
if let Err(e) = client.update_stream(id, None, Some(n)).await {
debug!("cannot update our stream's viewers: {e}");
}
});
}
}
OwnStreamEvent::Ended { id } => {
if self.own_stream.as_ref().is_some_and(|s| s.id == id) {
self.own_stream_ended();
}
}
}
}
fn stop_observing(&mut self) {
if let Some((_, tx)) = self.gateway.take() {
let _ = tx.send(GatewayCmd::Stop);
@@ -419,12 +735,28 @@ impl Session {
if let Some((_, tx)) = self.query.take() {
let _ = tx.send(QueryCmd::Stop);
}
self.gateway_gone(None);
self.gateway_presence = None;
self.query_presence = None;
self.state.observe = ObserveState::Off;
self.emit_state();
}
/// Forget the logged-in gateway and what came from it.
fn gateway_gone(&mut self, reason: Option<String>) {
if self.gateway_client.take().is_none() {
return;
}
if let Some(own) = &mut self.own_stream {
own.registered = false;
}
if !self.directory.is_empty() {
self.directory.clear();
self.feed_directory();
}
self.gateway_update(GatewayUpdate::Disconnected { reason });
}
fn stop_all(&mut self) {
self.stop_streams("session closed");
if let Some((_, tx)) = self.voice.take() {
@@ -461,20 +793,53 @@ impl Session {
self.emit(Event::InputLevel { session: Some(self.id), level_db: db, sending })
}
},
SourceEvent::OwnStream(g, e) if self.is_current(Source::Voice, g) => {
self.own_stream_event(e)
}
SourceEvent::Directory(g, result) if self.is_current(Source::Gateway, g) => {
match result {
Ok(streams) => {
self.directory =
streams.iter().map(|e| (e.id.clone(), e.clone())).collect();
self.feed_directory();
self.gateway_update(GatewayUpdate::Streams { streams });
}
Err(e) => self.gateway_update(GatewayUpdate::Failed {
request: "subscribe_streams".into(),
code: e.code(),
message: e.to_string(),
}),
}
}
SourceEvent::KnownServer(uid) => {
// A source may have told the real one meanwhile.
if self.state.server_uid.is_none() {
self.state.server_uid = Some(uid);
self.emit_state();
self.open_histories();
}
}
_ => debug!("event from a replaced source ignored"),
}
}
fn voice_event(&mut self, e: VoiceEvent) {
match e {
VoiceEvent::Connected { name, flavor, own_client } => {
VoiceEvent::Connected { name, flavor, own_client, server_uid, own_uid } => {
self.state.voice = VoiceState::Connected;
self.state.own_client = Some(own_client);
if own_uid.is_some() {
self.own_uid = own_uid;
}
self.learn_server_uid(server_uid, Source::Voice);
self.emit_state();
let capabilities = flavor.capabilities();
if capabilities.streams
&& let Some((_, voice)) = &self.voice
&& let Some((generation, voice)) = &self.voice
{
let generation = *generation;
let (own_tx, own_rx) = mpsc::unbounded_channel();
self.forward(own_rx, move |e| SourceEvent::OwnStream(generation, e));
let streams = StreamHandle::spawn(
self.id,
own_client,
@@ -484,14 +849,17 @@ impl Session {
self.frames.clone(),
self.audio.clone(),
self.settings.clone(),
own_tx,
);
if !self.stream_layers.is_empty() {
streams.send(StreamInput::Layers(self.stream_layers.clone()));
}
self.streams = Some(streams);
self.feed_directory();
}
self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities });
self.reopen_relayed_chats();
self.open_histories();
}
VoiceEvent::Presence(p) => {
// Client ids are reused: forget the volumes of those who left.
@@ -530,7 +898,7 @@ impl Session {
self.emit_state();
}
}
VoiceEvent::Chat(msg) => self.chat(msg),
VoiceEvent::Chat(msg) => self.chat(msg, MessageSource::Voice, None),
VoiceEvent::Audio(packet) => {
if let Some(a) = &self.audio {
a.send(AudioIn::Packet(packet));
@@ -558,18 +926,34 @@ impl Session {
fn gateway_event(&mut self, e: GatewayEvent) {
match e {
GatewayEvent::Connected => {
GatewayEvent::Connected(client) => {
self.state.observe = ObserveState::Observing;
let info = client.info().clone();
self.gateway_client = Some(client.clone());
if self.own_uid.is_none() {
self.own_uid = Some(info.uid.clone());
}
self.learn_server_uid(info.server_uid.clone(), Source::Gateway);
self.emit_state();
self.gateway_update(GatewayUpdate::Connected {
gateway_id: info.gateway_id,
server_uid: info.server_uid,
server_name: info.server_name,
uid: info.uid,
capabilities: client.capabilities(),
});
self.subscribe_gateway(&client);
self.register_own_stream();
self.open_histories();
}
GatewayEvent::Presence(p) => {
self.gateway_presence = Some(p);
self.publish_presence();
}
GatewayEvent::Chat(msg) => self.chat(msg),
GatewayEvent::Error(message) => self.error(format!("gateway: {message}")),
GatewayEvent::Push(push) => self.gateway_push(*push),
GatewayEvent::Disconnected(reason) => {
self.gateway = None;
self.gateway_gone(reason.clone());
self.gateway_presence = None;
self.state.observe = ObserveState::Off;
self.emit_state();
@@ -581,6 +965,78 @@ impl Session {
}
}
fn gateway_push(&mut self, push: Push) {
let ctx = self.chat_ctx();
match push {
Push::Chat { id, message } => {
let entry = HistoryEntry::new(id, message.clone());
self.chat(message, MessageSource::Gateway, Some(entry));
}
Push::Message(entry) => {
self.chat(entry.message.clone(), MessageSource::Gateway, Some(entry));
}
Push::Pinned { target, pin } => match ctx {
Some(ctx) => ctx.pinned(target, pin),
None => {
let message = HistoryMessage::unstored(&pin.entry);
let pin = gateway::Pin { message, by: pin.by, ts_ms: pin.ts_ms };
self.gateway_update(GatewayUpdate::Pinned { target, pin });
}
},
Push::Unpinned { target, message_id, by } => match ctx {
Some(ctx) => ctx.unpinned(target, message_id, by),
None => self.gateway_update(GatewayUpdate::Unpinned { target, message_id, by }),
},
Push::Reaction { target, message_id, emoji, user, added, count } => {
let push = ReactionPush { target, message_id, emoji, user, added, count };
match ctx {
Some(ctx) => ctx.reaction(push, self.own_uid.as_deref()),
None => self.gateway_update(GatewayUpdate::Reaction {
target: push.target,
message_id: push.message_id,
emoji: push.emoji,
user: push.user,
added: push.added,
count: push.count,
}),
}
}
Push::TopicUpdated(topic) => self.gateway_update(GatewayUpdate::Topic { topic }),
Push::EventUpdated(event) => self.gateway_update(GatewayUpdate::Event { event }),
Push::EventDeleted(id) => self.gateway_update(GatewayUpdate::EventDeleted { id }),
Push::EventReminder { event, starts_in_ms } => {
self.gateway_update(GatewayUpdate::EventReminder { event, starts_in_ms });
}
Push::StreamStarted(stream) => {
self.directory.insert(stream.id.clone(), stream.clone());
self.feed_directory();
self.gateway_update(GatewayUpdate::StreamStarted { stream });
}
Push::StreamUpdated(stream) => {
self.directory.insert(stream.id.clone(), stream.clone());
self.feed_directory();
self.gateway_update(GatewayUpdate::StreamUpdated { stream });
}
Push::StreamEnded { id, reason } => {
if self.directory.remove(&id).is_some() {
self.feed_directory();
}
self.gateway_update(GatewayUpdate::StreamEnded { id, reason });
}
Push::ActivityAdded(entry) => {
self.gateway_update(GatewayUpdate::ActivityAdded { entry })
}
Push::Capabilities(capabilities) => {
self.gateway_update(GatewayUpdate::Capabilities { capabilities });
}
Push::Error { code, message } => self.error(format!("gateway: {code:?}: {message}")),
Push::PresenceSnapshot(_)
| Push::PresenceDelta(_)
| Push::Other(_)
| Push::Disconnected(_) => {}
}
}
fn query_event(&mut self, e: QueryEvent) {
match e {
QueryEvent::Presence(p) => {
@@ -591,7 +1047,7 @@ impl Session {
self.query_presence = Some(p);
self.publish_presence();
}
QueryEvent::Chat(msg) => self.chat(msg),
QueryEvent::Chat(msg) => self.chat(msg, MessageSource::Query, None),
QueryEvent::Error(message) => self.error(format!("query: {message}")),
QueryEvent::Disconnected => {
self.query = None;
@@ -603,12 +1059,23 @@ impl Session {
}
}
fn chat(&mut self, msg: ChatMessage) {
/// A live message: reported, and stored (merged with other copies).
fn chat(&mut self, msg: ChatMessage, source: MessageSource, entry: Option<HistoryEntry>) {
let wanted = match &msg.target {
ChatTarget::Server | ChatTarget::Private(_) => true,
target => self.open_chats.contains(target) || !msg.via_relay,
};
if wanted && !self.dedup.is_duplicate(&msg) {
if !wanted {
return;
}
if let Some(ctx) = self.chat_ctx() {
let stored = match &entry {
Some(entry) => history::gateway_message(&ctx.server_uid, entry),
None => history::new_message(&ctx.server_uid, &msg, source),
};
ctx.store_live(vec![stored]);
}
if !self.dedup.is_duplicate(&msg) {
self.emit(Event::Chat { session: self.id, message: msg });
}
}
+44 -1
View File
@@ -1061,8 +1061,43 @@ pub static STREAM_PERMISSIONS: Key<StreamPermissions> = Key::new(
StreamPermissions::default,
);
/// Keep chat history in the client database. Off: messages seen from now
/// on are kept in memory only (for this run), nothing is read from or
/// written to the database.
pub static CHAT_STORE_HISTORY: Key<bool> =
Key::new("chat.store_history", Kind::Bool, "Keep chat history on this device.", || true);
/// Messages per history page: shown when a chat opens, fetched per step
/// when scrolling back, and per request while syncing with a gateway.
/// 0: everything at once. No maximum.
pub static CHAT_HISTORY_PAGE: Key<u32> = Key::new(
"chat.history_page",
Kind::UInt { min: 0 },
"Messages per chat history page (0: all at once).",
|| 100,
);
/// How far apart (ms) two copies of a message from different sources may
/// be stamped and still count as one message (e.g. live over voice and
/// again from the gateway). No maximum.
pub static CHAT_DEDUPE_TOLERANCE_MS: Key<u64> = Key::new(
"chat.dedupe_tolerance_ms",
Kind::UInt { min: 0 },
"Time difference (ms) within which two copies of a message are one.",
|| 5000,
);
/// Delete stored chat messages older than this many days (pinned ones
/// stay); 0 keeps everything.
pub static CHAT_RETENTION_DAYS: Key<u32> = Key::new(
"chat.retention_days",
Kind::UInt { min: 0 },
"Delete stored chat messages older than this many days (0: keep all).",
|| 0,
);
/// The keys every [`Settings`] knows from the start.
pub fn builtin_keys() -> [&'static dyn Setting; 11] {
pub fn builtin_keys() -> [&'static dyn Setting; 15] {
[
&CRASH_REPORTS,
&AUDIO,
@@ -1075,6 +1110,10 @@ pub fn builtin_keys() -> [&'static dyn Setting; 11] {
&STREAM_SRTP_PROFILES,
&STREAM_HARDWARE_ACCELERATION,
&STREAM_PERMISSIONS,
&CHAT_STORE_HISTORY,
&CHAT_HISTORY_PAGE,
&CHAT_DEDUPE_TOLERANCE_MS,
&CHAT_RETENTION_DAYS,
]
}
@@ -1127,6 +1166,10 @@ mod tests {
);
assert!(s.get(&STREAM_HARDWARE_ACCELERATION));
assert_eq!(s.get(&STREAM_ENCODER_BACKEND), "auto");
assert!(s.get(&CHAT_STORE_HISTORY));
assert_eq!(s.get(&CHAT_HISTORY_PAGE), 100);
assert_eq!(s.get(&CHAT_DEDUPE_TOLERANCE_MS), 5000);
assert_eq!(s.get(&CHAT_RETENTION_DAYS), 0);
assert_eq!(s.source("stream.fps"), Some(Source::Default));
let names: Vec<_> = s.keys().iter().map(|k| k.name()).collect();
assert!(names.contains(&"stream.permissions") && names.contains(&"audio"));
+258 -5
View File
@@ -3,18 +3,26 @@
//!
//! The voice task forwards stream notifications here and sends the resulting
//! commands. Only started for TeamSpeak 6 servers.
//!
//! Streams that started before we joined are looked up on the server
//! (`requeststreaminfo`) and in the session's gateway directory: its
//! registered entries (stream id and streamer) are handed to the stream
//! sessions ([`voelin_stream::Streams::discovered`]) for streamers in our
//! channel, and a [`StreamLookup`] answers for the gateway when the server
//! cannot. Our own stream's life (live, viewers, ended) goes back to the
//! session ([`OwnStreamEvent`]), which keeps its directory entry.
use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use tokio::sync::{broadcast, mpsc};
use tracing::debug;
use tsclientlib::ClientId;
use voelin_stream::{
ClientState, LayerFeedback, Output, Request, StreamEvent, StreamNotification, StreamerEvent,
StreamerOptions, Streams, WatchEvent,
ClientState, LayerFeedback, Output, Request, StreamEvent, StreamLookup, StreamNotification,
StreamerEvent, StreamerOptions, Streams, WatchEvent,
};
pub use voelin_stream::{
Codec, EncodedFrame, EndReason, FrameSource, Frequency, LayerId, LayerSet, LayerSpec,
@@ -145,10 +153,72 @@ pub(crate) enum StreamInput {
RequestFailed(Request, String),
/// Clients on the server: channel and `client_is_streaming`.
Clients(BTreeMap<u16, ClientState>),
/// The registered streams of the gateway's directory (full list).
Directory(Vec<StreamInfo>),
/// The voice connection is gone.
Shutdown(String),
}
/// Our own stream, for the session (the gateway directory).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum OwnStreamEvent {
Live {
id: String,
title: String,
kind: StreamKind,
},
/// Connected viewers.
Viewers(u32),
Ended {
id: String,
},
}
/// The kind of a stream as the gateway directory names it.
pub(crate) fn kind_name(kind: StreamKind) -> String {
match kind {
StreamKind::Camera => "camera".into(),
StreamKind::Screen => "screen".into(),
StreamKind::Window => "window".into(),
StreamKind::Other(v) => format!("other:{v}"),
}
}
/// [`kind_name`] back; unknown names are screens.
pub(crate) fn parse_kind(name: &str) -> StreamKind {
match name {
"camera" => StreamKind::Camera,
"window" => StreamKind::Window,
other => match other.strip_prefix("other:").and_then(|v| v.parse().ok()) {
Some(v) => StreamKind::from_u8(v),
None => StreamKind::Screen,
},
}
}
/// The gateway directory as the stream task sees it.
#[derive(Default)]
struct GatewayStreams {
entries: Vec<StreamInfo>,
/// Streamers the [`GatewayLookup`] was asked about.
wanted: Vec<ClientId>,
}
/// Looks unannounced streams up in the gateway's directory (after the
/// server, see [`voelin_stream::discovery`]).
struct GatewayLookup(Arc<Mutex<GatewayStreams>>);
impl StreamLookup for GatewayLookup {
fn lookup(&mut self, streamer: ClientId, _out: &mut voelin_stream::session::Outbox) -> bool {
let mut dir = self.0.lock().unwrap_or_else(PoisonError::into_inner);
let known = dir.entries.iter().any(|e| e.streamer == streamer);
if known {
dir.wanted.push(streamer);
}
known
}
}
pub(crate) struct StreamHandle {
tx: mpsc::UnboundedSender<StreamInput>,
}
@@ -164,11 +234,15 @@ impl StreamHandle {
frames: broadcast::Sender<StreamFrame>,
audio: Option<AudioHandle>,
settings: SharedSettings,
own: mpsc::UnboundedSender<OwnStreamEvent>,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
let mut streams = Streams::new(ClientId(own_client), config);
let gateway = Arc::new(Mutex::new(GatewayStreams::default()));
streams.add_lookup(Box::new(GatewayLookup(gateway.clone())));
let task = StreamTask {
session,
streams: Streams::new(ClientId(own_client), config),
streams,
voice,
events,
frames,
@@ -177,6 +251,12 @@ impl StreamHandle {
sink: None,
layers: Vec::new(),
settings,
own,
setup: None,
live: None,
viewers: 0,
clients: BTreeMap::new(),
gateway,
};
tokio::spawn(task.run(rx));
Self { tx }
@@ -203,6 +283,17 @@ struct StreamTask {
layers: Vec<LayerSpec>,
/// `stream.permissions` decides join requests.
settings: SharedSettings,
/// Our stream's life, for the session.
own: mpsc::UnboundedSender<OwnStreamEvent>,
/// The setup of our stream since `Start`.
setup: Option<StreamSetup>,
/// Our live stream's id.
live: Option<String>,
/// Connected viewers of our stream, as last told.
viewers: u32,
/// The clients as of the last update.
clients: BTreeMap<u16, ClientState>,
gateway: Arc<Mutex<GatewayStreams>>,
}
impl StreamTask {
@@ -232,6 +323,7 @@ impl StreamTask {
let session = self.session;
let result = match input {
StreamInput::Start { setup, auto_accept } => {
self.setup = Some(setup.clone());
let layers = self.layers.clone();
let options = StreamerOptions { setup, auto_accept, layers, ..Default::default() };
self.streams.start(options).map(|()| {
@@ -279,7 +371,14 @@ impl StreamTask {
StreamInput::Clients(clients) => {
// Streams of clients that left, stopped streaming or are not
// in our channel are gone; unannounced ones are looked up.
self.clients = clients.clone();
self.streams.update_clients(clients);
self.add_directory_streams();
Ok(())
}
StreamInput::Directory(entries) => {
self.gateway.lock().unwrap_or_else(PoisonError::into_inner).entries = entries;
self.add_directory_streams();
Ok(())
}
StreamInput::Shutdown(_) => Ok(()),
@@ -289,6 +388,30 @@ impl StreamTask {
}
}
/// Streams of the gateway directory we were not told about: streamers in
/// our channel that still stream (the sessions check the channel).
fn add_directory_streams(&mut self) {
let entries = {
let mut dir = self.gateway.lock().unwrap_or_else(PoisonError::into_inner);
dir.wanted.clear();
dir.entries.clone()
};
let own = self.streams.own_client();
for info in entries {
let stopped =
self.clients.get(&info.streamer.0).is_some_and(|c| c.streaming == Some(false));
if info.streamer != own && !stopped && self.streams.directory().get(&info.id).is_none()
{
debug!(stream = %info.id, streamer = info.streamer.0, "stream from the gateway directory");
self.streams.discovered(info);
}
}
}
fn own_stream(&self, event: OwnStreamEvent) {
let _ = self.own.send(event);
}
/// Send the requests on the connection and report the events.
fn flush(&mut self) {
while let Some(output) = self.streams.poll_output() {
@@ -316,6 +439,14 @@ impl StreamTask {
feedback,
};
self.sink = Some(sink.clone());
let setup = self.setup.clone().unwrap_or_default();
self.live = Some(id.clone());
self.viewers = 0;
self.own_stream(OwnStreamEvent::Live {
id: id.clone(),
title: setup.name,
kind: setup.kind,
});
self.emit(Event::StreamState { session, state: StreamState::Live { id, sink } });
}
StreamEvent::Streamer(StreamerEvent::Request { viewer, message }) => {
@@ -338,6 +469,12 @@ impl StreamTask {
}
}
StreamEvent::Streamer(StreamerEvent::Viewers(viewers)) => {
let connected =
viewers.iter().filter(|v| v.state == ViewerState::Connected).count() as u32;
if connected != self.viewers && self.live.is_some() {
self.viewers = connected;
self.own_stream(OwnStreamEvent::Viewers(connected));
}
self.emit(Event::StreamViewers { session, viewers });
}
// The sink already has it (layer feedback).
@@ -351,6 +488,9 @@ impl StreamTask {
if let Some(sink) = self.sink.take() {
sink.live.store(false, Ordering::Relaxed);
}
if let Some(id) = self.live.take() {
self.own_stream(OwnStreamEvent::Ended { id });
}
self.emit(Event::StreamState { session, state: StreamState::Ended(reason) });
}
StreamEvent::Watch { id, event } => {
@@ -405,6 +545,9 @@ impl StreamTask {
if let Some(sink) = self.sink.take() {
sink.live.store(false, Ordering::Relaxed);
}
if let Some(id) = self.live.take() {
self.own_stream(OwnStreamEvent::Ended { id });
}
for watched in self.streams.watching() {
let stream_id = watched.id().to_owned();
if let Some(audio) = &self.audio {
@@ -521,6 +664,25 @@ mod tests {
audio: Option<AudioHandle>,
settings: &Settings,
) -> (Handles, broadcast::Receiver<Event>, broadcast::Receiver<StreamFrame>) {
let (handles, rx, frames, _) = pair_full(audio, settings, false);
(handles, rx, frames)
}
/// [`pair_with`]; with `late`, the server does not tell the viewer
/// (session 2) about streams, as for a client that joined after the
/// stream started, and does not answer lookups. Also returns what the
/// streamer (session 1) reports about its own stream.
fn pair_full(
audio: Option<AudioHandle>,
settings: &Settings,
late: bool,
) -> (
Handles,
broadcast::Receiver<Event>,
broadcast::Receiver<StreamFrame>,
mpsc::UnboundedReceiver<OwnStreamEvent>,
) {
let (own_tx, own_rx) = mpsc::unbounded_channel();
let (events, rx) = broadcast::channel(4096);
let (frames, frames_rx) = broadcast::channel(4096);
let mut voices = Vec::new();
@@ -539,6 +701,7 @@ mod tests {
frames.clone(),
if session == 2 { audio.take() } else { None },
SharedSettings::new(settings.clone()),
if session == 1 { own_tx.clone() } else { mpsc::unbounded_channel().0 },
));
voices.push(voice_rx);
}
@@ -550,6 +713,10 @@ mod tests {
while let Some(cmd) = voice_rx.recv().await {
if let VoiceCmd::Stream(request) = cmd {
for (to, n) in relay(CLIENTS[i], request) {
let announcement = matches!(n, StreamNotification::Started { .. });
if late && to == CLIENTS[1] && announcement {
continue;
}
let index = CLIENTS.iter().position(|c| *c == to).unwrap();
handles[index].send(StreamInput::Notification(n));
}
@@ -557,7 +724,7 @@ mod tests {
}
});
}
(handles, rx, frames_rx)
(handles, rx, frames_rx, own_rx)
}
/// Session 1 streams (auto-accepting), session 2 watches; returns the sink
@@ -736,6 +903,92 @@ mod tests {
feeder.await.unwrap();
}
/// A viewer that was not told about a running stream, and whose server
/// lookup goes unanswered, finds it in the gateway directory and
/// watches it; the streamer reports its stream's life for the directory.
#[tokio::test(flavor = "multi_thread")]
async fn late_viewer_finds_the_stream_in_the_gateway_directory() {
let (handles, mut rx, _frames, mut own) = pair_full(None, &Settings::in_memory(), true);
let setup = StreamSetup {
name: "directory test".into(),
kind: StreamKind::Window,
..Default::default()
};
handles[0].send(StreamInput::Start { setup, auto_accept: true });
wait(&mut rx, |e| match e {
Event::StreamState { session: 1, state: StreamState::Live { .. } } => Some(()),
_ => None,
})
.await;
let live = timeout(Duration::from_secs(5), own.recv()).await.unwrap().unwrap();
assert_eq!(
live,
OwnStreamEvent::Live {
id: "s-1".into(),
title: "directory test".into(),
kind: StreamKind::Window
}
);
// Both in channel 1, the streamer streaming: the viewer asks the
// server, which does not answer.
let clients = BTreeMap::from([
(CLIENTS[0], ClientState { channel: 1, streaming: Some(true) }),
(CLIENTS[1], ClientState { channel: 1, streaming: Some(false) }),
]);
handles[1].send(StreamInput::Clients(clients));
tokio::time::sleep(Duration::from_millis(200)).await;
// The gateway's directory has it.
let entry = StreamInfo {
id: "s-1".into(),
streamer: ClientId(CLIENTS[0]),
name: "directory test".into(),
kind: parse_kind(&kind_name(StreamKind::Window)),
bitrate: 0,
viewer_limit: 0,
audio: true,
};
handles[1].send(StreamInput::Directory(vec![entry]));
wait(&mut rx, |e| match e {
Event::StreamsChanged { session: 2, streams }
if streams.iter().any(|s| s.id == "s-1") =>
{
Some(())
}
_ => None,
})
.await;
handles[1].send(StreamInput::Watch { stream_id: "s-1".into() });
wait(&mut rx, |e| match e {
Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()),
_ => None,
})
.await;
// One connected viewer, then the end.
let viewers = timeout(Duration::from_secs(5), own.recv()).await.unwrap().unwrap();
assert_eq!(viewers, OwnStreamEvent::Viewers(1));
handles[0].send(StreamInput::Stop);
loop {
match timeout(Duration::from_secs(5), own.recv()).await.unwrap().unwrap() {
OwnStreamEvent::Ended { id } => break assert_eq!(id, "s-1"),
OwnStreamEvent::Viewers(_) => {}
other => panic!("{other:?}"),
}
}
for h in handles.iter() {
h.send(StreamInput::Shutdown("done".into()));
}
}
#[test]
fn kind_names_round_trip() {
for kind in
[StreamKind::Camera, StreamKind::Screen, StreamKind::Window, StreamKind::Other(9)]
{
assert_eq!(parse_kind(&kind_name(kind)), kind);
}
assert_eq!(parse_kind("game"), StreamKind::Screen);
}
/// `stream.permissions` answers join requests unless it is `friends`.
#[tokio::test(flavor = "multi_thread")]
async fn permissions_answer_join_requests() {
+31 -1
View File
@@ -68,6 +68,11 @@ pub(crate) enum VoiceEvent {
name: String,
flavor: ServerFlavor,
own_client: u16,
/// The server's unique id (from its public key, as the server
/// generation computes it).
server_uid: String,
/// Our unique id as the server knows it.
own_uid: Option<String>,
},
Presence(Presence),
OwnChannel(ChannelId),
@@ -201,11 +206,20 @@ async fn run_inner(
{
let state = con.get_state()?;
let flavor = ServerFlavor::from_version_string(&state.server.version);
info!(server = %state.server.name, ?flavor, "voice connected");
let ids = voelin_gateway_proto::UniqueIds::from_omega(&state.server.public_key.to_ts());
let server_uid = ids.for_server(matches!(flavor, ServerFlavor::Ts6(_))).to_owned();
info!(server = %state.server.name, ?flavor, %server_uid, "voice connected");
let own_uid = state
.clients
.get(&state.own_client)
.and_then(|c| c.uid.as_ref())
.map(|u| u.as_ref().to_string());
let _ = events.send(VoiceEvent::Connected {
name: state.server.name.clone(),
flavor,
own_client: state.own_client.0,
server_uid,
own_uid,
});
}
// Subscribe to all channels to see everyone.
@@ -241,6 +255,13 @@ async fn run_inner(
MessageTarget::Channel => {
ChatTarget::Channel(own_channel.unwrap_or(0))
}
// Our own private message comes back to us: it
// belongs to the chat with its receiver.
MessageTarget::Client(to)
if Some(invoker.id) == own_client(&con) =>
{
ChatTarget::Private(client_uid(&con, to).unwrap_or_default())
}
MessageTarget::Client(_) | MessageTarget::Poke(_) => {
ChatTarget::Private(
invoker
@@ -314,6 +335,15 @@ async fn run_inner(
Ok(())
}
fn own_client(con: &Connection) -> Option<tsclientlib::ClientId> {
con.get_state().ok().map(|state| state.own_client)
}
fn client_uid(con: &Connection, client: &tsclientlib::ClientId) -> Option<String> {
let state = con.get_state().ok()?;
state.clients.get(client)?.uid.as_ref().map(|u| u.as_ref().to_string())
}
fn own_channel(con: &Connection) -> Option<ChannelId> {
let state = con.get_state().ok()?;
state.clients.get(&state.own_client).map(|c| c.channel.0)
+707
View File
@@ -0,0 +1,707 @@
//! Chat history and gateway features through the engine, against a fake
//! gateway (a WebSocket server speaking the tsgw protocol from memory).
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use futures::{SinkExt, StreamExt};
use serde_json::json;
use tokio::net::TcpListener;
use tokio::sync::broadcast::Receiver;
use tokio::sync::mpsc;
use tokio::time::timeout;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
use voelin_core::gateway::{GatewayRequest, GatewayUpdate};
use voelin_core::history::MessageSource;
use voelin_core::settings::Settings;
use voelin_core::{Command, Engine, Event, History, HistoryMessage, HistorySource, ObserveState};
use voelin_gateway_proto::{
ClientMsg, Envelope, ErrorCode, HistoryEntry, HistoryPage, PinInfo, ReactionCount, ServerMsg,
TopicInfo, UserRef, feature,
};
use voelin_model::{ChatMessage, ChatTarget, PresenceSnapshot};
const LOBBY: ChatTarget = ChatTarget::Channel(1);
const ME: &str = "me-uid";
/// A connected session: its pushes and open chats.
type Session = (mpsc::UnboundedSender<ServerMsg>, Arc<Mutex<HashSet<ChatTarget>>>);
/// The gateway's data.
#[derive(Default)]
struct State {
messages: Vec<HistoryEntry>,
rev: i64,
/// (message, emoji) → who reacted.
reactions: BTreeMap<(i64, String), BTreeSet<String>>,
topics: Vec<TopicInfo>,
/// Push channels of the connected sessions, with their open chats.
sessions: Vec<Session>,
/// Types of the requests received.
requests: Vec<String>,
/// Close connections at once (the gateway is down).
refuse: bool,
}
impl State {
fn next_rev(&mut self) -> i64 {
self.rev += 1;
self.rev
}
/// A message as `uid` sees it.
fn view(&self, entry: &HistoryEntry, uid: &str) -> HistoryEntry {
let mut e = entry.clone();
e.reactions = self
.reactions
.iter()
.filter(|((id, _), users)| *id == entry.id && !users.is_empty())
.map(|((_, emoji), users)| ReactionCount {
emoji: emoji.clone(),
count: users.len() as u32,
me: users.contains(uid),
})
.collect();
e
}
fn add(&mut self, target: ChatTarget, author: &str, text: &str, ts_ms: i64) -> HistoryEntry {
let rev = self.next_rev();
let message = ChatMessage {
target,
author_name: author.into(),
author_uid: Some(format!("{author}-uid")),
author_id: None,
text: text.into(),
ts_ms,
via_relay: true,
};
let entry =
HistoryEntry { rev, ..HistoryEntry::new(self.messages.len() as i64 + 1, message) };
self.messages.push(entry.clone());
self.push_open(&entry.message.target, ServerMsg::Message { entry: entry.clone() });
entry
}
fn push_open(&self, target: &ChatTarget, msg: ServerMsg) {
for (tx, open) in &self.sessions {
if open.lock().unwrap().contains(target) {
let _ = tx.send(msg.clone());
}
}
}
fn page(&self, q: &voelin_gateway_proto::HistoryQuery) -> HistoryPage {
let mut all: Vec<&HistoryEntry> = self
.messages
.iter()
.filter(|e| e.message.target == q.target)
.filter(|e| q.topic.is_none_or(|t| e.topic_id == Some(t)))
.filter(|e| q.before.is_none_or(|b| e.id < b))
.filter(|e| q.before_ms.is_none_or(|b| e.message.ts_ms < b))
.filter(|e| q.after.is_none_or(|a| e.id > a))
.collect();
let mut has_more = false;
if let Some(limit) = q.limit.map(|l| l as usize)
&& all.len() > limit
{
has_more = true;
all = all.split_off(all.len() - limit);
}
HistoryPage {
target: q.target.clone(),
topic: q.topic,
messages: all.into_iter().map(|e| self.view(e, ME)).collect(),
has_more,
}
}
}
struct FakeGateway {
state: Arc<Mutex<State>>,
url: String,
}
impl FakeGateway {
async fn start() -> Self {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("ws://{}/v1", listener.local_addr().unwrap());
let state: Arc<Mutex<State>> = Arc::default();
let st = state.clone();
tokio::spawn(async move {
while let Ok((tcp, _)) = listener.accept().await {
tokio::spawn(serve(tcp, st.clone()));
}
});
Self { state, url }
}
fn add(&self, target: ChatTarget, author: &str, text: &str, ts_ms: i64) -> HistoryEntry {
self.state.lock().unwrap().add(target, author, text, ts_ms)
}
fn requests(&self) -> Vec<String> {
self.state.lock().unwrap().requests.clone()
}
}
fn caps() -> Vec<String> {
[
feature::PRESENCE,
feature::RELAY,
feature::HISTORY,
feature::PINS,
feature::REACTIONS,
feature::TOPICS,
feature::EVENTS,
]
.map(String::from)
.to_vec()
}
async fn serve(tcp: tokio::net::TcpStream, state: Arc<Mutex<State>>) {
if state.lock().unwrap().refuse {
return;
}
#[allow(clippy::result_large_err)] // tungstenite's callback type
let callback = |_: &Request, mut response: Response| {
response
.headers_mut()
.insert("Sec-WebSocket-Protocol", voelin_gateway_proto::SUBPROTOCOL.parse().unwrap());
Ok(response)
};
let ws = tokio_tungstenite::accept_hdr_async(tcp, callback).await.unwrap();
let (mut sink, mut stream) = ws.split();
let (tx, mut rx) = mpsc::unbounded_channel::<Envelope<ServerMsg>>();
tokio::spawn(async move {
while let Some(env) = rx.recv().await {
let text = serde_json::to_string(&env).unwrap();
if sink.send(Message::Text(text.into())).await.is_err() {
break;
}
}
let _ = sink.close().await;
});
let _ = tx.send(Envelope::new(ServerMsg::Hello {
gateway_id: "fake-gw".into(),
server_uid: "fake-server".into(),
server_name: "Fake".into(),
nonce: "n".into(),
capabilities: caps(),
}));
// Pushes of this session.
let (push_tx, mut push_rx) = mpsc::unbounded_channel();
let open: Arc<Mutex<HashSet<ChatTarget>>> = Arc::default();
let forward = tx.clone();
tokio::spawn(async move {
while let Some(msg) = push_rx.recv().await {
if forward.send(Envelope::new(msg)).is_err() {
break;
}
}
});
let mut logged_in = false;
while let Some(Ok(frame)) = stream.next().await {
let Message::Text(text) = frame else { continue };
let env: Envelope<ClientMsg> = serde_json::from_str(text.as_str()).unwrap();
let id = env.id.unwrap_or(0);
let reply = {
let mut st = state.lock().unwrap();
let name = serde_json::to_value(&env.msg).unwrap()["type"].as_str().unwrap().to_owned();
st.requests.push(name);
answer(&mut st, env.msg, &open, &push_tx, &mut logged_in)
};
if tx.send(Envelope::with_id(id, reply)).is_err() {
break;
}
}
let mut st = state.lock().unwrap();
st.sessions.retain(|(t, _)| !t.same_channel(&push_tx));
}
fn answer(
st: &mut State,
msg: ClientMsg,
open: &Arc<Mutex<HashSet<ChatTarget>>>,
push: &mpsc::UnboundedSender<ServerMsg>,
logged_in: &mut bool,
) -> ServerMsg {
match msg {
ClientMsg::Auth { .. } => {
*logged_in = true;
st.sessions.push((push.clone(), open.clone()));
ServerMsg::AuthOk {
uid: ME.into(),
token: "t".into(),
token_expires: i64::MAX,
capabilities: caps(),
}
}
_ if !*logged_in => {
ServerMsg::Error { code: ErrorCode::NotAuthenticated, message: "".into() }
}
ClientMsg::Enable { .. } => ServerMsg::Enabled { features: caps() },
ClientMsg::SubscribePresence => {
let snapshot = PresenceSnapshot {
server_name: "Fake".into(),
channels: Vec::new(),
clients: Vec::new(),
};
let _ = push.send(ServerMsg::PresenceSnapshot { seq: 0, snapshot });
ServerMsg::Ok
}
ClientMsg::OpenChat { target } => {
open.lock().unwrap().insert(target);
ServerMsg::Ok
}
ClientMsg::CloseChat { target } => {
open.lock().unwrap().remove(&target);
ServerMsg::Ok
}
ClientMsg::SendChat { target, text } => {
// Posted as "me" (uid `me-uid`).
st.add(target, "me", &text, now_ms());
ServerMsg::Ok
}
ClientMsg::Post { target, text, topic } => {
let rev = st.next_rev();
let message = ChatMessage {
target: target.clone(),
author_name: "me".into(),
author_uid: Some(ME.into()),
author_id: None,
text,
ts_ms: now_ms(),
via_relay: true,
};
let entry = HistoryEntry {
rev,
topic_id: topic,
..HistoryEntry::new(st.messages.len() as i64 + 1, message)
};
st.messages.push(entry.clone());
st.push_open(&target, ServerMsg::Message { entry: entry.clone() });
ServerMsg::Posted { entry }
}
ClientMsg::QueryHistory(q) => ServerMsg::HistoryPage(st.page(&q)),
ClientMsg::Sync { target, since_rev, limit } => {
let mut changed: Vec<HistoryEntry> = st
.messages
.iter()
.filter(|e| e.message.target == target && e.rev > since_rev)
.map(|e| st.view(e, ME))
.collect();
changed.sort_by_key(|e| e.rev);
let has_more = limit.is_some_and(|l| changed.len() > l as usize);
if let Some(l) = limit {
changed.truncate(l as usize);
}
let rev = changed.last().map_or(since_rev, |e| e.rev);
ServerMsg::SyncPage { target, messages: changed, rev, has_more }
}
ClientMsg::Pin { message_id } => {
let rev = st.next_rev();
let Some(e) = st.messages.iter_mut().find(|e| e.id == message_id) else {
return ServerMsg::Error { code: ErrorCode::NotFound, message: "".into() };
};
e.pinned = true;
e.rev = rev;
let entry = e.clone();
let pin = PinInfo { entry: st.view(&entry, ME), by: me(), ts_ms: now_ms() };
st.push_open(
&entry.message.target,
ServerMsg::Pinned { target: entry.message.target.clone(), pin },
);
ServerMsg::Ok
}
ClientMsg::ListPins { target } => ServerMsg::Pins {
pins: st
.messages
.iter()
.filter(|e| e.pinned && e.message.target == target)
.map(|e| PinInfo { entry: st.view(e, ME), by: me(), ts_ms: 1 })
.collect(),
target,
},
ClientMsg::React { message_id, emoji } => {
let rev = st.next_rev();
let Some(e) = st.messages.iter_mut().find(|e| e.id == message_id) else {
return ServerMsg::Error { code: ErrorCode::NotFound, message: "".into() };
};
e.rev = rev;
let target = e.message.target.clone();
let users = st.reactions.entry((message_id, emoji.clone())).or_default();
users.insert(ME.into());
let count = users.len() as u32;
let push = ServerMsg::Reaction {
target: target.clone(),
message_id,
emoji,
user: me(),
added: true,
count,
};
st.push_open(&target, push);
ServerMsg::Ok
}
ClientMsg::CreateTopic { target, title, message_id } => {
let topic = TopicInfo {
id: st.topics.len() as i64 + 1,
target,
title,
creator: me(),
created_ms: 1,
root_message_id: message_id,
last_activity_ms: 1,
message_count: 0,
archived: false,
};
st.topics.push(topic.clone());
ServerMsg::Topic { topic }
}
ClientMsg::SubscribeEvents | ClientMsg::Ping => ServerMsg::Ok,
_ => ServerMsg::Error { code: ErrorCode::UnknownType, message: "not in the fake".into() },
}
}
fn me() -> UserRef {
UserRef { uid: ME.into(), name: "me".into() }
}
fn now_ms() -> i64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as i64
}
/// The next event matching `f`, within 10 s.
async fn wait<T>(rx: &mut Receiver<Event>, what: &str, mut f: impl FnMut(Event) -> Option<T>) -> T {
timeout(Duration::from_secs(10), async {
loop {
match rx.recv().await {
Ok(e) => {
if let Some(t) = f(e) {
return t;
}
}
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
Err(e) => panic!("{e}"),
}
}
})
.await
.unwrap_or_else(|_| panic!("timed out waiting for {what}"))
}
type Batch = (Vec<HistoryMessage>, HistorySource, bool);
async fn batch(rx: &mut Receiver<Event>, source: HistorySource) -> Batch {
wait(rx, &format!("{source:?} history"), |e| match e {
Event::ChatHistory { messages, source: s, complete, target, .. }
if s == source && target == LOBBY =>
{
Some((messages, s, complete))
}
_ => None,
})
.await
}
fn texts(messages: &[HistoryMessage]) -> Vec<&str> {
messages.iter().map(|m| m.message.text.as_str()).collect()
}
async fn update(
rx: &mut Receiver<Event>,
what: &str,
mut f: impl FnMut(&GatewayUpdate) -> bool,
) -> GatewayUpdate {
wait(rx, what, |e| match e {
Event::Gateway { update, .. } if f(&update) => Some(update),
_ => None,
})
.await
}
fn observe(engine: &Engine, session: u64, gw: &FakeGateway) {
let identity = tsclientlib::Identity::create();
engine.send(Command::ObserveGateway {
session,
url: gw.url.clone(),
identity: Box::new(identity),
});
}
fn temp_db(tag: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("voelin-core-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
dir.join("client.db")
}
/// Opening a chat shows the stored page, then the gateway's; older pages
/// come from the gateway; what was said while we were away arrives on the
/// next connect; the database keeps it all.
#[tokio::test(flavor = "multi_thread")]
async fn history_on_open_paging_and_offline_messages() {
let gw = FakeGateway::start().await;
for i in 1..=5 {
gw.add(LOBBY, "alice", &format!("m{i}"), i * 1000);
}
gw.add(ChatTarget::Server, "alice", "elsewhere", 500);
let path = temp_db("history");
let settings = Settings::in_memory();
settings.set_json("chat.history_page", json!(3)).unwrap();
let engine = Engine::start_with(settings.clone(), History::open(&path).unwrap());
let mut rx = engine.subscribe();
engine.send(Command::OpenChat { session: 1, target: LOBBY });
observe(&engine, 1, &gw);
// Nothing stored yet; then the gateway's latest page; then in sync.
let (local, _, complete) = batch(&mut rx, HistorySource::Local).await;
assert!(local.is_empty() && !complete);
let (page, _, complete) = batch(&mut rx, HistorySource::Gateway).await;
assert_eq!(texts(&page), ["m3", "m4", "m5"]);
assert!(!complete, "older messages exist");
assert!(page.iter().all(|m| m.remote_id.is_some() && m.source == MessageSource::Gateway));
let (synced, _, _) = batch(&mut rx, HistorySource::Gateway).await;
assert!(synced.is_empty(), "nothing new: {synced:?}");
// Older: the gateway's page before m3.
engine.send(Command::LoadOlderHistory { session: 1, target: LOBBY, before: Some(page[0].id) });
let (older, _, complete) = batch(&mut rx, HistorySource::Gateway).await;
assert_eq!(texts(&older), ["m1", "m2"]);
assert!(complete, "the beginning");
// Away: two messages and a pin on m2.
engine.send(Command::StopObserving { session: 1 });
wait(&mut rx, "gateway stopped", |e| match e {
Event::State { state, .. } if state.observe == ObserveState::Off => Some(()),
_ => None,
})
.await;
gw.add(LOBBY, "bob", "while away 1", 6000);
gw.add(LOBBY, "bob", "while away 2", 7000);
{
let mut st = gw.state.lock().unwrap();
let rev = st.next_rev();
let m2 = st.messages.iter_mut().find(|e| e.message.text == "m2").unwrap();
m2.pinned = true;
m2.rev = rev;
}
// Back: stored page at once, then what we missed.
observe(&engine, 1, &gw);
let (local, _, _) = batch(&mut rx, HistorySource::Local).await;
assert_eq!(texts(&local), ["m3", "m4", "m5"]);
let mut missed = Vec::new();
while missed.len() < 3 {
missed.extend(batch(&mut rx, HistorySource::Gateway).await.0);
}
missed.sort_by_key(|m| (m.message.ts_ms, m.id));
assert_eq!(texts(&missed), ["m2", "while away 1", "while away 2"]);
assert!(missed[0].pinned);
assert_eq!(missed[0].id, older[1].id, "the stored row was updated");
// It is all in the database, oldest first.
engine.send(Command::CloseSession { session: 1 });
let history = engine.history();
let stored = history.page("fake-server", &LOBBY, Default::default(), false).await.unwrap();
assert_eq!(texts(&stored), ["m1", "m2", "m3", "m4", "m5", "while away 1", "while away 2"]);
history.flush();
drop((engine, history));
// After a restart, with the gateway down: the stored page, found by the
// gateway's URL, which is remembered with the server's id.
gw.state.lock().unwrap().refuse = true;
let engine = Engine::start_with(settings, History::open(&path).unwrap());
let mut rx = engine.subscribe();
engine.send(Command::OpenChat { session: 7, target: LOBBY });
observe(&engine, 7, &gw);
let (local, source) = wait(&mut rx, "history without the gateway", |e| match e {
Event::ChatHistory { session: 7, messages, source, .. } => Some((messages, source)),
_ => None,
})
.await;
assert_eq!(source, HistorySource::Local);
assert_eq!(texts(&local), ["m5", "while away 1", "while away 2"]);
drop(engine);
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
/// Live messages, our own included, are stored once; pins, reactions,
/// topics and other requests go through Command::Gateway.
#[tokio::test(flavor = "multi_thread")]
async fn live_messages_and_gateway_requests() {
let gw = FakeGateway::start().await;
let engine = Engine::start();
let mut rx = engine.subscribe();
engine.send(Command::OpenChat { session: 1, target: LOBBY });
observe(&engine, 1, &gw);
let connected =
update(&mut rx, "connected", |u| matches!(u, GatewayUpdate::Connected { .. })).await;
let GatewayUpdate::Connected { server_uid, uid, capabilities, .. } = connected else {
unreachable!()
};
assert_eq!((server_uid.as_str(), uid.as_str()), ("fake-server", ME));
assert!(capabilities.iter().any(|c| c == feature::PINS));
// In sync (the chat is empty).
batch(&mut rx, HistorySource::Gateway).await;
// Our message: stored at once, then merged with the gateway's copy.
engine.send(Command::SendChat { session: 1, target: LOBBY, text: "hello".into() });
let (sent, _, _) = batch(&mut rx, HistorySource::Live).await;
assert_eq!((sent[0].source, sent[0].remote_id), (MessageSource::Local, None));
let (merged, _, _) = batch(&mut rx, HistorySource::Live).await;
assert_eq!(merged[0].id, sent[0].id, "one message");
let remote = merged[0].remote_id.expect("the gateway's id");
// A message from someone else arrives live.
gw.add(LOBBY, "bob", "hi me", now_ms());
let (live, _, _) = batch(&mut rx, HistorySource::Live).await;
assert_eq!(texts(&live), ["hi me"]);
assert_ne!(live[0].id, sent[0].id);
// Pin: done, pushed, the row is pinned.
engine
.send(Command::Gateway { session: 1, request: GatewayRequest::Pin { message_id: remote } });
let (mut pinned_row, mut pinned_push, mut done) = (None, None, false);
wait(&mut rx, "pin", |e| {
match e {
Event::ChatHistory { messages, source: HistorySource::Live, .. }
if messages[0].pinned =>
{
pinned_row = Some(messages[0].clone());
}
Event::Gateway { update: GatewayUpdate::Pinned { pin, .. }, .. } => {
pinned_push = Some(pin)
}
Event::Gateway { update: GatewayUpdate::Done { request }, .. } if request == "pin" => {
done = true
}
_ => {}
}
(pinned_row.is_some() && pinned_push.is_some() && done).then_some(())
})
.await;
assert_eq!(pinned_row.unwrap().id, sent[0].id);
assert_eq!(pinned_push.unwrap().message.id, sent[0].id);
// React: the row carries the count and that it was us.
engine.send(Command::Gateway {
session: 1,
request: GatewayRequest::React { message_id: remote, emoji: "👍".into() },
});
let row = wait(&mut rx, "reaction", |e| match e {
Event::ChatHistory { messages, source: HistorySource::Live, .. }
if !messages[0].reactions.is_empty() =>
{
Some(messages[0].clone())
}
_ => None,
})
.await;
assert_eq!(row.reactions, [ReactionCount { emoji: "👍".into(), count: 1, me: true }]);
update(&mut rx, "reaction push", |u| {
matches!(u, GatewayUpdate::Reaction { added: true, count: 1, .. })
})
.await;
// A topic from the message, and a post into it.
engine.send(Command::Gateway {
session: 1,
request: GatewayRequest::CreateTopic {
target: LOBBY,
title: "Plans".into(),
message_id: Some(remote),
},
});
let GatewayUpdate::Topic { topic } =
update(&mut rx, "topic", |u| matches!(u, GatewayUpdate::Topic { .. })).await
else {
unreachable!()
};
assert_eq!((topic.title.as_str(), topic.root_message_id), ("Plans", Some(remote)));
engine.send(Command::Gateway {
session: 1,
request: GatewayRequest::Post {
target: LOBBY,
text: "in topic".into(),
topic: Some(topic.id),
},
});
let GatewayUpdate::Posted { message } =
update(&mut rx, "posted", |u| matches!(u, GatewayUpdate::Posted { .. })).await
else {
unreachable!()
};
assert_eq!((message.topic_id, message.message.text.as_str()), (Some(topic.id), "in topic"));
assert_ne!(message.id, 0, "stored (in memory: negative ids)");
// Pins list with local ids.
engine.send(Command::Gateway { session: 1, request: GatewayRequest::Pins { target: LOBBY } });
let GatewayUpdate::Pins { pins, .. } =
update(&mut rx, "pins", |u| matches!(u, GatewayUpdate::Pins { .. })).await
else {
unreachable!()
};
assert_eq!(pins.iter().map(|p| p.message.id).collect::<Vec<_>>(), [sent[0].id]);
// Refusals come as Failed, with the gateway's code.
engine.send(Command::Gateway { session: 1, request: GatewayRequest::ConfigList });
let failed = update(&mut rx, "failed", |u| matches!(u, GatewayUpdate::Failed { .. })).await;
assert!(
matches!(failed, GatewayUpdate::Failed { request, code: Some(ErrorCode::UnknownType), .. } if request == "config_list")
);
// Without a gateway, too.
engine.send(Command::Gateway { session: 2, request: GatewayRequest::Streams });
let failed = wait(&mut rx, "no gateway", |e| match e {
Event::Gateway { session: 2, update } => Some(update),
_ => None,
})
.await;
assert!(matches!(failed, GatewayUpdate::Failed { code: None, .. }));
// Everything is one row per message in the (in-memory) history.
let stored = engine.history().page("fake-server", &LOBBY, Default::default(), false).await;
assert_eq!(texts(&stored.unwrap()), ["hello", "hi me", "in topic"]);
// The engine enabled the extensions and subscribed to events.
let requests = gw.requests();
assert!(requests.contains(&"enable".to_owned()), "{requests:?}");
assert!(requests.contains(&"subscribe_events".to_owned()), "{requests:?}");
// Requests serialize for tools.
assert_eq!(
serde_json::to_value(GatewayRequest::Pin { message_id: 7 }).unwrap(),
json!({"pin": {"message_id": 7}})
);
let parsed: GatewayRequest =
serde_json::from_value(json!({"topics": {"target": {"kind": "channel", "id": 1}}}))
.unwrap();
assert_eq!(parsed, GatewayRequest::Topics { target: LOBBY, include_archived: false });
}
/// With `chat.store_history` off nothing reaches the database; messages
/// are kept in memory with negative ids.
#[tokio::test(flavor = "multi_thread")]
async fn store_history_off_keeps_the_database_empty() {
let gw = FakeGateway::start().await;
gw.add(LOBBY, "alice", "secret", 1000);
let path = temp_db("nostore");
let settings = Settings::in_memory();
settings.set_json("chat.store_history", json!(false)).unwrap();
let engine = Engine::start_with(settings, History::open(&path).unwrap());
let mut rx = engine.subscribe();
engine.send(Command::OpenChat { session: 1, target: LOBBY });
observe(&engine, 1, &gw);
let (page, _, _) = batch(&mut rx, HistorySource::Gateway).await;
assert_eq!(texts(&page), ["secret"]);
assert!(page[0].id < 0, "{}", page[0].id);
let history = engine.history();
assert!(
history.page("fake-server", &LOBBY, Default::default(), false).await.unwrap().is_empty()
);
assert_eq!(
history.page("fake-server", &LOBBY, Default::default(), true).await.unwrap().len(),
1
);
drop((engine, history));
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
+987
View File
@@ -0,0 +1,987 @@
//! Chat history: the messages this device saw or fetched from a gateway,
//! per server and chat.
//!
//! Every message is one row, whatever delivered it: the voice connection,
//! a gateway (with its stable message id, [`StoredMessage::remote_id`]), a
//! query relay, or this device when it sent the message. The same message
//! often arrives twice (live over voice and again from the gateway);
//! [`Store::write_messages`] merges such copies (see [`WriteOutcome`]):
//!
//! - a gateway copy matches the row with its gateway id, else a row without
//! one of the same message;
//! - otherwise two copies are the same message when they come from different
//! sources, their text is equal once a relay prefix (`[nick] `) is removed,
//! they were stamped at most `tolerance_ms` apart, and they have the same
//! author: the same unique id, or the relay prefix of one names the author
//! of the other, or (without both unique ids) the same nickname.
//!
//! Pages are by time: `(ts_ms, id)` orders a chat ([`PageQuery`]). A
//! [`ChatCursor`] remembers how far a chat is synced with a gateway.
use rusqlite::{OptionalExtension, Row, Transaction, params};
use serde::{Deserialize, Serialize};
use crate::{Result, Store};
/// Where a chat message was posted.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ChatTarget {
Server,
Channel(u64),
/// Private chat with the client of this unique id.
Private(String),
}
impl ChatTarget {
/// The form stored in the database: `server`, `channel/<cid>`, `private/<uid>`.
pub fn key(&self) -> String {
match self {
ChatTarget::Server => "server".into(),
ChatTarget::Channel(cid) => format!("channel/{cid}"),
ChatTarget::Private(uid) => format!("private/{uid}"),
}
}
/// Parse [`Self::key`]; unknown forms are the server chat.
pub fn from_key(key: &str) -> Self {
match key.split_once('/') {
Some(("channel", cid)) => {
cid.parse().map(ChatTarget::Channel).unwrap_or(ChatTarget::Server)
}
Some(("private", uid)) => ChatTarget::Private(uid.to_owned()),
_ => ChatTarget::Server,
}
}
}
/// What delivered a message first.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MessageSource {
/// Our own voice connection.
Voice,
/// A `tsgw` gateway (live or from its history).
Gateway,
/// A query relay with the user's own credentials.
Query,
/// This device: sent by the user, or stored before sources were recorded.
#[default]
Local,
}
impl MessageSource {
pub fn as_str(self) -> &'static str {
match self {
MessageSource::Voice => "voice",
MessageSource::Gateway => "gateway",
MessageSource::Query => "query",
MessageSource::Local => "local",
}
}
pub fn parse(s: &str) -> Self {
match s {
"voice" => MessageSource::Voice,
"gateway" => MessageSource::Gateway,
"query" => MessageSource::Query,
_ => MessageSource::Local,
}
}
/// Bit in the `seen_by` column.
fn bit(self) -> i64 {
match self {
MessageSource::Voice => 1,
MessageSource::Gateway => 2,
MessageSource::Query => 4,
MessageSource::Local => 8,
}
}
}
/// Whether a row is known to the gateway.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SyncState {
/// Only seen by this device (no gateway copy yet).
#[default]
Local,
/// The gateway has it: [`StoredMessage::remote_id`] is set.
Synced,
}
fn is_false(b: &bool) -> bool {
!*b
}
/// One emoji on a message, as the gateway counts it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Reaction {
pub emoji: String,
pub count: u32,
/// The user reacted with this emoji.
#[serde(default, skip_serializing_if = "is_false")]
pub me: bool,
}
/// What a gateway says about a message.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RemoteInfo {
/// The gateway's message id.
pub id: i64,
/// Revision of the last change at the gateway.
pub rev: i64,
pub topic_id: Option<i64>,
pub reactions: Vec<Reaction>,
pub pinned: bool,
}
/// A message to store.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NewMessage {
pub server_uid: String,
pub target: ChatTarget,
/// Unix milliseconds.
pub ts_ms: i64,
pub author_uid: Option<String>,
pub author_name: String,
/// The author's client id on the server, if known.
pub author_id: Option<u16>,
/// Carried by a relay rather than our own connection.
pub via_relay: bool,
pub text: String,
pub source: MessageSource,
/// Set for messages from a gateway.
pub remote: Option<RemoteInfo>,
}
/// A stored message.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StoredMessage {
/// Assigned by the store; stable on this device.
pub id: i64,
pub server_uid: String,
pub target: ChatTarget,
/// Unix milliseconds.
pub ts_ms: i64,
pub author_uid: Option<String>,
pub author_name: String,
pub author_id: Option<u16>,
pub via_relay: bool,
pub text: String,
/// What delivered it first.
pub source: MessageSource,
/// The gateway's message id, once a gateway copy was stored.
pub remote_id: Option<i64>,
pub topic_id: Option<i64>,
/// Gateway revision of the last change (0 without a gateway copy).
pub rev: i64,
pub reactions: Vec<Reaction>,
pub pinned: bool,
pub sync_state: SyncState,
}
/// What [`Store::write_messages`] did with one message.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum WriteOutcome {
/// Stored as a new row.
Inserted,
/// Another copy of a stored message (see the [module docs](self)); the
/// row gained what this copy adds, e.g. the gateway id.
Merged,
/// A gateway message stored before, with changes (pin, reactions, topic).
Updated,
/// Nothing new.
Unchanged,
}
/// A stored message and what the write did.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Written {
pub message: StoredMessage,
pub outcome: WriteOutcome,
}
/// A window of a chat, by `(ts_ms, id)`. Pages are always oldest first.
///
/// Without `after`: the newest `limit` messages before `before` (the newest
/// of the chat without it). With `after`: the oldest `limit` messages after
/// it, up to `before` if given. `limit: None` is everything in range.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PageQuery {
pub before: Option<(i64, i64)>,
pub after: Option<(i64, i64)>,
pub limit: Option<usize>,
}
/// How far a chat is synced with a gateway.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ChatCursor {
/// The gateway the revision belongs to; another gateway starts over.
pub gateway_id: String,
/// The last gateway revision stored (`sync since_rev`).
pub rev: i64,
/// The gateway has nothing older than the oldest message stored from it.
pub complete: bool,
/// Unix milliseconds of the last sync.
pub updated_ms: i64,
}
/// Version 2: times in milliseconds, sources, gateway ids and metadata,
/// dedupe keys, sync cursors and server aliases. Old messages keep their
/// data (source `local`, their second times in milliseconds).
pub(crate) fn migrate_2(tx: &Transaction) -> rusqlite::Result<()> {
tx.execute_batch(
"ALTER TABLE messages ADD COLUMN ts_ms INTEGER NOT NULL DEFAULT 0;
UPDATE messages SET ts_ms = ts * 1000;
ALTER TABLE messages ADD COLUMN author_id INTEGER;
ALTER TABLE messages ADD COLUMN source TEXT NOT NULL DEFAULT 'local';
ALTER TABLE messages ADD COLUMN remote_id INTEGER;
ALTER TABLE messages ADD COLUMN topic_id INTEGER;
ALTER TABLE messages ADD COLUMN rev INTEGER NOT NULL DEFAULT 0;
ALTER TABLE messages ADD COLUMN sync_state INTEGER NOT NULL DEFAULT 0;
ALTER TABLE messages ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0;
ALTER TABLE messages ADD COLUMN reactions TEXT;
-- Sources that delivered the row (MessageSource bits), for dedupe.
ALTER TABLE messages ADD COLUMN seen_by INTEGER NOT NULL DEFAULT 8;
-- FNV-1a of the text without a relay prefix, for dedupe.
ALTER TABLE messages ADD COLUMN text_hash INTEGER NOT NULL DEFAULT 0;
DROP INDEX messages_by_target;
CREATE INDEX messages_by_time ON messages (server_uid, target, ts_ms, id);
CREATE UNIQUE INDEX messages_by_remote ON messages (server_uid, target, remote_id)
WHERE remote_id IS NOT NULL;
CREATE TABLE chat_cursors (
server_uid TEXT NOT NULL,
target TEXT NOT NULL,
gateway_id TEXT NOT NULL,
rev INTEGER NOT NULL DEFAULT 0,
complete INTEGER NOT NULL DEFAULT 0,
updated_ms INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (server_uid, target)
) WITHOUT ROWID;
CREATE TABLE server_aliases (
alias TEXT PRIMARY KEY,
server_uid TEXT NOT NULL,
updated_ms INTEGER NOT NULL DEFAULT 0
) WITHOUT ROWID;",
)?;
let rows: Vec<(i64, String)> = tx
.prepare("SELECT id, text FROM messages")?
.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?
.collect::<rusqlite::Result<_>>()?;
let mut update = tx.prepare("UPDATE messages SET text_hash = ?2 WHERE id = ?1")?;
for (id, text) in rows {
update.execute(params![id, text_hash(&text)])?;
}
Ok(())
}
/// A relay posts as `[nick] text`: the nick and the text.
fn split_relay(text: &str) -> (Option<&str>, &str) {
if let Some(rest) = text.strip_prefix('[')
&& let Some((nick, after)) = rest.split_once("] ")
&& !nick.is_empty()
{
return (Some(nick), after);
}
(None, text)
}
/// FNV-1a (64 bit) of the text without a relay prefix.
fn text_hash(text: &str) -> i64 {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in split_relay(text).1.bytes() {
hash ^= u64::from(byte);
hash = hash.wrapping_mul(0x0100_0000_01b3);
}
hash as i64
}
/// Whether a stored row and a new copy are the same message (the hash and
/// time already matched).
fn same_message(new: &NewMessage, old: &StoredMessage) -> bool {
let (new_prefix, new_text) = split_relay(&new.text);
let (old_prefix, old_text) = split_relay(&old.text);
if new_text != old_text {
return false;
}
if let (Some(a), Some(b)) = (&new.author_uid, &old.author_uid)
&& a == b
{
return true;
}
if new_prefix.is_some_and(|n| n == old.author_name)
|| old_prefix.is_some_and(|n| n == new.author_name)
{
return true;
}
(new.author_uid.is_none() || old.author_uid.is_none()) && new.author_name == old.author_name
}
const COLUMNS: &str = "id, server_uid, target, ts_ms, author_uid, author_name, author_id, \
via_relay, text, source, remote_id, topic_id, rev, reactions, pinned, sync_state";
fn reactions_json(reactions: &[Reaction]) -> Option<String> {
(!reactions.is_empty()).then(|| serde_json::to_string(reactions).unwrap_or_default())
}
fn message_from_row(r: &Row) -> rusqlite::Result<StoredMessage> {
let target: String = r.get(2)?;
let source: String = r.get(9)?;
let reactions: Option<String> = r.get(13)?;
Ok(StoredMessage {
id: r.get(0)?,
server_uid: r.get(1)?,
target: ChatTarget::from_key(&target),
ts_ms: r.get(3)?,
author_uid: r.get(4)?,
author_name: r.get(5)?,
author_id: r.get(6)?,
via_relay: r.get(7)?,
text: r.get(8)?,
source: MessageSource::parse(&source),
remote_id: r.get(10)?,
topic_id: r.get(11)?,
rev: r.get(12)?,
reactions: reactions.and_then(|j| serde_json::from_str(&j).ok()).unwrap_or_default(),
pinned: r.get(14)?,
sync_state: if r.get::<_, i64>(15)? == 1 { SyncState::Synced } else { SyncState::Local },
})
}
fn now_ms() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or_default()
}
/// Upsert one message inside `tx`.
fn write_one(tx: &Transaction, m: &NewMessage, tolerance_ms: i64) -> rusqlite::Result<Written> {
let target = m.target.key();
let by_id = |id: i64| -> rusqlite::Result<StoredMessage> {
tx.prepare_cached(&format!("SELECT {COLUMNS} FROM messages WHERE id = ?1"))?
.query_row([id], message_from_row)
};
if let Some(remote) = &m.remote {
// The same gateway message again.
let existing = tx
.prepare_cached(&format!(
"SELECT {COLUMNS} FROM messages
WHERE server_uid = ?1 AND target = ?2 AND remote_id = ?3"
))?
.query_row(params![m.server_uid, target, remote.id], message_from_row)
.optional()?;
if let Some(old) = existing {
let changed = old.rev != remote.rev
|| old.topic_id != remote.topic_id
|| old.pinned != remote.pinned
|| old.reactions != remote.reactions;
if !changed {
return Ok(Written { message: old, outcome: WriteOutcome::Unchanged });
}
tx.prepare_cached(
"UPDATE messages SET rev = ?2, topic_id = ?3, pinned = ?4, reactions = ?5 WHERE id = ?1",
)?
.execute(params![
old.id,
remote.rev,
remote.topic_id,
remote.pinned,
reactions_json(&remote.reactions)
])?;
return Ok(Written { message: by_id(old.id)?, outcome: WriteOutcome::Updated });
}
}
// Another copy of a message stored from a different source.
let hash = text_hash(&m.text);
let duplicate = {
let mut stmt = tx.prepare_cached(&format!(
"SELECT {COLUMNS} FROM messages
WHERE server_uid = ?1 AND target = ?2 AND ts_ms BETWEEN ?3 AND ?4
AND text_hash = ?5 AND (seen_by & ?6) = 0 AND (?7 = 0 OR remote_id IS NULL)
ORDER BY ABS(ts_ms - ?8), id"
))?;
let rows = stmt.query_map(
params![
m.server_uid,
target,
m.ts_ms.saturating_sub(tolerance_ms),
m.ts_ms.saturating_add(tolerance_ms),
hash,
m.source.bit(),
m.remote.is_some(),
m.ts_ms
],
message_from_row,
)?;
let mut found = None;
for row in rows {
let row = row?;
if same_message(m, &row) {
found = Some(row);
break;
}
}
found
};
if let Some(old) = duplicate {
let remote = m.remote.clone().unwrap_or_default();
tx.prepare_cached(
"UPDATE messages SET seen_by = seen_by | ?2,
author_uid = COALESCE(author_uid, ?3), author_id = COALESCE(author_id, ?4),
remote_id = COALESCE(?5, remote_id), rev = MAX(rev, ?6),
topic_id = COALESCE(?7, topic_id), pinned = CASE WHEN ?5 IS NULL THEN pinned ELSE ?8 END,
reactions = CASE WHEN ?5 IS NULL THEN reactions ELSE ?9 END,
sync_state = CASE WHEN ?5 IS NULL THEN sync_state ELSE 1 END
WHERE id = ?1",
)?
.execute(params![
old.id,
m.source.bit(),
m.author_uid,
m.author_id,
m.remote.as_ref().map(|r| r.id),
remote.rev,
remote.topic_id,
remote.pinned,
reactions_json(&remote.reactions)
])?;
let message = by_id(old.id)?;
let outcome = if message == old { WriteOutcome::Unchanged } else { WriteOutcome::Merged };
return Ok(Written { message, outcome });
}
let remote = m.remote.clone().unwrap_or_default();
tx.prepare_cached(
"INSERT INTO messages (server_uid, target, ts, ts_ms, author_uid, author_name, author_id,
via_relay, text, source, remote_id, topic_id, rev, reactions, pinned, sync_state,
seen_by, text_hash)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18)",
)?
.execute(params![
m.server_uid,
target,
m.ts_ms.div_euclid(1000),
m.ts_ms,
m.author_uid,
m.author_name,
m.author_id,
m.via_relay,
m.text,
m.source.as_str(),
m.remote.as_ref().map(|r| r.id),
remote.topic_id,
remote.rev,
reactions_json(&remote.reactions),
remote.pinned,
i64::from(m.remote.is_some()),
m.source.bit(),
hash
])?;
let id = tx.last_insert_rowid();
Ok(Written { message: by_id(id)?, outcome: WriteOutcome::Inserted })
}
impl Store {
/// Store messages in one transaction, merging copies of the same
/// message (see the [module docs](self)); results in input order.
pub fn write_messages(
&mut self,
messages: &[NewMessage],
tolerance_ms: i64,
) -> Result<Vec<Written>> {
let tx = self.db.transaction()?;
let mut out = Vec::with_capacity(messages.len());
for m in messages {
out.push(write_one(&tx, m, tolerance_ms.max(0))?);
}
tx.commit()?;
Ok(out)
}
/// A page of a chat, oldest first (see [`PageQuery`]).
pub fn messages(
&self,
server_uid: &str,
target: &ChatTarget,
query: PageQuery,
) -> Result<Vec<StoredMessage>> {
let (before_ts, before_id) = query.before.unwrap_or((i64::MAX, i64::MAX));
let (after_ts, after_id) = query.after.unwrap_or((i64::MIN, i64::MIN));
let ascending = query.after.is_some();
let sql = format!(
"SELECT {COLUMNS} FROM messages
WHERE server_uid = ?1 AND target = ?2 AND (ts_ms, id) < (?3, ?4) AND (ts_ms, id) > (?5, ?6)
ORDER BY ts_ms {order}, id {order} LIMIT ?7",
order = if ascending { "ASC" } else { "DESC" }
);
let limit = query.limit.map_or(-1, |l| l as i64);
let mut rows = self
.db
.prepare_cached(&sql)?
.query_map(
params![server_uid, target.key(), before_ts, before_id, after_ts, after_id, limit],
message_from_row,
)?
.collect::<rusqlite::Result<Vec<_>>>()?;
if !ascending {
rows.reverse();
}
Ok(rows)
}
/// One message by its local id.
pub fn message(&self, id: i64) -> Result<Option<StoredMessage>> {
Ok(self
.db
.prepare_cached(&format!("SELECT {COLUMNS} FROM messages WHERE id = ?1"))?
.query_row([id], message_from_row)
.optional()?)
}
/// One message by its gateway id.
pub fn message_by_remote(
&self,
server_uid: &str,
target: &ChatTarget,
remote_id: i64,
) -> Result<Option<StoredMessage>> {
Ok(self
.db
.prepare_cached(&format!(
"SELECT {COLUMNS} FROM messages
WHERE server_uid = ?1 AND target = ?2 AND remote_id = ?3"
))?
.query_row(params![server_uid, target.key(), remote_id], message_from_row)
.optional()?)
}
/// The oldest time of a message stored from the gateway, if any.
pub fn oldest_remote_ts(&self, server_uid: &str, target: &ChatTarget) -> Result<Option<i64>> {
Ok(self
.db
.prepare_cached(
"SELECT MIN(ts_ms) FROM messages
WHERE server_uid = ?1 AND target = ?2 AND remote_id IS NOT NULL",
)?
.query_row(params![server_uid, target.key()], |r| r.get(0))?)
}
/// Mark a gateway message (un)pinned; the updated row, `None` if it is
/// not stored.
pub fn set_pinned(
&mut self,
server_uid: &str,
target: &ChatTarget,
remote_id: i64,
pinned: bool,
) -> Result<Option<StoredMessage>> {
self.db
.prepare_cached(
"UPDATE messages SET pinned = ?4
WHERE server_uid = ?1 AND target = ?2 AND remote_id = ?3",
)?
.execute(params![server_uid, target.key(), remote_id, pinned])?;
self.message_by_remote(server_uid, target, remote_id)
}
/// Set the count of one emoji on a gateway message (0 removes it) and,
/// if given, whether the user reacted with it. The updated row, `None`
/// if the message is not stored.
pub fn set_reaction(
&mut self,
server_uid: &str,
target: &ChatTarget,
remote_id: i64,
emoji: &str,
count: u32,
me: Option<bool>,
) -> Result<Option<StoredMessage>> {
let tx = self.db.transaction()?;
let current: Option<(i64, Option<String>)> = tx
.prepare_cached(
"SELECT id, reactions FROM messages
WHERE server_uid = ?1 AND target = ?2 AND remote_id = ?3",
)?
.query_row(params![server_uid, target.key(), remote_id], |r| Ok((r.get(0)?, r.get(1)?)))
.optional()?;
let Some((id, json)) = current else { return Ok(None) };
let mut reactions: Vec<Reaction> =
json.and_then(|j| serde_json::from_str(&j).ok()).unwrap_or_default();
match reactions.iter().position(|r| r.emoji == emoji) {
_ if count == 0 => reactions.retain(|r| r.emoji != emoji),
Some(i) => {
reactions[i].count = count;
if let Some(me) = me {
reactions[i].me = me;
}
}
None => {
reactions.push(Reaction { emoji: emoji.to_owned(), count, me: me.unwrap_or(false) })
}
}
tx.prepare_cached("UPDATE messages SET reactions = ?2 WHERE id = ?1")?
.execute(params![id, reactions_json(&reactions)])?;
tx.commit()?;
self.message(id)
}
/// How far a chat is synced with a gateway.
pub fn chat_cursor(&self, server_uid: &str, target: &ChatTarget) -> Result<Option<ChatCursor>> {
Ok(self
.db
.prepare_cached(
"SELECT gateway_id, rev, complete, updated_ms FROM chat_cursors
WHERE server_uid = ?1 AND target = ?2",
)?
.query_row(params![server_uid, target.key()], |r| {
Ok(ChatCursor {
gateway_id: r.get(0)?,
rev: r.get(1)?,
complete: r.get(2)?,
updated_ms: r.get(3)?,
})
})
.optional()?)
}
pub fn set_chat_cursor(
&self,
server_uid: &str,
target: &ChatTarget,
cursor: &ChatCursor,
) -> Result<()> {
self.db
.prepare_cached(
"INSERT INTO chat_cursors (server_uid, target, gateway_id, rev, complete, updated_ms)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)
ON CONFLICT (server_uid, target) DO UPDATE SET gateway_id = excluded.gateway_id,
rev = excluded.rev, complete = excluded.complete, updated_ms = excluded.updated_ms",
)?
.execute(params![
server_uid,
target.key(),
cursor.gateway_id,
cursor.rev,
cursor.complete,
cursor.updated_ms
])?;
Ok(())
}
/// Forget the gateway ids of a chat (another gateway numbers its
/// messages differently) and its cursor; the rows stay, as seen by this
/// device, and are matched again with the new gateway's copies.
pub fn forget_remote_ids(&mut self, server_uid: &str, target: &ChatTarget) -> Result<usize> {
let tx = self.db.transaction()?;
let n = tx
.prepare_cached(
"UPDATE messages SET remote_id = NULL, rev = 0, sync_state = 0,
seen_by = CASE WHEN seen_by = 2 THEN 8 ELSE seen_by & ~2 END
WHERE server_uid = ?1 AND target = ?2 AND remote_id IS NOT NULL",
)?
.execute(params![server_uid, target.key()])?;
tx.prepare_cached("DELETE FROM chat_cursors WHERE server_uid = ?1 AND target = ?2")?
.execute(params![server_uid, target.key()])?;
tx.commit()?;
Ok(n)
}
/// The server unique id last seen under another name of the server
/// (e.g. `voice:<address>`, `gateway:<url>`).
pub fn server_alias(&self, alias: &str) -> Result<Option<String>> {
Ok(self
.db
.prepare_cached("SELECT server_uid FROM server_aliases WHERE alias = ?1")?
.query_row([alias], |r| r.get(0))
.optional()?)
}
pub fn set_server_alias(&self, alias: &str, server_uid: &str) -> Result<()> {
self.db
.prepare_cached(
"INSERT INTO server_aliases (alias, server_uid, updated_ms) VALUES (?1, ?2, ?3)
ON CONFLICT (alias) DO UPDATE SET server_uid = excluded.server_uid,
updated_ms = excluded.updated_ms",
)?
.execute(params![alias, server_uid, now_ms()])?;
Ok(())
}
/// Delete messages sent before `before_ms` (Unix milliseconds); pinned
/// ones stay.
pub fn prune_messages(&self, before_ms: i64) -> Result<usize> {
Ok(self
.db
.prepare_cached(
"DELETE FROM messages WHERE ts_ms < ?1 AND pinned = 0 AND server_uid <> ''",
)?
.execute([before_ms])?)
}
/// Give new messages ids from `first` on (e.g. negative ones, for a
/// database whose ids must not be confused with another's). SQLite
/// numbers a new row one above the largest id, so this keeps a hidden
/// row (no server) just below `first`. For an empty chat table.
pub fn start_message_ids_at(&self, first: i64) -> Result<()> {
self.db.execute(
"INSERT INTO messages (id, server_uid, target, ts, author_name, text)
VALUES (?1, '', '', 0, '', '')",
[first.saturating_sub(1)],
)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
const SRV: &str = "srv";
fn msg(source: MessageSource, author: &str, text: &str, ts_ms: i64) -> NewMessage {
NewMessage {
server_uid: SRV.into(),
target: ChatTarget::Channel(1),
ts_ms,
author_uid: Some(format!("uid-{author}")),
author_name: author.into(),
author_id: None,
via_relay: source != MessageSource::Voice,
text: text.into(),
source,
remote: None,
}
}
fn remote(mut m: NewMessage, id: i64, rev: i64) -> NewMessage {
m.source = MessageSource::Gateway;
m.remote = Some(RemoteInfo { id, rev, ..Default::default() });
m
}
fn outcomes(written: &[Written]) -> Vec<WriteOutcome> {
written.iter().map(|w| w.outcome).collect()
}
fn texts(rows: &[StoredMessage]) -> Vec<&str> {
rows.iter().map(|m| m.text.as_str()).collect()
}
#[test]
fn batch_insert_and_pages() {
let mut store = Store::open_in_memory().unwrap();
let target = ChatTarget::Channel(1);
let batch: Vec<_> = (0..10)
.map(|i| msg(MessageSource::Voice, "a", &format!("m{i}"), 1000 + i * 10))
.collect();
let written = store.write_messages(&batch, 5000).unwrap();
assert!(written.iter().all(|w| w.outcome == WriteOutcome::Inserted));
// Same time, higher id: after.
store.write_messages(&[msg(MessageSource::Voice, "a", "m9b", 1090)], 0).unwrap();
let page = |q| store.messages(SRV, &target, q).unwrap();
let newest = page(PageQuery { limit: Some(3), ..Default::default() });
assert_eq!(texts(&newest), ["m8", "m9", "m9b"]);
let pos = |m: &StoredMessage| (m.ts_ms, m.id);
let older =
page(PageQuery { before: Some(pos(&newest[0])), limit: Some(3), ..Default::default() });
assert_eq!(texts(&older), ["m5", "m6", "m7"]);
let after =
page(PageQuery { after: Some(pos(&older[0])), limit: Some(2), ..Default::default() });
assert_eq!(texts(&after), ["m6", "m7"]);
let range = page(PageQuery {
after: Some(pos(&older[0])),
before: Some(pos(&newest[0])),
limit: None,
});
assert_eq!(texts(&range), ["m6", "m7"]);
assert_eq!(page(PageQuery::default()).len(), 11, "no limit");
assert!(store.messages(SRV, &ChatTarget::Server, PageQuery::default()).unwrap().is_empty());
assert!(store.messages("other", &target, PageQuery::default()).unwrap().is_empty());
assert_eq!(store.prune_messages(1050).unwrap(), 5);
}
#[test]
fn copies_from_two_sources_are_one_row() {
let mut store = Store::open_in_memory().unwrap();
// Live over voice, then from the gateway 1.2 s later (clock skew).
let live =
store.write_messages(&[msg(MessageSource::Voice, "a", "hi", 10_000)], 5000).unwrap();
let gw = store
.write_messages(&[remote(msg(MessageSource::Gateway, "a", "hi", 11_200), 77, 5)], 5000)
.unwrap();
assert_eq!(outcomes(&gw), [WriteOutcome::Merged]);
let row = &gw[0].message;
assert_eq!((row.id, row.remote_id, row.rev), (live[0].message.id, Some(77), 5));
assert_eq!((row.source, row.sync_state), (MessageSource::Voice, SyncState::Synced));
// The gateway copy again: unchanged; with a pin: updated.
let again = store
.write_messages(&[remote(msg(MessageSource::Gateway, "a", "hi", 11_200), 77, 5)], 5000);
assert_eq!(outcomes(&again.unwrap()), [WriteOutcome::Unchanged]);
let mut pinned = remote(msg(MessageSource::Gateway, "a", "hi", 11_200), 77, 6);
pinned.remote.as_mut().unwrap().pinned = true;
let updated = store.write_messages(&[pinned], 5000).unwrap();
assert_eq!(outcomes(&updated), [WriteOutcome::Updated]);
assert!(updated[0].message.pinned);
// A second live copy from the same source is a new message (the
// author said it twice)...
let twice =
store.write_messages(&[msg(MessageSource::Voice, "a", "hi", 10_500)], 5000).unwrap();
assert_eq!(outcomes(&twice), [WriteOutcome::Inserted]);
// ...and the query relay's copy of it matches it, not the first one.
let relayed = store.write_messages(&[msg(MessageSource::Query, "a", "hi", 10_400)], 5000);
let relayed = relayed.unwrap();
assert_eq!(relayed[0].message.id, twice[0].message.id);
assert_eq!(relayed[0].outcome, WriteOutcome::Unchanged, "nothing visible changed");
// Too far apart in time, another author or another text: not the same.
for other in [
msg(MessageSource::Query, "a", "hi", 30_000),
msg(MessageSource::Query, "b", "hi", 10_000),
msg(MessageSource::Query, "a", "hi!", 10_000),
] {
assert_eq!(
outcomes(&store.write_messages(&[other], 5000).unwrap()),
[WriteOutcome::Inserted]
);
}
}
#[test]
fn relay_posts_match_the_gateway_copy() {
let mut store = Store::open_in_memory().unwrap();
// We sent "hey" through the gateway: stored at once as our own...
let mut own = msg(MessageSource::Local, "me", "hey", 5_000);
own.via_relay = false;
let own = store.write_messages(&[own], 5000).unwrap();
// ...the voice connection hears the relay post it as "[me] hey"...
let mut heard = msg(MessageSource::Voice, "tsgw relay", "[me] hey", 5_300);
heard.author_uid = Some("uid-relay".into());
let heard = store.write_messages(&[heard], 5000).unwrap();
assert_eq!(
(heard[0].message.id, heard[0].outcome),
(own[0].message.id, WriteOutcome::Unchanged)
);
// ...and the gateway pushes its copy with our uid.
let gw = store
.write_messages(&[remote(msg(MessageSource::Gateway, "me", "hey", 5_100), 9, 1)], 5000)
.unwrap();
assert_eq!((gw[0].message.id, gw[0].outcome), (own[0].message.id, WriteOutcome::Merged));
assert_eq!(gw[0].message.text, "hey");
// Without uids the nickname decides.
let mut a = msg(MessageSource::Voice, "x", "yo", 1);
a.author_uid = None;
let a = store.write_messages(&[a], 5000).unwrap();
let b =
store.write_messages(&[remote(msg(MessageSource::Gateway, "x", "yo", 2), 10, 2)], 5000);
assert_eq!(b.unwrap()[0].message.id, a[0].message.id);
}
#[test]
fn pins_reactions_and_cursors() {
let mut store = Store::open_in_memory().unwrap();
let target = ChatTarget::Channel(1);
store.write_messages(&[remote(msg(MessageSource::Gateway, "a", "x", 1), 5, 1)], 0).unwrap();
assert!(store.set_pinned(SRV, &target, 5, true).unwrap().unwrap().pinned);
assert!(store.set_pinned(SRV, &target, 6, true).unwrap().is_none());
let r = store.set_reaction(SRV, &target, 5, "👍", 2, Some(true)).unwrap().unwrap();
assert_eq!(r.reactions, [Reaction { emoji: "👍".into(), count: 2, me: true }]);
let r = store.set_reaction(SRV, &target, 5, "👍", 1, Some(false)).unwrap().unwrap();
assert_eq!(r.reactions, [Reaction { emoji: "👍".into(), count: 1, me: false }]);
assert!(
store
.set_reaction(SRV, &target, 5, "👍", 0, None)
.unwrap()
.unwrap()
.reactions
.is_empty()
);
// Pinned messages survive pruning.
assert_eq!(store.prune_messages(i64::MAX).unwrap(), 0);
assert_eq!(store.chat_cursor(SRV, &target).unwrap(), None);
let cursor = ChatCursor { gateway_id: "gw".into(), rev: 42, complete: true, updated_ms: 7 };
store.set_chat_cursor(SRV, &target, &cursor).unwrap();
assert_eq!(store.chat_cursor(SRV, &target).unwrap(), Some(cursor));
assert_eq!(store.oldest_remote_ts(SRV, &target).unwrap(), Some(1));
// Another gateway: ids and cursor are forgotten, the row stays.
assert_eq!(store.forget_remote_ids(SRV, &target).unwrap(), 1);
assert_eq!(store.chat_cursor(SRV, &target).unwrap(), None);
let row = &store.messages(SRV, &target, PageQuery::default()).unwrap()[0];
assert_eq!((row.remote_id, row.sync_state), (None, SyncState::Local));
// The new gateway's copy links to it again.
let again =
store.write_messages(&[remote(msg(MessageSource::Gateway, "a", "x", 1), 900, 1)], 0);
assert_eq!(again.unwrap()[0].message.id, row.id);
assert_eq!(store.server_alias("voice:host").unwrap(), None);
store.set_server_alias("voice:host", "uid1").unwrap();
store.set_server_alias("voice:host", "uid2").unwrap();
assert_eq!(store.server_alias("voice:host").unwrap().as_deref(), Some("uid2"));
}
/// A database of version 1 with messages is upgraded in place.
#[test]
fn migrates_version_1_with_data() {
let dir = std::env::temp_dir().join(format!("voelin-store-migrate-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("client.db");
{
let db = rusqlite::Connection::open(&path).unwrap();
db.execute_batch(crate::store::SCHEMA_1).unwrap();
db.pragma_update(None, "user_version", 1).unwrap();
db.execute_batch(
"INSERT INTO settings (key, value) VALUES ('k', '\"v\"');
INSERT INTO messages (server_uid, target, ts, author_uid, author_name, via_relay, text)
VALUES ('srv', 'channel/1', 100, 'uid-a', 'a', 0, 'old one'),
('srv', 'channel/1', 200, NULL, 'b', 1, '[c] old two');",
)
.unwrap();
}
let mut store = Store::open(&path).unwrap();
assert_eq!(store.schema_version().unwrap(), Store::SCHEMA_VERSION);
assert_eq!(store.setting::<String>("k").unwrap().as_deref(), Some("v"));
let rows = store.messages(SRV, &ChatTarget::Channel(1), PageQuery::default()).unwrap();
assert_eq!(texts(&rows), ["old one", "[c] old two"]);
assert_eq!((rows[0].ts_ms, rows[0].source), (100_000, MessageSource::Local));
assert!(rows[1].via_relay);
// The old rows take part in dedupe: the gateway copy of the relay post.
let mut gw = remote(msg(MessageSource::Gateway, "c", "old two", 201_000), 3, 3);
gw.author_uid = Some("uid-c".into());
let gw = store.write_messages(&[gw], 5000).unwrap();
assert_eq!((gw[0].message.id, gw[0].outcome), (rows[1].id, WriteOutcome::Merged));
drop(store);
// Opening again runs nothing.
let store = Store::open(&path).unwrap();
assert_eq!(
store.messages(SRV, &ChatTarget::Channel(1), PageQuery::default()).unwrap().len(),
2
);
drop(store);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn ids_can_start_elsewhere() {
let mut store = Store::open_in_memory().unwrap();
store.start_message_ids_at(-1000).unwrap();
let w = store.write_messages(&[msg(MessageSource::Voice, "a", "x", 1)], 0).unwrap();
assert_eq!(w[0].message.id, -1000);
let w = store.write_messages(&[msg(MessageSource::Voice, "a", "y", 2)], 0).unwrap();
assert_eq!(w[0].message.id, -999);
assert_eq!(store.prune_messages(i64::MAX).unwrap(), 2, "the hidden row stays");
let w = store.write_messages(&[msg(MessageSource::Voice, "a", "z", 3)], 0).unwrap();
assert_eq!(w[0].message.id, -1000);
}
#[test]
fn keys_round_trip() {
for t in [ChatTarget::Server, ChatTarget::Channel(12), ChatTarget::Private("a/b=".into())] {
assert_eq!(ChatTarget::from_key(&t.key()), t);
}
assert_eq!(split_relay("[nick] text"), (Some("nick"), "text"));
assert_eq!(split_relay("[] text"), (None, "[] text"));
assert_eq!(text_hash("[nick] text"), text_hash("text"));
}
}
+13 -6
View File
@@ -1,18 +1,25 @@
//! Local persistence for the client.
//!
//! One SQLite database holds identities, bookmarks, settings and a chat
//! cache. Passwords and query credentials never go into the database; they
//! live in a [`Secrets`] store (the OS keyring with the `keyring` feature).
//! One SQLite database holds identities, bookmarks, settings and the chat
//! history ([`chat`]). Passwords and query credentials never go into the
//! database; they live in a [`Secrets`] store (the OS keyring with the
//! `keyring` feature).
//!
//! The schema is versioned (`PRAGMA user_version`): opening a database runs
//! the migrations it has not seen, each in one transaction, keeping the data.
pub mod chat;
mod secrets;
mod store;
pub use chat::{
ChatCursor, ChatTarget, MessageSource, NewMessage, PageQuery, Reaction, RemoteInfo,
StoredMessage, SyncState, WriteOutcome, Written,
};
#[cfg(feature = "keyring")]
pub use secrets::KeyringSecrets;
pub use secrets::{MemorySecrets, Secrets};
pub use store::{
Bookmark, ChatTarget, IdentityEntry, QueryConfig, QueryTransport, Store, StoredMessage,
};
pub use store::{Bookmark, IdentityEntry, QueryConfig, QueryTransport, Store};
#[derive(Debug, thiserror::Error)]
pub enum Error {
+39 -128
View File
@@ -2,15 +2,27 @@
use std::path::Path;
use rusqlite::{Connection, OptionalExtension, params};
use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use tsclientlib::Identity;
use crate::{Error, Result};
/// Schema migrations; entry `i` upgrades from version `i` to `i + 1`.
const MIGRATIONS: &[&str] = &[r#"
/// A schema migration: SQL, or code for what SQL alone cannot do.
enum Migration {
Sql(&'static str),
Code(fn(&rusqlite::Transaction) -> rusqlite::Result<()>),
}
/// Schema migrations; entry `i` upgrades from version `i` to `i + 1`
/// (`PRAGMA user_version`). Add new ones at the end; never change one that
/// shipped.
const MIGRATIONS: &[Migration] =
&[Migration::Sql(SCHEMA_1), Migration::Code(crate::chat::migrate_2)];
/// Version 1: identities, bookmarks, settings and a first chat cache.
pub(crate) const SCHEMA_1: &str = r#"
CREATE TABLE identities (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
@@ -38,7 +50,7 @@ const MIGRATIONS: &[&str] = &[r#"
text TEXT NOT NULL
);
CREATE INDEX messages_by_target ON messages (server_uid, target, id);
"#];
"#;
/// A stored identity, without its private key.
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -104,42 +116,8 @@ impl Bookmark {
}
}
/// Where a chat message was posted.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ChatTarget {
Server,
Channel(u64),
/// Private chat with the client of this unique id.
Private(String),
}
impl ChatTarget {
fn key(&self) -> String {
match self {
ChatTarget::Server => "server".into(),
ChatTarget::Channel(cid) => format!("channel/{cid}"),
ChatTarget::Private(uid) => format!("private/{uid}"),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StoredMessage {
/// Assigned by the store; used for paging.
pub id: i64,
pub server_uid: String,
pub target: ChatTarget,
/// Unix timestamp in seconds.
pub ts: i64,
pub author_uid: Option<String>,
pub author_name: String,
/// Received through a gateway/query relay instead of our own connection.
pub via_relay: bool,
pub text: String,
}
pub struct Store {
db: Connection,
pub(crate) db: Connection,
}
impl Store {
@@ -167,18 +145,35 @@ impl Store {
Self::init(Connection::open_in_memory()?)
}
fn init(db: Connection) -> Result<Self> {
fn init(mut db: Connection) -> Result<Self> {
// Statements run through `prepare_cached` are parsed once per connection.
db.set_prepared_statement_cache_capacity(64);
db.pragma_update(None, "foreign_keys", true)?;
let version: i64 = db.pragma_query_value(None, "user_version", |r| r.get(0))?;
for (i, migration) in MIGRATIONS.iter().enumerate().skip(version as usize) {
db.execute_batch(migration)?;
db.pragma_update(None, "user_version", i as i64 + 1)?;
// Each migration with its version bump in one write transaction: a
// second connection that opens the file at the same time (the
// settings writer, the chat history) waits, then sees the new version.
loop {
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
let version: i64 = tx.pragma_query_value(None, "user_version", |r| r.get(0))?;
let Some(migration) = MIGRATIONS.get(version as usize) else { break };
match migration {
Migration::Sql(sql) => tx.execute_batch(sql)?,
Migration::Code(migrate) => migrate(&tx)?,
}
tx.pragma_update(None, "user_version", version + 1)?;
tx.commit()?;
}
Ok(Self { db })
}
/// The schema version (number of migrations applied).
pub fn schema_version(&self) -> Result<i64> {
Ok(self.db.pragma_query_value(None, "user_version", |r| r.get(0))?)
}
/// The number of schema migrations this version knows.
pub const SCHEMA_VERSION: i64 = MIGRATIONS.len() as i64;
// Identities
pub fn add_identity(&self, name: &str, identity: &Identity) -> Result<i64> {
@@ -329,63 +324,6 @@ impl Store {
tx.commit()?;
Ok(())
}
// Chat cache
pub fn add_message(&self, msg: &StoredMessage) -> Result<i64> {
self.db.execute(
"INSERT INTO messages (server_uid, target, ts, author_uid, author_name, via_relay, text)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![
msg.server_uid,
msg.target.key(),
msg.ts,
msg.author_uid,
msg.author_name,
msg.via_relay,
msg.text
],
)?;
Ok(self.db.last_insert_rowid())
}
/// Up to `limit` messages older than `before` (message id), oldest first.
pub fn history(
&self,
server_uid: &str,
target: &ChatTarget,
before: Option<i64>,
limit: usize,
) -> Result<Vec<StoredMessage>> {
let mut stmt = self.db.prepare(
"SELECT id, ts, author_uid, author_name, via_relay, text FROM messages
WHERE server_uid = ?1 AND target = ?2 AND id < ?3
ORDER BY id DESC LIMIT ?4",
)?;
let rows = stmt.query_map(
params![server_uid, target.key(), before.unwrap_or(i64::MAX), limit as i64],
|r| {
Ok(StoredMessage {
id: r.get(0)?,
server_uid: server_uid.to_string(),
target: target.clone(),
ts: r.get(1)?,
author_uid: r.get(2)?,
author_name: r.get(3)?,
via_relay: r.get(4)?,
text: r.get(5)?,
})
},
)?;
let mut messages = rows.collect::<rusqlite::Result<Vec<_>>>()?;
messages.reverse();
Ok(messages)
}
/// Delete cached messages older than `ts` (Unix seconds).
pub fn prune_messages(&self, ts: i64) -> Result<usize> {
Ok(self.db.execute("DELETE FROM messages WHERE ts < ?1", [ts])?)
}
}
#[cfg(test)]
@@ -457,33 +395,6 @@ mod tests {
assert!(!store.delete_setting("a").unwrap());
}
#[test]
fn chat_history_pages() {
let store = Store::open_in_memory().unwrap();
let target = ChatTarget::Channel(5);
for i in 0..10 {
store
.add_message(&StoredMessage {
id: 0,
server_uid: "srv".into(),
target: target.clone(),
ts: 1000 + i,
author_uid: None,
author_name: "a".into(),
via_relay: i % 2 == 0,
text: format!("m{i}"),
})
.unwrap();
}
let last = store.history("srv", &target, None, 3).unwrap();
let texts: Vec<_> = last.iter().map(|m| m.text.as_str()).collect();
assert_eq!(texts, ["m7", "m8", "m9"]);
let older = store.history("srv", &target, Some(last[0].id), 3).unwrap();
assert_eq!(older.iter().map(|m| m.text.as_str()).collect::<Vec<_>>(), ["m4", "m5", "m6"]);
assert!(store.history("srv", &ChatTarget::Server, None, 3).unwrap().is_empty());
assert_eq!(store.prune_messages(1005).unwrap(), 5);
}
#[test]
fn reopen_keeps_data_and_schema() {
let dir = std::env::temp_dir().join(format!("voelin-store-{}", std::process::id()));