zero_bounce/utility/
mod.rs1use std::io::Error as IOError;
2use std::io::Read;
3
4pub mod bulk_get_file;
5pub mod http_error;
6pub mod mock_constants;
7pub mod structures;
8
9pub use bulk_get_file::{format_get_file_error_message, get_file_json_indicates_error};
10
11pub const CONTENT_TYPE_JSON: &str = "application/json";
12pub const CONTENT_TYPE_STREAM: &str = "application/octet-stream";
13pub const MAX_JSON_RESPONSE_BYTES: usize = 16 * 1024 * 1024;
15pub const MAX_GETFILE_BYTES: usize = 256 * 1024 * 1024;
17
18pub(crate) fn read_limited(
21 mut reader: impl Read,
22 max_bytes: usize,
23 message: &str,
24) -> ZBResult<Vec<u8>> {
25 let mut body = Vec::new();
26 reader.by_ref().take(max_bytes as u64 + 1).read_to_end(&mut body)?;
27 if body.len() > max_bytes {
28 return Err(ZBError::explicit(message));
29 }
30 Ok(body)
31}
32
33#[cfg(test)]
34mod response_limit_tests {
35 use super::read_limited;
36 use std::io::{self, Read};
37
38 struct CountingReader {
39 remaining: usize,
40 read: usize,
41 }
42
43 impl Read for CountingReader {
44 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
45 let n = buf.len().min(self.remaining);
46 buf[..n].fill(b'x');
47 self.remaining -= n;
48 self.read += n;
49 Ok(n)
50 }
51 }
52
53 #[test]
54 fn stops_at_one_byte_past_limit() {
55 let mut source = CountingReader {
56 remaining: 10_000,
57 read: 0,
58 };
59 let error = read_limited(&mut source, 32, "too large").unwrap_err();
60 assert_eq!(error.to_string(), "too large");
61 assert_eq!(source.read, 33);
62 }
63
64 #[test]
65 fn accepts_body_at_limit() {
66 let body = read_limited(&b"exact"[..], 5, "too large").unwrap();
67 assert_eq!(body, b"exact");
68 }
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76#[non_exhaustive]
77pub enum ApiBaseUrl {
78 Default,
80 USA,
82 EU,
84}
85
86impl ApiBaseUrl {
87 pub fn as_str(&self) -> &'static str {
89 match self {
90 ApiBaseUrl::Default => "https://api.zerobounce.net/v2/",
91 ApiBaseUrl::USA => "https://api-us.zerobounce.net/v2/",
92 ApiBaseUrl::EU => "https://api-eu.zerobounce.net/v2/",
93 }
94 }
95}
96
97impl From<ApiBaseUrl> for String {
98 fn from(url: ApiBaseUrl) -> Self {
99 url.as_str().to_string()
100 }
101}
102
103impl From<&ApiBaseUrl> for String {
104 fn from(url: &ApiBaseUrl) -> Self {
105 url.as_str().to_string()
106 }
107}
108
109pub fn encode_path_segment(value: &str) -> String {
115 let mut encoded = String::with_capacity(value.len());
116 for byte in value.as_bytes() {
117 match byte {
118 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
119 encoded.push(*byte as char)
120 }
121 _ => encoded.push_str(&format!("%{:02X}", byte)),
122 }
123 }
124 encoded
125}
126
127pub const BULK_URI: &str = "https://bulkapi.zerobounce.net/v2";
128pub const LIST_EVALUATOR_URI: &str = "https://bulkapi.zerobounce.net/v2/listevaluator";
130pub const INBOX_PLACEMENT_URI: &str = "https://bulkapi.zerobounce.net/api/ipt";
131pub const ENDPOINT_CREDITS: &str = "/getcredits";
132pub const ENDPOINT_ACTIVITY_DATA: &str = "/activity";
133pub const ENDPOINT_SCORING: &str = "/scoring";
134pub const ENDPOINT_VALIDATE: &str = "/validate";
135pub const ENDPOINT_API_USAGE: &str = "/getapiusage";
136pub const ENDPOINT_BATCH_VALIDATE: &str = "/validatebatch";
137pub const ENDPOINT_FILE_SEND: &str = "/sendfile";
138pub const ENDPOINT_FILE_STATUS: &str = "/filestatus";
139pub const ENDPOINT_FILE_RESULT: &str = "/getfile";
140pub const ENDPOINT_FILE_DELETE: &str = "/deletefile";
141pub const ENDPOINT_SCORING_SEND: &str = "/scoring/sendfile";
142pub const ENDPOINT_SCORING_STATUS: &str = "/scoring/filestatus";
143pub const ENDPOINT_SCORING_RESULT: &str = "/scoring/getfile";
144pub const ENDPOINT_SCORING_DELETE: &str = "/scoring/deletefile";
145pub const ENDPOINT_EMAIL_FINDER: &str = "/guessformat";
146
147pub const S_VALID: &str = "valid";
149pub const S_INVALID: &str = "invalid";
150pub const S_CATCH_ALL: &str = "catch-all";
151pub const S_UNKNOWN: &str = "unknown";
152pub const S_SPAMTRAP: &str = "spamtrap";
153pub const S_ABUSE: &str = "abuse";
154pub const S_DO_NOT_MAIL: &str = "do_not_mail";
155
156pub const SS_ANTISPAM_SYSTEM: &str = "antispam_system";
158pub const SS_GREYLISTED: &str = "greylisted";
159pub const SS_MAIL_SERVER_TEMPORARY_ERROR: &str = "mail_server_temporary_error";
160pub const SS_FORCIBLE_DISCONNECT: &str = "forcible_disconnect";
161pub const SS_MAIL_SERVER_DID_NOT_RESPOND: &str = "mail_server_did_not_respond";
162pub const SS_TIMEOUT_EXCEEDED: &str = "timeout_exceeded";
163pub const SS_FAILED_SMTP_CONNECTION: &str = "failed_smtp_connection";
164pub const SS_MAILBOX_QUOTA_EXCEEDED: &str = "mailbox_quota_exceeded";
165pub const SS_EXCEPTION_OCCURRED: &str = "exception_occurred";
166pub const SS_POSSIBLE_TRAP: &str = "possible_trap";
167pub const SS_ROLE_BASED: &str = "role_based";
168pub const SS_GLOBAL_SUPPRESSION: &str = "global_suppression";
169pub const SS_MAILBOX_NOT_FOUND: &str = "mailbox_not_found";
170pub const SS_NO_DNS_ENTRIES: &str = "no_dns_entries";
171pub const SS_FAILED_SYNTAX_CHECK: &str = "failed_syntax_check";
172pub const SS_POSSIBLE_TYPO: &str = "possible_typo";
173pub const SS_UNROUTABLE_IP_ADDRESS: &str = "unroutable_ip_address";
174pub const SS_LEADING_PERIOD_REMOVED: &str = "leading_period_removed";
175pub const SS_DOES_NOT_ACCEPT_MAIL: &str = "does_not_accept_mail";
176pub const SS_ALIAS_ADDRESS: &str = "alias_address";
177pub const SS_ROLE_BASED_CATCH_ALL: &str = "role_based_catch_all";
178pub const SS_DISPOSABLE: &str = "disposable";
179pub const SS_TOXIC: &str = "toxic";
180pub const SS_ACCEPT_ALL: &str = "accept_all";
181pub const SS_AI_AGENT_MAILBOX: &str = "ai_agent_mailbox";
182
183#[derive(Debug)]
188#[non_exhaustive]
189pub enum ZBError {
190 ExplicitError(String),
193 ApiError { status: u16, message: String },
200 JsonError(serde_json::Error),
201 IntParseError(std::num::ParseIntError),
202 RequestError(reqwest::Error),
203 IOError(IOError),
204}
205
206pub type ZBResult<T> = Result<T, ZBError>;
207
208impl ZBError {
209 pub fn explicit(string: &str) -> ZBError {
210 ZBError::ExplicitError(string.to_string())
211 }
212
213 pub fn api(status: u16, message: impl Into<String>) -> ZBError {
214 ZBError::ApiError {
215 status,
216 message: message.into(),
217 }
218 }
219
220 pub fn status_code(&self) -> Option<u16> {
226 match self {
227 ZBError::ApiError { status, .. } => Some(*status),
228 _ => None,
229 }
230 }
231}
232
233impl std::fmt::Display for ZBError {
234 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235 match self {
236 ZBError::ExplicitError(message) => write!(formatter, "{message}"),
237 ZBError::ApiError { message, .. } => write!(formatter, "{message}"),
238 ZBError::JsonError(_) => {
239 write!(
240 formatter,
241 "ZeroBounce returned a response that is not valid JSON."
242 )
243 }
244 ZBError::IntParseError(_) => write!(
245 formatter,
246 "ZeroBounce returned a response that could not be read."
247 ),
248 ZBError::RequestError(error) => write!(formatter, "{error}"),
249 ZBError::IOError(error) => write!(formatter, "{error}"),
250 }
251 }
252}
253
254impl std::error::Error for ZBError {}
255
256fn redact_api_key(url: &mut reqwest::Url) {
262 if !url.query_pairs().any(|(key, _)| key == "api_key") {
263 return;
264 }
265 let pairs: Vec<(String, String)> = url
266 .query_pairs()
267 .map(|(key, value)| {
268 let value = if key == "api_key" {
269 "REDACTED".to_string()
270 } else {
271 value.into_owned()
272 };
273 (key.into_owned(), value)
274 })
275 .collect();
276 url.query_pairs_mut().clear().extend_pairs(pairs);
277}
278
279impl From<reqwest::Error> for ZBError {
280 fn from(mut value: reqwest::Error) -> ZBError {
281 if let Some(url) = value.url_mut() {
282 redact_api_key(url);
283 }
284 ZBError::RequestError(value)
285 }
286}
287
288impl From<serde_json::Error> for ZBError {
293 fn from(value: serde_json::Error) -> ZBError {
294 ZBError::JsonError(value)
295 }
296}
297
298impl From<IOError> for ZBError {
299 fn from(value: IOError) -> Self {
300 ZBError::IOError(value)
301 }
302}