encore-dev 2.0.0-beta.10

Rust SDK for Encore applications
Documentation
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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
//! System tests: tests of the whole app, which run as no service.
//!
//! A test in a service runs as that service, alone: a call to another service
//! is not answered, and what it publishes nothing handles. A test in a system
//! test suite — a crate whose directory holds an `encore.systest.json` —
//! runs against the app instead, in its test session: each service starts
//! when something first reaches it, as under `encore run`, with the secrets
//! and configs configured for tests and data that is the session's own.
//!
//! ```ignore
//! use encore::testing::system;
//!
//! static BILLING: Database = Database::named("billing");
//!
//! #[encore::test]
//! async fn placing_an_order_charges_the_card() -> Result<(), Box<dyn std::error::Error>> {
//!     let order = orders::place(&PlaceParams { sku: "tee".into(), qty: 2 }).await?;
//!     // The order's event has been handled by billing's subscription.
//!     system::settled().await?;
//!
//!     let row = BILLING
//!         .query_one("SELECT amount FROM charges WHERE order_id = $1", &[&order.id])
//!         .await?;
//!     assert_eq!(row.get::<_, i64>(0), 4000);
//!     Ok(())
//! }
//! ```
//!
//! A system test may use any resource the app declares, bound with `named`
//! or through a service's own declaration, and call any service.
//!
//! Each test has data of its own: an instance of every database, Redis
//! database and bucket, which starts as a service's test's does, the
//! databases migrated and the rest empty. What the services do for the test
//! they do on that data, whichever of them it is, so a test reads what they
//! wrote for it and nothing of another test's, and tests run side by side.
//!
//! A test can start from a [`Fixture`](super::Fixture) instead, as a
//! service's test can. Its setup calls the app, and what the services made
//! of that, in every database, bucket and Redis database, once what the
//! setup set in motion has finished, is what each test that loads the
//! fixture gets a copy of.
//!
//! What the app does for no request, as a Worker's loop or a job that finds
//! its work in a table, is done on the data the services share, which a test
//! does not see. A suite that tests such work says `"data": "shared"` in its
//! `encore.systest.json`: its tests then share that data too, and each other's.
//!
//! What a test publishes is sent, and each subscription handles it in the
//! service that declares it. [`settled`] waits for that: there is nothing to
//! [`deliver`](super::deliver).
//!
//! Each test has an id, which travels with every call and message it makes,
//! and with what those cause in turn, so that what the app did for the test
//! can be told from the rest.
//!
//! A test that drives the app's frontends asks for a [`browser`]: a headless
//! Chromium Encore runs for the test, whose pages reach the app in the test
//! session and are recorded.
//!
//! Run the tests with `encore test`, or with `cargo test` in the suite's
//! directory.

use std::collections::HashMap;
use std::fmt::Display;
use std::future::Future;
use std::panic::Location;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::Duration;

use encore_sdk_core::system_test::{NotSettled, Outcome, SystemTest};

pub use encore_sdk_core::system_test::telemetry::{
    Deliveries, Event, Kind, Link, Log, LostContext, Publishes, Queries, Requests, Span, Status,
    Telemetry, What,
};

use crate::error::{ErrCode, Error};
use crate::runtime::core;

/// The test session the process's tests run against.
fn session() -> Result<&'static std::sync::Arc<SystemTest>, Error> {
    core().system_test().ok_or_else(|| {
        Error::new(
            ErrCode::FailedPrecondition,
            "this is not a system test: only the tests of a system test suite, a directory \
             with an `encore.systest.json`, run against the app",
        )
    })
}

