eventdbx 3.8.7

An event-sourced, nosql, 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
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
use std::{
    fs,
    path::{Path, PathBuf},
};

use anyhow::{Context, Result, bail};
use chrono::Utc;
use clap::Args;
#[cfg(unix)]
use libc;
use serde::Deserialize;
use serde_json::Value;

use eventdbx::{
    config::{Config, DEFAULT_DOMAIN_NAME, load_or_default},
    schema::{AggregateSchema, SchemaManager},
    store::{AggregateQueryScope, EventStore},
};
use std::io::{self, Write};

#[derive(Args)]
pub struct DomainCheckoutArgs {
    /// Domain to activate
    #[arg(short = 'd', long = "domain", value_name = "NAME")]
    pub flag_domain: Option<String>,

    /// Domain to activate (positional alias for -d/--domain)
    #[arg(value_name = "NAME")]
    pub positional_domain: Option<String>,

    /// Create the domain before switching if it does not exist
    #[arg(
        short = 'c',
        long = "create",
        default_value_t = false,
        conflicts_with = "delete"
    )]
    pub create: bool,

    /// Delete the specified domain instead of switching
    #[arg(long, default_value_t = false)]
    pub delete: bool,

    /// Skip the interactive confirmation when deleting a domain
    #[arg(long, default_value_t = false, requires = "delete")]
    pub force: bool,
}

#[derive(Args)]
pub struct DomainMergeArgs {
    /// Source domain to import from
    #[arg(long = "from", value_name = "DOMAIN")]
    pub from: String,

    /// Target domain to import into (defaults to the currently active domain)
    #[arg(long = "into", value_name = "DOMAIN")]
    pub into: Option<String>,

    /// Replace conflicting schema definitions in the target domain
    #[arg(long, default_value_t = false)]
    pub overwrite_schemas: bool,
}

pub fn checkout(config_path: Option<PathBuf>, args: DomainCheckoutArgs) -> Result<()> {
    if args.delete {
        return delete_domain(config_path, &args);
    }

    let target = resolve_checkout_domain(&args)?;
    let (mut config, path) = load_or_default(config_path)?;

    if args.create {
        create_domain(&config, &target)?;
    }

    if config.active_domain() == target {
        println!(
            "Domain '{}' is already active (data directory: {}).",
            target,
            config.domain_data_dir().display()
        );
        return Ok(());
    }

    config.domain = target.clone();
    config.ensure_data_dir()?;
    let domain_root = config.domain_data_dir();
    config.updated_at = Utc::now();
    config.save(&path)?;

    println!(
        "Switched to domain '{}' (data directory: {}).",
        target,
        domain_root.display()
    );

    Ok(())
}

fn create_domain(config: &Config, domain: &str) -> Result<()> {
    if domain.eq_ignore_ascii_case(DEFAULT_DOMAIN_NAME) {
        println!("Domain '{}' already exists.", DEFAULT_DOMAIN_NAME);
        return Ok(());
    }

    let mut candidate = config.clone();
    candidate.domain = domain.to_string();
    let domain_dir = candidate.domain_data_dir();

    if domain_dir.exists() {
        println!(
            "Domain '{}' already exists (data directory: {}).",
            domain,
            domain_dir.display()
        );
        return Ok(());
    }

    candidate
        .ensure_data_dir()
        .with_context(|| format!("failed to create domain '{domain}'"))?;

    println!(
        "Created domain '{}' (data directory: {}).",
        domain,
        domain_dir.display()
    );
    Ok(())
}

fn delete_domain(config_path: Option<PathBuf>, args: &DomainCheckoutArgs) -> Result<()> {
    let target = resolve_checkout_domain(args)?;
    let (config, _) = load_or_default(config_path)?;

    if target.eq_ignore_ascii_case(DEFAULT_DOMAIN_NAME) {
        bail!("cannot delete the default domain");
    }
    if config.active_domain().eq_ignore_ascii_case(&target) {
        bail!("cannot delete the currently active domain; switch to a different domain first");
    }

    let mut candidate = config.clone();
    candidate.domain = target.clone();
    let domain_dir = candidate.domain_data_dir();

    if !domain_dir.exists() {
        println!("Domain '{}' does not exist.", target);
        return Ok(());
    }

    if !args.force && !confirm_delete(&target)? {
        println!("Domain deletion cancelled.");
        return Ok(());
    }

    ensure_domain_stopped(&candidate)?;

    fs::remove_dir_all(&domain_dir).with_context(|| {
        format!(
            "failed to delete domain '{}' at {}",
            target,
            domain_dir.display()
        )
    })?;

    println!(
        "Deleted domain '{}' (data directory: {}).",
        target,
        domain_dir.display()
    );
    Ok(())
}

