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

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 (see the module documentation, “Caller context”).

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 (SceneAsset, SceneRegion, SceneObject) in every account, with retention; capability is also what ObjectHistoryBackend::object_history_capability advertises.

§Panics

When supportedTypes names another type.

Source

pub fn set_history_clock_for_test(&self, ms: i64)

Fix the history clock at ms milliseconds since the epoch.

Source§

impl MemoryBackend

Source

pub fn new() -> Self

An empty backend with no accounts, whose callers are Principal ids (C = Id). Equivalent to Self::default.

Source§

impl<C: MemoryCaller> MemoryBackend<C>

Source

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

Register account_id with the urn:ietf:params:jmap:scene account capability object it advertises, and return self for chaining.

Until an account is registered every method call naming it is accountNotFound (RFC 8620 §3.6.2). The builder form of Self::register_account.

use jmap_scene_server::memory::MemoryBackend;
use jmap_server::JmapAccounts;
use jmap_types::Id;

let capability = serde_json::from_value(serde_json::json!({
    "mayCreateRegion": true,
    "mayCreateObject": true,
    "supportedVisualTypes": ["model/gltf-binary"],
    "maxRegionsPerAccount": null,
    "maxObjectsPerRegion": null,
    "maxAvatarsPerRegion": null,
    "maxAssetSizeBytes": null,
    "supportsSceneAsset": false
}))?;
let account = Id::from("a1");
let backend = MemoryBackend::new().with_account(&account, capability);
let caller = Id::from("alice");
tokio::runtime::Runtime::new()?.block_on(async {
    assert!(backend.account_exists(&caller, &account).await?);
    assert!(!backend.account_exists(&caller, &Id::from("a2")).await?);
    Ok(())
})
§Panics

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

Source

pub fn register_account(&self, account_id: &Id, capability: SceneCapability)

Register account_id with the urn:ietf:params:jmap:scene account capability object it advertises: the &self form of Self::with_account, for a backend already shared with a dispatcher.

Registering an account again replaces its capability; its objects are kept.

§Panics

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

Source

pub fn advertise(&self, account_id: &Id, uri: &str)

Advertise the companion capability uri (e.g. urn:ietf:params:jmap:chat) on account_id, so SceneBackend::has_capability answers true for it. List the same capability in the account’s Session accountCapabilities.

Source

pub fn set_supports_observe(&self, on: bool)

Advertise (true) or withdraw supportsObserve, for SceneBackend::supports_observe. List the same value in the Session’s urn:ietf:params:jmap:scene:websocket capability.

Trait Implementations§

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 ScopedState-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 Scene Foo/set (bd JMAP-y1yu.15): the whole store is one ScopedState, so a scope isolates every account, and an atomic rollback restores objects, state strings, change logs, derived counts and queued deliveries together. Under an atomic scope the backend leaves maxAvatarsPerRegion 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<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§

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

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 metadata_info<O>( &self, caller: &Self::CallerCtx, account_id: &Id, ) -> Option<DataTypeMetadataInfo>
where O: JmapObject,

The draft-ietf-jmap-metadata-05 §1.2.1 DataTypeMetadataInfo of O in account_id, as seen by caller, or None when the account’s urn:ietf:params:jmap:metadata capability does not list O. 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 get_objects<O: GetObject + Send + Sync>( &self, _caller: &C, account_id: &Id, ids: Option<&[Id]>, _properties: Option<&[String]>, ) -> Result<(Vec<O>, Vec<Id>), MemoryError>

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

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

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

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

