Struct wasmcloud_control_interface::client::Client

source ·
#[non_exhaustive]
pub struct Client { /* private fields */ }
Expand description

Lattice control interface client

Implementations§

source§

impl Client

source

pub fn new(nc: Client) -> Client

Convenience method for creating a new client with all default settings. This is the same as calling ClientBuilder::new(nc).build()

source

pub fn nats_client(&self) -> Client

Get a copy of the NATS client in use by this control client

source

pub fn lattice(&self) -> &str

Retrieve the lattice in use by the Client

source

pub async fn get_hosts( &self, ) -> Result<Vec<CtlResponse<Host>>, Box<dyn Error + Send + Sync>>

Queries the lattice for all responsive hosts, waiting for the full period specified by timeout.

source

pub async fn get_host_inventory( &self, host_id: &str, ) -> Result<CtlResponse<HostInventory>, Box<dyn Error + Send + Sync>>

Retrieves the contents of a running host

source

pub async fn get_claims( &self, ) -> Result<CtlResponse<Vec<HashMap<String, String>>>, Box<dyn Error + Send + Sync>>

Retrieves the full set of all cached claims in the lattice.

source

pub async fn perform_component_auction( &self, component_ref: &str, component_id: &str, constraints: impl Into<BTreeMap<String, String>>, ) -> Result<Vec<CtlResponse<ComponentAuctionAck>>, Box<dyn Error + Send + Sync>>

Performs an component auction within the lattice, publishing a set of constraints and the metadata for the component in question. This will always wait for the full period specified by duration, and then return the set of gathered results. It is then up to the client to choose from among the “auction winners” to issue the appropriate command to start an component. Clients cannot assume that auctions will always return at least one result.

source

pub async fn perform_provider_auction( &self, provider_ref: &str, provider_id: &str, constraints: impl Into<BTreeMap<String, String>>, ) -> Result<Vec<CtlResponse<ProviderAuctionAck>>, Box<dyn Error + Send + Sync>>

Performs a provider auction within the lattice, publishing a set of constraints and the metadata for the provider in question.

This will always wait for the full period specified by duration, and then return the set of gathered results. It is then up to the client to choose from among the “auction winners” and issue the appropriate command to start a provider.

Clients should not assume that auctions will always return at least one result.

§Arguments
  • provider_ref - The ID of the provider to auction
  • provider_id - The ID of the provider auction
  • constraints - Constraints that govern where the provider can be placed
source

pub async fn scale_component( &self, host_id: &str, component_ref: &str, component_id: &str, max_instances: u32, annotations: Option<BTreeMap<String, String>>, config: Vec<String>, ) -> Result<CtlResponse<()>, Box<dyn Error + Send + Sync>>

Sends a request to the given host to scale a given component.

This returns an acknowledgement of receipt of the command, not a confirmation that the component scaled. An acknowledgement will either indicate some form of validation failure, or, if no failure occurs, the receipt of the command.

To avoid blocking consumers, wasmCloud hosts will acknowledge the scale component command prior to fetching the component’s OCI bytes.

Client that need deterministic results as to whether the component completed its startup process must monitor the appropriate event in the control event stream.

§Arguments
  • host_id - The ID of the host to scale the component on
  • component_ref - The OCI reference of the component to scale
  • max_instances - The maximum number of instances this component can run concurrently. Specifying 0 will stop the component.
  • annotations - Optional annotations to apply to the component
  • config - List of named configuration to use for the component
  • allow_update - Whether to perform allow updates to the component (triggering a separate update)
source

pub async fn put_registries( &self, registries: HashMap<String, RegistryCredential>, ) -> Result<CtlResponse<()>, Box<dyn Error + Send + Sync>>

Publishes a registry credential map to the control interface of the lattice.

All hosts will be listening and overwrite their registry credential maps with the new information.

It is highly recommended you use TLS connections with NATS and isolate the control interface credentials when using this function in production as the data contains secrets

