surreal-client 0.4.0

CBOR-based SurrealDB client for the Vantage data framework
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! Connection builder for SurrealDB with authentication and engine creation

use crate::{DebugEngine, Engine, Result, SurrealClient, SurrealError, WsCborEngine, WsEngine};

use serde_json::{Value, json};
use url::Url;

/// Connection builder for SurrealDB
#[derive(Default, Debug, Clone)]
pub struct SurrealConnection {
    /// URL to connect to
    pub url: Option<String>,

    /// Namespace to use
    namespace: Option<String>,

    /// Database to use
    database: Option<String>,

    /// Authentication credentials
    auth: Option<AuthParams>,

    /// Whether to check SurrealDB version compatibility
    version_check: bool,

    /// Whether to enable debug mode for query logging
    debug: bool,
}

/// Authentication parameters
#[derive(Debug, Clone)]
pub enum AuthParams {
    /// Root authentication
    Root { username: String, password: String },
    /// Namespace authentication
    Namespace { username: String, password: String },
    /// Database authentication
    Database { username: String, password: String },
    /// Scope authentication
    Scope {
        namespace: String,
        database: String,
        scope: String,
        params: Value,
    },
    /// JWT token authentication
    Token(String),
}

impl SurrealConnection {
    /// Create a new connection builder
    pub fn new() -> Self {
        Self {
            version_check: true,
            debug: false,
            ..Default::default()
        }
    }

    /// Parse connection from DSN string
    pub fn dsn(dsn: impl AsRef<str>) -> Result<Self> {
        let mut conn = Self::new();
        let url = Url::parse(dsn.as_ref())?;

        // Ensure URL has a proper host
        if url.host().is_none() {
            return Err(SurrealError::Connection(
                "URL must have a valid host".to_string(),
            ));
        }

        // Store the URL without user credentials and path/query
        let base_url = format!("{}://{}", url.scheme(), url.host_str().unwrap());
        let port = url.port().map(|p| format!(":{}", p)).unwrap_or_default();
        let final_url = format!("{}{}", base_url, port);
        conn.url = Some(final_url);

        // Extract user credentials for root auth
        if !url.username().is_empty() {
            let username = url.username().to_string();
            let password = url.password().unwrap_or("").to_string();
            conn.auth = Some(AuthParams::Root { username, password });
        }

        // Extract namespace and database from path segments
        let path_segments: Vec<&str> = url.path_segments().map(|c| c.collect()).unwrap_or_default();

        if let Some(namespace) = path_segments.first().filter(|s| !s.is_empty()) {
            conn.namespace = Some(namespace.to_string());
        }
        if let Some(database) = path_segments.get(1).filter(|s| !s.is_empty()) {
            conn.database = Some(database.to_string());
        }

        // Parse query parameters
        for (key, value) in url.query_pairs() {
            match key.as_ref() {
                "namespace" => conn.namespace = Some(value.into_owned()),
                "database" => conn.database = Some(value.into_owned()),
                "version_check" => {
                    conn.version_check = value.parse().unwrap_or(true);
                }
                _ => {}
            }
        }

        Ok(conn)
    }

    /// Set the URL to connect to
    pub fn url(mut self, url: impl Into<String>) -> Self {
        self.url = Some(url.into());
        self
    }

