1
use std::sync::Arc;
2
use std::time::Duration;
3

            
4
use rpc::mux::MAX_STREAMS;
5
use rpc::{MAX_FRAME_BYTES, ScriptLimits, Session};
6
use sqlx::types::Uuid;
7
use tokio::sync::Semaphore;
8

            
9
use super::*;
10

            
11
#[derive(Debug)]
12
enum Sent {
13
    Data(String),
14
    Finished,
15
}
16

            
17
/// Sends wait for a permit, so a test decides how fast the client reads.
18
struct GatedSink {
19
    tx: mpsc::UnboundedSender<Sent>,
20
    gate: Arc<Semaphore>,
21
    /// `finish` reports, then waits for a permit: the channel is held inside it.
22
    finish_gate: Arc<Semaphore>,
23
}
24

            
25
impl ResponseSink for GatedSink {
26
370
    fn send(&self, bytes: Vec<u8>) -> SinkFuture<'_> {
27
370
        Box::pin(async move {
28
370
            if let Ok(permit) = self.gate.acquire().await {
29
370
                permit.forget();
30
            }
31
370
            let _ = self
32
370
                .tx
33
370
                .send(Sent::Data(String::from_utf8(bytes).unwrap_or_default()));
34
370
        })
35
370
    }
36

            
37
8
    fn finish(&self) -> SinkFuture<'_> {
38
8
        Box::pin(async move {
39
8
            let _ = self.tx.send(Sent::Finished);
40
8
            if let Ok(permit) = self.finish_gate.acquire().await {
41
7
                permit.forget();
42
            }
43
7
        })
44
8
    }
