Repository navigation
Expand file tree
/
Copy pathpersistence.rs
More file actions
299 lines (278 loc) · 11.1 KB
/
Copy pathpersistence.rs
File metadata and controls
299 lines (278 loc) · 11.1 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
//! Settings recovery is in memory. The first write preserves unreadable bytes
//! beside the original, including when a migration is the first writer.
use std::borrow::Cow;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use color_eyre::eyre::{Result, eyre};
use serde::Deserialize;
use serde_json::Value;
use serde_path_to_error::Segment;
use sha2::{Digest, Sha256};
use super::AppSettings;
use crate::policy::Policy;
// A settings editor and a background migration may save at the same time.
static WRITER: Mutex<()> = Mutex::new(());
impl AppSettings {
/// Launch stays available even when the data folder itself cannot be
/// resolved. Invalid settings are recovered by `load_from` in place.
pub fn load_for_launch() -> (Self, Option<String>) {
match Self::load() {
Ok(settings) => (settings, None),
Err(error) => {
tracing::error!(error = format!("{error:#}"), "could not load settings");
(
Self::default(),
Some(format!(
"Hex couldn't read its settings and started with defaults. ({error:#})"
)),
)
}
}
}
pub(crate) fn load_from(path: &Path) -> Result<Self> {
let (settings, migrated) = Self::read_from(path)?;
if migrated && let Err(error) = settings.write_to(path) {
tracing::warn!(%error, "could not persist normalized settings");
}
Ok(settings)
}
/// What `load_from` loads, without writing anything back: true when
/// `load_from` would persist a migration. Switches a managed lock holds
/// read off (`crate::policy`).
pub(crate) fn read_from(path: &Path) -> Result<(Self, bool)> {
Self::read_managed_from(path, Policy::current())
}
pub(super) fn read_managed_from(path: &Path, policy: Policy) -> Result<(Self, bool)> {
let (mut settings, migrated) = Self::read_saved_from(path)?;
policy.enforce(&mut settings);
Ok((settings, migrated))
}
fn read_saved_from(path: &Path) -> Result<(Self, bool)> {
let data = match fs::read(path) {
Ok(data) => data,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Ok((Self::default(), false));
}
Err(error) => {
tracing::warn!(path = %path.display(), %error, "could not read settings; using defaults without changing the file");
return Ok((Self::default(), false));
}
};
let (mut settings, mut repaired) = decode(&data);
let loaded = serde_json::to_value(&settings)?;
let hints = legacy_recognition_hints(&data);
if let Err(error) = settings.validate_recording_duck_volume() {
warn("recording_duck_volume", &error.to_string());
settings.recording_duck_volume = Self::default().recording_duck_volume;
repaired = true;
}
settings.dictation_processing.default_mode.name = "Global".into();
settings.repair_bare_primary_clicks();
#[cfg(target_os = "macos")]
settings.repair_mouse_shortcuts();
#[cfg(target_os = "linux")]
settings.repair_special_keys();
#[cfg(target_os = "linux")]
settings.repair_section_key();
settings.normalize_double_tap_settings();
settings.migrate_legacy_replacements();
settings.normalize_mode_application_names();
settings.migrate_disabled_transcription_model();
for hints in &hints {
crate::dictation::vocabulary::fold_hints(&mut settings.vocabulary, hints);
}
settings.apply_one_time_migrations();
settings.normalize_transcription_recents();
settings
.keyboard_model_switching
.mappings
.retain(|_, choice| choice.validate().is_ok());
// A saved import that can't run stays saved (`validate_saved`).
if let Err(error) = crate::transcription::models::validate_saved(&settings.transcription) {
warn("transcription", &error.to_string());
settings.transcription = Self::default().transcription;
repaired = true;
}
// A repair alone never rewrites the user's file. Ordinary migrations
// keep their existing write-on-load behavior for healthy settings.
let migrated =
!repaired && (!hints.is_empty() || serde_json::to_value(&settings)? != loaded);
Ok((settings, migrated))
}
pub(super) fn write_to(&self, path: &Path) -> Result<()> {
self.write_managed_to(path, Policy::current())
}
pub(super) fn write_managed_to(&self, path: &Path, policy: Policy) -> Result<()> {
self.validate_recording_duck_volume()?;
let _writer = WRITER.lock().unwrap_or_else(|error| error.into_inner());
let parent = path
.parent()
.ok_or_else(|| eyre!("settings path has no parent"))?;
fs::create_dir_all(parent)?;
let original = match fs::read(path) {
Ok(original) => {
if needs_backup(&original) {
backup(path, &original)?;
}
Some(original)
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
#[cfg(target_os = "macos")]
crate::desktop::onboarding::record_pending_at(parent)?;
None
}
// Never overwrite something we could not read and preserve.
Err(error) => return Err(error.into()),
};
let bytes = serde_json::to_vec_pretty(&*self.as_saved(policy, original.as_deref()))?;
crate::durable::write(path, &bytes)?;
Ok(())
}
/// What a save writes: these settings, with the switches a managed lock
/// holds off kept as the file (`saved`) has them.
fn as_saved(&self, policy: Policy, saved: Option<&[u8]>) -> Cow<'_, Self> {
if !policy.any() {
return Cow::Borrowed(self);
}
let saved = saved.map_or_else(Self::default, |data| decode(data).0);
let mut written = self.clone();
policy.keep_saved(&mut written, &saved);
Cow::Owned(written)
}
}
fn warn(key: &str, reason: &str) {
tracing::warn!(key, reason, "invalid setting; using its default in memory");
}
/// Recognition hints saved before they merged into the vocabulary: the
/// selected model's, then the recent models' from newest.
fn legacy_recognition_hints(data: &[u8]) -> Vec<String> {
#[derive(Default, Deserialize)]
#[serde(default)]
struct Selection {
recognition_hints: String,
}
#[derive(Default, Deserialize)]
#[serde(default)]
struct File {
transcription: Selection,
transcription_recents: Vec<Selection>,
}
let Ok(file) = serde_json::from_slice::<File>(data) else {
return Vec::new();
};
std::iter::once(file.transcription)
.chain(file.transcription_recents.into_iter().rev())
.map(|selection| selection.recognition_hints)
.filter(|hints| !hints.trim().is_empty())
.collect()
}
fn decode(data: &[u8]) -> (AppSettings, bool) {
let mut value: Value = match serde_json::from_slice(data) {
Ok(Value::Object(object)) => Value::Object(object),
Ok(_) => {
warn("$", "settings must be a JSON object");
return (AppSettings::default(), true);
}
Err(error) => {
warn("$", &error.to_string());
return (AppSettings::default(), true);
}
};
let mut repaired = false;
loop {
match serde_path_to_error::deserialize::<_, AppSettings>(&value) {
Ok(settings) => return (settings, repaired),
Err(error) => {
let path: Vec<_> = error.path().iter().collect();
warn(&error.path().to_string(), &error.inner().to_string());
// Deleting a field invokes its actual serde default, including
// section-specific defaults. A malformed list/map entry with
// required fields is removed as a unit on the next attempt.
if !remove(&mut value, &path) {
return (AppSettings::default(), true);
}
repaired = true;
}
}
}
}
/// Remove the deepest existing part of an error path. Each failed attempt
/// strictly shrinks the input; missing required fields cannot loop forever.
fn remove(value: &mut Value, path: &[&Segment]) -> bool {
let Some((first, rest)) = path.split_first() else {
return false;
};
match (value, first) {
(Value::Object(object), Segment::Map { key }) => {
if let Some(child) = object.get_mut(key)
&& remove(child, rest)
{
return true;
}
object.remove(key).is_some()
}
(Value::Array(array), Segment::Seq { index }) if *index < array.len() => {
if !remove(&mut array[*index], rest) {
array.remove(*index);
}
true
}
_ => false,
}
}
fn needs_backup(data: &[u8]) -> bool {
if !serde_json::from_slice::<Value>(data).is_ok_and(|value| value.is_object()) {
return true;
}
let Ok(settings) = serde_json::from_slice::<AppSettings>(data) else {
return true;
};
settings.validate_recording_duck_volume().is_err()
|| crate::transcription::models::validate_saved(&settings.transcription).is_err()
}
#[cfg(hex_capture)]
pub(super) fn healthy_file(path: &Path) -> bool {
fs::read(path).is_ok_and(|data| !needs_backup(&data))
}
fn backup_path(path: &Path, data: &[u8]) -> PathBuf {
let mut name = path.file_name().unwrap_or_default().to_os_string();
// Content-addressing also deduplicates a retry after a failed save or a
// process crash between the backup and the settings replacement.
let digest: String = Sha256::digest(data)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect();
name.push(format!(".unreadable-{digest}"));
path.with_file_name(name)
}
fn backup(path: &Path, data: &[u8]) -> Result<()> {
let backup = backup_path(path, data);
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
match options.open(&backup) {
Ok(mut file) => {
file.write_all(data)?;
file.sync_all()?;
}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
// A partial or replaced backup is not permission to lose data.
if fs::read(&backup)? != data {
return Err(eyre!("settings backup is incomplete: {}", backup.display()));
}
crate::durable::sync_file(&backup)?;
}
Err(error) => return Err(error.into()),
}
crate::durable::sync_directory(path.parent().unwrap_or(Path::new(".")))?;
tracing::warn!(path = %backup.display(), "preserved original settings before saving repaired settings");
Ok(())
}
#[cfg(test)]
mod tests;