/// Waits until nothing the test set in motion is still running or queued:
/// no request in flight to a service or through a gateway, and no message
/// waiting, being handled or due a retry on a subscription. For at most 30
/// seconds; see [`settled_with`].
///
/// It is the current test's work that is waited for, which is told by the
/// test's id travelling with it, and nothing else: not what another test set
/// in motion, so tests running side by side do not wait for each other, and
/// not what the app does for no test. The work of a service that did not
/// pass its request's context on has lost the test's id: it is not waited
/// for, and is done on data the test does not see. The test's telemetry
/// says which call lost it.
///
/// In a suite whose tests share the session's data (`"data": "shared"`),
/// everything the app has under way is waited for instead.
///
/// What a service does that is neither — a task it spawned that goes on
/// after its request was answered — is not waited for.
///
/// ```ignore
/// orders::place(&params).await?;   // publishes `order-placed`
/// system::settled().await?;        // billing has handled it
/// ```
pub async fn settled() -> Result<(), Error> {
    settled_with(SettleOptions::new()).await
}

/// [`settled`], as `options` say. The error of an app that did not settle
/// says what was still under way.
///
/// ```ignore
/// system::settled_with(SettleOptions::new().timeout(Duration::from_secs(5))).await?;
/// ```
pub async fn settled_with(options: SettleOptions) -> Result<(), Error> {
    wait(options.timeout).await
}

/// The options of [`settled_with`].
#[derive(Debug, Clone, Default)]
pub struct SettleOptions {
    timeout: Option<Duration>,
}

impl SettleOptions {
    /// The options [`settled`] waits with.
    pub fn new() -> Self {
        Self::default()
    }

    /// Waits for at most `timeout`, rather than 30 seconds.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }
}

async fn wait(timeout: Option<Duration>) -> Result<(), Error> {
    session()?;
    let test = super::current()?;
    // The session is asked over the process's connection to the daemon,
    // which answers when it has settled: off the async workers.
    let waited = tokio::task::spawn_blocking(move || {
        test.scope
            .core_scope()?
            .settled(timeout)
            .map_err(not_settled)
    })
    .await
    .map_err(|err| Error::internal(format!("waiting for the app to settle: {err}")))?;
    waited
}

fn not_settled(err: anyhow::Error) -> Error {
    let code = match err.downcast_ref::<NotSettled>() {
        Some(_) => ErrCode::DeadlineExceeded,
        None => ErrCode::Unavailable,
    };
    Error::new(code, format!("{err:#}"))
}

/// The URL of the gateway or frontend `name` in the test session, for a
/// client of the test's own, such as a WebSocket client. A frontend starts
/// when something first connects to it.
///
/// A request made with the SDK's clients, or the generated ones, carries
/// the test already. One made with another client carries it with
/// [`headers`].
pub fn url(name: &str) -> Result<String, Error> {
    let session = session()?;
    session.url(name).map(str::to_owned).ok_or_else(|| {
        let mut known: Vec<&str> = session.gateway_urls().keys().map(String::as_str).collect();
        known.sort_unstable();
        Error::not_found(format!(
            "the app has no gateway or frontend {name:?} (its gateways: {})",
            match known.is_empty() {
                true => "none".to_string(),
                false => known.join(", "),
            }
        ))
    })
}

/// The headers that make a request part of the current test, for a client
/// of the test's own: the test's id, as the Request Context field Encore
/// carries it in, and the test's span for the request to continue.
///
/// ```ignore
/// let mut request = http::Request::get(format!("{}/health", system::url("api")?));
/// for (name, value) in system::headers()? {
///     request = request.header(name, value);
/// }
/// ```
pub fn headers() -> Result<Vec<(String, String)>, Error> {
    session()?;
    let test = super::current()?;
    Ok(test
        .scope
        .core_scope()?
        .carry()
        .map(|carried| carried.headers())
        .unwrap_or_default())
}

/// What the app recorded for the current test, once it has [`settled`]:
/// every span of what the test caused — in the services it reached, in the
/// requests between them, in the deliveries of what was published for it —
/// and the lines logged in them.
///
/// Each span says what it is of ([`Span::what`]): a request a service was
/// handed, a query, a message published or delivered. A test asserts on
/// them:
///
/// ```ignore
/// let recorded = system::telemetry().await?;
/// assert_eq!(recorded.requests().service("catalog").count(), 1);
/// assert!(recorded.deliveries().all(|d| matches!(d.what, What::Delivery { handled: true, .. })));
/// assert_eq!(recorded.errors(), Vec::<String>::new());
/// ```
///
/// [`Telemetry::render`] is the tree of it a failed test prints, and
/// [`Telemetry::shape`] the same without what differs between runs, to keep
/// as a snapshot of which services a flow touches.
pub async fn telemetry() -> Result<Telemetry, Error> {
    telemetry_with(TelemetryOptions::new()).await
}

