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 TasksBackend.

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: every clone retains an handle to the same underlying object store and change log. See the Clone impl below for the contract; a casual reader who reaches for #[derive(Clone)] semantics will be wrong. To get a snapshot with independent state, construct a fresh MemoryBackend::new() and seed it via register_account / the typed test helpers.

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 (TaskList, Task), 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.

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

Source§

impl<C: MemoryCaller> MemoryBackend<C>

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). Idempotent; the id is stored without RFC 8620 §1.2 validation.

§Panics

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

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).

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, §4.1), Task/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.

TaskList writes need myRights.maySetMetadata on the TaskList, and Task writes need it on the Task’s TaskList before and after the update, or on the taskListId of a create (-05 §4.1). An absent maySetMetadata allows the write (fail-open, JMAP-bghk). This backend never sets Task updated, so a metadata-only change leaves it alone, as -05 §3.1 requires.

§Panics

Panics if data_type is not "TaskList" or "Task" (the rights object of draft-ietf-jmap-tasks-06 §3 and the type it contains; -05 §4.1), or if info.supports_private is true: this backend has no per-user state to own privateMetadata (-05 §2).

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; 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: "TaskList", "Task", or "TaskNotification". A seeded Task’s taskListId is counted in the TaskList reference index.

§Panics

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

Trait Implementations§

Source§

impl<C> Clone for MemoryBackend<C>

Manual Clone impl, NOT #[derive(Clone)].

