1use std::{collections::BTreeMap, fmt};
2
3macro_rules! codes {
5 ($($variant:ident => ($code:literal, $exit:literal)),+ $(,)?) => {
6 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
7 pub enum ErrorCode { $($variant),+ }
8 impl ErrorCode {
9 pub const ALL: &'static [Self] = &[$(Self::$variant),+];
10 pub fn exit_code(self) -> i32 { match self { $(Self::$variant => $exit),+ } }
11 pub fn as_str(self) -> &'static str { match self { $(Self::$variant => $code),+ } }
12 }
13 }
14}
15
16codes! {
17 PodcastFailed => ("podcast_failed", 1),
18 SubtitleSettings => ("subtitle_settings", 1),
19 SubtitleModel => ("subtitle_model", 1),
20 SubtitleIntegrity => ("subtitle_integrity", 1),
21 SubtitleRuntime => ("subtitle_runtime", 1),
22 SubtitlePlatform => ("subtitle_platform", 1),
23 SubtitleSpace => ("subtitle_space", 1),
24 SubtitleBusy => ("subtitle_busy", 1),
25 SubtitleFailed => ("subtitle_failed", 1),
26 UsageError => ("usage_error", 2),
27 InvalidUrl => ("invalid_url", 1),
28 MediaBusy => ("media_busy", 4),
29 StationNotFound => ("station_not_found", 1),
30 InvalidStation => ("invalid_station", 1),
31 InvalidUuid => ("invalid_uuid", 2),
32 DatabaseTooNew => ("database_too_new", 1),
33 Cancelled => ("cancelled", 1),
34 EmptyCatalog => ("empty_catalog", 1),
35 NoDirectoryServers => ("no_directory_servers", 1),
36 DirectoryRequest => ("directory_request", 1),
37 DirectoryResponseTooLarge => ("directory_response_too_large", 1),
38 InvalidPagination => ("invalid_pagination", 1),
39 CatalogTooLarge => ("catalog_too_large", 1),
40 CatalogShrink => ("catalog_shrink", 1),
41 DirectorySync => ("directory_sync", 1),
42 DataDirectory => ("data_directory", 1),
43 InvalidConfig => ("invalid_config", 1),
44 ReadConfig => ("read_config", 1),
45 InvalidSettings => ("invalid_settings", 1),
46 UnsupportedCodec => ("unsupported_codec", 1),
47 FinalPathMissing => ("final_path_missing", 1),
48 RecordingPublish => ("recording_publish", 1),
49 RecordingSizeMismatch => ("recording_size_mismatch", 1),
50 NoAudio => ("no_audio", 1),
51 MissingDependency => ("missing_dependency", 3),
52 InvalidDuration => ("invalid_duration", 2),
53 DurationUnit => ("duration_unit", 2),
54 DurationOverflow => ("duration_overflow", 2),
55 DurationRange => ("duration_range", 2),
56 NoStream => ("no_stream", 1),
57 RandomDisabled => ("random_disabled", 1),
58 NoMatchingStation => ("no_matching_station", 1),
59 NotPlaying => ("not_playing", 1),
60 WaitForPlayback => ("wait_for_playback", 1),
61 RecordingBusy => ("recording_busy", 1),
62 NoRecordingStream => ("no_recording_stream", 1),
63 RecordingSourcesFailed => ("recording_sources_failed", 1),
64 RuntimePathTooLong => ("runtime_path_too_long", 1),
65 PlayerStartup => ("player_startup", 1),
66 AudioDeviceFailed => ("audio_device_failed", 1),
67 AudioDevicesUnavailable => ("audio_devices_unavailable", 1),
68 NormalizationUnavailable => ("normalization_unavailable", 1),
69 PlayerClosed => ("player_closed", 1),
70 PlayerMessageTooLarge => ("player_message_too_large", 1),
71 PlayerExited => ("player_exited", 1),
72 ProcessTimeout => ("process_timeout", 1),
73 ArtworkHandoffTimeout => ("artwork_handoff_timeout", 1),
74 ProcessFailed => ("process_failed", 1),
75 BackgroundFailed => ("background_failed", 1),
76 EmptyStationName => ("empty_station_name", 2),
77 DuplicateStation => ("duplicate_station", 1),
78 NotCustom => ("not_custom", 1),
79 RecordingNotFound => ("recording_not_found", 1),
80 RecordingInUse => ("recording_in_use", 1),
81 InsufficientSpace => ("insufficient_space", 1),
82 LocalRecording => ("local_recording", 1),
83 EphemeralRecording => ("ephemeral_recording", 1),
84}
85
86#[derive(Debug, Clone)]
87pub struct DomainError {
88 pub code: ErrorCode,
89 pub params: BTreeMap<String, String>,
90}
91
92impl DomainError {
93 pub fn new(code: ErrorCode) -> Self {
94 Self {
95 code,
96 params: BTreeMap::new(),
97 }
98 }
99 pub fn with(mut self, key: &str, value: impl ToString) -> Self {
100 self.params.insert(key.into(), value.to_string());
101 self
102 }
103}
104impl fmt::Display for DomainError {
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 let template = crate::messages::text(self.code.as_str());
107 if self.params.is_empty() {
108 return f.write_str(template);
109 }
110 let params: Vec<(&str, String)> = self
111 .params
112 .iter()
113 .map(|(k, v)| (k.as_str(), v.clone()))
114 .collect();
115 f.write_str(&crate::messages::format_text(template, ¶ms))
116 }
117}
118
119pub(crate) fn check_cancelled(stop: &std::sync::atomic::AtomicBool) -> anyhow::Result<()> {
120 if stop.load(std::sync::atomic::Ordering::Relaxed) {
121 anyhow::bail!(DomainError::new(ErrorCode::Cancelled));
122 }
123 Ok(())
124}
125impl std::error::Error for DomainError {}
126
127pub fn exit_code(error: &anyhow::Error) -> i32 {
128 error
129 .downcast_ref::<DomainError>()
130 .map_or(1, |e| e.code.exit_code())
131}
132
133pub fn json_error(error: &anyhow::Error) -> serde_json::Value {
134 let domain = error.downcast_ref::<DomainError>();
135 serde_json::json!({"ok":false,"error":{
136 "code":domain.map(|e| e.code.as_str()).unwrap_or("general_error"),
137 "message":crate::clean_text(&format!("{error:#}")),
138 "params":domain.map(|e| e.params.clone()).unwrap_or_default()
139 }})
140}
141
142#[cfg(test)]
143mod tests {
144 use super::*;
145 #[test]
146 fn domain_exit_classes_are_explicit() {
147 for (code, expected) in [
148 (ErrorCode::UsageError, 2),
149 (ErrorCode::InvalidDuration, 2),
150 (ErrorCode::DurationRange, 2),
151 (ErrorCode::MissingDependency, 3),
152 (ErrorCode::MediaBusy, 4),
153 (ErrorCode::InvalidSettings, 1),
154 (ErrorCode::StationNotFound, 1),
155 ] {
156 assert_eq!(exit_code(&DomainError::new(code).into()), expected);
157 }
158 assert_eq!(exit_code(&anyhow::anyhow!("I/O")), 1);
159 }
160
161 #[test]
162 fn runtime_path_too_long_reports_the_offending_path() {
163 let error = DomainError::new(ErrorCode::RuntimePathTooLong)
164 .with("path", "/deep/dir/run/mpv-abc.sock");
165 assert!(error.to_string().contains("/deep/dir/run/mpv-abc.sock"));
166 }
167}