Struct nats::Options

source ·
pub struct Options { /* private fields */ }
Expand description

Connect options.

Implementations§

source§

impl Options

source

pub fn new() -> Options

Options for establishing a new NATS Connection.

§Example
let options = nats::Options::new();
let nc = options.connect("demo.nats.io")?;
source

pub fn with_token(token: &str) -> Options

Authenticate with NATS using a token.

§Example
let nc = nats::Options::with_token("t0k3n!").connect("demo.nats.io")?;
source

pub fn with_user_pass(user: &str, password: &str) -> Options

Authenticate with NATS using a username and password.

§Example
let nc = nats::Options::with_user_pass("derek", "s3cr3t!").connect("demo.nats.io")?;
source

pub fn with_credentials(path: impl AsRef<Path>) -> Options

Authenticate with NATS using a .creds file.

This will open the provided file, load its creds, perform the desired authentication, and then zero the memory used to store the creds before continuing.

§Example
let nc = nats::Options::with_credentials("path/to/my.creds").connect("connect.ngs.global")?;
source

pub fn with_static_credentials(creds: &str) -> Result<Options>

Authenticate with NATS using a static credential str, using the creds file format. Note that this is more hazardous than using the above with_credentials method because it retains the secret in-memory for the lifetime of this client instead of zeroing the credentials after holding them for a very short time, as the with_credentials method does.

§Example
let creds = "-----BEGIN NATS USER JWT-----
eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5...
------END NATS USER JWT------

************************* IMPORTANT *************************
NKEY Seed printed below can be used sign and prove identity.
NKEYs are sensitive and should be treated as secrets.

-----BEGIN USER NKEY SEED-----
SUAIO3FHUX5PNV2LQIIP7TZ3N4L7TX3W53MQGEIVYFIGA635OZCKEYHFLM
------END USER NKEY SEED------
";

let nc = nats::Options::with_static_credentials(creds)
    .expect("failed to parse static creds")
    .connect("connect.ngs.global")?;
source

pub fn with_jwt<J, S>(jwt_cb: J, sig_cb: S) -> Options
where J: Fn() -> Result<String> + Send + Sync + 'static, S: Fn(&[u8]) -> Vec<u8> + Send + Sync + 'static,

Authenticate with a function that loads user JWT and a signature function.

§Example
let seed = "SUANQDPB2RUOE4ETUA26CNX7FUKE5ZZKFCQIIW63OX225F2CO7UEXTM7ZY";
let kp = nkeys::KeyPair::from_seed(seed).unwrap();

fn load_jwt() -> std::io::Result<String> {
    todo!()
}

let nc = nats::Options::with_jwt(load_jwt, move |nonce| kp.sign(nonce).unwrap())
    .connect("localhost")?;
source

pub fn with_nkey<F>(nkey: &str, sig_cb: F) -> Options
where F: Fn(&[u8]) -> Vec<u8> + Send + Sync + 'static,

Authenticate with NATS using a public key and a signature function.

§Example
let nkey = "UAMMBNV2EYR65NYZZ7IAK5SIR5ODNTTERJOBOF4KJLMWI45YOXOSWULM";
let seed = "SUANQDPB2RUOE4ETUA26CNX7FUKE5ZZKFCQIIW63OX225F2CO7UEXTM7ZY";
let kp = nkeys::KeyPair::from_seed(seed).unwrap();

let nc = nats::Options::with_nkey(nkey, move |nonce| kp.sign(nonce).unwrap())
    .connect("localhost")?;
source

pub fn client_cert( self, cert: impl AsRef<Path>, key: impl AsRef<Path> ) -> Options

Set client certificate and private key files.

§Example
let nc = nats::Options::new()
    .client_cert("client-cert.pem", "client-key.pem")
    .connect("nats://localhost:4443")?;
source

pub fn tls_client_config(self, tls_client_config: ClientConfig) -> Options

Set the default TLS config that will be used for connections. Note that this is less secure than specifying TLS certificate file paths using the other methods on Options, which will avoid keeping raw key material in-memory and will zero memory buffers that temporarily contain key material during connection attempts. This is intended to be used as a method of last-resort when providing well-known file paths is not feasible.

To avoid version conflicts, the rustls version used by this crate is exported as nats::rustls.

§Example
let mut root_store = nats::rustls::RootCertStore::empty();
root_store.add_parsable_certificates(rustls_native_certs::load_native_certs()?);

let tls_client_config = nats::rustls::ClientConfig::builder()
    .with_root_certificates(root_store)
    .with_no_client_auth();

let nc = nats::Options::new()
    .tls_client_config(tls_client_config)
    .connect("nats://localhost:4443")?;
source

pub fn with_name(self, name: &str) -> Options

Add a name option to this configuration.

§Example
let nc = nats::Options::new()
    .with_name("My App")
    .connect("demo.nats.io")?;
source

pub fn no_echo(self) -> Options

Select option to not deliver messages that we have published.

§Example
let nc = nats::Options::new().no_echo().connect("demo.nats.io")?;
source

pub fn retry_on_failed_connect(self) -> Options

