use jmap_chat_types::space_set::{
CategoryPatch, ChannelCreate, ChannelPatch, MemberPatch, RolePatch,
};
use jmap_chat_types::{Category, Space, SpaceInvite, SpaceRole};
use jmap_types::{Id, Invocation, JmapError, PatchObject, State, UTCDate};
use serde_json::{json, Value};
use subtle::ConstantTimeEq;
use crate::backend::{
BackendSetError, ChatBackend, ChatLimits, SetError, SetErrorType, SpacePatchOp,
};
use crate::helpers::{
count_add_ops, enforce_max_objects_in_set, extract_account_id, finalize_set_response,
iso8601_before, not_found_json, now_utc_string, serialize_value, set_error_value,
SetAccumulators,
};
use jmap_server::{server_fail_from_backend, server_fail_value_from_backend};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StructuralKey {
AddRoles,
UpdateRoles,
RemoveRoles,
AddMembers,
UpdateMembers,
RemoveMembers,
AddChannels,
UpdateChannels,
RemoveChannels,
AddCategories,
UpdateCategories,
RemoveCategories,
}
impl StructuralKey {
fn from_wire(key: &str) -> Option<Self> {
Some(match key {
"addRoles" => Self::AddRoles,
"updateRoles" => Self::UpdateRoles,
"removeRoles" => Self::RemoveRoles,
"addMembers" => Self::AddMembers,
"updateMembers" => Self::UpdateMembers,
"removeMembers" => Self::RemoveMembers,
"addChannels" => Self::AddChannels,
"updateChannels" => Self::UpdateChannels,
"removeChannels" => Self::RemoveChannels,
"addCategories" => Self::AddCategories,
"updateCategories" => Self::UpdateCategories,
"removeCategories" => Self::RemoveCategories,
_ => return None,
})
}
fn wire_name(self) -> &'static str {
match self {
Self::AddRoles => "addRoles",
Self::UpdateRoles => "updateRoles",
Self::RemoveRoles => "removeRoles",
Self::AddMembers => "addMembers",
Self::UpdateMembers => "updateMembers",
Self::RemoveMembers => "removeMembers",
Self::AddChannels => "addChannels",
Self::UpdateChannels => "updateChannels",
Self::RemoveChannels => "removeChannels",
Self::AddCategories => "addCategories",
Self::UpdateCategories => "updateCategories",
Self::RemoveCategories => "removeCategories",
}
}
}
fn parse_structural_entries(key: StructuralKey, value: Value) -> Result<Vec<SpacePatchOp>, String> {
let canonical = key.wire_name();
let arr = match value {
Value::Array(a) => a,
other => {
return Err(format!(
"{canonical} must be a JSON array, got {}",
json_value_kind(&other)
));
}
};
let mut out = Vec::with_capacity(arr.len());
for (idx, entry) in arr.into_iter().enumerate() {
let op = match key {
StructuralKey::AddRoles => {
SpacePatchOp::AddRole(parse_entry::<SpaceRole>(canonical, idx, entry)?)
}
StructuralKey::RemoveRoles => {
SpacePatchOp::RemoveRole(parse_id_entry(canonical, idx, entry)?)
}
StructuralKey::UpdateRoles => {
let (id, patch) = parse_update_entry::<RolePatch>(canonical, idx, entry)?;
SpacePatchOp::UpdateRole { id, patch }
}
StructuralKey::AddMembers => {
let (user_id, role_ids) = parse_add_member_entry(canonical, idx, entry)?;
SpacePatchOp::AddMember(jmap_chat_types::MemberCreate::new(user_id, role_ids))
}
StructuralKey::RemoveMembers => {
SpacePatchOp::RemoveMember(parse_id_entry(canonical, idx, entry)?)
}
StructuralKey::UpdateMembers => {
let (id, patch) = parse_update_entry::<MemberPatch>(canonical, idx, entry)?;
SpacePatchOp::UpdateMember { user_id: id, patch }
}
StructuralKey::AddChannels => {
SpacePatchOp::AddChannel(parse_entry::<ChannelCreate>(canonical, idx, entry)?)
}
StructuralKey::RemoveChannels => {
SpacePatchOp::RemoveChannel(parse_id_entry(canonical, idx, entry)?)
}
StructuralKey::UpdateChannels => {
let (id, patch) = parse_update_entry::<ChannelPatch>(canonical, idx, entry)?;
SpacePatchOp::UpdateChannel { id, patch }
}
StructuralKey::AddCategories => {
SpacePatchOp::AddCategory(parse_entry::<Category>(canonical, idx, entry)?)
}
StructuralKey::RemoveCategories => {
SpacePatchOp::RemoveCategory(parse_id_entry(canonical, idx, entry)?)
}
StructuralKey::UpdateCategories => {
let (id, patch) = parse_update_entry::<CategoryPatch>(canonical, idx, entry)?;
SpacePatchOp::UpdateCategory { id, patch }
}
};
out.push(op);
}
Ok(out)
}
fn parse_entry<T: serde::de::DeserializeOwned>(
canonical: &'static str,
idx: usize,
entry: Value,
) -> Result<T, String> {
serde_json::from_value(entry)
.map_err(|e| format!("{canonical}[{idx}]: failed to parse entry: {e}"))
}
fn dedup_caller_members(members: Vec<Value>, caller_identity: &str) -> Vec<Value> {
let mut seen_ours = false;
members
.into_iter()
.filter(|m| {
if m.get("id").and_then(|v| v.as_str()) == Some(caller_identity) {
if seen_ours {
false
} else {
seen_ours = true;
true
}
} else {
true
}
})
.collect()
}
fn parse_id_entry(canonical: &'static str, idx: usize, entry: Value) -> Result<Id, String> {
match entry {
Value::String(s) => Ok(Id::from(s.as_str())),
other => Err(format!(
"{canonical}[{idx}] must be a string Id, got {}",
json_value_kind(&other)
)),
}
}
fn parse_update_entry<P: serde::de::DeserializeOwned>(
canonical: &'static str,
idx: usize,
entry: Value,
) -> Result<(Id, P), String> {
let mut obj = match entry {
Value::Object(o) => o,
other => {
return Err(format!(
"{canonical}[{idx}] must be a JSON object, got {}",
json_value_kind(&other)
));
}
};
let id_val = obj
.remove("id")
.ok_or_else(|| format!("{canonical}[{idx}] missing required \"id\" property"))?;
let id = match id_val {
Value::String(s) => Id::from(s.as_str()),
other => {
return Err(format!(
"{canonical}[{idx}].id must be a string, got {}",
json_value_kind(&other)
));
}
};
let patch: P = serde_json::from_value(Value::Object(obj))
.map_err(|e| format!("{canonical}[{idx}]: failed to parse patch fields: {e}"))?;
Ok((id, patch))
}
fn parse_add_member_entry(
canonical: &'static str,
idx: usize,
entry: Value,
) -> Result<(Id, Vec<Id>), String> {
let mut obj = match entry {
Value::Object(o) => o,
other => {
return Err(format!(
"{canonical}[{idx}] must be a JSON object, got {}",
json_value_kind(&other)
));
}
};
let id_val = obj
.remove("id")
.ok_or_else(|| format!("{canonical}[{idx}] missing required \"id\" property"))?;
let user_id = match id_val {
Value::String(s) => Id::from(s.as_str()),
other => {
return Err(format!(
"{canonical}[{idx}].id must be a string, got {}",
json_value_kind(&other)
));
}
};
let role_ids: Vec<Id> = match obj.remove("roleIds") {
None | Some(Value::Null) => Vec::new(),
Some(v) => serde_json::from_value(v)
.map_err(|e| format!("{canonical}[{idx}].roleIds must be a string array: {e}"))?,
};
if let Some(extra) = obj.keys().next() {
return Err(format!(
"{canonical}[{idx}] has unexpected property \"{extra}\""
));
}
Ok((user_id, role_ids))
}
fn json_value_kind(v: &Value) -> &'static str {
match v {
Value::Null => "null",
Value::Bool(_) => "boolean",
Value::Number(_) => "number",
Value::String(_) => "string",
Value::Array(_) => "array",
Value::Object(_) => "object",
}
}
pub async fn handle_space_get<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
let (account_id, mut args) = extract_account_id(args)?;
let ids: Option<Vec<Id>> = match args.remove("ids") {
None | Some(Value::Null) => None,
Some(v) => Some(
serde_json::from_value(v)
.map_err(|_| JmapError::invalid_arguments("ids must be an Id array"))?,
),
};
let properties: Option<Vec<String>> = match args.remove("properties") {
None | Some(Value::Null) => None,
Some(v) => Some(
serde_json::from_value(v)
.map_err(|_| JmapError::invalid_arguments("properties must be a string array"))?,
),
};
let ids_slice = ids.as_deref();
let (list, mut not_found) = backend
.get_objects::<Space>(caller, &account_id, ids_slice, properties.as_deref())
.await
.map_err(|e| server_fail_from_backend(&e))?;
let state = backend
.get_state::<Space>(caller, &account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?;
let caller_principal: Option<&Id> = B::principal_id(caller);
let mut visible_list: Vec<&Space> = Vec::with_capacity(list.len());
for space in &list {
if non_member_non_previewable(space, caller_principal) {
not_found.push(space.id.clone());
} else {
visible_list.push(space);
}
}
let list_json: Vec<Value> = visible_list
.iter()
.map(|space| project_space_for_caller(space, caller_principal, properties.as_deref()))
.collect::<Result<Vec<_>, _>>()?;
Ok((
json!({
"accountId": account_id.as_ref(),
"state": state.as_ref(),
"list": list_json,
"notFound": not_found_json(¬_found),
}),
vec![],
))
}
fn non_member_non_previewable(space: &Space, caller_principal: Option<&Id>) -> bool {
let Some(principal) = caller_principal else {
return false;
};
let is_member = space
.members
.iter()
.any(|m| m.id.as_ref() == principal.as_ref());
!is_member && !space.is_publicly_previewable
}
const NON_MEMBER_PREVIEWABLE_FIELDS: &[&str] = &[
"id",
"name",
"description",
"iconBlobId",
"memberCount",
"createdAt",
"isPublic",
"isPubliclyPreviewable",
];
const SPACE_READONLY: &[&str] = &[
"id",
"createdAt",
"memberCount",
"roles",
"members",
"categories",
"uncategorizedChannelIds",
];
const SPACE_METADATA_FIELDS: &[&str] = &[
"name",
"description",
"iconBlobId",
"isPublic",
"isPubliclyPreviewable",
];
fn project_space_for_caller(
space: &Space,
caller_principal: Option<&Id>,
properties: Option<&[String]>,
) -> Result<Value, JmapError> {
let full = serialize_value(space)?;
let allowed_fields: Option<Vec<&str>> = match caller_principal {
None => None,
Some(principal) => {
let is_member = space
.members
.iter()
.any(|m| m.id.as_ref() == principal.as_ref());
if is_member {
None
} else if space.is_publicly_previewable {
Some(NON_MEMBER_PREVIEWABLE_FIELDS.to_vec())
} else {
None
}
}
};
let request_filter: Option<&[String]> = properties;
match (allowed_fields, request_filter) {
(None, None) => Ok(full),
(None, Some(props)) => Ok(filter_object_fields(full, |k| props.iter().any(|p| p == k))),
(Some(cap), None) => Ok(filter_object_fields(full, |k| cap.contains(&k))),
(Some(cap), Some(props)) => Ok(filter_object_fields(full, |k| {
cap.contains(&k) && props.iter().any(|p| p == k)
})),
}
}
fn filter_object_fields<F: Fn(&str) -> bool>(value: Value, keep: F) -> Value {
match value {
Value::Object(map) => {
Value::Object(map.into_iter().filter(|(k, _)| keep(k.as_str())).collect())
}
other => other,
}
}
pub async fn handle_space_changes<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
jmap_server::handlers::handle_changes::<Space, B>(backend, caller, args).await
}
pub async fn handle_space_query<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
let (account_id, mut args) = extract_account_id(args)?;
let calculate_total: bool = args
.get("calculateTotal")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let limit: Option<u64> = match args.remove("limit") {
None | Some(Value::Null) => None,
Some(v) => match v.as_u64() {
Some(n) => Some(n),
None => {
return Err(JmapError::invalid_arguments(format!(
"limit: expected a non-negative integer, got {v}"
)))
}
},
};
let position: i64 = match args.remove("position") {
None | Some(Value::Null) => 0,
Some(v) => v.as_i64().ok_or_else(|| {
JmapError::invalid_arguments(format!("position: expected an integer, got {v}"))
})?,
};
let filter: Option<serde_json::Value> = match args.remove("filter") {
None | Some(Value::Null) => None,
Some(v) => Some(v),
};
let sort: Option<Vec<serde_json::Value>> = match args.remove("sort") {
None | Some(Value::Null) => None,
Some(v) => Some(
serde_json::from_value(v)
.map_err(|_| JmapError::invalid_arguments("sort must be an array"))?,
),
};
let result = backend
.query_objects::<Space>(
caller,
&account_id,
filter.as_ref(),
sort.as_deref(),
limit,
position,
)
.await
.map_err(|e| server_fail_from_backend(&e))?;
let mut resp = json!({
"accountId": account_id.as_ref(),
"queryState": result.query_state.as_ref(),
"canCalculateChanges": result.can_calculate_changes,
"position": result.position,
"ids": result.ids.iter().map(|id| id.as_ref()).collect::<Vec<_>>(),
});
if calculate_total {
if let Some(t) = result.total {
resp["total"] = json!(t);
}
}
Ok((resp, vec![]))
}
pub async fn handle_space_query_changes<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
let (account_id, args) = extract_account_id(args)?;
let since_query_state: State = match args.get("sinceQueryState").and_then(|v| v.as_str()) {
Some(s) => State::from(s),
None => return Err(JmapError::invalid_arguments("sinceQueryState is required")),
};
let max_changes: Option<u64> = match args.get("maxChanges") {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_u64().filter(|&n| n > 0).ok_or_else(|| {
JmapError::invalid_arguments("maxChanges must be a positive integer")
})?),
};
let up_to_id: Option<Id> = match args.get("upToId") {
None | Some(Value::Null) => None,
Some(Value::String(s)) => Some(Id::from(s.as_str())),
Some(_) => {
return Err(JmapError::invalid_arguments(
"upToId must be a string Id or null",
))
}
};
let calculate_total: bool = args
.get("calculateTotal")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let result = backend
.query_changes::<Space>(
caller,
&account_id,
&since_query_state,
None,
None,
max_changes,
up_to_id.as_ref(),
false,
)
.await
.map_err(JmapError::from)?;
let removed: Vec<&str> = result.removed.iter().map(|id| id.as_ref()).collect();
let added: Vec<Value> = result
.added
.iter()
.map(|item| {
json!({
"id": item.id.as_ref(),
"index": item.index,
})
})
.collect();
let mut resp = json!({
"accountId": account_id.as_ref(),
"oldQueryState": result.old_query_state.as_ref(),
"newQueryState": result.new_query_state.as_ref(),
"removed": removed,
"added": added,
});
if calculate_total {
if let Some(t) = result.total {
resp["total"] = json!(t);
}
}
Ok((resp, vec![]))
}
async fn check_space_count_limits<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
account_id: &Id,
space_id: &Id,
ops: &[SpacePatchOp],
limits: &ChatLimits,
) -> Result<Option<SetError>, JmapError> {
let (add_roles, add_members, add_channels, add_categories) = count_add_ops(ops);
if add_roles == 0 && add_members == 0 && add_channels == 0 && add_categories == 0 {
return Ok(None);
}
let (found, _not_found) = backend
.get_objects::<Space>(
caller,
account_id,
Some(std::slice::from_ref(space_id)),
None,
)
.await
.map_err(|e| server_fail_from_backend(&e))?;
let Some(space) = found.into_iter().next() else {
return Ok(None);
};
let cur_roles = u32::try_from(space.roles.len()).unwrap_or(u32::MAX);
let cur_members = u32::try_from(space.members.len()).unwrap_or(u32::MAX);
let cur_categories = u32::try_from(space.categories.len()).unwrap_or(u32::MAX);
let cur_channels = u32::try_from(
space.uncategorized_channel_ids.len()
+ space
.categories
.iter()
.map(|c| c.channel_ids.len())
.sum::<usize>(),
)
.unwrap_or(u32::MAX);
let exceeded =
|description: &'static str, current: u32, add: u32, cap: u32| -> Option<SetError> {
if add == 0 {
return None;
}
if current.saturating_add(add) > cap {
Some(SetError::new(SetErrorType::OverQuota).with_description(description))
} else {
None
}
};
Ok([
(
"too many roles",
cur_roles,
add_roles,
limits.max_roles_per_space,
),
(
"too many members",
cur_members,
add_members,
limits.max_space_members,
),
(
"too many channels",
cur_channels,
add_channels,
limits.max_channels_per_space,
),
(
"too many categories",
cur_categories,
add_categories,
limits.max_categories_per_space,
),
]
.into_iter()
.find_map(|(description, current, add, cap)| exceeded(description, current, add, cap)))
}
pub async fn handle_space_set<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
let (account_id, mut args) = extract_account_id(args)?;
enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;
let old_state = backend
.get_state::<Space>(caller, &account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?;
if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str()) {
if if_in_state != old_state.as_ref() {
return Err(JmapError::state_mismatch());
}
}
let mut created = serde_json::Map::new();
let mut not_created = serde_json::Map::new();
let mut updated = serde_json::Map::new();
let mut not_updated = serde_json::Map::new();
let mut destroyed_list: Vec<Value> = Vec::new();
let mut not_destroyed = serde_json::Map::new();
let mut mutated = false;
if let Some(create_map) = args.get("create").and_then(|v| v.as_object()) {
for (create_id, obj_val) in create_map {
let name = match obj_val.get("name").and_then(|v| v.as_str()) {
Some(s) if !s.is_empty() => s.to_owned(),
_ => {
not_created.insert(
create_id.clone(),
json!({ "type": "invalidProperties", "properties": ["name"] }),
);
continue;
}
};
if name.len() > 256 {
not_created.insert(
create_id.clone(),
json!({ "type": "invalidProperties", "properties": ["name"] }),
);
continue;
}
let is_public = obj_val
.get("isPublic")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let is_publicly_previewable = obj_val
.get("isPubliclyPreviewable")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let now_str = now_utc_string();
let now: UTCDate = UTCDate::from(now_str.as_ref());
let mut space = Space::new(
Id::from("placeholder"),
name,
vec![],
vec![],
vec![],
vec![],
now,
is_public,
is_publicly_previewable,
0,
);
if let Some(desc) = obj_val.get("description").and_then(|v| v.as_str()) {
space.description = Some(desc.to_owned());
}
match backend
.create_object::<Space>(caller, &account_id, create_id, space)
.await
{
Ok((_server_id, created_obj)) => {
mutated = true;
created.insert(
create_id.clone(),
serde_json::to_value(&created_obj)
.expect("derive(Serialize) on plain data is infallible"),
);
}
Err(BackendSetError::SetError(set_err)) => {
not_created.insert(create_id.clone(), set_error_value(&set_err));
}
Err(BackendSetError::Other(e)) => {
not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
}
Err(_) => {
not_created.insert(
create_id.clone(),
json!({
"type": "serverFail",
"description": "unhandled backend error variant",
}),
);
}
}
}
}
let space_limits = backend.limits(caller, &account_id);
if let Some(Value::Object(update_map)) = args.remove("update") {
for (id_str, patch_val) in update_map {
let id = Id::from(id_str.as_str());
let bad_props: Vec<&str> = SPACE_READONLY
.iter()
.copied()
.filter(|&field| patch_val.get(field).is_some())
.collect();
if !bad_props.is_empty() {
not_updated.insert(
id_str,
json!({ "type": "invalidProperties", "properties": bad_props }),
);
continue;
}
let Value::Object(mut patch_map) = patch_val else {
not_updated.insert(
id_str,
json!({ "type": "invalidPatch", "description": "patch must be a JSON object" }),
);
continue;
};
let mut ops: Vec<SpacePatchOp> = Vec::new();
let mut clean_patch = serde_json::Map::new();
let mut unknown_keys: Vec<String> = Vec::new();
let mut bad_structural_key: Option<(&'static str, String)> = None;
for (key, value) in std::mem::take(&mut patch_map) {
if let Some(structural) = StructuralKey::from_wire(&key) {
match parse_structural_entries(structural, value) {
Ok(parsed) => ops.extend(parsed),
Err(reason) => {
bad_structural_key = Some((structural.wire_name(), reason));
break;
}
}
} else if SPACE_METADATA_FIELDS.contains(&key.as_str()) {
clean_patch.insert(key, value);
} else {
unknown_keys.push(key);
}
}
if let Some((canonical, reason)) = bad_structural_key {
not_updated.insert(
id_str,
json!({
"type": "invalidProperties",
"properties": [canonical],
"description": reason,
}),
);
continue;
}
if !unknown_keys.is_empty() {
not_updated.insert(
id_str,
json!({ "type": "invalidProperties", "properties": unknown_keys }),
);
continue;
}
if ops.is_empty() && clean_patch.is_empty() {
not_updated.insert(
id_str,
json!({ "type": "invalidPatch", "description": "patch contains no valid fields" }),
);
continue;
}
if ops.iter().any(|op| match op {
SpacePatchOp::AddRole(role) => role.position == 0,
SpacePatchOp::UpdateRole { patch, .. } => patch.position == Some(0),
_ => false,
}) {
not_updated.insert(
id_str,
json!({
"type": "invalidProperties",
"properties": ["position"],
"description":
"SpaceRole.position 0 is reserved for the implicit @everyone role; defined roles MUST have position > 0 (draft-atwood-jmap-chat-00 §SpaceRole)",
}),
);
continue;
}
if !ops.is_empty() {
match check_space_count_limits(
backend,
caller,
&account_id,
&id,
&ops,
&space_limits,
)
.await
{
Ok(Some(err)) => {
not_updated.insert(id_str, set_error_value(&err));
continue;
}
Ok(None) => {}
Err(je) => return Err(je),
}
}
if !ops.is_empty() {
match backend
.apply_space_patch(caller, &account_id, &id, ops)
.await
{
Ok(op_results) => {
if let Some(first_err) =
op_results.iter().find_map(|r| r.outcome.as_ref().err())
{
not_updated.insert(id_str, set_error_value(first_err));
continue;
}
}
Err(BackendSetError::SetError(set_err)) => {
not_updated.insert(id_str, set_error_value(&set_err));
continue;
}
Err(BackendSetError::Other(e)) => {
not_updated.insert(id_str, server_fail_value_from_backend(&e));
continue;
}
Err(_) => {
not_updated.insert(
id_str,
json!({
"type": "serverFail",
"description": "unhandled backend error variant",
}),
);
continue;
}
}
}
if clean_patch.is_empty() {
mutated = true;
updated.insert(id_str, Value::Null);
continue;
}
let typed_patch: jmap_chat_types::SpaceMetadataPatch =
match serde_json::from_value(Value::Object(clean_patch)) {
Ok(p) => p,
Err(e) => {
not_updated.insert(
id_str,
json!({
"type": "invalidProperties",
"description": format!("metadata patch failed to deserialize: {e}"),
}),
);
continue;
}
};
match backend
.apply_space_metadata_patch(caller, &account_id, &id, typed_patch)
.await
{
Ok(Some(obj)) => {
mutated = true;
updated.insert(
id_str,
serde_json::to_value(&obj)
.expect("derive(Serialize) on plain data is infallible"),
);
}
Ok(None) => {
mutated = true;
updated.insert(id_str, Value::Null);
}
Err(BackendSetError::SetError(set_err)) => {
not_updated.insert(id_str, set_error_value(&set_err));
}
Err(BackendSetError::Other(e)) => {
not_updated.insert(id_str, server_fail_value_from_backend(&e));
}
Err(_) => {
not_updated.insert(
id_str,
json!({
"type": "serverFail",
"description": "unhandled backend error variant",
}),
);
}
}
}
}
if let Some(destroy_arr) = args.get("destroy").and_then(|v| v.as_array()) {
if let Some(bad) = destroy_arr.iter().find(|v| !v.is_string()) {
return Err(JmapError::invalid_arguments(format!(
"destroy: every element must be a string Id; got {bad}"
)));
}
for id_val in destroy_arr {
let Some(id_str) = id_val.as_str() else {
continue; };
let id = Id::from(id_str);
match backend
.destroy_object::<Space>(caller, &account_id, &id)
.await
{
Ok(()) => {
mutated = true;
destroyed_list.push(Value::String(id_str.to_owned()));
}
Err(BackendSetError::SetError(set_err)) => {
not_destroyed.insert(id_str.to_owned(), set_error_value(&set_err));
}
Err(BackendSetError::Other(e)) => {
not_destroyed.insert(id_str.to_owned(), server_fail_value_from_backend(&e));
}
Err(_) => {
not_destroyed.insert(
id_str.to_owned(),
json!({
"type": "serverFail",
"description": "unhandled backend error variant",
}),
);
}
}
}
}
finalize_set_response::<B, Space>(
backend,
caller,
&account_id,
old_state,
mutated,
SetAccumulators {
created,
updated,
destroyed: destroyed_list,
not_created,
not_updated,
not_destroyed,
},
)
.await
}
pub async fn handle_space_join<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
) -> Result<(Value, Vec<Invocation>), JmapError> {
let (account_id, args) = extract_account_id(args)?;
let caller_identity: Id = B::principal_id(caller)
.cloned()
.unwrap_or_else(|| account_id.clone());
let invite_code = args
.get("inviteCode")
.and_then(|v| v.as_str())
.map(|s| s.to_owned());
let space_id_str = args
.get("spaceId")
.and_then(|v| v.as_str())
.map(|s| s.to_owned());
let (space_id, current_members, invite_update): (Id, Vec<Value>, Option<(Id, u64)>) =
match (invite_code, space_id_str) {
(Some(_), Some(_)) | (None, None) => {
return Err(JmapError::invalid_arguments(
"exactly one of inviteCode or spaceId must be provided",
));
}
(Some(code), None) => {
let (invites, _) = backend
.get_objects::<SpaceInvite>(caller, &account_id, None, None)
.await
.map_err(|e| server_fail_from_backend(&e))?;
let invite = invites
.into_iter()
.find(|inv| inv.code.as_bytes().ct_eq(code.as_bytes()).into())
.ok_or_else(|| JmapError::invalid_arguments("invite code not found"))?;
if let Some(expires_at) = &invite.expires_at {
let now = now_utc_string();
if !iso8601_before(&now, expires_at) {
return Err(JmapError::invalid_arguments("invite has expired"));
}
}
if let Some(max) = invite.max_uses {
if invite.uses >= max {
return Err(JmapError::invalid_arguments(
"invite has reached its maximum number of uses",
));
}
}
let invite_id = invite.id.clone();
let new_uses = invite.uses.saturating_add(1);
let space_id = invite.space_id.clone();
let (spaces, _) = backend
.get_objects::<Space>(
caller,
&account_id,
Some(std::slice::from_ref(&space_id)),
None,
)
.await
.map_err(|e| server_fail_from_backend(&e))?;
let members: Vec<Value> = spaces
.into_iter()
.next()
.map(|s| {
s.members
.into_iter()
.map(serde_json::to_value)
.collect::<Result<Vec<_>, _>>()
})
.transpose()
.map_err(|e| server_fail_from_backend(&e))?
.unwrap_or_default();
(space_id, members, Some((invite_id, new_uses)))
}
(None, Some(sid)) => {
let space_id_typed = Id::from(sid.as_str());
let (spaces, _) = backend
.get_objects::<Space>(caller, &account_id, Some(&[space_id_typed]), None)
.await
.map_err(|e| server_fail_from_backend(&e))?;
let space = spaces
.into_iter()
.next()
.filter(|s| s.is_public)
.ok_or_else(JmapError::forbidden)?;
let space_id = space.id.clone();
let members: Vec<Value> = space
.members
.into_iter()
.map(serde_json::to_value)
.collect::<Result<Vec<_>, _>>()
.map_err(|e| server_fail_from_backend(&e))?;
(space_id, members, None)
}
};
let now_str = now_utc_string();
let mut new_members = current_members;
let already_member = new_members
.iter()
.any(|m| m.get("id").and_then(|v| v.as_str()) == Some(caller_identity.as_ref()));
if already_member {
return Err(JmapError::invalid_arguments(
"caller is already a member of this space",
));
}
new_members.push(json!({
"id": caller_identity.as_ref(),
"roleIds": [],
"joinedAt": now_str,
}));
let mut members_patch = serde_json::Map::new();
members_patch.insert("members".to_owned(), json!(new_members));
backend
.update_object::<Space>(
caller,
&account_id,
&space_id,
PatchObject::from_map(members_patch),
)
.await
.map_err(|e: jmap_server::BackendSetError<_>| server_fail_from_backend(&e))?;
let (post_spaces, _) = backend
.get_objects::<Space>(
caller,
&account_id,
Some(std::slice::from_ref(&space_id)),
None,
)
.await
.map_err(|e| server_fail_from_backend(&e))?;
let post_members: Vec<Value> = post_spaces
.into_iter()
.next()
.map(|s| {
s.members
.into_iter()
.map(serde_json::to_value)
.collect::<Result<Vec<_>, _>>()
})
.transpose()
.map_err(|e| server_fail_from_backend(&e))?
.unwrap_or_default();
let duplicate_count = post_members
.iter()
.filter(|m| m.get("id").and_then(|v| v.as_str()) == Some(caller_identity.as_ref()))
.count();
if duplicate_count > 1 {
let deduped = dedup_caller_members(post_members, caller_identity.as_ref());
let mut deduped_patch = serde_json::Map::new();
deduped_patch.insert("members".to_owned(), json!(deduped));
backend
.update_object::<Space>(
caller,
&account_id,
&space_id,
PatchObject::from_map(deduped_patch),
)
.await
.map_err(|e: jmap_server::BackendSetError<_>| server_fail_from_backend(&e))?;
}
if let Some((invite_id, new_uses)) = invite_update {
let mut uses_patch = serde_json::Map::new();
uses_patch.insert("uses".to_owned(), json!(new_uses));
backend
.update_object::<SpaceInvite>(
caller,
&account_id,
&invite_id,
PatchObject::from_map(uses_patch),
)
.await
.map_err(|e: jmap_server::BackendSetError<_>| server_fail_from_backend(&e))?;
}
Ok((
json!({ "accountId": account_id.as_ref(), "spaceId": space_id.as_ref() }),
vec![],
))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn dedup_caller_members_keeps_single_entry() {
let input = vec![json!({"id": "a1", "joinedAt": "2026-01-01T00:00:00.000Z"})];
let out = dedup_caller_members(input, "a1");
assert_eq!(out.len(), 1);
assert_eq!(out[0]["id"], "a1");
}
#[test]
fn dedup_caller_members_collapses_duplicates() {
let input = vec![
json!({"id": "a1", "joinedAt": "2026-01-01T00:00:00.000Z"}),
json!({"id": "a1", "joinedAt": "2026-01-01T00:00:00.001Z"}),
];
let out = dedup_caller_members(input, "a1");
assert_eq!(out.len(), 1);
assert_eq!(out[0]["id"], "a1");
assert_eq!(out[0]["joinedAt"], "2026-01-01T00:00:00.000Z");
}
#[test]
fn dedup_caller_members_collapses_three_duplicates() {
let input = vec![
json!({"id": "a1"}),
json!({"id": "a1"}),
json!({"id": "a1"}),
];
let out = dedup_caller_members(input, "a1");
assert_eq!(out.len(), 1);
assert_eq!(out[0]["id"], "a1");
}
#[test]
fn dedup_caller_members_preserves_other_members() {
let input = vec![
json!({"id": "u2"}),
json!({"id": "a1"}),
json!({"id": "u3"}),
json!({"id": "a1"}),
json!({"id": "u4"}),
];
let out = dedup_caller_members(input, "a1");
assert_eq!(out.len(), 4);
let ids: Vec<&str> = out
.iter()
.filter_map(|m| m.get("id").and_then(|v| v.as_str()))
.collect();
assert_eq!(ids, vec!["u2", "a1", "u3", "u4"]);
}
#[test]
fn dedup_caller_members_empty() {
let out = dedup_caller_members(vec![], "a1");
assert!(out.is_empty());
}
#[test]
fn dedup_caller_members_skips_malformed_entries() {
let input = vec![
json!({"joinedAt": "2026-01-01T00:00:00.000Z"}), json!({"id": 42}), json!({"id": "a1"}),
];
let out = dedup_caller_members(input, "a1");
assert_eq!(out.len(), 3);
}
}