jammi-db 0.26.2

Vector database, SQL federation, mutable companion tables, and trigger broker for Jammi AI
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
//! Per-cloud connection configuration.
//!
//! Each cloud backend has its own typed struct so missing credentials
//! surface as a Rust type error (or a [`StorageError::DriverInit`] at
//! construction time) rather than a stringly-typed `HashMap` lookup that
//! silently returns `None`.
//!
//! Each config type exposes a `validate()` method that catches partial
//! credential sets at config-load time — e.g. an `access_key_id` without
//! a `secret_access_key` — before the SDK surfaces the same error
//! deeper inside a request.
//!
//! [`StorageError::DriverInit`]: super::error::StorageError::DriverInit

use serde::{Deserialize, Serialize};

use super::error::StorageError;
use super::url::Scheme;

/// AWS S3 (or any S3-compatible) connection details.
///
/// Used to build the S3 driver via [`crate::storage::builder::build_object_store`].
/// Field names mirror the canonical AWS SDK env var conventions so a
/// caller can populate from `std::env::var` 1:1.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct S3Config {
    /// AWS region (e.g. `"us-east-1"`).
    pub region: Option<String>,
    /// Custom endpoint URL — for MinIO / LocalStack / S3-compatible services.
    pub endpoint: Option<String>,
    /// Access key ID. When unset, the SDK's default credential chain is used
    /// (env vars, instance profile, EKS IRSA token, etc).
    pub access_key_id: Option<String>,
    /// Secret access key paired with [`Self::access_key_id`].
    pub secret_access_key: Option<String>,
    /// Optional session token for temporary credentials (STS, SSO).
    pub session_token: Option<String>,
    /// Whether to allow plain HTTP (only used against test endpoints).
    /// Defaults to `false` so production deployments fail closed.
    #[serde(default)]
    pub allow_http: bool,
}

/// Google Cloud Storage connection details.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GcsConfig {
    /// Inline service-account JSON. When unset, the GCS driver falls back
    /// to Application Default Credentials (`GOOGLE_APPLICATION_CREDENTIALS`,
    /// Workload Identity, gcloud user creds).
    pub service_account_json: Option<String>,
    /// Path to a service-account JSON file. Alternative to
    /// [`Self::service_account_json`] for callers who want to keep the file
    /// out of the catalog row.
    pub service_account_path: Option<String>,
}

/// Azure Blob Storage connection details.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AzureConfig {
    /// Storage account name (e.g. `"myaccount"` for
    /// `myaccount.blob.core.windows.net`).
    pub account_name: Option<String>,
    /// Account access key. Mutually exclusive with [`Self::sas_token`].
    pub account_key: Option<String>,
    /// Shared-access-signature token.
    pub sas_token: Option<String>,
    /// Tenant id for OAuth / Managed Identity auth.
    pub tenant_id: Option<String>,
    /// Client id for OAuth.
    pub client_id: Option<String>,
    /// Client secret paired with [`Self::client_id`].
    pub client_secret: Option<String>,
}

/// Cloudflare R2 connection details.
///
/// R2 speaks the S3 API, so the driver is the S3 driver underneath. This
/// config exists so a deployer supplies only the R2-shaped inputs and the
/// engine derives the two S3 quirks R2 imposes — an account-scoped endpoint
/// and `region = "auto"` — rather than the deployer hand-rolling an
/// [`S3Config`] and risking either one.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct R2Config {
    /// Cloudflare account id. The endpoint is derived as
    /// `https://{account_id}.r2.cloudflarestorage.com` unless
    /// [`Self::endpoint`] overrides it.
    pub account_id: Option<String>,
    /// Explicit endpoint override — an R2 custom domain, or a test endpoint.
    /// Takes precedence over the account-derived endpoint.
    pub endpoint: Option<String>,
    /// R2 access key id (an S3-style token minted in the R2 dashboard / API).
    /// When unset, the S3 SDK's default credential chain applies.
    pub access_key_id: Option<String>,
    /// Secret access key paired with [`Self::access_key_id`].
    pub secret_access_key: Option<String>,
    /// Allow plain HTTP — only for test endpoints. Defaults `false` (fail closed).
    #[serde(default)]
    pub allow_http: bool,
}

/// Tagged union of per-cloud configuration. The variant selects which
/// driver the [`crate::storage::builder`] will construct.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum CloudConfig {
    /// AWS S3 (or S3-compatible) — see [`S3Config`].
    S3(S3Config),
    /// Google Cloud Storage — see [`GcsConfig`].
    Gcs(GcsConfig),
    /// Azure Blob — see [`AzureConfig`].
    Azure(AzureConfig),
    /// Cloudflare R2 — see [`R2Config`].
    R2(R2Config),
}

impl CloudConfig {
    /// Validate the variant's credential set at config-load time. Catches
    /// partial-credential mistakes (e.g. an `access_key_id` without its
    /// `secret_access_key`) before the SDK surfaces the same problem deep
    /// inside an I/O call.
    pub fn validate(&self) -> Result<(), StorageError> {
        match self {
            Self::S3(c) => c.validate(),
            Self::Gcs(c) => c.validate(),
            Self::Azure(c) => c.validate(),
            Self::R2(c) => c.validate(),
        }
    }
}

