reddb-io-server 1.2.0

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
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
use super::*;

impl RedDBServer {
    pub(crate) fn handle_v1_keyed_route(
        &self,
        method: &str,
        path: &str,
        query: &BTreeMap<String, String>,
        body: &[u8],
    ) -> Option<HttpResponse> {
        if let Some(rest) = path.strip_prefix("/v1/kv/") {
            return Some(self.handle_v1_kv(method, rest, query, body));
        }
        if let Some(rest) = path.strip_prefix("/v1/config/") {
            return Some(self.handle_v1_config(method, rest, query, body));
        }
        if let Some(rest) = path.strip_prefix("/v1/vault/") {
            return Some(self.handle_v1_vault(method, rest, query, body));
        }
        None
    }

    fn handle_v1_kv(
        &self,
        method: &str,
        rest: &str,
        query: &BTreeMap<String, String>,
        body: &[u8],
    ) -> HttpResponse {
        let parts = path_parts(rest);
        match parts.as_slice() {
            [collection, "tags", "invalidate"] => match method {
                "POST" => self.handle_invalidate_kv_tags(collection, body.to_vec()),
                _ => json_error(405, "method not allowed for KV tag invalidation endpoint"),
            },
            [collection, key, "watch"] => match method {
                "GET" => match decoded_http_kv_target(collection, key) {
                    Ok((collection, key)) => self.handle_watch_kv(&collection, &key, query),
                    Err(response) => response,
                },
                _ => json_error(405, "method not allowed for KV watch endpoint"),
            },
            [collection, key, "incr"] => match method {
                "POST" => {
                    let payload = match parse_json_body_allow_empty(body) {
                        Ok(payload) => payload,
                        Err(response) => return response,
                    };
                    let by = payload.get("by").and_then(JsonValue::as_i64).unwrap_or(1);
                    let path = match keyed_path(collection, key) {
                        Ok(path) => path,
                        Err(response) => return response,
                    };
                    let mut sql = format!("KV INCR {path} BY {by}");
                    if let Some(expire_ms) = json_u64_field_any(&payload, &["expire_ms", "ttl_ms"])
                    {
                        sql.push_str(&format!(" EXPIRE {expire_ms} ms"));
                    }
                    self.execute_keyed_sql(sql)
                }
                _ => json_error(405, "method not allowed for KV counter endpoint"),
            },
            [collection, key] => match method {
                "GET" => match decoded_http_kv_target(collection, key) {
                    Ok((collection, key)) => self.handle_get_kv(&collection, &key),
                    Err(response) => response,
                },
                "PUT" => self.handle_v1_kv_put(collection, key, body),
                "DELETE" => match decoded_http_kv_target(collection, key) {
                    Ok((collection, key)) => self.handle_delete_kv(&collection, &key),
                    Err(response) => response,
                },
                _ => json_error(405, "method not allowed for KV endpoint"),
            },
            _ => json_error(404, "route not found under /v1/kv"),
        }
    }

    fn handle_v1_kv_put(&self, collection: &str, key: &str, body: &[u8]) -> HttpResponse {
        let payload = match parse_json_body_allow_empty(body) {
            Ok(payload) => payload,
            Err(response) => return response,
        };
        let Some(value) = payload.get("value") else {
            return json_error(400, "field 'value' is required");
        };
        let tags = match json_string_array_field(&payload, "tags") {
            Ok(tags) => tags,
            Err(message) => return json_error(400, message),
        };
        let mut sql = format!(
            "KV PUT {} = {}",
            match keyed_path(collection, key) {
                Ok(path) => path,
                Err(response) => return response,
            },
            match keyed_value_literal(value) {
                Ok(literal) => literal,
                Err(response) => return response,
            }
        );
        if let Some(expire_ms) = json_u64_field_any(&payload, &["expire_ms", "ttl_ms"]) {
            sql.push_str(&format!(" EXPIRE {expire_ms} ms"));
        }
        append_tags_clause(&mut sql, &tags);
        self.execute_keyed_sql(sql)
    }

