use std::collections::BTreeMap;
use jmap_tasks_types::{Filter, Task, TaskComparator, TaskFilter, TaskFilterCondition};
use jmap_types::{Id, Invocation, JmapError, PatchObject, UTCDate};
use serde::Deserialize;
use serde_json::{Value, json};
use crate::TasksBackend;
use crate::helpers::{
SetAccumulators, check_metadata_entry, enforce_max_objects_in_set, extract_account_id,
finalize_set_response, reject_unsupported_sort, resolve_refs,
};
use jmap_server::{
HandlerOutput, QueryParams, backend_set_error_value, bool_arg, check_read_only_patch,
filter_arg, optional_arg, query_anchor_args, reject_server_set, server_fail_from_backend,
server_fail_value_from_backend,
};
pub async fn handle_task_get<B: TasksBackend>(
backend: &B,
caller: &B::CallerCtx,
mut args: Value,
using: &[String],
) -> Result<HandlerOutput, JmapError> {
let mut strip: Vec<&str> = Vec::new();
let (want_start, want_due) = match args.get_mut("properties") {
None | Some(Value::Null) => (false, false),
Some(Value::Array(props)) => {
let has = |name: &str| props.iter().any(|p| p == name);
let wanted = (has("utcStart"), has("utcDue"));
if wanted.0 || wanted.1 {
strip = ["start", "due", "timeZone", "timeZones"]
.into_iter()
.filter(|name| !has(name))
.collect();
props.extend(strip.iter().map(|name| json!(name)));
}
wanted
}
_ => (false, false),
};
let account_id: Id = args
.get("accountId")
.and_then(|v| v.as_str())
.ok_or_else(|| JmapError::invalid_arguments("accountId is required"))
.and_then(|s| {
Id::new_validated(s).map_err(|e| {
JmapError::invalid_arguments(format!("accountId is not a valid Id: {e}"))
})
})?;
let time_zone: Option<String> = match args.as_object_mut().and_then(|a| a.remove("timeZone")) {
None | Some(Value::Null) => None,
Some(Value::String(s)) => Some(s),
Some(v) => {
return Err(JmapError::invalid_arguments(format!(
"timeZone: expected a string, got {}",
jmap_server::json_type_name(&v)
)));
}
};
let HandlerOutput {
primary: mut response,
extra_invocations: tail,
..
} = jmap_server::handle_get_with_metadata::<Task, B>(backend, caller, args, using).await?;
if (want_start || want_due)
&& let Some(Value::Array(list)) = response.get_mut("list")
{
for item in list.iter_mut() {
if let Ok(task) = Task::deserialize(&*item) {
let (utc_start, utc_due) = backend
.compute_utc_times(caller, &account_id, &task, time_zone.as_deref())
.await;
let pairs = [
(want_start, "utcStart", task.start.is_some(), utc_start),
(want_due, "utcDue", task.due.is_some(), utc_due),
];
for (wanted, key, has_local, utc) in pairs {
match (wanted, has_local, utc) {
(true, false, _) => item[key] = Value::Null,
(true, true, Some(d)) => item[key] = Value::String(d.into_inner()),
_ => {}
}
}
}
if let Some(obj) = item.as_object_mut() {
for name in &strip {
obj.remove(*name);
}
}
}
}
Ok(HandlerOutput::new(response).with_extra(tail))
}
pub async fn handle_task_changes<B: TasksBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
using: &[String],
) -> Result<HandlerOutput, JmapError> {
jmap_server::handle_changes::<Task, B>(backend, caller, args, using).await
}
const TASK_ID_PROPERTIES: &[&str] = &["taskListId"];
pub async fn handle_task_set<B: TasksBackend>(
backend: &B,
caller: &B::CallerCtx,
created_ids: &BTreeMap<Id, Id>,
args: Value,
using: &[String],
) -> Result<HandlerOutput, JmapError> {
let (account_id, mut args) = extract_account_id(args)?;
if !backend
.account_exists(caller, &account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?
{
return Err(JmapError::account_not_found());
}
enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;
let old_state = backend
.get_state::<Task>(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_in_state != old_state.as_ref()
{
return Err(JmapError::state_mismatch());
}
let ctx = SetCtx {
backend,
caller,
account_id: &account_id,
created_ids,
using,
};
let mut acc = SetAccumulators::default();
let mut mutated = set_create(&ctx, &mut args, &mut acc).await?;
jmap_server::resolve_set_id_refs(&mut args, created_ids, &acc.created);
mutated |= set_update(&ctx, &mut args, &mut acc).await?;
mutated |= set_destroy(&ctx, &mut args, &mut acc).await?;
finalize_set_response::<B, Task>(backend, caller, &account_id, old_state, mutated, acc).await
}
struct SetCtx<'a, B: TasksBackend> {
backend: &'a B,
caller: &'a B::CallerCtx,
account_id: &'a Id,
created_ids: &'a BTreeMap<Id, Id>,
using: &'a [String],
}
async fn set_create<B: TasksBackend>(
ctx: &SetCtx<'_, B>,
args: &mut serde_json::Map<String, Value>,
acc: &mut SetAccumulators,
) -> Result<bool, JmapError> {
let mut mutated = false;
if let Some(Value::Object(create_map)) = args.remove("create") {
for (create_id, mut obj_val) in create_map {
if let Some(err) = obj_val.as_object().and_then(reject_server_set::<Task>) {
acc.not_created
.insert(create_id, serde_json::Value::from(&err));
continue;
}
if let Some(Err(err)) = obj_val
.as_object()
.map(|o| check_metadata_entry(o, true, ctx.using))
{
acc.not_created
.insert(create_id, serde_json::Value::from(&*err));
continue;
}
if let Err(err) = resolve_refs(&mut obj_val, TASK_ID_PROPERTIES, ctx.created_ids) {
acc.not_created
.insert(create_id, serde_json::Value::from(&*err));
continue;
}
if let Some(prop) = obj_val
.as_object()
.and_then(|o| o.iter().find(|(_, v)| has_bad_person_uri(v)))
.map(|(k, _)| k.clone())
{
acc.not_created.insert(create_id, person_uri_error(&prop));
continue;
}
let mut task: Task = match serde_path_to_error::deserialize(obj_val) {
Ok(t) => t,
Err(e) => {
let mut err =
json!({ "type": "invalidProperties", "description": e.to_string() });
if let Some(serde_path_to_error::Segment::Map { key }) = e.path().iter().next()
{
err["properties"] = json!([key]);
}
acc.not_created.insert(create_id, err);
continue;
}
};
let build = move |id: &Id| {
task.id = Some(id.clone());
task
};
match ctx
.backend
.create_object::<Task, _>(ctx.caller, ctx.account_id, &create_id, build)
.await
{
Ok((_new_id, created_obj)) => {
mutated = true;
acc.created
.insert(create_id, jmap_server::serialize_value(&created_obj)?);
}
Err(e) => {
acc.not_created
.insert(create_id, backend_set_error_value(e));
}
}
}
}
Ok(mutated)
}
async fn set_update<B: TasksBackend>(
ctx: &SetCtx<'_, B>,
args: &mut serde_json::Map<String, Value>,
acc: &mut SetAccumulators,
) -> Result<bool, JmapError> {
let mut mutated = false;
if let Some(Value::Object(update_map)) = args.remove("update") {
for (id_str, patch_val) in update_map {
mutated |= update_one(ctx, id_str, patch_val, acc).await?;
}
}
Ok(mutated)
}
async fn update_one<B: TasksBackend>(
ctx: &SetCtx<'_, B>,
id_str: String,
mut patch_val: Value,
acc: &mut SetAccumulators,
) -> Result<bool, JmapError> {
let id = match jmap_server::parse_wire_id(&id_str, "id") {
Ok(id) => id,
Err(err) => {
acc.not_updated
.insert(id_str, serde_json::Value::from(&*err));
return Ok(false);
}
};
if let Err(err) = resolve_refs(&mut patch_val, TASK_ID_PROPERTIES, ctx.created_ids) {
acc.not_updated
.insert(id_str, serde_json::Value::from(&*err));
return Ok(false);
}
if let Some(prop) = patch_val.as_object().and_then(bad_person_uri_in_patch) {
acc.not_updated.insert(id_str, person_uri_error(&prop));
return Ok(false);
}
let mut patch = match serde_json::from_value::<PatchObject>(patch_val) {
Ok(p) => p,
Err(e) => {
acc.not_updated.insert(
id_str,
json!({ "type": "invalidPatch", "description": e.to_string() }),
);
return Ok(false);
}
};
match check_read_only_patch::<_, Task>(
ctx.backend,
ctx.caller,
ctx.account_id,
&id,
patch.as_map_mut(),
)
.await
{
Ok(false) => {}
Ok(true) => {
acc.updated.insert(id_str, Value::Null);
return Ok(false);
}
Err(err) => {
acc.not_updated.insert(id_str, err);
return Ok(false);
}
}
let is_per_user_only = patch_is_per_user_only(&patch);
if let Err(err) = check_metadata_entry(patch.as_map(), false, ctx.using) {
acc.not_updated
.insert(id_str, serde_json::Value::from(&*err));
return Ok(false);
}
let update_result = if is_per_user_only {
ctx.backend
.update_task_per_user(ctx.caller, ctx.account_id, &id, patch)
.await
} else {
ctx.backend
.update_object::<Task>(ctx.caller, ctx.account_id, &id, patch)
.await
};
match update_result {
Ok(Some(obj)) => {
acc.updated
.insert(id_str, jmap_server::serialize_value(&obj)?);
Ok(true)
}
Ok(None) => {
acc.updated.insert(id_str, Value::Null);
Ok(true)
}
Err(e) => {
acc.not_updated.insert(id_str, backend_set_error_value(e));
Ok(false)
}
}
}
fn patch_is_per_user_only(patch: &PatchObject) -> bool {
patch.as_map().keys().all(|k| {
let head = k.split('/').next().unwrap_or(k);
jmap_tasks_types::is_per_user_task_property(head)
})
}
async fn set_destroy<B: TasksBackend>(
ctx: &SetCtx<'_, B>,
args: &mut serde_json::Map<String, Value>,
acc: &mut SetAccumulators,
) -> Result<bool, JmapError> {
let mut mutated = false;
if let Some(Value::Array(destroy_arr)) = args.remove("destroy") {
let id_strs: Vec<&str> = destroy_arr
.iter()
.map(|v| {
v.as_str().ok_or_else(|| {
JmapError::invalid_arguments(format!(
"destroy: every element must be a string Id; got {}",
jmap_server::json_type_name(v)
))
})
})
.collect::<Result<_, _>>()?;
for id_str in id_strs {
let id_str = id_str.to_owned();
let id = match jmap_server::parse_wire_id(&id_str, "id") {
Ok(id) => id,
Err(err) => {
acc.not_destroyed
.insert(id_str, serde_json::Value::from(&*err));
continue;
}
};
match ctx
.backend
.destroy_object::<Task>(ctx.caller, ctx.account_id, &id)
.await
{
Ok(()) => {
mutated = true;
acc.destroyed.push(Value::String(id_str));
}
Err(e) => {
acc.not_destroyed.insert(id_str, backend_set_error_value(e));
}
}
}
}
Ok(mutated)
}
fn has_bad_person_uri(value: &Value) -> bool {
match value {
Value::Object(m) => {
let bad_here = m.get("@type").and_then(Value::as_str) == Some("Person")
&& m.get("uri")
.and_then(Value::as_str)
.is_some_and(|u| jmap_types::uri::check_uri(u).is_err());
bad_here || m.values().any(has_bad_person_uri)
}
Value::Array(a) => a.iter().any(has_bad_person_uri),
_ => false,
}
}
fn bad_person_uri_in_patch(patch: &serde_json::Map<String, Value>) -> Option<String> {
patch.iter().find_map(|(path, v)| {
let direct = (path.ends_with("/assignee/uri") || path.ends_with("/author/uri"))
&& v.as_str()
.is_some_and(|u| jmap_types::uri::check_uri(u).is_err());
(direct || has_bad_person_uri(v)).then(|| path.split('/').next().unwrap_or(path).to_owned())
})
}
fn person_uri_error(property: &str) -> Value {
json!({
"type": "invalidProperties",
"properties": [property],
"description": "a Person uri is not an RFC 3986 URI",
})
}
pub async fn handle_task_copy<B: TasksBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
call_id: &str,
using: &[String],
) -> Result<HandlerOutput, JmapError> {
let (to_account_id, mut args) = extract_account_id(args)?;
if !backend
.account_exists(caller, &to_account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?
{
return Err(JmapError::account_not_found());
}
let from_account_id_str = args
.remove("fromAccountId")
.and_then(|v| v.as_str().map(|s| s.to_owned()))
.ok_or_else(|| JmapError::invalid_arguments("fromAccountId is required"))?;
let from_account_id = Id::new_validated(from_account_id_str)
.map_err(|e| JmapError::invalid_arguments(format!("fromAccountId: {e}")))?;
if from_account_id == to_account_id {
return Err(JmapError::invalid_arguments(
"fromAccountId must be different from accountId",
));
}
if !backend
.account_exists(caller, &from_account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?
{
return Err(JmapError::from_account_not_found());
}
let Some(Value::Object(create_map)) = args.remove("create") else {
return Err(JmapError::invalid_arguments("create is required"));
};
if let Some(if_from_in_state) = args.get("ifFromInState").and_then(|v| v.as_str()) {
let from_state = backend
.get_state::<Task>(caller, &from_account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?;
if if_from_in_state != from_state.as_ref() {
return Err(JmapError::state_mismatch());
}
}
let old_state = backend
.get_state::<Task>(caller, &to_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_in_state != old_state.as_ref()
{
return Err(JmapError::state_mismatch());
}
let on_success_destroy_original: bool = bool_arg(&args, "onSuccessDestroyOriginal", false);
let destroy_from_if_in_state: Option<String> = args
.get("destroyFromIfInState")
.and_then(|v| v.as_str())
.map(|s| s.to_owned());
let mut created = serde_json::Map::new();
let mut not_created = serde_json::Map::new();
let mut mutated = false;
let mut copied_source_ids: Vec<(String, Id)> = Vec::new();
for (create_id, client_val) in create_map {
let Some(source_id_str) = client_val.get("id").and_then(|v| v.as_str()) else {
not_created.insert(
create_id,
json!({"type": "invalidProperties", "properties": ["id"]}),
);
continue;
};
let source_id: Id = match jmap_server::parse_wire_id(source_id_str, "id") {
Ok(id) => id,
Err(err) => {
not_created.insert(create_id, serde_json::Value::from(&*err));
continue;
}
};
let mut source_tasks: Vec<Task> = match backend
.get_objects::<Task>(
caller,
&from_account_id,
Some(std::slice::from_ref(&source_id)),
None,
)
.await
{
Ok((objs, not_found)) => {
if !not_found.is_empty() || objs.is_empty() {
not_created.insert(create_id, json!({"type": "notFound"}));
continue;
}
objs
}
Err(e) => {
not_created.insert(create_id, server_fail_value_from_backend(&e));
continue;
}
};
if let Some(Err(err)) = client_val
.as_object()
.map(|o| check_metadata_entry(o, true, using))
{
not_created.insert(create_id, Value::from(&*err));
continue;
}
let info = backend.metadata_info::<Task>(caller, &to_account_id);
if !jmap_server::uses_metadata(using) || !info.as_ref().is_some_and(|i| i.supports_private)
{
source_tasks[0].private_metadata = None;
}
if info.is_none() {
source_tasks[0].metadata = None;
}
let Ok(Value::Object(mut merged)) = serde_json::to_value(&source_tasks[0]) else {
not_created.insert(
create_id,
json!({
"type": "serverFail",
"description": "failed to serialize source Task",
}),
);
continue;
};
if let Value::Object(client_props) = &client_val {
for (k, v) in client_props {
if k != "id" {
merged.insert(k.clone(), v.clone());
}
}
}
merged.remove("id");
if let Some(prop) = merged
.iter()
.find(|(_, v)| has_bad_person_uri(v))
.map(|(k, _)| k.clone())
{
not_created.insert(create_id, person_uri_error(&prop));
continue;
}
let task: Task = match serde_path_to_error::deserialize(Value::Object(merged)) {
Ok(t) => t,
Err(e) => {
let mut err = json!({ "type": "invalidProperties", "description": e.to_string() });
if let Some(serde_path_to_error::Segment::Map { key }) = e.path().iter().next() {
err["properties"] = json!([key]);
}
not_created.insert(create_id, err);
continue;
}
};
match backend
.copy_object(caller, &from_account_id, &to_account_id, task, &client_val)
.await
{
Ok((_new_id, created_task)) => {
mutated = true;
created.insert(
create_id.clone(),
jmap_server::serialize_value(&created_task)?,
);
copied_source_ids.push((create_id, source_id));
}
Err(e) => {
not_created.insert(create_id, backend_set_error_value(e));
}
}
}
let new_state = if mutated {
backend
.get_state::<Task>(caller, &to_account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?
} else {
old_state.clone()
};
let resp = json!({
"fromAccountId": from_account_id.as_ref(),
"accountId": to_account_id.as_ref(),
"oldState": old_state.as_ref(),
"newState": new_state.as_ref(),
"created": if created.is_empty() { Value::Null } else { Value::Object(created) },
"notCreated": if not_created.is_empty() { Value::Null } else { Value::Object(not_created) },
});
let mut extra: Vec<Invocation> = Vec::new();
if on_success_destroy_original && !copied_source_ids.is_empty() {
let from_old_state = backend
.get_state::<Task>(caller, &from_account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?;
let mut destroy_state_mismatch = false;
if let Some(if_state) = destroy_from_if_in_state.as_deref()
&& if_state != from_old_state.as_ref()
{
destroy_state_mismatch = true;
}
let mut destroyed_arr: Vec<Value> = Vec::new();
let mut not_destroyed = serde_json::Map::new();
if !destroy_state_mismatch {
for (_, source_id) in &copied_source_ids {
match backend
.destroy_object::<Task>(caller, &from_account_id, source_id)
.await
{
Ok(()) => {
destroyed_arr.push(Value::String(source_id.as_ref().to_owned()));
}
Err(e) => {
not_destroyed
.insert(source_id.as_ref().to_owned(), backend_set_error_value(e));
}
}
}
}
let from_new_state = backend
.get_state::<Task>(caller, &from_account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?;
let set_resp = if destroy_state_mismatch {
json!({
"type": "stateMismatch",
})
} else {
json!({
"accountId": from_account_id.as_ref(),
"oldState": from_old_state.as_ref(),
"newState": from_new_state.as_ref(),
"created": Value::Null,
"updated": Value::Null,
"destroyed": if destroyed_arr.is_empty() { Value::Null } else { Value::Array(destroyed_arr) },
"notCreated": Value::Null,
"notUpdated": Value::Null,
"notDestroyed": if not_destroyed.is_empty() { Value::Null } else { Value::Object(not_destroyed) },
})
};
let method_name = if destroy_state_mismatch {
"error".to_owned()
} else {
"Task/set".to_owned()
};
extra.push(Invocation::new(method_name, set_resp, call_id.to_owned()));
}
Ok(HandlerOutput::new(resp).with_extra(extra))
}
pub async fn handle_task_query<B: TasksBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
using: &[String],
) -> Result<HandlerOutput, JmapError> {
jmap_server::reject_metadata_filter_arg(
&args,
jmap_tasks_types::TaskFilterCondition::has_metadata_condition,
using,
)?;
reject_unsupported_sort::<TaskComparator>(args.get("sort"))?;
let (account_id, mut args) = extract_account_id(args)?;
if !backend
.account_exists(caller, &account_id)
.await
.map_err(|e| server_fail_from_backend(&e))?
{
return Err(JmapError::account_not_found());
}
jmap_server::I18nProjection::from_args::<Task>(
&mut args,
&[],
backend.i18n_info(caller, &account_id).as_ref(),
)?;
let calculate_total = bool_arg(&args, "calculateTotal", false);
let limit: Option<u64> = match args.get("limit") {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_u64().ok_or_else(|| {
JmapError::invalid_arguments(format!(
"limit: expected a non-negative integer, got {}",
jmap_server::json_type_name(v)
))
})?),
};
let position: i64 = match args.get("position") {
None | Some(Value::Null) => 0,
Some(v) => v.as_i64().ok_or_else(|| {
JmapError::invalid_arguments(format!(
"position: expected an integer, got {}",
jmap_server::json_type_name(v)
))
})?,
};
let (anchor, anchor_offset) = query_anchor_args(&args)?;
let filter: Option<TaskFilter> = filter_arg(&mut args)?;
let sort: Option<Vec<TaskComparator>> = optional_arg(&mut args, "sort", || {
JmapError::invalid_arguments("sort must be an array")
})?;
let expand_recurrences = bool_arg(&args, "expandRecurrences", false);
let time_zone: Option<String> = optional_arg(&mut args, "timeZone", || {
JmapError::invalid_arguments("timeZone must be a string")
})?;
if expand_recurrences {
let condition = match &filter {
Some(Filter::Condition(c)) if c.before.is_some() && c.after.is_some() => c,
_ => {
return Err(JmapError::invalid_arguments(
"expandRecurrences requires a FilterCondition with both 'before' and 'after'",
));
}
};
if let Some(secs) = expand_duration_seconds(condition)
&& u64::try_from(secs).is_ok_and(|secs| {
secs > backend
.limits(caller, &account_id)
.max_expanded_query_duration_seconds
})
{
return Err(JmapError::custom("expandDurationTooLarge"));
}
}
let query_args = crate::TaskQueryArgs::default()
.with_expand_recurrences(expand_recurrences)
.with_time_zone(time_zone);
let result = backend
.query_tasks(
caller,
&account_id,
QueryParams::new()
.filter(filter.as_ref())
.sort(sort.as_deref())
.limit(limit)
.position(position)
.anchor(anchor.as_ref())
.anchor_offset(anchor_offset),
&query_args,
)
.await
.map_err(JmapError::from)?;
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,
});
if calculate_total && let Some(t) = result.total {
resp["total"] = json!(t);
}
Ok(HandlerOutput::new(resp))
}
pub(crate) fn expand_duration_seconds(condition: &TaskFilterCondition) -> Option<i64> {
let epoch = |local: &jmap_tasks_types::LocalDateTime| {
UTCDate::from(format!("{local}Z")).to_epoch_seconds().ok()
};
Some(epoch(condition.before.as_ref()?)? - epoch(condition.after.as_ref()?)?)
}
pub async fn handle_task_query_changes<B: TasksBackend>(
backend: &B,
caller: &B::CallerCtx,
args: Value,
using: &[String],
) -> Result<HandlerOutput, JmapError> {
jmap_server::reject_metadata_filter_arg(
&args,
jmap_tasks_types::TaskFilterCondition::has_metadata_condition,
using,
)?;
reject_unsupported_sort::<TaskComparator>(args.get("sort"))?;
jmap_server::handle_query_changes::<Task, B>(backend, caller, args).await
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use crate::test_support::MockBackend;
#[tokio::test]
async fn query_unlisted_sort_property_returns_unsupported_sort() {
let backend = MockBackend::new_with_account("acc1");
for property in ["title", "recurrenceId"] {
let args = json!({ "accountId": "acc1", "sort": [{ "property": property }] });
let err = handle_task_query(&backend, &(), args, &[])
.await
.expect_err("unlisted sort property must be rejected");
assert_eq!(err.error_type.to_string(), "unsupportedSort", "{property}");
}
}
#[tokio::test]
async fn query_changes_unlisted_sort_property_returns_unsupported_sort() {
let backend = MockBackend::new_with_account("acc1");
let args = json!({
"accountId": "acc1",
"sinceQueryState": "0",
"sort": [{ "property": "start" }, { "property": "title" }]
});
let err = handle_task_query_changes(&backend, &(), args, &[])
.await
.expect_err("unlisted sort property must be rejected");
assert_eq!(err.error_type.to_string(), "unsupportedSort");
}
#[tokio::test]
async fn query_listed_sort_property_is_accepted() {
let backend = MockBackend::new_with_account("acc1");
for property in ["id", "uid", "start", "created", "updated"] {
let args = json!({ "accountId": "acc1", "sort": [{ "property": property }] });
handle_task_query(&backend, &(), args, &[])
.await
.expect("listed sort property must not be rejected");
}
}
#[tokio::test]
async fn get_unknown_account_returns_account_not_found() {
let backend = MockBackend::new();
let args = json!({ "accountId": "unknown", "ids": null });
let result = handle_task_get(&backend, &(), args, &[]).await;
let err = result.expect_err("must return error for unknown account");
assert_eq!(err.error_type.to_string(), "accountNotFound");
}
#[tokio::test]
async fn copy_missing_from_account_id_returns_invalid_arguments() {
let backend = MockBackend::new_with_account("acc1");
let args = json!({
"accountId": "acc1",
"create": {}
});
let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
let err = result.expect_err("must return error when fromAccountId missing");
assert_eq!(err.error_type.to_string(), "invalidArguments");
}
#[tokio::test]
async fn copy_same_account_returns_invalid_arguments() {
let backend = MockBackend::new_with_account("acc1");
let args = json!({
"accountId": "acc1",
"fromAccountId": "acc1",
"create": {}
});
let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
let err = result.expect_err("must reject same-account Task/copy per RFC 8620 §5.4");
assert_eq!(err.error_type.to_string(), "invalidArguments");
}
#[tokio::test]
async fn copy_missing_or_malformed_create_returns_invalid_arguments() {
let mut backend = MockBackend::new_with_account("acc1");
backend.add_account("acc2");
for create in [None, Some(json!(null)), Some(json!(["t1"]))] {
let mut args = json!({
"accountId": "acc2",
"fromAccountId": "acc1",
"ifFromInState": "stale",
});
if let Some(create) = create.clone() {
args["create"] = create;
}
let err = handle_task_copy(&backend, &(), args, "c0", &[])
.await
.expect_err("create is required");
assert_eq!(
err.error_type.to_string(),
"invalidArguments",
"create {create:?}: {err:?}"
);
}
}
#[tokio::test]
async fn copy_unknown_from_account_returns_from_account_not_found() {
let backend = MockBackend::new_with_account("acc1");
let args = json!({
"accountId": "acc1",
"fromAccountId": "no-such-account",
"create": {}
});
let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
let err = result.expect_err("must reject unknown fromAccountId");
assert_eq!(err.error_type.to_string(), "fromAccountNotFound");
}
#[tokio::test]
async fn copy_if_from_in_state_mismatch_returns_state_mismatch() {
let mut backend = MockBackend::new_with_account("acc1");
backend.add_account("acc2");
let args = json!({
"accountId": "acc1",
"fromAccountId": "acc2",
"ifFromInState": "stale-source-state",
"create": {}
});
let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
let err = result.expect_err("must reject stale ifFromInState");
assert_eq!(err.error_type.to_string(), "stateMismatch");
}
#[tokio::test]
async fn copy_if_in_state_mismatch_returns_state_mismatch() {
let mut backend = MockBackend::new_with_account("acc1");
backend.add_account("acc2");
let args = json!({
"accountId": "acc1",
"fromAccountId": "acc2",
"ifInState": "stale-destination-state",
"create": {}
});
let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
let err = result.expect_err("must reject stale ifInState");
assert_eq!(err.error_type.to_string(), "stateMismatch");
}
#[tokio::test]
async fn copy_create_entry_without_id_returns_invalid_properties() {
let mut backend = MockBackend::new_with_account("acc1");
backend.add_account("acc2");
let args = json!({
"accountId": "acc1",
"fromAccountId": "acc2",
"create": { "c1": {} }
});
let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
.await
.expect("top-level call must succeed");
let nc = resp["notCreated"].as_object().expect("notCreated present");
let err = nc.get("c1").expect("c1 in notCreated");
assert_eq!(err["type"], "invalidProperties");
assert_eq!(err["properties"][0], "id");
}
#[tokio::test]
async fn copy_unknown_source_id_returns_not_found() {
let mut backend = MockBackend::new_with_account("acc1");
backend.add_account("acc2");
let args = json!({
"accountId": "acc1",
"fromAccountId": "acc2",
"create": { "c1": { "id": "no-such-task" } }
});
let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
.await
.expect("top-level call must succeed");
let nc = resp["notCreated"].as_object().expect("notCreated present");
assert_eq!(nc["c1"]["type"], "notFound");
}
#[tokio::test]
async fn copy_fetches_source_and_overlays_client_overrides() {
let mut backend = MockBackend::new_with_account("acc1");
backend.add_account("acc2");
backend.seed_task("acc2", "src1", true);
let args = json!({
"accountId": "acc1",
"fromAccountId": "acc2",
"create": {
"c1": { "id": "src1", "title": "Overridden title" }
}
});
let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
.await
.expect("top-level call must succeed");
let created = resp["created"].as_object().expect("created present");
let c1 = created.get("c1").expect("c1 in created");
assert_eq!(
c1["title"], "Overridden title",
"client-supplied title must override source value: {resp}"
);
}
#[tokio::test]
async fn copy_on_success_destroy_original_emits_implicit_task_set() {
let mut backend = MockBackend::new_with_account("acc1");
backend.add_account("acc2");
backend.seed_task("acc2", "src1", true);
let args = json!({
"accountId": "acc1",
"fromAccountId": "acc2",
"onSuccessDestroyOriginal": true,
"create": {
"c1": { "id": "src1" }
}
});
let HandlerOutput {
extra_invocations: extra,
..
} = handle_task_copy(&backend, &(), args, "c0", &[])
.await
.expect("top-level call must succeed");
assert_eq!(extra.len(), 1, "must emit one implicit Task/set: {extra:?}");
let Invocation {
name: method,
arguments: val,
call_id: ci,
} = &extra[0];
assert_eq!(method, "Task/set");
assert_eq!(ci, "c0");
assert_eq!(val["accountId"], "acc2", "implicit set targets fromAccount");
let destroyed = val["destroyed"]
.as_array()
.expect("destroyed must be array");
assert_eq!(destroyed.len(), 1);
assert_eq!(destroyed[0], "src1");
assert!(val.get("oldState").is_some(), "oldState must be present");
assert!(val.get("newState").is_some(), "newState must be present");
}
#[tokio::test]
async fn copy_destroy_from_if_in_state_mismatch_aborts_destroy() {
let mut backend = MockBackend::new_with_account("acc1");
backend.add_account("acc2");
backend.seed_task("acc2", "src1", true);
let args = json!({
"accountId": "acc1",
"fromAccountId": "acc2",
"onSuccessDestroyOriginal": true,
"destroyFromIfInState": "stale-source-state",
"create": {
"c1": { "id": "src1" }
}
});
let HandlerOutput {
extra_invocations: extra,
..
} = handle_task_copy(&backend, &(), args, "c0", &[])
.await
.expect("top-level call must succeed");
assert_eq!(extra.len(), 1);
let Invocation { arguments: val, .. } = &extra[0];
assert_eq!(val["type"], "stateMismatch");
}
#[tokio::test]
async fn copy_without_on_success_emits_no_extra_invocations() {
let mut backend = MockBackend::new_with_account("acc1");
backend.add_account("acc2");
backend.seed_task("acc2", "src1", true);
let args = json!({
"accountId": "acc1",
"fromAccountId": "acc2",
"create": {
"c1": { "id": "src1" }
}
});
let HandlerOutput {
extra_invocations: extra,
..
} = handle_task_copy(&backend, &(), args, "c0", &[])
.await
.expect("top-level call must succeed");
assert!(
extra.is_empty(),
"no extra invocations without onSuccessDestroyOriginal: {extra:?}"
);
}
#[tokio::test]
async fn set_empty_destroy_returns_valid_response() {
let backend = MockBackend::new_with_account("acc1");
let args = json!({ "accountId": "acc1", "destroy": [] });
let HandlerOutput { primary: resp, .. } =
handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
.await
.expect("must not return top-level error");
assert_eq!(resp["accountId"], "acc1");
}
#[tokio::test]
async fn set_is_draft_revert_rejected_when_current_is_false() {
let mut backend = MockBackend::new_with_account("acc1");
backend.seed_task("acc1", "t1", false);
let args = json!({
"accountId": "acc1",
"update": {
"t1": { "isDraft": true }
}
});
let HandlerOutput { primary: resp, .. } =
handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
.await
.expect("must not return a top-level error");
let not_updated = resp["notUpdated"]
.as_object()
.expect("notUpdated must be an object");
assert!(
not_updated.contains_key("t1"),
"t1 must appear in notUpdated: {resp}"
);
assert_eq!(
not_updated["t1"]["type"].as_str(),
Some("invalidProperties"),
"error type must be invalidProperties"
);
assert_eq!(
not_updated["t1"]["properties"][0].as_str(),
Some("isDraft"),
"properties must list isDraft"
);
}
#[tokio::test]
async fn set_is_draft_true_on_draft_task_passes_to_backend() {
let mut backend = MockBackend::new_with_account("acc1");
backend.seed_task("acc1", "t2", true);
let args = json!({
"accountId": "acc1",
"update": {
"t2": { "isDraft": true }
}
});
let HandlerOutput { primary: resp, .. } =
handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
.await
.expect("must not return a top-level error");
if let Some(not_updated) = resp["notUpdated"].as_object()
&& let Some(err) = not_updated.get("t2")
{
assert_ne!(
err["type"].as_str(),
Some("invalidProperties"),
"isDraft:true on an existing draft must not produce invalidProperties"
);
}
}
#[tokio::test]
async fn set_is_draft_false_passes_to_backend() {
let mut backend = MockBackend::new_with_account("acc1");
backend.seed_task("acc1", "t3", true);
let args = json!({
"accountId": "acc1",
"update": {
"t3": { "isDraft": false }
}
});
let HandlerOutput { primary: resp, .. } =
handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
.await
.expect("must not return a top-level error");
if let Some(not_updated) = resp["notUpdated"].as_object()
&& let Some(err) = not_updated.get("t3")
{
assert_ne!(
err["type"].as_str(),
Some("invalidProperties"),
"isDraft:false must never produce invalidProperties"
);
}
}
#[tokio::test]
async fn get_without_utc_properties_omits_utc_fields() {
let backend = MockBackend::new_with_account("acc1");
let args = json!({
"accountId": "acc1",
"ids": null,
"properties": ["id", "title"] });
let HandlerOutput { primary: resp, .. } = handle_task_get(&backend, &(), args, &[])
.await
.expect("must succeed");
assert_eq!(resp["accountId"], "acc1");
let list = resp["list"].as_array().expect("list must be an array");
for item in list {
assert!(
item.get("utcStart").is_none(),
"utcStart must not appear when not in properties"
);
}
}
#[tokio::test]
async fn get_with_utc_start_in_properties_does_not_error() {
let backend = MockBackend::new_with_account("acc1");
let args = json!({
"accountId": "acc1",
"ids": null,
"properties": ["id", "utcStart", "utcDue"]
});
let HandlerOutput { primary: resp, .. } = handle_task_get(&backend, &(), args, &[])
.await
.expect("must succeed with utcStart in properties");
assert_eq!(resp["accountId"], "acc1");
}
#[tokio::test]
async fn set_per_user_only_patch_routes_to_per_user_update() {
use std::sync::atomic::Ordering;
let backend = MockBackend::new_with_account("acc1");
let args = json!({
"accountId": "acc1",
"update": { "t1": { "color": "#ff0000" } }
});
let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
.await
.expect("must not return top-level error");
assert_eq!(
backend.per_user_calls.load(Ordering::Relaxed),
1,
"per-user-only patch must route to update_task_per_user"
);
}
#[tokio::test]
async fn set_per_user_json_pointer_patch_routes_to_per_user_update() {
use std::sync::atomic::Ordering;
let backend = MockBackend::new_with_account("acc1");
let args = json!({
"accountId": "acc1",
"update": {
"t1": {
"keywords/done": true,
"alerts/0/offset": null
}
}
});
let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
.await
.expect("must not return top-level error");
assert_eq!(
backend.per_user_calls.load(Ordering::Relaxed),
1,
"JSON-pointer patch on per-user properties must route to update_task_per_user"
);
}
#[tokio::test]
async fn set_identical_id_with_per_user_patch_routes_to_per_user_update() {
use std::sync::atomic::Ordering;
let mut backend = MockBackend::new_with_account("acc1");
backend.seed_task("acc1", "t1", false);
let args = json!({
"accountId": "acc1",
"update": { "t1": { "id": "t1", "keywords/done": true } }
});
let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
.await
.expect("must not return top-level error");
assert_eq!(
backend.per_user_calls.load(Ordering::Relaxed),
1,
"identical id must not move a per-user patch to update_object"
);
}
#[tokio::test]
async fn set_shared_property_patch_routes_to_update_object() {
use std::sync::atomic::Ordering;
let backend = MockBackend::new_with_account("acc1");
let args = json!({
"accountId": "acc1",
"update": { "t1": { "title": "New title" } }
});
let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
.await
.expect("must not return top-level error");
assert_eq!(
backend.per_user_calls.load(Ordering::Relaxed),
0,
"shared-property patch must NOT route to update_task_per_user"
);
}
#[tokio::test]
async fn set_shared_property_null_patch_routes_to_update_object() {
use std::sync::atomic::Ordering;
let backend = MockBackend::new_with_account("acc1");
let args = json!({
"accountId": "acc1",
"update": { "t1": { "title": null } }
});
let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
.await
.expect("must not return top-level error");
assert_eq!(
backend.per_user_calls.load(Ordering::Relaxed),
0,
"delete-shared-property patch must NOT route to update_task_per_user"
);
}
#[tokio::test]
async fn set_mixed_patch_routes_to_update_object() {
use std::sync::atomic::Ordering;
let backend = MockBackend::new_with_account("acc1");
let args = json!({
"accountId": "acc1",
"update": { "t1": { "color": "#ff0000", "title": "New" } }
});
let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
.await
.expect("must not return top-level error");
assert_eq!(
backend.per_user_calls.load(Ordering::Relaxed),
0,
"mixed patch must route to update_object"
);
}
#[tokio::test]
async fn set_empty_patch_routes_to_update_object() {
use std::sync::atomic::Ordering;
let backend = MockBackend::new_with_account("acc1");
let args = json!({
"accountId": "acc1",
"update": { "t1": {} }
});
let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
.await
.expect("must not return top-level error");
assert_eq!(
backend.per_user_calls.load(Ordering::Relaxed),
0,
"empty patch must NOT route to update_task_per_user"
);
}
#[tokio::test]
async fn set_non_string_destroy_element_does_not_echo_value() {
let backend = MockBackend::new_with_account("acc");
let args = json!({ "accountId": "acc", "destroy": [{ "note": "CANARY-zegc" }] });
let err = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
.await
.expect_err("non-string destroy element must be a method error");
assert_eq!(err.error_type.to_string(), "invalidArguments");
let desc = err.description.as_deref().unwrap_or_default();
assert!(desc.contains("got object"), "{desc}");
assert!(!desc.contains("CANARY"), "{desc}");
}
#[tokio::test]
async fn set_create_typed_parse_failure_names_property() {
let backend = MockBackend::new_with_account("acc1");
let args = json!({
"accountId": "acc1",
"create": {
"badTitle": { "title": 5 },
"badSequence": { "sequence": "x" }
}
});
let HandlerOutput { primary: resp, .. } =
handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
.await
.expect("must not return top-level error");
assert!(resp["created"].is_null(), "nothing may be created: {resp}");
for (cid, prop) in [("badTitle", "title"), ("badSequence", "sequence")] {
let err = &resp["notCreated"][cid];
assert_eq!(err["type"], "invalidProperties", "{cid}: {resp}");
assert_eq!(err["properties"], json!([prop]), "{cid}: {resp}");
}
}
#[tokio::test]
async fn copy_typed_parse_failure_names_property() {
let mut backend = MockBackend::new_with_account("acc1");
backend.add_account("acc2");
backend.seed_task("acc2", "src1", true);
let args = json!({
"accountId": "acc1",
"fromAccountId": "acc2",
"create": {
"badTitle": { "id": "src1", "title": 5 }
}
});
let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
.await
.expect("must not return top-level error");
assert!(resp["created"].is_null(), "nothing may be created: {resp}");
let err = &resp["notCreated"]["badTitle"];
assert_eq!(err["type"], "invalidProperties", "{resp}");
assert_eq!(err["properties"], json!(["title"]), "{resp}");
}
}