datazen-driver-api 0.0.8

Public API (traits and types) for DataZen database driver plugins
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
//! Generic Driver Command API.
//!
//! Commands are the extension point for driver-specific operations. The host
//! uses [`DriverCommandDefinition`] for discovery and [`CommandResult`] as the
//! transport-neutral execution result.

use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;

fn default_true() -> bool {
    true
}

/// Access level required by a Driver Command.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CommandAccessLevel {
    Read,
    Write,
    HighRisk,
}

/// High-level grouping used by Workflow UI and docs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub enum CommandCategory {
    #[default]
    Query,
    Mutate,
    Admin,
    Observe,
    PubSub,
    Stream,
    Io,
}

/// Optional command metadata. Missing fields deserialize to workflow/UI-enabled defaults.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DriverCommandMetadata {
    #[serde(default)]
    pub category: CommandCategory,
    /// Explicit risk. When omitted, derived from permissions and command id.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub risk: Option<CommandAccessLevel>,
    #[serde(default = "default_true")]
    pub workflow: bool,
    #[serde(default = "default_true")]
    pub ui: bool,
    #[serde(default)]
    pub deprecated: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub replaced_by: Option<String>,
    /// When false, the host may execute this command without a live Connection.
    #[serde(default = "default_true")]
    pub requires_connection: bool,
}

impl Default for DriverCommandMetadata {
    fn default() -> Self {
        Self {
            category: CommandCategory::Query,
            risk: None,
            workflow: true,
            ui: true,
            deprecated: false,
            replaced_by: None,
            requires_connection: true,
        }
    }
}

impl DriverCommandMetadata {
    pub fn new(category: CommandCategory, risk: CommandAccessLevel) -> Self {
        Self {
            category,
            risk: Some(risk),
            ..Self::default()
        }
    }

    pub fn hide_from_workflow(mut self) -> Self {
        self.workflow = false;
        self
    }

    pub fn unbound(mut self) -> Self {
        self.requires_connection = false;
        self
    }
}

/// Metadata exposed by a driver for a command it supports.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DriverCommandDefinition {
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    /// JSON Schema describing the command input object.
    pub input_schema: JsonValue,
    pub output_schema: Option<JsonValue>,
    /// Existing DataZen permission identifiers required by this command.
    #[serde(default)]
    pub permissions: Vec<String>,
    #[serde(default)]
    pub metadata: DriverCommandMetadata,
}

/// Transport-neutral result returned by a Driver Command.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CommandResult {
    pub data: JsonValue,
}

impl CommandResult {
    pub fn new(data: JsonValue) -> Self {
        Self { data }
    }
}

/// Validate the generic structural part of a command's JSON Schema.
/// Driver-specific semantic validation remains inside the driver.
pub fn validate_command_input(
    definition: &DriverCommandDefinition,
    input: &JsonValue,
) -> Result<(), String> {
    if definition
        .input_schema
        .get("type")
        .and_then(JsonValue::as_str)
        == Some("object")
        && !input.is_object()
    {
        return Err(format!(
            "Command '{}' input must be an object",
            definition.id
        ));
    }

    if let Some(required) = definition
        .input_schema
        .get("required")
        .and_then(JsonValue::as_array)
    {
        for field in required.iter().filter_map(JsonValue::as_str) {
            if input.get(field).is_none() {
                return Err(format!(
                    "Command '{}' input is missing required field '{}'",
                    definition.id, field
                ));
            }
        }
    }

    Ok(())
}

/// Build the standard SQL `query` command definition.
pub fn query_command_definition() -> DriverCommandDefinition {
    DriverCommandDefinition {
        id: "query".into(),
        name: "Query".into(),
        description: Some("Execute a SQL query and return its result".into()),
        input_schema: serde_json::json!({
            "type": "object",
            "properties": {
                "sql": { "type": "string" },
                "limit": { "type": ["integer", "null"], "minimum": 1 },
                "params": {
                    "description": "Named or positional bind values substituted by the host before execution",
                    "type": ["object", "array", "null"]
                }
            },
            "required": ["sql"]
        }),
        output_schema: None,
        permissions: vec!["driver.query".into()],
        metadata: DriverCommandMetadata::new(CommandCategory::Query, CommandAccessLevel::Read),
    }
}

/// Build the standard SQL `execute` command definition.
pub fn execute_command_definition() -> DriverCommandDefinition {
    DriverCommandDefinition {
        id: "execute".into(),
        name: "Execute".into(),
        description: Some("Execute a SQL statement".into()),
        input_schema: serde_json::json!({
            "type": "object",
            "properties": { "sql": { "type": "string" } },
            "required": ["sql"]
        }),
        output_schema: Some(serde_json::json!({
            "type": "object",
            "properties": { "rowsAffected": { "type": "integer" } }
        })),
        permissions: vec!["driver.execute".into()],
        metadata: DriverCommandMetadata::new(CommandCategory::Mutate, CommandAccessLevel::Write),
    }
}

