encore-dev 2.0.0-beta.20

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
//! End-to-end system tests that run against the full application.
//!
//! While unit tests run inside a single service in isolation (service-to-service
//! calls are not served and Pub/Sub subscriptions do not run), tests in a
//! system test suite—a crate whose directory contains `encore.systest.json`—run
//! against the whole app in a dedicated test session. Services start on demand
//! just like `encore run`, using test secrets, test configs, and isolated test
//! data.
//!
//! ```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 can call any service and access any resource declared by the
//! app (either via `::named(...)` or through a service's own declaration).
//!
//! Each test gets isolated data across every Postgres database, ClickHouse
//! database, Redis database, and object bucket (with migrations applied). All
//! services handling requests for that test operate on the test's isolated
//! data, so tests can run in parallel without interfering with one another.
//!
//! System tests can also load a [`Fixture`](super::Fixture). When the fixture's
//! setup runs against the app and settles, the resulting state across all
//! databases, buckets, and Redis instances is snapshotted and copied for each
//! test that loads it.
//!
//! Background work that is not triggered by a test request (such as a worker
//! loop or polling job) runs against the session's shared data. To test such
//! background work, set `"data": "shared"` in `encore.systest.json`; tests in
//! that suite share data with background workers and with each other.
//!
//! Published Pub/Sub messages are delivered automatically to subscriptions in
//! their declaring services. Call [`settled`] to wait for delivery rather than
//! calling [`deliver`](super::deliver).
//!
//! Each test has an ID that propagates automatically across all outgoing
//! requests and messages so Encore can attribute work and route data correctly.
//! Making a service call or publishing a message from an unassociated thread
//! panics.
//!
//! To test frontends in a real browser, call [`browser`] to launch a managed
//! headless Chromium instance connected to the test session with automatic
//! recording and telemetry.
//!
//! Run system tests with `encore test`, or with `cargo test` inside 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,
            "not a system test: only tests in a system test suite (a directory with \
             `encore.systest.json`) run against the full app",
        )
    })
}

/// Waits up to 30 seconds for all asynchronous work triggered by the current
/// test to finish (no in-flight service or gateway requests, and no queued,
/// active, or retrying Pub/Sub deliveries). See [`settled_with`] to customize
/// the timeout.
///
/// Only work carrying the current test's ID is tracked, so parallel tests do
/// not wait on each other and unrelated background work is ignored. If a
/// service drops request context propagation, that downstream work loses the
/// test ID, runs against shared data, and is not awaited (inspect
/// [`telemetry`] to find lost context).
///
/// In suites configured with `"data": "shared"`, `settled` waits for all
/// in-flight work across the entire app. Detached tasks spawned by a service
/// after responding to a request are not tracked.
///
/// ```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
}

/// Like [`settled`], with custom [`SettleOptions`]. If the app does not settle
/// in time, the returned error lists what work is still in progress.
///
/// ```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:#}"))
}

/// Returns the URL of the named gateway or frontend in the current test
/// session, for use with custom clients (such as a WebSocket client).
/// Frontends start on demand on the first connection.
///
/// SDK and generated clients propagate test context automatically; for custom
/// clients, attach the headers returned by [`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(", "),
            }
        ))
    })
}

/// Returns HTTP headers that associate a custom client's request with the
/// current test (carrying the test ID in Request Context and the active trace
/// context).
///
/// ```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())
}

/// Waits for the app to settle and returns the [`Telemetry`] recorded for the
/// current test, including all service spans, inter-service requests, Pub/Sub
/// deliveries, queries, and log lines.
///
/// Inspect spans via [`Span::what`] and the helper filters on [`Telemetry`]:
///
/// ```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`] formats the same trace tree printed on test failure,
/// and [`Telemetry::shape`] strips run-specific values for snapshot testing.
pub async fn telemetry() -> Result<Telemetry, Error> {
    telemetry_with(TelemetryOptions::new()).await
}

/// Like [`telemetry`], with custom [`TelemetryOptions`] (for example, to
/// inspect telemetry immediately without waiting for the app to settle).
///
/// ```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
    }
}

/// Controls when [`browser`] recordings are saved.
#[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,
}

/// Options for launching a test browser with [`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,
}

/// Returns a managed headless Chromium [`Browser`] for the current test,
/// launching it on first call and closing it when the test ends.
///
/// The browser integrates directly with the test session:
///
/// - Pages reach gateways and frontends at their normal `encore run` addresses
///   (such as `http://localhost:4000`), automatically routed to the test
///   session.
/// - Every request from the browser carries the test's ID, so backend work
///   runs against the test's isolated data and is awaited by [`settled`].
/// - Browser actions, page requests, console errors, uncaught exceptions, and
///   failed requests appear in [`telemetry`] alongside the backend spans they
///   triggered.
/// - Page activity is recorded; on failure, an HTML replay file is saved
///   ([`Browser::recording`]).
///
/// Enable the `chromiumoxide` feature to use `testing::chromiumoxide::connect`,
/// or connect any other Chrome DevTools Protocol client to
/// [`Browser::ws_endpoint`]. Encore downloads the `browser/chromium` component
/// automatically on first use.
///
/// ```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
}

/// Like [`browser`], with custom [`BrowserOptions`]. Options only take effect
/// on the first call in a test; subsequent calls return the same browser.
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()),
            }),
        }
    }

    /// Returns the Chrome DevTools Protocol WebSocket endpoint
    /// (for example, `ws://127.0.0.1:53211/devtools/browser/…`).
    pub fn ws_endpoint(&self) -> &str {
        &self.inner.ws_endpoint
    }

    /// Returns the path where the HTML replay recording will be written when
    /// the test ends, or `None` if recording is disabled.
    pub fn recording(&self) -> Option<&Path> {
        self.inner.recording.as_deref()
    }

    /// Returns the URL for navigating to the named gateway or frontend inside
    /// the browser. Requests to this URL are routed 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 a named step in the test recording and
    /// [`telemetry`], tagged with the caller's source location.
    ///
    /// Browser actions (clicks, keystrokes, navigations) and the backend
    /// requests they trigger while `statement` runs are grouped under this
    /// step. If `statement` panics or is dropped before completing, the step is
    /// recorded as failed. Step-reporting failures never fail the test.
    ///
    /// ```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
        }
    }

    /// Like [`step`](Self::step) for fallible futures, recording any `Err`
    /// result as the step's error.
    #[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());
    }
}