Check if an email address exists without sending any email, written in Rust. Comes with a ⚙️ HTTP backend.
Rust emailemail-validationemail-validation-apiemail-verificationemail-verification-apiemail-verifierhacktoberfest
refactor: Merge worker into backend (#1404)
Amauryc0ddce273d39
diff --git a/.github/workflows/deploy_backend.yml b/.github/workflows/deploy_backend.ymlindex 3b82248c..88d06057 100644--- a/.github/workflows/deploy_backend.yml+++ b/.github/workflows/deploy_backend.yml@@ -22,4 +22,3 @@ jobs:username: ${{ secrets.DOCKER_USERNAME }}password: ${{ secrets.DOCKER_PASSWORD }}tags: "${{ steps.vars.outputs.GITHUB_TAG }}"- dockerfile: Dockerfile.backenddiff --git a/.github/workflows/deploy_worker.yml b/.github/workflows/deploy_worker.ymldeleted file mode 100644index 457b5078..00000000--- a/.github/workflows/deploy_worker.yml+++ /dev/null@@ -1,25 +0,0 @@-name: tag--on:- push:- tags:- - "worker/v*.*.*"--jobs:- docker-publish:- runs-on: ubuntu-latest- steps:- - uses: actions/checkout@master- - name: Set GITHUB_TAG arg- id: vars- run: echo ::set-output name=GITHUB_TAG::${GITHUB_REF:17} # Remove /refs/head/worker/- - name: Print version- run: echo "Publishing reacherhq/worker:${{ steps.vars.outputs.GITHUB_TAG }}"- - name: Publish to Registry- uses: elgohr/Publish-Docker-Github-Action@v5- with:- name: reacherhq/worker- username: ${{ secrets.DOCKER_USERNAME }}- password: ${{ secrets.DOCKER_PASSWORD }}- tags: "${{ steps.vars.outputs.GITHUB_TAG }}"- dockerfile: Dockerfile.workerdiff --git a/.vscode/settings.json b/.vscode/settings.jsonnew file mode 100644index 00000000..a7857b01--- /dev/null+++ b/.vscode/settings.json@@ -0,0 +1,3 @@+{+ "rust-analyzer.cargo.features": ["worker"]+}diff --git a/Cargo.lock b/Cargo.lockindex 4c3f8631..23833f1a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2412,37 +2412,24 @@ dependencies = ["check-if-email-exists","csv","dotenv",- "env_logger",+ "futures",+ "futures-lite 2.1.0",+ "lapin","log","openssl",+ "reqwest","sentry","serde","serde_json","sqlx","sqlxmq","tokio",- "uuid 1.6.1",- "warp",-]--[[package]]-name = "reacher_worker"-version = "1.0.0"-dependencies = [- "async-global-executor",- "async-smtp",- "check-if-email-exists",- "futures-lite 2.1.0",- "lapin",- "reqwest",- "sentry",- "serde",- "serde_json",- "tokio","tokio-executor-trait","tokio-reactor-trait","tracing","tracing-subscriber",+ "uuid 1.6.1",+ "warp",][[package]]diff --git a/Cargo.toml b/Cargo.tomlindex 9f2b30d7..861920f1 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,2 +1,2 @@[workspace]-members = ["backend", "cli", "core", "worker"]+members = ["backend", "cli", "core"]diff --git a/Dockerfile.backend b/Dockerfilesimilarity index 96%rename from Dockerfile.backendrename to Dockerfileindex 2abbe4ce..17dfc608 100644--- a/Dockerfile.backend+++ b/Dockerfile@@ -31,7 +31,7 @@ USER rootRUN apk add --no-cache chromium-chromedriverCOPY --from=cargo-build /usr/src/reacher/target/x86_64-unknown-linux-musl/release/reacher_backend .-COPY --from=cargo-build /usr/src/reacher/backend/docker.sh .+COPY --from=cargo-build /usr/src/reacher/docker.sh .RUN chown chrome:chrome reacher_backendRUN chown chrome:chrome docker.shdiff --git a/Dockerfile.worker b/Dockerfile.workerdeleted file mode 100644index a84ccb0a..00000000--- a/Dockerfile.worker+++ /dev/null@@ -1,55 +0,0 @@-# From https://shaneutt.com/blog/rust-fast-small-docker-image-builds/--# -------------------------------------------------------------------------------# Cargo Build Stage-# --------------------------------------------------------------------------------FROM messense/rust-musl-cross:x86_64-musl as cargo-build--WORKDIR /usr/src/reacher--RUN rm -f target/x86_64-unknown-linux-musl/release/deps/reacher*--COPY . .--ENV SQLX_OFFLINE=true--RUN cargo build --bin reacher_worker --release --target=x86_64-unknown-linux-musl--# -------------------------------------------------------------------------------# Final Stage-# --------------------------------------------------------------------------------FROM zenika/alpine-chrome--WORKDIR /home/reacher/--USER root--# Install chromedriver-# https://github.com/Zenika/alpine-chrome/blob/master/with-chromedriver/Dockerfile-RUN apk add --no-cache chromium-chromedriver--COPY --from=cargo-build /usr/src/reacher/target/x86_64-unknown-linux-musl/release/reacher_worker .-COPY --from=cargo-build /usr/src/reacher/worker/docker.sh .--RUN chown chrome:chrome reacher_worker-RUN chown chrome:chrome docker.sh--# User chrome was created in zenika/alpine-chrome-USER chrome--ENV RUST_LOG=reacher=info-ENV RCH_HTTP_HOST=0.0.0.0-ENV PORT=8080-ENV RCH_WEBDRIVER_ADDR=http://localhost:9515-# Bulk verification is disabled by default. Set to 1 to enable it.-ENV RCH_ENABLE_BULK=0--EXPOSE 8080--# Remove entrypoint from parent Docker file-# https://stackoverflow.com/questions/40122152/how-to-remove-entrypoint-from-parent-image-on-dockerfile-ENTRYPOINT []--CMD ["./docker.sh"]diff --git a/backend/Cargo.toml b/backend/Cargo.tomlindex f9df0f9f..71f4067b 100644--- a/backend/Cargo.toml+++ b/backend/Cargo.toml@@ -10,9 +10,12 @@ async-smtp = "0.6"check-if-email-exists = { path = "../core", features = ["headless"] }csv = "1.3.0"dotenv = "0.15.0"-env_logger = "0.10"+futures = { version = "0.3.29", optional = true }+futures-lite = { version = "2.1.0", optional = true }+lapin = { version = "2.3.1", optional = true }log = "0.4"openssl = { version = "0.10.57", features = ["vendored"] }+reqwest = { version = "0.11.22", features = ["json"], optional = true }sentry = "0.23"serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"@@ -26,5 +29,19 @@ sqlx = { version = "0.7", features = [] }sqlxmq = "0.5"tokio = { version = "1.29", features = ["macros"] }+tokio-executor-trait = { version = "2.1.1", optional = true }+tokio-reactor-trait = { version = "1.1.0", optional = true }+tracing = "0.1.40"+tracing-subscriber = "0.3.18"uuid = "1.6"warp = "0.3"++[features]+worker = [+ "futures",+ "futures-lite",+ "lapin",+ "reqwest",+ "tokio-executor-trait",+ "tokio-reactor-trait",+]diff --git a/backend/src/bin/prune_db.rs b/backend/src/bin/prune_db.rsindex 572dd17a..5c59ba8e 100644--- a/backend/src/bin/prune_db.rs+++ b/backend/src/bin/prune_db.rs@@ -1,11 +1,11 @@-use log::info;use sqlx::PgPool;use sqlx::Result;+use tracing::info;#[tokio::main]async fn main() -> Result<()> {dotenv::dotenv().expect("Unable to load environment variables from .env file");- env_logger::init(); // Initialize the logger+ tracing_subscriber::fmt::init();let db_url = std::env::var("DATABASE_URL").expect("Unable to read DATABASE_URL env var");let dry_mode: bool = std::env::var("DRY_RUN").is_ok();diff --git a/backend/src/routes/bulk/db.rs b/backend/src/http/bulk/db.rssimilarity index 100%rename from backend/src/routes/bulk/db.rsrename to backend/src/http/bulk/db.rsdiff --git a/backend/src/routes/bulk/error.rs b/backend/src/http/bulk/error.rssimilarity index 100%rename from backend/src/routes/bulk/error.rsrename to backend/src/http/bulk/error.rsdiff --git a/backend/src/routes/bulk/get.rs b/backend/src/http/bulk/get.rssimilarity index 98%rename from backend/src/routes/bulk/get.rsrename to backend/src/http/bulk/get.rsindex a7b549cc..004f591c 100644--- a/backend/src/routes/bulk/get.rs+++ b/backend/src/http/bulk/get.rs@@ -16,13 +16,14 @@//! This file implements the `GET /bulk/{id}` endpoint.+use check_if_email_exists::LOG_TARGET;use serde::Serialize;use sqlx::types::chrono::{DateTime, Utc};use sqlx::{Pool, Postgres};+use tracing::error;use warp::Filter;use super::{db::with_db, error::BulkError};-use check_if_email_exists::LOG_TARGET;/// NOTE: Type conversions from postgres to rust types/// are according to the table given by@@ -83,11 +84,10 @@ async fn job_status(.fetch_one(&conn_pool).await.map_err(|e| {- log::error!(+ error!(target: LOG_TARGET,"Failed to get job record for [job={}] with [error={}]",- job_id,- e+ job_id, e);BulkError::from(e)})?;@@ -109,7 +109,7 @@ async fn job_status(.fetch_one(&conn_pool).await.map_err(|e| {- log::error!(+ error!(target: LOG_TARGET,"Failed to get aggregate info for [job={}] with [error={}]",job_id,diff --git a/backend/src/http/bulk/mod.rs b/backend/src/http/bulk/mod.rsnew file mode 100644index 00000000..061d27e3--- /dev/null+++ b/backend/src/http/bulk/mod.rs@@ -0,0 +1,65 @@+// Reacher - Email Verification+// Copyright (C) 2018-2023 Reacher++// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published+// by the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.++// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.++// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++mod db;+mod error;+pub mod get;+pub mod post;+pub mod results;+mod task;++use std::env;++use check_if_email_exists::LOG_TARGET;+use sqlx::{Pool, Postgres};+use sqlxmq::{JobRegistry, JobRunnerHandle};+use tracing::info;++pub use task::email_verification_task;++/// Create a job registry with one task: the email verification task.+pub async fn create_job_registry(pool: &Pool<Postgres>) -> Result<JobRunnerHandle, sqlx::Error> {+ let min_task_conc = env::var("RCH_MINIMUM_TASK_CONCURRENCY").map_or(10, |var| {+ var.parse::<usize>()+ .expect("Environment variable RCH_MINIMUM_TASK_CONCURRENCY should parse to usize")+ });+ let max_conc_task_fetch = env::var("RCH_MAXIMUM_CONCURRENT_TASK_FETCH").map_or(20, |var| {+ var.parse::<usize>()+ .expect("Environment variable RCH_MAXIMUM_CONCURRENT_TASK_FETCH should parse to usize")+ });++ // registry needs to be given list of jobs it can accept+ let registry = JobRegistry::new(&[email_verification_task]);++ // create runner for the message queue associated+ // with this job registry+ let registry = registry+ // Create a job runner using the connection pool.+ .runner(pool)+ // Here is where you can configure the job runner+ // Aim to keep 10-20 jobs running at a time.+ .set_concurrency(min_task_conc, max_conc_task_fetch)+ // Start the job runner in the background.+ .run()+ .await?;++ info!(+ target: LOG_TARGET,+ "Bulk endpoints enabled with concurrency min={min_task_conc} to max={max_conc_task_fetch}."+ );++ Ok(registry)+}diff --git a/backend/src/routes/bulk/post.rs b/backend/src/http/bulk/post.rssimilarity index 96%rename from backend/src/routes/bulk/post.rsrename to backend/src/http/bulk/post.rsindex dffcd840..29db497f 100644--- a/backend/src/routes/bulk/post.rs+++ b/backend/src/http/bulk/post.rs@@ -20,6 +20,7 @@ use check_if_email_exists::CheckEmailInputProxy;use check_if_email_exists::LOG_TARGET;use serde::{Deserialize, Serialize};use sqlx::{Pool, Postgres};+use tracing::{debug, error};use warp::Filter;use super::{@@ -106,11 +107,10 @@ async fn create_bulk_request(.fetch_one(&conn_pool).await.map_err(|e| {- log::error!(+ error!(target: LOG_TARGET,"Failed to create job record for [body={:?}] with [error={}]",- &body,- e+ &body, e);BulkError::from(e)})?;@@ -118,11 +118,10 @@ async fn create_bulk_request(for task_input in body.into_iter() {let task_uuid = submit_job(&conn_pool, rec.id, task_input).await?;- log::debug!(+ debug!(target: LOG_TARGET,"Submitted task to sqlxmq for [job={}] with [uuid={}]",- rec.id,- task_uuid+ rec.id, task_uuid);}@@ -147,6 +146,6 @@ pub fn create_bulk_job(.and(warp::body::content_length_limit(1024 * 16)).and(warp::body::json()).and_then(create_bulk_request)- // View access logs by setting `RUST_LOG=reacher`.+ // View access logs by setting `RUST_LOG=reacher_backend`..with(warp::log(LOG_TARGET))}diff --git a/backend/src/routes/bulk/results/csv_helper.rs b/backend/src/http/bulk/results/csv_helper.rssimilarity index 100%rename from backend/src/routes/bulk/results/csv_helper.rsrename to backend/src/http/bulk/results/csv_helper.rsdiff --git a/backend/src/routes/bulk/results/mod.rs b/backend/src/http/bulk/results/mod.rssimilarity index 96%rename from backend/src/routes/bulk/results/mod.rsrename to backend/src/http/bulk/results/mod.rsindex dbcd635d..b19dbc9f 100644--- a/backend/src/routes/bulk/results/mod.rs+++ b/backend/src/http/bulk/results/mod.rs@@ -22,6 +22,7 @@ use serde::{Deserialize, Serialize};use sqlx::{Executor, Pool, Postgres, Row};use std::convert::TryInto;use std::iter::Iterator;+use tracing::error;use warp::Filter;use super::{@@ -68,11 +69,10 @@ async fn job_result(.fetch_one(&conn_pool).await.map_err(|e| {- log::error!(+ error!(target: LOG_TARGET,"Failed to fetch total_records for [job={}] with [error={}]",- job_id,- e+ job_id, e);BulkError::from(e)})?@@ -84,11 +84,10 @@ async fn job_result(.fetch_one(&conn_pool).await.map_err(|e| {- log::error!(+ error!(target: LOG_TARGET,"Failed to get total_processed for [job={}] with [error={}]",- job_id,- e+ job_id, e);BulkError::from(e)})?@@ -107,11 +106,10 @@ async fn job_result(let reply =serde_json::to_vec(&JobResultJsonResponse { results: data }).map_err(|e| {- log::error!(+ error!(target: LOG_TARGET,"Failed to convert json results to string for [job={}] with [error={}]",- job_id,- e+ job_id, e);BulkError::Json(e)@@ -151,7 +149,7 @@ async fn job_result_as_iter();let rows = conn_pool.fetch_all(query).await.map_err(|e| {- log::error!(+ error!(target: LOG_TARGET,"Failed to get results for [job={}] [limit={}] [offset={}] with [error={}]",job_id,@@ -196,7 +194,7 @@ async fn job_result_csv(for json_value in rows {let result_csv: JobResultCsvResponse = CsvWrapper(json_value).try_into().map_err(|e: &'static str| {- log::error!(+ error!(target: LOG_TARGET,"Failed to convert json to csv output struct for [job={}] [limit={}] [offset={}] to csv with [error={}]",job_id,@@ -208,7 +206,7 @@ async fn job_result_csv(BulkError::Csv(CsvError::Parse(e))})?;wtr.serialize(result_csv).map_err(|e| {- log::error!(+ error!(target: LOG_TARGET,"Failed to serialize result for [job={}] [limit={}] [offset={}] to csv with [error={}]",job_id,@@ -222,7 +220,7 @@ async fn job_result_csv(}let data = wtr.into_inner().map_err(|e| {- log::error!(+ error!(target: LOG_TARGET,"Failed to convert results for [job={}] [limit={}] [offset={}] to csv with [error={}]",job_id,@@ -245,6 +243,6 @@ pub fn get_bulk_job_result(.and(with_db(o)).and(warp::query::<JobResultRequest>()).and_then(job_result)- // View access logs by setting `RUST_LOG=reacher`.+ // View access logs by setting `RUST_LOG=reacher_backend`..with(warp::log(LOG_TARGET))}diff --git a/backend/src/routes/bulk/task.rs b/backend/src/http/bulk/task.rssimilarity index 97%rename from backend/src/routes/bulk/task.rsrename to backend/src/http/bulk/task.rsindex c33134e1..e4bc07ac 100644--- a/backend/src/routes/bulk/task.rs+++ b/backend/src/http/bulk/task.rs@@ -16,16 +16,18 @@//! This file implements the `POST /bulk` endpoint.-use super::error::BulkError;-use crate::check::check_email;use check_if_email_exists::LOG_TARGET;use check_if_email_exists::{CheckEmailInput, CheckEmailInputProxy, CheckEmailOutput, Reachable};use serde::{Deserialize, Serialize};use sqlx::{Pool, Postgres};use sqlxmq::{job, CurrentJob};use std::error::Error;+use tracing::{debug, error};use uuid::Uuid;+use super::error::BulkError;+use crate::check::check_email;+#[derive(Clone, Debug, Deserialize, Serialize)]pub struct TaskInput {// fields for CheckEmailInput@@ -104,11 +106,10 @@ pub async fn submit_job(.builder().set_json(&task_payload).map_err(|e| {- log::error!(+ error!(target: LOG_TARGET,"Failed to submit task with the following [input={:?}] with [error={}]",- task_payload.input,- e+ task_payload.input, e);BulkError::Json(e)@@ -116,11 +117,10 @@ pub async fn submit_job(.spawn(conn_pool).await.map_err(|e| {- log::error!(+ error!(target: LOG_TARGET,"Failed to submit task for [bulk_req={}] with [error={}]",- job_id,- e+ job_id, e);e@@ -150,7 +150,7 @@ pub async fn email_verification_task(let mut final_response: Option<CheckEmailOutput> = None;for check_email_input in task_payload.input {- log::debug!(+ debug!(target: LOG_TARGET,"Starting task [email={}] for [job={}] and [uuid={}]",check_email_input.to_email,@@ -161,7 +161,7 @@ pub async fn email_verification_task(let to_email = check_email_input.to_email.clone();let response = check_email(check_email_input).await;- log::debug!(+ debug!(target: LOG_TARGET,"Got task result [email={}] for [job={}] and [uuid={}] with [is_reachable={:?}]",to_email,@@ -204,8 +204,8 @@ pub async fn email_verification_task(.fetch_optional(current_job.pool()).await.map_err(|e| {- log::error!(- target:LOG_TARGET,+ error!(+ target: LOG_TARGET,"Failed to write [email={}] result to db for [job={}] and [uuid={}] with [error={}]",response.input,job_id,@@ -216,7 +216,7 @@ pub async fn email_verification_task(e})?;- log::debug!(+ debug!(target: LOG_TARGET,"Wrote result for [email={}] for [job={}] and [uuid={}]",response.input,diff --git a/backend/src/routes/check_email/mod.rs b/backend/src/http/check_email/mod.rssimilarity index 100%rename from backend/src/routes/check_email/mod.rsrename to backend/src/http/check_email/mod.rsdiff --git a/backend/src/routes/check_email/post.rs b/backend/src/http/check_email/post.rssimilarity index 100%rename from backend/src/routes/check_email/post.rsrename to backend/src/http/check_email/post.rsdiff --git a/backend/src/http/mod.rs b/backend/src/http/mod.rsnew file mode 100644index 00000000..69e44bf0--- /dev/null+++ b/backend/src/http/mod.rs@@ -0,0 +1,96 @@+// Reacher - Email Verification+// Copyright (C) 2018-2023 Reacher++// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published+// by the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.++// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.++// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++mod bulk;+pub mod check_email;+mod version;++use std::env;+use std::net::IpAddr;++use check_if_email_exists::LOG_TARGET;+use sqlx::{postgres::PgPoolOptions, Pool, Postgres};+use tracing::info;+use warp::Filter;++use super::errors;++pub fn create_routes(+ o: Option<Pool<Postgres>>,+) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone {+ version::get::get_version()+ .or(check_email::post::post_check_email())+ // The 3 following routes will 404 if o is None.+ .or(bulk::post::create_bulk_job(o.clone()))+ .or(bulk::get::get_bulk_job_status(o.clone()))+ .or(bulk::results::get_bulk_job_result(o))+ .recover(errors::handle_rejection)+}++/// Runs the Warp server.+///+/// This function starts the Warp server and listens for incoming requests.+/// It returns a `Result` indicating whether the server started successfully or encountered an error.+pub async fn run_warp_server() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {+ let host = env::var("RCH_HTTP_HOST")+ .unwrap_or_else(|_| "127.0.0.1".into())+ .parse::<IpAddr>()+ .expect("Environment variable RCH_HTTP_HOST is malformed.");+ let port = env::var("PORT")+ .map(|port: String| {+ port.parse::<u16>()+ .expect("Environment variable PORT is malformed.")+ })+ .unwrap_or(8080);++ let is_bulk_enabled = env::var("RCH_ENABLE_BULK").unwrap_or_else(|_| "0".into()) == "1";+ let db = if is_bulk_enabled {+ let pool = create_db().await?;+ let _registry = bulk::create_job_registry(&pool).await?;+ Some(pool)+ } else {+ None+ };++ let routes = create_routes(db);++ info!(target: LOG_TARGET, host=?host,port=?port, "Server is listening");+ warp::serve(routes).run((host, port)).await;++ Ok(())+}++/// Create a DB pool.+async fn create_db() -> Result<Pool<Postgres>, sqlx::Error> {+ let pg_conn =+ env::var("DATABASE_URL").expect("Environment variable DATABASE_URL should be set");+ let pg_max_conn = env::var("RCH_DATABASE_MAX_CONNECTIONS").map_or(5, |var| {+ var.parse::<u32>()+ .expect("Environment variable RCH_DATABASE_MAX_CONNECTIONS should parse to u32")+ });++ // create connection pool with database+ // connection pool internally the shared db connection+ // with arc so it can safely be cloned and shared across threads+ let pool = PgPoolOptions::new()+ .max_connections(pg_max_conn)+ .connect(pg_conn.as_str())+ .await?;++ sqlx::migrate!("./migrations").run(&pool).await?;++ Ok(pool)+}diff --git a/backend/src/routes/version/get.rs b/backend/src/http/version/get.rssimilarity index 100%rename from backend/src/routes/version/get.rsrename to backend/src/http/version/get.rsdiff --git a/backend/src/routes/version/mod.rs b/backend/src/http/version/mod.rssimilarity index 100%rename from backend/src/routes/version/mod.rsrename to backend/src/http/version/mod.rsdiff --git a/backend/src/lib.rs b/backend/src/lib.rsindex 8b28dc8c..e8ef4a93 100644--- a/backend/src/lib.rs+++ b/backend/src/lib.rs@@ -16,5 +16,7 @@pub mod check;mod errors;-pub mod routes;+pub mod http;pub mod sentry_util;+#[cfg(feature = "worker")]+pub mod worker;diff --git a/backend/src/main.rs b/backend/src/main.rsindex c8196a22..9872c75e 100644--- a/backend/src/main.rs+++ b/backend/src/main.rs@@ -18,119 +18,33 @@//! functions, depending on whether the `bulk` feature is enabled or not.use check_if_email_exists::LOG_TARGET;-use dotenv::dotenv;-use reacher_backend::routes::{bulk::email_verification_task, create_routes};-use reacher_backend::sentry_util::{setup_sentry, CARGO_PKG_VERSION};-use sqlx::{postgres::PgPoolOptions, Pool, Postgres};-use sqlxmq::{JobRegistry, JobRunnerHandle};-use std::{env, net::IpAddr};-use warp::Filter;+#[cfg(feature = "worker")]+use futures::try_join;+use tracing::info;++#[cfg(feature = "worker")]+use reacher_backend::worker::run_worker;+use reacher_backend::{+ http::run_warp_server,+ sentry_util::{setup_sentry, CARGO_PKG_VERSION},+};/// Run a HTTP server using warp with bulk endpoints.+/// If the worker feature is enabled, this function will also start a worker+/// that listens to an AMQP message queue.#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {- init_logger();+ // Initialize logging.+ tracing_subscriber::fmt::init();+ info!(target: LOG_TARGET, version=?CARGO_PKG_VERSION, "Running Reacher");// Setup sentry bug tracking.- let _guard = setup_sentry();-- let is_bulk_enabled = env::var("RCH_ENABLE_BULK").unwrap_or_else(|_| "0".into()) == "1";- if is_bulk_enabled {- let pool = create_db().await?;- let _registry = create_job_registry(&pool).await?;- let routes = create_routes(Some(pool));- run_warp_server(routes).await?;- } else {- let routes = create_routes(None);- run_warp_server(routes).await?;- }-- Ok(())-}--fn init_logger() {- // Read from .env file if present.- let _ = dotenv();- env_logger::init();- log::info!(target: LOG_TARGET, "Running Reacher v{}", CARGO_PKG_VERSION);-}--/// Create a DB pool.-pub async fn create_db() -> Result<Pool<Postgres>, sqlx::Error> {- let pg_conn =- env::var("DATABASE_URL").expect("Environment variable DATABASE_URL should be set");- let pg_max_conn = env::var("RCH_DATABASE_MAX_CONNECTIONS").map_or(5, |var| {- var.parse::<u32>()- .expect("Environment variable RCH_DATABASE_MAX_CONNECTIONS should parse to u32")- });-- // create connection pool with database- // connection pool internally the shared db connection- // with arc so it can safely be cloned and shared across threads- let pool = PgPoolOptions::new()- .max_connections(pg_max_conn)- .connect(pg_conn.as_str())- .await?;-- sqlx::migrate!("./migrations").run(&pool).await?;-- Ok(pool)-}--/// Create a job registry with one task: the email verification task.-async fn create_job_registry(pool: &Pool<Postgres>) -> Result<JobRunnerHandle, sqlx::Error> {- let min_task_conc = env::var("RCH_MINIMUM_TASK_CONCURRENCY").map_or(10, |var| {- var.parse::<usize>()- .expect("Environment variable RCH_MINIMUM_TASK_CONCURRENCY should parse to usize")- });- let max_conc_task_fetch = env::var("RCH_MAXIMUM_CONCURRENT_TASK_FETCH").map_or(20, |var| {- var.parse::<usize>()- .expect("Environment variable RCH_MAXIMUM_CONCURRENT_TASK_FETCH should parse to usize")- });-- // registry needs to be given list of jobs it can accept- let registry = JobRegistry::new(&[email_verification_task]);-- // create runner for the message queue associated- // with this job registry- let registry = registry- // Create a job runner using the connection pool.- .runner(pool)- // Here is where you can configure the job runner- // Aim to keep 10-20 jobs running at a time.- .set_concurrency(min_task_conc, max_conc_task_fetch)- // Start the job runner in the background.- .run()- .await?;-- log::info!(- target: LOG_TARGET,- "Bulk endpoints enabled with concurrency min={min_task_conc} to max={max_conc_task_fetch}."- );-- Ok(registry)-}+ let _guard: sentry::ClientInitGuard = setup_sentry();-async fn run_warp_server(- routes: impl Filter<Extract = impl warp::Reply, Error = warp::Rejection>- + Clone- + Send- + Sync- + 'static,-) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {- let host = env::var("RCH_HTTP_HOST")- .unwrap_or_else(|_| "127.0.0.1".into())- .parse::<IpAddr>()- .expect("Environment variable RCH_HTTP_HOST is malformed.");- let port = env::var("PORT")- .map(|port| {- port.parse::<u16>()- .expect("Environment variable PORT is malformed.")- })- .unwrap_or(8080);- println!("Server is listening on {host}:{port}.");+ let _http_server = run_warp_server();- warp::serve(routes).run((host, port)).await;+ #[cfg(feature = "worker")]+ try_join!(_http_server, run_worker())?;Ok(())}diff --git a/backend/src/routes/bulk/mod.rs b/backend/src/routes/bulk/mod.rsdeleted file mode 100644index 1332bfd8..00000000--- a/backend/src/routes/bulk/mod.rs+++ /dev/null@@ -1,24 +0,0 @@-// Reacher - Email Verification-// Copyright (C) 2018-2023 Reacher--// This program is free software: you can redistribute it and/or modify-// it under the terms of the GNU Affero General Public License as published-// by the Free Software Foundation, either version 3 of the License, or-// (at your option) any later version.--// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU Affero General Public License for more details.--// You should have received a copy of the GNU Affero General Public License-// along with this program. If not, see <https://www.gnu.org/licenses/>.--mod db;-mod error;-pub mod get;-pub mod post;-pub mod results;-mod task;--pub use task::email_verification_task;diff --git a/backend/src/routes/mod.rs b/backend/src/routes/mod.rsdeleted file mode 100644index ed3df73c..00000000--- a/backend/src/routes/mod.rs+++ /dev/null@@ -1,35 +0,0 @@-// Reacher - Email Verification-// Copyright (C) 2018-2023 Reacher--// This program is free software: you can redistribute it and/or modify-// it under the terms of the GNU Affero General Public License as published-// by the Free Software Foundation, either version 3 of the License, or-// (at your option) any later version.--// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU Affero General Public License for more details.--// You should have received a copy of the GNU Affero General Public License-// along with this program. If not, see <https://www.gnu.org/licenses/>.--pub mod bulk;-pub mod check_email;-mod version;--use super::errors;-use sqlx::{Pool, Postgres};-use warp::Filter;--pub fn create_routes(- o: Option<Pool<Postgres>>,-) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone {- version::get::get_version()- .or(check_email::post::post_check_email())- // The 3 following routes will 404 if o is None.- .or(bulk::post::create_bulk_job(o.clone()))- .or(bulk::get::get_bulk_job_status(o.clone()))- .or(bulk::results::get_bulk_job_result(o))- .recover(errors::handle_rejection)-}diff --git a/backend/src/sentry_util.rs b/backend/src/sentry_util.rsindex d1d93fbb..481df2d5 100644--- a/backend/src/sentry_util.rs+++ b/backend/src/sentry_util.rs@@ -29,6 +29,7 @@ use check_if_email_exists::mx::MxError;use check_if_email_exists::LOG_TARGET;use check_if_email_exists::{smtp::SmtpError, CheckEmailOutput};use sentry::protocol::{Event, Exception, Level, Values};+use tracing::{debug, info};use super::sentry_util;@@ -40,7 +41,7 @@ pub fn setup_sentry() -> sentry::ClientInitGuard {// will just silently ignore.let sentry = sentry::init(env::var("RCH_SENTRY_DSN").unwrap_or_else(|_| "".into()));if sentry.is_enabled() {- log::info!(target: LOG_TARGET, "Sentry is successfully set up.")+ info!(target: LOG_TARGET, "Sentry is successfully set up.")}sentry@@ -83,11 +84,7 @@ impl<'a> SentryError<'a> {/// info before sending to Sentry, by removing all instances of `username`.fn error(err: SentryError, result: &CheckEmailOutput) {let exception_value = redact(format!("{err:?}").as_str(), &result.syntax.username);- log::debug!(- target: LOG_TARGET,- "Sending error to Sentry: {}",- exception_value- );+ debug!(target: LOG_TARGET, "Sending error to Sentry: {}", exception_value);let exception = Exception {ty: err.get_exception_type(),@@ -148,8 +145,7 @@ pub fn log_unknown_errors(result: &CheckEmailOutput) {{// If the SMTP error is transient and known, we don't track it in// Sentry, just log it locally.- log::debug!(- target: LOG_TARGET,+ debug!(target: LOG_TARGET,"Transient error: {}",redact(response.message[0].as_str(),diff --git a/worker/src/worker.rs b/backend/src/worker/check_email.rssimilarity index 62%rename from worker/src/worker.rsrename to backend/src/worker/check_email.rsindex fde1ae3a..f823a14f 100644--- a/worker/src/worker.rs+++ b/backend/src/worker/check_email.rs@@ -14,17 +14,15 @@// You should have received a copy of the GNU Affero General Public License// along with this program. If not, see <https://www.gnu.org/licenses/>.-use std::env;--use check_if_email_exists::CheckEmailInput;-use check_if_email_exists::{check_email as ciee_check_email, CheckEmailOutput};+use check_if_email_exists::LOG_TARGET;+use check_if_email_exists::{CheckEmailInput, CheckEmailOutput};use lapin::message::Delivery;use lapin::options::*;use serde::Deserialize;use serde::Serialize;use tracing::{debug, info};-use crate::sentry_util::log_unknown_errors;+use crate::check::check_email;#[derive(Debug, Deserialize)]pub struct CheckEmailPayload {@@ -49,11 +47,11 @@ pub async fn process_check_email(delivery: Delivery,) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {let payload = serde_json::from_slice::<CheckEmailPayload>(&delivery.data)?;- info!(email=?payload.input.to_email, "Start check");- debug!(payload=?payload);+ info!(target: LOG_TARGET, email=?payload.input.to_email, "New job");+ debug!(target: LOG_TARGET, payload=?payload);let output = check_email(payload.input).await;- debug!(email=output.input,output=?output, "Done check-if-email-exists");+ debug!(target: LOG_TARGET, email=output.input,output=?output, "Done check-if-email-exists");// Check if we have a webhook to send the output to.if let Some(webhook) = payload.webhook {@@ -71,34 +69,11 @@ pub async fn process_check_email(.await?.text().await?;- debug!(email=?webhook_output.output.input,res=?res, "Received webhook response");- info!(email=?webhook_output.output.input, "Finished check");+ debug!(target: LOG_TARGET, email=?webhook_output.output.input,res=?res, "Received webhook response");+ info!(target: LOG_TARGET, email=?webhook_output.output.input, is_reachable=?webhook_output.output.is_reachable, "Finished check");}delivery.ack(BasicAckOptions::default()).await?;Ok(())}--/// Same as `check-if-email-exists`'s check email, but adds some additional-/// inputs and error handling.-async fn check_email(input: CheckEmailInput) -> CheckEmailOutput {- let from_email =- env::var("RCH_FROM_EMAIL").unwrap_or_else(|_| CheckEmailInput::default().from_email);- let hello_name: String =- env::var("RCH_HELLO_NAME").unwrap_or_else(|_| CheckEmailInput::default().hello_name);-- let input = CheckEmailInput {- // If we want to override core check-if-email-exists's default values- // for CheckEmailInput for the backend, we do it here.- from_email,- hello_name,- ..input- };-- let res = ciee_check_email(&input).await;-- log_unknown_errors(&res);-- res-}diff --git a/worker/src/main.rs b/backend/src/worker/mod.rssimilarity index 86%rename from worker/src/main.rsrename to backend/src/worker/mod.rsindex 133b1239..e1dc5daf 100644--- a/worker/src/main.rs+++ b/backend/src/worker/mod.rs@@ -16,23 +16,16 @@use std::env;+use check_if_email_exists::LOG_TARGET;use futures_lite::StreamExt;use lapin::{options::*, types::FieldTable, Connection, ConnectionProperties};use tracing::{error, info};-mod sentry_util;-mod worker;+mod check_email;-use sentry_util::setup_sentry;-use worker::process_check_email;--#[tokio::main]-async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {- // Setup sentry bug tracking.- let _guard = setup_sentry();-- tracing_subscriber::fmt::init();+use check_email::process_check_email;+pub async fn run_worker() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {// Make sure the worker is well configured.let addr = env::var("RCH_AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672".into());let backend_name = env::var("RCH_BACKEND_NAME").expect("RCH_BACKEND_NAME is not set");@@ -52,7 +45,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {// Receive channellet channel = conn.create_channel().await?;- info!(backend=?backend_name,state=?conn.status().state(), "Connected to AMQP broker");+ info!(target: LOG_TARGET, backend=?backend_name,state=?conn.status().state(), "Connected to AMQP broker");// Create queue "check_email.{Smtp,Headless}" with priority.let queue_name = format!("check_email.{:?}", verif_method);@@ -70,7 +63,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {).await?;- info!(queue=?queue_name, "Worker will start consuming messages");+ info!(target: LOG_TARGET, queue=?queue_name, "Worker will start consuming messages");let mut consumer = channel.basic_consume(&queue_name,@@ -85,7 +78,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {tokio::spawn(async move {let res = process_check_email(delivery).await;if let Err(err) = res {- error!(error=?err, "Error processing message");+ error!(target: LOG_TARGET, error=?err, "Error processing message");}});}diff --git a/backend/tests/check_email.rs b/backend/tests/check_email.rsindex add48e09..dbe37499 100644--- a/backend/tests/check_email.rs+++ b/backend/tests/check_email.rs@@ -18,8 +18,7 @@ use std::env;use check_if_email_exists::CheckEmailInput;use reacher_backend::check::REACHER_SECRET_HEADER;-use reacher_backend::routes::create_routes;-+use reacher_backend::http::create_routes;use warp::http::StatusCode;use warp::test::request;@@ -39,7 +38,6 @@ async fn test_input_foo_bar() {.await;assert_eq!(resp.status(), StatusCode::OK, "{:?}", resp.body());- println!("{:?}", resp.body());assert!(resp.body().starts_with(FOO_BAR_RESPONSE.as_bytes()));}diff --git a/backend/docker.sh b/docker.shsimilarity index 100%rename from backend/docker.shrename to docker.shdiff --git a/worker/Cargo.toml b/worker/Cargo.tomldeleted file mode 100644index e59c902e..00000000--- a/worker/Cargo.toml+++ /dev/null@@ -1,24 +0,0 @@-[package]-name = "reacher_worker"-version = "1.0.0"-edition = "2018"-description = "RabbitMQ worker for Reacher"-authors = ["Amaury <[email protected]>"]-license = "AGPL-3.0"-publish = false--[dependencies]-async-smtp = "0.6"-async-global-executor = "2.4.0"-check-if-email-exists = { path = "../core", features = ["headless"] }-futures-lite = "2.1.0"-lapin = "2.3.1"-reqwest = { version = "0.11.22", features = ["json"] }-sentry = "0.23"-serde = { version = "1.0", features = ["derive"] }-serde_json = "1.0"-tokio = { version = "1.29", features = ["macros"] }-tokio-executor-trait = "2.1.1"-tokio-reactor-trait = "1.1.0"-tracing = "0.1.40"-tracing-subscriber = "0.3.18"diff --git a/worker/README.md b/worker/README.mddeleted file mode 100644index 3442a350..00000000--- a/worker/README.md+++ /dev/null@@ -1,12 +0,0 @@-[](https://hub.docker.com/r/reacherhq/worker)-[](https://github.com/reacherhq/check-if-email-exists/actions)--<br /><br />--<p align="center"><img align="center" src="https://storage.googleapis.com/saasify-uploads-prod/696e287ad79f0e0352bc201b36d701849f7d55e7.svg" height="96" alt="reacher" /></p>-<h1 align="center">👷 Reacher Worker</h1>-<h4 align="center">RabbitMQ worker for Reacher Email Verification API: https://reacher.email.</h4>--<br /><br />--This crate holds a RabbitMQ worker for [Reacher](https://reacher.email). More documentation coming soon...diff --git a/worker/docker.sh b/worker/docker.shdeleted file mode 100755index 9c14fd55..00000000--- a/worker/docker.sh+++ /dev/null@@ -1,5 +0,0 @@-#!/bin/ash--# https://docs.docker.com/config/containers/multi-service_container/-chromedriver &-./reacher_workerdiff --git a/worker/src/sentry_util.rs b/worker/src/sentry_util.rsdeleted file mode 100644index 38a1e6ca..00000000--- a/worker/src/sentry_util.rs+++ /dev/null@@ -1,189 +0,0 @@-// Reacher - Email Verification-// Copyright (C) 2018-2023 Reacher--// This program is free software: you can redistribute it and/or modify-// it under the terms of the GNU Affero General Public License as published-// by the Free Software Foundation, either version 3 of the License, or-// (at your option) any later version.--// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU Affero General Public License for more details.--// You should have received a copy of the GNU Affero General Public License-// along with this program. If not, see <https://www.gnu.org/licenses/>.--//! Helper functions to send events to Sentry.-//!-//! This module also contains functions that check if the error's given by-//! `check-if-email-exists` are known errors, in which case we don't log them-//! to Sentry.--use std::borrow::Cow;-use std::env;--use async_smtp::smtp::error::Error as AsyncSmtpError;-use check_if_email_exists::misc::MiscError;-use check_if_email_exists::mx::MxError;-use check_if_email_exists::{smtp::SmtpError, CheckEmailOutput};-use sentry::protocol::{Event, Exception, Level, Values};-use tracing::{debug, info};--use super::sentry_util;--pub const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");--/// Setup Sentry.-pub fn setup_sentry() -> sentry::ClientInitGuard {- // Use an empty string if we don't have any env variable for sentry. Sentry- // will just silently ignore.- let sentry = sentry::init(env::var("RCH_SENTRY_DSN").unwrap_or_else(|_| "".into()));- if sentry.is_enabled() {- info!("Sentry is successfully set up.")- }-- sentry-}--/// If RCH_BACKEND_NAME environment variable is set, add it to the sentry-/// `server_name` properties.-/// For backwards compatibility, we also support HEROKU_APP_NAME env variable.-fn get_backend_name<'a>() -> Option<Cow<'a, str>> {- if let Ok(n) = env::var("RCH_BACKEND_NAME") {- return Some(n.into());- } else if let Ok(n) = env::var("HEROKU_APP_NAME") {- return Some(n.into());- }-- None-}--#[derive(Debug)]-enum SentryError<'a> {- // TODO: Probably a good idea would be to `impl std:error:Error` for the- // three errors below.- Misc(&'a MiscError),- Mx(&'a MxError),- Smtp(&'a SmtpError),-}--impl<'a> SentryError<'a> {- /// Get the error type to be passed into Sentry's Exception `ty` field.- fn get_exception_type(&self) -> String {- match self {- SentryError::Misc(_) => "MiscError".into(),- SentryError::Mx(_) => "MxError".into(),- SentryError::Smtp(_) => "SmtpError".into(),- }- }-}--/// Helper function to send an Error event to Sentry. We redact all sensitive-/// info before sending to Sentry, by removing all instances of `username`.-fn error(err: SentryError, result: &CheckEmailOutput) {- let exception_value = redact(format!("{err:?}").as_str(), &result.syntax.username);- debug!("Sending error to Sentry: {}", exception_value);-- let exception = Exception {- ty: err.get_exception_type(),- value: Some(exception_value),- ..Default::default()- };-- sentry::capture_event(Event {- exception: Values {- values: vec![exception],- },- level: Level::Error,- environment: Some("production".into()),- release: Some(CARGO_PKG_VERSION.into()),- message: Some(redact(- format!("{result:#?}").as_str(),- &result.syntax.username,- )),- server_name: get_backend_name(),- transaction: Some(format!("check_email:{}", result.syntax.domain)),- ..Default::default()- });-}--/// Function to replace all usernames from email, and replace them with-/// `***@domain.com` for privacy reasons.-fn redact(input: &str, username: &str) -> String {- input.replace(username, "***")-}--/// Check if the message contains known SMTP Transient errors.-fn skip_smtp_transient_errors(message: &[String]) -> bool {- let first_line = message[0].to_lowercase();-- // 4.3.2 Please try again later- first_line.contains("try again") ||- // Temporary local problem - please try later- first_line.contains("try later")-}--/// Checks if the output from `check-if-email-exists` has a known error, in-/// which case we don't log to Sentry to avoid spamming it.-pub fn log_unknown_errors(result: &CheckEmailOutput) {- match (&result.misc, &result.mx, &result.smtp) {- (Err(err), _, _) => {- // We log all misc errors.- sentry_util::error(SentryError::Misc(err), result);- }- (_, Err(err), _) => {- // We log all mx errors.- sentry_util::error(SentryError::Mx(err), result);- }- (_, _, Err(err)) if err.get_description().is_some() => {- // If the SMTP error is known, we don't track it in Sentry.- }- (_, _, Err(SmtpError::SmtpError(AsyncSmtpError::Transient(response))))- if skip_smtp_transient_errors(&response.message) =>- {- // If the SMTP error is transient and known, we don't track it in- // Sentry, just log it locally.- let redacted = redact(- response.message[0].as_str(),- result.syntax.username.as_str(),- );- debug!(email=?redacted, "Transient error");- }- (_, _, Err(err)) => {- // If it's a SMTP error we didn't catch above, we log to- // Sentry, to be able to debug them better. We don't want to- // spam Sentry and log all instances of the error, hence the- // `count` check.- sentry_util::error(SentryError::Smtp(err), result);- }- // If everything is ok, we just return the result.- (Ok(_), Ok(_), Ok(_)) => {}- }-}--#[cfg(test)]-mod tests {- use super::redact;-- #[test]- fn test_redact() {- assert_eq!("***@gmail.com", redact("[email protected]", "someone"));- assert_eq!(- "my email is ***@gmail.com.",- redact("my email is [email protected].", "someone")- );- assert_eq!(- "my email is ***@gmail.com., I repeat, my email is ***@gmail.com.",- redact(- "my email is [email protected]., I repeat, my email is [email protected].",- "someone"- )- );- assert_eq!(- "*** @ gmail . com",- redact("someone @ gmail . com", "someone")- );- assert_eq!("*** is here.", redact("someone is here.", "someone"));- }-}