    fn handle_v1_config(
        &self,
        method: &str,
        rest: &str,
        query: &BTreeMap<String, String>,
        body: &[u8],
    ) -> HttpResponse {
        let parts = path_parts(rest);
        match parts.as_slice() {
            [collection] => match method {
                "GET" => self.execute_keyed_sql(list_sql("CONFIG", collection, query)),
                _ => json_error(405, "method not allowed for Config collection endpoint"),
            },
            [collection, key, "resolve"] => match method {
                "POST" => match keyed_target(collection, key) {
                    Ok((collection, key)) => {
                        self.execute_keyed_sql(format!("RESOLVE CONFIG {collection} {key}"))
                    }
                    Err(response) => response,
                },
                _ => json_error(405, "method not allowed for Config resolve endpoint"),
            },
            [collection, key, "history"] => match method {
                "GET" => match keyed_target(collection, key) {
                    Ok((collection, key)) => {
                        self.execute_keyed_sql(format!("HISTORY CONFIG {collection} {key}"))
                    }
                    Err(response) => response,
                },
                _ => json_error(405, "method not allowed for Config history endpoint"),
            },
            [collection, key, "watch"] => match method {
                "GET" => match keyed_target(collection, key) {
                    Ok((collection, key)) => {
                        let from_lsn = query.get("from_lsn").and_then(|v| v.parse::<u64>().ok());
                        let mut sql = format!("WATCH CONFIG {collection} {key}");
                        if let Some(from_lsn) = from_lsn {
                            sql.push_str(&format!(" FROM LSN {from_lsn}"));
                        }
                        self.execute_keyed_sql(sql)
                    }
                    Err(response) => response,
                },
                _ => json_error(405, "method not allowed for Config watch endpoint"),
            },
            [_, _, "incr"] | [_, _, "decr"] => {
                json_error(405, "CONFIG counter operations are not supported")
            }
            [collection, key] => match method {
                "GET" => match keyed_target(collection, key) {
                    Ok((collection, key)) => {
                        self.execute_keyed_sql(format!("GET CONFIG {collection} {key}"))
                    }
                    Err(response) => response,
                },
                "PUT" => self.handle_v1_config_put(collection, key, body),
                "DELETE" => match keyed_target(collection, key) {
                    Ok((collection, key)) => {
                        self.execute_keyed_sql(format!("DELETE CONFIG {collection} {key}"))
                    }
                    Err(response) => response,
                },
                _ => json_error(405, "method not allowed for Config endpoint"),
            },
            _ => json_error(404, "route not found under /v1/config"),
        }
    }

    fn handle_v1_config_put(&self, collection: &str, key: &str, body: &[u8]) -> HttpResponse {
        let payload = match parse_json_body_allow_empty(body) {
            Ok(payload) => payload,
            Err(response) => return response,
        };
        if has_volatile_keyed_option(&payload) {
            return json_error(400, "CONFIG does not support TTL or expiration options");
        }
        let Some(value) = payload.get("secret_ref").or_else(|| payload.get("value")) else {
            return json_error(400, "field 'value' is required");
        };
        let tags = match json_string_array_field(&payload, "tags") {
            Ok(tags) => tags,
            Err(message) => return json_error(400, message),
        };
        let (collection, key) = match keyed_target(collection, key) {
            Ok(target) => target,
            Err(response) => return response,
        };
        let literal = match config_value_literal(value, payload.get("secret_ref").is_some()) {
            Ok(literal) => literal,
            Err(response) => return response,
        };
        let mut sql = format!("PUT CONFIG {collection} {key} = {literal}");
        append_tags_clause(&mut sql, &tags);
        self.execute_keyed_sql(sql)
    }

