Files
leleka/crates/runtime-client/tests/grpc_backend/server_and_frames.rs
T
2026-11-07 09:41:44 +01:00

126 lines
3.6 KiB
Rust

//! Starting the scripted server, frame builders and the blocking helpers of the tests.
#[allow(unused_imports)]
use super::*;
impl Server {
pub(super) async fn start(loaded: Option<LoadedModel>) -> Self {
let fake = Fake::new(loaded);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let (stop, stopped) = tokio::sync::oneshot::channel();
let service = fake.clone();
let task = tokio::spawn(async move {
tonic::transport::Server::builder()
.add_service(proto::runtime_server::RuntimeServer::new(service))
.serve_with_incoming_shutdown(
tokio_stream::wrappers::TcpListenerStream::new(listener),
async {
let _ = stopped.await;
},
)
.await
.unwrap();
});
Self {
address,
fake,
stop: Some(stop),
task,
}
}
pub(super) fn backend(&self) -> GrpcBackend {
GrpcBackend::new(
tokio::runtime::Handle::current(),
self.address,
TOKEN.into(),
)
}
pub(super) async fn finish(mut self) {
let _ = self.stop.take().unwrap().send(());
if tokio::time::timeout(Duration::from_millis(300), &mut self.task)
.await
.is_err()
{
self.task.abort();
}
}
}
pub(super) fn usage(i: u64, o: u64, r: u64) -> proto::Usage {
proto::Usage {
input_tokens: i,
output_tokens: o,
reused_input_tokens: r,
}
}
pub(super) fn terminal(state: i32, reason: &str, with_usage: bool) -> Payload {
Payload::Terminal(proto::Terminal {
state,
reason: reason.into(),
usage: with_usage.then(|| usage(10, 3, 2)),
error_code: if state == 2 {
"resource_exhausted".into()
} else {
String::new()
},
retryable: false,
})
}
pub(super) fn text(s: &str) -> Payload {
Payload::Text(proto::TextDelta { text: s.into() })
}
pub(super) fn request(id: &str) -> GenerationRequest {
GenerationRequest {
request_id: id.into(),
prompt: "<|im_start|>user\nhi<|im_end|>\n".into(),
max_output_tokens: 64,
temperature_milli: 700,
sampling: SamplingOptions {
top_p_micro: Some(900_000),
top_k: Some(20),
min_p_micro: Some(50_000),
repetition_penalty_micro: Some(1_100_000),
frequency_penalty_micro: Some(-500_000),
presence_penalty_micro: Some(250_000),
penalty_last_n: Some(64),
seed: Some(42),
},
}
}
/// Run a blocking backend call on a blocking thread, as the control plane does.
pub(super) async fn blocking<T: Send + 'static>(
mut backend: GrpcBackend,
call: impl FnOnce(&mut GrpcBackend) -> T + Send + 'static,
) -> (GrpcBackend, T) {
tokio::task::spawn_blocking(move || {
let value = call(&mut backend);
(backend, value)
})
.await
.unwrap()
}
pub(super) fn id() -> String {
uuid::Uuid::new_v4().to_string()
}
pub(super) fn drain(
stream: &mut leleka_backend_api::GenerationStream,
) -> (Vec<GenerationEvent>, bool) {
let mut events = Vec::new();
loop {
match stream.recv() {
Ok(Some(event)) => events.push(event),
Ok(None) => return (events, true),
Err(StreamError::MissingTerminal) => return (events, false),
}
}
}