make sync, switch to ureq

This commit is contained in:
Robin Appelman 2026-10-14 00:14:04 +02:00
commit ae1ef0657a
7 changed files with 603 additions and 948 deletions

View file

@ -7,24 +7,31 @@ use crate::config::{Config, FeedConfig};
use crate::error::{FetchError, FetchFeedError, HubError, ParseFeedError};
use crate::fetcher::{next_fetch, CacheHeaders, FetchPlan, FetchResponse};
use main_error::MainResult;
use reqwest::{Client, Response};
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::future::ready;
use std::hash::{Hash, Hasher};
use std::str::FromStr;
use std::time::{Duration};
use reqwest::header::{HeaderValue, USER_AGENT};
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::sleep;
use std::time::Duration;
use syndication::Feed;
use tokio::select;
use tokio::signal::ctrl_c;
use tokio::time::sleep;
use tracing::{debug, error, info, instrument, warn};
use ureq::http::header::{HeaderValue, USER_AGENT};
use ureq::http::Response;
use ureq::{Agent, Body};
const FETCHER_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"), " (", env!("CARGO_PKG_REPOSITORY"), ")");
const FETCHER_USER_AGENT: &str = concat!(
env!("CARGO_PKG_NAME"),
"/",
env!("CARGO_PKG_VERSION"),
" (",
env!("CARGO_PKG_REPOSITORY"),
")"
);
#[tokio::main]
async fn main() -> MainResult {
static RUNNING: AtomicBool = AtomicBool::new(true);
fn main() -> MainResult {
tracing_subscriber::fmt::init();
let mut args = std::env::args();
let bin = args.next().unwrap();
@ -41,37 +48,33 @@ async fn main() -> MainResult {
info!("Running rss trigger for {} feeds", config.feed.len());
let ctrl_c = async {
ctrl_c().await.ok();
};
ctrlc::set_handler(|| RUNNING.store(false, Ordering::SeqCst))?;
main_loop(config);
select! {
_ = ctrl_c => {},
_ = main_loop(config) => {}
}
Ok(())
}
async fn main_loop(config: Config) {
fn main_loop(config: Config) {
let mut fetcher = FeedFetcher::new(config.interval());
loop {
while RUNNING.load(Ordering::SeqCst) {
for feed in config.feed.iter() {
match fetcher.check_feed_updated(&feed.feed).await {
match fetcher.check_feed_updated(&feed.feed) {
Ok(true) => {
trigger(&fetcher.client, feed).await;
trigger(&fetcher.client, feed);
}
Err(e) => error!(error = ?e, feed = feed.feed, "failed to check feed"),
Ok(false) => {}
}
}
sleep(config.interval()).await;
sleep(config.interval());
}
}
#[instrument(skip_all, fields(feed = feed.feed))]
async fn trigger(client: &Client, feed: &FeedConfig) {
fn trigger(client: &Agent, feed: &FeedConfig) {
info!("Triggering hook");
let mut req = client
.post(&feed.hook)
@ -79,17 +82,20 @@ async fn trigger(client: &Client, feed: &FeedConfig) {
for (key, value) in &feed.headers {
req = req.header(key, value);
}
if !feed.body.is_null() {
req = req.json(&feed.body);
}
debug!(request = ?req, "sending trigger request");
if let Err(e) = req.send().await.and_then(|res| res.error_for_status()) {
let res = if feed.body.is_null() {
req.send_json(&feed.body)
} else {
req.send_empty()
};
if let Err(e) = res {
error!("{:#}", e);
}
}
pub struct FeedFetcher {
client: Client,
client: Agent,
base_interval: Duration,
cache: HashMap<String, u64>,
fetch_plans: HashMap<String, FetchPlan>,
@ -98,7 +104,7 @@ pub struct FeedFetcher {
impl FeedFetcher {
pub fn new(interval: Duration) -> Self {
FeedFetcher {
client: Client::default(),
client: Agent::new_with_defaults(),
base_interval: interval,
cache: HashMap::default(),
fetch_plans: HashMap::default(),
@ -113,17 +119,18 @@ impl FeedFetcher {
}
#[instrument(skip(self))]
pub async fn check_feed_updated(&mut self, feed: &str) -> Result<bool, FetchError> {
pub fn check_feed_updated(&mut self, feed: &str) -> Result<bool, FetchError> {
if !self.should_update(feed) {
warn!("skipping feed util rate limited expires");
return Ok(false);
}
let plan = self.fetch_plans.remove(feed).unwrap_or_default();
let fetch_result = self.get_feed_key(feed, &plan.headers).await;
let fetch_result = self.get_feed_key(feed, &plan.headers);
let (result, new_plan) = fetch_result.into_result();
let is_retry = new_plan.is_retry();
self.fetch_plans.insert(feed.into(), next_fetch(self.base_interval, Some(new_plan)));
self.fetch_plans
.insert(feed.into(), next_fetch(self.base_interval, Some(new_plan)));
let new_key = result?;
Ok(match (self.cache.get_mut(feed), new_key) {
@ -156,7 +163,7 @@ impl FeedFetcher {
}
#[instrument(skip(self))]
async fn get_feed_key(
fn get_feed_key(
&self,
feed: &str,
cache_headers: &CacheHeaders,
@ -164,15 +171,14 @@ impl FeedFetcher {
if let Some(hub) = feed.strip_prefix("docker-hub://") {
if let Some((user, repo)) = hub.split_once('/') {
hub::tags(&self.client, user, repo, cache_headers)
.await
.map(|tags| {
let mut hasher = DefaultHasher::new();
for tag in tags {
tag.id.hash(&mut hasher);
tag.last_updated.hash(&mut hasher);
}
ready(hasher.finish())
}).await
hasher.finish()
})
.map_err(FetchError::Hub)
} else {
FetchResponse::Error {
@ -182,37 +188,35 @@ impl FeedFetcher {
}
} else {
self.get_rss_feed_key(feed, cache_headers)
.await
.map_err(FetchError::Feed)
}
}
#[instrument(skip(self))]
async fn get_rss_feed_key(
fn get_rss_feed_key(
&self,
feed: &str,
cache_headers: &CacheHeaders,
) -> FetchResponse<u64, FetchFeedError> {
let response = self
let mut req = self
.client
.get(feed)
.headers(cache_headers.headers())
.header(USER_AGENT, HeaderValue::from_static(FETCHER_USER_AGENT))
.send()
.await;
.header(USER_AGENT, HeaderValue::from_static(FETCHER_USER_AGENT));
cache_headers.set_headers(req.headers_mut().unwrap());
let response = req.call();
let plan_result = FetchResponse::from_result(response);
plan_result
.map_err(FetchFeedError::Network)
.check_status_code(FetchFeedError::ClientError, FetchFeedError::ServerError)
.map(parse_rss_response)
.await
.flatten()
}
}
async fn parse_rss_response(response: Response) -> Result<u64, FetchFeedError> {
let content = response.text().await?;
fn parse_rss_response(response: Response<Body>) -> Result<u64, FetchFeedError> {
let content = response.into_body().read_to_string()?;
let channel = Feed::from_str(&content).map_err(ParseFeedError::Parse)?;
let mut hasher = DefaultHasher::new();