infrastore-cli 0.2.0

Command-line tool for loading and inspecting an infrastore store directly on disk
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
//! Write-side maintenance commands: `remove`, `transform`, and `template`.

use std::io::{IsTerminal, Write};
use std::path::Path;

use crate::color;
use crate::parse;
use crate::select::SelectorArgs;
use crate::store_access;

/// `remove`: delete a single series, confirming first when interactive.
pub fn remove(
    store_path: &Path,
    selector: &SelectorArgs,
    force: bool,
    dry_run: bool,
) -> Result<(), String> {
    let store = store_access::open_readonly(store_path)?;
    let (meta, key) = selector.resolve(&store)?;
    drop(store);

    if dry_run {
        println!(
            "Would remove {} '{}' (owner {}).",
            meta.time_series_type.as_str(),
            meta.name,
            meta.owner_id
        );
        return Ok(());
    }

    if !force && std::io::stdin().is_terminal() {
        print!(
            "Remove {} '{}' (owner {})? [y/N] ",
            meta.time_series_type.as_str(),
            meta.name,
            meta.owner_id
        );
        std::io::stdout().flush().ok();
        let mut answer = String::new();
        std::io::stdin()
            .read_line(&mut answer)
            .map_err(|e| e.to_string())?;
        let answer = answer.trim().to_ascii_lowercase();
        if answer != "y" && answer != "yes" {
            println!("{}", color::dim("Aborted."));
            return Ok(());
        }
    }

    let mut store = store_access::open_writable(store_path)?;
    store.remove_time_series(&key).map_err(|e| e.to_string())?;
    store.flush().map_err(|e| e.to_string())?;
    println!(
        "{}",
        color::header(&format!(
            "Removed '{}' (owner {}).",
            meta.name, meta.owner_id
        ))
    );
    Ok(())
}

/// `transform`: derive DeterministicSingleTimeSeries from stored SingleTimeSeries,
/// optionally scoped to an owner category and/or resolution.
pub fn transform(
    store_path: &Path,
    horizon: &str,
    interval: &str,
    owner_category: Option<&str>,
    resolution: Option<&str>,
) -> Result<(), String> {
    let horizon = parse::parse_period(horizon)?;
    let interval = parse::parse_period(interval)?;
    let owner_category = owner_category
        .map(parse::parse_owner_category)
        .transpose()?;
    let resolution = resolution.map(parse::parse_period).transpose()?;
    let mut store = store_access::open_writable(store_path)?;
    let n = store
        .transform_single_time_series(horizon, interval, owner_category, resolution)
        .map_err(|e| e.to_string())?;
    store.flush().map_err(|e| e.to_string())?;
    println!(
        "{}",
        color::header(&format!(
            "Transformed {n} SingleTimeSeries into DeterministicSingleTimeSeries."
        ))
    );
    Ok(())
}

/// `rename`: rename the single series a selector resolves to.
pub fn rename(
    store_path: &Path,
    selector: &SelectorArgs,
    new_name: &str,
    dry_run: bool,
) -> Result<(), String> {
    let store = store_access::open_readonly(store_path)?;
    let (meta, key) = selector.resolve(&store)?;
    drop(store);
    if dry_run {
        println!(
            "Would rename '{}' (owner {}) to '{new_name}'.",
            meta.name, meta.owner_id
        );
        return Ok(());
    }
    let mut store = store_access::open_writable(store_path)?;
    store
        .rename_time_series(&key, new_name)
        .map_err(|e| e.to_string())?;
    store.flush().map_err(|e| e.to_string())?;
    println!(
        "{}",
        color::header(&format!(
            "Renamed '{}' (owner {}) to '{new_name}'.",
            meta.name, meta.owner_id
        ))
    );
    Ok(())
}

/// `remove --all`: remove every series matching the selector (may be several).
pub fn remove_all(
    store_path: &Path,
    selector: &SelectorArgs,
    force: bool,
    dry_run: bool,
) -> Result<(), String> {
    let store = store_access::open_readonly(store_path)?;
    let filter = selector.to_filter()?;
    let matches = store
        .list_time_series(filter.clone())
        .map_err(|e| e.to_string())?;
    drop(store);
    if matches.is_empty() {
        println!("{}", color::dim("No time series matched the selector."));
        return Ok(());
    }
    if dry_run {
        println!("Would remove {} time series:", matches.len());
        for m in &matches {
            println!(
                "  - owner={} type={} name={}",
                m.owner_id,
                m.time_series_type.as_str(),
                m.name
            );
        }
        return Ok(());
    }
    if !force && std::io::stdin().is_terminal() {
        print!(
            "Remove {} time series matching the selector? [y/N] ",
            matches.len()
        );
        std::io::stdout().flush().ok();
        let mut answer = String::new();
        std::io::stdin()
            .read_line(&mut answer)
            .map_err(|e| e.to_string())?;
        let answer = answer.trim().to_ascii_lowercase();
        if answer != "y" && answer != "yes" {
            println!("{}", color::dim("Aborted."));
            return Ok(());
        }
    }
    let mut store = store_access::open_writable(store_path)?;
    let n = store.remove_by_filter(filter).map_err(|e| e.to_string())?;
    store.flush().map_err(|e| e.to_string())?;
    println!("{}", color::header(&format!("Removed {n} time series.")));
    Ok(())
}

