Skip to main content

RoutingContext

Struct RoutingContext 

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

Routing contexts are the way you specify the communication preferences for Veilid.

By default routing contexts have ‘safety routing’ enabled which offers sender privacy. privacy. To disable this and send RPC operations straight from the node use RoutingContext::with_safety() with a SafetySelection::Unsafe parameter. To enable receiver privacy, you should send to a private route RouteId that you have imported, rather than directly to a NodeId.

Implementations§

Source§

impl RoutingContext

Source

pub fn with_default_safety(self) -> VeilidAPIResult<Self>

Turn on sender privacy, enabling the use of safety routes. This is the default and calling this function is only necessary if you have previously disable safety or used other parameters.

Default values for hop count, stability and sequencing preferences are used.

  • Hop count default is dependent on config, but is set to 1 extra hop.
  • Stability default is to choose reliable routes, preferring them over low latency.
  • Sequencing default is to prefer ordered before unordered message delivery.

To customize the safety selection in use, use RoutingContext::with_safety().

Errors with VeilidAPIError::NotInitialized if the node is shut down (config unavailable).

Source

pub fn with_safety( self, safety_selection: SafetySelection, ) -> VeilidAPIResult<Self>

Use a custom SafetySelection. Can be used to disable safety via SafetySelection::Unsafe.

Errors with VeilidAPIError::Generic if SafetySelection::Unsafe is requested without the footgun-nodeid-target feature, or if hop_count exceeds the configured max route hop count. Errors with VeilidAPIError::InvalidArgument if a preferred_route is set that is not a known route id.

Source

pub fn with_sequencing(self, sequencing: Sequencing) -> Self

Use a specified Sequencing preference, with or without privacy.

Source

pub fn safety(&self) -> SafetySelection

Get the safety selection in use on this routing context.

Source

pub fn sequencing(&self) -> Sequencing

Get the sequencing used by this routing context

Source

pub fn api(&self) -> VeilidAPI

Get the VeilidAPI object that created this RoutingContext.

Source

pub async fn app_call( &self, target: Target, message: Vec<u8>, ) -> VeilidAPIResult<Vec<u8>>

App-level bidirectional call that expects a response to be returned.

Veilid apps may use this for arbitrary message passing.

  • target - a private route id
  • message - an arbitrary message blob of up to 32768 bytes.

Returns an answer blob of up to 32768 bytes.

Blocks on the network awaiting the reply; governed by network.rpc.timeout_ms.

Errors with VeilidAPIError::InvalidTarget if target is a NodeId (only RouteId is permitted without the footgun-nodeid-target feature). Otherwise errors with VeilidAPIError::NoConnection if the route could not be resolved or allocated (retryable), ::Timeout if the reply deadline elapsed (retryable), or ::TryAgain if a route is temporarily unavailable (retryable).

Source

pub async fn app_message( &self, target: Target, message: Vec<u8>, ) -> VeilidAPIResult<()>

App-level unidirectional message that does not expect any value to be returned.

Veilid apps may use this for arbitrary message passing.

  • target - a private route.
  • message - an arbitrary message blob of up to 32768 bytes.

Sends over the network but does not await a reply; returns once the statement is dispatched.

Errors with VeilidAPIError::InvalidTarget if target is a NodeId (only RouteId is permitted without the footgun-nodeid-target feature). Otherwise errors with VeilidAPIError::NoConnection if the route could not be resolved or allocated (retryable), ::Timeout if dispatch timed out (retryable), or ::TryAgain if a route is temporarily unavailable (retryable).

Source

pub async fn create_dht_record( &self, kind: CryptoKind, schema: DHTSchema, owner: Option<KeyPair>, ) -> VeilidAPIResult<DHTRecordDescriptor>

Creates a new DHT record

The record is considered ‘open’ after the create operation succeeds.

  • ‘kind’ - specify a cryptosystem kind to use
  • ‘schema’ - the schema to use when creating the DHT record
  • ‘owner’ - optionally specify an owner keypair to use. If you leave this as None then a random one will be generated. If specified, the crypto kind of the owner must match that of the kind parameter

Returns the newly allocated DHT record’s key if successful. Note: if you pass in an owner keypair this call is a deterministic! This means that if you try to create a new record for a given owner and schema that already exists it will fail.