    fn handle_v1_vault(
        &self,
        method: &str,
        rest: &str,
        query: &BTreeMap<String, String>,
        body: &[u8],
    ) -> HttpResponse {
        let parts = path_parts(rest);
        match parts.as_slice() {
            [collection] => match method {
                "GET" => self.execute_keyed_sql(list_sql("VAULT", collection, query)),
                _ => json_error(405, "method not allowed for Vault collection endpoint"),
            },
            [collection, key, "unseal"] => match method {
                "POST" => match keyed_path(collection, key) {
                    Ok(path) => self.execute_keyed_sql(format!("UNSEAL VAULT {path}")),
                    Err(response) => response,
                },
                _ => json_error(405, "method not allowed for Vault unseal endpoint"),
            },
            [collection, key, "history"] => match method {
                "GET" => match keyed_path(collection, key) {
                    Ok(path) => self.execute_keyed_sql(format!("HISTORY VAULT {path}")),
                    Err(response) => response,
                },
                _ => json_error(405, "method not allowed for Vault history endpoint"),
            },
            [_, _, "incr"] | [_, _, "decr"] => {
                json_error(405, "VAULT counter operations are not supported")
            }
            [collection, key] => match method {
                "GET" => match keyed_path(collection, key) {
                    Ok(path) => self.execute_keyed_sql(format!("VAULT GET {path}")),
                    Err(response) => response,
                },
                "PUT" => self.handle_v1_vault_put(collection, key, body, false),
                "DELETE" => match keyed_path(collection, key) {
                    Ok(path) => self.execute_keyed_sql(format!("DELETE VAULT {path}")),
                    Err(response) => response,
                },
                _ => json_error(405, "method not allowed for Vault endpoint"),
            },
            [collection, key, "rotate"] => match method {
                "POST" => self.handle_v1_vault_put(collection, key, body, true),
                _ => json_error(405, "method not allowed for Vault rotate endpoint"),
            },
            _ => json_error(404, "route not found under /v1/vault"),
        }
    }

    fn handle_v1_vault_put(
        &self,
        collection: &str,
        key: &str,
        body: &[u8],
        rotate: bool,
    ) -> HttpResponse {
        let payload = match parse_json_body_allow_empty(body) {
            Ok(payload) => payload,
            Err(response) => return response,
        };
        if has_volatile_keyed_option(&payload) {
            return json_error(400, "VAULT does not support TTL or expiration options");
        }
        let Some(value) = payload.get("value") else {
            return json_error(400, "field 'value' is required");
        };
        let tags = match json_string_array_field(&payload, "tags") {
            Ok(tags) => tags,
            Err(message) => return json_error(400, message),
        };
        let path = match keyed_path(collection, key) {
            Ok(path) => path,
            Err(response) => return response,
        };
        let literal = match keyed_value_literal(value) {
            Ok(literal) => literal,
            Err(response) => return response,
        };
        let mut sql = if rotate {
            format!("ROTATE VAULT {path} = {literal}")
        } else {
            format!("VAULT PUT {path} = {literal}")
        };
        append_tags_clause(&mut sql, &tags);
        self.execute_keyed_sql(sql)
    }

    fn execute_keyed_sql(&self, sql: String) -> HttpResponse {
        match self
            .query_use_cases()
            .execute(ExecuteQueryInput { query: sql })
        {
            Ok(result) => json_response(
                200,
                crate::presentation::query_result_json::runtime_query_json(&result, &None, &None),
            ),
            Err(err) => json_error(400, err.to_string()),
        }
    }
}

fn path_parts(rest: &str) -> Vec<&str> {
    rest.trim_matches('/')
        .split('/')
        .filter(|part| !part.is_empty())
        .collect()
}

fn keyed_path(collection: &str, key: &str) -> Result<String, HttpResponse> {
    let collection = decode_keyed_segment(collection, "collection")?;
    let key = decode_keyed_segment(key, "key")?;
    if !valid_keyed_ident(&collection) {
        return Err(json_error(
            400,
            "collection contains unsupported characters",
        ));
    }
    if key.is_empty() {
        return Err(json_error(400, "key contains unsupported characters"));
    }
    Ok(format!("{collection}.{}", keyed_key_sql_segment(&key)))
}

fn decoded_http_kv_target(collection: &str, key: &str) -> Result<(String, String), HttpResponse> {
    let collection = decode_keyed_segment(collection, "collection")?;
    let key = decode_keyed_segment(key, "key")?;
    if collection.is_empty() || key.is_empty() {
        return Err(json_error(400, "collection and key are required"));
    }
    Ok((collection, key))
}

fn keyed_target(collection: &str, key: &str) -> Result<(String, String), HttpResponse> {
    let collection = decode_keyed_segment(collection, "collection")?;
    let key = decode_keyed_segment(key, "key")?;
    if !valid_keyed_ident(&collection) {
        return Err(json_error(
            400,
            "collection contains unsupported characters",
        ));
    }
    if !valid_keyed_ident(&key) {
        return Err(json_error(400, "key contains unsupported characters"));
    }
    Ok((collection, key))
}

