typedb_driver/
driver.rs

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
418
419
420
421
422
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

use std::{
    collections::{HashMap, HashSet},
    fmt,
    sync::Arc,
};

use itertools::Itertools;

use crate::{
    common::{
        address::Address,
        error::{ConnectionError, Error},
        Result,
    },
    connection::{runtime::BackgroundRuntime, server_connection::ServerConnection},
    Credentials, DatabaseManager, DriverOptions, Options, Transaction, TransactionType, UserManager,
};

/// A connection to a TypeDB server which serves as the starting point for all interaction.
pub struct TypeDBDriver {
    server_connections: HashMap<Address, ServerConnection>,
    database_manager: DatabaseManager,
    user_manager: UserManager,
    background_runtime: Arc<BackgroundRuntime>,
    username: Option<String>,
    is_cloud: bool,
}

impl TypeDBDriver {
    const DRIVER_LANG: &'static str = "rust";
    const VERSION: &'static str = match option_env!("CARGO_PKG_VERSION") {
        None => "0.0.0",
        Some(version) => version,
    };

    pub const DEFAULT_ADDRESS: &'static str = "localhost:1729";

    /// Creates a new TypeDB Server connection.
    ///
    /// # Arguments
    ///
    /// * `address` — The address (host:port) on which the TypeDB Server is running
    /// * `Credentials` — The Credentials to connect with
    /// * `driver_options` — The DriverOptions to connect with
    ///
    /// # Examples
    ///
    /// ```rust
    #[cfg_attr(feature = "sync", doc = "Connection::new_core(\"127.0.0.1:1729\")")]
    #[cfg_attr(not(feature = "sync"), doc = "Connection::new_core(\"127.0.0.1:1729\").await")]
    /// ```
    #[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
    pub async fn new_core(
        address: impl AsRef<str>,
        credentials: Credentials,
        driver_options: DriverOptions,
    ) -> Result<Self> {
        Self::new_core_with_description(address, credentials, driver_options, Self::DRIVER_LANG).await
    }

    /// Creates a new TypeDB Server connection with a description.
    ///
    /// # Arguments
    ///
    /// * `address` — The address (host:port) on which the TypeDB Server is running
    /// * `Credentials` — The Credentials to connect with
    /// * `driver_options` — The DriverOptions to connect with
    /// * `driver_lang` — The language of the driver connecting to the server
    ///
    /// # Examples
    ///
    /// ```rust
    #[cfg_attr(feature = "sync", doc = "Connection::new_core(\"127.0.0.1:1729\", \"rust\")")]
    #[cfg_attr(not(feature = "sync"), doc = "Connection::new_core(\"127.0.0.1:1729\", \"rust\").await")]
    /// ```
    #[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
    pub async fn new_core_with_description(
        address: impl AsRef<str>,
        credentials: Credentials,
        driver_options: DriverOptions,
        driver_lang: impl AsRef<str>,
    ) -> Result<Self> {
        let id = address.as_ref().to_string();
        let address: Address = id.parse()?;
        let background_runtime = Arc::new(BackgroundRuntime::new()?);

        let (server_connection, database_info) = ServerConnection::new_core(
            background_runtime.clone(),
            address.clone(),
            credentials,
            driver_options,
            driver_lang.as_ref(),
            TypeDBDriver::VERSION,
        )
        .await?;

        // // validate
        // let advertised_address = server_connection
        //     .servers_all()?
        //     .into_iter()
        //     .exactly_one()
        //     .map_err(|e| ConnectionError::ServerConnectionFailedStatusError { error: e.to_string() })?;

        // TODO: this solidifies the assumption that servers don't change
        let server_connections: HashMap<Address, ServerConnection> = [(address, server_connection)].into();
        let database_manager = DatabaseManager::new(server_connections.clone(), database_info)?;
        let user_manager = UserManager::new(server_connections.clone());

        Ok(Self {
            server_connections,
            database_manager,
            user_manager,
            background_runtime,
            username: None,
            is_cloud: false,
        })
    }

    // TODO: Add examples
    /// Creates a new TypeDB Cloud connection.
    ///
    /// # Arguments
    ///
    /// * `init_addresses` — Addresses (host:port) on which TypeDB Cloud nodes are running
    /// * `credentials` — The Credentials to connect with
    /// * `driver_options` — The DriverOptions to connect with
    /// ```
    #[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
    pub async fn new_cloud<T: AsRef<str> + Sync>(
        // init_addresses: &[T], // TODO: return the slice version when we don't need to check the size
        init_addresses: &Vec<T>,
        credentials: Credentials,
        driver_options: DriverOptions,
    ) -> Result<Self> {
        Self::new_cloud_with_description(init_addresses, credentials, driver_options, Self::DRIVER_LANG).await
    }

    // TODO: Add examples
    /// Creates a new TypeDB Cloud connection.
    ///
    /// # Arguments
    ///
    /// * `init_addresses` — Addresses (host:port) on which TypeDB Cloud nodes are running
    /// * `credentials` — The Credentials to connect with
    /// * `driver_options` — The DriverOptions to connect with
    /// * `driver_lang` — The language of the driver connecting to the server
    /// ```
    #[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
    pub async fn new_cloud_with_description<T: AsRef<str> + Sync>(
        // init_addresses: &[T], // TODO: return the slice version when we don't need to check the size
        init_addresses: &Vec<T>,
        credentials: Credentials,
        driver_options: DriverOptions,
        driver_lang: impl AsRef<str>,
    ) -> Result<Self> {
        if let Some(single_address) = init_addresses.iter().next() {
            Self::new_core_with_description(single_address, credentials, driver_options, driver_lang).await
        } else {
            todo!("Only a single address is accepted for TypeDB Cloud 3.0")
        }
        // let background_runtime = Arc::new(BackgroundRuntime::new()?);
        // let servers = Self::fetch_server_list(background_runtime.clone(), init_addresses, credentials.clone())?;
        // let server_to_address = servers.into_iter().map(|address| (address.clone(), address)).collect();
        // Self::new_cloud_impl(server_to_address, background_runtime, credential)
    }

    // TODO: Add examples
    /// Creates a new TypeDB Cloud connection.
    ///
    /// # Arguments
    ///
    /// * `address_translation` — Translation map from addresses to be used by the driver for connection
    ///    to addresses received from the TypeDB server(s)
    /// * `credential` — The Credentials to connect with
    /// * `driver_options` — The DriverOptions to connect with
    /// ```
    #[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
    pub async fn new_cloud_with_translation<T, U>(
        // TODO: Find a better name
        address_translation: HashMap<T, U>,
        credential: Credentials,
        driver_options: DriverOptions,
    ) -> Result<Self>
    where
        T: AsRef<str> + Sync,
        U: AsRef<str> + Sync,
    {
        Self::new_cloud_with_translation_with_description(
            address_translation,
            credential,
            driver_options,
            Self::DRIVER_LANG,
        )
        .await
    }

    // TODO: Add examples
    /// Creates a new TypeDB Cloud connection.
    ///
    /// # Arguments
    ///
    /// * `address_translation` — Translation map from addresses to be used by the driver for connection
    ///    to addresses received from the TypeDB server(s)
    /// * `credentials` — The Credentials to connect with
    /// * `driver_options` — The DriverOptions to connect with
    /// * `driver_lang` — The language of the driver connecting to the server
    /// ```
    #[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
    pub async fn new_cloud_with_translation_with_description<T, U>(
        address_translation: HashMap<T, U>,
        credentials: Credentials,
        driver_options: DriverOptions,
        driver_lang: impl AsRef<str>,
    ) -> Result<Self>
    where
        T: AsRef<str> + Sync,
        U: AsRef<str> + Sync,
    {
        todo!("No address translation is available and only a single server is accepted for TypeDB Cloud 3.0")
        // let background_runtime = Arc::new(BackgroundRuntime::new()?);
        //
        // let fetched =
        //     Self::fetch_server_list(background_runtime.clone(), address_translation.keys(), credential.clone())?;
        //
        // let address_to_server: HashMap<Address, Address> = address_translation
        //     .into_iter()
        //     .map(|(public, private)| -> Result<_> { Ok((public.as_ref().parse()?, private.as_ref().parse()?)) })
        //     .try_collect()?;
        //
        // let provided: HashSet<Address> = address_to_server.values().cloned().collect();
        // let unknown = &provided - &fetched;
        // let unmapped = &fetched - &provided;
        // if !unknown.is_empty() || !unmapped.is_empty() {
        //     return Err(ConnectionError::AddressTranslationMismatch { unknown, unmapped }.into());
        // }
        //
        // debug_assert_eq!(fetched, provided);
        //
        // Self::new_cloud_impl(address_to_server, background_runtime, credential)
    }

    fn new_cloud_impl(
        address_to_server: HashMap<Address, Address>,
        background_runtime: Arc<BackgroundRuntime>,
        credentials: Credentials,
        driver_options: DriverOptions,
    ) -> Result<TypeDBDriver> {
        // let server_connections: HashMap<Address, ServerConnection> = address_to_server
        //     .into_iter()
        //     .map(|(public, private)| {
        //         ServerConnection::new_cloud(background_runtime.clone(), public, credential.clone())
        //             .map(|server_connection| (private, server_connection))
        //     })
        //     .try_collect()?;
        //
        // let errors = server_connections.values().map(|conn| conn.validate()).filter_map(Result::err).collect_vec();
        // if errors.len() == server_connections.len() {
        //     Err(ConnectionError::CloudAllNodesFailed {
        //         errors: errors.into_iter().map(|err| err.to_string()).join("\n"),
        //     })?
        // } else {
        //     Ok(Connection {
        //         server_connections,
        //         background_runtime,
        //         username: Some(credential.username().to_owned()),
        //         is_cloud: true,
        //     })
        // }
        todo!()
    }

    fn fetch_server_list(
        background_runtime: Arc<BackgroundRuntime>,
        addresses: impl IntoIterator<Item = impl AsRef<str>> + Clone,
        credentials: Credentials,
        driver_options: DriverOptions,
    ) -> Result<HashSet<Address>> {
        let addresses: Vec<Address> = addresses.into_iter().map(|addr| addr.as_ref().parse()).try_collect()?;
        for address in &addresses {
            let server_connection =
                ServerConnection::new_cloud(background_runtime.clone(), address.clone(), credentials.clone());
            match server_connection {
                Ok(server_connection) => match server_connection.servers_all() {
                    Ok(servers) => return Ok(servers.into_iter().collect()),
                    Err(Error::Connection(
                        ConnectionError::ServerConnectionFailedStatusError { .. } | ConnectionError::ConnectionFailed,
                    )) => (),
                    Err(err) => Err(err)?,
                },
                Err(Error::Connection(
                    ConnectionError::ServerConnectionFailedStatusError { .. } | ConnectionError::ConnectionFailed,
                )) => (),
                Err(err) => Err(err)?,
            }
        }
        Err(ConnectionError::ServerConnectionFailed { addresses }.into())
    }

    /// Checks it this connection is opened.
    //
    /// # Examples
    ///
    /// ```rust
    /// connection.is_open()
    /// ```
    pub fn is_open(&self) -> bool {
        self.background_runtime.is_open()
    }

    /// Check if the connection is to an Cloud server.
    ///
    /// # Examples
    ///
    /// ```rust
    /// connection.is_cloud()
    /// ```
    pub fn is_cloud(&self) -> bool {
        self.is_cloud
    }

    pub fn databases(&self) -> &DatabaseManager {
        &self.database_manager
    }

    pub fn users(&self) -> &UserManager {
        &self.user_manager
    }

    #[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
    pub async fn transaction(
        &self,
        database_name: impl AsRef<str>,
        transaction_type: TransactionType,
    ) -> Result<Transaction> {
        self.transaction_with_options(database_name, transaction_type, Options::new()).await
    }

    #[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
    pub async fn transaction_with_options(
        &self,
        database_name: impl AsRef<str>,
        transaction_type: TransactionType,
        options: Options,
    ) -> Result<Transaction> {
        let database_name = database_name.as_ref();
        let database = self.database_manager.get_cached_or_fetch(database_name).await?;
        let transaction_stream = database
            .run_failsafe(|database| async move {
                database.connection().open_transaction(database.name(), transaction_type, options).await
            })
            .await?;
        Ok(Transaction::new(transaction_stream))
    }

    /// Closes this connection if it is open.
    ///
    /// # Examples
    ///
    /// ```rust
    /// connection.force_close()
    /// ```
    pub fn force_close(&self) -> Result {
        if !self.is_open() {
            return Ok(());
        }

        let result =
            self.server_connections.values().map(ServerConnection::force_close).try_collect().map_err(Into::into);
        self.background_runtime.force_close().and(result)
    }

    pub(crate) fn server_count(&self) -> usize {
        self.server_connections.len()
    }

    pub(crate) fn servers(&self) -> impl Iterator<Item = &Address> {
        self.server_connections.keys()
    }

    pub(crate) fn connection(&self, id: &Address) -> Option<&ServerConnection> {
        self.server_connections.get(id)
    }

    pub(crate) fn connections(&self) -> impl Iterator<Item = (&Address, &ServerConnection)> + '_ {
        self.server_connections.iter()
    }

    pub(crate) fn username(&self) -> Option<&str> {
        self.username.as_deref()
    }

    pub(crate) fn unable_to_connect_error(&self) -> Error {
        Error::Connection(ConnectionError::ServerConnectionFailed {
            addresses: self.servers().map(Address::clone).collect_vec(),
        })
    }
}

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