pub trait ChatStore: ChatEvents {
// Required methods
fn create_object<O, F>(
&self,
caller: &Self::CallerCtx,
account_id: &Id,
create_id: &str,
build: F,
) -> impl Future<Output = Result<(Id, O), BackendSetError<Self::Error>>> + Send
where O: SetObject + Send + Sync,
F: FnOnce(&Id) -> O + Send;
fn update_object<O: SetObject + Send + Sync>(
&self,
caller: &Self::CallerCtx,
account_id: &Id,
id: &Id,
patch: O::Patch,
) -> impl Future<Output = Result<Option<O>, BackendSetError<Self::Error>>> + Send;
fn destroy_object<O: SetObject + Send + Sync>(
&self,
caller: &Self::CallerCtx,
account_id: &Id,
id: &Id,
) -> impl Future<Output = Result<(), BackendSetError<Self::Error>>> + Send;
fn supports_type<O: JmapObject>(
&self,
caller: &Self::CallerCtx,
account_id: &Id,
) -> bool;
// Provided method
fn create_message<F>(
&self,
caller: &Self::CallerCtx,
account_id: &Id,
create_id: &str,
build: F,
) -> impl Future<Output = Result<(Id, Message), BackendSetError<Self::Error>>> + Send
where F: FnOnce(&Id) -> Message + Send { ... }
}Expand description
Object writes and type support: the /set storage half of a chat backend.
Its defaults report outbound events through ChatEvents.
Part of ChatBackend (docs/design/chat-backend-split.md).
Required Methods§
Sourcefn create_object<O, F>(
&self,
caller: &Self::CallerCtx,
account_id: &Id,
create_id: &str,
build: F,
) -> impl Future<Output = Result<(Id, O), BackendSetError<Self::Error>>> + Send
fn create_object<O, F>( &self, caller: &Self::CallerCtx, account_id: &Id, create_id: &str, build: F, ) -> impl Future<Output = Result<(Id, O), BackendSetError<Self::Error>>> + Send
Create a new object.
Returns (assigned_id, created_object) on success. create_id is the
client-side creation id used in the /set request.
§Authorisation contract
This method is the canonical enforcement point for caller authorisation
per workspace AGENTS.md “Caller identity (foundation seam)” and per-crate
AGENTS.md “Permission enforcement: backend canonical”. The caller of a
chat account is its owner, whose Space member entry is the accountId
(draft-atwood-jmap-chat §Terminology). Implementors MUST verify that
caller may act as the owner of account_id before performing the
mutation, and MUST return BackendSetError::SetError carrying
SetErrorType::Forbidden otherwise. Handlers in this crate do no
account-access checking, so a backend that trusts the handler lets any
caller write any account. Space permission and role-hierarchy gates
resolve against the owner’s member entry through the may_* hooks (for
example ChatAccessPolicy::may_send_message), ChatSpaces::apply_space_patch and
ChatSpaces::apply_space_metadata_patch.
§Id assignment
The backend mints the new object’s id, calls build(&id) exactly
once to obtain the complete object, and stores that object under
id in the same atomic write. build sets the object’s id field
to the id it is given; the backend stores the built object as is.
RFC 8620 §5.3 lists id among the “server-set properties”.
Message/set builds an owner-composed Message with senderMsgId
equal to that id (draft-atwood-jmap-chat-00 §Message senderMsgId:
“Equals id for messages composed by the owner.”). A
server-originated Message (crate::message::store_server_message) carries
the senderMsgId its originator chose. In both cases the backend
stores senderMsgId unchanged.
§Per-type uniqueness contracts
For most types the (id) primary key is the only uniqueness invariant the backend must enforce, and the backend’s normal server-assigned-id discipline closes that. A few types carry additional uniqueness invariants on non-id fields that the backend MUST enforce atomically with the create — the handler pre-checks defensively but cannot close the two-concurrent-requests race window.
ReadPosition— at most one record per(account_id, chat_id). Clients cannot create one (ReadPosition/setcreate isforbidden); the server creates it on first message delivery incrate::message::handle_message_setand oncrate::space::handle_space_join, which pre-check via a sequential scan, but two concurrent requests for the samechatIdcan both pass the pre-check and then both reachcreate_object. The backend MUST enforce a unique constraint on(account_id, chat_id)at the storage layer (typically a composite unique index in a database backend) and surface a duplicate asBackendSetError::SetError(SetError::new( SetErrorType::AlreadyExists).with_existing_id(canonical)). See draft-atwood-jmap-chat-00 §ReadPosition.ChatContact— at most one record per(account_id, identity), compared octet for octet.crate::contact::handle_contact_setdoes not pre-check: the backend MUST reject a duplicate atomically with the create asBackendSetError::SetError(SetError::new( SetErrorType::AlreadyExists).with_existing_id(existing)), whereexistingis the id of theChatContactthat holds theidentity. See draft-atwood-jmap-chat-00 §ChatContact/set.CustomEmoji— at most one emoji per(account_id, spaceId, name), an absentspaceIdbeing the server-global scope.crate::emoji::handle_emoji_setdoes not pre-check: the backend MUST reject a duplicate create asBackendSetError::SetError(SetError::new( SetErrorType::AlreadyExists).with_existing_id(existing))and, inupdate_object, a rename onto a held name as aninvalidPropertiesSetErrornamingname. See draft-atwood-jmap-chat-00 §CustomEmojiname. The same holds for theChatLimitsemoji caps: the backend MUST reject, atomically with the write, a create that would put more thanmax_custom_emoji_per_spaceemoji in its Space, and a create orblobIdupdate naming a blob larger thanmax_custom_emoji_bytes, asBackendSetError::SetErrorwith anoverQuotaSetError(jmap-chat-implementer-guide §2.2: “The server MUST rejectCustomEmoji/setwithoverQuota… when the count or size limit is exceeded”). The handler pre-checks both, but the pre-check cannot close the race.Chatwithkind == Direct— at most one direct chat per(account_id, contact_id). The handler atcrate::chat::handle_chat_setuses optimistic create-then-validate with rollback; backends MAY enforce a storage-level unique constraint to eliminate the rollback path entirely, but it is not required because the handler’s rollback closes the race correctly. See draft-atwood-jmap-chat-00 §Chat.
The reference MemoryBackend does NOT
enforce the ReadPosition (account, chatId) uniqueness
constraint at the storage layer — it is single-Mutex
per-call so concurrent racing cannot occur in practice, but a
production backend that holds different locks per record (or
no lock at all between read and write) MUST.
§Errors
Reject a create that RFC 8620 §5.3 defines an error for with
BackendSetError::SetError carrying the matching
SetErrorType; the handler places it verbatim in notCreated.
For create these are forbidden, overQuota, tooLarge,
rateLimit and invalidProperties. An invalidProperties error
SHOULD name in properties “all the properties that were
invalid”, for example chatId when a Message names a Chat that does
not exist.
Return BackendSetError::Other only for unexpected storage
failures. The handler reports it as serverFail without the
error’s Display text, which tells the client to retry; a
deterministic rejection returned as Other invites retries that
cannot succeed.
§State and change log
RFC 8620 §5.1 defines the state string over “all the data of
this type in the account”: “If the data changes, this string MUST
change.” Every successful create_object,
update_object and
destroy_object MUST advance
get_state for O in account_id and
record the id as created, updated or destroyed so
get_changes reports it.
When ChatLimits::supports_threads is true, Message/get
returns the server-computed replyCount and unreadReplyCount
(draft-atwood-jmap-chat-00 §Message), so a write that changes them
changes those Messages. The backend MUST then also record as
updated in Message state:
- on a Message create or destroy (including
expire_messageandread_and_burn_message), the still-stored Message itsreplyTonames, whosereplyCountchanged; - on a
ReadPositionupdate that changeslastReadMessageId, each thread root (nothreadRootId) in that Chat with a direct reply not sent by the owner (senderIdis not the accountId) whose id moved acrosslastReadMessageId, whoseunreadReplyCountchanged.
The write, the state advance and the change record MUST be atomic
with respect to other callers: the reference MemoryBackend does
all three under one mutex acquisition, and a database backend uses
one transaction. A call that returns Err MUST leave the stored
data, the state and the change log unchanged.
Sourcefn update_object<O: SetObject + Send + Sync>(
&self,
caller: &Self::CallerCtx,
account_id: &Id,
id: &Id,
patch: O::Patch,
) -> impl Future<Output = Result<Option<O>, BackendSetError<Self::Error>>> + Send
fn update_object<O: SetObject + Send + Sync>( &self, caller: &Self::CallerCtx, account_id: &Id, id: &Id, patch: O::Patch, ) -> impl Future<Output = Result<Option<O>, BackendSetError<Self::Error>>> + Send
Apply a partial update (patch) to an existing object.
Returns Some(updated_object) if the backend modified any properties
beyond what the client requested (RFC 8620 §5.3 server-set field echo),
or None if the patch was applied verbatim.
§Authorisation contract
Implementors MUST verify that caller may act as the owner of
account_id before applying the patch and MUST return BackendSetError::SetError
with SetErrorType::Forbidden otherwise. See Self::create_object
for the workspace-canonical rationale; the same rule applies here.
§Patch format
patch is an RFC 8620 §5.3 PatchObject, not an RFC 7396 JSON
Merge Patch: “The keys are a path in JSON Pointer format
[RFC6901], with an implicit leading “/”“. So {"a/b": null}
removes member b of property a; it does not touch a top-level
property literally named a/b. A null value sets the
property’s default if it has one, otherwise removes it. A pointer
into an array, a pointer whose parent does not exist, or two keys
where one pointer is a prefix of the other “MUST be rejected with
an “invalidPatch” error“.
Implementors SHOULD apply patch with
jmap_server::apply_patch_object, which enforces these rules
all-or-nothing, and map any jmap_server::PatchPathError to
jmap_server::SetErrorType::InvalidPatch, as the reference
MemoryBackend does.
§Errors
As for create_object, plus these RFC 8620
§5.3 rules for update:
- “If an id given cannot be found, the update or destroy MUST be rejected with a “notFound” set error.“
- A patch that breaks the rules under “Patch format” is
invalidPatch. - A patched record that is invalid is
invalidProperties. That includes changing a server-set property, though “it is not an error to include a server-set property in an update as long as the value is identical to the current value on the server.”
§Atomicity
RFC 8620 §5.3: the server “MUST NOT only commit part of an update
to a single record”. Apply the whole patch and validate the result
before writing it, so that on any error the stored record is
unchanged. State and change log follow
create_object (“State and change log”); an
Ok(None) return still advances the state.
Sourcefn destroy_object<O: SetObject + Send + Sync>(
&self,
caller: &Self::CallerCtx,
account_id: &Id,
id: &Id,
) -> impl Future<Output = Result<(), BackendSetError<Self::Error>>> + Send
fn destroy_object<O: SetObject + Send + Sync>( &self, caller: &Self::CallerCtx, account_id: &Id, id: &Id, ) -> impl Future<Output = Result<(), BackendSetError<Self::Error>>> + Send
Destroy an existing object by id.
§Authorisation contract
Implementors MUST verify that caller may act as the owner of
account_id before destroying it and MUST return BackendSetError::SetError
with SetErrorType::Forbidden otherwise. See Self::create_object
for the workspace-canonical rationale; the same rule applies here.
§Errors
As for create_object, plus these RFC 8620
§5.3 rules for destroy: an unknown id, including one already
destroyed, is notFound, and a destroy that “would violate an ACL
or other permissions policy” is forbidden.
destroy_object::<Space> MUST return forbidden unless the caller
holds manage_space in that Space, checked atomically with the
destroy (draft-atwood-jmap-chat-00 §Destroying a Space, jmap-chat-spec
77c3474 L1391: “The caller SHOULD hold "manage_space"”; “Servers
SHOULD return a forbidden SetError when the caller does not satisfy
the deployment’s destroy-authorization rules”). This crate performs
the recommended check by choice. The handler does no check of its
own.
§Cascades
destroy_object::<Message> MUST also remove the id from its
Chat’s pinnedMessageIds (draft-atwood-jmap-chat-00 §Chat:
“When a pinned Message is hard-deleted, the server MUST remove
its id from this list.”), as
expire_message does. That change is
a Chat update.
destroy_object::<Space> MUST also destroy every channel Chat
whose spaceId is the Space and every Message in those Chats
(draft-atwood-jmap-chat-00 §Destroying a Space: “Cascades to all
channel Chats and their Messages. Hard-deletes all records; no
tombstones are retained.”). Those are Chat and Message destroys.
Every Chat destroy, including those cascades, MUST also destroy
the Chat’s ReadPosition (draft-atwood-jmap-chat-00 §ReadPosition:
the server “destroys it when the Chat is destroyed”). That is a
ReadPosition destroy.
If the backend itself changes another record because of the
destroy, it MUST advance that record type’s state and record the
change in the same atomic step, so /changes on that type sees it.
State and change log for O follow
create_object (“State and change log”).
Sourcefn supports_type<O: JmapObject>(
&self,
caller: &Self::CallerCtx,
account_id: &Id,
) -> bool
fn supports_type<O: JmapObject>( &self, caller: &Self::CallerCtx, account_id: &Id, ) -> bool
Returns true if this backend supports JMAP object type O for
account_id, as seen by caller.
§Types in scope
Implementors should answer for the object types this trait
covers (draft-atwood-jmap-chat-00): Chat, Message, Space,
SpaceInvite, SpaceBan, ChatBan, ChatContact, CustomEmoji,
ReadPosition, and PresenceStatus. Backends MAY answer for
object types from sibling extensions if they also implement those
traits. A backend that does not recognise O SHOULD return
false.
§Callers
The handler library in this crate does not call this method. The server consumer calls it when building the JMAP session capability response.
§Per-account semantics
Capabilities are per account (RFC 8620 §1.6.2, §2
accountCapabilities), so the answer may vary with caller and
account_id. Backends that support every type in this trait for
every account can ignore both arguments and return true.
§Why sync, not async
Type-support is a deployment capability question answered from in-process state. A backend whose supported types come from configuration or a per-account record SHOULD load it ahead of the request and answer from the in-memory snapshot. See the trait-level “Async vs sync method convention” section above for the workspace rationale.
Provided Methods§
Sourcefn create_message<F>(
&self,
caller: &Self::CallerCtx,
account_id: &Id,
create_id: &str,
build: F,
) -> impl Future<Output = Result<(Id, Message), BackendSetError<Self::Error>>> + Send
fn create_message<F>( &self, caller: &Self::CallerCtx, account_id: &Id, create_id: &str, build: F, ) -> impl Future<Output = Result<(Id, Message), BackendSetError<Self::Error>>> + Send
Store an owner-composed Message and report its
OutboundEvent::NewMessage as
one unit.
crate::message::handle_message_set calls this for every
Message/set create that passes its checks. draft-atwood-jmap-chat-00
§Message/set: “The server sets id, senderMsgId, senderId,
receivedAt, deliveryState, and delivery timestamp fields, then
enqueues the message for outbound delivery.”
build and every contract of Self::create_object (authorisation,
id assignment, errors, state and change log) apply unchanged. On
Ok the Message is stored and its NewMessage event, naming the
Message’s chatId, id and senderMsgId, is enqueued. On Err
nothing is stored and nothing is enqueued.
An overriding backend may fail the whole create when it cannot
enqueue the event; the handler reports the error in notCreated
like any Self::create_object error, so a
BackendSetError::Other becomes serverFail. A backend that
wants the store and the delivery fan-out in one transaction (for
example a SQLite backend committing a group send once) overrides
this.
§Default implementation
Calls Self::create_object for Message, then, on success,
ChatEvents::on_outbound_event with the NewMessage event. The store
and the enqueue are then two steps, and the enqueue cannot fail
the create.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".
Implementors§
impl<C: MemoryCaller> ChatStore for MemoryBackend<C>
memory only.