Files
leleka/crates/backend-api/src/contract_rules.rs
T

232 lines
8.1 KiB
Rust

//! The behavior of the contract types: the API version check, validation of a model descriptor, the rule that a
//! backend supports only a model it advertises, the error texts, and the bounded generation channel (`GenerationSink`
//! and `GenerationStream`) that carries events with exactly one terminal.
use super::{
Arc, AtomicBool, BACKEND_API_VERSION, BackendCapabilities, BackendError, BackendIdentity, ContractError, ErrorCode,
EventSender, FinishReason, GenerationEvent, GenerationSink, GenerationStream, GenerationTerminal, ModelDescriptor,
Mutex, Ordering, RecvError, SendError, StreamError, TrySendError, Usage, fmt, mpsc,
};
impl BackendIdentity {
pub fn supports_current_api(&self) -> bool {
self.api_version == BACKEND_API_VERSION
}
}
impl ModelDescriptor {
pub fn validate(&self) -> Result<(), ContractError> {
for (field, value) in [
("family", self.family.as_str()),
("architecture", self.architecture.as_str()),
("weight_format", self.weight_format.as_str()),
] {
if value.is_empty()
|| value
.chars()
.any(|ch| ch.is_whitespace() || ch.is_control())
{
return Err(ContractError::InvalidField(field));
}
}
let Some(hex) = self.artifact_digest.strip_prefix("sha256:") else {
return Err(ContractError::InvalidField("artifact_digest"));
};
if hex.len() != 64 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err(ContractError::InvalidField("artifact_digest"));
}
Ok(())
}
}
impl BackendCapabilities {
/// Refuse malformed descriptors and combinations not explicitly advertised.
///
/// This checks declared compatibility only; it does not verify artifact bytes
/// or admit memory, concurrency, hardware, or an experimental runtime mode.
pub fn supports(&self, model: &ModelDescriptor) -> bool {
model.validate().is_ok()
&& self.supported_models.iter().any(|supported| {
supported.family == model.family
&& supported.architecture == model.architecture
&& supported.weight_format == model.weight_format
})
}
}
impl fmt::Display for ContractError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidField(field) => write!(f, "invalid {field}"),
Self::UnsupportedApiVersion(version) => {
write!(f, "backend API version {version} is unsupported")
}
Self::GenerationAlreadyTerminal => {
f.write_str("generation already has a terminal event")
}
Self::GenerationBackpressure => f.write_str("generation event queue is full"),
Self::GenerationClosed => f.write_str("generation event stream is closed"),
}
}
}
impl std::error::Error for ContractError {}
impl fmt::Display for BackendError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}: {}", self.code, self.message)
}
}
impl std::error::Error for BackendError {}
impl GenerationSink {
pub fn channel() -> (Self, GenerationStream) {
let (sender, receiver) = mpsc::channel();
let closed = Arc::new(AtomicBool::new(false));
(
Self {
sender: EventSender::Unbounded(sender),
receiver_closed: Arc::clone(&closed),
terminal_sent: Mutex::new(false),
},
GenerationStream {
receiver,
receiver_closed: closed,
terminal_seen: false,
},
)
}
/// A finite event queue of 1..=16 events; invalid capacities are refused
/// before the channel can allocate or become a rendezvous channel.
pub fn bounded_channel(capacity: usize) -> Result<(Self, GenerationStream), ContractError> {
if !(1..=16).contains(&capacity) {
return Err(ContractError::InvalidField("event_capacity"));
}
let (sender, receiver) = mpsc::sync_channel(capacity);
let closed = Arc::new(AtomicBool::new(false));
Ok((
Self {
sender: EventSender::Bounded(sender),
receiver_closed: Arc::clone(&closed),
terminal_sent: Mutex::new(false),
},
GenerationStream {
receiver,
receiver_closed: closed,
terminal_seen: false,
},
))
}
/// Receiver destruction is observable without sending a token/event.
pub fn is_closed(&self) -> bool {
self.receiver_closed.load(Ordering::Acquire)
}
/// Never block cancellation behind a full event queue. A rejected terminal
/// has not been published and may be retried until capacity becomes available.
pub fn try_emit(&self, event: GenerationEvent) -> Result<(), ContractError> {
let is_terminal = matches!(event, GenerationEvent::Terminal(_));
let mut terminal_sent = self
.terminal_sent
.lock()
.map_err(|_| ContractError::GenerationClosed)?;
if *terminal_sent {
return Err(ContractError::GenerationAlreadyTerminal);
}
match &self.sender {
EventSender::Unbounded(sender) => sender
.send(event)
.map_err(|_| ContractError::GenerationClosed)?,
EventSender::Bounded(sender) => {
sender.try_send(event).map_err(|error| match error {
TrySendError::Full(_) => ContractError::GenerationBackpressure,
TrySendError::Disconnected(_) => ContractError::GenerationClosed,
})?
}
}
if is_terminal {
*terminal_sent = true;
}
Ok(())
}
pub fn emit(&self, event: GenerationEvent) -> Result<(), ContractError> {
let is_terminal = matches!(event, GenerationEvent::Terminal(_));
let mut terminal_sent = self.terminal_sent.lock().expect("generation lock poisoned");
if *terminal_sent {
return Err(ContractError::GenerationAlreadyTerminal);
}
match &self.sender {
EventSender::Unbounded(sender) => sender.send(event),
EventSender::Bounded(sender) => sender.send(event),
}
.map_err(|SendError(_)| ContractError::GenerationClosed)?;
if is_terminal {
*terminal_sent = true;
}
Ok(())
}
pub fn complete(&self, reason: FinishReason, usage: Usage) -> Result<(), ContractError> {
self.emit(GenerationEvent::Terminal(GenerationTerminal::Completed {
reason,
usage,
}))
}
pub fn fail(
&self,
code: ErrorCode,
message: impl Into<String>,
retryable: bool,
) -> Result<(), ContractError> {
self.emit(GenerationEvent::Terminal(GenerationTerminal::Failed {
code,
message: message.into(),
retryable,
}))
}
pub fn cancel(&self) -> Result<(), ContractError> {
self.emit(GenerationEvent::Terminal(GenerationTerminal::Cancelled))
}
}
impl Drop for GenerationStream {
fn drop(&mut self) {
self.receiver_closed.store(true, Ordering::Release);
}
}
impl GenerationStream {
pub fn recv(&mut self) -> Result<Option<GenerationEvent>, StreamError> {
if self.terminal_seen {
return Ok(None);
}
match self.receiver.recv() {
Ok(event) => {
if matches!(event, GenerationEvent::Terminal(_)) {
self.terminal_seen = true;
}
Ok(Some(event))
}
Err(RecvError) => Err(StreamError::MissingTerminal),
}
}
}
impl fmt::Display for StreamError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingTerminal => {
f.write_str("generation stream closed without a terminal event")
}
}
}
}
impl std::error::Error for StreamError {}