Select option to enable reconnect with backoff on first failed connection attempt. The reconnect logic with max_reconnects and the reconnect_delay_callback will be specified the same as before but will be invoked on the first failed connection attempt.

§Example
let nc = nats::Options::new()
    .retry_on_failed_connect()
    .connect("demo.nats.io")?;
source

pub fn max_reconnects<T: Into<Option<usize>>>( self, max_reconnects: T ) -> Options

Set the maximum number of reconnect attempts. If no servers remain that are under this threshold, then no further reconnect shall be attempted. The reconnect attempt for a server is reset upon successful connection. If None then there is no maximum number of attempts.

§Example
let nc = nats::Options::new()
    .max_reconnects(3)
    .connect("demo.nats.io")?;
source

pub fn reconnect_buffer_size(self, reconnect_buffer_size: usize) -> Options

Set the maximum amount of bytes to buffer when accepting outgoing traffic in disconnected mode.

The default value is 8mb.

§Example
let nc = nats::Options::new()
    .reconnect_buffer_size(64 * 1024)
    .connect("demo.nats.io")?;
source

pub fn connect<I: IntoServerList>(self, nats_urls: I) -> Result<Connection>

Establish a Connection with one or more NATS servers.

To pass more than one URL check out the the documentation of crate::connect().

Note: If an URL provides username and password, e.g. nats://derek:s3cr3t!@demo.nats.io, it will override the username and password set by the Options. Be aware that providing credentials in the URL is not safe and should not be used in production.

§Example
let options = nats::Options::new();
let nc = options.connect("demo.nats.io")?;

In the below case, the second server is configured to use TLS but the first one is not. Using the Options::tls_required() method can ensure that all servers are connected to with TLS, if that is your intention.

let options = nats::Options::new();
let nc = options.connect("nats://demo.nats.io:4222,tls://demo.nats.io:4443")?;
source

pub fn error_callback<F>(self, cb: F) -> Self
where F: Fn(Error) + Send + Sync + 'static,

Set a callback to be executed when an async error from a server has been received.

§Example
let nc = nats::Options::new()
    .error_callback(|err| println!("connection received an error: {}", err))
    .connect("demo.nats.io")?;
source

pub fn disconnect_callback<F>(self, cb: F) -> Self
where F: Fn() + Send + Sync + 'static,

Set a callback to be executed when connectivity to a server has been lost.

§Example
let nc = nats::Options::new()
    .disconnect_callback(|| println!("connection has been lost"))
    .connect("demo.nats.io")?;
source

pub fn reconnect_callback<F>(self, cb: F) -> Self
where F: Fn() + Send + Sync + 'static,

Set a callback to be executed when connectivity to a server has been reestablished.

§Example
let nc = nats::Options::new()
    .reconnect_callback(|| println!("connection has been reestablished"))
    .connect("demo.nats.io")?;
source

pub fn close_callback<F>(self, cb: F) -> Self
where F: Fn() + Send + Sync + 'static,

Set a callback to be executed when the client has been closed due to exhausting reconnect retries to known servers or by completing a drain request.

§Example
let nc = nats::Options::new()
    .close_callback(|| println!("connection has been closed"))
    .connect("demo.nats.io")?;
nc.drain().unwrap();
source

pub fn lame_duck_callback<F>(self, cb: F) -> Self
where F: Fn() + Send + Sync + 'static,

Set a callback to be executed when the server enters lame duck mode. Can be set to enable letting user know that client will be soon evicted.

§Example
let nc = nats::Options::new()
    .lame_duck_callback(|| println!("server entered lame duck mode"))
    .connect("demo.nats.io")?;
nc.drain().unwrap();
source

pub fn reconnect_delay_callback<F>(self, cb: F) -> Self
where F: Fn(usize) -> Duration + Send + Sync + 'static,

Set a callback to be executed for calculating the backoff duration to wait before a server reconnection attempt.

The function takes the number of reconnects as an argument and returns the Duration that should be waited before making the next connection attempt.

It is recommended that some random jitter is added to your returned Duration.

§Example
let nc = nats::Options::new()
    .reconnect_delay_callback(|c| Duration::from_millis(std::cmp::min((c * 100) as u64, 8000)))
    .connect("demo.nats.io")?;
source

pub fn tls_required(self, tls_required: bool) -> Options

Setting this requires that TLS be set for all server connections.

If you only want to use TLS for some server connections, you may declare them separately in the connect string by prefixing them with tls://host:port instead of nats://host:port.

§Examples

let nc = nats::Options::new()
    .tls_required(true)
    .connect("tls://demo.nats.io:4443")?;
source

pub fn add_root_certificate(self, path: impl AsRef<Path>) -> Options

Adds a root certificate file.

The file must be PEM encoded. All certificates in the file will be used.

§Examples

let nc = nats::Options::new()
    .add_root_certificate("my-certs.pem")
    .connect("tls://demo.nats.io:4443")?;

Trait Implementations§

source§

impl Debug for Options

source§

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

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

impl Default for Options

source§

fn default() -> Options

Returns the “default value” for a type. 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> 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> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

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

§

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