pub mod builtin;
pub mod rhai_plugin;
use crate::model::{Feed, FeedItem};
use async_trait::async_trait;
use tracing::{debug, info};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilterDecision {
Keep,
Drop,
}
#[async_trait]
pub trait Plugin: Send + Sync {
fn name(&self) -> &str;
async fn pre_process_feed(&self, _feed: &mut Feed) -> anyhow::Result<()> {
Ok(())
}
async fn filter_item(&self, _item: &FeedItem) -> anyhow::Result<FilterDecision> {
Ok(FilterDecision::Keep)
}
async fn transform_item(&self, _item: &mut FeedItem) -> anyhow::Result<()> {
Ok(())
}
async fn post_process_feed(&self, _feed: &mut Feed) -> anyhow::Result<()> {
Ok(())
}
async fn on_fetch_error(
&self,
_url: &str,
_title: &str,
_error: &anyhow::Error,
) -> Option<Feed> {
None
}
}
pub struct PluginPipeline {
plugins: Vec<Box<dyn Plugin>>,
}
impl PluginPipeline {
pub fn new() -> Self {
Self {
plugins: Vec::new(),
}
}
pub fn add_plugin(&mut self, plugin: Box<dyn Plugin>) {
info!("Registered plugin: {}", plugin.name());
self.plugins.push(plugin);
}
pub async fn handle_fetch_error(
&self,
url: &str,
title: &str,
error: &anyhow::Error,
) -> Option<Feed> {
for plugin in &self.plugins {
if let Some(fallback) = plugin.on_fetch_error(url, title, error).await {
return Some(fallback);
}
}
None
}
pub async fn process(&self, feed: &mut Feed) -> anyhow::Result<()> {
for plugin in &self.plugins {
plugin.pre_process_feed(feed).await?;
}
let mut filtered_items = Vec::with_capacity(feed.items.len());
for mut item in std::mem::take(&mut feed.items) {
let mut keep = true;
for plugin in &self.plugins {
match plugin.filter_item(&item).await {
Ok(FilterDecision::Keep) => {}
Ok(FilterDecision::Drop) => {
debug!("Plugin '{}' dropped item '{}'", plugin.name(), item.title);
keep = false;
break;
}
Err(e) => {
tracing::warn!(
"Plugin '{}' error filtering item '{}': {}. Defaulting to keep.",
plugin.name(),
item.title,
e
);
}
}
}
if keep {
for plugin in &self.plugins {
if let Err(e) = plugin.transform_item(&mut item).await {
tracing::warn!(
"Plugin '{}' error transforming item '{}': {}",
plugin.name(),
item.title,
e
);
}
}
filtered_items.push(item);
}
}
feed.items = filtered_items;
for plugin in &self.plugins {
plugin.post_process_feed(feed).await?;
}
Ok(())
}
}
impl Default for PluginPipeline {
fn default() -> Self {
Self::new()
}
}