fn confirm_delete(domain: &str) -> Result<bool> {
    print!("Type the domain name '{}' to confirm deletion: ", domain);
    io::stdout().flush()?;

    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    Ok(input.trim() == domain)
}

pub fn merge(config_path: Option<PathBuf>, args: DomainMergeArgs) -> Result<()> {
    let (config, _) = load_or_default(config_path)?;
    let source_domain = normalize_domain_name(&args.from)?;
    let target_domain = match args.into {
        Some(ref value) => normalize_domain_name(value)?,
        None => config.active_domain().to_string(),
    };

    if source_domain == target_domain {
        bail!("source and target domains must be different");
    }

    let mut source_config = config.clone();
    source_config.domain = source_domain.clone();
    source_config.ensure_data_dir()?;

    let mut target_config = config.clone();
    target_config.domain = target_domain.clone();
    target_config.ensure_data_dir()?;

    ensure_domain_stopped(&source_config)?;
    ensure_domain_stopped(&target_config)?;

    let schema_stats = merge_schemas(&source_config, &target_config, args.overwrite_schemas)?;
    let event_stats = merge_events(&source_config, &target_config)?;

    if schema_stats.added == 0 && schema_stats.replaced == 0 && event_stats.events == 0 {
        println!(
            "No data to merge from '{}' into '{}'.",
            source_domain, target_domain
        );
        return Ok(());
    }

    println!(
        "Merged {} aggregate(s) and {} event(s) from '{}' into '{}'.",
        event_stats.aggregates, event_stats.events, source_domain, target_domain
    );
    if event_stats.archived > 0 {
        println!(
            "  • {} aggregate(s) marked archived after merge",
            event_stats.archived
        );
    }
    if schema_stats.added > 0 || schema_stats.replaced > 0 {
        println!(
            "Merged schemas: {} added{}",
            schema_stats.added,
            if schema_stats.replaced > 0 {
                format!("; {} replaced", schema_stats.replaced)
            } else {
                String::new()
            }
        );
    }

    Ok(())
}

pub(crate) fn normalize_domain_name(raw: &str) -> Result<String> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        bail!("domain name cannot be empty");
    }

    if trimmed.eq_ignore_ascii_case(DEFAULT_DOMAIN_NAME) {
        return Ok(DEFAULT_DOMAIN_NAME.to_string());
    }

    let lower = trimmed.to_ascii_lowercase();
    if !matches!(lower.chars().next(), Some(ch) if ch.is_ascii_alphanumeric()) {
        bail!("domain name must begin with an ASCII letter or digit");
    }
    if !lower
        .chars()
        .skip(1)
        .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_')
    {
        bail!("domain name may only contain letters, numbers, '-' or '_'");
    }
    Ok(lower)
}

fn resolve_checkout_domain(args: &DomainCheckoutArgs) -> Result<String> {
    match (&args.flag_domain, &args.positional_domain) {
        (Some(flag), None) => normalize_domain_name(flag),
        (None, Some(positional)) => normalize_domain_name(positional),
        (Some(flag), Some(positional)) => {
            let normalized_flag = normalize_domain_name(flag)?;
            let normalized_positional = normalize_domain_name(positional)?;
            if normalized_flag != normalized_positional {
                bail!("conflicting domain inputs provided via -d/--domain and positional argument");
            }
            Ok(normalized_flag)
        }
        (None, None) => {
            bail!("domain name must be provided via -d/--domain or positional argument")
        }
    }
}

struct SchemaMergeStats {
    added: usize,
    replaced: usize,
}

