Lines
98.31 %
Functions
100 %
Branches
use std::sync::Arc;
use std::time::Duration;
use rpc::mux::MAX_STREAMS;
use rpc::{MAX_FRAME_BYTES, ScriptLimits, Session};
use sqlx::types::Uuid;
use tokio::sync::Semaphore;
use super::*;
#[derive(Debug)]
enum Sent {
Data(String),
Finished,
}
/// Sends wait for a permit, so a test decides how fast the client reads.
struct GatedSink {
tx: mpsc::UnboundedSender<Sent>,
gate: Arc<Semaphore>,
/// `finish` reports, then waits for a permit: the channel is held inside it.
finish_gate: Arc<Semaphore>,
impl ResponseSink for GatedSink {
fn send(&self, bytes: Vec<u8>) -> SinkFuture<'_> {
Box::pin(async move {
if let Ok(permit) = self.gate.acquire().await {
permit.forget();
let _ = self
.tx
.send(Sent::Data(String::from_utf8(bytes).unwrap_or_default()));
})
fn finish(&self) -> SinkFuture<'_> {
let _ = self.tx.send(Sent::Finished);
if let Ok(permit) = self.finish_gate.acquire().await {
struct Rig {
state: EvalChannelState,
sent: mpsc::UnboundedReceiver<Sent>,
fn rig() -> Rig {
rig_with(ScriptCtx::new(Uuid::new_v4()), Semaphore::MAX_PERMITS)
fn rig_with(ctx: ScriptCtx, permits: usize) -> Rig {
let (tx, sent) = mpsc::unbounded_channel();
let gate = Arc::new(Semaphore::new(permits));
let finish_gate = Arc::new(Semaphore::new(Semaphore::MAX_PERMITS));
let sink = Box::new(GatedSink {
tx,
gate: Arc::clone(&gate),
finish_gate: Arc::clone(&finish_gate),
});
let state = EvalChannelState::open(ctx, Session::new, sink).expect("open");
Rig {
state,
sent,
gate,
finish_gate,
impl Rig {
/// `expected` replies, each awaited; then a short grace window collects
/// an extra one so an over-emission trips the caller's count assertion.
async fn replies(&mut self, expected: usize) -> Vec<String> {
let mut out = Vec::new();
loop {
let budget = if out.len() < expected {
Duration::from_secs(10)
} else {
Duration::from_millis(100)
};
match tokio::time::timeout(budget, self.sent.recv()).await {
Ok(Some(Sent::Data(line))) => out.push(line),
Ok(Some(Sent::Finished)) => panic!("channel finished early: {out:?}"),
Ok(None) | Err(_) => break,
out
/// Everything the channel emits up to its finish.
async fn until_finished(&mut self) -> Vec<Sent> {
while let Ok(Some(event)) =
tokio::time::timeout(Duration::from_secs(10), self.sent.recv()).await
{
let finished = matches!(event, Sent::Finished);
out.push(event);
if finished {
break;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn empty_feed_produces_no_responses() {
let mut rig = rig();
rig.state.feed(b"").expect("feed");
assert!(rig.replies(0).await.is_empty());
async fn complete_frame_yields_response_with_trailing_newline() {
rig.state
.feed(b"(:id 1 :form (rpc-protocol-version))\n")
.expect("feed");
assert_eq!(rig.replies(1).await, ["(:id 1 :value 1)\n"]);
async fn a_frame_split_across_chunks_is_one_request() {
rig.state.feed(b"(:id 3 :form (rpc-proto").expect("feed");
rig.state.feed(b"col-version))\n").expect("feed");
assert_eq!(rig.replies(1).await, ["(:id 3 :value 1)\n"]);
async fn eof_answers_queued_forms_on_two_streams_then_finishes() {
.feed(
b"(:id 1 :form 1)\n(:id 2 :stream 1 :form 2)\n(:id 3 :form 3)\n(:id 4 :stream 1 :form 4)\n",
)
rig.state.end_input();
let events = rig.until_finished().await;
let (last, replies) = events.split_last().expect("events");
assert!(matches!(last, Sent::Finished), "{events:?}");
let mut lines: Vec<&str> = replies
.iter()
.map(|event| match event {
Sent::Data(line) => line.as_str(),
Sent::Finished => "",
.collect();
lines.sort_unstable();
assert_eq!(
lines,
[
"(:id 1 :value 1)\n",
"(:id 2 :stream 1 :value 2)\n",
"(:id 3 :value 3)\n",
"(:id 4 :stream 1 :value 4)\n",
]
);
async fn ending_input_mid_frame_only_finishes() {
rig.state.feed(b"(:id 1 :form (rpc-protocol").expect("feed");
assert!(matches!(&events[..], [Sent::Finished]), "{events:?}");
async fn a_stray_etx_byte_is_ordinary_input() {
.feed(b"(:id 7 :form 1)\n\x03\n(:id 8 :form 2)\n")
let replies = rig.replies(3).await;
assert_eq!(replies.len(), 3, "{replies:?}");
assert!(
replies.contains(&"(:id 7 :value 1)\n".to_owned()),
"{replies:?}"
replies.contains(&"(:id 8 :value 2)\n".to_owned()),
replies
.any(|line| line.starts_with("(:id 0 :error (:code parse")),
async fn a_stray_etx_byte_inside_a_form_is_that_forms_error() {
rig.state.feed(b"(:id 5 :form \x03)\n").expect("feed");
let replies = rig.replies(1).await;
assert_eq!(replies.len(), 1, "{replies:?}");
assert!(replies[0].starts_with("(:id 5 :error "), "{replies:?}");
async fn an_interrupt_frame_cancels_the_inflight_eval() {
// The loop counts to a billion with unbounded fuel, so only the interrupt can end it.
let ctx = ScriptCtx::new(Uuid::new_v4()).with_limits(ScriptLimits {
fuel: u64::MAX,
..ScriptLimits::default()
let mut rig = rig_with(ctx, Semaphore::MAX_PERMITS);
.feed(b"(:id 9 :form (do ((i 0 (+ i 1))) ((>= i 1000000000) i)))\n")
tokio::time::sleep(Duration::from_millis(20)).await;
rig.state.feed(b"(:interrupt 0)\n").expect("feed");
assert!(replies[0].starts_with("(:id 9 "), "{replies:?}");
assert!(replies[0].contains(":code interrupted"), "{replies:?}");
async fn a_frame_over_the_cap_gets_a_parse_reply_then_the_channel_ends() {
let oversized = format!("({}", "a".repeat(MAX_FRAME_BYTES));
for chunk in oversized.as_bytes().chunks(32 * 1024) {
rig.state.feed(chunk).expect("feed");
let [Sent::Data(reply), Sent::Finished] = &events[..] else {
panic!("expected a parse reply then the end: {events:?}");
assert!(reply.starts_with("(:id 0 :error (:code parse"), "{reply}");
assert!(reply.contains("exceeds 1048576 bytes"), "{reply}");
/// Feeds one garbage frame per call, each owed a direct reply, and counts how
/// many the channel took before it refused.
fn accepted_before_backlog(state: &mut EvalChannelState) -> Option<usize> {
(0..10_000).find(|_| state.feed(b"(garbage)\n").is_err())
async fn a_client_that_never_reads_stops_the_reader_and_hits_the_backlog() {
let mut rig = rig_with(ScriptCtx::new(Uuid::new_v4()), 0);
let accepted = accepted_before_backlog(&mut rig.state).expect("backlog reached");
// One reply in the sink, a full reply channel, one held by the reader, then the input queue.
assert!(accepted <= INPUT_CHUNKS + MAX_STREAMS + 2, "{accepted}");
assert!(accepted >= INPUT_CHUNKS, "{accepted}");
async fn a_reader_held_back_resumes_and_loses_nothing() {
let frames = INPUT_CHUNKS;
for _ in 0..frames {
rig.state.feed(b"(garbage)\n").expect("within the backlog");
rig.gate.add_permits(frames);
let replies = rig.replies(frames).await;
assert_eq!(replies.len(), frames);
async fn piped_forms_past_the_stream_queue_are_all_answered_in_order() {
let forms: String = (1..=200)
.map(|id| format!("(:id {id} :form {id})\n"))
rig.state.feed(forms.as_bytes()).expect("feed");
let replies = rig.replies(200).await;
let expected: Vec<String> = (1..=200)
.map(|id| format!("(:id {id} :value {id})\n"))
assert_eq!(replies, expected);
async fn a_closed_channel_stays_live_until_its_replies_are_sent() {
rig.state.feed(b"(:id 1 :form 1)\n").expect("feed");
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(rig.state.is_live(), "its reply is still unsent");
rig.gate.add_permits(1);
matches!(&events[..], [Sent::Data(_), Sent::Finished]),
"{events:?}"
async fn a_channel_is_not_live_once_its_last_reply_is_sent() {
rig.finish_gate.forget_permits(Semaphore::MAX_PERMITS);
!rig.state.is_live(),
"reported finished while still counted"
/// Tens of seconds of fuel-free looping: only an interrupt ends it inside the test bounds.
const ENDLESS: &str =
"(do ((j 0 (+ j 1))) ((>= j 10) j) (do ((i 0 (+ i 1))) ((>= i 1000000000) i)))";
fn unbounded_fuel() -> ScriptCtx {
ScriptCtx::new(Uuid::new_v4()).with_limits(ScriptLimits {
fn forms_behind_a_loop() -> String {
let queued: String = (2..=40)
format!("(:id 1 :form {ENDLESS})\n{queued}")
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn an_interrupt_in_the_same_chunk_passes_forms_waiting_for_room() {
let mut rig = rig_with(unbounded_fuel(), Semaphore::MAX_PERMITS);
let chunk = format!("{}(:interrupt 0)\n", forms_behind_a_loop());
rig.state.feed(chunk.as_bytes()).expect("feed");
assert!(replies[0].starts_with("(:id 1 "), "{replies:?}");
async fn a_later_interrupt_is_read_while_a_form_waits_for_room() {
.feed(forms_behind_a_loop().as_bytes())
tokio::time::sleep(Duration::from_millis(300)).await;
replies[0].contains("EpochInterrupt"),
"trapped while running, not cancelled before it started: {replies:?}"
async fn a_client_close_aborts_a_running_eval_and_ends_the_channel() {
rig.state.close();
assert!(matches!(events.last(), Some(Sent::Finished)), "{events:?}");
assert!(!rig.state.is_live());
async fn a_client_close_after_eof_still_aborts_what_is_running() {
async fn forms_before_a_framing_error_are_still_answered() {
let oversized = format!("(:id 1 :form 1)\n({}", "a".repeat(MAX_FRAME_BYTES));
rig.state.feed(oversized.as_bytes()).expect("feed");
let lines: Vec<&str> = events
.filter_map(|event| match event {
Sent::Data(line) => Some(line.as_str()),
Sent::Finished => None,
assert_eq!(lines.len(), 2, "{events:?}");
assert!(lines.contains(&"(:id 1 :value 1)\n"), "{lines:?}");
lines
"{lines:?}"