-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcache.rs
More file actions
2385 lines (2179 loc) · 92.2 KB
/
Copy pathcache.rs
File metadata and controls
2385 lines (2179 loc) · 92.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use anyhow::Result;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::collections::HashMap;
use std::path::PathBuf;
const CACHE_TTL_DAYS: i64 = 7;
/// Implemented by cache structs that carry a timestamp for TTL checks.
pub(crate) trait Expiring {
fn fetched_at(&self) -> DateTime<Utc>;
}
/// Read a whole-file cache. Returns `Ok(None)` on missing, expired, or corrupt
/// (unparseable) files. Propagates I/O errors.
fn read_cache<T: DeserializeOwned + Expiring>(profile: &str, filename: &str) -> Result<Option<T>> {
let path = cache_dir(profile).join(filename);
let content = match std::fs::read_to_string(&path) {
Ok(c) => c,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e.into()),
};
let cache: T = match serde_json::from_str(&content) {
Ok(c) => c,
Err(e) => {
eprintln!("warning: cache file {filename} unreadable ({e}); will refetch");
return Ok(None);
}
};
if (Utc::now() - cache.fetched_at()).num_days() >= CACHE_TTL_DAYS {
return Ok(None);
}
Ok(Some(cache))
}
/// Write a whole-file cache. Creates the cache directory if needed.
// NFR-R-G: Non-atomic cache write — direct std::fs::write means a crash mid-write leaves
// indeterminate file state. Self-healing via deserialization-failure → cache-miss path;
// LOW severity for single-user CLI. Optional improvement: temp-file + atomic rename pattern.
fn write_cache<T: Serialize>(profile: &str, filename: &str, data: &T) -> Result<()> {
let dir = cache_dir(profile);
std::fs::create_dir_all(&dir)?;
let content = serde_json::to_string_pretty(data)?;
std::fs::write(dir.join(filename), content)?;
Ok(())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CachedTeam {
pub id: String,
pub name: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct TeamCache {
pub fetched_at: DateTime<Utc>,
pub teams: Vec<CachedTeam>,
}
impl Expiring for TeamCache {
fn fetched_at(&self) -> DateTime<Utc> {
self.fetched_at
}
}
/// Pure fallback for the Windows `%LOCALAPPDATA%` path when `dirs::cache_dir()` returns
/// `None`. Accepts the raw `env::var("LOCALAPPDATA").ok()` value so the logic can be
/// tested on any platform without a `#[cfg(windows)]` gate.
///
/// Rules (BC-6.2.016 EC-1, EC-4):
/// - `Some(s)` where `s` is non-empty → `PathBuf::from(s)`
/// - `Some(s)` where `s` is empty → `PathBuf::from(".")` (treated as unset)
/// - `None` → `PathBuf::from(".")`
pub fn cache_localappdata_fallback(env_val: Option<String>) -> PathBuf {
env_val
.filter(|s| !s.is_empty())
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("."))
}
/// Root cache directory: `%LOCALAPPDATA%\jr` on Windows, `$XDG_CACHE_HOME/jr` or
/// `~/.cache/jr` on Unix.
pub fn cache_root() -> PathBuf {
// JR_CACHE_DIR override is debug builds only — release binaries ignore this env
// var to prevent path-injection attacks (BC-6.2.017). Seam must be first in body,
// before any OS-branch logic, so it fires on all platforms (S-WIN-2 prerequisite).
#[cfg(debug_assertions)]
if let Some(dir) = std::env::var("JR_CACHE_DIR").ok().filter(|s| !s.is_empty()) {
return PathBuf::from(dir);
}
#[cfg(windows)]
{
// Windows: %LOCALAPPDATA%\jr (e.g., C:\Users\Alice\AppData\Local\jr)
// BC-6.2.016: dirs::cache_dir() maps to %LOCALAPPDATA% (Local) on Windows.
// LOCALAPPDATA fallback filters empty string: unset and empty both route to ".".
dirs::cache_dir()
.unwrap_or_else(|| cache_localappdata_fallback(std::env::var("LOCALAPPDATA").ok()))
.join("jr")
}
#[cfg(not(windows))]
{
// Unix: $XDG_CACHE_HOME/jr or ~/.cache/jr (unchanged)
if let Ok(xdg) = std::env::var("XDG_CACHE_HOME") {
PathBuf::from(xdg).join("jr")
} else {
dirs::home_dir()
.unwrap_or_else(|| PathBuf::from("~"))
.join(".cache")
.join("jr")
}
}
}
/// Per-profile cache directory: `<cache_root>/v1/<profile>/`.
pub fn cache_dir(profile: &str) -> PathBuf {
cache_root().join("v1").join(profile)
}
/// Remove all cached data for a single profile. No-op if the directory does
/// not exist; other profiles are untouched.
pub fn clear_profile_cache(profile: &str) -> Result<()> {
let dir = cache_dir(profile);
if dir.exists() {
std::fs::remove_dir_all(dir)?;
}
Ok(())
}
pub fn read_team_cache(profile: &str) -> Result<Option<TeamCache>> {
read_cache(profile, "teams.json")
}
pub fn write_team_cache(profile: &str, teams: &[CachedTeam]) -> Result<()> {
write_cache(
profile,
"teams.json",
&TeamCache {
fetched_at: Utc::now(),
teams: teams.to_vec(),
},
)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectMeta {
pub project_type: String,
pub simplified: bool,
pub project_id: String,
pub service_desk_id: Option<String>,
pub fetched_at: DateTime<Utc>,
}
/// Read cached project metadata for a specific project key.
///
/// Keyed cache — not genericized because TTL is checked per-entry
/// (`ProjectMeta.fetched_at`), unlike whole-file caches.
pub fn read_project_meta(profile: &str, project_key: &str) -> Result<Option<ProjectMeta>> {
let path = cache_dir(profile).join("project_meta.json");
if !path.exists() {
return Ok(None);
}
let content = std::fs::read_to_string(&path)?;
let map: HashMap<String, ProjectMeta> = match serde_json::from_str(&content) {
Ok(m) => m,
Err(e) => {
eprintln!("warning: project_meta.json unreadable ({e}); will refetch");
return Ok(None);
}
};
match map.get(project_key) {
Some(meta) => {
let age = Utc::now() - meta.fetched_at;
if age.num_days() >= CACHE_TTL_DAYS {
Ok(None)
} else {
Ok(Some(meta.clone()))
}
}
None => Ok(None),
}
}
/// Write cached project metadata for a specific project key.
///
/// Merges into the existing map file, preserving entries for other projects.
pub fn write_project_meta(profile: &str, project_key: &str, meta: &ProjectMeta) -> Result<()> {
let dir = cache_dir(profile);
std::fs::create_dir_all(&dir)?;
let path = dir.join("project_meta.json");
// Read existing map or start fresh
let mut map: HashMap<String, ProjectMeta> = if path.exists() {
let content = std::fs::read_to_string(&path)?;
serde_json::from_str(&content).unwrap_or_else(|e| {
eprintln!(
"warning: project_meta.json unreadable ({e}); starting fresh — other cached projects will be lost"
);
HashMap::new()
})
} else {
HashMap::new()
};
map.insert(project_key.to_string(), meta.clone());
let content = serde_json::to_string_pretty(&map)?;
std::fs::write(&path, content)?;
Ok(())
}
/// Invalidate the cached project metadata for a specific project key.
///
/// Removes the entry for `project_key` from `project_meta.json` for the given
/// profile. Used by SEC-576-006 stale-ID self-heal: when
/// `attach_temporary_file` returns 404/403 with a cached `sdId`, the caller
/// invalidates this entry so `get_or_fetch_project_meta` does a fresh HTTP
/// fetch on the next call.
///
/// Model-b cache writer: disk errors are swallowed with a warning so a failed
/// invalidation never breaks the upload command. Returns `()` unconditionally.
pub fn invalidate_project_meta_cache(profile: &str, project_key: &str) {
let path = cache_dir(profile).join("project_meta.json");
if !path.exists() {
return;
}
let content = match std::fs::read_to_string(&path) {
Ok(c) => c,
Err(e) => {
eprintln!("warning: failed to invalidate project_meta cache for {project_key}: {e}");
return;
}
};
let mut map: HashMap<String, ProjectMeta> = match serde_json::from_str(&content) {
Ok(m) => m,
Err(e) => {
eprintln!("warning: failed to invalidate project_meta cache for {project_key}: {e}");
return;
}
};
if map.remove(project_key).is_none() {
return;
}
let new_content = match serde_json::to_string_pretty(&map) {
Ok(c) => c,
Err(e) => {
eprintln!("warning: failed to invalidate project_meta cache for {project_key}: {e}");
return;
}
};
if let Err(e) = std::fs::write(&path, new_content) {
eprintln!("warning: failed to invalidate project_meta cache for {project_key}: {e}");
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct WorkspaceCache {
pub workspace_id: String,
pub fetched_at: DateTime<Utc>,
}
impl Expiring for WorkspaceCache {
fn fetched_at(&self) -> DateTime<Utc> {
self.fetched_at
}
}
pub fn read_workspace_cache(profile: &str) -> Result<Option<WorkspaceCache>> {
read_cache(profile, "workspace.json")
}
pub fn write_workspace_cache(profile: &str, workspace_id: &str) -> Result<()> {
write_cache(
profile,
"workspace.json",
&WorkspaceCache {
workspace_id: workspace_id.to_string(),
fetched_at: Utc::now(),
},
)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CachedResolution {
pub id: String,
pub name: String,
#[serde(default)]
pub description: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ResolutionsCache {
pub resolutions: Vec<CachedResolution>,
pub fetched_at: DateTime<Utc>,
}
impl Expiring for ResolutionsCache {
fn fetched_at(&self) -> DateTime<Utc> {
self.fetched_at
}
}
pub fn read_resolutions_cache(profile: &str) -> Result<Option<ResolutionsCache>> {
read_cache(profile, "resolutions.json")
}
pub fn write_resolutions_cache(profile: &str, resolutions: &[CachedResolution]) -> Result<()> {
write_cache(
profile,
"resolutions.json",
&ResolutionsCache {
resolutions: resolutions.to_vec(),
fetched_at: Utc::now(),
},
)
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CmdbFieldsCache {
pub fields: Vec<(String, String)>,
pub fetched_at: DateTime<Utc>,
}
impl Expiring for CmdbFieldsCache {
fn fetched_at(&self) -> DateTime<Utc> {
self.fetched_at
}
}
pub fn read_cmdb_fields_cache(profile: &str) -> Result<Option<CmdbFieldsCache>> {
read_cache(profile, "cmdb_fields.json")
}
/// Best-effort writer: swallows disk-write errors with `eprintln!` and returns
/// `Ok(())`. A missed write costs at most one extra HTTP call on the next
/// invocation. Cache write failures MUST NOT break a successful API call.
///
/// Chosen model: (b) swallow + warn — this cache is a read-acceleration
/// shortcut, not a correctness-critical store. The call site in
/// `src/api/assets/linked.rs` does NOT use `let _ =`; errors are absorbed
/// inside this writer. Do not re-introduce `let _ =` or `?` at the call site.
pub fn write_cmdb_fields_cache(profile: &str, fields: &[(String, String)]) -> Result<()> {
let result = write_cache(
profile,
"cmdb_fields.json",
&CmdbFieldsCache {
fields: fields.to_vec(),
fetched_at: Utc::now(),
},
);
if let Err(e) = result {
eprintln!("warning: failed to write cmdb_fields cache: {e}");
}
Ok(())
}
/// Per-profile cache of `GET /rest/api/3/field` results (all Jira fields).
///
/// Mirrors `CmdbFieldsCache` exactly in struct layout and TTL behaviour.
/// Path: `~/.cache/jr/v1/<profile>/fields.json`. TTL: 7 days.
///
/// Content: `(id, name)` tuples — same tuple format as `CmdbFieldsCache`.
/// Old format (if ever changed) fails serde and self-heals as a cache miss;
/// no special migration needed. To break compatibility cleanly, bump the
/// cache root from `v1/` to `v2/` — old files orphan harmlessly.
#[derive(Debug, Serialize, Deserialize)]
pub struct FieldsCache {
pub fields: Vec<(String, String)>,
pub fetched_at: DateTime<Utc>,
}
impl Expiring for FieldsCache {
fn fetched_at(&self) -> DateTime<Utc> {
self.fetched_at
}
}
pub fn read_fields_cache(profile: &str) -> Result<Option<FieldsCache>> {
read_cache(profile, "fields.json")
}
/// Best-effort writer: swallows disk-write errors with `eprintln!` and returns
/// `Ok(())`. A missed write costs at most one extra HTTP call on the next
/// invocation. Cache write failures MUST NOT break a successful API call.
///
/// See "best-effort writer" pattern in CLAUDE.md Gotchas (request-type cache
/// writers). Chosen model: (b) swallow + warn — this cache is a read-
/// acceleration shortcut, not a correctness-critical store.
pub fn write_fields_cache(profile: &str, fields: &[(String, String)]) -> Result<()> {
let result = write_cache(
profile,
"fields.json",
&FieldsCache {
fields: fields.to_vec(),
fetched_at: Utc::now(),
},
);
if let Err(e) = result {
eprintln!("warning: failed to write fields cache: {e}");
}
Ok(())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CachedObjectTypeAttr {
pub id: String,
pub name: String,
#[serde(default)]
pub system: bool,
#[serde(default)]
pub hidden: bool,
#[serde(default)]
pub label: bool,
#[serde(default)]
pub position: i32,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ObjectTypeAttrCache {
pub fetched_at: DateTime<Utc>,
pub types: HashMap<String, Vec<CachedObjectTypeAttr>>,
}
/// Read cached attributes for a specific object type.
///
/// Keyed cache — not genericized because TTL is checked per-file
/// (`ObjectTypeAttrCache.fetched_at`) but lookup is per-key, with a different
/// return type (`Vec<CachedObjectTypeAttr>`) than the stored wrapper struct.
pub fn read_object_type_attr_cache(
profile: &str,
object_type_id: &str,
) -> Result<Option<Vec<CachedObjectTypeAttr>>> {
let path = cache_dir(profile).join("object_type_attrs.json");
if !path.exists() {
return Ok(None);
}
let content = std::fs::read_to_string(&path)?;
let cache: ObjectTypeAttrCache = match serde_json::from_str(&content) {
Ok(c) => c,
Err(e) => {
eprintln!("warning: object_type_attrs.json unreadable ({e}); will refetch");
return Ok(None);
}
};
let age = Utc::now() - cache.fetched_at;
if age.num_days() >= CACHE_TTL_DAYS {
return Ok(None);
}
Ok(cache.types.get(object_type_id).cloned())
}
/// Write cached attributes for a specific object type.
///
/// Merges into the existing map file, preserving entries for other object types.
///
/// Best-effort writer: swallows disk-write errors with `eprintln!` and returns
/// `Ok(())`. A missed write costs at most one extra HTTP call on the next
/// invocation. Cache write failures MUST NOT break a successful API call.
///
/// Chosen model: (b) swallow + warn — this cache is a read-acceleration
/// shortcut, not a correctness-critical store. The call site in
/// `src/api/assets/objects.rs` does NOT use `let _ =`; errors are absorbed
/// inside this writer. Do not re-introduce `let _ =` or `?` at the call site.
pub fn write_object_type_attr_cache(
profile: &str,
object_type_id: &str,
attrs: &[CachedObjectTypeAttr],
) -> Result<()> {
let result = (|| -> Result<()> {
let dir = cache_dir(profile);
std::fs::create_dir_all(&dir)?;
let path = dir.join("object_type_attrs.json");
let mut cache: ObjectTypeAttrCache = if path.exists() {
let content = std::fs::read_to_string(&path)?;
serde_json::from_str(&content).unwrap_or_else(|e| {
eprintln!(
"warning: object_type_attrs.json unreadable ({e}); starting fresh — other cached object types will be lost"
);
ObjectTypeAttrCache {
fetched_at: Utc::now(),
types: HashMap::new(),
}
})
} else {
ObjectTypeAttrCache {
fetched_at: Utc::now(),
types: HashMap::new(),
}
};
cache
.types
.insert(object_type_id.to_string(), attrs.to_vec());
cache.fetched_at = Utc::now();
let content = serde_json::to_string_pretty(&cache)?;
std::fs::write(&path, content)?;
Ok(())
})();
if let Err(e) = result {
eprintln!("warning: failed to write object_type_attrs cache: {e}");
}
Ok(())
}
/// Cached list of request types for a (profile, serviceDeskId) pair.
/// 7-day TTL. Cache file: ~/.cache/jr/v1/<profile>/request_types_<service_desk_id>.json
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct RequestTypeCache {
types: Vec<crate::types::jsm::RequestType>,
fetched_at: DateTime<Utc>,
}
impl Expiring for RequestTypeCache {
fn fetched_at(&self) -> DateTime<Utc> {
self.fetched_at
}
}
pub fn read_request_type_cache(
profile: &str,
service_desk_id: &str,
) -> Result<Option<Vec<crate::types::jsm::RequestType>>> {
debug_assert!(
service_desk_id
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-'),
"service_desk_id contains unsafe characters for filename: {service_desk_id:?}"
);
let filename = format!("request_types_{service_desk_id}.json");
Ok(read_cache::<RequestTypeCache>(profile, &filename)?.map(|c| c.types))
}
/// Write the request-type list to cache.
///
/// **Best-effort writer**: a `write_cache` failure (disk full, permission error)
/// is logged to stderr but does NOT propagate as an error. The contract is that
/// cache hygiene must never break a successful API call — at worst the next
/// invocation pays a cache miss.
///
/// (Diverges from `write_team_cache` / `write_workspace_cache` etc. which
/// propagate via `?`. Justified because the request-type cache is the first
/// cache where a write failure could leak a confusing exit code into a
/// scripted pipeline like `jr requesttype list --output json | jq ...`.)
pub fn write_request_type_cache(
profile: &str,
service_desk_id: &str,
types: &[crate::types::jsm::RequestType],
) -> Result<()> {
debug_assert!(
service_desk_id
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-'),
"service_desk_id contains unsafe characters for filename: {service_desk_id:?}"
);
let filename = format!("request_types_{service_desk_id}.json");
let result = write_cache(
profile,
&filename,
&RequestTypeCache {
types: types.to_vec(),
fetched_at: Utc::now(),
},
);
if let Err(e) = result {
eprintln!("warning: failed to write request type cache: {e}");
}
Ok(())
}
/// Cached fields for a specific request type within a service desk.
/// 7-day TTL. Cache file: ~/.cache/jr/v1/<profile>/request_type_fields_<service_desk_id>_<request_type_id>.json
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct RequestTypeFieldsCache {
response: crate::types::jsm::RequestTypeFieldsResponse,
fetched_at: DateTime<Utc>,
}
impl Expiring for RequestTypeFieldsCache {
fn fetched_at(&self) -> DateTime<Utc> {
self.fetched_at
}
}
pub fn read_request_type_fields_cache(
profile: &str,
service_desk_id: &str,
request_type_id: &str,
) -> Result<Option<crate::types::jsm::RequestTypeFieldsResponse>> {
debug_assert!(
service_desk_id
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-'),
"service_desk_id contains unsafe characters for filename: {service_desk_id:?}"
);
debug_assert!(
request_type_id
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-'),
"request_type_id contains unsafe characters for filename: {request_type_id:?}"
);
let filename = format!("request_type_fields_{service_desk_id}_{request_type_id}.json");
Ok(read_cache::<RequestTypeFieldsCache>(profile, &filename)?.map(|c| c.response))
}
/// Write the request-type fields response to cache.
///
/// **Best-effort writer**: a `write_cache` failure (disk full, permission error)
/// is logged to stderr but does NOT propagate as an error. The contract is that
/// cache hygiene must never break a successful API call — at worst the next
/// invocation pays a cache miss.
///
/// (Diverges from `write_team_cache` / `write_workspace_cache` etc. which
/// propagate via `?`. Justified because the request-type cache is the first
/// cache where a write failure could leak a confusing exit code into a
/// scripted pipeline like `jr requesttype fields <NAME> --output json | jq ...`.)
pub fn write_request_type_fields_cache(
profile: &str,
service_desk_id: &str,
request_type_id: &str,
response: &crate::types::jsm::RequestTypeFieldsResponse,
) -> Result<()> {
// SAFETY: JSM service desk IDs and request type IDs are documented as
// numeric strings (verified via Atlassian REST API v3 schema). The filename
// uses `_` as the delimiter; ambiguity would only arise if either ID
// contained `_`, which the Atlassian schema does not permit. If Atlassian
// ever changes IDs to non-numeric strings, switch to a structural delimiter
// (e.g., urlencoding both components) and bump the cache root to `v2/`.
// Charset constraint enforced by debug_assert! above (in debug builds).
debug_assert!(
service_desk_id
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-'),
"service_desk_id contains unsafe characters for filename: {service_desk_id:?}"
);
debug_assert!(
request_type_id
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-'),
"request_type_id contains unsafe characters for filename: {request_type_id:?}"
);
let filename = format!("request_type_fields_{service_desk_id}_{request_type_id}.json");
let result = write_cache(
profile,
&filename,
&RequestTypeFieldsCache {
response: response.clone(),
fetched_at: Utc::now(),
},
);
if let Err(e) = result {
eprintln!("warning: failed to write request type fields cache: {e}");
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
use tempfile::TempDir;
static ENV_MUTEX: Mutex<()> = Mutex::new(());
pub(super) fn with_temp_cache<F: FnOnce()>(f: F) {
// Recover from poison: catch_unwind below ensures env cleanup completed
// even if a prior test panicked, so the guarded state is consistent.
let guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
let dir = TempDir::new().unwrap();
// SAFETY: ENV_MUTEX serialises all tests that touch XDG_CACHE_HOME /
// JR_CACHE_DIR; the variables are only read inside cache functions called
// within this lock, so no concurrent env access occurs.
//
// JR_CACHE_DIR is the cross-platform debug seam (BC-6.2.017): on Windows,
// cache_root() uses %LOCALAPPDATA% and ignores XDG_CACHE_HOME, so we must
// also set JR_CACHE_DIR to dir/jr (matching what the XDG branch returns on
// Unix) to keep all platforms writing to the same tempdir.
unsafe {
std::env::set_var("XDG_CACHE_HOME", dir.path());
std::env::set_var("JR_CACHE_DIR", dir.path().join("jr"));
}
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
unsafe {
std::env::remove_var("XDG_CACHE_HOME");
std::env::remove_var("JR_CACHE_DIR");
}
drop(guard);
if let Err(e) = result {
std::panic::resume_unwind(e);
}
}
/// Set `var` to `value`, run `f`, then unconditionally remove `var` — even if
/// `f` panics. Mirrors `with_temp_cache` so BC-6.2.017 seam tests cannot leak
/// `JR_CACHE_DIR` / `JR_CONFIG_DIR` into subsequent tests on panic.
#[cfg(debug_assertions)]
pub(super) fn with_env_var<F: FnOnce() -> R, R>(var: &str, value: &str, f: F) -> R {
let guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
// SAFETY: ENV_MUTEX held; no concurrent env reads occur while we hold the lock.
unsafe { std::env::set_var(var, value) };
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
unsafe { std::env::remove_var(var) };
drop(guard);
match result {
Ok(v) => v,
Err(e) => std::panic::resume_unwind(e),
}
}
#[test]
fn cache_dir_includes_v1_and_profile_subdir() {
with_temp_cache(|| {
let dir = cache_dir("default");
assert!(dir.ends_with("v1/default"), "got: {}", dir.display());
});
}
#[test]
fn cross_profile_isolation_team_cache() {
with_temp_cache(|| {
write_team_cache(
"prod",
&[CachedTeam {
id: "t1".into(),
name: "Prod Team".into(),
}],
)
.unwrap();
let prod = read_team_cache("prod").unwrap().unwrap();
assert_eq!(prod.teams[0].name, "Prod Team");
assert!(read_team_cache("sandbox").unwrap().is_none());
});
}
#[test]
fn clear_profile_cache_removes_only_that_profile() {
with_temp_cache(|| {
write_team_cache(
"prod",
&[CachedTeam {
id: "p".into(),
name: "P".into(),
}],
)
.unwrap();
write_team_cache(
"sandbox",
&[CachedTeam {
id: "s".into(),
name: "S".into(),
}],
)
.unwrap();
clear_profile_cache("prod").unwrap();
assert!(
read_team_cache("prod").unwrap().is_none(),
"prod cache cleared"
);
assert!(
read_team_cache("sandbox").unwrap().is_some(),
"sandbox cache preserved"
);
});
}
#[test]
fn read_missing_cache_returns_none() {
with_temp_cache(|| {
let result = read_team_cache("default").unwrap();
assert!(result.is_none());
});
}
#[test]
fn write_then_read_returns_data() {
with_temp_cache(|| {
let teams = vec![
CachedTeam {
id: "uuid-1".into(),
name: "Alpha".into(),
},
CachedTeam {
id: "uuid-2".into(),
name: "Beta".into(),
},
];
write_team_cache("default", &teams).unwrap();
let cache = read_team_cache("default")
.unwrap()
.expect("cache should exist");
assert_eq!(cache.teams.len(), 2);
assert_eq!(cache.teams[0].name, "Alpha");
assert_eq!(cache.teams[1].name, "Beta");
});
}
#[test]
fn expired_cache_returns_none() {
with_temp_cache(|| {
let expired = TeamCache {
fetched_at: Utc::now() - chrono::Duration::days(8),
teams: vec![CachedTeam {
id: "uuid-1".into(),
name: "Old".into(),
}],
};
let dir = cache_dir("default");
std::fs::create_dir_all(&dir).unwrap();
let content = serde_json::to_string_pretty(&expired).unwrap();
std::fs::write(dir.join("teams.json"), content).unwrap();
let result = read_team_cache("default").unwrap();
assert!(result.is_none(), "expired cache should return None");
});
}
#[test]
fn valid_cache_within_ttl() {
with_temp_cache(|| {
let recent = TeamCache {
fetched_at: Utc::now() - chrono::Duration::days(3),
teams: vec![CachedTeam {
id: "uuid-1".into(),
name: "Recent".into(),
}],
};
let dir = cache_dir("default");
std::fs::create_dir_all(&dir).unwrap();
let content = serde_json::to_string_pretty(&recent).unwrap();
std::fs::write(dir.join("teams.json"), content).unwrap();
let cache = read_team_cache("default")
.unwrap()
.expect("cache should be valid");
assert_eq!(cache.teams.len(), 1);
assert_eq!(cache.teams[0].name, "Recent");
});
}
#[test]
fn read_missing_project_meta_returns_none() {
with_temp_cache(|| {
let result = read_project_meta("default", "NOEXIST").unwrap();
assert!(result.is_none());
});
}
#[test]
fn write_then_read_project_meta() {
with_temp_cache(|| {
let meta = ProjectMeta {
project_type: "service_desk".into(),
simplified: false,
project_id: "10042".into(),
service_desk_id: Some("15".into()),
fetched_at: Utc::now(),
};
write_project_meta("default", "HELPDESK", &meta).unwrap();
let loaded = read_project_meta("default", "HELPDESK")
.unwrap()
.expect("should exist");
assert_eq!(loaded.project_type, "service_desk");
assert_eq!(loaded.service_desk_id.as_deref(), Some("15"));
assert_eq!(loaded.project_id, "10042");
assert!(!loaded.simplified);
});
}
#[test]
fn expired_project_meta_returns_none() {
with_temp_cache(|| {
let meta = ProjectMeta {
project_type: "service_desk".into(),
simplified: false,
project_id: "10042".into(),
service_desk_id: Some("15".into()),
fetched_at: Utc::now() - chrono::Duration::days(8),
};
write_project_meta("default", "HELPDESK", &meta).unwrap();
let result = read_project_meta("default", "HELPDESK").unwrap();
assert!(result.is_none(), "expired project meta should return None");
});
}
#[test]
fn project_meta_multiple_projects() {
with_temp_cache(|| {
let jsm = ProjectMeta {
project_type: "service_desk".into(),
simplified: false,
project_id: "10042".into(),
service_desk_id: Some("15".into()),
fetched_at: Utc::now(),
};
let software = ProjectMeta {
project_type: "software".into(),
simplified: true,
project_id: "10001".into(),
service_desk_id: None,
fetched_at: Utc::now(),
};
write_project_meta("default", "HELPDESK", &jsm).unwrap();
write_project_meta("default", "DEV", &software).unwrap();
let jsm_loaded = read_project_meta("default", "HELPDESK")
.unwrap()
.expect("should exist");
assert_eq!(jsm_loaded.project_type, "service_desk");
let sw_loaded = read_project_meta("default", "DEV")
.unwrap()
.expect("should exist");
assert_eq!(sw_loaded.project_type, "software");
assert!(sw_loaded.service_desk_id.is_none());
});
}
#[test]
fn read_missing_workspace_cache_returns_none() {
with_temp_cache(|| {
let result = read_workspace_cache("default").unwrap();
assert!(result.is_none());
});
}
#[test]
fn write_then_read_workspace_cache() {
with_temp_cache(|| {
write_workspace_cache("default", "abc-123-def").unwrap();
let cache = read_workspace_cache("default")
.unwrap()
.expect("should exist");
assert_eq!(cache.workspace_id, "abc-123-def");
});
}
#[test]
fn expired_workspace_cache_returns_none() {
with_temp_cache(|| {
let expired = WorkspaceCache {
workspace_id: "old-id".into(),
fetched_at: Utc::now() - chrono::Duration::days(8),
};
let dir = cache_dir("default");
std::fs::create_dir_all(&dir).unwrap();
let content = serde_json::to_string_pretty(&expired).unwrap();
std::fs::write(dir.join("workspace.json"), content).unwrap();
let result = read_workspace_cache("default").unwrap();
assert!(
result.is_none(),
"expired workspace cache should return None"
);
});
}
#[test]
fn read_missing_cmdb_fields_cache_returns_none() {
with_temp_cache(|| {
let result = read_cmdb_fields_cache("default").unwrap();
assert!(result.is_none());
});
}
#[test]
fn write_then_read_cmdb_fields_cache() {
with_temp_cache(|| {
write_cmdb_fields_cache(
"default",
&[
("customfield_10191".into(), "Client".into()),
("customfield_10245".into(), "Hardware".into()),
],
)
.unwrap();
let cache = read_cmdb_fields_cache("default")
.unwrap()
.expect("should exist");
assert_eq!(
cache.fields,
vec![
("customfield_10191".to_string(), "Client".to_string()),