Skip to main content

r_package_installer/
model.rs

1use std::{
2    collections::BTreeMap,
3    fmt,
4    path::PathBuf,
5    sync::{
6        Arc,
7        atomic::{AtomicBool, Ordering},
8    },
9    time::Duration,
10};
11
12use crate::{Error, Result};
13
14/// A SHA-256 digest.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub struct Digest([u8; 32]);
17
18impl Digest {
19    /// Creates a digest from its 32-byte representation.
20    pub const fn from_bytes(bytes: [u8; 32]) -> Self {
21        Self(bytes)
22    }
23
24    /// Parses a digest from 64 hexadecimal characters.
25    pub fn from_hex(value: &str) -> Result<Self> {
26        let bytes = hex::decode(value).map_err(|_| Error::InvalidCacheKey(value.to_owned()))?;
27        let bytes: [u8; 32] = bytes
28            .try_into()
29            .map_err(|_| Error::InvalidCacheKey(value.to_owned()))?;
30        Ok(Self(bytes))
31    }
32
33    /// Returns the digest bytes.
34    pub const fn as_bytes(&self) -> &[u8; 32] {
35        &self.0
36    }
37}
38
39impl fmt::Display for Digest {
40    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
41        formatter.write_str(&hex::encode(self.0))
42    }
43}
44
45/// A caller-defined source or binary cache identity.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
47pub struct CacheKey(Digest);
48
49impl CacheKey {
50    /// Creates a cache key from a digest computed by the caller.
51    pub const fn from_digest(digest: Digest) -> Self {
52        Self(digest)
53    }
54
55    /// Parses a cache key from 64 hexadecimal characters.
56    pub fn from_hex(value: &str) -> Result<Self> {
57        Digest::from_hex(value).map(Self)
58    }
59}
60
61impl fmt::Display for CacheKey {
62    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
63        self.0.fmt(formatter)
64    }
65}
66
67/// Authoritative identity and compatibility information supplied upstream.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct ExpectedPackage {
70    /// Expected `Package` field and top-level directory name.
71    pub name: String,
72    /// Expected `Version` field.
73    pub version: String,
74    /// Optional required R major and minor version, such as `4.5`.
75    pub r_major_minor: Option<String>,
76    /// Optional required platform from the `Built` field.
77    pub platform: Option<String>,
78    /// Optional architecture that must occur in the package platform.
79    pub architecture: Option<String>,
80}
81
82/// A prebuilt R package archive.
83///
84/// ZIP, gzip-compressed tar, and XZ-compressed tar are detected from file contents.
85#[derive(Debug, Clone)]
86pub struct BinaryArtifact {
87    /// Path to the predownloaded archive.
88    pub path: PathBuf,
89}
90
91/// Per-child cancellation state. Cancelling does not affect other calls.
92#[derive(Debug, Clone, Default)]
93pub struct CancellationToken(Arc<AtomicBool>);
94
95impl CancellationToken {
96    /// Requests cancellation of the associated source installation.
97    pub fn cancel(&self) {
98        self.0.store(true, Ordering::Release);
99    }
100
101    /// Returns whether cancellation has been requested.
102    pub fn is_cancelled(&self) -> bool {
103        self.0.load(Ordering::Acquire)
104    }
105}
106
107/// Controls an `R CMD INSTALL` source build.
108#[derive(Debug, Clone)]
109pub struct SourceOptions {
110    /// R executable used to launch `R CMD INSTALL`.
111    pub r_executable: PathBuf,
112    /// Library paths exposed to R as source-build dependencies.
113    pub dependency_libraries: Vec<PathBuf>,
114    /// Additional environment variables for the source-build process.
115    pub environment: BTreeMap<String, String>,
116    /// Arguments joined and passed through `--configure-args`.
117    pub configure_args: Vec<String>,
118    /// Maximum duration allowed for the source-build process.
119    pub timeout: Duration,
120    /// Cancellation state observed while the source build is running.
121    pub cancellation: CancellationToken,
122    /// Allows packages declaring `StagedInstall: no` when set.
123    pub allow_non_staged: bool,
124}
125
126impl Default for SourceOptions {
127    fn default() -> Self {
128        Self {
129            r_executable: PathBuf::from("R"),
130            dependency_libraries: Vec::new(),
131            environment: BTreeMap::new(),
132            configure_args: Vec::new(),
133            timeout: Duration::from_secs(30 * 60),
134            cancellation: CancellationToken::default(),
135            allow_non_staged: false,
136        }
137    }
138}
139
140/// A predownloaded R source package archive and its build options.
141#[derive(Debug, Clone)]
142pub struct SourceArtifact {
143    /// Path to the source archive.
144    pub path: PathBuf,
145    /// Source installation policy.
146    pub options: SourceOptions,
147}
148
149/// A package artifact to prepare.
150#[derive(Debug, Clone)]
151pub enum Artifact {
152    /// A prebuilt package archive extracted natively by this crate.
153    Binary(BinaryArtifact),
154    /// A source package installed by `R CMD INSTALL`.
155    Source(SourceArtifact),
156}
157
158/// Inputs required to prepare one immutable cache entry.
159#[derive(Debug, Clone)]
160pub struct PrepareRequest {
161    /// Caller-defined identity for all inputs affecting the prepared tree.
162    pub key: CacheKey,
163    /// Expected SHA-256 digest of the artifact file.
164    pub artifact_digest: Digest,
165    /// Authoritative package identity and compatibility constraints.
166    pub expected: ExpectedPackage,
167    /// Predownloaded artifact to prepare.
168    pub artifact: Artifact,
169}
170
171/// Locking policy used while modifying a target R library.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub enum LockPolicy {
174    /// Acquire only base-R-compatible `00LOCK-<package>` locks.
175    Package,
176    /// Also acquire global `00LOCK` to serialize all library modifications.
177    StrictLibrary,
178}
179
180/// Waiting policy for another process preparing the same cache key.
181#[derive(Debug, Clone)]
182pub struct CacheLockPolicy {
183    /// Maximum time to wait for the cache entry to become available.
184    pub wait_timeout: Duration,
185    /// Delay between cache lookup attempts while waiting.
186    pub poll_interval: Duration,
187}
188
189impl Default for CacheLockPolicy {
190    fn default() -> Self {
191        Self {
192            wait_timeout: Duration::from_secs(5 * 60),
193            poll_interval: Duration::from_millis(100),
194        }
195    }
196}
197
198/// Operational policy shared by installer calls.
199#[derive(Debug, Clone)]
200pub struct InstallerOptions {
201    /// Locking policy for target libraries.
202    pub lock_policy: LockPolicy,
203    /// Waiting policy for cache-key contention.
204    pub cache_lock: CacheLockPolicy,
205    /// Maximum time spent retrying transient Windows filesystem failures.
206    pub windows_retry_timeout: Duration,
207    /// Resource and path limits enforced during archive extraction.
208    pub archive_limits: ArchiveLimits,
209}
210
211impl Default for InstallerOptions {
212    fn default() -> Self {
213        Self {
214            lock_policy: LockPolicy::Package,
215            cache_lock: CacheLockPolicy::default(),
216            windows_retry_timeout: Duration::from_secs(5),
217            archive_limits: ArchiveLimits::default(),
218        }
219    }
220}
221
222/// Resource and path limits for untrusted package archives.
223#[derive(Debug, Clone)]
224pub struct ArchiveLimits {
225    /// Maximum number of archive entries.
226    pub max_entries: usize,
227    /// Maximum total uncompressed size in bytes.
228    pub max_expanded_size: u64,
229    /// Maximum size of one regular file in bytes.
230    pub max_file_size: u64,
231    /// Maximum UTF-8 path length in bytes.
232    pub max_path_bytes: usize,
233    /// Maximum number of path components.
234    pub max_depth: usize,
235    /// Maximum ratio of expanded bytes to archive bytes.
236    pub max_expansion_ratio: u64,
237}
238
239impl Default for ArchiveLimits {
240    fn default() -> Self {
241        Self {
242            max_entries: 100_000,
243            max_expanded_size: 8 * 1024 * 1024 * 1024,
244            max_file_size: 2 * 1024 * 1024 * 1024,
245            max_path_bytes: 4096,
246            max_depth: 64,
247            max_expansion_ratio: 1_000,
248        }
249    }
250}
251
252/// Metadata read from a validated installed package tree.
253#[derive(Debug, Clone, PartialEq, Eq)]
254pub struct PackageMetadata {
255    /// Package name.
256    pub name: String,
257    /// Package version.
258    pub version: String,
259    /// Complete `Built` field.
260    pub built: String,
261    /// Optional `OS_type` field.
262    pub os_type: Option<String>,
263    /// Optional `Archs` field.
264    pub archs: Option<String>,
265}
266
267/// A validated immutable cache object.
268#[derive(Debug, Clone)]
269pub struct CacheEntry {
270    /// Cache key that identifies the object.
271    pub key: CacheKey,
272    /// Root containing the manifest, completion marker, and package tree.
273    pub root: PathBuf,
274    /// Root of the cached installed package tree.
275    pub package_root: PathBuf,
276    /// Validated package metadata.
277    pub package: PackageMetadata,
278    /// Deterministic digest of the package tree.
279    pub tree_digest: Digest,
280}
281
282/// A package present in a target R library.
283#[derive(Debug, Clone, PartialEq, Eq)]
284pub struct InstalledPackage {
285    /// Root of the installed package tree.
286    pub root: PathBuf,
287    /// Validated package metadata.
288    pub metadata: PackageMetadata,
289}
290
291/// Result of publishing a package into an R library.
292#[derive(Debug, Clone, PartialEq, Eq)]
293pub enum InstallOutcome {
294    /// The package was newly installed.
295    Installed(InstalledPackage),
296    /// An existing package was replaced.
297    Replaced(InstalledPackage),
298    /// The exact requested package tree was already installed.
299    AlreadyInstalled(InstalledPackage),
300    /// Publication committed, but removal of the backup could not finish.
301    CommittedCleanupPending {
302        /// Successfully published package.
303        package: InstalledPackage,
304        /// Preserved transaction lock containing recovery evidence.
305        lock: PathBuf,
306    },
307}
308
309/// Result of transactionally removing a package.
310#[derive(Debug, Clone, PartialEq, Eq)]
311pub enum RemovalOutcome {
312    /// No package existed at the requested path.
313    NotInstalled,
314    /// The package was removed and transaction cleanup completed.
315    Removed,
316    /// Removal committed, but backup cleanup could not finish.
317    CommittedCleanupPending {
318        /// Preserved transaction lock containing recovery evidence.
319        lock: PathBuf,
320    },
321}
322
323/// Metadata read from an R library lock directory.
324#[derive(Debug, Clone, PartialEq, Eq)]
325pub struct LockMetadata {
326    /// Path to the lock directory.
327    pub path: PathBuf,
328    /// Package recorded by an installer-owned lock, if available.
329    pub package: Option<String>,
330    /// Ownership token recorded by an installer-owned lock, if available.
331    pub token: Option<String>,
332    /// Operation recorded by an installer-owned lock, if available.
333    pub operation: Option<String>,
334    /// Latest durable transaction state, if available.
335    pub state: Option<String>,
336}
337
338/// Filesystem action selected for an interrupted transaction.
339#[derive(Debug, Clone, Copy, PartialEq, Eq)]
340pub enum RecoveryAction {
341    /// Restore the previous package after publication did not begin.
342    RestoreBackup,
343    /// Remove a failed publication and restore any previous package.
344    RollbackPublication,
345    /// Keep the published package and remove its backup.
346    FinishCommit,
347    /// Remove an unpublished staged package.
348    RemoveStaging,
349    /// Finish deleting a package whose removal already committed.
350    FinishRemoval,
351    /// Require caller-directed recovery because the state is ambiguous.
352    Manual,
353}
354
355/// A proposed recovery action derived from lock metadata and filesystem state.
356#[derive(Debug, Clone, PartialEq, Eq)]
357pub struct RecoveryPlan {
358    /// Lock metadata observed during the library scan.
359    pub lock: LockMetadata,
360    /// Action that will be revalidated before recovery begins.
361    pub action: RecoveryAction,
362}
363
364/// One entry found while scanning an R library.
365#[derive(Debug, Clone, PartialEq, Eq)]
366pub enum LibraryEntry {
367    /// A valid installed package.
368    Installed(InstalledPackage),
369    /// A package-like directory that failed validation.
370    Incomplete {
371        /// Path to the invalid entry.
372        path: PathBuf,
373        /// Validation failure reported for the entry.
374        reason: String,
375    },
376    /// A foreign or ambiguous lock that cannot be recovered automatically.
377    Locked(LockMetadata),
378    /// An installer-owned interrupted transaction with a recovery action.
379    Recoverable(RecoveryPlan),
380    /// A non-package filesystem entry.
381    Foreign(PathBuf),
382}