fn set_sql_title(mut definition: DriverCommandDefinition, title: &str) -> DriverCommandDefinition {
    if let Some(sql) = definition
        .input_schema
        .get_mut("properties")
        .and_then(|properties| properties.get_mut("sql"))
    {
        sql["title"] = JsonValue::String(title.into());
        sql["description"] = JsonValue::String(title.into());
    }
    definition
}

/// `query` with a driver-specific description and `sql` field title.
pub fn query_command_definition_for(
    description: &str,
    statement_title: &str,
) -> DriverCommandDefinition {
    let mut definition = query_command_definition();
    definition.description = Some(description.into());
    set_sql_title(definition, statement_title)
}

/// `execute` with a driver-specific description and `sql` field title.
pub fn execute_command_definition_for(
    description: &str,
    statement_title: &str,
) -> DriverCommandDefinition {
    let mut definition = execute_command_definition();
    definition.description = Some(description.into());
    set_sql_title(definition, statement_title)
}

/// Query + execute for non-SQL drivers that still use the `sql` input field.
pub fn statement_command_definitions(
    query_description: &str,
    execute_description: &str,
    statement_title: &str,
) -> Vec<DriverCommandDefinition> {
    vec![
        query_command_definition_for(query_description, statement_title),
        execute_command_definition_for(execute_description, statement_title),
    ]
}

/// Query-only drivers (writes are not exposed as commands).
pub fn query_only_command_definitions(
    description: &str,
    statement_title: &str,
) -> Vec<DriverCommandDefinition> {
    vec![query_command_definition_for(description, statement_title)]
}

const HIGH_RISK_TOKENS: &[&str] = &["flush", "drop", "restore", "exec", "truncate", "destroy"];
const WRITE_TOKENS: &[&str] = &[
    "execute", "write", "delete", "del", "set", "update", "insert", "add", "rename", "push", "pop",
    "remove", "ack", "create", "publish", "ttl", "reset", "xadd", "xack",
];

fn permission_tokens(definition: &DriverCommandDefinition) -> Vec<String> {
    let mut tokens = Vec::new();
    for value in definition
        .permissions
        .iter()
        .map(String::as_str)
        .chain(std::iter::once(definition.id.as_str()))
    {
        tokens.extend(
            value
                .split(|c: char| !c.is_ascii_alphanumeric())
                .filter(|t| !t.is_empty())
                .map(|t| t.to_ascii_lowercase()),
        );
    }
    tokens
}

/// Classify a command from explicit metadata, then permissions / command id.
pub fn required_access_level(definition: &DriverCommandDefinition) -> CommandAccessLevel {
    if let Some(risk) = definition.metadata.risk {
        return risk;
    }
    let tokens = permission_tokens(definition);
    if tokens
        .iter()
        .any(|t| HIGH_RISK_TOKENS.contains(&t.as_str()))
    {
        return CommandAccessLevel::HighRisk;
    }
    if tokens.iter().any(|t| WRITE_TOKENS.contains(&t.as_str())) {
        return CommandAccessLevel::Write;
    }
    if definition.permissions.is_empty() && definition.id != "query" {
        return CommandAccessLevel::Write;
    }
    CommandAccessLevel::Read
}

