Development Documentation (main branch) - For stable release docs, see docs.rs/eidetica

Instance

Struct Instance 

Source
pub struct Instance { /* private fields */ }
Expand description

Database implementation on top of the storage backend.

Instance manages infrastructure only:

  • Backend storage and device identity
  • System databases (_users, _databases, _sync)
  • User account management (create, login, list)

All database creation and key operations happen through User after login.

Instance is a cheap-to-clone handle around Arc<InstanceInternal>.

§Example

let instance = Instance::open(Box::new(InMemory::new())).await?;

// Create passwordless user
instance.create_user("alice", None).await?;
let mut user = instance.login_user("alice", None).await?;

// Use User API for operations
let mut settings = Doc::new();
settings.set("name", "my_database");
let default_key = user.get_default_key()?;
let db = user.create_database(settings, &default_key).await?;

Implementations§

Source§

impl Instance

Source

pub async fn open(backend: Box<dyn BackendImpl>) -> Result<Self>

Load an existing Instance or create a new one (recommended).

This is the recommended method for initializing an Instance. It automatically detects whether the backend contains existing system state (device key and system databases) and loads them, or creates new ones if starting fresh.

Instance manages infrastructure only:

  • Backend storage and device identity
  • System databases (_users, _databases, _sync)
  • User account management (create, login, list)

All database creation and key operations require explicit User login.

§Arguments
  • backend - The storage backend to use
§Returns

A Result containing the configured Instance

§Example
let backend = InMemory::new();
let instance = Instance::open(Box::new(backend)).await?;

// Create and login user explicitly
instance.create_user("alice", None).await?;
let mut user = instance.login_user("alice", None).await?;

// Use User API for operations
let mut settings = Doc::new();
settings.set("name", "my_database");
let default_key = user.get_default_key()?;
let db = user.create_database(settings, &default_key).await?;
Source

pub async fn open_with_clock( backend: Box<dyn BackendImpl>, clock: Arc<dyn Clock>, ) -> Result<Self>

Load an existing Instance or create a new one with a custom clock.

This is the same as Instance::open but allows injecting a custom clock for controllable timestamps in tests. The clock is used for timestamps in height calculations and peer tracking.

Only available with the testing feature or in test builds.

§Arguments
  • backend - The storage backend to use
  • clock - The time provider to use (typically FixedClock)
§Returns

A Result containing the configured Instance

Source

pub async fn create(backend: Box<dyn BackendImpl>) -> Result<Self>

Create a new Instance on a fresh backend (strict creation).

This method creates a new Instance and fails if the backend is already initialized (contains a device key and system databases). Use this when you want to ensure you’re creating a fresh instance.

Instance manages infrastructure only:

  • Backend storage and device identity
  • System databases (_users, _databases, _sync)
  • User account management (create, login, list)

All database creation and key operations require explicit User login.

For most use cases, prefer Instance::open() which automatically handles both new and existing backends.

§Arguments
  • backend - The storage backend to use (must be uninitialized)
§Returns

A Result containing the configured Instance, or InstanceAlreadyExists error if the backend is already initialized.

§Example
let backend = InMemory::new();
let instance = Instance::create(Box::new(backend)).await?;

// Create and login user explicitly
instance.create_user("alice", None).await?;
let mut user = instance.login_user("alice", None).await?;

// Use User API for operations
let mut settings = Doc::new();
settings.set("name", "my_database");
let default_key = user.get_default_key()?;
let db = user.create_database(settings, &default_key).await?;
Source

pub fn backend(&self) -> &Backend

Get a reference to the backend

Source

pub async fn has_entry(&self, id: &ID) -> bool

Check if an entry exists in storage.

Source

pub async fn has_database(&self, root_id: &ID) -> bool

Check if a database is present locally.

This differs from has_entry in that it checks for the active tracking of the database by the Instance. This method checks if we’re tracking the database’s tip state.

Source

pub async fn create_user( &self, user_id: &str, password: Option<&str>, ) -> Result<String>

Create a new user account with flexible password handling.

Creates a user with or without password protection. Passwordless users are appropriate for embedded applications where filesystem access = database access.

§Arguments
  • user_id - Unique user identifier (username)
  • password - Optional password. If None, user is passwordless (instant login, no encryption)
§Returns

A Result containing the user’s UUID (stable internal identifier)

Source

pub async fn login_user( &self, user_id: &str, password: Option<&str>, ) -> Result<User>

Login a user with flexible password handling.

Returns a User session object that provides access to user operations. For password-protected users, provide the password. For passwordless users, pass None.

§Arguments
  • user_id - User identifier (username)
  • password - Optional password. None for passwordless users.
§Returns

A Result containing the User session

Source

pub async fn list_users(&self) -> Result<Vec<String>>

List all user IDs.

§Returns

A Result containing a vector of user IDs

Source

pub fn device_key(&self) -> &PrivateKey

Test-only: Get the device signing key.

This is exposed for testing purposes only. In production, use the User API.

Source

pub fn device_id(&self) -> PublicKey

Get the device ID (public key).

§Returns

The device’s public key (device ID).

Source

pub async fn enable_sync(&self) -> Result<()>

Initializes the Sync module for this instance.

Enables synchronization operations for this instance. This method is idempotent; calling it multiple times has no effect.

§Errors

Returns an error if the sync settings database cannot be created or if device key generation/storage fails.

Source

pub fn sync(&self) -> Option<Arc<Sync>>

Get a reference to the Sync module.

Returns a cheap-to-clone Arc handle to the Sync module. The Sync module uses interior mutability (AtomicBool and OnceLock) so &self methods are sufficient.

§Returns

An Option containing an Arc<Sync> if the Sync module is initialized.

Source

pub async fn flush_sync(&self) -> Result<()>

Flush all pending sync operations.

This is a convenience method that processes all queued entries and retries any failed sends. If sync is not enabled, returns Ok(()).

This is useful to force pending syncs to complete, e.g. on program shutdown.

§Returns

Ok(()) if sync is not enabled or all operations completed successfully, or an error if sends failed.

Source

pub async fn put_entry( &self, tree_id: &ID, verification: VerificationStatus, entry: Entry, source: WriteSource, ) -> Result<()>

Write an entry to the backend and dispatch callbacks.

This is the central coordination point for all entry writes in the system. All writes must go through this method to ensure:

  • Entries are persisted to the backend
  • Appropriate callbacks are triggered based on write source
  • Hooks have full context (entry, database, instance)
§Arguments
  • tree_id - The root ID of the database being written to
  • verification - Authentication verification status of the entry
  • entry - The entry to write
  • source - Whether this is a local or remote write
§Returns

A Result indicating success or failure

Source

pub fn downgrade(&self) -> WeakInstance

Downgrade to a weak reference.

Creates a weak reference that does not prevent the Instance from being dropped. This is useful for preventing circular reference cycles in dependent objects.

§Returns

A WeakInstance that can be upgraded back to a strong reference.

Trait Implementations§

Source§

impl Clone for Instance

Source§

fn clone(&self) -> Instance

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Instance

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Handle for Instance

§

fn handle(&self) -> Self

Creates a new handle to the same underlying resource. Read more

Auto Trait Implementations§

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
§

impl<T> CompatExt for T

§

fn compat(self) -> Compat<T>

Applies the [Compat] adapter by value. Read more
§

fn compat_ref(&self) -> Compat<&T>

Applies the [Compat] adapter by shared reference. Read more
§

fn compat_mut(&mut self) -> Compat<&mut T>

Applies the [Compat] adapter by mutable reference. Read more
Source§

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

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

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

§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
§

impl<T> Instrument for T

§

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

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

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

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

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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

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

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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