1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
//! Wait behavior - add latency before response.
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::sync::LazyLock;
// Fixed patterns for the no-`javascript`-feature wait fallback (issue #481): compile once at
// first use instead of on every request. These are compile-time-constant patterns, so a compile
// failure is a programming error caught immediately by tests, not a data-dependent runtime error.
static WAIT_FLOOR_OFFSET_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"Math\.floor\s*\(\s*Math\.random\s*\(\s*\)\s*\*\s*(\d+)\s*\)\s*\+\s*(\d+)")
.expect("wait floor+offset pattern is a valid constant regex")
});
static WAIT_RANDOM_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"Math\.random\s*\(\s*\)\s*\*\s*(\d+)")
.expect("wait random pattern is a valid constant regex")
});
static WAIT_SOLO_MIN_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"var\s+min\s*=\s*Math\.ceil\s*\(\s*(\d+)\s*\)")
.expect("wait solo-min pattern is a valid constant regex")
});
static WAIT_SOLO_MAX_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"var\s+max\s*=\s*Math\.floor\s*\(\s*(\d+)\s*\)")
.expect("wait solo-max pattern is a valid constant regex")
});
/// Wait behavior - add latency before response
#[derive(Debug, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(untagged)]
pub enum WaitBehavior {
/// Fixed delay in milliseconds
Fixed(u64),
/// Random delay within range
Range {
#[serde(rename = "min")]
min_ms: u64,
#[serde(rename = "max")]
max_ms: u64,
},
/// JavaScript function that returns delay — the Mountebank-compatible spelling.
Function(String),
/// The same JavaScript function in Rift's object spelling (issue #608), as written by
/// `docs/features/fault-injection.md`, the shipped examples, and the SDKs. Executes
/// identically to [`Self::Function`]; kept as a distinct variant only so a config
/// round-trips to the spelling its author wrote. Not portable to Mountebank, which has no
/// object form — like [`Self::Range`], this is a documented Rift superset.
Inject { inject: String },
}
/// A `wait` function that threw (issue #1616): Mountebank answers the request with `500` and
/// `invalid wait injection` instead of serving the response, whatever `strictBehaviors` says.
///
/// Only a script error is one: a throw, a `ReferenceError`, a syntax error found when the source
/// is evaluated, or a throw while converting the result to a number. A result that is not a number
/// is no delay, not an error (issue #1588).
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{detail}")]
pub struct WaitScriptError {
/// What went wrong, for the log.
pub detail: String,
/// Mountebank's `data`: the thrown value's `message`. `None` when the thrown value has none,
/// as for `throw 'text'`, where Mountebank leaves `data` out.
pub data: Option<String>,
}
impl WaitBehavior {
/// The wait in milliseconds, or the error a `wait` function threw (issue #1616).
///
/// # Errors
///
/// [`WaitScriptError`] when a function `wait` throws or does not parse. Only a build with the
/// `javascript` feature can tell; without it the regex fallback cannot tell a throw from a
/// body it does not read, so both take a logged 100 ms fallback there.
pub fn get_duration_ms(&self) -> Result<u64, WaitScriptError> {
match self {
WaitBehavior::Fixed(ms) => Ok(*ms),
WaitBehavior::Range { min_ms, max_ms } => {
use rand::RngExt;
// `random_range` asserts a non-empty range, and this runs on the request task with no
// `catch_unwind` — an inverted range killed the worker on every request (#1148).
// The parse door refuses that shape, but this is a `pub` enum with `pub` fields, so
// the draw has to be total on its own. Clamp to `min` like the two sibling draw
// sites; swapping would quietly honour a config the door rejects.
if max_ms <= min_ms {
if max_ms < min_ms {
tracing::warn!(
"wait range has min {min_ms} greater than max {max_ms}; clamping to \
min. The parse door refuses this, so reaching it means the value was \
built in-process rather than loaded"
);
}
Ok(*min_ms)
} else {
Ok(rand::rng().random_range(*min_ms..=*max_ms))
}
}
// Both spellings of a JS-function wait run the identical path (issue #608): same Boa
// execution, same failure.
WaitBehavior::Function(js_func) | WaitBehavior::Inject { inject: js_func } => {
// No cap (issue #1612): like a numeric `wait` and like Mountebank, the computed
// delay is honoured as written. The sleep is an async `tokio::time::sleep`, which
// saturates an overflowing deadline, so a huge value holds no worker thread.
//
// `None` is reachable only without the `javascript` feature: the regex fallback
// did not recognise the body. It falls back to 100ms, loudly, so it is
// distinguishable from a genuine 100ms wait (B4, issue #355).
Ok(Self::execute_js_wait_function(js_func)?.unwrap_or_else(|| {
tracing::warn!(
target: "rift::script",
"wait function produced no usable delay; falling back to 100ms"
);
100
}))
}
}
}
/// Compute the delay for a string `wait` the way Mountebank does (`behaviors.js` `wait`,
/// issue #1588): `parseInt` first, so `"1000"` is 1000 and `"800ms"` is 800; otherwise the
/// source is called as a function, `(<source>)()`, so any callable expression works — a
/// `function`, an arrow, `async`, a parenthesised function. There is deliberately no prefix
/// check: Mountebank has none, and a copied routing rule is what kept arrows at 100 ms.
///
/// When the `javascript` feature is enabled the call runs on a bounded Boa `Context` (issue
/// #355 Item 6), and its answer is final: `Err` for a script that throws (issue #1616), a
/// delay otherwise. Without it, a regex fallback reads the common shapes, so
/// `--no-default-features` still builds and works for them; `Ok(None)` means it could not read
/// the source, and the caller takes its logged 100 ms fallback.
fn execute_js_wait_function(js_func: &str) -> Result<Option<u64>, WaitScriptError> {
let parsed = rift_types::status::js_parse_int(js_func);
if !parsed.is_nan() {
return Ok(Some(node_timeout_ms(parsed)));
}
let trimmed = js_func.trim();
#[cfg(feature = "javascript")]
{
Self::execute_js_wait_function_boa(trimmed).map(Some)
}
#[cfg(not(feature = "javascript"))]
{
Ok(Self::execute_js_wait_function_regex(trimmed))
}
}
/// Run the wait function for real on a bounded Boa `Context`: evaluate `(<js_func>)()` and
/// read the result as Node's `setTimeout` reads a delay ([`node_timeout_ms`]). `Err` for a
/// script that throws or does not parse, including a throw while converting the result
/// (issue #1616).
#[cfg(feature = "javascript")]
fn execute_js_wait_function_boa(js_func: &str) -> Result<u64, WaitScriptError> {
let mut context = crate::scripting::bounded_js_context();
let wrapped = format!("({js_func})()");
let failed = |stage: &str, e: &boa_engine::JsError, context: &mut boa_engine::Context| {
let detail = format!("wait function {stage}: {e}");
tracing::warn!(target: "rift::script", "{detail}");
WaitScriptError {
detail,
data: thrown_message(e, context),
}
};
let result = context
.eval(boa_engine::Source::from_bytes(wrapped.as_bytes()))
.map_err(|e| failed("script error", &e, &mut context))?;
// `to_number` fails only when the conversion itself throws (a `valueOf` that throws, a
// Symbol) — a throw, like the one above. A string, a Promise or `undefined` converts to
// `NaN`, which is a value, not an error.
let n = result.to_number(&mut context).map_err(|e| {
failed(
"result could not be converted to a number",
&e,
&mut context,
)
})?;
Ok(node_timeout_ms(n))
}
/// Regex-based fallback: the sole path when the `javascript` feature is disabled. With the
/// feature on, Boa's answer is final and this is never reached (issue #1616): a throwing
/// function must not turn into a guess at its `Math.random` shape.
#[cfg_attr(feature = "javascript", allow(dead_code))]
fn execute_js_wait_function_regex(trimmed: &str) -> Option<u64> {
if let Some(body) = extract_function_body(trimmed) {
// Handle Solo pattern:
// var min = Math.ceil(N); var max = Math.floor(M); var num = Math.floor(Math.random() * (max - min + 1)); var wait = (num + min); return wait;
if body.contains("var min") && body.contains("var max") {
return Self::parse_solo_wait_pattern(&body);
}
// Look for patterns like "Math.floor(Math.random() * 100) + 50"
// or "return Math.floor(Math.random() * 100) + 50;"
let body = body
.replace("return ", "")
.trim_end_matches(';')
.to_string();
// Parse: Math.floor(Math.random() * N) + M
if body.contains("Math.random()") {
use rand::RngExt;
// Extract multiplier and offset using the cached constant patterns.
if let Some(caps) = WAIT_FLOOR_OFFSET_RE.captures(&body) {
let range = caps.get(1)?.as_str().parse::<u64>().ok()?;
let offset = caps.get(2)?.as_str().parse::<u64>().ok()?;
return Some(rand::rng().random_range(offset..=offset.saturating_add(range)));
}
// Simpler pattern: Math.random() * N
if let Some(caps) = WAIT_RANDOM_RE.captures(&body) {
let range = caps.get(1)?.as_str().parse::<u64>().ok()?;
return Some(rand::rng().random_range(0..=range));
}
}
// Try to parse as a simple number. Parse signed so a negative literal clamps to 0
// (matching the Boa path) instead of failing to parse and dropping to the 100ms
// fallback (issue #490).
body.trim().parse::<i64>().ok().map(|v| v.max(0) as u64)
} else {
// An arrow with a bare numeric body, `() => 250` (issue #1588). Only a literal: this
// fallback is not a JavaScript parser.
let (_, body) = trimmed.split_once("=>")?;
body.trim()
.trim_end_matches(';')
.trim_end()
.parse::<i64>()
.ok()
.map(|v| v.max(0) as u64)
}
}
/// Parse Solo wait pattern:
/// var min = Math.ceil(N); var max = Math.floor(M); var num = Math.floor(Math.random() * (max - min + 1)); var wait = (num + min); return wait;
fn parse_solo_wait_pattern(body: &str) -> Option<u64> {
use rand::RngExt;
// Extract min value: var min = Math.ceil(N)
let min_val = WAIT_SOLO_MIN_RE
.captures(body)
.and_then(|c| c.get(1))
.and_then(|m| m.as_str().parse::<u64>().ok())
.unwrap_or(0);
// Extract max value: var max = Math.floor(N)
let max_val = WAIT_SOLO_MAX_RE
.captures(body)
.and_then(|c| c.get(1))
.and_then(|m| m.as_str().parse::<u64>().ok())
.unwrap_or(0);
// Generate random value in range [min, max]
if max_val >= min_val {
Some(rand::rng().random_range(min_val..=max_val))
} else {
Some(min_val)
}
}
}
/// What Mountebank puts in `data` for a thrown value: its `message` (issue #1616). A native error
/// (a `ReferenceError`, a syntax error) carries it directly; a thrown object is read for a
/// `message` property. `None` for a value without one, such as `throw 'text'`: Mountebank's
/// `error.message` is then `undefined` and `data` is left out, so the display string is not
/// substituted.
#[cfg(feature = "javascript")]
pub(crate) fn thrown_message(
e: &boa_engine::JsError,
context: &mut boa_engine::Context,
) -> Option<String> {
if let Some(native) = e.as_native() {
return Some(native.message().to_string());
}
let object = e.as_opaque()?.as_object()?;
// Domain-optional: a `message` getter that throws, or a message that cannot be made a string,
// leaves `data` out. Nothing is hidden: the request already fails with the 500 and the log line.
let message = object
.get(boa_engine::js_string!("message"), context)
.ok()?;
if message.is_undefined() {
return None;
}
message
.to_string(context)
.ok()
.map(|text| text.to_std_string_escaped())
}
/// A computed delay as Node's `setTimeout` reads it (issue #1588): `NaN`, an infinity or a
/// negative number is no delay; anything else is floored, and a value beyond `u64` saturates to
/// `u64::MAX`, which `tokio::time::sleep` saturates to its far-future deadline (issue #1612).
fn node_timeout_ms(n: f64) -> u64 {
if !n.is_finite() || n <= 0.0 {
return 0;
}
// Finite and positive: `as` floors and saturates at `u64::MAX`, which is the intent.
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let ms = n.floor() as u64;
ms
}
/// Extract function body from JavaScript function string: the text between the first `{` and the
/// last `}`, or `None` when either is missing or the `}` comes first.
fn extract_function_body(js_func: &str) -> Option<String> {
let start = js_func.find('{')?;
let end = js_func.rfind('}')?;
js_func
.get(start + 1..end)
.map(|body| body.trim().to_string())
}
#[cfg(test)]
mod tests {
use super::*;
// AC 608-1: every documented wait spelling deserializes, and each round-trips to the JSON the
// author wrote — `GET /imposters?replayable=true` must not rewrite one spelling into another.
#[test]
fn wait_accepts_all_four_shapes_and_round_trips() {
for raw in [
r#"100"#,
r#"{"min":100,"max":200}"#,
r#""function() { return 42; }""#,
r#"{"inject":"function() { return 42; }"}"#,
] {
let wait: WaitBehavior =
serde_json::from_str(raw).unwrap_or_else(|e| panic!("{raw} must parse: {e}"));
let back = serde_json::to_string(&wait).expect("serialize");
let (a, b): (serde_json::Value, serde_json::Value) = (
serde_json::from_str(raw).expect("raw json"),
serde_json::from_str(&back).expect("round-trip json"),
);
assert_eq!(a, b, "{raw} must round-trip unchanged, got {back}");
}
}
// AC 608-1: the object shapes are disjoint, so untagged resolution is unambiguous.
#[test]
fn wait_object_shapes_resolve_to_distinct_variants() {
let inject: WaitBehavior =
serde_json::from_str(r#"{"inject":"function() { return 1; }"}"#).expect("inject");
assert!(matches!(inject, WaitBehavior::Inject { .. }));
let range: WaitBehavior = serde_json::from_str(r#"{"min":1,"max":2}"#).expect("range");
assert!(matches!(range, WaitBehavior::Range { .. }));
// A wait object that is neither shape is still rejected — the new variant must not turn
// the enum into a catch-all that silently accepts nonsense.
assert!(serde_json::from_str::<WaitBehavior>(r#"{"bogus":true}"#).is_err());
assert!(serde_json::from_str::<WaitBehavior>(r#"{"inject":42}"#).is_err());
}
// AC 608-2: the object form is a spelling of the same JS-function wait — identical execution,
// not a second implementation. Holds on both the Boa path and the regex fallback, since the
// variants share `execute_js_wait_function`.
#[test]
fn wait_inject_executes_identically_to_bare_string() {
let js = "function() { return Math.floor(Math.random() * 0) + 250; }";
let bare = WaitBehavior::Function(js.to_string());
let object = WaitBehavior::Inject {
inject: js.to_string(),
};
assert_eq!(
bare.get_duration_ms().expect("a usable wait"),
object.get_duration_ms().expect("a usable wait")
);
assert_eq!(object.get_duration_ms().expect("a usable wait"), 250);
}
// AC 608-2: the object form gives the same delay as the bare string for a large value (no cap,
// issue #1612) and fails the same way (issues #355, #1616).
#[test]
fn wait_inject_shares_value_and_fallback() {
let js = "function() { return 999999999; }";
let huge = WaitBehavior::Inject {
inject: js.to_string(),
};
assert_eq!(
huge.get_duration_ms().expect("a usable wait"),
WaitBehavior::Function(js.to_string())
.get_duration_ms()
.expect("a usable wait"),
"the object form must give the same delay as the bare string form"
);
assert_eq!(huge.get_duration_ms().expect("a usable wait"), 999_999_999);
// Issue #1616: a source that does not parse is a script error in both spellings.
let unusable = "not a function at all";
let object = WaitBehavior::Inject {
inject: unusable.to_string(),
}
.get_duration_ms();
let bare = WaitBehavior::Function(unusable.to_string()).get_duration_ms();
#[cfg(feature = "javascript")]
assert!(
object.is_err() && bare.is_err(),
"both spellings fail the same way: {object:?} / {bare:?}"
);
#[cfg(not(feature = "javascript"))]
assert_eq!(
(object, bare),
(Ok(100), Ok(100)),
"without a JavaScript engine both take the same loud 100ms fallback"
);
}
#[test]
fn test_wait_behavior_fixed() {
let wait = WaitBehavior::Fixed(100);
assert_eq!(wait.get_duration_ms().expect("a usable wait"), 100);
}
#[test]
fn test_wait_behavior_range() {
let wait = WaitBehavior::Range {
min_ms: 100,
max_ms: 200,
};
for _ in 0..10 {
let duration = wait.get_duration_ms().expect("a usable wait");
assert!((100..=200).contains(&duration));
}
}
// Issue #1148: `random_range` panics on an empty range, and this ran on the request task with no
// `catch_unwind` — so an inverted range killed the worker and dropped the connection on every
// request to that stub, permanently, while the server stayed healthy. The door refuses this
// shape now, but `WaitBehavior` is a `pub` enum with `pub` fields, so the draw must be total on
// its own. Clamp to `min` (what the two sibling draw sites already do), never swap: swapping
// would quietly honour a config the door rejects.
#[test]
fn an_inverted_range_clamps_to_min_instead_of_panicking() {
let wait = WaitBehavior::Range {
min_ms: 100,
max_ms: 10,
};
// Looped, because a single assertion does not distinguish clamping from *swapping*: a swap
// would draw from 10..=100 and land on 100 about 1 run in 91. The clamp is deterministic,
// so every iteration must be 100.
for _ in 0..200 {
assert_eq!(wait.get_duration_ms().expect("a usable wait"), 100);
}
}
#[test]
fn an_equal_bound_range_is_that_value() {
let wait = WaitBehavior::Range {
min_ms: 250,
max_ms: 250,
};
assert_eq!(wait.get_duration_ms().expect("a usable wait"), 250);
}
// Adjacent unchecked `u64` add on two `\d+` captures. Driven at the regex fallback directly:
// with the `javascript` feature on, Boa answers first and never reaches it, so going through
// `get_duration_ms` would pass against the unfixed code and prove nothing. The fallback is the
// *sole* path in a build without that feature — which, per #1156, is every released artifact.
#[test]
fn the_regex_fallback_does_not_overflow_on_a_huge_multiplier() {
let js = "function() { return Math.floor(Math.random() * 18446744073709551615) + 5; }";
// The draw is random, so the discriminating assertion is that there *is* a value at all:
// before the fix `offset + range` overflowed, which panics in debug and wraps to an empty
// range — then panics inside `random_range` — in release.
let ms = WaitBehavior::execute_js_wait_function_regex(js)
.expect("the fallback recognises the pattern");
assert!(ms >= 5, "the draw starts at the offset, got {ms}");
}
#[test]
fn test_wait_behavior_serde() {
let yaml = "100";
let wait: WaitBehavior = serde_norway::from_str(yaml).unwrap();
assert!(matches!(wait, WaitBehavior::Fixed(100)));
let yaml = "min: 100\nmax: 200";
let wait: WaitBehavior = serde_norway::from_str(yaml).unwrap();
assert!(matches!(
wait,
WaitBehavior::Range {
min_ms: 100,
max_ms: 200
}
));
}
#[test]
fn test_wait_behavior_solo_js_pattern() {
// Solo pattern with min=0, max=0 -> returns 0
let js = " function() { var min = Math.ceil(0); var max = Math.floor(0); var num = Math.floor(Math.random() * (max - min + 1)); var wait = (num + min); return wait; } ";
let wait = WaitBehavior::Function(js.to_string());
assert_eq!(wait.get_duration_ms().expect("a usable wait"), 0);
// Solo pattern with min=50, max=100 -> returns value in range
let js = "function() { var min = Math.ceil(50); var max = Math.floor(100); var num = Math.floor(Math.random() * (max - min + 1)); var wait = (num + min); return wait; }";
let wait = WaitBehavior::Function(js.to_string());
for _ in 0..10 {
let duration = wait.get_duration_ms().expect("a usable wait");
assert!(
(50..=100).contains(&duration),
"Duration {duration} not in range 50-100"
);
}
}
#[test]
fn test_wait_behavior_js_function() {
// Simple random pattern
let js = "function() { return Math.floor(Math.random() * 100) + 50; }";
let wait = WaitBehavior::Function(js.to_string());
for _ in 0..10 {
let duration = wait.get_duration_ms().expect("a usable wait");
assert!(
(50..=150).contains(&duration),
"Duration {duration} not in range 50-150"
);
}
}
// Issue #355 Item 6: the wait function body is actually EXECUTED (not regex-scraped), so a
// function that isn't one of the previously-recognized `Math.random` shapes still works.
#[test]
fn wait_function_executes_js() {
let wait = WaitBehavior::Function("function() { return 42; }".to_string());
assert_eq!(wait.get_duration_ms().expect("a usable wait"), 42);
}
// Issue #1593: a wait function has `console` and the timers, as every script does. Mountebank
// does not await a promise a wait function returns, so neither does Rift: it is no delay
// (issue #1588), and its timer never runs.
#[cfg(feature = "javascript")]
#[test]
fn a_wait_function_has_console_and_timers_but_is_not_awaited() {
let logged =
WaitBehavior::Function("() => { console.log('w-1593'); return 7; }".to_string());
assert_eq!(logged.get_duration_ms().expect("a usable wait"), 7);
let timed =
WaitBehavior::Function("() => { setTimeout(() => {}, 1); return 9; }".to_string());
assert_eq!(timed.get_duration_ms().expect("a usable wait"), 9);
let promised =
WaitBehavior::Function("() => new Promise(r => setTimeout(() => r(5), 1))".to_string());
assert_eq!(promised.get_duration_ms().expect("a usable wait"), 0);
}
// A negative return value must not become an enormous u64 delay (underflow) or a negative
// sleep; it clamps to 0.
#[test]
fn wait_function_negative_clamps_to_zero() {
let wait = WaitBehavior::Function("function() { return -5; }".to_string());
assert_eq!(wait.get_duration_ms().expect("a usable wait"), 0);
}
// Issue #1612: a function wait is honoured as written, like a numeric `wait` and like
// Mountebank (`setTimeout(resolve, milliseconds)`, no cap). It used to clamp to 60 s.
#[test]
fn wait_function_huge_value_is_honoured() {
let wait = WaitBehavior::Function("function() { return 999999999; }".to_string());
assert_eq!(wait.get_duration_ms().expect("a usable wait"), 999_999_999);
}
// Issue #1612: a result beyond u64 saturates to u64::MAX rather than panicking or wrapping;
// `tokio::time::sleep` saturates that to its far-future deadline, the same as a numeric
// `wait` of u64::MAX. Boa only: the regex fallback does not read exponent literals.
#[cfg(feature = "javascript")]
#[test]
fn wait_function_beyond_u64_saturates() {
let wait = WaitBehavior::Function("function() { return 1e300; }".to_string());
assert_eq!(wait.get_duration_ms().expect("a usable wait"), u64::MAX);
}
// Issue #481: the no-`javascript`-feature regex fallback now uses shared LazyLock statics.
// Exercise it directly (the default-feature tests above hit the Boa path instead) so every
// constant pattern is compiled and matched — this pins that the statics' `.expect` never
// fires and the patterns still recognize each shape.
#[test]
fn wait_regex_fallback_parses_all_patterns() {
// Math.floor(Math.random() * N) + M
let floor = WaitBehavior::execute_js_wait_function_regex(
"function() { return Math.floor(Math.random() * 100) + 50; }",
);
assert!(matches!(floor, Some(d) if (50..=150).contains(&d)));
// Math.random() * N (no offset)
let random = WaitBehavior::execute_js_wait_function_regex(
"function() { return Math.floor(Math.random() * 30); }",
);
assert!(matches!(random, Some(d) if d <= 30));
// Solo pattern (var min = Math.ceil(N); var max = Math.floor(M); ...)
let solo = WaitBehavior::execute_js_wait_function_regex(
"function() { var min = Math.ceil(50); var max = Math.floor(100); var num = Math.floor(Math.random() * (max - min + 1)); var wait = (num + min); return wait; }",
);
assert!(matches!(solo, Some(d) if (50..=100).contains(&d)));
// Issue #490: a negative literal clamps to 0 in the regex fallback (was: parse::<u64> ->
// None -> 100ms), matching the Boa path.
assert_eq!(
WaitBehavior::execute_js_wait_function_regex("function() { return -5; }"),
Some(0)
);
}
// Issue #1384: a body the regex fallback cannot parse (it would answer the 100ms fallback), so
// only a real Boa evaluation yields 42.
#[cfg(feature = "javascript")]
#[test]
fn a_wait_function_only_boa_can_evaluate_runs_on_boa() {
let wait = WaitBehavior::Function("function() { return 2 * 21; }".to_string());
assert_eq!(wait.get_duration_ms().expect("a usable wait"), 42);
}
// Issue #1384, revised by #1588: a non-finite result does not saturate to `u64::MAX`
// (`Infinity`). Node's `setTimeout` reads it as no delay, so Rift does too — it used to take
// the 100 ms fallback. Boa only: the regex fallback does not read these names.
#[cfg(feature = "javascript")]
#[test]
fn a_non_finite_wait_is_no_delay() {
for body in ["Infinity", "NaN"] {
let wait = WaitBehavior::Function(format!("function() {{ return {body}; }}"));
assert_eq!(
wait.get_duration_ms().expect("a usable wait"),
0,
"return {body}"
);
}
}
// Issue #1588: Mountebank's `wait` reads a string with `parseInt` first and only otherwise
// evaluates `(<source>)()`, so any callable expression is a wait function — not just one that
// starts with `function`. Measured as the computed delay, never as wall time.
#[cfg(feature = "javascript")]
#[test]
fn any_callable_wait_expression_runs_like_mountebank() {
for (source, ms) in [
("() => 1000", 1000),
("() => { return 700; }", 700),
("x => 300", 300),
("(function(){return 400})", 400),
("async function () { return 5; }", 0),
("function () { return '500'; }", 500),
] {
let wait = WaitBehavior::Function(source.to_string());
assert_eq!(
wait.get_duration_ms().expect("a usable wait"),
ms,
"wait {source:?}"
);
}
}
// Issue #1588: Node's `setTimeout` treats a non-number, `NaN`, an infinity or a negative delay
// as no delay, so these answer at once in Mountebank instead of taking the 100 ms fallback.
#[cfg(feature = "javascript")]
#[test]
fn a_non_numeric_wait_result_is_no_delay() {
for source in [
"async () => 1",
"() => 'abc'",
"() => -5",
"function() { return Infinity; }",
"function() { return -Infinity; }",
"function() { return NaN; }",
"() => undefined",
] {
let wait = WaitBehavior::Function(source.to_string());
assert_eq!(
wait.get_duration_ms().expect("a usable wait"),
0,
"wait {source:?}"
);
}
}
// Issue #1616: a wait function that throws is an error carrying the thrown message, which the
// pipeline answers with Mountebank's `500 invalid wait injection`. It used to take the 100 ms
// fallback, indistinguishable from a working wait.
#[cfg(feature = "javascript")]
#[test]
fn a_throwing_wait_function_is_a_script_error() {
for (source, data) in [
("() => { throw new Error('x'); }", Some("x")),
(
"function(){ throw new TypeError('bad type'); }",
Some("bad type"),
),
(
"function(){ return nosuch.x; }",
Some("nosuch is not defined"),
),
("function(){ throw { message: 'custom' }; }", Some("custom")),
("function(){ throw 'plain'; }", None),
("function(){ throw 42; }", None),
("function(){ throw {}; }", None),
(
"() => ({ valueOf() { throw new Error('conv'); } })",
Some("conv"),
),
] {
let err = WaitBehavior::Function(source.to_string())
.get_duration_ms()
.expect_err(source);
assert_eq!(err.data.as_deref(), data, "wait {source:?}: {err}");
}
}
// Issue #1616: a syntax error is found at serve time, as in Mountebank (the create succeeds),
// and carries the parser's message. Boa words it differently from V8, so only presence is
// pinned.
#[cfg(feature = "javascript")]
#[test]
fn a_wait_function_that_does_not_parse_is_a_script_error() {
let err = WaitBehavior::Function("function(){ return ; }}".to_string())
.get_duration_ms()
.expect_err("a syntax error");
assert!(
err.data.as_deref().is_some_and(|d| !d.is_empty()),
"a syntax error carries its message: {err:?}"
);
}
// Issue #1616: with Boa on, its error is final. The regex fallback reads this body as a
// `Math.random` draw, so a fall-through would turn the throw into a delay.
#[cfg(feature = "javascript")]
#[test]
fn a_throw_does_not_fall_through_to_the_regex_fallback() {
let source = "function() { nosuch(); return Math.floor(Math.random() * 10) + 5; }";
assert!(WaitBehavior::execute_js_wait_function_regex(source).is_some());
assert!(
WaitBehavior::Function(source.to_string())
.get_duration_ms()
.is_err()
);
}
// Issue #1588: `parseInt` runs first, so a numeric string is its number, a trailing unit is
// ignored, and none of it needs a JavaScript engine — this holds in a no-`javascript` build.
#[test]
fn a_numeric_wait_string_is_read_with_parse_int() {
for (source, ms) in [
("1000", 1000),
("800ms", 800),
(" 250 ", 250),
("0", 0),
("-5", 0),
("0x10", 16),
("1e3", 1),
] {
let wait = WaitBehavior::Function(source.to_string());
assert_eq!(
wait.get_duration_ms().expect("a usable wait"),
ms,
"wait {source:?}"
);
let inject = WaitBehavior::Inject {
inject: source.to_string(),
};
assert_eq!(
inject.get_duration_ms().expect("a usable wait"),
ms,
"inject {source:?}"
);
}
}
// Issue #1588: without Boa, the regex fallback also reads an arrow with a bare numeric body.
#[test]
fn the_regex_fallback_reads_a_bare_arrow_body() {
assert_eq!(
WaitBehavior::execute_js_wait_function_regex("() => 250"),
Some(250)
);
assert_eq!(
WaitBehavior::execute_js_wait_function_regex("x => 300;"),
Some(300)
);
assert_eq!(
WaitBehavior::execute_js_wait_function_regex("() => { return 700; }"),
Some(700)
);
}
// Issue #1384: the solo pattern needs both `var min` and `var max`; `min` alone is not it.
#[test]
fn regex_fallback_needs_both_min_and_max_for_the_solo_pattern() {
assert_eq!(
WaitBehavior::execute_js_wait_function_regex(
"function() { var min = Math.ceil(5); return 7; }"
),
None
);
}
// Issue #1384: an inverted solo pattern answers `min` instead of drawing from an empty range,
// which `random_range` panics on.
#[test]
fn an_inverted_solo_pattern_returns_min() {
assert_eq!(
WaitBehavior::parse_solo_wait_pattern(
"var min = Math.ceil(20); var max = Math.floor(10);"
),
Some(20)
);
}
// Issue #1384: the clamp of an inverted range is the documented loud fallback, so it warns.
#[tracing_test::traced_test]
#[test]
fn an_inverted_range_warns() {
let wait = WaitBehavior::Range {
min_ms: 5,
max_ms: 3,
};
assert_eq!(wait.get_duration_ms().expect("a usable wait"), 5);
assert!(logs_contain("clamping to min"));
}
// Issue #1384: an equal-bound range is a valid config, so it answers its value silently.
#[tracing_test::traced_test]
#[test]
fn an_equal_range_does_not_warn() {
let wait = WaitBehavior::Range {
min_ms: 5,
max_ms: 5,
};
assert_eq!(wait.get_duration_ms().expect("a usable wait"), 5);
assert!(!logs_contain("clamping to min"));
}
// Issue #1384: a `}` before the first `{` leaves no body to extract.
#[test]
fn a_closing_brace_before_the_opening_one_has_no_body() {
assert_eq!(extract_function_body("function() } 5 {"), None);
assert_eq!(extract_function_body("function() {}").as_deref(), Some(""));
}
}