Skip to main content

MemoryBackend

Struct MemoryBackend 

Source
#[non_exhaustive]
pub struct MemoryBackend<C = Id> { /* private fields */ }
Available on crate feature memory only.
Expand description

A fully in-memory implementation of ChatBackend.

Stores objects as serialized JSON; each mutation bumps a monotonic state counter and records a change log entry. Used as both the integration-test harness and the canonical example for backend implementors.

Cloning is cheap and shared-state; see the Clone impl.

C is the JmapAccounts::CallerCtx: Id, the caller’s Principal id, by default, or () for a deployment without identity. This backend keeps no per-user state, so every caller acts as the account owner; JmapAccounts::principal_id returns MemoryCaller::principal.

Implementations§

Source§

impl<C: MemoryCaller> MemoryBackend<C>

Source

pub fn with_object_history( self, capability: ObjectHistoryAccountCapability, retention: HistoryRetention, ) -> Self

Keep object history for the types capability.supportedTypes lists (the eight chat history types), in every account, with retention; capability is also what ObjectHistoryBackend::object_history_capability advertises.

§Panics

When supportedTypes names a type without history, or another type.

Source

pub fn set_history_clock_for_test(&self, ms: i64)

Fix the history clock at ms milliseconds since the epoch.

Source

pub fn discard_version_for_test( &self, type_name: &str, account: &Id, id: &Id, version: u64, )

Discard one version of an object, in any order (§3.1).

Source

pub fn purge_object_history(&self, type_name: &str, account: &Id, id: &Id)

Discard every version of an object: the §8.3 administrative purge.

Source

pub fn set_rights_changed_at_for_test( &self, type_name: &str, account: &Id, ms: i64, )

Set the §8.2 cut for type_name in account: versions replaced before ms, and objects destroyed before it, are hidden.

Source§

impl MemoryBackend

Source

pub fn new() -> Self

Create a new, empty MemoryBackend.

The implicit @everyone role grants "view" and "send" in every Space; change that with set_everyone_permissions.

Its callers are Principal ids (C = Id); MemoryBackend::<()>::default() takes callers without identity.

Source§

impl<C: MemoryCaller> MemoryBackend<C>

Source

pub fn with_metadata_info( self, data_type: &str, info: DataTypeMetadataInfo, ) -> Self

Give data_type the draft-ietf-jmap-metadata-05 metadata property, configured by info (the DataTypeMetadataInfo of -05 §1.2.1). draft-atwood-jmap-chat-00 lets a server list Chat, Message and Space in the capability’s dataTypes.

Without this call a type has no metadata: Foo/set rejects a write to metadata or privateMetadata with invalidProperties and Foo/query rejects a metadata filter condition with unsupportedFilter. With it, Foo/set validates metadata writes (-05 §3.2), Foo/query evaluates the -05 §3.6 conditions, and Foo/changes honours ignoreMetadataOnlyChanges and reports updatedProperties (-05 §3.3). Advertising the capability in the session is the server’s job: list info under data_type in the account’s urn:ietf:params:jmap:metadata dataTypes.

None of the three types has a rights object or belongs to a container with one (the Space permission model is not one, per draft-atwood-jmap-chat-00 §Space), so -05 §4.1 asks only that the account is not read-only, and this backend has no read-only accounts: every metadata write passes rule 1’s maySetMetadata check (fail-open, JMAP-bghk).

§Panics

Panics if data_type is not "Chat", "Message" or "Space", or if info.supports_private is true: this backend has no per-user state to own privateMetadata (-05 §2).

Source

pub fn with_search_capability(self, capability: SearchCapability) -> Self

Advertise JMAP Search (urn:ietf:params:jmap:search, crate-jmap docs/specs/jmap-search.md) with capability for every account: ChatSettings::search_capability returns it.

When capability lists "Message" in dataTypes, Message/query evaluates where over the account’s Messages in Chats the owner may view, each as its stored representation without editHistory unless edit history is retained (as Message/get returns it), and $text as a case-insensitive substring of body (i;unicode-casemap). Advertising the capability in the session is the server’s job.

ponytail: the computed replyCount and unreadReplyCount, which Message/get fills in, are not stored, so a pointer to them is missing. Upgrade path: compute them into the candidate.

Source

pub fn set_everyone_permissions(&self, permissions: HashSet<ChatPermission>)

Set the permissions of the implicit @everyone role, which every member of every Space holds (draft-atwood-jmap-chat-00 §Space Permission Resolution step 1). The draft does not say where they are stored; this backend keeps one set for every Space without its own set from set_space_everyone_permissions.

Source

pub fn set_space_everyone_permissions( &self, space_id: &Id, permissions: HashSet<ChatPermission>, )

Set the permissions of the implicit @everyone role in Space space_id only, replacing the set_everyone_permissions set there.

Source

pub fn with_account(self, account_id: &Id) -> Self

Register account_id as known and return self, for builder-style fixture setup. Until then the account is unknown (accountNotFound, RFC 8620 §3.6.2).

§Panics

