Skip to main content

NatsClient

Struct NatsClient 

Source
pub struct NatsClient {
    pub client: Client,
    pub service: Arc<Service>,
    pub(crate) jetstream: Context,
    pub(crate) service_name: String,
    pub(crate) signals: Arc<ConnectionSignals>,
    pub(crate) stream_config: MessageBusConfig,
}
Expand description

Live handle to a NATS client including a JetStream connection.

Implements Publisher, Subscriber, Requester, and Responder.

Obtain one via NatsConfiguration::connect. The cheap-to-clone SharedNatsClient alias (Arc<NatsClient>) is the type passed around in application code.

Fields§

§client: Client

NATS connection.

§service: Arc<Service>

NATS Service for the component that owns this connection.

Having a NATS service allows us to use NATS to see which components are online, what version they’re using, and do additional introspection in the long term (currently only pings work).

§jetstream: Context

JetStream context, used by the Publisher, Subscriber, Requester, and Responder implementations.

§service_name: String

Durable consumer name; instances sharing the same name load-balance automatically.

§signals: Arc<ConnectionSignals>

Shared reconnect signals, also held by the connection’s event callback.

§stream_config: MessageBusConfig

Message bus configuration to create different kinds of streams.

Implementations§

Source§

impl NatsClient

Source

const MAINTENANCE_MODE_KEY: &str = "maintenance_mode"

Subject for the maintenance mode.

Maintenance mode is considered enabled if its value is 1 or unset, disabled if zero.

Source

pub async fn set_maintenance_mode( &self, maintenance_mode: bool, ) -> Result<(), NatsError>

Sets maintenance mode to the boolean value

Source

pub async fn is_in_maintenance_mode(&self) -> Result<bool, NatsError>

Returns true if the NATS K/V store says we are in maintenance mode

Source

pub async fn wait_for_maintenance_mode( &self, status: bool, ) -> Result<(), NatsError>

Returns a future that completes when maintenance mode has this status

Source§

impl NatsClient

Source

pub async fn make_nats_request<T: Serialize>( &self, subject: impl ToSubject, request: T, ) -> Result<Subscriber, NatsError>

Make a request over JetStream, and create a subscriber that’ll wait for a response over NATS

Source

pub async fn await_nats_response<U: DeserializeOwned, E: DeserializeOwned>( subscription: Subscriber, ) -> Result<Result<U, E>, NatsError>

Given a subscriber created using NatsClient::make_nats_request(), get the response.

Source§

impl NatsClient

Source

pub async fn get_roomserver_stream(&self) -> Result<Stream, NatsError>

Get the stream for the roomserver

Source

pub async fn set_up_streams(&self) -> Result<(), NatsError>

Sets up all required streams in NATS

Source§

impl NatsClient

Source

pub async fn notify_new_sync_data(&self) -> Result<(), NatsError>

Notifies clients that there is potentially some new data to be fetched in the sync endpoint.

NOTE: This is intentionally using a NATS core stream because there is no retention/acknowledgment requirements on that stream.

Source

pub async fn sync_data_subscriber(&self) -> Result<Subscriber, NatsError>

Subscribes to the sync update subject to get notified if something changed.

Source§

impl NatsClient

Source

pub(crate) fn internal_channel_size(&self) -> usize

Buffer size for the internal channel between a subscription’s background forward task and its consumer-facing stream. See ConsumerConfig::buffer_size.

Source

pub async fn connect_to_store(jetstream: &Context) -> Result<Store, NatsError>

Given a JetStream context, returns a key-value store

Source

pub(crate) async fn ensure_event_stream<E: Event>( &self, ) -> Result<Stream, CreateStreamError>

Ensures the JetStream event stream for E exists and returns its handle.

Shared by Publisher::publish (which discards the handle, just ensuring the stream exists) and Subscriber::subscribe (which uses the handle to create its consumer). The stream covers E::SUBJECT plus any COMPATIBLE_SUBJECTS, using the connection’s event retention policy.

Source

pub(crate) async fn ensure_command_stream( &self, subject_filter: &str, ) -> Result<Stream, CreateStreamError>

Ensures the WorkQueue JetStream stream for a command family exists and returns its handle.

Mirrors NatsClient::ensure_event_stream. Shared by the responder (Responder::respond) and the requester (Requester::request) so both agree on a single stream per SUBJECT_FILTER. The responder uses the handle to create its consumer; the requester just needs the stream to exist before publishing (and discards the handle), so a command sent before its responder is up is still durably captured.

The retention policy is always WorkQueue; only the limits come from MessageBusConfig::command_retention.

Source§

impl NatsClient

Source

async fn respond_inner<C: Command + Send + 'static>( &self, ) -> Result<impl Stream<Item = Result<NatsReceivedCommand<C>, Error>> + Send + 'static + use<C>, Error>

Helper that Responder::respond delegates to: creates the initial command stream up front (so setup errors surface synchronously) and wraps it in a resubscribing_stream that re-creates the stream after each disconnect.

Source

async fn make_command_stream<C: Command + 'static>( &self, ) -> Result<Pin<Box<dyn Stream<Item = Result<NatsReceivedCommand<C>, Error>> + Send>>, Error>

