1use std::fs::{self, File, TryLockError};
23use std::io;
24use std::path::Path;
25use std::time::{Duration, SystemTime, UNIX_EPOCH};
26
27use crate::core::paths::Paths;
28
29const STATE_VERSION: &str = "1";
31const RETRY_AFTER: Duration = Duration::from_secs(60 * 60);
33
34const STATE_FILE: &str = "bootstrap.state";
35const LOCK_FILE: &str = "bootstrap.lock";
36
37const SKIP_COMMANDS: &[&str] = &[
40 "bootstrap",
41 "daemon",
42 "daemon-control",
43 "doctor",
44 "uninstall",
45 "models",
46 "index",
47 "serve",
53];
54
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56enum ServiceState {
57 Pending,
59 Installed,
61 Unavailable,
63}
64
65#[derive(Debug)]
66struct State {
67 service: ServiceState,
68 updated: u64,
69}
70
71impl Default for State {
72 fn default() -> Self {
73 Self {
74 service: ServiceState::Pending,
75 updated: 0,
76 }
77 }
78}
79
80impl State {
81 fn load(path: &Path) -> Self {
82 let Ok(text) = fs::read_to_string(path) else {
83 return Self::default();
84 };
85 if !text
86 .lines()
87 .any(|line| line.trim() == format!("version={STATE_VERSION}"))
88 {
89 return Self::default();
90 }
91 let mut state = Self::default();
92 for line in text.lines() {
93 let Some((key, value)) = line.split_once('=') else {
94 continue;
95 };
96 match key.trim() {
97 "service" => {
98 state.service = match value.trim() {
99 "installed" => ServiceState::Installed,
100 "unavailable" => ServiceState::Unavailable,
101 _ => ServiceState::Pending,
102 }
103 }
104 "updated" => state.updated = value.trim().parse().unwrap_or(0),
105 _ => {}
106 }
107 }
108 state
109 }
110
111 fn save(&self, path: &Path) -> io::Result<()> {
112 let contents = format!(
113 "version={STATE_VERSION}\nservice={}\nupdated={}\n",
114 match self.service {
115 ServiceState::Pending => "pending",
116 ServiceState::Installed => "installed",
117 ServiceState::Unavailable => "unavailable",
118 },
119 self.updated
120 );
121 let tmp = path.with_extension("tmp");
122 fs::write(&tmp, contents)?;
123 fs::rename(&tmp, path)
124 }
125
126 fn should_retry(&self, now: u64) -> bool {
127 match self.service {
128 ServiceState::Installed => false,
129 ServiceState::Pending => true,
130 ServiceState::Unavailable => now.saturating_sub(self.updated) >= RETRY_AFTER.as_secs(),
131 }
132 }
133}
134
135#[derive(Clone, Copy, Debug, Default)]
138struct Switches {
139 offline: bool,
140 no_autostart: bool,
141 ci: bool,
142 portable: bool,
143 force: bool,
144}
145
146impl Switches {
147 fn from_process() -> Self {
148 Self {
149 offline: present("PAPER_OFFLINE"),
150 no_autostart: present("PAPER_NO_AUTOSTART"),
151 ci: present("CI"),
152 portable: present("PAPER_HOME"),
153 force: present("PAPER_FORCE_BOOTSTRAP"),
154 }
155 }
156}
157
158fn present(name: &str) -> bool {
159 match std::env::var(name) {
160 Ok(value) => !value.is_empty() && value != "0",
161 Err(_) => false,
162 }
163}
164
165fn should_run(command: &str, switches: &Switches) -> bool {
166 onboarding_enabled(switches) && !SKIP_COMMANDS.contains(&command)
167}
168
169fn onboarding_enabled(switches: &Switches) -> bool {
173 if switches.offline || switches.no_autostart || switches.ci {
174 return false;
175 }
176 !switches.portable || switches.force
178}
179
180fn pending_setup_notice(command: &str, switches: &Switches, state: &State) -> Option<&'static str> {
191 if command != "serve" || !onboarding_enabled(switches) {
192 return None;
193 }
194 if state.service != ServiceState::Pending {
195 return None;
196 }
197 Some(
198 "paper: setup has not run on this machine yet — background indexing is off and search \
199 is keyword-only until it does. Run `paper index` once; keyword search here picks it up \
200 on the next query (restart this server to load the embedding model for semantic \
201 search).",
202 )
203}
204
205fn now_unix() -> u64 {
206 SystemTime::now()
207 .duration_since(UNIX_EPOCH)
208 .map(|d| d.as_secs())
209 .unwrap_or(0)
210}
211
212struct BootstrapLock {
224 file: File,
225}
226
227impl BootstrapLock {
228 fn acquire(path: &Path) -> Option<Self> {
229 let file = match fs::OpenOptions::new()
230 .read(true)
231 .write(true)
232 .create(true)
233 .truncate(false)
234 .open(path)
235 {
236 Ok(file) => file,
237 Err(err) => {
238 tracing::warn!(
242 "could not open the setup lock at {} ({err:#}); background setup is skipped \
243 this run",
244 path.display()
245 );
246 return None;
247 }
248 };
249 match file.try_lock() {
250 Ok(()) => Some(Self { file }),
251 Err(TryLockError::WouldBlock) => None,
253 Err(TryLockError::Error(err)) => {
257 tracing::warn!(
258 "this filesystem cannot lock {} ({err:#}); background setup is skipped this \
259 run — `paper daemon-control install` does the same work without the race",
260 path.display()
261 );
262 None
263 }
264 }
265 }
266}
267
268impl Drop for BootstrapLock {
269 fn drop(&mut self) {
270 let _ = self.file.unlock();
273 }
274}
275
276pub async fn maybe_autostart(command: &str) {
279 let switches = Switches::from_process();
280 if !should_run(command, &switches) {
281 let state = State::load(&Paths::new().base_dir().join(STATE_FILE));
282 if let Some(notice) = pending_setup_notice(command, &switches, &state) {
283 eprintln!("{notice}");
286 }
287 return;
288 }
289
290 let paths = Paths::new();
291 if paths.ensure_dirs().is_err() {
292 return;
293 }
294
295 let state_path = paths.base_dir().join(STATE_FILE);
296 let lock_path = paths.base_dir().join(LOCK_FILE);
297
298 let state = State::load(&state_path);
299 if !state.should_retry(now_unix()) {
300 return;
301 }
302
303 let Some(_lock) = BootstrapLock::acquire(&lock_path) else {
304 return;
305 };
306
307 let state = State::load(&state_path);
309 if !state.should_retry(now_unix()) {
310 return;
311 }
312
313 eprintln!(
314 "paper: first run — setting up background indexing for your documents \
315 (disable with PAPER_NO_AUTOSTART=1)"
316 );
317
318 let next = match crate::cli::daemon::ensure_service() {
319 Ok(()) => State {
320 service: ServiceState::Installed,
321 updated: now_unix(),
322 },
323 Err(error) => {
324 tracing::warn!("could not install the Paper background service: {error:#}");
325 State {
326 service: ServiceState::Unavailable,
327 updated: now_unix(),
328 }
329 }
330 };
331 let _ = next.save(&state_path);
332}
333
334pub async fn ensure_models(workspace: &crate::cli::Workspace) {
341 let switches = Switches::from_process();
342 if switches.offline || switches.no_autostart {
343 return;
344 }
345 #[cfg(feature = "embeddings")]
346 {
347 if !workspace.embedding_model_installed() {
348 if let Ok(spec) = workspace
349 .model_manager
350 .spec(crate::core::models::MULTILINGUAL_EMBEDDING)
351 {
352 set_setup_status(
353 &workspace.paths,
354 &format!(
355 "downloading the embedding model ({} MB) — keyword and semantic search start once it lands",
356 spec.size_mb()
357 ),
358 );
359 }
360 tracing::info!(
361 "downloading the default multilingual embedding model in the background"
362 );
363 if let Err(error) = workspace
364 .model_manager
365 .ensure(crate::core::models::MULTILINGUAL_EMBEDDING)
366 .await
367 {
368 tracing::warn!(
369 "embedding model download failed ({error:#}); continuing with keyword search"
370 );
371 }
372 }
373 }
374 #[cfg(not(feature = "embeddings"))]
375 let _ = workspace;
376
377 #[cfg(feature = "ocr")]
381 if std::env::var_os("PAPER_NO_OCR").is_none() && !crate::core::extract::ocr::models_present() {
382 tracing::info!("downloading OCR models in the background");
383 if let Err(error) = crate::core::extract::ocr::ensure_models().await {
384 tracing::warn!("OCR model download failed ({error:#}); scanned pages stay unindexed");
385 }
386 }
387}
388
389pub async fn ensure_reranker(manager: &crate::core::models::ModelManager) {
394 let switches = Switches::from_process();
395 if switches.offline || switches.no_autostart {
396 return;
397 }
398 #[cfg(feature = "embeddings")]
399 if std::env::var_os("PAPER_NO_RERANKER").is_none()
400 && !manager.is_installed(crate::core::models::OPTIONAL_RERANKER)
401 {
402 tracing::info!("downloading the optional reranker in the background");
403 if let Err(error) = manager.ensure(crate::core::models::OPTIONAL_RERANKER).await {
404 tracing::warn!("reranker download failed ({error:#}); results stay dense+keyword");
405 }
406 }
407 #[cfg(not(feature = "embeddings"))]
408 let _ = manager;
409}
410
411const SETUP_STATUS_FILE: &str = "setup-status";
412
413pub fn set_setup_status(paths: &Paths, phase: &str) {
418 let _ = std::fs::write(paths.base_dir().join(SETUP_STATUS_FILE), phase);
419}
420
421pub fn clear_setup_status(paths: &Paths) {
422 let _ = std::fs::remove_file(paths.base_dir().join(SETUP_STATUS_FILE));
423}
424
425pub fn setup_status(paths: &Paths) -> Option<String> {
427 let text = std::fs::read_to_string(paths.base_dir().join(SETUP_STATUS_FILE)).ok()?;
428 let text = text.trim();
429 (!text.is_empty()).then(|| text.to_string())
430}
431
432pub fn index_is_empty(paths: &Paths) -> bool {
435 let Ok(connection) = crate::core::index::Connection::open(&paths.db_path()) else {
436 return true;
437 };
438 if crate::core::index::init_db(&connection).is_err() {
439 return true;
440 }
441 connection
442 .query_i64("SELECT COUNT(*) FROM chunks")
443 .map(|count| count == 0)
444 .unwrap_or(true)
445}
446
447#[cfg(test)]
448mod tests {
449 use super::*;
450
451 #[test]
452 fn skips_when_disabled() {
453 let enabled = Switches::default();
454 assert!(should_run("search", &enabled));
455
456 for switches in [
457 Switches {
458 offline: true,
459 ..enabled
460 },
461 Switches {
462 no_autostart: true,
463 ..enabled
464 },
465 Switches {
466 ci: true,
467 ..enabled
468 },
469 ] {
470 assert!(!should_run("search", &switches));
471 }
472 }
473
474 #[test]
475 fn skips_portable_installs_unless_forced() {
476 let portable = Switches {
477 portable: true,
478 ..Switches::default()
479 };
480 assert!(!should_run("search", &portable));
481 assert!(should_run(
482 "search",
483 &Switches {
484 force: true,
485 ..portable
486 }
487 ));
488 }
489
490 #[test]
491 fn skips_commands_that_manage_the_daemon() {
492 for command in SKIP_COMMANDS {
493 assert!(!should_run(command, &Switches::default()), "{command}");
494 }
495 for command in ["search", "answer", "aggregate"] {
496 assert!(should_run(command, &Switches::default()), "{command}");
497 }
498 }
499
500 #[test]
503 fn serve_never_bootstraps() {
504 assert!(!should_run("serve", &Switches::default()));
505 let forced_portable = Switches {
508 portable: true,
509 force: true,
510 ..Switches::default()
511 };
512 assert!(!should_run("serve", &forced_portable));
513 }
514
515 #[test]
518 fn a_lock_file_left_by_a_dead_run_does_not_block_setup() {
519 let dir = tempfile::tempdir().expect("tempdir");
520 let path = dir.path().join(LOCK_FILE);
521 fs::write(&path, b"").expect("write");
522 assert!(
523 BootstrapLock::acquire(&path).is_some(),
524 "an unheld lock file must be acquirable"
525 );
526 }
527
528 #[test]
534 fn a_held_lock_is_exclusive_and_released_on_drop() {
535 let dir = tempfile::tempdir().expect("tempdir");
536 let path = dir.path().join(LOCK_FILE);
537 let first = BootstrapLock::acquire(&path).expect("first acquisition");
538 assert!(
539 BootstrapLock::acquire(&path).is_none(),
540 "a second holder must be refused while the first lives"
541 );
542 drop(first);
543 assert!(
544 BootstrapLock::acquire(&path).is_some(),
545 "dropping the guard must release the lock"
546 );
547 }
548
549 #[test]
553 #[ignore = "child process helper for a_lock_is_released_when_its_holder_is_killed"]
554 fn lock_child_acquires_and_waits() {
555 let Ok(path) = std::env::var("PAPER_LOCK_CHILD") else {
556 return;
557 };
558 let lock = BootstrapLock::acquire(Path::new(&path)).expect("child acquires");
559 println!("acquired");
560 std::thread::sleep(Duration::from_secs(60));
561 drop(lock);
562 }
563
564 #[cfg(unix)]
567 #[test]
568 fn a_lock_file_that_cannot_be_opened_is_refused_not_assumed_held() {
569 use std::os::unix::fs::PermissionsExt;
570
571 let dir = tempfile::tempdir().expect("tempdir");
572 let path = dir.path().join(LOCK_FILE);
573 fs::write(&path, b"").expect("write");
574 let mut perms = fs::metadata(&path).expect("metadata").permissions();
575 perms.set_mode(0o444);
576 fs::set_permissions(&path, perms).expect("chmod");
577 assert!(
578 BootstrapLock::acquire(&path).is_none(),
579 "an unopenable lock file must refuse, never claim the lock"
580 );
581 }
582
583 #[test]
587 fn a_lock_is_released_when_its_holder_is_killed() {
588 use std::io::BufRead;
589
590 let dir = tempfile::tempdir().expect("tempdir");
591 let path = dir.path().join(LOCK_FILE);
592 let mut child = std::process::Command::new(std::env::current_exe().expect("exe"))
593 .args([
594 "--exact",
595 "bootstrap::tests::lock_child_acquires_and_waits",
596 "--ignored",
597 "--nocapture",
598 ])
599 .env("PAPER_LOCK_CHILD", &path)
600 .stdout(std::process::Stdio::piped())
601 .stderr(std::process::Stdio::null())
602 .spawn()
603 .expect("spawn helper");
604
605 let mut collected = String::new();
608 let mut reader = std::io::BufReader::new(child.stdout.take().expect("stdout"));
609 let mut line = String::new();
610 loop {
611 line.clear();
612 let read = reader.read_line(&mut line).expect("read helper output");
613 if read == 0 {
614 break;
615 }
616 collected.push_str(&line);
617 if line.contains("acquired") {
618 break;
619 }
620 }
621 assert!(
622 collected.contains("acquired"),
623 "helper never acquired the lock: {collected:?}"
624 );
625 assert!(
626 BootstrapLock::acquire(&path).is_none(),
627 "a live holder must refuse a second acquirer"
628 );
629
630 child.kill().expect("kill helper");
631 let _ = child.wait();
632
633 let mut acquired = None;
636 for _ in 0..100 {
637 if let Some(lock) = BootstrapLock::acquire(&path) {
638 acquired = Some(lock);
639 break;
640 }
641 std::thread::sleep(Duration::from_millis(20));
642 }
643 assert!(
644 acquired.is_some(),
645 "the lock must be free once its holder is dead"
646 );
647 }
648
649 #[test]
652 fn serve_says_when_setup_has_never_run() {
653 let pending = State {
654 service: ServiceState::Pending,
655 updated: 0,
656 };
657 let notice = pending_setup_notice("serve", &Switches::default(), &pending)
658 .expect("a pending setup must be announced to the editor-only install");
659 assert!(
660 notice.contains("paper index"),
661 "point at the command: {notice}"
662 );
663 assert!(
664 !notice.contains("bootstrap"),
665 "`paper bootstrap` is not a subcommand — never name it: {notice}"
666 );
667 assert!(
668 notice.contains("keyword-only"),
669 "say what search does in the meantime: {notice}"
670 );
671
672 let installed = State {
674 service: ServiceState::Installed,
675 updated: 0,
676 };
677 assert!(pending_setup_notice("serve", &Switches::default(), &installed).is_none());
678 assert!(pending_setup_notice("doctor", &Switches::default(), &pending).is_none());
680 let off = Switches {
682 no_autostart: true,
683 ..Switches::default()
684 };
685 assert!(pending_setup_notice("serve", &off, &pending).is_none());
686 }
687
688 #[test]
689 fn state_round_trips() {
690 let dir = tempfile::tempdir().expect("tempdir");
691 let path = dir.path().join(STATE_FILE);
692
693 let mut state = State::load(&path);
694 assert_eq!(state.service, ServiceState::Pending);
695 assert!(state.should_retry(0));
696
697 state.service = ServiceState::Installed;
698 state.updated = 42;
699 state.save(&path).expect("save");
700
701 let loaded = State::load(&path);
702 assert_eq!(loaded.service, ServiceState::Installed);
703 assert_eq!(loaded.updated, 42);
704 assert!(!loaded.should_retry(10_000));
705 }
706
707 #[test]
708 fn failed_installs_retry_after_the_backoff() {
709 let dir = tempfile::tempdir().expect("tempdir");
710 let path = dir.path().join(STATE_FILE);
711 let state = State {
712 service: ServiceState::Unavailable,
713 updated: 1_000,
714 };
715 state.save(&path).expect("save");
716 let loaded = State::load(&path);
717 assert!(!loaded.should_retry(1_000 + RETRY_AFTER.as_secs() - 1));
718 assert!(loaded.should_retry(1_000 + RETRY_AFTER.as_secs()));
719 }
720
721 #[test]
722 fn unknown_state_file_is_ignored() {
723 let dir = tempfile::tempdir().expect("tempdir");
724 let path = dir.path().join(STATE_FILE);
725 fs::write(&path, "version=0\nservice=installed\n").expect("write");
726 assert_eq!(State::load(&path).service, ServiceState::Pending);
727 }
728
729 #[test]
730 fn setup_status_round_trips_and_missing_is_none() {
731 let dir = tempfile::tempdir().expect("tempdir");
732 let paths = Paths::with_base(dir.path());
733 assert_eq!(setup_status(&paths), None);
734 set_setup_status(&paths, "indexing");
735 assert_eq!(setup_status(&paths).as_deref(), Some("indexing"));
736 clear_setup_status(&paths);
737 assert_eq!(setup_status(&paths), None);
738 }
739
740 #[test]
741 fn empty_index_is_reported_as_empty() {
742 let dir = tempfile::tempdir().expect("tempdir");
743 let paths = Paths::with_base(dir.path());
744 paths.ensure_dirs().expect("dirs");
745 assert!(index_is_empty(&paths));
746 }
747}