├── .dockerignore ├── .editorconfig ├── .env.example ├── .github ├── FUNDING.yml ├── dependabot.yml └── workflows │ ├── pr.yml │ ├── production.yml │ └── tag.yml ├── .gitignore ├── .rustfmt.toml ├── CHANGELOG.md ├── Cargo.lock ├── Cargo.toml ├── Dockerfile ├── LICENSE.AGPL ├── LICENSE.md ├── Procfile ├── README.md ├── SETUP.md ├── app.json ├── migrations ├── 20210316025847_setup.down.sql ├── 20210316025847_setup.up.sql ├── 20210921115907_clear.down.sql ├── 20210921115907_clear.up.sql ├── 20211013151757_fix_mq_latest_message.down.sql ├── 20211013151757_fix_mq_latest_message.up.sql ├── 20220117025847_email_data.down.sql ├── 20220117025847_email_data.up.sql ├── 20220208120856_fix_concurrent_poll.down.sql ├── 20220208120856_fix_concurrent_poll.up.sql ├── 20220713122907_fix-clear_all-keep-nil-message.down.sql ├── 20220713122907_fix-clear_all-keep-nil-message.up.sql ├── 20220810141100_result_created_at.down.sql ├── 20220810141100_result_created_at.up.sql └── README.md ├── openapi.json ├── sqlx-data.json ├── src ├── check.rs ├── errors.rs ├── lib.rs ├── main.rs ├── routes │ ├── bulk │ │ ├── db.rs │ │ ├── error.rs │ │ ├── get.rs │ │ ├── mod.rs │ │ ├── post.rs │ │ ├── results.rs │ │ └── task.rs │ ├── check_email │ │ ├── mod.rs │ │ └── post.rs │ ├── mod.rs │ └── version │ │ ├── get.rs │ │ └── mod.rs └── sentry_util.rs └── tests ├── README.md └── check_email.rs /.dockerignore: -------------------------------------------------------------------------------- 1 | target/ 2 | Dockerfile 3 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Top-most EditorConfig file 2 | root = true 3 | 4 | [*] 5 | indent_style=tab 6 | indent_size=tab 7 | tab_width=4 8 | end_of_line=lf 9 | charset=utf-8 10 | trim_trailing_whitespace=true 11 | max_line_length=120 12 | insert_final_newline=true 13 | 14 | [*.{yml,sh}] 15 | indent_style=space 16 | indent_size=2 17 | tab_width=8 18 | end_of_line=lf 19 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | DATABASE_URL=postgres://localhost/reacherdb 2 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: amaurym 4 | custom: https://www.paypal.me/amaurym10/20 5 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: "/" 5 | schedule: 6 | interval: weekly 7 | time: "02:00" 8 | timezone: Europe/Berlin 9 | open-pull-requests-limit: 10 10 | ignore: 11 | - dependency-name: async-smtp 12 | versions: 13 | - 0.4.0 14 | -------------------------------------------------------------------------------- /.github/workflows/pr.yml: -------------------------------------------------------------------------------- 1 | # Based on https://github.com/actions-rs/meta/blob/master/recipes/quickstart.md 2 | 3 | name: CI 4 | 5 | on: 6 | push: 7 | branches: 8 | - master 9 | pull_request: 10 | branches: 11 | - master 12 | 13 | # run builds and tests without sqlx's compile time query checks 14 | # https://github.com/launchbadge/sqlx/blob/master/sqlx-cli/README.md#force-building-in-offline-mode 15 | env: 16 | SQLX_OFFLINE: true 17 | 18 | jobs: 19 | # Cargo check. 20 | check: 21 | runs-on: ubuntu-latest 22 | steps: 23 | - name: Checkout sources 24 | uses: actions/checkout@v2 25 | 26 | - name: Install stable toolchain 27 | uses: actions-rs/toolchain@v1 28 | with: 29 | profile: minimal 30 | toolchain: stable 31 | override: true 32 | 33 | - name: Run cargo check 34 | uses: actions-rs/cargo@v1 35 | with: 36 | command: check 37 | 38 | # Cargo test. 39 | test: 40 | runs-on: ubuntu-latest 41 | steps: 42 | - name: Checkout sources 43 | uses: actions/checkout@v2 44 | 45 | - name: Install stable toolchain 46 | uses: actions-rs/toolchain@v1 47 | with: 48 | profile: minimal 49 | toolchain: stable 50 | override: true 51 | 52 | - name: Run cargo test 53 | uses: actions-rs/cargo@v1 54 | with: 55 | command: test 56 | args: --all 57 | 58 | # Cargo fmt and clippy. 59 | lints: 60 | runs-on: ubuntu-latest 61 | steps: 62 | - name: Checkout sources 63 | uses: actions/checkout@v2 64 | 65 | - name: Install stable toolchain 66 | uses: actions-rs/toolchain@v1 67 | with: 68 | profile: minimal 69 | toolchain: stable 70 | override: true 71 | components: rustfmt, clippy 72 | 73 | - name: Run cargo fmt 74 | uses: actions-rs/cargo@v1 75 | with: 76 | command: fmt 77 | args: --all -- --check 78 | 79 | - name: Run cargo clippy 80 | uses: actions-rs/cargo@v1 81 | with: 82 | command: clippy 83 | args: -- -D warnings 84 | -------------------------------------------------------------------------------- /.github/workflows/production.yml: -------------------------------------------------------------------------------- 1 | name: production 2 | 3 | on: 4 | push: 5 | tags: 6 | - v*.*.* 7 | 8 | jobs: 9 | # Deploy the code to Heroku. 10 | heroku-production: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v2 14 | - uses: akhileshns/heroku-deploy@v3.0.4 15 | with: 16 | heroku_api_key: ${{ secrets.HEROKU_API_KEY }} 17 | heroku_app_name: reacher-email-production-us 18 | heroku_email: ${{ secrets.HEROKU_EMAIL }} 19 | -------------------------------------------------------------------------------- /.github/workflows/tag.yml: -------------------------------------------------------------------------------- 1 | name: tag 2 | 3 | on: 4 | push: 5 | tags: 6 | - "v*.*.*" 7 | 8 | jobs: 9 | docker-publish: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@master 13 | - name: Set GITHUB_TAG env 14 | id: vars 15 | run: echo ::set-output name=GITHUB_TAG::${GITHUB_REF:10} # Remove /refs/head/ 16 | - name: Publish to Registry 17 | uses: elgohr/Publish-Docker-Github-Action@master 18 | with: 19 | name: reacherhq/backend 20 | username: ${{ secrets.DOCKER_USERNAME }} 21 | password: ${{ secrets.DOCKER_PASSWORD }} 22 | tags: "latest,${{ steps.vars.outputs.GITHUB_TAG }}" 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated 2 | target 3 | 4 | # OS-related files 5 | .DS_Store 6 | 7 | # Log files 8 | *.log 9 | 10 | # Secrets 11 | *.csv 12 | .env 13 | -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | hard_tabs = true 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. 4 | 5 | ### [0.3.12](https://github.com/reacherhq/backend/compare/v0.3.11...v0.3.12) (2021-10-11) 6 | 7 | 8 | ### Features 9 | 10 | * Add `smtp_port` field in request for validation through different port ([#233](https://github.com/reacherhq/backend/issues/233)) ([ea6b3fc](https://github.com/reacherhq/backend/commit/ea6b3fc01d406064d99863ad75b68cea8baa4480)) 11 | 12 | ### [0.3.11](https://github.com/reacherhq/backend/compare/v0.3.10...v0.3.11) (2021-09-13) 13 | 14 | 15 | ### Bug Fixes 16 | 17 | * Adding openssl as a vendored dependency ([#225](https://github.com/reacherhq/backend/issues/225)) ([02255d7](https://github.com/reacherhq/backend/commit/02255d73a78d05fd4355a68ca274d4d46bb67130)) 18 | 19 | ### [0.3.10](https://github.com/reacherhq/backend/compare/v0.3.9...v0.3.10) (2021-07-08) 20 | 21 | 22 | ### Bug Fixes 23 | 24 | * Filter out username when redacting emails ([#209](https://github.com/reacherhq/backend/issues/209)) ([b6fea2f](https://github.com/reacherhq/backend/commit/b6fea2f8454bd95242a55d75d24aa05cc31749d1)) 25 | * Redact emails in Sentry error messages ([#208](https://github.com/reacherhq/backend/issues/208)) ([f73a209](https://github.com/reacherhq/backend/commit/f73a209ec8a7e2c1529702ff263942b2b96d712c)) 26 | 27 | ### [0.3.9](https://github.com/reacherhq/backend/compare/v0.3.8...v0.3.9) (2021-06-20) 28 | 29 | 30 | ### Features 31 | 32 | * Add `proxy` field to check_email body ([#205](https://github.com/reacherhq/backend/issues/205)) ([0a54c31](https://github.com/reacherhq/backend/commit/0a54c315dff569fdf30d2edb0ad1769477816aca)) 33 | * Make `x-saasify-proxy-secret` optional ([#204](https://github.com/reacherhq/backend/issues/204)) ([258314e](https://github.com/reacherhq/backend/commit/258314eb47eaec308b5818acde7d18777630cf35)) 34 | 35 | ### [0.3.8](https://github.com/reacherhq/backend/compare/v0.3.7...v0.3.8) (2021-04-05) 36 | 37 | 38 | ### Features 39 | 40 | * Add Dockerfile ([#184](https://github.com/reacherhq/backend/issues/184)) ([9afbfe0](https://github.com/reacherhq/backend/commit/9afbfe0685d6e55257f7634414f9d9db812519ad)) 41 | 42 | 43 | ### Bug Fixes 44 | 45 | * Update check-if-email-exists deps ([#197](https://github.com/reacherhq/backend/issues/197)) ([cc8f3f0](https://github.com/reacherhq/backend/commit/cc8f3f054bbc3626d4c0f085aa3b02e266eff227)) 46 | 47 | ### [0.3.7](https://github.com/reacherhq/backend/compare/v0.3.6...v0.3.7) (2021-01-10) 48 | 49 | ### [0.3.6](https://github.com/reacherhq/backend/compare/v0.3.5...v0.3.6) (2020-12-14) 50 | 51 | ### [0.3.5](https://github.com/reacherhq/backend/compare/v0.3.4...v0.3.5) (2020-12-11) 52 | 53 | ### [0.3.4](https://github.com/reacherhq/backend/compare/v0.3.3...v0.3.4) (2020-11-25) 54 | 55 | 56 | ### Features 57 | 58 | * Remove diesel and DB ([#157](https://github.com/reacherhq/backend/issues/157)) ([bbbfe1b](https://github.com/reacherhq/backend/commit/bbbfe1b3fd9b35cb8e852684943a9b426296471b)) 59 | * Stop using Tor ([#156](https://github.com/reacherhq/backend/issues/156)) ([dee3043](https://github.com/reacherhq/backend/commit/dee304335d937e0f9bc9c70963a8b5a00f97eaa8)) 60 | 61 | ### [0.3.3](https://github.com/reacherhq/backend/compare/v0.3.2...v0.3.3) (2020-09-24) 62 | 63 | 64 | ### Bug Fixes 65 | 66 | * Show timeout error message in JSON ([#134](https://github.com/reacherhq/backend/issues/134)) ([8341fcd](https://github.com/reacherhq/backend/commit/8341fcdfbb0cb002c11db237122144999804000a)) 67 | 68 | ### [0.3.2](https://github.com/reacherhq/backend/compare/v0.3.1...v0.3.2) (2020-09-23) 69 | 70 | 71 | ### Bug Fixes 72 | 73 | * Add a better race future function ([#133](https://github.com/reacherhq/backend/issues/133)) ([a569b55](https://github.com/reacherhq/backend/commit/a569b55f81da78dfef4a26ee82b203d663765781)) 74 | 75 | ### [0.3.1](https://github.com/reacherhq/backend/compare/v0.3.0...v0.3.1) (2020-08-23) 76 | 77 | 78 | ### Features 79 | 80 | * Add saasify support ([#125](https://github.com/reacherhq/backend/issues/125)) ([2407a02](https://github.com/reacherhq/backend/commit/2407a02134479f88dcb93b8054ad538a73b8103d)) 81 | * Add v0 prefix to routes ([#126](https://github.com/reacherhq/backend/issues/126)) ([671a7a0](https://github.com/reacherhq/backend/commit/671a7a0899b16013ca5e727fd70ab22d2c429f2b)) 82 | 83 | ## [0.3.0](https://github.com/reacherhq/backend/compare/v0.2.5...v0.3.0) (2020-08-15) 84 | 85 | 86 | ### Features 87 | 88 | * Add basic authentication with Heroku ([#114](https://github.com/reacherhq/backend/issues/114)) ([ed95737](https://github.com/reacherhq/backend/commit/ed957371ced2b4752fb53b6ef38017587e9299aa)) 89 | 90 | ### [0.2.5](https://github.com/reacherhq/backend/compare/v0.2.4...v0.2.5) (2020-07-11) 91 | 92 | 93 | ### Bug Fixes 94 | 95 | * Update check-if-email-exists, use proxy in Yahoo API ([#99](https://github.com/reacherhq/backend/issues/99)) ([93cc16f](https://github.com/reacherhq/backend/commit/93cc16f59b078d113900ee7c697c1066bde0ef7e)) 96 | 97 | ### [0.2.4](https://github.com/reacherhq/backend/compare/v0.2.3...v0.2.4) (2020-06-30) 98 | 99 | 100 | ### Features 101 | 102 | * Add /version to heroku ([#82](https://github.com/reacherhq/backend/issues/82)) ([c619970](https://github.com/reacherhq/backend/commit/c619970ad6a67e6b3d6faf561dacae6dd1564f71)) 103 | * Deploy to serverless ([#80](https://github.com/reacherhq/backend/issues/80)) ([cbe7220](https://github.com/reacherhq/backend/commit/cbe7220d3dab47e627458ee8eb770b7704a99520)) 104 | 105 | 106 | ### Bug Fixes 107 | 108 | * Update packages and add more Sentry error checks ([#94](https://github.com/reacherhq/backend/issues/94)) ([e1141dd](https://github.com/reacherhq/backend/commit/e1141dd5a5116af0c1cd4b11b11058741efb4c02)) 109 | * **openapi:** Add input schema, fix descriptions ([#84](https://github.com/reacherhq/backend/issues/84)) ([ddc137c](https://github.com/reacherhq/backend/commit/ddc137c305d138ac63efbc7cdc68802fb8794154)) 110 | * Better loggin for staging vs prod ([#77](https://github.com/reacherhq/backend/issues/77)) ([044b1e4](https://github.com/reacherhq/backend/commit/044b1e4c46995d374b8ddaafa91df99b41912f39)) 111 | 112 | ### [0.2.3](https://github.com/reacherhq/backend/compare/v0.2.2...v0.2.3) (2020-05-30) 113 | 114 | 115 | ### Features 116 | 117 | * Add heroku deployment ([#72](https://github.com/reacherhq/backend/issues/72)) ([e08b70f](https://github.com/reacherhq/backend/commit/e08b70fa4a4d2b0d153a9200f84ac5164e0de204)) 118 | 119 | 120 | ### Bug Fixes 121 | 122 | * Add additional error message parsing ([#71](https://github.com/reacherhq/backend/issues/71)) ([8b7c394](https://github.com/reacherhq/backend/commit/8b7c394c982f6effa550284c3fbef17edc0d73a0)) 123 | 124 | ### [0.2.2](https://github.com/reacherhq/backend/compare/v0.2.1...v0.2.2) (2020-05-24) 125 | 126 | 127 | ### Features 128 | 129 | * Add success rate and verification time metrics ([#70](https://github.com/reacherhq/backend/issues/70)) ([911b9e1](https://github.com/reacherhq/backend/commit/911b9e1a0b7a32cac70b11b2f0af19fdc947b9de)) 130 | 131 | ### [0.2.1](https://github.com/reacherhq/backend/compare/v0.2.0...v0.2.1) (2020-05-23) 132 | 133 | 134 | ### Bug Fixes 135 | 136 | * Better retry mechanism, with or without Tor ([#68](https://github.com/reacherhq/backend/issues/68)) ([83fd4fe](https://github.com/reacherhq/backend/commit/83fd4fead130a1088cb23bdbc3040bd4f501efb9)) 137 | * Improve retry mechanism and error logging ([#69](https://github.com/reacherhq/backend/issues/69)) ([791da70](https://github.com/reacherhq/backend/commit/791da70a46f8a63887397435d0cc52d7c840ece2)) 138 | 139 | ## [0.2.0](https://github.com/reacherhq/backend/compare/v0.1.10...v0.2.0) (2020-05-16) 140 | 141 | 142 | ### Features 143 | 144 | * Add is_reachable field in json ([#63](https://github.com/reacherhq/backend/issues/63)) ([6fd5215](https://github.com/reacherhq/backend/commit/6fd5215285cf6b841d8c843857f9b9bf11940c82)) 145 | 146 | ### [0.1.10](https://github.com/reacherhq/backend/compare/v0.1.9...v0.1.10) (2020-05-10) 147 | 148 | 149 | ### Bug Fixes 150 | 151 | * Put correct SAASIFY_SECRET_HEADER ([#53](https://github.com/reacherhq/backend/issues/53)) ([21d0417](https://github.com/reacherhq/backend/commit/21d0417817b4c394d67ff1dd1cc48e6c8a7f50d8)) 152 | 153 | ### [0.1.9](https://github.com/reacherhq/backend/compare/v0.1.8...v0.1.9) (2020-05-10) 154 | 155 | 156 | ### Features 157 | 158 | * Add x-saasify-secret verification & retry mechanism ([#51](https://github.com/reacherhq/backend/issues/51)) ([5767e1e](https://github.com/reacherhq/backend/commit/5767e1e32497d6535ac5794a1afffbfe1cc60b05)), closes [#46](https://github.com/reacherhq/backend/issues/46) [#44](https://github.com/reacherhq/backend/issues/44) 159 | 160 | 161 | ### Bug Fixes 162 | 163 | * Fix dockerfiles ENV ([#52](https://github.com/reacherhq/backend/issues/52)) ([c2cd1f4](https://github.com/reacherhq/backend/commit/c2cd1f42bd3d01359da9987441e05b992bdbf15c)) 164 | 165 | ### [0.1.8](https://github.com/reacherhq/backend/compare/v0.1.7...v0.1.8) (2020-05-09) 166 | 167 | 168 | ### Features 169 | 170 | * Use custom FROM email, defined in env ([#49](https://github.com/reacherhq/backend/issues/49)) ([ea31e4a](https://github.com/reacherhq/backend/commit/ea31e4abbe7e86860fbc28a4627d826afcb2b1af)), closes [#48](https://github.com/reacherhq/backend/issues/48) 171 | 172 | ### [0.1.7](https://github.com/reacherhq/backend/compare/v0.1.6...v0.1.7) (2020-05-09) 173 | 174 | 175 | ### Bug Fixes 176 | 177 | * **deps:** Update check-if-email-exists to 0.8.1 ([#47](https://github.com/reacherhq/backend/issues/47)) ([6d83593](https://github.com/reacherhq/backend/commit/6d83593415a0956b21b6fa2e7b88b076f3bc649f)) 178 | * **openapi:** Fix outdated ref to EmailResult ([6b1615d](https://github.com/reacherhq/backend/commit/6b1615da7146232971e055d7e5fb710f585cd855)) 179 | 180 | ### [0.1.6](https://github.com/reacherhq/backend/compare/v0.1.5...v0.1.6) (2020-05-08) 181 | 182 | 183 | ### Bug Fixes 184 | 185 | * **deps:** Update to check-if-email-exists 0.8 ([#45](https://github.com/reacherhq/backend/issues/45)) ([2eaf1a2](https://github.com/reacherhq/backend/commit/2eaf1a29162a51671026156cd8be6dd592f3b76a)) 186 | 187 | ### [0.1.5](https://github.com/reacherhq/backend/compare/v0.1.4...v0.1.5) (2020-05-04) 188 | 189 | 190 | ### Bug Fixes 191 | 192 | * Fix CI building production build ([#43](https://github.com/reacherhq/backend/issues/43)) ([0a04981](https://github.com/reacherhq/backend/commit/0a04981ddc6af3b4bccf136c36bfe4dcd53b7d38)) 193 | 194 | ### [0.1.4](https://github.com/reacherhq/backend/compare/v0.1.3...v0.1.4) (2020-05-04) 195 | 196 | 197 | ### Features 198 | 199 | * Add sentry error logging ([#42](https://github.com/reacherhq/backend/issues/42)) ([37c1889](https://github.com/reacherhq/backend/commit/37c18891ccecc1b11fe306ca1bbeff7d9cd98f82)) 200 | 201 | ### [0.1.3](https://github.com/reacherhq/backend/compare/v0.1.2...v0.1.3) (2020-05-04) 202 | 203 | 204 | ### Features 205 | 206 | * Add openapi specification ([#39](https://github.com/reacherhq/backend/issues/39)) ([2c0c91d](https://github.com/reacherhq/backend/commit/2c0c91d073136bdc18f2d6d3a1ab3e60945e348f)) 207 | 208 | ### [0.1.2](https://github.com/reacherhq/backend/compare/v0.1.1...v0.1.2) (2020-05-02) 209 | 210 | 211 | ### Features 212 | 213 | * Add logging of routes ([#34](https://github.com/reacherhq/backend/issues/34)) ([3181087](https://github.com/reacherhq/backend/commit/3181087a5a627cfa13a72269f189f4e302f47e60)) 214 | 215 | ### [0.1.1](https://github.com/reacherhq/backend/compare/v0.1.0...v0.1.1) (2020-05-02) 216 | 217 | 218 | ### Bug Fixes 219 | 220 | * CI tar.gz executable file before release ([#31](https://github.com/reacherhq/backend/issues/31)) ([c1cb9c2](https://github.com/reacherhq/reacher-microservices/commit/c1cb9c26bba7ab660258bd3d21d09cf446da0246)) 221 | 222 | ## 0.1.0 (2020-05-02) 223 | 224 | 225 | ### Features 226 | 227 | * Add /verify/demo endpoint ([5b036b2](https://github.com/reacherhq/backend/commit/5b036b2b2fc7d9fa1740dbb1a29b07ec78e3153f)) 228 | * Add a Dockerfile with Tor ([#24](https://github.com/reacherhq/backend/issues/24)) ([53210fc](https://github.com/reacherhq/reacher-microservices/commit/53210fcca03d1f4b6baad7573b18c49432e389e7)) 229 | * Add bulk verification ([46a418e](https://github.com/reacherhq/backend/commit/46a418e40f9ff1e896eaa00ddeba9d3d6da9abac)) 230 | * Add find or create user ([f06e96a](https://github.com/reacherhq/backend/commit/f06e96a117dcd2eb0535e70e18e69e15d144d48b)) 231 | * Add HTTP server inside Dockerfile ([#28](https://github.com/reacherhq/backend/issues/28)) ([f82610e](https://github.com/reacherhq/reacher-microservices/commit/f82610ecdc6f360e3be8f076fab793b13fb88251)) 232 | * Add serverless rust for email-exists ([3b186fe](https://github.com/reacherhq/backend/commit/3b186fee406af38faf6ec5e82cb68f0d30599b55)) 233 | 234 | 235 | ### Bug Fixes 236 | 237 | * Allow usage of express middlewares ([a37b8f5](https://github.com/reacherhq/backend/commit/a37b8f5bcbeea366f4c658f6dad4becf38245eeb)) 238 | * Return HTTP error when verification fails ([#30](https://github.com/reacherhq/backend/issues/30)) ([9074768](https://github.com/reacherhq/reacher-microservices/commit/90747689ff83640aa5b8b37d54a2f0b09cc433b3)) 239 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "reacher_backend" 3 | version = "0.4.0" 4 | edition = "2018" 5 | license = "AGPL-3.0" 6 | publish = false 7 | 8 | [dependencies] 9 | async-smtp = "0.5" 10 | check-if-email-exists = "0.8" 11 | csv = "1.1.6" 12 | dotenv = "0.15.0" 13 | env_logger = "0.9" 14 | log = "0.4" 15 | openssl = { version = "0.10.41", features = ["vendored"] } 16 | sentry = "0.23" 17 | serde = { version = "1.0", features = ["derive"] } 18 | serde_json = "1.0" 19 | sqlx = { version = "0.6", features = [ "runtime-tokio-native-tls", "postgres", "uuid", "chrono", "json", "offline", "migrate" ] } 20 | sqlxmq = "0.4" 21 | tokio = { version = "1.20", features = ["macros"] } 22 | uuid = "1.1" 23 | warp = "0.3" 24 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # From https://shaneutt.com/blog/rust-fast-small-docker-image-builds/ 2 | 3 | # ------------------------------------------------------------------------------ 4 | # Cargo Build Stage 5 | # ------------------------------------------------------------------------------ 6 | 7 | FROM messense/rust-musl-cross:x86_64-musl as cargo-build 8 | 9 | WORKDIR /usr/src/reacher 10 | 11 | RUN rm -f target/x86_64-unknown-linux-musl/release/deps/reacher* 12 | 13 | COPY . . 14 | 15 | ENV SQLX_OFFLINE=true 16 | 17 | RUN cargo build --release --target=x86_64-unknown-linux-musl 18 | 19 | # ------------------------------------------------------------------------------ 20 | # Final Stage 21 | # ------------------------------------------------------------------------------ 22 | 23 | FROM alpine:latest 24 | 25 | RUN addgroup -g 1000 reacher 26 | 27 | RUN adduser -D -s /bin/sh -u 1000 -G reacher reacher 28 | 29 | WORKDIR /home/reacher/bin/ 30 | 31 | COPY --from=cargo-build /usr/src/reacher/target/x86_64-unknown-linux-musl/release/reacher_backend . 32 | 33 | RUN chown reacher:reacher reacher_backend 34 | 35 | USER reacher 36 | 37 | ENV RUST_LOG=reacher=info 38 | ENV RCH_HTTP_HOST=0.0.0.0 39 | ENV PORT=8080 40 | # Bulk verification is disabled by default. Set to 1 to enable it. 41 | ENV RCH_ENABLE_BULK=0 42 | 43 | EXPOSE 8080 44 | 45 | CMD ["./reacher_backend"] 46 | -------------------------------------------------------------------------------- /LICENSE.AGPL: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | `reacherhq/backend`'s source code is provided under a **dual license model**. 2 | 3 | ### Commercial license 4 | 5 | If you want to use `reacherhq/backend` to develop commercial sites, tools, and applications, the Commercial License is the appropriate license. With this option, your source code is kept proprietary. Purchase an `reacherhq/backend` Commercial License at https://reacher.email/pricing. 6 | 7 | ### Open source license 8 | 9 | If you are creating an open source application under a license compatible with the GNU Affero GPL license v3, you may use `reacherhq/backend` under the terms of the [AGPL-3.0](./LICENSE.AGPL). 10 | 11 | [Read more](https://help.reacher.email/reacher-licenses) about Reacher's license. 12 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: ./target/release/reacher_backend 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Actions Status](https://github.com/reacherhq/backend/workflows/pr/badge.svg)](https://github.com/reacherhq/backend/actions) 2 | [![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) 3 | 4 |