Creates the durable pull consumer for C on its WorkQueue stream and returns the commands it delivers, pulling at most command_prefetch at a time so idle instances can take the rest.

Source§

impl NatsClient

Source

async fn subscribe_inner<E: Event + 'static>( &self, ) -> Result<Pin<Box<dyn Stream<Item = Result<NatsReceivedEvent<E>, Error>> + Send>>, Error>

Core subscription logic: creates the JetStream stream and consumer and returns a pinned stream of deserialized events.

Called by Subscriber::subscribe for the initial subscription and again by the background reconnect task after each disconnect.

Trait Implementations§

Source§

impl Clone for NatsClient

Source§

fn clone(&self) -> NatsClient

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 NatsClient

Source§

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

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

impl Publisher for NatsClient

Source§

async fn publish<E>(&self, message: E) -> Result<(), Error>
where E: Event + Clone + 'static,

Serializes message to JSON and publishes it to the JetStream subject defined by Event::SUBJECT. Creates the stream if it does not yet exist (idempotent), using the retention policy from MessageBusConfig::retention. The current OpenTelemetry span is injected into message headers.

Source§

impl Requester for NatsClient

Source§

async fn request<C: Command + Send>(&self, cmd: C) -> Result<C::Reply, Error>

Sends cmd over JetStream and awaits a typed reply on a core-NATS inbox.

Encodes the command payload with Command::into_payload, ensures the command’s JetStream stream exists, then publishes to the subject from Command::subject with the reply subject carried in the header. Ensuring the stream means a command sent before its responder is up is durably captured rather than dropped.

Source§

impl Responder for NatsClient

Source§

fn respond<C: Command + Send + 'static>( self, ) -> impl Future<Output = Result<impl Stream<Item = Result<impl ReceivedCommand<C>, Error>> + Send + 'static, Error>> + Send + 'static

Creates a JetStream stream and durable pull consumer for C::SUBJECT, then returns a stream that yields received commands.

The stream uses WorkQueue retention so each message is delivered to exactly one instance in the consumer group. Multiple instances sharing the same service_name automatically load-balance.

Source§

impl Subscriber for NatsClient

Source§

async fn subscribe<E: Event + 'static>( &self, ) -> Result<impl Stream<Item = Result<impl ReceivedEvent<E> + Send + Sync + 'static, Error>> + Send + 'static, Error>

Subscribes to E::SUBJECT using a durable JetStream pull consumer named after this connection’s service_name.

Creates the stream and consumer synchronously before returning (so a publish immediately after subscribe() will not be lost). A background task then forwards messages through an internal channel and automatically re-subscribes if the NATS connection drops, using exponential backoff.

Multiple service instances with the same service_name will automatically load-balance message delivery.

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
§

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

§

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
§

impl<T> DropFlavorWrapper<T> for T

§

type Flavor = MayDrop

The DropFlavor that [wrap]s T into Self
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FutureExt for T

§

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

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

fn with_current_context(self) -> WithContext<Self>

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

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

§

const WITNESS: W = W::MAKE

A constant of the type witness
§

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

§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
§

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> JsonCastable<CanonicalJsonValue> for T

§

impl<T> JsonCastable<Value> for T

§

impl<D> OwoColorize for D

§

fn fg<C>(&self) -> FgColorDisplay<'_, C, Self>
where C: Color,

Set the foreground color generically Read more
§

fn bg<C>(&self) -> BgColorDisplay<'_, C, Self>
where C: Color,

Set the background color generically. Read more
§

fn black(&self) -> FgColorDisplay<'_, Black, Self>

Change the foreground color to black
§

fn on_black(&self) -> BgColorDisplay<'_, Black, Self>

Change the background color to black
§

fn red(&self) -> FgColorDisplay<'_, Red, Self>

Change the foreground color to red
§

fn on_red(&self) -> BgColorDisplay<'_, Red, Self>

Change the background color to red
§

fn green(&self) -> FgColorDisplay<'_, Green, Self>

Change the foreground color to green
§

fn on_green(&self) -> BgColorDisplay<'_, Green, Self>

Change the background color to green
§

fn yellow(&self) -> FgColorDisplay<'_, Yellow, Self>

Change the foreground color to yellow
§

fn on_yellow(&self) -> BgColorDisplay<'_, Yellow, Self>

Change the background color to yellow
§

fn blue(&self) -> FgColorDisplay<'_, Blue, Self>

Change the foreground color to blue
§

fn on_blue(&self) -> BgColorDisplay<'_, Blue, Self>

Change the background color to blue
§

fn magenta(&self) -> FgColorDisplay<'_, Magenta, Self>

Change the foreground color to magenta
§

fn on_magenta(&self) -> BgColorDisplay<'_, Magenta, Self>

Change the background color to magenta
§

fn purple(&self) -> FgColorDisplay<'_, Magenta, Self>

Change the foreground color to purple
§

fn on_purple(&self) -> BgColorDisplay<'_, Magenta, Self>

Change the background color to purple
§

fn cyan(&self) -> FgColorDisplay<'_, Cyan, Self>

