Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 37 additions & 6 deletions crates/tinycomputer-browser/src/fake/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@

#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

use std::sync::{Arc, Mutex};
use std::{
sync::{Arc, Mutex},
time::Duration,
};

use serde_json::{Value, json};

Expand Down Expand Up @@ -38,6 +41,8 @@ pub(crate) struct Fake {
script: Arc<Script>,
stall: Arc<Stall>,
focus: PageFocus,
close_delay: Option<Duration>,
fail_close: bool,
}

impl std::fmt::Debug for Fake {
Expand All @@ -59,6 +64,8 @@ impl Fake {
script: Arc::new(script),
stall: Arc::new(|_| false),
focus: PageFocus::OnTarget,
close_delay: None,
fail_close: false,
}
}

Expand All @@ -79,6 +86,19 @@ impl Fake {
self
}

/// Delays the engine's `close` response, as a browser that takes time to
/// flush its profile before it exits.
pub(crate) fn delaying_close(mut self, delay: Duration) -> Self {
self.close_delay = Some(delay);
self
}

/// Makes the engine fail when the caller asks it to close the browser.
pub(crate) fn failing_close(mut self) -> Self {
self.fail_close = true;
self
}

pub(crate) fn actions(&self) -> Vec<String> {
self.sent
.lock()
Expand Down Expand Up @@ -176,11 +196,22 @@ impl Engine for Fake {
if (self.stall)(&command) {
return Box::pin(std::future::pending());
}
let reply = self
.focus_reply(&command)
.or_else(|| (self.script)(&command))
.unwrap_or_else(|| default_reply(&command));
Box::pin(async move { reply })
let reply = if command["action"] == "close" && self.fail_close {
failure("browser close failed")
} else {
self.focus_reply(&command)
.or_else(|| (self.script)(&command))
.unwrap_or_else(|| default_reply(&command))
};
let delay = (command["action"] == "close")
.then_some(self.close_delay)
.flatten();
Box::pin(async move {
if let Some(delay) = delay {
tokio::time::sleep(delay).await;
}
reply
})
}
}

Expand Down
22 changes: 19 additions & 3 deletions crates/tinycomputer-browser/src/sessions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ struct Session {
dir: PathBuf,
action_context: ActionContext,
refs: Vec<ElementRef>,
closed: bool,
}

impl std::fmt::Debug for Session {
Expand All @@ -113,6 +114,11 @@ impl std::fmt::Debug for Session {

impl Session {
async fn run(&mut self, command: Value) -> Result<Value> {
if self.closed {
return Err(Error::NoSuchSession {
id: self.info.id.to_string(),
});
}
reply::data(&self.engine.execute(command).await)
}

Expand Down Expand Up @@ -334,6 +340,7 @@ impl Browser {
dir: self.scratch.join(id.as_str()),
action_context,
refs: Vec::new(),
closed: false,
};
// A browser this module launches says what to set when it cannot
// start; one attached to keeps the engine's own words.
Expand Down Expand Up @@ -387,15 +394,24 @@ impl Browser {
///
/// # Errors
///
/// Only when the session table itself is unusable.
/// When the session table cannot be read or the browser does not confirm
/// that it closed. A failed close stays in the table so a later caller
/// can retry and no profile owner can mistake the attempt for completion.
pub async fn close_session(&self, id: &SessionId) -> Result<()> {
let Some(session) = self.lock_sessions()?.remove(id) else {
let session = self.lock_sessions()?.get(id).cloned();
let Some(session) = session else {
return Ok(());
};
let mut session = session.lock().await;
if session.closed {
return Ok(());
}
// A browser that is already gone has nothing left to close.
let _closed = session.run(json!({"action": "close"})).await;
session.run(json!({"action": "close"})).await?;
let _removed = std::fs::remove_dir_all(&session.dir);
session.closed = true;
drop(session);
self.lock_sessions()?.remove(id);
Ok(())
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Tests for opening, capping, and naming sessions, and their scratch space.

use std::sync::Arc;
use std::{sync::Arc, time::Duration};

use tinycomputer_bus::browser::{NavigateRequest, SessionId, SessionOptions};

Expand Down Expand Up @@ -32,6 +32,58 @@ async fn opening_launches_explicitly_then_sets_the_viewport() {
.expect("closing twice succeeds");
}

#[tokio::test]
async fn a_second_close_waits_for_the_browser_to_finish_closing() {
let fake = Fake::new().delaying_close(Duration::from_millis(100));
let (browser, id) = open(&fake, "concurrent-close").await;
let browser = Arc::new(browser);
let first_browser = browser.clone();
let first_id = id.clone();
let first = tokio::spawn(async move { first_browser.close_session(&first_id).await });

tokio::time::timeout(Duration::from_secs(1), async {
while fake.actions().last().map(String::as_str) != Some("close") {
tokio::task::yield_now().await;
}
})
.await
.expect("first close reached the engine");

let second_browser = browser.clone();
let (closed, wait) = tokio::sync::oneshot::channel();
let second = tokio::spawn(async move {
let result = second_browser.close_session(&id).await;
let _ = closed.send(());
result
});
assert!(
tokio::time::timeout(Duration::from_millis(20), wait)
.await
.is_err(),
"a concurrent close must wait for the in-flight close"
);

first.await.unwrap().unwrap();
tokio::time::timeout(Duration::from_secs(1), second)
.await
.expect("second close follows the first")
.unwrap()
.unwrap();
assert!(browser.list_sessions().await.unwrap().is_empty());
}

#[tokio::test]
async fn a_failed_close_keeps_the_session_unconfirmed() {
let fake = Fake::new()
.delaying_close(Duration::from_millis(20))
.failing_close();
let (browser, id) = open(&fake, "failed-close").await;
let error = browser.close_session(&id).await.unwrap_err();

assert!(error.to_string().contains("browser close failed"));
assert_eq!(browser.list_sessions().await.unwrap().len(), 1);
}

#[tokio::test]
async fn a_failed_launch_opens_nothing() {
let fake = Fake::scripted(|command| {
Expand Down
Loading