Skip to content

Commit

Permalink
*: Switch to anyhow::Result (fixes #50)
Browse files Browse the repository at this point in the history
  • Loading branch information
AMDmi3 committed Dec 28, 2024
1 parent 1c02662 commit 71c97e8
Show file tree
Hide file tree
Showing 14 changed files with 48 additions and 67 deletions.
4 changes: 2 additions & 2 deletions repology-vulnupdater/src/datetime.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
// SPDX-FileCopyrightText: Copyright 2024 Dmitry Marakasov <[email protected]>
// SPDX-License-Identifier: GPL-3.0-or-later

use anyhow::Error;
use anyhow::Result;
use chrono::{DateTime, NaiveDateTime, Utc};

pub fn parse_utc_datetime(date: &str) -> Result<DateTime<Utc>, Error> {
pub fn parse_utc_datetime(date: &str) -> Result<DateTime<Utc>> {
Ok(NaiveDateTime::parse_from_str(date, "%Y-%m-%dT%H:%M:%S%.3f")?.and_utc())
}

Expand Down
8 changes: 4 additions & 4 deletions repology-vulnupdater/src/fetcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use std::borrow::Cow;
use std::time::{Duration, Instant};

use anyhow::{Error, bail};
use anyhow::{Result, bail};
use chrono::{TimeDelta, Utc};
use metrics::counter;
use serde::Deserialize;
Expand All @@ -31,7 +31,7 @@ pub struct NvdFetcher {
}

impl NvdFetcher {
pub fn new() -> Result<Self, Error> {
pub fn new() -> Result<Self> {
let inner = Inner {
client: reqwest::Client::builder()
.user_agent(USER_AGENT)
Expand All @@ -45,7 +45,7 @@ impl NvdFetcher {
})
}

async fn fetch(&self, url: &str) -> Result<String, Error> {
async fn fetch(&self, url: &str) -> Result<String> {
let mut inner = self.inner.lock().await;

if let Some(elapsed) = inner.last_request_time.map(|instant| instant.elapsed()) {
Expand Down Expand Up @@ -104,7 +104,7 @@ impl<'a> Paginator<'a> {
}
}

pub async fn fetch_next(&mut self) -> Result<Option<String>, Error> {
pub async fn fetch_next(&mut self) -> Result<Option<String>> {
if let Some(total_results) = self.total_results {
if self.start_index >= total_results {
return Ok(None);
Expand Down
4 changes: 2 additions & 2 deletions repology-vulnupdater/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ mod vulnupdater;

use std::cell::LazyCell;

use anyhow::{Context, Error, bail};
use anyhow::{Context, Result, bail};
use clap::Parser as _;
use sqlx::Executor;
use sqlx::postgres::PgPoolOptions;
Expand All @@ -30,7 +30,7 @@ use status_tracker::SourceUpdateStatusTracker;
use vulnupdater::{Datasource, VulnUpdater};

#[tokio::main]
async fn main() -> Result<(), Error> {
async fn main() -> Result<()> {
let args = Args::parse();

if let Some(log_directory) = &args.log_directory {
Expand Down
6 changes: 3 additions & 3 deletions repology-vulnupdater/src/processors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
pub mod cpe;
pub mod cve;

use anyhow::Error;
use anyhow::Result;
use async_trait::async_trait;

pub struct DatasourceProcessStatus {
Expand All @@ -13,6 +13,6 @@ pub struct DatasourceProcessStatus {

#[async_trait]
pub trait DatasourceProcessor {
async fn process(&self, data: &str) -> Result<DatasourceProcessStatus, Error>;
async fn finalize(&self) -> Result<(), Error>;
async fn process(&self, data: &str) -> Result<DatasourceProcessStatus>;
async fn finalize(&self) -> Result<()>;
}
6 changes: 3 additions & 3 deletions repology-vulnupdater/src/processors/cpe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ mod schema;

use std::str::FromStr as _;

use anyhow::Error;
use anyhow::Result;
use async_trait::async_trait;
use indoc::indoc;
use metrics::counter;
Expand Down Expand Up @@ -52,7 +52,7 @@ impl<'a> CpeProcessor<'a> {

#[async_trait]
impl DatasourceProcessor for CpeProcessor<'_> {
async fn process(&self, data: &str) -> Result<DatasourceProcessStatus, Error> {
async fn process(&self, data: &str) -> Result<DatasourceProcessStatus> {
counter!("repology_vulnupdater_processor_runs_total", "processor" => "cpe", "stage" => "processing").increment(1);
counter!("repology_vulnupdater_processor_data_bytes_total", "processor" => "cpe")
.increment(data.len() as u64);
Expand Down Expand Up @@ -174,7 +174,7 @@ impl DatasourceProcessor for CpeProcessor<'_> {
})
}

async fn finalize(&self) -> Result<(), Error> {
async fn finalize(&self) -> Result<()> {
if self.skip_finalization {
return Ok(());
}
Expand Down
6 changes: 3 additions & 3 deletions repology-vulnupdater/src/processors/cve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
mod cpe_matches;
mod schema;

use anyhow::Error;
use anyhow::Result;
use async_trait::async_trait;
use indoc::indoc;
use metrics::counter;
Expand Down Expand Up @@ -36,7 +36,7 @@ impl<'a> CveProcessor<'a> {

#[async_trait]
impl DatasourceProcessor for CveProcessor<'_> {
async fn process(&self, data: &str) -> Result<DatasourceProcessStatus, Error> {
async fn process(&self, data: &str) -> Result<DatasourceProcessStatus> {
counter!("repology_vulnupdater_processor_runs_total", "processor" => "cve", "stage" => "processing").increment(1);
counter!("repology_vulnupdater_processor_data_bytes_total", "processor" => "cve")
.increment(data.len() as u64);
Expand Down Expand Up @@ -124,7 +124,7 @@ impl DatasourceProcessor for CveProcessor<'_> {
Ok(DatasourceProcessStatus { num_changes })
}

async fn finalize(&self) -> Result<(), Error> {
async fn finalize(&self) -> Result<()> {
if self.skip_finalization {
return Ok(());
}
Expand Down
14 changes: 5 additions & 9 deletions repology-vulnupdater/src/status_tracker.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: Copyright 2024 Dmitry Marakasov <[email protected]>
// SPDX-License-Identifier: GPL-3.0-or-later

use anyhow::Error;
use anyhow::Result;
use chrono::{DateTime, Utc};
use indoc::indoc;
use sqlx::{FromRow, PgPool};
Expand All @@ -23,7 +23,7 @@ impl<'a> SourceUpdateStatusTracker<'a> {
Self { pool }
}

pub async fn get(&self, name: &str) -> Result<SourceUpdateStatus, Error> {
pub async fn get(&self, name: &str) -> Result<SourceUpdateStatus> {
Ok(sqlx::query_as(indoc! {"
SELECT current_full_update_offset, last_full_update_time, last_update_time
FROM update_status
Expand All @@ -35,11 +35,7 @@ impl<'a> SourceUpdateStatusTracker<'a> {
.unwrap_or_default())
}

pub async fn register_update_attempt(
&self,
name: &str,
time: DateTime<Utc>,
) -> Result<(), Error> {
pub async fn register_update_attempt(&self, name: &str, time: DateTime<Utc>) -> Result<()> {
sqlx::query(indoc! {"
INSERT INTO update_status(name, last_update_attempt_time)
VALUES ($1, $2)
Expand All @@ -52,7 +48,7 @@ impl<'a> SourceUpdateStatusTracker<'a> {
Ok(())
}

pub async fn register_successful_update(&self, name: &str, is_full: bool) -> Result<(), Error> {
pub async fn register_successful_update(&self, name: &str, is_full: bool) -> Result<()> {
sqlx::query(indoc! {"
UPDATE update_status
SET
Expand All @@ -72,7 +68,7 @@ impl<'a> SourceUpdateStatusTracker<'a> {
&self,
name: &str,
current_offset: u64,
) -> Result<(), Error> {
) -> Result<()> {
sqlx::query(indoc! {"
UPDATE update_status
SET current_full_update_offset = $2
Expand Down
15 changes: 6 additions & 9 deletions repology-vulnupdater/src/vulnupdater.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

use std::time::Duration;

use anyhow::Error;
use anyhow::Result;
use chrono::{DateTime, TimeDelta, Utc};
use metrics::{counter, gauge};
use tracing::{info, instrument, warn};
Expand Down Expand Up @@ -43,7 +43,7 @@ impl<'a> VulnUpdater<'a> {
&self,
datasource: &Datasource<'a>,
now: DateTime<Utc>,
) -> Result<Paginator, Error> {
) -> Result<Paginator> {
let pager = self.fetcher.paginate(datasource.url);
self.status_tracker
.register_update_attempt(datasource.name, now)
Expand All @@ -55,7 +55,7 @@ impl<'a> VulnUpdater<'a> {
&self,
datasource: &Datasource<'a>,
offset: u64,
) -> Result<Paginator, Error> {
) -> Result<Paginator> {
let mut pager = self.fetcher.paginate(datasource.url);
pager.seek(offset);
Ok(pager)
Expand All @@ -66,7 +66,7 @@ impl<'a> VulnUpdater<'a> {
datasource: &Datasource<'a>,
now: DateTime<Utc>,
since: DateTime<Utc>,
) -> Result<Paginator, Error> {
) -> Result<Paginator> {
let start_date = (since - INCREMENTAL_UPDATE_OVERLAP).min(now - INCREMENTAL_UPDATE_OVERLAP);
let end_date = now + INCREMENTAL_UPDATE_OVERLAP;
if (end_date - start_date) > MAX_INCREMENTAL_UPDATE_SPAN {
Expand Down Expand Up @@ -95,7 +95,7 @@ impl<'a> VulnUpdater<'a> {
&self,
datasource: &Datasource<'a>,
update_period: Option<Duration>,
) -> Result<Option<DateTime<Utc>>, Error> {
) -> Result<Option<DateTime<Utc>>> {
let source_status = self.status_tracker.get(datasource.name).await?;

let now = Utc::now();
Expand Down Expand Up @@ -166,10 +166,7 @@ impl<'a> VulnUpdater<'a> {
}

#[instrument("oneshot", skip_all)]
pub async fn process_datasources_once(
&self,
datasources: &[Datasource<'a>],
) -> Result<(), Error> {
pub async fn process_datasources_once(&self, datasources: &[Datasource<'a>]) -> Result<()> {
for datasource in datasources {
self.update_datasource(datasource, None).await?;
}
Expand Down
4 changes: 2 additions & 2 deletions repology-webapp/src/badges.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: Copyright 2024 Dmitry Marakasov <[email protected]>
// SPDX-License-Identifier: GPL-3.0-or-later

use anyhow::Error;
use anyhow::Result;

use repology_common::PackageStatus;

Expand Down Expand Up @@ -106,7 +106,7 @@ pub fn render_generic_badge(
header: Option<&str>,
min_width: usize,
font_measurer: &FontMeasurer,
) -> Result<String, Error> {
) -> Result<String> {
let num_rows = cells.len();
let num_columns = if num_rows > 0 { cells[0].len() } else { 0 };

Expand Down
9 changes: 2 additions & 7 deletions repology-webapp/src/font.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

use std::path::Path;

use anyhow::Error;
use anyhow::Result;
use tracing::{error, info};

#[allow(unused)]
Expand Down Expand Up @@ -55,12 +55,7 @@ impl FontMeasurer {
}
}

pub fn get_text_width(
&self,
text: &str,
size: usize,
style: FontStyle,
) -> Result<usize, Error> {
pub fn get_text_width(&self, text: &str, size: usize, style: FontStyle) -> Result<usize> {
// as ttf_parser documentation say, Face::parse is really fast so there's no
// need to store it in Font
let face = ttf_parser::Face::parse(
Expand Down
4 changes: 2 additions & 2 deletions repology-webapp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ mod xmlwriter;
use std::sync::Arc;
use std::time::Instant;

use anyhow::{Context, Error};
use anyhow::{Context, Result};
use axum::{
Router,
body::HttpBody,
Expand Down Expand Up @@ -90,7 +90,7 @@ async fn track_metrics(matched_path: MatchedPath, req: Request, next: Next) -> i
not(feature = "coverage"),
tracing::instrument(name = "app init", skip_all)
)]
pub async fn create_app(pool: PgPool) -> Result<Router, Error> {
pub async fn create_app(pool: PgPool) -> Result<Router> {
info!("initializing font measurer");
let font_measurer = FontMeasurer::new();

Expand Down
6 changes: 3 additions & 3 deletions repology-webapp/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

mod config;

use anyhow::{Context, Error};
use anyhow::{Context, Result};
use clap::Parser;
use metrics::{counter, gauge};
use sqlx::Executor;
Expand Down Expand Up @@ -64,7 +64,7 @@ fn collect_tokio_runtime_metrics() {
}
}

async fn async_main() -> Result<(), Error> {
async fn async_main() -> Result<()> {
let config = Config::parse();

if let Some(log_directory) = &config.log_directory {
Expand Down Expand Up @@ -143,7 +143,7 @@ async fn async_main() -> Result<(), Error> {
.context("error starting HTTP server")
}

fn main() -> Result<(), Error> {
fn main() -> Result<()> {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
Expand Down
Loading

0 comments on commit 71c97e8

Please sign in to comment.