1
//! A real `web` server and a headless Chrome over chromedriver, against a
2
//! freshly registered tenant of the test database.
3

            
4
use std::collections::HashMap;
5
use std::future::Future;
6
use std::net::{TcpListener, TcpStream};
7
use std::path::{Path, PathBuf};
8
use std::pin::Pin;
9
use std::process::{Child, Command, Stdio};
10
use std::time::{Duration, Instant};
11

            
12
use anyhow::{Context, Result, anyhow, bail};
13
use axum::Json;
14
use server::command::{
15
    CmdResult, FinanceEntity, account::CreateAccount, commodity::CreateCommodity,
16
};
17
use sqlx::Connection;
18
use tempfile::TempDir;
19
use tests_integration::tenant_guard::TestTenant;
20
use uuid::Uuid;
21
use web::model::RegisterUserSchema;
22

            
23
use super::driver::Driver;
24
use super::listener::owned_by;
25

            
26
const STARTUP: Duration = Duration::from_secs(90);
27

            
28
/// How long a page or an element may take to be ready. The server bounds each
29
/// database acquire and connect at 10 s. A cold page request waits on up to
30
/// three (the directory route, the tenant connect, the tenant acquire), the
31
/// options fetch behind `data-suggest-ready` on one more, and two more cover
32
/// the browser's own navigation and a WebDriver round trip stalled by the
33
/// same contention.
34
pub(super) const READY_DEADLINE: Duration = Duration::from_secs(6 * 10);
35
const PASSWORD: &str = "e2e-password-1";
36

            
37
/// A child in the test's own process group, so whatever kills the test also
38
/// reaches it. Dropping it kills its descendants (Chrome) and then itself.
39
pub(super) struct Process(Child);
40

            
41
impl Process {
42
60
    pub(super) fn spawn(command: &mut Command) -> std::io::Result<Self> {
43
60
        command.spawn().map(Self)
44
60
    }
45

            
46
5
    pub(super) fn id(&self) -> u32 {
47
5
        self.0.id()
48
5
    }
49
}
50

            
51
/// Every descendant of `pid`, children before their parents.
52
155
pub(super) fn descendants(pid: u32) -> Vec<u32> {
53
155
    let children = Command::new("pgrep")
54
155
        .args(["-P", &pid.to_string()])
55
155
        .stderr(Stdio::null())
56
155
        .output()
57
155
        .map(|out| String::from_utf8_lossy(&out.stdout).into_owned())
58
        .unwrap_or_default();
59
155
    let children: Vec<u32> = children
60
155
        .lines()
61
36
        .filter_map(|l| l.trim().parse().ok())
62
        .collect();
63
155
    children
64
155
        .iter()
65
36
        .flat_map(|child| descendants(*child))
66
155
        .chain(children.iter().copied())
67
        .collect()
68
155
}
69

            
70
impl Drop for Process {
71
117
    fn drop(&mut self) {
72
117
        for pid in descendants(self.0.id()) {
73
18
            drop(
74
18
                Command::new("kill")
75
18
                    .args(["-KILL", &pid.to_string()])
76
18
                    .stderr(Stdio::null())
77
18
                    .status(),
78
18
            );
79
        }
80
117
        drop(self.0.kill());
81
117
        drop(self.0.wait());
82
117
    }
83
}
84

            
85
173
fn free_port() -> Result<u16> {
86
173
    Ok(TcpListener::bind("127.0.0.1:0")?.local_addr()?.port())
87
173
}
88

            
89
/// Attempts to start a listener on a fresh port before giving up.
90
const START_ATTEMPTS: usize = 3;
91

            
92
/// Spawns `start(port)` on a fresh port until it listens. A port picked by
93
/// `free_port` can be taken by a parallel test before the child binds it, so a
94
/// child that exits before listening is retried on a new port.
95
116
async fn start_listening<F>(what: &str, mut start: F) -> Result<(Process, u16)>
96
116
where
97
116
    F: FnMut(u16) -> Result<Process>,