§Arguments
  • registries - A map of registry names to their credentials to be used for fetching from specific registries

Puts a link into the lattice.

§Errors

Returns an error if it was unable to put the link

Deletes a link from the lattice metadata keyvalue bucket.

This is an idempotent operation.

§Errors

Returns an error if it was unable to delete.

Retrieves the list of link definitions stored in the lattice metadata key-value bucket.

If the client was created with caching, this will return the cached list of links. Otherwise, it will query the bucket for the list of links.

source

pub async fn put_config( &self, config_name: &str, config: impl Into<HashMap<String, String>>, ) -> Result<CtlResponse<()>, Box<dyn Error + Send + Sync>>

Puts a named config, replacing any data that is already present.

Config names must be valid NATS subject strings and not contain any . or > characters.

§Arguments
  • config_name - Name of the configuration that should be saved
  • config - contents of the configuration to be saved
source

pub async fn delete_config( &self, config_name: &str, ) -> Result<CtlResponse<()>, Box<dyn Error + Send + Sync>>

Delete the named config item.

Config names must be valid NATS subject strings and not contain any . or > characters.

§Arguments
  • config_name - Name of the configuration that should be deleted
source

pub async fn get_config( &self, config_name: &str, ) -> Result<CtlResponse<HashMap<String, String>>, Box<dyn Error + Send + Sync>>

Get the named config item.

§Arguments
  • config_name - The name of the config to fetch. Config names must be valid NATS subject strings and not contain any . or > characters.
§Returns

A map of key-value pairs representing the contents of the config item. This response is wrapped in the CtlResponse type. If the config item does not exist, the host will return a CtlResponse with a success field set to true and a response field set to Option::None. If the config item exists, the host will return a CtlResponse with a success field set to true and a response field set to Option::Some containing the key-value pairs of the config item.

§Example
let nc_client = async_nats::connect("127.0.0.1:4222").await.expect("failed to build NATS client");
let ctl_client = wasmcloud_control_interface::Client::new(nc_client);
ctl_client.put_config(
    "foo",
    HashMap::from_iter(vec![("key".to_string(), "value".to_string())]),
)
.await
.expect("should be able to put config");

let config_resp = ctl_client.get_config("foo").await.expect("should be able to get config");
assert!(config_resp.succeeded());
assert_eq!(config_resp.data(), Some(&HashMap::from_iter(vec![("key".to_string(), "value".to_string())])));

// Note that the host will return a success response even if the config item does not exist.
// Errors are reserved for communication problems with the host or with the config store.
let absent_config_resp = ctl_client.get_config("bar").await.expect("should be able to get config");
assert!(absent_config_resp.succeeded());
assert_eq!(absent_config_resp.data(), None);
source

pub async fn put_label( &self, host_id: &str, key: &str, value: &str, ) -> Result<CtlResponse<()>, Box<dyn Error + Send + Sync>>

Put a new (or update an existing) label on the given host.

§Arguments
  • host_id - ID of the host on which the label should be placed
  • key - The key of the label
  • value - The value of the label
§Errors

Will return an error if there is a communication problem with the host

source

pub async fn delete_label( &self, host_id: &str, key: &str, ) -> Result<CtlResponse<()>, Box<dyn Error + Send + Sync>>

Removes a label from the given host.

§Arguments
  • host_id - ID of the host on which the label should be deleted
  • key - The key of the label that should be deleted
§Errors

Will return an error if there is a communication problem with the host

source

pub async fn update_component( &self, host_id: &str, existing_component_id: &str, new_component_ref: &str, annotations: Option<BTreeMap<String, String>>, ) -> Result<CtlResponse<()>, Box<dyn Error + Send + Sync>>

Command a host to replace an existing component with a new component indicated by an OCI image reference.

The host will acknowledge this request as soon as it verifies that the target component is running.