/// [`telemetry`], as `options` say: of what has been recorded by now,
/// without waiting for the app to settle, or waiting for at most a timeout.
///
/// ```ignore
/// let now = system::telemetry_with(TelemetryOptions::new().settle(false)).await?;
/// ```
pub async fn telemetry_with(options: TelemetryOptions) -> Result<Telemetry, Error> {
    session()?;
    let test = super::current()?;
    let TelemetryOptions { settle, timeout } = options;
    tokio::task::spawn_blocking(move || {
        test.scope
            .core_scope()?
            .telemetry(settle, timeout)
            .map_err(not_settled)
    })
    .await
    .map_err(|err| Error::internal(format!("reading the test's telemetry: {err}")))?
}

/// The options of [`telemetry_with`].
#[derive(Debug, Clone)]
pub struct TelemetryOptions {
    settle: bool,
    timeout: Option<Duration>,
}

impl Default for TelemetryOptions {
    fn default() -> Self {
        TelemetryOptions {
            settle: true,
            timeout: None,
        }
    }
}

impl TelemetryOptions {
    /// The options [`telemetry`] reads with: once the app has settled,
    /// waiting for at most 30 seconds.
    pub fn new() -> Self {
        Self::default()
    }

    /// Whether to wait for the app to [settle](settled) first, which is when
    /// all of what the test caused is recorded. `false` reads what has been
    /// recorded by now. `true` by default.
    pub fn settle(mut self, settle: bool) -> Self {
        self.settle = settle;
        self
    }

    /// Waits for the app to settle for at most `timeout`, rather than 30
    /// seconds.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }
}

/// When what a test's [`browser`] recorded is kept.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Record {
    /// For a test that failed, or whose runner does not say how it ended.
    Failed,
    /// For every test.
    All,
    /// Never: nothing is recorded.
    Off,
}

/// How a test wants its browser: see [`browser_with`].
#[derive(Debug, Clone, Default)]
pub struct BrowserOptions {
    record: Option<Record>,
    args: Vec<String>,
    window: Option<(u32, u32)>,
}

impl BrowserOptions {
    pub fn new() -> Self {
        Self::default()
    }

    /// When what the browser recorded is kept. Without it, what
    /// `ENCORE_TEST_RECORD` says (`failed`, `all` or `off`), else
    /// [`Record::Failed`].
    pub fn record(mut self, record: Record) -> Self {
        self.record = Some(record);
        self
    }

    /// More command-line arguments for the browser, after Encore's own.
    pub fn args<I, A>(mut self, args: I) -> Self
    where
        I: IntoIterator<Item = A>,
        A: Into<String>,
    {
        self.args.extend(args.into_iter().map(Into::into));
        self
    }

    /// The size of the browser's window, in CSS pixels: 1280×800 without it.
    pub fn window(mut self, width: u32, height: u32) -> Self {
        self.window = Some((width, height));
        self
    }
}

/// The current test's browser: see [`browser`]. Cheap to clone, and every
/// clone is the same browser.
#[derive(Debug, Clone)]
pub struct Browser {
    inner: Arc<BrowserInner>,
}

#[derive(Debug)]
struct BrowserInner {
    ws_endpoint: String,
    urls: HashMap<String, String>,
    recording: Option<PathBuf>,
    steps: Steps,
}