98
116
{
99
116
    let mut last = anyhow!("{what} was never started");
100
116
    for _ in 0..START_ATTEMPTS {
101
116
        let port = free_port()?;
102
116
        let mut process = start(port)?;
103
116
        match wait_for_port(port, &mut process, what, STARTUP).await {
104
116
            Ok(()) => return Ok((process, port)),
105
            Err(err) => last = err,
106
        }
107
    }
108
    Err(last)
109
116
}
110

            
111
/// Waits until `process` itself listens on `port`. A connect alone is not
112
/// enough: a foreign listener that won the port answers it too.
113
117
pub(super) async fn wait_for_port(
114
117
    port: u16,
115
117
    process: &mut Process,
116
117
    what: &str,
117
117
    startup: Duration,
118
117
) -> Result<()> {
119
117
    let deadline = Instant::now() + startup;
120
284
    while Instant::now() < deadline {
121
283
        if let Some(status) = process.0.try_wait()? {
122
            bail!("{what} exited with {status} before listening on {port}");
123
283
        }
124
283
        if owned_by(process.0.id(), port) && TcpStream::connect(("127.0.0.1", port)).is_ok() {
125
116
            return Ok(());
126
167
        }
127
167
        tokio::time::sleep(Duration::from_millis(100)).await;
128
    }
129
1
    bail!("{what} did not listen on {port} within {startup:?}")
130
117
}
131

            
132
/// A chromedriver whose temp files (its `scoped_dir`, Chrome's singleton
133
/// directories) all land under `tmp`.
134
59
pub(super) async fn chromedriver(tmp: &Path) -> Result<(Process, String)> {
135
59
    let (process, port) = start_listening("chromedriver", |port| {
136
59
        Process::spawn(
137
59
            Command::new("chromedriver")
138
59
                .arg(format!("--port={port}"))
139
59
                .env("TMPDIR", tmp)
140
59
                .stdout(Stdio::null())
141
59
                .stderr(Stdio::null()),
142
59
        )
143
59
        .context("chromedriver must be on PATH")
144
59
    })
145
59
    .await?;
146
59
    Ok((process, format!("http://127.0.0.1:{port}")))
147
59
}
148

            
149
/// `DATABASE_URL` naming `database` instead.
150
57
fn database_url(database: &str) -> Result<String> {
151
57
    let base = std::env::var("DATABASE_URL")?;
152
57
    let (head, query) = base.split_once('?').unwrap_or((&base, ""));
153
57
    let (server, _) = head
154
57
        .rsplit_once('/')
155
        .ok_or_else(|| anyhow!("DATABASE_URL names no database"))?;
156
57
    let query = if query.is_empty() {
157
57
        String::new()
158
    } else {
159
        format!("?{query}")
160
    };
161
57
    Ok(format!("{server}/{database}{query}"))
162
57
}
163

            
164
/// The server's own directory database, so its boot migrates nothing the
165
/// other tests share.
166
struct Directory {
167
    url: String,
168
    _guard: TestTenant,
169
}
170

            
171
impl Directory {
172
57
    async fn create() -> Result<Self> {
173
57
        let name = format!("nomisync_e2e_{}", Uuid::new_v4().simple());
174
57
        let guard = TestTenant::database(name.clone());
175
57
        let mut conn = server::db::get_connection().await?;
176
57
        sqlx::query(sqlx::AssertSqlSafe(format!("CREATE DATABASE {name}")))
177
57
            .execute(&mut *conn)
178
57
            .await?;
179
57
        let url = database_url(&name)?;
180
57
        Ok(Self { url, _guard: guard })
181
57
    }
182

            
183
    /// Copies the directory row of `user` from the shared directory.
184
57
    async fn admit(&self, user: Uuid) -> Result<()> {
185
57
        let mut shared = server::db::get_connection().await?;
186
57
        let row: (String, String, String, String, String) = sqlx::query_as(
187
57
            "SELECT user_name, email, user_password, database_name, jwt_public_key \
188
57
             FROM users WHERE id = $1",
189
57
        )
190
57
        .bind(user)
191
57
        .fetch_one(&mut *shared)
192
57
        .await?;
193
57
        let mut own = sqlx::PgConnection::connect(&self.url).await?;
194
57
        sqlx::query(
195
57
            "INSERT INTO users (id, user_name, email, user_password, database_name, \
196
57
             jwt_public_key, verified) VALUES ($1, $2, $3, $4, $5, $6, TRUE)",
197
57
        )
198
57
        .bind(user)
199
57
        .bind(row.0)
200
57
        .bind(row.1)
201
57
        .bind(row.2)
202
57
        .bind(row.3)
203
57
        .bind(row.4)
204
57
        .execute(&mut own)
205
57
        .await?;
206
57
        Ok(own.close().await?)
207
57
    }
