improve telemetry ergonomics

This commit is contained in:
2025-12-31 11:15:39 -05:00
parent 778c1a0dfd
commit b8475a12ad
10 changed files with 210 additions and 234 deletions

View File

@@ -5,12 +5,18 @@ use std::fmt::Display;
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
pub struct Commanding;
pub struct CommandRegistry {
client: Arc<Client>,
}
impl CommandRegistry {
pub fn new(client: Arc<Client>) -> Self {
Self { client }
}
impl Commanding {
pub fn register_handler<C: IntoCommandDefinition, F, E: Display>(
client: Arc<Client>,
command_name: String,
&self,
command_name: impl Into<String>,
mut callback: F,
) -> CommandHandle
where
@@ -20,8 +26,9 @@ impl Commanding {
let result = CommandHandle {
cancellation_token: cancellation_token.clone(),
};
let client = self.client.clone();
let command_definition = C::create(command_name);
let command_definition = C::create(command_name.into());
tokio::spawn(async move {
while !cancellation_token.is_cancelled() {

11
api/src/client/config.rs Normal file
View File

@@ -0,0 +1,11 @@
pub struct ClientConfiguration {
pub send_buffer_size: usize,
}
impl Default for ClientConfiguration {
fn default() -> Self {
Self {
send_buffer_size: 128,
}
}
}

View File

@@ -1,3 +1,4 @@
use crate::client::config::ClientConfiguration;
use crate::client::error::{ConnectError, MessageError};
use crate::client::{Callback, ClientChannel, OutgoingMessage, RegisteredCallback};
use crate::messages::callback::GenericCallbackError;
@@ -23,6 +24,7 @@ pub struct ClientContext {
pub cancel: CancellationToken,
pub request: Request,
pub connected_state_tx: watch::Sender<bool>,
pub client_configuration: ClientConfiguration,
}
impl ClientContext {
@@ -71,7 +73,7 @@ impl ClientContext {
};
info!("Connected to {}", self.request.uri());
let (tx, rx) = mpsc::channel(128);
let (tx, rx) = mpsc::channel(self.client_configuration.send_buffer_size);
*write_lock = tx;
drop(write_lock);

View File

@@ -1,8 +1,10 @@
pub mod command;
mod config;
mod context;
pub mod error;
pub mod telemetry;
use crate::client::config::ClientConfiguration;
use crate::client::error::{MessageError, RequestError};
use crate::messages::callback::GenericCallbackError;
use crate::messages::payload::RequestMessagePayload;
@@ -41,6 +43,16 @@ pub struct Client {
impl Client {
pub fn connect<R>(request: R) -> Result<Self, ConnectError>
where
R: IntoClientRequest,
{
Self::connect_with_config(request, ClientConfiguration::default())
}
pub fn connect_with_config<R>(
request: R,
config: ClientConfiguration,
) -> Result<Self, ConnectError>
where
R: IntoClientRequest,
{
@@ -52,6 +64,7 @@ impl Client {
cancel: cancel.clone(),
request: request.into_client_request()?,
connected_state_tx,
client_configuration: config,
};
context.start(channel.clone())?;

View File

@@ -1,77 +1,104 @@
use crate::client::error::MessageError;
use crate::client::Client;
use crate::data_type::DataType;
use crate::data_value::DataValue;
use crate::messages::telemetry_definition::TelemetryDefinitionRequest;
use crate::messages::telemetry_entry::TelemetryEntry;
use api_core::data_type::{DataType, ToDataType};
use chrono::{DateTime, Utc};
use std::marker::PhantomData;
use std::sync::Arc;
use tokio::sync::{oneshot, RwLock};
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
pub struct Telemetry;
pub struct TelemetryRegistry {
client: Arc<Client>,
}
impl Telemetry {
pub async fn register(
client: Arc<Client>,
name: String,
impl TelemetryRegistry {
pub fn new(client: Arc<Client>) -> Self {
Self { client }
}
#[inline]
pub async fn register_generic(
&self,
name: impl Into<String>,
data_type: DataType,
) -> TelemetryHandle {
let cancellation_token = CancellationToken::new();
let cancel_token = cancellation_token.clone();
let stored_client = client.clone();
) -> GenericTelemetryHandle {
// inner for compilation performance
async fn inner(
client: Arc<Client>,
name: String,
data_type: DataType,
) -> GenericTelemetryHandle {
let cancellation_token = CancellationToken::new();
let cancel_token = cancellation_token.clone();
let stored_client = client.clone();
let response_uuid = Arc::new(RwLock::new(Uuid::nil()));
let response_uuid = Arc::new(RwLock::new(Uuid::nil()));
let response_uuid_inner = response_uuid.clone();
let (tx, rx) = oneshot::channel();
let response_uuid_inner = response_uuid.clone();
let (tx, rx) = oneshot::channel();
tokio::spawn(async move {
let mut write_lock = Some(response_uuid_inner.write().await);
let _ = tx.send(());
while !cancel_token.is_cancelled() {
if let Ok(response) = client
.send_request(TelemetryDefinitionRequest {
name: name.clone(),
data_type,
})
.await
{
let mut lock = match write_lock {
None => response_uuid_inner.write().await,
Some(lock) => lock,
};
// Update the value in the lock
*lock = response.uuid;
// Set this value so the loop works
write_lock = None;
tokio::spawn(async move {
let mut write_lock = Some(response_uuid_inner.write().await);
let _ = tx.send(());
while !cancel_token.is_cancelled() {
if let Ok(response) = client
.send_request(TelemetryDefinitionRequest {
name: name.clone(),
data_type,
})
.await
{
let mut lock = match write_lock {
None => response_uuid_inner.write().await,
Some(lock) => lock,
};
// Update the value in the lock
*lock = response.uuid;
// Set this value so the loop works
write_lock = None;
}
client.wait_disconnected().await;
}
});
client.wait_disconnected().await;
// Wait until the write lock is acquired
let _ = rx.await;
// Wait until the write lock is released for the first time
drop(response_uuid.read().await);
GenericTelemetryHandle {
cancellation_token,
uuid: response_uuid,
client: stored_client,
}
});
// Wait until the write lock is acquired
let _ = rx.await;
// Wait until the write lock is released for the first time
drop(response_uuid.read().await);
TelemetryHandle {
cancellation_token,
uuid: response_uuid,
client: stored_client,
}
inner(self.client.clone(), name.into(), data_type).await
}
#[inline]
pub async fn register<T: ToDataType>(&self, name: impl Into<String>) -> TelemetryHandle<T> {
self.register_generic(name, T::DATA_TYPE).await.coerce()
}
}
pub struct TelemetryHandle {
impl Drop for GenericTelemetryHandle {
fn drop(&mut self) {
self.cancellation_token.cancel();
}
}
pub struct GenericTelemetryHandle {
cancellation_token: CancellationToken,
uuid: Arc<RwLock<Uuid>>,
client: Arc<Client>,
}
impl TelemetryHandle {
impl GenericTelemetryHandle {
pub async fn publish(
&self,
value: DataValue,
@@ -97,10 +124,42 @@ impl TelemetryHandle {
Ok(())
}
}
impl Drop for TelemetryHandle {
fn drop(&mut self) {
self.cancellation_token.cancel();
#[inline]
pub async fn publish_now(&self, value: DataValue) -> Result<(), MessageError> {
self.publish(value, Utc::now()).await
}
fn coerce<T: Into<DataValue>>(self) -> TelemetryHandle<T> {
TelemetryHandle::<T> {
generic_handle: self,
_phantom: PhantomData,
}
}
}
pub struct TelemetryHandle<T> {
generic_handle: GenericTelemetryHandle,
_phantom: PhantomData<T>,
}
impl<T> TelemetryHandle<T> {
pub fn to_generic(self) -> GenericTelemetryHandle {
self.generic_handle
}
pub fn as_generic(&self) -> &GenericTelemetryHandle {
&self.generic_handle
}
}
impl<T: Into<DataValue>> TelemetryHandle<T> {
#[inline]
pub async fn publish(&self, value: T, timestamp: DateTime<Utc>) -> Result<(), MessageError> {
self.as_generic().publish(value.into(), timestamp).await
}
#[inline]
pub async fn publish_now(&self, value: T) -> Result<(), MessageError> {
self.publish(value, Utc::now()).await
}
}