hazine 0.2.0

Runs a DuckDB Quack server for DuckLake on localhost, reached through an SSH tunnel.
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
//! The files `hazine setup` writes, rendered from embedded templates.
//!
//! Everything here is pure: no file system, no processes.

use std::collections::HashMap;
use std::net::SocketAddr;

use crate::Error;

const INIT_SQL: &str = include_str!("../../templates/init.sql");
const SERVE_SQL: &str = include_str!("../../templates/serve.sql");
const ENV_FILE: &str = include_str!("../../templates/hazine.env");
const UNIT_FILE: &str = include_str!("../../templates/hazine.service");

/// How Postgres connections negotiate TLS (libpq's `PGSSLMODE`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum SslMode {
    Disable,
    Allow,
    Prefer,
    Require,
    VerifyCa,
    VerifyFull,
}

impl SslMode {
    /// The value libpq expects.
    pub fn as_str(self) -> &'static str {
        match self {
            SslMode::Disable => "disable",
            SslMode::Allow => "allow",
            SslMode::Prefer => "prefer",
            SslMode::Require => "require",
            SslMode::VerifyCa => "verify-ca",
            SslMode::VerifyFull => "verify-full",
        }
    }
}

/// How S3 object URLs are built.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum UrlStyle {
    /// `https://bucket.endpoint/key` (AWS and most providers).
    Vhost,
    /// `https://endpoint/bucket/key` (MinIO, SeaweedFS and others).
    Path,
}

impl UrlStyle {
    fn as_str(self) -> &'static str {
        match self {
            UrlStyle::Vhost => "vhost",
            UrlStyle::Path => "path",
        }
    }
}

/// The Postgres server holding the DuckLake catalog. The password is a secret
/// and lives in the env file, not here.
#[derive(Debug, Clone)]
pub struct Catalog {
    pub host: String,
    pub port: u16,
    pub database: String,
    pub user: String,
    pub sslmode: SslMode,
}

/// The S3-compatible object storage holding the DuckLake data. The keys are
/// secrets and live in the env file, not here.
#[derive(Debug, Clone)]
pub struct Storage {
    /// `s3://bucket/prefix/`
    pub data_path: String,
    /// `host[:port]`; AWS when unset.
    pub endpoint: Option<String>,
    pub region: String,
    pub url_style: UrlStyle,
    pub use_ssl: bool,
}

/// What DuckDB may use.
#[derive(Debug, Clone)]
pub struct Resources {
    pub threads: usize,
    /// DuckDB's `memory_limit`, e.g. `100GB`.
    pub memory_limit: String,
    /// systemd's `MemoryMax`, e.g. `112G`.
    pub memory_max: String,
}

/// The values of `/etc/hazine/hazine.env`.
#[derive(Clone)]
pub struct Secrets {
    pub quack_token: String,
    pub pg_password: String,
    pub s3_key_id: String,
    pub s3_secret: String,
}

impl std::fmt::Debug for Secrets {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Secrets([REDACTED])")
    }
}

/// The names of the env file's secrets, as hazine serve sees them.
pub const SECRET_ENVS: [&str; 4] = [
    "QUACK_TOKEN",
    "PGPASSWORD",
    "HAZINE_S3_KEY_ID",
    "HAZINE_S3_SECRET",
];

/// The main database hazine serve opens: the DuckLake catalog in the Postgres
/// that the `PG*` variables describe.
pub const DATABASE: &str = "ducklake:postgres:";

/// `s3://bucket/prefix` checked and given a trailing slash, as DuckLake wants.
pub fn data_path(path: &str) -> Result<String, Error> {
    let invalid = |reason: &str| Error::InvalidSetting {
        name: "data path",
        reason: format!("{path:?} {reason}"),
    };
    let rest = path
        .strip_prefix("s3://")
        .ok_or_else(|| invalid("does not start with s3://"))?;
    if rest.split('/').next().unwrap_or_default().is_empty() {
        return Err(invalid("has no bucket"));
    }
    if path.chars().any(char::is_control) {
        return Err(invalid("contains control characters"));
    }
    Ok(if path.ends_with('/') {
        path.to_string()
    } else {
        format!("{path}/")
    })
}

/// The bucket part of a checked data path, as the S3 secret's scope.
fn scope(data_path: &str) -> &str {
    let rest = &data_path["s3://".len()..];
    let bucket = rest.split('/').next().unwrap_or_default();
    &data_path[.."s3://".len() + bucket.len()]
}

/// `value` as a SQL string literal body: single quotes doubled.
fn sql_str(value: &str) -> String {
    value.replace('\'', "''")
}