/// The current test's browser: a headless Chromium Encore runs for the test,
/// for a tool of the test's own to drive. It is started the first time the
/// test asks, and ends with the test.
///
/// It is the test's in every way a call the test makes is:
///
/// - It reaches the app where `encore run` has it. A frontend says itself
///   where its API is, as `http://localhost:4000`: a page's requests there,
///   and to the frontends' own addresses, go to the test session.
/// - Each request a page makes to the app carries the test, so what the app
///   does for a click is done on the test's data, and [`settled`] waits for
///   it.
/// - What the test has the browser do, and each request a page makes, is in
///   the test's [`telemetry`], with what the app did for a request under
///   it. So is what a page says went wrong: an error on its console, an
///   exception nothing caught, a request that failed.
/// - Its pages are recorded. A test that fails is left a file that plays
///   them back beside all of that ([`Browser::recording`]).
///
/// The `chromiumoxide` feature connects chromiumoxide to it
/// (`testing::chromiumoxide::connect`). This is for any other tool that
/// speaks the DevTools Protocol.
///
/// The browser is the `browser/chromium` component, which Encore downloads
/// the first time a test asks for one.
///
/// ```ignore
/// let browser = system::browser().await?;
/// let (chromium, handler) = chromiumoxide::Browser::connect(browser.ws_endpoint()).await?;
/// let page = chromium.new_page(browser.url("web")?).await?;
/// ```
pub async fn browser() -> Result<Browser, Error> {
    browser_with(BrowserOptions::default()).await
}

/// [`browser`], as `options` say. They are the first ask's to say: a test
/// has one browser, and asking again gives the same one.
pub async fn browser_with(options: BrowserOptions) -> Result<Browser, Error> {
    use encore_sdk_core::system_test::BrowserOptions as CoreOptions;
    session()?;
    let test = super::current()?;
    let options = CoreOptions {
        record: options.record.map(|record| {
            match record {
                Record::Failed => "failed",
                Record::All => "all",
                Record::Off => "off",
            }
            .to_string()
        }),
        args: options.args,
        width: options.window.map(|(width, _)| width).unwrap_or_default(),
        height: options.window.map(|(_, height)| height).unwrap_or_default(),
    };
    // The session answers once the browser has started, which the first
    // time on a machine is once it is downloaded: off the async workers.
    let started = tokio::task::spawn_blocking(move || {
        test.scope
            .core_scope()?
            .browser(&options)
            .map_err(|err| Error::unavailable(format!("{err:#}")))
    })
    .await
    .map_err(|err| Error::internal(format!("starting the test's browser: {err}")))??;
    Ok(Browser {
        inner: Arc::new(BrowserInner {
            ws_endpoint: started.ws_endpoint,
            urls: started.urls,
            recording: Some(started.recording)
                .filter(|path| !path.is_empty())
                .map(PathBuf::from),
            steps: Steps::new(started.steps_url),
        }),
    })
}

impl Browser {
    /// A browser at `ws_endpoint` that takes its steps at `steps_url`,
    /// with `urls` for the app's: for tests of what is built on one.
    #[cfg(test)]
    pub(super) fn at(ws_endpoint: &str, steps_url: &str, urls: &[(&str, &str)]) -> Browser {
        Browser {
            inner: Arc::new(BrowserInner {
                ws_endpoint: ws_endpoint.to_string(),
                urls: urls
                    .iter()
                    .map(|(name, url)| (name.to_string(), url.to_string()))
                    .collect(),
                recording: None,
                steps: Steps::new(steps_url.to_string()),
            }),
        }
    }

    /// What a DevTools Protocol client connects to: the address of a
    /// WebSocket, as a browser gives for itself
    /// (`ws://127.0.0.1:53211/devtools/browser/…`).
    pub fn ws_endpoint(&self) -> &str {
        &self.inner.ws_endpoint
    }

    /// The file the recording is written to when the test ends, if it is
    /// kept: one HTML file that plays the pages back beside what the test
    /// and the app did. `None` when nothing is recorded.
    pub fn recording(&self) -> Option<&Path> {
        self.inner.recording.as_deref()
    }