async fn query_changes<O: QueryObject + Send + Sync>( &self, _caller: &C, _account_id: &Id, _params: QueryChangesParams<'_, O>, ) -> Result<QueryChangesResult, BackendChangesError<MemoryError>>

Execute a /queryChanges and return deltas since since_query_state. 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> SceneBackend for MemoryBackend<C>

Source§

async fn observer_accounts( &self, _caller: &C, _own: &Id, ) -> Result<Vec<Id>, MemoryError>

Every registered account, in id order: access to each region is checked separately.

Source§

async fn scene_capability( &self, _caller: &C, account_id: &Id, ) -> Result<SceneCapability, MemoryError>

The account-level urn:ietf:params:jmap:scene capability object (draft-atwood-jmap-scene-00 §Account-Level Capability Object) the consumer advertises for account_id to this caller. Read more
Source§

async fn blob_size( &self, _caller: &C, account_id: &Id, blob_id: &Id, ) -> Result<Option<u64>, MemoryError>

The size in bytes of blob blob_id, or None if no such blob was uploaded to account_id (RFC 8620 §6.1). Read more
Source§

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

Create an 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<MemoryError>>

Apply an RFC 8620 §5.3 PatchObject 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<MemoryError>>

Destroy an object by id. Unknown id is notFound; the state advances only when the destroy commits. The handler has already applied the permission check. Read more
Source§

async fn may_modify_asset( &self, caller: &C, _account_id: &Id, asset: &SceneAsset, ) -> Result<bool, MemoryError>

true if the caller may update or destroy asset: “Only the asset owner or an admin may modify asset metadata” (draft-atwood-jmap-scene-00 §SceneAsset/set Update Errors; Destroy Errors use the “Same permission model as update”). Read more
Source§

fn has_capability(&self, _caller: &C, account_id: &Id, uri: &str) -> bool

true if the consumer advertises the capability uri for account_id. Read more
Source§

async fn region_binding( &self, _caller: &C, _account_id: &Id, property: BindingProperty, id: &Id, ) -> Result<BindingTarget, MemoryError>

What the binding property set to id references, for the checks of draft-atwood-jmap-scene-00 §Creating a Region (“the server MUST verify that the referenced object exists and the caller has access to it”) and §Updating a Region (for activeCallId: “(a) the referenced VTCCall exists, (b) its state is not \"ended\", and (c) the caller is a participant in or moderator of the referenced call, or has deployment-defined administrative privileges”). Read more
Source§

async fn channel_in_space( &self, _caller: &C, _account_id: &Id, channel_id: &Id, space_id: &Id, ) -> Result<bool, MemoryError>

true if channel_id “is a channel of the Space named by spaceId” (draft-atwood-jmap-scene-00 §Updating a Region, the binding checks). Read more
Source§

async fn may_update_region( &self, caller: &C, _account_id: &Id, region: &SceneRegion, ) -> Result<bool, MemoryError>

true if the caller may update region: “Only the owner or an admin may modify region properties” (draft-atwood-jmap-scene-00 §SceneRegion/set Update Errors). Read more
Source§

async fn may_destroy_region( &self, caller: &C, _account_id: &Id, region: &SceneRegion, ) -> Result<bool, MemoryError>

true if the caller may destroy region: “Only the region owner or an admin may destroy a region” (draft-atwood-jmap-scene-00 §SceneRegion/set Destroy Errors). Read more
Source§

async fn may_modify_object( &self, caller: &C, account_id: &Id, object: &SceneObject, ) -> Result<bool, MemoryError>

true if the caller may update or destroy object: “Only the object’s ownerId, the region owner, or a deployment-admin may modify another user’s object” (draft-atwood-jmap-scene-00 §SceneObject/set Update Errors; Destroy Errors use the “Same permission model as update”). Read more
Source§

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

The caller’s userId: “The authenticated user identity string” (draft-atwood-jmap-scene-00 §SceneAvatar userId). Read more
Source§

async fn may_enter_region( &self, caller: &C, _account_id: &Id, region: &SceneRegion, ) -> Result<bool, MemoryError>

true unless the caller is barred from entering region, which it already has access to: “User is banned or ejected with a cooldown period still active” (draft-atwood-jmap-scene-00 §Create Errors). SceneAvatar/set create and an update that re-enters a region return forbidden when this is false, since “The user already knows the region exists”. Access under the region’s accessPolicy is Self::may_access_region, not this hook: a create without it is invalidProperties naming regionId, a re-entry notFound. Read more
Source§

async fn may_access_region( &self, caller: &C, account_id: &Id, region_id: &Id, ) -> Result<bool, MemoryError>

true if the caller has access to region region_id (draft-atwood-jmap-scene-00 §Region Access): “A user has access to a region when its accessPolicy admits the user, when the user is the region owner, when the user has deployment-defined administrative privileges, or when the user has an active SceneAvatar in it.” "invite" admits “The users whose userIds are listed in invitedUserIds”, and “Servers MAY admit users to an \"invite\" region by other mechanisms as well”. Read more
Source§

async fn is_object_visible( &self, caller: &C, _account_id: &Id, object: &SceneObject, ) -> Result<bool, MemoryError>

true if object is in the caller’s visibility set: “The server SHOULD apply visibility filtering to limit the objects returned based on the authenticated user’s avatar position within the region. The specific visibility algorithm is deployment-defined” (draft-atwood-jmap-scene-00 §Visibility Contract). Read more
Source§

async fn is_user_blocked( &self, caller: &C, user_id: &str, ) -> Result<bool, MemoryError>

true if user_id is blocked on the caller’s own contact list (draft-atwood-jmap-scene-00 at 33702a5 §Blocked-Contact Spatial Presence, L2672): “SceneAvatar records belonging to a blocked ChatContact SHOULD be excluded from SceneAvatar/get responses and SceneAvatar/query results delivered to the blocking user”. Read more
Source§

async fn may_see_region_avatars( &self, caller: &C, _account_id: &Id, region_id: &Id, ) -> Result<bool, MemoryError>

true if the caller may see the SceneAvatar records of region region_id (draft-atwood-jmap-scene-00 at 6bcd9d8, L2654): “When a SceneRegion’s activeCallId references a VTCCall with e2eeEnabled set to true, the server SHOULD NOT expose the region’s SceneAvatar records to users who are not participants in the bound VTCCall: for such users it SHOULD return notFound for SceneAvatar/get, exclude the records from SceneAvatar/query, and suppress SceneAvatarEvent … delivery (entered, left, and ejected).” Read more
Source§

async fn avatar_view( &self, caller: &C, account_id: &Id, avatar: &SceneAvatar, ) -> Result<AvatarView, MemoryError>

What the caller may see of avatar, another user’s avatar (draft-atwood-jmap-scene-00 at jmap-chat-spec 93f2258, §Avatar Visibility): “A server MAY also limit which SceneAvatar records, and which of their properties, each caller sees: for example, to keep opponents’ positions from players during a competitive round”. The rule is deployment-defined. Read more
Source§

fn supports_observe(&self, _caller: &C) -> bool

true if the server advertises supportsObserve in its urn:ietf:params:jmap:scene:websocket Session capability (SceneWebSocketCapability; draft-atwood-jmap-scene-wss-00 at jmap-chat-spec 93f2258). Read more
Source§

async fn may_observe_region( &self, _caller: &C, _account_id: &Id, region: &SceneRegion, ) -> Result<bool, MemoryError>

true unless the server declines observers of region for deployment-defined policy: “A server MAY also decline observers of a region for deployment-defined policy reasons even when allowObservers is true” (jmap-chat-spec 93f2258 §SceneStreamEnable). Read more
Source§

async fn set_observing( &self, caller: &C, account_id: &Id, region_id: &Id, observing: bool, ) -> Result<(), MemoryError>

Record that one connection of the caller started (observing true) or stopped (false) observing region region_id of account_id (jmap-chat-spec 93f2258, observerCount). Read more
Source§

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

The reserved display names (draft-atwood-jmap-scene-00 §Avatar Identity and Impersonation, jmap-chat-spec 77c3474 L2776): “The server MAY maintain a list of reserved display names that correspond to system roles or administrative functions and MAY reject SceneAvatar/set operations that attempt to use a reserved name with a SetError of type forbidden.” This crate rejects them by choice. Read more
Source§

async fn may_eject_avatar( &self, caller: &C, account_id: &Id, avatar: &SceneAvatar, ) -> Result<bool, MemoryError>

true if the caller may eject avatar, another user’s avatar: “region owners and administrators may set leftAt on another user’s avatar to eject them” (draft-atwood-jmap-scene-00 §Update Errors). Read more
Source§

async fn accept_interaction( &self, _caller: &C, _account_id: &Id, event: &SceneInteractionEvent, ) -> Result<bool, MemoryError>

Accept an interaction that passed the SceneObject/interact checks, or refuse it for its rate (draft-atwood-jmap-scene-00 §SceneObject/interact). Read more
Source§

async fn accept_region_event( &self, caller: &C, account_id: &Id, event: &SceneRegionEvent, ) -> Result<bool, MemoryError>

Accept a region event that passed the SceneRegion/broadcast checks, or refuse it for its rate (draft-atwood-jmap-scene-00 at jmap-chat-spec 93f2258, §SceneRegion/broadcast). Read more
Source§

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

Per-backend capability probe: true if this backend supports the JMAP object type O for account_id. Not called by the handlers; consumers use it when assembling their Session capabilities (“Deployments … MAY omit support for SceneAsset methods”).
Source§

fn avatar_display_name( &self, caller: &Self::CallerCtx, account_id: &Id, user_id: &str, ) -> impl Future<Output = Result<String, Self::Error>> + Send

The displayName of a new avatar for user_id when the create supplies none: “the server sets it from the user profile or ChatContact when {{JMAP-CHAT}} is present”. Read more

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