In debug builds, if account_id is the empty string (RFC 8620 §1.2, bd:JMAP-dx0s).

Source

pub fn seed_object( &self, account_id: &Id, type_name: &'static str, id: &Id, value: Value, )

Seed a pre-existing object into the store without bumping the state counter or recording a change-log entry. Test-fixture setup only (to store an object as a logged create, use insert_object); registers account_id as known. Mirrors jmap_mail_server::memory::MemoryBackend::seed_object.

type_name is the TYPE_NAME of a type this backend stores: "Chat", "Message", "Space", "ChatContact", "ReadPosition", "CustomEmoji", "SpaceInvite", "SpaceBan", "ChatBan", "PresenceStatus".

§Panics

If type_name is not one of the names above, or value is not a JSON object whose id string equals id.

Source

pub fn mint_id(&self) -> Id

Mint a fresh object id, as ChatStore::create_object does.

For a wrapping backend that must act on the complete object before it is stored (for example, to commit it elsewhere first): mint the id, build the object, act, then store it with insert_object or insert_message.

Source

pub async fn insert_object<O: SetObject + Send + Sync>( &self, account_id: &Id, object: O, ) -> Result<O, BackendSetError<MemoryError>>

Store object under its own id in account_id as a create: the state advances and the change log records the id as created, as for ChatStore::create_object, with the same per-type uniqueness checks. The id may be one the caller chose (such as a hash-derived ChatContact id) or one from mint_id.

§Errors
  • alreadyExists naming the stored object when the id is taken, or when a per-type uniqueness contract (ChatContact identity, CustomEmoji name) is violated.
  • BackendSetError::Other when account_id is not registered, or when object does not serialize to a JSON object with a non-empty id string.
Source

pub async fn insert_message( &self, account_id: &Id, message: Message, ) -> Result<Message, BackendSetError<MemoryError>>

insert_object for an owner-composed Message, also recording its OutboundEvent::NewMessage in the same write, as ChatStore::create_message does.

§Errors

As insert_object.

Source

pub fn with_change_log_limit(self, limit: usize) -> Self

Keep at most limit change-log entries (at least one) per data type and account, dropping the oldest. A Foo/changes from a state older than the oldest kept entry then fails with cannotCalculateChanges (RFC 8620 §5.2), and the client resyncs. Without a limit the log grows with every change, which suits tests but not a long-running embedder.

Source

pub fn with_event_limit(self, limit: usize) -> Self

Keep at most limit of the recorded lifecycle events and of the recorded outbound events (each list separately), dropping the oldest. 0 records none. Without a limit both lists grow until drained with drain_lifecycle_events and drain_outbound_events.

Source

pub fn drain_lifecycle_events(&self) -> Vec<LifecycleEvent>

Drain the lifecycle callbacks recorded so far (ChatEvents::on_chat_destroyed, ChatEvents::on_space_destroyed, ChatEvents::on_space_ban_created), oldest first.

Source

pub fn drain_outbound_events(&self) -> Vec<OutboundEvent>

Drain the ChatEvents::on_outbound_event events recorded so far, oldest first.

Trait Implementations§

Source§

impl<C: MemoryCaller> ChatAccessPolicy for MemoryBackend<C>

Source§

async fn may_broadcast_mention( &self, _caller: &C, account_id: &Id, space_id: &Id, chat_id: &Id, ) -> Result<Result<(), SetError>, Self::Error>

Reference implementation of ChatAccessPolicy::may_broadcast_mention.

Implements draft-atwood-jmap-chat-00 §BroadcastMention: a non-empty broadcastMentions array in a channel requires the ChatPermission::MentionBroadcast permission, resolved in channel chat_id per §Space Permission Resolution. The caller’s member entry is account_id (draft §Terminology). A Space or Chat that does not exist is permitted, matching the ban gate.

Source§

async fn may_send_message( &self, _caller: &C, account_id: &Id, chat_id: &Id, ) -> Result<Result<(), SetError>, Self::Error>

Reference implementation of ChatAccessPolicy::may_send_message.

Implements draft-atwood-jmap-chat-00 §Message/set: in a group Chat the owner’s ChatMember entry (id = accountId) must exist; in a channel the owner must be a member of the containing Space and hold "send" after §Space Permission Resolution. A channel whose Space does not exist has no members, so the create is forbidden. Direct chats are not restricted. A Chat that does not exist is permitted so create_object surfaces the normal error.

Source§

async fn may_view_chat( &self, _caller: &C, account_id: &Id, chat_id: &Id, ) -> Result<bool, Self::Error>

Reference implementation of ChatAccessPolicy::may_view_chat.

Implements draft-atwood-jmap-chat-00 §Message/query: a channel’s messages are visible only when the owner holds "view" there after §Space Permission Resolution. Other Chats, and Chats that do not exist, are visible. query_objects applies the same rule.

Source§

async fn may_set_pinned_messages( &self, _caller: &C, account_id: &Id, chat_id: &Id, ) -> Result<Result<(), SetError>, Self::Error>

Reference implementation of ChatAccessPolicy::may_set_pinned_messages.

Implements draft-atwood-jmap-chat-00 §Chat pinnedMessageIds: group chats require the caller to be a member with role admin; direct chats permit the owner freely; channel chats require the ChatPermission::Pin permission, resolved in the channel per §Space Permission Resolution. A Chat that does not exist is permitted so update_object surfaces notFound.

The caller is the owner, whose member entry is the accountId (draft §Terminology), so the gate looks up account_id in members whether or not JmapAccounts::principal_id resolves an identity.

Source§

async fn slow_mode_check( &self, _caller: &C, _account_id: &Id, _chat_id: &Id, ) -> Result<(), SlowModeError>

Reference implementation of ChatAccessPolicy::slow_mode_check.

Demonstration-only: this backend has no rate-tracker and always returns Ok(()). The kit defines the hook; production backends plug in their own per-(account, chat, caller) tracker and the SHOULD-exempt permission logic per draft-atwood-jmap-chat-00 §Chat slowModeSeconds + commit de60acb.

The override exists rather than relying on the trait’s default Ok(()) so the posture is explicit in the reference impl — a future contributor reading MemoryBackend cannot mistake the absence of a rate-tracker for an oversight.

Source§

fn is_contact_blocked( &self, caller: &Self::CallerCtx, account_id: &Id, contact_id: &Id, ) -> impl Future<Output = Result<bool, Self::Error>> + Send

Whether the ChatContact contact_id has blocked: true on the contact list of account_id. Read more
Source§

fn validate_pinned_message_ids( &self, caller: &Self::CallerCtx, account_id: &Id, chat_id: &Id, added: &[Id], ) -> impl Future<Output = Result<Result<(), SetError>, Self::Error>> + Send

Referential check consulted by handle_chat_set before an update that adds ids to pinnedMessageIds is applied. Read more
Source§

impl<C: MemoryCaller> ChatEvents for MemoryBackend<C>

Source§

fn on_chat_destroyed( &self, _caller: &C, _account_id: &Id, chat_id: &Id, ) -> impl Future<Output = ()> + Send

Records the call for MemoryBackend::take_lifecycle_events_for_test.

Source§

fn on_space_destroyed( &self, _caller: &C, _account_id: &Id, space_id: &Id, ) -> impl Future<Output = ()> + Send

Records the call for MemoryBackend::take_lifecycle_events_for_test.

Source§

fn on_space_ban_created( &self, _caller: &C, _account_id: &Id, ban: &SpaceBan, ) -> impl Future<Output = ()> + Send

Records the call for MemoryBackend::take_lifecycle_events_for_test.

Source§

fn on_outbound_event( &self, _caller: &C, _account_id: &Id, event: &OutboundEvent, ) -> impl Future<Output = ()> + Send

Records the event for MemoryBackend::take_outbound_events_for_test.

Source§

impl<C: MemoryCaller> ChatMessageLifecycle for MemoryBackend<C>

Source§

async fn expire_message( &self, _caller: &C, account_id: &Id, message_id: &Id, ) -> Result<(), Self::Error>

Reference implementation of ChatMessageLifecycle::expire_message.

Hard-deletes the message from the in-memory store and appends a Message change-log entry recording the id as destroyed, so subsequent Message/changes calls see the expiry per draft-atwood-jmap-chat-00.

If the message is already gone (e.g., a previous expire_message call or a cascade destroy already removed it), returns Ok(()) without bumping state — the expiry is a no-op, consistent with the trait’s idempotency contract.

Source§

async fn read_and_burn_message( &self, _caller: &C, account_id: &Id, message_id: &Id, patch: PatchObject, ) -> Result<(), BackendSetError<Self::Error>>

Reference implementation of ChatMessageLifecycle::read_and_burn_message.

Validates the patch on a clone and hard-deletes the row under one hold of the backend lock, recording the id as destroyed. The patched copy is never stored: the row is removed in the same critical section, so only the deletion is observable. An invalid patch returns before any write.

Source§

impl<C: MemoryCaller> ChatModeration for MemoryBackend<C>

Source§

fn create_chat_ban<F>( &self, caller: &Self::CallerCtx, account_id: &Id, create_id: &str, build: F, ) -> impl Future<Output = Result<(Id, ChatBan), BackendSetError<Self::Error>>> + Send
where F: FnOnce(&Id) -> ChatBan + Send,

Store a ChatBan and remove the banned user from the Chat’s members as one unit. Read more
Source§

fn update_chat_ban( &self, caller: &Self::CallerCtx, account_id: &Id, id: &Id, patch: PatchObject, ) -> impl Future<Output = Result<Option<ChatBan>, BackendSetError<Self::Error>>> + Send

Apply a ChatBan/set update to the stored ban id. Read more
Source§

fn destroy_chat_ban( &self, caller: &Self::CallerCtx, account_id: &Id, id: &Id, ) -> impl Future<Output = Result<(), BackendSetError<Self::Error>>> + Send

Lift the ChatBan id. Read more
Source§

fn kick_chat_members( &self, _caller: &Self::CallerCtx, _account_id: &Id, _chat: &Chat, _user_ids: &[Id], ) -> impl Future<Output = Result<Result<(), SetError>, Self::Error>> + Send

Apply the kickMembers key of a Chat/set update. Read more
Source§

impl<C: MemoryCaller> ChatResolvers for MemoryBackend<C>

Source§

async fn attachment_blob( &self, _caller: &C, account_id: &Id, blob_id: &Id, ) -> Result<Result<Option<AttachmentBlob>, SetError>, Self::Error>

Reference implementation of ChatResolvers::attachment_blob: reports the blob registered via MemoryBackend::set_attachment_blob_for_test, else Ok(Ok(None)).

Source§

fn filenode_attachment( &self, _caller: &Self::CallerCtx, _account_id: &Id, _chat: &Chat, _attachment: &AttachmentCreate, ) -> impl Future<Output = Result<Result<Option<Attachment>, SetError>, Self::Error>> + Send

FileNode resolution consulted by handle_message_set for each create Attachment that carries filenodeId. Read more
Source§

impl<C: MemoryCaller> ChatRestrictions for MemoryBackend<C>

Source§

fn may_create_message( &self, _caller: &Self::CallerCtx, _account_id: &Id, _chat: &Chat, ) -> impl Future<Output = Result<Result<(), SetError>, Self::Error>> + Send

Per-Chat restriction gate consulted by handle_message_set before each Message create, with the stored target Chat. Read more
Source§

fn may_update_message( &self, _caller: &Self::CallerCtx, _account_id: &Id, _chat: &Chat, _message: &Message, _patch_keys: &[&str], ) -> impl Future<Output = Result<Result<(), SetError>, Self::Error>> + Send

Per-Chat restriction gate consulted by handle_message_set before each Message update, with the stored Message, its stored Chat and the client’s patch keys. Read more
Source§

fn may_update_chat( &self, _caller: &Self::CallerCtx, _account_id: &Id, _chat: &Chat, _patch_keys: &[&str], ) -> impl Future<Output = Result<Result<(), SetError>, Self::Error>> + Send

Per-Chat restriction gate consulted by handle_chat_set before each Chat update, with the stored Chat and the client’s patch keys. Read more
Source§

impl<C: MemoryCaller> ChatSettings for MemoryBackend<C>

Source§

fn limits(&self, _caller: &C, _account_id: &Id) -> ChatLimits

Reference implementation of ChatSettings::limits.

Returns the test-only override set via MemoryBackend::set_limits_for_test when present, else falls back to ChatLimits::default. Production backends ignore the override knob and read from their own per-account configuration.

Source§

fn retains_edit_history(&self) -> bool

Reference implementation of ChatSettings::retains_edit_history.

Returns the test-only override set via MemoryBackend::set_retains_edit_history_for_test when set; otherwise returns false, matching the trait default. The reference backend does not retain edit history out of the box.

Spec: draft-atwood-jmap-chat-00 commit 0783fc4.

Source§

async fn owner_user_id( &self, _caller: &C, account_id: &Id, ) -> Result<Option<String>, Self::Error>

Reference implementation of ChatSettings::owner_user_id.

Returns the value set via MemoryBackend::set_owner_user_id_for_test for account_id, or None when unset.

Source§

async fn search_capability( &self, _caller: &C, _account_id: &Id, ) -> Result<Option<SearchCapability>, Self::Error>

Reference implementation of ChatSettings::search_capability: the capability set by MemoryBackend::with_search_capability, for every account.

Source§

fn maintains_unread_count(&self) -> bool

Whether the backend keeps Chat.unreadCount itself instead of the kit recomputing it. Read more
Source§

impl<C: MemoryCaller> ChatSpaces for MemoryBackend<C>

Source§

async fn join_space_with_invite( &self, _caller: &C, account_id: &Id, invite_id: &Id, joined_at: &UTCDate, ) -> Result<Result<(), InviteJoinRefusal>, Self::Error>

Reference implementation of ChatSpaces::join_space_with_invite.

Every check and both writes run under one hold of the backend lock, which is the atomic operation draft-atwood-jmap-chat-00 §Space/join requires. All checks precede the first write, so a refusal or error leaves storage unchanged.

Source§

fn protect_last_admin(&self, _caller: &C, _account_id: &Id) -> bool

Reference implementation of ChatSpaces::protect_last_admin.

Returns the test-only override set via MemoryBackend::set_protect_last_admin_for_test when set; otherwise returns false, opposite the trait default of true. See that method’s documentation and bd:JMAP-g7wu.2.4.3 for the rationale: production deployments inherit the trait default; the reference backend opts out so existing demo tests don’t have to seed admin memberships.

Source§

fn space_extension_properties( &self, _caller: &C, _account_id: &Id, ) -> &'static [&'static str]

