use jmap_chat_types::SpacePatchOp;
use jmap_server::{BackendSetError, JmapBackend, JmapObject, SetError, SetErrorType, SetObject};
#[non_exhaustive]
#[derive(Debug)]
pub struct OpResult {
pub op_index: usize,
pub outcome: Result<Option<jmap_types::Id>, SetError>,
}
impl OpResult {
#[must_use]
pub const fn ok(op_index: usize, id: Option<jmap_types::Id>) -> Self {
Self {
op_index,
outcome: Ok(id),
}
}
#[must_use]
pub const fn err(op_index: usize, error: SetError) -> Self {
Self {
op_index,
outcome: Err(error),
}
}
#[must_use]
pub const fn with_op_index(mut self, op_index: usize) -> Self {
self.op_index = op_index;
self
}
#[must_use]
pub fn with_outcome(mut self, outcome: Result<Option<jmap_types::Id>, SetError>) -> Self {
self.outcome = outcome;
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChatLimits {
pub max_roles_per_space: u32,
pub max_space_members: u32,
pub max_channels_per_space: u32,
pub max_categories_per_space: u32,
pub max_group_chat_members: u32,
pub supported_body_types: &'static [&'static str],
pub server_reserved_body_types: &'static [&'static str],
pub encrypted_body_types: &'static [&'static str],
pub supports_threads: bool,
pub max_body_bytes: u64,
pub max_attachment_bytes: u64,
pub max_attachments_per_message: u64,
}
impl Default for ChatLimits {
fn default() -> Self {
Self::new(50, 10_000, 500, 100)
}
}
impl ChatLimits {
pub const fn new(
max_roles_per_space: u32,
max_space_members: u32,
max_channels_per_space: u32,
max_categories_per_space: u32,
) -> Self {
Self {
max_roles_per_space,
max_space_members,
max_channels_per_space,
max_categories_per_space,
max_group_chat_members: 1_000,
supported_body_types: crate::message::SUPPORTED_BODY_TYPES,
server_reserved_body_types: &[],
encrypted_body_types: crate::message::ENCRYPTED_BODY_TYPES,
supports_threads: false,
max_body_bytes: 100_000,
max_attachment_bytes: 50_000_000,
max_attachments_per_message: 16,
}
}
#[must_use]
pub const fn with_max_roles_per_space(mut self, max: u32) -> Self {
self.max_roles_per_space = max;
self
}
#[must_use]
pub const fn with_max_space_members(mut self, max: u32) -> Self {
self.max_space_members = max;
self
}
#[must_use]
pub const fn with_max_channels_per_space(mut self, max: u32) -> Self {
self.max_channels_per_space = max;
self
}
#[must_use]
pub const fn with_max_categories_per_space(mut self, max: u32) -> Self {
self.max_categories_per_space = max;
self
}
#[must_use]
pub const fn with_max_group_chat_members(mut self, max: u32) -> Self {
self.max_group_chat_members = max;
self
}
#[must_use]
pub const fn with_supported_body_types(mut self, types: &'static [&'static str]) -> Self {
self.supported_body_types = types;
self
}
#[must_use]
pub const fn with_server_reserved_body_types(mut self, types: &'static [&'static str]) -> Self {
self.server_reserved_body_types = types;
self
}
#[must_use]
pub const fn with_encrypted_body_types(mut self, types: &'static [&'static str]) -> Self {
self.encrypted_body_types = types;
self
}
#[must_use]
pub const fn with_supports_threads(mut self, supports: bool) -> Self {
self.supports_threads = supports;
self
}
#[must_use]
pub const fn with_max_body_bytes(mut self, max: u64) -> Self {
self.max_body_bytes = max;
self
}
#[must_use]
pub const fn with_max_attachment_bytes(mut self, max: u64) -> Self {
self.max_attachment_bytes = max;
self
}
#[must_use]
pub const fn with_max_attachments_per_message(mut self, max: u64) -> Self {
self.max_attachments_per_message = max;
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AttachmentBlob {
pub size: u64,
pub sha256: [u8; 32],
}
impl AttachmentBlob {
#[must_use]
pub const fn new(size: u64, sha256: [u8; 32]) -> Self {
Self { size, sha256 }
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EmojiSetOp {
Create,
Update,
Destroy,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InviteJoinRefusal {
NotFound,
Exhausted,
AlreadyMember,
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct SlowModeError {
pub retry_after: jmap_types::UTCDate,
}
impl SlowModeError {
#[must_use]
pub const fn new(retry_after: jmap_types::UTCDate) -> Self {
Self { retry_after }
}
}
impl std::fmt::Display for SlowModeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"slow-mode rate limit; retry after {}",
self.retry_after.as_ref()
)
}
}
impl std::error::Error for SlowModeError {}
pub trait ChatBackend: JmapBackend {
fn create_object<O, F>(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
create_id: &str,
build: F,
) -> impl std::future::Future<Output = Result<(jmap_types::Id, O), BackendSetError<Self::Error>>>
+ Send
where
O: SetObject + Send + Sync,
F: FnOnce(&jmap_types::Id) -> O + Send;
fn create_message<F>(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
create_id: &str,
build: F,
) -> impl std::future::Future<
Output = Result<(jmap_types::Id, jmap_chat_types::Message), BackendSetError<Self::Error>>,
> + Send
where
F: FnOnce(&jmap_types::Id) -> jmap_chat_types::Message + Send,
{
async move {
let (id, message) = self
.create_object::<jmap_chat_types::Message, _>(caller, account_id, create_id, build)
.await?;
let event = crate::OutboundEvent::NewMessage {
chat_id: message.chat_id.clone(),
message_id: message.id.clone(),
sender_msg_id: message.sender_msg_id.clone(),
};
self.on_outbound_event(caller, account_id, &event).await;
Ok((id, message))
}
}
fn update_object<O: SetObject + Send + Sync>(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
id: &jmap_types::Id,
patch: O::Patch,
) -> impl std::future::Future<Output = Result<Option<O>, BackendSetError<Self::Error>>> + Send;
fn destroy_object<O: SetObject + Send + Sync>(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
id: &jmap_types::Id,
) -> impl std::future::Future<Output = Result<(), BackendSetError<Self::Error>>> + Send;
fn on_chat_destroyed(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
chat_id: &jmap_types::Id,
) -> impl std::future::Future<Output = ()> + Send {
let _ = (caller, account_id, chat_id);
async {}
}
fn on_space_destroyed(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
space_id: &jmap_types::Id,
) -> impl std::future::Future<Output = ()> + Send {
let _ = (caller, account_id, space_id);
async {}
}
fn on_space_ban_created(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
ban: &jmap_chat_types::SpaceBan,
) -> impl std::future::Future<Output = ()> + Send {
let _ = (caller, account_id, ban);
async {}
}
fn on_outbound_event(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
event: &crate::OutboundEvent,
) -> impl std::future::Future<Output = ()> + Send {
let _ = (caller, account_id, event);
async {}
}
fn supports_type<O: JmapObject>(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
) -> bool;
fn generate_invite_code(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
) -> impl std::future::Future<Output = Result<String, Self::Error>> + Send;
fn join_space_with_invite(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
invite_id: &jmap_types::Id,
joined_at: &jmap_types::UTCDate,
) -> impl std::future::Future<Output = Result<Result<(), InviteJoinRefusal>, Self::Error>> + Send;
fn read_and_burn_message(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
message_id: &jmap_types::Id,
patch: jmap_types::PatchObject,
) -> impl std::future::Future<Output = Result<(), BackendSetError<Self::Error>>> + Send;
fn limits(&self, _caller: &Self::CallerCtx, _account_id: &jmap_types::Id) -> ChatLimits {
ChatLimits::default()
}
fn apply_space_patch(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
space_id: &jmap_types::Id,
ops: Vec<SpacePatchOp>,
) -> impl std::future::Future<Output = Result<Vec<OpResult>, BackendSetError<Self::Error>>> + Send;
fn apply_space_metadata_patch(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
space_id: &jmap_types::Id,
patch: jmap_chat_types::SpaceMetadataPatch,
) -> impl std::future::Future<
Output = Result<Option<jmap_chat_types::Space>, BackendSetError<Self::Error>>,
> + Send;
fn space_extension_properties(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
) -> &'static [&'static str] {
let _ = (caller, account_id);
&[]
}
fn protect_last_admin(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> bool {
let _ = (caller, account_id);
true
}
fn retains_edit_history(&self) -> bool {
false
}
fn maintains_unread_count(&self) -> bool {
false
}
fn is_contact_blocked(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
contact_id: &jmap_types::Id,
) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
async move {
let (contacts, _) = self
.get_objects::<jmap_chat_types::ChatContact>(
caller,
account_id,
Some(std::slice::from_ref(contact_id)),
None,
)
.await?;
Ok(contacts.iter().any(|c| c.id == *contact_id && c.blocked))
}
}
fn owner_user_id(
&self,
_caller: &Self::CallerCtx,
_account_id: &jmap_types::Id,
) -> impl std::future::Future<Output = Result<Option<String>, Self::Error>> + Send {
async { Ok(None) }
}
fn everyone_permissions(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
space: &jmap_chat_types::Space,
) -> impl std::future::Future<
Output = Result<std::collections::HashSet<jmap_chat_types::ChatPermission>, Self::Error>,
> + Send;
fn may_set_custom_emoji(
&self,
_caller: &Self::CallerCtx,
_account_id: &jmap_types::Id,
_target_space_id: Option<&jmap_types::Id>,
_op: EmojiSetOp,
) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
async { Ok(Ok(())) }
}
fn may_broadcast_mention(
&self,
_caller: &Self::CallerCtx,
_account_id: &jmap_types::Id,
_space_id: &jmap_types::Id,
_chat_id: &jmap_types::Id,
) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
async { Ok(Ok(())) }
}
fn may_set_pinned_messages(
&self,
_caller: &Self::CallerCtx,
_account_id: &jmap_types::Id,
_chat_id: &jmap_types::Id,
) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
async { Ok(Ok(())) }
}
fn may_set_space_ban(
&self,
_caller: &Self::CallerCtx,
_account_id: &jmap_types::Id,
_space_id: &jmap_types::Id,
) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
async { Ok(Ok(())) }
}
fn may_set_space_invite(
&self,
_caller: &Self::CallerCtx,
_account_id: &jmap_types::Id,
_space_id: &jmap_types::Id,
_created_by: Option<&jmap_types::Id>,
) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
async { Ok(Ok(())) }
}
fn may_get_space_invite(
&self,
_caller: &Self::CallerCtx,
_account_id: &jmap_types::Id,
_invite: &jmap_chat_types::SpaceInvite,
) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
async { Ok(true) }
}
fn may_get_space_ban(
&self,
_caller: &Self::CallerCtx,
_account_id: &jmap_types::Id,
_ban: &jmap_chat_types::SpaceBan,
) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
async { Ok(true) }
}
fn may_send_message(
&self,
_caller: &Self::CallerCtx,
_account_id: &jmap_types::Id,
_chat_id: &jmap_types::Id,
) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
async { Ok(Ok(())) }
}
fn may_create_message(
&self,
_caller: &Self::CallerCtx,
_account_id: &jmap_types::Id,
_chat: &jmap_chat_types::Chat,
) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
async { Ok(Ok(())) }
}
fn may_update_message(
&self,
_caller: &Self::CallerCtx,
_account_id: &jmap_types::Id,
_chat: &jmap_chat_types::Chat,
_message: &jmap_chat_types::Message,
_patch_keys: &[&str],
) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
async { Ok(Ok(())) }
}
fn may_update_chat(
&self,
_caller: &Self::CallerCtx,
_account_id: &jmap_types::Id,
_chat: &jmap_chat_types::Chat,
_patch_keys: &[&str],
) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
async { Ok(Ok(())) }
}
fn attachment_blob(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
blob_id: &jmap_types::Id,
) -> impl std::future::Future<
Output = Result<Result<Option<AttachmentBlob>, SetError>, Self::Error>,
> + Send;
fn filenode_attachment(
&self,
_caller: &Self::CallerCtx,
_account_id: &jmap_types::Id,
_chat: &jmap_chat_types::Chat,
_attachment: &jmap_chat_types::AttachmentCreate,
) -> impl std::future::Future<
Output = Result<Result<Option<jmap_chat_types::Attachment>, SetError>, Self::Error>,
> + Send {
async { Ok(Ok(None)) }
}
fn may_view_chat(
&self,
_caller: &Self::CallerCtx,
_account_id: &jmap_types::Id,
_chat_id: &jmap_types::Id,
) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
async { Ok(true) }
}
fn validate_pinned_message_ids(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
chat_id: &jmap_types::Id,
added: &[jmap_types::Id],
) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
async move {
let (messages, _) = self
.get_objects::<jmap_chat_types::Message>(caller, account_id, Some(added), None)
.await?;
let in_chat = |id: &jmap_types::Id| {
messages
.iter()
.any(|m| m.id == *id && m.chat_id == *chat_id)
};
if added.iter().all(in_chat) {
return Ok(Ok(()));
}
Ok(Err(SetError::new(SetErrorType::InvalidProperties)
.with_properties(["pinnedMessageIds"])
.with_description(
"pinned id is not a Message in this Chat",
)))
}
}
fn slow_mode_check(
&self,
_caller: &Self::CallerCtx,
_account_id: &jmap_types::Id,
_chat_id: &jmap_types::Id,
) -> impl std::future::Future<Output = Result<(), SlowModeError>> + Send {
async { Ok(()) }
}
fn expire_message(
&self,
_caller: &Self::CallerCtx,
_account_id: &jmap_types::Id,
_message_id: &jmap_types::Id,
) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send {
async { Ok(()) }
}
}
#[cfg(test)]
mod tests {
use super::SlowModeError;
use jmap_types::UTCDate;
#[test]
fn slow_mode_error_display_contains_retry_after() {
let err = SlowModeError::new(UTCDate::from("2026-05-16T12:34:56Z"));
let rendered = format!("{err}");
assert!(
rendered.contains("slow-mode rate limit"),
"Display missing prefix: {rendered}"
);
assert!(
rendered.contains("2026-05-16T12:34:56Z"),
"Display missing retry_after timestamp: {rendered}"
);
}
#[test]
fn slow_mode_error_is_std_error() {
fn assert_is_error<E: std::error::Error>(_: &E) {}
let err = SlowModeError::new(UTCDate::from("2026-05-16T12:34:56Z"));
assert_is_error(&err);
}
#[test]
fn slow_mode_error_boxes_as_dyn_error() {
let err = SlowModeError::new(UTCDate::from("2026-05-16T12:34:56Z"));
let boxed: Box<dyn std::error::Error> = Box::new(err);
assert!(boxed.to_string().contains("slow-mode rate limit"));
}
use super::OpResult;
use jmap_server::{SetError, SetErrorType};
#[test]
fn op_result_ok_carries_op_index_and_optional_id() {
let r = OpResult::ok(3, Some(jmap_types::Id::from("space-1")));
assert_eq!(r.op_index, 3);
assert_eq!(r.outcome, Ok(Some(jmap_types::Id::from("space-1"))));
}
#[test]
fn op_result_ok_with_none_id_for_update_or_destroy() {
let r = OpResult::ok(0, None);
assert_eq!(r.op_index, 0);
assert_eq!(r.outcome, Ok(None));
}
#[test]
fn op_result_err_carries_op_index_and_set_error() {
let r = OpResult::err(7, SetError::new(SetErrorType::Forbidden));
assert_eq!(r.op_index, 7);
match r.outcome {
Err(e) => assert_eq!(e.error_type, SetErrorType::Forbidden),
Ok(_) => panic!("expected Err outcome"),
}
}
#[test]
fn op_result_with_op_index_replaces_field() {
let r = OpResult::ok(0, None).with_op_index(42);
assert_eq!(r.op_index, 42);
assert_eq!(r.outcome, Ok(None));
}
#[test]
fn op_result_with_outcome_replaces_field() {
let r =
OpResult::ok(0, None).with_outcome(Err(SetError::new(SetErrorType::InvalidProperties)));
assert_eq!(r.op_index, 0);
match r.outcome {
Err(e) => assert_eq!(e.error_type, SetErrorType::InvalidProperties),
Ok(_) => panic!("expected Err outcome after with_outcome"),
}
}
use super::ChatLimits;
#[test]
fn op_result_ok_is_const_fn() {
const _R: OpResult = OpResult::ok(0, None);
}
#[test]
fn chat_limits_builder_is_const_fn() {
const _LIMITS: ChatLimits = ChatLimits::new(1, 2, 3, 4)
.with_max_roles_per_space(10)
.with_max_space_members(20)
.with_max_channels_per_space(30)
.with_max_categories_per_space(40);
}
}