fn valid_keyed_ident(value: &str) -> bool {
    !value.is_empty()
        && value
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'.')
}

fn decode_keyed_segment(segment: &str, name: &str) -> Result<String, HttpResponse> {
    percent_decode_path_segment(segment)
        .map_err(|err| json_error(400, format!("invalid {name} path segment: {err}")))
}

fn keyed_key_sql_segment(key: &str) -> String {
    if valid_keyed_ident(key) {
        return key.to_string();
    }
    format!("'{}'", key.replace('\'', "''"))
}

fn list_sql(domain: &str, collection: &str, query: &BTreeMap<String, String>) -> String {
    let collection = if valid_keyed_ident(collection) {
        collection.to_string()
    } else {
        "_invalid_".to_string()
    };
    let mut sql = format!("LIST {domain} {collection}");
    if let Some(prefix) = query
        .get("prefix")
        .filter(|prefix| valid_keyed_ident(prefix))
    {
        sql.push_str(&format!(" PREFIX {prefix}"));
    }
    if let Some(limit) = query
        .get("limit")
        .and_then(|value| value.parse::<usize>().ok())
    {
        sql.push_str(&format!(" LIMIT {limit}"));
    }
    if let Some(offset) = query
        .get("offset")
        .and_then(|value| value.parse::<usize>().ok())
    {
        sql.push_str(&format!(" OFFSET {offset}"));
    }
    sql
}

fn keyed_value_literal(value: &JsonValue) -> Result<String, HttpResponse> {
    match value {
        JsonValue::String(value) => Ok(format!("'{}'", value.replace('\'', "''"))),
        JsonValue::Number(value) => Ok(value.to_string()),
        JsonValue::Bool(value) => Ok(value.to_string()),
        JsonValue::Null => Ok("NULL".to_string()),
        JsonValue::Array(_) | JsonValue::Object(_) => crate::json::to_string(value)
            .map_err(|err| json_error(400, format!("failed to encode JSON value: {err}"))),
    }
}

fn config_value_literal(
    value: &JsonValue,
    explicit_secret_ref: bool,
) -> Result<String, HttpResponse> {
    if explicit_secret_ref {
        let Some(object) = value.as_object() else {
            return Err(json_error(400, "field 'secret_ref' must be an object"));
        };
        let collection = object
            .get("collection")
            .and_then(JsonValue::as_str)
            .ok_or_else(|| json_error(400, "secret_ref.collection is required"))?;
        let key = object
            .get("key")
            .and_then(JsonValue::as_str)
            .ok_or_else(|| json_error(400, "secret_ref.key is required"))?;
        let path = keyed_path(collection, key)?;
        return Ok(format!("SECRET_REF(vault, {path})"));
    }
    keyed_value_literal(value)
}

fn append_tags_clause(sql: &mut String, tags: &[String]) {
    if tags.is_empty() {
        return;
    }
    sql.push_str(" TAGS [");
    for (index, tag) in tags.iter().enumerate() {
        if index > 0 {
            sql.push_str(", ");
        }
        sql.push('\'');
        sql.push_str(&tag.replace('\'', "''"));
        sql.push('\'');
    }
    sql.push(']');
}

fn has_volatile_keyed_option(payload: &JsonValue) -> bool {
    payload.get("ttl").is_some()
        || payload.get("ttl_ms").is_some()
        || payload.get("expire").is_some()
        || payload.get("expire_ms").is_some()
        || payload.get("expires_at").is_some()
}

fn json_u64_field_any(payload: &JsonValue, names: &[&str]) -> Option<u64> {
    names
        .iter()
        .find_map(|name| payload.get(name).and_then(JsonValue::as_u64))
}

fn json_string_array_field(payload: &JsonValue, field: &str) -> Result<Vec<String>, String> {
    let Some(value) = payload.get(field) else {
        return Ok(Vec::new());
    };
    let Some(values) = value.as_array() else {
        return Err(format!("field '{field}' must be an array of strings"));
    };
    values
        .iter()
        .map(|value| {
            value
                .as_str()
                .map(str::to_string)
                .ok_or_else(|| format!("field '{field}' must contain only strings"))
        })
        .collect()
}