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, reranker_id: &str) {
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() && !manager.is_installed(reranker_id) {
400 tracing::info!("downloading the reranker in the background");
401 if let Err(error) = manager.ensure(reranker_id).await {
402 tracing::warn!("reranker download failed ({error:#}); results stay dense+keyword");
403 }
404 }
405 #[cfg(not(feature = "embeddings"))]
406 let _ = (manager, reranker_id);
407}
408
409pub fn is_offline() -> bool {
411 Switches::from_process().offline
412}
413
414const SETUP_STATUS_FILE: &str = "setup-status";
415
416pub fn set_setup_status(paths: &Paths, phase: &str) {
421 let _ = std::fs::write(paths.base_dir().join(SETUP_STATUS_FILE), phase);
422}
423
424pub fn clear_setup_status(paths: &Paths) {
425 let _ = std::fs::remove_file(paths.base_dir().join(SETUP_STATUS_FILE));
426}
427
428pub fn setup_status(paths: &Paths) -> Option<String> {
430 let text = std::fs::read_to_string(paths.base_dir().join(SETUP_STATUS_FILE)).ok()?;
431 let text = text.trim();
432 (!text.is_empty()).then(|| text.to_string())
433}
434
435pub fn index_is_empty(paths: &Paths) -> bool {
438 let Ok(connection) = crate::core::index::Connection::open(&paths.db_path()) else {
439 return true;
440 };
441 if crate::core::index::init_db(&connection).is_err() {
442 return true;
443 }
444 connection
445 .query_i64("SELECT COUNT(*) FROM chunks")
446 .map(|count| count == 0)
447 .unwrap_or(true)
448}
449
450#[cfg(test)]
451mod tests {
452 use super::*;
453
454 #[test]
455 fn skips_when_disabled() {
456 let enabled = Switches::default();
457 assert!(should_run("search", &enabled));
458
459 for switches in [
460 Switches {
461 offline: true,
462 ..enabled
463 },
464 Switches {
465 no_autostart: true,
466 ..enabled
467 },
468 Switches {
469 ci: true,
470 ..enabled
471 },
472 ] {
473 assert!(!should_run("search", &switches));
474 }
475 }
476
477 #[test]
478 fn skips_portable_installs_unless_forced() {
479 let portable = Switches {
480 portable: true,
481 ..Switches::default()
482 };
483 assert!(!should_run("search", &portable));
484 assert!(should_run(
485 "search",
486 &Switches {
487 force: true,
488 ..portable
489 }
490 ));
491 }
492
493 #[test]
494 fn skips_commands_that_manage_the_daemon() {
495 for command in SKIP_COMMANDS {
496 assert!(!should_run(command, &Switches::default()), "{command}");
497 }
498 for command in ["search", "answer", "aggregate"] {
499 assert!(should_run(command, &Switches::default()), "{command}");
500 }
501 }
502
503 #[test]
506 fn serve_never_bootstraps() {
507 assert!(!should_run("serve", &Switches::default()));
508 let forced_portable = Switches {
511 portable: true,
512 force: true,
513 ..Switches::default()
514 };
515 assert!(!should_run("serve", &forced_portable));
516 }
517
518 #[test]
521 fn a_lock_file_left_by_a_dead_run_does_not_block_setup() {
522 let dir = tempfile::tempdir().expect("tempdir");
523 let path = dir.path().join(LOCK_FILE);
524 fs::write(&path, b"").expect("write");
525 assert!(
526 BootstrapLock::acquire(&path).is_some(),
527 "an unheld lock file must be acquirable"
528 );
529 }
530
531 #[test]
537 fn a_held_lock_is_exclusive_and_released_on_drop() {
538 let dir = tempfile::tempdir().expect("tempdir");
539 let path = dir.path().join(LOCK_FILE);
540 let first = BootstrapLock::acquire(&path).expect("first acquisition");
541 assert!(
542 BootstrapLock::acquire(&path).is_none(),
543 "a second holder must be refused while the first lives"
544 );
545 drop(first);
546 assert!(
547 BootstrapLock::acquire(&path).is_some(),
548 "dropping the guard must release the lock"
549 );
550 }
551
552 #[test]
556 #[ignore = "child process helper for a_lock_is_released_when_its_holder_is_killed"]
557 fn lock_child_acquires_and_waits() {
558 let Ok(path) = std::env::var("PAPER_LOCK_CHILD") else {
559 return;
560 };
561 let lock = BootstrapLock::acquire(Path::new(&path)).expect("child acquires");
562 println!("acquired");
563 std::thread::sleep(Duration::from_secs(60));
564 drop(lock);
565 }
566
567 #[cfg(unix)]
570 #[test]
571 fn a_lock_file_that_cannot_be_opened_is_refused_not_assumed_held() {
572 use std::os::unix::fs::PermissionsExt;
573
574 let dir = tempfile::tempdir().expect("tempdir");
575 let path = dir.path().join(LOCK_FILE);
576 fs::write(&path, b"").expect("write");
577 let mut perms = fs::metadata(&path).expect("metadata").permissions();
578 perms.set_mode(0o444);
579 fs::set_permissions(&path, perms).expect("chmod");
580 assert!(
581 BootstrapLock::acquire(&path).is_none(),
582 "an unopenable lock file must refuse, never claim the lock"
583 );
584 }
585
586 #[test]
590 fn a_lock_is_released_when_its_holder_is_killed() {
591 use std::io::BufRead;
592
593 let dir = tempfile::tempdir().expect("tempdir");
594 let path = dir.path().join(LOCK_FILE);
595 let mut child = std::process::Command::new(std::env::current_exe().expect("exe"))
596 .args([
597 "--exact",
598 "bootstrap::tests::lock_child_acquires_and_waits",
599 "--ignored",
600 "--nocapture",
601 ])
602 .env("PAPER_LOCK_CHILD", &path)
603 .stdout(std::process::Stdio::piped())
604 .stderr(std::process::Stdio::null())
605 .spawn()
606 .expect("spawn helper");
607
608 let mut collected = String::new();
611 let mut reader = std::io::BufReader::new(child.stdout.take().expect("stdout"));
612 let mut line = String::new();
613 loop {
614 line.clear();
615 let read = reader.read_line(&mut line).expect("read helper output");
616 if read == 0 {
617 break;
618 }
619 collected.push_str(&line);
620 if line.contains("acquired") {
621 break;
622 }
623 }
624 assert!(
625 collected.contains("acquired"),
626 "helper never acquired the lock: {collected:?}"
627 );
628 assert!(
629 BootstrapLock::acquire(&path).is_none(),
630 "a live holder must refuse a second acquirer"
631 );
632
633 child.kill().expect("kill helper");
634 let _ = child.wait();
635
636 let mut acquired = None;
639 for _ in 0..100 {
640 if let Some(lock) = BootstrapLock::acquire(&path) {
641 acquired = Some(lock);
642 break;
643 }
644 std::thread::sleep(Duration::from_millis(20));
645 }
646 assert!(
647 acquired.is_some(),
648 "the lock must be free once its holder is dead"
649 );
650 }
651
652 #[test]
655 fn serve_says_when_setup_has_never_run() {
656 let pending = State {
657 service: ServiceState::Pending,
658 updated: 0,
659 };
660 let notice = pending_setup_notice("serve", &Switches::default(), &pending)
661 .expect("a pending setup must be announced to the editor-only install");
662 assert!(
663 notice.contains("paper index"),
664 "point at the command: {notice}"
665 );
666 assert!(
667 !notice.contains("bootstrap"),
668 "`paper bootstrap` is not a subcommand — never name it: {notice}"
669 );
670 assert!(
671 notice.contains("keyword-only"),
672 "say what search does in the meantime: {notice}"
673 );
674
675 let installed = State {
677 service: ServiceState::Installed,
678 updated: 0,
679 };
680 assert!(pending_setup_notice("serve", &Switches::default(), &installed).is_none());
681 assert!(pending_setup_notice("doctor", &Switches::default(), &pending).is_none());
683 let off = Switches {
685 no_autostart: true,
686 ..Switches::default()
687 };
688 assert!(pending_setup_notice("serve", &off, &pending).is_none());
689 }
690
691 #[test]
692 fn state_round_trips() {
693 let dir = tempfile::tempdir().expect("tempdir");
694 let path = dir.path().join(STATE_FILE);
695
696 let mut state = State::load(&path);
697 assert_eq!(state.service, ServiceState::Pending);
698 assert!(state.should_retry(0));
699
700 state.service = ServiceState::Installed;
701 state.updated = 42;
702 state.save(&path).expect("save");
703
704 let loaded = State::load(&path);
705 assert_eq!(loaded.service, ServiceState::Installed);
706 assert_eq!(loaded.updated, 42);
707 assert!(!loaded.should_retry(10_000));
708 }
709
710 #[test]
711 fn failed_installs_retry_after_the_backoff() {
712 let dir = tempfile::tempdir().expect("tempdir");
713 let path = dir.path().join(STATE_FILE);
714 let state = State {
715 service: ServiceState::Unavailable,
716 updated: 1_000,
717 };
718 state.save(&path).expect("save");
719 let loaded = State::load(&path);
720 assert!(!loaded.should_retry(1_000 + RETRY_AFTER.as_secs() - 1));
721 assert!(loaded.should_retry(1_000 + RETRY_AFTER.as_secs()));
722 }
723
724 #[test]
725 fn unknown_state_file_is_ignored() {
726 let dir = tempfile::tempdir().expect("tempdir");
727 let path = dir.path().join(STATE_FILE);
728 fs::write(&path, "version=0\nservice=installed\n").expect("write");
729 assert_eq!(State::load(&path).service, ServiceState::Pending);
730 }
731
732 #[test]
733 fn setup_status_round_trips_and_missing_is_none() {
734 let dir = tempfile::tempdir().expect("tempdir");
735 let paths = Paths::with_base(dir.path());
736 assert_eq!(setup_status(&paths), None);
737 set_setup_status(&paths, "indexing");
738 assert_eq!(setup_status(&paths).as_deref(), Some("indexing"));
739 clear_setup_status(&paths);
740 assert_eq!(setup_status(&paths), None);
741 }
742
743 #[test]
744 fn empty_index_is_reported_as_empty() {
745 let dir = tempfile::tempdir().expect("tempdir");
746 let paths = Paths::with_base(dir.path());
747 paths.ensure_dirs().expect("dirs");
748 assert!(index_is_empty(&paths));
749 }
750}