mod limit;
use std::collections::HashSet;
use std::fmt;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use jmap_chat_types::{ChatPresenceEvent, ChatStreamEnable, ChatTypingEvent, EphemeralMessage};
use jmap_types::{Id, JmapError};
use jmap_websocket::server::{ExtensionHandler, ExtensionMessage, ExtensionSender};
use tokio::sync::broadcast;
use tokio::task::JoinHandle;
use tokio::time::Instant;
use crate::ChatBackend;
use crate::ephemeral::{
CompanionStreams, EphemeralSubscription, project_presence, should_deliver_typing,
};
use limit::{Limiter, Window, sleep_until};
const ENABLE: &str = "ChatStreamEnable";
const DISABLE: &str = "ChatStreamDisable";
#[derive(Debug, Clone)]
enum ChatEvent {
Typing(ChatTypingEvent),
Presence(ChatPresenceEvent),
}
#[derive(Clone)]
pub struct ChatEventHub {
tx: broadcast::Sender<ChatEvent>,
}
impl fmt::Debug for ChatEventHub {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ChatEventHub")
.field("connections", &self.tx.receiver_count())
.finish()
}
}
impl ChatEventHub {
pub fn new(capacity: usize) -> Self {
let (tx, _) = broadcast::channel(capacity);
Self { tx }
}
pub fn publish_typing(&self, event: ChatTypingEvent) {
let _ = self.tx.send(ChatEvent::Typing(event));
}
pub fn publish_presence(&self, event: ChatPresenceEvent) {
let _ = self.tx.send(ChatEvent::Presence(event));
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChatStreamLimits {
typing: Option<Duration>,
presence: Option<Duration>,
}
impl Default for ChatStreamLimits {
fn default() -> Self {
Self {
typing: Some(Duration::from_secs(3)),
presence: Some(Duration::from_secs(30)),
}
}
}
impl ChatStreamLimits {
pub fn typing_window(mut self, window: Option<Duration>) -> Self {
self.typing = window;
self
}
pub fn presence_window(mut self, window: Option<Duration>) -> Self {
self.presence = window;
self
}
pub fn typing_window_value(&self) -> Option<Duration> {
self.typing
}
pub fn presence_window_value(&self) -> Option<Duration> {
self.presence
}
}
type Observer = Box<dyn FnMut(&EphemeralSubscription) + Send>;
struct Shared<B: ChatBackend> {
backend: Arc<B>,
caller: B::CallerCtx,
accounts: HashSet<Id>,
subscription: Mutex<EphemeralSubscription>,
}
impl<B: ChatBackend> Shared<B> {
fn subscription(&self) -> EphemeralSubscription {
self.subscription
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone()
}
async fn typing(&self, event: &ChatTypingEvent) -> bool {
let covered = self
.subscription()
.typing()
.is_some_and(|scope| scope.covers(&event.chat_id));
covered
&& self.accounts.contains(&event.account_id)
&& should_deliver_typing(&*self.backend, &self.caller, &event.account_id, event)
.await
.unwrap_or(false)
}
async fn presence(&self, event: &ChatPresenceEvent) -> Option<ChatPresenceEvent> {
let covered = self
.subscription()
.presence()
.is_some_and(|scope| scope.covers(&event.contact_id));
if !covered || !self.accounts.contains(&event.account_id) {
return None;
}
project_presence(&*self.backend, &self.caller, &event.account_id, event)
.await
.ok()
.flatten()
}
}
pub struct ChatStreamHandler<B: ChatBackend> {
shared: Arc<Shared<B>>,
hub: ChatEventHub,
companions: CompanionStreams,
limits: ChatStreamLimits,
observers: Vec<Observer>,
task: Option<JoinHandle<()>>,
}
impl<B: ChatBackend> fmt::Debug for ChatStreamHandler<B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ChatStreamHandler")
.field("accounts", &self.shared.accounts)
.field("subscription", &self.shared.subscription())
.field("companions", &self.companions)
.field("limits", &self.limits)
.finish_non_exhaustive()
}
}
impl<B: ChatBackend> ChatStreamHandler<B> {
pub fn new(
backend: Arc<B>,
caller: B::CallerCtx,
accounts: impl IntoIterator<Item = Id>,
hub: &ChatEventHub,
) -> Self {
Self {
shared: Arc::new(Shared {
backend,
caller,
accounts: accounts.into_iter().collect(),
subscription: Mutex::new(EphemeralSubscription::default()),
}),
hub: hub.clone(),
companions: CompanionStreams::default(),
limits: ChatStreamLimits::default(),
observers: Vec::new(),
task: None,
}
}
pub fn with_companions(mut self, companions: CompanionStreams) -> Self {
self.companions = companions;
self
}
pub fn companions(&self) -> CompanionStreams {
self.companions
}
pub fn with_limits(mut self, limits: ChatStreamLimits) -> Self {
self.limits = limits;
self
}
pub fn on_subscription_change(
mut self,
observer: impl FnMut(&EphemeralSubscription) + Send + 'static,
) -> Self {
self.observers.push(Box::new(observer));
self
}
pub fn subscription(&self) -> EphemeralSubscription {
self.shared.subscription()
}
fn set(&mut self, subscription: EphemeralSubscription) {
*self
.shared
.subscription
.lock()
.unwrap_or_else(PoisonError::into_inner) = subscription.clone();
for observer in &mut self.observers {
observer(&subscription);
}
}
fn enable(&mut self, message: &ExtensionMessage) -> Result<(), JmapError> {
let enable: ChatStreamEnable = message.deserialize()?;
let mut next = self.subscription();
next.replace_with(&enable, self.companions)?;
self.set(next);
Ok(())
}
}
impl<B: ChatBackend> ExtensionHandler for ChatStreamHandler<B> {
fn message_types(&self) -> &[&str] {
&[ENABLE, DISABLE]
}
fn start(&mut self, events: ExtensionSender) {
let rx = self.hub.tx.subscribe();
self.task = Some(tokio::spawn(forward(
Arc::clone(&self.shared),
self.limits,
rx,
events,
)));
}
async fn handle(&mut self, message: ExtensionMessage) -> Result<(), JmapError> {
if message.message_type == ENABLE {
self.enable(&message)
} else {
self.set(EphemeralSubscription::default());
Ok(())
}
}
async fn close(&mut self) {
if let Some(task) = self.task.take() {
task.abort();
}
self.set(EphemeralSubscription::default());
}
}
impl<B: ChatBackend> Drop for ChatStreamHandler<B> {
fn drop(&mut self) {
if let Some(task) = self.task.take() {
task.abort();
}
}
}
type TypingKey = (Id, Id, Id);
type PresenceKey = (Id, Id);
async fn forward<B: ChatBackend>(
shared: Arc<Shared<B>>,
limits: ChatStreamLimits,
mut rx: broadcast::Receiver<ChatEvent>,
events: ExtensionSender,
) {
let window = |per, keep_latest| {
Some(Window {
max: 1,
per,
keep_latest,
})
};
let mut typing: Limiter<TypingKey, ()> =
Limiter::new(limits.typing.and_then(|p| window(p, false)));
let mut presence: Limiter<PresenceKey, ChatPresenceEvent> =
Limiter::new(limits.presence.and_then(|p| window(p, true)));
loop {
tokio::select! {
() = events.closed() => return,
() = sleep_until(presence.next_due()) => {
for (_, held) in presence.take_due(Instant::now()) {
if let Some(frame) = shared.presence(&held).await {
send(&events, EphemeralMessage::Presence(frame));
}
}
}
received = rx.recv() => match received {
Ok(ChatEvent::Typing(event)) => {
if shared.typing(&event).await {
let key = (
event.account_id.clone(),
event.chat_id.clone(),
event.sender_id.clone(),
);
if !event.typing || typing.offer(key, (), Instant::now()).is_some() {
send(&events, EphemeralMessage::Typing(event));
}
}
}
Ok(ChatEvent::Presence(event)) => {
if let Some(frame) = shared.presence(&event).await {
let key = (event.account_id.clone(), event.contact_id.clone());
if presence.offer(key, event, Instant::now()).is_some() {
send(&events, EphemeralMessage::Presence(frame));
}
}
}
Err(broadcast::error::RecvError::Lagged(_)) => {}
Err(broadcast::error::RecvError::Closed) => return,
},
}
}
}
fn send(events: &ExtensionSender, frame: EphemeralMessage) {
let _ = events.try_send(&frame);
}
#[cfg(all(test, feature = "memory"))]
mod tests {
use super::*;
use crate::ephemeral::IdScope;
use crate::memory::MemoryBackend;
use serde_json::{Value, json};
fn handler() -> ChatStreamHandler<MemoryBackend<()>> {
let hub = ChatEventHub::new(8);
ChatStreamHandler::new(
Arc::new(MemoryBackend::default()),
(),
[Id::from("a1")],
&hub,
)
}
fn message(ty: &str, body: Value) -> ExtensionMessage {
let Value::Object(body) = body else {
panic!("object")
};
ExtensionMessage::new(ty, body)
}
#[test]
fn registers_the_two_control_messages() {
assert_eq!(
handler().message_types(),
["ChatStreamEnable", "ChatStreamDisable"]
);
}
#[tokio::test]
async fn enable_replaces_and_disable_clears() {
let mut h = handler();
h.handle(message(
ENABLE,
json!({"dataTypes": ["typing"], "chatIds": ["c1"]}),
))
.await
.unwrap();
assert_eq!(
h.subscription().typing(),
Some(&IdScope::Only(vec![Id::from("c1")]))
);
h.handle(message(ENABLE, json!({"dataTypes": ["presence"]})))
.await
.unwrap();
assert_eq!(h.subscription().typing(), None);
assert_eq!(h.subscription().presence(), Some(&IdScope::All));
h.handle(message(DISABLE, json!({}))).await.unwrap();
assert_eq!(h.subscription(), EphemeralSubscription::default());
h.handle(message(DISABLE, json!({}))).await.unwrap();
}
#[tokio::test]
async fn unrecognized_data_types_leave_the_subscription_alone() {
let mut h = handler();
h.handle(message(ENABLE, json!({"dataTypes": ["typing"]})))
.await
.unwrap();
let err = h
.handle(message(ENABLE, json!({"id": "e1", "dataTypes": ["vtc"]})))
.await
.unwrap_err();
assert_eq!(err.error_type.as_str(), "invalidArguments");
assert_eq!(h.subscription().typing(), Some(&IdScope::All));
}
#[tokio::test]
async fn a_malformed_enable_is_not_request() {
let mut h = handler();
let err = h
.handle(message(ENABLE, json!({"dataTypes": "typing"})))
.await
.unwrap_err();
assert_eq!(err.error_type.as_str(), "notRequest");
}
#[tokio::test]
async fn observers_see_every_change_and_the_close() {
let seen = Arc::new(Mutex::new(Vec::new()));
let log = Arc::clone(&seen);
let mut h = handler()
.with_companions(CompanionStreams {
vtc: true,
..CompanionStreams::default()
})
.on_subscription_change(move |s| log.lock().unwrap().push(s.vtc()));
h.handle(message(ENABLE, json!({"dataTypes": ["vtc"]})))
.await
.unwrap();
let _ = h.handle(message(ENABLE, json!({"dataTypes": []}))).await;
h.handle(message(DISABLE, json!({}))).await.unwrap();
h.handle(message(ENABLE, json!({"dataTypes": ["vtc"]})))
.await
.unwrap();
h.close().await;
assert_eq!(*seen.lock().unwrap(), [true, false, true, false]);
}
#[test]
fn default_limits_are_the_drafts() {
let l = ChatStreamLimits::default();
assert_eq!(l.typing_window_value(), Some(Duration::from_secs(3)));
assert_eq!(l.presence_window_value(), Some(Duration::from_secs(30)));
let l = l.typing_window(None);
assert_eq!(l.typing_window_value(), None);
}
}