Local-only: builds and opens the record in the local store without network fanout. The returned record is left open; close it with RoutingContext::close_dht_record or it leaks the open handle.

Errors with VeilidAPIError::Generic if kind is an unsupported crypto kind or owner is a malformed keypair. Errors with VeilidAPIError::InvalidArgument if schema has an invalid subkey/member/writer count, if owner is the wrong crypto kind for kind, or if this node’s id would be a schema member. Errors with VeilidAPIError::NotInitialized if the node is shut down.

Source

pub async fn open_dht_record( &self, record_key: RecordKey, default_writer: Option<KeyPair>, ) -> VeilidAPIResult<DHTRecordDescriptor>

Opens a DHT record at a specific key.

Associates a ‘default_writer’ secret if one is provided to provide writer capability. The writer can be overridden if specified here via the set_dht_value writer.

Records may only be opened or created. If a record is re-opened it will use the new writer and routing context ignoring the settings of the last time it was opened. This allows one to open a record a second time without first closing it, which will keep the active ‘watches’ on the record but change the default writer or safety selection.

Returns the DHT record descriptor for the opened record if successful.

Half of an open/close pair: close it with RoutingContext::close_dht_record or the open handle and its watches leak. Re-opening an already-open record is safe and replaces the writer and safety selection in place, preserving active watches. Returns from the local store without a network round-trip when the record is already local; otherwise blocks on a network inspect (subkey 0), and returns TryAgain if offline.

Errors with VeilidAPIError::Generic if record_key is an unsupported kind or malformed, or default_writer is a malformed keypair. Errors with VeilidAPIError::TryAgain if the record is not yet local and the node is offline (retryable), ::KeyNotFound if the record does not exist on the network, and ::NotInitialized if the node is shut down.

Source

pub async fn close_dht_record( &self, record_key: RecordKey, ) -> VeilidAPIResult<()>

Closes a DHT record at a specific key that was opened with create_dht_record or open_dht_record.

Closing a record allows you to re-open it with a different routing context.

The release half of the open/close pair; cancels the record’s watch (in the background) and drops any associated transaction. Blocks holding the record lock until pending writes are flushed to the local store (awaits a disk flush). Closing a record that is local but not currently open is a no-op; closing one not in the local store returns KeyNotFound.

Errors with VeilidAPIError::Generic if record_key is an unsupported kind or malformed, and ::NotInitialized if the node is shut down. Neither KeyNotFound nor these errors are retryable.

Source

pub async fn flush_dht_record( &self, record_key: RecordKey, timeout: Option<Duration>, ) -> VeilidAPIResult<bool>

Waits for any pending offline subkey writes for a DHT record to be flushed to the network.

Returns immediately with Ok(true) if there are no pending writes. When a timeout is specified, returns Ok(true) if all pending writes were flushed, or Ok(false) if timeout elapsed first. When no timeout is specified, waits indefinitely for writes to be flushed and then returns Ok(true). If the system shuts down while waiting, returns Err(VeilidAPIError::NotInitialized). Errors with VeilidAPIError::Generic if record_key is an unsupported kind or malformed.

Blocks until pending writes flush, the timeout elapses, or shutdown; non-blocking when there are no pending writes.

Source

pub async fn delete_dht_record( &self, record_key: RecordKey, ) -> VeilidAPIResult<()>

Deletes a DHT record at a specific key.

If the record is opened, it must be closed before it is deleted. Deleting a record does not delete it from the network, but will remove the storage of the record locally, and will prevent its value from being refreshed on the network by this node.

Local-only: closes the record if still open, then removes it from the local store; no network round-trip.

Errors with VeilidAPIError::Generic if record_key is an unsupported kind or malformed, ::KeyNotFound if the record is not in the local store, and ::NotInitialized if the node is shut down. None are retryable.

Source

pub async fn get_dht_value( &self, record_key: RecordKey, subkey: ValueSubkey, force_refresh: bool, ) -> VeilidAPIResult<Option<ValueData>>

Gets the latest value of a subkey.

May pull the latest value from the network, but by setting ‘force_refresh’ you can force a network data refresh. Can only be used on opened records.

