Files
leleka/crates/runtime-client/src/client.rs
T

346 lines
13 KiB
Rust

//! One-shot runtime commands. No generation replay or automatic lifecycle retry.
use crate::{FRAME_LIMIT, MESSAGE_LIMIT, PROTOCOL_VERSION, convert, proto};
use prost::Message;
use std::{net::SocketAddr, time::Duration};
use tonic::{Request, Status, transport::Channel};
#[derive(Clone)]
pub struct RuntimeClient {
client: proto::runtime_client::RuntimeClient<Channel>,
token: String,
}
impl RuntimeClient {
pub async fn connect(address: SocketAddr, token: String) -> Result<Self, Status> {
convert::literal_loopback(address)?;
if !convert::valid_token(&token) {
return Err(Status::invalid_argument("invalid_runtime_credential"));
}
let channel = tonic::transport::Endpoint::from_shared(format!("http://{address}"))
.map_err(|_| Status::invalid_argument("invalid_runtime_endpoint"))?
.connect_timeout(Duration::from_secs(2))
.tcp_nodelay(true)
.connect()
.await
.map_err(|_| Status::unavailable("runtime_connection_failed"))?;
let mut client = Self {
client: proto::runtime_client::RuntimeClient::new(channel)
.max_decoding_message_size(MESSAGE_LIMIT)
.max_encoding_message_size(MESSAGE_LIMIT),
token,
};
client.handshake().await?;
Ok(client)
}
fn request<T: Message>(
&self,
value: T,
limit: usize,
timeout: Duration,
) -> Result<Request<T>, Status> {
if value.encoded_len() > limit {
return Err(Status::resource_exhausted("message_limit"));
}
let mut request = Request::new(value);
request.metadata_mut().insert(
"authorization",
format!("Bearer {}", self.token)
.parse()
.map_err(|_| Status::invalid_argument("invalid_runtime_credential"))?,
);
request.set_timeout(timeout);
Ok(request)
}
pub async fn handshake(&mut self) -> Result<proto::Snapshot, Status> {
let request = self.request(
proto::Hello {
protocol_version: PROTOCOL_VERSION,
backend_api_version: 2,
},
FRAME_LIMIT,
Duration::from_secs(2),
)?;
let value = self.client.handshake(request).await?.into_inner();
validate_snapshot(&value)?;
Ok(value)
}
pub async fn snapshot(&mut self) -> Result<proto::Snapshot, Status> {
let request = self.request(proto::Empty {}, FRAME_LIMIT, Duration::from_secs(2))?;
let value = self.client.snapshot(request).await?.into_inner();
validate_snapshot(&value)?;
Ok(value)
}
pub async fn watch(
&mut self,
cursor: proto::Cursor,
) -> Result<tonic::Streaming<proto::Snapshot>, Status> {
let request = self.request(cursor, FRAME_LIMIT, Duration::from_secs(3600))?;
Ok(self.client.watch(request).await?.into_inner())
}
pub async fn load(
&mut self,
command: proto::LoadRequest,
) -> Result<proto::OperationResult, Status> {
let id = command.operation_id.clone();
let epoch = command.expected_epoch.clone();
let request = self.request(command, FRAME_LIMIT, Duration::from_secs(5))?;
let value = self.client.load(request).await?.into_inner();
validate_operation(&value, &id, &epoch, false)?;
Ok(value)
}
pub async fn unload(
&mut self,
command: proto::UnloadRequest,
) -> Result<proto::OperationResult, Status> {
let id = command.operation_id.clone();
let epoch = command.expected_epoch.clone();
let request = self.request(command, FRAME_LIMIT, Duration::from_secs(5))?;
let value = self.client.unload(request).await?.into_inner();
validate_operation(&value, &id, &epoch, false)?;
Ok(value)
}
pub async fn operation(
&mut self,
query: proto::OperationQuery,
) -> Result<proto::OperationResult, Status> {
let id = query.operation_id.clone();
let epoch = query.expected_epoch.clone();
let request = self.request(query, FRAME_LIMIT, Duration::from_secs(2))?;
let value = self.client.operation(request).await?.into_inner();
validate_operation(&value, &id, &epoch, true)?;
Ok(value)
}
pub async fn cancel(
&mut self,
command: proto::CancelRequest,
) -> Result<proto::CancelAck, Status> {
let id = command.request_id.clone();
let epoch = command.expected_epoch.clone();
let request = self.request(command, FRAME_LIMIT, Duration::from_secs(5))?;
let value = self.client.cancel(request).await?.into_inner();
if value.request_id != id || value.epoch != epoch || !value.acknowledged {
return Err(Status::data_loss("invalid_cancel_ack"));
}
Ok(value)
}
/// Change the settings of the loaded model (JSON document, `leleka_runtime::serve_tuning`); the engine reopens its serve stack,
/// which takes tens of seconds, so the deadline is generous.
pub async fn reconfigure(
&mut self,
command: proto::ReconfigureRequest,
) -> Result<proto::ReconfigureReply, Status> {
let epoch = command.expected_epoch.clone();
let request = self.request(command, FRAME_LIMIT, Duration::from_secs(1800))?;
let value = self.client.reconfigure(request).await?.into_inner();
if value.epoch != epoch {
return Err(Status::data_loss("invalid_reconfigure_reply"));
}
Ok(value)
}
pub async fn generate(
&mut self,
command: proto::GenerateRequest,
) -> Result<RuntimeGeneration, Status> {
let id = command.request_id.clone();
let epoch = command.expected_epoch.clone();
let request = self.request(command, MESSAGE_LIMIT, Duration::from_secs(3600))?;
let response = self.client.generate(request).await?;
if response
.metadata()
.get("x-leleka-accepted")
.and_then(|v| v.to_str().ok())
!= Some("true")
{
// Dispatch may already have occurred: never mark this retryable.
return Err(Status::data_loss("missing_acceptance_state"));
}
Ok(RuntimeGeneration {
stream: response.into_inner(),
client: self.clone(),
id,
epoch,
sequence: 0,
terminal: false,
failed: false,
})
}
}
fn validate_operation(
value: &proto::OperationResult,
id: &str,
epoch: &str,
query: bool,
) -> Result<(), Status> {
if value.operation_id != id
|| !matches!(value.state, 1..=4)
|| value.encoded_len() > FRAME_LIMIT
|| uuid::Uuid::parse_str(&value.epoch).is_err()
|| (value.epoch != epoch && !(query && value.state == 4))
{
return Err(Status::data_loss("invalid_operation_result"));
}
Ok(())
}
pub fn validate_snapshot(value: &proto::Snapshot) -> Result<(), Status> {
if snapshot_is_malformed(value) {
return Err(Status::data_loss("invalid_runtime_snapshot"));
}
if !value.model_ready
&& value
.capabilities
.as_ref()
.is_some_and(|c| !c.models.is_empty())
{
return Err(Status::data_loss("unloaded_capability_advertisement"));
}
if let Some(loaded) = &value.loaded {
validate_loaded_identity(loaded)?;
}
Ok(())
}
/// The versions, the epoch, the sequence and the size of a snapshot, and that a ready model is reported.
fn snapshot_is_malformed(value: &proto::Snapshot) -> bool {
value.protocol_version != PROTOCOL_VERSION
|| value.backend_api_version != 2
|| uuid::Uuid::parse_str(&value.epoch).is_err()
|| value.sequence == 0
|| !value.full_snapshot
|| (value.model_ready && value.loaded.is_none())
|| value.encoded_len() > FRAME_LIMIT
}
// The loaded model a snapshot reports must be one the contract accepts for its own descriptor and mode.
fn validate_loaded_identity(loaded: &proto::LoadedModel) -> Result<(), Status> {
let descriptor = convert::descriptor_from_proto(
loaded
.descriptor
.as_ref()
.ok_or_else(|| Status::data_loss("missing_loaded_descriptor"))?,
)?;
let config = convert::config_from_proto(&proto::LoadConfig {
version: loaded.load_config_version,
mode: loaded.effective_mode.clone(),
gpu_memory_limit_bytes: None,
allow_experimental: true,
})?;
let result = leleka_backend_api::LoadedModel {
handle: loaded.handle.clone(),
descriptor: descriptor.clone(),
load_config_version: config.load_config_version,
effective_mode: config.inference_mode.clone(),
mode_identity_digest: loaded.mode_identity_digest.clone(),
};
result
.validate_for_load(&descriptor, &config)
.map_err(|_| Status::data_loss("invalid_loaded_identity"))
}
/// Validates request/epoch/sequence, initial acceptance and terminal completeness.
/// Drop cancels observation's request; it never retries it or unloads the model.
pub struct RuntimeGeneration {
stream: tonic::Streaming<proto::GenerationFrame>,
client: RuntimeClient,
id: String,
epoch: String,
sequence: u64,
terminal: bool,
failed: bool,
}
impl RuntimeGeneration {
pub async fn message(&mut self) -> Result<Option<proto::GenerationFrame>, Status> {
if self.terminal {
return Ok(None);
}
if self.failed {
return Err(Status::data_loss("generation_stream_failed"));
}
let value = self.next_frame().await?;
self.check_frame(&value)?;
if let Some(proto::generation_frame::Payload::Terminal(terminal)) = &value.payload {
self.finish_after_terminal(terminal).await?;
}
self.sequence = value.sequence;
Ok(Some(value))
}
/// Any failure ends the generation: every later read says so.
fn fail(&mut self, status: Status) -> Status {
self.failed = true;
status
}
async fn next_frame(&mut self) -> Result<proto::GenerationFrame, Status> {
match self.stream.message().await {
Ok(Some(value)) => Ok(value),
Ok(None) => Err(self.fail(Status::data_loss("generation_missing_terminal"))),
Err(status) => Err(self.fail(status)),
}
}
fn check_frame(&mut self, value: &proto::GenerationFrame) -> Result<(), Status> {
let first = self.sequence == 0;
if value.request_id != self.id
|| value.epoch != self.epoch
|| value.sequence != self.sequence + 1
|| value.encoded_len() > FRAME_LIMIT
|| value.payload.is_none()
|| (first && !is_acceptance(&value.payload))
|| (!first
&& matches!(
value.payload,
Some(proto::generation_frame::Payload::Accepted(_))
))
{
return Err(self.fail(Status::data_loss("invalid_generation_frame")));
}
Ok(())
}
async fn finish_after_terminal(&mut self, terminal: &proto::Terminal) -> Result<(), Status> {
if !matches!(terminal.state, 1..=3) || (terminal.state == 1 && terminal.usage.is_none()) {
return Err(self.fail(Status::data_loss("invalid_generation_terminal")));
}
// Do not publish the terminal until the HTTP2 stream finishes
// successfully. Duplicate frames and errors after terminal fail.
match self.stream.message().await {
Ok(None) => {}
Ok(Some(_)) => return Err(self.fail(Status::data_loss("generation_after_terminal"))),
Err(status) => return Err(self.fail(status)),
}
self.terminal = true;
Ok(())
}
}
/// The payload is the `Accepted` frame with `accepted` set.
fn is_acceptance(payload: &Option<proto::generation_frame::Payload>) -> bool {
matches!(
payload,
Some(proto::generation_frame::Payload::Accepted(
proto::Accepted { accepted: true }
))
)
}
impl Drop for RuntimeGeneration {
fn drop(&mut self) {
if !self.terminal {
let mut client = self.client.clone();
let command = proto::CancelRequest {
request_id: self.id.clone(),
expected_epoch: self.epoch.clone(),
};
if let Ok(handle) = tokio::runtime::Handle::try_current() {
handle.spawn(async move {
let _ = client.cancel(command).await;
});
}
}
}
}
#[cfg(test)]
mod tests;