zebflow 0.7.9

Reactive web automation platform — pipelines, templates, and real-time collaboration in a single binary.
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
//! Project DB connection management service.

use std::sync::Arc;

use rand::Rng;
use serde_json::json;

use crate::platform::adapters::data::DataAdapter;
use crate::platform::error::PlatformError;
use crate::platform::model::{
    ProjectDbConnection, ProjectDbConnectionListItem, ProjectDbConnectionTestResult,
    TestProjectDbConnectionRequest, UpsertProjectDbConnectionRequest, now_ts, slug_segment,
};
use crate::platform::sekejap;

/// Project-scoped DB connections stored in the metadata catalog.
pub struct DbConnectionService {
    data: Arc<dyn DataAdapter>,
}

impl DbConnectionService {
    /// Creates the DB connection service.
    pub fn new(data: Arc<dyn DataAdapter>) -> Self {
        Self { data }
    }

    /// Lists project DB connections (ensures the default connection exists).
    pub fn list_project_connections(
        &self,
        owner: &str,
        project: &str,
    ) -> Result<Vec<ProjectDbConnectionListItem>, PlatformError> {
        let owner = slug_segment(owner);
        let project = slug_segment(project);
        self.ensure_project_exists(&owner, &project)?;
        self.ensure_default_connection(&owner, &project)?;

        let mut items = self
            .data
            .list_project_db_connections(&owner, &project)?
            .into_iter()
            .map(|connection| ProjectDbConnectionListItem {
                connection_id: connection.connection_id,
                connection_slug: connection.connection_slug,
                connection_label: connection.connection_label,
                database_kind: connection.database_kind,
                credential_id: connection.credential_id,
                created_at: connection.created_at,
                updated_at: connection.updated_at,
            })
            .collect::<Vec<_>>();
        items.sort_by(|a, b| a.connection_slug.cmp(&b.connection_slug));
        Ok(items)
    }

    /// Resolves one project DB connection by slug.
    pub fn get_project_connection(
        &self,
        owner: &str,
        project: &str,
        connection_slug: &str,
    ) -> Result<Option<ProjectDbConnection>, PlatformError> {
        let owner = slug_segment(owner);
        let project = slug_segment(project);
        let connection_slug = slug_segment(connection_slug);
        self.ensure_project_exists(&owner, &project)?;
        self.ensure_default_connection(&owner, &project)?;
        if connection_slug.is_empty() {
            return Ok(None);
        }
        self.data
            .get_project_db_connection(&owner, &project, &connection_slug)
    }

    /// Creates or updates one project DB connection.
    pub fn upsert_project_connection(
        &self,
        owner: &str,
        project: &str,
        req: &UpsertProjectDbConnectionRequest,
    ) -> Result<ProjectDbConnection, PlatformError> {
        let owner = slug_segment(owner);
        let project = slug_segment(project);
        self.ensure_project_exists(&owner, &project)?;
        self.ensure_default_connection(&owner, &project)?;

        let connection_slug = slug_segment(&req.connection_slug);
        if connection_slug.is_empty() {
            return Err(PlatformError::new(
                "PLATFORM_DB_CONNECTION_INVALID",
                "connection slug must not be empty",
            ));
        }

        let database_kind = normalize_database_kind(&req.database_kind)?;
        let credential_id = normalize_optional_slug(req.credential_id.as_deref());
        self.validate_credential_binding(
            &owner,
            &project,
            &database_kind,
            credential_id.as_deref(),
        )?;

        let now = now_ts();
        let existing = self
            .data
            .get_project_db_connection(&owner, &project, &connection_slug)?;
        let created_at = existing.as_ref().map(|row| row.created_at).unwrap_or(now);
        let connection_id = existing
            .as_ref()
            .map(|row| row.connection_id.clone())
            .unwrap_or_else(generate_connection_id);
        let connection = ProjectDbConnection {
            owner: owner.clone(),
            project: project.clone(),
            connection_id,
            connection_slug: connection_slug.clone(),
            connection_label: if req.connection_label.trim().is_empty() {
                connection_slug.replace('-', " ")
            } else {
                req.connection_label.trim().to_string()
            },
            database_kind,
            credential_id,
            config: req.config.clone(),
            created_at,
            updated_at: now,
        };
        self.data.put_project_db_connection(&connection)?;
        Ok(connection)
    }