Returns None if the value subkey has not yet been set. Returns Some(data) if the value subkey has valid data.

Non-blocking when a local value exists and force_refresh is false; otherwise blocks on a network fanout and returns TryAgain if offline.

Errors with VeilidAPIError::InvalidArgument if the record is not open, ::Generic if record_key is an unsupported kind or malformed, ::TryAgain if a network refresh is needed and the node is offline (retryable), ::KeyNotFound if the record no longer exists, and ::NotInitialized if shut down.

Source

pub async fn set_dht_value( &self, record_key: RecordKey, subkey: ValueSubkey, data: Vec<u8>, options: Option<SetDHTValueOptions>, ) -> VeilidAPIResult<Option<ValueData>>

Pushes a changed subkey value to the network. The DHT record must first by opened via open_dht_record or create_dht_record.

The writer, if specified, will override the ‘default_writer’ specified when the record is opened.

Returns None if the value was successfully set. Returns Some(data) if the value set was older than the one available on the network.

Blocks on a network fanout to push the value; when offline or the fanout fails, queues the write for later flush (if allow_offline) and returns Ok(None).

Errors with VeilidAPIError::InvalidArgument if the record is not open, ::Generic if record_key is an unsupported kind or the record is not writable (no writer) or the value fails schema validation (subkey out of schema range, data larger than the per-subkey limit, or wrong writer for the subkey), ::TryAgain if the record is currently in a transaction (retryable), ::KeyNotFound if the record no longer exists, and ::NotInitialized if shut down. A failed network fanout does not error; the write is deferred (returns Ok(None)).

Source

pub async fn watch_dht_values( &self, record_key: RecordKey, subkeys: Option<ValueSubkeyRangeSet>, expiration: Option<Timestamp>, count: Option<u32>, ) -> VeilidAPIResult<bool>

Add or update a watch to a DHT value that informs the user via an VeilidUpdate::ValueChange callback when the record has subkeys change. One remote node will be selected to perform the watch and it will offer an expiration time based on a suggestion, and make an attempt to continue to report changes via the callback. Nodes that agree to doing watches will be put on our ‘ping’ list to ensure they are still around otherwise the watch will be cancelled and will have to be re-watched. Can only be used on opened records.

