arcadedb_protocol/options.rs
1//! Connection configuration: the [`ClientOptions`] builder.
2//!
3//! Everything [`ArcadeDbClient::connect_with`](crate::ArcadeDbClient::connect_with)
4//! needs, spelled explicitly: endpoint, credentials, TLS,
5//! connect/retry policy, and the default per-request deadline. Credentials
6//! are validated up front (non-ASCII metadata is a typed error, never a
7//! panic).
8
9use std::time::Duration;
10
11use tonic::transport::ClientTlsConfig;
12
13use crate::error::{ArcadeDbError, Result};
14
15/// Connection settings for
16/// [`ArcadeDbClient::connect_with`](crate::ArcadeDbClient::connect_with).
17///
18/// Defaults: plaintext transport, 30 connect attempts with a 400ms backoff,
19/// no per-request deadline.
20#[derive(Clone, Debug)]
21pub struct ClientOptions {
22 pub(crate) addr: String,
23 pub(crate) user: String,
24 pub(crate) pass: String,
25 pub(crate) database: String,
26 /// `Some` → TLS transport (`https` scheme + this config).
27 pub(crate) tls: Option<ClientTlsConfig>,
28 /// Per-attempt TCP connect deadline.
29 pub(crate) connect_timeout: Option<Duration>,
30 pub(crate) connect_attempts: u32,
31 pub(crate) connect_backoff: Duration,
32 /// Applied to every request as the gRPC `grpc-timeout` deadline.
33 pub(crate) request_timeout: Option<Duration>,
34 /// Create the database on connect when it does not exist (the Java
35 /// `DatabaseFactory.exists() → create()/open()` idiom).
36 pub(crate) open_or_create: bool,
37}
38
39impl ClientOptions {
40 /// Settings for `addr` (`host:port`), credentials, and the default
41 /// database — plaintext transport, default retry policy.
42 pub fn new(
43 addr: impl Into<String>,
44 user: impl Into<String>,
45 pass: impl Into<String>,
46 database: impl Into<String>,
47 ) -> Self {
48 Self {
49 addr: addr.into(),
50 user: user.into(),
51 pass: pass.into(),
52 database: database.into(),
53 tls: None,
54 connect_timeout: None,
55 connect_attempts: 30,
56 connect_backoff: Duration::from_millis(400),
57 request_timeout: None,
58 open_or_create: false,
59 }
60 }
61
62 /// After connecting, create `database` if it does not exist (as a
63 /// `"graph"` database). Tolerates the `AlreadyExists` race — two
64 /// bootstrapping workers pointing at the same fresh database both
65 /// succeed.
66 pub fn open_or_create(mut self, yes: bool) -> Self {
67 self.open_or_create = yes;
68 self
69 }
70
71 /// Use a TLS transport with this config (e.g.
72 /// `ClientTlsConfig::new().ca_certificate(..)`). Implies the `https`
73 /// scheme; without it the channel is plaintext.
74 pub fn tls(mut self, config: ClientTlsConfig) -> Self {
75 self.tls = Some(config);
76 self
77 }
78
79 /// Per-attempt TCP connect deadline (a cold JVM that accepts nothing
80 /// fails the attempt fast instead of hanging).
81 pub fn connect_timeout(mut self, timeout: Duration) -> Self {
82 self.connect_timeout = Some(timeout);
83 self
84 }
85
86 /// How many times to retry the TCP connect before giving up (default 30).
87 pub fn connect_attempts(mut self, attempts: u32) -> Self {
88 self.connect_attempts = attempts.max(1);
89 self
90 }
91
92 /// Delay between connect attempts (default 400ms).
93 pub fn connect_backoff(mut self, backoff: Duration) -> Self {
94 self.connect_backoff = backoff;
95 self
96 }
97
98 /// Default per-request gRPC deadline, applied to every call that does
99 /// not set its own timeout. Prevents a hung server from stalling callers
100 /// forever (and the [`Transaction`](crate::Transaction) drop-guard from
101 /// silently rolling back a wedged transaction).
102 pub fn request_timeout(mut self, timeout: Duration) -> Self {
103 self.request_timeout = Some(timeout);
104 self
105 }
106
107 /// Read settings from the environment with the standard `ARCADEDB_`
108 /// prefix: `ARCADEDB_ADDR`, `ARCADEDB_USER`, `ARCADEDB_PASSWORD`,
109 /// `ARCADEDB_DATABASE`. Missing/empty variables are a
110 /// [`ArcadeDbError::InvalidInput`] naming the first offender.
111 pub fn from_env() -> Result<Self> {
112 Self::from_env_prefix("ARCADEDB")
113 }
114
115 /// [`from_env`](Self::from_env) with a custom prefix (`{PREFIX}_ADDR`, …).
116 pub fn from_env_prefix(prefix: &str) -> Result<Self> {
117 let get = |suffix: &str| -> Result<String> {
118 let name = format!("{prefix}_{suffix}");
119 std::env::var(&name)
120 .ok()
121 .filter(|v| !v.is_empty())
122 .ok_or_else(|| ArcadeDbError::InvalidInput {
123 message: format!(
124 "ClientOptions::from_env: environment variable `{name}` is not set"
125 ),
126 })
127 };
128 Ok(Self::new(
129 get("ADDR")?,
130 get("USER")?,
131 get("PASSWORD")?,
132 get("DATABASE")?,
133 ))
134 }
135
136 /// Validate before dialing: non-empty fields and ASCII-only metadata
137 /// values (anything else is a typed error, never a panic).
138 pub(crate) fn validate(&self) -> Result<()> {
139 let check = |value: &str, what: &str| -> Result<()> {
140 if value.is_empty() {
141 return Err(ArcadeDbError::InvalidInput {
142 message: format!("ClientOptions: {what} must not be empty"),
143 });
144 }
145 if value.parse::<tonic::metadata::MetadataValue<_>>().is_err() {
146 return Err(ArcadeDbError::InvalidInput {
147 message: format!(
148 "ClientOptions: {what} contains characters invalid in a gRPC metadata value (visible ASCII only)"
149 ),
150 });
151 }
152 Ok(())
153 };
154 check(&self.addr, "addr")?;
155 check(&self.user, "user")?;
156 check(&self.pass, "password")?;
157 check(&self.database, "database")?;
158 Ok(())
159 }
160}