jmap-tasks-server 0.3.0

JMAP Tasks method handlers — backend-agnostic, plugs into jmap-server Dispatcher
Documentation
//! Private helper utilities shared across handler modules.

use jmap_types::{Id, JmapError, JmapObject, State};
use serde_json::{json, Map, Value};

use crate::backend::TasksBackend;
use jmap_server::{server_fail_from_backend, HandlerOutput};

pub(crate) use jmap_server::{enforce_max_objects_in_set, extract_account_id};

/// Sentinel `id` the `/set` create handlers insert before deserializing.
///
/// RFC 8620 §5.3 makes `id` server-set, so the client must not supply one
/// on create, yet `TaskList` declares `id` as a required field (and
/// `Task` as an optional one). The `TaskList/set` and `Task/set` create
/// handlers insert this sentinel before `serde_json::from_value`, then
/// the backend's `create_object` MUST replace it with a real, unique,
/// account-scoped Id. Clients must never see this value.
///
/// Defined as a constant so every write-side handler site uses the same
/// string and a rename is caught at compile time. Mirrors the canonical
/// `crate-jmap-mail-server/src/helpers.rs` `PLACEHOLDER_ID` pattern
/// (bd:JMAP-ic0j.10).
pub(crate) const PLACEHOLDER_ID: &str = "placeholder";

/// Per-`/set` accumulators emitted in the RFC 8620 §5.3 response envelope.
///
/// The six fields correspond to the six top-level result keys (`created`,
/// `updated`, `destroyed`, `notCreated`, `notUpdated`, `notDestroyed`).
/// Each `/set` handler builds these as it walks the request's `create`,
/// `update`, and `destroy` maps, then hands the bundle to
/// [`finalize_set_response`] for envelope construction.
///
/// Bundling the six accumulators into a struct (instead of six positional
/// parameters) keeps [`finalize_set_response`] under clippy's
/// `too_many_arguments` threshold and lets callers use struct-update syntax
/// (`SetAccumulators { created, ..Default::default() }`) when only a subset
/// of the maps is non-empty.
#[derive(Debug, Default)]
pub(crate) struct SetAccumulators {
    pub created: Map<String, Value>,
    pub updated: Map<String, Value>,
    pub destroyed: Vec<Value>,
    pub not_created: Map<String, Value>,
    pub not_updated: Map<String, Value>,
    pub not_destroyed: Map<String, Value>,
}

/// Build the final `/set` method response and re-fetch `newState` from the
/// backend if any mutation occurred.
///
/// All three `/set` handlers in this crate (`TaskList/set`, `Task/set`,
/// `TaskNotification/set`) end with the same boilerplate: refresh the state
/// token if `mutated`, then emit a `HandlerOutput` wrapping
/// the canonical RFC 8620 §5.3 envelope. Centralising it here keeps the three
/// sites in lockstep — if a future revision changes which keys are emitted
/// (e.g. RFC 8620 §5.3.1 may flip a key from `null` to omitted), all three
/// handlers update at once.
///
/// The `O` type parameter is the JMAP object type for the state token
/// (e.g. `Task`, `TaskList`, `TaskNotification`); its only role is to
/// disambiguate the `get_state::<O>` call inside the helper.
///
/// Empty maps/arrays serialize as `null` (JMAP convention). The `Invocation`
/// vector is always empty for the three call sites — no `/set` call generates
/// follow-up invocations today.
pub(crate) async fn finalize_set_response<B, O>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    old_state: State,
    mutated: bool,
    acc: SetAccumulators,
) -> Result<HandlerOutput, JmapError>
where
    B: TasksBackend,
    O: JmapObject + Send + Sync,
{
    let new_state = if mutated {
        backend
            .get_state::<O>(caller, account_id)
            .await
            .map_err(|e| server_fail_from_backend(&e))?
    } else {
        old_state.clone()
    };

    let SetAccumulators {
        created,
        updated,
        destroyed,
        not_created,
        not_updated,
        not_destroyed,
    } = acc;

    Ok(HandlerOutput::new(json!({
        "accountId": 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) },
        "updated":      if updated.is_empty()      { Value::Null } else { Value::Object(updated) },
        "destroyed":    if destroyed.is_empty()    { Value::Null } else { Value::Array(destroyed) },
        "notCreated":   if not_created.is_empty()  { Value::Null } else { Value::Object(not_created) },
        "notUpdated":   if not_updated.is_empty()  { Value::Null } else { Value::Object(not_updated) },
        "notDestroyed": if not_destroyed.is_empty() { Value::Null } else { Value::Object(not_destroyed) },
    })))
}

/// Serialize a [`SetError`] to a JSON value for inclusion in
/// `notCreated`/`notUpdated`/`notDestroyed` maps.
pub(crate) fn set_error_value(e: &crate::backend::SetError) -> serde_json::Value {
    serde_json::to_value(e).expect("derive(Serialize) on plain data is infallible")
}