Repository navigation
Expand file tree
/
Copy pathretention.rs
More file actions
1482 lines (1384 loc) · 51.8 KB
/
Copy pathretention.rs
File metadata and controls
1482 lines (1384 loc) · 51.8 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
//! Keeps the captures folder from growing forever.
//!
//! A bundle's prompt (`summary.md`, `scrawl.json`, `contact-sheet.png`, `frames/`) is small; its
//! video, audio and full-size frames are nearly all of its size. After `mediaDays` the heavy
//! media (and the `zoom/` sheets made from it) goes to the Trash and the prompt stays; after
//! `bundleDays` the whole bundle goes. Both live under `"retention"` in `~/.config/scrawl/config.json` (`null` keeps forever). A bundle
//! younger than a day or changed within the last day, one whose media is still copying
//! (`.media-pending`, `.media-sending`), one Scrawl is working on, a pinned one (`.pinned`), one
//! still waiting to reach OpenCode (`.deliver.json`), and one `scrawl recover` hasn't built yet
//! are never touched.
//!
//! Cabled-iPhone videos are also re-encoded to HEVC at the size keyframes use (`shrink`), which
//! makes them about ten times smaller.
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
#[cfg(not(windows))]
use std::process::Command;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result, ensure};
use serde::{Deserialize, Serialize};
use crate::log::scrawl_log;
/// Marks a bundle to keep forever.
pub const PINNED: &str = ".pinned";
/// Present on this Mac while a bundle's heavy media streams to another one.
pub const MEDIA_SENDING: &str = ".media-sending";
/// Written when the heavy media went to the Trash: when, and after how many days.
pub const MEDIA_CLEANED: &str = ".media-cleaned";
/// Where media waits, beside the bundles, while it moves to the Trash.
const STAGING: &str = ".trash-staging";
const DAY_MS: u64 = 24 * 60 * 60 * 1000;
/// A sync marker older than this belongs to a copy that died.
const STALE_MARKER: Duration = Duration::from_secs(24 * 60 * 60);
/// Long edge iPhone video is re-encoded to: the size its keyframes are decoded at.
const SHRINK_EDGE: u32 = crate::phone::PHONE_FRAME_EDGE;
/// Videos above this rate are worth re-encoding (native iPhone mirror video is ~18 Mbps; a
/// shrunk one ~2).
const SHRINK_ABOVE_BPS: u64 = 6_000_000;
/// How long after a capture its video is shrunk, so pasting and sending go first.
const SHRINK_DELAY: Duration = Duration::from_secs(60);
/// The daily shrink sweep picks up bundles left alone this long (a capture whose shrink was
/// missed, or one copied from another Mac).
const SHRINK_SETTLE_MS: u64 = 10 * 60 * 1000;
/// How often cleanup runs. Hourly, so media goes within an hour of `mediaDays`, not a day late.
const PASS_EVERY: Duration = Duration::from_secs(3600);
/// How often a pass also re-encodes missed iPhone videos (each try can take a while).
const SHRINK_EVERY: Duration = Duration::from_secs(24 * 3600);
/// Made from the heavy media (`scrawl zoom` sheets and frame ranges), so it goes with it.
const DERIVED_MEDIA: [&str; 1] = ["zoom"];
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Policy {
/// Days to keep video, audio and full-size frames; `None` keeps them.
#[serde(default = "default_media_days")]
pub media_days: Option<u32>,
/// Days to keep the bundle itself; `None` keeps it.
#[serde(default = "default_bundle_days")]
pub bundle_days: Option<u32>,
}
fn default_media_days() -> Option<u32> {
Some(7)
}
fn default_bundle_days() -> Option<u32> {
Some(30)
}
impl Default for Policy {
fn default() -> Self {
Preset::Week.policy()
}
}
/// The choices in the menu bar's Keep Recordings menu.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Preset {
Week,
Month,
Forever,
}
impl Preset {
pub const ALL: [Self; 3] = [Self::Week, Self::Month, Self::Forever];
pub fn label(self) -> &'static str {
match self {
Self::Week => "Video for 7 Days",
Self::Month => "Video for 30 Days",
Self::Forever => "Forever",
}
}
pub fn policy(self) -> Policy {
let (media_days, bundle_days) = match self {
Self::Week => (Some(7), Some(30)),
Self::Month => (Some(30), Some(90)),
Self::Forever => (None, None),
};
Policy {
media_days,
bundle_days,
}
}
}
impl Policy {
pub fn preset(&self) -> Option<Preset> {
Preset::ALL.into_iter().find(|p| p.policy() == *self)
}
pub fn load() -> Self {
Self::load_from(&crate::handoff::default_config_path())
}
pub fn load_in(config: &crate::handoff::EngineConfig, path: &Path) -> Self {
let _ = config;
Self::load_from(path)
}
pub fn load_from(path: &Path) -> Self {
std::fs::read(path)
.ok()
.and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
.and_then(|config| config.get("retention").cloned())
.and_then(|value| serde_json::from_value(value).ok())
.unwrap_or_default()
}
/// Writes `"retention"`, keeping the rest of the config (and its `0600` mode) as it is.
pub fn save_to(&self, path: &Path) -> Result<()> {
crate::handoff::set_config_value_in(path, "retention", serde_json::to_value(self)?)
}
}
// MARK: What Scrawl is busy with
static BUSY: Mutex<BTreeSet<PathBuf>> = Mutex::new(BTreeSet::new());
static RECORDING: AtomicUsize = AtomicUsize::new(0);
/// Holds a bundle out of cleanup while Scrawl works on it.
pub struct Claim(PathBuf);
/// Claims `dir` unless something else already has.
pub fn claim(dir: &Path) -> Option<Claim> {
let key = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
let inserted = BUSY
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(key.clone());
// Built after the lock is released: a refused `Claim` would unlock on drop.
inserted.then(|| Claim(key))
}
fn is_claimed(dir: &Path) -> bool {
let key = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
BUSY.lock()
.unwrap_or_else(|e| e.into_inner())
.contains(&key)
}
impl Drop for Claim {
fn drop(&mut self) {
BUSY.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&self.0);
}
}
/// Held by a running capture; cleanup and re-encoding wait until none is.
pub struct Recording(());
impl Recording {
pub fn start() -> Self {
RECORDING.fetch_add(1, Ordering::AcqRel);
Self(())
}
}
impl Drop for Recording {
fn drop(&mut self) {
RECORDING.fetch_sub(1, Ordering::AcqRel);
}
}
fn recording() -> bool {
RECORDING.load(Ordering::Acquire) > 0
}
// MARK: Planning
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Manifest {
#[serde(default)]
created_at_ms: Option<u64>,
#[serde(default)]
duration_ms: u64,
#[serde(default)]
video: Option<String>,
#[serde(default)]
source: Option<String>,
#[serde(default)]
device: Option<ManifestDevice>,
}
#[derive(Debug, Default, Deserialize)]
struct ManifestDevice {
#[serde(default)]
capture: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Action {
/// Move these heavy files out of the bundle and into the Trash.
TrashMedia {
bundle: PathBuf,
items: Vec<PathBuf>,
},
/// Move the whole bundle to the Trash.
TrashBundle(PathBuf),
/// Re-encode the bundle's iPhone video.
Shrink { bundle: PathBuf, video: PathBuf },
}
fn modified_ago(path: &Path, now: SystemTime) -> Option<Duration> {
let modified = path.metadata().ok()?.modified().ok()?;
Some(now.duration_since(modified).unwrap_or_default())
}
/// When anything last changed in the folder itself: an entry added, removed or renamed (a copy
/// arriving, a zoom, a re-encode). Uses the change time, which `tar` can't backdate.
#[cfg(unix)]
fn changed_ago(path: &Path, now: SystemTime) -> Option<Duration> {
use std::os::unix::fs::MetadataExt;
let meta = path.metadata().ok()?;
let changed = UNIX_EPOCH + Duration::new(meta.ctime().max(0) as u64, meta.ctime_nsec() as u32);
Some(now.duration_since(changed).unwrap_or_default())
}
/// NTFS's change time for the folder (`ChangeTime`), which moves when an entry is added, removed
/// or renamed, like the Unix ctime.
#[cfg(windows)]
fn changed_ago(path: &Path, now: SystemTime) -> Option<Duration> {
let changed =
crate::win::shell::change_time(path).or_else(|| path.metadata().ok()?.modified().ok())?;
Some(now.duration_since(changed).unwrap_or_default())
}
/// A sync marker that is recent enough to mean a copy is still running.
fn live_marker(dir: &Path, name: &str, now: SystemTime) -> bool {
modified_ago(&dir.join(name), now).is_some_and(|ago| ago < STALE_MARKER)
}
fn created_ms(dir: &Path, manifest: &Manifest) -> Option<u64> {
manifest.created_at_ms.or_else(|| {
// `scrawl-<ms>-…`
let name = dir.file_stem()?.to_str()?;
name.strip_prefix("scrawl-")?
.split('-')
.next()?
.parse()
.ok()
})
}
/// What one cleanup pass would do to the bundles in `captures`, given `now`.
pub fn plan(captures: &Path, policy: &Policy, now: SystemTime) -> Vec<Action> {
plan_packages(captures, policy, now, false)
}
fn plan_packages(captures: &Path, policy: &Policy, now: SystemTime, hex: bool) -> Vec<Action> {
let now_ms = now
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64;
let Ok(entries) = std::fs::read_dir(captures) else {
return Vec::new();
};
let mut bundles: Vec<PathBuf> = entries
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| {
p.extension().is_some_and(|ext| {
ext == if hex {
crate::bundle::EXTENSION
} else {
"scrawl"
}
}) && std::fs::symlink_metadata(p).is_ok_and(|m| m.is_dir())
})
.collect();
bundles.sort();
let mut actions = Vec::new();
for dir in bundles {
if dir.join(PINNED).exists()
|| dir.join(crate::delivery::PENDING).exists()
|| is_claimed(&dir)
|| (!hex && crate::recover::owed(&dir))
|| live_marker(&dir, crate::handoff::MEDIA_PENDING, now)
|| live_marker(&dir, MEDIA_SENDING, now)
{
continue;
}
let manifest: Manifest = if hex {
// Neither the directory's age nor a partial/future manifest gives Hex ownership.
let Ok(b) = crate::bundle::read_manifest(&dir) else {
continue;
};
Manifest {
created_at_ms: Some(b.created_at_ms),
..Default::default()
}
} else {
std::fs::read(dir.join("scrawl.json"))
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or_default()
};
let Some(created) = created_ms(&dir, &manifest).or_else(|| {
let ago = modified_ago(&dir, now)?;
Some(now_ms.saturating_sub(ago.as_millis() as u64))
}) else {
continue;
};
let age_ms = now_ms.saturating_sub(created);
let unchanged_ms = changed_ago(&dir, now).map_or(0, |ago| ago.as_millis() as u64);
let settled = |ms: u64| age_ms >= ms && unchanged_ms >= ms;
if !settled(SHRINK_SETTLE_MS) {
continue;
}
if !settled(DAY_MS) {
if let Some(video) = shrinkable(&dir, &manifest) {
actions.push(Action::Shrink { bundle: dir, video });
}
continue;
}
let due = |days: Option<u32>| days.is_some_and(|d| age_ms >= u64::from(d.max(1)) * DAY_MS);
if due(policy.bundle_days) {
actions.push(Action::TrashBundle(dir));
continue;
}
if due(policy.media_days) {
let items: Vec<PathBuf> = crate::handoff::HEAVY_MEDIA
.iter()
.chain(&DERIVED_MEDIA)
// A capture that crashed mid-recording leaves its streamed audio here.
.chain(std::iter::once(&crate::recover::PARTIAL_AUDIO))
.map(|rel| dir.join(rel))
.filter(|p| p.exists())
.collect();
if !items.is_empty() {
actions.push(Action::TrashMedia { bundle: dir, items });
}
continue;
}
if let Some(video) = shrinkable(&dir, &manifest) {
actions.push(Action::Shrink { bundle: dir, video });
}
}
actions
}
/// A cabled-iPhone video recorded at native size and rate.
fn shrinkable(dir: &Path, manifest: &Manifest) -> Option<PathBuf> {
if manifest.source.as_deref() != Some("iphone")
|| manifest
.device
.as_ref()
.is_none_or(|d| d.capture != "mirror")
|| manifest.duration_ms == 0
{
return None;
}
let video = dir.join(manifest.video.as_deref()?);
let bytes = video.metadata().ok()?.len();
let bps = bytes.saturating_mul(8_000) / manifest.duration_ms;
(bps > SHRINK_ABOVE_BPS).then_some(video)
}
// MARK: Doing it
/// Moves `path` to the Trash.
pub type Trasher<'a> = &'a dyn Fn(&Path) -> Result<()>;
#[cfg(windows)]
pub fn trash(path: &Path) -> Result<()> {
crate::win::shell::recycle(path)?;
ensure!(
!path.exists(),
"Could not move {} to the Recycle Bin",
path.display()
);
Ok(())
}
#[cfg(not(windows))]
pub fn trash(path: &Path) -> Result<()> {
let output = Command::new("/usr/bin/trash")
.arg(path)
.output()
.context("Could not run /usr/bin/trash")?;
ensure!(
output.status.success() && !path.exists(),
"Could not move {} to the Trash: {}",
path.display(),
String::from_utf8_lossy(&output.stderr).trim()
);
Ok(())
}
fn size_of(path: &Path) -> u64 {
let Ok(meta) = std::fs::symlink_metadata(path) else {
return 0;
};
if meta.is_dir() {
std::fs::read_dir(path)
.map(|entries| {
entries
.filter_map(Result::ok)
.map(|e| size_of(&e.path()))
.sum()
})
.unwrap_or(0)
} else {
meta.len()
}
}
/// Everything in the captures folder, in bytes.
pub fn captures_size(captures: &Path) -> u64 {
size_of(captures)
}
pub fn format_bytes(bytes: u64) -> String {
const MB: f64 = 1_000_000.0;
let mb = bytes as f64 / MB;
if mb >= 1000.0 {
format!("{:.1} GB", mb / 1000.0)
} else {
format!("{mb:.0} MB")
}
}
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Report {
pub media_trashed: usize,
pub bundles_trashed: usize,
pub freed: u64,
pub shrunk: usize,
pub errors: usize,
}
/// Puts a bundle's heavy media in the Trash as one folder named after the bundle, so it reads
/// (and restores) as a unit, then notes the cleanup in the bundle. The note is written only
/// once the folder reaches the Trash; anything that doesn't gets back to the bundle, so a
/// missing or failing trasher can't lose it.
fn trash_media(bundle: &Path, items: &[PathBuf], days: u32, trasher: Trasher) -> Result<u64> {
let name = bundle
.file_stem()
.context("Bundle has no name")?
.to_string_lossy();
let staging_root = bundle.parent().context("Bundle has no parent")?.join(
if crate::bundle::manifest_name(bundle) == Some(crate::bundle::MANIFEST) {
".hex-annotation-staging"
} else {
STAGING
},
);
let staging = staging_root.join(format!("{name} media"));
// A folder left by an earlier attempt (an interrupted pass, or a trasher that failed) holds
// media that must not be deleted: stage beside it and put everything back if this fails.
std::fs::create_dir_all(&staging)?;
let result = stage_and_trash(bundle, items, days, &staging, trasher);
if result.is_err() {
restore_staged(&staging, bundle);
let _ = std::fs::remove_dir(&staging);
}
let _ = std::fs::remove_dir(&staging_root);
result
}
/// Moves `items` into `staging`, sends the folder to the Trash, and only then marks the bundle
/// cleaned.
fn stage_and_trash(
bundle: &Path,
items: &[PathBuf],
days: u32,
staging: &Path,
trasher: Trasher,
) -> Result<u64> {
let mut freed = 0;
let mut moved = Vec::new();
for item in items {
let Some(file) = item.file_name() else {
continue;
};
let destination = staging.join(file);
ensure!(
!destination.exists(),
"{} is already staged for the Trash",
destination.display()
);
freed += size_of(item);
std::fs::rename(item, &destination)
.with_context(|| format!("Could not stage {}", item.display()))?;
moved.push(file.to_string_lossy().into_owned());
}
trasher(staging)?;
let note = serde_json::json!({
"cleanedAtMs": crate::pipeline::now_epoch_ms(),
"afterDays": days,
"trashed": moved,
});
std::fs::write(
bundle.join(MEDIA_CLEANED),
serde_json::to_vec_pretty(¬e)?,
)?;
Ok(freed)
}
/// The bundle name a staged folder belongs to: `<stem> media` is `<stem>`'s.
fn staged_stem(staging: &Path) -> Option<String> {
let name = staging.file_name()?.to_string_lossy();
name.strip_suffix(" media").map(str::to_owned)
}
/// Moves everything in `staging` back into `bundle`, never over an existing entry. Whatever
/// can't be put back stays in `staging`; returns how many entries came back.
fn restore_staged(staging: &Path, bundle: &Path) -> usize {
let Ok(entries) = std::fs::read_dir(staging) else {
return 0;
};
let mut restored = 0;
for entry in entries.filter_map(|entry| entry.ok()) {
let destination = bundle.join(entry.file_name());
if destination.exists() {
continue;
}
if std::fs::rename(entry.path(), &destination).is_ok() {
restored += 1;
}
}
restored
}
/// Puts media left in `<captures>/.trash-staging` back into its bundle, so a failed or
/// interrupted cleanup never strands the bundle's video outside it and a stale
/// `.media-cleaned` never claims it is gone. Staging whose bundle is gone goes to the Trash.
fn recover_staged_media(captures: &Path, trasher: Trasher, now: SystemTime) -> usize {
recover_staging(captures, trasher, now, false)
}
fn recover_staging(captures: &Path, trasher: Trasher, now: SystemTime, hex: bool) -> usize {
let root = captures.join(if hex {
".hex-annotation-staging"
} else {
STAGING
});
if !std::fs::symlink_metadata(&root).is_ok_and(|m| m.is_dir()) {
return 0;
}
let Ok(entries) = std::fs::read_dir(&root) else {
return 0;
};
let mut staged: Vec<PathBuf> = entries
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
.filter(|path| std::fs::symlink_metadata(path).is_ok_and(|m| m.is_dir()))
.collect();
staged.sort();
let mut restored = 0;
for staging in staged {
let Some(stem) = staged_stem(&staging) else {
continue;
};
let ext = if hex {
crate::bundle::EXTENSION
} else {
"scrawl"
};
let bundle = captures.join(format!("{stem}.{ext}"));
if hex && bundle.exists() && crate::bundle::read_manifest(&bundle).is_err() {
continue;
}
if bundle.is_dir() {
let Some(_claim) = claim(&bundle) else {
continue;
};
if live_marker(&bundle, crate::handoff::MEDIA_PENDING, now)
|| live_marker(&bundle, MEDIA_SENDING, now)
{
continue;
}
let count = restore_staged(&staging, &bundle);
if count > 0 {
let _ = std::fs::remove_file(bundle.join(MEDIA_CLEANED));
restored += count;
}
} else if !bundle.exists()
&& let Err(error) = trasher(&staging)
{
scrawl_log(format!(
"retention: staged media for {} kept: {error:#}",
bundle.display()
));
continue;
}
let _ = std::fs::remove_dir(&staging);
}
let _ = std::fs::remove_dir(&root);
restored
}
/// Runs a plan. Each step is checked again just before it runs, in case a capture or a copy
/// started meanwhile.
pub fn apply(actions: &[Action], policy: &Policy, trasher: Trasher, shrink: bool) -> Report {
let mut report = Report::default();
for action in actions {
let bundle = match action {
Action::TrashMedia { bundle, .. }
| Action::TrashBundle(bundle)
| Action::Shrink { bundle, .. } => bundle,
};
let Some(_claim) = claim(bundle) else {
continue;
};
let now = SystemTime::now();
if live_marker(bundle, crate::handoff::MEDIA_PENDING, now)
|| live_marker(bundle, MEDIA_SENDING, now)
|| bundle.join(PINNED).exists()
|| bundle.join(crate::delivery::PENDING).exists()
{
continue;
}
let result = match action {
Action::TrashMedia { bundle, items } => {
trash_media(bundle, items, policy.media_days.unwrap_or(0), trasher).map(|freed| {
report.media_trashed += 1;
report.freed += freed;
})
}
Action::TrashBundle(bundle) => {
let size = size_of(bundle);
trasher(bundle).map(|()| {
report.bundles_trashed += 1;
report.freed += size;
})
}
Action::Shrink { bundle, video } if shrink => {
if recording() {
continue;
}
shrink_video(bundle, video).map(|shrunk| {
if let Some(s) = shrunk {
report.shrunk += 1;
report.freed += s.before.saturating_sub(s.after);
}
})
}
Action::Shrink { .. } => Ok(()),
};
if let Err(error) = result {
report.errors += 1;
scrawl_log(format!("retention: {}: {error:#}", bundle.display()));
}
}
report
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Shrunk {
pub before: u64,
pub after: u64,
pub width: u32,
pub height: u32,
pub ms: u64,
}
/// Re-encodes `video` (inside `bundle`) to HEVC at the keyframe size with the same timeline,
/// then swaps it in. The new movie is written beside the bundle, not in it, so a copy to
/// another Mac never picks up half of it. `None` when it was already small.
pub fn shrink_video(bundle: &Path, video: &Path) -> Result<Option<Shrunk>> {
let probe = crate::helper::probe(video)?;
if probe.width.max(probe.height) <= SHRINK_EDGE * 115 / 100 {
return Ok(None);
}
let name = bundle
.file_stem()
.context("Bundle has no name")?
.to_string_lossy();
let tmp = bundle
.parent()
.context("Bundle has no parent")?
.join(format!(".{name}.shrinking.mov"));
let result = crate::helper::shrink(video, &tmp, SHRINK_EDGE);
let shrunk = match result {
Ok(s) if s.after > 0 && s.after < s.before => s,
Ok(s) => {
let _ = std::fs::remove_file(&tmp);
scrawl_log(format!(
"shrink: {} kept ({} → {} bytes)",
video.display(),
s.before,
s.after
));
return Ok(None);
}
Err(e) => {
let _ = std::fs::remove_file(&tmp);
return Err(e);
}
};
// A sync that started while encoding streams the original; let it finish with that.
let now = SystemTime::now();
if live_marker(bundle, MEDIA_SENDING, now)
|| live_marker(bundle, crate::handoff::MEDIA_PENDING, now)
{
let _ = std::fs::remove_file(&tmp);
anyhow::bail!("its media started copying while it was being shrunk");
}
std::fs::rename(&tmp, video)?;
scrawl_log(format!(
"shrink: {} {} → {} ({}×{}, {:.1} s)",
video.display(),
format_bytes(shrunk.before),
format_bytes(shrunk.after),
shrunk.width,
shrunk.height,
shrunk.ms as f64 / 1000.0
));
Ok(Some(shrunk))
}
/// Removes what a crash mid-cleanup or mid-shrink left beside the bundles.
fn sweep_leftovers(captures: &Path, now: SystemTime) {
let Ok(entries) = std::fs::read_dir(captures) else {
return;
};
for path in entries.filter_map(|e| e.ok().map(|e| e.path())) {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let leftover = name.ends_with(".shrinking.mov");
if leftover
&& modified_ago(&path, now).is_some_and(|ago| ago > Duration::from_secs(6 * 3600))
{
let _ = std::fs::remove_dir_all(&path).or_else(|_| std::fs::remove_file(&path));
}
}
}
/// One cleanup pass over `captures`, planned as if `ahead` from now (for trying it out).
/// Without `shrink` it only trashes, so a video that doesn't get smaller isn't re-encoded hourly.
pub fn run_pass(
captures: &Path,
policy: &Policy,
dry_run: bool,
ahead: Duration,
shrink: bool,
trasher: Trasher,
) -> (Vec<Action>, Report) {
let now = SystemTime::now();
// Before planning: media a failed or interrupted cleanup staged goes back, so its bundle
// can be cleaned again and a stale note never claims it is gone.
if !dry_run {
recover_staged_media(captures, trasher, now);
}
let mut actions = plan(captures, policy, now + ahead);
if !shrink {
actions.retain(|a| !matches!(a, Action::Shrink { .. }));
}
if dry_run {
return (actions, Report::default());
}
sweep_leftovers(captures, now);
let report = apply(&actions, policy, trasher, true);
if report != Report::default() {
scrawl_log(format!(
"retention: media of {} bundle(s) and {} whole bundle(s) to the Trash, {} video(s) shrunk, {} freed, {} error(s)",
report.media_trashed,
report.bundles_trashed,
report.shrunk,
format_bytes(report.freed),
report.errors
));
}
(actions, report)
}
/// Hex never consumes the legacy staging area, loose files, or .scrawl
/// bundles in a shared root. A full, supported manifest is required.
pub fn clean_annotations(root: &Path, policy: &Policy, trash: Trasher) -> Report {
let now = SystemTime::now();
recover_staging(root, trash, now, true);
apply(
&plan_packages(root, policy, now, true),
policy,
trash,
false,
)
}
/// Why a bundle's video is gone, for errors that need it.
pub fn missing_media_reason(dir: &Path) -> Option<String> {
let note: serde_json::Value =
serde_json::from_slice(&std::fs::read(dir.join(MEDIA_CLEANED)).ok()?).ok()?;
let days = note
.get("afterDays")
.and_then(serde_json::Value::as_u64)
.unwrap_or(0);
Some(if days > 0 {
format!(
"The bundle's video was cleaned up after {days} days and is in the Trash \
(Scrawl menu › Keep Recordings sets how long video is kept)"
)
} else {
"The bundle's video was cleaned up and is in the Trash".to_owned()
})
}
// MARK: Background worker
enum Job {
Pass,
Shrink(PathBuf),
}
pub const MAX_RETENTION_JOBS: usize = 64;
static WORKER: std::sync::OnceLock<flume::Sender<Job>> = std::sync::OnceLock::new();
static DROPPED_JOBS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
pub fn dropped_jobs() -> usize {
DROPPED_JOBS.load(Ordering::Acquire)
}
fn lower_priority() {
// SAFETY: only changes the calling thread's scheduling class.
#[cfg(target_os = "macos")]
unsafe {
libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_UTILITY, 0);
}
#[cfg(windows)]
crate::win::shell::background_thread();
}
/// Starts the app's cleanup: a pass shortly after launch, then hourly, plus shrinking each
/// iPhone capture a minute after it's made.
pub fn start() {
if WORKER.get().is_some() {
return;
}
let (sender, receiver) = flume::bounded(MAX_RETENTION_JOBS);
if WORKER.set(sender).is_err() {
return;
}
let _ = std::thread::Builder::new()
.name("scrawl-retention".into())
.spawn(move || worker(&receiver));
}
fn try_enqueue(sender: &flume::Sender<Job>, job: Job, dropped: &std::sync::atomic::AtomicUsize) {
if sender.try_send(job).is_err() {
dropped.fetch_add(1, Ordering::AcqRel);
}
}
/// Runs a pass soon, after the policy changed.
pub fn nudge() {
if let Some(worker) = WORKER.get() {
try_enqueue(worker, Job::Pass, &DROPPED_JOBS);
}
}
/// Queues a just-finished iPhone capture for shrinking (only in the app).
pub fn after_phone_capture(bundle: &Path) {
if let Some(worker) = WORKER.get() {
try_enqueue(worker, Job::Shrink(bundle.to_path_buf()), &DROPPED_JOBS);
}
}
fn worker(jobs: &flume::Receiver<Job>) {
lower_priority();
let captures = crate::handoff::default_captures_dir();
let mut next_pass = Instant::now() + Duration::from_secs(90);
let mut last_pass: Option<SystemTime> = None;
let mut last_shrink: Option<SystemTime> = None;
let mut shrinks: Vec<(Instant, Instant, PathBuf)> = Vec::new();
loop {
let now = Instant::now();
let wake = shrinks
.iter()
.map(|(due, _, _)| *due)
.chain([next_pass])
.min()
.unwrap_or(next_pass);
match jobs.recv_timeout(
wake.saturating_duration_since(now)
.min(Duration::from_secs(3600)),
) {
Ok(Job::Pass) => next_pass = Instant::now() + Duration::from_secs(5),
Ok(Job::Shrink(dir)) => {
let due = Instant::now() + SHRINK_DELAY;
shrinks.push((due, due + Duration::from_secs(2 * 3600), dir));
}
Err(flume::RecvTimeoutError::Timeout) => {}
Err(flume::RecvTimeoutError::Disconnected) => return,
}
let now = Instant::now();
let mut later = Vec::new();
for (due, give_up, dir) in shrinks.drain(..) {
if due > now {
later.push((due, give_up, dir));
continue;
}
match shrink_now(&dir) {
// Busy: a capture is running or the media is still copying. Try again soon; a
// later pass catches anything that gives up.
Err(()) if now < give_up => {
later.push((now + Duration::from_secs(30), give_up, dir))
}
_ => {}
}
}
shrinks = later;
// The Mac sleeps through `Instant`s, so passes also go by the wall clock.
let pass_due = last_pass.is_none_or(|at| {
SystemTime::now().duration_since(at).unwrap_or_default() >= PASS_EVERY
});
if Instant::now() >= next_pass || (last_pass.is_some() && pass_due) {
if recording() {
next_pass = Instant::now() + Duration::from_secs(60);
continue;
}
let policy = Policy::load();
let shrink = last_shrink.is_none_or(|at| {
SystemTime::now().duration_since(at).unwrap_or_default() >= SHRINK_EVERY
});
let (actions, report) =
run_pass(&captures, &policy, false, Duration::ZERO, shrink, &trash);
if shrink {
last_shrink = Some(SystemTime::now());
}
// Hourly passes that find nothing stay out of the log after the first.
if last_pass.is_none() || !actions.is_empty() {
scrawl_log(format!(
"retention: pass over {} ({} action(s), policy {:?}/{:?} days), {} now",
captures.display(),
actions.len(),
policy.media_days,
policy.bundle_days,
format_bytes(captures_size(&captures)),
));
}
let _ = report;
last_pass = Some(SystemTime::now());
next_pass = Instant::now() + PASS_EVERY;
}
}
}
/// `Err` when the bundle is busy and should be retried.
fn shrink_now(dir: &Path) -> std::result::Result<(), ()> {
let now = SystemTime::now();
if recording()
|| live_marker(dir, crate::handoff::MEDIA_PENDING, now)
|| live_marker(dir, MEDIA_SENDING, now)
{
return Err(());
}
let Some(_claim) = claim(dir) else {
return Err(());
};
let manifest: Manifest = match std::fs::read(dir.join("scrawl.json"))
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
{
Some(m) => m,
None => return Ok(()),
};
if dir.join(PINNED).exists() {
return Ok(());
}
if let Some(video) = shrinkable(dir, &manifest)
&& let Err(error) = shrink_video(dir, &video)
{
scrawl_log(format!("shrink: {}: {error:#}", dir.display()));
}
Ok(())
}
#[cfg(test)]