mirror of
https://codeberg.org/icewind/rss-webhook-trigger.git
synced 2026-11-30 04:00:49 +01:00
make sync, switch to ureq
This commit is contained in:
parent
bdf01dced0
commit
ae1ef0657a
7 changed files with 603 additions and 948 deletions
|
|
@ -1,5 +1,4 @@
|
|||
use crate::error::ConfigError;
|
||||
use reqwest::header::{HeaderValue, InvalidHeaderValue};
|
||||
use secretfile::{load, SecretError};
|
||||
use serde::de::Error;
|
||||
use serde::{Deserialize, Deserializer};
|
||||
|
|
@ -8,7 +7,8 @@ use std::collections::HashMap;
|
|||
use std::convert::{TryFrom, TryInto};
|
||||
use std::fs::read_to_string;
|
||||
use std::path::Path;
|
||||
use tokio::time::Duration;
|
||||
use std::time::Duration;
|
||||
use ureq::http::header::{HeaderValue, InvalidHeaderValue};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct Config {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
use reqwest::StatusCode;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
use thiserror::Error;
|
||||
use ureq::http::StatusCode;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ParseFeedError {
|
||||
|
|
@ -16,7 +16,7 @@ pub enum ParseFeedError {
|
|||
#[derive(Debug, Error)]
|
||||
pub enum FetchFeedError {
|
||||
#[error("Error while fetching feed: {0:#}")]
|
||||
Network(#[from] reqwest::Error),
|
||||
Network(#[from] ureq::Error),
|
||||
#[error("Error while parsing feed: {0:#}")]
|
||||
Parse(#[from] ParseFeedError),
|
||||
#[error("Docker hub returned a server error {0}")]
|
||||
|
|
@ -42,7 +42,7 @@ pub enum ConfigError {
|
|||
#[derive(Debug, Error)]
|
||||
pub enum HubError {
|
||||
#[error("Error while fetching docker hub info: {0:#}")]
|
||||
Network(#[from] reqwest::Error),
|
||||
Network(#[from] ureq::Error),
|
||||
#[error("Error while parsing hub response: {0:#}")]
|
||||
Parse(#[from] serde_json::Error),
|
||||
#[error("Docker hub returned a server error {0}")]
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
use reqwest::header::{
|
||||
HeaderMap, HeaderValue, ETAG, IF_MODIFIED_SINCE, IF_NONE_MATCH, LAST_MODIFIED, RETRY_AFTER,
|
||||
};
|
||||
use reqwest::{Response, StatusCode};
|
||||
use std::future::Future;
|
||||
use std::time::{Duration, Instant};
|
||||
use time::format_description::well_known::Rfc2822;
|
||||
use time::OffsetDateTime;
|
||||
use ureq::http::header::{
|
||||
HeaderMap, HeaderValue, ETAG, IF_MODIFIED_SINCE, IF_NONE_MATCH, LAST_MODIFIED, RETRY_AFTER,
|
||||
};
|
||||
use ureq::http::{Response, StatusCode};
|
||||
use ureq::Body;
|
||||
|
||||
/// waiting 6 hours after a 429 should be slow enough for everyone
|
||||
const DEFAULT_BACKOFF: Duration = Duration::from_secs(6 * 60 * 60);
|
||||
|
|
@ -74,12 +74,6 @@ impl CacheHeaders {
|
|||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn headers(&self) -> HeaderMap {
|
||||
let mut headers = HeaderMap::new();
|
||||
self.set_headers(&mut headers);
|
||||
headers
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FetchPlan {
|
||||
|
|
@ -168,8 +162,8 @@ impl<T, E> FetchResponse<T, E> {
|
|||
}
|
||||
}
|
||||
|
||||
impl<E> FetchResponse<Response, E> {
|
||||
pub fn from_result(result: Result<Response, E>) -> FetchResponse<Response, E> {
|
||||
impl<E> FetchResponse<Response<Body>, E> {
|
||||
pub fn from_result(result: Result<Response<Body>, E>) -> FetchResponse<Response<Body>, E> {
|
||||
match result {
|
||||
Ok(response) => {
|
||||
let cache_header = CacheHeaders::from_headers(response.headers());
|
||||
|
|
@ -231,16 +225,15 @@ impl<E> FetchResponse<Response, E> {
|
|||
}
|
||||
|
||||
impl<T, E> FetchResponse<T, E> {
|
||||
pub async fn map<U, Fut, F>(self, f: F) -> FetchResponse<U, E>
|
||||
pub fn map<U, F>(self, f: F) -> FetchResponse<U, E>
|
||||
where
|
||||
Fut: Future<Output = U>,
|
||||
F: Fn(T) -> Fut,
|
||||
F: Fn(T) -> U,
|
||||
{
|
||||
match self {
|
||||
FetchResponse::Retry { time, headers } => FetchResponse::Retry { time, headers },
|
||||
FetchResponse::Ok { headers, response } => FetchResponse::Ok {
|
||||
headers,
|
||||
response: f(response).await,
|
||||
response: f(response),
|
||||
},
|
||||
FetchResponse::NotModified { headers } => FetchResponse::NotModified { headers },
|
||||
FetchResponse::Error { error, headers } => FetchResponse::Error { error, headers },
|
||||
|
|
@ -275,10 +268,7 @@ impl<T, E> FetchResponse<Result<T, E>, E> {
|
|||
response: Err(error),
|
||||
} => FetchResponse::Error { error, headers },
|
||||
FetchResponse::NotModified { headers } => FetchResponse::NotModified { headers },
|
||||
FetchResponse::Error { error, headers } => FetchResponse::Error {
|
||||
error,
|
||||
headers,
|
||||
},
|
||||
FetchResponse::Error { error, headers } => FetchResponse::Error { error, headers },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
33
src/hub.rs
33
src/hub.rs
|
|
@ -1,40 +1,43 @@
|
|||
use crate::error::HubError;
|
||||
use crate::fetcher::{CacheHeaders, FetchResponse};
|
||||
use reqwest::{Client};
|
||||
use reqwest::header::{HeaderValue, USER_AGENT};
|
||||
use crate::FETCHER_USER_AGENT;
|
||||
use serde::Deserialize;
|
||||
use time::OffsetDateTime;
|
||||
use tracing::instrument;
|
||||
use crate::FETCHER_USER_AGENT;
|
||||
use ureq::http::header::USER_AGENT;
|
||||
use ureq::http::HeaderValue;
|
||||
use ureq::Agent;
|
||||
|
||||
#[instrument(skip(client))]
|
||||
pub async fn tags(
|
||||
client: &Client,
|
||||
pub fn tags(
|
||||
client: &Agent,
|
||||
user: &str,
|
||||
repo: &str,
|
||||
cache_headers: &CacheHeaders,
|
||||
) -> FetchResponse<Vec<HubTag>, HubError> {
|
||||
let result = client
|
||||
let mut req = client
|
||||
.get(format!(
|
||||
"https://hub.docker.com/v2/repositories/{}/{}/tags",
|
||||
user, repo
|
||||
))
|
||||
.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 result = req.call();
|
||||
|
||||
FetchResponse::from_result(result)
|
||||
.map_err(HubError::Network)
|
||||
.check_status_code(HubError::ClientError, HubError::ServerError)
|
||||
.map(|response| async {
|
||||
.map(|response| {
|
||||
response
|
||||
.text()
|
||||
.await
|
||||
.into_body()
|
||||
.read_to_string()
|
||||
.map_err(HubError::Network)
|
||||
.and_then(|text| serde_json::from_str::<HubTagResponse>(&text).map_err(HubError::Parse))
|
||||
.and_then(|text| {
|
||||
serde_json::from_str::<HubTagResponse>(&text).map_err(HubError::Parse)
|
||||
})
|
||||
.map(|result| result.results)
|
||||
}).await.flatten()
|
||||
})
|
||||
.flatten()
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
|
|
|
|||
96
src/main.rs
96
src/main.rs
|
|
@ -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();
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue