eventdbx 1.1.0

An event-sourced, key-value, write-side database system.
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
use std::{collections::BTreeMap, path::PathBuf};

use anyhow::{Result, anyhow};
use clap::{Args, Subcommand, ValueEnum};

use eventdbx::config::{
    CsvPluginConfig, HttpPluginConfig, JsonPluginConfig, LogPluginConfig, PluginConfig,
    PluginDefinition, PluginKind, PostgresColumnConfig, PostgresPluginConfig, SqlitePluginConfig,
    TcpPluginConfig, load_or_default,
};

#[derive(Subcommand)]
pub enum PluginCommands {
    /// Configure the Postgres plugin
    #[command(name = "postgres")]
    PostgresConfigure(PluginPostgresConfigureArgs),
    /// Configure the SQLite plugin
    #[command(name = "sqlite")]
    SqliteConfigure(PluginSqliteConfigureArgs),
    /// Configure the CSV plugin
    #[command(name = "csv")]
    CsvConfigure(PluginCsvConfigureArgs),
    /// Configure the TCP plugin
    #[command(name = "tcp")]
    TcpConfigure(PluginTcpConfigureArgs),
    /// Configure the HTTP plugin
    #[command(name = "http")]
    HttpConfigure(PluginHttpConfigureArgs),
    /// Configure the JSON file plugin
    #[command(name = "json")]
    JsonConfigure(PluginJsonConfigureArgs),
    /// Configure the logging plugin
    #[command(name = "log")]
    LogConfigure(PluginLogConfigureArgs),
    /// Configure per-plugin field mappings
    #[command(name = "map")]
    Map(PluginMapArgs),
}

#[derive(Args)]
pub struct PluginPostgresConfigureArgs {
    /// Connection string used to reach the Postgres database
    #[arg(long = "connection")]
    pub connection: String,

    /// Disable the plugin after configuring
    #[arg(long, default_value_t = false)]
    pub disable: bool,
}

#[derive(Args)]
pub struct PluginSqliteConfigureArgs {
    /// Path to the SQLite database file
    #[arg(long)]
    pub path: PathBuf,

    /// Disable the plugin after configuring
    #[arg(long, default_value_t = false)]
    pub disable: bool,
}

#[derive(Args)]
pub struct PluginCsvConfigureArgs {
    /// Output directory for CSV files
    #[arg(long)]
    pub output_dir: PathBuf,

    /// Disable the plugin after configuring
    #[arg(long, default_value_t = false)]
    pub disable: bool,
}

#[derive(Args)]
pub struct PluginTcpConfigureArgs {
    /// Hostname or IP of the TCP service
    #[arg(long)]
    pub host: String,

    /// Port of the TCP service
    #[arg(long)]
    pub port: u16,

    /// Disable the plugin after configuring
    #[arg(long, default_value_t = false)]
    pub disable: bool,
}

#[derive(Args)]
pub struct PluginHttpConfigureArgs {
    /// HTTP endpoint to POST aggregate updates to
    #[arg(long)]
    pub endpoint: String,

    /// Additional headers to send (key=value)
    #[arg(long = "header", value_parser = parse_key_value, value_name = "KEY=VALUE")]
    pub headers: Vec<KeyValue>,

    /// Disable the plugin after configuring
    #[arg(long, default_value_t = false)]
    pub disable: bool,
}

#[derive(Args)]
pub struct PluginJsonConfigureArgs {
    /// File path to append JSON snapshots into
    #[arg(long)]
    pub path: PathBuf,

    /// Pretty-print JSON
    #[arg(long, default_value_t = false)]
    pub pretty: bool,

    /// Disable the plugin after configuring
    #[arg(long, default_value_t = false)]
    pub disable: bool,
}

#[derive(Args)]
pub struct PluginLogConfigureArgs {
    /// Log level to use (trace, debug, info, warn, error)
    #[arg(long, default_value = "info")]
    pub level: String,

