Skip to content

Commit f813bd2

Browse files
chore: update deps, cleanup
Signed-off-by: Henry Gressmann <[email protected]>
1 parent a9e9f90 commit f813bd2

File tree

14 files changed

+61
-64
lines changed

14 files changed

+61
-64
lines changed

Cargo.lock

Lines changed: 5 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ reqwest={version="0.12", default-features=false, features=[
6666
]}
6767

6868
# database
69-
duckdb={version="1.0", git="https://github.com/explodingcamera-contrib/duckdb-rs", features=[
69+
duckdb={version="1.1", git="https://github.com/explodingcamera-contrib/duckdb-rs", features=[
7070
"bundled",
7171
"time",
7272
"r2d2",

data/licenses-npm.json

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

src/app/core/geoip.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,8 @@ impl LiwanGeoIP {
5252
}
5353

5454
let edition = geoip.maxmind_edition.as_deref().unwrap_or("GeoLite2-City");
55-
let default_path = PathBuf::from(config.data_dir.clone()).join(format!("./geoip/{}.mmdb", edition));
56-
let path = geoip.maxmind_db_path.as_ref().map(PathBuf::from).unwrap_or(default_path);
55+
let default_path = PathBuf::from(config.data_dir.clone()).join(format!("./geoip/{edition}.mmdb"));
56+
let path = geoip.maxmind_db_path.as_ref().map_or(default_path, PathBuf::from);
5757
if let Some(parent) = path.parent() {
5858
std::fs::create_dir_all(parent)?;
5959
}
@@ -84,8 +84,8 @@ impl LiwanGeoIP {
8484
let reader = self.reader.read().map_err(|_| eyre::eyre!("Failed to acquire GeoIP reader lock"))?;
8585
let reader = reader.as_ref().ok_or_eyre("GeoIP database not found")?;
8686
let lookup: maxminddb::geoip2::City = reader.lookup(*ip)?;
87-
let city = lookup.city.and_then(|city| city.names.and_then(|names| names.get("en").map(|s| s.to_string())));
88-
let country_code = lookup.country.and_then(|country| country.iso_code.map(|s| s.to_string()));
87+
let city = lookup.city.and_then(|city| city.names.and_then(|names| names.get("en").map(|s| (*s).to_string())));
88+
let country_code = lookup.country.and_then(|country| country.iso_code.map(ToString::to_string));
8989
Ok(LookupResult { city, country_code })
9090
}
9191

@@ -103,10 +103,7 @@ impl LiwanGeoIP {
103103
let db_md5 = if db_exists { file_md5(&self.path)? } else { String::new() };
104104

105105
let mut update = false;
106-
if !db_exists {
107-
tracing::info!("GeoIP database doesn't exist, attempting to download...");
108-
update = true;
109-
} else {
106+
if db_exists {
110107
match get_latest_md5(&maxmind_edition, &maxmind_account_id, &maxmind_license_key).await {
111108
Ok(latest_md5) => {
112109
if latest_md5 != db_md5 {
@@ -118,6 +115,9 @@ impl LiwanGeoIP {
118115
tracing::warn!(error = ?e, "Failed to get latest MaxMind database MD5 hash, skipping update");
119116
}
120117
};
118+
} else {
119+
tracing::info!("GeoIP database doesn't exist, attempting to download...");
120+
update = true;
121121
}
122122

123123
if update {
@@ -175,7 +175,7 @@ pub fn keep_updated(geoip: Option<LiwanGeoIP>) {
175175
}
176176

177177
async fn get_latest_md5(edition: &str, account_id: &str, license_key: &str) -> Result<String> {
178-
let url = format!("{}{}{}", BASE_URL, METADATA_ENDPOINT, edition);
178+
let url = format!("{BASE_URL}{METADATA_ENDPOINT}{edition}");
179179
let client = reqwest::Client::new();
180180
let response = client
181181
.get(&url)
@@ -204,7 +204,7 @@ fn file_md5(path: &Path) -> Result<String> {
204204
}
205205

206206
async fn download_maxmind_db(edition: &str, account_id: &str, license_key: &str) -> Result<PathBuf> {
207-
let url = format!("{}{}{}/download?suffix=tar.gz", BASE_URL, DOWNLOAD_ENDPOINT, edition);
207+
let url = format!("{BASE_URL}{DOWNLOAD_ENDPOINT}{edition}/download?suffix=tar.gz");
208208

209209
let client = reqwest::Client::new();
210210
let response = client.get(url).basic_auth(account_id, Some(license_key)).send().await?.error_for_status()?;

src/app/core/onboarding.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ pub struct LiwanOnboarding {
1111
}
1212

1313
impl LiwanOnboarding {
14-
pub fn try_new(pool: SqlitePool) -> Result<Self> {
14+
pub fn try_new(pool: &SqlitePool) -> Result<Self> {
1515
let onboarding = {
1616
tracing::debug!("Checking if an onboarding token needs to be generated");
1717
let conn = pool.get()?;

src/app/core/reports.rs

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ fn filter_sql(filters: &[DimensionFilter]) -> Result<(String, ParamVec)> {
113113
let mut params = ParamVec::new();
114114

115115
if filters.is_empty() {
116-
return Ok(("".to_owned(), params));
116+
return Ok((String::new(), params));
117117
}
118118

119119
let filter_clauses = filters
@@ -138,7 +138,7 @@ fn filter_sql(filters: &[DimensionFilter]) -> Result<(String, ParamVec)> {
138138
};
139139

140140
if inversed {
141-
format!("not {}", sql)
141+
format!("not {sql}")
142142
} else {
143143
sql.to_owned()
144144
}
@@ -165,29 +165,29 @@ fn filter_sql(filters: &[DimensionFilter]) -> Result<(String, ParamVec)> {
165165
}
166166

167167
Ok(match filter.dimension {
168-
Dimension::Url => format!("concat(fqdn, path) {}", filter_value),
169-
Dimension::Path => format!("path {}", filter_value),
170-
Dimension::Fqdn => format!("fqdn {}", filter_value),
171-
Dimension::Referrer => format!("referrer {}", filter_value),
172-
Dimension::Platform => format!("platform {}", filter_value),
173-
Dimension::Browser => format!("browser {}", filter_value),
174-
Dimension::Mobile => format!("mobile::text {}", filter_value),
175-
Dimension::Country => format!("country {}", filter_value),
176-
Dimension::City => format!("city {}", filter_value),
168+
Dimension::Url => format!("concat(fqdn, path) {filter_value}"),
169+
Dimension::Path => format!("path {filter_value}"),
170+
Dimension::Fqdn => format!("fqdn {filter_value}"),
171+
Dimension::Referrer => format!("referrer {filter_value}"),
172+
Dimension::Platform => format!("platform {filter_value}"),
173+
Dimension::Browser => format!("browser {filter_value}"),
174+
Dimension::Mobile => format!("mobile::text {filter_value}"),
175+
Dimension::Country => format!("country {filter_value}"),
176+
Dimension::City => format!("city {filter_value}"),
177177
})
178178
})
179179
.collect::<Result<Vec<String>>>()?;
180180

181181
Ok((format!("and ({})", filter_clauses.join(" and ")), params))
182182
}
183183

184-
fn metric_sql(metric: &Metric) -> Result<String> {
185-
Ok(match metric {
184+
fn metric_sql(metric: Metric) -> String {
185+
match metric {
186186
Metric::Views => "count(sd.created_at)",
187187
Metric::UniqueVisitors => "count(distinct sd.visitor_id)",
188188
Metric::Sessions => "count(distinct sd.visitor_id || '-' || date_trunc('minute', timestamp 'epoch' + interval '1 second' * cast(floor(extract(epoch from created_at) / 1800) * 1800 as bigint)))",
189189
Metric::AvgViewsPerSession => "count(sd.created_at) / count(distinct sd.visitor_id)",
190-
}.to_owned())
190+
}.to_owned()
191191
}
192192

193193
pub fn online_users(conn: &DuckDBConn, entities: &[String]) -> Result<u64> {
@@ -227,7 +227,7 @@ pub fn overall_report(
227227
let mut params = ParamVec::new();
228228

229229
let (filters_sql, filters_params) = filter_sql(filters)?;
230-
let metric_sql = metric_sql(metric)?;
230+
let metric_sql = metric_sql(*metric);
231231

232232
let entity_vars = repeat_vars(entities.len());
233233

@@ -292,12 +292,12 @@ pub fn overall_report(
292292

293293
match metric {
294294
Metric::Views | Metric::UniqueVisitors | Metric::Sessions => {
295-
let rows = stmt.query_map(duckdb::params_from_iter(params), |row| Ok(row.get(1)?))?;
295+
let rows = stmt.query_map(duckdb::params_from_iter(params), |row| row.get(1))?;
296296
let report_graph = rows.collect::<Result<Vec<f64>, duckdb::Error>>()?;
297297
Ok(report_graph)
298298
}
299299
Metric::AvgViewsPerSession => {
300-
let rows = stmt.query_map(duckdb::params_from_iter(params), |row| Ok(row.get(1)?))?;
300+
let rows = stmt.query_map(duckdb::params_from_iter(params), |row| row.get(1))?;
301301
let report_graph = rows.collect::<Result<Vec<f64>, duckdb::Error>>()?;
302302
Ok(report_graph)
303303
}
@@ -320,10 +320,10 @@ pub fn overall_stats(
320320
let entity_vars = repeat_vars(entities.len());
321321
let (filters_sql, filters_params) = filter_sql(filters)?;
322322

323-
let metric_total = metric_sql(&Metric::Views)?;
324-
let metric_sessions = metric_sql(&Metric::Sessions)?;
325-
let metric_unique_visitors = metric_sql(&Metric::UniqueVisitors)?;
326-
let metric_avg_views_per_visitor = metric_sql(&Metric::AvgViewsPerSession)?;
323+
let metric_total = metric_sql(Metric::Views);
324+
let metric_sessions = metric_sql(Metric::Sessions);
325+
let metric_unique_visitors = metric_sql(Metric::UniqueVisitors);
326+
let metric_avg_views_per_visitor = metric_sql(Metric::AvgViewsPerSession);
327327

328328
params.push(range.start());
329329
params.push(range.end());
@@ -386,7 +386,7 @@ pub fn dimension_report(
386386
let entity_vars = repeat_vars(entities.len());
387387
let (filters_sql, filters_params) = filter_sql(filters)?;
388388

389-
let metric_column = metric_sql(metric)?;
389+
let metric_column = metric_sql(*metric);
390390
let (dimension_column, group_by_columns) = match dimension {
391391
Dimension::Url => ("concat(fqdn, path)", "fqdn, path"),
392392
Dimension::Path => ("path", "path"),

src/app/mod.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ impl Liwan {
6161
geoip: core::geoip::LiwanGeoIP::try_new(config.clone(), conn_app.clone())?,
6262

6363
events: LiwanEvents::try_new(conn_events.clone(), conn_app.clone())?,
64-
onboarding: LiwanOnboarding::try_new(conn_app.clone())?,
64+
onboarding: LiwanOnboarding::try_new(&conn_app)?,
6565
sessions: LiwanSessions::new(conn_app.clone()),
6666
entities: LiwanEntities::new(conn_app.clone()),
6767
projects: LiwanProjects::new(conn_app.clone()),
@@ -82,7 +82,7 @@ impl Liwan {
8282
geoip: core::geoip::LiwanGeoIP::try_new(config.clone(), conn_app.clone())?,
8383

8484
events: LiwanEvents::try_new(conn_events.clone(), conn_app.clone())?,
85-
onboarding: LiwanOnboarding::try_new(conn_app.clone())?,
85+
onboarding: LiwanOnboarding::try_new(&conn_app)?,
8686
sessions: LiwanSessions::new(conn_app.clone()),
8787
entities: LiwanEntities::new(conn_app.clone()),
8888
projects: LiwanProjects::new(conn_app.clone()),
@@ -117,16 +117,16 @@ impl Liwan {
117117
let projects = [("public-project", "Public Project", true), ("private-project", "Private Project", false)];
118118
let users = [("admin", "admin", UserRole::Admin), ("user", "user", UserRole::User)];
119119

120-
for (username, password, role) in users.iter() {
121-
self.users.create(username, password, *role, &[])?;
120+
for (username, password, role) in users {
121+
self.users.create(username, password, role, &[])?;
122122
}
123123

124-
for (project_id, display_name, public) in projects.iter() {
124+
for (project_id, display_name, public) in projects {
125125
self.projects.create(
126126
&models::Project {
127127
id: project_id.to_string(),
128128
display_name: display_name.to_string(),
129-
public: *public,
129+
public,
130130
secret: None,
131131
},
132132
&[],
@@ -135,10 +135,10 @@ impl Liwan {
135135

136136
let start = OffsetDateTime::now_utc().checked_sub(time::Duration::days(365)).unwrap();
137137
let end = OffsetDateTime::now_utc();
138-
for (entity_id, display_name, fqdn, project_ids) in entities.iter() {
138+
for (entity_id, display_name, fqdn, project_ids) in entities {
139139
self.entities.create(
140140
&models::Entity { id: entity_id.to_string(), display_name: display_name.to_string() },
141-
project_ids,
141+
&project_ids,
142142
)?;
143143
let events = crate::utils::seed::random_events(
144144
(start, end),

src/config.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,7 @@ fn default_data_dir() -> String {
1919
{
2020
let home = std::env::var("HOME").ok().unwrap_or_else(|| "/root".to_string());
2121
std::env::var("XDG_DATA_HOME")
22-
.map(|data_home| format!("{data_home}/liwan/data"))
23-
.unwrap_or_else(|_| format!("{home}/.local/share/liwan/data"))
22+
.map_or_else(|_| format!("{home}/.local/share/liwan/data"), |data_home| format!("{data_home}/liwan/data"))
2423
}
2524

2625
#[cfg(not(target_family = "unix"))]
@@ -43,6 +42,7 @@ pub struct Config {
4342
pub duckdb: Option<DuckdbConfig>,
4443
}
4544

45+
#[must_use]
4646
pub fn default_maxmind_edition() -> Option<String> {
4747
Some("GeoLite2-City".to_string())
4848
}
@@ -108,7 +108,7 @@ impl Config {
108108
config = config
109109
.join(Toml::file(format!("{config_dir}/liwan/config.toml")))
110110
.join(Toml::file(format!("{config_dir}/liwan/liwan.config.toml")))
111-
.join(Toml::file(format!("{config_dir}/liwan.config.toml")))
111+
.join(Toml::file(format!("{config_dir}/liwan.config.toml")));
112112
}
113113

114114
let config: Config = config

src/utils/seed.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,9 +78,7 @@ fn random_el<T>(slice: &[T], scale: f64) -> &T {
7878
let mut rng = rand::thread_rng();
7979
let len = slice.len();
8080

81-
if len == 0 {
82-
panic!("Cannot choose from an empty slice");
83-
}
81+
assert!(len != 0, "Cannot choose from an empty slice");
8482

8583
let uniform_random: f64 = rng.gen();
8684
let weighted_random = (uniform_random.powf(1.0 - scale)).min(1.0);

src/web/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ pub fn create_router(app: Liwan, events: Sender<Event>) -> impl IntoEndpoint {
7878
.nest("/api", api_router)
7979
.at("/script.js", serve_script)
8080
.nest("/", EmbeddedFilesEndpoint::<Files>::new())
81-
.with(AddData::new(app.clone()))
81+
.with(AddData::new(app))
8282
.with(AddData::new(events))
8383
.with(CookieJarManager::new())
8484
.with(Compression::new().algorithms([CompressionAlgo::BR, CompressionAlgo::GZIP]))

0 commit comments

Comments
 (0)