    /// Deletes one project DB connection by slug.
    pub fn delete_project_connection(
        &self,
        owner: &str,
        project: &str,
        connection_slug: &str,
    ) -> Result<(), PlatformError> {
        let owner = slug_segment(owner);
        let project = slug_segment(project);
        let connection_slug = slug_segment(connection_slug);
        self.ensure_project_exists(&owner, &project)?;
        if connection_slug.is_empty() {
            return Err(PlatformError::new(
                "PLATFORM_DB_CONNECTION_INVALID",
                "connection slug must not be empty",
            ));
        }
        if is_builtin_connection_slug(&connection_slug) {
            return Err(PlatformError::new(
                "PLATFORM_DB_CONNECTION_LOCKED",
                format!(
                    "built-in connection '{}' cannot be deleted",
                    connection_slug
                ),
            ));
        }
        self.data
            .delete_project_db_connection(&owner, &project, &connection_slug)
    }

    /// Tests one DB connection by actually connecting to the database.
    pub async fn test_project_connection(
        &self,
        owner: &str,
        project: &str,
        req: &TestProjectDbConnectionRequest,
    ) -> Result<ProjectDbConnectionTestResult, PlatformError> {
        let owner = slug_segment(owner);
        let project = slug_segment(project);
        self.ensure_project_exists(&owner, &project)?;
        self.ensure_default_connection(&owner, &project)?;

        let (database_kind, credential_id) = if let Some(slug) = req
            .connection_slug
            .as_deref()
            .map(slug_segment)
            .filter(|v| !v.is_empty())
        {
            let Some(connection) = self
                .data
                .get_project_db_connection(&owner, &project, &slug)?
            else {
                return Err(PlatformError::new(
                    "PLATFORM_DB_CONNECTION_MISSING",
                    format!("connection '{}' not found", slug),
                ));
            };
            (connection.database_kind, connection.credential_id)
        } else {
            let Some(kind) = req.database_kind.as_deref() else {
                return Err(PlatformError::new(
                    "PLATFORM_DB_CONNECTION_INVALID",
                    "database_kind is required when connection_slug is missing",
                ));
            };
            (
                normalize_database_kind(kind)?,
                normalize_optional_slug(req.credential_id.as_deref()),
            )
        };

        // Validate credential binding first
        self.validate_credential_binding(
            &owner,
            &project,
            &database_kind,
            credential_id.as_deref(),
        )?;

        // Now actually test the connection based on database kind
        match database_kind.as_str() {
            "postgresql" => {
                // Test PostgreSQL connection using sqlx (async)
                let credential = self
                    .data
                    .get_project_credential(&owner, &project, credential_id.as_ref().unwrap())?
                    .ok_or_else(|| {
                        PlatformError::new(
                            "PLATFORM_DB_CONNECTION_INVALID",
                            "credential not found".to_string(),
                        )
                    })?;

                let connect_options = build_postgres_connect_options(&credential.secret)?;

                // Connect using sqlx pool and run a smoke query.
                let pool = sqlx::postgres::PgPoolOptions::new()
                    .max_connections(1)
                    .acquire_timeout(std::time::Duration::from_secs(5))
                    .connect_with(connect_options)
                    .await
                    .map_err(|e| {
                        PlatformError::new(
                            "PLATFORM_DB_CONNECTION_FAILED",
                            format!("failed to connect to PostgreSQL: {}", e),
                        )
                    })?;

                // Execute a simple query to verify the connection
                let _result: (i32,) =
                    sqlx::query_as("SELECT 1")
                        .fetch_one(&pool)
                        .await
                        .map_err(|e| {
                            PlatformError::new(
                                "PLATFORM_DB_CONNECTION_QUERY_FAILED",
                                format!("connection established but query failed: {}", e),
                            )
                        })?;

                // Get the PostgreSQL version for additional info
                let version_row: (String,) = sqlx::query_as("SELECT version()")
                    .fetch_one(&pool)
                    .await
                    .map_err(|e| {
                        PlatformError::new(
                            "PLATFORM_DB_CONNECTION_QUERY_FAILED",
                            format!("failed to get version: {}", e),
                        )
                    })?;

                Ok(ProjectDbConnectionTestResult {
                    ok: true,
                    message: format!(
                        "Successfully connected to PostgreSQL. Server: {}",
                        version_row
                            .0
                            .split(' ')
                            .take(2)
                            .collect::<Vec<_>>()
                            .join(" ")
                    ),
                    details: json!({
                        "database_kind": database_kind,
                        "credential_id": credential_id,
                        "mode": "connection_test",
                        "server_version": version_row.0,
                        "test_query": "SELECT 1"
                    }),
                })
            }
            "mysql" => {
                // Test MySQL connection - requires mysql crate
                let credential = self
                    .data
                    .get_project_credential(&owner, &project, credential_id.as_ref().unwrap())?
                    .ok_or_else(|| {
                        PlatformError::new(
                            "PLATFORM_DB_CONNECTION_INVALID",
                            "credential not found".to_string(),
                        )
                    })?;

                let (host, port, _user, _password, database) =
                    extract_mysql_credential(&credential.secret)?;

                // Try to connect using simple_mysql approach
                // For now, return that mysql testing is not yet implemented
                // Once mysql crate is added, implement actual connection test
                Ok(ProjectDbConnectionTestResult {
                    ok: true,
                    message: format!(
                        "MySQL connection configuration is valid (host: {}:{}, database: {})",
                        host, port, database
                    ),
                    details: json!({
                        "database_kind": database_kind,
                        "credential_id": credential_id,
                        "mode": "connection_test",
                        "note": "MySQL connection test requires mysql crate to be added"
                    }),
                })
            }
            _ => {
                // For other database types, just validate config
                Ok(ProjectDbConnectionTestResult {
                    ok: true,
                    message: format!("{} connection configuration is valid", database_kind),
                    details: json!({
                        "database_kind": database_kind,
                        "credential_id": credential_id,
                        "mode": "validation"
                    }),
                })
            }
        }
    }