Reference implementation of ChatSpaces::space_extension_properties: the list set via MemoryBackend::set_space_extension_properties_for_test, empty by default. Values are stored unvalidated.

Source§

async fn apply_space_patch( &self, _caller: &C, account_id: &Id, space_id: &Id, ops: Vec<SpacePatchOp>, ) -> Result<Vec<OpResult>, BackendSetError<Self::Error>>

Reference implementation of ChatSpaces::apply_space_patch.

Dispatches each SpacePatchOp to a per-variant helper. All twelve variants are implemented: Category (bd:JMAP-g7wu.2.4.5), Channel (bd:JMAP-g7wu.2.4.4), and Role/Member (bd:JMAP-g7wu.2.4.3).

The entire patch runs under one mutex acquisition, providing best-effort transactional semantics for the reference impl. A failure mid-way through the op vector does NOT roll back ops that already succeeded — they remain applied. Exception: the helper runs a pre-validation pass over the ops and rejects the whole patch up-front with a single forbidden SetError if any op would fail permission or role-hierarchy enforcement. This implements criterion 6 “whole-patch reject on permission failure” from bd:JMAP-g7wu.2.4.3. Per-op failures with other error types (NotFound, InvalidProperties) keep the legacy per-op outcome shape. Production backends should wrap the sequence in a real transaction.