    /// Optional template using {aggregate}, {id}, {event}
    #[arg(long)]
    pub template: Option<String>,

    /// Disable the plugin after configuring
    #[arg(long, default_value_t = false)]
    pub disable: bool,
}

#[derive(Debug, Clone)]
pub struct KeyValue {
    pub key: String,
    pub value: String,
}

#[derive(Args)]
pub struct PluginMapArgs {
    /// Plugin identifier
    #[arg(long, value_enum)]
    pub plugin: Option<PluginTarget>,

    /// Aggregate name to configure
    #[arg(long)]
    pub aggregate: String,

    /// Field name to configure
    #[arg(long)]
    pub field: String,

    /// Data type to use for the field (e.g., VARCHAR(255))
    #[arg(long = "datatype")]
    pub data_type: String,
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
#[clap(rename_all = "lowercase")]
pub enum PluginTarget {
    Postgres,
    Sqlite,
    Csv,
    Tcp,
    Http,
    Json,
    Log,
}

impl From<PluginTarget> for PluginKind {
    fn from(value: PluginTarget) -> Self {
        match value {
            PluginTarget::Postgres => PluginKind::Postgres,
            PluginTarget::Sqlite => PluginKind::Sqlite,
            PluginTarget::Csv => PluginKind::Csv,
            PluginTarget::Tcp => PluginKind::Tcp,
            PluginTarget::Http => PluginKind::Http,
            PluginTarget::Json => PluginKind::Json,
            PluginTarget::Log => PluginKind::Log,
        }
    }
}

pub fn execute(config_path: Option<PathBuf>, command: PluginCommands) -> Result<()> {
    let (mut config, path) = load_or_default(config_path)?;

    match command {
        PluginCommands::PostgresConfigure(args) => {
            let existing_mapping = config
                .plugins
                .iter()
                .find_map(|def| match &def.config {
                    PluginConfig::Postgres(settings) => Some(settings.field_mappings.clone()),
                    _ => None,
                })
                .unwrap_or_default();

            let definition = PluginDefinition {
                enabled: !args.disable,
                config: PluginConfig::Postgres(PostgresPluginConfig {
                    connection_string: args.connection,
                    field_mappings: existing_mapping,
                }),
            };
            config.set_plugin(definition);
            config.ensure_data_dir()?;
            config.save(&path)?;
            if args.disable {
                println!("Postgres plugin disabled");
            } else {
                println!("Postgres plugin configured");
            }
        }
        PluginCommands::SqliteConfigure(args) => {
            let definition = PluginDefinition {
                enabled: !args.disable,
                config: PluginConfig::Sqlite(SqlitePluginConfig {
                    path: args.path.clone(),
                }),
            };
            config.set_plugin(definition);
            config.ensure_data_dir()?;
            config.save(&path)?;
            if args.disable {
                println!("SQLite plugin disabled");
            } else {
                println!("SQLite plugin configured");
            }
        }
        PluginCommands::CsvConfigure(args) => {
            let definition = PluginDefinition {
                enabled: !args.disable,
                config: PluginConfig::Csv(CsvPluginConfig {
                    output_dir: args.output_dir.clone(),
                }),
            };
            config.set_plugin(definition);
            config.ensure_data_dir()?;
            config.save(&path)?;
            if args.disable {
                println!("CSV plugin disabled");
            } else {
                println!("CSV plugin configured");
            }
        }
        PluginCommands::TcpConfigure(args) => {
            let definition = PluginDefinition {
                enabled: !args.disable,
                config: PluginConfig::Tcp(TcpPluginConfig {
                    host: args.host,
                    port: args.port,
                }),
            };
            config.set_plugin(definition);
            config.ensure_data_dir()?;
            config.save(&path)?;
            if args.disable {
                println!("TCP plugin disabled");
            } else {
                println!("TCP plugin configured");
            }
        }
        PluginCommands::HttpConfigure(args) => {
            let mut headers = BTreeMap::new();
            for entry in args.headers {
                headers.insert(entry.key, entry.value);
            }
            let definition = PluginDefinition {
                enabled: !args.disable,
                config: PluginConfig::Http(HttpPluginConfig {
                    endpoint: args.endpoint,
                    headers,
                }),
            };
            config.set_plugin(definition);
            config.ensure_data_dir()?;
            config.save(&path)?;
            if args.disable {
                println!("HTTP plugin disabled");
            } else {
                println!("HTTP plugin configured");
            }
        }
        PluginCommands::JsonConfigure(args) => {
            let definition = PluginDefinition {
                enabled: !args.disable,
                config: PluginConfig::Json(JsonPluginConfig {
                    path: args.path,
                    pretty: args.pretty,
                }),
            };
            config.set_plugin(definition);
            config.ensure_data_dir()?;
            config.save(&path)?;
            if args.disable {
                println!("JSON plugin disabled");
            } else {
                println!("JSON plugin configured");
            }
        }
        PluginCommands::LogConfigure(args) => {
            let definition = PluginDefinition {
                enabled: !args.disable,
                config: PluginConfig::Log(LogPluginConfig {
                    level: args.level.clone(),
                    template: args.template.clone(),
                }),
            };
            config.set_plugin(definition);
            config.ensure_data_dir()?;
            config.save(&path)?;
            if args.disable {
                println!("Log plugin disabled");
            } else {
                println!("Log plugin configured");
            }
        }
        PluginCommands::Map(args) => match args.plugin {
            None => {
                config.set_column_type(&args.aggregate, &args.field, args.data_type.clone());
                config.ensure_data_dir()?;
                config.save(&path)?;
                println!(
                    "Mapped base {}.{} as {}",
                    args.aggregate, args.field, args.data_type
                );
            }
            Some(plugin) => match PluginKind::from(plugin) {
                PluginKind::Postgres => {
                    let definition = config
                        .plugins
                        .iter_mut()
                        .find(|def| matches!(def.config, PluginConfig::Postgres(_)))
                        .ok_or_else(|| {
                        anyhow!(
                            "configure postgres plugin before mapping fields with `eventdbx plugin postgres --connection=...`"
                        )
                    })?;

                    match &mut definition.config {
                        PluginConfig::Postgres(settings) => {
                            let mut field_config = PostgresColumnConfig::default();
                            field_config.data_type = Some(args.data_type.clone());

                            settings
                                .field_mappings
                                .entry(args.aggregate.clone())
                                .or_default()
                                .insert(args.field.clone(), field_config);

                            config.ensure_data_dir()?;
                            config.save(&path)?;

                            println!(
                                "Mapped {}.{} as {}",
                                args.aggregate, args.field, args.data_type
                            );
                        }
                        _ => {
                            return Err(anyhow!(
                                "unexpected plugin configuration variant; reconfigure the postgres plugin and try again"
                            ));
                        }
                    }
                }
                PluginKind::Sqlite => {
                    return Err(anyhow!(
                        "field mapping is not supported for the SQLite plugin"
                    ));
                }
                PluginKind::Csv => {
                    return Err(anyhow!("field mapping is not supported for the CSV plugin"));
                }
                PluginKind::Tcp | PluginKind::Http | PluginKind::Json | PluginKind::Log => {
                    return Err(anyhow!(
                        "field mapping is only supported for the Postgres plugin"
                    ));
                }
            },
        },
    }

    Ok(())
}
fn parse_key_value(raw: &str) -> Result<KeyValue, String> {
    let mut parts = raw.splitn(2, '=');
    let key = parts
        .next()
        .ok_or_else(|| "missing key".to_string())?
        .trim()
        .to_string();
    let value = parts
        .next()
        .ok_or_else(|| "missing value".to_string())?
        .trim()
        .to_string();

    if key.is_empty() {
        return Err("header key cannot be empty".to_string());
    }

    Ok(KeyValue { key, value })
}