Cloning a MemoryBackend does not copy any state — both the original and the clone hold handles to the same ScopedState and observe each other’s mutations. This is intentional: handler registration in crate::register_tasks_handlers takes Arc<B> and each method handler closure clones it; without shared mutation semantics, every handler would see a snapshot stale by the time it runs. The manual impl exists (instead of #[derive(Clone)]) so the contract is visible at the type, not buried in the module docs.

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 tasks Foo/set (bd JMAP-y1yu.11): 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 and the derived per-account indexes together, onDestroyRemoveTasks cascades included.

Commit checks nothing beyond what the handlers already check: taskListHasTask is judged within one TaskList/set, which moves no Tasks; draft-ietf-jmap-tasks-06 sets no uniqueness rule for TaskList role; and this backend has no cross-object caps.

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<C> Default for MemoryBackend<C>

An empty backend: MemoryBackend::new for any caller context, such as MemoryBackend::<()>::default() for a deployment without identity.

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_objects<O: QueryObject + Send + Sync>( &self, caller: &C, account_id: &Id, params: QueryParams<'_, O>, ) -> Result<QueryResult, BackendQueryError<Self::Error>>

Returns the matching object ids in this account, sorted by id unless a Task sort says otherwise, paginated by position and limit.

§Task sort

A Task sort may use the docs/specs/jmap-tasks-local.md Sorting properties id, uid, start, created and updated, with no collation or i;octet, i;ascii-casemap or i;unicode-casemap (applied to id and uid). Ties are broken by id; a task without the sort property comes after the tasks with it in ascending order. With no time-zone database, start is compared as a LocalDateTime string and the call is unsupportedSort when the matched tasks with a start are in more than one zone (a floating task counts as the query’s zone, here Etc/UTC). Any other sort property, and any sort of another type, is unsupportedSort.

§Filter and other sorts are NOT honored

This reference implementation supports exactly one filter shape: a single Task condition whose only set fields are inTaskLists (which the TaskList/set onDestroyRemoveTasks cascade, draft-tasks-06 §3.4, needs), workflowStatus, progress, after and before (jmapio/jmap #456; see TasksBackend::query_tasks for the time-zone limit; here the query zone is Etc/UTC), and the draft-ietf-jmap-metadata-05 §3.6 shared-metadata conditions once MemoryBackend::with_metadata_info opts Task in. It does not support any other filter, or any sort beyond the Task sort above. RFC 8620 §5.5 mandates that an unsupported filter produces unsupportedFilter at the method level, and an unsupported sort produces unsupportedSort. A production backend MUST inspect both arguments against the type’s QueryObject supported sets and reject queries that exceed them.

To prevent consumers copying the silent-drop shape into a real backend (a workspace test-integrity hazard documented in the MemoryBackend module rustdoc), this method fails loud when either argument is non-trivial:

  • filter is Some carrying any non-null field other than those Task fields, or any operator tree it cannot evaluate → returns BackendQueryError::Method carrying unsupportedFilter. A metadata condition on a type that is not opted in is also unsupportedFilter, and a malformed one invalidArguments (draft-ietf-jmap-metadata-05 §3.6).
  • sort is Some with a comparator other than the Task sort above → returns BackendQueryError::Method carrying unsupportedSort.

Callers that want “all objects in this account” pass filter = None, sort = None.

Mirrors the reference-impl correctness teaching applied to the isDraft re-check in update_object (bd:JMAP-h47t.4): the demo backend models the spec invariant rather than the spec-violating shortcut.

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 those of the original /query and are applied by re-running Self::query_objects (a filter it refuses fails here the same way). removed holds the destroyed ids and the updated ids that no longer match (a Task moved out of the queried inTaskLists); added holds the created and updated ids that match now, with their index in the current result. Mirrors the canonical jmap-mail-server MemoryBackend::query_changes.

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§

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> TasksBackend for MemoryBackend<C>

Source§

async fn query_tasks( &self, caller: &C, account_id: &Id, params: QueryParams<'_, Task>, args: &TaskQueryArgs, ) -> Result<QueryResult, BackendQueryError<Self::Error>>

Task/query over the stored tasks.

Evaluates inTaskLists, workflowStatus, progress, after, before and the shared-metadata conditions in one FilterCondition; anything else, and any operator tree, is unsupportedFilter, as is after / before on a task whose timeZone is not the query’s (there is no time-zone database). With expandRecurrences the maxExpandedQueryDuration cap (TasksBackend::limits) is checked again; non-recurring matches keep their ids as their single instances, and a recurring match is cannotCalculateOccurrences, since there is no recurrence engine. Sorting is as in JmapReads::query_objects, with start and floating tasks read in the timeZone argument.

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 (TaskList or Task). Read more
Source§

async fn copy_object<O: SetObject + Send + Sync>( &self, _caller: &C, _from_account_id: &Id, to_account_id: &Id, obj: O, create: &Value, ) -> Result<(Id, O), BackendSetError<Self::Error>>

Store obj, a record read from from_account_id, as a new record in to_account_id, for /copy (RFC 8620 §5.4). 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 update_task_per_user( &self, caller: &C, account_id: &Id, id: &Id, patch: PatchObject, ) -> Result<Option<Task>, BackendSetError<Self::Error>>

Apply a patch that contains only per-user Task properties (draft-tasks-06 §4.5.1 — keywords, color, freeBusyStatus, useDefaultAlerts, alerts). 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 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§

async fn task_list_has_tasks( &self, _caller: &C, account_id: &Id, task_list_id: &Id, ) -> Result<bool, MemoryError>

Returns true if the given task list contains at least one task. Read more
Source§

fn compute_utc_times( &self, _caller: &Self::CallerCtx, _account_id: &Id, _task: &Task, _tz_hint: Option<&str>, ) -> impl Future<Output = (Option<UTCDate>, Option<UTCDate>)> + Send

Compute utcStart and utcDue for a Task by converting the task’s start/due local-time fields and time zone into UTC (draft-tasks-06 §4, utcStart/utcDue paragraphs). Read more
Source§

fn limits(&self, caller: &Self::CallerCtx, account_id: &Id) -> TasksLimits

Implementation-defined caps for account_id as seen by caller (workspace AGENTS.md “Backend caps and limits”). The default is TasksLimits::default; override it to vary caps per account.

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> 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> 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<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