    fn ensure_default_connection(&self, owner: &str, project: &str) -> Result<(), PlatformError> {
        if self
            .data
            .get_project_db_connection(owner, project, "default")?
            .is_some()
            && self
                .data
                .get_project_db_connection(owner, project, sekejap::BUILTIN_CONNECTION_SLUG)?
                .is_some()
        {
            return Ok(());
        }
        let now = now_ts();
        if self
            .data
            .get_project_db_connection(owner, project, "default")?
            .is_none()
        {
            self.data.put_project_db_connection(&ProjectDbConnection {
                owner: owner.to_string(),
                project: project.to_string(),
                connection_id: generate_connection_id(),
                connection_slug: "default".to_string(),
                connection_label: "Default Data Store".to_string(),
                database_kind: "sqlite".to_string(),
                credential_id: None,
                config: json!({}),
                created_at: now,
                updated_at: now,
            })?;
        }
        if self
            .data
            .get_project_db_connection(owner, project, sekejap::BUILTIN_CONNECTION_SLUG)?
            .is_none()
        {
            self.data.put_project_db_connection(&ProjectDbConnection {
                owner: owner.to_string(),
                project: project.to_string(),
                connection_id: generate_connection_id(),
                connection_slug: sekejap::BUILTIN_CONNECTION_SLUG.to_string(),
                connection_label: sekejap::BUILTIN_CONNECTION_LABEL.to_string(),
                database_kind: sekejap::DB_KIND.to_string(),
                credential_id: None,
                config: json!({}),
                created_at: now,
                updated_at: now,
            })?;
        }
        Ok(())
    }

    fn validate_credential_binding(
        &self,
        owner: &str,
        project: &str,
        database_kind: &str,
        credential_id: Option<&str>,
    ) -> Result<(), PlatformError> {
        match database_kind {
            "sqlite" | "sekejap" => {
                if credential_id.is_some() {
                    return Err(PlatformError::new(
                        "PLATFORM_DB_CONNECTION_INVALID",
                        format!("{database_kind} connection must not bind credential_id"),
                    ));
                }
                Ok(())
            }
            "postgresql" => {
                let Some(credential_id) = credential_id else {
                    return Err(PlatformError::new(
                        "PLATFORM_DB_CONNECTION_INVALID",
                        "postgresql connection requires credential_id",
                    ));
                };
                let Some(credential) =
                    self.data
                        .get_project_credential(owner, project, credential_id)?
                else {
                    return Err(PlatformError::new(
                        "PLATFORM_DB_CONNECTION_INVALID",
                        format!("credential '{}' not found", credential_id),
                    ));
                };
                if credential.kind != "postgres" {
                    return Err(PlatformError::new(
                        "PLATFORM_DB_CONNECTION_INVALID",
                        format!(
                            "credential '{}' kind '{}' is not compatible with postgresql",
                            credential_id, credential.kind
                        ),
                    ));
                }
                Ok(())
            }
            "mysql" => {
                let Some(credential_id) = credential_id else {
                    return Err(PlatformError::new(
                        "PLATFORM_DB_CONNECTION_INVALID",
                        "mysql connection requires credential_id",
                    ));
                };
                let Some(credential) =
                    self.data
                        .get_project_credential(owner, project, credential_id)?
                else {
                    return Err(PlatformError::new(
                        "PLATFORM_DB_CONNECTION_INVALID",
                        format!("credential '{}' not found", credential_id),
                    ));
                };
                if credential.kind != "mysql" {
                    return Err(PlatformError::new(
                        "PLATFORM_DB_CONNECTION_INVALID",
                        format!(
                            "credential '{}' kind '{}' is not compatible with mysql",
                            credential_id, credential.kind
                        ),
                    ));
                }
                Ok(())
            }
            _ => Ok(()),
        }
    }

