1use crate::runtime_mode::{appimage_channel_file, read_channel_file};
27use serde::{Deserialize, Serialize};
28use std::fs::{File, OpenOptions, TryLockError};
29use std::path::{Path, PathBuf};
30use std::time::{Duration, Instant};
31
32pub const RECORD_FILE: &str = "appimage-channels.json";
34
35const MAX_RECORDS: usize = 16;
37
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct FileId {
41 pub size: u64,
42 pub mtime_ns: u128,
44 pub dev: u64,
46 pub ino: u64,
47}
48
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50struct Record {
51 path: String,
52 channel: String,
53 id: FileId,
54}
55
56pub fn file_id(path: &Path) -> Option<FileId> {
58 let meta = std::fs::metadata(path).ok().filter(|m| m.is_file())?;
59 let mtime_ns = meta.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?.as_nanos();
60 #[cfg(unix)]
61 let (dev, ino) = {
62 use std::os::unix::fs::MetadataExt;
63 (meta.dev(), meta.ino())
64 };
65 #[cfg(not(unix))]
66 let (dev, ino) = (0, 0);
67 Some(FileId { size: meta.len(), mtime_ns, dev, ino })
68}
69
70fn plain_channel(s: &str) -> bool {
72 !s.is_empty() && s.len() <= 64 && s.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
73}
74
75fn is_this_file(record: &Record, path: &str, now: &FileId) -> bool {
79 let old = &record.id;
80 if old.size != now.size || old.mtime_ns != now.mtime_ns {
81 return false;
82 }
83 let has_object = old.dev != 0 || old.ino != 0;
84 record.path == path || (has_object && old.dev == now.dev && old.ino == now.ino) || !Path::new(&record.path).is_file()
85}
86
87const VERSION: u32 = 1;
90
91#[derive(Serialize, Deserialize)]
92struct Stored {
93 version: u32,
94 records: Vec<Record>,
95}
96
97fn load(record: &Path) -> (Vec<Record>, bool) {
99 let Ok(text) = std::fs::read_to_string(record) else { return (Vec::new(), true) };
100 let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else { return (Vec::new(), true) };
102 match value.get("version").and_then(serde_json::Value::as_u64) {
103 Some(v) if v > u64::from(VERSION) => (Vec::new(), false),
104 Some(_) => match serde_json::from_value::<Stored>(value) {
105 Ok(stored) => (stored.records, true),
106 Err(_) => (Vec::new(), true),
107 },
108 None => (Vec::new(), true),
110 }
111}
112
113fn save(record: &Path, records: Vec<Record>) -> std::io::Result<()> {
114 if let Some(dir) = record.parent() {
115 std::fs::create_dir_all(dir)?;
116 }
117 let tmp = record.with_extension(format!("tmp{}", std::process::id()));
118 std::fs::write(&tmp, serde_json::to_vec_pretty(&Stored { version: VERSION, records }).map_err(std::io::Error::other)?)?;
119 std::fs::rename(&tmp, record).inspect_err(|_| {
120 let _ = std::fs::remove_file(&tmp);
121 })
122}
123
124#[derive(Debug, Clone, PartialEq, Eq)]
126pub struct Found {
127 pub channel: String,
128 pub was_at: String,
129}
130
131pub fn lookup(record: &Path, appimage: &Path) -> Option<Found> {
133 let now = file_id(appimage)?;
134 let path = appimage.to_string_lossy();
135 load(record)
136 .0
137 .into_iter()
138 .rev()
139 .filter(|r| plain_channel(&r.channel))
140 .find(|r| is_this_file(r, &path, &now))
141 .map(|r| Found { channel: r.channel, was_at: r.path })
142}
143
144const LOCK_TIMEOUT: Duration = Duration::from_secs(5);
146const LOCK_RETRY: Duration = Duration::from_millis(10);
147
148fn lock_record(record: &Path, timeout: Duration) -> std::io::Result<File> {
153 if let Some(dir) = record.parent() {
154 std::fs::create_dir_all(dir)?;
155 }
156 let mut name = record.file_name().map(std::ffi::OsString::from).unwrap_or_else(|| RECORD_FILE.into());
157 name.push(".lock");
158 #[allow(clippy::suspicious_open_options)]
159 let file = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(record.with_file_name(name))?;
160 let started = Instant::now();
161 loop {
162 match file.try_lock() {
163 Ok(()) => return Ok(file),
164 Err(TryLockError::WouldBlock) if started.elapsed() < timeout => std::thread::sleep(LOCK_RETRY),
165 Err(TryLockError::WouldBlock) => {
166 return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "the AppImage channel record is locked by another start"))
167 }
168 Err(TryLockError::Error(e)) => return Err(e),
169 }
170 }
171}
172
173pub fn remember(record: &Path, appimage: &Path, channel: &str) -> std::io::Result<()> {
180 remember_within(record, appimage, channel, LOCK_TIMEOUT)
181}
182
183fn remember_within(record: &Path, appimage: &Path, channel: &str, timeout: Duration) -> std::io::Result<()> {
184 if !plain_channel(channel) {
185 return Ok(());
186 }
187 let Some(id) = file_id(appimage) else { return Ok(()) };
188 let path = appimage.to_string_lossy().into_owned();
189 let _turn = lock_record(record, timeout)?;
190 let (mut records, writable) = load(record);
191 if !writable {
192 return Ok(());
193 }
194 records.retain(|r| r.path != path && !is_this_file(r, &path, &id));
196 records.push(Record { path, channel: channel.to_string(), id });
197 if records.len() > MAX_RECORDS {
198 let extra = records.len() - MAX_RECORDS;
199 records.drain(..extra);
200 }
201 save(record, records)
202}
203
204#[derive(Debug, Clone, Default, PartialEq, Eq)]
206pub struct Reconciled {
207 pub channel: Option<String>,
209 pub moved_from: Option<String>,
211}
212
213pub fn reconcile(record: &Path, appimage: &Path) -> Reconciled {
216 let beside = read_channel_file(&appimage_channel_file(appimage)).filter(|c| plain_channel(c));
217 let found = lookup(record, appimage);
218 let Some(channel) = beside.clone().or_else(|| found.as_ref().map(|f| f.channel.clone())) else {
219 return Reconciled::default();
220 };
221 if beside.is_none() {
222 let _ = std::fs::write(appimage_channel_file(appimage), format!("{channel}\n"));
223 }
224 let moved_from = found.map(|f| f.was_at).filter(|was| *was != appimage.to_string_lossy());
225 let _ = remember(record, appimage, &channel);
226 Reconciled { channel: Some(channel), moved_from }
227}
228
229pub fn record_path() -> Option<PathBuf> {
231 crate::data_paths::agentmux_root().ok().map(|root| root.join("shared").join(RECORD_FILE))
232}
233
234pub fn moved_channel(appimage: &Path) -> Option<String> {
236 lookup(&record_path()?, appimage).map(|f| f.channel)
237}
238
239#[cfg(test)]
240mod tests;