Change the foreground color to cyan
§

fn on_cyan(&self) -> BgColorDisplay<'_, Cyan, Self>

Change the background color to cyan
§

fn white(&self) -> FgColorDisplay<'_, White, Self>

Change the foreground color to white
§

fn on_white(&self) -> BgColorDisplay<'_, White, Self>

Change the background color to white
§

fn default_color(&self) -> FgColorDisplay<'_, Default, Self>

Change the foreground color to the terminal default
§

fn on_default_color(&self) -> BgColorDisplay<'_, Default, Self>

Change the background color to the terminal default
§

fn bright_black(&self) -> FgColorDisplay<'_, BrightBlack, Self>

Change the foreground color to bright black
§

fn on_bright_black(&self) -> BgColorDisplay<'_, BrightBlack, Self>

Change the background color to bright black
§

fn bright_red(&self) -> FgColorDisplay<'_, BrightRed, Self>

Change the foreground color to bright red
§

fn on_bright_red(&self) -> BgColorDisplay<'_, BrightRed, Self>

Change the background color to bright red
§

fn bright_green(&self) -> FgColorDisplay<'_, BrightGreen, Self>

Change the foreground color to bright green
§

fn on_bright_green(&self) -> BgColorDisplay<'_, BrightGreen, Self>

Change the background color to bright green
§

fn bright_yellow(&self) -> FgColorDisplay<'_, BrightYellow, Self>

Change the foreground color to bright yellow
§

fn on_bright_yellow(&self) -> BgColorDisplay<'_, BrightYellow, Self>

Change the background color to bright yellow
§

fn bright_blue(&self) -> FgColorDisplay<'_, BrightBlue, Self>

Change the foreground color to bright blue
§

fn on_bright_blue(&self) -> BgColorDisplay<'_, BrightBlue, Self>

Change the background color to bright blue
§

fn bright_magenta(&self) -> FgColorDisplay<'_, BrightMagenta, Self>

Change the foreground color to bright magenta
§

fn on_bright_magenta(&self) -> BgColorDisplay<'_, BrightMagenta, Self>

Change the background color to bright magenta
§

fn bright_purple(&self) -> FgColorDisplay<'_, BrightMagenta, Self>

Change the foreground color to bright purple
§

fn on_bright_purple(&self) -> BgColorDisplay<'_, BrightMagenta, Self>

Change the background color to bright purple
§

fn bright_cyan(&self) -> FgColorDisplay<'_, BrightCyan, Self>

Change the foreground color to bright cyan
§

fn on_bright_cyan(&self) -> BgColorDisplay<'_, BrightCyan, Self>

Change the background color to bright cyan
§

fn bright_white(&self) -> FgColorDisplay<'_, BrightWhite, Self>

Change the foreground color to bright white
§

fn on_bright_white(&self) -> BgColorDisplay<'_, BrightWhite, Self>

Change the background color to bright white
§

fn bold(&self) -> BoldDisplay<'_, Self>

Make the text bold
§

fn dimmed(&self) -> DimDisplay<'_, Self>

Make the text dim
§

fn italic(&self) -> ItalicDisplay<'_, Self>

Make the text italicized
§

fn underline(&self) -> UnderlineDisplay<'_, Self>

Make the text underlined
Make the text blink
Make the text blink (but fast!)
§

fn reversed(&self) -> ReversedDisplay<'_, Self>

Swap the foreground and background colors
§

fn hidden(&self) -> HiddenDisplay<'_, Self>

Hide the text
§

fn strikethrough(&self) -> StrikeThroughDisplay<'_, Self>

Cross out the text
§

fn color<Color>(&self, color: Color) -> FgDynColorDisplay<'_, Color, Self>
where Color: DynColor,

Set the foreground color at runtime. Only use if you do not know which color will be used at compile-time. If the color is constant, use either [OwoColorize::fg] or a color-specific method, such as [OwoColorize::green], Read more
§

fn on_color<Color>(&self, color: Color) -> BgDynColorDisplay<'_, Color, Self>
where Color: DynColor,

Set the background color at runtime. Only use if you do not know what color to use at compile-time. If the color is constant, use either [OwoColorize::bg] or a color-specific method, such as [OwoColorize::on_yellow], Read more
§

fn fg_rgb<const R: u8, const G: u8, const B: u8>( &self, ) -> FgColorDisplay<'_, CustomColor<R, G, B>, Self>

Set the foreground color to a specific RGB value.
§

fn bg_rgb<const R: u8, const G: u8, const B: u8>( &self, ) -> BgColorDisplay<'_, CustomColor<R, G, B>, Self>

Set the background color to a specific RGB value.
§

fn truecolor(&self, r: u8, g: u8, b: u8) -> FgDynColorDisplay<'_, Rgb, Self>

Sets the foreground color to an RGB value.
§

fn on_truecolor(&self, r: u8, g: u8, b: u8) -> BgDynColorDisplay<'_, Rgb, Self>

Sets the background color to an RGB value.
§

fn style(&self, style: Style) -> Styled<&Self>

Apply a runtime-determined style
§

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

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