    /// The URL a page reaches the gateway or frontend `name` at: the one
    /// `encore run` has it at, which the frontend is written against. The
    /// browser's requests there go to the test session.
    pub fn url(&self, name: &str) -> Result<String, Error> {
        self.inner.urls.get(name).cloned().ok_or_else(|| {
            let mut known: Vec<&str> = self
                .inner
                .urls
                .keys()
                .map(String::as_str)
                .filter(|known| *known != "proxy")
                .collect();
            known.sort_unstable();
            Error::not_found(format!(
                "the app has no gateway or frontend {name:?} (it has: {})",
                match known.is_empty() {
                    true => "none".to_string(),
                    false => known.join(", "),
                }
            ))
        })
    }

    /// Runs `statement` as the step `name` of the test: a statement of the
    /// test, as it reads, with where it is.
    ///
    /// Encore reads what the test's tool has the browser do — a click, a
    /// key, a navigation — off the protocol. That says what was done, not
    /// which line of the test did it. What the browser is told between a
    /// step's beginning and its end is that step's doing: in the recording
    /// and in the test's [`telemetry`], the click is under the statement,
    /// and the requests it set off under the click.
    ///
    /// `statement` is not polled until Encore knows the step has begun. A
    /// step that panics, or is dropped before it finishes, is recorded as
    /// failed. Reporting never fails the test: with no browser to tell, the
    /// statement runs as it is.
    ///
    /// ```ignore
    /// browser.step("pay", page.find_element("button#pay").await?.click()).await?;
    /// ```
    #[track_caller]
    pub fn step<F: Future>(
        &self,
        name: impl Into<String>,
        statement: F,
    ) -> impl Future<Output = F::Output> {
        let (browser, name, at) = (self.inner.clone(), name.into(), Location::caller());
        async move {
            let mut open = browser.steps.begin(&name, at).await;
            let output = statement.await;
            open.end(None).await;
            output
        }
    }

    /// [`step`](Self::step), for a statement that can fail: its error is
    /// the step's.
    #[track_caller]
    pub fn try_step<T, E: Display, F: Future<Output = Result<T, E>>>(
        &self,
        name: impl Into<String>,
        statement: F,
    ) -> impl Future<Output = Result<T, E>> {
        let (browser, name, at) = (self.inner.clone(), name.into(), Location::caller());
        async move {
            let mut open = browser.steps.begin(&name, at).await;
            let output = statement.await;
            open.end(output.as_ref().err().map(|err| err.to_string()))
                .await;
            output
        }
    }
}

/// How long saying a step began or ended may take: the browser's endpoint
/// is on this machine.
const STEP_TIMEOUT: Duration = Duration::from_secs(5);

/// How long saying that a step was left unfinished may take: said while a
/// thread unwinds or a future is dropped, which must not be held up.
const STEP_LEFT_TIMEOUT: Duration = Duration::from_millis(300);

/// Says which statement of a test is running, to the endpoint of the test's
/// browser, over HTTP: `POST <url>/stepBegin` and `POST <url>/stepEnd`.
#[derive(Debug)]
struct Steps {
    /// `http://127.0.0.1:<port>/encore/<token>`. Empty where there is
    /// nowhere to say it.
    url: String,
    /// Set once the endpoint has not answered: nothing more is said.
    gone: AtomicBool,
}

fn steps_client() -> &'static reqwest::Client {
    static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
    CLIENT.get_or_init(|| {
        reqwest::Client::builder()
            // This machine's own address: never through a proxy.
            .no_proxy()
            // Each test may run in a runtime of its own, and a connection
            // kept from one test is not the next one's to use.
            .pool_max_idle_per_host(0)
            .timeout(STEP_TIMEOUT)
            .build()
            .unwrap_or_default()
    })
}

impl Steps {
    fn new(url: String) -> Self {
        Steps {
            url,
            gone: AtomicBool::new(false),
        }
    }

    fn silent(&self) -> bool {
        self.url.is_empty() || self.gone.load(Ordering::Relaxed)
    }

