dittolive_ditto

Struct Ditto

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

The entrypoint for accessing all Ditto functionality.

Use the Ditto object to access all other Ditto APIs, such as:

Implementations§

Source§

impl Ditto

Source

pub async fn open(config: DittoConfig) -> Result<Ditto, DittoError>

Open a new Ditto instance using a DittoConfig

§Example
// Load your database ID somehow, ENV is a good option
let database_id = std::env::var("DITTO_DATABASE_ID")?;

// Choose one of the following types of connection config
let connect = DittoConfigConnect::Server {
    url: "https://example.com/your-server-url".parse().unwrap(),
};
let connect = DittoConfigConnect::SmallPeersOnly {
    private_key: Some("https://example.com/your-server-url".bytes().collect()),
};
let connect = DittoConfigConnect::SmallPeersOnly { private_key: None };

let config = DittoConfig::new(database_id, connect);
let ditto = Ditto::open(config).await?;
Source

pub fn open_sync(config: DittoConfig) -> Result<Ditto, DittoError>

Open a new Ditto instance using a DittoConfig

This is a synchronous blocking variant of Ditto::open() that will wait until initialization is complete.

§Example
// Load your database ID somehow, ENV is a good option
let database_id = std::env::var("DITTO_DATABASE_ID")?;

// Choose one of the following types of connection config
let connect = DittoConfigConnect::Server {
    url: "https://example.com/your-server-url".parse().unwrap(),
};
let connect = DittoConfigConnect::SmallPeersOnly {
    private_key: Some("https://example.com/your-server-url".bytes().collect()),
};
let connect = DittoConfigConnect::SmallPeersOnly { private_key: None };

let config = DittoConfig::new(database_id, connect);
let ditto = Ditto::open_sync(config)?;
Source§

impl Ditto

Source

pub fn close(self)

Clean shutdown of the Ditto instance

Source

pub fn start_sync(&self) -> Result<(), DittoError>

Starts the network transports. Ditto will connect to other devices.

By default, Ditto will enable all peer-to-peer transport types. The network configuration can be customized using set_transport_config.

Performance of initial sync when bootstrapping a new peer can be improved by calling disable_sync_with_v3 before calling start_sync. Only do this when all peers in the mesh are known to be running Ditto v4 or higher.

Source

pub fn stop_sync(&self)

Stop syncing on all transports.

You may continue to use the Ditto store locally but no data will sync to or from other devices.

Source

pub fn is_sync_active(&self) -> bool

Returns true if sync is currently active, otherwise returns false.

Use Ditto::start_sync to activate and Ditto::stop_sync to deactivate sync.

Source

pub fn set_transport_config(&self, config: TransportConfig)

Set a new TransportConfig and begin syncing over these transports. Any change to start or stop a specific transport should proceed via providing a modified configuration to this method.

Source

pub fn update_transport_config(&self, update: impl FnOnce(&mut TransportConfig))

Convenience method to update the current transport config of the receiver.

Invokes the block with a copy of the current transport config which you can alter to your liking. The updated transport config is then set on the receiver.

You may use this method to alter the configuration at any time. Sync will not begin until ditto.start_sync() is invoked.

§Example

Edit the config by simply mutating the &mut TransportConfig passed to your callback:

use dittolive_ditto::prelude::*;

// Enable the TCP listener on port 4000
ditto.update_transport_config(|config| {
    config.listen.tcp.enabled = true;
    config.listen.tcp.interface_ip = "0.0.0.0".to_string();
    config.listen.tcp.port = 4000;
});
Source

pub fn transport_config(&self) -> TransportConfig

Returns a snapshot of the currently configured transports.

§Example
let transport_config = ditto.transport_config();
println!("Current transport config: {transport_config:#?}");
Source§

impl Ditto

Source

pub fn with_sdk_version<R>(ret: impl FnOnce(&str) -> R) -> R

Return the version of the SDK.

Source§

impl Ditto

Source

pub fn set_offline_only_license_token( &self, license_token: &str, ) -> Result<(), DittoError>

Activate an offline Ditto instance by setting a license token.

You cannot initiate sync on an offline (OfflinePlayground, Manual, or SharedKey) Ditto instance before you have activated it.

Source

pub fn set_license_from_env(&self, var_name: &str) -> Result<(), DittoError>

Look for a license token from a given environment variable.

Source§

impl Ditto

Source

pub fn store(&self) -> &Store

Returns a reference to the underlying local data store.

Source

pub fn sync(&self) -> &Sync

Entrypoint to Ditto’s Sync API for syncing documents between peers.

Source

pub fn small_peer_info(&self) -> &SmallPeerInfo

Return a reference to the SmallPeerInfo object.

Source

pub fn absolute_persistence_directory(&self) -> PathBuf

The absolute path to the persistence directory used by Ditto to persist data.

This returns the final, resolved absolute file path where Ditto stores its data. The value depends on what was provided in DittoConfig::persistence_directory.

  • If an absolute path was provided, it returns that path unchanged.
  • If a relative path was provided, it returns the path resolved relative to [ditto.default_root_directory()].
  • If no path was provided, it returns the default path using the pattern {default_root}/ditto-{database-id} where {default_root} corresponds to [ditto.default_root_directory()] and {database-id} is the Ditto database ID in lowercase.

This property always returns a consistent value throughout the lifetime of the Ditto instance and represents the actual directory being used for persistence.

  • Note: “Database ID” was previously referred to as “App ID” in older versions of the SDK.

  • Note: It is not recommended to directly read or write to this directory as its structure and contents are managed by Ditto and may change in future versions.

  • Note: When DittoLogger is enabled, logs may be written to this directory even after a Ditto instance has been deallocated. Please refer to the documentation of DittoLogger for more information.

  • See also: DittoConfig::persistence_directory