5 | 6 |

reacher

7 |

⚙️ Reacher Backend

8 |

Backend Server for Reacher Email Verification API: https://reacher.email.

9 | 10 |

11 | 12 | # ⚠️⚠️ IMPORTANT UPDATE ⚠️⚠️ 13 | 14 | This repo has been moved to the monorepo [reacherhq/check-if-email-exists](https://github.com/reacherhq/check-if-email-exists), in the `backend` subfolder. 15 | 16 | ## Reacher Backend 17 | 18 | This repository holds the backend for [Reacher](https://reacher.email). The backend is a HTTP server with the following components: 19 | 20 | - [`check-if-email-exists`](https://github.com/reacherhq/check-if-email-exists), which performs the core email verification logic, 21 | - [`warp`](https://github.com/seanmonstar/warp) web framework. 22 | 23 | ## Get Started 24 | 25 | There are 2 ways you can run this backend. 26 | 27 | ### 1. Use Docker 28 | 29 | The [Docker image](./Dockerfile) is hosted on Docker Hub: https://hub.docker.com/r/reacherhq/backend. 30 | 31 | To run it, run the following command: 32 | 33 | ```bash 34 | docker run -p 8080:8080 reacherhq/backend 35 | ``` 36 | 37 | You can then send a POST request with the following body to `http://localhost:8080/v0/check_email`: 38 | 39 | ```js 40 | { 41 | "to_email": "someone@gmail.com", 42 | "from_email": "my@my-server.com", // (optional) email to use in the `FROM` SMTP command, defaults to "user@example.org" 43 | "hello_name": "my-server.com", // (optional) name to use in the `EHLO` SMTP command, defaults to "localhost" 44 | "proxy": { // (optional) SOCK5 proxy to run the verification through, default is empty 45 | "host": "my-proxy.io", 46 | "port": 1080 47 | }, 48 | "smtp_port": 587 // (optional) SMTP port to do the email verification, defaults to 25 49 | } 50 | ``` 51 | 52 | ### 2. Run locally 53 | 54 | If you prefer to run the server locally on your machine, just clone the repository and run: 55 | 56 | ```bash 57 | cargo run 58 | ``` 59 | 60 | The server will then be listening on `http://127.0.0.1:8080`. 61 | 62 | ### Configuration 63 | 64 | These are the environment variables used to configure the HTTP server: 65 | 66 | | Env Var | Required? | Description | Default | 67 | | ----------------------------------- | --------------------------- | ---------------------------------------------------------------------------------------------------------- | ------------------ | 68 | | `RCH_ENABLE_BULK` | No | If set to 1, then bulk verification endpoints will be added to the backend. | 0 | 69 | | `DATABASE_URL` | Yes if `RCH_ENABLE_BULK==1` | Database connection string for storing results and task queue | not defined | 70 | | `RCH_HTTP_HOST` | No | The host name to bind the HTTP server to. | `127.0.0.1` | 71 | | `PORT` | No | The port to bind the HTTP server to, often populated by the cloud provider. | `8080` | 72 | | `RCH_FROM_EMAIL` | No | The email to use in the `MAIL FROM:` SMTP command. | `user@example.org` | 73 | | `RCH_SENTRY_DSN` | No | If set, bug reports will be sent to this [Sentry](https://sentry.io) DSN. | not defined | 74 | | `RCH_DATABASE_MAX_CONNECTIONS` | No | Connections created for the database pool | 5 | 75 | | `RCH_MINIMUM_TASK_CONCURRENCY` | No | Minimum number of concurrent running tasks below which more tasks are fetched | 10 | 76 | | `RCH_MAXIMUM_CONCURRENT_TASK_FETCH` | No | Maximum number of tasks fetched at once | 20 | 77 | | `RUST_LOG` | No | One of `trace,debug,warn,error,info`. 💡 PRO TIP: `RUST_LOG=debug` is very handful for debugging purposes. | not defined | 78 | 79 | ## REST API Documentation 80 | 81 | Read docs on https://help.reacher.email/rest-api-documentation. 82 | 83 | The API basically only exposes one endpoint: `POST /v0/check_email` expecting the following body: 84 | 85 | ```js 86 | { 87 | "to_email": "someone@gmail.com", 88 | "from_email": "my@my-server.com", // (optional) email to use in the `FROM` SMTP command, defaults to "user@example.org" 89 | "hello_name": "my-server.com", // (optional) name to use in the `EHLO` SMTP command, defaults to "localhost" 90 | "proxy": { // (optional) SOCK5 proxy to run the verification through, default is empty 91 | "host": "my-proxy.io", 92 | "port": 1080 93 | }, 94 | "smtp_port": 587 // (optional) SMTP port to do the email verification, defaults to 25 95 | } 96 | ``` 97 | 98 | Also check [`openapi.json`](./openapi.json) for the complete OpenAPI specification. 99 | 100 | ## License 101 | 102 | `reacherhq/backend`'s source code is provided under a **dual license model**. 103 | 104 | ### Commercial license 105 | 106 | If you want to use `reacherhq/backend` to develop commercial sites, tools, and applications, the Commercial License is the appropriate license. With this option, your source code is kept proprietary. Purchase an `reacherhq/backend` Commercial License at https://reacher.email/pricing. 107 | 108 | ### Open source license 109 | 110 | If you are creating an open source application under a license compatible with the GNU Affero GPL license v3, you may use `reacherhq/backend` under the terms of the [AGPL-3.0](./LICENSE.AGPL). 111 | 112 | [Read more](https://help.reacher.email/reacher-licenses) about Reacher's license. 113 | 114 | ## Sponsor my Open-Source Work 115 | 116 | If you like my open-source work at Reacher, consider [sponsoring me](https://github.com/sponsors/amaurym/)! You'll also get 8000 free email verifications every month with your Reacher account, and a this contribution would mean A WHOLE LOT to me. 117 | -------------------------------------------------------------------------------- /SETUP.md: -------------------------------------------------------------------------------- 1 | ## Dev environment installation 2 | 3 | 1. Install [docker](https://docs.docker.com/get-docker/) 4 | 2. Run the following command to get a postgresql database running - `docker run --name -p 5432:5432 -e POSTGRES_PASSWORD= -d postgres:14`. Note that default user and database is postgres. 5 | 3. Download migrations from [sqlxmq](https://github.com/Diggsey/sqlxmq#database-schema) to setup database for message queue. 6 | 4. Install [psql](https://blog.timescale.com/blog/how-to-install-psql-on-mac-ubuntu-debian-windows/) to apply migrations to db. 7 | 5. Use `cargo install rargs` and run the following to apply migrations - `ls migrations/**/*up.sql | rargs psql postgres://postgres:@localhost/postgres -f {0}` 8 | 6. Add a `.env` file with a single key for the connection string `DATABASE_URL=postgres://postgres:@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. 9 | -------------------------------------------------------------------------------- /app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "reacher", 3 | "buildpacks": [{ "url": "emk/rust" }], 4 | "description": "Real-Time Email Verification API", 5 | "env": { 6 | "RCH_HTTP_HOST": { 7 | "description": "The host name to bind the HTTP server to.", 8 | "value": "0.0.0.0" 9 | } 10 | }, 11 | "keywords": ["email", "smtp", "rust", "email-validation", "email-verification"], 12 | "logo": "https://storage.googleapis.com/saasify-uploads-prod/696e287ad79f0e0352bc201b36d701849f7d55e7.svg", 13 | "repository": "https://github.com/reacherhq/backend" 14 | } 15 | -------------------------------------------------------------------------------- /migrations/20210316025847_setup.down.sql: -------------------------------------------------------------------------------- 1 | DROP FUNCTION mq_checkpoint; 2 | DROP FUNCTION mq_keep_alive; 3 | DROP FUNCTION mq_delete; 4 | DROP FUNCTION mq_commit; 5 | DROP FUNCTION mq_insert; 6 | DROP FUNCTION mq_poll; 7 | DROP FUNCTION mq_active_channels; 8 | DROP FUNCTION mq_latest_message; 9 | DROP TABLE mq_payloads; 10 | DROP TABLE mq_msgs; 11 | DROP FUNCTION mq_uuid_exists; 12 | DROP TYPE mq_new_t; 13 | -------------------------------------------------------------------------------- /migrations/20210316025847_setup.up.sql: -------------------------------------------------------------------------------- 1 | CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; 2 | 3 | -- The UDT for creating messages 4 | CREATE TYPE mq_new_t AS ( 5 | -- Unique message ID 6 | id UUID, 7 | -- Delay before message is processed 8 | delay INTERVAL, 9 | -- Number of retries if initial processing fails 10 | retries INT, 11 | -- Initial backoff between retries 12 | retry_backoff INTERVAL, 13 | -- Name of channel 14 | channel_name TEXT, 15 | -- Arguments to channel 16 | channel_args TEXT, 17 | -- Interval for two-phase commit (or NULL to disable two-phase commit) 18 | commit_interval INTERVAL, 19 | -- Whether this message should be processed in order with respect to other 20 | -- ordered messages. 21 | ordered BOOLEAN, 22 | -- Name of message 23 | name TEXT, 24 | -- JSON payload 25 | payload_json TEXT, 26 | -- Binary payload 27 | payload_bytes BYTEA 28 | ); 29 | 30 | -- Small, frequently updated table of messages 31 | CREATE TABLE mq_msgs ( 32 | id UUID PRIMARY KEY, 33 | created_at TIMESTAMPTZ DEFAULT NOW(), 34 | attempt_at TIMESTAMPTZ DEFAULT NOW(), 35 | attempts INT NOT NULL DEFAULT 5, 36 | retry_backoff INTERVAL NOT NULL DEFAULT INTERVAL '1 second', 37 | channel_name TEXT NOT NULL, 38 | channel_args TEXT NOT NULL, 39 | commit_interval INTERVAL, 40 | after_message_id UUID DEFAULT uuid_nil() REFERENCES mq_msgs(id) ON DELETE SET DEFAULT 41 | ); 42 | 43 | -- Insert dummy message so that the 'nil' UUID can be referenced 44 | INSERT INTO mq_msgs (id, channel_name, channel_args, after_message_id) VALUES (uuid_nil(), '', '', NULL); 45 | 46 | -- Internal helper function to check that a UUID is neither NULL nor NIL 47 | CREATE FUNCTION mq_uuid_exists( 48 | id UUID 49 | ) RETURNS BOOLEAN AS $$ 50 | SELECT id IS NOT NULL AND id != uuid_nil() 51 | $$ LANGUAGE SQL IMMUTABLE; 52 | 53 | -- Index for polling 54 | CREATE INDEX ON mq_msgs(channel_name, channel_args, attempt_at) WHERE id != uuid_nil() AND NOT mq_uuid_exists(after_message_id); 55 | -- Index for adding messages 56 | CREATE INDEX ON mq_msgs(channel_name, channel_args, created_at, id) WHERE id != uuid_nil() AND after_message_id IS NOT NULL; 57 | 58 | -- Index for ensuring strict message order 59 | CREATE UNIQUE INDEX mq_msgs_channel_name_channel_args_after_message_id_idx ON mq_msgs(channel_name, channel_args, after_message_id); 60 | 61 | 62 | -- Large, less frequently updated table of message payloads 63 | CREATE TABLE mq_payloads( 64 | id UUID PRIMARY KEY, 65 | name TEXT NOT NULL, 66 | payload_json JSONB, 67 | payload_bytes BYTEA 68 | ); 69 | 70 | -- Internal helper function to return the most recently added message in a queue. 71 | CREATE FUNCTION mq_latest_message(from_channel_name TEXT, from_channel_args TEXT) 72 | RETURNS UUID AS $$ 73 | SELECT COALESCE( 74 | ( 75 | SELECT id FROM mq_msgs 76 | WHERE channel_name = from_channel_name 77 | AND channel_args = from_channel_args 78 | AND after_message_id IS NOT NULL 79 | AND id != uuid_nil() 80 | ORDER BY created_at DESC, id DESC 81 | LIMIT 1 82 | ), 83 | uuid_nil() 84 | ) 85 | $$ LANGUAGE SQL STABLE; 86 | 87 | -- Internal helper function to randomly select a set of channels with "ready" messages. 88 | CREATE FUNCTION mq_active_channels(channel_names TEXT[], batch_size INT) 89 | RETURNS TABLE(name TEXT, args TEXT) AS $$ 90 | SELECT channel_name, channel_args 91 | FROM mq_msgs 92 | WHERE id != uuid_nil() 93 | AND attempt_at <= NOW() 94 | AND (channel_names IS NULL OR channel_name = ANY(channel_names)) 95 | AND NOT mq_uuid_exists(after_message_id) 96 | GROUP BY channel_name, channel_args 97 | ORDER BY RANDOM() 98 | LIMIT batch_size 99 | $$ LANGUAGE SQL STABLE; 100 | 101 | -- Main entry-point for job runner: pulls a batch of messages from the queue. 102 | CREATE FUNCTION mq_poll(channel_names TEXT[], batch_size INT DEFAULT 1) 103 | RETURNS TABLE( 104 | id UUID, 105 | is_committed BOOLEAN, 106 | name TEXT, 107 | payload_json TEXT, 108 | payload_bytes BYTEA, 109 | retry_backoff INTERVAL, 110 | wait_time INTERVAL 111 | ) AS $$ 112 | BEGIN 113 | RETURN QUERY UPDATE mq_msgs 114 | SET 115 | attempt_at = CASE WHEN mq_msgs.attempts = 1 THEN NULL ELSE NOW() + mq_msgs.retry_backoff END, 116 | attempts = mq_msgs.attempts - 1, 117 | retry_backoff = mq_msgs.retry_backoff * 2 118 | FROM ( 119 | SELECT 120 | msgs.id 121 | FROM mq_active_channels(channel_names, batch_size) AS active_channels 122 | INNER JOIN LATERAL ( 123 | SELECT * FROM mq_msgs 124 | WHERE mq_msgs.id != uuid_nil() 125 | AND mq_msgs.attempt_at <= NOW() 126 | AND mq_msgs.channel_name = active_channels.name 127 | AND mq_msgs.channel_args = active_channels.args 128 | AND NOT mq_uuid_exists(mq_msgs.after_message_id) 129 | ORDER BY mq_msgs.attempt_at ASC 130 | LIMIT batch_size 131 | ) AS msgs ON TRUE 132 | LIMIT batch_size 133 | ) AS messages_to_update 134 | LEFT JOIN mq_payloads ON mq_payloads.id = messages_to_update.id 135 | WHERE mq_msgs.id = messages_to_update.id 136 | RETURNING 137 | mq_msgs.id, 138 | mq_msgs.commit_interval IS NULL, 139 | mq_payloads.name, 140 | mq_payloads.payload_json::TEXT, 141 | mq_payloads.payload_bytes, 142 | mq_msgs.retry_backoff / 2, 143 | interval '0' AS wait_time; 144 | 145 | IF NOT FOUND THEN 146 | RETURN QUERY SELECT 147 | NULL::UUID, 148 | NULL::BOOLEAN, 149 | NULL::TEXT, 150 | NULL::TEXT, 151 | NULL::BYTEA, 152 | NULL::INTERVAL, 153 | MIN(mq_msgs.attempt_at) - NOW() 154 | FROM mq_msgs 155 | WHERE mq_msgs.id != uuid_nil() 156 | AND NOT mq_uuid_exists(mq_msgs.after_message_id) 157 | AND (channel_names IS NULL OR mq_msgs.channel_name = ANY(channel_names)); 158 | END IF; 159 | END; 160 | $$ LANGUAGE plpgsql; 161 | 162 | -- Creates new messages 163 | CREATE FUNCTION mq_insert(new_messages mq_new_t[]) 164 | RETURNS VOID AS $$ 165 | BEGIN 166 | PERFORM pg_notify(CONCAT('mq_', channel_name), '') 167 | FROM unnest(new_messages) AS new_msgs 168 | GROUP BY channel_name; 169 | 170 | IF FOUND THEN 171 | PERFORM pg_notify('mq', ''); 172 | END IF; 173 | 174 | INSERT INTO mq_payloads ( 175 | id, 176 | name, 177 | payload_json, 178 | payload_bytes 179 | ) SELECT 180 | id, 181 | name, 182 | payload_json::JSONB, 183 | payload_bytes 184 | FROM UNNEST(new_messages); 185 | 186 | INSERT INTO mq_msgs ( 187 | id, 188 | attempt_at, 189 | attempts, 190 | retry_backoff, 191 | channel_name, 192 | channel_args, 193 | commit_interval, 194 | after_message_id 195 | ) 196 | SELECT 197 | id, 198 | NOW() + delay + COALESCE(commit_interval, INTERVAL '0'), 199 | retries + 1, 200 | retry_backoff, 201 | channel_name, 202 | channel_args, 203 | commit_interval, 204 | CASE WHEN ordered 205 | THEN 206 | LAG(id, 1, mq_latest_message(channel_name, channel_args)) 207 | OVER (PARTITION BY channel_name, channel_args, ordered ORDER BY id) 208 | ELSE 209 | NULL 210 | END 211 | FROM UNNEST(new_messages); 212 | END; 213 | $$ LANGUAGE plpgsql; 214 | 215 | -- Commits messages previously created with a non-NULL commit interval. 216 | CREATE FUNCTION mq_commit(msg_ids UUID[]) 217 | RETURNS VOID AS $$ 218 | BEGIN 219 | UPDATE mq_msgs 220 | SET 221 | attempt_at = attempt_at - commit_interval, 222 | commit_interval = NULL 223 | WHERE id = ANY(msg_ids) 224 | AND commit_interval IS NOT NULL; 225 | END; 226 | $$ LANGUAGE plpgsql; 227 | 228 | 229 | -- Deletes messages from the queue. This occurs when a message has been 230 | -- processed, or when it expires without being processed. 231 | CREATE FUNCTION mq_delete(msg_ids UUID[]) 232 | RETURNS VOID AS $$ 233 | BEGIN 234 | PERFORM pg_notify(CONCAT('mq_', channel_name), '') 235 | FROM mq_msgs 236 | WHERE id = ANY(msg_ids) 237 | AND after_message_id = uuid_nil() 238 | GROUP BY channel_name; 239 | 240 | IF FOUND THEN 241 | PERFORM pg_notify('mq', ''); 242 | END IF; 243 | 244 | DELETE FROM mq_msgs WHERE id = ANY(msg_ids); 245 | DELETE FROM mq_payloads WHERE id = ANY(msg_ids); 246 | END; 247 | $$ LANGUAGE plpgsql; 248 | 249 | 250 | -- Can be called during the initial commit interval, or when processing 251 | -- a message. Indicates that the caller is still active and will prevent either 252 | -- the commit interval elapsing or the message being retried for the specified 253 | -- interval. 254 | CREATE FUNCTION mq_keep_alive(msg_ids UUID[], duration INTERVAL) 255 | RETURNS VOID AS $$ 256 | UPDATE mq_msgs 257 | SET 258 | attempt_at = NOW() + duration, 259 | commit_interval = commit_interval + ((NOW() + duration) - attempt_at) 260 | WHERE id = ANY(msg_ids) 261 | AND attempt_at < NOW() + duration; 262 | $$ LANGUAGE SQL; 263 | 264 | 265 | -- Called during lengthy processing of a message to checkpoint the progress. 266 | -- As well as behaving like `mq_keep_alive`, the message payload can be 267 | -- updated. 268 | CREATE FUNCTION mq_checkpoint( 269 | msg_id UUID, 270 | duration INTERVAL, 271 | new_payload_json TEXT, 272 | new_payload_bytes BYTEA, 273 | extra_retries INT 274 | ) 275 | RETURNS VOID AS $$ 276 | UPDATE mq_msgs 277 | SET 278 | attempt_at = GREATEST(attempt_at, NOW() + duration), 279 | attempts = attempts + COALESCE(extra_retries, 0) 280 | WHERE id = msg_id; 281 | 282 | UPDATE mq_payloads 283 | SET 284 | payload_json = COALESCE(new_payload_json::JSONB, payload_json), 285 | payload_bytes = COALESCE(new_payload_bytes, payload_bytes) 286 | WHERE 287 | id = msg_id; 288 | $$ LANGUAGE SQL; 289 | 290 | -------------------------------------------------------------------------------- /migrations/20210921115907_clear.down.sql: -------------------------------------------------------------------------------- 1 | DROP FUNCTION mq_clear; 2 | DROP FUNCTION mq_clear_all; 3 | -------------------------------------------------------------------------------- /migrations/20210921115907_clear.up.sql: -------------------------------------------------------------------------------- 1 | -- Deletes all messages from a list of channel names. 2 | CREATE FUNCTION mq_clear(channel_names TEXT[]) 3 | RETURNS VOID AS $$ 4 | BEGIN 5 | WITH deleted_ids AS ( 6 | DELETE FROM mq_msgs WHERE channel_name = ANY(channel_names) RETURNING id 7 | ) 8 | DELETE FROM mq_payloads WHERE id IN (SELECT id FROM deleted_ids); 9 | END; 10 | $$ LANGUAGE plpgsql; 11 | 12 | -- Deletes all messages. 13 | CREATE FUNCTION mq_clear_all() 14 | RETURNS VOID AS $$ 15 | BEGIN 16 | WITH deleted_ids AS ( 17 | DELETE FROM mq_msgs RETURNING id 18 | ) 19 | DELETE FROM mq_payloads WHERE id IN (SELECT id FROM deleted_ids); 20 | END; 21 | $$ LANGUAGE plpgsql; 22 | -------------------------------------------------------------------------------- /migrations/20211013151757_fix_mq_latest_message.down.sql: -------------------------------------------------------------------------------- 1 | CREATE OR REPLACE FUNCTION mq_latest_message(from_channel_name TEXT, from_channel_args TEXT) 2 | RETURNS UUID AS $$ 3 | SELECT COALESCE( 4 | ( 5 | SELECT id FROM mq_msgs 6 | WHERE channel_name = from_channel_name 7 | AND channel_args = from_channel_args 8 | AND after_message_id IS NOT NULL 9 | AND id != uuid_nil() 10 | ORDER BY created_at DESC, id DESC 11 | LIMIT 1 12 | ), 13 | uuid_nil() 14 | ) 15 | $$ LANGUAGE SQL STABLE; 16 | -------------------------------------------------------------------------------- /migrations/20211013151757_fix_mq_latest_message.up.sql: -------------------------------------------------------------------------------- 1 | CREATE OR REPLACE FUNCTION mq_latest_message(from_channel_name TEXT, from_channel_args TEXT) 2 | RETURNS UUID AS $$ 3 | SELECT COALESCE( 4 | ( 5 | SELECT id FROM mq_msgs 6 | WHERE channel_name = from_channel_name 7 | AND channel_args = from_channel_args 8 | AND after_message_id IS NOT NULL 9 | AND id != uuid_nil() 10 | AND NOT EXISTS( 11 | SELECT * FROM mq_msgs AS mq_msgs2 12 | WHERE mq_msgs2.after_message_id = mq_msgs.id 13 | ) 14 | ORDER BY created_at DESC 15 | LIMIT 1 16 | ), 17 | uuid_nil() 18 | ) 19 | $$ LANGUAGE SQL STABLE; -------------------------------------------------------------------------------- /migrations/20220117025847_email_data.down.sql: -------------------------------------------------------------------------------- 1 | DROP INDEX job_emails; 2 | DROP TABLE email_results; 3 | DROP TABLE bulk_jobs; 4 | DROP TYPE valid_status; -------------------------------------------------------------------------------- /migrations/20220117025847_email_data.up.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE bulk_jobs ( 2 | id SERIAL PRIMARY KEY, 3 | created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), 4 | total_records INTEGER NOT NULL 5 | ); 6 | CREATE TABLE email_results ( 7 | id SERIAL PRIMARY KEY, 8 | job_id INTEGER, 9 | result JSONB, 10 | FOREIGN KEY (job_id) REFERENCES bulk_jobs(id) 11 | ); 12 | CREATE INDEX job_emails ON email_results USING HASH (job_id); -------------------------------------------------------------------------------- /migrations/20220208120856_fix_concurrent_poll.down.sql: -------------------------------------------------------------------------------- 1 | -- Main entry-point for job runner: pulls a batch of messages from the queue. 2 | CREATE OR REPLACE FUNCTION mq_poll(channel_names TEXT[], batch_size INT DEFAULT 1) 3 | RETURNS TABLE( 4 | id UUID, 5 | is_committed BOOLEAN, 6 | name TEXT, 7 | payload_json TEXT, 8 | payload_bytes BYTEA, 9 | retry_backoff INTERVAL, 10 | wait_time INTERVAL 11 | ) AS $$ 12 | BEGIN 13 | RETURN QUERY UPDATE mq_msgs 14 | SET 15 | attempt_at = CASE WHEN mq_msgs.attempts = 1 THEN NULL ELSE NOW() + mq_msgs.retry_backoff END, 16 | attempts = mq_msgs.attempts - 1, 17 | retry_backoff = mq_msgs.retry_backoff * 2 18 | FROM ( 19 | SELECT 20 | msgs.id 21 | FROM mq_active_channels(channel_names, batch_size) AS active_channels 22 | INNER JOIN LATERAL ( 23 | SELECT * FROM mq_msgs 24 | WHERE mq_msgs.id != uuid_nil() 25 | AND mq_msgs.attempt_at <= NOW() 26 | AND mq_msgs.channel_name = active_channels.name 27 | AND mq_msgs.channel_args = active_channels.args 28 | AND NOT mq_uuid_exists(mq_msgs.after_message_id) 29 | ORDER BY mq_msgs.attempt_at ASC 30 | LIMIT batch_size 31 | ) AS msgs ON TRUE 32 | LIMIT batch_size 33 | ) AS messages_to_update 34 | LEFT JOIN mq_payloads ON mq_payloads.id = messages_to_update.id 35 | WHERE mq_msgs.id = messages_to_update.id 36 | RETURNING 37 | mq_msgs.id, 38 | mq_msgs.commit_interval IS NULL, 39 | mq_payloads.name, 40 | mq_payloads.payload_json::TEXT, 41 | mq_payloads.payload_bytes, 42 | mq_msgs.retry_backoff / 2, 43 | interval '0' AS wait_time; 44 | 45 | IF NOT FOUND THEN 46 | RETURN QUERY SELECT 47 | NULL::UUID, 48 | NULL::BOOLEAN, 49 | NULL::TEXT, 50 | NULL::TEXT, 51 | NULL::BYTEA, 52 | NULL::INTERVAL, 53 | MIN(mq_msgs.attempt_at) - NOW() 54 | FROM mq_msgs 55 | WHERE mq_msgs.id != uuid_nil() 56 | AND NOT mq_uuid_exists(mq_msgs.after_message_id) 57 | AND (channel_names IS NULL OR mq_msgs.channel_name = ANY(channel_names)); 58 | END IF; 59 | END; 60 | $$ LANGUAGE plpgsql; -------------------------------------------------------------------------------- /migrations/20220208120856_fix_concurrent_poll.up.sql: -------------------------------------------------------------------------------- 1 | 2 | -- Main entry-point for job runner: pulls a batch of messages from the queue. 3 | CREATE OR REPLACE FUNCTION mq_poll(channel_names TEXT[], batch_size INT DEFAULT 1) 4 | RETURNS TABLE( 5 | id UUID, 6 | is_committed BOOLEAN, 7 | name TEXT, 8 | payload_json TEXT, 9 | payload_bytes BYTEA, 10 | retry_backoff INTERVAL, 11 | wait_time INTERVAL 12 | ) AS $$ 13 | BEGIN 14 | RETURN QUERY UPDATE mq_msgs 15 | SET 16 | attempt_at = CASE WHEN mq_msgs.attempts = 1 THEN NULL ELSE NOW() + mq_msgs.retry_backoff END, 17 | attempts = mq_msgs.attempts - 1, 18 | retry_backoff = mq_msgs.retry_backoff * 2 19 | FROM ( 20 | SELECT 21 | msgs.id 22 | FROM mq_active_channels(channel_names, batch_size) AS active_channels 23 | INNER JOIN LATERAL ( 24 | SELECT mq_msgs.id FROM mq_msgs 25 | WHERE mq_msgs.id != uuid_nil() 26 | AND mq_msgs.attempt_at <= NOW() 27 | AND mq_msgs.channel_name = active_channels.name 28 | AND mq_msgs.channel_args = active_channels.args 29 | AND NOT mq_uuid_exists(mq_msgs.after_message_id) 30 | ORDER BY mq_msgs.attempt_at ASC 31 | LIMIT batch_size 32 | ) AS msgs ON TRUE 33 | LIMIT batch_size 34 | ) AS messages_to_update 35 | LEFT JOIN mq_payloads ON mq_payloads.id = messages_to_update.id 36 | WHERE mq_msgs.id = messages_to_update.id 37 | AND mq_msgs.attempt_at <= NOW() 38 | RETURNING 39 | mq_msgs.id, 40 | mq_msgs.commit_interval IS NULL, 41 | mq_payloads.name, 42 | mq_payloads.payload_json::TEXT, 43 | mq_payloads.payload_bytes, 44 | mq_msgs.retry_backoff / 2, 45 | interval '0' AS wait_time; 46 | 47 | IF NOT FOUND THEN 48 | RETURN QUERY SELECT 49 | NULL::UUID, 50 | NULL::BOOLEAN, 51 | NULL::TEXT, 52 | NULL::TEXT, 53 | NULL::BYTEA, 54 | NULL::INTERVAL, 55 | MIN(mq_msgs.attempt_at) - NOW() 56 | FROM mq_msgs 57 | WHERE mq_msgs.id != uuid_nil() 58 | AND NOT mq_uuid_exists(mq_msgs.after_message_id) 59 | AND (channel_names IS NULL OR mq_msgs.channel_name = ANY(channel_names)); 60 | END IF; 61 | END; 62 | $$ LANGUAGE plpgsql; 63 | -------------------------------------------------------------------------------- /migrations/20220713122907_fix-clear_all-keep-nil-message.down.sql: -------------------------------------------------------------------------------- 1 | -- Add down migration script here 2 | -------------------------------------------------------------------------------- /migrations/20220713122907_fix-clear_all-keep-nil-message.up.sql: -------------------------------------------------------------------------------- 1 | CREATE OR REPLACE FUNCTION mq_clear(channel_names TEXT[]) 2 | RETURNS VOID AS $$ 3 | BEGIN 4 | WITH deleted_ids AS ( 5 | DELETE FROM mq_msgs 6 | WHERE channel_name = ANY(channel_names) 7 | AND id != uuid_nil() 8 | RETURNING id 9 | ) 10 | DELETE FROM mq_payloads WHERE id IN (SELECT id FROM deleted_ids); 11 | END; 12 | $$ LANGUAGE plpgsql; 13 | COMMENT ON FUNCTION mq_clear IS 14 | 'Deletes all messages with corresponding payloads from a list of channel names'; 15 | 16 | 17 | CREATE OR REPLACE FUNCTION mq_clear_all() 18 | RETURNS VOID AS $$ 19 | BEGIN 20 | WITH deleted_ids AS ( 21 | DELETE FROM mq_msgs 22 | WHERE id != uuid_nil() 23 | RETURNING id 24 | ) 25 | DELETE FROM mq_payloads WHERE id IN (SELECT id FROM deleted_ids); 26 | END; 27 | $$ LANGUAGE plpgsql; 28 | COMMENT ON FUNCTION mq_clear_all IS 29 | 'Deletes all messages with corresponding payloads'; 30 | -------------------------------------------------------------------------------- /migrations/20220810141100_result_created_at.down.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE email_results 2 | DROP COLUMN created_at; 3 | -------------------------------------------------------------------------------- /migrations/20220810141100_result_created_at.up.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE email_results 2 | ADD created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(); -------------------------------------------------------------------------------- /migrations/README.md: -------------------------------------------------------------------------------- 1 | # Database and Migrations 2 | 3 | ## Migrations 4 | 5 | All migrations in this folder are embedded directly in the `reacher_backend` binary, so you don't need to run the migrations manually. 6 | 7 | The migrations come from 2 sources: 8 | - `sqlxmq` migrations 9 | - Reacher's own migrations 10 | 11 | ## `sqlxmq` migrations 12 | 13 | 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): 14 | 15 | - `20210316025847_setup.{up,down}.sql` 16 | - `20210921115907_clear.{up,down}.sql` 17 | - `20211013151757_fix_mq_latest_message.{up,down}.sql` 18 | - `20220208120856_fix_concurrent_poll.{up,down}.sql` 19 | - `20220713122907_fix-clear_all-keep-nil-message.{up,down}.sql` 20 | 21 | ## Reacher migrations 22 | 23 | The following migrations are specific to Reacher: 24 | 25 | - `20220117025847_email_data.down.sql`: set up the `bulk_jobs` and `email_results` tables 26 | - `20220810141100_result_created_at.down.sql`: add a `created_at` column on `email_result` 27 | 28 | ## Advanced Usage 29 | 30 | For more advanced usage (such as reverting to an old state), please use the `sqlx` CLI command. 31 | 32 | See https://github.com/launchbadge/sqlx/blob/main/sqlx-cli/README.md 33 | -------------------------------------------------------------------------------- /openapi.json: -------------------------------------------------------------------------------- 1 | { 2 | "openapi": "3.0.0", 3 | "info": { 4 | "title": "Reacher", 5 | "version": "0.3.*", 6 | "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.", 7 | "license": { 8 | "name": "AGPL-3.0 OR Commercial", 9 | "url": "https://github.com/reacherhq/backend/blob/master/LICENSE.md" 10 | }, 11 | "contact": { 12 | "name": "Reacher", 13 | "url": "https://reacher.email", 14 | "email": "amaury@reacher.email" 15 | }, 16 | "termsOfService": "https://github.com/reacherhq/policies/blob/master/terms/index.fr.md" 17 | }, 18 | "servers": [ 19 | { 20 | "url": "https://api.reacher.email/v0", 21 | "description": "Reacher Production" 22 | } 23 | ], 24 | "paths": { 25 | "/check_email": { 26 | "post": { 27 | "summary": "/check_email", 28 | "responses": { 29 | "200": { 30 | "description": "OK", 31 | "content": { 32 | "application/json": { 33 | "schema": { 34 | "$ref": "#/components/schemas/CheckEmailOutput" 35 | }, 36 | "examples": { 37 | "Example with test@gmail.com": { 38 | "value": { 39 | "input": "test@gmail.com", 40 | "is_reachable": "invalid", 41 | "misc": { 42 | "is_disposable": false, 43 | "is_role_account": true 44 | }, 45 | "mx": { 46 | "accepts_mail": true, 47 | "records": [ 48 | "alt4.gmail-smtp-in.l.google.com.", 49 | "alt2.gmail-smtp-in.l.google.com.", 50 | "alt3.gmail-smtp-in.l.google.com.", 51 | "gmail-smtp-in.l.google.com.", 52 | "alt1.gmail-smtp-in.l.google.com." 53 | ] 54 | }, 55 | "smtp": { 56 | "can_connect_smtp": true, 57 | "has_full_inbox": false, 58 | "is_catch_all": false, 59 | "is_deliverable": false, 60 | "is_disabled": false 61 | }, 62 | "syntax": { 63 | "domain": "gmail.com", 64 | "is_valid_syntax": true, 65 | "username": "test" 66 | } 67 | } 68 | } 69 | } 70 | } 71 | } 72 | } 73 | }, 74 | "operationId": "post-check-email", 75 | "description": "Perform a full verification of an email address.", 76 | "requestBody": { 77 | "content": { 78 | "application/json": { 79 | "schema": { 80 | "$ref": "#/components/schemas/CheckEmailInput" 81 | } 82 | } 83 | }, 84 | "description": "Input containing all parameters necessary for an email verification." 85 | }, 86 | "parameters": [ 87 | { 88 | "schema": { 89 | "type": "string" 90 | }, 91 | "in": "header", 92 | "name": "Authorization", 93 | "description": "Your personal Reacher API key", 94 | "required": true 95 | } 96 | ] 97 | }, 98 | "parameters": [] 99 | } 100 | }, 101 | "components": { 102 | "schemas": { 103 | "CheckEmailOutput": { 104 | "title": "CheckEmailOutput", 105 | "type": "object", 106 | "x-examples": { 107 | "Example with test@gmail.com": { 108 | "input": "test@gmail.com", 109 | "is_reachable": "invalid", 110 | "misc": { 111 | "is_disposable": false, 112 | "is_role_account": true 113 | }, 114 | "mx": { 115 | "accepts_mail": true, 116 | "records": [ 117 | "alt4.gmail-smtp-in.l.google.com.", 118 | "alt2.gmail-smtp-in.l.google.com.", 119 | "alt3.gmail-smtp-in.l.google.com.", 120 | "gmail-smtp-in.l.google.com.", 121 | "alt1.gmail-smtp-in.l.google.com." 122 | ] 123 | }, 124 | "smtp": { 125 | "can_connect_smtp": true, 126 | "has_full_inbox": false, 127 | "is_catch_all": false, 128 | "is_deliverable": false, 129 | "is_disabled": false 130 | }, 131 | "syntax": { 132 | "domain": "gmail.com", 133 | "is_valid_syntax": true, 134 | "username": "test" 135 | } 136 | } 137 | }, 138 | "description": "The verification result of an email.", 139 | "properties": { 140 | "input": { 141 | "type": "string", 142 | "format": "email", 143 | "description": "The input email address." 144 | }, 145 | "is_reachable": { 146 | "$ref": "#/components/schemas/Reachable" 147 | }, 148 | "misc": { 149 | "oneOf": [ 150 | { 151 | "$ref": "#/components/schemas/MiscDetails" 152 | }, 153 | { 154 | "$ref": "#/components/schemas/Error" 155 | } 156 | ], 157 | "description": "Miscellaneous information about the email account." 158 | }, 159 | "mx": { 160 | "oneOf": [ 161 | { 162 | "$ref": "#/components/schemas/MxDetails" 163 | }, 164 | { 165 | "$ref": "#/components/schemas/Error" 166 | } 167 | ], 168 | "description": "Information gathered from querying the MX records of the mail server." 169 | }, 170 | "smtp": { 171 | "oneOf": [ 172 | { 173 | "$ref": "#/components/schemas/SmtpDetails" 174 | }, 175 | { 176 | "$ref": "#/components/schemas/Error" 177 | } 178 | ], 179 | "description": "Verifications performed by connecting to the mail server via SMTP." 180 | }, 181 | "syntax": { 182 | "$ref": "#/components/schemas/SyntaxDetails" 183 | } 184 | }, 185 | "required": ["input", "misc", "mx", "smtp", "syntax", "is_reachable"] 186 | }, 187 | "Error": { 188 | "title": "Error", 189 | "type": "object", 190 | "description": "Object describing an error happening during the misc, MX, or SMTP verifications.", 191 | "properties": { 192 | "type": { 193 | "type": "string", 194 | "description": "An error type." 195 | }, 196 | "message": { 197 | "type": "string", 198 | "description": "A human-readable description of the error." 199 | } 200 | }, 201 | "required": ["type", "message"] 202 | }, 203 | "MiscDetails": { 204 | "title": "MiscDetails", 205 | "type": "object", 206 | "description": "Miscellaneous information about the email account.", 207 | "properties": { 208 | "is_disposable": { 209 | "type": "boolean", 210 | "description": "Is the address provided by a known disposable email address provider?" 211 | }, 212 | "is_role_account": { 213 | "type": "boolean", 214 | "description": "Is this email a role-based account?" 215 | } 216 | }, 217 | "required": ["is_disposable", "is_role_account"] 218 | }, 219 | "MxDetails": { 220 | "title": "MxDetails", 221 | "type": "object", 222 | "properties": { 223 | "accepts_mail": { 224 | "type": "boolean", 225 | "description": "Does the server accept mails?" 226 | }, 227 | "records": { 228 | "type": "array", 229 | "description": "The list of FQDN (Fully Qualified Domain Names) of the mail server.", 230 | "items": { 231 | "type": "string" 232 | } 233 | } 234 | }, 235 | "required": ["accepts_mail", "records"], 236 | "description": "Object holding the MX details of the mail server." 237 | }, 238 | "SmtpDetails": { 239 | "title": "SmtpDetails", 240 | "type": "object", 241 | "description": "Verifications performed by connecting to the mail server via SMTP.", 242 | "properties": { 243 | "can_connect_smtp": { 244 | "type": "boolean", 245 | "description": "Can the mail exchanger of the email address domain be contacted successfully?" 246 | }, 247 | "has_full_inbox": { 248 | "type": "boolean", 249 | "description": "Is the inbox of this mailbox full?" 250 | }, 251 | "is_catch_all": { 252 | "type": "boolean", 253 | "description": "Is this email address a catch-all address?" 254 | }, 255 | "is_deliverable": { 256 | "type": "boolean", 257 | "description": "Is an email sent to this address deliverable?" 258 | }, 259 | "is_disabled": { 260 | "type": "boolean", 261 | "description": "Has this email address been disabled by the email provider?" 262 | } 263 | }, 264 | "required": ["can_connect_smtp", "has_full_inbox", "is_catch_all", "is_deliverable", "is_disabled"] 265 | }, 266 | "SyntaxDetails": { 267 | "title": "SyntaxDetails", 268 | "type": "object", 269 | "description": "Syntax validation of an email address.", 270 | "properties": { 271 | "domain": { 272 | "type": "string", 273 | "description": "The domain name of the email, i.e. the part after the \"@\" symbol." 274 | }, 275 | "is_valid_syntax": { 276 | "type": "boolean", 277 | "description": "Is the address syntactically valid?" 278 | }, 279 | "username": { 280 | "type": "string", 281 | "description": "The username of the email, i.e. the part before the \"@\" symbol." 282 | } 283 | }, 284 | "required": ["domain", "is_valid_syntax", "username"] 285 | }, 286 | "Reachable": { 287 | "type": "string", 288 | "title": "Reachable", 289 | "enum": ["invalid", "unknown", "safe", "risky"], 290 | "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." 291 | }, 292 | "CheckEmailInput": { 293 | "title": "CheckEmailInput", 294 | "type": "object", 295 | "description": "Input containing all parameters necessary for an email verification.", 296 | "properties": { 297 | "from_email": { 298 | "type": "string", 299 | "description": "In the SMTP connection, the FROM email address." 300 | }, 301 | "to_email": { 302 | "type": "string", 303 | "description": "The email address to check." 304 | }, 305 | "hello_name": { 306 | "type": "string", 307 | "description": "In the SMTP connection, the EHLO hostname." 308 | }, 309 | "proxy": { 310 | "$ref": "#/components/schemas/CheckEmailInputProxy" 311 | } 312 | }, 313 | "required": ["to_email"] 314 | }, 315 | "CheckEmailInputProxy": { 316 | "title": "CheckEmailInputProxy", 317 | "type": "object", 318 | "x-examples": { 319 | "example-1": { 320 | "value": { 321 | "host": "my-proxy.io", 322 | "port": 1080 323 | } 324 | } 325 | }, 326 | "properties": { 327 | "host": { 328 | "type": "string", 329 | "description": "The proxy host." 330 | }, 331 | "port": { 332 | "type": "integer", 333 | "description": "The proxy port." 334 | } 335 | }, 336 | "required": ["host", "port"] 337 | } 338 | }, 339 | "securitySchemes": { 340 | "Authorization": { 341 | "name": "Authorization", 342 | "type": "apiKey", 343 | "in": "header", 344 | "description": "A Reacher API key is required for all requests. Sign up on https://reacher.email to get your personal API key." 345 | } 346 | } 347 | } 348 | } 349 | -------------------------------------------------------------------------------- /sqlx-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "db": "PostgreSQL", 3 | "1039a6d3d732a86b9b3b2e19e6c8e3c857125d1c4cf916ac32789bfd0176b6b5": { 4 | "describe": { 5 | "columns": [ 6 | { 7 | "name": "result", 8 | "ordinal": 0, 9 | "type_info": "Jsonb" 10 | } 11 | ], 12 | "nullable": [ 13 | true 14 | ], 15 | "parameters": { 16 | "Left": [ 17 | "Int4", 18 | "Int8", 19 | "Int8" 20 | ] 21 | } 22 | }, 23 | "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" 24 | }, 25 | "13862fe23ea729215fb1cfee3aadc14dfa9373dc8137c4f1da199e3ae66efd50": { 26 | "describe": { 27 | "columns": [ 28 | { 29 | "name": "total_processed", 30 | "ordinal": 0, 31 | "type_info": "Int8" 32 | }, 33 | { 34 | "name": "safe_count", 35 | "ordinal": 1, 36 | "type_info": "Int8" 37 | }, 38 | { 39 | "name": "risky_count", 40 | "ordinal": 2, 41 | "type_info": "Int8" 42 | }, 43 | { 44 | "name": "invalid_count", 45 | "ordinal": 3, 46 | "type_info": "Int8" 47 | }, 48 | { 49 | "name": "unknown_count", 50 | "ordinal": 4, 51 | "type_info": "Int8" 52 | }, 53 | { 54 | "name": "finished_at", 55 | "ordinal": 5, 56 | "type_info": "Timestamptz" 57 | } 58 | ], 59 | "nullable": [ 60 | null, 61 | null, 62 | null, 63 | null, 64 | null, 65 | null 66 | ], 67 | "parameters": { 68 | "Left": [ 69 | "Int4" 70 | ] 71 | } 72 | }, 73 | "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" 74 | }, 75 | "1a964da4784832e5f631f2c2e727382532c86c7e66e46254d72ef0af03021975": { 76 | "describe": { 77 | "columns": [], 78 | "nullable": [], 79 | "parameters": { 80 | "Left": [ 81 | "Int4", 82 | "Jsonb" 83 | ] 84 | } 85 | }, 86 | "query": "\n\t\t\tINSERT INTO email_results (job_id, result)\n\t\t\tVALUES ($1, $2)\n\t\t\t" 87 | }, 88 | "47af0157fa867e147e49d80b121b1881df93a6619434a1fd1fc9a58315b4044b": { 89 | "describe": { 90 | "columns": [ 91 | { 92 | "name": "id", 93 | "ordinal": 0, 94 | "type_info": "Int4" 95 | }, 96 | { 97 | "name": "created_at", 98 | "ordinal": 1, 99 | "type_info": "Timestamptz" 100 | }, 101 | { 102 | "name": "total_records", 103 | "ordinal": 2, 104 | "type_info": "Int4" 105 | } 106 | ], 107 | "nullable": [ 108 | false, 109 | false, 110 | false 111 | ], 112 | "parameters": { 113 | "Left": [ 114 | "Int4" 115 | ] 116 | } 117 | }, 118 | "query": "\n\t\tSELECT id, created_at, total_records FROM bulk_jobs\n\t\tWHERE id = $1\n\t\tLIMIT 1\n\t\t" 119 | }, 120 | "981f650b6c663feeae8a93e7ecf86326e7a5e6d5c8fd03c03565d86982d0381a": { 121 | "describe": { 122 | "columns": [ 123 | { 124 | "name": "id", 125 | "ordinal": 0, 126 | "type_info": "Int4" 127 | } 128 | ], 129 | "nullable": [ 130 | false 131 | ], 132 | "parameters": { 133 | "Left": [ 134 | "Int4" 135 | ] 136 | } 137 | }, 138 | "query": "\n\t\tINSERT INTO bulk_jobs (total_records)\n\t\tVALUES ($1)\n\t\tRETURNING id\n\t\t" 139 | }, 140 | "ac5e197ca20a1393e4ea45248d5e702c0edbbf57624f2bb416f0fd0401a44dcf": { 141 | "describe": { 142 | "columns": [ 143 | { 144 | "name": "total_records", 145 | "ordinal": 0, 146 | "type_info": "Int4" 147 | } 148 | ], 149 | "nullable": [ 150 | false 151 | ], 152 | "parameters": { 153 | "Left": [ 154 | "Int4" 155 | ] 156 | } 157 | }, 158 | "query": "SELECT total_records FROM bulk_jobs WHERE id = $1;" 159 | }, 160 | "f58d4d05a6ab4c1ffda39396df4c403f7588266ae8d954985fc1eda9751febcc": { 161 | "describe": { 162 | "columns": [ 163 | { 164 | "name": "count", 165 | "ordinal": 0, 166 | "type_info": "Int8" 167 | } 168 | ], 169 | "nullable": [ 170 | null 171 | ], 172 | "parameters": { 173 | "Left": [ 174 | "Int4" 175 | ] 176 | } 177 | }, 178 | "query": "SELECT COUNT(*) FROM email_results WHERE job_id = $1;" 179 | } 180 | } -------------------------------------------------------------------------------- /src/check.rs: -------------------------------------------------------------------------------- 1 | // Reacher - Email Verification 2 | // Copyright (C) 2018-2022 Reacher 3 | 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published 6 | // by the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | //! This file contains shared logic for checking one email. 18 | 19 | use super::sentry_util; 20 | use check_if_email_exists::{check_email as ciee_check_email, CheckEmailInput, CheckEmailOutput}; 21 | use std::time::Instant; 22 | 23 | /// Timeout after which we drop the `check-if-email-exists` check. We run the 24 | /// checks twice (to avoid greylisting), so each verification takes 20s max. 25 | pub const SMTP_TIMEOUT: u64 = 10; 26 | 27 | /// Same as `check-if-email-exists`'s check email, but adds some additional 28 | /// logging and error handling, and also only handles 1 email. 29 | /// 30 | /// # Panics 31 | /// 32 | /// If more than 1 email is passed inside input, then this function panics. 33 | pub async fn check_email(input: &CheckEmailInput) -> CheckEmailOutput { 34 | // Run `ciee_check_email` with retries if necessary. Also measure the 35 | // verification time. 36 | let now = Instant::now(); 37 | 38 | assert!( 39 | input.to_emails.len() == 1, 40 | "We currently hardcode the BATCH_SIZE to 1. qed." 41 | ); 42 | 43 | let res = ciee_check_email(input) 44 | .await 45 | .pop() 46 | .expect("Input only has one email, so does output. qed."); 47 | 48 | // Log on Sentry the `is_reachable` field. 49 | // We should definitely log this somewhere else than Sentry. 50 | // TODO https://github.com/reacherhq/backend/issues/207 51 | sentry_util::metrics( 52 | format!("is_reachable={:?}", res.is_reachable), 53 | now.elapsed().as_millis(), 54 | res.syntax.domain.as_ref(), 55 | ); 56 | 57 | sentry_util::log_unknown_errors(&res); 58 | 59 | res 60 | } 61 | -------------------------------------------------------------------------------- /src/errors.rs: -------------------------------------------------------------------------------- 1 | // Reacher - Email Verification 2 | // Copyright (C) 2018-2022 Reacher 3 | 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published 6 | // by the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | //! Describe a common response error to be used by all routes, should an error 18 | //! happen. 19 | 20 | use serde::Serialize; 21 | use warp::{http, reject}; 22 | 23 | /// Struct describing an error response. 24 | #[derive(Serialize, Debug)] 25 | pub struct ReacherResponseError { 26 | #[serde(skip)] 27 | code: http::StatusCode, 28 | message: String, 29 | } 30 | 31 | impl reject::Reject for ReacherResponseError {} 32 | 33 | /// This function receives a `Rejection` and tries to return a custom value, 34 | /// otherwise simply passes the rejection along. 35 | pub async fn handle_rejection(err: warp::Rejection) -> Result { 36 | if let Some(err) = err.find::() { 37 | Ok((warp::reply::with_status(warp::reply::json(err), err.code),)) 38 | } else { 39 | Err(err) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Reacher - Email Verification 2 | // Copyright (C) 2018-2022 Reacher 3 | 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published 6 | // by the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pub mod check; 18 | mod errors; 19 | pub mod routes; 20 | pub mod sentry_util; 21 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | // Reacher - Email Verification 2 | // Copyright (C) 2018-2022 Reacher 3 | 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published 6 | // by the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | //! Main entry point of the `reacher_backend` binary. It has two `main` 18 | //! functions, depending on whether the `bulk` feature is enabled or not. 19 | 20 | use dotenv::dotenv; 21 | use reacher_backend::routes::{bulk::email_verification_task, create_routes}; 22 | use reacher_backend::sentry_util::{setup_sentry, CARGO_PKG_VERSION}; 23 | use sqlx::{postgres::PgPoolOptions, Pool, Postgres}; 24 | use sqlxmq::{JobRegistry, OwnedHandle}; 25 | use std::{env, net::IpAddr}; 26 | use warp::Filter; 27 | 28 | /// Run a HTTP server using warp with bulk endpoints. 29 | #[tokio::main] 30 | async fn main() -> Result<(), Box> { 31 | init_logger(); 32 | 33 | // Setup sentry bug tracking. 34 | let _guard = setup_sentry(); 35 | 36 | let is_bulk_enabled = env::var("RCH_ENABLE_BULK").unwrap_or_else(|_| "0".into()) == "1"; 37 | if is_bulk_enabled { 38 | log::info!(target: "reacher", "Bulk endpoints enabled."); 39 | let pool = create_db().await?; 40 | let _registry = create_job_registry(&pool).await?; 41 | let routes = create_routes(Some(pool)); 42 | run_warp_server(routes).await?; 43 | } else { 44 | let routes = create_routes(None); 45 | run_warp_server(routes).await?; 46 | } 47 | 48 | Ok(()) 49 | } 50 | 51 | fn init_logger() { 52 | // Read from .env file if present. 53 | let _ = dotenv(); 54 | env_logger::init(); 55 | log::info!(target: "reacher", "Running Reacher v{}", CARGO_PKG_VERSION); 56 | } 57 | 58 | /// Create a DB pool. 59 | pub async fn create_db() -> Result, sqlx::Error> { 60 | let pg_conn = 61 | env::var("DATABASE_URL").expect("Environment variable DATABASE_URL should be set"); 62 | let pg_max_conn = env::var("RCH_DATABASE_MAX_CONNECTIONS").map_or(5, |var| { 63 | var.parse::() 64 | .expect("Environment variable RCH_DATABASE_MAX_CONNECTIONS should parse to u32") 65 | }); 66 | 67 | // create connection pool with database 68 | // connection pool internally the shared db connection 69 | // with arc so it can safely be cloned and shared across threads 70 | let pool = PgPoolOptions::new() 71 | .max_connections(pg_max_conn) 72 | .connect(pg_conn.as_str()) 73 | .await?; 74 | 75 | sqlx::migrate!("./migrations").run(&pool).await?; 76 | 77 | Ok(pool) 78 | } 79 | 80 | /// Create a job registry with one task: the email verification task. 81 | async fn create_job_registry(pool: &Pool) -> Result { 82 | let min_task_conc = env::var("RCH_MINIMUM_TASK_CONCURRENCY").map_or(10, |var| { 83 | var.parse::() 84 | .expect("Environment variable RCH_MINIMUM_TASK_CONCURRENCY should parse to usize") 85 | }); 86 | let max_conc_task_fetch = env::var("RCH_MAXIMUM_CONCURRENT_TASK_FETCH").map_or(20, |var| { 87 | var.parse::() 88 | .expect("Environment variable RCH_MAXIMUM_CONCURRENT_TASK_FETCH should parse to usize") 89 | }); 90 | 91 | // registry needs to be given list of jobs it can accept 92 | let registry = JobRegistry::new(&[email_verification_task]); 93 | 94 | // create runner for the message queue associated 95 | // with this job registry 96 | let registry = registry 97 | // Create a job runner using the connection pool. 98 | .runner(pool) 99 | // Here is where you can configure the job runner 100 | // Aim to keep 10-20 jobs running at a time. 101 | .set_concurrency(min_task_conc, max_conc_task_fetch) 102 | // Start the job runner in the background. 103 | .run() 104 | .await?; 105 | 106 | Ok(registry) 107 | } 108 | 109 | async fn run_warp_server( 110 | routes: impl Filter 111 | + Clone 112 | + Send 113 | + Sync 114 | + 'static, 115 | ) -> Result<(), Box> { 116 | let host = env::var("RCH_HTTP_HOST") 117 | .unwrap_or_else(|_| "127.0.0.1".into()) 118 | .parse::() 119 | .expect("Environment variable RCH_HTTP_HOST is malformed."); 120 | let port = env::var("PORT") 121 | .map(|port| { 122 | port.parse::() 123 | .expect("Environment variable PORT is malformed.") 124 | }) 125 | .unwrap_or(8080); 126 | log::info!(target: "reacher", "Server is listening on {}:{}.", host, port); 127 | 128 | warp::serve(routes).run((host, port)).await; 129 | 130 | Ok(()) 131 | } 132 | -------------------------------------------------------------------------------- /src/routes/bulk/db.rs: -------------------------------------------------------------------------------- 1 | // Reacher - Email Verification 2 | // Copyright (C) 2018-2022 Reacher 3 | 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published 6 | // by the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | use sqlx::{Pool, Postgres}; 18 | use warp::Filter; 19 | 20 | /// Warp filter that extracts a Pg Pool if the option is Some, or else rejects 21 | /// with a 404. 22 | pub fn with_db( 23 | o: Option>, 24 | ) -> impl Filter,), Error = warp::Rejection> + Clone { 25 | warp::any().and_then(move || { 26 | let o = o.clone(); // Still not 100% sure why I need to clone here... 27 | async move { 28 | if let Some(conn_pool) = o { 29 | Ok(conn_pool) 30 | } else { 31 | Err(warp::reject::not_found()) 32 | } 33 | } 34 | }) 35 | } 36 | -------------------------------------------------------------------------------- /src/routes/bulk/error.rs: -------------------------------------------------------------------------------- 1 | // Reacher - Email Verification 2 | // Copyright (C) 2018-2022 Reacher 3 | 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published 6 | // by the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | use warp::reject; 18 | 19 | #[derive(Debug)] 20 | pub enum CsvError { 21 | CsvLib(csv::Error), 22 | CsvLibWriter(Box>>>), 23 | Parse(&'static str), 24 | } 25 | 26 | /// Catch all error struct for the bulk endpoints 27 | #[derive(Debug)] 28 | pub enum BulkError { 29 | EmptyInput, 30 | JobInProgress, 31 | Db(sqlx::Error), 32 | Csv(CsvError), 33 | Json(serde_json::Error), 34 | } 35 | 36 | // Defaults to Internal server error 37 | impl reject::Reject for BulkError {} 38 | 39 | // wrap sql errors as db errors for reacher 40 | impl From for BulkError { 41 | fn from(e: sqlx::Error) -> Self { 42 | BulkError::Db(e) 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/routes/bulk/get.rs: -------------------------------------------------------------------------------- 1 | // Reacher - Email Verification 2 | // Copyright (C) 2018-2022 Reacher 3 | 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published 6 | // by the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | //! This file implements the `GET /bulk/{id}` endpoint. 18 | 19 | use super::{db::with_db, error::BulkError}; 20 | use serde::Serialize; 21 | use sqlx::types::chrono::{DateTime, Utc}; 22 | use sqlx::{Pool, Postgres}; 23 | use warp::Filter; 24 | 25 | /// NOTE: Type conversions from postgres to rust types 26 | /// are according to the table given by 27 | /// [sqlx here](https://docs.rs/sqlx/latest/sqlx/postgres/types/index.html) 28 | #[derive(Debug, Serialize, PartialEq, Eq)] 29 | enum ValidStatus { 30 | Running, 31 | Completed, 32 | } 33 | 34 | /// Job record stores the information about a submitted job 35 | /// 36 | /// `job_status` field is an update on read field. It's 37 | /// status will be derived from counting number of 38 | /// completed email verification tasks. It will be updated 39 | /// with the most recent status of the job. 40 | #[derive(sqlx::FromRow, Debug, Serialize)] 41 | struct JobRecord { 42 | id: i32, 43 | created_at: DateTime, 44 | total_records: i32, 45 | } 46 | 47 | /// Summary of a bulk verification job status 48 | #[derive(Debug, Serialize)] 49 | struct JobStatusSummary { 50 | total_safe: i32, 51 | total_risky: i32, 52 | total_invalid: i32, 53 | total_unknown: i32, 54 | } 55 | 56 | /// Complete information about a bulk verification job 57 | #[derive(Debug, Serialize)] 58 | struct JobStatusResponseBody { 59 | job_id: i32, 60 | created_at: DateTime, 61 | finished_at: Option>, 62 | total_records: i32, 63 | total_processed: i32, 64 | summary: JobStatusSummary, 65 | job_status: ValidStatus, 66 | } 67 | 68 | async fn job_status( 69 | job_id: i32, 70 | conn_pool: Pool, 71 | ) -> Result { 72 | let job_rec = sqlx::query_as!( 73 | JobRecord, 74 | r#" 75 | SELECT id, created_at, total_records FROM bulk_jobs 76 | WHERE id = $1 77 | LIMIT 1 78 | "#, 79 | job_id 80 | ) 81 | .fetch_one(&conn_pool) 82 | .await 83 | .map_err(|e| { 84 | log::error!( 85 | target: "reacher", 86 | "Failed to get job record for [job={}] with [error={}]", 87 | job_id, 88 | e 89 | ); 90 | BulkError::from(e) 91 | })?; 92 | 93 | let agg_info = sqlx::query!( 94 | r#" 95 | SELECT 96 | COUNT(*) as total_processed, 97 | COUNT(CASE WHEN result ->> 'is_reachable' LIKE 'safe' THEN 1 END) as safe_count, 98 | COUNT(CASE WHEN result ->> 'is_reachable' LIKE 'risky' THEN 1 END) as risky_count, 99 | COUNT(CASE WHEN result ->> 'is_reachable' LIKE 'invalid' THEN 1 END) as invalid_count, 100 | COUNT(CASE WHEN result ->> 'is_reachable' LIKE 'unknown' THEN 1 END) as unknown_count, 101 | (SELECT created_at FROM email_results WHERE job_id = $1 ORDER BY created_at DESC LIMIT 1) as finished_at 102 | FROM email_results 103 | WHERE job_id = $1 104 | "#, 105 | job_id 106 | ) 107 | .fetch_one(&conn_pool) 108 | .await 109 | .map_err(|e| { 110 | log::error!( 111 | target: "reacher", 112 | "Failed to get aggregate info for [job={}] with [error={}]", 113 | job_id, 114 | e 115 | ); 116 | BulkError::from(e) 117 | })?; 118 | 119 | let (job_status, finished_at) = if (agg_info 120 | .total_processed 121 | .expect("sql COUNT() returns an int. qed.") as i32) 122 | < job_rec.total_records 123 | { 124 | (ValidStatus::Running, None) 125 | } else { 126 | ( 127 | ValidStatus::Completed, 128 | Some( 129 | agg_info 130 | .finished_at 131 | .expect("always at least one task in the job. qed."), 132 | ), 133 | ) 134 | }; 135 | 136 | Ok(warp::reply::json(&JobStatusResponseBody { 137 | job_id: job_rec.id, 138 | created_at: job_rec.created_at, 139 | finished_at, 140 | total_records: job_rec.total_records, 141 | total_processed: agg_info 142 | .total_processed 143 | .expect("sql COUNT returns an int. qed.") as i32, 144 | summary: JobStatusSummary { 145 | total_safe: agg_info.safe_count.expect("sql COUNT returns an int. qed.") as i32, 146 | total_risky: agg_info 147 | .risky_count 148 | .expect("sql COUNT returns an int. qed.") as i32, 149 | total_invalid: agg_info 150 | .invalid_count 151 | .expect("sql COUNT returns an int. qed.") as i32, 152 | total_unknown: agg_info 153 | .unknown_count 154 | .expect("sql COUNT returns an int. qed.") as i32, 155 | }, 156 | job_status, 157 | })) 158 | } 159 | 160 | pub fn get_bulk_job_status( 161 | o: Option>, 162 | ) -> impl Filter + Clone { 163 | warp::path!("v0" / "bulk" / i32) 164 | .and(warp::get()) 165 | .and(with_db(o)) 166 | .and_then(job_status) 167 | // View access logs by setting `RUST_LOG=reacher`. 168 | .with(warp::log("reacher")) 169 | } 170 | -------------------------------------------------------------------------------- /src/routes/bulk/mod.rs: -------------------------------------------------------------------------------- 1 | // Reacher - Email Verification 2 | // Copyright (C) 2018-2022 Reacher 3 | 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published 6 | // by the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | mod db; 18 | mod error; 19 | pub mod get; 20 | pub mod post; 21 | pub mod results; 22 | mod task; 23 | 24 | pub use task::email_verification_task; 25 | -------------------------------------------------------------------------------- /src/routes/bulk/post.rs: -------------------------------------------------------------------------------- 1 | // Reacher - Email Verification 2 | // Copyright (C) 2018-2022 Reacher 3 | 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published 6 | // by the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | //! This file implements the `POST /bulk` endpoint. 18 | 19 | use super::{ 20 | db::with_db, 21 | error::BulkError, 22 | task::{submit_job, TaskInput}, 23 | }; 24 | use check_if_email_exists::CheckEmailInputProxy; 25 | use serde::{Deserialize, Serialize}; 26 | use sqlx::{Pool, Postgres}; 27 | use std::cmp::min; 28 | use warp::Filter; 29 | 30 | // this configures the number of emails passed to every task 31 | // this can be configured but will require changes in the 32 | // in the `crate::check::check_email` function which assumes a task can have 33 | // only one email. This will also require changing the 34 | // email_verification_task itself to handle multiple 35 | // outputs and commit them to the database. 36 | const EMAIL_TASK_BATCH_SIZE: usize = 1; 37 | 38 | /// Endpoint request body. 39 | #[derive(Clone, Debug, Deserialize, Serialize)] 40 | struct CreateBulkRequestBody { 41 | input_type: String, 42 | input: Vec, 43 | proxy: Option, 44 | hello_name: Option, 45 | from_email: Option, 46 | smtp_ports: Option>, 47 | } 48 | 49 | struct CreateBulkRequestBodyIterator { 50 | body: CreateBulkRequestBody, 51 | index: usize, 52 | batch_size: usize, 53 | } 54 | 55 | impl IntoIterator for CreateBulkRequestBody { 56 | type Item = TaskInput; 57 | type IntoIter = CreateBulkRequestBodyIterator; 58 | 59 | fn into_iter(self) -> Self::IntoIter { 60 | CreateBulkRequestBodyIterator { 61 | body: self, 62 | index: 0, 63 | batch_size: EMAIL_TASK_BATCH_SIZE, 64 | } 65 | } 66 | } 67 | 68 | impl Iterator for CreateBulkRequestBodyIterator { 69 | type Item = TaskInput; 70 | 71 | fn next(&mut self) -> Option { 72 | if self.index < self.body.input.len() { 73 | let bounded_index = min(self.index + self.batch_size, self.body.input.len()); 74 | let to_emails = self.body.input[self.index..bounded_index].to_vec(); 75 | let item = TaskInput { 76 | to_emails, 77 | smtp_ports: self.body.smtp_ports.clone().unwrap_or_else(|| vec![25]), 78 | proxy: self.body.proxy.clone(), 79 | hello_name: self.body.hello_name.clone(), 80 | from_email: self.body.from_email.clone(), 81 | }; 82 | 83 | self.index = bounded_index; 84 | Some(item) 85 | } else { 86 | None 87 | } 88 | } 89 | } 90 | 91 | /// Endpoint response body. 92 | #[derive(Clone, Debug, Deserialize, Serialize)] 93 | struct CreateBulkResponseBody { 94 | job_id: i32, 95 | } 96 | 97 | /// handles input, creates db entry for job and tasks for verification 98 | async fn create_bulk_request( 99 | conn_pool: Pool, 100 | body: CreateBulkRequestBody, 101 | ) -> Result { 102 | if body.input.is_empty() { 103 | return Err(BulkError::EmptyInput.into()); 104 | } 105 | 106 | // create job entry 107 | let rec = sqlx::query!( 108 | r#" 109 | INSERT INTO bulk_jobs (total_records) 110 | VALUES ($1) 111 | RETURNING id 112 | "#, 113 | body.input.len() as i32 114 | ) 115 | .fetch_one(&conn_pool) 116 | .await 117 | .map_err(|e| { 118 | log::error!( 119 | target: "reacher", 120 | "Failed to create job record for [body={:?}] with [error={}]", 121 | &body, 122 | e 123 | ); 124 | BulkError::from(e) 125 | })?; 126 | 127 | for task_input in body.into_iter() { 128 | let task_uuid = submit_job(&conn_pool, rec.id, task_input).await?; 129 | 130 | log::debug!( 131 | target: "reacher", 132 | "Submitted task to sqlxmq for [job={}] with [uuid={}]", 133 | rec.id, 134 | task_uuid 135 | ); 136 | } 137 | 138 | Ok(warp::reply::json(&CreateBulkResponseBody { 139 | job_id: rec.id, 140 | })) 141 | } 142 | 143 | /// Create the `POST /bulk` endpoint. 144 | /// The endpoint accepts list of email address and creates 145 | /// a new job to check them. 146 | pub fn create_bulk_job( 147 | o: Option>, 148 | ) -> impl Filter + Clone { 149 | warp::path!("v0" / "bulk") 150 | .and(warp::post()) 151 | .and(with_db(o)) 152 | // When accepting a body, we want a JSON body (and to reject huge 153 | // payloads)... 154 | // TODO: Configure max size limit for a bulk job 155 | .and(warp::body::content_length_limit(1024 * 16)) 156 | .and(warp::body::json()) 157 | .and_then(create_bulk_request) 158 | // View access logs by setting `RUST_LOG=reacher`. 159 | .with(warp::log("reacher")) 160 | } 161 | -------------------------------------------------------------------------------- /src/routes/bulk/results.rs: -------------------------------------------------------------------------------- 1 | // Reacher - Email Verification 2 | // Copyright (C) 2018-2022 Reacher 3 | 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published 6 | // by the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | //! This file implements the /bulk/{id}/results endpoints. 18 | 19 | use super::{ 20 | db::with_db, 21 | error::{BulkError, CsvError}, 22 | }; 23 | use csv::WriterBuilder; 24 | use serde::{Deserialize, Serialize}; 25 | use sqlx::{Executor, Pool, Postgres, Row}; 26 | use std::convert::{TryFrom, TryInto}; 27 | use warp::Filter; 28 | 29 | /// Defines the download format, passed in as a query param. 30 | #[derive(Serialize, Deserialize)] 31 | #[serde(rename_all = "lowercase")] 32 | enum JobResultResponseFormat { 33 | Json, 34 | Csv, 35 | } 36 | 37 | // limit and offset are optional in the request 38 | // if they are unspecified their default values 39 | // are 50 and 0 respectively 40 | #[derive(Serialize, Deserialize)] 41 | struct JobResultRequest { 42 | format: Option, 43 | limit: Option, 44 | offset: Option, 45 | } 46 | 47 | #[derive(Serialize, Deserialize)] 48 | struct JobResultJsonResponse { 49 | results: Vec, 50 | } 51 | 52 | /// Wrapper for serde json value to convert 53 | /// into a csv response 54 | #[derive(Debug)] 55 | struct CsvWrapper(serde_json::Value); 56 | 57 | /// Simplified output of `CheckEmailOutput` struct 58 | /// for csv fields. 59 | #[derive(Debug, Serialize)] 60 | struct JobResultCsvResponse { 61 | input: String, 62 | is_reachable: String, 63 | #[serde(rename = "misc.is_disposable")] 64 | misc_is_disposable: bool, 65 | #[serde(rename = "misc.is_role_account")] 66 | misc_is_role_account: bool, 67 | #[serde(rename = "mx.accepts_mail")] 68 | mx_accepts_mail: bool, 69 | #[serde(rename = "smtp.can_connect")] 70 | smtp_can_connect: bool, 71 | #[serde(rename = "smtp.has_full_inbox")] 72 | smtp_has_full_inbox: bool, 73 | #[serde(rename = "smtp.is_catch_all")] 74 | smtp_is_catch_all: bool, 75 | #[serde(rename = "smtp.is_deliverable")] 76 | smtp_is_deliverable: bool, 77 | #[serde(rename = "smtp.is_disabled")] 78 | smtp_is_disabled: bool, 79 | #[serde(rename = "syntax.is_valid_syntax")] 80 | syntax_is_valid_syntax: bool, 81 | #[serde(rename = "syntax.domain")] 82 | syntax_domain: String, 83 | #[serde(rename = "syntax.username")] 84 | syntax_username: String, 85 | error: Option, 86 | } 87 | 88 | /// Convert csv wrapper to csv response 89 | /// Performs multiple allocations for string fields 90 | /// throw error if field is missing 91 | impl TryFrom for JobResultCsvResponse { 92 | type Error = &'static str; 93 | 94 | fn try_from(value: CsvWrapper) -> Result { 95 | let mut input: String = String::default(); 96 | let mut is_reachable: String = String::default(); 97 | let mut misc_is_disposable: bool = false; 98 | let mut misc_is_role_account: bool = false; 99 | let mut mx_accepts_mail: bool = false; 100 | let mut smtp_can_connect: bool = false; 101 | let mut smtp_has_full_inbox: bool = false; 102 | let mut smtp_is_catch_all: bool = false; 103 | let mut smtp_is_deliverable: bool = false; 104 | let mut smtp_is_disabled: bool = false; 105 | let mut syntax_is_valid_syntax: bool = false; 106 | let mut syntax_domain: String = String::default(); 107 | let mut syntax_username: String = String::default(); 108 | let mut error: Option = None; 109 | 110 | let top_level = value 111 | .0 112 | .as_object() 113 | .ok_or("Failed to find top level object")?; 114 | for (key, val) in top_level.keys().zip(top_level.values()) { 115 | match key.as_str() { 116 | "input" => input = val.as_str().ok_or("input should be a string")?.to_string(), 117 | "is_reachable" => { 118 | is_reachable = val 119 | .as_str() 120 | .ok_or("is_reachable should be a string")? 121 | .to_string() 122 | } 123 | "misc" => { 124 | let misc_obj = val.as_object().ok_or("misc field should be an object")?; 125 | for (key, val) in misc_obj.keys().zip(misc_obj.values()) { 126 | match key.as_str() { 127 | "error" => error = Some(val.to_string()), 128 | "is_disposable" => { 129 | misc_is_disposable = 130 | val.as_bool().ok_or("is_disposable should be a boolean")? 131 | } 132 | "is_role_account" => { 133 | misc_is_role_account = 134 | val.as_bool().ok_or("is_role_account should be a boolean")? 135 | } 136 | _ => {} 137 | } 138 | } 139 | } 140 | "mx" => { 141 | let mx_obj = val.as_object().ok_or("mx field should be an object")?; 142 | for (key, val) in mx_obj.keys().zip(mx_obj.values()) { 143 | match key.as_str() { 144 | "error" => error = Some(val.to_string()), 145 | "accepts_email" => { 146 | mx_accepts_mail = 147 | val.as_bool().ok_or("accepts_email should be a boolean")? 148 | } 149 | _ => {} 150 | } 151 | } 152 | } 153 | "smtp" => { 154 | let smtp_obj = val.as_object().ok_or("mx field should be an object")?; 155 | for (key, val) in smtp_obj.keys().zip(smtp_obj.values()) { 156 | match key.as_str() { 157 | "error" => error = Some(val.to_string()), 158 | "can_connect_smtp" => { 159 | smtp_can_connect = val 160 | .as_bool() 161 | .ok_or("can_connect_smtp should be a boolean")? 162 | } 163 | "has_full_inbox" => { 164 | smtp_has_full_inbox = 165 | val.as_bool().ok_or("has_full_inbox should be a boolean")? 166 | } 167 | "is_catch_all" => { 168 | smtp_is_catch_all = 169 | val.as_bool().ok_or("is_catch_all should be a boolean")? 170 | } 171 | "is_deliverable" => { 172 | smtp_is_deliverable = 173 | val.as_bool().ok_or("is_deliverable should be a boolean")? 174 | } 175 | "is_disabled" => { 176 | smtp_is_disabled = 177 | val.as_bool().ok_or("is_disabled should be a boolean")? 178 | } 179 | _ => {} 180 | } 181 | } 182 | } 183 | "syntax" => { 184 | let syntax_obj = val.as_object().ok_or("syntax field should be an object")?; 185 | for (key, val) in syntax_obj.keys().zip(syntax_obj.values()) { 186 | match key.as_str() { 187 | "error" => error = Some(val.to_string()), 188 | "is_valid_syntax" => { 189 | syntax_is_valid_syntax = 190 | val.as_bool().ok_or("is_valid_syntax should be a boolean")? 191 | } 192 | "username" => { 193 | syntax_username = val 194 | .as_str() 195 | .ok_or("username should be a string")? 196 | .to_string() 197 | } 198 | "domain" => { 199 | syntax_domain = 200 | val.as_str().ok_or("domain should be a string")?.to_string() 201 | } 202 | _ => {} 203 | } 204 | } 205 | } 206 | // ignore unknown fields 207 | _ => {} 208 | } 209 | } 210 | 211 | Ok(JobResultCsvResponse { 212 | input, 213 | is_reachable, 214 | misc_is_disposable, 215 | misc_is_role_account, 216 | mx_accepts_mail, 217 | smtp_can_connect, 218 | smtp_has_full_inbox, 219 | smtp_is_catch_all, 220 | smtp_is_deliverable, 221 | smtp_is_disabled, 222 | syntax_domain, 223 | syntax_is_valid_syntax, 224 | syntax_username, 225 | error, 226 | }) 227 | } 228 | } 229 | 230 | async fn job_result( 231 | job_id: i32, 232 | conn_pool: Pool, 233 | req: JobResultRequest, 234 | ) -> Result { 235 | // Throw an error if the job is still running. 236 | // Is there a way to combine these 2 requests in one? 237 | let total_records = sqlx::query!( 238 | r#"SELECT total_records FROM bulk_jobs WHERE id = $1;"#, 239 | job_id 240 | ) 241 | .fetch_one(&conn_pool) 242 | .await 243 | .map_err(|e| { 244 | log::error!( 245 | target: "reacher", 246 | "Failed to fetch total_records for [job={}] with [error={}]", 247 | job_id, 248 | e 249 | ); 250 | BulkError::from(e) 251 | })? 252 | .total_records; 253 | let total_processed = sqlx::query!( 254 | r#"SELECT COUNT(*) FROM email_results WHERE job_id = $1;"#, 255 | job_id 256 | ) 257 | .fetch_one(&conn_pool) 258 | .await 259 | .map_err(|e| { 260 | log::error!( 261 | target: "reacher", 262 | "Failed to get total_processed for [job={}] with [error={}]", 263 | job_id, 264 | e 265 | ); 266 | BulkError::from(e) 267 | })? 268 | .count 269 | .unwrap_or(0); 270 | 271 | if total_processed < total_records as i64 { 272 | return Err(BulkError::JobInProgress.into()); 273 | } 274 | 275 | let format = req.format.unwrap_or(JobResultResponseFormat::Json); 276 | match format { 277 | JobResultResponseFormat::Json => { 278 | let data = job_result_json( 279 | job_id, 280 | req.limit.unwrap_or(50), 281 | req.offset.unwrap_or(0), 282 | conn_pool, 283 | ) 284 | .await?; 285 | 286 | let reply = 287 | serde_json::to_vec(&JobResultJsonResponse { results: data }).map_err(|e| { 288 | log::error!( 289 | target: "reacher", 290 | "Failed to convert json results to string for [job={}] with [error={}]", 291 | job_id, 292 | e 293 | ); 294 | 295 | BulkError::Json(e) 296 | })?; 297 | 298 | Ok(warp::reply::with_header( 299 | reply, 300 | "Content-Type", 301 | "application/json", 302 | )) 303 | } 304 | JobResultResponseFormat::Csv => { 305 | let data = job_result_csv( 306 | job_id, 307 | req.limit.unwrap_or(5000), 308 | req.offset.unwrap_or(0), 309 | conn_pool, 310 | ) 311 | .await?; 312 | 313 | Ok(warp::reply::with_header(data, "Content-Type", "text/csv")) 314 | } 315 | } 316 | } 317 | 318 | async fn job_result_json( 319 | job_id: i32, 320 | limit: u64, 321 | offset: u64, 322 | conn_pool: Pool, 323 | ) -> Result, warp::Rejection> { 324 | let query = sqlx::query!( 325 | r#" 326 | SELECT result FROM email_results 327 | WHERE job_id = $1 328 | ORDER BY id 329 | LIMIT $2 OFFSET $3 330 | "#, 331 | job_id, 332 | limit as i64, 333 | offset as i64 334 | ); 335 | 336 | let rows: Vec = conn_pool 337 | .fetch_all(query) 338 | .await 339 | .map_err(|e| { 340 | log::error!( 341 | target: "reacher", 342 | "Failed to get results for [job={}] [limit={}] [offset={}] with [error={}]", 343 | job_id, 344 | limit, 345 | offset, 346 | e 347 | ); 348 | 349 | BulkError::from(e) 350 | })? 351 | .iter() 352 | .map(|row| row.get("result")) 353 | .collect(); 354 | 355 | Ok(rows) 356 | } 357 | 358 | async fn job_result_csv( 359 | job_id: i32, 360 | limit: u64, 361 | offset: u64, 362 | conn_pool: Pool, 363 | ) -> Result, warp::Rejection> { 364 | let query = sqlx::query!( 365 | r#" 366 | SELECT result FROM email_results 367 | WHERE job_id = $1 368 | ORDER BY id 369 | LIMIT $2 OFFSET $3 370 | "#, 371 | job_id, 372 | limit as i64, 373 | offset as i64 374 | ); 375 | 376 | let mut wtr = WriterBuilder::new().has_headers(true).from_writer(vec![]); 377 | 378 | for json_value in conn_pool 379 | .fetch_all(query) 380 | .await 381 | .map_err(|e| { 382 | log::error!( 383 | target: "reacher", 384 | "Failed to get results for [job={}] with [error={}]", 385 | job_id, 386 | e 387 | ); 388 | 389 | BulkError::from(e) 390 | })? 391 | .iter() 392 | .map(|row| row.get("result")) 393 | { 394 | let result_csv: JobResultCsvResponse = CsvWrapper(json_value).try_into().map_err(|e: &'static str| { 395 | log::error!( 396 | target: "reacher", 397 | "Failed to convert json to csv output struct for [job={}] [limit={}] [offset={}] to csv with [error={}]", 398 | job_id, 399 | limit, 400 | offset, 401 | e 402 | ); 403 | 404 | BulkError::Csv(CsvError::Parse(e)) 405 | })?; 406 | wtr.serialize(result_csv).map_err(|e| { 407 | log::error!( 408 | target: "reacher", 409 | "Failed to serialize result for [job={}] [limit={}] [offset={}] to csv with [error={}]", 410 | job_id, 411 | limit, 412 | offset, 413 | e 414 | ); 415 | 416 | BulkError::Csv(CsvError::CsvLib(e)) 417 | })?; 418 | } 419 | 420 | let data = wtr.into_inner().map_err(|e| { 421 | log::error!( 422 | target: "reacher", 423 | "Failed to convert results for [job={}] [limit={}] [offset={}] to csv with [error={}]", 424 | job_id, 425 | limit, 426 | offset, 427 | e 428 | ); 429 | 430 | BulkError::Csv(CsvError::CsvLibWriter(Box::new(e))) 431 | })?; 432 | 433 | Ok(data) 434 | } 435 | 436 | pub fn get_bulk_job_result( 437 | o: Option>, 438 | ) -> impl Filter + Clone { 439 | warp::path!("v0" / "bulk" / i32 / "results") 440 | .and(warp::get()) 441 | .and(with_db(o)) 442 | .and(warp::query::()) 443 | .and_then(job_result) 444 | // View access logs by setting `RUST_LOG=reacher`. 445 | .with(warp::log("reacher")) 446 | } 447 | -------------------------------------------------------------------------------- /src/routes/bulk/task.rs: -------------------------------------------------------------------------------- 1 | // Reacher - Email Verification 2 | // Copyright (C) 2018-2022 Reacher 3 | 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published 6 | // by the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | //! This file implements the `POST /bulk` endpoint. 18 | 19 | use super::error::BulkError; 20 | use crate::check::{check_email, SMTP_TIMEOUT}; 21 | use check_if_email_exists::{CheckEmailInput, CheckEmailInputProxy, CheckEmailOutput, Reachable}; 22 | use serde::{Deserialize, Serialize}; 23 | use sqlx::{Pool, Postgres}; 24 | use sqlxmq::{job, CurrentJob}; 25 | use std::{error::Error, time::Duration}; 26 | use uuid::Uuid; 27 | 28 | #[derive(Clone, Debug, Deserialize, Serialize)] 29 | pub struct TaskInput { 30 | // fields for CheckEmailInput 31 | pub to_emails: Vec, // chunk of email from request. This always has at most `EMAIL_TASK_BATCH_SIZE` items. 32 | pub smtp_ports: Vec, // override empty smtp ports from request with default value 33 | pub proxy: Option, 34 | pub hello_name: Option, 35 | pub from_email: Option, 36 | } 37 | 38 | pub struct TaskInputIterator { 39 | body: TaskInput, 40 | index: usize, 41 | } 42 | 43 | impl IntoIterator for TaskInput { 44 | type Item = CheckEmailInput; 45 | type IntoIter = TaskInputIterator; 46 | 47 | fn into_iter(self) -> Self::IntoIter { 48 | TaskInputIterator { 49 | body: self, 50 | index: 0, 51 | } 52 | } 53 | } 54 | 55 | /// Iterate through all the `smtp_ports`. 56 | impl Iterator for TaskInputIterator { 57 | type Item = CheckEmailInput; 58 | 59 | fn next(&mut self) -> Option { 60 | if self.index < self.body.smtp_ports.len() { 61 | let mut item = CheckEmailInput::new(self.body.to_emails.clone()); 62 | 63 | if let Some(name) = &self.body.hello_name { 64 | item.set_hello_name(name.clone()); 65 | } 66 | 67 | if let Some(email) = &self.body.from_email { 68 | item.set_from_email(email.clone()); 69 | } 70 | 71 | item.set_smtp_port(self.body.smtp_ports[self.index]); 72 | 73 | if let Some(proxy) = &self.body.proxy { 74 | item.set_proxy(proxy.clone()); 75 | } 76 | 77 | item.set_smtp_timeout(Duration::from_secs(SMTP_TIMEOUT)); 78 | 79 | self.index += 1; 80 | Some(item) 81 | } else { 82 | None 83 | } 84 | } 85 | } 86 | 87 | /// Struct that's serialized into the sqlxmq own `payload_json` table. 88 | #[derive(Debug, Deserialize, Serialize)] 89 | struct TaskPayload { 90 | id: i32, 91 | input: TaskInput, 92 | } 93 | 94 | pub async fn submit_job( 95 | conn_pool: &Pool, 96 | job_id: i32, 97 | task_input: TaskInput, 98 | ) -> Result { 99 | let task_payload = TaskPayload { 100 | id: job_id, 101 | input: task_input, 102 | }; 103 | 104 | let uuid = email_verification_task 105 | .builder() 106 | .set_json(&task_payload) 107 | .map_err(|e| { 108 | log::error!( 109 | target: "reacher", 110 | "Failed to submit task with the following [input={:?}] with [error={}]", 111 | task_payload.input, 112 | e 113 | ); 114 | 115 | BulkError::Json(e) 116 | })? 117 | .spawn(conn_pool) 118 | .await 119 | .map_err(|e| { 120 | log::error!( 121 | target: "reacher", 122 | "Failed to submit task for [bulk_req={}] with [error={}]", 123 | job_id, 124 | e 125 | ); 126 | 127 | e 128 | })?; 129 | 130 | Ok(uuid) 131 | } 132 | 133 | /// Arguments to the `#[job]` attribute allow setting default task options. 134 | /// This task tries to verify the given email and inserts the results 135 | /// into the email verification db table 136 | /// NOTE: if EMAIL_TASK_BATCH_SIZE is made greater than 1 this logic 137 | /// will have to be changed to handle a vector outputs from `check_email`. 138 | /// 139 | /// Small note about namings: what sqlxmq calls a "job", we call it a "task". 140 | /// We call a "job" a user bulk request, i.e. a list of "tasks". 141 | /// Please be careful while reading code. 142 | #[job] 143 | pub async fn email_verification_task( 144 | mut current_job: CurrentJob, 145 | // Additional arguments are optional, but can be used to access context 146 | // provided via [`JobRegistry::set_context`]. 147 | ) -> Result<(), Box> { 148 | let task_payload: TaskPayload = current_job.json()?.ok_or("Got empty task.")?; 149 | let job_id = task_payload.id; 150 | 151 | let mut final_response: Option = None; 152 | 153 | for check_email_input in task_payload.input { 154 | log::debug!( 155 | target:"reacher", 156 | "Starting task [email={}] for [job={}] and [uuid={}]", 157 | check_email_input.to_emails[0], 158 | task_payload.id, 159 | current_job.id(), 160 | ); 161 | 162 | let response = check_email(&check_email_input).await; 163 | 164 | log::debug!( 165 | target:"reacher", 166 | "Got task result [email={}] for [job={}] and [uuid={}] with [is_reachable={:?}]", 167 | check_email_input.to_emails[0], 168 | task_payload.id, 169 | current_job.id(), 170 | response.is_reachable, 171 | ); 172 | 173 | let is_reachable = response.is_reachable == Reachable::Unknown; 174 | final_response = Some(response); 175 | // unsuccessful validation continue iteration with next possible smtp port 176 | if is_reachable { 177 | continue; 178 | } 179 | // successful validation attempt complete job break iteration 180 | else { 181 | break; 182 | } 183 | } 184 | 185 | // final response can only be empty if there 186 | // were no validation attempts. This can can 187 | // never occur currently 188 | if let Some(response) = final_response { 189 | // write results and terminate iteration 190 | #[allow(unused_variables)] 191 | let rec = sqlx::query!( 192 | r#" 193 | INSERT INTO email_results (job_id, result) 194 | VALUES ($1, $2) 195 | "#, 196 | job_id, 197 | serde_json::json!(response) 198 | ) 199 | // TODO: This is a simplified solution and will work when 200 | // the job queue and email results tables are in the same 201 | // database. Keeping them in separate database will require 202 | // some custom logic on the job registry side 203 | // https://github.com/Diggsey/sqlxmq/issues/4 204 | .fetch_optional(current_job.pool()) 205 | .await 206 | .map_err(|e| { 207 | log::error!( 208 | target:"reacher", 209 | "Failed to write [email={}] result to db for [job={}] and [uuid={}] with [error={}]", 210 | response.input, 211 | job_id, 212 | current_job.id(), 213 | e 214 | ); 215 | 216 | e 217 | })?; 218 | 219 | log::debug!( 220 | target:"reacher", 221 | "Wrote result for [email={}] for [job={}] and [uuid={}]", 222 | response.input, 223 | job_id, 224 | current_job.id(), 225 | ); 226 | } 227 | 228 | current_job.complete().await?; 229 | Ok(()) 230 | } 231 | -------------------------------------------------------------------------------- /src/routes/check_email/mod.rs: -------------------------------------------------------------------------------- 1 | // Reacher - Email Verification 2 | // Copyright (C) 2018-2022 Reacher 3 | 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published 6 | // by the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pub mod post; 18 | -------------------------------------------------------------------------------- /src/routes/check_email/post.rs: -------------------------------------------------------------------------------- 1 | // Reacher - Email Verification 2 | // Copyright (C) 2018-2022 Reacher 3 | 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published 6 | // by the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | //! This file implements the `POST /check_email` endpoint. 18 | 19 | use crate::check::check_email; 20 | use check_if_email_exists::{CheckEmailInput, CheckEmailInputProxy}; 21 | use serde::{Deserialize, Serialize}; 22 | use std::env; 23 | use warp::Filter; 24 | 25 | /// Endpoint request body. 26 | #[derive(Clone, Debug, Deserialize, Serialize)] 27 | pub struct EndpointRequest { 28 | from_email: Option, 29 | hello_name: Option, 30 | proxy: Option, 31 | smtp_port: Option, 32 | to_email: String, 33 | } 34 | 35 | impl From for CheckEmailInput { 36 | fn from(req: EndpointRequest) -> Self { 37 | // Create Request for check_if_email_exists from body 38 | let mut input = CheckEmailInput::new(vec![req.to_email]); 39 | input 40 | .set_from_email(req.from_email.unwrap_or_else(|| { 41 | env::var("RCH_FROM_EMAIL").unwrap_or_else(|_| "user@example.org".into()) 42 | })) 43 | .set_hello_name(req.hello_name.unwrap_or_else(|| "gmail.com".into())); 44 | 45 | if let Some(proxy_input) = req.proxy { 46 | input.set_proxy(proxy_input); 47 | } 48 | 49 | if let Some(smtp_port) = req.smtp_port { 50 | input.set_smtp_port(smtp_port); 51 | } 52 | 53 | input 54 | } 55 | } 56 | 57 | /// The main endpoint handler that implements the logic of this route. 58 | async fn handler(body: EndpointRequest) -> Result { 59 | // Run the future to check an email. 60 | Ok(warp::reply::json(&check_email(&body.into()).await)) 61 | } 62 | 63 | /// Create the `POST /check_email` endpoint. 64 | pub fn post_check_email( 65 | ) -> impl Filter + Clone { 66 | warp::path!("v0" / "check_email") 67 | .and(warp::post()) 68 | // When accepting a body, we want a JSON body (and to reject huge 69 | // payloads)... 70 | .and(warp::body::content_length_limit(1024 * 16)) 71 | .and(warp::body::json()) 72 | .and_then(handler) 73 | // View access logs by setting `RUST_LOG=reacher`. 74 | .with(warp::log("reacher")) 75 | } 76 | -------------------------------------------------------------------------------- /src/routes/mod.rs: -------------------------------------------------------------------------------- 1 | // Reacher - Email Verification 2 | // Copyright (C) 2018-2022 Reacher 3 | 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published 6 | // by the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pub mod bulk; 18 | pub mod check_email; 19 | mod version; 20 | 21 | use super::errors; 22 | use sqlx::{Pool, Postgres}; 23 | use warp::Filter; 24 | 25 | pub fn create_routes( 26 | o: Option>, 27 | ) -> impl Filter + Clone { 28 | version::get::get_version() 29 | .or(check_email::post::post_check_email()) 30 | // The 3 following routes will 404 if o is None. 31 | .or(bulk::post::create_bulk_job(o.clone())) 32 | .or(bulk::get::get_bulk_job_status(o.clone())) 33 | .or(bulk::results::get_bulk_job_result(o)) 34 | .recover(errors::handle_rejection) 35 | } 36 | -------------------------------------------------------------------------------- /src/routes/version/get.rs: -------------------------------------------------------------------------------- 1 | // Reacher - Email Verification 2 | // Copyright (C) 2018-2022 Reacher 3 | 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published 6 | // by the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | //! This file implements the `GET /version` endpoint. 18 | 19 | use crate::sentry_util::CARGO_PKG_VERSION; 20 | use serde::{Deserialize, Serialize}; 21 | use warp::Filter; 22 | 23 | /// Endpoint response body. 24 | #[derive(Clone, Debug, Deserialize, Serialize)] 25 | struct EndpointVersion { 26 | version: String, 27 | } 28 | 29 | /// Create the `GET /version` endpoint. 30 | pub fn get_version() -> impl Filter + Clone 31 | { 32 | warp::path("version").and(warp::get()).map(|| { 33 | warp::reply::json(&EndpointVersion { 34 | version: CARGO_PKG_VERSION.into(), 35 | }) 36 | }) 37 | } 38 | 39 | #[cfg(test)] 40 | mod tests { 41 | use super::get_version; 42 | use crate::sentry_util::CARGO_PKG_VERSION; 43 | use warp::http::StatusCode; 44 | use warp::test::request; 45 | 46 | #[tokio::test] 47 | async fn test_get_version() { 48 | let resp = request() 49 | .path("/version") 50 | .method("GET") 51 | .reply(&get_version()) 52 | .await; 53 | 54 | assert_eq!(resp.status(), StatusCode::OK); 55 | assert_eq!( 56 | resp.body(), 57 | format!("{{\"version\":\"{}\"}}", CARGO_PKG_VERSION).as_str() 58 | ); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/routes/version/mod.rs: -------------------------------------------------------------------------------- 1 | // Reacher - Email Verification 2 | // Copyright (C) 2018-2022 Reacher 3 | 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published 6 | // by the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pub mod get; 18 | -------------------------------------------------------------------------------- /src/sentry_util.rs: -------------------------------------------------------------------------------- 1 | // Reacher - Email Verification 2 | // Copyright (C) 2018-2022 Reacher 3 | 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published 6 | // by the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | //! Helper functions to send events to Sentry. 18 | //! 19 | //! This module also contains functions that check if the error's given by 20 | //! `check-if-email-exists` are known errors, in which case we don't log them 21 | //! to Sentry. 22 | 23 | use super::sentry_util; 24 | use async_smtp::smtp::error::Error as AsyncSmtpError; 25 | use check_if_email_exists::{smtp::SmtpError, CheckEmailOutput}; 26 | use sentry::protocol::{Event, Level, Value}; 27 | use std::io::Error as IoError; 28 | use std::{collections::BTreeMap, env}; 29 | 30 | pub const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION"); 31 | 32 | /// Setup Sentry. 33 | pub fn setup_sentry() -> sentry::ClientInitGuard { 34 | // Use an empty string if we don't have any env variable for sentry. Sentry 35 | // will just silently ignore. 36 | let sentry = sentry::init(env::var("RCH_SENTRY_DSN").unwrap_or_else(|_| "".into())); 37 | if sentry.is_enabled() { 38 | log::info!(target: "reacher", "Sentry is successfully set up.") 39 | } 40 | 41 | sentry 42 | } 43 | 44 | /// If BACKEND_NAME environment variable is set, add it to the sentry `extra` 45 | /// properties. 46 | /// For backwards compatibility, we also support HEROKU_APP_NAME env variable. 47 | fn add_backend_name(mut extra: BTreeMap) -> BTreeMap { 48 | if let Ok(n) = env::var("BACKEND_NAME") { 49 | extra.insert("BACKEND_NAME".into(), n.into()); 50 | } else if let Ok(n) = env::var("HEROKU_APP_NAME") { 51 | extra.insert("BACKEND_NAME".into(), n.into()); 52 | } 53 | 54 | extra 55 | } 56 | 57 | /// Helper function to send an Info event to Sentry. We use these events for 58 | /// analytics purposes (I know, Sentry shouldn't be used for that...). 59 | /// TODO https://github.com/reacherhq/backend/issues/207 60 | pub fn metrics(message: String, duration: u128, domain: &str) { 61 | log::info!(target: "reacher", "Sending info to Sentry: {}", message); 62 | 63 | let mut extra = BTreeMap::new(); 64 | 65 | extra.insert("duration".into(), duration.to_string().into()); 66 | extra.insert("domain".into(), domain.into()); 67 | extra = add_backend_name(extra); 68 | 69 | sentry::capture_event(Event { 70 | extra, 71 | level: Level::Info, 72 | message: Some(message), 73 | release: Some(CARGO_PKG_VERSION.into()), 74 | ..Default::default() 75 | }); 76 | } 77 | 78 | /// Helper function to send an Error event to Sentry. We redact all sensitive 79 | /// info before sending to Sentry, but removing all instances of `username`. 80 | pub fn error(message: String, result: Option<&str>, username: &str) { 81 | let redacted_message = redact(message.as_str(), username); 82 | log::debug!(target: "reacher", "Sending error to Sentry: {}", redacted_message); 83 | 84 | let mut extra = BTreeMap::new(); 85 | if let Some(result) = result { 86 | extra.insert("CheckEmailOutput".into(), redact(result, username).into()); 87 | } 88 | 89 | extra = add_backend_name(extra); 90 | 91 | sentry::capture_event(Event { 92 | extra, 93 | level: Level::Error, 94 | message: Some(redacted_message), 95 | release: Some(CARGO_PKG_VERSION.into()), 96 | ..Default::default() 97 | }); 98 | } 99 | 100 | /// Function to replace all usernames from email, and replace them with 101 | /// `***@domain.com` for privacy reasons. 102 | fn redact(input: &str, username: &str) -> String { 103 | input.replace(username, "***") 104 | } 105 | 106 | /// Check if the message contains known SMTP IO errors. 107 | fn has_smtp_io_errors(error: &IoError) -> bool { 108 | // code: 104, kind: ConnectionReset, message: "Connection reset by peer", 109 | error.raw_os_error() == Some(104) || 110 | // kind: Other, error: "incomplete", 111 | error.to_string() == "incomplete" 112 | } 113 | 114 | /// Check if the message contains known SMTP Transient errors. 115 | fn has_smtp_transient_errors(message: &[String]) -> bool { 116 | let first_line = message[0].to_lowercase(); 117 | 118 | // 4.3.2 Please try again later 119 | first_line.contains("try again") || 120 | // Temporary local problem - please try later 121 | first_line.contains("try later") 122 | } 123 | 124 | /// Checks if the output from `check-if-email-exists` has a known error, in 125 | /// which case we don't log to Sentry to avoid spamming it. 126 | pub fn log_unknown_errors(result: &CheckEmailOutput) { 127 | match (&result.misc, &result.mx, &result.smtp) { 128 | (Err(error), _, _) => { 129 | // We log misc errors. 130 | sentry_util::error( 131 | format!("{:?}", error), 132 | Some(format!("{:#?}", result).as_ref()), 133 | result.syntax.username.as_str(), 134 | ); 135 | } 136 | (_, Err(error), _) => { 137 | // We log mx errors. 138 | sentry_util::error( 139 | format!("{:?}", error), 140 | Some(format!("{:#?}", result).as_ref()), 141 | result.syntax.username.as_str(), 142 | ); 143 | } 144 | (_, _, Err(SmtpError::SmtpError(AsyncSmtpError::Transient(response)))) 145 | if has_smtp_transient_errors(&response.message) => 146 | { 147 | log::debug!(target: "reacher", "Transient error: {}", response.message[0]); 148 | } 149 | (_, _, Err(SmtpError::SmtpError(AsyncSmtpError::Io(err)))) if has_smtp_io_errors(err) => { 150 | log::debug!(target: "reacher", "Io error: {}", err); 151 | } 152 | (_, _, Err(error)) => { 153 | // If it's a SMTP error we didn't catch above, we log to 154 | // Sentry, to be able to debug them better. We don't want to 155 | // spam Sentry and log all instances of the error, hence the 156 | // `count` check. 157 | sentry_util::error( 158 | format!("{:?}", error), 159 | Some(format!("{:#?}", result).as_ref()), 160 | result.syntax.username.as_str(), 161 | ); 162 | } 163 | // If everything is ok, we just return the result. 164 | (Ok(_), Ok(_), Ok(_)) => {} 165 | } 166 | } 167 | 168 | #[cfg(test)] 169 | mod tests { 170 | use super::redact; 171 | 172 | #[test] 173 | fn test_redact() { 174 | assert_eq!("***@gmail.com", redact("someone@gmail.com", "someone")); 175 | assert_eq!( 176 | "my email is ***@gmail.com.", 177 | redact("my email is someone@gmail.com.", "someone") 178 | ); 179 | assert_eq!( 180 | "my email is ***@gmail.com., I repeat, my email is ***@gmail.com.", 181 | redact( 182 | "my email is someone@gmail.com., I repeat, my email is someone@gmail.com.", 183 | "someone" 184 | ) 185 | ); 186 | assert_eq!( 187 | "*** @ gmail . com", 188 | redact("someone @ gmail . com", "someone") 189 | ); 190 | assert_eq!("*** is here.", redact("someone is here.", "someone")); 191 | } 192 | } 193 | -------------------------------------------------------------------------------- /tests/README.md: -------------------------------------------------------------------------------- 1 | # Integration Tests 2 | 3 | Files in this folder are Reacher backend's integration tests. They need the following to work: 4 | 5 | - a working internet connection. 6 | -------------------------------------------------------------------------------- /tests/check_email.rs: -------------------------------------------------------------------------------- 1 | // Reacher - Email Verification 2 | // Copyright (C) 2018-2022 Reacher 3 | 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published 6 | // by the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | use reacher_backend::routes::{check_email::post::EndpointRequest, create_routes}; 18 | use serde_json; 19 | use warp::http::StatusCode; 20 | use warp::test::request; 21 | 22 | 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":""}}"#; 23 | const FOO_BAR_BAZ_RESPONSE: &str = r#"{"input":"foo@bar.baz","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":"foo@bar.baz","domain":"bar.baz","is_valid_syntax":true,"username":"foo"}}"#; 24 | 25 | #[tokio::test] 26 | async fn test_input_foo_bar() { 27 | let resp = request() 28 | .path("/v0/check_email") 29 | .method("POST") 30 | .json(&serde_json::from_str::(r#"{"to_email": "foo@bar"}"#).unwrap()) 31 | .reply(&create_routes(None)) 32 | .await; 33 | 34 | assert_eq!(resp.status(), StatusCode::OK); 35 | assert_eq!(resp.body(), FOO_BAR_RESPONSE); 36 | } 37 | 38 | #[tokio::test] 39 | async fn test_input_foo_bar_baz() { 40 | let resp = request() 41 | .path("/v0/check_email") 42 | .method("POST") 43 | .json(&serde_json::from_str::(r#"{"to_email": "foo@bar.baz"}"#).unwrap()) 44 | .reply(&create_routes(None)) 45 | .await; 46 | 47 | assert_eq!(resp.status(), StatusCode::OK); 48 | assert_eq!(resp.body(), FOO_BAR_BAZ_RESPONSE); 49 | } 50 | --------------------------------------------------------------------------------