§Caller identity

The caller is the owner, whose member entry is the accountId (draft-atwood-jmap-chat-00 §Terminology), so permission and role-hierarchy gates resolve against account_id. They apply whether or not JmapAccounts::principal_id resolves an identity; this backend never consults it.

§Change-log emission

One consolidated change-log entry per affected type per call:

  • Space: one updated entry if any op mutated the host Space.
  • Chat: one entry combining all channels created, updated, and destroyed by this patch. Same batching rationale as the Space entry — keeps Chat/changes from amplifying state-token rotations.
  • Message: one destroyed entry listing every Message cascade-destroyed by RemoveChannel.

Category-cascade Chat mutations (apply_category_op → set_channel_category) and the Channel variants both populate the per-type tracking sets, so a Chat/changes subscriber sees the cascade regardless of which Space/set patch key triggered it (bd:JMAP-g7wu.2.4.9 closed the original gap).

Source§

async fn apply_space_metadata_patch( &self, _caller: &C, account_id: &Id, space_id: &Id, patch: SpaceMetadataPatch, ) -> Result<Option<Space>, BackendSetError<Self::Error>>

Reference implementation of ChatSpaces::apply_space_metadata_patch.

Applies the JSON Merge Patch to the target Space’s top-level metadata fields under a single mutex acquisition, with the manage_space permission gate applied atomically against the owner’s member entry, mirroring the Self::apply_space_patch contract.

