Skip to main content

rss_proxy/plugin/
mod.rs

1pub mod builtin;
2pub mod rhai_plugin;
3
4use crate::model::{Feed, FeedItem};
5use async_trait::async_trait;
6use tracing::{debug, info};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum FilterDecision {
10    Keep,
11    Drop,
12}
13
14#[async_trait]
15pub trait Plugin: Send + Sync {
16    /// Human-readable plugin name
17    fn name(&self) -> &str;
18
19    /// Feed-level pre-processing (executed before item filtering)
20    async fn pre_process_feed(&self, _feed: &mut Feed) -> anyhow::Result<()> {
21        Ok(())
22    }
23
24    /// Evaluates whether an item should be kept or dropped
25    async fn filter_item(&self, _item: &FeedItem) -> anyhow::Result<FilterDecision> {
26        Ok(FilterDecision::Keep)
27    }
28
29    /// Transforms/mutates an item in-place (e.g., cleans URLs, modifies title, alters content)
30    async fn transform_item(&self, _item: &mut FeedItem) -> anyhow::Result<()> {
31        Ok(())
32    }
33
34    /// Feed-level post-processing (e.g. sorting, item count limiting)
35    async fn post_process_feed(&self, _feed: &mut Feed) -> anyhow::Result<()> {
36        Ok(())
37    }
38
39    /// Invoked when upstream feed fails to fetch or parse. Returns an optional fallback Feed (e.g., NOP feed)
40    async fn on_fetch_error(
41        &self,
42        _url: &str,
43        _title: &str,
44        _error: &anyhow::Error,
45    ) -> Option<Feed> {
46        None
47    }
48}
49
50pub struct PluginPipeline {
51    plugins: Vec<Box<dyn Plugin>>,
52}
53
54impl PluginPipeline {
55    pub fn new() -> Self {
56        Self {
57            plugins: Vec::new(),
58        }
59    }
60
61    pub fn add_plugin(&mut self, plugin: Box<dyn Plugin>) {
62        info!("Registered plugin: {}", plugin.name());
63        self.plugins.push(plugin);
64    }
65
66    /// Handle upstream fetch errors by delegating to plugins that implement on_fetch_error
67    pub async fn handle_fetch_error(
68        &self,
69        url: &str,
70        title: &str,
71        error: &anyhow::Error,
72    ) -> Option<Feed> {
73        for plugin in &self.plugins {
74            if let Some(fallback) = plugin.on_fetch_error(url, title, error).await {
75                return Some(fallback);
76            }
77        }
78        None
79    }
80
81    /// Process a feed through all stages of the pipeline:
82    /// 1. pre_process_feed
83    /// 2. filter_item (dropping rejected items)
84    /// 3. transform_item (mutating remaining items)
85    /// 4. post_process_feed
86    pub async fn process(&self, feed: &mut Feed) -> anyhow::Result<()> {
87        // Stage 1: Pre-process feed
88        for plugin in &self.plugins {
89            plugin.pre_process_feed(feed).await?;
90        }
91
92        // Stage 2 & 3: Filter & Transform items
93        let mut filtered_items = Vec::with_capacity(feed.items.len());
94
95        for mut item in std::mem::take(&mut feed.items) {
96            let mut keep = true;
97
98            for plugin in &self.plugins {
99                match plugin.filter_item(&item).await {
100                    Ok(FilterDecision::Keep) => {}
101                    Ok(FilterDecision::Drop) => {
102                        debug!("Plugin '{}' dropped item '{}'", plugin.name(), item.title);
103                        keep = false;
104                        break;
105                    }
106                    Err(e) => {
107                        tracing::warn!(
108                            "Plugin '{}' error filtering item '{}': {}. Defaulting to keep.",
109                            plugin.name(),
110                            item.title,
111                            e
112                        );
113                    }
114                }
115            }
116
117            if keep {
118                for plugin in &self.plugins {
119                    if let Err(e) = plugin.transform_item(&mut item).await {
120                        tracing::warn!(
121                            "Plugin '{}' error transforming item '{}': {}",
122                            plugin.name(),
123                            item.title,
124                            e
125                        );
126                    }
127                }
128                filtered_items.push(item);
129            }
130        }
131
132        feed.items = filtered_items;
133
134        // Stage 4: Post-process feed
135        for plugin in &self.plugins {
136            plugin.post_process_feed(feed).await?;
137        }
138
139        Ok(())
140    }
141}