1use crate::Lb;
2use crate::model::clock;
3use crate::model::core_config::Config;
4use crate::model::errors::LbResult;
5use crate::service::lb_id::LbID;
6use basic_human_duration::ChronoHumanDuration;
7use chrono::NaiveDateTime;
8use serde::{Deserialize, Serialize};
9use std::path::PathBuf;
10use time::Duration;
11
12#[cfg(not(target_family = "wasm"))]
13use std::path::Path;
14
15#[cfg(not(target_family = "wasm"))]
16use std::env;
17
18#[cfg(not(target_family = "wasm"))]
19use chrono::{DateTime, Local, TimeZone};
20
21#[cfg(not(target_family = "wasm"))]
22use tokio::fs::{self, OpenOptions};
23
24#[cfg(not(target_family = "wasm"))]
25use tokio::io::AsyncWriteExt;
26
27#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
28pub struct DebugInfo {
29 pub lb_id: LbID,
30 pub time: String,
31 pub name: String,
32 pub last_synced: String,
33 pub lb_version: String,
34 pub rust_triple: String,
35 pub os_info: String,
36 pub lb_dir: String,
37 pub server_url: String,
38 pub integrity: String,
39 pub is_syncing: bool,
40 pub status: String,
41 pub panics: Vec<String>,
42}
43
44pub trait DebugInfoDisplay {
45 fn to_string(&self) -> String;
46}
47
48impl DebugInfoDisplay for LbResult<DebugInfo> {
49 fn to_string(&self) -> String {
50 match self {
51 Ok(debug_info) => serde_json::to_string_pretty(debug_info).unwrap_or_default(),
52 Err(err) => format!("Error retrieving debug info: {:?}", err),
53 }
54 }
55}
56
57impl Lb {
58 async fn human_last_synced(&self) -> String {
59 let tx = self.ro_tx().await;
60 let db = tx.db();
61
62 let last_synced = *db.last_synced.as_ref().unwrap_or(&0);
63
64 if last_synced != 0 {
65 Duration::milliseconds(clock::get_time().0 - last_synced)
66 .format_human()
67 .to_string()
68 } else {
69 "never".to_string()
70 }
71 }
72
73 async fn lb_id(&self) -> LbResult<LbID> {
74 let mut tx = self.begin_tx().await;
75 let db = tx.db();
76
77 let lb_id = if let Some(id) = db.id.as_ref().copied() {
78 id
79 } else {
80 let new_id = LbID::generate();
81 db.id.replace(new_id)?;
82 new_id
83 };
84
85 tx.end();
86
87 Ok(lb_id)
88 }
89
90 fn now(&self) -> String {
91 let now = chrono::Local::now();
92 now.format("%Y-%m-%d %H:%M:%S %Z").to_string()
93 }
94
95 #[cfg(not(target_family = "wasm"))]
96 async fn collect_panics(&self, populate_content: bool) -> LbResult<Vec<PanicInfo>> {
97 let mut panics = vec![];
98 let mut iter = iter_panic_files(&self.config.writeable_path).await?;
99 while let Some(entry) = iter.next().await? {
100 let content = if populate_content { entry.content().await? } else { String::new() };
101 panics.push(PanicInfo { time: entry.time, file_path: entry.file_path, content });
102 }
103 panics.sort_by_key(|panic| std::cmp::Reverse(panic.time));
104
105 Ok(panics)
106 }
107
108 #[cfg(not(target_family = "wasm"))]
110 pub async fn recent_panic(&self) -> LbResult<Option<DateTime<Local>>> {
111 let panics = self.collect_panics(false).await?;
112 Ok(panics
113 .first()
114 .and_then(|panic| Local.from_local_datetime(&panic.time).single()))
115 }
116
117 #[instrument(level = "debug", skip(self), err(Debug))]
118 #[cfg(not(target_family = "wasm"))]
119 pub async fn write_panic_to_file(&self, error_header: String, bt: String) -> LbResult<String> {
120 let file_name = generate_panic_filename(&self.config.writeable_path);
121 let content = generate_panic_content(&self.config, &error_header, &bt);
122
123 let mut file = OpenOptions::new()
124 .create(true)
125 .append(true)
126 .open(&file_name)
127 .await?;
128
129 file.write_all(content.as_bytes()).await?;
130
131 Ok(file_name)
132 }
133
134 #[instrument(level = "debug", skip(self), err(Debug))]
135 #[cfg(not(target_family = "wasm"))]
136 pub async fn debug_info(&self, check_docs: bool) -> LbResult<DebugInfo> {
137 let account = self.get_account()?;
138
139 let arch = env::consts::ARCH;
140 let os = env::consts::OS;
141 let family = env::consts::FAMILY;
142
143 let (integrity, last_synced, panics, lb_id) = tokio::join!(
144 self.test_repo_integrity(check_docs),
145 self.human_last_synced(),
146 self.collect_panics(true),
147 self.lb_id()
148 );
149
150 let panics = panics?.into_iter().map(|panic| panic.content).collect();
151
152 let mut status = self.status().await;
153 status.space_used = None;
154 let status = format!("{status:?}");
155 let is_syncing = self.syncer.try_lock().is_err();
156
157 Ok(DebugInfo {
158 time: self.now(),
159 name: account.username.clone(),
160 lb_version: self.config.lb_version.clone(),
161 lb_id: lb_id?,
162 rust_triple: format!("{arch}.{family}.{os}"),
163 server_url: account.api_url.clone(),
164 integrity: format!(
165 "{} {integrity:?}",
166 if check_docs { "" } else { "doc checks skipped" }
167 ),
168 lb_dir: self.config.writeable_path.clone(),
169 last_synced,
170 os_info: self.config.os_version.clone().unwrap_or_default(),
171 status,
172 is_syncing,
173 panics,
174 })
175 }
176}
177
178#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct PanicInfo {
180 pub time: NaiveDateTime,
181 pub file_path: PathBuf,
182 pub content: String,
183}
184
185#[cfg(not(target_family = "wasm"))]
186pub struct PanicFiles {
187 entries: tokio::fs::ReadDir,
188 base_path: PathBuf,
189}
190
191#[cfg(not(target_family = "wasm"))]
192pub struct PanicFile {
193 pub time: NaiveDateTime,
194 pub file_path: PathBuf,
195}
196
197#[cfg(not(target_family = "wasm"))]
198impl PanicFiles {
199 pub async fn next(&mut self) -> LbResult<Option<PanicFile>> {
200 const PREFIX: &str = "panic---";
201 const SUFFIX: &str = ".log";
202 const TIMESTAMP_FORMAT: &str = "%Y-%m-%d---%H-%M-%S";
203
204 while let Some(entry) = self.entries.next_entry().await? {
205 let file_name = entry.file_name().into_string().unwrap_or_default();
206 if !file_name.starts_with(PREFIX) || !file_name.ends_with(SUFFIX) {
207 continue;
208 }
209 let timestamp_str = &file_name[PREFIX.len()..file_name.len() - SUFFIX.len()];
210 let Ok(time) = NaiveDateTime::parse_from_str(timestamp_str, TIMESTAMP_FORMAT) else {
211 continue;
212 };
213 let file_path = self.base_path.join(file_name);
214 return Ok(Some(PanicFile { time, file_path }));
215 }
216 Ok(None)
217 }
218}
219
220#[cfg(not(target_family = "wasm"))]
221impl PanicFile {
222 pub async fn content(&self) -> LbResult<String> {
223 Ok(fs::read_to_string(&self.file_path).await?)
224 }
225}
226
227#[cfg(not(target_family = "wasm"))]
228pub(crate) async fn iter_panic_files(path: &str) -> LbResult<PanicFiles> {
229 let base_path = Path::new(path).to_path_buf();
230 let entries = fs::read_dir(&base_path).await?;
231 Ok(PanicFiles { entries, base_path })
232}
233
234#[cfg(not(target_family = "wasm"))]
236pub(crate) async fn latest_panic_time(path: &str) -> LbResult<Option<i64>> {
237 let mut iter = iter_panic_files(path).await?;
238 let mut max: Option<i64> = None;
239 while let Some(entry) = iter.next().await? {
240 let new_ts = entry.time.and_utc().timestamp_millis();
241 match &mut max {
242 Some(ts) => {
243 if new_ts > *ts {
244 *ts = new_ts;
245 }
246 }
247 None => max = Some(new_ts),
248 }
249 }
250 Ok(max)
251}
252
253pub fn generate_panic_filename(path: &str) -> String {
254 let timestamp = chrono::Local::now().format("%Y-%m-%d---%H-%M-%S");
255 format!("{path}/panic---{timestamp}.log")
256}
257
258pub fn generate_panic_content(config: &Config, panic_info: &str, bt: &str) -> String {
259 let version = &config.lb_version;
260 let time = chrono::Local::now().format("%Y-%m-%d %H:%M:%S %Z");
261 let config = serde_json::to_string_pretty(config).unwrap_or_default();
262 format!("{version} panicked at {panic_info}\n\ntime: {time}\n\n{}\n\n{config}\n", bt.trim_end())
263}