    /// Set the namespace
    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
        self.namespace = Some(namespace.into());
        self
    }

    /// Set the database
    pub fn database(mut self, database: impl Into<String>) -> Self {
        self.database = Some(database.into());
        self
    }

    /// Set root authentication
    pub fn auth_root(mut self, username: impl Into<String>, password: impl Into<String>) -> Self {
        self.auth = Some(AuthParams::Root {
            username: username.into(),
            password: password.into(),
        });
        self
    }

    /// Set namespace authentication
    pub fn auth_namespace(
        mut self,
        username: impl Into<String>,
        password: impl Into<String>,
    ) -> Self {
        self.auth = Some(AuthParams::Namespace {
            username: username.into(),
            password: password.into(),
        });
        self
    }

    /// Set database authentication
    pub fn auth_database(
        mut self,
        username: impl Into<String>,
        password: impl Into<String>,
    ) -> Self {
        self.auth = Some(AuthParams::Database {
            username: username.into(),
            password: password.into(),
        });
        self
    }

    /// Set scope authentication
    pub fn auth_scope(
        mut self,
        namespace: impl Into<String>,
        database: impl Into<String>,
        scope: impl Into<String>,
        params: Value,
    ) -> Self {
        self.auth = Some(AuthParams::Scope {
            namespace: namespace.into(),
            database: database.into(),
            scope: scope.into(),
            params,
        });
        self
    }

    /// Set JWT token authentication
    pub fn auth_token(mut self, token: impl Into<String>) -> Self {
        self.auth = Some(AuthParams::Token(token.into()));
        self
    }

    /// Set version check flag
    pub fn version_check(mut self, check: bool) -> Self {
        self.version_check = check;
        self
    }

    /// Enable debug mode for query logging
    pub fn with_debug(mut self, enabled: bool) -> Self {
        self.debug = enabled;
        self
    }

    // /// Configure connection pool with custom settings
    // pub fn with_pool_config(mut self, config: PoolConfig) -> Self {
    //     self.pool_config = Some(config);
    //     self
    // }

    pub async fn init_ws_engine(&self, engine: &mut dyn Engine) -> Result<()> {
        match self.auth.as_ref().ok_or(SurrealError::Connection(
            "Attempted to connect without auth".to_string(),
        ))? {
            AuthParams::Root { username, password } => {
                engine
                    .send_message(
                        "signin",
                        json!([{
                            "user": username,
                            "pass": password
                        }]),
                    )
                    .await?;
            }
            AuthParams::Namespace { username, password } => {
                engine
                    .send_message("signin", json!([{
                        "user": username,
                        "pass": password,
                        "NS": self.namespace.clone().ok_or(SurrealError::Connection("Namespace is required for namespace auth".to_string())
                    )?}]))
                    .await?;
            }
            AuthParams::Database { username, password } => {
                engine
                    .send_message("signin", json!([{
                        "user": username,
                        "pass": password,
                        "NS": self.namespace.clone().ok_or( SurrealError::Connection("Namespace is required for namespace auth".to_string()) )?,
                        "DB": self.database.clone().ok_or(
                        SurrealError::Connection("Database is required for database auth".to_string())
                    )?}]))
                    .await?;
            }
            _ => {
                return Err(SurrealError::Connection(
                    "Unsupported authentication method for WebSocket".to_string(),
                ));
            }
        }

        // After authentication, set namespace and database
        if let Some(namespace) = &self.namespace {
            engine
                .send_message(
                    "use",
                    json!([namespace, self.database.as_ref().unwrap_or(&String::new())]),
                )
                .await?;
        }

        Ok(())
    }

    pub async fn init_cbor_engine(&self, engine: &mut crate::WsCborEngine) -> Result<()> {
        use ciborium::Value as CborValue;

        match self.auth.as_ref().ok_or(SurrealError::Connection(
            "Attempted to connect without auth".to_string(),
        ))? {
            AuthParams::Root { username, password } => {
                let auth_params = CborValue::Array(vec![CborValue::Map(vec![
                    (
                        CborValue::Text("user".to_string()),
                        CborValue::Text(username.clone()),
                    ),
                    (
                        CborValue::Text("pass".to_string()),
                        CborValue::Text(password.clone()),
                    ),
                ])]);
                engine.send_message_cbor("signin", auth_params).await?;
            }
            AuthParams::Namespace { username, password } => {
                let namespace = self.namespace.clone().ok_or(SurrealError::Connection(
                    "Namespace is required for namespace auth".to_string(),
                ))?;
                let auth_params = CborValue::Array(vec![CborValue::Map(vec![
                    (
                        CborValue::Text("user".to_string()),
                        CborValue::Text(username.clone()),
                    ),
                    (
                        CborValue::Text("pass".to_string()),
                        CborValue::Text(password.clone()),
                    ),
                    (
                        CborValue::Text("NS".to_string()),
                        CborValue::Text(namespace),
                    ),
                ])]);
                engine.send_message_cbor("signin", auth_params).await?;
            }
            AuthParams::Database { username, password } => {
                let namespace = self.namespace.clone().ok_or(SurrealError::Connection(
                    "Namespace is required for database auth".to_string(),
                ))?;
                let database = self.database.clone().ok_or(SurrealError::Connection(
                    "Database is required for database auth".to_string(),
                ))?;
                let auth_params = CborValue::Array(vec![CborValue::Map(vec![
                    (
                        CborValue::Text("user".to_string()),
                        CborValue::Text(username.clone()),
                    ),
                    (
                        CborValue::Text("pass".to_string()),
                        CborValue::Text(password.clone()),
                    ),
                    (
                        CborValue::Text("NS".to_string()),
                        CborValue::Text(namespace),
                    ),
                    (CborValue::Text("DB".to_string()), CborValue::Text(database)),
                ])]);
                engine.send_message_cbor("signin", auth_params).await?;
            }
            _ => {
                return Err(SurrealError::Connection(
                    "Unsupported authentication method for CBOR WebSocket".to_string(),
                ));
            }
        }

        // After authentication, set namespace and database
        if let Some(namespace) = &self.namespace {
            let use_params = CborValue::Array(vec![
                CborValue::Text(namespace.clone()),
                CborValue::Text(self.database.as_ref().unwrap_or(&String::new()).clone()),
            ]);
            engine.send_message_cbor("use", use_params).await?;
        }

        Ok(())
    }

    /// Connect to SurrealDB and return an immutable client
    pub async fn connect(self) -> Result<SurrealClient> {
        let url_str = self
            .url
            .as_ref()
            .ok_or_else(|| SurrealError::Connection("URL is required".to_string()))?;
        let url = Url::parse(url_str)
            .map_err(|e| SurrealError::Connection(format!("Invalid URL: {}", e)))?;

        let mut engine: Box<dyn Engine> = match url.scheme() {
            "ws" | "wss" => Box::new(WsEngine::from_connection(&self).await?),
            "cbor" => {
                let mut cbor_engine = WsCborEngine::from_connection(&self).await?;
                self.init_cbor_engine(&mut cbor_engine).await?;
                Box::new(cbor_engine)
            }
            // "http" | "https" => Box::new(HttpEngine::new(url_str)?),
            _ => {
                return Err(SurrealError::Protocol(
                    "Unsupported protocol. Use ws://, wss://, cbor://, http://, or https://"
                        .to_string(),
                ));
            }
        };

        // Wrap with debug engine if debug mode is enabled
        if self.debug {
            engine = DebugEngine::wrap(engine);
        }

        // Connect to the database
        // engine.connect().await?;
        let client = SurrealClient::new(engine, self.namespace, self.database);
        Ok(client.with_debug(self.debug))
    }

    /*
        // Set namespace and database if provided
        if self.namespace.is_some() || self.database.is_some() {
            let message = crate::surreal_client::RpcMessage::new("use")
                .with_id(1)
                .with_params(vec![
                    self.namespace
                        .clone()
                        .map(Value::String)
                        .unwrap_or(Value::Null),
                    self.database
                        .clone()
                        .map(Value::String)
                        .unwrap_or(Value::Null),
                ]);

            engine.rpc(message).await?;

            // For HTTP engines, update the namespace/database in the engine
            if let Some(http_engine) = engine.as_any_mut().downcast_mut::<HttpEngine>() {
                http_engine.set_namespace_database(self.namespace.clone(), self.database.clone());
            }
        }

        // Authenticate if credentials provided
        if let Some(auth) = &self.auth {
            match auth {
                AuthParams::Root { username, password } => {
                    let message = crate::surreal_client::RpcMessage::new("signin")
                        .with_id(2)
                        .with_params(vec![Value::Object({
                            let mut map = serde_json::Map::new();
                            map.insert("user".to_string(), Value::String(username.clone()));
                            map.insert("pass".to_string(), Value::String(password.clone()));
                            map
                        })]);

                    let response = engine.rpc(message).await?;

                    // For HTTP engines, set the token if we got one
                    if let Value::String(token) = response {
                        if let Some(http_engine) = engine.as_any_mut().downcast_mut::<HttpEngine>()
                        {
                            http_engine.set_token(Some(token));
                        }
                    }
                }
                AuthParams::Namespace { username, password } => {
                    let message = crate::surreal_client::RpcMessage::new("signin")
                        .with_id(2)
                        .with_params(vec![Value::Object({
                            let mut map = serde_json::Map::new();
                            map.insert(
                                "NS".to_string(),
                                self.namespace
                                    .clone()
                                    .map(Value::String)
                                    .unwrap_or(Value::Null),
                            );
                            map.insert("user".to_string(), Value::String(username.clone()));
                            map.insert("pass".to_string(), Value::String(password.clone()));
                            map
                        })]);

                    let response = engine.rpc(message).await?;

                    if let Value::String(token) = response {
                        if let Some(http_engine) = engine.as_any_mut().downcast_mut::<HttpEngine>()
                        {
                            http_engine.set_token(Some(token));
                        }
                    }
                }
                AuthParams::Database { username, password } => {
                    let message = crate::surreal_client::RpcMessage::new("signin")
                        .with_id(2)
                        .with_params(vec![Value::Object({
                            let mut map = serde_json::Map::new();
                            map.insert(
                                "NS".to_string(),
                                self.namespace
                                    .clone()
                                    .map(Value::String)
                                    .unwrap_or(Value::Null),
                            );
                            map.insert(
                                "DB".to_string(),
                                self.database
                                    .clone()
                                    .map(Value::String)
                                    .unwrap_or(Value::Null),
                            );
                            map.insert("user".to_string(), Value::String(username.clone()));
                            map.insert("pass".to_string(), Value::String(password.clone()));
                            map
                        })]);

                    let response = engine.rpc(message).await?;

                    if let Value::String(token) = response {
                        if let Some(http_engine) = engine.as_any_mut().downcast_mut::<HttpEngine>()
                        {
                            http_engine.set_token(Some(token));
                        }
                    }
                }
                AuthParams::Scope {
                    namespace,
                    database,
                    scope,
                    params,
                } => {
                    let mut auth_params = if let Value::Object(map) = params {
                        map.clone()
                    } else {
                        serde_json::Map::new()
                    };

                    auth_params.insert("NS".to_string(), Value::String(namespace.clone()));
                    auth_params.insert("DB".to_string(), Value::String(database.clone()));
                    auth_params.insert("SC".to_string(), Value::String(scope.clone()));

                    let message = crate::surreal_client::RpcMessage::new("signin")
                        .with_id(2)
                        .with_params(vec![Value::Object(auth_params)]);

                    let response = engine.rpc(message).await?;

                    if let Value::String(token) = response {
                        if let Some(http_engine) = engine.as_any_mut().downcast_mut::<HttpEngine>()
                        {
                            http_engine.set_token(Some(token));
                        }
                    }
                }
                AuthParams::Token(token) => {
                    let message = crate::surreal_client::RpcMessage::new("authenticate")
                        .with_id(2)
                        .with_params(vec![Value::String(token.clone())]);

                    engine.rpc(message).await?;

                    if let Some(http_engine) = engine.as_any_mut().downcast_mut::<HttpEngine>() {
                        http_engine.set_token(Some(token.clone()));
                    }
                }
            }
        }

        // Check version if enabled
        if self.version_check {
            let message = crate::surreal_client::RpcMessage::new("version").with_id(3);
            let _version = engine.rpc(message).await?;
            // TODO: Add actual version compatibility check
        }

        // Create the immutable client
        Ok(SurrealClient::new(engine, self.namespace, self.database))
    }
    */
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_connection_builder() {
        let conn = SurrealConnection::new()
            .url("ws://localhost:8000")
            .namespace("test_ns")
            .database("test_db")
            .auth_root("root", "root")
            .version_check(false);

        assert_eq!(conn.url, Some("ws://localhost:8000".to_string()));
        assert_eq!(conn.namespace, Some("test_ns".to_string()));
        assert_eq!(conn.database, Some("test_db".to_string()));
        assert!(!conn.version_check);
        assert!(matches!(conn.auth, Some(AuthParams::Root { .. })));
    }

    #[test]
    fn test_dsn_parsing() {
        let conn = SurrealConnection::dsn(
            "ws://root:root@localhost:8000/test_ns/test_db?version_check=false",
        )
        .unwrap();

        assert_eq!(conn.url, Some("ws://localhost:8000".to_string()));
        assert_eq!(conn.namespace, Some("test_ns".to_string()));
        assert_eq!(conn.database, Some("test_db".to_string()));
        assert!(!conn.version_check);
        assert!(matches!(conn.auth, Some(AuthParams::Root { .. })));
    }

    #[test]
    fn test_dsn_with_query_params() {
        let conn =
            SurrealConnection::dsn("http://localhost:8000?namespace=ns&database=db").unwrap();

        assert_eq!(conn.url, Some("http://localhost:8000".to_string()));
        assert_eq!(conn.namespace, Some("ns".to_string()));
        assert_eq!(conn.database, Some("db".to_string()));
    }

    #[test]
    fn test_auth_methods() {
        let conn1 = SurrealConnection::new().auth_root("admin", "pass");
        assert!(matches!(conn1.auth, Some(AuthParams::Root { .. })));

        let conn2 = SurrealConnection::new().auth_namespace("ns_user", "ns_pass");
        assert!(matches!(conn2.auth, Some(AuthParams::Namespace { .. })));

        let conn3 = SurrealConnection::new().auth_database("db_user", "db_pass");
        assert!(matches!(conn3.auth, Some(AuthParams::Database { .. })));

        let conn4 = SurrealConnection::new().auth_token("jwt_token");
        assert!(matches!(conn4.auth, Some(AuthParams::Token(_))));
    }

    #[tokio::test]
    async fn test_connection_to_client_flow() {
        // Example of the new flow: Connection -> authenticate -> creates engine -> returns immutable client

        // This would be the typical usage:
        // let client = Connection::new()
        //     .url("ws://localhost:8000")
        //     .namespace("bakery")
        //     .database("inventory")
        //     .auth_root("root", "root")
        //     .connect()
        //     .await
        //     .unwrap();

        // For testing, we just verify the builder pattern works
        let connection = SurrealConnection::new()
            .url("ws://localhost:8000")
            .namespace("test_namespace")
            .database("test_database")
            .auth_root("admin", "password")
            .version_check(false);

        assert_eq!(connection.url, Some("ws://localhost:8000".to_string()));
        assert_eq!(connection.namespace, Some("test_namespace".to_string()));
        assert_eq!(connection.database, Some("test_database".to_string()));
        assert!(!connection.version_check);
        assert!(matches!(connection.auth, Some(AuthParams::Root { .. })));

        // The client would be immutable once created:
        // - client.query() - no mut needed
        // - client.select() - no mut needed
        // - client.let_var() - changes session but client stays immutable
        // - Multiple clients can be cloned, each with unique session
    }
}