impl Default for SchemaMergeStats {
    fn default() -> Self {
        Self {
            added: 0,
            replaced: 0,
        }
    }
}

struct EventMergeStats {
    aggregates: usize,
    events: usize,
    archived: usize,
}

impl Default for EventMergeStats {
    fn default() -> Self {
        Self {
            aggregates: 0,
            events: 0,
            archived: 0,
        }
    }
}

fn merge_schemas(source: &Config, target: &Config, overwrite: bool) -> Result<SchemaMergeStats> {
    let source_manager = SchemaManager::load(source.schema_store_path())?;
    let target_manager = SchemaManager::load(target.schema_store_path())?;
    let source_items = source_manager.snapshot();

    if source_items.is_empty() {
        return Ok(SchemaMergeStats::default());
    }

    let mut target_items = target_manager.snapshot();
    let mut stats = SchemaMergeStats::default();

    for (name, schema) in source_items {
        match target_items.get(&name) {
            Some(existing) => {
                if schemas_equivalent(existing, &schema) {
                    continue;
                }
                if !overwrite {
                    bail!(
                        "schema '{}' already exists in target domain with different definition (use --overwrite-schemas to replace)",
                        name
                    );
                }
                target_items.insert(name.clone(), schema.clone());
                stats.replaced += 1;
            }
            None => {
                target_items.insert(name.clone(), schema.clone());
                stats.added += 1;
            }
        }
    }

    if stats.added > 0 || stats.replaced > 0 {
        target_manager.replace_all(target_items)?;
    }

    Ok(stats)
}

fn schemas_equivalent(lhs: &AggregateSchema, rhs: &AggregateSchema) -> bool {
    schema_signature(lhs) == schema_signature(rhs)
}

fn schema_signature(schema: &AggregateSchema) -> Value {
    let mut value = serde_json::to_value(schema).expect("schema should serialize successfully");
    if let Value::Object(ref mut map) = value {
        map.remove("created_at");
        map.remove("updated_at");
    }
    value
}

fn merge_events(source: &Config, target: &Config) -> Result<EventMergeStats> {
    let source_path = source.event_store_path();
    if !source_path.exists() {
        return Ok(EventMergeStats::default());
    }

    let source_store = EventStore::open_read_only(source_path, source.encryption_key()?)?;
    let target_store = EventStore::open(
        target.event_store_path(),
        target.encryption_key()?,
        target.snowflake_worker_id,
    )?;

    let mut stats = EventMergeStats::default();
    let mut aggregates = source_store.aggregates_paginated_with_transform(
        0,
        None,
        None,
        AggregateQueryScope::IncludeArchived,
        |aggregate| Some(aggregate),
    );
    aggregates.sort_by(|a, b| {
        a.aggregate_type
            .cmp(&b.aggregate_type)
            .then_with(|| a.aggregate_id.cmp(&b.aggregate_id))
    });

    for aggregate in aggregates {
        if aggregate.version == 0 {
            continue;
        }
        if target_store
            .aggregate_version(&aggregate.aggregate_type, &aggregate.aggregate_id)?
            .is_some()
        {
            bail!(
                "aggregate '{}::{}' already exists in target domain; aborting merge",
                aggregate.aggregate_type,
                aggregate.aggregate_id
            );
        }

        let events =
            source_store.list_events(&aggregate.aggregate_type, &aggregate.aggregate_id)?;
        for event in events {
            target_store.append_replica(event)?;
            stats.events += 1;
        }

        if aggregate.archived {
            target_store.set_archive(
                &aggregate.aggregate_type,
                &aggregate.aggregate_id,
                true,
                None,
            )?;
            stats.archived += 1;
        }

        stats.aggregates += 1;
    }

    Ok(stats)
}

fn ensure_domain_stopped(config: &Config) -> Result<()> {
    let pid_path = config.pid_file_path();
    if !pid_path.exists() {
        return Ok(());
    }
    match read_pid(&pid_path)? {
        Some(pid) if process_is_running(pid) => bail!(
            "EventDBX server appears to be running for domain '{}' (pid {}); stop it before merging",
            config.active_domain(),
            pid
        ),
        _ => Ok(()),
    }
}

