Merge remote-tracking branch 'origin/pull/808'

This commit is contained in:
Matthew Esposito 2023-12-26 15:11:44 -05:00
commit f5b54197c4
No known key found for this signature in database
6 changed files with 51 additions and 3 deletions

View File

@ -240,6 +240,7 @@ Assign a default value for each user-modifiable setting by passing environment v
| `SUBSCRIPTIONS` | `+`-delimited list of subreddits (`sub1+sub2+sub3+...`) | _(none)_ | | `SUBSCRIPTIONS` | `+`-delimited list of subreddits (`sub1+sub2+sub3+...`) | _(none)_ |
| `HIDE_AWARDS` | `["on", "off"]` | `off` | | `HIDE_AWARDS` | `["on", "off"]` | `off` |
| `DISABLE_VISIT_REDDIT_CONFIRMATION` | `["on", "off"]` | `off` | | `DISABLE_VISIT_REDDIT_CONFIRMATION` | `["on", "off"]` | `off` |
| `DISABLE_STATS_COLLECTION | Any string to disable | _(none)_ |
You can also configure Libreddit with a configuration file. An example `libreddit.toml` can be found below: You can also configure Libreddit with a configuration file. An example `libreddit.toml` can be found below:

View File

@ -61,6 +61,9 @@
}, },
"LIBREDDIT_PUSHSHIFT_FRONTEND": { "LIBREDDIT_PUSHSHIFT_FRONTEND": {
"required": false "required": false
},
"LIBREDDIT_DISABLE_STATS_COLLECTION": {
"required": false
} }
} }
} }

View File

@ -7,10 +7,11 @@ use libflate::gzip;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use percent_encoding::{percent_encode, CONTROLS}; use percent_encoding::{percent_encode, CONTROLS};
use serde_json::Value; use serde_json::Value;
use std::{io, result::Result}; use std::{io, result::Result, sync::atomic::Ordering::SeqCst};
use crate::dbg_msg; use crate::instance_info::INSTANCE_INFO;
use crate::server::RequestExt; use crate::server::RequestExt;
use crate::{config, dbg_msg};
const REDDIT_URL_BASE: &str = "https://www.reddit.com"; const REDDIT_URL_BASE: &str = "https://www.reddit.com";
@ -127,6 +128,10 @@ fn reddit_head(path: String, quarantine: bool) -> Boxed<Result<Response<Body>, S
/// will recurse on the URL that Reddit provides in the Location HTTP header /// will recurse on the URL that Reddit provides in the Location HTTP header
/// in its response. /// in its response.
fn request(method: &'static Method, path: String, redirect: bool, quarantine: bool) -> Boxed<Result<Response<Body>, String>> { fn request(method: &'static Method, path: String, redirect: bool, quarantine: bool) -> Boxed<Result<Response<Body>, String>> {
// Increment reddit request count. This will include head requests.
if config::get_setting("LIBREDDIT_DISABLE_STATS_COLLECTION").is_none() {
INSTANCE_INFO.reddit_requests.fetch_add(1, SeqCst);
}
// Build Reddit URL from path. // Build Reddit URL from path.
let url = format!("{}{}", REDDIT_URL_BASE, path); let url = format!("{}{}", REDDIT_URL_BASE, path);

View File

@ -68,6 +68,9 @@ pub struct Config {
#[serde(rename = "LIBREDDIT_ROBOTS_DISABLE_INDEXING")] #[serde(rename = "LIBREDDIT_ROBOTS_DISABLE_INDEXING")]
pub(crate) robots_disable_indexing: Option<String>, pub(crate) robots_disable_indexing: Option<String>,
#[serde(rename = "LIBREDDIT_DISABLE_STATS_COLLECTION")]
pub(crate) disable_stats_collection: Option<String>,
#[serde(rename = "LIBREDDIT_PUSHSHIFT_FRONTEND")] #[serde(rename = "LIBREDDIT_PUSHSHIFT_FRONTEND")]
pub(crate) pushshift: Option<String>, pub(crate) pushshift: Option<String>,
} }
@ -102,6 +105,7 @@ impl Config {
default_disable_visit_reddit_confirmation: parse("LIBREDDIT_DEFAULT_DISABLE_VISIT_REDDIT_CONFIRMATION"), default_disable_visit_reddit_confirmation: parse("LIBREDDIT_DEFAULT_DISABLE_VISIT_REDDIT_CONFIRMATION"),
banner: parse("LIBREDDIT_BANNER"), banner: parse("LIBREDDIT_BANNER"),
robots_disable_indexing: parse("LIBREDDIT_ROBOTS_DISABLE_INDEXING"), robots_disable_indexing: parse("LIBREDDIT_ROBOTS_DISABLE_INDEXING"),
disable_stats_collection: parse("LIBREDDIT_DISABLE_STATS_COLLECTION"),
pushshift: parse("LIBREDDIT_PUSHSHIFT_FRONTEND"), pushshift: parse("LIBREDDIT_PUSHSHIFT_FRONTEND"),
} }
} }
@ -125,6 +129,7 @@ fn get_setting_from_config(name: &str, config: &Config) -> Option<String> {
"LIBREDDIT_DEFAULT_DISABLE_VISIT_REDDIT_CONFIRMATION" => config.default_disable_visit_reddit_confirmation.clone(), "LIBREDDIT_DEFAULT_DISABLE_VISIT_REDDIT_CONFIRMATION" => config.default_disable_visit_reddit_confirmation.clone(),
"LIBREDDIT_BANNER" => config.banner.clone(), "LIBREDDIT_BANNER" => config.banner.clone(),
"LIBREDDIT_ROBOTS_DISABLE_INDEXING" => config.robots_disable_indexing.clone(), "LIBREDDIT_ROBOTS_DISABLE_INDEXING" => config.robots_disable_indexing.clone(),
"LIBREDDIT_DISABLE_STATS_COLLECTION" => config.disable_stats_collection.clone(),
"LIBREDDIT_PUSHSHIFT_FRONTEND" => config.pushshift.clone(), "LIBREDDIT_PUSHSHIFT_FRONTEND" => config.pushshift.clone(),
_ => None, _ => None,
} }
@ -179,3 +184,16 @@ fn test_alt_env_config_precedence() {
fn test_default_subscriptions() { fn test_default_subscriptions() {
assert_eq!(get_setting("LIBREDDIT_DEFAULT_SUBSCRIPTIONS"), Some("news+bestof".into())); assert_eq!(get_setting("LIBREDDIT_DEFAULT_SUBSCRIPTIONS"), Some("news+bestof".into()));
} }
#[test]
fn test_stats_collection_empty() {
assert_eq!(get_setting("LIBREDDIT_DISABLE_STATS_COLLECTION"), None);
}
#[test]
#[sealed_test]
fn test_stats_collection_true() {
let config_to_write = r#"LIBREDDIT_DISABLE_STATS_COLLECTION = "1""#;
write("libreddit.toml", config_to_write).unwrap();
assert!(get_setting("LIBREDDIT_DISABLE_STATS_COLLECTION").is_some());
}

View File

@ -1,3 +1,5 @@
use std::sync::atomic::{AtomicU32, Ordering::SeqCst};
use crate::{ use crate::{
config::{Config, CONFIG}, config::{Config, CONFIG},
server::RequestExt, server::RequestExt,
@ -88,6 +90,8 @@ pub(crate) struct InstanceInfo {
deploy_date: String, deploy_date: String,
compile_mode: String, compile_mode: String,
deploy_unix_ts: i64, deploy_unix_ts: i64,
pub(crate) reddit_requests: AtomicU32,
pub(crate) total_requests: AtomicU32,
config: Config, config: Config,
} }
@ -103,6 +107,8 @@ impl InstanceInfo {
compile_mode: "Release".into(), compile_mode: "Release".into(),
deploy_unix_ts: OffsetDateTime::now_local().unwrap_or_else(|_| OffsetDateTime::now_utc()).unix_timestamp(), deploy_unix_ts: OffsetDateTime::now_local().unwrap_or_else(|_| OffsetDateTime::now_utc()).unix_timestamp(),
config: CONFIG.clone(), config: CONFIG.clone(),
reddit_requests: AtomicU32::new(0),
total_requests: AtomicU32::new(0),
} }
} }
fn to_table(&self) -> String { fn to_table(&self) -> String {
@ -122,6 +128,9 @@ impl InstanceInfo {
["Deploy timestamp", &self.deploy_unix_ts.to_string()], ["Deploy timestamp", &self.deploy_unix_ts.to_string()],
["Compile mode", &self.compile_mode], ["Compile mode", &self.compile_mode],
["SFW only", &convert(&self.config.sfw_only)], ["SFW only", &convert(&self.config.sfw_only)],
["Disable stats collection", &convert(&self.config.disable_stats_collection)],
["Reddit request count", &self.reddit_requests.load(SeqCst).to_string()],
["Total request count", &self.total_requests.load(SeqCst).to_string()],
["Pushshift frontend", &convert(&self.config.pushshift)], ["Pushshift frontend", &convert(&self.config.pushshift)],
//TODO: fallback to crate::config::DEFAULT_PUSHSHIFT_FRONTEND //TODO: fallback to crate::config::DEFAULT_PUSHSHIFT_FRONTEND
]) ])
@ -157,6 +166,9 @@ impl InstanceInfo {
Deploy timestamp: {}\n Deploy timestamp: {}\n
Compile mode: {}\n Compile mode: {}\n
SFW only: {:?}\n SFW only: {:?}\n
Disable stats collection: {:?}\n
Reddit request count: {}\n
Total request count: {}\n
Pushshift frontend: {:?}\n Pushshift frontend: {:?}\n
Config:\n Config:\n
Banner: {:?}\n Banner: {:?}\n
@ -178,6 +190,9 @@ impl InstanceInfo {
self.deploy_unix_ts, self.deploy_unix_ts,
self.compile_mode, self.compile_mode,
self.config.sfw_only, self.config.sfw_only,
self.config.disable_stats_collection,
self.reddit_requests.load(SeqCst),
self.total_requests.load(SeqCst),
self.config.pushshift, self.config.pushshift,
self.config.banner, self.config.banner,
self.config.default_hide_awards, self.config.default_hide_awards,

View File

@ -20,10 +20,11 @@ use std::{
result::Result, result::Result,
str::{from_utf8, Split}, str::{from_utf8, Split},
string::ToString, string::ToString,
sync::atomic::Ordering::SeqCst,
}; };
use time::Duration; use time::Duration;
use crate::dbg_msg; use crate::{config, dbg_msg, instance_info::INSTANCE_INFO};
type BoxResponse = Pin<Box<dyn Future<Output = Result<Response<Body>, String>> + Send>>; type BoxResponse = Pin<Box<dyn Future<Output = Result<Response<Body>, String>> + Send>>;
@ -234,6 +235,11 @@ impl Server {
match router.recognize(&format!("/{}{}", req.method().as_str(), path)) { match router.recognize(&format!("/{}{}", req.method().as_str(), path)) {
// If a route was configured for this path // If a route was configured for this path
Ok(found) => { Ok(found) => {
if config::get_setting("LIBREDDIT_DISABLE_STATS_COLLECTION").is_none() {
// Add to total_requests count
INSTANCE_INFO.total_requests.fetch_add(1, SeqCst);
}
let mut parammed = req; let mut parammed = req;
parammed.set_params(found.params().clone()); parammed.set_params(found.params().clone());