    /// Sends a command, and returns its answer. `None` once the endpoint
    /// has failed to answer one: not Encore's browser, or it has closed,
    /// and the test goes on as it is.
    async fn post(&self, command: &str, params: &serde_json::Value) -> Option<serde_json::Value> {
        if self.silent() {
            return None;
        }
        let sent = steps_client()
            .post(format!("{}/{command}", self.url))
            .json(params)
            .send()
            .await
            .and_then(|response| response.error_for_status());
        let answer = match sent {
            Ok(response) => response.json().await.ok(),
            Err(_) => None,
        };
        if answer.is_none() {
            self.gone.store(true, Ordering::Relaxed);
        }
        answer
    }

    /// Says the step `name`, written at `at`, begins. Returns once the
    /// endpoint has taken it, so that what the caller has the browser do
    /// next comes after it.
    async fn begin<'a>(&'a self, name: &str, at: &Location<'_>) -> OpenStep<'a> {
        let params = serde_json::json!({"name": name, "file": at.file(), "line": at.line()});
        let id = self
            .post("stepBegin", &params)
            .await
            .and_then(|answer| answer["id"].as_str().map(str::to_string));
        OpenStep { steps: self, id }
    }
}

/// A step that has begun, and not ended. Dropped without [`end`](Self::end)
/// — its statement panicked, or was dropped unfinished — it ends as failed.
struct OpenStep<'a> {
    steps: &'a Steps,
    /// `None` where nothing took the step, and once it has ended.
    id: Option<String>,
}

impl OpenStep<'_> {
    /// Says the step ended, with `error` if it failed.
    async fn end(&mut self, error: Option<String>) {
        let Some(id) = self.id.take() else {
            return;
        };
        let params = match error {
            Some(error) => serde_json::json!({"id": id, "error": error}),
            None => serde_json::json!({"id": id}),
        };
        self.steps.post("stepEnd", &params).await;
    }
}

impl Drop for OpenStep<'_> {
    fn drop(&mut self) {
        let Some(id) = self.id.take() else {
            return;
        };
        if self.steps.silent() {
            return;
        }
        let error = match std::thread::panicking() {
            true => "the statement panicked",
            false => "the statement did not finish",
        };
        let body = serde_json::json!({"id": id, "error": error}).to_string();
        // Nothing can be awaited here, and the runtime may be on its way
        // out with the test: said on this thread, to this machine, briefly.
        let _ = post_now(&format!("{}/stepEnd", self.steps.url), &body);
    }
}

/// POSTs `body`, as JSON, to the `http://` address `url` of this machine,
/// without a runtime, and does not wait for more than the answer's start.
fn post_now(url: &str, body: &str) -> std::io::Result<()> {
    use std::io::{Read as _, Write as _};
    use std::net::{TcpStream, ToSocketAddrs as _};

    let invalid = || std::io::Error::new(std::io::ErrorKind::InvalidInput, "not an http:// URL");
    let rest = url.strip_prefix("http://").ok_or_else(invalid)?;
    let (authority, path) = match rest.find('/') {
        Some(at) => rest.split_at(at),
        None => (rest, "/"),
    };
    let addr = authority.to_socket_addrs()?.next().ok_or_else(invalid)?;
    let mut stream = TcpStream::connect_timeout(&addr, STEP_LEFT_TIMEOUT)?;
    stream.set_write_timeout(Some(STEP_LEFT_TIMEOUT))?;
    stream.set_read_timeout(Some(STEP_LEFT_TIMEOUT))?;
    write!(
        stream,
        "POST {path} HTTP/1.1\r\nHost: {authority}\r\nContent-Type: application/json\r\n\
         Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
        body.len()
    )?;
    stream.flush()?;
    // Until the endpoint has taken it: its answer says nothing more.
    let mut first = [0u8; 16];
    let _ = stream.read(&mut first);
    Ok(())
}

/// Says how a test run by `#[encore::test]` ended, and for a system test
/// that failed, what it caused in the app: on standard error, under the
/// failure the test harness prints.
pub(super) struct Reported {
    scope: Arc<super::Scope>,
    ended: std::cell::Cell<bool>,
}

impl Reported {
    pub(super) fn new(scope: Arc<super::Scope>) -> Self {
        Reported {
            scope,
            ended: std::cell::Cell::new(false),
        }
    }

