Skip to main content

active_call/callrecord/
mod.rs

1use crate::CallOption;
2use crate::{
3    call::ActiveCallType,
4    config::{CallRecordConfig, S3Vendor},
5};
6use anyhow::Result;
7use chrono::{DateTime, Local, Utc};
8use futures::stream::{FuturesUnordered, StreamExt};
9use object_store::PutPayload;
10use object_store::{
11    ObjectStore, ObjectStoreExt, aws::AmazonS3Builder, azure::MicrosoftAzureBuilder,
12    gcp::GoogleCloudStorageBuilder, path::Path as ObjectPath,
13};
14use reqwest;
15use serde::{Deserialize, Serialize};
16use serde_with::skip_serializing_none;
17use std::{
18    collections::HashMap, future::Future, path::Path, pin::Pin, str::FromStr, sync::Arc,
19    time::Instant,
20};
21use tokio::{fs::File, io::AsyncWriteExt};
22use tokio_util::sync::CancellationToken;
23use tracing::{info, warn};
24
25pub type CallRecordSender = tokio::sync::mpsc::UnboundedSender<CallRecord>;
26pub type CallRecordReceiver = tokio::sync::mpsc::UnboundedReceiver<CallRecord>;
27
28pub type FnSaveCallRecord = Arc<
29    Box<
30        dyn Fn(
31                CancellationToken,
32                Arc<dyn CallRecordFormatter>,
33                Arc<CallRecordConfig>,
34                CallRecord,
35            ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>
36            + Send
37            + Sync,
38    >,
39>;
40
41#[derive(Debug, Clone, Serialize, Deserialize)]
42#[serde(rename_all = "camelCase")]
43pub enum CallRecordEventType {
44    Event,
45    Command,
46    Sip,
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize)]
50#[serde(rename_all = "camelCase")]
51pub struct CallRecordEvent {
52    pub r#type: CallRecordEventType,
53    pub timestamp: u64,
54    pub content: String,
55}
56
57impl CallRecordEvent {
58    pub async fn write<T: Serialize>(r#type: CallRecordEventType, obj: T, file: &mut File) {
59        let content = match serde_json::to_string(&obj) {
60            Ok(s) => s,
61            Err(_) => return,
62        };
63        let event = Self {
64            r#type,
65            timestamp: crate::media::get_timestamp(),
66            content,
67        };
68        match serde_json::to_string(&event) {
69            Ok(line) => {
70                file.write_all(format!("{}\n", line).as_bytes()).await.ok();
71            }
72            Err(_) => {}
73        }
74    }
75}
76
77#[skip_serializing_none]
78#[derive(Debug, Clone, Serialize, Deserialize, Default)]
79#[serde(rename_all = "camelCase")]
80pub struct CallRecord {
81    pub call_type: ActiveCallType,
82    pub option: Option<CallOption>,
83    pub call_id: String,
84    pub start_time: DateTime<Utc>,
85    pub ring_time: Option<DateTime<Utc>>,
86    pub answer_time: Option<DateTime<Utc>>,
87    pub end_time: DateTime<Utc>,
88    pub caller: String,
89    pub callee: String,
90    pub status_code: u16,
91    pub hangup_reason: Option<CallRecordHangupReason>,
92    #[serde(skip_serializing_if = "Vec::is_empty")]
93    #[serde(default)]
94    pub hangup_messages: Vec<CallRecordHangupMessage>,
95    #[serde(skip_serializing_if = "Vec::is_empty")]
96    #[serde(default)]
97    pub recorder: Vec<CallRecordMedia>,
98    pub extras: Option<HashMap<String, serde_json::Value>>,
99    pub dump_event_file: Option<String>,
100    pub refer_callrecord: Option<Box<CallRecord>>,
101    /// SIP Call-IDs of every dialog belonging to this session (primary leg,
102    /// bridge legs, REFER transfer legs), resolved by the sipflow capture
103    /// ([`crate::sipflow`]) so post-call hooks can merge all legs' signaling.
104    #[serde(default, skip_serializing_if = "Vec::is_empty")]
105    pub sip_call_ids: Vec<String>,
106}
107
108#[derive(Debug, Clone, Serialize, Deserialize)]
109#[serde(rename_all = "camelCase")]
110pub struct CallRecordMedia {
111    pub track_id: String,
112    pub path: String,
113    pub size: u64,
114    #[serde(skip_serializing_if = "Option::is_none")]
115    pub extra: Option<HashMap<String, serde_json::Value>>,
116}
117
118#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
119#[serde(rename_all = "camelCase")]
120pub enum CallRecordHangupReason {
121    ByCaller,
122    ByCallee,
123    ByRefer,
124    BySystem,
125    Autohangup,
126    InactivityTimeout,
127    NoAnswer,
128    NoBalance,
129    AnswerMachine,
130    ServerUnavailable,
131    Canceled,
132    Rejected,
133    Failed,
134    Other(String),
135}
136
137#[derive(Debug, Clone, Serialize, Deserialize)]
138#[serde(rename_all = "camelCase")]
139pub struct CallRecordHangupMessage {
140    pub code: u16,
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub reason: Option<String>,
143    #[serde(skip_serializing_if = "Option::is_none")]
144    pub target: Option<String>,
145}
146
147impl FromStr for CallRecordHangupReason {
148    type Err = anyhow::Error;
149
150    fn from_str(s: &str) -> Result<Self, Self::Err> {
151        match s.to_lowercase().as_str() {
152            "caller" => Ok(Self::ByCaller),
153            "callee" => Ok(Self::ByCallee),
154            "refer" => Ok(Self::ByRefer),
155            "system" => Ok(Self::BySystem),
156            "autohangup" => Ok(Self::Autohangup),
157            "inactivitytimeout" => Ok(Self::InactivityTimeout),
158            "noanswer" => Ok(Self::NoAnswer),
159            "nobalance" => Ok(Self::NoBalance),
160            "answermachine" => Ok(Self::AnswerMachine),
161            "serverunavailable" => Ok(Self::ServerUnavailable),
162            "canceled" => Ok(Self::Canceled),
163            "rejected" => Ok(Self::Rejected),
164            "failed" => Ok(Self::Failed),
165            _ => Ok(Self::Other(s.to_string())),
166        }
167    }
168}
169impl ToString for CallRecordHangupReason {
170    fn to_string(&self) -> String {
171        match self {
172            Self::ByCaller => "caller".to_string(),
173            Self::ByCallee => "callee".to_string(),
174            Self::ByRefer => "refer".to_string(),
175            Self::BySystem => "system".to_string(),
176            Self::Autohangup => "autohangup".to_string(),
177            Self::InactivityTimeout => "inactivityTimeout".to_string(),
178            Self::NoAnswer => "noAnswer".to_string(),
179            Self::NoBalance => "noBalance".to_string(),
180            Self::AnswerMachine => "answerMachine".to_string(),
181            Self::ServerUnavailable => "serverUnavailable".to_string(),
182            Self::Canceled => "canceled".to_string(),
183            Self::Rejected => "rejected".to_string(),
184            Self::Failed => "failed".to_string(),
185            Self::Other(s) => s.to_string(),
186        }
187    }
188}
189
190pub fn default_cdr_file_name(record: &CallRecord) -> String {
191    format!(
192        "{}_{}.json",
193        record
194            .start_time
195            .with_timezone(&Local)
196            .format("%Y%m%d-%H%M%S"),
197        record.call_id
198    )
199}
200
201pub trait CallRecordFormatter: Send + Sync {
202    fn format(&self, record: &CallRecord) -> Result<String> {
203        Ok(serde_json::to_string(record)?)
204    }
205    fn format_file_name(&self, record: &CallRecord) -> String;
206    fn format_dump_events_path(&self, record: &CallRecord) -> String;
207    fn format_media_path(&self, record: &CallRecord, media: &CallRecordMedia) -> String;
208}
209
210/// Post-processing hooks run by the [`CallRecordManager`] around the saver
211/// (single-record counterpart of rustpbx's `CallRecordHook`). Implement
212/// either method; both default to no-ops. Heavy work should be spawned.
213#[async_trait::async_trait]
214pub trait CallRecordHook: Send + Sync {
215    /// Runs before the record is handed to the saver; may mutate the record
216    /// (e.g. enrich fields that must appear in the persisted document).
217    async fn on_record_enrich(&self, _record: &mut CallRecord) -> Result<()> {
218        Ok(())
219    }
220
221    /// Runs after the saver finished (successfully or not).
222    async fn on_record_completed(&self, _record: &mut CallRecord) -> Result<()> {
223        Ok(())
224    }
225}
226
227pub struct DefaultCallRecordFormatter {
228    pub root: String,
229}
230
231impl Default for DefaultCallRecordFormatter {
232    fn default() -> Self {
233        Self {
234            root: "./config/cdr".to_string(),
235        }
236    }
237}
238
239impl DefaultCallRecordFormatter {
240    pub fn new_with_config(config: &CallRecordConfig) -> Self {
241        let root = match config {
242            CallRecordConfig::Local { root } => root.clone(),
243            CallRecordConfig::S3 { root, .. } => root.clone(),
244            _ => "./config/cdr".to_string(),
245        };
246        Self { root }
247    }
248}
249
250impl CallRecordFormatter for DefaultCallRecordFormatter {
251    fn format_file_name(&self, record: &CallRecord) -> String {
252        let trimmed_root = self.root.trim_end_matches('/');
253        let file_name = default_cdr_file_name(record);
254        if trimmed_root.is_empty() {
255            file_name
256        } else {
257            format!(
258                "{}/{}/{}",
259                trimmed_root,
260                record.start_time.with_timezone(&Local).format("%Y%m%d"),
261                file_name
262            )
263        }
264    }
265
266    fn format_dump_events_path(&self, record: &CallRecord) -> String {
267        format!(
268            "{}/{}/{}.jsonl",
269            self.root.trim_end_matches('/'),
270            record.start_time.with_timezone(&Local).format("%Y%m%d"),
271            record.call_id
272        )
273    }
274
275    fn format_media_path(&self, record: &CallRecord, media: &CallRecordMedia) -> String {
276        let file_name = Path::new(&media.path)
277            .file_name()
278            .unwrap_or_else(|| std::ffi::OsStr::new("unknown"))
279            .to_string_lossy()
280            .to_string();
281
282        format!(
283            "{}/{}/{}_{}_{}",
284            self.root.trim_end_matches('/'),
285            record.start_time.with_timezone(&Local).format("%Y%m%d"),
286            record.call_id,
287            media.track_id,
288            file_name
289        )
290    }
291}
292
293pub fn build_object_store_from_s3(
294    vendor: &S3Vendor,
295    bucket: &str,
296    region: &str,
297    access_key: &str,
298    secret_key: &str,
299    endpoint: &str,
300) -> Result<Arc<dyn ObjectStore>> {
301    let store: Arc<dyn ObjectStore> = match vendor {
302        S3Vendor::AWS => {
303            let builder = AmazonS3Builder::new()
304                .with_bucket_name(bucket)
305                .with_region(region)
306                .with_access_key_id(access_key)
307                .with_secret_access_key(secret_key);
308
309            let instance = if !endpoint.is_empty() {
310                builder.with_endpoint(endpoint).build()?
311            } else {
312                builder.build()?
313            };
314            Arc::new(instance)
315        }
316        S3Vendor::GCP => {
317            let instance = GoogleCloudStorageBuilder::new()
318                .with_bucket_name(bucket)
319                .with_service_account_key(secret_key)
320                .build()?;
321            Arc::new(instance)
322        }
323        S3Vendor::Azure => {
324            let instance = MicrosoftAzureBuilder::new()
325                .with_container_name(bucket)
326                .with_account(access_key)
327                .with_access_key(secret_key)
328                .build()?;
329            Arc::new(instance)
330        }
331        S3Vendor::Aliyun | S3Vendor::Tencent | S3Vendor::Minio | S3Vendor::DigitalOcean => {
332            let instance = AmazonS3Builder::new()
333                .with_bucket_name(bucket)
334                .with_region(region)
335                .with_access_key_id(access_key)
336                .with_secret_access_key(secret_key)
337                .with_endpoint(endpoint)
338                .with_virtual_hosted_style_request(false)
339                .build()?;
340            Arc::new(instance)
341        }
342    };
343
344    Ok(store)
345}
346
347pub struct CallRecordManager {
348    pub max_concurrent: usize,
349    pub sender: CallRecordSender,
350    config: Arc<CallRecordConfig>,
351    cancel_token: CancellationToken,
352    receiver: CallRecordReceiver,
353    saver_fn: FnSaveCallRecord,
354    formatter: Arc<dyn CallRecordFormatter>,
355    hooks: Vec<Arc<dyn CallRecordHook>>,
356}
357
358pub struct CallRecordManagerBuilder {
359    pub cancel_token: Option<CancellationToken>,
360    pub config: Option<CallRecordConfig>,
361    pub max_concurrent: Option<usize>,
362    saver_fn: Option<FnSaveCallRecord>,
363    formatter: Option<Arc<dyn CallRecordFormatter>>,
364    hooks: Vec<Arc<dyn CallRecordHook>>,
365}
366
367impl CallRecordManagerBuilder {
368    pub fn new() -> Self {
369        Self {
370            cancel_token: None,
371            config: None,
372            max_concurrent: None,
373            saver_fn: None,
374            formatter: None,
375            hooks: Vec::new(),
376        }
377    }
378
379    pub fn with_cancel_token(mut self, cancel_token: CancellationToken) -> Self {
380        self.cancel_token = Some(cancel_token);
381        self
382    }
383
384    pub fn with_config(mut self, config: CallRecordConfig) -> Self {
385        self.config = Some(config);
386        self
387    }
388
389    pub fn with_saver(mut self, saver: FnSaveCallRecord) -> Self {
390        self.saver_fn = Some(saver);
391        self
392    }
393
394    pub fn with_formatter(mut self, formatter: Arc<dyn CallRecordFormatter>) -> Self {
395        self.formatter = Some(formatter);
396        self
397    }
398
399    pub fn with_max_concurrent(mut self, max_concurrent: usize) -> Self {
400        self.max_concurrent = Some(max_concurrent);
401        self
402    }
403
404    /// Appends a post-processing hook (see [`CallRecordHook`]).
405    pub fn with_hook(mut self, hook: Arc<dyn CallRecordHook>) -> Self {
406        self.hooks.push(hook);
407        self
408    }
409
410    pub fn build(self) -> CallRecordManager {
411        let cancel_token = self.cancel_token.unwrap_or_default();
412        let config = Arc::new(self.config.unwrap_or_default());
413        let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
414        let saver_fn = self
415            .saver_fn
416            .unwrap_or_else(|| Arc::new(Box::new(CallRecordManager::default_saver)));
417        let formatter = self
418            .formatter
419            .unwrap_or_else(|| Arc::new(DefaultCallRecordFormatter::default()));
420        let max_concurrent = self.max_concurrent.unwrap_or(64);
421
422        match config.as_ref() {
423            CallRecordConfig::Local { root } => {
424                if !Path::new(&root).exists() {
425                    match std::fs::create_dir_all(&root) {
426                        Ok(_) => {
427                            info!("CallRecordManager created directory: {}", root);
428                        }
429                        Err(e) => {
430                            warn!("CallRecordManager failed to create directory: {}", e);
431                        }
432                    }
433                }
434            }
435            _ => {}
436        }
437
438        CallRecordManager {
439            max_concurrent,
440            cancel_token,
441            sender,
442            receiver,
443            config,
444            saver_fn,
445            formatter,
446            hooks: self.hooks,
447        }
448    }
449}
450
451impl CallRecordManager {
452    fn default_saver(
453        _cancel_token: CancellationToken,
454        formatter: Arc<dyn CallRecordFormatter>,
455        config: Arc<CallRecordConfig>,
456        record: CallRecord,
457    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
458        Box::pin(async move {
459            let mut record = record;
460            let start_time = Instant::now();
461            let result = match config.as_ref() {
462                CallRecordConfig::Local { .. } => {
463                    Self::save_local_record(formatter.clone(), &mut record).await
464                }
465                CallRecordConfig::S3 {
466                    vendor,
467                    bucket,
468                    region,
469                    access_key,
470                    secret_key,
471                    endpoint,
472                    with_media,
473                    keep_media_copy,
474                    ..
475                } => {
476                    Self::save_with_s3_like(
477                        formatter.clone(),
478                        vendor,
479                        bucket,
480                        region,
481                        access_key,
482                        secret_key,
483                        endpoint,
484                        with_media,
485                        keep_media_copy,
486                        &record,
487                    )
488                    .await
489                }
490                CallRecordConfig::Http {
491                    url,
492                    headers,
493                    with_media,
494                    keep_media_copy,
495                } => {
496                    Self::save_with_http(
497                        formatter.clone(),
498                        url,
499                        headers,
500                        with_media,
501                        keep_media_copy,
502                        &record,
503                    )
504                    .await
505                }
506            };
507            let file_name = match result {
508                Ok(file_name) => file_name,
509                Err(e) => {
510                    warn!("Failed to save call record: {}", e);
511                    return Err(e);
512                }
513            };
514            let elapsed = start_time.elapsed();
515            info!(
516                ?elapsed,
517                call_id = record.call_id,
518                file_name,
519                "CallRecordManager saved"
520            );
521            Ok(())
522        })
523    }
524
525    async fn save_local_record(
526        formatter: Arc<dyn CallRecordFormatter>,
527        record: &mut CallRecord,
528    ) -> Result<String> {
529        let file_content = formatter.format(record)?;
530        let file_name = formatter.format_file_name(record);
531
532        // Ensure parent directory exists
533        if let Some(parent) = Path::new(&file_name).parent() {
534            tokio::fs::create_dir_all(parent).await.map_err(|e| {
535                anyhow::anyhow!("Failed to create parent directory for {}: {}", file_name, e)
536            })?;
537        }
538
539        let mut file = File::create(&file_name).await.map_err(|e| {
540            anyhow::anyhow!("Failed to create call record file {}: {}", file_name, e)
541        })?;
542        file.write_all(file_content.as_bytes()).await?;
543        file.flush().await?;
544        Ok(file_name.to_string())
545    }
546
547    pub async fn save_with_http(
548        formatter: Arc<dyn CallRecordFormatter>,
549        url: &String,
550        headers: &Option<HashMap<String, String>>,
551        with_media: &Option<bool>,
552        keep_media_copy: &Option<bool>,
553        record: &CallRecord,
554    ) -> Result<String> {
555        let client = reqwest::Client::new();
556        // Serialize call record to JSON
557        let call_log_json = formatter.format(record)?;
558        // Create multipart form
559        let mut form = reqwest::multipart::Form::new().text("calllog.json", call_log_json);
560
561        // Add media files if with_media is true
562        if with_media.unwrap_or(false) {
563            for media in &record.recorder {
564                if std::path::Path::new(&media.path).exists() {
565                    match tokio::fs::read(&media.path).await {
566                        Ok(file_content) => {
567                            let file_name = std::path::Path::new(&media.path)
568                                .file_name()
569                                .unwrap_or_else(|| std::ffi::OsStr::new("unknown"))
570                                .to_string_lossy()
571                                .to_string();
572
573                            let part = match reqwest::multipart::Part::bytes(file_content)
574                                .file_name(file_name.clone())
575                                .mime_str("application/octet-stream")
576                            {
577                                Ok(part) => part,
578                                Err(_) => {
579                                    // Fallback to default MIME type if parsing fails
580                                    reqwest::multipart::Part::bytes(
581                                        tokio::fs::read(&media.path).await?,
582                                    )
583                                    .file_name(file_name)
584                                }
585                            };
586
587                            form = form.part(format!("media_{}", media.track_id), part);
588                        }
589                        Err(e) => {
590                            warn!("Failed to read media file {}: {}", media.path, e);
591                        }
592                    }
593                }
594            }
595            if let Some(dump_events_file) = &record.dump_event_file {
596                if Path::new(&dump_events_file).exists() {
597                    let file_name = Path::new(&dump_events_file)
598                        .file_name()
599                        .unwrap_or_else(|| std::ffi::OsStr::new("unknown"))
600                        .to_string_lossy()
601                        .to_string();
602                    match reqwest::multipart::Part::bytes(tokio::fs::read(&dump_events_file).await?)
603                        .file_name(file_name.clone())
604                        .mime_str("application/octet-stream")
605                    {
606                        Ok(part) => {
607                            form = form.part(format!("dump_events_{}", file_name), part);
608                        }
609                        Err(_) => {}
610                    };
611                }
612            }
613        }
614        let mut request = client.post(url).multipart(form);
615        if let Some(headers_map) = headers {
616            for (key, value) in headers_map {
617                request = request.header(key, value);
618            }
619        }
620        let response = request.send().await?;
621        if response.status().is_success() {
622            let response_text = response.text().await.unwrap_or_default();
623
624            if keep_media_copy.unwrap_or(false) {
625                for media in &record.recorder {
626                    let p = Path::new(&media.path);
627                    if p.exists() {
628                        tokio::fs::remove_file(p).await.ok();
629                    }
630                }
631            }
632            Ok(format!("HTTP upload successful: {}", response_text))
633        } else {
634            Err(anyhow::anyhow!(
635                "HTTP upload failed with status: {} - {}",
636                response.status(),
637                response.text().await.unwrap_or_default()
638            ))
639        }
640    }
641
642    pub async fn save_with_s3_like(
643        formatter: Arc<dyn CallRecordFormatter>,
644        vendor: &S3Vendor,
645        bucket: &String,
646        region: &String,
647        access_key: &String,
648        secret_key: &String,
649        endpoint: &String,
650        with_media: &Option<bool>,
651        keep_media_copy: &Option<bool>,
652        record: &CallRecord,
653    ) -> Result<String> {
654        let start_time = Instant::now();
655        let object_store =
656            build_object_store_from_s3(vendor, bucket, region, access_key, secret_key, endpoint)?;
657
658        // Serialize call record to JSON
659        let call_log_json = formatter.format(record)?;
660        // Upload call log JSON
661        let filename = formatter.format_file_name(record);
662        let local_files = vec![filename.clone()];
663        let json_path = ObjectPath::from(filename);
664        let buf_size = call_log_json.len();
665        match object_store
666            .put(&json_path, PutPayload::from(call_log_json))
667            .await
668        {
669            Ok(_) => {
670                info!(
671                    elapsed = start_time.elapsed().as_secs_f64(),
672                    %json_path,
673                    buf_size,
674                    "upload call record"
675                );
676            }
677            Err(e) => {
678                warn!(
679                   %json_path,
680                    "failed to upload call record: {}", e
681                );
682            }
683        }
684        // Upload media files if with_media is true
685        if with_media.unwrap_or(false) {
686            let mut media_files = vec![];
687            for media in &record.recorder {
688                if Path::new(&media.path).exists() {
689                    let media_path = ObjectPath::from(formatter.format_media_path(record, media));
690                    media_files.push((media.path.clone(), media_path));
691                }
692            }
693            if let Some(dump_events_file) = &record.dump_event_file {
694                if Path::new(&dump_events_file).exists() {
695                    let dump_events_path =
696                        ObjectPath::from(formatter.format_dump_events_path(record));
697                    media_files.push((dump_events_file.clone(), dump_events_path));
698                }
699            }
700            for (path, media_path) in &media_files {
701                let start_time = Instant::now();
702                let file_content = match tokio::fs::read(path).await {
703                    Ok(file_content) => file_content,
704                    Err(e) => {
705                        warn!("failed to read media file {}: {}", path, e);
706                        continue;
707                    }
708                };
709                let buf_size = file_content.len();
710                match object_store
711                    .put(media_path, PutPayload::from(file_content))
712                    .await
713                {
714                    Ok(_) => {
715                        info!(
716                            elapsed = start_time.elapsed().as_secs_f64(),
717                            %media_path,
718                            buf_size,
719                            "upload media file"
720                        );
721                    }
722                    Err(e) => {
723                        warn!(%media_path,"failed to upload media file: {}", e);
724                    }
725                }
726            }
727        }
728        // Optionally delete local media files if keep_media_copy is false
729        if !keep_media_copy.unwrap_or(false) {
730            for media in &record.recorder {
731                let p = Path::new(&media.path);
732                if p.exists() {
733                    tokio::fs::remove_file(p).await.ok();
734                }
735            }
736            for file_name in &local_files {
737                let p = Path::new(file_name);
738                if p.exists() {
739                    tokio::fs::remove_file(p).await.ok();
740                }
741            }
742        }
743
744        Ok(format!(
745            "{}/{}",
746            endpoint.trim_end_matches('/'),
747            json_path.to_string().trim_start_matches('/')
748        ))
749    }
750
751    pub async fn serve(&mut self) {
752        let token = self.cancel_token.clone();
753        info!("CallRecordManager serving");
754        tokio::select! {
755            _ = token.cancelled() => {}
756            _ = self.recv_loop() => {}
757        }
758        info!("CallRecordManager served");
759    }
760
761    async fn recv_loop(&mut self) -> Result<()> {
762        let mut futures = FuturesUnordered::new();
763        loop {
764            let limit = self.max_concurrent - futures.len();
765            if limit == 0 {
766                if let Some(_) = futures.next().await {}
767                continue;
768            }
769            let mut buffer = Vec::with_capacity(limit);
770            if self.receiver.recv_many(&mut buffer, limit).await == 0 {
771                break;
772            }
773
774            for mut record in buffer {
775                let cancel_token_ref = self.cancel_token.clone();
776                let save_fn_ref = self.saver_fn.clone();
777                let config_ref = self.config.clone();
778                let formatter_ref = self.formatter.clone();
779                let hooks = self.hooks.clone();
780
781                futures.push(async move {
782                    for hook in &hooks {
783                        if let Err(e) = hook.on_record_enrich(&mut record).await {
784                            warn!(
785                                call_id = record.call_id,
786                                "callrecord on_record_enrich hook failed: {}", e
787                            );
788                        }
789                    }
790                    // The saver consumes the record; keep a copy for the
791                    // post-save hooks (records are small).
792                    let result =
793                        save_fn_ref(cancel_token_ref, formatter_ref, config_ref, record.clone())
794                            .await;
795                    for hook in &hooks {
796                        if let Err(e) = hook.on_record_completed(&mut record).await {
797                            warn!(
798                                call_id = record.call_id,
799                                "callrecord on_record_completed hook failed: {}", e
800                            );
801                        }
802                    }
803                    if let Err(e) = result {
804                        warn!("Failed to save call record: {}", e);
805                    }
806                });
807            }
808            while let Some(_) = futures.next().await {}
809        }
810        Ok(())
811    }
812}
813
814#[cfg(test)]
815mod tests {
816    use super::*;
817
818    /// Records the order hook/saver invocations happen in.
819    struct OrderingHook {
820        events: std::sync::Arc<std::sync::Mutex<Vec<String>>>,
821        name: &'static str,
822    }
823
824    #[async_trait::async_trait]
825    impl CallRecordHook for OrderingHook {
826        async fn on_record_enrich(&self, record: &mut CallRecord) -> Result<()> {
827            self.events
828                .lock()
829                .unwrap()
830                .push(format!("{}:enrich", self.name));
831            // Enrich must be able to mutate the persisted record.
832            record.sip_call_ids.push(format!("from-{}", self.name));
833            Ok(())
834        }
835
836        async fn on_record_completed(&self, _record: &mut CallRecord) -> Result<()> {
837            self.events
838                .lock()
839                .unwrap()
840                .push(format!("{}:completed", self.name));
841            Ok(())
842        }
843    }
844
845    fn sample_record() -> CallRecord {
846        CallRecord {
847            call_type: crate::call::ActiveCallType::Sip,
848            option: None,
849            call_id: "s.test".into(),
850            start_time: Utc::now(),
851            ring_time: None,
852            answer_time: None,
853            end_time: Utc::now(),
854            caller: "a".into(),
855            callee: "b".into(),
856            status_code: 200,
857            hangup_reason: None,
858            hangup_messages: Vec::new(),
859            recorder: Vec::new(),
860            extras: None,
861            dump_event_file: None,
862            refer_callrecord: None,
863            sip_call_ids: Vec::new(),
864        }
865    }
866
867    #[tokio::test]
868    async fn hooks_run_around_the_saver() {
869        let events = Arc::new(std::sync::Mutex::new(Vec::new()));
870        let saved: Arc<std::sync::Mutex<Vec<String>>> = Arc::new(std::sync::Mutex::new(Vec::new()));
871
872        let saver_saved = saved.clone();
873        let saver: FnSaveCallRecord = Arc::new(Box::new(
874            move |_token, _formatter, _config, record| {
875                let saver_saved = saver_saved.clone();
876                Box::pin(async move {
877                    saver_saved.lock().unwrap().push(record.call_id.clone());
878                    Ok(())
879                })
880            },
881        ));
882
883        // Build the manager field-by-field so the test can close the
884        // channel after sending (swap out the manager's own sender clone).
885        let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
886        let mut manager = CallRecordManager {
887            max_concurrent: 4,
888            sender,
889            config: Arc::new(CallRecordConfig::default()),
890            cancel_token: CancellationToken::new(),
891            receiver,
892            saver_fn: saver,
893            formatter: Arc::new(DefaultCallRecordFormatter::default()),
894            hooks: vec![Arc::new(OrderingHook {
895                events: events.clone(),
896                name: "h1",
897            })],
898        };
899
900        manager.sender.send(sample_record()).unwrap();
901        let real_sender = std::mem::replace(
902            &mut manager.sender,
903            tokio::sync::mpsc::unbounded_channel().0,
904        );
905        drop(real_sender);
906        manager.recv_loop().await.unwrap();
907
908        let timeline = events.lock().unwrap().clone();
909        assert_eq!(
910            timeline,
911            vec!["h1:enrich".to_string(), "h1:completed".to_string()]
912        );
913        // The saver saw the enriched record.
914        assert_eq!(saved.lock().unwrap().len(), 1);
915    }
916}