45
}
46

            
47
struct Rig {
48
    state: EvalChannelState,
49
    sent: mpsc::UnboundedReceiver<Sent>,
50
    gate: Arc<Semaphore>,
51
    finish_gate: Arc<Semaphore>,
52
}
53

            
54
11
fn rig() -> Rig {
55
11
    rig_with(ScriptCtx::new(Uuid::new_v4()), Semaphore::MAX_PERMITS)
56
11
}
57

            
58
19
fn rig_with(ctx: ScriptCtx, permits: usize) -> Rig {
59
19
    let (tx, sent) = mpsc::unbounded_channel();
60
19
    let gate = Arc::new(Semaphore::new(permits));
61
19
    let finish_gate = Arc::new(Semaphore::new(Semaphore::MAX_PERMITS));
62
19
    let sink = Box::new(GatedSink {
63
19
        tx,
64
19
        gate: Arc::clone(&gate),
65
19
        finish_gate: Arc::clone(&finish_gate),
66
19
    });
67
19
    let state = EvalChannelState::open(ctx, Session::new, sink).expect("open");
68
19
    Rig {
69
19
        state,
70
19
        sent,
71
19
        gate,
72
19
        finish_gate,
73
19
    }
74
19
}
75

            
76
impl Rig {
77
    /// `expected` replies, each awaited; then a short grace window collects
78
    /// an extra one so an over-emission trips the caller's count assertion.
79
10
    async fn replies(&mut self, expected: usize) -> Vec<String> {
80
10
        let mut out = Vec::new();
81
        loop {
82
291
            let budget = if out.len() < expected {
83
273
                Duration::from_secs(10)
84
            } else {
85
18
                Duration::from_millis(100)
86
            };
87
291
            match tokio::time::timeout(budget, self.sent.recv()).await {
88
281
                Ok(Some(Sent::Data(line))) => out.push(line),
89
                Ok(Some(Sent::Finished)) => panic!("channel finished early: {out:?}"),
90
10
                Ok(None) | Err(_) => break,
91
            }
92
        }
93
10
        out
94
10
    }
95

            
96
    /// Everything the channel emits up to its finish.
97
8
    async fn until_finished(&mut self) -> Vec<Sent> {
98
8
        let mut out = Vec::new();
99
        while let Ok(Some(event)) =
100
97
            tokio::time::timeout(Duration::from_secs(10), self.sent.recv()).await
101
        {
102
97
            let finished = matches!(event, Sent::Finished);
103
97
            out.push(event);
104
97
            if finished {
105
8
                break;
106
89
            }
107
        }
108
8
        out
109
8
    }
110
}
111

            
112
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
113
1
async fn empty_feed_produces_no_responses() {
114
1
    let mut rig = rig();
115
1
    rig.state.feed(b"").expect("feed");
116
1
    assert!(rig.replies(0).await.is_empty());
117
1
}
118

            
119
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
120
1
async fn complete_frame_yields_response_with_trailing_newline() {
121
1
    let mut rig = rig();
122
1
    rig.state
123
1
        .feed(b"(:id 1 :form (rpc-protocol-version))\n")
124
1
        .expect("feed");
125
1
    assert_eq!(rig.replies(1).await, ["(:id 1 :value 1)\n"]);
126
1
}
127

            
128
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
129
1
async fn a_frame_split_across_chunks_is_one_request() {
130
1
    let mut rig = rig();
131
1
    rig.state.feed(b"(:id 3 :form (rpc-proto").expect("feed");
132
1
    rig.state.feed(b"col-version))\n").expect("feed");
133
1
    assert_eq!(rig.replies(1).await, ["(:id 3 :value 1)\n"]);
134
1
}
135

            
136
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
137
1
async fn eof_answers_queued_forms_on_two_streams_then_finishes() {
138
1
    let mut rig = rig();
139
1
    rig.state
140
1
        .feed(
141
1
            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",
142
1
        )
143
1
        .expect("feed");
144
1
    rig.state.end_input();
145
1
    let events = rig.until_finished().await;
146
1
    let (last, replies) = events.split_last().expect("events");
147
1
    assert!(matches!(last, Sent::Finished), "{events:?}");
148
1
    let mut lines: Vec<&str> = replies
149
1
        .iter()
150
4
        .map(|event| match event {
151
4
            Sent::Data(line) => line.as_str(),
152
            Sent::Finished => "",
153
4
        })
154
        .collect();
155
1
    lines.sort_unstable();
156
1
    assert_eq!(
157
1
        lines,
158
1
        [
159
1
            "(:id 1 :value 1)\n",
160
1
            "(:id 2 :stream 1 :value 2)\n",
161
1
            "(:id 3 :value 3)\n",
162
1
            "(:id 4 :stream 1 :value 4)\n",
163
1
        ]
164
1
    );
165
1
}
166

            
167
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
168
1
async fn ending_input_mid_frame_only_finishes() {
169
1
    let mut rig = rig();
170
1
    rig.state.feed(b"(:id 1 :form (rpc-protocol").expect("feed");
171
1
    rig.state.end_input();
172
1
    let events = rig.until_finished().await;
173
1
    assert!(matches!(&events[..], [Sent::Finished]), "{events:?}");
174
1
}
175

            
176
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
177
1
async fn a_stray_etx_byte_is_ordinary_input() {
178
1
    let mut rig = rig();
179
1
    rig.state
180
1
        .feed(b"(:id 7 :form 1)\n\x03\n(:id 8 :form 2)\n")
181
1
        .expect("feed");
182
1
    let replies = rig.replies(3).await;
183
1
    assert_eq!(replies.len(), 3, "{replies:?}");
184
1
    assert!(
185
1
        replies.contains(&"(:id 7 :value 1)\n".to_owned()),
186
        "{replies:?}"
187
    );
188
1
    assert!(
189
1
        replies.contains(&"(:id 8 :value 2)\n".to_owned()),
190
        "{replies:?}"
191
    );
192
1
    assert!(
193
1
        replies
194
1
            .iter()
195
1
            .any(|line| line.starts_with("(:id 0 :error (:code parse")),
196
1
        "{replies:?}"
197
1
    );
198
1
}
199

            
200
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
201
1
async fn a_stray_etx_byte_inside_a_form_is_that_forms_error() {
202
1
    let mut rig = rig();
203
1
    rig.state.feed(b"(:id 5 :form \x03)\n").expect("feed");
204
1
    let replies = rig.replies(1).await;
205
1
    assert_eq!(replies.len(), 1, "{replies:?}");
206
1
    assert!(replies[0].starts_with("(:id 5 :error "), "{replies:?}");
207
1
}
208

            
209
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
210
1
async fn an_interrupt_frame_cancels_the_inflight_eval() {
211
    // The loop counts to a billion with unbounded fuel, so only the interrupt can end it.
212
1
    let ctx = ScriptCtx::new(Uuid::new_v4()).with_limits(ScriptLimits {
213
1
        fuel: u64::MAX,
214
1
        ..ScriptLimits::default()
215
1
    });
216
1
    let mut rig = rig_with(ctx, Semaphore::MAX_PERMITS);
217
1
    rig.state
218
1
        .feed(b"(:id 9 :form (do ((i 0 (+ i 1))) ((>= i 1000000000) i)))\n")
219
1
        .expect("feed");
220
1
    tokio::time::sleep(Duration::from_millis(20)).await;
221
1
    rig.state.feed(b"(:interrupt 0)\n").expect("feed");
222
1
    let replies = rig.replies(1).await;
223
1
    assert_eq!(replies.len(), 1, "{replies:?}");
224
1
    assert!(replies[0].starts_with("(:id 9 "), "{replies:?}");
225
1
    assert!(replies[0].contains(":code interrupted"), "{replies:?}");
226
1
}
227

            
228
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
229
1
async fn a_frame_over_the_cap_gets_a_parse_reply_then_the_channel_ends() {
230
1
    let mut rig = rig();
231
1
    let oversized = format!("({}", "a".repeat(MAX_FRAME_BYTES));
232
1
    for chunk in oversized.as_bytes().chunks(32 * 1024) {
233
33
        rig.state.feed(chunk).expect("feed");
234
    }
235
1
    let events = rig.until_finished().await;
236
1
    let [Sent::Data(reply), Sent::Finished] = &events[..] else {
237
        panic!("expected a parse reply then the end: {events:?}");
238
    };
239
1
    assert!(reply.starts_with("(:id 0 :error (:code parse"), "{reply}");
240
1
    assert!(reply.contains("exceeds 1048576 bytes"), "{reply}");
241
1
}
242

            
243
/// Feeds one garbage frame per call, each owed a direct reply, and counts how
244
/// many the channel took before it refused.
245
1
fn accepted_before_backlog(state: &mut EvalChannelState) -> Option<usize> {
246
65
    (0..10_000).find(|_| state.feed(b"(garbage)\n").is_err())
247
1
}
248

            
249
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
250
1
async fn a_client_that_never_reads_stops_the_reader_and_hits_the_backlog() {
251
1
    let mut rig = rig_with(ScriptCtx::new(Uuid::new_v4()), 0);
252
1
    let accepted = accepted_before_backlog(&mut rig.state).expect("backlog reached");
253
    // One reply in the sink, a full reply channel, one held by the reader, then the input queue.
254
1
    assert!(accepted <= INPUT_CHUNKS + MAX_STREAMS + 2, "{accepted}");
255
1
    assert!(accepted >= INPUT_CHUNKS, "{accepted}");
256
1
}
257

            
258
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
259
1
async fn a_reader_held_back_resumes_and_loses_nothing() {
260
1
    let mut rig = rig_with(ScriptCtx::new(Uuid::new_v4()), 0);
261
1
    let frames = INPUT_CHUNKS;
262
1
    for _ in 0..frames {
263
64
        rig.state.feed(b"(garbage)\n").expect("within the backlog");
264
    }
265
1
    rig.gate.add_permits(frames);
266
1
    let replies = rig.replies(frames).await;
267
1
    assert_eq!(replies.len(), frames);
268
1
}
269

            
270
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
271
1
async fn piped_forms_past_the_stream_queue_are_all_answered_in_order() {
272
1
    let mut rig = rig();
273
1
    let forms: String = (1..=200)
274
200
        .map(|id| format!("(:id {id} :form {id})\n"))
275
        .collect();
276
1
    rig.state.feed(forms.as_bytes()).expect("feed");
277
1
    let replies = rig.replies(200).await;
278
1
    let expected: Vec<String> = (1..=200)
279
200
        .map(|id| format!("(:id {id} :value {id})\n"))
280
        .collect();
281
1
    assert_eq!(replies, expected);
282
1
}
283

            
284
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
285
1
async fn a_closed_channel_stays_live_until_its_replies_are_sent() {
286
1
    let mut rig = rig_with(ScriptCtx::new(Uuid::new_v4()), 0);
287
1
    rig.state.feed(b"(:id 1 :form 1)\n").expect("feed");
288
1
    rig.state.end_input();
289
1
    tokio::time::sleep(Duration::from_millis(200)).await;
290
1
    assert!(rig.state.is_live(), "its reply is still unsent");
291
1
    rig.gate.add_permits(1);
292
1
    let events = rig.until_finished().await;
293
1
    assert!(
294
1
        matches!(&events[..], [Sent::Data(_), Sent::Finished]),
295
1
        "{events:?}"
296
1
    );
297
1
}
298

            
299
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
300
1
async fn a_channel_is_not_live_once_its_last_reply_is_sent() {
301
1
    let mut rig = rig();
302
1
    rig.finish_gate.forget_permits(Semaphore::MAX_PERMITS);
303
1
    rig.state.feed(b"(:id 1 :form 1)\n").expect("feed");
304
1
    rig.state.end_input();
305
1
    let events = rig.until_finished().await;
306
1
    assert!(
307
1
        matches!(&events[..], [Sent::Data(_), Sent::Finished]),
308
        "{events:?}"
309
    );
310
1
    assert!(
311
1
        !rig.state.is_live(),
312
1
        "reported finished while still counted"
313
1
    );
314
1
}
315

            
316
/// Tens of seconds of fuel-free looping: only an interrupt ends it inside the test bounds.
317
const ENDLESS: &str =
318
    "(do ((j 0 (+ j 1))) ((>= j 10) j) (do ((i 0 (+ i 1))) ((>= i 1000000000) i)))";