    /// The test returned.
    pub(super) fn ended(&self, failed: bool) {
        self.ended.set(true);
        self.report(failed);
    }

    fn report(&self, failed: bool) {
        // A test that never reached Encore caused nothing in the app, and
        // is not what starts the runtime.
        let Some(test) = self.scope.core.get() else {
            return;
        };
        if !crate::runtime::initialized().is_some_and(|core| core.system_test().is_some()) {
            return;
        }
        test.set_outcome(match failed {
            true => Outcome::Failed,
            false => Outcome::Passed,
        });
        if !failed {
            return;
        }
        // As it is now: a failed test may have left the app at work.
        if let Ok(recorded) = test.telemetry(false, None) {
            let tree = recorded.render();
            if !tree.is_empty() {
                eprintln!("\nWhat this test caused in the app:");
                for line in tree.lines() {
                    eprintln!("  {line}");
                }
            }
        }
    }
}

impl Drop for Reported {
    fn drop(&mut self) {
        // A test that never returned panicked.
        if !self.ended.get() && std::thread::panicking() {
            self.report(true);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{Read as _, Write as _};
    use std::net::TcpListener;
    use std::sync::Mutex;

    /// What a test's statements and the endpoint they are reported to saw,
    /// in order.
    type Seen = Arc<Mutex<Vec<String>>>;

    /// An endpoint that takes steps as a browser's does: its address, and
    /// what it was sent, each as `<command> <body>`.
    fn endpoint() -> (String, Seen) {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let url = format!("http://{}/encore/token", listener.local_addr().unwrap());
        let seen = Seen::default();
        let taken = seen.clone();
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let Ok(mut stream) = stream else { return };
                let mut request = Vec::new();
                let mut buf = [0u8; 4096];
                let (head, length) = loop {
                    let Ok(n) = stream.read(&mut buf) else {
                        break (0, 0);
                    };
                    if n == 0 {
                        break (0, 0);
                    }
                    request.extend_from_slice(&buf[..n]);
                    let Some(head) = request.windows(4).position(|w| w == b"\r\n\r\n") else {
                        continue;
                    };
                    let length = String::from_utf8_lossy(&request[..head])
                        .lines()
                        .find_map(|line| {
                            let (name, value) = line.split_once(':')?;
                            name.eq_ignore_ascii_case("content-length")
                                .then(|| value.trim().parse::<usize>().ok())?
                        })
                        .unwrap_or(0);
                    break (head + 4, length);
                };
                while request.len() < head + length {
                    let Ok(n) = stream.read(&mut buf) else { break };
                    if n == 0 {
                        break;
                    }
                    request.extend_from_slice(&buf[..n]);
                }
                let text = String::from_utf8_lossy(&request).into_owned();
                let command = text
                    .split_whitespace()
                    .nth(1)
                    .and_then(|path| path.rsplit('/').next())
                    .unwrap_or_default()
                    .to_string();
                let body = text.get(head..).unwrap_or_default().to_string();
                let answer = match command.as_str() {
                    "stepBegin" => r#"{"id":"0123456789abcdef"}"#,
                    _ => "{}",
                };
                taken.lock().unwrap().push(format!("{command} {body}"));
                let _ = write!(
                    stream,
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\
                     Content-Length: {}\r\nConnection: close\r\n\r\n{answer}",
                    answer.len()
                );
            }
        });
        (url, seen)
    }

    fn browser_at(steps_url: &str) -> Browser {
        Browser::at(
            "ws://127.0.0.1:1/devtools/browser/token",
            steps_url,
            &[
                ("api", "http://127.0.0.1:4001"),
                ("proxy", "http://127.0.0.1:4000"),
            ],
        )
    }

    fn json(line: &str) -> serde_json::Value {
        let (_, body) = line.split_once(' ').unwrap();
        serde_json::from_str(body).unwrap()
    }

    #[tokio::test]
    async fn a_step_has_begun_before_its_statement_runs() {
        let (url, seen) = endpoint();
        let browser = browser_at(&url);
        let ran = seen.clone();
        let line = line!() + 2;
        let answer = browser
            .step("pay", async move {
                ran.lock().unwrap().push("ran".to_string());
                42
            })
            .await;
        assert_eq!(answer, 42);

        let seen = seen.lock().unwrap().clone();
        assert_eq!(seen.len(), 3, "{seen:?}");
        assert!(seen[0].starts_with("stepBegin "), "{seen:?}");
        assert_eq!(seen[1], "ran");
        assert!(seen[2].starts_with("stepEnd "), "{seen:?}");
        let begun = json(&seen[0]);
        assert_eq!(begun["name"], "pay");
        // Where the test said it, not where the SDK reports it from.
        assert!(begun["file"].as_str().unwrap().ends_with("system.rs"));
        assert_eq!(begun["line"], line);
        let ended = json(&seen[2]);
        assert_eq!(ended["id"], "0123456789abcdef");
        assert!(ended.get("error").is_none());
    }

    #[tokio::test]
    async fn a_statement_s_error_is_its_step_s() {
        let (url, seen) = endpoint();
        let browser = browser_at(&url);
        let failed: Result<(), String> = browser
            .try_step("pay", async { Err("no button#pay".to_string()) })
            .await;
        assert_eq!(failed.unwrap_err(), "no button#pay");
        let said = seen.lock().unwrap().clone();
        assert_eq!(json(&said[1])["error"], "no button#pay");

        let fine: Result<u8, String> = browser.try_step("wait", async { Ok(1) }).await;
        assert_eq!(fine, Ok(1));
        let said = seen.lock().unwrap().clone();
        assert!(json(&said[3]).get("error").is_none());
    }

    #[tokio::test]
    async fn a_step_left_unfinished_ends_as_failed() {
        let (url, seen) = endpoint();
        let browser = browser_at(&url);
        let waited = tokio::time::timeout(
            Duration::from_millis(200),
            browser.step("wait for thanks", std::future::pending::<()>()),
        )
        .await;
        assert!(waited.is_err());
        let seen = seen.lock().unwrap().clone();
        assert_eq!(seen.len(), 2, "{seen:?}");
        let ended = json(&seen[1]);
        assert_eq!(ended["id"], "0123456789abcdef");
        assert_eq!(ended["error"], "the statement did not finish");
    }

    #[tokio::test]
    async fn with_nowhere_to_say_it_a_statement_runs_as_it_is() {
        // No endpoint: a browser that takes no steps.
        let browser = browser_at("");
        assert_eq!(browser.step("pay", async { 1 }).await, 1);

        // One that has gone: a port nothing listens on.
        let closed = TcpListener::bind("127.0.0.1:0").unwrap();
        let url = format!("http://{}/encore/token", closed.local_addr().unwrap());
        drop(closed);
        let browser = browser_at(&url);
        assert_eq!(browser.step("pay", async { 2 }).await, 2);
        // And is not asked again.
        assert!(browser.inner.steps.silent());
        let again: Result<u8, String> = browser.try_step("pay", async { Ok(3) }).await;
        assert_eq!(again, Ok(3));
    }

    #[test]
    fn a_name_the_app_has_none_of_says_what_it_has() {
        let browser = browser_at("");
        assert_eq!(browser.url("api").unwrap(), "http://127.0.0.1:4001");
        let err = browser.url("web").unwrap_err();
        assert_eq!(err.code, ErrCode::NotFound);
        // The service proxy is no gateway or frontend to name.
        assert!(err.message.ends_with("(it has: api)"), "{}", err.message);
    }

    #[test]
    fn a_step_s_end_is_said_without_a_runtime() {
        let (url, seen) = endpoint();
        post_now(&format!("{url}/stepEnd"), r#"{"id":"ab"}"#).unwrap();
        let seen = seen.lock().unwrap().clone();
        assert_eq!(seen, vec![r#"stepEnd {"id":"ab"}"#.to_string()]);
        assert!(post_now("https://example.com/x", "{}").is_err());
    }
}