evidentsource-client 1.0.0-rc1

Rust client for the EvidentSource event sourcing platform
Documentation
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! EvidentSource - the main entrypoint for connecting to an EvidentSource server.

use std::time::Duration;

use chrono::{DateTime, Utc};
use futures::stream::{self, StreamExt};
use futures::Stream;
use http::Uri;
use tonic::transport::{Channel, ClientTlsConfig};

use evidentsource_core::domain::{DatabaseError, DatabaseName};
use evidentsource_core::{DatabaseCatalog, DatabaseIdentity};

use crate::auth::Credentials;
use crate::connection::Connection;
use crate::conversions::timestamp_to_datetime;
use crate::EvidentSourceClient;

/// A simple database identity returned from create_database.
#[derive(Debug, Clone)]
pub struct DatabaseIdentityImpl {
    name: DatabaseName,
    created_at: DateTime<Utc>,
}

impl DatabaseIdentity for DatabaseIdentityImpl {
    fn name(&self) -> &DatabaseName {
        &self.name
    }

    fn created_at(&self) -> DateTime<Utc> {
        self.created_at
    }
}

/// The main entrypoint for connecting to an EvidentSource server.
///
/// `EvidentSource` manages the gRPC connection and provides methods for:
/// - Listing available databases (`DatabaseCatalog` trait)
/// - Creating and deleting databases
/// - Connecting to a specific database for operations
///
/// # Example
///
/// ```ignore
/// use evidentsource_client::EvidentSource;
/// use evidentsource_core::domain::DatabaseName;
///
/// // Connect to the server
/// let es = EvidentSource::connect_to_server("http://localhost:50051").await?;
///
/// // List all databases
/// let mut databases = es.list_databases();
/// while let Some(name) = databases.next().await {
///     println!("Database: {}", name);
/// }
///
/// // Connect to a specific database
/// let db_name = DatabaseName::new("my-db")?;
/// let conn = es.connect(&db_name).await?;
///
/// // Use the connection for operations
/// let latest = conn.latest_database().await?;
/// println!("Latest revision: {}", latest.revision());
/// ```
#[derive(Clone)]
pub struct EvidentSource {
    client: EvidentSourceClient,
}

impl EvidentSource {
    /// Create a builder for configuring and connecting to an EvidentSource server.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use evidentsource_client::EvidentSource;
    /// use std::time::Duration;
    ///
    /// let es = EvidentSource::builder("http://localhost:50051")
    ///     .connect_timeout(Duration::from_secs(10))
    ///     .connect()
    ///     .await?;
    /// ```
    pub fn builder(addr: &str) -> EvidentSourceBuilder {
        EvidentSourceBuilder::new(addr)
    }

    /// Connect to an EvidentSource server without authentication.
    ///
    /// This only works if the server has `allow_anonymous=true`.
    ///
    /// # Arguments
    ///
    /// * `addr` - The server address (e.g., `http://localhost:50051` or `https://api.example.com`)
    ///
    /// # Example
    ///
    /// ```ignore
    /// let es = EvidentSource::connect_to_server("http://localhost:50051").await?;
    /// ```
    pub async fn connect_to_server(addr: &str) -> Result<Self, crate::Error> {
        Self::connect_with_auth(addr, Credentials::None).await
    }

    /// Connect to an EvidentSource server with authentication credentials.
    ///
    /// # Arguments
    ///
    /// * `addr` - The server address (e.g., `http://localhost:50051` or `https://api.example.com`)
    /// * `credentials` - Authentication credentials (BearerToken, DevMode, or None)
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use evidentsource_client::{EvidentSource, Credentials, DevModeCredentials};
    ///
    /// // With bearer token (production - requires TLS)
    /// let es = EvidentSource::connect_with_auth(
    ///     "https://api.example.com:50051",
    ///     Credentials::BearerToken(my_jwt_token),
    /// ).await?;
    ///
    /// // With DevMode credentials (local development)
    /// let es = EvidentSource::connect_with_auth(
    ///     "http://localhost:50051",
    ///     Credentials::DevMode(
    ///         DevModeCredentials::new("dev-user@example.com")
    ///             .with_email("dev@example.com")
    ///             .with_display_name("Developer")
    ///     ),
    /// ).await?;
    /// ```
    pub async fn connect_with_auth(
        addr: &str,
        credentials: Credentials,
    ) -> Result<Self, crate::Error> {
        let client = EvidentSourceClient::with_credentials(addr, credentials).await?;
        Ok(Self { client })
    }

