Skip to content

Check if an email address exists without sending any email, written in Rust. Comes with a ⚙️ HTTP backend.

feat: Move `backend` code to this repo (#1138)

Amaury0dc60531d26e
diff --git a/.github/workflows/deploy_backend.yml b/.github/workflows/deploy_backend.yml
new file mode 100644
index 00000000..64c2631f
--- /dev/null
+++ b/.github/workflows/deploy_backend.yml
@@ -0,0 +1,23 @@
+name: tag
+
+on:
+ push:
+ tags:
+ - "backend/v*.*.*"
+
+jobs:
+ docker-publish:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@master
+ - run: cd backend
+ - name: Set GITHUB_TAG env
+ id: vars
+ run: echo ::set-output name=GITHUB_TAG::${GITHUB_REF:18} # Remove /refs/head/backend/
+ - name: Publish to Registry
+ uses: elgohr/Publish-Docker-Github-Action@master
+ with:
+ name: reacherhq/backend
+ username: ${{ secrets.DOCKER_USERNAME }}
+ password: ${{ secrets.DOCKER_PASSWORD }}
+ tags: "latest,${{ steps.vars.outputs.GITHUB_TAG }}"
diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy_cli.yml
similarity index 92%
rename from .github/workflows/deploy.yml
rename to .github/workflows/deploy_cli.yml
index aeb0b810..1e387fdd 100644
--- a/.github/workflows/deploy.yml
+++ b/.github/workflows/deploy_cli.yml
@@ -4,7 +4,7 @@ on:
tags:
- "v*" # Push events to matching v*, i.e. v1.0, v20.15.10
-name: deploy
+name: deploy_cli
env:
# TODO: Rename to your binary
BIN: check_if_email_exists
@@ -192,18 +192,3 @@ jobs:
asset_path: ${{ env.BIN }}.tar.gz
asset_name: ${{ env.BIN }}-${{ matrix.target }}.tar.gz
asset_content_type: application/gzip
-
- docker-publish:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@master
- - name: Set GITHUB_TAG env
- id: vars
- run: echo ::set-output name=GITHUB_TAG::${GITHUB_REF:10} # Remove /refs/head/
- - name: Publish to Registry
- uses: elgohr/Publish-Docker-Github-Action@master
- with:
- name: reacherhq/check-if-email-exists
- username: ${{ secrets.DOCKER_USERNAME }}
- password: ${{ secrets.DOCKER_PASSWORD }}
- tags: "latest,${{ steps.vars.outputs.GITHUB_TAG }}"
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml
index 90d67928..a113f6c1 100644
--- a/.github/workflows/pr.yml
+++ b/.github/workflows/pr.yml
@@ -1,6 +1,6 @@
# Based on https://github.com/actions-rs/meta/blob/master/recipes/quickstart.md
-name: CI
+name: pr
on:
pull_request:
@@ -8,7 +8,53 @@ on:
branches:
- master
+# For backend, run builds and tests without sqlx's compile time query checks
+# https://github.com/launchbadge/sqlx/blob/master/sqlx-cli/README.md#force-building-in-offline-mode
+env:
+ SQLX_OFFLINE: true
+
jobs:
+ # Cargo check.
+ check:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout sources
+ uses: actions/checkout@v2
+
+ - name: Install stable toolchain
+ uses: actions-rs/toolchain@v1
+ with:
+ profile: minimal
+ toolchain: stable
+ override: true
+
+ - name: Run cargo check
+ uses: actions-rs/cargo@v1
+ with:
+ command: check
+ args: --all
+
+ # Cargo test.
+ test:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout sources
+ uses: actions/checkout@v2
+
+ - name: Install stable toolchain
+ uses: actions-rs/toolchain@v1
+ with:
+ profile: minimal
+ toolchain: stable
+ override: true
+
+ - name: Run cargo test
+ uses: actions-rs/cargo@v1
+ with:
+ command: test
+ args: --all
+
+ # Cargo fmt and clippy
lints:
runs-on: ubuntu-latest
steps:
@@ -33,4 +79,4 @@ jobs:
uses: actions-rs/cargo@v1
with:
command: clippy
- args: -- -D warnings -A deprecated
+ args: --all -- -D warnings -A deprecated
diff --git a/.github/workflows/ci.yml b/.github/workflows/pr_cli.yml
similarity index 98%
rename from .github/workflows/ci.yml
rename to .github/workflows/pr_cli.yml
index 5f2f4f3e..fc0fc659 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/pr_cli.yml
@@ -1,4 +1,5 @@
-name: CI
+# CI actions for the CLI only. We test that the CLI works on various platforms.
+name: cli
on:
push:
diff --git a/.gitignore b/.gitignore
index 695a3d7a..037d383a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,3 +4,4 @@
# sensitive data
/test_suite/src/sensitive_fixtures/*.json
+.env
diff --git a/.rustfmt.toml b/.rustfmt.toml
new file mode 100644
index 00000000..218e2032
--- /dev/null
+++ b/.rustfmt.toml
@@ -0,0 +1 @@
+hard_tabs = true
diff --git a/Cargo.lock b/Cargo.lock
index bd077b4c..dd573f8c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2,6 +2,32 @@
# It is not intended for manual editing.
version = 3
+[[package]]
+name = "addr2line"
+version = "0.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9ecd88a8c8378ca913a680cd98f0f13ac67383d35993f86c90a70e3f137816b"
+dependencies = [
+ "gimli",
+]
+
+[[package]]
+name = "adler"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
+
+[[package]]
+name = "ahash"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47"
+dependencies = [
+ "getrandom",
+ "once_cell",
+ "version_check",
+]
+
[[package]]
name = "aho-corasick"
version = "0.7.18"
@@ -11,12 +37,27 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "android_system_properties"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7ed72e1635e121ca3e79420540282af22da58be50de153d36f81ddc6b83aa9e"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "anyhow"
version = "1.0.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15af2628f6890fe2609a3b91bef4c83450512802e59489f9c1cb1fa5df064a61"
+[[package]]
+name = "anymap2"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d301b3b94cb4b2f23d7917810addbbaff90738e0ca2be692bd027e70d7e0330c"
+
[[package]]
name = "ascii_utils"
version = "0.9.3"
@@ -225,6 +266,15 @@ dependencies = [
"syn",
]
+[[package]]
+name = "atoi"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7c57d12312ff59c811c0643f4d80830505833c9ffaebd193d819392b265be8e"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "atomic-waker"
version = "1.0.0"
@@ -248,6 +298,21 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
+[[package]]
+name = "backtrace"
+version = "0.3.66"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cab84319d616cfb654d03394f38ab7e6f0919e181b1b57e1fd15e7fb4077d9a7"
+dependencies = [
+ "addr2line",
+ "cc",
+ "cfg-if",
+ "libc",
+ "miniz_oxide",
+ "object",
+ "rustc-demangle",
+]
+
[[package]]
name = "base64"
version = "0.13.0"
@@ -256,9 +321,27 @@ checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd"
[[package]]
name = "bitflags"
-version = "1.2.1"
+version = "1.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
+
+[[package]]
+name = "block-buffer"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "block-buffer"
+version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"
+checksum = "0bf7fe51849ea569fd452f37822f606a5cabb684dc918707a0193fd4664ff324"
+dependencies = [
+ "generic-array",
+]
[[package]]
name = "blocking"
@@ -274,6 +357,28 @@ dependencies = [
"once_cell",
]
+[[package]]
+name = "bstr"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223"
+dependencies = [
+ "lazy_static",
+ "memchr",
+ "regex-automata",
+ "serde",
+]
+
+[[package]]
+name = "buf_redux"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b953a6887648bb07a535631f2bc00fbdb2a2216f135552cb3f534ed136b9c07f"
+dependencies = [
+ "memchr",
+ "safemem",
+]
+
[[package]]
name = "bufstream"
version = "0.1.4"
@@ -286,11 +391,17 @@ version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c59e7af012c713f529e7a3ee57ce9b31ddd858d4b512923602f74608b009631"
+[[package]]
+name = "byteorder"
+version = "1.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"
+
[[package]]
name = "bytes"
-version = "1.0.1"
+version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b700ce4376041dcd0a327fd0097c41095743c4c8af8887265942faf1100bd040"
+checksum = "ec8a7b6a70fde80372154c65702f00a0f56f3e1c36abbc6c440484be248856db"
[[package]]
name = "cache-padded"
@@ -332,11 +443,34 @@ dependencies = [
"trust-dns-proto",
]
+[[package]]
+name = "check-if-email-exists"
+version = "0.8.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bcefe39f6af22e8a556e3b64aefca5d58e7ed98a2e0848990f23e9b801a86a35"
+dependencies = [
+ "async-native-tls",
+ "async-recursion",
+ "async-smtp",
+ "async-std",
+ "async-std-resolver",
+ "futures",
+ "log",
+ "mailchecker",
+ "rand",
+ "reacher-fast-socks5",
+ "regex",
+ "reqwest",
+ "serde",
+ "serde_json",
+ "trust-dns-proto",
+]
+
[[package]]
name = "check-if-email-exists-cli"
version = "0.8.32"
dependencies = [
- "check-if-email-exists",
+ "check-if-email-exists 0.8.32",
"clap",
"env_logger",
"hyper",
@@ -348,13 +482,19 @@ dependencies = [
]
[[package]]
-name = "check-if-email-exists-test-suite"
-version = "0.8.24"
+name = "chrono"
+version = "0.4.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bfd4d1b31faaa3a89d7934dbded3111da0d2ef28e3ebccdb4f0179f5929d1ef1"
dependencies = [
- "check-if-email-exists",
+ "iana-time-zone",
+ "js-sys",
+ "num-integer",
+ "num-traits",
"serde",
- "serde_json",
- "tokio",
+ "time",
+ "wasm-bindgen",
+ "winapi",
]
[[package]]
@@ -417,9 +557,43 @@ dependencies = [
[[package]]
name = "core-foundation-sys"
-version = "0.8.2"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc"
+
+[[package]]
+name = "cpufeatures"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59a6001667ab124aebae2a495118e11d30984c3a653e99d86d58971708cf5e4b"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crc"
+version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ea221b5284a47e40033bf9b66f35f984ec0ea2931eb03505246cd27a963f981b"
+checksum = "53757d12b596c16c78b83458d732a5d1a17ab3f53f2f7412f6fb57cc8a140ab3"
+dependencies = [
+ "crc-catalog",
+]
+
+[[package]]
+name = "crc-catalog"
+version = "2.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2d0165d2900ae6778e36e80bbc4da3b5eefccee9ba939761f9c2882a5d9af3ff"
+
+[[package]]
+name = "crossbeam-queue"
+version = "0.3.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1cd42583b04998a5363558e5f9291ee5a5ff6b49944332103f251e7479a82aa7"
+dependencies = [
+ "cfg-if",
+ "crossbeam-utils",
+]
[[package]]
name = "crossbeam-utils"
@@ -431,6 +605,38 @@ dependencies = [
"lazy_static",
]
+[[package]]
+name = "crypto-common"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "csv"
+version = "1.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22813a6dc45b335f9bade10bf7271dc477e81113e89eb251a0bc2a8a81c536e1"
+dependencies = [
+ "bstr",
+ "csv-core",
+ "itoa 0.4.7",
+ "ryu",
+ "serde",
+]
+
+[[package]]
+name = "csv-core"
+version = "0.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b2466559f260f48ad25fe6317b3c8dac77b5bdb5763ac7d9d6103530663bc90"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "ctor"
version = "0.1.20"
@@ -447,11 +653,79 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ee2393c4a91429dffb4bedf19f4d6abf27d8a732c8ce4980305d782e5426d57"
+[[package]]
+name = "debugid"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6ee87af31d84ef885378aebca32be3d682b0e0dc119d5b4860a2c5bb5046730"
+dependencies = [
+ "serde",
+ "uuid 0.8.2",
+]
+
+[[package]]
+name = "digest"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2fb860ca6fafa5552fb6d0e816a69c8e49f0908bf524e30a90d97c85892d506"
+dependencies = [
+ "block-buffer 0.10.2",
+ "crypto-common",
+ "subtle",
+]
+
+[[package]]
+name = "dirs"
+version = "4.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059"
+dependencies = [
+ "dirs-sys",
+]
+
+[[package]]
+name = "dirs-sys"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6"
+dependencies = [
+ "libc",
+ "redox_users",
+ "winapi",
+]
+
+[[package]]
+name = "dotenv"
+version = "0.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77c90badedccf4105eca100756a0b1289e191f6fcbdadd3cee1d2f614f97da8f"
+
+[[package]]
+name = "dotenvy"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e851a83c30366fd01d75b913588e95e74a1705c1ecc5d58b1f8e1a6d556525f"
+dependencies = [
+ "dirs",
+]
+
[[package]]
name = "either"
version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457"
+dependencies = [
+ "serde",
+]
[[package]]
name = "encoding_rs"
@@ -489,9 +763,9 @@ dependencies = [
[[package]]
name = "event-listener"
-version = "2.5.1"
+version = "2.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f7531096570974c3a9dcf9e4b8e1cede1ec26cf5046219fb3b9d897503b9be59"
+checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"
[[package]]
name = "fast-socks5"
@@ -597,6 +871,17 @@ dependencies = [
"futures-util",
]
+[[package]]
+name = "futures-intrusive"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "62007592ac46aa7c2b6416f7deb9a8a8f63a01e0f1d6e1787d5630170db2b63e"
+dependencies = [
+ "futures-core",
+ "lock_api",
+ "parking_lot 0.11.2",
+]
+
[[package]]
name = "futures-io"
version = "0.3.21"
@@ -659,6 +944,16 @@ dependencies = [
"slab",
]
+[[package]]
+name = "generic-array"
+version = "0.14.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bff49e947297f3312447abdca79f45f4738097cc82b06e72054d2223f601f1b9"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
[[package]]
name = "getrandom"
version = "0.2.3"
@@ -667,9 +962,15 @@ checksum = "7fcd999463524c52659517fe2cea98493cfe485d10565e7b0fb07dbba7ad2753"
dependencies = [
"cfg-if",
"libc",
- "wasi 0.10.2+wasi-snapshot-preview1",
+ "wasi 0.10.0+wasi-snapshot-preview1",
]
+[[package]]
+name = "gimli"
+version = "0.26.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22030e2c5a68ec659fde1e949a745124b48e6fa8b045b7ed5bd1fe4ccc5c4e5d"
+
[[package]]
name = "gloo-timers"
version = "0.2.1"
@@ -708,11 +1009,57 @@ version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04"
+[[package]]
+name = "hashbrown"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
+dependencies = [
+ "ahash",
+]
+
+[[package]]
+name = "hashlink"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d452c155cb93fecdfb02a73dd57b5d8e442c2063bd7aac72f1bc5e4263a43086"
+dependencies = [
+ "hashbrown 0.12.3",
+]
+
+[[package]]
+name = "headers"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cff78e5788be1e0ab65b04d306b2ed5092c815ec97ec70f4ebd5aee158aa55d"
+dependencies = [
+ "base64",
+ "bitflags",
+ "bytes",
+ "headers-core",
+ "http",
+ "httpdate",
+ "mime",
+ "sha-1 0.10.0",
+]
+
+[[package]]
+name = "headers-core"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7f66481bfee273957b1f20485a4ff3362987f85b2c236580d81b4eb7a326429"
+dependencies = [
+ "http",
+]
+
[[package]]
name = "heck"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9"
+dependencies = [
+ "unicode-segmentation",
+]
[[package]]
name = "hermit-abi"
@@ -723,6 +1070,30 @@ dependencies = [
"libc",
]
+[[package]]
+name = "hex"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+
+[[package]]
+name = "hkdf"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "791a029f6b9fc27657f6f188ec6e5e43f6911f6f878e0dc5501396e09809d437"
+dependencies = [
+ "hmac",
+]
+
+[[package]]
+name = "hmac"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
+dependencies = [
+ "digest 0.10.3",
+]
+
[[package]]
name = "hostname"
version = "0.3.1"
@@ -812,16 +1183,29 @@ dependencies = [
]
[[package]]
-name = "idna"
-version = "0.2.3"
+name = "iana-time-zone"
+version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "418a0a6fab821475f634efe3ccc45c013f742efe03d853e8d3355d5cb850ecf8"
+checksum = "808cf7d67cf4a22adc5be66e75ebdf769b3f2ea032041437a7061f97a63dad4b"
dependencies = [
- "matches",
- "unicode-bidi",
- "unicode-normalization",
-]
-
+ "android_system_properties",
+ "core-foundation-sys",
+ "js-sys",
+ "wasm-bindgen",
+ "winapi",
+]
+
+[[package]]
+name = "idna"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "418a0a6fab821475f634efe3ccc45c013f742efe03d853e8d3355d5cb850ecf8"
+dependencies = [
+ "matches",
+ "unicode-bidi",
+ "unicode-normalization",
+]
+
[[package]]
name = "indexmap"
version = "1.6.2"
@@ -829,7 +1213,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "824845a0bf897a9042383849b02c1bc219c2383772efcd5c6f9766fa4b81aef3"
dependencies = [
"autocfg",
- "hashbrown",
+ "hashbrown 0.9.1",
]
[[package]]
@@ -859,6 +1243,15 @@ version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68f2d64f2edebec4ce84ad108148e67e1064789bee435edc5b60ad398714a3a9"
+[[package]]
+name = "itertools"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a9a9d19fa1e79b6215ff29b9d6880b706147f16e9b1dbb1e4e5947b5b02bc5e3"
+dependencies = [
+ "either",
+]
+
[[package]]
name = "itoa"
version = "0.4.7"
@@ -873,9 +1266,9 @@ checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35"
[[package]]
name = "js-sys"
-version = "0.3.51"
+version = "0.3.59"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "83bdfbace3a0e81a4253f73b49e960b053e396a11012cbd49b9b74d6a2b67062"
+checksum = "258451ab10b34f8af53416d1fdab72c22e805f0c92a1136d59470ec0b11138b2"
dependencies = [
"wasm-bindgen",
]
@@ -958,11 +1351,20 @@ version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08"
+[[package]]
+name = "md-5"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "658646b21e0b72f7866c7038ab086d3d5e1cd6271f060fd37defb241949d0582"
+dependencies = [
+ "digest 0.10.3",
+]
+
[[package]]
name = "memchr"
-version = "2.4.0"
+version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b16bd47d9e329435e309c58469fe0791c2d0d1ba96ec0954152a5ae2b04387dc"
+checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
[[package]]
name = "mime"
@@ -970,12 +1372,31 @@ version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d"
+[[package]]
+name = "mime_guess"
+version = "2.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4192263c238a5f0d0c6bfd21f336a313a4ce1c450542449ca191bb657b4642ef"
+dependencies = [
+ "mime",
+ "unicase",
+]
+
[[package]]
name = "minimal-lexical"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
+[[package]]
+name = "miniz_oxide"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6f5c75688da582b8ffc1f1799e9db273f32133c49e048f614d22ec3256773ccc"
+dependencies = [
+ "adler",
+]
+
[[package]]
name = "mio"
version = "0.8.4"
@@ -988,6 +1409,24 @@ dependencies = [
"windows-sys",
]
+[[package]]
+name = "multipart"
+version = "0.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "00dec633863867f29cb39df64a397cdf4a6354708ddd7759f70c7fb51c5f9182"
+dependencies = [
+ "buf_redux",
+ "httparse",
+ "log",
+ "mime",
+ "mime_guess",
+ "quick-error",
+ "rand",
+ "safemem",
+ "tempfile",
+ "twoway",
+]
+
[[package]]
name = "native-tls"
version = "0.2.8"
@@ -1016,6 +1455,25 @@ dependencies = [
"minimal-lexical",
]
+[[package]]
+name = "num-integer"
+version = "0.1.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9"
+dependencies = [
+ "autocfg",
+ "num-traits",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd"
+dependencies = [
+ "autocfg",
+]
+
[[package]]
name = "num_cpus"
version = "1.13.0"
@@ -1026,12 +1484,27 @@ dependencies = [
"libc",
]
+[[package]]
+name = "object"
+version = "0.29.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "21158b2c33aa6d4561f1c0a6ea283ca92bc54802a93b263e910746d679a7eb53"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "once_cell"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "18a6dbe30758c9f83eb00cbea4ac95966305f5a7772f3f42ebfc7fc7eddbd8e1"
+[[package]]
+name = "opaque-debug"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5"
+
[[package]]
name = "openssl"
version = "0.10.41"
@@ -1099,6 +1572,17 @@ version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "427c3892f9e783d91cc128285287e70a59e206ca452770ece88a76f7a3eddd72"
+[[package]]
+name = "parking_lot"
+version = "0.11.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99"
+dependencies = [
+ "instant",
+ "lock_api",
+ "parking_lot_core 0.8.5",
+]
+
[[package]]
name = "parking_lot"
version = "0.12.1"
@@ -1106,7 +1590,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f"
dependencies = [
"lock_api",
- "parking_lot_core",
+ "parking_lot_core 0.9.3",
+]
+
+[[package]]
+name = "parking_lot_core"
+version = "0.8.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d76e8e1493bcac0d2766c42737f34458f1c8c50c0d23bcb24ea953affb273216"
+dependencies = [
+ "cfg-if",
+ "instant",
+ "libc",
+ "redox_syscall",
+ "smallvec",
+ "winapi",
]
[[package]]
@@ -1122,6 +1620,12 @@ dependencies = [
"windows-sys",
]
+[[package]]
+name = "paste"
+version = "1.0.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9423e2b32f7a043629287a536f21951e8c6a82482d0acb1eeebfc90bc2225b22"
+
[[package]]
name = "percent-encoding"
version = "2.1.0"
@@ -1226,9 +1730,9 @@ checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
[[package]]
name = "quote"
-version = "1.0.9"
+version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c3d0b9745dc2debf507c8422de05d7226cc1f0644216dfdfead988f9b1ab32a7"
+checksum = "f53dc8cf16a769a6f677e09e7ff2cd4be1ea0f48754aac39520536962011de0d"
dependencies = [
"proc-macro2",
]
@@ -1276,15 +1780,47 @@ dependencies = [
"tokio-stream",
]
+[[package]]
+name = "reacher_backend"
+version = "0.4.0"
+dependencies = [
+ "async-smtp",
+ "check-if-email-exists 0.8.32 (registry+https://github.com/rust-lang/crates.io-index)",
+ "csv",
+ "dotenv",
+ "env_logger",
+ "log",
+ "openssl",
+ "sentry",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "sqlxmq",
+ "tokio",
+ "uuid 1.1.2",
+ "warp",
+]
+
[[package]]
name = "redox_syscall"
-version = "0.2.9"
+version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5ab49abadf3f9e1c4bc499e8845e152ad87d2ad2d30371841171169e9d75feee"
+checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a"
dependencies = [
"bitflags",
]
+[[package]]
+name = "redox_users"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b033d837a7cf162d7993aded9304e30a83213c648b6e389db233191f891e5c2b"
+dependencies = [
+ "getrandom",
+ "redox_syscall",
+ "thiserror",
+]
+
[[package]]
name = "regex"
version = "1.6.0"
@@ -1296,6 +1832,12 @@ dependencies = [
"regex-syntax",
]
+[[package]]
+name = "regex-automata"
+version = "0.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132"
+
[[package]]
name = "regex-syntax"
version = "0.6.27"
@@ -1359,12 +1901,33 @@ dependencies = [
"quick-error",
]
+[[package]]
+name = "rustc-demangle"
+version = "0.1.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ef03e0a2b150c7a90d01faf6254c9c48a41e95fb2a8c2ac1c6f0d2b9aefc342"
+
+[[package]]
+name = "rustc_version"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366"
+dependencies = [
+ "semver",
+]
+
[[package]]
name = "ryu"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e"
+[[package]]
+name = "safemem"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef703b7cb59335eae2eb93ceb664c0eb7ea6bf567079d843e09420219668e072"
+
[[package]]
name = "schannel"
version = "0.1.19"
@@ -1375,6 +1938,12 @@ dependencies = [
"winapi",
]
+[[package]]
+name = "scoped-tls"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2"
+
[[package]]
name = "scopeguard"
version = "1.1.0"
@@ -1404,6 +1973,93 @@ dependencies = [
"libc",
]
+[[package]]
+name = "semver"
+version = "1.0.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93f6841e709003d68bb2deee8c343572bf446003ec20a583e76f7b15cebf3711"
+
+[[package]]
+name = "sentry"
+version = "0.23.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "546b9b6f76c26c60ffbcf0b7136e15169fe13d43949b4aadb7c1edc1c3f3a26f"
+dependencies = [
+ "httpdate",
+ "reqwest",
+ "sentry-backtrace",
+ "sentry-contexts",
+ "sentry-core",
+ "sentry-panic",
+ "tokio",
+]
+
+[[package]]
+name = "sentry-backtrace"
+version = "0.23.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9cd0cba2aff36ac98708f7a6e7abbdde82dbaf180d5870c41084dc1b473648b9"
+dependencies = [
+ "backtrace",
+ "lazy_static",
+ "regex",
+ "sentry-core",
+]
+
+[[package]]
+name = "sentry-contexts"
+version = "0.23.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9bacf1c62427c6c97b896640d0c4dd204bbd3b79dd192d7cb40891aa5ee11d58"
+dependencies = [
+ "hostname",
+ "lazy_static",
+ "libc",
+ "regex",
+ "rustc_version",
+ "sentry-core",
+ "uname",
+]
+
+[[package]]
+name = "sentry-core"
+version = "0.23.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9a957270c9a430218f8031c866493061a27e35a70250e9527f093563a33ce6b"
+dependencies = [
+ "chrono",
+ "lazy_static",
+ "rand",
+ "sentry-types",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "sentry-panic"
+version = "0.23.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "692bf989f0c99f025e33d7f58e62822c3771f56d189698c66dcc863122255d95"
+dependencies = [
+ "sentry-backtrace",
+ "sentry-core",
+]
+
+[[package]]
+name = "sentry-types"
+version = "0.23.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f4dd2266fee014a86e250e98e389191ecd23be546b5c42b6a2fb9af2972fadac"
+dependencies = [
+ "chrono",
+ "debugid",
+ "serde",
+ "serde_json",
+ "thiserror",
+ "url",
+ "uuid 0.8.2",
+]
+
[[package]]
name = "serde"
version = "1.0.143"
@@ -1447,6 +2103,41 @@ dependencies = [
"serde",
]
+[[package]]
+name = "sha-1"
+version = "0.9.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "99cd6713db3cf16b6c84e06321e049a9b9f699826e16096d23bbcc44d15d51a6"
+dependencies = [
+ "block-buffer 0.9.0",
+ "cfg-if",
+ "cpufeatures",
+ "digest 0.9.0",
+ "opaque-debug",
+]
+
+[[package]]
+name = "sha-1"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "028f48d513f9678cda28f6e4064755b3fbb2af6acd672f2c209b62323f7aea0f"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest 0.10.3",
+]
+
+[[package]]
+name = "sha2"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "55deaec60f81eefe3cce0dc50bda92d6d8e88f2a27df7c5033b42afeb1ed2676"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest 0.10.3",
+]
+
[[package]]
name = "signal-hook"
version = "0.3.14"
@@ -1488,12 +2179,164 @@ dependencies = [
"winapi",
]
+[[package]]
+name = "sqlformat"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4b7922be017ee70900be125523f38bdd644f4f06a1b16e8fa5a8ee8c34bffd4"
+dependencies = [
+ "itertools",
+ "nom",
+ "unicode_categories",
+]
+
+[[package]]
+name = "sqlx"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "788841def501aabde58d3666fcea11351ec3962e6ea75dbcd05c84a71d68bcd1"
+dependencies = [
+ "sqlx-core",
+ "sqlx-macros",
+]
+
+[[package]]
+name = "sqlx-core"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8c21d3b5e7cadfe9ba7cdc1295f72cc556c750b4419c27c219c0693198901f8e"
+dependencies = [
+ "ahash",
+ "atoi",
+ "base64",
+ "bitflags",
+ "byteorder",
+ "bytes",
+ "chrono",
+ "crc",
+ "crossbeam-queue",
+ "dirs",
+ "dotenvy",
+ "either",
+ "event-listener",
+ "futures-channel",
+ "futures-core",
+ "futures-intrusive",
+ "futures-util",
+ "hashlink",
+ "hex",
+ "hkdf",
+ "hmac",
+ "indexmap",
+ "itoa 1.0.1",
+ "libc",
+ "log",
+ "md-5",
+ "memchr",
+ "once_cell",
+ "paste",
+ "percent-encoding",
+ "rand",
+ "serde",
+ "serde_json",
+ "sha-1 0.10.0",
+ "sha2",
+ "smallvec",
+ "sqlformat",
+ "sqlx-rt",
+ "stringprep",
+ "thiserror",
+ "tokio-stream",
+ "url",
+ "uuid 1.1.2",
+ "whoami",
+]
+
+[[package]]
+name = "sqlx-macros"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4adfd2df3557bddd3b91377fc7893e8fa899e9b4061737cbade4e1bb85f1b45c"
+dependencies = [
+ "dotenvy",
+ "either",
+ "heck",
+ "hex",
+ "once_cell",
+ "proc-macro2",
+ "quote",
+ "serde",
+ "serde_json",
+ "sha2",
+ "sqlx-core",
+ "sqlx-rt",
+ "syn",
+ "url",
+]
+
+[[package]]
+name = "sqlx-rt"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7be52fc7c96c136cedea840ed54f7d446ff31ad670c9dea95ebcb998530971a3"
+dependencies = [
+ "native-tls",
+ "once_cell",
+ "tokio",
+ "tokio-native-tls",
+]
+
+[[package]]
+name = "sqlxmq"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8bef5e9c333f8b98c121afc082af5376fafaee861c0f9be53eb106275aff1b61"
+dependencies = [
+ "anymap2",
+ "chrono",
+ "dotenv",
+ "log",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "sqlxmq_macros",
+ "tokio",
+ "uuid 1.1.2",
+]
+
+[[package]]
+name = "sqlxmq_macros"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "625cc6611e76374d96995925ebf10a97b28cdcc95202c8a09f3b6a303cba5a78"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "stringprep"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ee348cb74b87454fff4b551cbf727025810a004f88aeacae7f85b87f4e9a1c1"
+dependencies = [
+ "unicode-bidi",
+ "unicode-normalization",
+]
+
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
+[[package]]
+name = "subtle"
+version = "2.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601"
+
[[package]]
name = "syn"
version = "1.0.95"
@@ -1536,24 +2379,35 @@ checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb"
[[package]]
name = "thiserror"
-version = "1.0.25"
+version = "1.0.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fa6f76457f59514c7eeb4e59d891395fab0b2fd1d40723ae737d64153392e9c6"
+checksum = "f5f6586b7f764adc0231f4c79be7b920e766bb2f3e51b3661cdb263828f19994"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
-version = "1.0.25"
+version = "1.0.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8a36768c0fbf1bb15eca10defa29526bda730a2376c2ab4393ccfa16fb1a318d"
+checksum = "12bafc5b54507e0149cdf1b145a5d80ab80a90bcd9275df43d4fff68460f6c21"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
+[[package]]
+name = "time"
+version = "0.1.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255"
+dependencies = [
+ "libc",
+ "wasi 0.10.0+wasi-snapshot-preview1",
+ "winapi",
+]
+
[[package]]
name = "tinyvec"
version = "1.2.0"
@@ -1571,17 +2425,20 @@ checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"
[[package]]
name = "tokio"
-version = "1.19.2"
+version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c51a52ed6686dd62c320f9b89299e9dfb46f730c7a48e635c19f21d116cb1439"
+checksum = "7a8325f63a7d4774dd041e363b2409ed1c5cbbd0f867795e661df066b2b0a581"
dependencies = [
+ "autocfg",
"bytes",
"libc",
"memchr",
"mio",
"num_cpus",
"once_cell",
+ "parking_lot 0.12.1",
"pin-project-lite",
+ "signal-hook-registry",
"socket2",
"tokio-macros",
"winapi",
@@ -1631,6 +2488,19 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "tokio-tungstenite"
+version = "0.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "511de3f85caf1c98983545490c3d09685fa8eb634e57eec22bb4db271f46cbd8"
+dependencies = [
+ "futures-util",
+ "log",
+ "pin-project",
+ "tokio",
+ "tungstenite",
+]
+
[[package]]
name = "tokio-util"
version = "0.6.7"
@@ -1658,6 +2528,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09adeb8c97449311ccd28a427f96fb563e7fd31aabf994189879d9da2394b89d"
dependencies = [
"cfg-if",
+ "log",
"pin-project-lite",
"tracing-core",
]
@@ -1708,7 +2579,7 @@ dependencies = [
"lazy_static",
"log",
"lru-cache",
- "parking_lot",
+ "parking_lot 0.12.1",
"resolv-conf",
"smallvec",
"thiserror",
@@ -1721,6 +2592,58 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642"
+[[package]]
+name = "tungstenite"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0b2d8558abd2e276b0a8df5c05a2ec762609344191e5fd23e292c910e9165b5"
+dependencies = [
+ "base64",
+ "byteorder",
+ "bytes",
+ "http",
+ "httparse",
+ "log",
+ "rand",
+ "sha-1 0.9.8",
+ "thiserror",
+ "url",
+ "utf-8",
+]
+
+[[package]]
+name = "twoway"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59b11b2b5241ba34be09c3cc85a36e56e48f9888862e19cedf23336d35316ed1"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "typenum"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987"
+
+[[package]]
+name = "uname"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b72f89f0ca32e4db1c04e2a72f5345d59796d4866a1ee0609084569f73683dc8"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "unicase"
+version = "2.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6"
+dependencies = [
+ "version_check",
+]
+
[[package]]
name = "unicode-bidi"
version = "0.3.5"
@@ -1745,6 +2668,18 @@ dependencies = [
"tinyvec",
]
+[[package]]
+name = "unicode-segmentation"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e8820f5d777f6224dc4be3632222971ac30164d4a258d595640799554ebfd99"
+
+[[package]]
+name = "unicode_categories"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e"
+
[[package]]
name = "url"
version = "2.2.2"
@@ -1755,6 +2690,32 @@ dependencies = [
"idna",
"matches",
"percent-encoding",
+ "serde",
+]
+
+[[package]]
+name = "utf-8"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
+
+[[package]]
+name = "uuid"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7"
+dependencies = [
+ "getrandom",
+ "serde",
+]
+
+[[package]]
+name = "uuid"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd6469f4314d5f1ffec476e05f17cc9a78bc7a27a6a857842170bdf8d6f98d2f"
+dependencies = [
+ "getrandom",
]
[[package]]
@@ -1795,11 +2756,41 @@ dependencies = [
"try-lock",
]
+[[package]]
+name = "warp"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3cef4e1e9114a4b7f1ac799f16ce71c14de5778500c5450ec6b7b920c55b587e"
+dependencies = [
+ "bytes",
+ "futures-channel",
+ "futures-util",
+ "headers",
+ "http",
+ "hyper",
+ "log",
+ "mime",
+ "mime_guess",
+ "multipart",
+ "percent-encoding",
+ "pin-project",
+ "scoped-tls",
+ "serde",
+ "serde_json",
+ "serde_urlencoded",
+ "tokio",
+ "tokio-stream",
+ "tokio-tungstenite",
+ "tokio-util",
+ "tower-service",
+ "tracing",
+]
+
[[package]]
name = "wasi"
-version = "0.10.2+wasi-snapshot-preview1"
+version = "0.10.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6"
+checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f"
[[package]]
name = "wasi"
@@ -1809,9 +2800,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasm-bindgen"
-version = "0.2.74"
+version = "0.2.82"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d54ee1d4ed486f78874278e63e4069fc1ab9f6a18ca492076ffb90c5eb2997fd"
+checksum = "fc7652e3f6c4706c8d9cd54832c4a4ccb9b5336e2c3bd154d5cccfbf1c1f5f7d"
dependencies = [
"cfg-if",
"wasm-bindgen-macro",
@@ -1819,13 +2810,13 @@ dependencies = [
[[package]]
name = "wasm-bindgen-backend"
-version = "0.2.74"
+version = "0.2.82"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3b33f6a0694ccfea53d94db8b2ed1c3a8a4c86dd936b13b9f0a15ec4a451b900"
+checksum = "662cd44805586bd52971b9586b1df85cdbbd9112e4ef4d8f41559c334dc6ac3f"
dependencies = [
"bumpalo",
- "lazy_static",
"log",
+ "once_cell",
"proc-macro2",
"quote",
"syn",
@@ -1846,9 +2837,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro"
-version = "0.2.74"
+version = "0.2.82"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "088169ca61430fe1e58b8096c24975251700e7b1f6fd91cc9d59b04fb9b18bd4"
+checksum = "b260f13d3012071dfb1512849c033b1925038373aea48ced3012c09df952c602"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
@@ -1856,9 +2847,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro-support"
-version = "0.2.74"
+version = "0.2.82"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "be2241542ff3d9f241f5e2cb6dd09b37efe786df8851c54957683a49f0987a97"
+checksum = "5be8e654bdd9b79216c2929ab90721aa82faf65c48cdf08bdc4e7f51357b80da"
dependencies = [
"proc-macro2",
"quote",
@@ -1869,9 +2860,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-shared"
-version = "0.2.74"
+version = "0.2.82"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d7cff876b8f18eed75a66cf49b65e7f967cb354a7aa16003fb55dbfd25b44b4f"
+checksum = "6598dd0bd3c7d51095ff6531a5b23e02acdc81804e30d8f07afb77b7215a140a"
[[package]]
name = "web-sys"
@@ -1892,6 +2883,16 @@ dependencies = [
"cc",
]
+[[package]]
+name = "whoami"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "524b58fa5a20a2fb3014dd6358b70e6579692a56ef6fce928834e488f42f65e8"
+dependencies = [
+ "wasm-bindgen",
+ "web-sys",
+]
+
[[package]]
name = "widestring"
version = "0.5.1"
diff --git a/Cargo.toml b/Cargo.toml
index 80996153..40bd32bb 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[workspace]
members = [
+ "backend",
"cli",
"core",
- "test_suite"
]
diff --git a/Dockerfile b/Dockerfile
deleted file mode 100644
index 9030999f..00000000
--- a/Dockerfile
+++ /dev/null
@@ -1,22 +0,0 @@
-# Deprecated.
-# This Dockerfile is for demo purposes, and should not be used in production.
-# For a production-ready web server, please see https://github.com/reacherhq/backend.
-# This Dockerfile will be **deprecated** soon, and removed from the
-# Docker Hub: https://hub.docker.com/r/reacherhq/check-if-email-exists.
-FROM alpine
-
-# `ciee` stands for check-if-email-exists
-WORKDIR /ciee
-# Fetch latest version
-ENV CIEE_VERSION 0.8.32
-
-# Install needed libraries
-RUN apk update && \
- apk add --no-cache openssl wget && \
- rm -rf /var/cache/apk/*
-
-# Download the binary from Github
-RUN wget https://github.com/reacherhq/check-if-email-exists/releases/download/v${CIEE_VERSION}/check-if-email-exists-v${CIEE_VERSION}-x86_64-unknown-linux-musl.tar.gz \
- && tar -xvzf check-if-email-exists-v${CIEE_VERSION}-x86_64-unknown-linux-musl.tar.gz
-
-CMD ["./check_if_email_exists", "--http", "--http-host", "0.0.0.0"]
diff --git a/Dockerfile b/Dockerfile
new file mode 120000
index 00000000..4600149d
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1 @@
+backend/Dockerfile
\ No newline at end of file
diff --git a/README.md b/README.md
index fd31c7eb..0367186d 100644
--- a/README.md
+++ b/README.md
@@ -1,147 +1,72 @@
[![Crate](https://img.shields.io/crates/v/check-if-email-exists.svg)](https://crates.io/crates/check-if-email-exists)
[![Docs](https://docs.rs/check-if-email-exists/badge.svg)](https://docs.rs/check-if-email-exists)
-[![Actions Status](https://github.com/reacherhq/check-if-email-exists/workflows/CI/badge.svg)](https://github.com/reacherhq/check-if-email-exists/actions)
+[![Docker](https://img.shields.io/docker/v/reacherhq/backend?color=0db7ed&label=docker&sort=date)](https://hub.docker.com/r/reacherhq/backend)
+[![Actions Status](https://github.com/reacherhq/check-if-email-exists/workflows/pr/badge.svg)](https://github.com/reacherhq/check-if-email-exists/actions)
[![Github Sponsor](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&link=https://github.com/sponsors/amaurym)](https://github.com/sponsors/amaurym)
-<br /><br /><br />
+<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">check-if-email-exists</h1>
-<h4 align="center">Check if an email address exists without sending any email.</h4>
+<h4 align="center">Check if an email address exists without sending any email.<br/>Comes with a <a href="./backend">⚙️ HTTP backend</a>.</h4>
<br /><br /><br />
## 👉 Live Demo: https://reacher.email
-<a href="https://www.hookdoo.com/?github"><img src="https://storage.googleapis.com/saasify-uploads-prod/696e287ad79f0e0352bc201b36d701849f7d55e7.svg" height="96" alt="hookdoo" align="left" /></a>
+<img src="https://storage.googleapis.com/saasify-uploads-prod/696e287ad79f0e0352bc201b36d701849f7d55e7.svg" height="68" align="left" />
-If you don't have time to waste configuring, hosting, debugging, and maintaining your own email verifier, we offer a **SaaS** solution that has all of the capabilities `check-if-email-exists` provides, plus a lot more, and all that packaged in a nice friendly web interface. If you are interested, find out more at [Reacher](https://reacher.email/?ref=github). If you have any questions, you can contact me at [email protected].
+This is open-source, but I also offer a **SaaS** solution that has `check-if-email-exists` packaged in a nice friendly web interface. If you are interested, find out more at [Reacher](https://reacher.email/?ref=github). If you have any questions, you can contact me at [email protected].
<br />
-## What Does This Tool Check?
-
-| Included? | Feature | Description | JSON field |
-| --------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
-| ✅ | **Email reachability** | How confident are we in sending an email to this address? Can be one of `safe`, `risky`, `invalid` or `unknown`. | `is_reachable` |
-| ✅ | **Syntax validation** | Is the address syntactically valid? | `syntax.is_valid_syntax` |
-| ✅ | **DNS records validation** | Does the domain of the email address have valid MX DNS records? | `mx.accepts_mail` |
-| ✅ | **Disposable email address (DEA) validation** | Is the address provided by a known [disposable email address](https://en.wikipedia.org/wiki/Disposable_email_address) provider? | `misc.is_disposable` |
-| ✅ | **SMTP server validation** | Can the mail exchanger of the email address domain be contacted successfully? | `smtp.can_connect_smtp` |
-| ✅ | **Email deliverability** | Is an email sent to this address deliverable? | `smtp.is_deliverable` |
-| ✅ | **Mailbox disabled** | Has this email address been disabled by the email provider? | `smtp.is_disabled` |
-| ✅ | **Full inbox** | Is the inbox of this mailbox full? | `smtp.has_full_inbox` |
-| ✅ | **Catch-all address** | Is this email address a [catch-all](https://debounce.io/blog/help/what-is-a-catch-all-or-accept-all/) address? | `smtp.is_catch_all` |
-| ✅ | **Role account validation** | Is the email address a well-known role account? | `misc.is_role_account` |
-| 🔜 | **Free email provider check** | Is the email address bound to a known free email provider? | [Issue #89](https://github.com/reacherhq/check-if-email-exists/issues/89) |
-| 🔜 | **Syntax validation, provider-specific** | According to the syntactic rules of the target mail provider, is the address syntactically valid? | [Issue #90](https://github.com/reacherhq/check-if-email-exists/issues/90) |
-| 🔜 | **Honeypot detection** | Does email address under test hide a [honeypot](https://en.wikipedia.org/wiki/Spamtrap)? | [Issue #91](https://github.com/reacherhq/check-if-email-exists/issues/91) |
-| 🔜 | **Gravatar** | Does this email address have a [Gravatar](https://gravatar.com/) profile picture? | [Issue #92](https://github.com/reacherhq/check-if-email-exists/issues/92) |
-| 🔜 | **Have I Been Pwned?** | Has this email been compromised in a [data breach](https://haveibeenpwned.com/)? | [Issue #289](https://github.com/reacherhq/check-if-email-exists/issues/289) |
-
-## 🤔 Why?
-
-Many online services (https://hunter.io, https://verify-email.org, https://email-checker.net) offer this service for a paid fee. Here is an open-source alternative to those tools.
-
-## License
-
-`check-if-email-exists`'s source code is provided under a **dual license model**.
-
-### Commercial license
+## Get Started
-If you want to use `check-if-email-exists` to develop commercial sites, tools, and applications, the Commercial License is the appropriate license. With this option, your source code is kept proprietary. Purchase a `check-if-email-exists` Commercial License at https://reacher.email/pricing.
-
-### Open source license
-
-If you are creating an open-source application under a license compatible with the GNU Affero GPL license v3, you may use `check-if-email-exists` under the terms of the [AGPL-3.0](./LICENSE.AGPL).
+3 non-SaaS ways to get started with `check-if-email-exists`.
-[Read more](https://help.reacher.email/reacher-licenses) about Reacher's license.
+### 1. ⚙️ HTTP backend using Docker (popular method 🥇) [[Full docs](./backend/README.md)]
-## Try It Yourself
+This option allows you to run a HTTP backend using Docker 🐳, on a cloud instance or your own server. Please note that outbound port 25 must be open.
-There are 5 ways you can try `check-if-email-exists`.
-
-### 1. Use the Hosted Version: https://reacher.email 🥇
-
-Reacher is a simple SaaS using this library, also [open-source](https://github.com/reacherhq/backend)!
-
-> If you would like a high free tier to test Reacher, consider [sponsoring me](https://github.com/sponsors/amaurym/)! You'll get 8000 free email verifications every month, and this contribution would mean A WHOLE LOT to me.
-
-### 2. One-Click Deploy to Heroku
-
-Reacher provides a fully-fledged REST backend at https://github.com/reacherhq/backend. It is the same backend running for our main product https://reacher.email.
-
-The backend is built using the fast web framework [warp](https://github.com/seanmonstar/warp) and exposes an API endpoint for making email verifications.
-
-For a one-click deploy to [Heroku](https://heroku.com), click on the purple Heroku button at [reacherhq/backend](https://github.com/reacherhq/backend#get-started).
-
-### 3. Use Docker
+```bash
+docker run -p 8080:8080 reacherhq/backend:latest
+```
-A Docker image with a fully-fledged HTTP backend is hosted on https://hub.docker.com/r/reacherhq/backend.
+Then send a `POST http://localhost:8080/v0/check_email` request with the following body:
-For more information on how to use the Docker image, please head to [reacherhq/backend](https://github.com/reacherhq/backend#2-use-docker).
+```js
+{
+ "to_email": "[email protected]",
+ "from_email": "[email protected]", // (optional) email to use in the `FROM` SMTP command, defaults to "[email protected]"
+ "hello_name": "my-server.com", // (optional) name to use in the `EHLO` SMTP command, defaults to "localhost"
+ "proxy": { // (optional) SOCK5 proxy to run the verification through, default is empty
+ "host": "my-proxy.io",
+ "port": 1080,
+ "username": "me", // (optional) Proxy username
+ "password": "pass" // (optional) Proxy password
+ },
+ "smtp_port": 587 // (optional) SMTP port to do the email verification, defaults to 25
+}
+```
-### 4. Download the Binary
+### 2. Download the CLI [[Full docs](./cli/README.md)]
-> Note: The binary doesn't connect to any backend, it checks the email directly from your computer.
+> Note: The CLI binary doesn't connect to any backend, it checks the email directly from your computer.
Head to the [releases page](https://github.com/reacherhq/check-if-email-exists/releases) and download the binary for your platform.
-```
+```bash
> $ check_if_email_exists --help
check_if_email_exists 0.8.32
Check if an email address exists without sending an email.
USAGE:
check_if_email_exists [FLAGS] [OPTIONS] [TO_EMAIL]
-
-ARGS:
- <TO_EMAIL> The email to check
-
-FLAGS:
- -h, --help Print help information
- --http DEPRECATED. Runs an HTTP server. This option will be removed in v0.9.0
- -V, --version Print version information
-
-OPTIONS:
- --from-email <FROM_EMAIL>
- The email to use in the `MAIL FROM:` SMTP command [env: FROM_EMAIL=] [default:
-
- --hello-name <HELLO_NAME>
- The name to use in the `EHLO:` SMTP command [env: HELLO_NAME=] [default: localhost]
-
- --http-host <HTTP_HOST>
- DEPRECATED. Sets the host IP address on which the HTTP server should bind. Only used
- when `--http` flag is on. This option will be removed in v0.9.0 [env: HOST=] [default:
- 127.0.0.1]
-
- --http-port <HTTP_PORT>
- DEPRECATED. Sets the port on which the HTTP server should bind. Only used when the `--http`
- flag is on. If not set, then it will use $PORT or default to 3000. This option will be
- removed in v0.9.0 [env: PORT=] [default: 3000]
-
- --proxy-host <PROXY_HOST>
- Use the specified SOCKS5 proxy host to perform email verification [env: PROXY_HOST=]
-
- --proxy-port <PROXY_PORT>
- Use the specified SOCKS5 proxy port to perform email verification. Only used when
- `--proxy-host` flag is set [env: PROXY_PORT=] [default: 1080]
-
- --smtp-port <SMTP_PORT>
- The email to check [env: SMTP_PORT=] [default: 25]
-
- --yahoo-use-api <YAHOO_USE_API>
- For Yahoo email addresses, use Yahoo's API instead of connecting directly to their SMTP
- servers [env: YAHOO_USE_API=] [default: true]
```
-**💡 PRO TIP:** To show debug logs when running the binary, run:
+Check out the [dedicated README.md](./cli/README.md) for all options and flags.
-```bash
-RUST_LOG=debug check_if_email_exists [FLAGS] [OPTIONS] [TO_EMAIL]
-```
-
-### 5. Usage as a Rust Library
+### 3. Programmatic Usage [[Full docs](https://docs.rs/check-if-email-exists)]
In your own Rust project, you can add `check-if-email-exists` in your `Cargo.toml`:
@@ -159,18 +84,6 @@ async fn check() {
// Let's say we want to test the deliverability of [email protected].
let mut input = CheckEmailInput::new(vec!["[email protected]".into()]);
- // Optionally, we can also tweak the configuration parameters used in the
- // verification.
- input
- .set_from_email("[email protected]".into()) // Used in the `MAIL FROM:` command
- .set_hello_name("example.org".into()) // Used in the `EHLO` command
- .set_proxy(CheckEmailInputProxy { // Use a SOCKS5 proxy to verify the email
- host: "my-proxy.io".into(),
- port: 1080,
- username: None, // You can also set it non-empty
- password: None
- });
-
// Verify this email, using async/await syntax.
let result = check_email(&input).await;
@@ -219,7 +132,43 @@ The output will be a JSON with the below format, the fields should be self-expla
}
```
-You can also take a look at the [documentation](https://help.reacher.email/rest-api-documentation) of this JSON object.
+## What Does This Tool Check?
+
+| Included? | Feature | Description | JSON field |
+| --------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
+| ✅ | **Email reachability** | How confident are we in sending an email to this address? Can be one of `safe`, `risky`, `invalid` or `unknown`. | `is_reachable` |
+| ✅ | **Syntax validation** | Is the address syntactically valid? | `syntax.is_valid_syntax` |
+| ✅ | **DNS records validation** | Does the domain of the email address have valid MX DNS records? | `mx.accepts_mail` |
+| ✅ | **Disposable email address (DEA) validation** | Is the address provided by a known [disposable email address](https://en.wikipedia.org/wiki/Disposable_email_address) provider? | `misc.is_disposable` |
+| ✅ | **SMTP server validation** | Can the mail exchanger of the email address domain be contacted successfully? | `smtp.can_connect_smtp` |
+| ✅ | **Email deliverability** | Is an email sent to this address deliverable? | `smtp.is_deliverable` |
+| ✅ | **Mailbox disabled** | Has this email address been disabled by the email provider? | `smtp.is_disabled` |
+| ✅ | **Full inbox** | Is the inbox of this mailbox full? | `smtp.has_full_inbox` |
+| ✅ | **Catch-all address** | Is this email address a [catch-all](https://debounce.io/blog/help/what-is-a-catch-all-or-accept-all/) address? | `smtp.is_catch_all` |
+| ✅ | **Role account validation** | Is the email address a well-known role account? | `misc.is_role_account` |
+| 🔜 | **Free email provider check** | Is the email address bound to a known free email provider? | [Issue #89](https://github.com/reacherhq/check-if-email-exists/issues/89) |
+| 🔜 | **Syntax validation, provider-specific** | According to the syntactic rules of the target mail provider, is the address syntactically valid? | [Issue #90](https://github.com/reacherhq/check-if-email-exists/issues/90) |
+| 🔜 | **Honeypot detection** | Does email address under test hide a [honeypot](https://en.wikipedia.org/wiki/Spamtrap)? | [Issue #91](https://github.com/reacherhq/check-if-email-exists/issues/91) |
+| 🔜 | **Gravatar** | Does this email address have a [Gravatar](https://gravatar.com/) profile picture? | [Issue #92](https://github.com/reacherhq/check-if-email-exists/issues/92) |
+| 🔜 | **Have I Been Pwned?** | Has this email been compromised in a [data breach](https://haveibeenpwned.com/)? | [Issue #289](https://github.com/reacherhq/check-if-email-exists/issues/289) |
+
+## 🤔 Why?
+
+Many online services (https://hunter.io, https://verify-email.org, https://email-checker.net) offer this service for a paid fee. Here is an open-source alternative to those tools.
+
+## License
+
+`check-if-email-exists`'s source code is provided under a **dual license model**.
+
+### Commercial license
+
+If you want to use `check-if-email-exists` to develop commercial sites, tools, and applications, the Commercial License is the appropriate license. With this option, your source code is kept proprietary. Purchase a `check-if-email-exists` Commercial License at https://reacher.email/pricing.
+
+### Open source license
+
+If you are creating an open-source application under a license compatible with the GNU Affero GPL license v3, you may use `check-if-email-exists` under the terms of the [AGPL-3.0](./LICENSE.AGPL).
+
+[➡️ Read more](https://help.reacher.email/reacher-licenses) about Reacher's license.
## ❓ FAQ
@@ -229,30 +178,14 @@ This means that the server does not allow real-time verification of an email rig
#### The library hangs/takes a long time/doesn't show anything after 1 minute.
-Most ISPs block outgoing SMTP requests through port 25, to prevent spam. `check-if-email-exists` needs to have this port open to make a connection to the email's SMTP server, so won't work behind these ISPs, and will instead hang until it times out. There's unfortunately no easy workaround for this problem, see for example [this StackOverflow thread](https://stackoverflow.com/questions/18139102/how-to-get-around-an-isp-block-on-port-25-for-smtp). One solution is to rent a Linux cloud server with a static IP and no blocked ports, see for example our [Deploy to Heroku](#2-deploy-to-heroku) section.
+Most ISPs block outgoing SMTP requests through port 25, to prevent spam. `check-if-email-exists` needs to have this port open to make a connection to the email's SMTP server, so won't work behind these ISPs, and will instead hang until it times out. There's unfortunately no easy workaround for this problem, see for example [this StackOverflow thread](https://stackoverflow.com/questions/18139102/how-to-get-around-an-isp-block-on-port-25-for-smtp). One solution is to rent a Linux cloud server with a static IP and no blocked ports, see for example our [Self-Host Guide](https://help.reacher.email/self-host-guide) for which cloud providers open port 25.
-To see in detail what the binary is doing behind the scenes, run it in verbose mode to see the logs.
+To see in detail what the binary is doing behind the scenes, run it in verbose mode with `RUST_LOG=debug` to see the logs.
-#### I have another question
+#### I have another question.
Feel free to check out Reacher's [FAQ](https://help.reacher.email/faq).
## 🔨 Build From Source
-First, [install Rust](https://www.rust-lang.org/tools/install); you'll need Rust 1.37.0 or later. Then, run the following commands:
-
-```bash
-# Download the code
-$ git clone https://github.com/reacherhq/check-if-email-exists
-$ cd check-if-email-exists
-
-# Build in release mode
-$ cargo build --release
-
-# Run the binary
-$ ./target/release/check_if_email_exists --help
-```
-
-## Legacy Bash Script
-
-The 1st version of this tool was a simple bash script that made a telnet call. If you would like to use that simpler version, have a look at the [`legacy`](https://github.com/reacherhq/check-if-email-exists/tree/legacy) branch. The reasons for porting the bash script to the current codebase are explained [in issue #4](https://github.com/reacherhq/check-if-email-exists/issues/4).
+Build the [CLI from source](./cli/README.md#build-from-source) or the [HTTP backend from source](./backend/README.md#build-from-source).
diff --git a/backend/.dockerignore b/backend/.dockerignore
new file mode 100644
index 00000000..342ee837
--- /dev/null
+++ b/backend/.dockerignore
@@ -0,0 +1,2 @@
+target/
+Dockerfile
diff --git a/backend/.env.example b/backend/.env.example
new file mode 100644
index 00000000..95db3e2c
--- /dev/null
+++ b/backend/.env.example
@@ -0,0 +1 @@
+DATABASE_URL=postgres://localhost/reacherdb
diff --git a/backend/Cargo.toml b/backend/Cargo.toml
new file mode 100644
index 00000000..d34fd074
--- /dev/null
+++ b/backend/Cargo.toml
@@ -0,0 +1,23 @@
+[package]
+name = "reacher_backend"
+version = "0.4.0"
+edition = "2018"
+license = "AGPL-3.0"
+publish = false
+
+[dependencies]
+async-smtp = "0.5"
+check-if-email-exists = "0.8.32"
+csv = "1.1.6"
+dotenv = "0.15.0"
+env_logger = "0.9"
+log = "0.4"
+openssl = { version = "0.10.41", features = ["vendored"] }
+sentry = "0.23"
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
+sqlx = { version = "0.6", features = [ "runtime-tokio-native-tls", "postgres", "uuid", "chrono", "json", "offline", "migrate" ] }
+sqlxmq = "0.4"
+tokio = { version = "1.20", features = ["macros"] }
+uuid = "1.1"
+warp = "0.3"
diff --git a/backend/Dockerfile b/backend/Dockerfile
new file mode 100644
index 00000000..d45dd557
--- /dev/null
+++ b/backend/Dockerfile
@@ -0,0 +1,45 @@
+# From https://shaneutt.com/blog/rust-fast-small-docker-image-builds/
+
+# ------------------------------------------------------------------------------
+# Cargo Build Stage
+# ------------------------------------------------------------------------------
+
+FROM messense/rust-musl-cross:x86_64-musl as cargo-build
+
+WORKDIR /usr/src/reacher
+
+RUN rm -f target/x86_64-unknown-linux-musl/release/deps/reacher*
+
+COPY . .
+
+ENV SQLX_OFFLINE=true
+
+RUN cargo build --release --target=x86_64-unknown-linux-musl
+
+# ------------------------------------------------------------------------------
+# Final Stage
+# ------------------------------------------------------------------------------
+
+FROM alpine:latest
+
+RUN addgroup -g 1000 reacher
+
+RUN adduser -D -s /bin/sh -u 1000 -G reacher reacher
+
+WORKDIR /home/reacher/bin/
+
+COPY --from=cargo-build /usr/src/reacher/target/x86_64-unknown-linux-musl/release/reacher_backend .
+
+RUN chown reacher:reacher reacher_backend
+
+USER reacher
+
+ENV RUST_LOG=reacher=info
+ENV RCH_HTTP_HOST=0.0.0.0
+ENV PORT=8080
+# Bulk verification is disabled by default. Set to 1 to enable it.
+ENV RCH_ENABLE_BULK=0
+
+EXPOSE 8080
+
+CMD ["./reacher_backend"]
diff --git a/backend/README.md b/backend/README.md
new file mode 100644
index 00000000..a43f0921
--- /dev/null
+++ b/backend/README.md
@@ -0,0 +1,112 @@
+[![Docker](https://img.shields.io/docker/v/reacherhq/backend?color=0db7ed&label=docker&sort=date)](https://hub.docker.com/r/reacherhq/backend)
+[![Actions Status](https://github.com/reacherhq/check-if-email-exists/workflows/pr/badge.svg)](https://github.com/reacherhq/check-if-email-exists/actions)
+[![Github Sponsor](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&link=https://github.com/sponsors/amaurym)](https://github.com/sponsors/amaurym)
+
+<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 Backend</h1>
+<h4 align="center">REST Server for Reacher Email Verification API: https://reacher.email.</h4>
+
+<br /><br />
+
+This create holds the backend for [Reacher](https://reacher.email). The backend is a HTTP server with the following components:
+
+- [`check-if-email-exists`](https://github.com/reacherhq/check-if-email-exists), which performs the core email verification logic,
+- [`warp`](https://github.com/seanmonstar/warp) web framework.
+
+> 💡 Update: Bulk email verification is currently being worked on, and is in **beta** phase. You can try to use the bulk verification endpoints by setting the environment variable `RCH_ENABLE_BULK=1`. The documentation is currently being [worked on](https://github.com/reacherhq/backend/issues/321).
+
+## Get Started
+
+The [Docker image](./Dockerfile) is hosted on Docker Hub: https://hub.docker.com/r/reacherhq/backend.
+
+To run it, run the following command:
+
+```bash
+docker run -p 8080:8080 reacherhq/backend:latest
+```
+
+Then send a `POST http://localhost:8080/v0/check_email` request with the following body:
+
+```js
+{
+ "to_email": "[email protected]",
+ "from_email": "[email protected]", // (optional) email to use in the `FROM` SMTP command, defaults to "[email protected]"
+ "hello_name": "my-server.com", // (optional) name to use in the `EHLO` SMTP command, defaults to "localhost"
+ "proxy": { // (optional) SOCK5 proxy to run the verification through, default is empty
+ "host": "my-proxy.io",
+ "port": 1080,
+ "username": "me", // (optional) Proxy username
+ "password": "pass" // (optional) Proxy password
+ },
+ "smtp_port": 587 // (optional) SMTP port to do the email verification, defaults to 25
+}
+```
+
+### Configuration
+
+These are the environment variables used to configure the HTTP server. To pass them to the Docker container, use the `-e {ENV_VAR}={VALUE}` flag.
+
+| Env Var | Required? | Description | Default |
+| ----------------------------------- | --------------------------- | ---------------------------------------------------------------------------------------------------------- | ------------------ |
+| `RCH_ENABLE_BULK` | No | If set to 1, then bulk verification endpoints will be added to the backend. | 0 |
+| `DATABASE_URL` | Yes if `RCH_ENABLE_BULK==1` | Database connection string for storing results and task queue | not defined |
+| `RCH_HTTP_HOST` | No | The host name to bind the HTTP server to. | `127.0.0.1` |
+| `PORT` | No | The port to bind the HTTP server to, often populated by the cloud provider. | `8080` |
+| `RCH_FROM_EMAIL` | No | The email to use in the `MAIL FROM:` SMTP command. | `[email protected]` |
+| `RCH_SENTRY_DSN` | No | If set, bug reports will be sent to this [Sentry](https://sentry.io) DSN. | not defined |
+| `RCH_DATABASE_MAX_CONNECTIONS` | No | (Bulk) Connections created for the database pool | 5 |
+| `RCH_MINIMUM_TASK_CONCURRENCY` | No | (Bulk) Minimum number of concurrent running tasks below which more tasks are fetched | 10 |
+| `RCH_MAXIMUM_CONCURRENT_TASK_FETCH` | No | (Bulk) Maximum number of tasks fetched at once | 20 |
+| `RUST_LOG` | No | One of `trace,debug,warn,error,info`. 💡 PRO TIP: `RUST_LOG=debug` is very handful for debugging purposes. | not defined |
+
+## REST API Documentation
+
+Read docs on https://help.reacher.email/rest-api-documentation.
+
+The API exposes the following endpoint: `POST /v0/check_email` expecting the following body:
+
+```js
+{
+ "to_email": "[email protected]",
+ "from_email": "[email protected]", // (optional) email to use in the `FROM` SMTP command, defaults to "[email protected]"
+ "hello_name": "my-server.com", // (optional) name to use in the `EHLO` SMTP command, defaults to "localhost"
+ "proxy": { // (optional) SOCK5 proxy to run the verification through, default is empty
+ "host": "my-proxy.io",
+ "port": 1080,
+ "username": "me", // (optional) Proxy username
+ "password": "pass" // (optional) Proxy password
+ },
+ "smtp_port": 587 // (optional) SMTP port to do the email verification, defaults to 25
+}
+```
+
+For example, you can send the following `curl` request:
+
+```bash
+curl -X POST \
+ -H'Content-Type: application/json' \
+ -d'{"to_email":"[email protected]"}' \
+ http://localhost:8080/v0/check_email
+```
+
+Also check the [OpenAPI documentation](https://help.reacher.email/rest-api-documentation).
+
+## Build From Source
+
+You can build the backend from source to generate a binary, and run the server locally on your machine. First, [install Rust](https://www.rust-lang.org/tools/install); you'll need Rust 1.37.0 or later. Make sure `openssl` is installed too. Then, run the following commands:
+
+```bash
+# Download the code
+$ git clone https://github.com/reacherhq/check-if-email-exists
+$ cd check-if-email-exists
+
+# Build the backend binary in release mode (more performant).
+$ cargo build --release --bin reacher_backend
+
+# Run the binary with some useful logs.
+$ RUST_LOG=info ./target/release/reacher_backend
+```
+
+The server will then be listening on `http://127.0.0.1:8080`.
diff --git a/backend/SETUP.md b/backend/SETUP.md
new file mode 100644
index 00000000..417acd2d
--- /dev/null
+++ b/backend/SETUP.md
@@ -0,0 +1,8 @@
+## Dev environment installation
+
+1. Install [docker](https://docs.docker.com/get-docker/)
+2. Run the following command to get a postgresql database running - `docker run --name <container-name> -p 5432:5432 -e POSTGRES_PASSWORD=<password> -d postgres:14`. Note that default user and database is postgres.
+3. Download migrations from [sqlxmq](https://github.com/Diggsey/sqlxmq#database-schema) to setup database for message queue.
+4. Install [psql](https://blog.timescale.com/blog/how-to-install-psql-on-mac-ubuntu-debian-windows/) to apply migrations to db.
+5. Use `cargo install rargs` and run the following to apply migrations - `ls migrations/**/*up.sql | rargs psql postgres://postgres:<password>@localhost/postgres -f {0}`
+6. Add a `.env` file with a single key for the connection string `DATABASE_URL=postgres://postgres:<password>@localhost/postgres`. This will be read by the application at runtime from the environment and be used to connect to the environment. This will also be used by sqlx to verify sql queries at compile time. **NOTE:** You only need to run this migration once for a fresh database.
diff --git a/backend/migrations/20210316025847_setup.down.sql b/backend/migrations/20210316025847_setup.down.sql
new file mode 100644
index 00000000..1aa472e8
--- /dev/null
+++ b/backend/migrations/20210316025847_setup.down.sql
@@ -0,0 +1,12 @@
+DROP FUNCTION mq_checkpoint;
+DROP FUNCTION mq_keep_alive;
+DROP FUNCTION mq_delete;
+DROP FUNCTION mq_commit;
+DROP FUNCTION mq_insert;
+DROP FUNCTION mq_poll;
+DROP FUNCTION mq_active_channels;
+DROP FUNCTION mq_latest_message;
+DROP TABLE mq_payloads;
+DROP TABLE mq_msgs;
+DROP FUNCTION mq_uuid_exists;
+DROP TYPE mq_new_t;
diff --git a/backend/migrations/20210316025847_setup.up.sql b/backend/migrations/20210316025847_setup.up.sql
new file mode 100644
index 00000000..bf7f8f85
--- /dev/null
+++ b/backend/migrations/20210316025847_setup.up.sql
@@ -0,0 +1,289 @@
+CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
+
+-- The UDT for creating messages
+CREATE TYPE mq_new_t AS (
+ -- Unique message ID
+ id UUID,
+ -- Delay before message is processed
+ delay INTERVAL,
+ -- Number of retries if initial processing fails
+ retries INT,
+ -- Initial backoff between retries
+ retry_backoff INTERVAL,
+ -- Name of channel
+ channel_name TEXT,
+ -- Arguments to channel
+ channel_args TEXT,
+ -- Interval for two-phase commit (or NULL to disable two-phase commit)
+ commit_interval INTERVAL,
+ -- Whether this message should be processed in order with respect to other
+ -- ordered messages.
+ ordered BOOLEAN,
+ -- Name of message
+ name TEXT,
+ -- JSON payload
+ payload_json TEXT,
+ -- Binary payload
+ payload_bytes BYTEA
+);
+
+-- Small, frequently updated table of messages
+CREATE TABLE mq_msgs (
+ id UUID PRIMARY KEY,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ attempt_at TIMESTAMPTZ DEFAULT NOW(),
+ attempts INT NOT NULL DEFAULT 5,
+ retry_backoff INTERVAL NOT NULL DEFAULT INTERVAL '1 second',
+ channel_name TEXT NOT NULL,
+ channel_args TEXT NOT NULL,
+ commit_interval INTERVAL,
+ after_message_id UUID DEFAULT uuid_nil() REFERENCES mq_msgs(id) ON DELETE SET DEFAULT
+);
+
+-- Insert dummy message so that the 'nil' UUID can be referenced
+INSERT INTO mq_msgs (id, channel_name, channel_args, after_message_id) VALUES (uuid_nil(), '', '', NULL);
+
+-- Internal helper function to check that a UUID is neither NULL nor NIL
+CREATE FUNCTION mq_uuid_exists(
+ id UUID
+) RETURNS BOOLEAN AS $$
+ SELECT id IS NOT NULL AND id != uuid_nil()
+$$ LANGUAGE SQL IMMUTABLE;
+
+-- Index for polling
+CREATE INDEX ON mq_msgs(channel_name, channel_args, attempt_at) WHERE id != uuid_nil() AND NOT mq_uuid_exists(after_message_id);
+-- Index for adding messages
+CREATE INDEX ON mq_msgs(channel_name, channel_args, created_at, id) WHERE id != uuid_nil() AND after_message_id IS NOT NULL;
+
+-- Index for ensuring strict message order
+CREATE UNIQUE INDEX mq_msgs_channel_name_channel_args_after_message_id_idx ON mq_msgs(channel_name, channel_args, after_message_id);
+
+
+-- Large, less frequently updated table of message payloads
+CREATE TABLE mq_payloads(
+ id UUID PRIMARY KEY,
+ name TEXT NOT NULL,
+ payload_json JSONB,
+ payload_bytes BYTEA
+);
+
+-- Internal helper function to return the most recently added message in a queue.
+CREATE FUNCTION mq_latest_message(from_channel_name TEXT, from_channel_args TEXT)
+RETURNS UUID AS $$
+ SELECT COALESCE(
+ (
+ SELECT id FROM mq_msgs
+ WHERE channel_name = from_channel_name
+ AND channel_args = from_channel_args
+ AND after_message_id IS NOT NULL
+ AND id != uuid_nil()
+ ORDER BY created_at DESC, id DESC
+ LIMIT 1
+ ),
+ uuid_nil()
+ )
+$$ LANGUAGE SQL STABLE;
+
+-- Internal helper function to randomly select a set of channels with "ready" messages.
+CREATE FUNCTION mq_active_channels(channel_names TEXT[], batch_size INT)
+RETURNS TABLE(name TEXT, args TEXT) AS $$
+ SELECT channel_name, channel_args
+ FROM mq_msgs
+ WHERE id != uuid_nil()
+ AND attempt_at <= NOW()
+ AND (channel_names IS NULL OR channel_name = ANY(channel_names))
+ AND NOT mq_uuid_exists(after_message_id)
+ GROUP BY channel_name, channel_args
+ ORDER BY RANDOM()
+ LIMIT batch_size
+$$ LANGUAGE SQL STABLE;
+
+-- Main entry-point for job runner: pulls a batch of messages from the queue.
+CREATE FUNCTION mq_poll(channel_names TEXT[], batch_size INT DEFAULT 1)
+RETURNS TABLE(
+ id UUID,
+ is_committed BOOLEAN,
+ name TEXT,
+ payload_json TEXT,
+ payload_bytes BYTEA,
+ retry_backoff INTERVAL,
+ wait_time INTERVAL
+) AS $$
+BEGIN
+ RETURN QUERY UPDATE mq_msgs
+ SET
+ attempt_at = CASE WHEN mq_msgs.attempts = 1 THEN NULL ELSE NOW() + mq_msgs.retry_backoff END,
+ attempts = mq_msgs.attempts - 1,
+ retry_backoff = mq_msgs.retry_backoff * 2
+ FROM (
+ SELECT
+ msgs.id
+ FROM mq_active_channels(channel_names, batch_size) AS active_channels
+ INNER JOIN LATERAL (
+ SELECT * FROM mq_msgs
+ WHERE mq_msgs.id != uuid_nil()
+ AND mq_msgs.attempt_at <= NOW()
+ AND mq_msgs.channel_name = active_channels.name
+ AND mq_msgs.channel_args = active_channels.args
+ AND NOT mq_uuid_exists(mq_msgs.after_message_id)
+ ORDER BY mq_msgs.attempt_at ASC
+ LIMIT batch_size
+ ) AS msgs ON TRUE
+ LIMIT batch_size
+ ) AS messages_to_update
+ LEFT JOIN mq_payloads ON mq_payloads.id = messages_to_update.id
+ WHERE mq_msgs.id = messages_to_update.id
+ RETURNING
+ mq_msgs.id,
+ mq_msgs.commit_interval IS NULL,
+ mq_payloads.name,
+ mq_payloads.payload_json::TEXT,
+ mq_payloads.payload_bytes,
+ mq_msgs.retry_backoff / 2,
+ interval '0' AS wait_time;
+
+ IF NOT FOUND THEN
+ RETURN QUERY SELECT
+ NULL::UUID,
+ NULL::BOOLEAN,
+ NULL::TEXT,
+ NULL::TEXT,
+ NULL::BYTEA,
+ NULL::INTERVAL,
+ MIN(mq_msgs.attempt_at) - NOW()
+ FROM mq_msgs
+ WHERE mq_msgs.id != uuid_nil()
+ AND NOT mq_uuid_exists(mq_msgs.after_message_id)
+ AND (channel_names IS NULL OR mq_msgs.channel_name = ANY(channel_names));
+ END IF;
+END;
+$$ LANGUAGE plpgsql;
+
+-- Creates new messages
+CREATE FUNCTION mq_insert(new_messages mq_new_t[])
+RETURNS VOID AS $$
+BEGIN
+ PERFORM pg_notify(CONCAT('mq_', channel_name), '')
+ FROM unnest(new_messages) AS new_msgs
+ GROUP BY channel_name;
+
+ IF FOUND THEN
+ PERFORM pg_notify('mq', '');
+ END IF;
+
+ INSERT INTO mq_payloads (
+ id,
+ name,
+ payload_json,
+ payload_bytes
+ ) SELECT
+ id,
+ name,
+ payload_json::JSONB,
+ payload_bytes
+ FROM UNNEST(new_messages);
+
+ INSERT INTO mq_msgs (
+ id,
+ attempt_at,
+ attempts,
+ retry_backoff,
+ channel_name,
+ channel_args,
+ commit_interval,
+ after_message_id
+ )
+ SELECT
+ id,
+ NOW() + delay + COALESCE(commit_interval, INTERVAL '0'),
+ retries + 1,
+ retry_backoff,
+ channel_name,
+ channel_args,
+ commit_interval,
+ CASE WHEN ordered
+ THEN
+ LAG(id, 1, mq_latest_message(channel_name, channel_args))
+ OVER (PARTITION BY channel_name, channel_args, ordered ORDER BY id)
+ ELSE
+ NULL
+ END
+ FROM UNNEST(new_messages);
+END;
+$$ LANGUAGE plpgsql;
+
+-- Commits messages previously created with a non-NULL commit interval.
+CREATE FUNCTION mq_commit(msg_ids UUID[])
+RETURNS VOID AS $$
+BEGIN
+ UPDATE mq_msgs
+ SET
+ attempt_at = attempt_at - commit_interval,
+ commit_interval = NULL
+ WHERE id = ANY(msg_ids)
+ AND commit_interval IS NOT NULL;
+END;
+$$ LANGUAGE plpgsql;
+
+
+-- Deletes messages from the queue. This occurs when a message has been
+-- processed, or when it expires without being processed.
+CREATE FUNCTION mq_delete(msg_ids UUID[])
+RETURNS VOID AS $$
+BEGIN
+ PERFORM pg_notify(CONCAT('mq_', channel_name), '')
+ FROM mq_msgs
+ WHERE id = ANY(msg_ids)
+ AND after_message_id = uuid_nil()
+ GROUP BY channel_name;
+
+ IF FOUND THEN
+ PERFORM pg_notify('mq', '');
+ END IF;
+
+ DELETE FROM mq_msgs WHERE id = ANY(msg_ids);
+ DELETE FROM mq_payloads WHERE id = ANY(msg_ids);
+END;
+$$ LANGUAGE plpgsql;
+
+
+-- Can be called during the initial commit interval, or when processing
+-- a message. Indicates that the caller is still active and will prevent either
+-- the commit interval elapsing or the message being retried for the specified
+-- interval.
+CREATE FUNCTION mq_keep_alive(msg_ids UUID[], duration INTERVAL)
+RETURNS VOID AS $$
+ UPDATE mq_msgs
+ SET
+ attempt_at = NOW() + duration,
+ commit_interval = commit_interval + ((NOW() + duration) - attempt_at)
+ WHERE id = ANY(msg_ids)
+ AND attempt_at < NOW() + duration;
+$$ LANGUAGE SQL;
+
+
+-- Called during lengthy processing of a message to checkpoint the progress.
+-- As well as behaving like `mq_keep_alive`, the message payload can be
+-- updated.
+CREATE FUNCTION mq_checkpoint(
+ msg_id UUID,
+ duration INTERVAL,
+ new_payload_json TEXT,
+ new_payload_bytes BYTEA,
+ extra_retries INT
+)
+RETURNS VOID AS $$
+ UPDATE mq_msgs
+ SET
+ attempt_at = GREATEST(attempt_at, NOW() + duration),
+ attempts = attempts + COALESCE(extra_retries, 0)
+ WHERE id = msg_id;
+
+ UPDATE mq_payloads
+ SET
+ payload_json = COALESCE(new_payload_json::JSONB, payload_json),
+ payload_bytes = COALESCE(new_payload_bytes, payload_bytes)
+ WHERE
+ id = msg_id;
+$$ LANGUAGE SQL;
+
diff --git a/backend/migrations/20210921115907_clear.down.sql b/backend/migrations/20210921115907_clear.down.sql
new file mode 100644
index 00000000..e15638db
--- /dev/null
+++ b/backend/migrations/20210921115907_clear.down.sql
@@ -0,0 +1,2 @@
+DROP FUNCTION mq_clear;
+DROP FUNCTION mq_clear_all;
diff --git a/backend/migrations/20210921115907_clear.up.sql b/backend/migrations/20210921115907_clear.up.sql
new file mode 100644
index 00000000..bd1c1f60
--- /dev/null
+++ b/backend/migrations/20210921115907_clear.up.sql
@@ -0,0 +1,21 @@
+-- Deletes all messages from a list of channel names.
+CREATE FUNCTION mq_clear(channel_names TEXT[])
+RETURNS VOID AS $$
+BEGIN
+ WITH deleted_ids AS (
+ DELETE FROM mq_msgs WHERE channel_name = ANY(channel_names) RETURNING id
+ )
+ DELETE FROM mq_payloads WHERE id IN (SELECT id FROM deleted_ids);
+END;
+$$ LANGUAGE plpgsql;
+
+-- Deletes all messages.
+CREATE FUNCTION mq_clear_all()
+RETURNS VOID AS $$
+BEGIN
+ WITH deleted_ids AS (
+ DELETE FROM mq_msgs RETURNING id
+ )
+ DELETE FROM mq_payloads WHERE id IN (SELECT id FROM deleted_ids);
+END;
+$$ LANGUAGE plpgsql;
diff --git a/backend/migrations/20211013151757_fix_mq_latest_message.down.sql b/backend/migrations/20211013151757_fix_mq_latest_message.down.sql
new file mode 100644
index 00000000..d09bd4af
--- /dev/null
+++ b/backend/migrations/20211013151757_fix_mq_latest_message.down.sql
@@ -0,0 +1,15 @@
+CREATE OR REPLACE FUNCTION mq_latest_message(from_channel_name TEXT, from_channel_args TEXT)
+RETURNS UUID AS $$
+ SELECT COALESCE(
+ (
+ SELECT id FROM mq_msgs
+ WHERE channel_name = from_channel_name
+ AND channel_args = from_channel_args
+ AND after_message_id IS NOT NULL
+ AND id != uuid_nil()
+ ORDER BY created_at DESC, id DESC
+ LIMIT 1
+ ),
+ uuid_nil()
+ )
+$$ LANGUAGE SQL STABLE;
diff --git a/backend/migrations/20211013151757_fix_mq_latest_message.up.sql b/backend/migrations/20211013151757_fix_mq_latest_message.up.sql
new file mode 100644
index 00000000..b987c5e1
--- /dev/null
+++ b/backend/migrations/20211013151757_fix_mq_latest_message.up.sql
@@ -0,0 +1,19 @@
+CREATE OR REPLACE FUNCTION mq_latest_message(from_channel_name TEXT, from_channel_args TEXT)
+RETURNS UUID AS $$
+ SELECT COALESCE(
+ (
+ SELECT id FROM mq_msgs
+ WHERE channel_name = from_channel_name
+ AND channel_args = from_channel_args
+ AND after_message_id IS NOT NULL
+ AND id != uuid_nil()
+ AND NOT EXISTS(
+ SELECT * FROM mq_msgs AS mq_msgs2
+ WHERE mq_msgs2.after_message_id = mq_msgs.id
+ )
+ ORDER BY created_at DESC
+ LIMIT 1
+ ),
+ uuid_nil()
+ )
+$$ LANGUAGE SQL STABLE;
\ No newline at end of file
diff --git a/backend/migrations/20220117025847_email_data.down.sql b/backend/migrations/20220117025847_email_data.down.sql
new file mode 100644
index 00000000..ed211e33
--- /dev/null
+++ b/backend/migrations/20220117025847_email_data.down.sql
@@ -0,0 +1,4 @@
+DROP INDEX job_emails;
+DROP TABLE email_results;
+DROP TABLE bulk_jobs;
+DROP TYPE valid_status;
\ No newline at end of file
diff --git a/backend/migrations/20220117025847_email_data.up.sql b/backend/migrations/20220117025847_email_data.up.sql
new file mode 100644
index 00000000..d53e83d5
--- /dev/null
+++ b/backend/migrations/20220117025847_email_data.up.sql
@@ -0,0 +1,12 @@
+CREATE TABLE bulk_jobs (
+ id SERIAL PRIMARY KEY,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ total_records INTEGER NOT NULL
+);
+CREATE TABLE email_results (
+ id SERIAL PRIMARY KEY,
+ job_id INTEGER,
+ result JSONB,
+ FOREIGN KEY (job_id) REFERENCES bulk_jobs(id)
+);
+CREATE INDEX job_emails ON email_results USING HASH (job_id);
\ No newline at end of file
diff --git a/backend/migrations/20220208120856_fix_concurrent_poll.down.sql b/backend/migrations/20220208120856_fix_concurrent_poll.down.sql
new file mode 100644
index 00000000..6cd2d21e
--- /dev/null
+++ b/backend/migrations/20220208120856_fix_concurrent_poll.down.sql
@@ -0,0 +1,60 @@
+-- Main entry-point for job runner: pulls a batch of messages from the queue.
+CREATE OR REPLACE FUNCTION mq_poll(channel_names TEXT[], batch_size INT DEFAULT 1)
+RETURNS TABLE(
+ id UUID,
+ is_committed BOOLEAN,
+ name TEXT,
+ payload_json TEXT,
+ payload_bytes BYTEA,
+ retry_backoff INTERVAL,
+ wait_time INTERVAL
+) AS $$
+BEGIN
+ RETURN QUERY UPDATE mq_msgs
+ SET
+ attempt_at = CASE WHEN mq_msgs.attempts = 1 THEN NULL ELSE NOW() + mq_msgs.retry_backoff END,
+ attempts = mq_msgs.attempts - 1,
+ retry_backoff = mq_msgs.retry_backoff * 2
+ FROM (
+ SELECT
+ msgs.id
+ FROM mq_active_channels(channel_names, batch_size) AS active_channels
+ INNER JOIN LATERAL (
+ SELECT * FROM mq_msgs
+ WHERE mq_msgs.id != uuid_nil()
+ AND mq_msgs.attempt_at <= NOW()
+ AND mq_msgs.channel_name = active_channels.name
+ AND mq_msgs.channel_args = active_channels.args
+ AND NOT mq_uuid_exists(mq_msgs.after_message_id)
+ ORDER BY mq_msgs.attempt_at ASC
+ LIMIT batch_size
+ ) AS msgs ON TRUE
+ LIMIT batch_size
+ ) AS messages_to_update
+ LEFT JOIN mq_payloads ON mq_payloads.id = messages_to_update.id
+ WHERE mq_msgs.id = messages_to_update.id
+ RETURNING
+ mq_msgs.id,
+ mq_msgs.commit_interval IS NULL,
+ mq_payloads.name,
+ mq_payloads.payload_json::TEXT,
+ mq_payloads.payload_bytes,
+ mq_msgs.retry_backoff / 2,
+ interval '0' AS wait_time;
+
+ IF NOT FOUND THEN
+ RETURN QUERY SELECT
+ NULL::UUID,
+ NULL::BOOLEAN,
+ NULL::TEXT,
+ NULL::TEXT,
+ NULL::BYTEA,
+ NULL::INTERVAL,
+ MIN(mq_msgs.attempt_at) - NOW()
+ FROM mq_msgs
+ WHERE mq_msgs.id != uuid_nil()
+ AND NOT mq_uuid_exists(mq_msgs.after_message_id)
+ AND (channel_names IS NULL OR mq_msgs.channel_name = ANY(channel_names));
+ END IF;
+END;
+$$ LANGUAGE plpgsql;
\ No newline at end of file
diff --git a/backend/migrations/20220208120856_fix_concurrent_poll.up.sql b/backend/migrations/20220208120856_fix_concurrent_poll.up.sql
new file mode 100644
index 00000000..cae6151e
--- /dev/null
+++ b/backend/migrations/20220208120856_fix_concurrent_poll.up.sql
@@ -0,0 +1,62 @@
+
+-- Main entry-point for job runner: pulls a batch of messages from the queue.
+CREATE OR REPLACE FUNCTION mq_poll(channel_names TEXT[], batch_size INT DEFAULT 1)
+RETURNS TABLE(
+ id UUID,
+ is_committed BOOLEAN,
+ name TEXT,
+ payload_json TEXT,
+ payload_bytes BYTEA,
+ retry_backoff INTERVAL,
+ wait_time INTERVAL
+) AS $$
+BEGIN
+ RETURN QUERY UPDATE mq_msgs
+ SET
+ attempt_at = CASE WHEN mq_msgs.attempts = 1 THEN NULL ELSE NOW() + mq_msgs.retry_backoff END,
+ attempts = mq_msgs.attempts - 1,
+ retry_backoff = mq_msgs.retry_backoff * 2
+ FROM (
+ SELECT
+ msgs.id
+ FROM mq_active_channels(channel_names, batch_size) AS active_channels
+ INNER JOIN LATERAL (
+ SELECT mq_msgs.id FROM mq_msgs
+ WHERE mq_msgs.id != uuid_nil()
+ AND mq_msgs.attempt_at <= NOW()
+ AND mq_msgs.channel_name = active_channels.name
+ AND mq_msgs.channel_args = active_channels.args
+ AND NOT mq_uuid_exists(mq_msgs.after_message_id)
+ ORDER BY mq_msgs.attempt_at ASC
+ LIMIT batch_size
+ ) AS msgs ON TRUE
+ LIMIT batch_size
+ ) AS messages_to_update
+ LEFT JOIN mq_payloads ON mq_payloads.id = messages_to_update.id
+ WHERE mq_msgs.id = messages_to_update.id
+ AND mq_msgs.attempt_at <= NOW()
+ RETURNING
+ mq_msgs.id,
+ mq_msgs.commit_interval IS NULL,
+ mq_payloads.name,
+ mq_payloads.payload_json::TEXT,
+ mq_payloads.payload_bytes,
+ mq_msgs.retry_backoff / 2,
+ interval '0' AS wait_time;
+
+ IF NOT FOUND THEN
+ RETURN QUERY SELECT
+ NULL::UUID,
+ NULL::BOOLEAN,
+ NULL::TEXT,
+ NULL::TEXT,
+ NULL::BYTEA,
+ NULL::INTERVAL,
+ MIN(mq_msgs.attempt_at) - NOW()
+ FROM mq_msgs
+ WHERE mq_msgs.id != uuid_nil()
+ AND NOT mq_uuid_exists(mq_msgs.after_message_id)
+ AND (channel_names IS NULL OR mq_msgs.channel_name = ANY(channel_names));
+ END IF;
+END;
+$$ LANGUAGE plpgsql;
diff --git a/backend/migrations/20220713122907_fix-clear_all-keep-nil-message.down.sql b/backend/migrations/20220713122907_fix-clear_all-keep-nil-message.down.sql
new file mode 100644
index 00000000..d2f607c5
--- /dev/null
+++ b/backend/migrations/20220713122907_fix-clear_all-keep-nil-message.down.sql
@@ -0,0 +1 @@
+-- Add down migration script here
diff --git a/backend/migrations/20220713122907_fix-clear_all-keep-nil-message.up.sql b/backend/migrations/20220713122907_fix-clear_all-keep-nil-message.up.sql
new file mode 100644
index 00000000..4dd1f0b3
--- /dev/null
+++ b/backend/migrations/20220713122907_fix-clear_all-keep-nil-message.up.sql
@@ -0,0 +1,29 @@
+CREATE OR REPLACE FUNCTION mq_clear(channel_names TEXT[])
+RETURNS VOID AS $$
+BEGIN
+ WITH deleted_ids AS (
+ DELETE FROM mq_msgs
+ WHERE channel_name = ANY(channel_names)
+ AND id != uuid_nil()
+ RETURNING id
+ )
+ DELETE FROM mq_payloads WHERE id IN (SELECT id FROM deleted_ids);
+END;
+$$ LANGUAGE plpgsql;
+COMMENT ON FUNCTION mq_clear IS
+ 'Deletes all messages with corresponding payloads from a list of channel names';
+
+
+CREATE OR REPLACE FUNCTION mq_clear_all()
+RETURNS VOID AS $$
+BEGIN
+ WITH deleted_ids AS (
+ DELETE FROM mq_msgs
+ WHERE id != uuid_nil()
+ RETURNING id
+ )
+ DELETE FROM mq_payloads WHERE id IN (SELECT id FROM deleted_ids);
+END;
+$$ LANGUAGE plpgsql;
+COMMENT ON FUNCTION mq_clear_all IS
+ 'Deletes all messages with corresponding payloads';
diff --git a/backend/migrations/20220810141100_result_created_at.down.sql b/backend/migrations/20220810141100_result_created_at.down.sql
new file mode 100644
index 00000000..80b95f10
--- /dev/null
+++ b/backend/migrations/20220810141100_result_created_at.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE email_results
+DROP COLUMN created_at;
diff --git a/backend/migrations/20220810141100_result_created_at.up.sql b/backend/migrations/20220810141100_result_created_at.up.sql
new file mode 100644
index 00000000..ab28f019
--- /dev/null
+++ b/backend/migrations/20220810141100_result_created_at.up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE email_results
+ADD created_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
\ No newline at end of file
diff --git a/backend/migrations/README.md b/backend/migrations/README.md
new file mode 100644
index 00000000..5d9c3206
--- /dev/null
+++ b/backend/migrations/README.md
@@ -0,0 +1,32 @@
+# 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.
+
+The migrations come from 2 sources:
+- `sqlxmq` migrations
+- Reacher's own migrations
+
+## `sqlxmq` migrations
+
+The following migration files have been copied from the [sqlxmq repo](https://github.com/Diggsey/sqlxmq) as per the [given instructions](https://github.com/Diggsey/sqlxmq/blob/6d3ed6fb99e7592e370a7f3ec074ce0bebae62fd/README.md?plain=1#L111):
+
+- `20210316025847_setup.{up,down}.sql`
+- `20210921115907_clear.{up,down}.sql`
+- `20211013151757_fix_mq_latest_message.{up,down}.sql`
+- `20220208120856_fix_concurrent_poll.{up,down}.sql`
+- `20220713122907_fix-clear_all-keep-nil-message.{up,down}.sql`
+
+## Reacher migrations
+
+The following migrations are specific to Reacher:
+
+- `20220117025847_email_data.down.sql`: set up the `bulk_jobs` and `email_results` tables
+- `20220810141100_result_created_at.down.sql`: add a `created_at` column on `email_result`
+
+## 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.md
diff --git a/backend/openapi.json b/backend/openapi.json
new file mode 100644
index 00000000..d4228200
--- /dev/null
+++ b/backend/openapi.json
@@ -0,0 +1,348 @@
+{
+ "openapi": "3.0.0",
+ "info": {
+ "title": "Reacher",
+ "version": "0.3.*",
+ "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.",
+ "license": {
+ "name": "AGPL-3.0 OR Commercial",
+ "url": "https://github.com/reacherhq/backend/blob/master/LICENSE.md"
+ },
+ "contact": {
+ "name": "Reacher",
+ "url": "https://reacher.email",
+ "email": "[email protected]"
+ },
+ "termsOfService": "https://github.com/reacherhq/policies/blob/master/terms/index.fr.md"
+ },
+ "servers": [
+ {
+ "url": "https://api.reacher.email/v0",
+ "description": "Reacher Production"
+ }
+ ],
+ "paths": {
+ "/check_email": {
+ "post": {
+ "summary": "/check_email",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CheckEmailOutput"
+ },
+ "examples": {
+ "Example with [email protected]": {
+ "value": {
+ "input": "[email protected]",
+ "is_reachable": "invalid",
+ "misc": {
+ "is_disposable": false,
+ "is_role_account": true
+ },
+ "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."
+ ]
+ },
+ "smtp": {
+ "can_connect_smtp": true,
+ "has_full_inbox": false,
+ "is_catch_all": false,
+ "is_deliverable": false,
+ "is_disabled": false
+ },
+ "syntax": {
+ "domain": "gmail.com",
+ "is_valid_syntax": true,
+ "username": "test"
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "operationId": "post-check-email",
+ "description": "Perform a full verification of an email address.",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CheckEmailInput"
+ }
+ }
+ },
+ "description": "Input containing all parameters necessary for an email verification."
+ },
+ "parameters": [
+ {
+ "schema": {
+ "type": "string"
+ },
+ "in": "header",
+ "name": "Authorization",
+ "description": "Your personal Reacher API key",
+ "required": true
+ }
+ ]
+ },
+ "parameters": []
+ }
+ },
+ "components": {
+ "schemas": {
+ "CheckEmailOutput": {
+ "title": "CheckEmailOutput",
+ "type": "object",
+ "x-examples": {
+ "Example with [email protected]": {
+ "input": "[email protected]",
+ "is_reachable": "invalid",
+ "misc": {
+ "is_disposable": false,
+ "is_role_account": true
+ },
+ "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."
+ ]
+ },
+ "smtp": {
+ "can_connect_smtp": true,
+ "has_full_inbox": false,
+ "is_catch_all": false,
+ "is_deliverable": false,
+ "is_disabled": false
+ },
+ "syntax": {
+ "domain": "gmail.com",
+ "is_valid_syntax": true,
+ "username": "test"
+ }
+ }
+ },
+ "description": "The verification result of an email.",
+ "properties": {
+ "input": {
+ "type": "string",
+ "format": "email",
+ "description": "The input email address."
+ },
+ "is_reachable": {
+ "$ref": "#/components/schemas/Reachable"
+ },
+ "misc": {
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/MiscDetails"
+ },
+ {
+ "$ref": "#/components/schemas/Error"
+ }
+ ],
+ "description": "Miscellaneous information about the email account."
+ },
+ "mx": {
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/MxDetails"
+ },
+ {
+ "$ref": "#/components/schemas/Error"
+ }
+ ],
+ "description": "Information gathered from querying the MX records of the mail server."
+ },
+ "smtp": {
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/SmtpDetails"
+ },
+ {
+ "$ref": "#/components/schemas/Error"
+ }
+ ],
+ "description": "Verifications performed by connecting to the mail server via SMTP."
+ },
+ "syntax": {
+ "$ref": "#/components/schemas/SyntaxDetails"
+ }
+ },
+ "required": ["input", "misc", "mx", "smtp", "syntax", "is_reachable"]
+ },
+ "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"]
+ },
+ "MiscDetails": {
+ "title": "MiscDetails",
+ "type": "object",
+ "description": "Miscellaneous information about the email account.",
+ "properties": {
+ "is_disposable": {
+ "type": "boolean",
+ "description": "Is the address provided by a known disposable email address provider?"
+ },
+ "is_role_account": {
+ "type": "boolean",
+ "description": "Is this email a role-based account?"
+ }
+ },
+ "required": ["is_disposable", "is_role_account"]
+ },
+ "MxDetails": {
+ "title": "MxDetails",
+ "type": "object",
+ "properties": {
+ "accepts_mail": {
+ "type": "boolean",
+ "description": "Does the server accept mails?"
+ },
+ "records": {
+ "type": "array",
+ "description": "The list of FQDN (Fully Qualified Domain Names) of the mail server.",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": ["accepts_mail", "records"],
+ "description": "Object holding the MX details of the mail server."
+ },
+ "SmtpDetails": {
+ "title": "SmtpDetails",
+ "type": "object",
+ "description": "Verifications performed by connecting to the mail server via SMTP.",
+ "properties": {
+ "can_connect_smtp": {
+ "type": "boolean",
+ "description": "Can the mail exchanger of the email address domain be contacted successfully?"
+ },
+ "has_full_inbox": {
+ "type": "boolean",
+ "description": "Is the inbox of this mailbox full?"
+ },
+ "is_catch_all": {
+ "type": "boolean",
+ "description": "Is this email address a catch-all address?"
+ },
+ "is_deliverable": {
+ "type": "boolean",
+ "description": "Is an email sent to this address deliverable?"
+ },
+ "is_disabled": {
+ "type": "boolean",
+ "description": "Has this email address been disabled by the email provider?"
+ }
+ },
+ "required": ["can_connect_smtp", "has_full_inbox", "is_catch_all", "is_deliverable", "is_disabled"]
+ },
+ "SyntaxDetails": {
+ "title": "SyntaxDetails",
+ "type": "object",
+ "description": "Syntax validation of an email address.",
+ "properties": {
+ "domain": {
+ "type": "string",
+ "description": "The domain name of the email, i.e. the part after the \"@\" symbol."
+ },
+ "is_valid_syntax": {
+ "type": "boolean",
+ "description": "Is the address syntactically valid?"
+ },
+ "username": {
+ "type": "string",
+ "description": "The username of the email, i.e. the part before the \"@\" symbol."
+ }
+ },
+ "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 FAQ to know the meanings of the 4 possibilities: https://help.reacher.email/email-attributes-inside-json."
+ },
+ "CheckEmailInput": {
+ "title": "CheckEmailInput",
+ "type": "object",
+ "description": "Input containing all parameters necessary for an email 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"
+ }
+ },
+ "required": ["to_email"]
+ },
+ "CheckEmailInputProxy": {
+ "title": "CheckEmailInputProxy",
+ "type": "object",
+ "x-examples": {
+ "example-1": {
+ "value": {
+ "host": "my-proxy.io",
+ "port": 1080
+ }
+ }
+ },
+ "properties": {
+ "host": {
+ "type": "string",
+ "description": "The proxy host."
+ },
+ "port": {
+ "type": "integer",
+ "description": "The proxy port."
+ }
+ },
+ "required": ["host", "port"]
+ }
+ },
+ "securitySchemes": {
+ "Authorization": {
+ "name": "Authorization",
+ "type": "apiKey",
+ "in": "header",
+ "description": "A Reacher API key is required for all requests. Sign up on https://reacher.email to get your personal API key."
+ }
+ }
+ }
+}
diff --git a/backend/sqlx-data.json b/backend/sqlx-data.json
new file mode 100644
index 00000000..f59fda49
--- /dev/null
+++ b/backend/sqlx-data.json
@@ -0,0 +1,180 @@
+{
+ "db": "PostgreSQL",
+ "1039a6d3d732a86b9b3b2e19e6c8e3c857125d1c4cf916ac32789bfd0176b6b5": {
+ "describe": {
+ "columns": [
+ {
+ "name": "result",
+ "ordinal": 0,
+ "type_info": "Jsonb"
+ }
+ ],
+ "nullable": [
+ true
+ ],
+ "parameters": {
+ "Left": [
+ "Int4",
+ "Int8",
+ "Int8"
+ ]
+ }
+ },
+ "query": "\n\t\tSELECT result FROM email_results\n\t\tWHERE job_id = $1\n\t\tORDER BY id\n\t\tLIMIT $2 OFFSET $3\n\t\t"
+ },
+ "13862fe23ea729215fb1cfee3aadc14dfa9373dc8137c4f1da199e3ae66efd50": {
+ "describe": {
+ "columns": [
+ {
+ "name": "total_processed",
+ "ordinal": 0,
+ "type_info": "Int8"
+ },
+ {
+ "name": "safe_count",
+ "ordinal": 1,
+ "type_info": "Int8"
+ },
+ {
+ "name": "risky_count",
+ "ordinal": 2,
+ "type_info": "Int8"
+ },
+ {
+ "name": "invalid_count",
+ "ordinal": 3,
+ "type_info": "Int8"
+ },
+ {
+ "name": "unknown_count",
+ "ordinal": 4,
+ "type_info": "Int8"
+ },
+ {
+ "name": "finished_at",
+ "ordinal": 5,
+ "type_info": "Timestamptz"
+ }
+ ],
+ "nullable": [
+ null,
+ null,
+ null,
+ null,
+ null,
+ null
+ ],
+ "parameters": {
+ "Left": [
+ "Int4"
+ ]
+ }
+ },
+ "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 email_results WHERE job_id = $1 ORDER BY created_at DESC LIMIT 1) as finished_at\n\t\tFROM email_results\n\t\tWHERE job_id = $1\n\t\t"
+ },
+ "1a964da4784832e5f631f2c2e727382532c86c7e66e46254d72ef0af03021975": {
+ "describe": {
+ "columns": [],
+ "nullable": [],
+ "parameters": {
+ "Left": [
+ "Int4",
+ "Jsonb"
+ ]
+ }
+ },
+ "query": "\n\t\t\tINSERT INTO email_results (job_id, result)\n\t\t\tVALUES ($1, $2)\n\t\t\t"
+ },
+ "47af0157fa867e147e49d80b121b1881df93a6619434a1fd1fc9a58315b4044b": {
+ "describe": {
+ "columns": [
+ {
+ "name": "id",
+ "ordinal": 0,
+ "type_info": "Int4"
+ },
+ {
+ "name": "created_at",
+ "ordinal": 1,
+ "type_info": "Timestamptz"
+ },
+ {
+ "name": "total_records",
+ "ordinal": 2,
+ "type_info": "Int4"
+ }
+ ],
+ "nullable": [
+ false,
+ false,
+ false
+ ],
+ "parameters": {
+ "Left": [
+ "Int4"
+ ]
+ }
+ },
+ "query": "\n\t\tSELECT id, created_at, total_records FROM bulk_jobs\n\t\tWHERE id = $1\n\t\tLIMIT 1\n\t\t"
+ },
+ "981f650b6c663feeae8a93e7ecf86326e7a5e6d5c8fd03c03565d86982d0381a": {
+ "describe": {
+ "columns": [
+ {
+ "name": "id",
+ "ordinal": 0,
+ "type_info": "Int4"
+ }
+ ],
+ "nullable": [
+ false
+ ],
+ "parameters": {
+ "Left": [
+ "Int4"
+ ]
+ }
+ },
+ "query": "\n\t\tINSERT INTO bulk_jobs (total_records)\n\t\tVALUES ($1)\n\t\tRETURNING id\n\t\t"
+ },
+ "ac5e197ca20a1393e4ea45248d5e702c0edbbf57624f2bb416f0fd0401a44dcf": {
+ "describe": {
+ "columns": [
+ {
+ "name": "total_records",
+ "ordinal": 0,
+ "type_info": "Int4"
+ }
+ ],
+ "nullable": [
+ false
+ ],
+ "parameters": {
+ "Left": [
+ "Int4"
+ ]
+ }
+ },
+ "query": "SELECT total_records FROM bulk_jobs WHERE id = $1;"
+ },
+ "f58d4d05a6ab4c1ffda39396df4c403f7588266ae8d954985fc1eda9751febcc": {
+ "describe": {
+ "columns": [
+ {
+ "name": "count",
+ "ordinal": 0,
+ "type_info": "Int8"
+ }
+ ],
+ "nullable": [
+ null
+ ],
+ "parameters": {
+ "Left": [
+ "Int4"
+ ]
+ }
+ },
+ "query": "SELECT COUNT(*) FROM email_results WHERE job_id = $1;"
+ }
+}
\ No newline at end of file
diff --git a/backend/src/check.rs b/backend/src/check.rs
new file mode 100644
index 00000000..879b2f80
--- /dev/null
+++ b/backend/src/check.rs
@@ -0,0 +1,60 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2022 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 contains shared logic for checking one email.
+
+use super::sentry_util;
+use check_if_email_exists::{check_email as ciee_check_email, CheckEmailInput, CheckEmailOutput};
+use std::time::Instant;
+
+/// Timeout after which we drop the `check-if-email-exists` check. We run the
+/// checks twice (to avoid greylisting), so each verification takes 20s max.
+pub const SMTP_TIMEOUT: u64 = 10;
+
+/// Same as `check-if-email-exists`'s check email, but adds some additional
+/// logging and error handling, and also only handles 1 email.
+///
+/// # Panics
+///
+/// If more than 1 email is passed inside input, then this function panics.
+pub async fn check_email(input: &CheckEmailInput) -> CheckEmailOutput {
+ // Run `ciee_check_email` with retries if necessary. Also measure the
+ // verification time.
+ let now = Instant::now();
+
+ assert!(
+ input.to_emails.len() == 1,
+ "We currently hardcode the BATCH_SIZE to 1. qed."
+ );
+
+ let res = ciee_check_email(input)
+ .await
+ .pop()
+ .expect("Input only has one email, so does output. qed.");
+
+ // Log on Sentry the `is_reachable` field.
+ // We should definitely log this somewhere else than Sentry.
+ // TODO https://github.com/reacherhq/backend/issues/207
+ sentry_util::metrics(
+ format!("is_reachable={:?}", res.is_reachable),
+ now.elapsed().as_millis(),
+ res.syntax.domain.as_ref(),
+ );
+
+ sentry_util::log_unknown_errors(&res);
+
+ res
+}
diff --git a/backend/src/errors.rs b/backend/src/errors.rs
new file mode 100644
index 00000000..a69a50b7
--- /dev/null
+++ b/backend/src/errors.rs
@@ -0,0 +1,41 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2022 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/>.
+
+//! Describe a common response error to be used by all routes, should an error
+//! happen.
+
+use serde::Serialize;
+use warp::{http, reject};
+
+/// Struct describing an error response.
+#[derive(Serialize, Debug)]
+pub struct ReacherResponseError {
+ #[serde(skip)]
+ code: http::StatusCode,
+ 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/lib.rs b/backend/src/lib.rs
new file mode 100644
index 00000000..2f05331f
--- /dev/null
+++ b/backend/src/lib.rs
@@ -0,0 +1,20 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2022 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 check;
+mod errors;
+pub mod routes;
+pub mod sentry_util;
diff --git a/backend/src/main.rs b/backend/src/main.rs
new file mode 100644
index 00000000..2c803d91
--- /dev/null
+++ b/backend/src/main.rs
@@ -0,0 +1,131 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2022 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 dotenv::dotenv;
+use reacher_backend::routes::{bulk::email_verification_task, create_routes};
+use reacher_backend::sentry_util::{setup_sentry, CARGO_PKG_VERSION};
+use sqlx::{postgres::PgPoolOptions, Pool, Postgres};
+use sqlxmq::{JobRegistry, OwnedHandle};
+use std::{env, net::IpAddr};
+use warp::Filter;
+
+/// Run a HTTP server using warp with bulk endpoints.
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
+ init_logger();
+
+ // Setup sentry bug tracking.
+ let _guard = setup_sentry();
+
+ let is_bulk_enabled = env::var("RCH_ENABLE_BULK").unwrap_or_else(|_| "0".into()) == "1";
+ if is_bulk_enabled {
+ log::info!(target: "reacher", "Bulk endpoints enabled.");
+ let pool = create_db().await?;
+ let _registry = create_job_registry(&pool).await?;
+ let routes = create_routes(Some(pool));
+ run_warp_server(routes).await?;
+ } else {
+ let routes = create_routes(None);
+ run_warp_server(routes).await?;
+ }
+
+ Ok(())
+}
+
+fn init_logger() {
+ // Read from .env file if present.
+ let _ = dotenv();
+ env_logger::init();
+ log::info!(target: "reacher", "Running Reacher v{}", CARGO_PKG_VERSION);
+}
+
+/// Create a DB pool.
+pub async fn create_db() -> Result<Pool<Postgres>, sqlx::Error> {
+ let pg_conn =
+ env::var("DATABASE_URL").expect("Environment variable DATABASE_URL should be set");
+ let pg_max_conn = env::var("RCH_DATABASE_MAX_CONNECTIONS").map_or(5, |var| {
+ var.parse::<u32>()
+ .expect("Environment variable RCH_DATABASE_MAX_CONNECTIONS should parse to u32")
+ });
+
+ // create connection pool with database
+ // connection pool internally the shared db connection
+ // with arc so it can safely be cloned and shared across threads
+ let pool = PgPoolOptions::new()
+ .max_connections(pg_max_conn)
+ .connect(pg_conn.as_str())
+ .await?;
+
+ sqlx::migrate!("./migrations").run(&pool).await?;
+
+ Ok(pool)
+}
+
+/// Create a job registry with one task: the email verification task.
+async fn create_job_registry(pool: &Pool<Postgres>) -> Result<OwnedHandle, sqlx::Error> {
+ let min_task_conc = env::var("RCH_MINIMUM_TASK_CONCURRENCY").map_or(10, |var| {
+ var.parse::<usize>()
+ .expect("Environment variable RCH_MINIMUM_TASK_CONCURRENCY should parse to usize")
+ });
+ let max_conc_task_fetch = env::var("RCH_MAXIMUM_CONCURRENT_TASK_FETCH").map_or(20, |var| {
+ var.parse::<usize>()
+ .expect("Environment variable RCH_MAXIMUM_CONCURRENT_TASK_FETCH should parse to usize")
+ });
+
+ // registry needs to be given list of jobs it can accept
+ let registry = JobRegistry::new(&[email_verification_task]);
+
+ // create runner for the message queue associated
+ // with this job registry
+ let registry = registry
+ // Create a job runner using the connection pool.
+ .runner(pool)
+ // Here is where you can configure the job runner
+ // Aim to keep 10-20 jobs running at a time.
+ .set_concurrency(min_task_conc, max_conc_task_fetch)
+ // Start the job runner in the background.
+ .run()
+ .await?;
+
+ Ok(registry)
+}
+
+async fn run_warp_server(
+ routes: impl Filter<Extract = impl warp::Reply, Error = warp::Rejection>
+ + Clone
+ + Send
+ + Sync
+ + 'static,
+) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
+ let host = env::var("RCH_HTTP_HOST")
+ .unwrap_or_else(|_| "127.0.0.1".into())
+ .parse::<IpAddr>()
+ .expect("Environment variable RCH_HTTP_HOST is malformed.");
+ let port = env::var("PORT")
+ .map(|port| {
+ port.parse::<u16>()
+ .expect("Environment variable PORT is malformed.")
+ })
+ .unwrap_or(8080);
+ log::info!(target: "reacher", "Server is listening on {}:{}.", host, port);
+
+ warp::serve(routes).run((host, port)).await;
+
+ Ok(())
+}
diff --git a/backend/src/routes/bulk/db.rs b/backend/src/routes/bulk/db.rs
new file mode 100644
index 00000000..049691d6
--- /dev/null
+++ b/backend/src/routes/bulk/db.rs
@@ -0,0 +1,35 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2022 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 sqlx::{Pool, Postgres};
+use warp::Filter;
+
+/// Warp filter that extracts a Pg Pool if the option is Some, or else rejects
+/// with a 404.
+pub fn with_db(
+ o: Option<Pool<Postgres>>,
+) -> impl Filter<Extract = (Pool<Postgres>,), Error = warp::Rejection> + Clone {
+ warp::any().and_then(move || {
+ let o = o.clone(); // Still not 100% sure why I need to clone here...
+ async move {
+ if let Some(conn_pool) = o {
+ Ok(conn_pool)
+ } else {
+ Err(warp::reject::not_found())
+ }
+ }
+ })
+}
diff --git a/backend/src/routes/bulk/error.rs b/backend/src/routes/bulk/error.rs
new file mode 100644
index 00000000..2ae12d58
--- /dev/null
+++ b/backend/src/routes/bulk/error.rs
@@ -0,0 +1,44 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2022 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 warp::reject;
+
+#[derive(Debug)]
+pub enum CsvError {
+ CsvLib(csv::Error),
+ CsvLibWriter(Box<csv::IntoInnerError<csv::Writer<Vec<u8>>>>),
+ Parse(&'static str),
+}
+
+/// Catch all error struct for the bulk endpoints
+#[derive(Debug)]
+pub enum BulkError {
+ EmptyInput,
+ JobInProgress,
+ Db(sqlx::Error),
+ Csv(CsvError),
+ Json(serde_json::Error),
+}
+
+// Defaults to Internal server error
+impl reject::Reject for BulkError {}
+
+// wrap sql errors as db errors for reacher
+impl From<sqlx::Error> for BulkError {
+ fn from(e: sqlx::Error) -> Self {
+ BulkError::Db(e)
+ }
+}
diff --git a/backend/src/routes/bulk/get.rs b/backend/src/routes/bulk/get.rs
new file mode 100644
index 00000000..cf349aaa
--- /dev/null
+++ b/backend/src/routes/bulk/get.rs
@@ -0,0 +1,169 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2022 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 super::{db::with_db, error::BulkError};
+use serde::Serialize;
+use sqlx::types::chrono::{DateTime, Utc};
+use sqlx::{Pool, Postgres};
+use warp::Filter;
+
+/// 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 JobStatusSummary {
+ total_safe: i32,
+ total_risky: i32,
+ total_invalid: i32,
+ total_unknown: i32,
+}
+
+/// Complete information about a bulk verification job
+#[derive(Debug, Serialize)]
+struct JobStatusResponseBody {
+ job_id: i32,
+ created_at: DateTime<Utc>,
+ finished_at: Option<DateTime<Utc>>,
+ total_records: i32,
+ total_processed: i32,
+ summary: JobStatusSummary,
+ job_status: ValidStatus,
+}
+
+async fn job_status(
+ job_id: i32,
+ conn_pool: Pool<Postgres>,
+) -> Result<impl warp::Reply, warp::Rejection> {
+ let job_rec = sqlx::query_as!(
+ JobRecord,
+ r#"
+ SELECT id, created_at, total_records FROM bulk_jobs
+ WHERE id = $1
+ LIMIT 1
+ "#,
+ job_id
+ )
+ .fetch_one(&conn_pool)
+ .await
+ .map_err(|e| {
+ log::error!(
+ target: "reacher",
+ "Failed to get job record for [job={}] with [error={}]",
+ job_id,
+ e
+ );
+ BulkError::from(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 email_results WHERE job_id = $1 ORDER BY created_at DESC LIMIT 1) as finished_at
+ FROM email_results
+ WHERE job_id = $1
+ "#,
+ job_id
+ )
+ .fetch_one(&conn_pool)
+ .await
+ .map_err(|e| {
+ log::error!(
+ target: "reacher",
+ "Failed to get aggregate info for [job={}] with [error={}]",
+ job_id,
+ e
+ );
+ BulkError::from(e)
+ })?;
+
+ 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(&JobStatusResponseBody {
+ 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: JobStatusSummary {
+ 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 get_bulk_job_status(
+ o: Option<Pool<Postgres>>,
+) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone {
+ warp::path!("v0" / "bulk" / i32)
+ .and(warp::get())
+ .and(with_db(o))
+ .and_then(job_status)
+ // View access logs by setting `RUST_LOG=reacher`.
+ .with(warp::log("reacher"))
+}
diff --git a/backend/src/routes/bulk/mod.rs b/backend/src/routes/bulk/mod.rs
new file mode 100644
index 00000000..31f25c3b
--- /dev/null
+++ b/backend/src/routes/bulk/mod.rs
@@ -0,0 +1,24 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2022 Reacher
+
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+mod db;
+mod error;
+pub mod get;
+pub mod post;
+pub mod results;
+mod task;
+
+pub use task::email_verification_task;
diff --git a/backend/src/routes/bulk/post.rs b/backend/src/routes/bulk/post.rs
new file mode 100644
index 00000000..fba41544
--- /dev/null
+++ b/backend/src/routes/bulk/post.rs
@@ -0,0 +1,160 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2022 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 /bulk` endpoint.
+
+use super::{
+ db::with_db,
+ error::BulkError,
+ task::{submit_job, TaskInput},
+};
+use check_if_email_exists::CheckEmailInputProxy;
+use serde::{Deserialize, Serialize};
+use sqlx::{Pool, Postgres};
+use std::cmp::min;
+use warp::Filter;
+
+// this configures the number of emails passed to every task
+// this can be configured but will require changes in the
+// in the `crate::check::check_email` function which assumes a task can have
+// only one email. This will also require changing the
+// email_verification_task itself to handle multiple
+// outputs and commit them to the database.
+const EMAIL_TASK_BATCH_SIZE: usize = 1;
+
+/// Endpoint request body.
+#[derive(Clone, Debug, Deserialize, Serialize)]
+struct CreateBulkRequestBody {
+ input_type: String,
+ input: Vec<String>,
+ proxy: Option<CheckEmailInputProxy>,
+ hello_name: Option<String>,
+ from_email: Option<String>,
+ smtp_ports: Option<Vec<u16>>,
+}
+
+struct CreateBulkRequestBodyIterator {
+ body: CreateBulkRequestBody,
+ index: usize,
+ batch_size: usize,
+}
+
+impl IntoIterator for CreateBulkRequestBody {
+ type Item = TaskInput;
+ type IntoIter = CreateBulkRequestBodyIterator;
+
+ fn into_iter(self) -> Self::IntoIter {
+ CreateBulkRequestBodyIterator {
+ body: self,
+ index: 0,
+ batch_size: EMAIL_TASK_BATCH_SIZE,
+ }
+ }
+}
+
+impl Iterator for CreateBulkRequestBodyIterator {
+ type Item = TaskInput;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.index < self.body.input.len() {
+ let bounded_index = min(self.index + self.batch_size, self.body.input.len());
+ let to_emails = self.body.input[self.index..bounded_index].to_vec();
+ let item = TaskInput {
+ to_emails,
+ smtp_ports: self.body.smtp_ports.clone().unwrap_or_else(|| vec![25]),
+ proxy: self.body.proxy.clone(),
+ hello_name: self.body.hello_name.clone(),
+ from_email: self.body.from_email.clone(),
+ };
+
+ self.index = bounded_index;
+ Some(item)
+ } else {
+ None
+ }
+ }
+}
+
+/// Endpoint response body.
+#[derive(Clone, Debug, Deserialize, Serialize)]
+struct CreateBulkResponseBody {
+ job_id: i32,
+}
+
+/// handles input, creates db entry for job and tasks for verification
+async fn create_bulk_request(
+ conn_pool: Pool<Postgres>,
+ body: CreateBulkRequestBody,
+) -> Result<impl warp::Reply, warp::Rejection> {
+ if body.input.is_empty() {
+ return Err(BulkError::EmptyInput.into());
+ }
+
+ // create job entry
+ let rec = sqlx::query!(
+ r#"
+ INSERT INTO bulk_jobs (total_records)
+ VALUES ($1)
+ RETURNING id
+ "#,
+ body.input.len() as i32
+ )
+ .fetch_one(&conn_pool)
+ .await
+ .map_err(|e| {
+ log::error!(
+ target: "reacher",
+ "Failed to create job record for [body={:?}] with [error={}]",
+ &body,
+ e
+ );
+ BulkError::from(e)
+ })?;
+
+ for task_input in body.into_iter() {
+ let task_uuid = submit_job(&conn_pool, rec.id, task_input).await?;
+
+ log::debug!(
+ target: "reacher",
+ "Submitted task to sqlxmq for [job={}] with [uuid={}]",
+ rec.id,
+ task_uuid
+ );
+ }
+
+ Ok(warp::reply::json(&CreateBulkResponseBody {
+ job_id: rec.id,
+ }))
+}
+
+/// Create the `POST /bulk` endpoint.
+/// The endpoint accepts list of email address and creates
+/// a new job to check them.
+pub fn create_bulk_job(
+ o: Option<Pool<Postgres>>,
+) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone {
+ warp::path!("v0" / "bulk")
+ .and(warp::post())
+ .and(with_db(o))
+ // 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 * 16))
+ .and(warp::body::json())
+ .and_then(create_bulk_request)
+ // View access logs by setting `RUST_LOG=reacher`.
+ .with(warp::log("reacher"))
+}
diff --git a/backend/src/routes/bulk/results.rs b/backend/src/routes/bulk/results.rs
new file mode 100644
index 00000000..75781116
--- /dev/null
+++ b/backend/src/routes/bulk/results.rs
@@ -0,0 +1,446 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2022 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 super::{
+ db::with_db,
+ error::{BulkError, CsvError},
+};
+use csv::WriterBuilder;
+use serde::{Deserialize, Serialize};
+use sqlx::{Executor, Pool, Postgres, Row};
+use std::convert::{TryFrom, TryInto};
+use warp::Filter;
+
+/// Defines the download format, passed in as a query param.
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+enum JobResultResponseFormat {
+ Json,
+ Csv,
+}
+
+// limit and offset are optional in the request
+// if they are unspecified their default values
+// are 50 and 0 respectively
+#[derive(Serialize, Deserialize)]
+struct JobResultRequest {
+ format: Option<JobResultResponseFormat>,
+ limit: Option<u64>,
+ offset: Option<u64>,
+}
+
+#[derive(Serialize, Deserialize)]
+struct JobResultJsonResponse {
+ results: Vec<serde_json::Value>,
+}
+
+/// Wrapper for serde json value to convert
+/// into a csv response
+#[derive(Debug)]
+struct CsvWrapper(serde_json::Value);
+
+/// Simplified output of `CheckEmailOutput` struct
+/// for csv fields.
+#[derive(Debug, Serialize)]
+struct JobResultCsvResponse {
+ 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 = "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>,
+}
+
+/// Convert csv wrapper to csv response
+/// Performs multiple allocations for string fields
+/// throw error if field is missing
+impl TryFrom<CsvWrapper> for JobResultCsvResponse {
+ type Error = &'static str;
+
+ fn try_from(value: CsvWrapper) -> Result<Self, Self::Error> {
+ let mut input: String = String::default();
+ let mut is_reachable: String = String::default();
+ let mut misc_is_disposable: bool = false;
+ let mut misc_is_role_account: bool = false;
+ let mut mx_accepts_mail: bool = false;
+ let mut smtp_can_connect: bool = false;
+ let mut smtp_has_full_inbox: bool = false;
+ let mut smtp_is_catch_all: bool = false;
+ let mut smtp_is_deliverable: bool = false;
+ let mut smtp_is_disabled: bool = false;
+ let mut syntax_is_valid_syntax: bool = false;
+ let mut syntax_domain: String = String::default();
+ let mut syntax_username: String = String::default();
+ let mut error: Option<String> = None;
+
+ let top_level = value
+ .0
+ .as_object()
+ .ok_or("Failed to find top level object")?;
+ for (key, val) in top_level.keys().zip(top_level.values()) {
+ match key.as_str() {
+ "input" => input = val.as_str().ok_or("input should be a string")?.to_string(),
+ "is_reachable" => {
+ is_reachable = val
+ .as_str()
+ .ok_or("is_reachable should be a string")?
+ .to_string()
+ }
+ "misc" => {
+ let misc_obj = val.as_object().ok_or("misc field should be an object")?;
+ for (key, val) in misc_obj.keys().zip(misc_obj.values()) {
+ match key.as_str() {
+ "error" => error = Some(val.to_string()),
+ "is_disposable" => {
+ misc_is_disposable =
+ val.as_bool().ok_or("is_disposable should be a boolean")?
+ }
+ "is_role_account" => {
+ misc_is_role_account =
+ val.as_bool().ok_or("is_role_account should be a boolean")?
+ }
+ _ => {}
+ }
+ }
+ }
+ "mx" => {
+ let mx_obj = val.as_object().ok_or("mx field should be an object")?;
+ for (key, val) in mx_obj.keys().zip(mx_obj.values()) {
+ match key.as_str() {
+ "error" => error = Some(val.to_string()),
+ "accepts_email" => {
+ mx_accepts_mail =
+ val.as_bool().ok_or("accepts_email should be a boolean")?
+ }
+ _ => {}
+ }
+ }
+ }
+ "smtp" => {
+ let smtp_obj = val.as_object().ok_or("mx field should be an object")?;
+ for (key, val) in smtp_obj.keys().zip(smtp_obj.values()) {
+ match key.as_str() {
+ "error" => error = Some(val.to_string()),
+ "can_connect_smtp" => {
+ smtp_can_connect = val
+ .as_bool()
+ .ok_or("can_connect_smtp should be a boolean")?
+ }
+ "has_full_inbox" => {
+ smtp_has_full_inbox =
+ val.as_bool().ok_or("has_full_inbox should be a boolean")?
+ }
+ "is_catch_all" => {
+ smtp_is_catch_all =
+ val.as_bool().ok_or("is_catch_all should be a boolean")?
+ }
+ "is_deliverable" => {
+ smtp_is_deliverable =
+ val.as_bool().ok_or("is_deliverable should be a boolean")?
+ }
+ "is_disabled" => {
+ smtp_is_disabled =
+ val.as_bool().ok_or("is_disabled should be a boolean")?
+ }
+ _ => {}
+ }
+ }
+ }
+ "syntax" => {
+ let syntax_obj = val.as_object().ok_or("syntax field should be an object")?;
+ for (key, val) in syntax_obj.keys().zip(syntax_obj.values()) {
+ match key.as_str() {
+ "error" => error = Some(val.to_string()),
+ "is_valid_syntax" => {
+ syntax_is_valid_syntax =
+ val.as_bool().ok_or("is_valid_syntax should be a boolean")?
+ }
+ "username" => {
+ syntax_username = val
+ .as_str()
+ .ok_or("username should be a string")?
+ .to_string()
+ }
+ "domain" => {
+ syntax_domain =
+ val.as_str().ok_or("domain should be a string")?.to_string()
+ }
+ _ => {}
+ }
+ }
+ }
+ // ignore unknown fields
+ _ => {}
+ }
+ }
+
+ Ok(JobResultCsvResponse {
+ input,
+ is_reachable,
+ misc_is_disposable,
+ misc_is_role_account,
+ mx_accepts_mail,
+ smtp_can_connect,
+ smtp_has_full_inbox,
+ smtp_is_catch_all,
+ smtp_is_deliverable,
+ smtp_is_disabled,
+ syntax_domain,
+ syntax_is_valid_syntax,
+ syntax_username,
+ error,
+ })
+ }
+}
+
+async fn job_result(
+ job_id: i32,
+ conn_pool: Pool<Postgres>,
+ req: JobResultRequest,
+) -> 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 bulk_jobs WHERE id = $1;"#,
+ job_id
+ )
+ .fetch_one(&conn_pool)
+ .await
+ .map_err(|e| {
+ log::error!(
+ target: "reacher",
+ "Failed to fetch total_records for [job={}] with [error={}]",
+ job_id,
+ e
+ );
+ BulkError::from(e)
+ })?
+ .total_records;
+ let total_processed = sqlx::query!(
+ r#"SELECT COUNT(*) FROM email_results WHERE job_id = $1;"#,
+ job_id
+ )
+ .fetch_one(&conn_pool)
+ .await
+ .map_err(|e| {
+ log::error!(
+ target: "reacher",
+ "Failed to get total_processed for [job={}] with [error={}]",
+ job_id,
+ e
+ );
+ BulkError::from(e)
+ })?
+ .count
+ .unwrap_or(0);
+
+ if total_processed < total_records as i64 {
+ return Err(BulkError::JobInProgress.into());
+ }
+
+ let format = req.format.unwrap_or(JobResultResponseFormat::Json);
+ match format {
+ JobResultResponseFormat::Json => {
+ let data = job_result_json(
+ job_id,
+ req.limit.unwrap_or(50),
+ req.offset.unwrap_or(0),
+ conn_pool,
+ )
+ .await?;
+
+ let reply =
+ serde_json::to_vec(&JobResultJsonResponse { results: data }).map_err(|e| {
+ log::error!(
+ target: "reacher",
+ "Failed to convert json results to string for [job={}] with [error={}]",
+ job_id,
+ e
+ );
+
+ BulkError::Json(e)
+ })?;
+
+ Ok(warp::reply::with_header(
+ reply,
+ "Content-Type",
+ "application/json",
+ ))
+ }
+ JobResultResponseFormat::Csv => {
+ let data = job_result_csv(
+ job_id,
+ req.limit.unwrap_or(5000),
+ req.offset.unwrap_or(0),
+ conn_pool,
+ )
+ .await?;
+
+ Ok(warp::reply::with_header(data, "Content-Type", "text/csv"))
+ }
+ }
+}
+
+async fn job_result_json(
+ job_id: i32,
+ limit: u64,
+ offset: u64,
+ conn_pool: Pool<Postgres>,
+) -> Result<Vec<serde_json::Value>, warp::Rejection> {
+ let query = sqlx::query!(
+ r#"
+ SELECT result FROM email_results
+ WHERE job_id = $1
+ ORDER BY id
+ LIMIT $2 OFFSET $3
+ "#,
+ job_id,
+ limit as i64,
+ offset as i64
+ );
+
+ let rows: Vec<serde_json::Value> = conn_pool
+ .fetch_all(query)
+ .await
+ .map_err(|e| {
+ log::error!(
+ target: "reacher",
+ "Failed to get results for [job={}] [limit={}] [offset={}] with [error={}]",
+ job_id,
+ limit,
+ offset,
+ e
+ );
+
+ BulkError::from(e)
+ })?
+ .iter()
+ .map(|row| row.get("result"))
+ .collect();
+
+ Ok(rows)
+}
+
+async fn job_result_csv(
+ job_id: i32,
+ limit: u64,
+ offset: u64,
+ conn_pool: Pool<Postgres>,
+) -> Result<Vec<u8>, warp::Rejection> {
+ let query = sqlx::query!(
+ r#"
+ SELECT result FROM email_results
+ WHERE job_id = $1
+ ORDER BY id
+ LIMIT $2 OFFSET $3
+ "#,
+ job_id,
+ limit as i64,
+ offset as i64
+ );
+
+ let mut wtr = WriterBuilder::new().has_headers(true).from_writer(vec![]);
+
+ for json_value in conn_pool
+ .fetch_all(query)
+ .await
+ .map_err(|e| {
+ log::error!(
+ target: "reacher",
+ "Failed to get results for [job={}] with [error={}]",
+ job_id,
+ e
+ );
+
+ BulkError::from(e)
+ })?
+ .iter()
+ .map(|row| row.get("result"))
+ {
+ let result_csv: JobResultCsvResponse = CsvWrapper(json_value).try_into().map_err(|e: &'static str| {
+ log::error!(
+ target: "reacher",
+ "Failed to convert json to csv output struct for [job={}] [limit={}] [offset={}] to csv with [error={}]",
+ job_id,
+ limit,
+ offset,
+ e
+ );
+
+ BulkError::Csv(CsvError::Parse(e))
+ })?;
+ wtr.serialize(result_csv).map_err(|e| {
+ log::error!(
+ target: "reacher",
+ "Failed to serialize result for [job={}] [limit={}] [offset={}] to csv with [error={}]",
+ job_id,
+ limit,
+ offset,
+ e
+ );
+
+ BulkError::Csv(CsvError::CsvLib(e))
+ })?;
+ }
+
+ let data = wtr.into_inner().map_err(|e| {
+ log::error!(
+ target: "reacher",
+ "Failed to convert results for [job={}] [limit={}] [offset={}] to csv with [error={}]",
+ job_id,
+ limit,
+ offset,
+ e
+ );
+
+ BulkError::Csv(CsvError::CsvLibWriter(Box::new(e)))
+ })?;
+
+ Ok(data)
+}
+
+pub fn get_bulk_job_result(
+ o: Option<Pool<Postgres>>,
+) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone {
+ warp::path!("v0" / "bulk" / i32 / "results")
+ .and(warp::get())
+ .and(with_db(o))
+ .and(warp::query::<JobResultRequest>())
+ .and_then(job_result)
+ // View access logs by setting `RUST_LOG=reacher`.
+ .with(warp::log("reacher"))
+}
diff --git a/backend/src/routes/bulk/task.rs b/backend/src/routes/bulk/task.rs
new file mode 100644
index 00000000..1a607fe4
--- /dev/null
+++ b/backend/src/routes/bulk/task.rs
@@ -0,0 +1,230 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2022 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 /bulk` endpoint.
+
+use super::error::BulkError;
+use crate::check::{check_email, SMTP_TIMEOUT};
+use check_if_email_exists::{CheckEmailInput, CheckEmailInputProxy, CheckEmailOutput, Reachable};
+use serde::{Deserialize, Serialize};
+use sqlx::{Pool, Postgres};
+use sqlxmq::{job, CurrentJob};
+use std::{error::Error, time::Duration};
+use uuid::Uuid;
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+pub struct TaskInput {
+ // fields for CheckEmailInput
+ pub to_emails: Vec<String>, // chunk of email from request. This always has at most `EMAIL_TASK_BATCH_SIZE` items.
+ pub smtp_ports: Vec<u16>, // override empty smtp ports from request with default value
+ pub proxy: Option<CheckEmailInputProxy>,
+ pub hello_name: Option<String>,
+ pub from_email: Option<String>,
+}
+
+pub struct TaskInputIterator {
+ body: TaskInput,
+ index: usize,
+}
+
+impl IntoIterator for TaskInput {
+ type Item = CheckEmailInput;
+ type IntoIter = TaskInputIterator;
+
+ fn into_iter(self) -> Self::IntoIter {
+ TaskInputIterator {
+ body: self,
+ index: 0,
+ }
+ }
+}
+
+/// Iterate through all the `smtp_ports`.
+impl Iterator for TaskInputIterator {
+ type Item = CheckEmailInput;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.index < self.body.smtp_ports.len() {
+ let mut item = CheckEmailInput::new(self.body.to_emails.clone());
+
+ if let Some(name) = &self.body.hello_name {
+ item.set_hello_name(name.clone());
+ }
+
+ if let Some(email) = &self.body.from_email {
+ item.set_from_email(email.clone());
+ }
+
+ item.set_smtp_port(self.body.smtp_ports[self.index]);
+
+ if let Some(proxy) = &self.body.proxy {
+ item.set_proxy(proxy.clone());
+ }
+
+ item.set_smtp_timeout(Duration::from_secs(SMTP_TIMEOUT));
+
+ self.index += 1;
+ Some(item)
+ } else {
+ None
+ }
+ }
+}
+
+/// Struct that's serialized into the sqlxmq own `payload_json` table.
+#[derive(Debug, Deserialize, Serialize)]
+struct TaskPayload {
+ id: i32,
+ input: TaskInput,
+}
+
+pub async fn submit_job(
+ conn_pool: &Pool<Postgres>,
+ job_id: i32,
+ task_input: TaskInput,
+) -> Result<Uuid, BulkError> {
+ let task_payload = TaskPayload {
+ id: job_id,
+ input: task_input,
+ };
+
+ let uuid = email_verification_task
+ .builder()
+ .set_json(&task_payload)
+ .map_err(|e| {
+ log::error!(
+ target: "reacher",
+ "Failed to submit task with the following [input={:?}] with [error={}]",
+ task_payload.input,
+ e
+ );
+
+ BulkError::Json(e)
+ })?
+ .spawn(conn_pool)
+ .await
+ .map_err(|e| {
+ log::error!(
+ target: "reacher",
+ "Failed to submit task for [bulk_req={}] with [error={}]",
+ job_id,
+ e
+ );
+
+ e
+ })?;
+
+ Ok(uuid)
+}
+
+/// Arguments to the `#[job]` attribute allow setting default task options.
+/// This task tries to verify the given email and inserts the results
+/// into the email verification db table
+/// NOTE: if EMAIL_TASK_BATCH_SIZE is made greater than 1 this logic
+/// will have to be changed to handle a vector outputs from `check_email`.
+///
+/// Small note about namings: what sqlxmq calls a "job", we call it a "task".
+/// We call a "job" a user bulk request, i.e. a list of "tasks".
+/// Please be careful while reading code.
+#[job]
+pub async fn email_verification_task(
+ mut current_job: CurrentJob,
+ // Additional arguments are optional, but can be used to access context
+ // provided via [`JobRegistry::set_context`].
+) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
+ let task_payload: TaskPayload = current_job.json()?.ok_or("Got empty task.")?;
+ let job_id = task_payload.id;
+
+ let mut final_response: Option<CheckEmailOutput> = None;
+
+ for check_email_input in task_payload.input {
+ log::debug!(
+ target:"reacher",
+ "Starting task [email={}] for [job={}] and [uuid={}]",
+ check_email_input.to_emails[0],
+ task_payload.id,
+ current_job.id(),
+ );
+
+ let response = check_email(&check_email_input).await;
+
+ log::debug!(
+ target:"reacher",
+ "Got task result [email={}] for [job={}] and [uuid={}] with [is_reachable={:?}]",
+ check_email_input.to_emails[0],
+ task_payload.id,
+ current_job.id(),
+ response.is_reachable,
+ );
+
+ let is_reachable = response.is_reachable == Reachable::Unknown;
+ final_response = Some(response);
+ // unsuccessful validation continue iteration with next possible smtp port
+ if is_reachable {
+ continue;
+ }
+ // successful validation attempt complete job break iteration
+ else {
+ break;
+ }
+ }
+
+ // final response can only be empty if there
+ // were no validation attempts. This can can
+ // never occur currently
+ if let Some(response) = final_response {
+ // write results and terminate iteration
+ #[allow(unused_variables)]
+ let rec = sqlx::query!(
+ r#"
+ INSERT INTO email_results (job_id, result)
+ VALUES ($1, $2)
+ "#,
+ job_id,
+ serde_json::json!(response)
+ )
+ // TODO: This is a simplified solution and will work when
+ // the job queue and email results tables are in the same
+ // database. Keeping them in separate database will require
+ // some custom logic on the job registry side
+ // https://github.com/Diggsey/sqlxmq/issues/4
+ .fetch_optional(current_job.pool())
+ .await
+ .map_err(|e| {
+ log::error!(
+ target:"reacher",
+ "Failed to write [email={}] result to db for [job={}] and [uuid={}] with [error={}]",
+ response.input,
+ job_id,
+ current_job.id(),
+ e
+ );
+
+ e
+ })?;
+
+ log::debug!(
+ target:"reacher",
+ "Wrote result for [email={}] for [job={}] and [uuid={}]",
+ response.input,
+ job_id,
+ current_job.id(),
+ );
+ }
+
+ current_job.complete().await?;
+ Ok(())
+}
diff --git a/backend/src/routes/check_email/mod.rs b/backend/src/routes/check_email/mod.rs
new file mode 100644
index 00000000..57e086f1
--- /dev/null
+++ b/backend/src/routes/check_email/mod.rs
@@ -0,0 +1,17 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2022 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/routes/check_email/post.rs b/backend/src/routes/check_email/post.rs
new file mode 100644
index 00000000..cb4b5f2f
--- /dev/null
+++ b/backend/src/routes/check_email/post.rs
@@ -0,0 +1,75 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2022 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 /check_email` endpoint.
+
+use crate::check::check_email;
+use check_if_email_exists::{CheckEmailInput, CheckEmailInputProxy};
+use serde::{Deserialize, Serialize};
+use std::env;
+use warp::Filter;
+
+/// Endpoint request body.
+#[derive(Clone, Debug, Deserialize, Serialize)]
+pub struct EndpointRequest {
+ from_email: Option<String>,
+ hello_name: Option<String>,
+ proxy: Option<CheckEmailInputProxy>,
+ smtp_port: Option<u16>,
+ to_email: String,
+}
+
+impl From<EndpointRequest> for CheckEmailInput {
+ fn from(req: EndpointRequest) -> Self {
+ // Create Request for check_if_email_exists from body
+ let mut input = CheckEmailInput::new(vec![req.to_email]);
+ input
+ .set_from_email(req.from_email.unwrap_or_else(|| {
+ env::var("RCH_FROM_EMAIL").unwrap_or_else(|_| "[email protected]".into())
+ }))
+ .set_hello_name(req.hello_name.unwrap_or_else(|| "gmail.com".into()));
+
+ if let Some(proxy_input) = req.proxy {
+ input.set_proxy(proxy_input);
+ }
+
+ if let Some(smtp_port) = req.smtp_port {
+ input.set_smtp_port(smtp_port);
+ }
+
+ input
+ }
+}
+
+/// The main endpoint handler that implements the logic of this route.
+async fn handler(body: EndpointRequest) -> Result<impl warp::Reply, warp::Rejection> {
+ // Run the future to check an email.
+ Ok(warp::reply::json(&check_email(&body.into()).await))
+}
+
+/// Create the `POST /check_email` endpoint.
+pub fn post_check_email(
+) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone {
+ warp::path!("v0" / "check_email")
+ .and(warp::post())
+ // 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)
+ // View access logs by setting `RUST_LOG=reacher`.
+ .with(warp::log("reacher"))
+}
diff --git a/backend/src/routes/mod.rs b/backend/src/routes/mod.rs
new file mode 100644
index 00000000..f023fc6f
--- /dev/null
+++ b/backend/src/routes/mod.rs
@@ -0,0 +1,35 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2022 Reacher
+
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+pub mod bulk;
+pub mod check_email;
+mod version;
+
+use super::errors;
+use sqlx::{Pool, Postgres};
+use warp::Filter;
+
+pub fn create_routes(
+ o: Option<Pool<Postgres>>,
+) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
+ version::get::get_version()
+ .or(check_email::post::post_check_email())
+ // The 3 following routes will 404 if o is None.
+ .or(bulk::post::create_bulk_job(o.clone()))
+ .or(bulk::get::get_bulk_job_status(o.clone()))
+ .or(bulk::results::get_bulk_job_result(o))
+ .recover(errors::handle_rejection)
+}
diff --git a/backend/src/routes/version/get.rs b/backend/src/routes/version/get.rs
new file mode 100644
index 00000000..441968ea
--- /dev/null
+++ b/backend/src/routes/version/get.rs
@@ -0,0 +1,60 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2022 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 /version` endpoint.
+
+use crate::sentry_util::CARGO_PKG_VERSION;
+use serde::{Deserialize, Serialize};
+use warp::Filter;
+
+/// Endpoint response body.
+#[derive(Clone, Debug, Deserialize, Serialize)]
+struct EndpointVersion {
+ version: String,
+}
+
+/// Create the `GET /version` endpoint.
+pub fn get_version() -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone
+{
+ warp::path("version").and(warp::get()).map(|| {
+ warp::reply::json(&EndpointVersion {
+ version: CARGO_PKG_VERSION.into(),
+ })
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::get_version;
+ use crate::sentry_util::CARGO_PKG_VERSION;
+ use warp::http::StatusCode;
+ use warp::test::request;
+
+ #[tokio::test]
+ async fn test_get_version() {
+ let resp = request()
+ .path("/version")
+ .method("GET")
+ .reply(&get_version())
+ .await;
+
+ assert_eq!(resp.status(), StatusCode::OK);
+ assert_eq!(
+ resp.body(),
+ format!("{{\"version\":\"{}\"}}", CARGO_PKG_VERSION).as_str()
+ );
+ }
+}
diff --git a/backend/src/routes/version/mod.rs b/backend/src/routes/version/mod.rs
new file mode 100644
index 00000000..bf578eed
--- /dev/null
+++ b/backend/src/routes/version/mod.rs
@@ -0,0 +1,17 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2022 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 get;
diff --git a/backend/src/sentry_util.rs b/backend/src/sentry_util.rs
new file mode 100644
index 00000000..1827e65f
--- /dev/null
+++ b/backend/src/sentry_util.rs
@@ -0,0 +1,192 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2022 Reacher
+
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+//! Helper functions to send events to Sentry.
+//!
+//! This module also contains functions that check if the error's given by
+//! `check-if-email-exists` are known errors, in which case we don't log them
+//! to Sentry.
+
+use super::sentry_util;
+use async_smtp::smtp::error::Error as AsyncSmtpError;
+use check_if_email_exists::{smtp::SmtpError, CheckEmailOutput};
+use sentry::protocol::{Event, Level, Value};
+use std::io::Error as IoError;
+use std::{collections::BTreeMap, env};
+
+pub const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
+
+/// Setup Sentry.
+pub fn setup_sentry() -> sentry::ClientInitGuard {
+ // Use an empty string if we don't have any env variable for sentry. Sentry
+ // will just silently ignore.
+ let sentry = sentry::init(env::var("RCH_SENTRY_DSN").unwrap_or_else(|_| "".into()));
+ if sentry.is_enabled() {
+ log::info!(target: "reacher", "Sentry is successfully set up.")
+ }
+
+ sentry
+}
+
+/// If BACKEND_NAME environment variable is set, add it to the sentry `extra`
+/// properties.
+/// For backwards compatibility, we also support HEROKU_APP_NAME env variable.
+fn add_backend_name(mut extra: BTreeMap<String, Value>) -> BTreeMap<String, Value> {
+ if let Ok(n) = env::var("BACKEND_NAME") {
+ extra.insert("BACKEND_NAME".into(), n.into());
+ } else if let Ok(n) = env::var("HEROKU_APP_NAME") {
+ extra.insert("BACKEND_NAME".into(), n.into());
+ }
+
+ extra
+}
+
+/// Helper function to send an Info event to Sentry. We use these events for
+/// analytics purposes (I know, Sentry shouldn't be used for that...).
+/// TODO https://github.com/reacherhq/backend/issues/207
+pub fn metrics(message: String, duration: u128, domain: &str) {
+ log::info!(target: "reacher", "Sending info to Sentry: {}", message);
+
+ let mut extra = BTreeMap::new();
+
+ extra.insert("duration".into(), duration.to_string().into());
+ extra.insert("domain".into(), domain.into());
+ extra = add_backend_name(extra);
+
+ sentry::capture_event(Event {
+ extra,
+ level: Level::Info,
+ message: Some(message),
+ release: Some(CARGO_PKG_VERSION.into()),
+ ..Default::default()
+ });
+}
+
+/// Helper function to send an Error event to Sentry. We redact all sensitive
+/// info before sending to Sentry, but removing all instances of `username`.
+pub fn error(message: String, result: Option<&str>, username: &str) {
+ let redacted_message = redact(message.as_str(), username);
+ log::debug!(target: "reacher", "Sending error to Sentry: {}", redacted_message);
+
+ let mut extra = BTreeMap::new();
+ if let Some(result) = result {
+ extra.insert("CheckEmailOutput".into(), redact(result, username).into());
+ }
+
+ extra = add_backend_name(extra);
+
+ sentry::capture_event(Event {
+ extra,
+ level: Level::Error,
+ message: Some(redacted_message),
+ release: Some(CARGO_PKG_VERSION.into()),
+ ..Default::default()
+ });
+}
+
+/// Function to replace all usernames from email, and replace them with
+/// `***@domain.com` for privacy reasons.
+fn redact(input: &str, username: &str) -> String {
+ input.replace(username, "***")
+}
+
+/// Check if the message contains known SMTP IO errors.
+fn has_smtp_io_errors(error: &IoError) -> bool {
+ // code: 104, kind: ConnectionReset, message: "Connection reset by peer",
+ error.raw_os_error() == Some(104) ||
+ // kind: Other, error: "incomplete",
+ error.to_string() == "incomplete"
+}
+
+/// Check if the message contains known SMTP Transient errors.
+fn has_smtp_transient_errors(message: &[String]) -> bool {
+ let first_line = message[0].to_lowercase();
+
+ // 4.3.2 Please try again later
+ first_line.contains("try again") ||
+ // Temporary local problem - please try later
+ first_line.contains("try later")
+}
+
+/// Checks if the output from `check-if-email-exists` has a known error, in
+/// which case we don't log to Sentry to avoid spamming it.
+pub fn log_unknown_errors(result: &CheckEmailOutput) {
+ match (&result.misc, &result.mx, &result.smtp) {
+ (Err(error), _, _) => {
+ // We log misc errors.
+ sentry_util::error(
+ format!("{:?}", error),
+ Some(format!("{:#?}", result).as_ref()),
+ result.syntax.username.as_str(),
+ );
+ }
+ (_, Err(error), _) => {
+ // We log mx errors.
+ sentry_util::error(
+ format!("{:?}", error),
+ Some(format!("{:#?}", result).as_ref()),
+ result.syntax.username.as_str(),
+ );
+ }
+ (_, _, Err(SmtpError::SmtpError(AsyncSmtpError::Transient(response))))
+ if has_smtp_transient_errors(&response.message) =>
+ {
+ log::debug!(target: "reacher", "Transient error: {}", response.message[0]);
+ }
+ (_, _, Err(SmtpError::SmtpError(AsyncSmtpError::Io(err)))) if has_smtp_io_errors(err) => {
+ log::debug!(target: "reacher", "Io error: {}", err);
+ }
+ (_, _, Err(error)) => {
+ // If it's a SMTP error we didn't catch above, we log to
+ // Sentry, to be able to debug them better. We don't want to
+ // spam Sentry and log all instances of the error, hence the
+ // `count` check.
+ sentry_util::error(
+ format!("{:?}", error),
+ Some(format!("{:#?}", result).as_ref()),
+ result.syntax.username.as_str(),
+ );
+ }
+ // If everything is ok, we just return the result.
+ (Ok(_), Ok(_), Ok(_)) => {}
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::redact;
+
+ #[test]
+ fn test_redact() {
+ assert_eq!("***@gmail.com", redact("[email protected]", "someone"));
+ assert_eq!(
+ "my email is ***@gmail.com.",
+ redact("my email is [email protected].", "someone")
+ );
+ assert_eq!(
+ "my email is ***@gmail.com., I repeat, my email is ***@gmail.com.",
+ redact(
+ "my email is [email protected]., I repeat, my email is [email protected].",
+ "someone"
+ )
+ );
+ assert_eq!(
+ "*** @ gmail . com",
+ redact("someone @ gmail . com", "someone")
+ );
+ assert_eq!("*** is here.", redact("someone is here.", "someone"));
+ }
+}
diff --git a/backend/tests/README.md b/backend/tests/README.md
new file mode 100644
index 00000000..57b9c75c
--- /dev/null
+++ b/backend/tests/README.md
@@ -0,0 +1,5 @@
+# Integration Tests
+
+Files in this folder are Reacher backend's integration tests. They need the following to work:
+
+- a working internet connection.
diff --git a/backend/tests/check_email.rs b/backend/tests/check_email.rs
new file mode 100644
index 00000000..d379bdc8
--- /dev/null
+++ b/backend/tests/check_email.rs
@@ -0,0 +1,49 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2022 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 reacher_backend::routes::{check_email::post::EndpointRequest, create_routes};
+use serde_json;
+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},"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":""}}"#;
+const FOO_BAR_BAZ_RESPONSE: &str = r#"{"input":"[email protected]","is_reachable":"invalid","misc":{"is_disposable":false,"is_role_account":false},"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"}}"#;
+
+#[tokio::test]
+async fn test_input_foo_bar() {
+ let resp = request()
+ .path("/v0/check_email")
+ .method("POST")
+ .json(&serde_json::from_str::<EndpointRequest>(r#"{"to_email": "foo@bar"}"#).unwrap())
+ .reply(&create_routes(None))
+ .await;
+
+ assert_eq!(resp.status(), StatusCode::OK);
+ assert_eq!(resp.body(), FOO_BAR_RESPONSE);
+}
+
+#[tokio::test]
+async fn test_input_foo_bar_baz() {
+ let resp = request()
+ .path("/v0/check_email")
+ .method("POST")
+ .json(&serde_json::from_str::<EndpointRequest>(r#"{"to_email": "[email protected]"}"#).unwrap())
+ .reply(&create_routes(None))
+ .await;
+
+ assert_eq!(resp.status(), StatusCode::OK);
+ assert_eq!(resp.body(), FOO_BAR_BAZ_RESPONSE);
+}
diff --git a/cli/README.md b/cli/README.md
new file mode 100644
index 00000000..7781d08e
--- /dev/null
+++ b/cli/README.md
@@ -0,0 +1,79 @@
+<br /><br /><br />
+
+<h1 align="center">check-if-email-exists CLI</h1>
+<h4 align="center">Email verification from your terminal.</h4>
+
+<br /><br /><br />
+
+> Note: The CLI binary doesn't connect to any backend, it checks the email directly from your computer.
+
+## Usage
+
+Head to the [releases page](https://github.com/reacherhq/check-if-email-exists/releases) and download the binary for your platform.
+
+Then run:
+
+```bash
+> $ check_if_email_exists --help
+check_if_email_exists 0.8.32
+Check if an email address exists without sending an email.
+
+USAGE:
+ check_if_email_exists [FLAGS] [OPTIONS] [TO_EMAIL]
+
+ARGS:
+ <TO_EMAIL> The email to check
+
+FLAGS:
+ -h, --help Print help information
+ --http DEPRECATED. Runs an HTTP server. This option will be removed in v0.9.0
+ -V, --version Print version information
+
+OPTIONS:
+ --from-email <FROM_EMAIL>
+ The email to use in the `MAIL FROM:` SMTP command [env: FROM_EMAIL=] [default:
+
+ --hello-name <HELLO_NAME>
+ The name to use in the `EHLO:` SMTP command [env: HELLO_NAME=] [default: localhost]
+
+ --proxy-host <PROXY_HOST>
+ Use the specified SOCKS5 proxy host to perform email verification [env: PROXY_HOST=]
+
+ --proxy-port <PROXY_PORT>
+ Use the specified SOCKS5 proxy port to perform email verification. Only used when
+ `--proxy-host` flag is set [env: PROXY_PORT=] [default: 1080]
+
+ --smtp-port <SMTP_PORT>
+ The email to check [env: SMTP_PORT=] [default: 25]
+
+ --yahoo-use-api <YAHOO_USE_API>
+ For Yahoo email addresses, use Yahoo's API instead of connecting directly to their SMTP
+ servers [env: YAHOO_USE_API=] [default: true]
+```
+
+**💡 PRO TIP:** To show debug logs when running the binary, run:
+
+```bash
+RUST_LOG=debug check_if_email_exists
+```
+
+## Build From Source
+
+First, [install Rust](https://www.rust-lang.org/tools/install); you'll need Rust 1.37.0 or later. Then, run the following commands:
+
+```bash
+# Download the code
+$ git clone https://github.com/reacherhq/check-if-email-exists
+$ cd check-if-email-exists
+
+# Build in release mode
+$ cargo build --release
+
+# Run the binary
+$ ./target/release/check_if_email_exists --help
+```
+
+## Legacy Bash Script
+
+The 1st version of this tool was a simple bash script that made a telnet call. If you would like to use that simpler version, have a look at the [`legacy`](https://github.com/reacherhq/check-if-email-exists/tree/legacy) branch. The reasons for porting the bash script to the current codebase are explained [in issue #4](https://github.com/reacherhq/check-if-email-exists/issues/4).
diff --git a/test_suite/Cargo.toml b/test_suite/Cargo.toml
deleted file mode 100644
index b5798fc2..00000000
--- a/test_suite/Cargo.toml
+++ /dev/null
@@ -1,11 +0,0 @@
-[package]
-name = "check-if-email-exists-test-suite"
-version = "0.8.24"
-edition = "2018"
-publish = false
-
-[dependencies]
-check-if-email-exists = { path = "../core" }
-serde = "1.0.143"
-serde_json = "1.0.83"
-tokio = { version = "1.16.1", features = ["rt"] }
diff --git a/test_suite/src/fixtures/foo.json b/test_suite/src/fixtures/foo.json
deleted file mode 100644
index d58c5871..00000000
--- a/test_suite/src/fixtures/foo.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "input": "foo",
- "is_reachable": "invalid",
- "misc": { "is_disposable": false, "is_role_account": false },
- "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": ""
- }
-}
diff --git a/test_suite/src/fixtures/[email protected] b/test_suite/src/fixtures/[email protected]
deleted file mode 100644
index f2252afe..00000000
--- a/test_suite/src/fixtures/[email protected]
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "input": "[email protected]",
- "is_reachable": "invalid",
- "misc": { "is_disposable": false, "is_role_account": false },
- "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"
- }
-}
diff --git a/test_suite/src/fixtures/[email protected] b/test_suite/src/fixtures/[email protected]
deleted file mode 100644
index 9d3b4c06..00000000
--- a/test_suite/src/fixtures/[email protected]
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "input": "foo@bar",
- "is_reachable": "invalid",
- "misc": { "is_disposable": false, "is_role_account": false },
- "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": ""
- }
-}
diff --git a/test_suite/src/fixtures/[email protected] b/test_suite/src/fixtures/[email protected]
deleted file mode 100644
index 4236b82b..00000000
--- a/test_suite/src/fixtures/[email protected]
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "input": "[email protected]",
- "is_reachable": "invalid",
- "misc": { "is_disposable": false, "is_role_account": false },
- "mx": {
- "accepts_mail": true,
- "records": [
- "alt4.gmail-smtp-in.l.google.com.",
- "alt1.gmail-smtp-in.l.google.com.",
- "alt2.gmail-smtp-in.l.google.com.",
- "gmail-smtp-in.l.google.com.",
- "alt3.gmail-smtp-in.l.google.com."
- ]
- },
- "smtp": {
- "can_connect_smtp": true,
- "has_full_inbox": false,
- "is_catch_all": false,
- "is_deliverable": false,
- "is_disabled": true
- },
- "syntax": {
- "address": "[email protected]",
- "domain": "gmail.com",
- "is_valid_syntax": true,
- "username": "someone"
- }
-}
diff --git a/test_suite/src/fixtures/[email protected] b/test_suite/src/fixtures/[email protected]
deleted file mode 100644
index 1206c499..00000000
--- a/test_suite/src/fixtures/[email protected]
+++ /dev/null
@@ -1,26 +0,0 @@
-{
- "input": "[email protected]",
- "is_reachable": "invalid",
- "misc": { "is_disposable": false, "is_role_account": false },
- "mx": {
- "accepts_mail": true,
- "records": [
- "mta7.am0.yahoodns.net.",
- "mta6.am0.yahoodns.net.",
- "mta5.am0.yahoodns.net."
- ]
- },
- "smtp": {
- "can_connect_smtp": true,
- "has_full_inbox": false,
- "is_catch_all": false,
- "is_deliverable": false,
- "is_disabled": false
- },
- "syntax": {
- "address": "[email protected]",
- "domain": "yahoo.com",
- "is_valid_syntax": true,
- "username": "yahoo"
- }
-}
diff --git a/test_suite/src/lib.rs b/test_suite/src/lib.rs
deleted file mode 100644
index d5e44fcf..00000000
--- a/test_suite/src/lib.rs
+++ /dev/null
@@ -1,102 +0,0 @@
-// check-if-email-exists
-// Copyright (C) 2018-2022 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/>.
-
-//! E2E tests
-
-#[cfg(test)]
-mod tests {
- use check_if_email_exists::{check_email, CheckEmailInput};
- use serde_json;
- use std::fs;
- use tokio::runtime::Runtime;
-
- /// Function to test all fixtures from a folder.
- fn test_all_from_folder(folder: &str) {
- let runtime = Runtime::new().unwrap();
- let paths = fs::read_dir(folder).unwrap();
-
- // For every fixture file, we compare:
- // - the result of `check_email` with the email in the filename
- // - the contents of the file
- for path in paths {
- let path = path.unwrap().path();
- let file = fs::File::open(path.clone()).unwrap();
- let filename = path.file_stem().unwrap().to_str().unwrap();
- if filename.starts_with(".") {
- // Don't process hidden files.
- continue;
- }
- let expected: serde_json::Value = serde_json::from_reader(file).unwrap();
-
- println!("Check {}", filename);
- let input = CheckEmailInput::new(vec![filename.into()]);
- let result = runtime.block_on(check_email(&input));
- let actual = serde_json::to_value(&result[0]).unwrap();
-
- // Uncomment to see the JSON result of `check_email`.
- // println!("{}", actual);
-
- // For the input,misc,smtp,syntax fields, we match exact JSON.
- assert_eq!(expected.get("input"), actual.get("input"),);
- assert_eq!(expected.get("is_reachable"), actual.get("is_reachable"),);
- assert_eq!(expected.get("misc"), actual.get("misc"),);
- assert_eq!(expected.get("smtp"), actual.get("smtp"),);
- assert_eq!(expected.get("syntax"), actual.get("syntax"),);
-
- // For the mx field, the `records` field array can contain elements
- // in different order. We only check length in that case
- if expected.get("mx").unwrap().get("error").is_some() {
- assert_eq!(expected.get("mx"), actual.get("mx"));
- } else {
- assert_eq!(
- expected.get("mx").unwrap().get("accepts_mail"),
- actual.get("mx").unwrap().get("accepts_mail")
- );
-
- assert_eq!(
- expected
- .get("mx")
- .unwrap()
- .get("records")
- .unwrap()
- .as_array()
- .unwrap()
- .len(),
- actual
- .get("mx")
- .unwrap()
- .get("records")
- .unwrap()
- .as_array()
- .unwrap()
- .len()
- );
- }
- }
- }
-
- #[test]
- fn should_pass_fixtures() {
- test_all_from_folder("./src/fixtures");
- }
-
- #[test]
- fn should_pass_sensitive_fixtures() {
- // These fixtures contain real-file emails, they are not committed to
- // git.
- test_all_from_folder("./src/sensitive_fixtures");
- }
-}
diff --git a/test_suite/src/sensitive_fixtures/.gitkeep b/test_suite/src/sensitive_fixtures/.gitkeep
deleted file mode 100644
index e69de29b..00000000