|
| 1 | +/* |
| 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * This source code is licensed under the BSD-style license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. |
| 7 | + */ |
| 8 | + |
| 9 | +use std::collections::HashMap; |
| 10 | +use std::path::Path; |
| 11 | +use std::path::PathBuf; |
| 12 | +use std::time::Duration; |
| 13 | +use std::time::SystemTime; |
| 14 | +use std::time::UNIX_EPOCH; |
| 15 | + |
| 16 | +use anyhow::Context; |
| 17 | +use anyhow::Result; |
| 18 | +use anyhow::ensure; |
| 19 | +use chrono::DateTime; |
| 20 | +use chrono::Utc; |
| 21 | +use digest::Digest; |
| 22 | +use digest::Output; |
| 23 | +use rattler_conda_types::PrefixRecord; |
| 24 | +use rattler_conda_types::prefix_record::PathsEntry; |
| 25 | +use serde::Deserialize; |
| 26 | +use serde::Serialize; |
| 27 | +use serde_json; |
| 28 | +use sha2::Sha256; |
| 29 | +use tokio::fs; |
| 30 | +use walkdir::WalkDir; |
| 31 | + |
| 32 | +use crate::hash_utils; |
| 33 | +use crate::pack_meta::History; |
| 34 | +use crate::pack_meta::Offsets; |
| 35 | + |
| 36 | +/// Fingerprint of the conda environment, used to detect if two envs are using the same |
| 37 | +/// "base" env. |
| 38 | +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] |
| 39 | +pub struct CondaMetaFingerprint { |
| 40 | + hash: Output<Sha256>, |
| 41 | +} |
| 42 | + |
| 43 | +impl CondaMetaFingerprint { |
| 44 | + async fn from_env(path: &Path) -> Result<Self> { |
| 45 | + let mut hasher = Sha256::new(); |
| 46 | + hash_utils::hash_directory_tree(&path.join("conda-meta"), &mut hasher).await?; |
| 47 | + Ok(Self { |
| 48 | + hash: hasher.finalize(), |
| 49 | + }) |
| 50 | + } |
| 51 | + |
| 52 | + fn ensure_can_sync_to(&self, other: &CondaMetaFingerprint) -> Result<()> { |
| 53 | + ensure!(self.hash == other.hash); |
| 54 | + Ok(()) |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] |
| 59 | +pub struct PackMetaFingerprint { |
| 60 | + offsets: Output<Sha256>, |
| 61 | + pub history: History, |
| 62 | +} |
| 63 | + |
| 64 | +impl PackMetaFingerprint { |
| 65 | + async fn from_env(path: &Path) -> Result<Self> { |
| 66 | + let pack_meta = path.join("pack-meta"); |
| 67 | + |
| 68 | + // Read first line of history.jsonl |
| 69 | + let contents = fs::read_to_string(pack_meta.join("history.jsonl")).await?; |
| 70 | + let history = History::from_contents(&contents)?; |
| 71 | + |
| 72 | + // Read entire offsets.jsonl file |
| 73 | + let mut hasher = Sha256::new(); |
| 74 | + let contents = fs::read_to_string(pack_meta.join("offsets.jsonl")).await?; |
| 75 | + let offsets = Offsets::from_contents(&contents)?; |
| 76 | + for ent in offsets.entries { |
| 77 | + let contents = bincode::serialize(&(ent.path, ent.mode, ent.offsets.len()))?; |
| 78 | + hasher.update(contents.len().to_le_bytes()); |
| 79 | + hasher.update(&contents); |
| 80 | + } |
| 81 | + let offsets = hasher.finalize(); |
| 82 | + |
| 83 | + Ok(Self { history, offsets }) |
| 84 | + } |
| 85 | + |
| 86 | + fn ensure_can_sync_to(&self, other: &PackMetaFingerprint) -> Result<()> { |
| 87 | + ensure!( |
| 88 | + self.history.entries.first().context("empty history")? |
| 89 | + == other.history.entries.first().context("empty history")? |
| 90 | + ); |
| 91 | + ensure!( |
| 92 | + self.history |
| 93 | + .entries |
| 94 | + .last() |
| 95 | + .context("empty history")? |
| 96 | + .timestamp |
| 97 | + <= other |
| 98 | + .history |
| 99 | + .entries |
| 100 | + .last() |
| 101 | + .context("empty history")? |
| 102 | + .timestamp |
| 103 | + ); |
| 104 | + |
| 105 | + ensure!(self.offsets == other.offsets); |
| 106 | + |
| 107 | + Ok(()) |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] |
| 112 | +pub struct CondaFingerprint { |
| 113 | + pub conda_meta: CondaMetaFingerprint, |
| 114 | + pub pack_meta: PackMetaFingerprint, |
| 115 | +} |
| 116 | + |
| 117 | +impl CondaFingerprint { |
| 118 | + pub async fn from_env(path: &Path) -> Result<Self> { |
| 119 | + Ok(Self { |
| 120 | + conda_meta: CondaMetaFingerprint::from_env(path).await?, |
| 121 | + pack_meta: PackMetaFingerprint::from_env(path).await?, |
| 122 | + }) |
| 123 | + } |
| 124 | + |
| 125 | + pub fn ensure_can_sync_to(&self, other: &CondaFingerprint) -> Result<()> { |
| 126 | + self.conda_meta |
| 127 | + .ensure_can_sync_to(&other.conda_meta) |
| 128 | + .context("conda-meta")?; |
| 129 | + self.pack_meta |
| 130 | + .ensure_can_sync_to(&other.pack_meta) |
| 131 | + .context("pack-meta")?; |
| 132 | + Ok(()) |
| 133 | + } |
| 134 | + |
| 135 | + pub fn mtime_comparator( |
| 136 | + a: &Self, |
| 137 | + b: &Self, |
| 138 | + ) -> Result<Box<dyn Fn(&SystemTime, &SystemTime) -> std::cmp::Ordering + Send + Sync>> { |
| 139 | + let (a_prefix, a_base) = a.pack_meta.history.first()?; |
| 140 | + let (b_prefix, b_base) = b.pack_meta.history.first()?; |
| 141 | + ensure!(a_prefix == b_prefix); |
| 142 | + // NOTE(agallagher): There appears to be some mtime drift on some files after fbpkg creation, |
| 143 | + // so acccount for that here. |
| 144 | + let slop = Duration::from_secs(5 * 60); |
| 145 | + let a_base = UNIX_EPOCH + Duration::from_secs(a_base) + slop; |
| 146 | + let b_base = UNIX_EPOCH + Duration::from_secs(b_base) + slop; |
| 147 | + |
| 148 | + let a_window = a |
| 149 | + .pack_meta |
| 150 | + .history |
| 151 | + .prefix_and_last_update_window()? |
| 152 | + .1 |
| 153 | + .map(|(s, e)| { |
| 154 | + ( |
| 155 | + UNIX_EPOCH + Duration::from_secs(s), |
| 156 | + UNIX_EPOCH + Duration::from_secs(e + 1), |
| 157 | + ) |
| 158 | + }); |
| 159 | + let b_window = b |
| 160 | + .pack_meta |
| 161 | + .history |
| 162 | + .prefix_and_last_update_window()? |
| 163 | + .1 |
| 164 | + .map(|(s, e)| { |
| 165 | + ( |
| 166 | + UNIX_EPOCH + Duration::from_secs(s), |
| 167 | + UNIX_EPOCH + Duration::from_secs(e + 1), |
| 168 | + ) |
| 169 | + }); |
| 170 | + Ok(Box::new(move |a: &SystemTime, b: &SystemTime| { |
| 171 | + match ( |
| 172 | + *a > a_base && a_window.is_none_or(|(s, e)| *a < s || *a > e), |
| 173 | + *b > b_base && b_window.is_none_or(|(s, e)| *b < s || *b > e), |
| 174 | + ) { |
| 175 | + (true, false) => std::cmp::Ordering::Greater, |
| 176 | + (false, true) => std::cmp::Ordering::Less, |
| 177 | + (false, false) => std::cmp::Ordering::Equal, |
| 178 | + (true, true) => a.cmp(b), |
| 179 | + } |
| 180 | + })) |
| 181 | + } |
| 182 | +} |
| 183 | + |
| 184 | +async fn load_metadata(env: &Path) -> Result<Vec<PrefixRecord>> { |
| 185 | + let conda_meta_path = env.join("conda-meta"); |
| 186 | + let mut records = Vec::new(); |
| 187 | + |
| 188 | + for entry in WalkDir::new(&conda_meta_path) |
| 189 | + .min_depth(1) |
| 190 | + .into_iter() |
| 191 | + .filter_map(|e| e.ok()) |
| 192 | + .filter(|e| e.file_name() != "history") |
| 193 | + { |
| 194 | + let content = fs::read_to_string(entry.path()) |
| 195 | + .await |
| 196 | + .with_context(|| format!("reading {:?}", entry.path()))?; |
| 197 | + let record: PrefixRecord = serde_json::from_str(&content)?; |
| 198 | + records.push(record); |
| 199 | + } |
| 200 | + |
| 201 | + Ok(records) |
| 202 | +} |
| 203 | + |
| 204 | +fn index_metadata(records: &[PrefixRecord]) -> HashMap<PathBuf, (&PathsEntry, &PrefixRecord)> { |
| 205 | + let mut path_map = HashMap::new(); |
| 206 | + |
| 207 | + for record in records { |
| 208 | + // Add all paths from paths_data to the map |
| 209 | + for paths_entry in &record.paths_data.paths { |
| 210 | + path_map.insert(paths_entry.relative_path.clone(), (paths_entry, record)); |
| 211 | + } |
| 212 | + } |
| 213 | + |
| 214 | + path_map |
| 215 | +} |
| 216 | + |
| 217 | +pub enum Change { |
| 218 | + Missing, |
| 219 | + Added, |
| 220 | + Modified, |
| 221 | +} |
| 222 | + |
| 223 | +pub async fn diff(env: &Path) -> Result<Vec<(PathBuf, Change)>> { |
| 224 | + let metadata = load_metadata(env).await?; |
| 225 | + let mut index = index_metadata(&metadata); |
| 226 | + let mut changes = Vec::new(); |
| 227 | + |
| 228 | + for entry in WalkDir::new(env) |
| 229 | + .into_iter() |
| 230 | + .filter_map(|e| e.ok()) |
| 231 | + .filter(|e| e.file_type().is_file()) |
| 232 | + .filter(|e| !e.path().starts_with(env.join("conda-meta"))) |
| 233 | + { |
| 234 | + let file_path = entry.path(); |
| 235 | + let relative_path = file_path.strip_prefix(env)?; |
| 236 | + |
| 237 | + if let Some((relative_path, (paths_entry, prefix_record))) = |
| 238 | + index.remove_entry(relative_path) |
| 239 | + { |
| 240 | + // File is tracked in metadata, check if it's modified |
| 241 | + let file_metadata = fs::symlink_metadata(file_path).await?; |
| 242 | + let file_size = file_metadata.len(); |
| 243 | + let file_mtime = file_metadata.modified()?; |
| 244 | + |
| 245 | + let mut is_modified = false; |
| 246 | + |
| 247 | + // Compare size if available (now we have direct access to PathsEntry) |
| 248 | + if !is_modified { |
| 249 | + if let Some(size_in_bytes) = paths_entry.size_in_bytes { |
| 250 | + is_modified = file_size != size_in_bytes; |
| 251 | + } |
| 252 | + } |
| 253 | + |
| 254 | + // Compare mtime with package record timestamp |
| 255 | + // If package timestamp > file mtime, then file is not modified |
| 256 | + if !is_modified { |
| 257 | + let package_timestamp = prefix_record |
| 258 | + .repodata_record |
| 259 | + .package_record |
| 260 | + .timestamp |
| 261 | + .context("no timestamp")?; |
| 262 | + |
| 263 | + // Convert file mtime to chrono DateTime for comparison |
| 264 | + let duration_since_epoch = file_mtime.duration_since(UNIX_EPOCH)?; |
| 265 | + let file_datetime = DateTime::<Utc>::from_timestamp( |
| 266 | + duration_since_epoch.as_secs() as i64, |
| 267 | + duration_since_epoch.subsec_nanos(), |
| 268 | + ) |
| 269 | + .context("failed to convert mtime to DateTime")?; |
| 270 | + |
| 271 | + // If file was modified after package installation, it's been modified |
| 272 | + if file_datetime > package_timestamp { |
| 273 | + is_modified = true; |
| 274 | + } |
| 275 | + } |
| 276 | + |
| 277 | + if is_modified { |
| 278 | + changes.push((relative_path, Change::Modified)); |
| 279 | + } |
| 280 | + } else { |
| 281 | + // File exists but is not tracked in metadata |
| 282 | + changes.push((relative_path.to_path_buf(), Change::Added)); |
| 283 | + } |
| 284 | + } |
| 285 | + |
| 286 | + // Remaining paths in index are missing files |
| 287 | + for path in index.into_keys() { |
| 288 | + changes.push((path, Change::Missing)); |
| 289 | + } |
| 290 | + |
| 291 | + Ok(changes) |
| 292 | +} |
0 commit comments