    /// Create an EvidentSource instance from an existing client.
    pub fn from_client(client: EvidentSourceClient) -> Self {
        Self { client }
    }

    /// Connect to a specific database.
    ///
    /// This returns a `Connection` that maintains a live subscription to
    /// database updates and implements `DatabaseProvider` and `DatabaseConnection`.
    ///
    /// # Arguments
    ///
    /// * `database` - The name of the database to connect to
    ///
    /// # Example
    ///
    /// ```ignore
    /// let db_name = DatabaseName::new("my-db")?;
    /// let conn = es.connect(&db_name).await?;
    /// ```
    pub async fn connect(&self, database: &DatabaseName) -> Result<Connection, DatabaseError> {
        Connection::new(self.client.clone(), database.clone()).await
    }

    /// Get a reference to the underlying gRPC client.
    ///
    /// This provides access to low-level operations not exposed through
    /// the high-level API.
    pub fn client(&self) -> &EvidentSourceClient {
        &self.client
    }

    /// Get a mutable reference to the underlying gRPC client.
    pub fn client_mut(&mut self) -> &mut EvidentSourceClient {
        &mut self.client
    }
}

impl std::fmt::Debug for EvidentSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EvidentSource").finish()
    }
}

impl DatabaseCatalog for EvidentSource {
    type Identity = DatabaseIdentityImpl;

    fn list_databases(&self) -> impl Stream<Item = DatabaseName> {
        let mut client = self.client.clone();

        stream::once(async move {
            let result = client.fetch_catalog().await;

            match result {
                Ok(response_stream) => response_stream
                    .filter_map(|result| async move {
                        match result {
                            Ok(reply) => DatabaseName::new(&reply.database_name).ok(),
                            Err(_) => None,
                        }
                    })
                    .boxed(),
                Err(_) => stream::empty().boxed(),
            }
        })
        .flatten()
    }

    fn create_database(
        &self,
        name: DatabaseName,
    ) -> impl std::future::Future<Output = Result<Self::Identity, DatabaseError>> {
        let mut client = self.client.clone();

        async move {
            let proto_db = client
                .create_database(name.to_string())
                .await
                .map_err(|e| match e {
                    crate::Error::GrpcStatus(ref status) => {
                        crate::status_mapping::to_database_error(status, &name.to_string())
                    }
                    _ => DatabaseError::ServerError(e.to_string()),
                })?;

            let db_name = DatabaseName::new(&proto_db.name)?;
            let created_at = proto_db
                .created_at
                .ok_or_else(|| {
                    DatabaseError::ServerError("missing created_at timestamp".to_string())
                })
                .and_then(|ts| {
                    timestamp_to_datetime(ts).map_err(|e| {
                        DatabaseError::ServerError(format!("invalid timestamp: {}", e))
                    })
                })?;

            Ok(DatabaseIdentityImpl {
                name: db_name,
                created_at,
            })
        }
    }

    fn delete_database(
        &self,
        name: DatabaseName,
    ) -> impl std::future::Future<Output = Result<(), DatabaseError>> {
        let mut client = self.client.clone();

        async move {
            client
                .delete_database(name.to_string())
                .await
                .map_err(|e| match e {
                    crate::Error::GrpcStatus(ref status) => {
                        crate::status_mapping::to_database_error(status, &name.to_string())
                    }
                    _ => DatabaseError::ServerError(e.to_string()),
                })?;

            Ok(())
        }
    }
}

/// TLS configuration for the connection.
#[derive(Debug, Clone)]
pub enum TlsConfig {
    /// Use the system's native TLS roots.
    Native,
    /// Disable TLS verification (not recommended for production).
    Disabled,
}