208
}
209

            
210
57
async fn web_server(directory: &Directory) -> Result<(Process, String)> {
211
57
    let manifest = Path::new(env!("CARGO_MANIFEST_DIR"));
212
57
    let redis = crate::common::redis_url();
213
57
    let (process, port) = start_listening("web", |port| {
214
57
        let child = Command::new(env!("CARGO_BIN_EXE_web"))
215
57
            .env("WEB_LISTEN", format!("127.0.0.1:{port}"))
216
57
            .env("METRICS_LISTEN", format!("127.0.0.1:{}", free_port()?))
217
57
            .env("STATIC_PATH", manifest.join("static"))
218
57
            .env("TRUSTED_PROXIES", "none")
219
57
            .env("INSECURE_COOKIES", "1")
220
57
            .env("REDIS_URL", &redis)
221
57
            .env("DATABASE_URL", &directory.url)
222
57
            .env("RUST_LOG", "warn")
223
            .spawn()
224
57
            .context("the web binary")?;
225
57
        Ok(Process(child))
226
57
    })
227
57
    .await?;
228
57
    Ok((process, format!("http://127.0.0.1:{port}")))
229
57
}
230

            
231
/// Where the screenshots go: `E2E_SHOTS`, else a temporary directory.
232
57
fn shots_dir() -> PathBuf {
233
57
    std::env::var_os("E2E_SHOTS").map_or_else(
234
57
        || std::env::temp_dir().join("nomisync-e2e-shots"),
235
57
        PathBuf::from,
236
    )
237
57
}
238

            
239
/// A registered user who can log in, and the ids of what was seeded.
240
pub struct Tenant {
241
    pub id: Uuid,
242
    pub email: String,
243
    pub password: &'static str,
244
    pub accounts: HashMap<&'static str, Uuid>,
245
    pub commodities: HashMap<&'static str, Uuid>,
246
}
247

            
248
57
async fn register() -> Result<(Uuid, String, TestTenant)> {
249
57
    let email = format!("e2e-{}@example.test", Uuid::new_v4().simple());
250
57
    let guard = TestTenant::registered(email.clone());
251
57
    let schema = RegisterUserSchema {
252
57
        name: "E2E".to_string(),
253
57
        email: email.clone(),
254
57
        password: PASSWORD.to_string(),
255
57
    };
256
57
    let registered = web::register::register_user_handler(Json(schema)).await;
257
57
    registered
258
57
        .map(drop)
259
        .map_err(|e| anyhow!("register: {e:?}"))?;
260
57
    let verified = server::command::user::verify_user_password(&email, PASSWORD)
261
57
        .await
262
        .map_err(|e| anyhow!("verify: {e:?}"))?
263
        .ok_or_else(|| anyhow!("the registered user cannot log in"))?;
264
57
    Ok((verified.user_id, email, guard))
265
57
}
266

            
267
456
async fn account(user: Uuid, name: &str, parent: Option<Uuid>) -> Result<Uuid> {
268
456
    let mut command = CreateAccount::new().name(name.to_string()).user_id(user);
269
456
    if let Some(parent) = parent {
270
114
        command = command.parent(parent);
271
342
    }
272
456
    match command.run().await.map_err(|e| anyhow!("{e:?}"))? {
273
456
        Some(CmdResult::Entity(FinanceEntity::Account(account))) => Ok(account.id),
274
        other => bail!("expected an account, got {other:?}"),
275
    }
276
456
}
277

            
278
114
async fn commodity(user: Uuid, symbol: &str) -> Result<Uuid> {
279
114
    let created = CreateCommodity::new()
280
114
        .symbol(symbol.to_string())
281
114
        .name(symbol.to_string())
282
114
        .user_id(user)
283
114
        .run()
284
114
        .await
285
        .map_err(|e| anyhow!("{e:?}"))?;
286
114
    match created {
287
114
        Some(CmdResult::String(id)) => Ok(Uuid::parse_str(&id)?),
288
        other => bail!("expected a commodity id, got {other:?}"),
289
    }
290
114
}
291

            
292
/// Two top-level accounts named `Cafe` (`Cafe` and `Cafe2` here), a child
293
/// of each top-level name, and plain accounts.
294
57
async fn seed(id: Uuid, email: String) -> Result<Tenant> {
295
57
    let mut accounts = HashMap::new();
296
57
    for name in ["Suica", "Wallet", "Bank", "Transportation", "Cafe"] {
297
285
        accounts.insert(name, account(id, name, None).await?);
298
    }
299
57
    accounts.insert("Cafe2", account(id, "Cafe", None).await?);
300
57
    accounts.insert(
301
57
        "JR",
302
57
        account(id, "JR", Some(accounts["Transportation"])).await?,
303
    );
304
57
    accounts.insert(
305
57
        "McDonalds",
306
57
        account(id, "McDonalds", Some(accounts["Cafe"])).await?,
307
    );
308
57
    let mut commodities = HashMap::new();
309
57
    for symbol in ["JPY", "EUR"] {
310
114
        commodities.insert(symbol, commodity(id, symbol).await?);
311
    }
312
57
    Ok(Tenant {
313
57
        id,
314
57
        email,
315
57
        password: PASSWORD,
316
57
        accounts,
317
57
        commodities,
318
57
    })
319
57
}
320

            
321
pub struct Harness {
322
    pub driver: Driver,
323
    pub base: String,
324
    pub tenant: Tenant,
325
    pub shots: PathBuf,
326
    _web: Process,
327
    _chromedriver: Process,
328
    // Removed after the processes that use them are killed.
329
    _directory: Directory,
330
    _tenant: TestTenant,
331
    // Declared last: removed only after chromedriver and Chrome are killed.
332
    _tmp: TempDir,
333
}
334

            
335
impl Harness {
336
57
    async fn start() -> Result<Self> {
337
57
        let (id, email, guard) = register().await?;
338
57
        let tenant = seed(id, email).await?;
339
57
        let directory = Directory::create().await?;
340
57
        let tmp = TempDir::new()?;
341
57
        let (web, base) = web_server(&directory).await?;
342
57
        directory.admit(tenant.id).await?;
343
57
        let (chromedriver, endpoint) = chromedriver(tmp.path()).await?;
344
57
        let driver = Driver::connect(&endpoint).await?;
345
57
        let shots = shots_dir();
346
57
        std::fs::create_dir_all(&shots)?;
347
57
        Ok(Self {
348
57
            driver,
349
57
            base,
350
57
            tenant,
351
57
            shots,
352
57
            _web: web,
353
57
            _chromedriver: chromedriver,
354
57
            _directory: directory,
355
57
            _tenant: guard,
356
57
            _tmp: tmp,
357
57
        })
358
57
    }
359

            
360
140
    pub fn url(&self, path: &str) -> String {
361
140
        format!("{}{path}", self.base)
362
140
    }
363

            
364
123
    pub fn account(&self, name: &str) -> Uuid {
365
123
        self.tenant.accounts.get(name).copied().unwrap_or_default()
366
123
    }
367

            
368
97
    pub fn commodity(&self, symbol: &str) -> Uuid {
369
97
        self.tenant
370
97
            .commodities
371
97
            .get(symbol)
372
97
            .copied()
373
97
            .unwrap_or_default()
374
97
    }
375
}
376

            
377
pub type Scenario<'a> = Pin<Box<dyn Future<Output = Result<()>> + 'a>>;
378

            
379
/// Runs `body` against a fresh harness; its tenant and database are removed
380
/// when the harness drops, however `body` ends.
381
57
pub async fn with_harness(body: impl for<'a> FnOnce(&'a Harness) -> Scenario<'a>) -> Result<()> {
382
57
    let harness = Harness::start().await?;
383
57
    let outcome = body(&harness).await;
384
57
    drop(harness.driver.quit().await);
385
57
    outcome
386
57
}