/// `clear`: remove all series, or all for one owner, confirming when interactive.
pub fn clear(
    store_path: &Path,
    owner_id: Option<i64>,
    owner_category: Option<&str>,
    force: bool,
    dry_run: bool,
) -> Result<(), String> {
    let owner = match (owner_id, owner_category) {
        (Some(id), Some(cat)) => Some((id, parse::parse_owner_category(cat)?)),
        (None, None) => None,
        _ => {
            return Err("clear requires both --owner-id and --owner-category, or neither".into());
        }
    };
    if dry_run {
        let store = store_access::open_readonly(store_path)?;
        let mut filter = infrastore_core::ListFilter::new();
        if let Some((id, cat)) = owner {
            filter = filter.owner_id(id).owner_category(cat);
        }
        let n = store.list_keys(filter).map_err(|e| e.to_string())?.len();
        println!("Would clear {n} time series.");
        return Ok(());
    }
    if !force && std::io::stdin().is_terminal() {
        let scope = match owner {
            Some((id, _)) => format!("owner {id}"),
            None => "the entire store".to_string(),
        };
        print!("Clear all time series for {scope}? [y/N] ");
        std::io::stdout().flush().ok();
        let mut answer = String::new();
        std::io::stdin()
            .read_line(&mut answer)
            .map_err(|e| e.to_string())?;
        let answer = answer.trim().to_ascii_lowercase();
        if answer != "y" && answer != "yes" {
            println!("{}", color::dim("Aborted."));
            return Ok(());
        }
    }
    let mut store = store_access::open_writable(store_path)?;
    let n = store.clear_time_series(owner).map_err(|e| e.to_string())?;
    store.flush().map_err(|e| e.to_string())?;
    println!("{}", color::header(&format!("Cleared {n} time series.")));
    Ok(())
}

/// `replace-owner`: reassign every series from one owner to another.
pub fn replace_owner(
    store_path: &Path,
    old: i64,
    new: i64,
    owner_category: &str,
    dry_run: bool,
) -> Result<(), String> {
    let category = parse::parse_owner_category(owner_category)?;
    if dry_run {
        let store = store_access::open_readonly(store_path)?;
        let filter = infrastore_core::ListFilter::new()
            .owner_id(old)
            .owner_category(category);
        let n = store.list_keys(filter).map_err(|e| e.to_string())?.len();
        println!("Would reassign {n} time series from owner {old} to {new}.");
        return Ok(());
    }
    let mut store = store_access::open_writable(store_path)?;
    let n = store
        .replace_owner(old, new, category)
        .map_err(|e| e.to_string())?;
    store.flush().map_err(|e| e.to_string())?;
    println!(
        "{}",
        color::header(&format!(
            "Reassigned {n} time series from owner {old} to {new}."
        ))
    );
    Ok(())
}

/// `copy`: copy the single series a selector resolves to onto another owner.
pub fn copy(
    store_path: &Path,
    selector: &SelectorArgs,
    dst_owner_id: i64,
    dst_owner_type: &str,
    new_name: Option<&str>,
    dry_run: bool,
) -> Result<(), String> {
    let store = store_access::open_readonly(store_path)?;
    let (meta, key) = selector.resolve(&store)?;
    drop(store);
    if dry_run {
        println!(
            "Would copy '{}' (owner {}) to owner {dst_owner_id} ({dst_owner_type}) as '{}'.",
            meta.name,
            meta.owner_id,
            new_name.unwrap_or(&meta.name)
        );
        return Ok(());
    }
    let mut store = store_access::open_writable(store_path)?;
    store
        .copy_time_series(&key, dst_owner_id, dst_owner_type, new_name)
        .map_err(|e| e.to_string())?;
    store.flush().map_err(|e| e.to_string())?;
    println!(
        "{}",
        color::header(&format!(
            "Copied to owner {dst_owner_id} ({dst_owner_type})."
        ))
    );
    Ok(())
}

/// `persist`: write the store to a new NetCDF + SQLite artifact.
pub fn persist(store_path: &Path, dest: &Path) -> Result<(), String> {
    let mut store = store_access::open_writable(store_path)?;
    store.persist_to(dest).map_err(|e| e.to_string())?;
    println!(
        "{}",
        color::header(&format!("Persisted store to {}.", dest.display()))
    );
    Ok(())
}