fn read_pid(path: &Path) -> Result<Option<u32>> {
    let contents = fs::read_to_string(path)
        .with_context(|| format!("failed to read pid file at {}", path.display()))?;
    let trimmed = contents.trim();
    if trimmed.is_empty() {
        return Ok(None);
    }
    if let Ok(record) = serde_json::from_str::<PidRecord>(trimmed) {
        return Ok(Some(record.pid));
    }
    trimmed
        .parse::<u32>()
        .map(Some)
        .map_err(|err| anyhow::anyhow!("invalid pid contents at {}: {}", path.display(), err))
}

fn process_is_running(pid: u32) -> bool {
    #[cfg(unix)]
    {
        unsafe {
            if libc::kill(pid as libc::pid_t, 0) == 0 {
                true
            } else {
                let err = io::Error::last_os_error();
                !matches!(err.raw_os_error(), Some(libc::ESRCH))
            }
        }
    }
    #[cfg(windows)]
    {
        use windows_sys::Win32::{
            Foundation::CloseHandle,
            System::Threading::{OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION},
        };
        unsafe {
            let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
            if handle == 0 {
                false
            } else {
                CloseHandle(handle);
                true
            }
        }
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = pid;
        false
    }
}

#[derive(Deserialize)]
struct PidRecord {
    pid: u32,
}

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

    #[test]
    fn normalizes_default_domain_case_insensitively() {
        let result = normalize_domain_name("DEFAULT").expect("domain should normalize");
        assert_eq!(result, DEFAULT_DOMAIN_NAME);
    }

    #[test]
    fn normalizes_custom_domain() {
        let result = normalize_domain_name("Herds-01").expect("domain should normalize");
        assert_eq!(result, "herds-01");
    }

    #[test]
    fn resolve_domain_from_flag() {
        let args = DomainCheckoutArgs {
            flag_domain: Some("Herds".to_string()),
            positional_domain: None,
            create: false,
            delete: false,
            force: false,
        };
        let result = resolve_checkout_domain(&args).expect("flag domain should resolve");
        assert_eq!(result, "herds");
    }

    #[test]
    fn resolve_domain_from_positional() {
        let args = DomainCheckoutArgs {
            flag_domain: None,
            positional_domain: Some("Herds_01".to_string()),
            create: false,
            delete: false,
            force: false,
        };
        let result = resolve_checkout_domain(&args).expect("positional domain should resolve");
        assert_eq!(result, "herds_01");
    }

    #[test]
    fn resolve_conflicting_inputs_errors() {
        let args = DomainCheckoutArgs {
            flag_domain: Some("alpha".to_string()),
            positional_domain: Some("beta".to_string()),
            create: false,
            delete: false,
            force: false,
        };
        assert!(resolve_checkout_domain(&args).is_err());
    }

    #[test]
    fn rejects_invalid_characters() {
        assert!(normalize_domain_name("bad/name").is_err());
        assert!(normalize_domain_name("  ").is_err());
        assert!(normalize_domain_name("-leading").is_err());
    }

    #[test]
    fn schema_signature_ignores_timestamps() {
        let now = Utc::now();
        let schema_a = sample_schema("alpha", now);
        let mut schema_b = sample_schema("alpha", now + chrono::Duration::seconds(5));
        assert!(schemas_equivalent(&schema_a, &schema_b));

        schema_b.events.insert(
            "alpha_updated".to_string(),
            eventdbx::schema::EventSchema::default(),
        );
        assert!(!schemas_equivalent(&schema_a, &schema_b));
    }

    fn sample_schema(name: &str, timestamp: chrono::DateTime<chrono::Utc>) -> AggregateSchema {
        let mut events = BTreeMap::new();
        events.insert(
            format!("{}_created", name),
            eventdbx::schema::EventSchema::default(),
        );
        AggregateSchema {
            aggregate: name.to_string(),
            snapshot_threshold: None,
            locked: false,
            field_locks: Vec::new(),
            hidden: false,
            hidden_fields: Vec::new(),
            column_types: BTreeMap::new(),
            events,
            created_at: timestamp,
            updated_at: timestamp,
        }
    }
}