/// Configuration for exponential backoff retry behavior.
#[derive(Debug, Clone)]
pub struct BackoffConfig {
    /// Initial delay before first retry.
    pub initial: Duration,
    /// Maximum delay between retries.
    pub max: Duration,
    /// Multiplier applied to delay after each retry.
    pub multiplier: f64,
}

impl Default for BackoffConfig {
    fn default() -> Self {
        Self {
            initial: Duration::from_millis(100),
            max: Duration::from_secs(30),
            multiplier: 2.0,
        }
    }
}

/// Builder for configuring and connecting to an EvidentSource server.
///
/// # Example
///
/// ```ignore
/// use evidentsource_client::{EvidentSource, Credentials, DevModeCredentials};
/// use std::time::Duration;
///
/// let es = EvidentSource::builder("http://localhost:50051")
///     .credentials(Credentials::DevMode(
///         DevModeCredentials::new("dev-user@example.com")
///     ))
///     .connect_timeout(Duration::from_secs(10))
///     .tls(TlsConfig::Native)
///     .connect()
///     .await?;
/// ```
#[derive(Debug, Clone)]
pub struct EvidentSourceBuilder {
    addr: String,
    credentials: Credentials,
    tls_config: Option<TlsConfig>,
    connect_timeout: Option<Duration>,
    backoff: Option<BackoffConfig>,
}

impl EvidentSourceBuilder {
    /// Create a new builder with the given server address.
    pub fn new(addr: &str) -> Self {
        Self {
            addr: addr.to_string(),
            credentials: Credentials::None,
            tls_config: None,
            connect_timeout: None,
            backoff: None,
        }
    }

    /// Set the authentication credentials.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let es = EvidentSource::builder("http://localhost:50051")
    ///     .credentials(Credentials::DevMode(DevModeCredentials::new("dev-user")))
    ///     .connect()
    ///     .await?;
    /// ```
    pub fn credentials(mut self, credentials: Credentials) -> Self {
        self.credentials = credentials;
        self
    }

    /// Set the TLS configuration.
    ///
    /// For HTTPS addresses, TLS is enabled by default with native roots.
    pub fn tls(mut self, config: TlsConfig) -> Self {
        self.tls_config = Some(config);
        self
    }

    /// Set the connection timeout.
    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = Some(timeout);
        self
    }

    /// Set the backoff configuration for retries.
    pub fn backoff(mut self, config: BackoffConfig) -> Self {
        self.backoff = Some(config);
        self
    }

    /// Connect to the server with the configured options.
    pub async fn connect(self) -> Result<EvidentSource, crate::Error> {
        let uri = Uri::try_from(&self.addr)?;
        let mut channel_builder = Channel::builder(uri.clone());

        // Apply connect timeout
        if let Some(timeout) = self.connect_timeout {
            channel_builder = channel_builder.connect_timeout(timeout);
        }

        // Apply TLS configuration
        let is_https = uri.scheme_str() == Some("https");
        match self.tls_config {
            Some(TlsConfig::Native) | None if is_https => {
                let tls_config = ClientTlsConfig::new()
                    .with_native_roots()
                    .domain_name(uri.host().unwrap_or("localhost"));
                channel_builder = channel_builder.tls_config(tls_config)?;
            }
            Some(TlsConfig::Disabled) => {
                // TLS disabled, don't configure
            }
            _ => {
                // HTTP connection, no TLS needed
            }
        }

        let channel = channel_builder.connect().await?;
        let interceptor = crate::auth::AuthInterceptor::new(self.credentials);
        let client =
            crate::com::evidentsource::evident_source_client::EvidentSourceClient::with_interceptor(
                channel,
                interceptor,
            );

        Ok(EvidentSource {
            client: EvidentSourceClient { client },
        })
    }

    /// Get the configured backoff settings.
    ///
    /// This can be used when creating connections to propagate retry settings.
    pub fn get_backoff(&self) -> Option<&BackoffConfig> {
        self.backoff.as_ref()
    }
}