See bd:JMAP-g7wu.2.4.13.

Source§

async fn everyone_permissions( &self, _caller: &C, _account_id: &Id, space: &Space, ) -> Result<HashSet<ChatPermission>, Self::Error>

Source§

async fn generate_invite_code( &self, _caller: &C, _account_id: &Id, ) -> Result<String, MemoryError>

Generate a cryptographically random invite code. Read more
Source§

impl<C: MemoryCaller> ChatStore for MemoryBackend<C>

Source§

async fn create_message<F>( &self, _caller: &C, account_id: &Id, _create_id: &str, build: F, ) -> Result<(Id, Message), BackendSetError<Self::Error>>
where F: FnOnce(&Id) -> Message + Send,

Mints the id, builds and stores the Message, records the state change and pushes the NewMessage event under one lock acquisition, so no other caller observes the Message without its event or the event without its Message.

Source§

async fn create_object<O, F>( &self, _caller: &C, account_id: &Id, _create_id: &str, build: F, ) -> Result<(Id, O), BackendSetError<Self::Error>>
where O: SetObject + Send + Sync, F: FnOnce(&Id) -> O + Send,

Create a new object. Read more
Source§

async fn update_object<O: SetObject + Send + Sync>( &self, _caller: &C, account_id: &Id, id: &Id, patch: O::Patch, ) -> Result<Option<O>, BackendSetError<Self::Error>>

Apply a partial update (patch) to an existing object. Read more
Source§

async fn destroy_object<O: SetObject + Send + Sync>( &self, _caller: &C, account_id: &Id, id: &Id, ) -> Result<(), BackendSetError<Self::Error>>

Destroy an existing object by id. Read more
Source§

fn supports_type<O: JmapObject>(&self, _caller: &C, _account_id: &Id) -> bool

Returns true if this backend supports JMAP object type O for account_id, as seen by caller. Read more
Source§

impl<C> Clone for MemoryBackend<C>

Manual Clone impl, not #[derive(Clone)]: cloning is shared-state.

A clone copies no data. The original and the clone hold Arc::clones of the same Mutex-guarded store and observe each other’s mutations, so one handle can seed or inspect state while another serves requests. This impl must never become a deep copy; for independent state construct a fresh MemoryBackend::new instead of calling .clone().

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<C: MemoryCaller> ConditionalBackend for MemoryBackend<C>