/// `value` single-quoted for a systemd `EnvironmentFile`, which takes it
/// verbatim. A value with a single quote or a control character cannot be
/// written that way and is refused.
fn env_value(name: &'static str, value: &str) -> Result<String, Error> {
    if value.contains('\'') || value.chars().any(char::is_control) {
        return Err(Error::InvalidSetting {
            name,
            reason: "must not contain single quotes or control characters".into(),
        });
    }
    Ok(format!("'{value}'"))
}

/// The variables in an env file `hazine setup` wrote, quotes removed.
pub fn parse_env(content: &str) -> HashMap<String, String> {
    content
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
        .filter_map(|line| line.split_once('='))
        .map(|(name, value)| {
            let value = value.trim();
            let unquoted = ['\'', '"']
                .iter()
                .find_map(|&q| value.strip_prefix(q)?.strip_suffix(q))
                .unwrap_or(value);
            (name.trim().to_string(), unquoted.to_string())
        })
        .collect()
}

/// `template` with each `{{name}}` replaced by its value.
fn fill(template: &str, values: &[(&str, &str)]) -> String {
    values
        .iter()
        .fold(template.to_string(), |text, (name, value)| {
            text.replace(&format!("{{{{{name}}}}}"), value)
        })
}

/// The `CREATE SECRET` for the data's object storage; the keys come from the
/// environment.
fn data_secret(storage: &Storage) -> String {
    let endpoint = storage
        .endpoint
        .as_deref()
        .map(|endpoint| format!("    ENDPOINT '{}',\n", sql_str(endpoint)))
        .unwrap_or_default();
    format!(
        "CREATE SECRET hazine_data (\n    \
         TYPE s3,\n    \
         SCOPE '{scope}',\n    \
         KEY_ID getenv('HAZINE_S3_KEY_ID'),\n    \
         SECRET getenv('HAZINE_S3_SECRET'),\n\
         {endpoint}    \
         REGION '{region}',\n    \
         URL_STYLE '{url_style}',\n    \
         USE_SSL {use_ssl}\n\
         );",
        scope = sql_str(scope(&storage.data_path)),
        region = sql_str(&storage.region),
        url_style = storage.url_style.as_str(),
        use_ssl = storage.use_ssl,
    )
}

/// `init.sql`.
pub fn init_sql(storage: &Storage, resources: &Resources) -> String {
    let body = fill(
        INIT_SQL,
        &[
            ("threads", &resources.threads.to_string()),
            ("memory_limit", &sql_str(&resources.memory_limit)),
            ("data_secret", &data_secret(storage)),
        ],
    );
    format!("{body}{SERVE_SQL}")
}

/// SQL that attaches the lake the way hazine serve opens it, and lists the
/// data path: setup runs it to find bad settings before the service starts.
/// The first time, it also creates the DuckLake catalog with its data path.
pub fn check_sql(storage: &Storage) -> String {
    format!(
        "LOAD ducklake;\nLOAD postgres;\nLOAD httpfs;\n{secret}\n\
         ATTACH '{DATABASE}' AS lake (DATA_PATH '{data_path}');\n\
         SELECT count(*) AS files FROM glob('{data_path}*');\n",
        secret = data_secret(storage),
        data_path = sql_str(&storage.data_path),
    )
}

/// `hazine.env`.
pub fn env_file(
    secrets: &Secrets,
    catalog: &Catalog,
    quack_addr: SocketAddr,
) -> Result<String, Error> {
    Ok(fill(
        ENV_FILE,
        &[
            (
                "quack_token",
                &env_value("Quack token", &secrets.quack_token)?,
            ),
            ("quack_addr", &quack_addr.to_string()),
            ("pg_host", &env_value("Postgres host", &catalog.host)?),
            ("pg_port", &catalog.port.to_string()),
            (
                "pg_database",
                &env_value("Postgres database", &catalog.database)?,
            ),
            ("pg_user", &env_value("Postgres user", &catalog.user)?),
            (
                "pg_password",
                &env_value("Postgres password", &secrets.pg_password)?,
            ),
            ("pg_sslmode", catalog.sslmode.as_str()),
            ("s3_key_id", &env_value("S3 key id", &secrets.s3_key_id)?),
            ("s3_secret", &env_value("S3 secret", &secrets.s3_secret)?),
        ],
    ))
}

