forked from Txio-labs/txio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.rs
More file actions
59 lines (48 loc) · 1.98 KB
/
Copy pathdb.rs
File metadata and controls
59 lines (48 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
use mongodb::{Client, error::Error, options::ClientOptions};
pub async fn establish_connection(uri: &str) -> mongodb::error::Result<Client> {
let mut client_options = ClientOptions::parse(uri).await?;
let server_api = mongodb::options::ServerApi::builder()
.version(mongodb::options::ServerApiVersion::V1)
.build();
client_options.server_api = Some(server_api);
let client = Client::with_options(client_options)?;
Ok(client)
}
pub fn describe_connection_error(uri: &str, error: &Error) -> String {
let base = format!("Failed to connect to MongoDB. {error}");
if uri.starts_with("mongodb+srv://") && is_dns_resolution_error(error) {
let host = extract_mongo_host(uri).unwrap_or("unknown host");
return format!(
"{base} Atlas SRV lookup failed for `{host}`. \
Copy the exact connection string from MongoDB Atlas > Connect > Drivers. \
If you intended to use local Mongo for development, set MONGO_URI to \
`mongodb://localhost:27017/txio` instead of a `mongodb+srv://` URI."
);
}
if uri.starts_with("mongodb://mongodb") {
return format!(
"{base} The host `mongodb` only resolves inside the Docker Compose network. \
If you are running the API directly on your machine with `cargo run`, use \
`mongodb://localhost:27017/txio`."
);
}
base
}
fn is_dns_resolution_error(error: &Error) -> bool {
let message = error.to_string();
message.contains("DNS resolution")
|| message.contains("DnsResolve")
|| message.contains("_mongodb._tcp")
}
fn extract_mongo_host(uri: &str) -> Option<&str> {
let (_, remainder) = uri.split_once("://")?;
let without_credentials = remainder
.rsplit_once('@')
.map(|(_, value)| value)
.unwrap_or(remainder);
let authority = without_credentials
.split('/')
.next()
.unwrap_or(without_credentials);
authority.split(',').next()
}