1#[cfg(test)]
2mod test;
3
4use std::{ffi::OsString, path::PathBuf};
5
6use monger_core::Monger;
7use mongodb::{
8 options::{ClientOptions, Credential as DriverCredential, Tls, TlsOptions as DriverTlsOptions},
9 sync::Client,
10};
11use typed_builder::TypedBuilder;
12
13use crate::{
14 error::Result,
15 launch::{Launcher, Node},
16};
17
18#[derive(Debug, Clone)]
19pub enum Topology {
20 Single,
21 ReplicaSet {
22 set_name: String,
23 db_paths: Vec<PathBuf>,
24 },
25 Sharded {
26 num_mongos: u8,
27 shard_db_paths: Vec<Vec<PathBuf>>,
28 config_db_path: PathBuf,
29 },
30}
31
32#[derive(Debug)]
33pub struct Cluster {
34 pub(crate) monger: Monger,
35 pub(crate) client: Client,
36 pub(crate) client_options: ClientOptions,
37 pub(crate) topology: Topology,
38 pub(crate) tls: Option<TlsOptions>,
39 pub(crate) auth: Option<Credential>,
40 pub(crate) nodes: Vec<Node>,
41 pub(crate) cluster_id: String,
42}
43
44#[derive(Clone, Debug, TypedBuilder)]
45pub struct ClusterOptions {
46 pub topology: Topology,
47
48 pub version_id: String,
49
50 #[builder(default)]
51 pub paths: Vec<PathBuf>,
52
53 #[builder(default)]
54 pub tls: Option<TlsOptions>,
55
56 #[builder(default)]
57 pub auth: Option<Credential>,
58
59 #[builder(default)]
60 extra_mongod_args: Vec<OsString>,
61
62 #[builder(default)]
63 verbose: bool,
64
65 #[builder(default)]
66 deprecated_tls_options: bool,
67
68 #[builder(default)]
69 save_logs: bool,
70}
71
72#[derive(Debug, Clone)]
73pub struct TlsOptions {
74 pub weak_tls: bool,
75 pub allow_invalid_certificates: bool,
76 pub ca_file_path: PathBuf,
77 pub server_cert_file_path: PathBuf,
78 pub client_cert_file_path: PathBuf,
79}
80
81impl From<TlsOptions> for Tls {
82 fn from(opts: TlsOptions) -> Self {
83 DriverTlsOptions::builder()
84 .allow_invalid_certificates(opts.allow_invalid_certificates)
85 .ca_file_path(opts.ca_file_path.to_string_lossy().into_owned())
86 .cert_key_file_path(opts.server_cert_file_path.to_string_lossy().into_owned())
87 .build()
88 .into()
89 }
90}
91
92#[derive(Debug, Clone)]
93pub struct Credential {
94 pub username: String,
95 pub password: String,
96 pub key_file: PathBuf,
97}
98
99impl From<Credential> for DriverCredential {
100 fn from(credential: Credential) -> Self {
101 Self::builder()
102 .username(credential.username)
103 .password(credential.password)
104 .build()
105 }
106}
107
108impl Cluster {
109 pub fn new(options: ClusterOptions) -> Result<Self> {
110 let launcher = Launcher::new(
111 options.topology,
112 options.version_id,
113 options.tls,
114 options.auth,
115 options.verbose,
116 options.deprecated_tls_options,
117 options.save_logs,
118 options.extra_mongod_args,
119 )?;
120
121 launcher.initialize_cluster()
122 }
123
124 pub fn client_options(&self) -> &ClientOptions {
125 &self.client_options
126 }
127}