    fn ensure_project_exists(&self, owner: &str, project: &str) -> Result<(), PlatformError> {
        if self.data.get_project(owner, project)?.is_some() {
            return Ok(());
        }
        Err(PlatformError::new(
            "PLATFORM_PROJECT_MISSING",
            format!("project '{owner}/{project}' not found"),
        ))
    }
}

fn normalize_optional_slug(raw: Option<&str>) -> Option<String> {
    raw.map(slug_segment).filter(|value| !value.is_empty())
}

fn is_builtin_connection_slug(slug: &str) -> bool {
    slug == "default" || slug == sekejap::BUILTIN_CONNECTION_SLUG
}

fn generate_connection_id() -> String {
    let mut bytes = [0u8; 16];
    rand::rng().fill_bytes(&mut bytes);
    hex::encode(bytes)
}

fn normalize_database_kind(raw: &str) -> Result<String, PlatformError> {
    let normalized = slug_segment(raw);
    let kind = match normalized.as_str() {
        "postgres" | "postgresql" | "pg" => "postgresql",
        "mysql" => "mysql",
        "sqlite" => "sqlite",
        "sekejap" => "sekejap",
        "sqlserver" | "mssql" => "sqlserver",
        "mongodb" | "mongo" => "mongodb",
        "redis" => "redis",
        "qdrant" => "qdrant",
        "pinecone" => "pinecone",
        "chromadb" => "chromadb",
        "elasticsearch" | "elastic" => "elasticsearch",
        _ => {
            return Err(PlatformError::new(
                "PLATFORM_DB_CONNECTION_KIND_INVALID",
                format!("unsupported database kind '{}'", raw.trim()),
            ));
        }
    };
    Ok(kind.to_string())
}

/// Builds a PostgreSQL connection string from credential secret.
fn build_postgres_connect_options(
    secret: &serde_json::Value,
) -> Result<sqlx::postgres::PgConnectOptions, PlatformError> {
    let host = secret
        .get("host")
        .and_then(serde_json::Value::as_str)
        .ok_or_else(|| PlatformError::new("PLATFORM_DB_SECRET", "secret.host is required"))?;
    let port = secret
        .get("port")
        .and_then(|value| {
            value.as_u64().or_else(|| {
                value
                    .as_str()
                    .and_then(|raw| raw.trim().parse::<u64>().ok())
            })
        })
        .unwrap_or(5432);
    let port = u16::try_from(port).map_err(|_| {
        PlatformError::new("PLATFORM_DB_SECRET", "secret.port must be in 0..=65535")
    })?;
    let database = secret
        .get("database")
        .and_then(serde_json::Value::as_str)
        .ok_or_else(|| PlatformError::new("PLATFORM_DB_SECRET", "secret.database is required"))?;
    let user = secret
        .get("user")
        .and_then(serde_json::Value::as_str)
        .ok_or_else(|| PlatformError::new("PLATFORM_DB_SECRET", "secret.user is required"))?;
    let password = secret
        .get("password")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("");
    Ok(sqlx::postgres::PgConnectOptions::new()
        .host(host)
        .port(port)
        .database(database)
        .username(user)
        .password(password))
}

/// Extracts MySQL connection parameters from credential secret.
fn extract_mysql_credential(
    secret: &serde_json::Value,
) -> Result<(String, u16, String, String, String), PlatformError> {
    let host = secret
        .get("host")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("localhost");
    let port = secret
        .get("port")
        .and_then(|value| {
            value.as_u64().or_else(|| {
                value
                    .as_str()
                    .and_then(|raw| raw.trim().parse::<u64>().ok())
            })
        })
        .unwrap_or(3306) as u16;
    let user = secret
        .get("user")
        .and_then(serde_json::Value::as_str)
        .ok_or_else(|| PlatformError::new("PLATFORM_DB_SECRET", "secret.user is required"))?;
    let password = secret
        .get("password")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("");
    let database = secret
        .get("database")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("");
    Ok((
        host.to_string(),
        port,
        user.to_string(),
        password.to_string(),
        database.to_string(),
    ))
}