/// `compact`: reclaim reusable space; print the compaction report. Confirms
/// first when interactive (it rewrites store internals); `--force` bypasses.
pub fn compact(
    store_path: &Path,
    force: bool,
    format: crate::output::Format,
) -> Result<(), String> {
    if !force && std::io::stdin().is_terminal() {
        print!("Compact the store (rewrites internal bookkeeping)? [y/N] ");
        std::io::stdout().flush().ok();
        let mut answer = String::new();
        std::io::stdin()
            .read_line(&mut answer)
            .map_err(|e| e.to_string())?;
        let answer = answer.trim().to_ascii_lowercase();
        if answer != "y" && answer != "yes" {
            println!("{}", color::dim("Aborted."));
            return Ok(());
        }
    }
    let mut store = store_access::open_writable(store_path)?;
    let report = store.compact().map_err(|e| e.to_string())?;
    store.flush().map_err(|e| e.to_string())?;
    match format {
        crate::output::Format::Json => crate::output::print_json(&serde_json::json!({
            "slots_reclaimed": report.slots_reclaimed,
            "datasets_dropped": report.datasets_dropped,
            "feature_sets_reclaimed": report.feature_sets_reclaimed,
        }))?,
        _ => {
            let headers = vec!["Metric".to_string(), "Value".to_string()];
            let rows = vec![
                vec![
                    "slots_reclaimed".to_string(),
                    report.slots_reclaimed.to_string(),
                ],
                vec![
                    "datasets_dropped".to_string(),
                    report.datasets_dropped.to_string(),
                ],
                vec![
                    "feature_sets_reclaimed".to_string(),
                    report.feature_sets_reclaimed.to_string(),
                ],
            ];
            if format == crate::output::Format::Csv {
                crate::output::display_csv_rows(&headers, &rows)?;
            } else {
                crate::output::display_table_dyn(&headers, &rows);
            }
        }
    }
    Ok(())
}

/// `template`: print an example descriptor for the given time-series type.
pub fn template(ts_type: &str) -> Result<(), String> {
    let kind = parse::parse_ts_type(ts_type)?;
    use infrastore_core::TimeSeriesType::*;
    let body = match kind {
        SingleTimeSeries => SINGLE,
        NonSequentialTimeSeries => NON_SEQUENTIAL,
        Deterministic => DETERMINISTIC,
        Probabilistic => PROBABILISTIC,
        Scenarios => SCENARIOS,
        DeterministicSingleTimeSeries => {
            return Err(
                "DeterministicSingleTimeSeries is derived via `infrastore transform`, not a descriptor"
                    .to_string(),
            );
        }
    };
    print!("{body}");
    Ok(())
}

const SINGLE: &str = r#"{
  "owner_id": 42,
  "owner_type": "Generator",
  "owner_category": "component",
  "name": "load",
  "type": "single",
  "dtype": "f64",
  "units": "MW",
  "ext": "Profile",
  "csv": "load.csv",
  "has_header": true,
  "initial_timestamp": "2024-01-01T00:00:00Z",
  "resolution": "1h",
  "features": {
    "model_year": 2030
  }
}
"#;

const NON_SEQUENTIAL: &str = r#"{
  "owner_id": 42,
  "owner_type": "Generator",
  "owner_category": "component",
  "name": "events",
  "type": "non_sequential",
  "dtype": "f64",
  "units": "MW",
  "csv": "events.csv",
  "has_header": true
}
"#;

const DETERMINISTIC: &str = r#"{
  "owner_id": 42,
  "owner_type": "Generator",
  "owner_category": "component",
  "name": "load_forecast",
  "type": "deterministic",
  "dtype": "f64",
  "units": "MW",
  "csv": "forecast.csv",
  "has_header": true,
  "initial_timestamp": "2024-01-01T00:00:00Z",
  "resolution": "1h",
  "horizon": "24h",
  "interval": "1h",
  "count": 7
}
"#;

const PROBABILISTIC: &str = r#"{
  "owner_id": 42,
  "owner_type": "Generator",
  "owner_category": "component",
  "name": "load_prob",
  "type": "probabilistic",
  "dtype": "f64",
  "units": "MW",
  "csv": "prob.csv",
  "has_header": true,
  "initial_timestamp": "2024-01-01T00:00:00Z",
  "resolution": "1h",
  "horizon": "24h",
  "interval": "1h",
  "count": 7,
  "percentiles": [10.0, 50.0, 90.0]
}
"#;

const SCENARIOS: &str = r#"{
  "owner_id": 42,
  "owner_type": "Generator",
  "owner_category": "component",
  "name": "load_scenarios",
  "type": "scenarios",
  "dtype": "f64",
  "units": "MW",
  "csv": "scenarios.csv",
  "has_header": true,
  "initial_timestamp": "2024-01-01T00:00:00Z",
  "resolution": "1h",
  "horizon": "24h",
  "interval": "1h",
  "count": 7,
  "scenario_count": 10
}
"#;