/// `hazine.service`.
pub fn unit_file(resources: &Resources) -> String {
    fill(UNIT_FILE, &[("memory_max", &resources.memory_max)])
}

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

    fn catalog() -> Catalog {
        Catalog {
            host: "pg.example.org".into(),
            port: 5433,
            database: "ducklake".into(),
            user: "hazine".into(),
            sslmode: SslMode::VerifyFull,
        }
    }

    fn storage(endpoint: Option<&str>) -> Storage {
        Storage {
            data_path: "s3://lake/hazine/".into(),
            endpoint: endpoint.map(Into::into),
            region: "eu-central".into(),
            url_style: UrlStyle::Path,
            use_ssl: true,
        }
    }

    fn resources() -> Resources {
        Resources {
            threads: 8,
            memory_limit: "25GB".into(),
            memory_max: "28G".into(),
        }
    }

    fn secrets() -> Secrets {
        Secrets {
            quack_token: "tok".into(),
            pg_password: "p@ss$word\"".into(),
            s3_key_id: "AKID".into(),
            s3_secret: "s3/secret+key".into(),
        }
    }

    #[test]
    fn data_paths_are_checked_and_end_in_a_slash() {
        for (path, expected) in [
            ("s3://lake", "s3://lake/"),
            ("s3://lake/hazine", "s3://lake/hazine/"),
            ("s3://lake/hazine/", "s3://lake/hazine/"),
        ] {
            assert_eq!(data_path(path).unwrap(), expected);
            assert_eq!(scope(expected), "s3://lake");
        }
        for path in ["lake/hazine", "s3:///hazine", "gcs://lake/", "s3://la\nke/"] {
            assert!(data_path(path).is_err(), "{path:?}");
        }
    }

    #[test]
    fn init_sql_holds_settings_but_no_secrets() {
        let init = init_sql(&storage(Some("fsn1.example.com")), &resources());
        assert!(!init.contains("{{"), "{init}");
        for part in [
            "SET threads = 8;",
            "SET memory_limit = '25GB';",
            "SCOPE 's3://lake',",
            "KEY_ID getenv('HAZINE_S3_KEY_ID'),",
            "SECRET getenv('HAZINE_S3_SECRET'),\n    ENDPOINT 'fsn1.example.com',\n    REGION 'eu-central',",
            "URL_STYLE 'path',",
            "USE_SSL true\n);",
            "FROM quack_serve(",
        ] {
            assert!(init.contains(part), "{part} missing from\n{init}");
        }
        assert!(!init.contains("ATTACH"), "the lake is the main database");
    }

    #[test]
    fn without_an_endpoint_s3_means_aws() {
        let init = init_sql(&storage(None), &resources());
        assert!(!init.contains("ENDPOINT"));
        assert!(init.contains("SECRET getenv('HAZINE_S3_SECRET'),\n    REGION"));
    }

    #[test]
    fn the_check_creates_the_catalog_with_its_data_path() {
        let check = check_sql(&storage(None));
        assert!(
            check.contains("ATTACH 'ducklake:postgres:' AS lake (DATA_PATH 's3://lake/hazine/');")
        );
        assert!(check.contains("FROM glob('s3://lake/hazine/*')"));
        assert!(!check.contains("quack_serve"));
    }

    #[test]
    fn the_env_file_round_trips() {
        let addr = "127.0.0.1:1294".parse().unwrap();
        let content = env_file(&secrets(), &catalog(), addr).unwrap();
        assert!(!content.contains("{{"), "{content}");
        let env = parse_env(&content);
        for (name, value) in [
            ("QUACK_TOKEN", "tok"),
            ("HAZINE_QUACK_ADDR", "127.0.0.1:1294"),
            ("HAZINE_DATABASE", DATABASE),
            ("PGHOST", "pg.example.org"),
            ("PGPORT", "5433"),
            ("PGDATABASE", "ducklake"),
            ("PGUSER", "hazine"),
            ("PGPASSWORD", "p@ss$word\""),
            ("PGSSLMODE", "verify-full"),
            ("HAZINE_S3_KEY_ID", "AKID"),
            ("HAZINE_S3_SECRET", "s3/secret+key"),
        ] {
            assert_eq!(env.get(name).map(String::as_str), Some(value), "{name}");
        }
        for name in SECRET_ENVS {
            assert!(env.contains_key(name), "{name}");
        }
    }

    #[test]
    fn unwritable_secrets_are_refused() {
        let addr = "127.0.0.1:1294".parse().unwrap();
        for bad in ["it's", "two\nlines"] {
            let mut secrets = secrets();
            secrets.pg_password = bad.into();
            assert!(matches!(
                env_file(&secrets, &catalog(), addr),
                Err(Error::InvalidSetting { .. })
            ));
        }
    }

    #[test]
    fn the_unit_gets_the_memory_cap() {
        let unit = unit_file(&resources());
        assert!(unit.contains("\nMemoryMax=28G\n"));
        assert!(!unit.contains("{{") && !unit.contains("postgresql.service"));
    }
}