Source

pub fn config(&self) -> DittoConfig

Returns an owned snapshot of the effective DittoConfig as used by the core library.

  • Modifying this DittoConfig have no effect on the active Ditto configuration.
  • The returned DittoConfig may be different than the one passed to [Ditto::open{,_sync}] because it will have resolved details such as the absolute path to the persistence directory.
Source

pub fn app_id(&self) -> AppId

Returns the AppId being used by this Ditto instance.

Source

pub fn set_device_name(&self, name: &str)

Set a custom identifier for the current device.

When using observe_peers, each remote peer is represented by a short UTF-8 “device name”. By default this will be a truncated version of the device’s hostname. It does not need to be unique among peers. Configure the device name before calling start_sync. If it is too long it will be truncated.

Source

pub fn presence(&self) -> &Arc<Presence>

Return a handle to the Presence API to monitor peers’ activity in the Ditto mesh.

§Example

Use ditto.presence().graph() to request a current PresenceGraph of connected peers:

use dittolive_ditto::prelude::*;

let presence_graph: PresenceGraph = ditto.presence().graph();
println!("Ditto mesh right now: {presence_graph:#?}");
§Example

Use ditto.presence().observe(...) to subscribe to changes in mesh presence:

use dittolive_ditto::prelude::*;

let _observer = ditto.presence().observe(|graph| {
    println!("Ditto mesh update! {graph:#?}");
});

// The observer is cancelled when dropped.
// In a real application, hold onto it for as long as you need it alive.
drop(_observer);
Source

pub fn disk_usage(&self) -> &DiskUsage

Return a DiskUsage to monitor the disk usage of the Ditto instance. It can be used to retrieve an immediate representation of the Ditto file system:

let fs_tree = ditto.disk_usage().exec();

Or to bind a callback to the changes :

let handle = ditto.disk_usage().observe(|fs_tree| {
    // do something with the graph
});
// The handle must be kept to keep receiving updates on the file system.
// To stop receiving update, drop the handle.
Source

pub fn auth(&self) -> Option<DittoAuthenticator>

Returns the current DittoAuthenticator, if it exists.

The DittoAuthenticator is available when using the OnlinePlayground and OnlineWithAuthentication identities.

Source

pub fn is_activated(&self) -> bool

Returns true if this Ditto instance has been activated with a valid license token.

Source§

impl Ditto

Source

pub fn builder() -> DittoBuilder

Entrypoint to constructing Ditto with the builder pattern.

§Example
use dittolive_ditto::prelude::*;

fn main() -> anyhow::Result<()> {
    let app_id = AppId::from_env("DITTO_APP_ID")?;
    let playground_token = std::env::var("DITTO_PLAYGROUND_TOKEN")?;
    let cloud_sync = true;
    let custom_auth_url = None;

    // Initialize Ditto
    let ditto = Ditto::builder()
        .with_root(Arc::new(PersistentRoot::from_current_exe()?))
        .with_identity(|ditto_root| {
            identity::OnlinePlayground::new(
                ditto_root,
                app_id,
                playground_token,
                cloud_sync,
                custom_auth_url,
            )
        })?
        .build()?;

    Ok(())
}

See the crate docs for examples of what to do next using Ditto.

Source§

impl Ditto

Source

pub fn run_garbage_collection(&self)

Removes all sync metadata for any remote peers which aren’t currently connected. This method shouldn’t usually be called. Manually running garbage collection often will result in slower sync times. Ditto automatically runs a garbage a collection process in the background at optimal times.

Manually running garbage collection is typically only useful during testing if large amounts of data are being generated. Alternatively, if an entire data set is to be evicted and it’s clear that maintaining this metadata isn’t necessary, then garbage collection could be run after evicting the old data.

Source

pub fn disable_sync_with_v3(&self) -> Result<(), DittoError>

Disable sync with peers running version 3 or lower of the Ditto SDK.

Required for the execution of mutating DQL statements.

This setting spreads to other peers on connection. Those peers will in turn spread it further until all peers in the mesh take on the same setting. This is irreversible and will persist across restarts of the Ditto instance.

Calling this method before calling start_sync is recommended whenever possible. This improves performance of initial sync when this peer has never before connected to a Ditto mesh for which sync with v3 peers is disabled.

Trait Implementations§

Source§

impl Deref for Ditto

Source§

type Target = DittoFields

The resulting type after dereferencing.
Source§

fn deref(&self) -> &DittoFields

Dereferences the value.
Source§

impl Drop for Ditto

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl Freeze for Ditto

§

impl !RefUnwindSafe for Ditto

§

impl Send for Ditto

§

impl Sync for Ditto

§

impl Unpin for Ditto

§

impl !UnwindSafe for Ditto

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
§

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
§

impl<T> FitForCArc for T

§

type CArcWrapped = ThinArc<T>

§

impl<T> FitForCBox for T

§

type CBoxWrapped = ThinBox<T>

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

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.

§

impl<T> ManuallyDropMut for T

§

type Ret = ManuallyDrop<T>

§

fn manually_drop_mut<'__>(&'__ mut self) -> &'__ mut ManuallyDrop<T>

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
§

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

§

fn to<T>(self) -> T
where Self: Into<T>,

Converts to T by calling Into<T>::into.
§

fn try_to<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Tries to convert to T by calling TryInto<T>::try_into.
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
§

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

§

impl<F> ZeroSizedElseWrathOfTheGඞds for F