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
feat!: Add `/v1/{check_email,bulk}` endpoints with throttle&concurrency (#1537)
Amaury08522e4326bb
diff --git a/.github/workflows/deploy_backend.yml b/.github/workflows/deploy_backend.ymlindex c1b700d3..7845a450 100644--- a/.github/workflows/deploy_backend.yml+++ b/.github/workflows/deploy_backend.yml@@ -3,7 +3,7 @@ name: deploy_backendon:push:tags:- - "backend/v*.*.*"+ - "v*.*.*"jobs:docker-publish:@@ -12,7 +12,7 @@ jobs:- uses: actions/checkout@master- name: Set GITHUB_TAG argid: vars- run: echo ::set-output name=GITHUB_TAG::${GITHUB_REF:18} # Remove /refs/head/backend/+ run: echo ::set-output name=GITHUB_TAG::${GITHUB_REF}- name: Print versionrun: echo "Publishing reacherhq/backend:${{ steps.vars.outputs.GITHUB_TAG }}"- name: Publish to Registrydiff --git a/.github/workflows/deploy_cli.yml b/.github/workflows/deploy_cli.ymlindex 5dc1586a..151f4e35 100644--- a/.github/workflows/deploy_cli.yml+++ b/.github/workflows/deploy_cli.yml@@ -3,7 +3,7 @@ name: deploy_clion:push:tags:- - "cli/v*"+ - "v*.*.*"env:# TODO: Rename to your binarydiff --git a/.gitignore b/.gitignoreindex 0cba1cb8..c3d5909c 100644--- a/.gitignore+++ b/.gitignore@@ -3,6 +3,9 @@ target.DS_Storeprivate+# docker-compose+backend/postgres_data+# Output when debugging Hotmail password recovery using a headless browser.hotmail.jpegdiff --git a/.sqlx/query-0968b040845ecce236576f65df3d3648f7ce03bc5ae0ebe9f36f878c309061c8.json b/.sqlx/query-0968b040845ecce236576f65df3d3648f7ce03bc5ae0ebe9f36f878c309061c8.jsonnew file mode 100644index 00000000..749ef84f--- /dev/null+++ b/.sqlx/query-0968b040845ecce236576f65df3d3648f7ce03bc5ae0ebe9f36f878c309061c8.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n\t\tSELECT id, created_at, total_records FROM v1_bulk_job\n\t\tWHERE id = $1\n\t\tLIMIT 1\n\t\t",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Int4"+ },+ {+ "ordinal": 1,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 2,+ "name": "total_records",+ "type_info": "Int4"+ }+ ],+ "parameters": {+ "Left": [+ "Int4"+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "0968b040845ecce236576f65df3d3648f7ce03bc5ae0ebe9f36f878c309061c8"+}diff --git a/.sqlx/query-1e5a713008953f95d626e578ed0f2bc2cfc2b1599d8c5d09d11287a661fccd0e.json b/.sqlx/query-1e5a713008953f95d626e578ed0f2bc2cfc2b1599d8c5d09d11287a661fccd0e.jsonnew file mode 100644index 00000000..8f835ea1--- /dev/null+++ b/.sqlx/query-1e5a713008953f95d626e578ed0f2bc2cfc2b1599d8c5d09d11287a661fccd0e.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT total_records FROM v1_bulk_job WHERE id = $1;",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "total_records",+ "type_info": "Int4"+ }+ ],+ "parameters": {+ "Left": [+ "Int4"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "1e5a713008953f95d626e578ed0f2bc2cfc2b1599d8c5d09d11287a661fccd0e"+}diff --git a/.sqlx/query-323970c6cb4f5d4b7c0cb3293d1e6fd146c7d682e28e6cb72de6bbe14a3e04b7.json b/.sqlx/query-323970c6cb4f5d4b7c0cb3293d1e6fd146c7d682e28e6cb72de6bbe14a3e04b7.jsonnew file mode 100644index 00000000..78e30929--- /dev/null+++ b/.sqlx/query-323970c6cb4f5d4b7c0cb3293d1e6fd146c7d682e28e6cb72de6bbe14a3e04b7.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n\t\tSELECT result FROM v1_task_result\n\t\tWHERE job_id = $1\n\t\tORDER BY id\n\t\tLIMIT $2 OFFSET $3\n\t\t",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "result",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Int4",+ "Int8",+ "Int8"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "323970c6cb4f5d4b7c0cb3293d1e6fd146c7d682e28e6cb72de6bbe14a3e04b7"+}diff --git a/.sqlx/query-594dfc319a34dfdcf316758798a9ad099c298480b4f1dabc69b1dc6e2f4687a0.json b/.sqlx/query-594dfc319a34dfdcf316758798a9ad099c298480b4f1dabc69b1dc6e2f4687a0.jsonnew file mode 100644index 00000000..13615e58--- /dev/null+++ b/.sqlx/query-594dfc319a34dfdcf316758798a9ad099c298480b4f1dabc69b1dc6e2f4687a0.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT COUNT(*) FROM v1_task_result WHERE job_id = $1;",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Int4"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "594dfc319a34dfdcf316758798a9ad099c298480b4f1dabc69b1dc6e2f4687a0"+}diff --git a/.sqlx/query-96a32768eb750971bad4df10560b0331bf52b44dbd59020369adbbc6bc8dc830.json b/.sqlx/query-96a32768eb750971bad4df10560b0331bf52b44dbd59020369adbbc6bc8dc830.jsonnew file mode 100644index 00000000..a64ac891--- /dev/null+++ b/.sqlx/query-96a32768eb750971bad4df10560b0331bf52b44dbd59020369adbbc6bc8dc830.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n\t\tINSERT INTO v1_bulk_job (total_records)\n\t\tVALUES ($1)\n\t\tRETURNING id\n\t\t",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Int4"+ }+ ],+ "parameters": {+ "Left": [+ "Int4"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "96a32768eb750971bad4df10560b0331bf52b44dbd59020369adbbc6bc8dc830"+}diff --git a/.sqlx/query-030e82770e9458ee745aa647eba42da57167a810dd708d991e3dfdff32217273.json b/.sqlx/query-aaa1cf5961de24b1fb68f856205afe4d3bfaf55e3371f46a472ea3d5705d35b2.jsonsimilarity index 54%rename from .sqlx/query-030e82770e9458ee745aa647eba42da57167a810dd708d991e3dfdff32217273.jsonrename to .sqlx/query-aaa1cf5961de24b1fb68f856205afe4d3bfaf55e3371f46a472ea3d5705d35b2.jsonindex 98395822..b8242e06 100644--- a/.sqlx/query-030e82770e9458ee745aa647eba42da57167a810dd708d991e3dfdff32217273.json+++ b/.sqlx/query-aaa1cf5961de24b1fb68f856205afe4d3bfaf55e3371f46a472ea3d5705d35b2.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n\t\t\t\tINSERT INTO reacher_results (payload, worker, result)\n\t\t\t\tVALUES ($1, $2, $3)\n\t\t\t\tRETURNING id\n\t\t\t\t",+ "query": "\n\t\t\t\tINSERT INTO v1_task_result (payload, job_id, backend_name, result)\n\t\t\t\tVALUES ($1, $2, $3, $4)\n\t\t\t\tRETURNING id\n\t\t\t\t","describe": {"columns": [{@@ -12,6 +12,7 @@"parameters": {"Left": ["Jsonb",+ "Int4","Text","Jsonb"]@@ -20,5 +21,5 @@false]},- "hash": "030e82770e9458ee745aa647eba42da57167a810dd708d991e3dfdff32217273"+ "hash": "aaa1cf5961de24b1fb68f856205afe4d3bfaf55e3371f46a472ea3d5705d35b2"}diff --git a/.sqlx/query-d682d43a07f3969bcb3113ae3600766e9197d48bdc7ccb73a53c938cb45f910f.json b/.sqlx/query-d682d43a07f3969bcb3113ae3600766e9197d48bdc7ccb73a53c938cb45f910f.jsonnew file mode 100644index 00000000..fdc7b286--- /dev/null+++ b/.sqlx/query-d682d43a07f3969bcb3113ae3600766e9197d48bdc7ccb73a53c938cb45f910f.json@@ -0,0 +1,52 @@+{+ "db_name": "PostgreSQL",+ "query": "\n\t\tSELECT\n\t\t\tCOUNT(*) as total_processed,\n\t\t\tCOUNT(CASE WHEN result ->> 'is_reachable' LIKE 'safe' THEN 1 END) as safe_count,\n\t\t\tCOUNT(CASE WHEN result ->> 'is_reachable' LIKE 'risky' THEN 1 END) as risky_count,\n\t\t\tCOUNT(CASE WHEN result ->> 'is_reachable' LIKE 'invalid' THEN 1 END) as invalid_count,\n\t\t\tCOUNT(CASE WHEN result ->> 'is_reachable' LIKE 'unknown' THEN 1 END) as unknown_count,\n\t\t\t(SELECT created_at FROM v1_task_result WHERE job_id = $1 ORDER BY created_at DESC LIMIT 1) as finished_at\n\t\tFROM v1_task_result\n\t\tWHERE job_id = $1\n\t\t",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "total_processed",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "safe_count",+ "type_info": "Int8"+ },+ {+ "ordinal": 2,+ "name": "risky_count",+ "type_info": "Int8"+ },+ {+ "ordinal": 3,+ "name": "invalid_count",+ "type_info": "Int8"+ },+ {+ "ordinal": 4,+ "name": "unknown_count",+ "type_info": "Int8"+ },+ {+ "ordinal": 5,+ "name": "finished_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Int4"+ ]+ },+ "nullable": [+ null,+ null,+ null,+ null,+ null,+ null+ ]+ },+ "hash": "d682d43a07f3969bcb3113ae3600766e9197d48bdc7ccb73a53c938cb45f910f"+}diff --git a/.sqlx/query-a1f7a67d3708b8cf74361c33bfdd1dcbe9938a78b6c4ff550336ee4d16eb3ff3.json b/.sqlx/query-f7ac211d1216f1c0cecc80074a7307b69ee10ca90a712a6e38175c898b8e06b1.jsonsimilarity index 54%rename from .sqlx/query-a1f7a67d3708b8cf74361c33bfdd1dcbe9938a78b6c4ff550336ee4d16eb3ff3.jsonrename to .sqlx/query-f7ac211d1216f1c0cecc80074a7307b69ee10ca90a712a6e38175c898b8e06b1.jsonindex 6658bc74..abcac7de 100644--- a/.sqlx/query-a1f7a67d3708b8cf74361c33bfdd1dcbe9938a78b6c4ff550336ee4d16eb3ff3.json+++ b/.sqlx/query-f7ac211d1216f1c0cecc80074a7307b69ee10ca90a712a6e38175c898b8e06b1.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n\t\t\t\tINSERT INTO reacher_results (payload, worker, error)\n\t\t\t\tVALUES ($1, $2, $3)\n\t\t\t\tRETURNING id\n\t\t\t\t",+ "query": "\n\t\t\t\tINSERT INTO v1_task_result (payload, job_id, backend_name, error)\n\t\t\t\tVALUES ($1, $2, $3, $4)\n\t\t\t\tRETURNING id\n\t\t\t\t","describe": {"columns": [{@@ -12,6 +12,7 @@"parameters": {"Left": ["Jsonb",+ "Int4","Text","Text"]@@ -20,5 +21,5 @@false]},- "hash": "a1f7a67d3708b8cf74361c33bfdd1dcbe9938a78b6c4ff550336ee4d16eb3ff3"+ "hash": "f7ac211d1216f1c0cecc80074a7307b69ee10ca90a712a6e38175c898b8e06b1"}diff --git a/.vscode/settings.json b/.vscode/settings.jsonnew file mode 100644index 00000000..2decb065--- /dev/null+++ b/.vscode/settings.json@@ -0,0 +1,3 @@+{+ "rust-analyzer.cargo.features": "all"+}diff --git a/Cargo.lock b/Cargo.lockindex 48616230..37586135 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -575,7 +575,7 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"[[package]]name = "check-if-email-exists"-version = "0.9.1"+version = "0.10.0"dependencies = ["async-native-tls","async-recursion",@@ -600,14 +600,16 @@ dependencies = ["sentry","serde","serde_json",+ "thiserror","tokio","tracing",][[package]]name = "check-if-email-exists-cli"-version = "0.9.1"+version = "0.10.0"dependencies = [+ "anyhow","check-if-email-exists","clap","env_logger",@@ -928,7 +930,7 @@ dependencies = ["proc-macro2","quote","strsim 0.11.1",- "syn 2.0.66",+ "syn 2.0.87",][[package]]@@ -950,7 +952,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806"dependencies = ["darling_core 0.20.10","quote",- "syn 2.0.66",+ "syn 2.0.87",][[package]]@@ -1059,7 +1061,7 @@ dependencies = ["darling 0.20.10","proc-macro2","quote",- "syn 2.0.66",+ "syn 2.0.87",][[package]]@@ -1069,7 +1071,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c"dependencies = ["derive_builder_core 0.20.2",- "syn 2.0.66",+ "syn 2.0.87",][[package]]@@ -2990,34 +2992,15 @@ dependencies = [[[package]]name = "reacher_backend"-version = "0.7.0"+version = "0.10.0"dependencies = [+ "anyhow","async-smtp","check-if-email-exists","config","csv","dotenv",- "openssl",- "sentry",- "serde",- "serde_json",- "sqlx",- "sqlxmq",- "tokio",- "tracing",- "tracing-subscriber",- "uuid 1.10.0",- "warp",-]--[[package]]-name = "reacher_worker"-version = "0.1.0"-dependencies = [- "async-smtp",- "check-if-email-exists",- "config",- "futures-lite 2.5.0",+ "futures","lapin","openssl","reqwest 0.12.5",@@ -3026,11 +3009,14 @@ dependencies = ["serde_json","sqlx","sqlxmq",+ "thiserror","tokio","tokio-executor-trait","tokio-reactor-trait","tracing","tracing-subscriber",+ "uuid 1.10.0",+ "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/backend/Cargo.toml b/backend/Cargo.tomlindex fab5e20b..ff1d51dc 100644--- a/backend/Cargo.toml+++ b/backend/Cargo.toml@@ -1,17 +1,23 @@[package]name = "reacher_backend"-version = "0.7.0"+version = "0.10.0"edition = "2018"license = "AGPL-3.0"publish = false[dependencies]+anyhow = "1.0"async-smtp = "0.6"check-if-email-exists = { path = "../core", features = ["sentry"] }config = "0.14"csv = "1.3.0"dotenv = "0.15.0"+futures = { version = "0.3.30", optional = true }+lapin = { version = "2.3.1", optional = true }+tokio-executor-trait = { version = "2.1.1", optional = true }+tokio-reactor-trait = { version = "1.1.0", optional = true }openssl = { version = "0.10.64", features = ["vendored"] }+reqwest = { version = "0.12.5", features = ["json", "socks"], optional = true }sentry = "0.23"serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"@@ -24,8 +30,18 @@ sqlx = { version = "0.7", features = ["migrate",] }sqlxmq = "0.5"+thiserror = "1.0"tokio = { version = "1.40", features = ["macros"] }tracing = "0.1.40"tracing-subscriber = "0.3.18"uuid = "1.10"warp = "0.3"++[features]+worker = [+ "futures",+ "lapin",+ "tokio-executor-trait",+ "tokio-reactor-trait",+ "reqwest",+]diff --git a/backend/Dockerfile b/backend/Dockerfileindex fea4dbac..f142de34 100644--- a/backend/Dockerfile+++ b/backend/Dockerfile@@ -14,7 +14,7 @@ COPY . .ENV SQLX_OFFLINE=true-RUN cargo build --bin reacher_backend --release --target=x86_64-unknown-linux-musl+RUN cargo build --bin reacher_backend --features worker --release --target=x86_64-unknown-linux-musl# ------------------------------------------------------------------------------# Final Stagediff --git a/backend/backend_config.toml b/backend/backend_config.tomlindex 8d17f2be..214e5791 100644--- a/backend/backend_config.toml+++ b/backend/backend_config.toml@@ -1,39 +1,104 @@# Backend configuration-# Backend name to identify the backend.+# Name to identify the backend.backend_name = "backend-dev"-# Backend host to bind to.+# Host to bind the backend to.http_host = "127.0.0.1"-# Backend port.+# Port for the backend.http_port = 8080-# Shared secret between a trusted client and the backend, that must be present-# in the `x-reacher-secret` header of all incoming requests.+# Shared secret between a trusted client and the backend, required in the+# `x-reacher-secret` header of all incoming requests.# header_secret = "my-secret"-# The name to use during the EHLO/HELO command in the SMTP conversation.-# Ideally, this should match the reverse DNS of the IP address of the server.+# Name to use during the EHLO/HELO command in the SMTP conversation.+# Ideally, this should match the reverse DNS of the server's IP address.hello_name = "reacher"-# The email to use during the MAIL FROM command in the SMTP conversation.+# Email to use during the MAIL FROM command in the SMTP conversation.# Ideally, the domain of this email should match the "hello_name" above.from_email = "[email protected]"-# The address of the Chrome WebDriver server to use for making headless email-# verifications.+# Address of the Chrome WebDriver server for headless email verifications.webdriver_addr = "http://localhost:9515"-# Throttle the maximum number of requests per second, per minute, per hour, an+# Uncomment the following lines to route all SMTP verification requests through+# a specified proxy. Note that the proxy must be a SOCKS5 proxy to work with+# the SMTP protocol. This proxy will not be used for headless verifications.+#+# The username and password are optional and only needed if the proxy requires+# authentication.+# [proxy]+# host = "my.proxy.com"+# port = 1080+# username = "my-username"+# password = "my-password"++# Verification method to use for each email provider. Available methods are:+# "smtp", "headless", and "api". Note that not all methods are supported by+# all email providers.+[verif_method]+# Gmail currently only supports the "smtp" method.+gmail = "smtp"+# Hotmail B2B currently only supports the "smtp" method.+hotmailb2b = "smtp"+# Hotmail B2C supports both "headless" and "smtp" methods. The "headless"+# method is recommended.+hotmailb2c = "headless"+# Yahoo supports both "headless" and "smtp" methods. The "headless" method is+# recommended.+yahoo = "headless"++[worker]+enable = false++# Fields below are only used if the worker is enabled.++# Throttle the maximum number of requests per second, per minute, per hour, and# per day for this worker.-# All fields are optional, comment them out to disable the limit.+# All fields are optional; comment them out to disable the limit.#-# Important: these throttle configurations only apply to bulk verification, and+# Important: these throttle configurations only apply to bulk verification and# not to the single /v0/check_email endpoint. The latter endpoint always# executes the verification immediately, regardless of the throttle settings.-[throttle]+[worker.throttle]# max_requests_per_second = 20# max_requests_per_minute = 100# max_requests_per_hour = 1000-max_requests_per_day = 20000+# max_requests_per_day = 20000++# RabbitMQ configuration.+[worker.rabbitmq]+url = "amqp://guest:guest@localhost:5672"++# Queues to consume emails from. By default, the worker consumes from all+# queues.+#+# To consume from only a subset of queues, uncomment the line `queues = "all"`+# and specify the queues you want to consume from.+#+# Below is the exhaustive list of queue names that the worker can consume from:+# - "check.gmail": subscribe exclusively to Gmail emails.+# - "check.hotmailb2b": subscribe exclusively to Hotmail B2B emails.+# - "check.hotmailb2c": subscribe exclusively to Hotmail B2C emails.+# - "check.yahoo": subscribe exclusively to Yahoo emails.+# - "check.everything_else": subscribe to all emails that are not Gmail, Yahoo, or Hotmail.+#+# queues = ["check.gmail", "check.hotmail.b2b", "check.hotmail.b2c", "check.yahoo", "check.everything_else"]+queues = "all"++# Number of concurrent emails to verify for this worker across all queues.+concurrency = 20++# Postgres configuration. Currently, a Postgres database is required to store+# the results of the verifications. This might change in the future, allowing+# for pluggable storage.+[worker.postgres]+db_url = "postgresql://localhost/reacherdb"++# Optional webhook URL to send the results to. This will send one POST request+# per email verification, with the result in the body.+# [worker.webhook.on_each_email]+# url = "http://localhost:8080/webhook"diff --git a/backend/migrations/20220117025847_email_data.down.sql b/backend/migrations/20220117025847_email_data.down.sqlindex 5309e662..ed211e33 100644--- a/backend/migrations/20220117025847_email_data.down.sql+++ b/backend/migrations/20220117025847_email_data.down.sql@@ -1,4 +1,4 @@-DROP INDEX v0_job_emails;-DROP TABLE v0_bulk_results;-DROP TABLE v0_bulk_jobs;+DROP INDEX job_emails;+DROP TABLE email_results;+DROP TABLE bulk_jobs;DROP TYPE valid_status;\ No newline at end of filediff --git a/backend/migrations/20220117025847_email_data.up.sql b/backend/migrations/20220117025847_email_data.up.sqlindex 2fb0ee81..d53e83d5 100644--- a/backend/migrations/20220117025847_email_data.up.sql+++ b/backend/migrations/20220117025847_email_data.up.sql@@ -1,12 +1,12 @@-CREATE TABLE v0_bulk_jobs (+CREATE TABLE bulk_jobs (id SERIAL PRIMARY KEY,created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),total_records INTEGER NOT NULL);-CREATE TABLE v0_bulk_results (+CREATE TABLE email_results (id SERIAL PRIMARY KEY,job_id INTEGER,result JSONB,- FOREIGN KEY (job_id) REFERENCES v0_bulk_jobs(id)+ FOREIGN KEY (job_id) REFERENCES bulk_jobs(id));-CREATE INDEX v0_job_emails ON v0_bulk_results USING HASH (job_id);\ No newline at end of file+CREATE INDEX job_emails ON email_results USING HASH (job_id);\ No newline at end of filediff --git a/backend/migrations/20220810141100_result_created_at.down.sql b/backend/migrations/20220810141100_result_created_at.down.sqlindex e761e47e..80b95f10 100644--- a/backend/migrations/20220810141100_result_created_at.down.sql+++ b/backend/migrations/20220810141100_result_created_at.down.sql@@ -1,2 +1,2 @@-ALTER TABLE v0_bulk_results+ALTER TABLE email_resultsDROP COLUMN created_at;diff --git a/backend/migrations/20220810141100_result_created_at.up.sql b/backend/migrations/20220810141100_result_created_at.up.sqlindex ee522dda..ab28f019 100644--- a/backend/migrations/20220810141100_result_created_at.up.sql+++ b/backend/migrations/20220810141100_result_created_at.up.sql@@ -1,2 +1,2 @@-ALTER TABLE v0_bulk_results+ALTER TABLE email_resultsADD created_at TIMESTAMPTZ NOT NULL DEFAULT NOW();\ No newline at end of filediff --git a/backend/migrations/20240929230957_v1_worker_results.down.sql b/backend/migrations/20240929230957_v1_worker_results.down.sqlnew file mode 100644index 00000000..621aea38--- /dev/null+++ b/backend/migrations/20240929230957_v1_worker_results.down.sql@@ -0,0 +1,4 @@+-- Add down migration script here+DROP INDEX IF EXISTS v1_worker_results_job_id;+DROP TABLE IF EXISTS v1_task_result;+DROP TABLE IF EXISTS v1_bulk_job;diff --git a/backend/migrations/20240929230957_v1_worker_results.up.sql b/backend/migrations/20240929230957_v1_worker_results.up.sqlnew file mode 100644index 00000000..d055b77c--- /dev/null+++ b/backend/migrations/20240929230957_v1_worker_results.up.sql@@ -0,0 +1,17 @@+CREATE TABLE v1_bulk_job (+ id SERIAL PRIMARY KEY,+ total_records INTEGER NOT NULL,+ created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL+);++CREATE TABLE v1_task_result (+ id SERIAL PRIMARY KEY,+ job_id INTEGER NOT NULL REFERENCES v1_bulk_job(id) ON DELETE CASCADE,+ payload JSONB NOT NULL,+ backend_name TEXT NOT NULL,+ result JSONB,+ error TEXT,+ created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL+);++CREATE INDEX idx_v1_task_result_job_id ON v1_task_result (job_id);diff --git a/backend/openapi.json b/backend/openapi.jsonindex 4447718b..a37655f5 100644--- a/backend/openapi.json+++ b/backend/openapi.json@@ -2,8 +2,8 @@"openapi": "3.0.0","info": {"title": "Reacher",- "version": "0.5.0",- "description": "### What is Reacher?\n\nReacher is a powerful, free and open-source email verification API service. It is provided both as a SaaS and as a self-host solution.",+ "version": "0.10.0",+ "description": "### What is Reacher?\n\nReacher is a robust, open-source email verification API service available as both a SaaS and self-hosted solution.","license": {"name": "AGPL-3.0 OR Commercial","url": "https://github.com/reacherhq/check-if-email-exists/blob/master/LICENSE.md"@@ -17,57 +17,261 @@},"servers": [{- "url": "https://api.reacher.email/v0",+ "url": "https://api.reacher.email","description": "Reacher Production"}],"paths": {- "/check_email": {+ "/v1/check_email": {"post": {- "summary": "/check_email",+ "summary": "/v1/check_email","responses": {"200": {"description": "OK","content": {"application/json": {"schema": {+ "type": "object","$ref": "#/components/schemas/CheckEmailOutput"- },- "examples": {- "Example with [email protected]": {- "value": {- "input": "[email protected]",- "is_reachable": "invalid",- "misc": {- "is_disposable": false,- "is_role_account": true+ }+ }+ }+ }+ },+ "operationId": "post-v1-check-email",+ "x-stoplight": {+ "id": "yho6jrv7p04qv"+ },+ "description": "Perform a comprehensive verification of an email address. This endpoint supersedes the previous `/v0/check_email` endpoint, maintaining the same input and output format. Unlike the `/v0/check_email` endpoint, the new `/v1/check_email` endpoint queues the email for verification, and the Reacher server processes the queue based on its configuration settings such as throttle and concurrency.",+ "requestBody": {+ "description": "Request object containing all parameters necessary for an email verification.",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "$ref": "#/components/schemas/CheckEmailRequest"+ }+ }+ }+ }+ },+ "parameters": [],+ "servers": []+ },+ "/v1/bulk": {+ "post": {+ "summary": "/v1/bulk",+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "required": ["job_id"],+ "properties": {+ "job_id": {+ "type": "integer",+ "x-stoplight": {+ "id": "614agdy9mxybk"+ },+ "description": "The unique ID generated for this bulk verification job. Use this `job_id` to query the progress or results of the bulk verification."+ }+ }+ }+ }+ }+ }+ },+ "operationId": "post-v1-bulk",+ "x-stoplight": {+ "id": "jpoyy08arq31b"+ },+ "description": "Initiate a bulk email verification.",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "required": ["input"],+ "properties": {+ "input": {+ "type": "array",+ "x-stoplight": {+ "id": "fsitj4yhkzk8e"+ },+ "description": "A list of emails to verify.",+ "items": {+ "x-stoplight": {+ "id": "kgcb3i4u5sfgr"+ },+ "type": "string"+ }+ },+ "webhook": {+ "$ref": "#/components/schemas/TaskWebhook"+ }+ }+ }+ }+ }+ }+ }+ },+ "/v1/bulk/{job_id}": {+ "parameters": [+ {+ "schema": {+ "type": "integer"+ },+ "name": "job_id",+ "in": "path",+ "required": true,+ "description": "The unique bulk verification job ID"+ }+ ],+ "get": {+ "summary": "/v1/bulk/{job_id}",+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "required": [+ "job_id",+ "created_at",+ "total_records",+ "total_processed",+ "summary",+ "job_status"+ ],+ "properties": {+ "job_id": {+ "type": "integer",+ "x-stoplight": {+ "id": "4f6vqudy7zank"+ }+ },+ "created_at": {+ "type": "string",+ "x-stoplight": {+ "id": "7baymbmoaj5vo"},- "mx": {- "accepts_mail": true,- "records": [- "alt4.gmail-smtp-in.l.google.com.",- "alt2.gmail-smtp-in.l.google.com.",- "alt3.gmail-smtp-in.l.google.com.",- "gmail-smtp-in.l.google.com.",- "alt1.gmail-smtp-in.l.google.com."- ]+ "format": "date-time",+ "description": "The date and time when the bulk verification job was created."+ },+ "finished_at": {+ "type": "string",+ "x-stoplight": {+ "id": "7lhzxsb1ixnvz"},- "smtp": {- "can_connect_smtp": true,- "has_full_inbox": false,- "is_catch_all": false,- "is_deliverable": false,- "is_disabled": false,- "verif_method": {- "type": "Smtp",- "host": "alt3.gmail-smtp-in.l.google.com."- }+ "format": "date-time",+ "description": "If the bulk verification job is completed, the date and time when it was finished."+ },+ "total_records": {+ "type": "integer",+ "x-stoplight": {+ "id": "y8q2zhagq8zd6"+ },+ "description": "The number of emails to verify in the bulk verification job."+ },+ "total_processed": {+ "type": "integer",+ "x-stoplight": {+ "id": "oqxvsorhd06ch"},- "syntax": {- "domain": "gmail.com",- "is_valid_syntax": true,- "username": "test"+ "description": "The number of emails that have been verified at the time of the query."+ },+ "summary": {+ "type": "object",+ "x-stoplight": {+ "id": "n5q382zces1lq"+ },+ "description": "A summary of the processed emails.",+ "required": [+ "total_safe",+ "total_invalid",+ "total_risky",+ "total_unknown"+ ],+ "properties": {+ "total_safe": {+ "type": "integer",+ "x-stoplight": {+ "id": "4nss0vedcrjc4"+ },+ "description": "The number of emails where `is_reachable` is \"safe\"."+ },+ "total_invalid": {+ "type": "integer",+ "x-stoplight": {+ "id": "uzzk7ija2l5sv"+ },+ "description": "The number of emails where `is_reachable` is \"invalid\"."+ },+ "total_risky": {+ "type": "integer",+ "x-stoplight": {+ "id": "sqjtoggge6us3"+ },+ "description": "The number of emails where `is_reachable` is \"risky\"."+ },+ "total_unknown": {+ "type": "integer",+ "x-stoplight": {+ "id": "8lsodukakqreu"+ },+ "description": "The number of emails where `is_reachable` is \"unknown\"."+ }}+ },+ "job_status": {+ "x-stoplight": {+ "id": "tsw5sp5cxe7ad"+ },+ "enum": ["Running", "Completed"],+ "description": "The status of the job, either \"Running\" or \"Completed\"."+ }+ }+ }+ }+ }+ }+ },+ "operationId": "get-v1-bulk",+ "x-stoplight": {+ "id": "phrhxrak01ja6"+ },+ "description": "Retrieve the progress of a bulk verification job."+ }+ },+ "/v1/bulk/{job_id}/results": {+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "name": "job_id",+ "in": "path",+ "required": true,+ "description": "The unique bulk verification job ID"+ }+ ],+ "get": {+ "summary": "Retrieve bulk verification results",+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "required": ["results"],+ "properties": {+ "results": {+ "$ref": "#/components/schemas/CheckEmailOutput"}}}@@ -75,17 +279,59 @@}}},- "operationId": "post-check-email",- "description": "Perform a full verification of an email address.",+ "operationId": "get-v1-bulk-results",+ "x-stoplight": {+ "id": "skx9nlfib3but"+ },+ "description": "Retrieve the results of a bulk verification job. This endpoint will return an error if the job is still running. Please query `GET /v1/bulk/{job_id}` first to check the job's progress.",+ "parameters": [+ {+ "schema": {+ "type": "integer",+ "default": 50+ },+ "in": "query",+ "name": "limit",+ "description": "The number of results to return."+ },+ {+ "schema": {+ "type": "integer"+ },+ "in": "query",+ "name": "offset",+ "description": "The offset from which to return the results, equivalent to the number of elements in the array to skip."+ }+ ]+ }+ },+ "/v0/check_email": {+ "post": {+ "summary": "/v0/check_email",+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CheckEmailOutput"+ },+ "examples": {}+ }+ }+ }+ },+ "operationId": "post-v0-check-email",+ "description": "**Sunset notice: please use `/v1/check_email` instead.** Both endpoints accept the same input arguments and return the same output; only their internal implementation differs. Perform a comprehensive verification of an email address. Unlike the `/v1/check_email` endpoint, this endpoint performs an email verification immediately, without considering the Reacher server's throttling, concurrency, and other configurations. As such, this endpoint is slightly riskier than `/v1/check_email`, as the Reacher server's IP reputation can be impacted if this endpoint is called too frequently.","requestBody": {"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/CheckEmailInput"+ "$ref": "#/components/schemas/CheckEmailRequest"}}},- "description": "Input containing all parameters necessary for an email verification."+ "description": "Request object containing all parameters necessary for an email verification."},"parameters": [{@@ -97,13 +343,63 @@"description": "Your personal Reacher API key","required": true}- ]+ ],+ "x-stoplight": {+ "id": "9cw3vilj3q88h"+ },+ "deprecated": true},"parameters": []}},"components": {"schemas": {+ "CheckEmailRequest": {+ "title": "CheckEmailRequest",+ "x-stoplight": {+ "id": "834398a8ce480"+ },+ "type": "object",+ "description": "A request object to perform an email verification. The `to_email` field is required, all other fields are optional.",+ "required": ["to_email"],+ "properties": {+ "from_email": {+ "type": "string",+ "description": "In the SMTP connection, the FROM email address."+ },+ "to_email": {+ "type": "string",+ "description": "The email address to check."+ },+ "hello_name": {+ "type": "string",+ "description": "In the SMTP connection, the EHLO hostname."+ },+ "proxy": {+ "$ref": "#/components/schemas/CheckEmailInputProxy"+ },+ "smtp_port": {+ "type": "number",+ "description": "SMTP port to use for email validation. Defaults to 25, but 465, 587, and 2525 are sometimes also used."+ },+ "gmail_verif_method": {+ "$ref": "#/components/schemas/GmailVerifMethod"+ },+ "hotmailb2b_verif_method": {+ "$ref": "#/components/schemas/HotmailB2BVerifMethod"+ },+ "hotmailb2c_verif_method": {+ "$ref": "#/components/schemas/HotmailB2CVerifMethod"+ },+ "yahoo_verif_method": {+ "$ref": "#/components/schemas/YahooVerifMethod"+ },+ "check_gravatar": {+ "type": "boolean",+ "description": "Whether to check if a Gravatar image exists for the given email."+ }+ }+ },"CheckEmailOutput": {"title": "CheckEmailOutput","type": "object",@@ -139,12 +435,20 @@}}},- "description": "The verification result of an email.",+ "description": "The result of the email verification process.",+ "required": [+ "input",+ "is_reachable",+ "misc",+ "mx",+ "smtp",+ "syntax"+ ],"properties": {"input": {"type": "string","format": "email",- "description": "The input email address."+ "description": "The email address that was verified."},"is_reachable": {"$ref": "#/components/schemas/Reachable"@@ -155,10 +459,10 @@"$ref": "#/components/schemas/MiscDetails"},{- "$ref": "#/components/schemas/Error"+ "$ref": "#/components/schemas/CoreError"}],- "description": "Miscellaneous information about the email account."+ "description": "Additional information about the email account."},"mx": {"oneOf": [@@ -166,10 +470,10 @@"$ref": "#/components/schemas/MxDetails"},{- "$ref": "#/components/schemas/Error"+ "$ref": "#/components/schemas/CoreError"}],- "description": "Information gathered from querying the MX records of the mail server."+ "description": "Details obtained from querying the mail server's MX records."},"smtp": {"oneOf": [@@ -177,10 +481,10 @@"$ref": "#/components/schemas/SmtpDetails"},{- "$ref": "#/components/schemas/Error"+ "$ref": "#/components/schemas/CoreError"}],- "description": "Verifications performed by connecting to the mail server via SMTP."+ "description": "Results from connecting to the mail server via SMTP."},"syntax": {"$ref": "#/components/schemas/SyntaxDetails"@@ -188,48 +492,30 @@"debug": {"$ref": "#/components/schemas/DebugDetails"}- },- "required": [- "input",- "is_reachable",- "misc",- "mx",- "smtp",- "syntax"- ]+ }},- "Error": {- "title": "Error",- "type": "object",- "description": "Object describing an error happening during the misc, MX, or SMTP verifications.",- "properties": {- "type": {- "type": "string",- "description": "An error type."- },- "message": {- "type": "string",- "description": "A human-readable description of the error."- }- },- "required": ["type", "message"]+ "Reachable": {+ "type": "string",+ "title": "Reachable",+ "enum": ["invalid", "unknown", "safe", "risky"],+ "description": "An enumeration describing the confidence level that the recipient address is valid: `safe`, `risky`, `invalid`, or `unknown`. Refer to our FAQ for detailed definitions: https://docs.reacher.email/getting-started/is-reachable."},"MiscDetails": {"title": "MiscDetails","type": "object",- "description": "Miscellaneous information about the email account.",+ "description": "Additional information about the email account.","properties": {"is_disposable": {"type": "boolean",- "description": "Is the address provided by a known disposable email address provider?"+ "description": "Indicates if the email address is from a known disposable email provider."},"is_role_account": {"type": "boolean",- "description": "Is this email a role-based account?"+ "description": "Indicates if the email address is a role-based account."},"gravatar_url": {"type": "string",- "description": "URL to the email's Gravatar profile picture. It is only populated if check_gravatar is set to true in the request, and if the email has an associated Gravatar."+ "description": "URL to the Gravatar profile picture associated with the email, if available and requested."}},"required": ["is_disposable", "is_role_account"]@@ -240,43 +526,43 @@"properties": {"accepts_mail": {"type": "boolean",- "description": "Does the server accept mails?"+ "description": "Indicates if the mail server accepts emails."},"records": {"type": "array",- "description": "The list of FQDN (Fully Qualified Domain Names) of the mail server.",+ "description": "List of Fully Qualified Domain Names (FQDN) of the mail server.","items": {"type": "string"}}},"required": ["accepts_mail", "records"],- "description": "Object holding the MX details of the mail server."+ "description": "Details about the mail server's MX records."},"SmtpDetails": {"title": "SmtpDetails","type": "object",- "description": "Verifications performed by connecting to the mail server via SMTP.",+ "description": "Results from SMTP connection attempts to the mail server.","properties": {"can_connect_smtp": {"type": "boolean",- "description": "Can the mail exchanger of the email address domain be contacted successfully?"+ "description": "Indicates if the mail exchanger can be contacted successfully."},"has_full_inbox": {"type": "boolean",- "description": "Is the inbox of this mailbox full?"+ "description": "Indicates if the mailbox is full."},"is_catch_all": {"type": "boolean",- "description": "Is this email address a catch-all address?"+ "description": "Indicates if the email address is a catch-all address."},"is_deliverable": {"type": "boolean",- "description": "Is an email sent to this address deliverable?"+ "description": "Indicates if an email sent to this address is deliverable."},"is_disabled": {"type": "boolean",- "description": "Has this email address been disabled by the email provider?"+ "description": "Indicates if the email address has been disabled by the provider."}},"required": [@@ -290,43 +576,65 @@"SyntaxDetails": {"title": "SyntaxDetails","type": "object",- "description": "Syntax validation of an email address.",+ "description": "Validation of the email address syntax.","properties": {"domain": {"type": "string",- "description": "The domain name of the email, i.e. the part after the \"@\" symbol."+ "description": "The domain part of the email address."},"is_valid_syntax": {"type": "boolean",- "description": "Is the address syntactically valid?"+ "description": "Indicates if the email address syntax is valid."},"username": {"type": "string",- "description": "The username of the email, i.e. the part before the \"@\" symbol."+ "description": "The username part of the email address."}},"required": ["domain", "is_valid_syntax", "username"]},- "Reachable": {- "type": "string",- "title": "Reachable",- "enum": ["invalid", "unknown", "safe", "risky"],- "description": "An enum to describe how confident we are that the recipient address is real: `safe`, `risky`, `invalid` and `unknown`. Check our docs to know the meanings of the 4 possibilities: https://docs.reacher.email/getting-started/publish-your-docs."+ "CoreError": {+ "title": "CoreError",+ "x-stoplight": {+ "id": "a872ead6474cd"+ },+ "type": "object",+ "description": "Details of an error encountered during the verification process.",+ "properties": {+ "type": {+ "type": "string",+ "description": "The type of error."+ },+ "message": {+ "type": "string",+ "description": "A human-readable description of the error."+ }+ },+ "required": ["type", "message"]},"YahooVerifMethod": {"type": "string","title": "YahooVerifMethod","enum": ["Api", "Headless", "Smtp"],- "description": "An enum to describe how we verify Yahoo emails."+ "description": "Enumeration describing the method used to verify Yahoo emails."},- "HotmailVerifMethod": {+ "HotmailB2BVerifMethod": {"type": "string","x-stoplight": {"id": "ntdugsleyotut"},- "title": "HotmailVerifMethod",- "enum": ["Api", "Headless", "Smtp"],- "description": "An enum to describe how we verify Hotmail emails."+ "title": "HotmailB2BVerifMethod",+ "enum": ["Smtp"],+ "description": "Enumeration describing the method used to verify Hotmail B2B emails."+ },+ "HotmailB2CVerifMethod": {+ "type": "string",+ "x-stoplight": {+ "id": "cuc5bj6ra2t0i"+ },+ "title": "HotmailB2CVerifMethod",+ "enum": ["Smtp", "Headless", "Api"],+ "description": "Enumeration describing the method used to verify Hotmail B2C emails."},"GmailVerifMethod": {"type": "string",@@ -335,68 +643,9 @@},"title": "GmailVerifMethod","enum": ["Api", "Smtp"],- "description": "An enum to describe how we verify Gmail emails.",+ "description": "Enumeration describing the method used to verify Gmail emails.","x-internal": false},- "CheckEmailInput": {- "title": "CheckEmailInput",- "type": "object",- "description": "Input containing all parameters necessary for an email verification, as well as some config on how to perform the verification.",- "properties": {- "from_email": {- "type": "string",- "description": "In the SMTP connection, the FROM email address."- },- "to_email": {- "type": "string",- "description": "The email address to check."- },- "hello_name": {- "type": "string",- "description": "In the SMTP connection, the EHLO hostname."- },- "proxy": {- "$ref": "#/components/schemas/CheckEmailInputProxy"- },- "smtp_port": {- "type": "number",- "description": "SMTP port to use for email validation. Generally, ports 25, 465, 587 and 2525 are used."- },- "yahoo_verif_method": {- "$ref": "#/components/schemas/YahooVerifMethod"- },- "gmail_verif_method": {- "$ref": "#/components/schemas/GmailVerifMethod"- },- "hotmail_verif_method": {- "$ref": "#/components/schemas/HotmailVerifMethod"- },- "check_gravatar": {- "type": "boolean",- "description": "Whether to check if a gravatar image is existing for the given email."- },- "retries": {- "type": "number",- "default": 2,- "description": "Number of retries of SMTP connections to do."- },- "smtp_security": {- "type": "string",- "example": "Opportunistic",- "enum": [- "None",- "Opportunistic",- "Required",- "Wrapper"- ],- "description": "How to apply TLS to a SMTP client connection."- },- "smtp_timeout": {- "$ref": "#/components/schemas/Duration"- }- },- "required": ["to_email"]- },"CheckEmailInputProxy": {"title": "CheckEmailInputProxy","type": "object",@@ -411,23 +660,23 @@"properties": {"host": {"type": "string",- "description": "The proxy host."+ "description": "The proxy host address."},"port": {"type": "integer",- "description": "The proxy port."+ "description": "The proxy port number."},"username": {"type": "string",- "description": "Username to pass to proxy authentication."+ "description": "Username for proxy authentication."},"password": {"type": "string",- "description": "Password to pass to proxy authentication."+ "description": "Password for proxy authentication."}},"required": ["host", "port"],- "description": "Proxy information for email verification."+ "description": "Proxy configuration for email verification."},"DebugDetails": {"title": "DebugDetails",@@ -441,14 +690,14 @@"x-stoplight": {"id": "60i65k60m8e8d"},- "description": "The time when the email verification started."+ "description": "The timestamp when the email verification started."},"end_time": {"type": "string","x-stoplight": {"id": "zw4ccbvwsoh6q"},- "description": "The time when the email verification ended."+ "description": "The timestamp when the email verification ended."},"duration": {"$ref": "#/components/schemas/Duration"@@ -458,7 +707,7 @@"x-stoplight": {"id": "2jrbdecvqh4t5"},- "description": "The name of the server that performed the email verification."+ "description": "The name of the server that performed the verification."},"smtp": {"$ref": "#/components/schemas/DebugDetailsSmtp"@@ -478,15 +727,15 @@"id": "bg9y0iez4zati"},"type": "object",- "description": "An object representing a duration (seconds + nanoseconds).",+ "description": "An object representing a duration in seconds and nanoseconds.","properties": {"secs": {"type": "number",- "description": "Seconds"+ "description": "Duration in seconds."},"nanos": {"type": "number",- "description": "Nanoseconds"+ "description": "Duration in nanoseconds."}},"required": ["secs", "nanos"]@@ -502,7 +751,7 @@"$ref": "#/components/schemas/VerifMethod"}},- "description": "Smtp details used for debugging, such as which method is used."+ "description": "SMTP details used for debugging, including the verification method."},"VerifMethod": {"title": "VerifMethod",@@ -510,31 +759,54 @@"id": "9xw9e1jwti230"},"type": "object",+ "description": "The method used for email verification.",+ "required": ["type"],"properties": {"type": {"x-stoplight": {"id": "4ogsz639tcdb6"},"enum": ["Smtp", "Headless", "Api", "Skipped"],- "description": "The method used to perform the email verification"- },- "host": {+ "description": "The method used for the email verification."+ }+ }+ },+ "TaskWebhook": {+ "title": "TaskWebhook",+ "x-stoplight": {+ "id": "6053d3ngu2hfn"+ },+ "type": "object",+ "description": "Optional webhook configuration for sending email verification results during bulk verification.",+ "properties": {+ "on_each_email": {+ "$ref": "#/components/schemas/Webhook"+ }+ }+ },+ "Webhook": {+ "title": "Webhook",+ "x-stoplight": {+ "id": "p9emghvcb92fj"+ },+ "type": "object",+ "description": "Configuration for a webhook to receive email verification results. The method will be POST, and the body will contain the email verification response.",+ "required": ["url"],+ "properties": {+ "url": {"type": "string","x-stoplight": {- "id": "lxbxckircn0sk"+ "id": "iraaa1ism4bzi"},- "description": "If `type` is `SmtpConnection`, the hostname that Reacher connected to."+ "description": "The URL to send the email verification results to."},- "port": {- "type": "number",+ "extra": {+ "type": "object","x-stoplight": {- "id": "xqfdjyoiodq23"- },- "description": "If `type` is `SmtpConnection`, the port that Reacher connected to."+ "id": "f20boz81d2fei"+ }}- },- "required": ["type"],- "description": "The verification method used for the email."+ }}},"securitySchemes": {@@ -544,6 +816,12 @@"in": "header","description": "A Reacher API key is required for all requests. Sign up on https://reacher.email to get your personal API key."}+ },+ "requestBodies": {}+ },+ "security": [+ {+ "Authorization": []}- }+ ]}diff --git a/backend/src/config.rs b/backend/src/config.rsindex f64e9ee3..30d4537f 100644--- a/backend/src/config.rs+++ b/backend/src/config.rs@@ -1,9 +1,41 @@+// 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/>.++use crate::create_db;+#[cfg(feature = "worker")]+use crate::worker::check_email::TaskWebhook;+#[cfg(feature = "worker")]+use crate::worker::setup_rabbit_mq;+use anyhow::bail;use check_if_email_exists::config::ReacherConfig;-use check_if_email_exists::SentryConfig;+use check_if_email_exists::{+ CheckEmailInputProxy, GmailVerifMethod, HotmailB2BVerifMethod, HotmailB2CVerifMethod,+ SentryConfig, YahooVerifMethod,+};use config::Config;+#[cfg(feature = "worker")]+use lapin::Channel;+use serde::de::{self, Deserializer, Visitor};use serde::Deserialize;+use sqlx::PgPool;+#[cfg(feature = "worker")]+use std::sync::Arc;+use std::{env, fmt};-#[derive(Debug, Deserialize)]+#[derive(Debug, Default, Deserialize)]pub struct BackendConfig {/// Name of the backend.pub backend_name: String,@@ -12,6 +44,10 @@ pub struct BackendConfig {pub from_email: String,pub hello_name: String,pub webdriver_addr: String,+ pub proxy: Option<CheckEmailInputProxy>,++ /// Verification method configuration.+ pub verif_method: VerifMethodConfig,/** Backend-specific config*//// Backend host@@ -20,9 +56,22 @@ pub struct BackendConfig {pub http_port: u16,/// Shared secret between a trusted client and the backend.pub header_secret: Option<String>,- pub throttle: ThrottleConfig,- pub webhook: Option<WebhookConfig>,++ /// Worker configuration, only present if the backend is a worker.+ pub worker: WorkerConfig,++ /// Sentry configuration to report errors.pub sentry: Option<SentryConfig>,++ // Internal fields, not part of the configuration.+ #[serde(skip)]+ pg_pool: Option<PgPool>,+ #[cfg(feature = "worker")]+ #[serde(skip)]+ check_email_channel: Option<Arc<Channel>>,+ #[cfg(feature = "worker")]+ #[serde(skip)]+ preprocess_channel: Option<Arc<Channel>>,}impl BackendConfig {@@ -33,6 +82,269 @@ impl BackendConfig {webdriver_addr: self.webdriver_addr.clone(),}}++ /// Get the worker configuration.+ ///+ /// # Panics+ ///+ /// Panics if the worker configuration is missing.+ pub fn must_worker_config(&self) -> Result<MustWorkerConfig, anyhow::Error> {+ match (+ self.worker.enable,+ &self.worker.throttle,+ &self.worker.rabbitmq,+ &self.worker.postgres,+ &self.pg_pool,+ #[cfg(feature = "worker")]+ &self.check_email_channel,+ #[cfg(feature = "worker")]+ &self.preprocess_channel,+ ) {+ #[cfg(feature = "worker")]+ (+ true,+ Some(throttle),+ Some(rabbitmq),+ Some(postgres),+ Some(pg_pool),+ Some(check_email_channel),+ Some(preprocess_channel),+ ) => Ok(MustWorkerConfig {+ pg_pool: pg_pool.clone(),+ #[cfg(feature = "worker")]+ check_email_channel: check_email_channel.clone(),+ #[cfg(feature = "worker")]+ preprocess_channel: preprocess_channel.clone(),+ throttle: throttle.clone(),+ rabbitmq: rabbitmq.clone(),+ #[cfg(feature = "worker")]+ webhook: self.worker.webhook.clone(),+ postgres: postgres.clone(),+ }),+ #[cfg(feature = "worker")]+ (true, _, _, _, _, _, _) => bail!("Worker configuration is missing"),+ _ => bail!("Calling must_worker_config on a non-worker backend"),+ }+ }++ pub fn get_pg_pool(&self) -> Option<PgPool> {+ self.pg_pool.clone()+ }++ #[cfg(feature = "worker")]+ pub fn get_check_email_channel(&self) -> Option<Arc<Channel>> {+ self.check_email_channel.clone()+ }++ #[cfg(feature = "worker")]+ pub fn get_preprocess_channel(&self) -> Option<Arc<Channel>> {+ self.preprocess_channel.clone()+ }+}++#[derive(Debug, Default, Deserialize, Clone)]+pub struct VerifMethodConfig {+ /// Verification method for Gmail emails.+ pub gmail: GmailVerifMethod,+ /// Verification method for Hotmail B2B emails.+ pub hotmailb2b: HotmailB2BVerifMethod,+ /// Verification method for Hotmail B2C emails.+ pub hotmailb2c: HotmailB2CVerifMethod,+ /// Verification method for Yahoo emails.+ pub yahoo: YahooVerifMethod,+}++#[derive(Debug, Default, Deserialize, Clone)]+pub struct WorkerConfig {+ pub enable: bool,++ /// Throttle configuration for the worker.+ pub throttle: Option<ThrottleConfig>,+ pub rabbitmq: Option<RabbitMQConfig>,+ /// Optional webhook configuration to send email verification results.+ #[cfg(feature = "worker")]+ pub webhook: Option<TaskWebhook>,+ /// Postgres database configuration to store email verification+ /// results.+ pub postgres: Option<PostgresConfig>,+}++/// Worker configuration that must be present if worker.enable is true. Used as+/// a domain type to ensure that the worker configuration is present.+#[derive(Debug, Clone)]+pub struct MustWorkerConfig {+ pub pg_pool: PgPool,+ #[cfg(feature = "worker")]+ pub check_email_channel: Arc<Channel>,+ #[cfg(feature = "worker")]+ pub preprocess_channel: Arc<Channel>,++ pub throttle: ThrottleConfig,+ pub rabbitmq: RabbitMQConfig,+ #[cfg(feature = "worker")]+ pub webhook: Option<TaskWebhook>,+ pub postgres: PostgresConfig,+}++#[derive(Debug, Clone)]+pub enum RabbitMQQueues {+ All,+ Only(Vec<Queue>),+}++/// Deserialize RabbitMQQueues from a string or a list of strings.+/// If the value is "all", then we return RabbitMQQueues::All.+/// If the value is a list of strings, then we return RabbitMQQueues::Only.+impl<'de> Deserialize<'de> for RabbitMQQueues {+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>+ where+ D: Deserializer<'de>,+ {+ struct RabbitMQQueuesVisitor;++ impl<'de> Visitor<'de> for RabbitMQQueuesVisitor {+ type Value = RabbitMQQueues;++ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {+ formatter.write_str("a string 'all' or a list of queue strings")+ }++ fn visit_str<E>(self, value: &str) -> Result<RabbitMQQueues, E>+ where+ E: de::Error,+ {+ if value == "all" {+ Ok(RabbitMQQueues::All)+ } else {+ Err(de::Error::unknown_variant(value, &["all"]))+ }+ }++ fn visit_seq<A>(self, mut seq: A) -> Result<RabbitMQQueues, A::Error>+ where+ A: serde::de::SeqAccess<'de>,+ {+ let mut queues = Vec::new();+ while let Some(value) = seq.next_element()? {+ queues.push(value);+ }+ Ok(RabbitMQQueues::Only(queues))+ }+ }++ deserializer.deserialize_any(RabbitMQQueuesVisitor)+ }+}++impl RabbitMQQueues {+ pub fn to_queues(&self) -> Vec<Queue> {+ match self {+ RabbitMQQueues::All => vec![+ Queue::Gmail,+ Queue::HotmailB2B,+ Queue::HotmailB2C,+ Queue::Yahoo,+ Queue::EverythingElse,+ ],+ RabbitMQQueues::Only(queues) => queues.clone(),+ }+ }+}++#[derive(Debug, Deserialize, Clone)]+pub struct RabbitMQConfig {+ pub url: String,+ /// Queues to consume emails from. By default the worker consumes from all+ /// queues.+ ///+ /// If you wish to consume from only a subset of queues, you can uncomment+ /// the line `queues = "all"`, and then specify the queues you want to+ /// consume from.+ ///+ /// Below is the exhaustive list of queue names that the worker can consume from:+ /// - "check.gmail": subcribe exclusively to Gmail emails.+ /// - "check.hotmailb2b": subcribe exclusively to Hotmail B2B emails.+ /// - "check.hotmailb2c": subcribe exclusively to Hotmail B2C emails.+ /// - "check.yahoo": subcribe exclusively to Yahoo emails.+ /// - "check.everything_else": subcribe to all emails that are not Gmail, Yahoo, or Hotmail.+ ///+ /// queues = ["check.gmail", "check.hotmailb2b", "check.hotmailb2c", "check.yahoo", "check.everything_else"]+ pub queues: RabbitMQQueues,+ /// Total number of concurrent messages that the worker can process, across+ /// all queues.+ pub concurrency: u16,+}++/// Queue names that the worker can consume from. Each email is routed to a+/// one and only one queue, based on the email provider. A single worker can+/// consume from multiple queues.+#[derive(Debug, Clone)]+pub enum Queue {+ Gmail,+ HotmailB2B,+ HotmailB2C,+ Yahoo,+ EverythingElse,+}++impl fmt::Display for Queue {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Queue::Gmail => write!(f, "check.gmail"),+ Queue::HotmailB2B => write!(f, "check.hotmailb2b"),+ Queue::HotmailB2C => write!(f, "check.hotmailb2c"),+ Queue::Yahoo => write!(f, "check.yahoo"),+ Queue::EverythingElse => write!(f, "check.everything_else"),+ }+ }+}++// Implement Deserialize for the Queue enum+impl<'de> Deserialize<'de> for Queue {+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>+ where+ D: Deserializer<'de>,+ {+ struct QueueVisitor;++ impl<'de> Visitor<'de> for QueueVisitor {+ type Value = Queue;++ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {+ formatter.write_str("a valid queue string")+ }++ fn visit_str<E>(self, value: &str) -> Result<Queue, E>+ where+ E: de::Error,+ {+ match value {+ "check.gmail" => Ok(Queue::Gmail),+ "check.hotmailb2b" => Ok(Queue::HotmailB2B),+ "check.hotmailb2c" => Ok(Queue::HotmailB2C),+ "check.yahoo" => Ok(Queue::Yahoo),+ "check.everything_else" => Ok(Queue::EverythingElse),+ _ => Err(de::Error::unknown_variant(+ value,+ &[+ "check.gmail",+ "check.hotmailb2b",+ "check.hotmailb2c",+ "check.yahoo",+ "check.everything_else",+ ],+ )),+ }+ }+ }++ deserializer.deserialize_str(QueueVisitor)+ }+}++#[derive(Debug, Deserialize, Clone)]+pub struct PostgresConfig {+ pub db_url: String,}#[derive(Debug, Deserialize, Clone)]@@ -55,20 +367,61 @@ impl ThrottleConfig {}}-#[derive(Debug, Deserialize, Clone)]-pub struct WebhookConfig {- pub url: String,-}-/// Load the worker configuration from the worker_config.toml file and from the/// environment.-pub fn load_config() -> Result<BackendConfig, config::ConfigError> {+pub async fn load_config() -> Result<BackendConfig, anyhow::Error> {let cfg = Config::builder().add_source(config::File::with_name("backend_config"))- .add_source(config::Environment::with_prefix("RCH"))+ .add_source(config::Environment::with_prefix("RCH").separator("__")).build()?;- let cfg = cfg.try_deserialize::<BackendConfig>()?;+ let mut cfg = cfg.try_deserialize::<BackendConfig>()?;++ let pg_pool = if cfg.worker.enable {+ let db_url = cfg+ .worker+ .postgres+ .as_ref()+ .map(|c| &c.db_url)+ .ok_or_else(|| {+ anyhow::anyhow!("Worker configuration is missing the postgres configuration")+ })?;+ Some(create_db(db_url).await?)+ } else if let Ok(db_url) = env::var("DATABASE_URL") {+ // For legacy reasons, we also support the DATABASE_URL environment variable:+ Some(create_db(&db_url).await?)+ } else {+ None+ };+ cfg.pg_pool = pg_pool;++ #[cfg(feature = "worker")]+ {+ let (check_email_channel, preprocess_channel) = if cfg.worker.enable {+ let rabbitmq_config = cfg.worker.rabbitmq.as_ref().ok_or_else(|| {+ anyhow::anyhow!("Worker configuration is missing the rabbitmq configuration")+ })?;+ let (check_email_channel, preprocess_channel) =+ setup_rabbit_mq(&cfg.backend_name, rabbitmq_config).await?;+ (+ Some(Arc::new(check_email_channel)),+ Some(Arc::new(preprocess_channel)),+ )+ } else {+ (None, None)+ };+ cfg.check_email_channel = check_email_channel;+ cfg.preprocess_channel = preprocess_channel;+ }Ok(cfg)}++#[cfg(test)]+mod test {+ #[tokio::test]+ async fn test_load_config() {+ let cfg = super::load_config().await;+ assert!(cfg.is_ok());+ }+}diff --git a/backend/src/db.rs b/backend/src/db.rsnew file mode 100644index 00000000..c260675b--- /dev/null+++ b/backend/src/db.rs@@ -0,0 +1,39 @@+// 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/>.++use anyhow::Context;+use check_if_email_exists::LOG_TARGET;+use sqlx::{postgres::PgPoolOptions, PgPool};++use tracing::{debug, info};++/// Create a DB pool.+pub async fn create_db(db_url: &str) -> Result<PgPool, anyhow::Error> {+ debug!(target: LOG_TARGET, "Connecting to DB: {}", db_url);+ // 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()+ .connect(db_url)+ .await+ .with_context(|| format!("Connecting to postgres DB {db_url}"))?;++ sqlx::migrate!("./migrations").run(&pool).await?;++ info!(target: LOG_TARGET, table="v1_task_result", "Connected to DB, Reacher will write verification results to DB");++ Ok(pool)+}diff --git a/backend/src/http/error.rs b/backend/src/http/error.rsnew file mode 100644index 00000000..207e7dae--- /dev/null+++ b/backend/src/http/error.rs@@ -0,0 +1,120 @@+// 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/>.++use check_if_email_exists::{CheckEmailInputBuilderError, LOG_TARGET};+use serde::ser::SerializeStruct;+use serde::Serialize;+use std::fmt;+use std::fmt::Debug;+use tracing::error;+use warp::{http::StatusCode, reject};++/// Trait combining Display and Debug.+pub trait DisplayDebug: fmt::Display + Debug + Sync + Send {}++impl<T: fmt::Display + Debug + Sync + Send> DisplayDebug for T {}++/// Struct describing an error response.+#[derive(Debug)]+pub struct ReacherResponseError {+ pub code: StatusCode,+ pub error: Box<dyn DisplayDebug>,+}++impl reject::Reject for ReacherResponseError {}++impl Serialize for ReacherResponseError {+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>+ where+ S: serde::Serializer,+ {+ let mut state = serializer.serialize_struct("ReacherResponseError", 1)?;+ state.serialize_field("error", &self.error.to_string())?;+ state.end()+ }+}++impl fmt::Display for ReacherResponseError {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "{}", self.error)+ }+}++impl ReacherResponseError {+ pub fn new<T: DisplayDebug + 'static>(code: StatusCode, error: T) -> Self {+ Self {+ code,+ error: Box::new(error),+ }+ }+}++impl From<CheckEmailInputBuilderError> for ReacherResponseError {+ fn from(e: CheckEmailInputBuilderError) -> Self {+ Self {+ code: StatusCode::BAD_REQUEST,+ error: Box::new(e),+ }+ }+}++impl From<serde_json::Error> for ReacherResponseError {+ fn from(e: serde_json::Error) -> Self {+ ReacherResponseError::new(StatusCode::INTERNAL_SERVER_ERROR, e)+ }+}++#[cfg(feature = "worker")]+impl From<lapin::Error> for ReacherResponseError {+ fn from(e: lapin::Error) -> Self {+ ReacherResponseError::new(StatusCode::INTERNAL_SERVER_ERROR, e)+ }+}++impl From<sqlx::Error> for ReacherResponseError {+ fn from(e: sqlx::Error) -> Self {+ ReacherResponseError::new(StatusCode::INTERNAL_SERVER_ERROR, e)+ }+}++impl From<csv::Error> for ReacherResponseError {+ fn from(e: csv::Error) -> Self {+ ReacherResponseError::new(StatusCode::INTERNAL_SERVER_ERROR, e)+ }+}++impl From<csv::IntoInnerError<csv::Writer<Vec<u8>>>> for ReacherResponseError {+ fn from(e: csv::IntoInnerError<csv::Writer<Vec<u8>>>) -> Self {+ ReacherResponseError::new(StatusCode::INTERNAL_SERVER_ERROR, e)+ }+}++impl From<warp::http::status::InvalidStatusCode> for ReacherResponseError {+ fn from(e: warp::http::status::InvalidStatusCode) -> Self {+ ReacherResponseError::new(StatusCode::INTERNAL_SERVER_ERROR, e)+ }+}++/// This function receives a `Rejection` and tries to return a custom value,+/// otherwise simply passes the rejection along.+pub async fn handle_rejection(err: warp::Rejection) -> Result<impl warp::Reply, warp::Rejection> {+ if let Some(err) = err.find::<ReacherResponseError>() {+ error!(target: LOG_TARGET, code=?err.code, message=?err.to_string(), "Request rejected");+ Ok((warp::reply::with_status(warp::reply::json(err), err.code),))+ } else {+ Err(err)+ }+}diff --git a/backend/src/http/mod.rs b/backend/src/http/mod.rsindex 77cdfd36..fdd6a20f 100644--- a/backend/src/http/mod.rs+++ b/backend/src/http/mod.rs@@ -14,38 +14,55 @@// 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 error;mod v0;+#[cfg(feature = "worker")]+mod v1;mod version;+use crate::config::BackendConfig;use check_if_email_exists::LOG_TARGET;-use serde::Serialize;-use sqlx::postgres::PgPoolOptions;-use sqlx::{Pool, Postgres};+use error::handle_rejection;+pub use error::ReacherResponseError;+use sqlx::PgPool;use sqlxmq::JobRunnerHandle;use std::env;use std::net::IpAddr;use std::sync::Arc;use tracing::info;-use warp::Filter;-use warp::{http, reject};--use crate::config::BackendConfig;-pub use v0::check_email::post::CheckEmailRequest;+use warp::http::StatusCode;+use warp::Filter;-/// Creates the routes for the HTTP server.-/// Making it public so that it can be used in tests/check_email.rs.pub fn create_routes(config: Arc<BackendConfig>,- o: Option<Pool<Postgres>>,) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone {- version::get::get_version()- .or(v0::check_email::post::post_check_email(config.clone()))+ let pg_pool = config.get_pg_pool();+ let t = version::get::get_version()+ .or(v0::check_email::post::post_check_email(Arc::clone(&config)))// The 3 following routes will 404 if o is None.- .or(v0::bulk::post::create_bulk_job(config, o.clone()))- .or(v0::bulk::get::get_bulk_job_status(o.clone()))- .or(v0::bulk::results::get_bulk_job_result(o))- .recover(handle_rejection)+ .or(v0::bulk::post::create_bulk_job(+ Arc::clone(&config),+ pg_pool.clone(),+ ))+ .or(v0::bulk::get::get_bulk_job_status(pg_pool.clone()))+ .or(v0::bulk::results::get_bulk_job_result(pg_pool));++ #[cfg(feature = "worker")]+ {+ t.or(v1::check_email::post::v1_check_email(Arc::clone(&config)))+ .or(v1::bulk::post::v1_create_bulk_job(Arc::clone(&config)))+ .or(v1::bulk::get_progress::v1_get_bulk_job_progress(+ Arc::clone(&config),+ ))+ .or(v1::bulk::get_results::v1_get_bulk_job_results(config))+ .recover(handle_rejection)+ }++ #[cfg(not(feature = "worker"))]+ {+ t.recover(handle_rejection)+ }}/// Runs the Warp server.@@ -57,7 +74,7 @@ pub fn create_routes(/// keep it alive.pub async fn run_warp_server(config: Arc<BackendConfig>,-) -> Result<Option<JobRunnerHandle>, Box<dyn std::error::Error + Send + Sync>> {+) -> Result<Option<JobRunnerHandle>, anyhow::Error> {let host = config.http_host.parse::<IpAddr>()@@ -72,18 +89,20 @@ pub async fn run_warp_server(}).unwrap_or(config.http_port);- // Run bulk job listener.+ let routes = create_routes(Arc::clone(&config));++ // Run v0 bulk job listener.let is_bulk_enabled = env::var("RCH_ENABLE_BULK").unwrap_or_else(|_| "0".into()) == "1";- let (db, runner) = if is_bulk_enabled {- let pool = create_db().await?;- let runner = v0::bulk::create_job_registry(&pool).await?;- (Some(pool), Some(runner))+ let runner = if is_bulk_enabled {+ let pg_pool = config+ .get_pg_pool()+ .expect("DATABASE_URL is required when RCH_ENABLE_BULK is set");+ let runner = v0::bulk::create_job_registry(&pg_pool).await?;+ Some(runner)} else {- (None, None)+ None};- let routes = create_routes(config.clone(), db);-info!(target: LOG_TARGET, host=?host,port=?port, "Server is listening");warp::serve(routes).run((host, port)).await;@@ -91,18 +110,22 @@ pub async fn run_warp_server(Ok(runner)}-/// Create a DB pool for the deprecated /v0/bulk endpoints.-async fn create_db() -> Result<Pool<Postgres>, sqlx::Error> {- let pg_conn = env::var("DATABASE_URL").expect("Environment variable DATABASE_URL must be set");-- // 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().connect(pg_conn.as_str()).await?;-- sqlx::migrate!("./migrations").run(&pool).await?;-- Ok(pool)+/// Warp filter to add the database pool to the handler. If the pool is not+/// configured, it will return an error.+pub fn with_db(+ pg_pool: Option<PgPool>,+) -> impl Filter<Extract = (PgPool,), Error = warp::Rejection> + Clone {+ warp::any().and_then(move || {+ let pool = pg_pool.clone();+ async move {+ pool.ok_or_else(|| {+ warp::reject::custom(ReacherResponseError::new(+ StatusCode::SERVICE_UNAVAILABLE,+ "Please configure a database on Reacher before calling this endpoint",+ ))+ })+ }+ })}/// The header which holds the Reacher backend secret.@@ -123,30 +146,3 @@ pub fn check_header(config: Arc<BackendConfig>) -> warp::filters::BoxedFilter<()warp::any().boxed()}}--/// Warp filter that adds the BackendConfig to the handler.-pub fn with_config(- config: Arc<BackendConfig>,-) -> impl Filter<Extract = (Arc<BackendConfig>,), Error = std::convert::Infallible> + Clone {- warp::any().map(move || config.clone())-}--/// Struct describing an error response.-#[derive(Serialize, Debug)]-pub struct ReacherResponseError {- #[serde(skip)]- pub code: http::StatusCode,- pub message: String,-}--impl reject::Reject for ReacherResponseError {}--/// This function receives a `Rejection` and tries to return a custom value,-/// otherwise simply passes the rejection along.-pub async fn handle_rejection(err: warp::Rejection) -> Result<impl warp::Reply, warp::Rejection> {- if let Some(err) = err.find::<ReacherResponseError>() {- Ok((warp::reply::with_status(warp::reply::json(err), err.code),))- } else {- Err(err)- }-}diff --git a/backend/src/http/v0/check_email/post.rs b/backend/src/http/v0/check_email/post.rsindex 3eb3e16e..29a4e68e 100644--- a/backend/src/http/v0/check_email/post.rs+++ b/backend/src/http/v0/check_email/post.rs@@ -16,13 +16,15 @@//! This file implements the `POST /v0/check_email` endpoint.-use check_if_email_exists::{check_email, CheckEmailInput, CheckEmailInputProxy, LOG_TARGET};+use check_if_email_exists::{+ check_email, CheckEmailInput, CheckEmailInputProxy, GmailVerifMethod, LOG_TARGET,+};use serde::{Deserialize, Serialize};use std::sync::Arc;use warp::{http, Filter};use crate::config::BackendConfig;-use crate::http::{check_header, handle_rejection, with_config, ReacherResponseError};+use crate::http::{check_header, ReacherResponseError};/// The request body for the `POST /v0/check_email` endpoint.#[derive(Debug, Deserialize, Serialize)]@@ -30,6 +32,10 @@ pub struct CheckEmailRequest {pub to_email: String,pub from_email: Option<String>,pub hello_name: Option<String>,+ pub gmail_verif_method: Option<GmailVerifMethod>,+ pub hotmailb2b_verif_method: Option<String>,+ pub hotmailb2c_verif_method: Option<String>,+ pub yahoo_verif_method: Option<String>,pub proxy: Option<CheckEmailInputProxy>,}@@ -39,28 +45,36 @@ impl CheckEmailRequest {to_email: self.to_email.clone(),from_email: self.from_email.clone().unwrap_or(config.from_email.clone()),hello_name: self.hello_name.clone().unwrap_or(config.hello_name.clone()),- proxy: self.proxy.clone(),+ gmail_verif_method: config.verif_method.gmail,+ hotmailb2b_verif_method: config.verif_method.hotmailb2b,+ hotmailb2c_verif_method: config.verif_method.hotmailb2c,+ yahoo_verif_method: config.verif_method.yahoo,+ proxy: self+ .proxy+ .as_ref()+ .or_else(|| config.proxy.as_ref())+ .cloned(),..Default::default()}}}/// The main endpoint handler that implements the logic of this route.-async fn handler(+async fn http_handler(config: Arc<BackendConfig>,body: CheckEmailRequest,) -> Result<impl warp::Reply, warp::Rejection> {// The to_email field must be presentif body.to_email.is_empty() {- Err(warp::reject::custom(ReacherResponseError {- code: http::StatusCode::BAD_REQUEST,- message: "to_email field is required.".to_string(),- }))+ Err(+ ReacherResponseError::new(http::StatusCode::BAD_REQUEST, "to_email field is required.")+ .into(),+ )} else {// Run the future to check an email.Ok(warp::reply::json(&check_email(- &body.to_check_email_input(config.clone()),+ &body.to_check_email_input(Arc::clone(&config)),&config.get_reacher_config(),).await,@@ -74,14 +88,20 @@ pub fn post_check_email<'a>() -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone + 'a {warp::path!("v0" / "check_email").and(warp::post())- .and(check_header(config.clone()))+ .and(check_header(Arc::clone(&config))).and(with_config(config))// When accepting a body, we want a JSON body (and to reject huge// payloads)....and(warp::body::content_length_limit(1024 * 16)).and(warp::body::json())- .and_then(handler)+ .and_then(http_handler)// View access logs by setting `RUST_LOG=reacher`..with(warp::log(LOG_TARGET))- .recover(handle_rejection)+}++/// Warp filter that adds the BackendConfig to the handler.+fn with_config(+ config: Arc<BackendConfig>,+) -> impl Filter<Extract = (Arc<BackendConfig>,), Error = std::convert::Infallible> + Clone {+ warp::any().map(move || Arc::clone(&config))}diff --git a/backend/src/http/v1/bulk/get_progress.rs b/backend/src/http/v1/bulk/get_progress.rsnew file mode 100644index 00000000..a77ff973--- /dev/null+++ b/backend/src/http/v1/bulk/get_progress.rs@@ -0,0 +1,156 @@+// 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/>.++//! This file implements the `GET /bulk/{id}` endpoint.++use std::sync::Arc;++use check_if_email_exists::LOG_TARGET;+use serde::Serialize;+use sqlx::types::chrono::{DateTime, Utc};+use sqlx::PgPool;+use warp::http::StatusCode;+use warp::Filter;++use crate::config::BackendConfig;+use crate::http::{with_db, ReacherResponseError};++/// NOTE: Type conversions from postgres to rust types+/// are according to the table given by+/// [sqlx here](https://docs.rs/sqlx/latest/sqlx/postgres/types/index.html)+#[derive(Debug, Serialize, PartialEq, Eq)]+enum ValidStatus {+ Running,+ Completed,+}++/// Job record stores the information about a submitted job+///+/// `job_status` field is an update on read field. It's+/// status will be derived from counting number of+/// completed email verification tasks. It will be updated+/// with the most recent status of the job.+#[derive(sqlx::FromRow, Debug, Serialize)]+struct JobRecord {+ id: i32,+ created_at: DateTime<Utc>,+ total_records: i32,+}++/// Summary of a bulk verification job status+#[derive(Debug, Serialize)]+struct ResponseSummary {+ total_safe: i32,+ total_risky: i32,+ total_invalid: i32,+ total_unknown: i32,+}++/// Complete information about a bulk verification job+#[derive(Debug, Serialize)]+struct Response {+ job_id: i32,+ created_at: DateTime<Utc>,+ finished_at: Option<DateTime<Utc>>,+ total_records: i32,+ total_processed: i32,+ summary: ResponseSummary,+ job_status: ValidStatus,+}++async fn http_handler(job_id: i32, conn_pool: PgPool) -> Result<impl warp::Reply, warp::Rejection> {+ let job_rec = sqlx::query_as!(+ JobRecord,+ r#"+ SELECT id, created_at, total_records FROM v1_bulk_job+ WHERE id = $1+ LIMIT 1+ "#,+ job_id+ )+ .fetch_one(&conn_pool)+ .await+ .map_err(|e| ReacherResponseError::new(StatusCode::BAD_REQUEST, e))?;++ let agg_info = sqlx::query!(+ r#"+ SELECT+ COUNT(*) as total_processed,+ COUNT(CASE WHEN result ->> 'is_reachable' LIKE 'safe' THEN 1 END) as safe_count,+ COUNT(CASE WHEN result ->> 'is_reachable' LIKE 'risky' THEN 1 END) as risky_count,+ COUNT(CASE WHEN result ->> 'is_reachable' LIKE 'invalid' THEN 1 END) as invalid_count,+ COUNT(CASE WHEN result ->> 'is_reachable' LIKE 'unknown' THEN 1 END) as unknown_count,+ (SELECT created_at FROM v1_task_result WHERE job_id = $1 ORDER BY created_at DESC LIMIT 1) as finished_at+ FROM v1_task_result+ WHERE job_id = $1+ "#,+ job_id+ )+ .fetch_one(&conn_pool)+ .await+ .map_err(ReacherResponseError::from)?;++ let (job_status, finished_at) = if (agg_info+ .total_processed+ .expect("sql COUNT() returns an int. qed.") as i32)+ < job_rec.total_records+ {+ (ValidStatus::Running, None)+ } else {+ (+ ValidStatus::Completed,+ Some(+ agg_info+ .finished_at+ .expect("always at least one task in the job. qed."),+ ),+ )+ };++ Ok(warp::reply::json(&Response {+ job_id: job_rec.id,+ created_at: job_rec.created_at,+ finished_at,+ total_records: job_rec.total_records,+ total_processed: agg_info+ .total_processed+ .expect("sql COUNT returns an int. qed.") as i32,+ summary: ResponseSummary {+ total_safe: agg_info.safe_count.expect("sql COUNT returns an int. qed.") as i32,+ total_risky: agg_info+ .risky_count+ .expect("sql COUNT returns an int. qed.") as i32,+ total_invalid: agg_info+ .invalid_count+ .expect("sql COUNT returns an int. qed.") as i32,+ total_unknown: agg_info+ .unknown_count+ .expect("sql COUNT returns an int. qed.") as i32,+ },+ job_status,+ }))+}++pub fn v1_get_bulk_job_progress(+ config: Arc<BackendConfig>,+) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone {+ warp::path!("v1" / "bulk" / i32)+ .and(warp::get())+ .and(with_db(config.get_pg_pool()))+ .and_then(http_handler)+ // View access logs by setting `RUST_LOG=reacher`.+ .with(warp::log(LOG_TARGET))+}diff --git a/backend/src/http/v1/bulk/get_results/csv_helper.rs b/backend/src/http/v1/bulk/get_results/csv_helper.rsnew file mode 100644index 00000000..37a4ccf5--- /dev/null+++ b/backend/src/http/v1/bulk/get_results/csv_helper.rs@@ -0,0 +1,168 @@+// 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/>.++use serde::Serialize;+use std::convert::TryFrom;++/// Wrapper for serde json value to convert+/// into a csv response+#[derive(Debug)]+pub struct CsvWrapper(pub serde_json::Value);++/// Simplified output of `CheckEmailOutput` struct+/// for csv fields.+#[derive(Debug, Serialize)]+pub struct CsvResponse {+ input: String,+ is_reachable: String,+ #[serde(rename = "misc.is_disposable")]+ misc_is_disposable: bool,+ #[serde(rename = "misc.is_role_account")]+ misc_is_role_account: bool,+ #[serde(rename = "misc.gravatar_url")]+ misc_gravatar_url: Option<String>,+ #[serde(rename = "mx.accepts_mail")]+ mx_accepts_mail: bool,+ #[serde(rename = "smtp.can_connect")]+ smtp_can_connect: bool,+ #[serde(rename = "smtp.has_full_inbox")]+ smtp_has_full_inbox: bool,+ #[serde(rename = "smtp.is_catch_all")]+ smtp_is_catch_all: bool,+ #[serde(rename = "smtp.is_deliverable")]+ smtp_is_deliverable: bool,+ #[serde(rename = "smtp.is_disabled")]+ smtp_is_disabled: bool,+ #[serde(rename = "syntax.is_valid_syntax")]+ syntax_is_valid_syntax: bool,+ #[serde(rename = "syntax.domain")]+ syntax_domain: String,+ #[serde(rename = "syntax.username")]+ syntax_username: String,+ error: Option<String>,+}++impl TryFrom<CsvWrapper> for CsvResponse {+ type Error = &'static str;++ fn try_from(value: CsvWrapper) -> Result<Self, Self::Error> {+ let top_level = value+ .0+ .as_object()+ .ok_or("Failed to find top level object")?;++ let input = top_level+ .get("input")+ .and_then(|v| v.as_str())+ .ok_or("input should be a string")?+ .to_string();+ let is_reachable = top_level+ .get("is_reachable")+ .and_then(|v| v.as_str())+ .ok_or("is_reachable should be a string")?+ .to_string();++ let misc = top_level+ .get("misc")+ .and_then(|v| v.as_object())+ .ok_or("misc field should be an object")?;+ let misc_is_disposable = misc+ .get("is_disposable")+ .and_then(|v| v.as_bool())+ .ok_or("is_disposable should be a boolean")?;+ let misc_is_role_account = misc+ .get("is_role_account")+ .and_then(|v| v.as_bool())+ .ok_or("is_role_account should be a boolean")?;+ let misc_gravatar_url = misc+ .get("gravatar_url")+ .and_then(|v| v.as_str())+ .map(|s| s.to_string());++ let mx = top_level+ .get("mx")+ .and_then(|v| v.as_object())+ .ok_or("mx field should be an object")?;+ let mx_accepts_mail = mx+ .get("accepts_email")+ .and_then(|v| v.as_bool())+ .ok_or("accepts_email should be a boolean")?;++ let smtp = top_level+ .get("smtp")+ .and_then(|v| v.as_object())+ .ok_or("smtp field should be an object")?;+ let smtp_can_connect = smtp+ .get("can_connect_smtp")+ .and_then(|v| v.as_bool())+ .ok_or("can_connect_smtp should be a boolean")?;+ let smtp_has_full_inbox = smtp+ .get("has_full_inbox")+ .and_then(|v| v.as_bool())+ .ok_or("has_full_inbox should be a boolean")?;+ let smtp_is_catch_all = smtp+ .get("is_catch_all")+ .and_then(|v| v.as_bool())+ .ok_or("is_catch_all should be a boolean")?;+ let smtp_is_deliverable = smtp+ .get("is_deliverable")+ .and_then(|v| v.as_bool())+ .ok_or("is_deliverable should be a boolean")?;+ let smtp_is_disabled = smtp+ .get("is_disabled")+ .and_then(|v| v.as_bool())+ .ok_or("is_disabled should be a boolean")?;++ let syntax = top_level+ .get("syntax")+ .and_then(|v| v.as_object())+ .ok_or("syntax field should be an object")?;+ let syntax_is_valid_syntax = syntax+ .get("is_valid_syntax")+ .and_then(|v| v.as_bool())+ .ok_or("is_valid_syntax should be a boolean")?;+ let syntax_domain = syntax+ .get("domain")+ .and_then(|v| v.as_str())+ .ok_or("domain should be a string")?+ .to_string();+ let syntax_username = syntax+ .get("username")+ .and_then(|v| v.as_str())+ .ok_or("username should be a string")?+ .to_string();++ let error = top_level.get("error").map(|v| v.to_string());++ Ok(CsvResponse {+ input,+ is_reachable,+ misc_is_disposable,+ misc_is_role_account,+ misc_gravatar_url,+ mx_accepts_mail,+ smtp_can_connect,+ smtp_has_full_inbox,+ smtp_is_catch_all,+ smtp_is_deliverable,+ smtp_is_disabled,+ syntax_is_valid_syntax,+ syntax_domain,+ syntax_username,+ error,+ })+ }+}diff --git a/backend/src/http/v1/bulk/get_results/mod.rs b/backend/src/http/v1/bulk/get_results/mod.rsnew file mode 100644index 00000000..ad11eb40--- /dev/null+++ b/backend/src/http/v1/bulk/get_results/mod.rs@@ -0,0 +1,188 @@+// 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/>.++//! This file implements the /bulk/{id}/results endpoints.++use check_if_email_exists::LOG_TARGET;+use csv::WriterBuilder;+use serde::{Deserialize, Serialize};+use sqlx::{Executor, PgPool, Row};+use std::iter::Iterator;+use std::{convert::TryInto, sync::Arc};+use warp::http::StatusCode;+use warp::Filter;++use crate::config::BackendConfig;+use crate::http::{with_db, ReacherResponseError};+use csv_helper::{CsvResponse, CsvWrapper};++mod csv_helper;++/// Defines the download format, passed in as a query param.+#[derive(Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+enum ResponseFormat {+ Json,+ Csv,+}++// limit and offset are optional in the request+// If unspecified, offset will default to 0.+#[derive(Serialize, Deserialize)]+struct Request {+ format: Option<ResponseFormat>,+ limit: Option<u64>,+ offset: Option<u64>,+}++#[derive(Serialize, Deserialize)]+struct Response {+ results: Vec<serde_json::Value>,+}++async fn http_handler(+ job_id: i32,+ pg_pool: PgPool,+ req: Request,+) -> Result<impl warp::Reply, warp::Rejection> {+ // Throw an error if the job is still running.+ // Is there a way to combine these 2 requests in one?+ let total_records = sqlx::query!(+ r#"SELECT total_records FROM v1_bulk_job WHERE id = $1;"#,+ job_id+ )+ .fetch_one(&pg_pool)+ .await+ .map_err(ReacherResponseError::from)?+ .total_records;+ let total_processed = sqlx::query!(+ r#"SELECT COUNT(*) FROM v1_task_result WHERE job_id = $1;"#,+ job_id+ )+ .fetch_one(&pg_pool)+ .await+ .map_err(ReacherResponseError::from)?+ .count+ .unwrap_or(0);++ if total_processed < total_records as i64 {+ return Err(ReacherResponseError::new(+ StatusCode::BAD_REQUEST,+ format!("Job {} is still running, please try again later", job_id),+ )+ .into());+ }++ let format = req.format.unwrap_or(ResponseFormat::Json);+ match format {+ ResponseFormat::Json => {+ let data = job_result_json(job_id, req.limit, req.offset.unwrap_or(0), pg_pool).await?;++ let reply = serde_json::to_vec(&Response { results: data })+ .map_err(ReacherResponseError::from)?;++ Ok(warp::reply::with_header(+ reply,+ "Content-Type",+ "application/json",+ ))+ }+ ResponseFormat::Csv => {+ let data = job_result_csv(job_id, req.limit, req.offset.unwrap_or(0), pg_pool).await?;++ Ok(warp::reply::with_header(data, "Content-Type", "text/csv"))+ }+ }+}++async fn job_result_as_iter(+ job_id: i32,+ limit: Option<u64>,+ offset: u64,+ pg_pool: PgPool,+) -> Result<Box<dyn Iterator<Item = serde_json::Value>>, ReacherResponseError> {+ let query = sqlx::query!(+ r#"+ SELECT result FROM v1_task_result+ WHERE job_id = $1+ ORDER BY id+ LIMIT $2 OFFSET $3+ "#,+ job_id,+ limit.map(|l| l as i64),+ offset as i64+ );++ let rows = pg_pool+ .fetch_all(query)+ .await+ .map_err(ReacherResponseError::from)?;++ Ok(Box::new(+ rows.into_iter()+ .map(|row| row.get::<serde_json::Value, &str>("result")),+ ))+}++async fn job_result_json(+ job_id: i32,+ limit: Option<u64>,+ offset: u64,+ pg_pool: PgPool,+) -> Result<Vec<serde_json::Value>, warp::Rejection> {+ // For JSON responses, we don't want ot return more than 50 results at a+ // time, to avoid having a too big payload (unless client specifies a limit)++ Ok(+ job_result_as_iter(job_id, limit.or(Some(50)), offset, pg_pool)+ .await?+ .collect(),+ )+}++async fn job_result_csv(+ job_id: i32,+ limit: Option<u64>,+ offset: u64,+ pg_pool: PgPool,+) -> Result<Vec<u8>, warp::Rejection> {+ let rows = job_result_as_iter(job_id, limit, offset, pg_pool).await?;+ let mut wtr = WriterBuilder::new().has_headers(true).from_writer(vec![]);++ for json_value in rows {+ let result_csv: CsvResponse = CsvWrapper(json_value)+ .try_into()+ .map_err(|e| ReacherResponseError::new(StatusCode::INTERNAL_SERVER_ERROR, e))?;+ wtr.serialize(result_csv)+ .map_err(|e| ReacherResponseError::new(StatusCode::INTERNAL_SERVER_ERROR, e))?;+ }++ let data = wtr.into_inner().map_err(ReacherResponseError::from)?;++ Ok(data)+}++pub fn v1_get_bulk_job_results(+ config: Arc<BackendConfig>,+) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone {+ warp::path!("v1" / "bulk" / i32 / "results")+ .and(warp::get())+ .and(with_db(config.get_pg_pool()))+ .and(warp::query::<Request>())+ .and_then(http_handler)+ // View access logs by setting `RUST_LOG=reacher_backend`.+ .with(warp::log(LOG_TARGET))+}diff --git a/worker/src/lib.rs b/backend/src/http/v1/bulk/mod.rssimilarity index 71%rename from worker/src/lib.rsrename to backend/src/http/v1/bulk/mod.rsindex 78974b21..ad83e7be 100644--- a/worker/src/lib.rs+++ b/backend/src/http/v1/bulk/mod.rs@@ -14,14 +14,6 @@// 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/>.-//! Main entry point of the `reacher_backend` binary. It has two `main`-//! functions, depending on whether the `bulk` feature is enabled or not.--use std::env;--pub mod check_email;-pub mod config;-pub mod db;-pub mod worker;--pub const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");+pub mod get_progress;+pub mod get_results;+pub mod post;diff --git a/backend/src/http/v1/bulk/post.rs b/backend/src/http/v1/bulk/post.rsnew file mode 100644index 00000000..3ade77ab--- /dev/null+++ b/backend/src/http/v1/bulk/post.rs@@ -0,0 +1,166 @@+// 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/>.++//! This file implements the `POST /v1/bulk` endpoint.++use std::sync::Arc;++use check_if_email_exists::LOG_TARGET;+use futures::stream::StreamExt;+use futures::stream::TryStreamExt;+use lapin::Channel;+use lapin::{options::*, BasicProperties};+use serde::{Deserialize, Serialize};+use sqlx::PgPool;+use tracing::info;+use warp::http::StatusCode;+use warp::Filter;++use crate::config::BackendConfig;+use crate::http::check_header;+use crate::http::v1::with_channel;+use crate::http::with_db;+use crate::http::CheckEmailRequest;+use crate::http::ReacherResponseError;+use crate::worker::check_email::TaskWebhook;+use crate::worker::preprocess::PreprocessTask;++const PREPROCESS_QUEUE: &str = "preprocess";++/// POST v1/bulk endpoint request body.+#[derive(Debug, Deserialize)]+struct Request {+ input: Vec<String>,+ webhook: Option<TaskWebhook>,+}++/// POST v1/bulk endpoint response body.+#[derive(Clone, Debug, Deserialize, Serialize)]+struct Response {+ job_id: i32,+}++async fn http_handler(+ channel: Arc<Channel>,+ pg_pool: PgPool,+ body: Request,+) -> Result<impl warp::Reply, warp::Rejection> {+ if body.input.is_empty() {+ return Err(ReacherResponseError::new(StatusCode::BAD_REQUEST, "Empty input").into());+ }++ // create job entry+ let rec = sqlx::query!(+ r#"+ INSERT INTO v1_bulk_job (total_records)+ VALUES ($1)+ RETURNING id+ "#,+ body.input.len() as i32+ )+ .fetch_one(&pg_pool)+ .await+ .map_err(ReacherResponseError::from)?;++ let payloads = body.input.iter().map(|email| {+ let input = CheckEmailRequest {+ to_email: email.clone(),+ from_email: None,+ hello_name: None,+ proxy: None,+ gmail_verif_method: None,+ hotmailb2b_verif_method: None,+ hotmailb2c_verif_method: None,+ yahoo_verif_method: None,+ };++ Ok(PreprocessTask {+ input,+ job_id: Some(rec.id),+ webhook: body.webhook.clone(),+ })+ });+ let payloads = payloads.collect::<Result<Vec<_>, ReacherResponseError>>()?;++ let n = payloads.len();+ let stream = futures::stream::iter(payloads);++ let properties = BasicProperties::default()+ .with_content_type("application/json".into())+ .with_priority(1);++ stream+ .map::<Result<_, ReacherResponseError>, _>(Ok)+ .try_for_each_concurrent(10, |payload| async {+ publish_task(Arc::clone(&channel), payload, properties.clone()).await+ })+ .await?;++ info!(+ target: LOG_TARGET,+ queue = PREPROCESS_QUEUE,+ "Added {n} emails to the queue",+ );+ Ok(warp::reply::json(&Response { job_id: rec.id }))+}++/// Publish a task to the "preprocess" queue.+pub async fn publish_task(+ channel: Arc<Channel>,+ payload: PreprocessTask,+ properties: BasicProperties,+) -> Result<(), ReacherResponseError> {+ let channel = Arc::clone(&channel);++ let payload_u8 = serde_json::to_vec(&payload)?;+ channel+ .basic_publish(+ "",+ PREPROCESS_QUEUE,+ BasicPublishOptions::default(),+ &payload_u8,+ properties,+ )+ .await+ .map_err(ReacherResponseError::from)?+ .await+ .map_err(ReacherResponseError::from)?;++ info!(target: LOG_TARGET, email=?payload.input.to_email, queue=?PREPROCESS_QUEUE, "Published task");++ Ok(())+}++/// Create the `POST /bulk` endpoint.+/// The endpoint accepts list of email address and creates+/// a new job to check them.+pub fn v1_create_bulk_job(+ config: Arc<BackendConfig>,+) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone {+ warp::path!("v1" / "bulk")+ .and(warp::post())+ .and(check_header(Arc::clone(&config)))+ .and(with_channel(config.get_preprocess_channel()))+ .and(with_db(config.get_pg_pool()))+ // When accepting a body, we want a JSON body (and to reject huge+ // payloads)...+ // TODO: Configure max size limit for a bulk job+ .and(warp::body::content_length_limit(1024 * 1024 * 50))+ .and(warp::body::json())+ .and_then(http_handler)+ // View access logs by setting `RUST_LOG=reacher_backend`.+ .with(warp::log(LOG_TARGET))+}diff --git a/backend/src/http/v1/check_email/mod.rs b/backend/src/http/v1/check_email/mod.rsnew file mode 100644index 00000000..9fbd6cb2--- /dev/null+++ b/backend/src/http/v1/check_email/mod.rs@@ -0,0 +1,17 @@+// 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 post;diff --git a/backend/src/http/v1/check_email/post.rs b/backend/src/http/v1/check_email/post.rsnew file mode 100644index 00000000..56b8f733--- /dev/null+++ b/backend/src/http/v1/check_email/post.rs@@ -0,0 +1,167 @@+// 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/>.++//! This file implements the `POST /v1/check_email` endpoint.++use check_if_email_exists::LOG_TARGET;+use futures::StreamExt;+use lapin::options::{+ BasicAckOptions, BasicConsumeOptions, BasicRejectOptions, QueueDeclareOptions,+};+use lapin::types::FieldTable;+use lapin::{BasicProperties, Channel};+use std::sync::Arc;+use warp::http::StatusCode;+use warp::{http, Filter};++use crate::config::BackendConfig;+use crate::http::v0::check_email::post::CheckEmailRequest;+use crate::http::v1::bulk::post::publish_task;+use crate::http::v1::with_channel;+use crate::http::{check_header, ReacherResponseError};+use crate::worker::consume::MAX_QUEUE_PRIORITY;+use crate::worker::preprocess::PreprocessTask;+use crate::worker::response::SingleShotReply;++/// The main endpoint handler that implements the logic of this route.+async fn http_handler(+ channel: Arc<Channel>,+ body: CheckEmailRequest,+) -> Result<impl warp::Reply, warp::Rejection> {+ // The to_email field must be present+ if body.to_email.is_empty() {+ return Err(ReacherResponseError::new(+ http::StatusCode::BAD_REQUEST,+ "to_email field is required.",+ )+ .into());+ }++ // Follow this RPC tutorial:+ // https://www.rabbitmq.com/tutorials/tutorial-six-javascript#callback-queue+ let correlation_id = uuid::Uuid::new_v4();+ let reply_queue = channel+ .queue_declare(+ "", // Let RabbitMQ generate a unique name+ QueueDeclareOptions {+ auto_delete: true,+ durable: false,+ exclusive: true,+ ..Default::default()+ },+ FieldTable::default(),+ )+ .await+ .map_err(ReacherResponseError::from)?;++ let properties = BasicProperties::default()+ .with_content_type("application/json".into())+ .with_priority(MAX_QUEUE_PRIORITY) // Highes priority+ .with_correlation_id(correlation_id.to_string().into())+ .with_reply_to(reply_queue.name().to_owned());++ publish_task(+ channel.clone(),+ PreprocessTask {+ input: body,+ job_id: None,+ webhook: None,+ },+ properties,+ )+ .await?;++ // Wait for the callback from the worker.+ let mut consumer = channel+ .basic_consume(+ reply_queue.name().as_str(),+ format!("rpc.{}", correlation_id).as_str(),+ BasicConsumeOptions::default(),+ FieldTable::default(),+ )+ .await+ .map_err(ReacherResponseError::from)?;++ // We don't need to loop here, because we only expect one reply.+ if let Some(delivery) = consumer.next().await {+ let delivery = delivery.map_err(ReacherResponseError::from)?;++ if delivery+ .properties+ .correlation_id()+ .as_ref()+ .map(|s| s.as_str())+ == Some(correlation_id.to_string().as_str())+ {+ delivery+ .ack(BasicAckOptions::default())+ .await+ .map_err(ReacherResponseError::from)?;++ let single_shot_response = serde_json::from_slice::<SingleShotReply>(&delivery.data)+ .map_err(ReacherResponseError::from)?;++ match single_shot_response {+ SingleShotReply::Ok(body) => {+ return Ok(warp::reply::with_header(+ body,+ "Content-Type",+ "application/json",+ ));+ }+ SingleShotReply::Err((e, code)) => {+ let status_code =+ StatusCode::from_u16(code).map_err(ReacherResponseError::from)?;+ return Err(ReacherResponseError::new(status_code, e).into());+ }+ }+ } else {+ delivery+ .reject(BasicRejectOptions { requeue: false })+ .await+ .map_err(ReacherResponseError::from)?;+ return Err(ReacherResponseError::new(+ http::StatusCode::INTERNAL_SERVER_ERROR,+ "Failed to get a reply from the worker.",+ )+ .into());+ }+ }++ // Run the future to check an email.+ Err(ReacherResponseError::new(+ http::StatusCode::INTERNAL_SERVER_ERROR,+ "Failed to get a reply from the worker.",+ )+ .into())+}++/// Create the `POST /v1/check_email` endpoint.+pub fn v1_check_email(+ config: Arc<BackendConfig>,+) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone {+ warp::path!("v1" / "check_email")+ .and(warp::post())+ .and(check_header(Arc::clone(&config)))+ .and(with_channel(config.get_preprocess_channel()))+ // When accepting a body, we want a JSON body (and to reject huge+ // payloads)...+ .and(warp::body::content_length_limit(1024 * 16))+ .and(warp::body::json())+ .and_then(http_handler)+ // View access logs by setting `RUST_LOG=reacher`.+ .with(warp::log(LOG_TARGET))+}diff --git a/backend/src/http/v1/mod.rs b/backend/src/http/v1/mod.rsnew file mode 100644index 00000000..3fdfe8df--- /dev/null+++ b/backend/src/http/v1/mod.rs@@ -0,0 +1,43 @@+// 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/>.++use lapin::Channel;+use std::sync::Arc;+use warp::http::StatusCode;+use warp::Filter;++use super::ReacherResponseError;++pub mod bulk;+pub mod check_email;++/// Warp filter that extracts lapin Channel, or returns a 503 error if it's not+/// available.+pub fn with_channel(+ channel: Option<Arc<Channel>>,+) -> impl Filter<Extract = (Arc<Channel>,), Error = warp::Rejection> + Clone {+ warp::any().and_then(move || {+ let channel = channel.clone();+ async move {+ channel.ok_or_else(|| {+ warp::reject::custom(ReacherResponseError::new(+ StatusCode::SERVICE_UNAVAILABLE,+ "Please configure a RabbitMQ instance on Reacher before calling this endpoint",+ ))+ })+ }+ })+}diff --git a/backend/src/lib.rs b/backend/src/lib.rsindex 408bec1b..b6ecc9ca 100644--- a/backend/src/lib.rs+++ b/backend/src/lib.rs@@ -15,6 +15,11 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.pub mod config;+mod db;pub mod http;+#[cfg(feature = "worker")]+pub mod worker;++pub use db::create_db;const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");diff --git a/backend/src/main.rs b/backend/src/main.rsindex f3f74038..f444ba59 100644--- a/backend/src/main.rs+++ b/backend/src/main.rs@@ -18,6 +18,8 @@//! functions, depending on whether the `bulk` feature is enabled or not.use check_if_email_exists::{setup_sentry, LOG_TARGET};+#[cfg(feature = "worker")]+use reacher_backend::worker::run_worker;use std::sync::Arc;use tracing::info;@@ -28,11 +30,11 @@ const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");/// Run a HTTP server using warp with bulk endpoints.#[tokio::main]-async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {+async fn main() -> Result<(), anyhow::Error> {// Initialize logging.tracing_subscriber::fmt::init();info!(target: LOG_TARGET, version=?CARGO_PKG_VERSION, "Running Reacher");- let config = load_config()?;+ let config = load_config().await?;// Setup sentry bug tracking.let _guard: sentry::ClientInitGuard;@@ -40,7 +42,27 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {_guard = setup_sentry(sentry_config);}- let _bulk_job_runner = run_warp_server(Arc::new(config)).await?;+ let config = Arc::new(config);++ #[cfg(feature = "worker")]+ {+ let server_future = run_warp_server(Arc::clone(&config));+ let worker_future = async {+ if config.worker.enable {+ run_worker(config).await?;+ }+ Ok(())+ };++ tokio::try_join!(server_future, worker_future)?;++ info!("Shutting down...");+ }++ #[cfg(not(feature = "worker"))]+ {+ run_warp_server(config).await?;+ }Ok(())}diff --git a/backend/src/worker/check_email.rs b/backend/src/worker/check_email.rsnew file mode 100644index 00000000..fd83c7a7--- /dev/null+++ b/backend/src/worker/check_email.rs@@ -0,0 +1,201 @@+// 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/>.++use super::response::save_to_db;+use crate::config::BackendConfig;+use crate::worker::response::send_single_shot_reply;+use check_if_email_exists::{+ check_email, CheckEmailInput, CheckEmailOutput, Reachable, LOG_TARGET,+};+use core::time;+use lapin::message::Delivery;+use lapin::{options::*, Channel};+use serde::{Deserialize, Serialize};+use std::fmt::Debug;+use std::sync::Arc;+use thiserror::Error;+use tracing::{debug, info};+use warp::http::StatusCode;++#[derive(Debug, Deserialize, Serialize)]+pub struct CheckEmailTask {+ pub input: CheckEmailInput,+ // If the task is a part of a job, then this field will be set.+ pub job_id: Option<i32>,+ pub webhook: Option<TaskWebhook>,+}++impl CheckEmailTask {+ /// Returns true if the task is a single-shot email verification via the+ /// /v1/check_email, endpoint, i.e. not a part of a bulk verification job.+ pub fn is_single_shot(&self) -> bool {+ self.job_id.is_none()+ }+}++/// The errors that can occur when processing a task.+#[derive(Debug, Error)]+pub enum TaskError {+ /// The worker is at full capacity and cannot accept more tasks. Note that+ /// this error only occurs for single-shot tasks, and not for bulk+ /// verification, as for bulk verification tasks the task will simply stay+ /// in the queue until one worker is ready to process it.+ #[error("Worker at full capacity, wait {0:?}")]+ Throttle(time::Duration),+ #[error("Lapin error: {0}")]+ Lapin(lapin::Error),+ #[error("Reqwest error during webhook: {0}")]+ Reqwest(reqwest::Error),+}++impl TaskError {+ /// Returns the status code that should be returned to the client.+ pub fn status_code(&self) -> StatusCode {+ match self {+ Self::Throttle(_) => StatusCode::TOO_MANY_REQUESTS,+ Self::Lapin(_) => StatusCode::INTERNAL_SERVER_ERROR,+ Self::Reqwest(_) => StatusCode::INTERNAL_SERVER_ERROR,+ }+ }+}++impl From<lapin::Error> for TaskError {+ fn from(err: lapin::Error) -> Self {+ Self::Lapin(err)+ }+}++impl From<reqwest::Error> for TaskError {+ fn from(err: reqwest::Error) -> Self {+ Self::Reqwest(err)+ }+}++impl Serialize for TaskError {+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>+ where+ S: serde::Serializer,+ {+ serializer.serialize_str(&self.to_string())+ }+}++#[derive(Debug, Deserialize, Clone, Serialize)]+pub struct TaskWebhook {+ pub on_each_email: Option<Webhook>,+}++#[derive(Debug, Deserialize, Clone, Serialize)]+pub struct Webhook {+ pub url: String,+ pub extra: Option<serde_json::Value>,+}++#[derive(Debug, Serialize)]+struct WebhookOutput<'a> {+ result: &'a CheckEmailOutput,+ extra: &'a Option<serde_json::Value>,+}++/// Processes the check email task asynchronously.+pub(crate) async fn do_check_email_work(+ payload: &CheckEmailTask,+ delivery: Delivery,+ channel: Arc<Channel>,+ config: Arc<BackendConfig>,+) -> Result<(), anyhow::Error> {+ let worker_output = inner_check_email(payload, Arc::clone(&config)).await;++ match (&worker_output, delivery.redelivered) {+ (Ok(output), false) if output.is_reachable == Reachable::Unknown => {+ // If is_reachable is unknown, then we requeue the message, but only once.+ // We might want to add a requeue counter in the future, see:+ // https://stackoverflow.com/questions/25226080/rabbitmq-how-to-requeue-message-with-counter+ delivery+ .reject(BasicRejectOptions { requeue: true })+ .await?;+ info!(target: LOG_TARGET, email=?&payload.input.to_email, is_reachable=?Reachable::Unknown, "Requeued message");+ }+ (Err(e), false) => {+ // Same as above, if processing the message failed, we requeue it.+ delivery+ .reject(BasicRejectOptions { requeue: true })+ .await?;+ info!(target: LOG_TARGET, email=?&payload.input.to_email, err=?e, "Requeued message");+ }+ _ => {+ // This is the happy path. We acknowledge the message and:+ // - If it's a single-shot email verification, we send a reply to the client.+ // - If it's a bulk verification, we save the result to the database.+ delivery.ack(BasicAckOptions::default()).await?;++ if payload.is_single_shot() {+ send_single_shot_reply(channel, &delivery, &worker_output).await?;+ } else {+ save_to_db(+ &config.backend_name,+ config.get_pg_pool(),+ payload,+ &worker_output,+ )+ .await?;+ }++ info!(target: LOG_TARGET,+ email=payload.input.to_email,+ worker_output=?worker_output.map(|o| o.is_reachable),+ job_id=?payload.job_id,+ "Done check",+ );+ }+ }++ Ok(())+}++async fn inner_check_email(+ payload: &CheckEmailTask,+ config: Arc<BackendConfig>,+) -> Result<CheckEmailOutput, TaskError> {+ let output = check_email(&payload.input, &config.get_reacher_config()).await;++ // Check if we have a webhook to send the output to.+ if let Some(TaskWebhook {+ on_each_email: Some(webhook),+ }) = &payload.webhook+ {+ let webhook_output = WebhookOutput {+ result: &output,+ extra: &webhook.extra,+ };++ let client = reqwest::Client::new();+ let res = client+ .post(&webhook.url)+ .json(&webhook_output)+ .header(+ "x-reacher-secret",+ std::env::var("RCH_HEADER_SECRET").unwrap_or_default(),+ )+ .send()+ .await?+ .text()+ .await?;+ debug!(target: LOG_TARGET, email=?webhook_output.result.input,res=?res, "Received webhook response");+ }++ Ok(output)+}diff --git a/backend/src/worker/consume.rs b/backend/src/worker/consume.rsnew file mode 100644index 00000000..ca71280b--- /dev/null+++ b/backend/src/worker/consume.rs@@ -0,0 +1,328 @@+// 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/>.++use super::check_email::{do_check_email_work, CheckEmailTask, TaskError};+use super::preprocess::{do_preprocess_work, PreprocessTask};+use super::response::send_single_shot_reply;+use crate::config::{BackendConfig, RabbitMQConfig, RabbitMQQueues, ThrottleConfig};+use anyhow::Context;+use check_if_email_exists::LOG_TARGET;+use futures::stream::StreamExt;+use lapin::{options::*, types::FieldTable, Channel, Connection, ConnectionProperties};+use std::sync::Arc;+use std::time::{Duration, Instant};+use tokio::sync::Mutex;+use tracing::{debug, error, info};++pub const MAX_QUEUE_PRIORITY: u8 = 5;++/// Set up the RabbitMQ connection and declare all queues. This creates two+/// channels, one for checking emails and one for preprocessing. The+/// preprocessing channel is used to figure out the email provider and route+/// the message to the correct queue.+///+/// The check channel is used to consume messages from the queues. It has a+/// global prefetch limit set to the concurrency limit.+///+/// Returns a tuple of (check_channel, preprocess_channel).+pub async fn setup_rabbit_mq(+ backend_name: &str,+ config: &RabbitMQConfig,+) -> Result<(Channel, Channel), anyhow::Error> {+ let options = ConnectionProperties::default()+ // Use tokio executor and reactor.+ .with_executor(tokio_executor_trait::Tokio::current())+ .with_reactor(tokio_reactor_trait::Tokio)+ .with_connection_name(backend_name.into());++ let conn = Connection::connect(&config.url, options)+ .await+ .with_context(|| format!("Connecting to rabbitmq {}", &config.url))?;+ let check_channel = conn.create_channel().await?;+ let preprocess_channel = conn.create_channel().await?;++ info!(target: LOG_TARGET, backend=?backend_name,state=?conn.status().state(), "Connected to AMQP broker");++ let mut queue_args = FieldTable::default();+ queue_args.insert("x-max-priority".into(), MAX_QUEUE_PRIORITY.into());++ // Assert all queues are declared.+ for queue in RabbitMQQueues::All.to_queues().iter() {+ check_channel+ .queue_declare(+ format!("{}", queue).as_str(),+ QueueDeclareOptions {+ durable: true,+ ..Default::default()+ },+ queue_args.clone(),+ )+ .await?;+ }++ // Set up prefetch (concurrency) limit using qos+ check_channel+ .basic_qos(+ config.concurrency,+ // Set global to true to apply to all consumers.+ // ref: https://www.rabbitmq.com/docs/consumer-prefetch#independent-consumers+ BasicQosOptions { global: true },+ )+ .await?;++ preprocess_channel+ .queue_declare(+ "preprocess",+ QueueDeclareOptions {+ durable: true,+ ..Default::default()+ },+ queue_args,+ )+ .await?;++ info!(target: LOG_TARGET, queues=?config.queues.to_queues(), concurrency=?config.concurrency, "Worker will start consuming messages");++ Ok((check_channel, preprocess_channel))+}++/// Start the worker to consume messages from the queue.+pub async fn run_worker(config: Arc<BackendConfig>) -> Result<(), anyhow::Error> {+ tokio::try_join!(+ consume_preprocess(Arc::clone(&config)),+ consume_check_email(config)+ )?;++ Ok(())+}++/// Consume "Preprocess" queue, by figuring out the email provider and routing+/// (i.e. re-publishing) to the correct queue.+async fn consume_preprocess(config: Arc<BackendConfig>) -> Result<(), anyhow::Error> {+ let preprocess_channel = config.must_worker_config()?.preprocess_channel;+ let check_email_channel = config.must_worker_config()?.check_email_channel;++ let mut consumer = preprocess_channel+ .basic_consume(+ "preprocess",+ format!("{}-preprocess", &config.backend_name).as_str(),+ BasicConsumeOptions::default(),+ FieldTable::default(),+ )+ .await?;++ // Loop over the incoming messages+ while let Some(delivery) = consumer.next().await {+ let delivery = delivery?;+ let payload = serde_json::from_slice::<PreprocessTask>(&delivery.data)?;+ debug!(target: LOG_TARGET, email=payload.input.to_email, "New Preprocess job");++ let channel_clone = Arc::clone(&check_email_channel);+ let config_clone = Arc::clone(&config);++ tokio::spawn(async move {+ if let Err(e) =+ do_preprocess_work(&payload, delivery, channel_clone, config_clone).await+ {+ error!(target: LOG_TARGET, email=payload.input.to_email, error=?e, "Error preprocessing message");+ }+ });+ }+ Ok(())+}++async fn consume_check_email(config: Arc<BackendConfig>) -> Result<(), anyhow::Error> {+ let config_clone = Arc::clone(&config);+ let worker_config = config_clone.must_worker_config()?;+ let channel = worker_config.check_email_channel;++ let throttle = Arc::new(Mutex::new(Throttle::new()));++ for queue in worker_config.rabbitmq.queues.to_queues() {+ let channel_clone = Arc::clone(&channel);+ let config_clone = Arc::clone(&config);+ let throttle_clone = Arc::clone(&throttle);+ let queue_clone = queue.clone();++ tokio::spawn(async move {+ let worker_config = config_clone.must_worker_config()?;++ let mut consumer = channel_clone+ .basic_consume(+ queue_clone.to_string().as_str(),+ format!("{}-{}", &config_clone.backend_name, &queue_clone).as_str(),+ BasicConsumeOptions::default(),+ FieldTable::default(),+ )+ .await?;++ // Loop over the incoming messages+ while let Some(delivery) = consumer.next().await {+ let delivery = delivery?;+ let payload = serde_json::from_slice::<CheckEmailTask>(&delivery.data)?;+ debug!(target: LOG_TARGET, queue=?queue_clone.to_string(), email=?payload.input.to_email, "Consuming message");++ // Reset throttle counters if needed+ throttle_clone.lock().await.reset_if_needed();++ // Check if we should throttle before fetching the next message+ if let Some(wait_duration) = throttle_clone+ .lock()+ .await+ .should_throttle(&worker_config.throttle)+ {+ info!(target: LOG_TARGET, wait=?wait_duration, email=?payload.input.to_email, "Too many requests, throttling");++ // For single-shot tasks, we return an error early, so that the user knows they need to retry.+ if payload.is_single_shot() {+ debug!(target: LOG_TARGET, email=payload.input.to_email, job_id=?payload.job_id, queue=?queue_clone.to_string(), "Rejecting single-shot email because of throttling");+ delivery+ .reject(BasicRejectOptions { requeue: false })+ .await?;++ send_single_shot_reply(+ Arc::clone(&channel_clone),+ &delivery,+ &Err(TaskError::Throttle(wait_duration)),+ )+ .await?;+ } else {+ // Put back the message into the same queue, so that other+ // workers can pick it up.+ delivery+ .reject(BasicRejectOptions { requeue: true })+ .await?;+ debug!(target: LOG_TARGET, email=payload.input.to_email, job_id=?payload.job_id, queue=?queue_clone.to_string(), "Requeued message because of throttling");+ }++ continue;+ }++ let config_clone2 = Arc::clone(&config_clone);+ let channel_clone2 = Arc::clone(&channel_clone);++ info!(target: LOG_TARGET, email=payload.input.to_email, job_id=?payload.job_id, queue=?queue_clone.to_string(), "Starting task");+ tokio::spawn(async move {+ if let Err(e) =+ do_check_email_work(&payload, delivery, channel_clone2, config_clone2).await+ {+ error!(target: LOG_TARGET, email=payload.input.to_email, error=?e, "Error processing message");+ }+ });++ // Increment throttle counters once we spawn the task+ throttle_clone.lock().await.increment_counters();+ }++ Ok::<(), anyhow::Error>(())+ });+ }++ Ok(())+}++#[derive(Clone)]+struct Throttle {+ requests_per_second: u32,+ requests_per_minute: u32,+ requests_per_hour: u32,+ requests_per_day: u32,+ last_reset_second: Instant,+ last_reset_minute: Instant,+ last_reset_hour: Instant,+ last_reset_day: Instant,+}++impl Throttle {+ fn new() -> Self {+ let now = Instant::now();+ Throttle {+ requests_per_second: 0,+ requests_per_minute: 0,+ requests_per_hour: 0,+ requests_per_day: 0,+ last_reset_second: now,+ last_reset_minute: now,+ last_reset_hour: now,+ last_reset_day: now,+ }+ }++ fn reset_if_needed(&mut self) {+ let now = Instant::now();++ // Reset per-second counter+ if now.duration_since(self.last_reset_second) >= Duration::from_secs(1) {+ self.requests_per_second = 0;+ self.last_reset_second = now;+ }++ // Reset per-minute counter+ if now.duration_since(self.last_reset_minute) >= Duration::from_secs(60) {+ self.requests_per_minute = 0;+ self.last_reset_minute = now;+ }++ // Reset per-hour counter+ if now.duration_since(self.last_reset_hour) >= Duration::from_secs(3600) {+ self.requests_per_hour = 0;+ self.last_reset_hour = now;+ }++ // Reset per-day counter+ if now.duration_since(self.last_reset_day) >= Duration::from_secs(86400) {+ self.requests_per_day = 0;+ self.last_reset_day = now;+ }+ }++ fn increment_counters(&mut self) {+ self.requests_per_second += 1;+ self.requests_per_minute += 1;+ self.requests_per_hour += 1;+ self.requests_per_day += 1;+ }++ fn should_throttle(&self, config: &ThrottleConfig) -> Option<Duration> {+ let now = Instant::now();++ if let Some(max_per_second) = config.max_requests_per_second {+ if self.requests_per_second >= max_per_second {+ return Some(Duration::from_secs(1) - now.duration_since(self.last_reset_second));+ }+ }++ if let Some(max_per_minute) = config.max_requests_per_minute {+ if self.requests_per_minute >= max_per_minute {+ return Some(Duration::from_secs(60) - now.duration_since(self.last_reset_minute));+ }+ }++ if let Some(max_per_hour) = config.max_requests_per_hour {+ if self.requests_per_hour >= max_per_hour {+ return Some(Duration::from_secs(3600) - now.duration_since(self.last_reset_hour));+ }+ }++ if let Some(max_per_day) = config.max_requests_per_day {+ if self.requests_per_day >= max_per_day {+ return Some(Duration::from_secs(86400) - now.duration_since(self.last_reset_day));+ }+ }++ None+ }+}diff --git a/backend/src/worker/mod.rs b/backend/src/worker/mod.rsnew file mode 100644index 00000000..cc6ad654--- /dev/null+++ b/backend/src/worker/mod.rs@@ -0,0 +1,29 @@+// 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/>.++// Each file corresponds to one step in the worker pipeline. The worker pipeline+// is defined as:+// - consume from RabbitMQ+// - preprocess+// - check email+// - send response (either to the reply_to queue or save to the database)++pub mod check_email;+pub mod consume;+pub mod preprocess;+pub mod response;++pub use consume::{run_worker, setup_rabbit_mq};diff --git a/backend/src/worker/preprocess.rs b/backend/src/worker/preprocess.rsnew file mode 100644index 00000000..937b0b75--- /dev/null+++ b/backend/src/worker/preprocess.rs@@ -0,0 +1,88 @@+// 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/>.++use super::check_email::CheckEmailTask;+use super::check_email::TaskWebhook;+use crate::config::{BackendConfig, Queue};+use crate::http::CheckEmailRequest;+use anyhow::anyhow;+use check_if_email_exists::mx::check_mx;+use check_if_email_exists::syntax::check_syntax;+use check_if_email_exists::{is_gmail, is_hotmail_b2b, is_hotmail_b2c, is_yahoo, LOG_TARGET};+use lapin::message::Delivery;+use lapin::{options::*, Channel};+use serde::{Deserialize, Serialize};+use std::fmt::Debug;+use std::sync::Arc;+use tracing::debug;++#[derive(Debug, Deserialize, Serialize)]+pub struct PreprocessTask {+ pub input: CheckEmailRequest,+ // If the task is a part of a job, then this field will be set.+ pub job_id: Option<i32>,+ pub webhook: Option<TaskWebhook>,+}++/// Preprocess the email and send it to the appropriate queue for verification.+pub async fn do_preprocess_work(+ payload: &PreprocessTask,+ delivery: Delivery,+ channel: Arc<Channel>,+ config: Arc<BackendConfig>,+) -> Result<(), anyhow::Error> {+ let syntax = check_syntax(&payload.input.to_email);+ let mx = check_mx(&syntax).await?;+ // Get first hostname from MX records.+ let mx_hostname = mx+ .lookup?+ .iter()+ .next()+ .ok_or_else(|| anyhow!("No MX records found"))?+ .exchange()+ .to_string();++ let queue = match mx_hostname.as_str() {+ hostname if is_gmail(hostname) => Queue::Gmail,+ hostname if is_hotmail_b2b(hostname) => Queue::HotmailB2B,+ hostname if is_hotmail_b2c(hostname) => Queue::HotmailB2C,+ hostname if is_yahoo(hostname) => Queue::Yahoo,+ _ => Queue::EverythingElse,+ };+ let check_email_input = payload.input.to_check_email_input(config);+ let check_email_task = CheckEmailTask {+ input: check_email_input,+ job_id: payload.job_id,+ webhook: payload.webhook.clone(),+ };+ let check_email_payload = serde_json::to_vec(&check_email_task)?;++ channel+ .basic_publish(+ "",+ format!("{}", queue).as_str(),+ BasicPublishOptions::default(),+ &check_email_payload,+ delivery.properties.clone(),+ )+ .await?+ .await?;++ delivery.ack(BasicAckOptions::default()).await?;+ debug!(target: LOG_TARGET, email=?payload.input.to_email, queue=?queue.to_string(), "Message do_preprocess_worked");++ Ok(())+}diff --git a/backend/src/worker/response.rs b/backend/src/worker/response.rsnew file mode 100644index 00000000..90a47a12--- /dev/null+++ b/backend/src/worker/response.rs@@ -0,0 +1,159 @@+// 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/>.++use super::check_email::{CheckEmailTask, TaskError};+use anyhow::bail;+use check_if_email_exists::{CheckEmailOutput, LOG_TARGET};+use lapin::message::Delivery;+use lapin::options::BasicPublishOptions;+use lapin::{BasicProperties, Channel};+use serde::{Deserialize, Serialize};+use sqlx::PgPool;+use std::convert::TryFrom;+use std::sync::Arc;+use tracing::debug;+use warp::http::StatusCode;++/// Save the task result to the database. This only happens if the task is a+/// part of a bulk verification job. If no pool is provided, the function will+/// simply return without doing anything.+///+/// # Panics+///+/// Panics if the task is a single-shot task, i.e. if `payload.job_id` is `None`.+pub async fn save_to_db(+ backend_name: &str,+ pg_pool: Option<PgPool>,+ payload: &CheckEmailTask,+ worker_output: &Result<CheckEmailOutput, TaskError>,+) -> Result<(), anyhow::Error> {+ let pg_pool = pg_pool.ok_or_else(|| anyhow::anyhow!("No DB pool provided"))?;+ let job_id = payload.job_id.unwrap();++ let payload_json = serde_json::to_value(payload)?;++ match worker_output {+ Ok(output) => {+ let output_json = serde_json::to_value(output)?;++ sqlx::query!(+ r#"+ INSERT INTO v1_task_result (payload, job_id, backend_name, result)+ VALUES ($1, $2, $3, $4)+ RETURNING id+ "#,+ payload_json,+ job_id,+ backend_name,+ output_json,+ )+ .fetch_one(&pg_pool)+ .await?;+ }+ Err(err) => {+ sqlx::query!(+ r#"+ INSERT INTO v1_task_result (payload, job_id, backend_name, error)+ VALUES ($1, $2, $3, $4)+ RETURNING id+ "#,+ payload_json,+ job_id,+ backend_name,+ err.to_string(),+ )+ .fetch_one(&pg_pool)+ .await?;+ }+ }++ debug!(target: LOG_TARGET, email=?payload.input.to_email, "Wrote to DB");++ Ok(())+}++/// For single-shot email verifications, the worker will send a reply to the+/// client with the result of the verification. Since both CheckEmailOutput and+/// TaskError are not Deserialize, we need to create a new struct that can be+/// serialized and deserialized.+#[derive(Debug, Deserialize, Serialize)]+pub enum SingleShotReply {+ /// JSON serialization of CheckEmailOutput+ Ok(Vec<u8>),+ /// String representation of TaskError with its status code.+ /// Unfortunately, we cannot use StatusCode directly, as it is not+ /// Serialize.+ Err((String, u16)),+}++impl TryFrom<&Result<CheckEmailOutput, TaskError>> for SingleShotReply {+ type Error = serde_json::Error;++ fn try_from(result: &Result<CheckEmailOutput, TaskError>) -> Result<Self, Self::Error> {+ match result {+ Ok(output) => Ok(Self::Ok(serde_json::to_vec(output)?)),+ Err(TaskError::Throttle(e)) => Ok(Self::Err((+ TaskError::Throttle(*e).to_string(),+ StatusCode::TOO_MANY_REQUESTS.as_u16(),+ ))),+ Err(e) => Ok(Self::Err((+ e.to_string(),+ StatusCode::INTERNAL_SERVER_ERROR.as_u16(),+ ))),+ }+ }+}++/// Send reply, in an "RPC mode", to the queue that initiated the request. We+/// follow this guide:+/// https://www.rabbitmq.com/tutorials/tutorial-six-javascript.html+///+/// This only applies for single-shot email verifications on the+/// /v1/check_email endpoint, and not to bulk verifications.+pub async fn send_single_shot_reply(+ channel: Arc<Channel>,+ delivery: &Delivery,+ worker_output: &Result<CheckEmailOutput, TaskError>,+) -> Result<(), anyhow::Error> {+ if let (Some(reply_to), Some(correlation_id)) = (+ delivery.properties.reply_to(),+ delivery.properties.correlation_id(),+ ) {+ let properties = BasicProperties::default()+ .with_correlation_id(correlation_id.to_owned())+ .with_content_type("application/json".into());++ let single_shot_response = SingleShotReply::try_from(worker_output)?;+ let reply_payload = serde_json::to_vec(&single_shot_response)?;++ channel+ .basic_publish(+ "",+ reply_to.as_str(),+ BasicPublishOptions::default(),+ &reply_payload,+ properties,+ )+ .await?+ .await?;++ debug!(target: LOG_TARGET, reply_to=?reply_to.to_string(), correlation_id=?correlation_id.to_string(), "Sent reply")+ } else {+ bail!("Missing reply_to or correlation_id");+ }++ Ok(())+}diff --git a/backend/tests/check_email.rs b/backend/tests/check_email.rsindex 76ec6e4d..326133e8 100644--- a/backend/tests/check_email.rs+++ b/backend/tests/check_email.rs@@ -14,110 +14,113 @@// 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::sync::Arc;--use reacher_backend::config::{BackendConfig, ThrottleConfig};-use reacher_backend::http::{create_routes, CheckEmailRequest, REACHER_SECRET_HEADER};-use warp::http::StatusCode;-use warp::test::request;--const FOO_BAR_RESPONSE: &str = r#"{"input":"foo@bar","is_reachable":"invalid","misc":{"is_disposable":false,"is_role_account":false,"gravatar_url":null,"haveibeenpwned":null},"mx":{"accepts_mail":false,"records":[]},"smtp":{"can_connect_smtp":false,"has_full_inbox":false,"is_catch_all":false,"is_deliverable":false,"is_disabled":false},"syntax":{"address":null,"domain":"","is_valid_syntax":false,"username":"","normalized_email":null,"suggestion":null}"#;-const FOO_BAR_BAZ_RESPONSE: &str = r#"{"input":"[email protected]","is_reachable":"invalid","misc":{"is_disposable":false,"is_role_account":false,"gravatar_url":null,"haveibeenpwned":null},"mx":{"accepts_mail":false,"records":[]},"smtp":{"can_connect_smtp":false,"has_full_inbox":false,"is_catch_all":false,"is_deliverable":false,"is_disabled":false},"syntax":{"address":"[email protected]","domain":"bar.baz","is_valid_syntax":true,"username":"foo","normalized_email":"[email protected]","suggestion":null}"#;--fn create_backend_config(header_secret: &str) -> Arc<BackendConfig> {- Arc::new(BackendConfig {- backend_name: "reacher-test".into(),- from_email: "test".into(),- hello_name: "test".into(),- webdriver_addr: "localhost:9515".into(),- http_host: "localhost".into(),- http_port: 8080,- header_secret: Some(header_secret.to_string()),- throttle: ThrottleConfig::new_without_throttle(),- sentry: None,- webhook: None,- })-}--#[tokio::test]-async fn test_input_foo_bar() {- let resp = request()- .path("/v0/check_email")- .method("POST")- .header(REACHER_SECRET_HEADER, "foobar")- .json(&serde_json::from_str::<CheckEmailRequest>(r#"{"to_email": "foo@bar"}"#).unwrap())- .reply(&create_routes(create_backend_config("foobar"), None))- .await;-- assert_eq!(resp.status(), StatusCode::OK, "{:?}", resp.body());- assert!(resp.body().starts_with(FOO_BAR_RESPONSE.as_bytes()));-}--#[tokio::test]-async fn test_input_foo_bar_baz() {- let resp = request()- .path("/v0/check_email")- .method("POST")- .header(REACHER_SECRET_HEADER, "foobar")- .json(&serde_json::from_str::<CheckEmailRequest>(r#"{"to_email": "[email protected]"}"#).unwrap())- .reply(&create_routes(create_backend_config("foobar"), None))- .await;-- assert_eq!(resp.status(), StatusCode::OK, "{:?}", resp.body());- assert!(resp.body().starts_with(FOO_BAR_BAZ_RESPONSE.as_bytes()));-}--#[tokio::test]-async fn test_reacher_secret_missing_header() {- let resp = request()- .path("/v0/check_email")- .method("POST")- .json(&serde_json::from_str::<CheckEmailRequest>(r#"{"to_email": "[email protected]"}"#).unwrap())- .reply(&create_routes(create_backend_config("foobar"), None))- .await;-- assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{:?}", resp.body());- assert_eq!(resp.body(), r#"Missing request header "x-reacher-secret""#);-}--#[tokio::test]-async fn test_reacher_secret_wrong_secret() {- let resp = request()- .path("/v0/check_email")- .method("POST")- .header(REACHER_SECRET_HEADER, "barbaz")- .json(&serde_json::from_str::<CheckEmailRequest>(r#"{"to_email": "[email protected]"}"#).unwrap())- .reply(&create_routes(create_backend_config("foobar"), None))- .await;-- assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{:?}", resp.body());- assert_eq!(resp.body(), r#"Invalid request header "x-reacher-secret""#);-}--#[tokio::test]-async fn test_reacher_secret_correct_secret() {- let resp = request()- .path("/v0/check_email")- .method("POST")- .header(REACHER_SECRET_HEADER, "foobar")- .json(&serde_json::from_str::<CheckEmailRequest>(r#"{"to_email": "foo@bar"}"#).unwrap())- .reply(&create_routes(create_backend_config("foobar"), None))- .await;-- assert_eq!(resp.status(), StatusCode::OK, "{:?}", resp.body());- assert!(resp.body().starts_with(FOO_BAR_RESPONSE.as_bytes()));-}--#[tokio::test]-async fn test_reacher_to_mail_empty() {- let resp = request()- .path("/v0/check_email")- .method("POST")- .header(REACHER_SECRET_HEADER, "foobar")- .json(&serde_json::from_str::<CheckEmailRequest>(r#"{"to_email": ""}"#).unwrap())- .reply(&create_routes(create_backend_config("foobar"), None))- .await;-- assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{:?}", resp.body());- assert_eq!(resp.body(), r#"{"message":"to_email field is required."}"#);+#[cfg(not(feature = "worker"))]+mod tests {+ use std::sync::Arc;++ use reacher_backend::config::BackendConfig;+ use reacher_backend::http::{create_routes, CheckEmailRequest, REACHER_SECRET_HEADER};+ use warp::http::StatusCode;+ use warp::test::request;++ const FOO_BAR_RESPONSE: &str = r#"{"input":"foo@bar","is_reachable":"invalid","misc":{"is_disposable":false,"is_role_account":false,"gravatar_url":null,"haveibeenpwned":null},"mx":{"accepts_mail":false,"records":[]},"smtp":{"can_connect_smtp":false,"has_full_inbox":false,"is_catch_all":false,"is_deliverable":false,"is_disabled":false},"syntax":{"address":null,"domain":"","is_valid_syntax":false,"username":"","normalized_email":null,"suggestion":null}"#;+ const FOO_BAR_BAZ_RESPONSE: &str = r#"{"input":"[email protected]","is_reachable":"invalid","misc":{"is_disposable":false,"is_role_account":false,"gravatar_url":null,"haveibeenpwned":null},"mx":{"accepts_mail":false,"records":[]},"smtp":{"can_connect_smtp":false,"has_full_inbox":false,"is_catch_all":false,"is_deliverable":false,"is_disabled":false},"syntax":{"address":"[email protected]","domain":"bar.baz","is_valid_syntax":true,"username":"foo","normalized_email":"[email protected]","suggestion":null}"#;++ fn create_backend_config(header_secret: &str) -> Arc<BackendConfig> {+ let mut config = BackendConfig::default();+ config.header_secret = Some(header_secret.to_string());+ Arc::new(config)+ }++ #[tokio::test]+ async fn test_input_foo_bar() {+ let resp = request()+ .path("/v0/check_email")+ .method("POST")+ .header(REACHER_SECRET_HEADER, "foobar")+ .json(&serde_json::from_str::<CheckEmailRequest>(r#"{"to_email": "foo@bar"}"#).unwrap())+ .reply(&create_routes(create_backend_config("foobar")))+ .await;++ assert_eq!(resp.status(), StatusCode::OK, "{:?}", resp.body());+ assert!(resp.body().starts_with(FOO_BAR_RESPONSE.as_bytes()));+ }++ #[tokio::test]+ async fn test_input_foo_bar_baz() {+ let resp = request()+ .path("/v0/check_email")+ .method("POST")+ .header(REACHER_SECRET_HEADER, "foobar")+ .json(+ &serde_json::from_str::<CheckEmailRequest>(r#"{"to_email": "[email protected]"}"#)+ .unwrap(),+ )+ .reply(&create_routes(create_backend_config("foobar")))+ .await;++ assert_eq!(resp.status(), StatusCode::OK, "{:?}", resp.body());+ assert!(resp.body().starts_with(FOO_BAR_BAZ_RESPONSE.as_bytes()));+ }++ #[tokio::test]+ async fn test_reacher_secret_missing_header() {+ let resp = request()+ .path("/v0/check_email")+ .method("POST")+ .json(+ &serde_json::from_str::<CheckEmailRequest>(r#"{"to_email": "[email protected]"}"#)+ .unwrap(),+ )+ .reply(&create_routes(create_backend_config("foobar")))+ .await;++ assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{:?}", resp.body());+ assert_eq!(resp.body(), r#"Missing request header "x-reacher-secret""#);+ }++ #[tokio::test]+ async fn test_reacher_secret_wrong_secret() {+ let resp = request()+ .path("/v0/check_email")+ .method("POST")+ .header(REACHER_SECRET_HEADER, "barbaz")+ .json(+ &serde_json::from_str::<CheckEmailRequest>(r#"{"to_email": "[email protected]"}"#)+ .unwrap(),+ )+ .reply(&create_routes(create_backend_config("foobar")))+ .await;++ assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{:?}", resp.body());+ assert_eq!(resp.body(), r#"Invalid request header "x-reacher-secret""#);+ }++ #[tokio::test]+ async fn test_reacher_secret_correct_secret() {+ let resp = request()+ .path("/v0/check_email")+ .method("POST")+ .header(REACHER_SECRET_HEADER, "foobar")+ .json(&serde_json::from_str::<CheckEmailRequest>(r#"{"to_email": "foo@bar"}"#).unwrap())+ .reply(&create_routes(create_backend_config("foobar")))+ .await;++ assert_eq!(resp.status(), StatusCode::OK, "{:?}", resp.body());+ assert!(resp.body().starts_with(FOO_BAR_RESPONSE.as_bytes()));+ }++ #[tokio::test]+ async fn test_reacher_to_mail_empty() {+ let resp = request()+ .path("/v0/check_email")+ .method("POST")+ .header(REACHER_SECRET_HEADER, "foobar")+ .json(&serde_json::from_str::<CheckEmailRequest>(r#"{"to_email": ""}"#).unwrap())+ .reply(&create_routes(create_backend_config("foobar")))+ .await;++ assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{:?}", resp.body());+ assert_eq!(resp.body(), r#"{"error":"to_email field is required."}"#);+ }}diff --git a/cli/Cargo.toml b/cli/Cargo.tomlindex b178b156..71bfbd26 100644--- a/cli/Cargo.toml+++ b/cli/Cargo.toml@@ -1,6 +1,6 @@[package]name = "check-if-email-exists-cli"-version = "0.9.1"+version = "0.10.0"default-run = "check_if_email_exists"edition = "2018"description = "Check if an email address exists without sending any email."@@ -13,6 +13,7 @@ name = "check_if_email_exists"path = "src/main.rs"[dependencies]+anyhow = "1.0"check-if-email-exists = { path = "../core" }clap = { version = "3.2", features = ["derive", "env"] }env_logger = "0.11"diff --git a/cli/README.md b/cli/README.mdindex 4e9dbe1e..fdabd356 100644--- a/cli/README.md+++ b/cli/README.md@@ -15,7 +15,7 @@ Then run:```bash> $ check_if_email_exists --help-check-if-email-exists-cli 0.9.1+check-if-email-exists-cliCheck if an email address exists without sending any email.USAGE:@@ -34,8 +34,8 @@ OPTIONS:--gmail-verif-method <GMAIL_VERIF_METHOD>- Select how to verify Gmail email addresses: Api or Smtp [env: GMAIL_VERIF_METHOD=]- [default: Smtp]+ Select how to verify Gmail email addresses: api or smtp [env: GMAIL_VERIF_METHOD=]+ [default: smtp]-h, --helpPrint help information@@ -46,9 +46,13 @@ OPTIONS:--hello-name <HELLO_NAME>The name to use in the `EHLO:` SMTP command [env: HELLO_NAME=] [default: gmail.com]- --hotmail-verif-method <HOTMAIL_VERIF_METHOD>- Select how to verify Hotmail email addresses: Api, Headless or Smtp [env:- HOTMAIL_VERIF_METHOD=] [default: Headless]+ --hotmailb2b-verif-method <HOTMAILB2B_VERIF_METHOD>+ Select how to verify Hotmail B2B email addresses: smtp [env: HOTMAILB2B_VERIF_METHOD=]+ [default: smtp]++ --hotmailb2c-verif-method <HOTMAILB2C_VERIF_METHOD>+ Select how to verify Hotmail B2C email addresses: headless or smtp [env:+ HOTMAILB2C_VERIF_METHOD=] [default: headless]--proxy-host <PROXY_HOST>Use the specified SOCKS5 proxy host to perform email verification [env: PROXY_HOST=]@@ -72,8 +76,9 @@ OPTIONS:Print version information--yahoo-verif-method <YAHOO_VERIF_METHOD>- Select how to verify Yahoo email addresses: Api, Headless or Smtp [env:- YAHOO_VERIF_METHOD=] [default: Headless]+ Select how to verify Yahoo email addresses: api, headless or smtp [env:+ YAHOO_VERIF_METHOD=] [default: headless]+```**💡 PRO TIP:** To show debug logs when running the binary, run:diff --git a/cli/src/main.rs b/cli/src/main.rsindex f9adb842..56007903 100644--- a/cli/src/main.rs+++ b/cli/src/main.rs@@ -16,7 +16,7 @@use check_if_email_exists::{check_email, config::ReacherConfig, CheckEmailInputBuilder, CheckEmailInputProxy,- GmailVerifMethod, HotmailVerifMethod, YahooVerifMethod,+ GmailVerifMethod, HotmailB2BVerifMethod, HotmailB2CVerifMethod, YahooVerifMethod,};use clap::Parser;use once_cell::sync::Lazy;@@ -56,17 +56,21 @@ pub struct Cli {#[clap(long, env, default_value = "25")]pub smtp_port: u16,- /// Select how to verify Yahoo email addresses: Api, Headless or Smtp.- #[clap(long, env, default_value = "Headless", parse(try_from_str))]+ /// Select how to verify Yahoo email addresses: api, headless or smtp.+ #[clap(long, env, default_value = "headless", parse(try_from_str))]pub yahoo_verif_method: YahooVerifMethod,- /// Select how to verify Gmail email addresses: Api or Smtp.- #[clap(long, env, default_value = "Smtp", parse(try_from_str))]+ /// Select how to verify Gmail email addresses: api or smtp.+ #[clap(long, env, default_value = "smtp", parse(try_from_str))]pub gmail_verif_method: GmailVerifMethod,- /// Select how to verify Hotmail email addresses: Api, Headless or Smtp.- #[clap(long, env, default_value = "Headless", parse(try_from_str))]- pub hotmail_verif_method: HotmailVerifMethod,+ /// Select how to verify Hotmail B2B email addresses: smtp.+ #[clap(long, env, default_value = "smtp", parse(try_from_str))]+ pub hotmailb2b_verif_method: HotmailB2BVerifMethod,++ /// Select how to verify Hotmail B2C email addresses: headless or smtp.+ #[clap(long, env, default_value = "headless", parse(try_from_str))]+ pub hotmailb2c_verif_method: HotmailB2CVerifMethod,/// Whether to check if a gravatar image is existing for the given email.#[clap(long, env, default_value = "false", parse(try_from_str))]@@ -84,7 +88,7 @@ pub struct Cli {pub(crate) static CONF: Lazy<Cli> = Lazy::new(Cli::parse);#[tokio::main]-async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {+async fn main() -> Result<(), anyhow::Error> {env_logger::init();let to_email = &CONF.to_email;@@ -97,7 +101,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {.smtp_port(CONF.smtp_port).yahoo_verif_method(CONF.yahoo_verif_method).gmail_verif_method(CONF.gmail_verif_method)- .hotmail_verif_method(CONF.hotmail_verif_method)+ .hotmailb2b_verif_method(CONF.hotmailb2b_verif_method)+ .hotmailb2c_verif_method(CONF.hotmailb2c_verif_method).check_gravatar(CONF.check_gravatar).haveibeenpwned_api_key(CONF.haveibeenpwned_api_key.clone());diff --git a/core/Cargo.toml b/core/Cargo.tomlindex 4c2593d6..6090fb49 100644--- a/core/Cargo.toml+++ b/core/Cargo.toml@@ -1,6 +1,6 @@[package]name = "check-if-email-exists"-version = "0.9.1"+version = "0.10.0"authors = ["Amaury <[email protected]>"]categories = ["email"]description = "Check if an email address exists without sending any email"@@ -36,6 +36,7 @@ reqwest = { version = "0.12.5", features = ["json", "socks"] }sentry = { version = "0.23", optional = true }serde = { version = "1.0.214", features = ["derive"] }serde_json = "1.0.124"+thiserror = "1.0"tracing = "0.1.40"[dev-dependencies]diff --git a/core/src/lib.rs b/core/src/lib.rsindex 6afb4994..9a55076d 100644--- a/core/src/lib.rs+++ b/core/src/lib.rs@@ -85,6 +85,7 @@ use misc::{check_misc, MiscDetails};use mx::check_mx;use rand::Rng;use smtp::{check_smtp, SmtpDetails, SmtpError};+pub use smtp::{is_gmail, is_hotmail, is_hotmail_b2b, is_hotmail_b2c, is_yahoo};use std::time::{Duration, SystemTime};use syntax::{check_syntax, get_similar_mail_provider};pub use util::input_output::*;diff --git a/core/src/mx/mod.rs b/core/src/mx/mod.rsindex 3e18f7c6..f044eee3 100644--- a/core/src/mx/mod.rs+++ b/core/src/mx/mod.rs@@ -14,8 +14,6 @@// 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::io;-use crate::syntax::SyntaxDetails;use crate::util::ser_with_display::ser_with_display;use hickory_resolver::error::{ResolveError, ResolveErrorKind};@@ -23,6 +21,8 @@ use hickory_resolver::lookup::MxLookup;use hickory_resolver::system_conf::read_system_conf;use hickory_resolver::TokioAsyncResolver;use serde::{ser::SerializeMap, Serialize, Serializer};+use std::io;+use thiserror::Error;/// Details about the MX lookup.#[derive(Debug)]@@ -69,14 +69,16 @@ impl Serialize for MxDetails {}/// Errors that can happen on MX lookups.-#[derive(Debug, Serialize)]+#[derive(Debug, Error, Serialize)]#[serde(tag = "type", content = "message")]pub enum MxError {/// Error with IO.#[serde(serialize_with = "ser_with_display")]+ #[error("IO error: {0}")]IoError(io::Error),/// Error while resolving MX lookups.#[serde(serialize_with = "ser_with_display")]+ #[error("Resolve error: {0}")]ResolveError(Box<ResolveError>),}diff --git a/core/src/smtp/gmail.rs b/core/src/smtp/gmail.rsindex d33399a3..221d2caf 100644--- a/core/src/smtp/gmail.rs+++ b/core/src/smtp/gmail.rs@@ -23,24 +23,19 @@ use crate::{use async_smtp::EmailAddress;use reqwest::Error as ReqwestError;use serde::Serialize;-use std::fmt;+use thiserror::Error;const GLXU_PAGE: &str = "https://mail.google.com/mail/gxlu";/// Possible errors when checking Gmail email addresses.-#[derive(Debug, Serialize)]+#[derive(Debug, Error, Serialize)]pub enum GmailError {/// Error when serializing or deserializing HTTP requests and responses.#[serde(serialize_with = "ser_with_display")]+ #[error("Error serializing or deserializing HTTP requests and responses: {0}")]ReqwestError(ReqwestError),}-impl fmt::Display for GmailError {- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {- write!(f, "{self:?}")- }-}-impl From<ReqwestError> for GmailError {fn from(error: ReqwestError) -> Self {GmailError::ReqwestError(error)@@ -49,7 +44,7 @@ impl From<ReqwestError> for GmailError {/// Use HTTP request to verify if a Gmail email address exists./// See: <https://blog.0day.rocks/abusing-gmail-to-get-previously-unlisted-e-mail-addresses-41544b62b2>-pub async fn check_gmail(+pub async fn check_gmail_via_api(to_email: &EmailAddress,input: &CheckEmailInput,) -> Result<SmtpDetails, GmailError> {@@ -98,7 +93,7 @@ mod tests {.build().unwrap();- let smtp_details = check_gmail(&to_email, &input).await;+ let smtp_details = check_gmail_via_api(&to_email, &input).await;assert!(smtp_details.is_ok());assert!(smtp_details.unwrap().is_deliverable);diff --git a/core/src/smtp/mod.rs b/core/src/smtp/mod.rsindex 4efe44c6..c6d7c49d 100644--- a/core/src/smtp/mod.rs+++ b/core/src/smtp/mod.rs@@ -32,14 +32,14 @@ use serde::{Deserialize, Serialize};use crate::{config::ReacherConfig, util::input_output::CheckEmailInput, GmailVerifMethod,- HotmailVerifMethod, YahooVerifMethod,+ HotmailB2CVerifMethod, YahooVerifMethod,};use connect::check_smtp_with_retry;pub use error::*;-use self::{+pub use self::{gmail::is_gmail,- outlook::{is_hotmail, is_microsoft365},+ outlook::{is_hotmail, is_hotmail_b2b, is_hotmail_b2c},yahoo::is_yahoo,};@@ -98,94 +98,62 @@ pub async fn check_smtp(input: &CheckEmailInput,config: &ReacherConfig,) -> (Result<SmtpDetails, SmtpError>, SmtpDebug) {- let host = host.to_string();+ let host_str = host.to_string();let to_email_str = to_email.to_string();- if is_hotmail(&host) {- match (&input.hotmail_verif_method, is_microsoft365(&host)) {- (HotmailVerifMethod::OneDriveApi, true) => {- match outlook::microsoft365::check_microsoft365_api(to_email, input).await {- Ok(Some(smtp_details)) => {- return {- (- Ok(smtp_details),- SmtpDebug {- verif_method: VerifMethod::Api,- },- )- }- }- // Continue in the event of an error/ambiguous result.- Err(err) => {- return (- Err(err.into()),- SmtpDebug {- verif_method: VerifMethod::Api,- },- );- }- _ => {}- }- }-- (HotmailVerifMethod::Headless, false) => {- return (- outlook::headless::check_password_recovery(- to_email.to_string().as_str(),- &config.webdriver_addr,- )+ if is_hotmail_b2c(&host_str) {+ if let HotmailB2CVerifMethod::Headless = &input.hotmailb2c_verif_method {+ return (+ outlook::headless::check_password_recovery(&to_email_str, &config.webdriver_addr).await- .map_err(|err| err.into()),- SmtpDebug {- verif_method: VerifMethod::Headless,- },- );- }- _ => {}- };- } else if is_gmail(&host) {+ .map_err(Into::into),+ SmtpDebug {+ verif_method: VerifMethod::Headless,+ },+ );+ }+ } else if is_gmail(&host_str) {if let GmailVerifMethod::Api = &input.gmail_verif_method {return (- gmail::check_gmail(to_email, input)+ gmail::check_gmail_via_api(to_email, input).await- .map_err(|err| err.into()),+ .map_err(Into::into),SmtpDebug {verif_method: VerifMethod::Api,},);- };- } else if is_yahoo(&host) {+ }+ } else if is_yahoo(&host_str) {match &input.yahoo_verif_method {YahooVerifMethod::Api => {return (yahoo::check_api(&to_email_str, input).await- .map_err(|e| e.into()),+ .map_err(Into::into),SmtpDebug {verif_method: VerifMethod::Api,},- )+ );}-YahooVerifMethod::Headless => {return (yahoo::check_headless(&to_email_str, &config.webdriver_addr).await- .map_err(|e| e.into()),+ .map_err(Into::into),SmtpDebug {verif_method: VerifMethod::Headless,},- )+ );}- _ => {}- };+ _ => {} // For everything else, we use SMTP+ }}(- check_smtp_with_retry(to_email, &host, port, domain, input, input.retries).await,+ check_smtp_with_retry(to_email, &host_str, port, domain, input, input.retries).await,SmtpDebug {verif_method: VerifMethod::Smtp(SmtpConnection {- host,+ host: host_str,port,used_proxy: input.proxy.is_some(),}),diff --git a/core/src/smtp/outlook/mod.rs b/core/src/smtp/outlook/mod.rsindex 4fae77f7..5d3386c0 100644--- a/core/src/smtp/outlook/mod.rs+++ b/core/src/smtp/outlook/mod.rs@@ -12,16 +12,21 @@ pub mod microsoft365;/// - *@hotmail.fr -> `eur.olc.protection.outlook.com.`/// - *@hotmail.nl -> `eur.olc.protection.outlook.com.`///-/// But Microsoft 365 addresses end with "mail.protection.outlook.com."+/// But Microsoft 365 (B2B) addresses end with "mail.protection.outlook.com."////// TL;DR:-/// - @outlook.* and @hotmail.* -> end with ".olc.protection.outlook.com."-/// - Microsoft 365 emails -> end with ".mail.protection.outlook.com."+/// - B2C emails -> end with ".olc.protection.outlook.com."+/// - B2B emails -> end with ".mail.protection.outlook.com."pub fn is_hotmail(host: &str) -> bool {host.to_lowercase().ends_with(".protection.outlook.com.")}-/// Check if an address is a Microsoft365 email address.-pub fn is_microsoft365(host: &str) -> bool {+/// Check if an address is a Hotmail B2B email address.+pub fn is_hotmail_b2b(host: &str) -> bool {is_hotmail(host) && !host.ends_with(".olc.protection.outlook.com.")}++/// Check if an address is a Hotmail B2C email address.+pub fn is_hotmail_b2c(host: &str) -> bool {+ is_hotmail(host) && host.ends_with(".olc.protection.outlook.com.")+}diff --git a/core/src/smtp/yahoo/mod.rs b/core/src/smtp/yahoo/mod.rsindex 977df9af..eaf9194a 100644--- a/core/src/smtp/yahoo/mod.rs+++ b/core/src/smtp/yahoo/mod.rs@@ -22,36 +22,33 @@ use crate::util::ser_with_display::ser_with_display;use reqwest::Error as ReqwestError;use serde::Serialize;use serde_json::error::Error as SerdeError;-use std::fmt;+use thiserror::Error;pub use api::check_api;-pub use headless::check_headless;/// Possible errors when checking Yahoo email addresses.-#[derive(Debug, Serialize)]+#[derive(Debug, Error, Serialize)]pub enum YahooError {/// Cannot find "acrumb" field in cookie.+ #[error("Cannot find \"acrumb\" field in cookie")]NoAcrumb,/// Cannot find "sessionIndex" hidden input in body+ #[error("Cannot find \"sessionIndex\" hidden input in body")]NoSessionIndex,/// Cannot find cookie in Yahoo response.+ #[error("Cannot find cookie in Yahoo response")]NoCookie,/// Error when serializing or deserializing HTTP requests and responses.#[serde(serialize_with = "ser_with_display")]+ #[error("Error serializing or deserializing HTTP requests and responses: {0}")]ReqwestError(ReqwestError),/// Error when serializing or deserializing HTTP requests and responses.#[serde(serialize_with = "ser_with_display")]+ #[error("Error serializing or deserializing HTTP requests and responses: {0}")]SerdeError(SerdeError),}-impl fmt::Display for YahooError {- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {- // Customize so only `x` and `y` are denoted.- write!(f, "{self:?}")- }-}-impl From<ReqwestError> for YahooError {fn from(error: ReqwestError) -> Self {YahooError::ReqwestError(error)diff --git a/core/src/util/input_output.rs b/core/src/util/input_output.rsindex e66cd775..8a143b72 100644--- a/core/src/util/input_output.rs+++ b/core/src/util/input_output.rs@@ -73,7 +73,7 @@ impl SmtpSecurity {}/// Select how to verify Yahoo emails.-#[derive(Debug, Clone, Copy, Deserialize, Serialize)]+#[derive(Debug, Clone, Copy, Default, PartialEq, Deserialize, Serialize)]pub enum YahooVerifMethod {/// Use Yahoo's API to check if an email exists.Api,@@ -83,6 +83,7 @@ pub enum YahooVerifMethod {/// its endpoint, usually http://localhost:9515, into the environment/// variable RCH_WEBDRIVER_ADDR. We recommend running chromedriver (and not/// geckodriver) as it allows parallel requests.+ #[default]Headless,/// Use Yahoo's SMTP servers to check if an email exists.Smtp,@@ -93,21 +94,21 @@ impl FromStr for YahooVerifMethod {fn from_str(s: &str) -> Result<Self, Self::Err> {match s {- "Api" => Ok(Self::Api),-- "Headless" => Ok(Self::Headless),- "Smtp" => Ok(Self::Smtp),+ "api" => Ok(Self::Api),+ "headless" => Ok(Self::Headless),+ "smtp" => Ok(Self::Smtp),_ => Err(format!("Unknown yahoo verify method: {}", s)),}}}/// Select how to verify Gmail emails.-#[derive(Debug, Clone, Copy, Deserialize, Serialize)]+#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize)]pub enum GmailVerifMethod {/// Use Gmail's API to check if an email exists.Api,/// Use Gmail's SMTP servers to check if an email exists.+ #[default]Smtp,}@@ -116,39 +117,55 @@ impl FromStr for GmailVerifMethod {fn from_str(s: &str) -> Result<Self, Self::Err> {match s {- "Api" => Ok(Self::Api),- "Smtp" => Ok(Self::Smtp),+ "api" => Ok(Self::Api),+ "smtp" => Ok(Self::Smtp),_ => Err(format!("Unknown gmail verify method: {}", s)),}}}-/// Select how to verify Hotmail emails.-#[derive(Debug, Clone, Copy, Deserialize, Serialize)]-pub enum HotmailVerifMethod {- /// Use OneDrive API to check if an email exists.- OneDriveApi,+/// Select how to verify Hotmail B2B emails.+#[derive(Debug, Clone, Copy, Default, PartialEq, Deserialize, Serialize)]+pub enum HotmailB2BVerifMethod {+ /// Use Hotmail's SMTP servers to check if an email exists.+ #[default]+ Smtp,+}++impl FromStr for HotmailB2BVerifMethod {+ type Err = String;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s {+ "smtp" => Ok(Self::Smtp),+ _ => Err(format!("Unknown hotmailb2b verify method: {}", s)),+ }+ }+}++/// Select how to verify Hotmail B2C emails.+#[derive(Debug, Clone, Copy, Default, PartialEq, Deserialize, Serialize)]+pub enum HotmailB2CVerifMethod {/// Use Hotmail's password recovery page to check if an email exists.////// This assumes you have a WebDriver compatible process running, then pass/// its endpoint, usually http://localhost:9515, into the environment/// variable RCH_WEBDRIVER_ADDR. We recommend running chromedriver (and not/// geckodriver) as it allows parallel requests.+ #[default]Headless,/// Use Hotmail's SMTP servers to check if an email exists.Smtp,}-impl FromStr for HotmailVerifMethod {+impl FromStr for HotmailB2CVerifMethod {type Err = String;fn from_str(s: &str) -> Result<Self, Self::Err> {match s {- "OneDriveApi" => Ok(Self::OneDriveApi),-- "Headless" => Ok(Self::Headless),- "Smtp" => Ok(Self::Smtp),- _ => Err(format!("Unknown hotmail verify method: {}", s)),+ "headless" => Ok(Self::Headless),+ "smtp" => Ok(Self::Smtp),+ _ => Err(format!("Unknown hotmailb2c verify method: {}", s)),}}}@@ -193,7 +210,11 @@ pub struct CheckEmailInput {/// Select how to verify Hotmail/Outlook/Microsoft email addresses.////// Defaults to Headless.- pub hotmail_verif_method: HotmailVerifMethod,+ pub hotmailb2b_verif_method: HotmailB2BVerifMethod,+ /// Select how to verify Hotmail/Outlook/Microsoft email addresses.+ ///+ /// Defaults to Headless.+ pub hotmailb2c_verif_method: HotmailB2CVerifMethod,/// Whether to check if a gravatar image is existing for the given email./// Adds a bit of latency to the verification process.///@@ -223,9 +244,10 @@ impl Default for CheckEmailInput {smtp_port: 25,smtp_security: SmtpSecurity::default(),smtp_timeout: Some(Duration::from_secs(30)),- yahoo_verif_method: YahooVerifMethod::Headless,- gmail_verif_method: GmailVerifMethod::Smtp,- hotmail_verif_method: HotmailVerifMethod::Headless,+ yahoo_verif_method: YahooVerifMethod::default(),+ gmail_verif_method: GmailVerifMethod::default(),+ hotmailb2b_verif_method: HotmailB2BVerifMethod::default(),+ hotmailb2c_verif_method: HotmailB2CVerifMethod::default(),check_gravatar: false,haveibeenpwned_api_key: None,retries: 1,diff --git a/docker-compose.local.yaml b/docker-compose.local.yamlnew file mode 100644index 00000000..af695d89--- /dev/null+++ b/docker-compose.local.yaml@@ -0,0 +1,66 @@+# Same as docker-compose.yaml but with the backend image version set to build+# from the local Dockerfile. This is useful for development purposes.+version: "3.8"++services:+ rabbitmq:+ image: rabbitmq:4.0-management+ container_name: rabbitmq+ ports:+ - "5672:5672"+ - "15672:15672"+ environment:+ RABBITMQ_DEFAULT_USER: guest+ RABBITMQ_DEFAULT_PASS: guest+ restart: always++ postgres:+ image: postgres:14+ container_name: postgres+ ports:+ - "5432:5432"+ environment:+ POSTGRES_USER: postgres+ POSTGRES_PASSWORD: postgres+ POSTGRES_DB: reacher_db+ volumes:+ - ./backend/postgres_data:/var/lib/postgresql/data+ restart: always++ worker1:+ build:+ context: .+ dockerfile: backend/Dockerfile+ container_name: worker1+ ports:+ - "8080:8080"+ depends_on:+ - postgres+ - rabbitmq+ environment:+ RCH__BACKEND_NAME: worker1+ RUST_LOG: reacher=info+ RCH__HTTP_HOST: 0.0.0.0+ RCH__WORKER__ENABLE: true+ RCH__WORKER__RABBITMQ__URL: amqp://guest:guest@rabbitmq:5672+ RCH__WORKER__POSTGRES__DB_URL: postgres://postgres:postgres@postgres:5432/reacher_db+ restart: always++ worker2:+ build:+ context: .+ dockerfile: backend/Dockerfile+ container_name: worker2+ ports:+ - "8081:8080"+ depends_on:+ - postgres+ - rabbitmq+ environment:+ RCH__BACKEND_NAME: worker2+ RUST_LOG: reacher=info+ RCH__HTTP_HOST: 0.0.0.0+ RCH__WORKER__ENABLE: true+ RCH__WORKER__RABBITMQ__URL: amqp://guest:guest@rabbitmq:5672+ RCH__WORKER__POSTGRES__DB_URL: postgres://postgres:postgres@postgres:5432/reacher_db+ restart: alwaysdiff --git a/docker-compose.yaml b/docker-compose.yamlindex 3402f5c0..24bd3458 100644--- a/docker-compose.yaml+++ b/docker-compose.yaml@@ -10,43 +10,49 @@ services:environment:RABBITMQ_DEFAULT_USER: guestRABBITMQ_DEFAULT_PASS: guest+ restart: alwayspostgres:- image: postgres:17+ image: postgres:14container_name: postgresports:- "5432:5432"environment:POSTGRES_USER: postgresPOSTGRES_PASSWORD: postgres- POSTGRES_DB: reacher_worker_db+ POSTGRES_DB: reacher_db+ restart: alwaysworker1:- build:- context: .- dockerfile: docker/Dockerfile.worker+ image: reacherhq/backend:v0.10.0-beta.0container_name: worker1+ ports:+ - "8080:8080"depends_on:- postgres- rabbitmqenvironment:- RCH_NAME: worker1- RCH_RABBITMQ_URL: amqp://guest:guest@rabbitmq:5672- RCH_RABBITMQ_QUEUE: check.Headless.*- RCH_DB_URL: postgres://postgres:postgres@postgres:5432/reacher_worker_db+ RCH__BACKEND_NAME: worker1+ RUST_LOG: reacher=info+ RCH__HTTP_HOST: 0.0.0.0+ RCH__WORKER__ENABLE: true+ RCH__WORKER__RABBITMQ__URL: amqp://guest:guest@rabbitmq:5672+ RCH__WORKER__POSTGRES__DB_URL: postgres://postgres:postgres@postgres:5432/reacher_dbrestart: alwaysworker2:- build:- context: .- dockerfile: docker/Dockerfile.worker+ image: reacherhq/backend:v0.10.0-beta.0container_name: worker2+ ports:+ - "8081:8080"depends_on:- postgres- rabbitmqenvironment:- RCH_NAME: worker2- RCH_RABBITMQ_URL: amqp://guest:guest@rabbitmq:5672- RCH_RABBITMQ_QUEUE: check.*- RCH_DB_URL: postgres://postgres:postgres@postgres:5432/reacher_worker_db+ RCH__BACKEND_NAME: worker2+ RUST_LOG: reacher=info+ RCH__HTTP_HOST: 0.0.0.0+ RCH__WORKER__ENABLE: true+ RCH__WORKER__RABBITMQ__URL: amqp://guest:guest@rabbitmq:5672+ RCH__WORKER__POSTGRES__DB_URL: postgres://postgres:postgres@postgres:5432/reacher_dbrestart: alwaysdiff --git a/worker/.env.example b/worker/.env.exampledeleted file mode 100644index 41ef7540..00000000--- a/worker/.env.example+++ /dev/null@@ -1,8 +0,0 @@-# Copy this file to .env-# ```bash-# cp .env.example .env-# ```-#-# Then tweak the values to match your desired config.--DATABASE_URL=postgresql://localhost:5432/reacher_worker_dbdiff --git a/worker/Cargo.toml b/worker/Cargo.tomldeleted file mode 100644index 627cda59..00000000--- a/worker/Cargo.toml+++ /dev/null@@ -1,30 +0,0 @@-[package]-name = "reacher_worker"-version = "0.1.0"-edition = "2021"--[dependencies]-config = { version = "0.14.0", features = ["toml"] }-futures-lite = "2.3.0"-lapin = { version = "2.3.1" }-tokio-executor-trait = { version = "2.1.1" }-tokio-reactor-trait = { version = "1.1.0" }-async-smtp = "0.6"-check-if-email-exists = { path = "../core", features = ["sentry"] }-openssl = { version = "0.10.64", features = ["vendored"] }-reqwest = { version = "0.12.5", features = ["json", "socks"] }-sentry = "0.23"-serde = { version = "1.0", features = ["derive"] }-serde_json = "1.0"-sqlx = { version = "0.7", features = [- "runtime-tokio-native-tls",- "postgres",- "uuid",- "chrono",- "json",- "migrate",-] }-sqlxmq = "0.5"-tokio = { version = "1.35", features = ["macros"] }-tracing = "0.1.40"-tracing-subscriber = "0.3.18"diff --git a/worker/README.md b/worker/README.mddeleted file mode 100644index 1bd732aa..00000000--- a/worker/README.md+++ /dev/null@@ -1,28 +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 Task Queue</h1>-<h4 align="center">Architecture for distributing tasks from a queue to multiple Reacher workers.</h4>--<br /><br />--## Get Started--The easiest way to get started is with Docker Compose. This setup runs one queue and two Reacher Workers. From the **root** folder, run:--```bash-docker compose up --build-# Wait for everything to run correctly-```--Then, publish some email verification requests to the RabbitMQ queue:--```bash-cd worker-cargo run -p reacher_worker --bin publish_message <email1> <email2> ...-```--The Docker Compose logs will show the two workers sharing the email verifications. You may ask [email protected] about other methods for publishing messages to this queue (JavaScript, Python...).diff --git a/worker/migrations/20240929230957_init.sql b/worker/migrations/20240929230957_init.sqldeleted file mode 100644index 479f6dbf..00000000--- a/worker/migrations/20240929230957_init.sql+++ /dev/null@@ -1,9 +0,0 @@--- Add migration script here-CREATE TABLE reacher_results (- id SERIAL NOT NULL PRIMARY KEY,- payload jsonb NOT NULL,- worker TEXT NOT NULL,- result jsonb,- error TEXT,- created_at TIMESTAMPTZ DEFAULT NOW()-);diff --git a/worker/migrations/README.md b/worker/migrations/README.mddeleted file mode 100644index c7b70443..00000000--- a/worker/migrations/README.md+++ /dev/null@@ -1,11 +0,0 @@-# Database and Migrations--## Migrations--All migrations in this folder are embedded directly in the `reacher_backend` binary, so you don't need to run the migrations manually.--## Advanced Usage--For more advanced usage (such as reverting to an old state), please use the `sqlx` CLI command.--See https://github.com/launchbadge/sqlx/blob/main/sqlx-cli/README.mddiff --git a/worker/src/bin/publish_message.rs b/worker/src/bin/publish_message.rsdeleted file mode 100644index 3855cfd9..00000000--- a/worker/src/bin/publish_message.rs+++ /dev/null@@ -1,40 +0,0 @@-use check_if_email_exists::CheckEmailInput;-use lapin::{options::*, BasicProperties};-use reacher_worker::check_email::WorkerPayload;-use reacher_worker::config::load_config;-use reacher_worker::worker::setup_rabbit_mq;-use std::env;--#[tokio::main]-async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {- let worker_config = load_config()?;- let channel = setup_rabbit_mq(&worker_config).await?;-- let payloads: Vec<WorkerPayload> = env::args()- .skip(1) // Path to the binary- .map(|s| WorkerPayload {- input: CheckEmailInput {- to_email: s,- ..Default::default()- },- extra: None,- })- .collect();-- for payload in payloads {- let payload_bz = serde_json::to_vec(&payload)?;- channel- .basic_publish(- "",- "check.*",- BasicPublishOptions::default(),- &payload_bz,- BasicProperties::default(),- )- .await?;-- println!("Published message: {:?}", payload.input.to_email);- }-- Ok(())-}diff --git a/worker/src/check_email.rs b/worker/src/check_email.rsdeleted file mode 100644index dd2bfeba..00000000--- a/worker/src/check_email.rs+++ /dev/null@@ -1,129 +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/>.--use crate::config::WorkerConfig;-use crate::db::save_to_db;-use check_if_email_exists::config::ReacherConfig;-use check_if_email_exists::{check_email, CheckEmailInput, CheckEmailOutput};-use check_if_email_exists::{Reachable, LOG_TARGET};-use lapin::message::Delivery;-use lapin::{options::*, BasicProperties, Channel};-use serde::{Deserialize, Serialize};-use sqlx::PgPool;-use std::fmt::Debug;-use std::sync::Arc;-use tracing::{debug, info};--#[derive(Debug, Deserialize, Serialize)]-pub struct WorkerPayload {- pub input: CheckEmailInput,- pub extra: Option<serde_json::Value>,-}--#[derive(Debug, Serialize)]-struct WebhookOutput<'a> {- output: &'a CheckEmailOutput,- extra: &'a Option<serde_json::Value>,-}--/// Processes the check email task asynchronously.-pub async fn process_queue_message(- payload: &WorkerPayload,- delivery: Delivery,- channel: Arc<Channel>,- pg_pool: PgPool,- config: WorkerConfig,-) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {- let worker_output = process_check_email(payload, delivery, channel, config.clone()).await;- save_to_db(pg_pool, config, payload, worker_output).await-}--async fn process_check_email(- payload: &WorkerPayload,- delivery: Delivery,- channel: Arc<Channel>,- config: WorkerConfig,-) -> Result<CheckEmailOutput, Box<dyn std::error::Error + Send + Sync>> {- info!(target: LOG_TARGET, email=payload.input.to_email, "Start email verification");-- let reacher_config = ReacherConfig {- backend_name: config.name.clone(),- ..Default::default()- };- let output = check_email(&payload.input, &reacher_config).await;- let reply_payload = serde_json::to_string(&output)?;- let reply_payload = reply_payload.as_bytes();-- // Send reply by following this guide:- // https://www.rabbitmq.com/tutorials/tutorial-six-javascript.html- if let (Some(reply_to), Some(correlation_id)) = (- delivery.properties.reply_to(),- delivery.properties.correlation_id(),- ) {- let properties = BasicProperties::default()- .with_correlation_id(correlation_id.to_owned())- .with_content_type("application/json".into());-- channel- .basic_publish(- "",- reply_to.as_str(),- BasicPublishOptions::default(),- reply_payload,- properties,- )- .await?- .await?;-- debug!(target: LOG_TARGET, reply_to=?reply_to, correlation_id=?correlation_id, "Sent reply")- }-- // Check if we have a webhook to send the output to.- if let Some(webhook_url) = &config.webhook.url {- let webhook_output = WebhookOutput {- output: &output,- extra: &payload.extra,- };-- let client = reqwest::Client::new();- let res = client- .post(webhook_url)- .json(&webhook_output)- .header("x-reacher-secret", std::env::var("RCH_HEADER_SECRET")?)- .send()- .await?- .text()- .await?;- debug!(target: LOG_TARGET, email=?webhook_output.output.input,res=?res, "Received webhook response");- }-- let is_reachable = output.is_reachable.to_owned();-- // If is_reachable is unknown, then we requeue the message, but only once.- // We might want to add a requeue counter in the future, see:- // https://stackoverflow.com/questions/25226080/rabbitmq-how-to-requeue-message-with-counter- if is_reachable == Reachable::Unknown && !delivery.redelivered {- delivery- .reject(BasicRejectOptions { requeue: true })- .await?;- info!(target: LOG_TARGET, email=?&payload.input.to_email, "Requeued message");- } else {- delivery.ack(BasicAckOptions::default()).await?;- info!(target: LOG_TARGET, email=output.input, is_reachable=?output.is_reachable, "Done check");- }-- Ok(output)-}diff --git a/worker/src/config.rs b/worker/src/config.rsdeleted file mode 100644index edaca92f..00000000--- a/worker/src/config.rs+++ /dev/null@@ -1,162 +0,0 @@-use check_if_email_exists::SentryConfig;-use config::Config;-use serde::de::{self, Deserializer, Visitor};-use serde::Deserialize;-use std::fmt;--#[derive(Debug, Deserialize, Clone)]-pub struct WorkerConfig {- /// Name of the worker.- pub name: String,- pub rabbitmq: RabbitMQConfig,- pub throttle: ThrottleConfig,- pub db: DBConfig,- pub webhook: WebhookConfig,- pub sentry: SentryConfig,-}--#[derive(Debug, Deserialize, Clone)]-pub struct RabbitMQConfig {- pub url: String,- /// Queue name to consume messages from.- ///- /// The queue name MUST be one of the following:- /// - "check.Smtp.gmail": verifies any Gmail email, using SMTP.- /// - "check.Smtp.yahoo": verifies any Yahoo email, using SMTP.- /// - "check.Smtp.hotmail.b2b": verifies any B2B Hotmail email, using SMTP.- /// - "check.Smtp.hotmail.b2c": verifies any B2C Hotmail email (@outlook, @live, @hotmail), using SMTP.- /// - "check.Smtp.hotmail.*": verifies any Hotmail email, using SMTP.- /// - "check.Smtp.*": verifies any email, using SMTP.- /// - "check.Headless.yahoo": verifies any Yahoo email, using a headless browser.- /// - "check.Headless.hotmail.b2c": verifies any B2C Hotmail email (@outlook, @live, @hotmail) email, using a headless browser.- /// - "check.Headless.*": verifies any email, using a headless browser.- /// - "check.*": verifies any email, using the default method.- pub queue: Queue,- pub concurrency: u16,-}--/// Queue names that the worker can consume from.-#[derive(Debug, Clone)]-pub enum Queue {- /// Verifies any Gmail email, using SMTP.- SmtpGmail,- /// Verifies any Yahoo email, using SMTP.- SmtpYahoo,- /// Verifies any B2B Hotmail email, using SMTP.- SmtpHotmailB2B,- /// Verifies any B2C Hotmail email (@outlook, @live, @hotmail), using SMTP.- SmtpHotmailB2C,- /// Verifies any Hotmail email, using SMTP.- SmtpHotmailAll,- /// Verifies any email, using SMTP.- SmtpAll,- /// Verifies any Yahoo email, using a headless browser.- HeadlessYahoo,- /// Verifies any B2C Hotmail email (@outlook, @live, @hotmail) email, using a headless browser.- HeadlessHotmailB2C,- /// Verifies any email, using a headless browser.- HeadlessAll,- /// Verifies any email, using the default method.- All,-}--impl fmt::Display for Queue {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- match self {- Queue::SmtpGmail => write!(f, "check.Smtp.gmail"),- Queue::SmtpYahoo => write!(f, "check.Smtp.yahoo"),- Queue::SmtpHotmailB2B => write!(f, "check.Smtp.hotmail.b2b"),- Queue::SmtpHotmailB2C => write!(f, "check.Smtp.hotmail.b2c"),- Queue::SmtpHotmailAll => write!(f, "check.Smtp.hotmail.*"),- Queue::SmtpAll => write!(f, "check.Smtp.*"),- Queue::HeadlessYahoo => write!(f, "check.Headless.yahoo"),- Queue::HeadlessHotmailB2C => write!(f, "check.Headless.hotmail.b2c"),- Queue::HeadlessAll => write!(f, "check.Headless.*"),- Queue::All => write!(f, "check.*"),- }- }-}--// Implement Deserialize for the Queue enum-impl<'de> Deserialize<'de> for Queue {- fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>- where- D: Deserializer<'de>,- {- struct QueueVisitor;-- impl<'de> Visitor<'de> for QueueVisitor {- type Value = Queue;-- fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {- formatter.write_str("a valid queue string")- }-- fn visit_str<E>(self, value: &str) -> Result<Queue, E>- where- E: de::Error,- {- match value {- "check.Smtp.gmail" => Ok(Queue::SmtpGmail),- "check.Smtp.yahoo" => Ok(Queue::SmtpYahoo),- "check.Smtp.hotmail.b2b" => Ok(Queue::SmtpHotmailB2B),- "check.Smtp.hotmail.b2c" => Ok(Queue::SmtpHotmailB2C),- "check.Smtp.hotmail.*" => Ok(Queue::SmtpHotmailAll),- "check.Smtp.*" => Ok(Queue::SmtpAll),- "check.Headless.yahoo" => Ok(Queue::HeadlessYahoo),- "check.Headless.hotmail.b2c" => Ok(Queue::HeadlessHotmailB2C),- "check.Headless.*" => Ok(Queue::HeadlessAll),- "check.*" => Ok(Queue::All),- _ => Err(de::Error::unknown_variant(- value,- &[- "check.Smtp.gmail",- "check.Smtp.yahoo",- "check.Smtp.hotmail.b2b",- "check.Smtp.hotmail.b2c",- "check.Smtp.hotmail.*",- "check.Smtp.*",- "check.Headless.yahoo",- "check.Headless.hotmail.b2c",- "check.Headless.*",- "check.*",- ],- )),- }- }- }-- deserializer.deserialize_str(QueueVisitor)- }-}--#[derive(Debug, Deserialize, Clone)]-pub struct ThrottleConfig {- pub max_requests_per_second: Option<u32>,- pub max_requests_per_minute: Option<u32>,- pub max_requests_per_hour: Option<u32>,- pub max_requests_per_day: Option<u32>,-}--#[derive(Debug, Deserialize, Clone)]-pub struct DBConfig {- pub url: String,-}--#[derive(Debug, Deserialize, Clone)]-pub struct WebhookConfig {- pub url: Option<String>,-}--/// Load the worker configuration from the worker_config.toml file and from the-/// environment.-pub fn load_config() -> Result<WorkerConfig, config::ConfigError> {- let cfg = Config::builder()- .add_source(config::File::with_name("worker_config"))- .add_source(config::Environment::with_prefix("RCH").separator("_"))- .build()?;-- let cfg = cfg.try_deserialize::<WorkerConfig>()?;-- Ok(cfg)-}diff --git a/worker/src/db.rs b/worker/src/db.rsdeleted file mode 100644index 9b5610fa..00000000--- a/worker/src/db.rs+++ /dev/null@@ -1,82 +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/>.--use check_if_email_exists::{CheckEmailOutput, LOG_TARGET};-use sqlx::{postgres::PgPoolOptions, PgPool};-use tracing::{debug, info};--use crate::{check_email::WorkerPayload, config::WorkerConfig};--pub async fn save_to_db(- pg_pool: PgPool,- config: WorkerConfig,- payload: &WorkerPayload,- worker_output: Result<CheckEmailOutput, Box<dyn std::error::Error + Send + Sync>>,-) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {- let payload_json = serde_json::to_value(payload)?;-- match worker_output {- Ok(output) => {- let output_json = serde_json::to_value(output)?;-- sqlx::query!(- r#"- INSERT INTO reacher_results (payload, worker, result)- VALUES ($1, $2, $3)- RETURNING id- "#,- payload_json,- config.name,- output_json,- )- .fetch_one(&pg_pool)- .await?;- }- Err(err) => {- sqlx::query!(- r#"- INSERT INTO reacher_results (payload, worker, error)- VALUES ($1, $2, $3)- RETURNING id- "#,- payload_json,- config.name,- err.to_string(),- )- .fetch_one(&pg_pool)- .await?;- }- }-- debug!(target: LOG_TARGET, email=?payload.input.to_email, "Wrote to DB");-- Ok(())-}--/// Create a DB pool.-pub async fn create_db(config: &WorkerConfig) -> Result<PgPool, sqlx::Error> {- debug!(target: LOG_TARGET, "Connecting to DB... {db_url}", db_url=config.db.url);- // 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().connect(&config.db.url).await?;-- sqlx::migrate!("./migrations").run(&pool).await?;-- info!(target: LOG_TARGET, table="email_results", "Connected to DB, Reacher will write results to DB");-- Ok(pool)-}diff --git a/worker/src/main.rs b/worker/src/main.rsdeleted file mode 100644index 9cd3413c..00000000--- a/worker/src/main.rs+++ /dev/null@@ -1,41 +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/>.--//! Main entry point of the `reacher_backend` binary. It has two `main`-//! functions, depending on whether the `bulk` feature is enabled or not.--use check_if_email_exists::{setup_sentry, LOG_TARGET};-use reacher_worker::config::load_config;-use reacher_worker::db::create_db;-use reacher_worker::worker::run_worker;-use reacher_worker::CARGO_PKG_VERSION;-use tracing::info;--#[tokio::main]-async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {- // Initialize logging.- tracing_subscriber::fmt::init();- info!(target: LOG_TARGET, version=?CARGO_PKG_VERSION, "Running Reacher Worker");-- let config = load_config()?;-- // Setup sentry bug tracking.- let _guard: sentry::ClientInitGuard = setup_sentry(&config.sentry);-- let pg_pool = create_db(&config).await?;-- run_worker(config, pg_pool).await-}diff --git a/worker/src/worker.rs b/worker/src/worker.rsdeleted file mode 100644index a7aacba9..00000000--- a/worker/src/worker.rs+++ /dev/null@@ -1,200 +0,0 @@-use crate::check_email::process_queue_message;-use crate::check_email::WorkerPayload;-use crate::config::WorkerConfig;-use check_if_email_exists::LOG_TARGET;-use futures_lite::stream::StreamExt;-use lapin::{options::*, types::FieldTable, Channel, Connection, ConnectionProperties};-use sqlx::PgPool;-use std::sync::Arc;-use std::time::Duration;-use std::time::Instant;-use tokio::time::sleep;-use tracing::{error, info};--pub async fn setup_rabbit_mq(config: &WorkerConfig) -> Result<Channel, lapin::Error> {- let options = ConnectionProperties::default()- // Use tokio executor and reactor.- .with_executor(tokio_executor_trait::Tokio::current())- .with_reactor(tokio_reactor_trait::Tokio)- .with_connection_name(config.name.clone().into());-- let conn = Connection::connect(&config.rabbitmq.url, options).await?;- let channel = conn.create_channel().await?;-- info!(target: LOG_TARGET, backend=?config.name,state=?conn.status().state(), "Connected to AMQP broker");-- let queue_name = config.rabbitmq.queue.to_string();- let mut queue_args = FieldTable::default();- queue_args.insert("x-max-priority".into(), 5.into());-- channel- .queue_declare(- &queue_name,- QueueDeclareOptions {- durable: true,- ..Default::default()- },- queue_args,- )- .await?;-- // Set up prefetch (concurrency) limit using qos- channel- .basic_qos(config.rabbitmq.concurrency, BasicQosOptions::default())- .await?;-- info!(target: LOG_TARGET, queue=?queue_name, "Worker will start consuming messages");-- Ok(channel)-}--pub async fn run_worker(- config: WorkerConfig,- pg_pool: PgPool,-) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {- let channel = Arc::new(setup_rabbit_mq(&config).await?);-- let mut consumer = channel- .basic_consume(- &config.rabbitmq.queue.to_string(),- &config.name,- BasicConsumeOptions::default(),- FieldTable::default(),- )- .await?;-- let mut throttle = Throttle::new();-- // Loop over the incoming messages- while let Some(delivery) = consumer.next().await {- let delivery = delivery?;- let payload = serde_json::from_slice::<WorkerPayload>(&delivery.data)?;- info!(target: LOG_TARGET, email=payload.input.to_email, "New job");-- // Reset throttle counters if needed- throttle.reset_if_needed();-- let config_clone = config.clone();- let channel_clone = channel.clone();- let pg_pool_clone = pg_pool.clone();-- tokio::spawn(async move {- if let Err(e) = process_queue_message(- &payload,- delivery,- channel_clone,- pg_pool_clone,- config_clone,- )- .await- {- error!(target: LOG_TARGET, email=payload.input.to_email, error=?e, "Error processing message");- }- });-- // Increment throttle counters once we spawn the task- throttle.increment_counters();-- // Check if we should throttle before fetching the next message- if let Some(wait_duration) = throttle.should_throttle(&config) {- info!(target: LOG_TARGET, wait=?wait_duration, "Too many requests, throttling");- sleep(wait_duration).await;- continue;- }- }-- Ok(())-}--#[derive(Clone)]-struct Throttle {- requests_per_second: u32,- requests_per_minute: u32,- requests_per_hour: u32,- requests_per_day: u32,- last_reset_second: Instant,- last_reset_minute: Instant,- last_reset_hour: Instant,- last_reset_day: Instant,-}--impl Throttle {- fn new() -> Self {- let now = Instant::now();- Throttle {- requests_per_second: 0,- requests_per_minute: 0,- requests_per_hour: 0,- requests_per_day: 0,- last_reset_second: now,- last_reset_minute: now,- last_reset_hour: now,- last_reset_day: now,- }- }-- fn reset_if_needed(&mut self) {- let now = Instant::now();-- // Reset per-second counter- if now.duration_since(self.last_reset_second) >= Duration::from_secs(1) {- self.requests_per_second = 0;- self.last_reset_second = now;- }-- // Reset per-minute counter- if now.duration_since(self.last_reset_minute) >= Duration::from_secs(60) {- self.requests_per_minute = 0;- self.last_reset_minute = now;- }-- // Reset per-hour counter- if now.duration_since(self.last_reset_hour) >= Duration::from_secs(3600) {- self.requests_per_hour = 0;- self.last_reset_hour = now;- }-- // Reset per-day counter- if now.duration_since(self.last_reset_day) >= Duration::from_secs(86400) {- self.requests_per_day = 0;- self.last_reset_day = now;- }- }-- fn increment_counters(&mut self) {- self.requests_per_second += 1;- self.requests_per_minute += 1;- self.requests_per_hour += 1;- self.requests_per_day += 1;- }-- fn should_throttle(&self, config: &WorkerConfig) -> Option<Duration> {- let now = Instant::now();-- if let Some(max_per_second) = config.throttle.max_requests_per_second {- if self.requests_per_second >= max_per_second {- return Some(Duration::from_secs(1) - now.duration_since(self.last_reset_second));- }- }-- if let Some(max_per_minute) = config.throttle.max_requests_per_minute {- if self.requests_per_minute >= max_per_minute {- return Some(Duration::from_secs(60) - now.duration_since(self.last_reset_minute));- }- }-- if let Some(max_per_hour) = config.throttle.max_requests_per_hour {- if self.requests_per_hour >= max_per_hour {- return Some(Duration::from_secs(3600) - now.duration_since(self.last_reset_hour));- }- }-- if let Some(max_per_day) = config.throttle.max_requests_per_day {- if self.requests_per_day >= max_per_day {- return Some(Duration::from_secs(86400) - now.duration_since(self.last_reset_day));- }- }-- None- }-}diff --git a/worker/worker_config.toml b/worker/worker_config.tomldeleted file mode 100644index d1f3edd3..00000000--- a/worker/worker_config.toml+++ /dev/null@@ -1,35 +0,0 @@-name = "worker1.reacher.dev"--[rabbitmq]-url = "amqp://guest:guest@localhost:5672"-# Queue name to consume messages from.-#-# The queue name MUST be one of the following:-# - "check.Smtp.gmail": verifies any Gmail email, using SMTP.-# - "check.Smtp.yahoo": verifies any Yahoo email, using SMTP.-# - "check.Smtp.hotmail.b2b": verifies any B2B Hotmail email, using SMTP.-# - "check.Smtp.hotmail.b2c": verifies any B2C Hotmail email (@outlook, @live, @hotmail), using SMTP.-# - "check.Smtp.hotmail.*": verifies any Hotmail email, using SMTP.-# - "check.Smtp.*": verifies any email, using SMTP.-# - "check.Headless.yahoo": verifies any Yahoo email, using a headless browser.-# - "check.Headless.hotmail.b2c": verifies any B2C Hotmail email (@outlook, @live, @hotmail) email, using a headless browser.-# - "check.Headless.*": verifies any email, using a headless browser.-# - "check.*": verifies any email, using the default method.-queue = "check.*"-concurrency = 20--# Throttle the maximum number of requests per second, per minute, per hour, an-# per day for this worker.-# All fields are optional, comment them out to disable the limit.-[throttle]-# max_requests_per_second = 20-max_requests_per_minute = 100-# max_requests_per_hour = 1000-max_requests_per_day = 20000--[db]-url = "postgresql://localhost/reacher_worker_db"--# The optional webhook URL to send the results to.-[webhook]-# url = "http://localhost:8080/webhook"