There is only one watch permitted per record. If a change to a watch is desired, the previous one will be overwritten.

  • key is the record key to watch. it must first be opened for reading or writing.
  • subkeys:
    • None: specifies watching the entire range of subkeys.
    • Some(range): is the the range of subkeys to watch. The range must not exceed 512 discrete non-overlapping or adjacent subranges. If no range is specified, this is equivalent to watching the entire range of subkeys.
  • expiration:
    • None: specifies a watch with no expiration
    • Some(timestamp): the desired timestamp of when to automatically terminate the watch, in microseconds. If this value is less than network.rpc.timeout_ms milliseconds in the future, this function will return an error immediately.
  • `count:
    • None: specifies a watch count of u32::MAX
    • Some(count): is the number of times the watch will be sent, maximum. A zero value here is equivalent to a cancellation.

Returns Ok(true) if a watch is active for this record. Returns Ok(false) if the entire watch has been cancelled.

Re-watching the same record replaces the prior watch’s desired parameters in place; only one watch exists per record. Records the desired watch state and returns without a network round-trip; a background task reconciles it with a remote node.

Errors with VeilidAPIError::InvalidArgument if the record is not open or a non-zero expiration is sooner than network.rpc.timeout_ms in the future; ::Generic if record_key is an unsupported kind or malformed, or no local record is found; and ::NotInitialized if shut down. None are retryable; no network errors surface here since reconciliation is deferred to a background task.

DHT watches are accepted with the following conditions:

  • First-come first-served basis for arbitrary unauthenticated readers, up to network.dht.public_watch_limit per record.
  • If a member (either the owner or a SMPL schema member) has opened the key for writing (even if no writing is performed) then the watch will be signed and guaranteed network.dht.member_watch_limit per writer.

Members can be specified via the SMPL schema and do not need to allocate writable subkeys in order to offer a member watch capability.

Source

pub async fn cancel_dht_watch( &self, record_key: RecordKey, subkeys: Option<ValueSubkeyRangeSet>, ) -> VeilidAPIResult<bool>

Cancels a watch early.

This is a convenience function that cancels watching all subkeys in a range. The subkeys specified here are subtracted from the currently-watched subkey range. Can only be used on opened records.

  • subkeys:
    • None: specifies watching the entire range of subkeys.
    • Some(range): is the the range of subkeys to watch. The range must not exceed 512 discrete non-overlapping or adjacent subranges. If no range is specified, this is equivalent to watching the entire range of subkeys.

Only the subkey range is changed, the expiration and count remain the same. If no subkeys remain, the watch is entirely cancelled and will receive no more updates.

Returns Ok(true) if a watch is active for this record. Returns Ok(false) if the entire watch has been cancelled.

A no-op returning Ok(false) when no watch is active for the record. Records the reduced desired watch state and returns without a network round-trip; a background task sends the cancel.

Errors with VeilidAPIError::InvalidArgument if the record is not open, ::Generic if record_key is an unsupported kind or malformed or no local record is found, and ::NotInitialized if shut down. None are retryable.

Source

pub async fn inspect_dht_record( &self, record_key: RecordKey, subkeys: Option<ValueSubkeyRangeSet>, scope: DHTReportScope, ) -> VeilidAPIResult<DHTRecordReport>

Inspects a DHT record for subkey state. This is useful for checking if you should push new subkeys to the network, or retrieve the current state of a record from the network to see what needs updating locally. Can only be used on opened records.

  • key is the record key to inspect. it must first be opened for reading or writing.

  • subkeys:

    • None: specifies inspecting the entire range of subkeys.
    • Some(range): is the the range of subkeys to inspect. The range must not exceed 512 discrete non-overlapping or adjacent subranges. If no range is specified, this is equivalent to watching the entire range of subkeys.
  • scope is what kind of range the inspection has:

    • DHTReportScope::Local` Results will be only for a locally stored record. Useful for seeing what subkeys you have locally and which ones have not been retrieved.

    • DHTReportScope::SyncGet Return the local sequence numbers and the network sequence numbers with GetValue fanout parameters. Provides an independent view of both the local sequence numbers and the network sequence numbers for nodes that would be reached as if the local copy did not exist locally. Useful for determining if the current local copy should be updated from the network.

    • DHTReportScope::SyncSet Return the local sequence numbers and the network sequence numbers with SetValue fanout parameters. Provides an independent view of both the local sequence numbers and the network sequence numbers for nodes that would be reached as if the local copy did not exist locally. Useful for determining if the unchanged local copy should be pushed to the network.

    • DHTReportScope::UpdateGet Return the local sequence numbers and the network sequence numbers with GetValue fanout parameters. Provides an view of both the local sequence numbers and the network sequence numbers for nodes that would be reached as if a GetValue operation were being performed, including accepting newer values from the network. Useful for determining which subkeys would change with a GetValue operation.

    • DHTReportScope::UpdateSet Return the local sequence numbers and the network sequence numbers with SetValue fanout parameters. Provides an view of both the local sequence numbers and the network sequence numbers for nodes that would be reached as if a SetValue operation were being performed, including accepting newer values from the network. This simulates a SetValue with the initial sequence number incremented by 1, like a real SetValue would when updating. Useful for determine which subkeys would change with an SetValue operation.

Returns Ok(DHTRecordReport) with the subkey ranges that were returned that overlapped the schema, and sequence numbers for each of the subkeys in the range.

DHTReportScope::Local is local-only and non-blocking; the Sync/Update scopes block on a network inspect fanout and return TryAgain if offline.

Errors with VeilidAPIError::InvalidArgument if the record is not open, ::Generic if record_key is an unsupported kind or malformed, ::TryAgain if a network scope is requested and the node is offline (retryable), and ::NotInitialized if shut down.

Trait Implementations§

Source§

impl Clone for RoutingContext

Source§

fn clone(&self) -> RoutingContext

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 Debug for RoutingContext

Source§

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

Formats the value using the given formatter. 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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

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

Initializes a with the given initializer. Read more
Source§

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

Dereferences the given pointer. Read more
Source§

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

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

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

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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