ic_query/cache/model.rs
1//! Module: cache::model
2//!
3//! Responsibility: define shared cache-validation and local inventory report contracts.
4//! Does not own: filesystem traversal, cache-family validation, or CLI output.
5//! Boundary: names family validation outcomes and exposes generic header, age,
6//! recovery-policy, and lock evidence without performing family-specific validation.
7
8use serde::{Deserialize as SerdeDeserialize, Serialize};
9use std::{fmt, path::PathBuf};
10
11/// Current serialized schema version for cache-status reports.
12pub const CACHE_STATUS_REPORT_SCHEMA_VERSION: u32 = 1;
13
14///
15/// CacheValidationStatus
16///
17/// Semantic validation result for an existing family-specific cache.
18///
19
20#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
21#[serde(rename_all = "snake_case")]
22pub enum CacheValidationStatus {
23 /// The cache passed its family-specific schema, identity, and completeness checks.
24 #[serde(rename = "ok")]
25 Valid,
26 /// The cache exists but failed family-specific validation.
27 Invalid,
28}
29
30impl CacheValidationStatus {
31 /// Return the stable serialized status label.
32 #[must_use]
33 pub const fn as_str(self) -> &'static str {
34 match self {
35 Self::Valid => "ok",
36 Self::Invalid => "invalid",
37 }
38 }
39}
40
41impl fmt::Display for CacheValidationStatus {
42 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
43 formatter.write_str(self.as_str())
44 }
45}
46
47///
48/// CacheRefreshAttemptStatus
49///
50/// Lifecycle state for a complete-cache refresh attempt.
51///
52
53#[derive(Clone, Copy, Debug, Eq, PartialEq, SerdeDeserialize, Serialize)]
54#[serde(rename_all = "snake_case")]
55pub enum CacheRefreshAttemptStatus {
56 /// A refresh started or published intermediate collection progress.
57 Running,
58 /// A refresh exhausted its source and published a complete cache.
59 Complete,
60 /// A refresh terminated without replacing the complete cache.
61 Failed,
62}
63
64impl CacheRefreshAttemptStatus {
65 /// Return the stable serialized lifecycle label.
66 #[must_use]
67 pub const fn as_str(self) -> &'static str {
68 match self {
69 Self::Running => "running",
70 Self::Complete => "complete",
71 Self::Failed => "failed",
72 }
73 }
74}
75
76impl fmt::Display for CacheRefreshAttemptStatus {
77 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
78 formatter.write_str(self.as_str())
79 }
80}
81
82///
83/// CacheHeaderStatus
84///
85/// Generic header-integrity classification for one complete cache file.
86///
87
88#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
89#[serde(rename_all = "snake_case")]
90pub enum CacheHeaderStatus {
91 /// The generic cache header is readable.
92 Readable,
93 /// The generic cache header cannot be read or parsed.
94 Invalid,
95}
96
97impl CacheHeaderStatus {
98 /// Return the stable serialized status label.
99 #[must_use]
100 pub const fn as_str(self) -> &'static str {
101 match self {
102 Self::Readable => "readable",
103 Self::Invalid => "invalid",
104 }
105 }
106}
107
108///
109/// CacheAgeStatus
110///
111/// Caller-relative age classification for one complete cache file.
112///
113
114#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
115#[serde(rename_all = "snake_case")]
116pub enum CacheAgeStatus {
117 /// The cache is within its registered family stale threshold.
118 Fresh,
119 /// The cache is older than its registered family stale threshold.
120 Stale,
121 /// The cache has a readable age but no registered family stale threshold.
122 Unmanaged,
123 /// The cache age cannot be calculated from its generic timestamp evidence.
124 Unknown,
125}
126
127impl CacheAgeStatus {
128 /// Return the stable serialized status label.
129 #[must_use]
130 pub const fn as_str(self) -> &'static str {
131 match self {
132 Self::Fresh => "fresh",
133 Self::Stale => "stale",
134 Self::Unmanaged => "unmanaged",
135 Self::Unknown => "unknown",
136 }
137 }
138}
139
140///
141/// CacheRecoveryPolicy
142///
143/// Owner policy for replacing recoverable invalid content at a canonical cache path.
144///
145
146#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
147#[serde(rename_all = "snake_case")]
148pub enum CacheRecoveryPolicy {
149 /// An ordinary owner read-through replaces recoverable invalid content.
150 Automatic,
151 /// Recovery requires an explicitly selected refresh operation.
152 Explicit,
153 /// Ordinary read-through creates a missing cache but does not replace invalid content.
154 MissingOnly,
155 /// The path does not identify a current canonical cache owner.
156 Unknown,
157}
158
159impl CacheRecoveryPolicy {
160 /// Return the stable serialized policy label.
161 #[must_use]
162 pub const fn as_str(self) -> &'static str {
163 match self {
164 Self::Automatic => "automatic",
165 Self::Explicit => "explicit",
166 Self::MissingOnly => "missing_only",
167 Self::Unknown => "unknown",
168 }
169 }
170}
171
172///
173/// CacheRefreshLockStatus
174///
175/// Generic age or validity classification for one refresh lock.
176///
177
178#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
179#[serde(rename_all = "snake_case")]
180pub enum CacheRefreshLockStatus {
181 /// The lock is within the stale threshold recorded by its owner.
182 Active,
183 /// The lock is older than the stale threshold recorded by its owner.
184 Stale,
185 /// The lock is unreadable, malformed, or future-dated.
186 Invalid,
187}
188
189impl CacheRefreshLockStatus {
190 /// Return the stable serialized status label.
191 #[must_use]
192 pub const fn as_str(self) -> &'static str {
193 match self {
194 Self::Active => "active",
195 Self::Stale => "stale",
196 Self::Invalid => "invalid",
197 }
198 }
199}
200
201///
202/// CacheStatusRequest
203///
204/// Local cache-root inspection request with a caller-supplied observation time.
205///
206
207#[derive(Clone, Debug, Eq, PartialEq)]
208pub struct CacheStatusRequest {
209 /// User-level cache root to inspect.
210 pub cache_root: PathBuf,
211 /// Observation time used to calculate cache ages.
212 pub now_unix_secs: u64,
213}
214
215impl CacheStatusRequest {
216 /// Construct a local cache-status request.
217 #[must_use]
218 pub fn new(cache_root: impl Into<PathBuf>, now_unix_secs: u64) -> Self {
219 Self {
220 cache_root: cache_root.into(),
221 now_unix_secs,
222 }
223 }
224}
225
226///
227/// CacheStatusReport
228///
229/// Bounded local inventory of known complete caches and refresh locks.
230///
231
232#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
233pub struct CacheStatusReport {
234 /// Cache-status report schema version.
235 pub schema_version: u32,
236 /// Inspected user-level cache root.
237 pub cache_root: String,
238 /// UTC timestamp at which local inspection was requested.
239 pub inspected_at: String,
240 /// Whether the cache root existed.
241 pub cache_root_found: bool,
242 /// Maximum number of cache and refresh-lock files inspected in one report.
243 pub scan_limit: usize,
244 /// Whether additional cache or refresh-lock candidates existed beyond the scan limit.
245 pub truncated: bool,
246 /// Whether the generic inventory performed family-specific semantic validation.
247 pub family_validation_performed: bool,
248 /// Number of cache rows returned.
249 pub cache_count: usize,
250 /// Number of caches with readable generic headers.
251 pub readable_header_count: usize,
252 /// Number of caches with unreadable or malformed generic headers.
253 pub invalid_header_count: usize,
254 /// Number of caches fresh under an explicit family policy.
255 pub fresh_count: usize,
256 /// Number of caches stale under an explicit family policy.
257 pub stale_count: usize,
258 /// Number of readable caches whose family has no registered age policy.
259 pub unmanaged_age_count: usize,
260 /// Number of caches whose age cannot be calculated from generic evidence.
261 pub unknown_age_count: usize,
262 /// Sum of filesystem sizes for returned cache files.
263 pub total_size_bytes: u64,
264 /// Canonically path-ordered cache rows.
265 pub caches: Vec<CacheStatusRow>,
266 /// Number of refresh-lock rows returned.
267 pub refresh_lock_count: usize,
268 /// Number of locks still active under their recorded stale policy.
269 pub active_refresh_lock_count: usize,
270 /// Number of locks older than their recorded stale policy.
271 pub stale_refresh_lock_count: usize,
272 /// Number of unreadable, malformed, or future-dated locks.
273 pub invalid_refresh_lock_count: usize,
274 /// Sum of filesystem sizes for returned refresh-lock files.
275 pub refresh_lock_size_bytes: u64,
276 /// Canonically path-ordered refresh-lock rows.
277 pub refresh_locks: Vec<CacheRefreshLockStatusRow>,
278}
279
280///
281/// CacheStatusRow
282///
283/// Generic local metadata and caller-relative age for one complete cache file.
284///
285
286#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
287pub struct CacheStatusRow {
288 /// Stable component label inferred from cache identity or canonical path.
289 pub component: String,
290 /// Absolute cache-file path.
291 pub cache_path: String,
292 /// Cache-root-relative path.
293 pub relative_path: String,
294 /// Generic cache-header integrity without family-specific semantic validation.
295 pub header_status: CacheHeaderStatus,
296 /// Caller-relative age classification kept separate from header integrity.
297 pub age_status: CacheAgeStatus,
298 /// Owner policy for recovering invalid content at this canonical path.
299 pub recovery_policy: CacheRecoveryPolicy,
300 /// Serialized cache schema version when readable.
301 pub schema_version: Option<u32>,
302 /// Serialized network identity when present.
303 pub network: Option<String>,
304 /// Cache collection timestamp when readable.
305 pub fetched_at: Option<String>,
306 /// Caller-relative age when the timestamp is valid and not in the future.
307 pub age_seconds: Option<u64>,
308 /// Family age threshold when one is explicitly defined.
309 pub stale_after_seconds: Option<u64>,
310 /// Filesystem size of this cache file.
311 pub size_bytes: u64,
312 /// Generic header or timestamp inspection error; family-specific validation is separate.
313 pub inspection_error: Option<String>,
314}
315
316///
317/// CacheRefreshLockStatusRow
318///
319/// Local identity, ownership, age, and stale policy for one refresh lock.
320///
321
322#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
323pub struct CacheRefreshLockStatusRow {
324 /// Stable component label inferred from the recorded cache target.
325 pub component: String,
326 /// Absolute refresh-lock path.
327 pub refresh_lock_path: String,
328 /// Cache-root-relative refresh-lock path.
329 pub relative_path: String,
330 /// Generic lock age or validity classification.
331 pub status: CacheRefreshLockStatus,
332 /// Serialized refresh-lock schema version when readable.
333 pub schema_version: Option<u32>,
334 /// Serialized network identity when readable.
335 pub network: Option<String>,
336 /// Operating-system process id recorded by the lock owner when readable.
337 pub pid: Option<u32>,
338 /// Raw Unix-millisecond acquisition time when readable.
339 pub started_at_unix_ms: Option<u64>,
340 /// UTC acquisition timestamp when readable.
341 pub started_at: Option<String>,
342 /// Caller-relative lock age when the timestamp is not in the future.
343 pub age_seconds: Option<u64>,
344 /// Stale threshold recorded by the lock owner.
345 pub stale_after_seconds: Option<u64>,
346 /// Cache target recorded by the lock owner when readable.
347 pub target_path: Option<String>,
348 /// Filesystem size of this refresh-lock file.
349 pub size_bytes: u64,
350 /// Lock parse, shape, or timestamp error.
351 pub error: Option<String>,
352}
353
354#[cfg(test)]
355mod tests {
356 use super::*;
357
358 #[test]
359 fn typed_statuses_keep_stable_json_labels() {
360 for (status, expected) in [
361 (CacheValidationStatus::Valid, "ok"),
362 (CacheValidationStatus::Invalid, "invalid"),
363 ] {
364 assert_eq!(status.as_str(), expected);
365 assert_eq!(status.to_string(), expected);
366 assert_eq!(
367 serde_json::to_value(status).expect("serialize cache validation status"),
368 serde_json::json!(expected)
369 );
370 }
371 for (status, expected) in [
372 (CacheRefreshAttemptStatus::Running, "running"),
373 (CacheRefreshAttemptStatus::Complete, "complete"),
374 (CacheRefreshAttemptStatus::Failed, "failed"),
375 ] {
376 assert_eq!(status.as_str(), expected);
377 assert_eq!(status.to_string(), expected);
378 assert_eq!(
379 serde_json::from_value::<CacheRefreshAttemptStatus>(serde_json::json!(expected))
380 .expect("deserialize refresh-attempt status"),
381 status
382 );
383 assert_eq!(
384 serde_json::to_value(status).expect("serialize refresh-attempt status"),
385 serde_json::json!(expected)
386 );
387 }
388 assert!(
389 serde_json::from_value::<CacheRefreshAttemptStatus>(serde_json::json!("unknown"))
390 .is_err()
391 );
392 for (status, expected) in [
393 (CacheHeaderStatus::Readable, "readable"),
394 (CacheHeaderStatus::Invalid, "invalid"),
395 ] {
396 assert_eq!(status.as_str(), expected);
397 assert_eq!(
398 serde_json::to_value(status).expect("serialize cache header status"),
399 serde_json::json!(expected)
400 );
401 }
402 for (status, expected) in [
403 (CacheAgeStatus::Fresh, "fresh"),
404 (CacheAgeStatus::Stale, "stale"),
405 (CacheAgeStatus::Unmanaged, "unmanaged"),
406 (CacheAgeStatus::Unknown, "unknown"),
407 ] {
408 assert_eq!(status.as_str(), expected);
409 assert_eq!(
410 serde_json::to_value(status).expect("serialize cache age status"),
411 serde_json::json!(expected)
412 );
413 }
414 for (policy, expected) in [
415 (CacheRecoveryPolicy::Automatic, "automatic"),
416 (CacheRecoveryPolicy::Explicit, "explicit"),
417 (CacheRecoveryPolicy::MissingOnly, "missing_only"),
418 (CacheRecoveryPolicy::Unknown, "unknown"),
419 ] {
420 assert_eq!(policy.as_str(), expected);
421 assert_eq!(
422 serde_json::to_value(policy).expect("serialize cache recovery policy"),
423 serde_json::json!(expected)
424 );
425 }
426 for (status, expected) in [
427 (CacheRefreshLockStatus::Active, "active"),
428 (CacheRefreshLockStatus::Stale, "stale"),
429 (CacheRefreshLockStatus::Invalid, "invalid"),
430 ] {
431 assert_eq!(status.as_str(), expected);
432 assert_eq!(
433 serde_json::to_value(status).expect("serialize refresh-lock status"),
434 serde_json::json!(expected)
435 );
436 }
437 }
438}