use std::fs::{self, File, TryLockError};
use std::io;
use std::path::Path;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::core::paths::Paths;
const STATE_VERSION: &str = "1";
const RETRY_AFTER: Duration = Duration::from_secs(60 * 60);
const STATE_FILE: &str = "bootstrap.state";
const LOCK_FILE: &str = "bootstrap.lock";
const SKIP_COMMANDS: &[&str] = &[
"bootstrap",
"daemon",
"daemon-control",
"doctor",
"models",
"index",
"serve",
];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ServiceState {
Pending,
Installed,
Unavailable,
}
#[derive(Debug)]
struct State {
service: ServiceState,
updated: u64,
}
impl Default for State {
fn default() -> Self {
Self {
service: ServiceState::Pending,
updated: 0,
}
}
}
impl State {
fn load(path: &Path) -> Self {
let Ok(text) = fs::read_to_string(path) else {
return Self::default();
};
if !text
.lines()
.any(|line| line.trim() == format!("version={STATE_VERSION}"))
{
return Self::default();
}
let mut state = Self::default();
for line in text.lines() {
let Some((key, value)) = line.split_once('=') else {
continue;
};
match key.trim() {
"service" => {
state.service = match value.trim() {
"installed" => ServiceState::Installed,
"unavailable" => ServiceState::Unavailable,
_ => ServiceState::Pending,
}
}
"updated" => state.updated = value.trim().parse().unwrap_or(0),
_ => {}
}
}
state
}
fn save(&self, path: &Path) -> io::Result<()> {
let contents = format!(
"version={STATE_VERSION}\nservice={}\nupdated={}\n",
match self.service {
ServiceState::Pending => "pending",
ServiceState::Installed => "installed",
ServiceState::Unavailable => "unavailable",
},
self.updated
);
let tmp = path.with_extension("tmp");
fs::write(&tmp, contents)?;
fs::rename(&tmp, path)
}
fn should_retry(&self, now: u64) -> bool {
match self.service {
ServiceState::Installed => false,
ServiceState::Pending => true,
ServiceState::Unavailable => now.saturating_sub(self.updated) >= RETRY_AFTER.as_secs(),
}
}
}
#[derive(Clone, Copy, Debug, Default)]
struct Switches {
offline: bool,
no_autostart: bool,
ci: bool,
portable: bool,
force: bool,
}
impl Switches {
fn from_process() -> Self {
Self {
offline: present("PAPER_OFFLINE"),
no_autostart: present("PAPER_NO_AUTOSTART"),
ci: present("CI"),
portable: present("PAPER_HOME"),
force: present("PAPER_FORCE_BOOTSTRAP"),
}
}
}
fn present(name: &str) -> bool {
match std::env::var(name) {
Ok(value) => !value.is_empty() && value != "0",
Err(_) => false,
}
}
fn should_run(command: &str, switches: &Switches) -> bool {
onboarding_enabled(switches) && !SKIP_COMMANDS.contains(&command)
}
fn onboarding_enabled(switches: &Switches) -> bool {
if switches.offline || switches.no_autostart || switches.ci {
return false;
}
!switches.portable || switches.force
}
fn pending_setup_notice(command: &str, switches: &Switches, state: &State) -> Option<&'static str> {
if command != "serve" || !onboarding_enabled(switches) {
return None;
}
if state.service != ServiceState::Pending {
return None;
}
Some(
"paper: setup has not run on this machine yet — background indexing is off and search \
is keyword-only until it does. Run `paper index` once; keyword search here picks it up \
on the next query (restart this server to load the embedding model for semantic \
search).",
)
}
fn now_unix() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
struct BootstrapLock {
file: File,
}
impl BootstrapLock {
fn acquire(path: &Path) -> Option<Self> {
let file = match fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(path)
{
Ok(file) => file,
Err(err) => {
tracing::warn!(
"could not open the setup lock at {} ({err:#}); background setup is skipped \
this run",
path.display()
);
return None;
}
};
match file.try_lock() {
Ok(()) => Some(Self { file }),
Err(TryLockError::WouldBlock) => None,
Err(TryLockError::Error(err)) => {
tracing::warn!(
"this filesystem cannot lock {} ({err:#}); background setup is skipped this \
run — `paper daemon-control install` does the same work without the race",
path.display()
);
None
}
}
}
}
impl Drop for BootstrapLock {
fn drop(&mut self) {
let _ = self.file.unlock();
}
}
pub async fn maybe_autostart(command: &str) {
let switches = Switches::from_process();
if !should_run(command, &switches) {
let state = State::load(&Paths::new().base_dir().join(STATE_FILE));
if let Some(notice) = pending_setup_notice(command, &switches, &state) {
eprintln!("{notice}");
}
return;
}
let paths = Paths::new();
if paths.ensure_dirs().is_err() {
return;
}
let state_path = paths.base_dir().join(STATE_FILE);
let lock_path = paths.base_dir().join(LOCK_FILE);
let state = State::load(&state_path);
if !state.should_retry(now_unix()) {
return;
}
let Some(_lock) = BootstrapLock::acquire(&lock_path) else {
return;
};
let state = State::load(&state_path);
if !state.should_retry(now_unix()) {
return;
}
eprintln!(
"paper: first run — setting up background indexing for your documents \
(disable with PAPER_NO_AUTOSTART=1)"
);
let next = match crate::cli::daemon::ensure_service() {
Ok(()) => State {
service: ServiceState::Installed,
updated: now_unix(),
},
Err(error) => {
tracing::warn!("could not install the Paper background service: {error:#}");
State {
service: ServiceState::Unavailable,
updated: now_unix(),
}
}
};
let _ = next.save(&state_path);
}
pub async fn ensure_models(workspace: &crate::cli::Workspace) {
let switches = Switches::from_process();
if switches.offline || switches.no_autostart {
return;
}
#[cfg(feature = "embeddings")]
{
if !workspace.embedding_model_installed() {
tracing::info!("downloading the default embedding model in the background");
if let Err(error) = workspace
.model_manager
.ensure(crate::core::models::DEFAULT_EMBEDDING)
.await
{
tracing::warn!(
"embedding model download failed ({error:#}); continuing with keyword search"
);
}
}
if std::env::var_os("PAPER_NO_RERANKER").is_none()
&& !workspace
.model_manager
.is_installed(crate::core::models::OPTIONAL_RERANKER)
{
tracing::info!("downloading the optional reranker in the background");
if let Err(error) = workspace
.model_manager
.ensure(crate::core::models::OPTIONAL_RERANKER)
.await
{
tracing::warn!("reranker download failed ({error:#}); results stay dense+keyword");
}
}
}
#[cfg(not(feature = "embeddings"))]
let _ = workspace;
#[cfg(feature = "ocr")]
if std::env::var_os("PAPER_NO_OCR").is_none() && !crate::core::extract::ocr::models_present() {
tracing::info!("downloading OCR models in the background");
if let Err(error) = crate::core::extract::ocr::ensure_models().await {
tracing::warn!("OCR model download failed ({error:#}); scanned pages stay unindexed");
}
}
}
pub fn index_is_empty(paths: &Paths) -> bool {
let Ok(connection) = crate::core::index::Connection::open(&paths.db_path()) else {
return true;
};
if crate::core::index::init_db(&connection).is_err() {
return true;
}
connection
.query_i64("SELECT COUNT(*) FROM chunks")
.map(|count| count == 0)
.unwrap_or(true)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn skips_when_disabled() {
let enabled = Switches::default();
assert!(should_run("search", &enabled));
for switches in [
Switches {
offline: true,
..enabled
},
Switches {
no_autostart: true,
..enabled
},
Switches {
ci: true,
..enabled
},
] {
assert!(!should_run("search", &switches));
}
}
#[test]
fn skips_portable_installs_unless_forced() {
let portable = Switches {
portable: true,
..Switches::default()
};
assert!(!should_run("search", &portable));
assert!(should_run(
"search",
&Switches {
force: true,
..portable
}
));
}
#[test]
fn skips_commands_that_manage_the_daemon() {
for command in SKIP_COMMANDS {
assert!(!should_run(command, &Switches::default()), "{command}");
}
for command in ["search", "answer", "aggregate"] {
assert!(should_run(command, &Switches::default()), "{command}");
}
}
#[test]
fn serve_never_bootstraps() {
assert!(!should_run("serve", &Switches::default()));
let forced_portable = Switches {
portable: true,
force: true,
..Switches::default()
};
assert!(!should_run("serve", &forced_portable));
}
#[test]
fn a_lock_file_left_by_a_dead_run_does_not_block_setup() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join(LOCK_FILE);
fs::write(&path, b"").expect("write");
assert!(
BootstrapLock::acquire(&path).is_some(),
"an unheld lock file must be acquirable"
);
}
#[test]
fn a_held_lock_is_exclusive_and_released_on_drop() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join(LOCK_FILE);
let first = BootstrapLock::acquire(&path).expect("first acquisition");
assert!(
BootstrapLock::acquire(&path).is_none(),
"a second holder must be refused while the first lives"
);
drop(first);
assert!(
BootstrapLock::acquire(&path).is_some(),
"dropping the guard must release the lock"
);
}
#[test]
#[ignore = "child process helper for a_lock_is_released_when_its_holder_is_killed"]
fn lock_child_acquires_and_waits() {
let Ok(path) = std::env::var("PAPER_LOCK_CHILD") else {
return;
};
let lock = BootstrapLock::acquire(Path::new(&path)).expect("child acquires");
println!("acquired");
std::thread::sleep(Duration::from_secs(60));
drop(lock);
}
#[cfg(unix)]
#[test]
fn a_lock_file_that_cannot_be_opened_is_refused_not_assumed_held() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join(LOCK_FILE);
fs::write(&path, b"").expect("write");
let mut perms = fs::metadata(&path).expect("metadata").permissions();
perms.set_mode(0o444);
fs::set_permissions(&path, perms).expect("chmod");
assert!(
BootstrapLock::acquire(&path).is_none(),
"an unopenable lock file must refuse, never claim the lock"
);
}
#[test]
fn a_lock_is_released_when_its_holder_is_killed() {
use std::io::BufRead;
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join(LOCK_FILE);
let mut child = std::process::Command::new(std::env::current_exe().expect("exe"))
.args([
"--exact",
"bootstrap::tests::lock_child_acquires_and_waits",
"--ignored",
"--nocapture",
])
.env("PAPER_LOCK_CHILD", &path)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.spawn()
.expect("spawn helper");
let mut collected = String::new();
let mut reader = std::io::BufReader::new(child.stdout.take().expect("stdout"));
let mut line = String::new();
loop {
line.clear();
let read = reader.read_line(&mut line).expect("read helper output");
if read == 0 {
break;
}
collected.push_str(&line);
if line.contains("acquired") {
break;
}
}
assert!(
collected.contains("acquired"),
"helper never acquired the lock: {collected:?}"
);
assert!(
BootstrapLock::acquire(&path).is_none(),
"a live holder must refuse a second acquirer"
);
child.kill().expect("kill helper");
let _ = child.wait();
let mut acquired = None;
for _ in 0..100 {
if let Some(lock) = BootstrapLock::acquire(&path) {
acquired = Some(lock);
break;
}
std::thread::sleep(Duration::from_millis(20));
}
assert!(
acquired.is_some(),
"the lock must be free once its holder is dead"
);
}
#[test]
fn serve_says_when_setup_has_never_run() {
let pending = State {
service: ServiceState::Pending,
updated: 0,
};
let notice = pending_setup_notice("serve", &Switches::default(), &pending)
.expect("a pending setup must be announced to the editor-only install");
assert!(
notice.contains("paper index"),
"point at the command: {notice}"
);
assert!(
!notice.contains("bootstrap"),
"`paper bootstrap` is not a subcommand — never name it: {notice}"
);
assert!(
notice.contains("keyword-only"),
"say what search does in the meantime: {notice}"
);
let installed = State {
service: ServiceState::Installed,
updated: 0,
};
assert!(pending_setup_notice("serve", &Switches::default(), &installed).is_none());
assert!(pending_setup_notice("doctor", &Switches::default(), &pending).is_none());
let off = Switches {
no_autostart: true,
..Switches::default()
};
assert!(pending_setup_notice("serve", &off, &pending).is_none());
}
#[test]
fn state_round_trips() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join(STATE_FILE);
let mut state = State::load(&path);
assert_eq!(state.service, ServiceState::Pending);
assert!(state.should_retry(0));
state.service = ServiceState::Installed;
state.updated = 42;
state.save(&path).expect("save");
let loaded = State::load(&path);
assert_eq!(loaded.service, ServiceState::Installed);
assert_eq!(loaded.updated, 42);
assert!(!loaded.should_retry(10_000));
}
#[test]
fn failed_installs_retry_after_the_backoff() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join(STATE_FILE);
let state = State {
service: ServiceState::Unavailable,
updated: 1_000,
};
state.save(&path).expect("save");
let loaded = State::load(&path);
assert!(!loaded.should_retry(1_000 + RETRY_AFTER.as_secs() - 1));
assert!(loaded.should_retry(1_000 + RETRY_AFTER.as_secs()));
}
#[test]
fn unknown_state_file_is_ignored() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join(STATE_FILE);
fs::write(&path, "version=0\nservice=installed\n").expect("write");
assert_eq!(State::load(&path).service, ServiceState::Pending);
}
#[test]
fn empty_index_is_reported_as_empty() {
let dir = tempfile::tempdir().expect("tempdir");
let paths = Paths::with_base(dir.path());
paths.ensure_dirs().expect("dirs");
assert!(index_is_empty(&paths));
}
}