/// Reject commands that need a higher access level than the caller was granted.
pub fn check_command_access(
    definition: &DriverCommandDefinition,
    granted: CommandAccessLevel,
) -> Result<(), String> {
    let required = required_access_level(definition);
    if required > granted {
        return Err(format!(
            "Command '{}' is not allowed at the current permission level",
            definition.id
        ));
    }
    Ok(())
}

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

    #[test]
    fn standard_query_definition_is_schema_driven() {
        let definition = query_command_definition();
        assert_eq!(definition.id, "query");
        assert_eq!(definition.name, "Query");
        assert_eq!(definition.input_schema["type"], "object");
        assert_eq!(
            definition.input_schema["required"],
            serde_json::json!(["sql"])
        );
        assert_eq!(
            definition.input_schema["properties"]["sql"]["type"],
            "string"
        );
        assert_eq!(definition.input_schema["properties"]["limit"]["minimum"], 1);
        assert!(definition.output_schema.is_none());
        assert_eq!(definition.permissions, vec!["driver.query"]);
    }

    #[test]
    fn standard_execute_definition_is_schema_driven() {
        let definition = execute_command_definition();
        assert_eq!(definition.id, "execute");
        assert_eq!(definition.name, "Execute");
        assert_eq!(
            definition.input_schema["required"],
            serde_json::json!(["sql"])
        );
        assert_eq!(definition.output_schema.as_ref().unwrap()["type"], "object");
        assert_eq!(definition.permissions, vec!["driver.execute"]);
    }

    #[test]
    fn command_input_validation_accepts_valid_input() {
        let definition = query_command_definition();
        assert!(
            validate_command_input(&definition, &serde_json::json!({"sql": "SELECT 1"})).is_ok()
        );
    }

    #[test]
    fn command_input_validation_rejects_non_object() {
        let definition = query_command_definition();
        let error =
            validate_command_input(&definition, &serde_json::json!("SELECT 1")).unwrap_err();
        assert!(error.contains("must be an object"));
    }

    #[test]
    fn command_input_validation_rejects_missing_required_field() {
        let definition = query_command_definition();
        let error = validate_command_input(&definition, &serde_json::json!({})).unwrap_err();
        assert!(error.contains("missing required field 'sql'"));
    }

    #[test]
    fn command_definition_uses_camel_case_wire_names() {
        let definition = DriverCommandDefinition {
            id: "custom-command".into(),
            name: "Custom Command".into(),
            description: None,
            input_schema: serde_json::json!({"type": "object"}),
            output_schema: Some(serde_json::json!({"type": "string"})),
            permissions: vec!["driver.custom.execute".into()],
            metadata: DriverCommandMetadata::default(),
        };
        let encoded = serde_json::to_value(&definition).unwrap();
        assert_eq!(encoded["inputSchema"]["type"], "object");
        assert_eq!(encoded["outputSchema"]["type"], "string");
        assert_eq!(
            encoded["permissions"],
            serde_json::json!(["driver.custom.execute"])
        );
        assert_eq!(encoded["metadata"]["workflow"], true);
        assert_eq!(encoded["metadata"]["category"], "query");
    }

    #[test]
    fn command_definition_deserializes_without_permissions() {
        let encoded = serde_json::json!({
            "id": "legacy-command",
            "name": "Legacy Command",
            "description": null,
            "inputSchema": {"type": "object"},
            "outputSchema": null
        });
        let definition: DriverCommandDefinition = serde_json::from_value(encoded).unwrap();
        assert!(definition.permissions.is_empty());
        assert!(definition.metadata.workflow);
        assert!(!definition.metadata.deprecated);
    }

    #[test]
    fn query_definition_includes_default_metadata() {
        let definition = query_command_definition();
        assert_eq!(definition.metadata.category, CommandCategory::Query);
        assert_eq!(definition.metadata.risk, Some(CommandAccessLevel::Read));
        assert!(definition.metadata.workflow);
        assert!(definition.metadata.ui);
        assert!(definition.metadata.requires_connection);
    }

    #[test]
    fn query_only_definitions_omit_execute() {
        let ids: Vec<_> = query_only_command_definitions("Scan a table", "scan <table>")
            .into_iter()
            .map(|d| d.id)
            .collect();
        assert_eq!(ids, vec!["query"]);
    }

    #[test]
    fn explicit_metadata_risk_overrides_permission_tokens() {
        let mut definition = query_command_definition();
        definition.metadata.risk = Some(CommandAccessLevel::HighRisk);
        assert_eq!(
            required_access_level(&definition),
            CommandAccessLevel::HighRisk
        );
    }

    #[test]
    fn command_result_preserves_arbitrary_json() {
        let payload = serde_json::json!({"rows": [{"id": 1}], "metadata": {"source": "mysql"}});
        assert_eq!(CommandResult::new(payload.clone()).data, payload);
    }

    #[test]
    fn command_result_round_trips_as_json() {
        let result = CommandResult::new(serde_json::json!({ "rowsAffected": 3 }));
        let encoded = serde_json::to_value(&result).unwrap();
        let decoded: CommandResult = serde_json::from_value(encoded).unwrap();
        assert_eq!(decoded.data["rowsAffected"], 3);
    }

    #[test]
    fn query_is_read_and_execute_is_write() {
        assert_eq!(
            required_access_level(&query_command_definition()),
            CommandAccessLevel::Read
        );
        assert_eq!(
            required_access_level(&execute_command_definition()),
            CommandAccessLevel::Write
        );
    }

    #[test]
    fn redis_style_permissions_classify_risk() {
        let info = DriverCommandDefinition {
            id: "info".into(),
            name: "Info".into(),
            description: None,
            input_schema: serde_json::json!({"type": "object"}),
            output_schema: None,
            permissions: vec!["redis:allow-info".into()],
            metadata: DriverCommandMetadata::default(),
        };
        let set = DriverCommandDefinition {
            id: "set_string".into(),
            name: "Set".into(),
            description: None,
            input_schema: serde_json::json!({"type": "object"}),
            output_schema: None,
            permissions: vec!["redis:allow-set-string".into()],
            metadata: DriverCommandMetadata::default(),
        };
        let flush = DriverCommandDefinition {
            id: "flush_db".into(),
            name: "Flush".into(),
            description: None,
            input_schema: serde_json::json!({"type": "object"}),
            output_schema: None,
            permissions: vec!["redis:allow-flush-db".into()],
            metadata: DriverCommandMetadata::default(),
        };
        assert_eq!(required_access_level(&info), CommandAccessLevel::Read);
        assert_eq!(required_access_level(&set), CommandAccessLevel::Write);
        assert_eq!(required_access_level(&flush), CommandAccessLevel::HighRisk);
        assert!(check_command_access(&flush, CommandAccessLevel::Write).is_err());
        assert!(check_command_access(&set, CommandAccessLevel::Write).is_ok());
        assert!(check_command_access(&info, CommandAccessLevel::Read).is_ok());
    }
}