impl S3Config {
    /// Reject partial explicit credentials. Leaving everything unset is
    /// allowed (and means "fall back to the SDK's default chain"); pairing
    /// `access_key_id` with a missing `secret_access_key` (or vice-versa)
    /// is rejected up front. A `session_token` without an `access_key_id`
    /// is rejected because STS-style credentials require all three.
    pub fn validate(&self) -> Result<(), StorageError> {
        match (
            self.access_key_id.as_deref(),
            self.secret_access_key.as_deref(),
        ) {
            (Some(_), None) => Err(StorageError::DriverInit {
                scheme: Scheme::S3,
                reason: "access_key_id is set but secret_access_key is missing".into(),
            }),
            (None, Some(_)) => Err(StorageError::DriverInit {
                scheme: Scheme::S3,
                reason: "secret_access_key is set but access_key_id is missing".into(),
            }),
            _ => {
                if self.session_token.is_some() && self.access_key_id.is_none() {
                    return Err(StorageError::DriverInit {
                        scheme: Scheme::S3,
                        reason: "session_token requires access_key_id and secret_access_key".into(),
                    });
                }
                Ok(())
            }
        }
    }
}

impl GcsConfig {
    /// `service_account_json` and `service_account_path` are mutually
    /// exclusive — supplying both is ambiguous about which credential the
    /// driver should honour. Either-or-neither (neither => ADC) is valid.
    pub fn validate(&self) -> Result<(), StorageError> {
        if self.service_account_json.is_some() && self.service_account_path.is_some() {
            return Err(StorageError::DriverInit {
                scheme: Scheme::Gcs,
                reason: "service_account_json and service_account_path are mutually exclusive"
                    .into(),
            });
        }
        Ok(())
    }
}

impl AzureConfig {
    /// `account_name` is required whenever any other Azure field is set —
    /// without it the SDK has no host to talk to. `account_key` and
    /// `sas_token` are mutually exclusive (the SDK uses different signing
    /// paths for each). OAuth fields (`tenant_id`/`client_id`/`client_secret`)
    /// must come as a complete triple or not at all.
    pub fn validate(&self) -> Result<(), StorageError> {
        let any_set = self.account_key.is_some()
            || self.sas_token.is_some()
            || self.tenant_id.is_some()
            || self.client_id.is_some()
            || self.client_secret.is_some();
        if any_set && self.account_name.is_none() {
            return Err(StorageError::DriverInit {
                scheme: Scheme::Azure,
                reason: "account_name is required when any other Azure credential field is set"
                    .into(),
            });
        }
        if self.account_key.is_some() && self.sas_token.is_some() {
            return Err(StorageError::DriverInit {
                scheme: Scheme::Azure,
                reason: "account_key and sas_token are mutually exclusive".into(),
            });
        }
        let oauth_set = [
            self.tenant_id.is_some(),
            self.client_id.is_some(),
            self.client_secret.is_some(),
        ];
        let oauth_count = oauth_set.iter().filter(|b| **b).count();
        if oauth_count != 0 && oauth_count != oauth_set.len() {
            return Err(StorageError::DriverInit {
                scheme: Scheme::Azure,
                reason: "tenant_id, client_id, and client_secret must all be set together".into(),
            });
        }
        Ok(())
    }
}

impl R2Config {
    /// The S3 endpoint the R2 driver talks to: the explicit `endpoint` override
    /// if set, else the account-scoped `https://{account_id}.r2.cloudflarestorage.com`.
    /// `None` when neither is available — a config error caught by [`Self::validate`].
    pub fn resolved_endpoint(&self) -> Option<String> {
        self.endpoint.clone().or_else(|| {
            self.account_id
                .as_ref()
                .map(|a| format!("https://{a}.r2.cloudflarestorage.com"))
        })
    }