Note that acknowledgement occurs before the new bytes are downloaded. Live-updating an component can take a long time and control clients cannot block waiting for a reply that could come several seconds later.

To properly verify that a component has been updated, create listener for the appropriate [PublishedEvent] on the control events channel

§Arguments
  • host_id - ID of the host on which the component should be updated
  • existing_component_id - ID of the existing component
  • new_component_ref - New component reference that should be used
  • annotations - Annotations to place on the newly updated component
source

pub async fn start_provider( &self, host_id: &str, provider_ref: &str, provider_id: &str, annotations: Option<BTreeMap<String, String>>, provider_configuration: Vec<String>, ) -> Result<CtlResponse<()>, Box<dyn Error + Send + Sync>>

Command a host to start a provider with a given OCI reference.

The specified link name will be used (or “default” if none is specified).

The target wasmCloud host will acknowledge the receipt of this command before downloading the provider’s bytes from the OCI registry, indicating either a validation failure or success.

Clients that need deterministic guarantees that the provider has completed its startup process, should monitor the control event stream for the appropriate event.

The provider_configuration parameter is a list of named configs to use for this provider, and configurations are not required.

§Arguments
  • host_id - ID of the host on which to start the provider
  • provider_ref - Image reference of the provider to start
  • provider_id - ID of the provider to start
  • annotations - Annotations to place on the started provider
  • provider_configuration - Configuration relevant to the provider (if any)
source

pub async fn stop_provider( &self, host_id: &str, provider_id: &str, ) -> Result<CtlResponse<()>, Box<dyn Error + Send + Sync>>

Issues a command to a host to stop a provider for the given OCI reference, link name, and contract ID.

The target wasmCloud host will acknowledge the receipt of this command, and will not supply a discrete confirmation that a provider has terminated. For that kind of information, the client must also monitor the control event stream

§Arguments
  • host_id - ID of the host on which to stop the provider
  • provider_id - ID of the provider to stop
source

pub async fn stop_host( &self, host_id: &str, timeout_ms: Option<u64>, ) -> Result<CtlResponse<()>, Box<dyn Error + Send + Sync>>

Issues a command to a specific host to perform a graceful termination.

The target host will acknowledge receipt of the command before it attempts a shutdown.

To deterministically verify that the host is down, a client should monitor for the “host stopped” event or passively detect the host down by way of a lack of heartbeat receipts

§Arguments
  • host_id - ID of the host to stop
  • timeout_ms - (optional) amount of time to allow the host to complete stopping
source

pub async fn events_receiver( &self, event_types: Vec<String>, ) -> Result<Receiver<Event>, Box<dyn Error + Send + Sync>>

Returns the receiver end of a channel that subscribes to the lattice event stream.

Any Events that are published after this channel is created will be added to the receiver channel’s buffer, which can be observed or handled if needed.

See the example for how you could use this receiver to handle events.

§Example
use wasmcloud_control_interface::{Client, ClientBuilder};
async {
  let nc = async_nats::connect("127.0.0.1:4222").await.unwrap();
  let client = ClientBuilder::new(nc)
                .timeout(std::time::Duration::from_millis(1000))
                .auction_timeout(std::time::Duration::from_millis(1000))
                .build();
  let mut receiver = client.events_receiver(vec!["component_scaled".to_string()]).await.unwrap();
  while let Some(evt) = receiver.recv().await {
      println!("Event received: {:?}", evt);
  }
};
§Arguments
  • event_types - List of types of events to listen for

Trait Implementations§

source§

impl Clone for Client

source§

fn clone(&self) -> Client

Returns a copy 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 Client

source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Client

§

impl !RefUnwindSafe for Client

§

impl Send for Client

§

impl Sync for Client

§

impl Unpin for Client

§

impl !UnwindSafe for Client

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, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> FutureExt for T

source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
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> 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
source§

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

source§

impl<T> MaybeSendSync for T