1use crate::error::{DomainError, ErrorCode};
2use crate::{
3 USER_AGENT,
4 config::{Config, validate_url},
5 model::{Recording, Station},
6 process,
7 store::Store,
8};
9use anyhow::{Context, Result, bail};
10use serde_json::Value;
11use std::{
12 fs::{self, OpenOptions},
13 io::{BufRead, BufReader},
14 path::{Path, PathBuf},
15 process::{Child, Command, Stdio},
16 sync::{
17 Arc,
18 atomic::{AtomicBool, AtomicU64, Ordering},
19 },
20 thread,
21 time::{Duration, Instant},
22};
23
24pub struct Recorder {
25 pub space_estimated: bool,
26 child: Child,
27 pub record: Recording,
28 partial: PathBuf,
29 deadline: Option<Instant>,
30 target_duration: Option<Duration>,
31 ended_without_stop: bool,
32 timed_out: bool,
33 progress: Arc<AtomicU64>,
34 duration_ms: u64,
35 readers: Vec<thread::JoinHandle<()>>,
36 errors: Arc<std::sync::Mutex<String>>,
37 reconnects: Arc<AtomicU64>,
38 finished: bool,
39 stop_requested: bool,
40}
41
42pub struct RecordingMetadata<'a> {
43 pub station: &'a Station,
44 pub track: Option<&'a str>,
45}
46
47fn filename_component(text: &str, max_chars: usize, max_bytes: usize) -> String {
48 let mut result = String::new();
49 for c in text
50 .chars()
51 .filter(|c| c.is_alphanumeric() || *c == '-' || *c == '_')
52 .take(max_chars)
53 {
54 if result.len() + c.len_utf8() > max_bytes {
55 break;
56 }
57 result.push(c);
58 }
59 result
60}
61
62fn track_filename_component(text: &str, max_bytes: usize) -> String {
63 let words: Vec<_> = text
64 .split_whitespace()
65 .map(|word| filename_component(word, 40, max_bytes))
66 .filter(|word| !word.is_empty())
67 .collect();
68 filename_component(&words.join("_"), 40, max_bytes)
69}
70
71const ERROR_TAIL_BYTES: usize = 8192;
72
73fn recording_progress(line: &str) -> bool {
74 line.split_once('=').is_some_and(|(key, _)| {
75 matches!(
76 key,
77 "frame"
78 | "fps"
79 | "bitrate"
80 | "total_size"
81 | "out_time_us"
82 | "out_time_ms"
83 | "out_time"
84 | "dup_frames"
85 | "drop_frames"
86 | "speed"
87 | "progress"
88 )
89 })
90}
91
92fn append_error_tail(text: &mut String, line: &str) {
93 text.extend(
95 line.chars()
96 .filter(|c| !c.is_control() || *c == '\n' || *c == '\t'),
97 );
98 let mut start = text.len().saturating_sub(ERROR_TAIL_BYTES);
99 while !text.is_char_boundary(start) {
100 start += 1;
101 }
102 if start > 0 {
103 text.drain(..start);
104 }
105}
106
107pub fn probe(config: &Config, url: &str, stop: &Arc<AtomicBool>) -> Result<Value> {
108 probe_with_timeout(
109 config,
110 url,
111 stop,
112 Duration::from_secs(config.settings.probe_timeout_secs),
113 )
114}
115
116fn probe_with_timeout(
117 config: &Config,
118 url: &str,
119 stop: &Arc<AtomicBool>,
120 timeout: Duration,
121) -> Result<Value> {
122 let data = process::output(
123 Command::new(&config.settings.ffprobe).args([
124 "-v",
125 "error",
126 "-rw_timeout",
127 "5000000",
128 "-analyzeduration",
129 "1000000",
130 "-probesize",
131 "262144",
132 "-user_agent",
133 USER_AGENT,
134 "-select_streams",
135 "a:0",
136 "-show_entries",
137 "stream=codec_name,bit_rate:format=duration,bit_rate",
138 "-of",
139 "json",
140 "-i",
141 url,
142 ]),
143 timeout,
144 stop,
145 )?;
146 Ok(serde_json::from_slice(&data)?)
147}
148
149pub fn format_for_codec(codec: &str) -> Result<(&'static str, &'static str)> {
150 match codec {
151 "mp3" => Ok(("mp3", "mp3")),
152 "aac" => Ok(("aac", "adts")),
153 "vorbis" => Ok(("ogg", "ogg")),
154 "opus" => Ok(("opus", "opus")),
155 _ => bail!(DomainError::new(ErrorCode::UnsupportedCodec).with("codec", codec)),
156 }
157}
158
159pub fn sidecar(record: &Recording) -> Result<()> {
160 let path = PathBuf::from(format!("{}.json", record.path));
161 let temp = PathBuf::from(format!("{}.tmp", path.display()));
162 fs::write(&temp, serde_json::to_vec_pretty(record)?)?;
163 fs::rename(temp, path)?;
164 Ok(())
165}
166
167fn publish(partial: &Path, final_path: &Path) -> Result<()> {
169 #[cfg(target_os = "linux")]
170 let publication = {
171 use std::{ffi::CString, os::unix::ffi::OsStrExt};
172 let from = CString::new(partial.as_os_str().as_bytes())?;
173 let to = CString::new(final_path.as_os_str().as_bytes())?;
174 let result = unsafe {
175 libc::syscall(
177 libc::SYS_renameat2,
178 libc::AT_FDCWD,
179 from.as_ptr(),
180 libc::AT_FDCWD,
181 to.as_ptr(),
182 libc::RENAME_NOREPLACE,
183 )
184 };
185 if result == 0 {
186 Ok(())
187 } else {
188 Err(std::io::Error::last_os_error())
189 }
190 };
191 #[cfg(not(target_os = "linux"))]
192 let publication = fs::hard_link(partial, final_path);
193
194 if let Err(error) = publication {
195 if error.kind() != std::io::ErrorKind::AlreadyExists {
196 return Err(error.into());
197 }
198 use std::os::unix::fs::MetadataExt;
199 let source = fs::symlink_metadata(partial)?;
200 let target = fs::symlink_metadata(final_path)?;
201 if partial == final_path
205 || !source.is_file()
206 || !target.is_file()
207 || source.dev() != target.dev()
208 || source.ino() != target.ino()
209 {
210 return Err(error.into());
211 }
212 fs::remove_file(partial)?;
213 return Ok(());
214 }
215 #[cfg(not(target_os = "linux"))]
216 fs::remove_file(partial)?;
217 Ok(())
218}
219
220fn complete_finalization(store: &Store, record: &mut Recording) -> Result<()> {
221 let partial = PathBuf::from(&record.path);
222 let final_path = PathBuf::from(
223 record
224 .final_path
225 .as_ref()
226 .context(DomainError::new(ErrorCode::FinalPathMissing))?,
227 );
228 if partial.exists() {
229 publish(&partial, &final_path).with_context(|| {
230 DomainError::new(ErrorCode::RecordingPublish)
231 .with("id", &record.id)
232 .with("path", partial.display())
233 .with("final_path", final_path.display())
234 })?;
235 }
236 let size = fs::metadata(&final_path)?.len();
237 if size != record.size_bytes || size == 0 {
238 bail!(DomainError::new(ErrorCode::RecordingSizeMismatch));
239 }
240 let mut complete = record.clone();
241 complete.path = final_path.to_string_lossy().into();
242 complete.status = "complete".into();
243 complete.error = None;
244 complete.recovery_pending = false;
245 sidecar(&complete)?;
247 store.save_recording(&complete)?;
248 let _ = fs::remove_file(format!("{}.json", partial.display()));
249 *record = complete;
250 Ok(())
251}
252
253pub fn recover(store: &Store) -> Result<Vec<String>> {
254 let mut warnings = Vec::new();
255 for mut r in store.unfinished_recordings()? {
256 let result = (|| -> Result<()> {
257 if r.status == "finalizing" {
258 return complete_finalization(store, &mut r);
259 }
260 if r.status == "recording" {
261 r.status = "interrupted".into();
262 r.stopped_at = Some(chrono::Utc::now().to_rfc3339());
263 r.error = Some("上一个会话未正常结束;保留临时文件供恢复".into());
264 r.size_bytes = fs::metadata(&r.path).map(|m| m.len()).unwrap_or(0);
265 r.recovery_pending = true;
266 store.save_recording(&r)?;
267 }
268 let retry = r.recovery_pending;
269 if retry {
270 r.error = Some(
271 if Path::new(&r.path).exists() {
272 "上一个会话未正常结束;临时文件保留,元数据已恢复"
273 } else {
274 "上一个会话未正常结束;音频文件缺失,元数据已恢复"
275 }
276 .into(),
277 );
278 }
279 r.recovery_pending = false;
280 sidecar(&r)?;
281 if retry {
282 store.save_recording(&r)?;
283 }
284 Ok(())
285 })();
286 if let Err(error) = result {
287 let message = format!(
288 "恢复失败: 录音 {} ({}):{error:#};使用 recordings recover 重试",
289 r.id, r.path
290 );
291 r.error = Some(message.clone());
292 r.recovery_pending = true;
293 if let Err(db_error) = store.save_recording(&r) {
294 warnings.push(format!("{message};数据库: {db_error:#}"));
295 } else {
296 warnings.push(message);
297 }
298 }
299 }
300 Ok(warnings)
301}
302
303fn required_space(
306 reserve_mb: u64,
307 station_kbps: u32,
308 info: &Value,
309 duration: Option<Duration>,
310) -> (u64, bool) {
311 let positive = |v: &Value| {
312 v.as_str()
313 .and_then(|v| v.parse::<u64>().ok())
314 .or_else(|| v.as_u64())
315 .filter(|v| *v > 0)
316 };
317 let bitrate = positive(&info["streams"][0]["bit_rate"])
318 .or_else(|| positive(&info["format"]["bit_rate"]))
319 .or_else(|| (station_kbps > 0).then_some(u64::from(station_kbps) * 1000));
320 let reserve = reserve_mb.saturating_mul(1024 * 1024);
321 match (duration, bitrate) {
322 (Some(duration), Some(bitrate)) => {
323 let bytes = u128::from(bitrate).saturating_mul(duration.as_nanos());
324 let bytes = bytes.div_ceil(8_000_000_000).min(u128::from(u64::MAX)) as u64;
325 (reserve.saturating_add(bytes), true)
326 }
327 (None, _) | (_, None) => (reserve, false),
328 }
329}
330
331impl Recorder {
332 pub fn start(
333 config: &Config,
334 store: &Store,
335 station: &Station,
336 url: &str,
337 dir: &Path,
338 duration: Option<Duration>,
339 stop: &Arc<AtomicBool>,
340 ) -> Result<Self> {
341 validate_url(url)?;
342 let info = probe(config, url, stop)?;
343 Self::start_with_info(config, store, station, url, dir, duration, info)
344 }
345
346 pub fn start_with_info(
347 config: &Config,
348 store: &Store,
349 station: &Station,
350 url: &str,
351 dir: &Path,
352 duration: Option<Duration>,
353 info: Value,
354 ) -> Result<Self> {
355 Self::start_with_metadata(
356 config,
357 store,
358 RecordingMetadata {
359 station,
360 track: None,
361 },
362 url,
363 dir,
364 duration,
365 info,
366 )
367 }
368
369 pub fn start_with_metadata(
370 config: &Config,
371 store: &Store,
372 metadata: RecordingMetadata<'_>,
373 url: &str,
374 dir: &Path,
375 duration: Option<Duration>,
376 info: Value,
377 ) -> Result<Self> {
378 let station = metadata.station;
379 let track = metadata
380 .track
381 .map(crate::clean_text)
382 .map(|title| title.trim().to_owned())
383 .filter(|title| !title.is_empty());
384 validate_url(url)?;
385 let codec = info["streams"][0]["codec_name"]
386 .as_str()
387 .context(DomainError::new(ErrorCode::NoAudio))?
388 .to_owned();
389 let (extension, muxer) = format_for_codec(&codec)?;
390 let dir = std::path::absolute(dir)?;
391 let (required, space_estimated) = required_space(
392 config.settings.recording_min_free_mb,
393 station.bitrate,
394 &info,
395 duration,
396 );
397 let mut ancestor = dir.as_path();
400 loop {
401 match fs::metadata(ancestor) {
402 Ok(_) => break,
403 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
404 ancestor = ancestor
405 .parent()
406 .context(DomainError::new(ErrorCode::FinalPathMissing))?;
407 }
408 Err(error) => return Err(error.into()),
409 }
410 }
411 let available = fs2::available_space(ancestor)?;
412 if available < required {
413 bail!(
414 DomainError::new(ErrorCode::InsufficientSpace)
415 .with("available", available)
416 .with("required", required)
417 );
418 }
419 fs::create_dir_all(&dir)?;
420 let dir = fs::canonicalize(dir)?;
421 let id = uuid::Uuid::new_v4().to_string();
422 let name = filename_component(&station.name, 60, 180);
425 let track_name = track_filename_component(track.as_deref().unwrap_or(""), 200 - name.len());
426 let label = if track_name.is_empty() {
427 name
428 } else {
429 format!("{name}-{track_name}")
430 };
431 let base = format!(
432 "{}-{}-{}",
433 chrono::Local::now().format("%Y%m%d-%H%M%S"),
434 label,
435 &id[..8]
436 );
437 let final_path = dir.join(format!("{base}.{extension}"));
438 let partial = dir.join(format!("{base}.{extension}.part"));
439 let file = OpenOptions::new()
440 .write(true)
441 .create_new(true)
442 .open(&partial)?;
443 let mut command = Command::new(&config.settings.ffmpeg);
444 command.args([
445 "-hide_banner",
446 "-loglevel",
447 "warning",
448 "-nostats",
449 "-rw_timeout",
450 "12000000",
451 "-reconnect",
456 "1",
457 "-reconnect_streamed",
458 "1",
459 "-reconnect_delay_max",
460 "2",
461 "-analyzeduration",
462 "1000000",
463 "-probesize",
464 "262144",
465 "-user_agent",
466 USER_AGENT,
467 "-i",
468 url,
469 "-map",
470 "0:a:0",
471 "-c:a",
472 "copy",
473 ]);
474 if let Some(duration) = duration {
475 command.arg("-t").arg(duration.as_secs_f64().to_string());
476 }
477 command.args(["-progress", "pipe:2", "-f", muxer, "pipe:1"]);
478 command
480 .stdin(Stdio::piped())
481 .stdout(Stdio::from(file))
482 .stderr(Stdio::piped());
483 let child_result = process::spawn_owned(command);
484 let mut child = match child_result {
485 Ok(child) => child,
486 Err(e) => {
487 let _ = fs::remove_file(&partial);
488 return Err(e).context(
489 DomainError::new(ErrorCode::MissingDependency).with("program", "ffmpeg"),
490 );
491 }
492 };
493 let progress = Arc::new(AtomicU64::new(0));
494 let latest = progress.clone();
495 let errors = Arc::new(std::sync::Mutex::new(String::new()));
496 let target = errors.clone();
497 let reconnects = Arc::new(AtomicU64::new(0));
498 let retry_count = reconnects.clone();
499 let stderr = child.stderr.take().unwrap();
500 let reader = thread::spawn(move || {
501 let mut input = BufReader::new(stderr);
502 let mut line = String::new();
503 loop {
504 line.clear();
505 match input.read_line(&mut line) {
506 Ok(0) | Err(_) => break,
507 _ => {}
508 }
509 if let Some(value) = line.trim().strip_prefix("out_time_us=") {
510 if let Ok(value) = value.parse::<u64>() {
511 latest.fetch_max(value / 1000, Ordering::Relaxed);
512 }
513 } else if !recording_progress(line.trim()) {
514 if line.contains("Will reconnect at") || line.contains("Failed to open segment")
520 {
521 retry_count.fetch_add(1, Ordering::Relaxed);
522 }
523 let mut text = target.lock().unwrap();
524 append_error_tail(&mut text, &line);
525 }
526 }
527 });
528 let record = Recording {
529 id,
530 stationuuid: station.stationuuid.clone(),
531 station_name: station.name.clone(),
532 track,
533 source_url_resolved: url.into(),
534 started_at: chrono::Utc::now().to_rfc3339(),
535 stopped_at: None,
536 media_duration_ms: None,
537 codec,
538 container: muxer.into(),
539 path: partial.to_string_lossy().into(),
540 final_path: Some(final_path.to_string_lossy().into()),
541 size_bytes: 0,
542 status: "recording".into(),
543 error: None,
544 reconnects: 0,
545 recovery_pending: false,
546 };
547 let recorder = Self {
548 space_estimated,
549 child,
550 record,
551 partial,
552 deadline: duration.map(|d| {
553 Instant::now() + d + Duration::from_secs(config.settings.playback_timeout_secs)
554 }),
555 target_duration: duration,
556 ended_without_stop: false,
557 timed_out: false,
558 progress,
559 duration_ms: 0,
560 readers: vec![reader],
561 errors,
562 reconnects,
563 finished: false,
564 stop_requested: false,
565 };
566 store.save_recording(&recorder.record)?;
567 sidecar(&recorder.record)?;
568 Ok(recorder)
569 }
570
571 pub fn poll(&mut self) -> Result<bool> {
572 self.duration_ms = self.progress.load(Ordering::Relaxed);
573 self.ended_without_stop = self.child.try_wait()?.is_some();
574 self.timed_out =
575 !self.ended_without_stop && self.deadline.is_some_and(|d| Instant::now() >= d);
576 Ok(self.ended_without_stop || self.timed_out)
577 }
578
579 pub fn elapsed_ms(&self) -> u64 {
580 self.duration_ms
581 }
582
583 fn stop_child(&mut self) -> Result<std::process::ExitStatus> {
584 if let Some(status) = self.child.try_wait()? {
585 return Ok(status);
586 }
587 self.stop_requested = true;
590 unsafe { libc::kill(self.child.id() as libc::pid_t, libc::SIGINT) };
591 let deadline = Instant::now() + Duration::from_secs(3);
592 loop {
593 if let Some(status) = self.child.try_wait()? {
594 return Ok(status);
595 }
596 if Instant::now() >= deadline {
597 self.child.kill()?;
598 return Ok(self.child.wait()?);
599 }
600 thread::sleep(Duration::from_millis(30));
601 }
602 }
603
604 pub fn finish(self, config: &Config, store: &Store, reason: Option<&str>) -> Result<Recording> {
605 self.finish_cancellable(config, store, reason, &Arc::new(AtomicBool::new(false)))
606 }
607
608 pub fn finish_cancellable(
609 mut self,
610 config: &Config,
611 store: &Store,
612 reason: Option<&str>,
613 stop: &Arc<AtomicBool>,
614 ) -> Result<Recording> {
615 let status = self.stop_child()?;
616 for handle in self.readers.drain(..) {
617 let _ = handle.join();
618 }
619 self.duration_ms = self.progress.load(Ordering::Relaxed);
620 self.record.stopped_at = Some(chrono::Utc::now().to_rfc3339());
621 self.record.reconnects = self.reconnects.load(Ordering::Relaxed);
622 self.record.size_bytes = fs::metadata(&self.partial)?.len();
623 let verification = probe_with_timeout(
624 config,
625 &self.partial.to_string_lossy(),
626 stop,
627 Duration::from_secs(2),
628 );
629 if let Ok(info) = &verification {
630 self.record.media_duration_ms = info["format"]["duration"]
631 .as_str()
632 .and_then(|s| s.parse::<f64>().ok())
633 .filter(|d| d.is_finite() && *d >= 0.)
634 .map(|d| (d * 1000.) as u64);
635 }
636 let premature = self.ended_without_stop
637 && self.target_duration.is_none_or(|d| {
638 self.record
639 .media_duration_ms
640 .unwrap_or(self.duration_ms)
641 .saturating_add(100)
642 < d.as_millis() as u64
643 });
644 let reason = reason.or(if self.timed_out {
645 Some("录音未在时限内完成")
646 } else if premature && status.success() {
647 Some("直播源提前结束")
648 } else {
649 None
650 });
651 let graceful = status.success() || self.stop_requested;
654 self.record.status = if graceful && reason.is_none() && self.record.size_bytes > 0 {
655 "complete"
656 } else if reason.is_some() {
657 "interrupted"
658 } else {
659 "failed"
660 }
661 .into();
662 if self.record.status == "complete"
663 && verification
664 .as_ref()
665 .ok()
666 .and_then(|info| info["streams"][0]["codec_name"].as_str())
667 != Some(self.record.codec.as_str())
668 {
669 self.record.status = "failed".into();
670 self.record.error = Some("录音文件未通过音频轨道验证;保留临时文件".into());
671 }
672 if self.record.media_duration_ms.is_none() && self.duration_ms > 0 {
674 self.record.media_duration_ms = Some(self.duration_ms);
675 }
676 if self.record.status == "complete" {
677 self.record.status = "finalizing".into();
680 store.save_recording(&self.record)?;
681 sidecar(&self.record)?;
682 if let Err(error) = complete_finalization(store, &mut self.record) {
683 self.record.recovery_pending = true;
684 self.record.error = Some(format!(
685 "录音 {} ({}) 收尾待重试: {error:#}",
686 self.record.id, self.record.path
687 ));
688 let _ = store.save_recording(&self.record);
689 let _ = sidecar(&self.record);
690 return Err(error).context(self.record.error.clone().unwrap());
691 }
692 } else {
693 let errors = self.errors.lock().unwrap();
694 let summary = self
695 .record
696 .error
697 .as_deref()
698 .or(reason)
699 .map(str::to_owned)
700 .unwrap_or_else(|| format!("FFmpeg: {status}"));
701 self.record.error = Some(if errors.trim().is_empty() {
702 summary
703 } else {
704 format!("{summary}\n{}", errors.trim())
705 });
706 }
707 if self.record.status != "complete" {
708 store.save_recording(&self.record)?;
709 sidecar(&self.record)?;
710 }
711 self.finished = true;
712 Ok(self.record.clone())
713 }
714}
715
716impl Drop for Recorder {
717 fn drop(&mut self) {
718 if !self.finished {
719 let _ = self.stop_child();
720 }
721 for handle in self.readers.drain(..) {
722 let _ = handle.join();
723 }
724 }
725}
726
727pub fn parse_duration(value: &str) -> Result<Duration> {
728 let split = value
729 .find(|c: char| !c.is_ascii_digit())
730 .unwrap_or(value.len());
731 let n = value[..split]
732 .parse::<u64>()
733 .context(DomainError::new(ErrorCode::InvalidDuration))?;
734 let factor = match &value[split..] {
735 "" | "s" => 1,
736 "m" => 60,
737 "h" => 3600,
738 _ => bail!(DomainError::new(ErrorCode::DurationUnit)),
739 };
740 let secs = n
741 .checked_mul(factor)
742 .context(DomainError::new(ErrorCode::DurationOverflow))?;
743 if secs == 0 || secs > 365 * 24 * 3600 {
744 bail!(DomainError::new(ErrorCode::DurationRange));
745 }
746 Ok(Duration::from_secs(secs))
747}
748
749#[cfg(test)]
750mod tests {
751 use super::*;
752
753 #[test]
754 fn recording_track_is_optional_for_older_metadata() {
755 let dir = tempfile::tempdir().unwrap();
756 let old = pending(dir.path());
757 let value = serde_json::to_value(&old).unwrap();
758 assert!(value.get("track").is_none());
759 let decoded: Recording = serde_json::from_value(value).unwrap();
760 assert!(decoded.track.is_none());
761 }
762
763 fn pending(dir: &Path) -> Recording {
764 let partial = dir.join("test.mp3.part");
765 fs::write(&partial, b"verified audio").unwrap();
766 Recording {
767 id: uuid::Uuid::new_v4().to_string(),
768 stationuuid: uuid::Uuid::new_v4().to_string(),
769 station_name: "test".into(),
770 track: None,
771 source_url_resolved: "https://example.com/audio".into(),
772 started_at: "2026-01-01T00:00:00Z".into(),
773 stopped_at: Some("2026-01-01T00:00:01Z".into()),
774 media_duration_ms: Some(1000),
775 codec: "mp3".into(),
776 container: "mp3".into(),
777 path: partial.to_string_lossy().into(),
778 final_path: Some(dir.join("test.mp3").to_string_lossy().into()),
779 size_bytes: 14,
780 status: "finalizing".into(),
781 error: None,
782 reconnects: 0,
783 recovery_pending: false,
784 }
785 }
786
787 #[test]
788 fn space_estimate_prefers_audio_bitrate_and_reports_unknown_totals() {
789 let reserve = 16 * 1024 * 1024;
790 let mut info =
791 serde_json::json!({"streams":[{"bit_rate":"128000"}], "format":{"bit_rate":"256000"}});
792 assert_eq!(
793 required_space(16, 320, &info, Some(Duration::from_millis(1500))),
794 (reserve + 24000, true)
795 );
796 assert_eq!(required_space(16, 320, &info, None), (reserve, false));
797 info["streams"][0]["bit_rate"] = "0".into();
798 assert_eq!(
799 required_space(16, 320, &info, Some(Duration::from_secs(1))),
800 (reserve + 32000, true)
801 );
802 assert_eq!(
803 required_space(16, 0, &Value::Null, Some(Duration::from_secs(1))),
804 (reserve, false)
805 );
806 assert_eq!(
807 required_space(16, 128, &Value::Null, Some(Duration::from_secs(1))),
808 (reserve + 16000, true)
809 );
810 let extreme = serde_json::json!({"streams":[{"bit_rate":u64::MAX.to_string()}]});
811 assert_eq!(
812 required_space(16, 0, &extreme, Some(Duration::from_secs(u64::MAX))),
813 (u64::MAX, true)
814 );
815 }
816
817 #[test]
818 fn recovery_repairs_each_publication_boundary_idempotently() {
819 for phase in 0..5 {
820 let dir = tempfile::tempdir().unwrap();
821 let store = Store::open(&dir.path().join("radio.db")).unwrap();
822 let mut r = pending(dir.path());
823 r.reconnects = 2;
824 store.save_recording(&r).unwrap();
825 sidecar(&r).unwrap();
826 if phase >= 1 {
827 fs::hard_link(&r.path, r.final_path.as_ref().unwrap()).unwrap();
828 }
829 if phase >= 2 {
830 publish(
831 Path::new(&r.path),
832 Path::new(r.final_path.as_ref().unwrap()),
833 )
834 .unwrap();
835 }
836 if phase >= 3 {
837 let mut complete = r.clone();
838 complete.path = complete.final_path.clone().unwrap();
839 complete.status = "complete".into();
840 sidecar(&complete).unwrap();
841 }
842 if phase == 4 {
843 let lock = rusqlite::Connection::open(dir.path().join("radio.db")).unwrap();
845 lock.execute_batch("BEGIN IMMEDIATE").unwrap();
846 assert!(complete_finalization(&store, &mut r).is_err());
847 lock.execute_batch("ROLLBACK").unwrap();
848 }
849 recover(&store).unwrap();
850 recover(&store).unwrap();
851 let saved = store.recordings(1).unwrap().remove(0);
852 assert_eq!(saved.status, "complete");
853 assert_eq!(saved.reconnects, 2);
854 assert_eq!(fs::read(&saved.path).unwrap(), b"verified audio");
855 assert_eq!(
856 serde_json::from_slice::<Recording>(
857 &fs::read(format!("{}.json", saved.path)).unwrap()
858 )
859 .unwrap()
860 .id,
861 saved.id
862 );
863 assert!(!Path::new(&r.path).exists());
864 }
865 }
866
867 #[test]
868 fn successful_sidecar_retry_clears_recovery_pending_state() {
869 let dir = tempfile::tempdir().unwrap();
870 let store = Store::open(&dir.path().join("radio.db")).unwrap();
871 let mut r = pending(dir.path());
872 r.status = "recording".into();
873 r.path = dir.path().join("missing/old.part").to_string_lossy().into();
874 store.save_recording(&r).unwrap();
875 assert_eq!(recover(&store).unwrap().len(), 1);
876 assert_eq!(store.unfinished_recordings().unwrap().len(), 1);
877 let mut retry = store.recordings(1).unwrap().remove(0);
878 assert!(retry.recovery_pending);
879 retry.error = Some("diagnostic wording has changed".into());
880 store.save_recording(&retry).unwrap();
881 assert_eq!(store.unfinished_recordings().unwrap().len(), 1);
882 fs::create_dir(dir.path().join("missing")).unwrap();
883 assert!(recover(&store).unwrap().is_empty());
884 assert!(store.unfinished_recordings().unwrap().is_empty());
885 let saved = store.recordings(1).unwrap().remove(0);
886 assert_eq!(saved.status, "interrupted");
887 assert!(!saved.recovery_pending);
888 assert!(saved.error.as_deref().unwrap().contains("音频文件缺失"));
889 assert!(Path::new(&format!("{}.json", saved.path)).exists());
890 assert!(recover(&store).unwrap().is_empty());
891 }
892
893 #[test]
894 fn recovery_selection_uses_the_flag_instead_of_error_text() {
895 let dir = tempfile::tempdir().unwrap();
896 let store = Store::open(&dir.path().join("radio.db")).unwrap();
897 let mut record = pending(dir.path());
898 record.status = "interrupted".into();
899 record.error = Some("恢复失败: diagnostic text alone".into());
900 store.save_recording(&record).unwrap();
901 assert!(store.unfinished_recordings().unwrap().is_empty());
902 record.recovery_pending = true;
903 record.error = None;
904 store.save_recording(&record).unwrap();
905 assert_eq!(store.unfinished_recordings().unwrap().len(), 1);
906 assert!(recover(&store).unwrap().is_empty());
907 assert!(store.unfinished_recordings().unwrap().is_empty());
908 }
909
910 #[test]
911 fn version_one_database_migrates_legacy_recovery_state_once() {
912 let dir = tempfile::tempdir().unwrap();
913 let path = dir.path().join("legacy.db");
914 let mut record = pending(dir.path());
915 record.status = "interrupted".into();
916 record.error = Some("恢复失败: old-format sidecar failure".into());
917 let mut json = serde_json::to_value(&record).unwrap();
918 json.as_object_mut().unwrap().remove("recovery_pending");
919 let conn = rusqlite::Connection::open(&path).unwrap();
920 conn.execute_batch("CREATE TABLE recordings (id TEXT PRIMARY KEY,status TEXT NOT NULL,json TEXT NOT NULL);
921 CREATE TABLE stations (uuid TEXT PRIMARY KEY,name TEXT NOT NULL,search TEXT NOT NULL,
922 country TEXT NOT NULL,languages TEXT NOT NULL,tags TEXT NOT NULL,bitrate INTEGER NOT NULL,
923 popularity INTEGER NOT NULL,custom INTEGER NOT NULL,active INTEGER NOT NULL,json TEXT NOT NULL);
924 CREATE TABLE meta (key TEXT PRIMARY KEY,value TEXT NOT NULL);
925 CREATE TABLE favorites (uuid TEXT PRIMARY KEY REFERENCES stations(uuid),created_at TEXT NOT NULL);
926 CREATE TABLE history (id INTEGER PRIMARY KEY,uuid TEXT NOT NULL REFERENCES stations(uuid),played_at TEXT NOT NULL);
927 CREATE INDEX history_station ON history(uuid);
928 PRAGMA user_version=1;").unwrap();
929 conn.execute(
930 "INSERT INTO recordings VALUES (?1,?2,?3)",
931 rusqlite::params![record.id, record.status, json.to_string()],
932 )
933 .unwrap();
934 drop(conn);
935 let store = Store::open(&path).unwrap();
936 assert!(store.unfinished_recordings().unwrap()[0].recovery_pending);
937 assert!(recover(&store).unwrap().is_empty());
938 assert!(!store.recordings(1).unwrap()[0].recovery_pending);
939 drop(store);
940 let store = Store::open(&path).unwrap();
941 assert!(store.unfinished_recordings().unwrap().is_empty());
942 let conn = rusqlite::Connection::open(&path).unwrap();
943 assert_eq!(
944 conn.pragma_query_value(None, "user_version", |r| r.get::<_, u32>(0))
945 .unwrap(),
946 10
947 );
948 }
949
950 #[test]
951 fn publication_never_overwrites_an_existing_file() {
952 let dir = tempfile::tempdir().unwrap();
953 let store = Store::open(&dir.path().join("radio.db")).unwrap();
954 let mut r = pending(dir.path());
955 store.save_recording(&r).unwrap();
956 fs::write(r.final_path.as_ref().unwrap(), b"other recording").unwrap();
957 assert!(complete_finalization(&store, &mut r).is_err());
958 assert_eq!(
959 fs::read(r.final_path.as_ref().unwrap()).unwrap(),
960 b"other recording"
961 );
962 assert_eq!(fs::read(&r.path).unwrap(), b"verified audio");
963 fs::remove_file(r.final_path.as_ref().unwrap()).unwrap();
964 recover(&store).unwrap();
965 assert_eq!(store.recordings(1).unwrap()[0].status, "complete");
966 }
967
968 #[test]
969 fn publication_rejects_matching_contents_and_symlink_destinations() {
970 use std::os::unix::fs::symlink;
971 for symlink_target in [false, true] {
972 let dir = tempfile::tempdir().unwrap();
973 let store = Store::open(&dir.path().join("radio.db")).unwrap();
974 let mut r = pending(dir.path());
975 let final_path = PathBuf::from(r.final_path.as_ref().unwrap());
976 if symlink_target {
977 symlink(&r.path, &final_path).unwrap();
978 } else {
979 fs::copy(&r.path, &final_path).unwrap();
980 }
981 assert!(complete_finalization(&store, &mut r).is_err());
982 assert_eq!(fs::read(&r.path).unwrap(), b"verified audio");
983 assert_eq!(fs::read(final_path).unwrap(), b"verified audio");
984 assert_eq!(r.status, "finalizing");
985 }
986 }
987}