    /// Require an addressable endpoint (an `account_id` or an explicit `endpoint`),
    /// and reject a half-set credential pair — the same fail-closed discipline the
    /// other backends apply.
    pub fn validate(&self) -> Result<(), StorageError> {
        if self.resolved_endpoint().is_none() {
            return Err(StorageError::DriverInit {
                scheme: Scheme::R2,
                reason: "R2 requires either account_id or an explicit endpoint".into(),
            });
        }
        match (
            self.access_key_id.as_deref(),
            self.secret_access_key.as_deref(),
        ) {
            (Some(_), None) => Err(StorageError::DriverInit {
                scheme: Scheme::R2,
                reason: "access_key_id is set but secret_access_key is missing".into(),
            }),
            (None, Some(_)) => Err(StorageError::DriverInit {
                scheme: Scheme::R2,
                reason: "secret_access_key is set but access_key_id is missing".into(),
            }),
            _ => Ok(()),
        }
    }
}

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

    #[test]
    fn s3_validate_rejects_half_credentials() {
        let bad = S3Config {
            access_key_id: Some("AKIA…".into()),
            ..Default::default()
        };
        assert!(matches!(
            bad.validate(),
            Err(StorageError::DriverInit {
                scheme: Scheme::S3,
                ..
            })
        ));

        let also_bad = S3Config {
            secret_access_key: Some("xyz".into()),
            ..Default::default()
        };
        assert!(matches!(
            also_bad.validate(),
            Err(StorageError::DriverInit {
                scheme: Scheme::S3,
                ..
            })
        ));
    }

    #[test]
    fn s3_validate_rejects_orphan_session_token() {
        let bad = S3Config {
            session_token: Some("FwoGZ…".into()),
            ..Default::default()
        };
        assert!(matches!(
            bad.validate(),
            Err(StorageError::DriverInit {
                scheme: Scheme::S3,
                ..
            })
        ));
    }

    #[test]
    fn s3_validate_accepts_default_chain() {
        assert!(S3Config::default().validate().is_ok());
    }

    #[test]
    fn s3_validate_accepts_full_credentials() {
        let good = S3Config {
            access_key_id: Some("AKIA…".into()),
            secret_access_key: Some("xyz".into()),
            ..Default::default()
        };
        assert!(good.validate().is_ok());
    }

    #[test]
    fn r2_derives_endpoint_from_account_id() {
        let cfg = R2Config {
            account_id: Some("abc123".into()),
            ..Default::default()
        };
        assert_eq!(
            cfg.resolved_endpoint().as_deref(),
            Some("https://abc123.r2.cloudflarestorage.com")
        );
    }

    #[test]
    fn r2_explicit_endpoint_overrides_account_id() {
        let cfg = R2Config {
            account_id: Some("abc123".into()),
            endpoint: Some("https://files.example.com".into()),
            ..Default::default()
        };
        assert_eq!(
            cfg.resolved_endpoint().as_deref(),
            Some("https://files.example.com")
        );
    }

    #[test]
    fn r2_validate_requires_account_or_endpoint() {
        assert!(matches!(
            R2Config::default().validate(),
            Err(StorageError::DriverInit {
                scheme: Scheme::R2,
                ..
            })
        ));
    }

    #[test]
    fn r2_validate_rejects_half_credentials() {
        let bad = R2Config {
            account_id: Some("abc".into()),
            access_key_id: Some("k".into()),
            ..Default::default()
        };
        assert!(matches!(
            bad.validate(),
            Err(StorageError::DriverInit {
                scheme: Scheme::R2,
                ..
            })
        ));
    }

    #[test]
    fn r2_validate_accepts_account_plus_full_credentials() {
        let good = R2Config {
            account_id: Some("abc".into()),
            access_key_id: Some("k".into()),
            secret_access_key: Some("s".into()),
            ..Default::default()
        };
        assert!(good.validate().is_ok());
    }

    #[test]
    fn gcs_validate_rejects_both_json_and_path() {
        let bad = GcsConfig {
            service_account_json: Some("{...}".into()),
            service_account_path: Some("/key.json".into()),
        };
        assert!(matches!(
            bad.validate(),
            Err(StorageError::DriverInit {
                scheme: Scheme::Gcs,
                ..
            })
        ));
    }

    #[test]
    fn gcs_validate_accepts_default_or_one_source() {
        assert!(GcsConfig::default().validate().is_ok());
        assert!(GcsConfig {
            service_account_json: Some("{...}".into()),
            ..Default::default()
        }
        .validate()
        .is_ok());
    }

    #[test]
    fn azure_validate_rejects_missing_account_name() {
        let bad = AzureConfig {
            account_key: Some("k".into()),
            ..Default::default()
        };
        assert!(matches!(
            bad.validate(),
            Err(StorageError::DriverInit {
                scheme: Scheme::Azure,
                ..
            })
        ));
    }

    #[test]
    fn azure_validate_rejects_key_and_sas_together() {
        let bad = AzureConfig {
            account_name: Some("acct".into()),
            account_key: Some("k".into()),
            sas_token: Some("?sv=…".into()),
            ..Default::default()
        };
        assert!(matches!(
            bad.validate(),
            Err(StorageError::DriverInit {
                scheme: Scheme::Azure,
                ..
            })
        ));
    }

    #[test]
    fn azure_validate_rejects_partial_oauth() {
        let bad = AzureConfig {
            account_name: Some("acct".into()),
            tenant_id: Some("t".into()),
            client_id: Some("c".into()),
            ..Default::default()
        };
        assert!(matches!(
            bad.validate(),
            Err(StorageError::DriverInit {
                scheme: Scheme::Azure,
                ..
            })
        ));
    }

    #[test]
    fn azure_validate_accepts_complete_oauth_triple() {
        let good = AzureConfig {
            account_name: Some("acct".into()),
            tenant_id: Some("t".into()),
            client_id: Some("c".into()),
            client_secret: Some("s".into()),
            ..Default::default()
        };
        assert!(good.validate().is_ok());
    }
}