use std::sync::Arc;
use serde::Serialize;
use super::job::ServerlessJob;
use super::types::EndpointHealth;
use crate::{Result, RunpodClient};
#[cfg(feature = "tracing")]
const TRACING_TARGET: &str = "runpod_sdk::serverless";
#[derive(Clone)]
pub struct ServerlessEndpoint {
endpoint_id: Arc<String>,
client: RunpodClient,
}
impl ServerlessEndpoint {
pub fn new(endpoint_id: impl Into<String>, client: RunpodClient) -> Self {
Self {
endpoint_id: Arc::new(endpoint_id.into()),
client,
}
}
pub fn endpoint_id(&self) -> &str {
&self.endpoint_id
}
pub fn run<I>(&self, input: &I) -> Result<ServerlessJob>
where
I: Serialize,
{
let input_value = serde_json::to_value(input)?;
Ok(ServerlessJob::new(
Arc::clone(&self.endpoint_id),
input_value,
self.client.clone(),
))
}
pub async fn run_now<I, O>(&self, input: &I) -> Result<O>
where
I: Serialize,
O: serde::de::DeserializeOwned,
{
let job = self.run(input)?;
let value = job.await?;
Ok(serde_json::from_value(value)?)
}
pub async fn health(&self) -> Result<EndpointHealth> {
#[cfg(feature = "tracing")]
tracing::debug!(
target: TRACING_TARGET,
endpoint_id = %self.endpoint_id,
"Checking endpoint health"
);
let path = format!("{}/health", self.endpoint_id);
let response = self.client.get_api(&path).send().await?;
let response = response.error_for_status()?;
let health: EndpointHealth = response.json().await?;
#[cfg(feature = "tracing")]
tracing::debug!(
target: TRACING_TARGET,
endpoint_id = %self.endpoint_id,
workers_ready = health.workers.ready,
jobs_in_queue = health.jobs.in_queue,
"Endpoint health retrieved"
);
Ok(health)
}
pub async fn purge_queue(&self) -> Result<()> {
#[cfg(feature = "tracing")]
tracing::debug!(
target: TRACING_TARGET,
endpoint_id = %self.endpoint_id,
"Purging endpoint queue"
);
let path = format!("{}/purge-queue", self.endpoint_id);
let response = self.client.post_api(&path).send().await?;
response.error_for_status()?;
#[cfg(feature = "tracing")]
tracing::info!(
target: TRACING_TARGET,
endpoint_id = %self.endpoint_id,
"Endpoint queue purged successfully"
);
Ok(())
}
}
impl std::fmt::Debug for ServerlessEndpoint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Endpoint")
.field("endpoint_id", &self.endpoint_id)
.finish()
}
}