Conditional chat Foo/set (bd JMAP-y1yu.9): the whole store is one ScopedState, so a scope isolates every type in every account, and an atomic rollback restores objects, state strings, change logs, push subscriptions and the queued lifecycle and outbound events, so nothing is announced for a change that never happened (§4.3). Under an atomic scope the backend leaves its cross-object checks (CustomEmoji names and per-Space counts, the push subscription cap) to the commit, which checks the final state (final_state_failures).

Source§

async fn begin_set( &self, _caller: &C, request: SetScopeRequest<'_>, ) -> Result<Box<dyn SetScope>, BeginSetError<MemoryError>>

Open the scope one Foo/set method call runs in (§4, §6.1). Read more
Source§

fn hidden_properties( &self, caller: &Self::CallerCtx, account_id: Option<&Id>, data_type: &str, ids: &[Id], ) -> impl Future<Output = Result<BTreeMap<Id, Vec<String>>, Self::Error>> + Send

For each of ids (objects of data_type in account_id), the top-level properties caller may not read, beyond what Foo/get already leaves out or blanks for them (§9.1). Read more
Source§

impl ConformanceBackend for MemoryBackend<()>

Source§

fn caller(&self, _account_id: &Id)

Available on crate feature testkit only.

A caller without identity: every request acts as every account’s owner.

Source§

async fn seed(&self, account_id: &Id, type_name: &'static str, object: Value)

Available on crate feature testkit only.
§Panics

If object has no id string.

Source§

async fn add_account(&self, account_id: &Id, owner_user_id: &str)

Available on crate feature testkit only.
Provision account_id, owned by owner_user_id (the ownerUserId Session field, as returned by ChatSettings::owner_user_id), so JmapAccounts::account_exists reports it and it holds no objects.
Source§

fn take_outbound_events(&self) -> Option<Vec<OutboundEvent>>

Available on crate feature testkit only.
Drain the OutboundEvents the backend has enqueued since the last call, oldest first. Read more
Source§

impl ConformanceBackend for MemoryBackend<Id>

Source§

fn caller(&self, account_id: &Id) -> Id

Available on crate feature testkit only.

The account id: the owner’s Space member id (draft-atwood-jmap-chat-00 §Terminology).

Source§

async fn seed(&self, account_id: &Id, type_name: &'static str, object: Value)

Available on crate feature testkit only.
§Panics

If object has no id string.

Source§

async fn add_account(&self, account_id: &Id, owner_user_id: &str)

Available on crate feature testkit only.
Provision account_id, owned by owner_user_id (the ownerUserId Session field, as returned by ChatSettings::owner_user_id), so JmapAccounts::account_exists reports it and it holds no objects.
Source§

fn take_outbound_events(&self) -> Option<Vec<OutboundEvent>>

Available on crate feature testkit only.
Drain the OutboundEvents the backend has enqueued since the last call, oldest first. Read more
Source§

impl<C> Default for MemoryBackend<C>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<C: MemoryCaller> JmapAccounts for MemoryBackend<C>

Source§

fn principal_id(caller: &C) -> Option<&Id>

Source§

fn metadata_info<O: JmapObject>( &self, _caller: &C, _account_id: &Id, ) -> Option<DataTypeMetadataInfo>

The info set by MemoryBackend::with_metadata_info, the same for every account.

Source§

type Error = MemoryError

The error type returned by storage operations. Read more
Source§

type CallerCtx = C

The per-request caller context type produced by the auth layer and forwarded by crate::Dispatcher::dispatch into every method call. Read more
Source§

async fn account_exists( &self, _caller: &C, account_id: &Id, ) -> Result<bool, Self::Error>

Return true if the given account exists in this backend. Read more
Source§

fn accept_language(caller: &Self::CallerCtx) -> Option<&str>

The request’s Accept-Language header field value (RFC 9110 §12.5.4), as the HTTP or WebSocket layer recorded it in the caller context, or None. Read more
Source§

fn max_objects_in_set(&self, caller: &Self::CallerCtx, account_id: &Id) -> u64

Maximum number of objects this account permits in a single /set call (RFC 8620 §5.3 maxObjectsInSet) (bd:JMAP-ayoz.41.1). Read more
Source§

fn max_objects_in_get(&self, caller: &Self::CallerCtx, account_id: &Id) -> u64

Maximum number of ids this account permits in a single /get call (RFC 8620 §5.1 maxObjectsInGet) (bd:JMAP-yt1w.31). Read more
Source§

fn i18n_info( &self, caller: &Self::CallerCtx, account_id: &Id, ) -> Option<I18nInfo>

What account_id supports of urn:ietf:params:jmap:i18n (draft-atwood-jmap-updates-00), as seen by caller, or None when the account does not support localizations. Read more
Source§

impl<C: MemoryCaller> JmapReads for MemoryBackend<C>

Source§

async fn query_changes<O: QueryObject + Send + Sync>( &self, caller: &C, account_id: &Id, params: QueryChangesParams<'_, O>, ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>>

Returns the changes to a /query result set since since_query_state.

RFC 8620 §5.6: /queryChanges reports changes to the results of the same query, so filter and sort are applied by re-running Self::query_objects, which also hides Messages in Chats the caller cannot view and Spaces the caller may not see: an id that /query omits is never announced in added. removed holds the destroyed ids and the updated ids that no longer match. Mirrors the canonical jmap-mail-server MemoryBackend::query_changes.

ponytail: only the queried type’s change log is read, so a Message hidden or revealed by a Chat membership change (no Message change) is not reported; a backend that needs this logs such Messages as updated.

Source§

async fn get_objects<O: GetObject + Send + Sync>( &self, _caller: &C, account_id: &Id, ids: Option<&[Id]>, _properties: Option<&[String]>, ) -> Result<(Vec<O>, Vec<Id>), Self::Error>

Fetch objects by id (or all objects when ids is None). Read more
Source§

async fn get_state<O: JmapObject + Send + Sync>( &self, _caller: &C, account_id: &Id, ) -> Result<State, Self::Error>

Return the current state token for an object type in the given account. Read more
Source§

async fn get_changes<O: JmapObject + Send + Sync>( &self, _caller: &C, account_id: &Id, params: ChangesParams<'_>, ) -> Result<ChangesResult, BackendChangesError<Self::Error>>

Return changes since params.since_state, up to params.max_changes entries, honouring params.ignore_metadata_only_changes (see ChangesParams). Read more
Source§

async fn query_objects<O: QueryObject + Send + Sync>( &self, _caller: &C, account_id: &Id, params: QueryParams<'_, O>, ) -> Result<QueryResult, BackendQueryError<Self::Error>>

Execute a /query and return a page of matching ids. Read more
Source§

impl<C: MemoryCaller> ObjectHistoryBackend for MemoryBackend<C>

Source§

fn object_history_capability( &self, _caller: &C, account_id: &Id, ) -> Option<ObjectHistoryAccountCapability>

The urn:ietf:params:jmap:object-history value of account_id’s accountCapabilities (§2.1), or None for no history in the account. The handlers accept history arguments only for the types it lists, so advertisement and behaviour agree. List only types for which jmap_object_history_types::is_history_type is true.
Source§

async fn get_object_history<O: HistoryObject>( &self, _caller: &C, account_id: &Id, params: HistoryGetParams<'_>, ) -> Result<HistoryGetResult<O>, BackendQueryError<MemoryError>>

The §3 selection for a history Foo/get (at least one flag set). Read more
Source§

async fn query_destroyed<O: HistoryObject + QueryObject>( &self, _caller: &C, account_id: &Id, params: DestroyedQueryParams<'_, O>, ) -> Result<QueryResult, BackendQueryError<MemoryError>>

Foo/query with onlyDestroyed (§4): over the destroyed objects with a retained version, restored ones excluded; filter and sort apply to the final version; the window is strict on the final version’s replaced; a null or empty sort orders by destruction time, most recent first. An unsupported filter or sort is BackendQueryError::Method (unsupportedFilter/unsupportedSort). Read more
Source§

async fn query_destroyed_changes<O: HistoryObject + QueryObject>( &self, _caller: &C, account_id: &Id, params: DestroyedQueryChangesParams<'_, O>, ) -> Result<QueryChangesResult, BackendChangesError<MemoryError>>

Foo/queryChanges with onlyDestroyed (-04 §4): a destroy adds an object, a restore or discard removes it. A since_query_state not minted by query_destroyed for the same window is CannotCalculate; so is a state the backend cannot track (§4 MAY). Read more
Source§

async fn restore_object<O: HistoryObject + SetObject>( &self, _caller: &C, account_id: &Id, id: &Id, patch: Option<PatchObject>, ) -> Result<Restored<O>, BackendSetError<MemoryError>>

Restore the destroyed object id (§5.1), applying patch (already shape-checked; None for none) to its final version. Read more
Source§

impl<C: MemoryCaller> PushSubscriptionBackend for MemoryBackend<C>

Reference RFC 8620 §7.2 push subscription storage.

Single-owner mode (every caller acts as the owner): every subscription belongs to the one caller, and MAX_PUSH_SUBSCRIPTIONS caps them all.

ponytail: url and keys are stored as plain values and dropped on destroy without zeroization. This backend is demonstration-quality; the secure-erase MUST (rfc8620.txt:3725-3727) is a consumer MUST stated on PushSubscriptionBackend.

ponytail: no creation rate limit and no PushVerification delivery. The backend has no clock window and no HTTP client; both are consumer MUSTs stated on PushSubscriptionBackend.

Source§

async fn create_push_subscription( &self, _caller: &C, new: PushSubscription, ) -> Result<StoredPushSubscription, BackendSetError<MemoryError>>

Store new under a fresh id with a 128-bit verification code, or return overQuota when MAX_PUSH_SUBSCRIPTIONS are already stored. The cap is checked under the same lock as the insert. A chatPush that fails validate_chat_push is rejected and nothing is stored.

Source§

async fn update_push_subscription( &self, _caller: &C, sub: PushSubscription, ) -> Result<PushSubscription, BackendSetError<MemoryError>>

Replace the stored subscription with sub. A chatPush that fails validate_chat_push is rejected and the stored one is kept.

Source§

const PUSH_SUBSCRIPTION_EXTENSION_PROPERTIES: &'static [&'static str]

The extension property names, beyond those of RFC 8620 §7.2, that PushSubscription/get accepts in its properties argument (e.g. chatPush, draft-atwood-jmap-chat-push-00). Read more
Source§

async fn list_push_subscriptions( &self, _caller: &C, ) -> Result<Vec<StoredPushSubscription>, MemoryError>

Return every push subscription created with the credentials that caller identifies, and no others. Read more
Source§

async fn destroy_push_subscription( &self, _caller: &C, id: &Id, ) -> Result<(), BackendSetError<MemoryError>>

Delete the caller’s subscription with this id, or return notFound if the caller has none. Read more
Source§

const PUSH_SUBSCRIPTION_EXTENSION_CAPABILITIES: &'static [(&'static str, &'static str)]

Extension properties that exist only for a request whose using holds a capability, as (property, capability URI) pairs (e.g. ("emailPush", "urn:ietf:params:jmap:emailpush"), draft-ietf-jmap-emailpush-05 §4: “To get or set the emailPush property, the client MUST include” the capability in using). Read more
Source§

impl<C: MemoryCaller> SpacePolicy for MemoryBackend<C>

Source§

async fn may_set_custom_emoji( &self, _caller: &C, _account_id: &Id, _target_space_id: Option<&Id>, _op: EmojiSetOp, ) -> Result<Result<(), SetError>, Self::Error>

Reference implementation of SpacePolicy::may_set_custom_emoji.

Demonstration-only: returns Ok(Ok(())) unconditionally. The reference backend does not honor identity-scoped permissions because it treats every caller as the account owner, whatever JmapAccounts::principal_id returns. A meaningful permission model — e.g. “only members of the target Space may modify a Space-scoped emoji” — requires the production backend to override both principal_id and this method.

Spec: draft-atwood-jmap-chat-00 commit 9344aec (authorization for CustomEmoji/set is implementation-defined).

Source§

async fn may_set_space_ban( &self, _caller: &C, account_id: &Id, space_id: &Id, ) -> Result<Result<(), SetError>, Self::Error>

Reference implementation of SpacePolicy::may_set_space_ban.

Implements draft-atwood-jmap-chat-00 §SpaceBan/set: each op “Requires "ban" permission in the Space.” A Space that does not exist is permitted, matching the pinned-messages gate. The caller’s member entry is account_id (draft §Terminology).

Source§

async fn may_set_space_invite( &self, _caller: &C, account_id: &Id, space_id: &Id, created_by: Option<&Id>, ) -> Result<Result<(), SetError>, Self::Error>

Reference implementation of SpacePolicy::may_set_space_invite.

Implements draft-atwood-jmap-chat-00 §SpaceInvite/set: create “Requires "manage_members" permission”; destroy also permits “ownership of the invite”, which is createdBy equal to account_id (draft §SpaceInvite.createdBy). A Space that does not exist is permitted, matching the ban gate.

Source§

async fn may_get_space_invite( &self, _caller: &C, account_id: &Id, invite: &SpaceInvite, ) -> Result<bool, Self::Error>

Reference implementation of SpacePolicy::may_get_space_invite.

Implements draft-atwood-jmap-chat-00 §SpaceInvite/get: only a member of the invite’s Space sees it, and only if it holds manage_members or created the invite (createdBy equal to account_id, the caller’s member entry per draft §Terminology). An invite whose Space does not exist is visible, matching Self::may_set_space_invite, which lets such an invite be created.

Source§

async fn may_get_space_ban( &self, _caller: &C, account_id: &Id, ban: &SpaceBan, ) -> Result<bool, Self::Error>

Reference implementation of SpacePolicy::may_get_space_ban.

Implements draft-atwood-jmap-chat-00 §SpaceBan/get: a holder of ban in the ban’s Space sees it, and so does the banned user (userId equal to account_id). Everyone else does not. A ban whose Space does not exist is visible, matching Self::may_set_space_ban, which lets such a ban be created.

Auto Trait Implementations§

§

impl<C = Id> !RefUnwindSafe for MemoryBackend<C>

§

impl<C = Id> !UnwindSafe for MemoryBackend<C>

§

impl<C> Forget for MemoryBackend<C>

§

impl<C> Freeze for MemoryBackend<C>
where PhantomData<fn() -> C>: Freeze,

§

impl<C> Move for MemoryBackend<C>

§

impl<C> Send for MemoryBackend<C>
where PhantomData<fn() -> C>: Send,

§

impl<C> Sync for MemoryBackend<C>
where PhantomData<fn() -> C>: Sync,

§

impl<C> Unpin for MemoryBackend<C>
where PhantomData<fn() -> C>: Unpin,

§

impl<C> UnsafeUnpin for MemoryBackend<C>
where PhantomData<fn() -> C>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> ChatBackend for T

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> JmapBackend for T

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more