319

            
320
4
fn unbounded_fuel() -> ScriptCtx {
321
4
    ScriptCtx::new(Uuid::new_v4()).with_limits(ScriptLimits {
322
4
        fuel: u64::MAX,
323
4
        ..ScriptLimits::default()
324
4
    })
325
4
}
326

            
327
4
fn forms_behind_a_loop() -> String {
328
4
    let queued: String = (2..=40)
329
156
        .map(|id| format!("(:id {id} :form {id})\n"))
330
        .collect();
331
4
    format!("(:id 1 :form {ENDLESS})\n{queued}")
332
4
}
333

            
334
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
335
1
async fn an_interrupt_in_the_same_chunk_passes_forms_waiting_for_room() {
336
1
    let mut rig = rig_with(unbounded_fuel(), Semaphore::MAX_PERMITS);
337
1
    let chunk = format!("{}(:interrupt 0)\n", forms_behind_a_loop());
338
1
    rig.state.feed(chunk.as_bytes()).expect("feed");
339
1
    let replies = rig.replies(1).await;
340
1
    assert!(replies[0].starts_with("(:id 1 "), "{replies:?}");
341
1
    assert!(replies[0].contains(":code interrupted"), "{replies:?}");
342
1
}
343

            
344
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
345
1
async fn a_later_interrupt_is_read_while_a_form_waits_for_room() {
346
1
    let mut rig = rig_with(unbounded_fuel(), Semaphore::MAX_PERMITS);
347
1
    rig.state
348
1
        .feed(forms_behind_a_loop().as_bytes())
349
1
        .expect("feed");
350
1
    tokio::time::sleep(Duration::from_millis(300)).await;
351
1
    rig.state.feed(b"(:interrupt 0)\n").expect("feed");
352
1
    let replies = rig.replies(1).await;
353
1
    assert!(replies[0].starts_with("(:id 1 "), "{replies:?}");
354
1
    assert!(replies[0].contains(":code interrupted"), "{replies:?}");
355
1
    assert!(
356
1
        replies[0].contains("EpochInterrupt"),
357
1
        "trapped while running, not cancelled before it started: {replies:?}"
358
1
    );
359
1
}
360

            
361
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
362
1
async fn a_client_close_aborts_a_running_eval_and_ends_the_channel() {
363
1
    let mut rig = rig_with(unbounded_fuel(), Semaphore::MAX_PERMITS);
364
1
    rig.state
365
1
        .feed(forms_behind_a_loop().as_bytes())
366
1
        .expect("feed");
367
1
    tokio::time::sleep(Duration::from_millis(300)).await;
368
1
    rig.state.close();
369
1
    let events = rig.until_finished().await;
370
1
    assert!(matches!(events.last(), Some(Sent::Finished)), "{events:?}");
371
1
    assert!(!rig.state.is_live());
372
1
}
373

            
374
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
375
1
async fn a_client_close_after_eof_still_aborts_what_is_running() {
376
1
    let mut rig = rig_with(unbounded_fuel(), Semaphore::MAX_PERMITS);
377
1
    rig.state
378
1
        .feed(forms_behind_a_loop().as_bytes())
379
1
        .expect("feed");
380
1
    rig.state.end_input();
381
1
    tokio::time::sleep(Duration::from_millis(300)).await;
382
1
    rig.state.close();
383
1
    let events = rig.until_finished().await;
384
1
    assert!(matches!(events.last(), Some(Sent::Finished)), "{events:?}");
385
1
    assert!(!rig.state.is_live());
386
1
}
387

            
388
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
389
1
async fn forms_before_a_framing_error_are_still_answered() {
390
1
    let mut rig = rig();
391
1
    let oversized = format!("(:id 1 :form 1)\n({}", "a".repeat(MAX_FRAME_BYTES));
392
1
    rig.state.feed(oversized.as_bytes()).expect("feed");
393
1
    let events = rig.until_finished().await;
394
1
    let lines: Vec<&str> = events
395
1
        .iter()
396
3
        .filter_map(|event| match event {
397
2
            Sent::Data(line) => Some(line.as_str()),
398
1
            Sent::Finished => None,
399
3
        })
400
        .collect();
401
1
    assert_eq!(lines.len(), 2, "{events:?}");
402
1
    assert!(lines.contains(&"(:id 1 :value 1)\n"), "{lines:?}");
403
1
    assert!(
404
1
        lines
405
1
            .iter()
406
1
            .any(|line| line.starts_with("(:id 0 :error (:code parse")),
407
1
        "{lines:?}"
408
1
    );
409
1
}