volumeleaders-agent 0.3.0

Agent-oriented CLI for VolumeLeaders data
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
use std::io::{self, Write};

use serde::Serialize;
use serde_json::Value;

use crate::common::trade_transforms::{TradeRecordKind, transformed_trade_values};

/// Writes `value` as compact JSON to stdout, newline-terminated.
///
/// When `json_table` is true, arrays of objects are converted to
/// array-of-arrays format with a header row before serialization.
pub fn print_json<T: Serialize>(value: &T, json_table: bool) -> io::Result<()> {
    if json_table {
        let v = serde_json::to_value(value)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
        match &v {
            Value::Array(arr) if arr.first().is_some_and(Value::is_object) => {
                let table = values_to_table(arr);
                write_json(&mut io::stdout().lock(), &table)
            }
            _ => write_json(&mut io::stdout().lock(), &v),
        }
    } else {
        write_json(&mut io::stdout().lock(), value)
    }
}

/// Parses a comma-separated output field list.
///
/// Empty input and `all` both mean no filtering. Field names are case-sensitive.
/// Raw record output uses VolumeLeaders JSON keys; transformed output may expose
/// semantic keys such as `type`, `venue`, `events`, and `window` instead.
pub fn selected_fields(fields: Option<&str>) -> Option<Vec<String>> {
    let fields = fields?.trim();
    if fields.is_empty() || fields.eq_ignore_ascii_case("all") {
        return None;
    }

    let fields: Vec<String> = fields
        .split(',')
        .map(str::trim)
        .filter(|field| !field.is_empty())
        .map(ToOwned::to_owned)
        .collect();

    if fields.is_empty() {
        None
    } else {
        Some(fields)
    }
}

/// Serializes records to JSON values and retains only selected fields.
pub fn records_to_values<T: Serialize>(records: &[T], fields: Option<&[String]>) -> Vec<Value> {
    records
        .iter()
        .map(|record| {
            let mut value = serde_json::to_value(record).unwrap_or(Value::Null);
            if let Some(fields) = fields
                && let Some(map) = value.as_object_mut()
            {
                retain_selected_fields(map, fields);
            }
            value
        })
        .collect()
}

/// Outputs pre-serialized record values with compact JSON defaults and optional custom fields.
pub fn print_record_values(
    records: &[Value],
    compact_headers: &[&str],
    fields: Option<&str>,
    all_fields: bool,
    json_table: bool,
) -> io::Result<()> {
    write_record_values(
        io::stdout().lock(),
        records,
        compact_headers,
        fields,
        all_fields,
        json_table,
    )
}

/// Transforms trade-shaped records and outputs them with field filtering.
pub fn print_transformed_record_values<T: Serialize>(
    records: &[T],
    kind: TradeRecordKind,
    compact_headers: &[&str],
    fields: Option<&str>,
    all_fields: bool,
    json_table: bool,
) -> io::Result<()> {
    transformed_trade_values(records, kind)
        .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
        .and_then(|values| {
            print_record_values(&values, compact_headers, fields, all_fields, json_table)
        })
}

/// Writes pre-serialized record values to `writer`.
pub(crate) fn write_record_values<W: Write>(
    mut writer: W,
    records: &[Value],
    compact_headers: &[&str],
    fields: Option<&str>,
    all_fields: bool,
    json_table: bool,
) -> io::Result<()> {
    let custom_fields = selected_fields(fields);
    let raw_fields_requested =
        fields.is_some_and(|fields| fields.trim().eq_ignore_ascii_case("all"));

    if let Some(fields) = custom_fields.as_deref() {
        validate_value_fields(records, fields)?;
    }

    if all_fields || raw_fields_requested {
        if json_table {
            let table = values_to_table(records);
            return write_json(&mut writer, &table);
        }
        return write_json(&mut writer, &records);
    }

    let default_fields: Vec<String> = compact_headers
        .iter()
        .map(|field| (*field).to_string())
        .collect();
    let selected = custom_fields
        .as_deref()
        .unwrap_or(default_fields.as_slice());
    let values = filter_record_values(records, selected);
    if json_table {
        let table = values_to_table(&values);
        write_json(&mut writer, &table)
    } else {
        write_json(&mut writer, &values)
    }
}

/// Checks custom output fields against record keys when records are available.
pub fn validate_record_fields<T: Serialize>(records: &[T], fields: &[String]) -> io::Result<()> {
    validate_selected_fields(available_record_fields(records)?, fields)
}

/// Outputs record lists with compact JSON defaults and optional custom fields.
pub fn print_records<T: Serialize>(
    records: &[T],
    compact_headers: &[&str],
    fields: Option<&str>,
    all_fields: bool,
    json_table: bool,
) -> io::Result<()> {
    let custom_fields = selected_fields(fields);
    let raw_fields_requested =
        fields.is_some_and(|fields| fields.trim().eq_ignore_ascii_case("all"));

    if let Some(fields) = custom_fields.as_deref() {
        validate_record_fields(records, fields)?;
    }

    if all_fields || raw_fields_requested {
        return print_json(&records, json_table);
    }

    let default_fields: Vec<String> = compact_headers
        .iter()
        .map(|field| (*field).to_string())
        .collect();
    let selected = custom_fields
        .as_deref()
        .unwrap_or(default_fields.as_slice());
    let values = records_to_values(records, Some(selected));
    print_json(&values, json_table)
}

fn available_record_fields<T: Serialize>(records: &[T]) -> io::Result<Vec<String>> {
    let mut fields = Vec::new();
    for record in records {
        let value = serde_json::to_value(record)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
        collect_unique_fields(value.as_object(), &mut fields);
    }
    fields.sort();
    Ok(fields)
}

fn filter_record_values(records: &[Value], fields: &[String]) -> Vec<Value> {
    records
        .iter()
        .map(|record| {
            let mut value = record.clone();
            if let Some(map) = value.as_object_mut() {
                retain_selected_fields(map, fields);
            }
            value
        })
        .collect()
}

fn validate_value_fields(records: &[Value], fields: &[String]) -> io::Result<()> {
    validate_selected_fields(available_value_fields(records), fields)
}

fn validate_selected_fields(available: Vec<String>, fields: &[String]) -> io::Result<()> {
    if available.is_empty() {
        return Ok(());
    }

    let missing = missing_fields(&available, fields);

    if missing.is_empty() {
        return Ok(());
    }

    Err(io::Error::new(
        io::ErrorKind::InvalidInput,
        format!(
            "unknown output field(s): {}. Available fields: {}",
            missing.join(", "),
            available.join(", ")
        ),
    ))
}

fn missing_fields<'a>(available: &[String], requested: &'a [String]) -> Vec<&'a str> {
    requested
        .iter()
        .map(String::as_str)
        .filter(|field| !available.iter().any(|available| available == field))
        .collect()
}

fn available_value_fields(records: &[Value]) -> Vec<String> {
    let mut fields = Vec::new();
    for record in records {
        collect_unique_fields(record.as_object(), &mut fields);
    }
    fields.sort();
    fields
}

fn collect_unique_fields(map: Option<&serde_json::Map<String, Value>>, fields: &mut Vec<String>) {
    if let Some(map) = map {
        for key in map.keys() {
            if !fields.iter().any(|field| field == key) {
                fields.push(key.clone());
            }
        }
    }
}

fn retain_selected_fields(map: &mut serde_json::Map<String, Value>, fields: &[String]) {
    map.retain(|key, _| fields.iter().any(|field| field == key));
}

/// Prints `value` as compact JSON.
pub fn print_result<T: Serialize>(value: &T, json_table: bool) -> io::Result<()> {
    print_json(value, json_table)
}

/// Convert an output write result into the CLI exit code convention.
pub fn finish_output(result: io::Result<()>) -> i32 {
    match result {
        Ok(()) => 0,
        Err(err) => {
            eprintln!("output error: {err}");
            1
        }
    }
}

/// Converts an array of JSON objects into JSON Table format: an array whose
/// first element is the header row (field names) and remaining elements are
/// value rows. Headers are the union of all object keys, ordered by first
/// appearance across all rows. Missing keys in any row produce `null`.
pub(crate) fn values_to_table(records: &[Value]) -> Value {
    if !records.first().is_some_and(Value::is_object) {
        return Value::Array(records.to_vec());
    }

    let mut headers: Vec<String> = Vec::new();
    let mut seen = std::collections::HashSet::new();
    for record in records {
        if let Value::Object(obj) = record {
            for key in obj.keys() {
                if seen.insert(key.clone()) {
                    headers.push(key.clone());
                }
            }
        }
    }

    let header_row = Value::Array(headers.iter().map(|h| Value::String(h.clone())).collect());

    let mut table = Vec::with_capacity(records.len() + 1);
    table.push(header_row);

    for record in records {
        if let Value::Object(obj) = record {
            let row: Vec<Value> = headers
                .iter()
                .map(|h| obj.get(h).cloned().unwrap_or(Value::Null))
                .collect();
            table.push(Value::Array(row));
        }
    }

    Value::Array(table)
}

/// Writes `value` as compact JSON to `writer`, newline-terminated.
fn write_json<W: Write, T: Serialize>(writer: &mut W, value: &T) -> io::Result<()> {
    serde_json::to_writer(&mut *writer, value)
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
    writer.write_all(b"\n")
}

#[cfg(test)]
mod tests {
    use serde::Serialize;

    use super::{
        finish_output, print_records, records_to_values, selected_fields, values_to_table,
        write_json, write_record_values,
    };

    #[derive(Debug, Serialize)]
    struct TestRecord {
        symbol: String,
        price: f64,
        volume: u64,
    }

    fn sample_records() -> Vec<TestRecord> {
        vec![
            TestRecord {
                symbol: "AAPL".to_string(),
                price: 150.5,
                volume: 1_000_000,
            },
            TestRecord {
                symbol: "MSFT".to_string(),
                price: 320.75,
                volume: 500_000,
            },
        ]
    }

    #[test]
    fn output_compact_json() {
        let record = &sample_records()[0];
        let mut buf = Vec::new();
        write_json(&mut buf, record).unwrap();
        let output = String::from_utf8(buf).unwrap();

        // Compact JSON is a single line plus trailing newline.
        let lines: Vec<&str> = output.lines().collect();
        assert_eq!(lines.len(), 1, "compact JSON should be a single line");
        assert!(output.ends_with('\n'));

        let parsed: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
        assert_eq!(parsed["symbol"], "AAPL");
        assert_eq!(parsed["price"], 150.5);
        assert_eq!(parsed["volume"], 1_000_000);
    }

    #[test]
    fn selected_fields_trims_all_sentinel() {
        assert_eq!(selected_fields(Some(" all ")), None);
        assert_eq!(
            selected_fields(Some(" symbol, price ")),
            Some(vec!["symbol".to_string(), "price".to_string()])
        );
    }

    #[test]
    fn selected_fields_returns_none_for_empty_input() {
        assert_eq!(selected_fields(None), None);
        assert_eq!(selected_fields(Some("")), None);
        assert_eq!(selected_fields(Some(",,,")), None);
    }

    #[test]
    fn records_to_values_filters_to_selected_fields() {
        let records = sample_records();
        let values = records_to_values(&records, Some(&["symbol".to_string()]));

        assert_eq!(values[0]["symbol"], "AAPL");
        assert!(values[0].get("price").is_none());
    }

    #[test]
    fn records_to_values_without_fields_preserves_all_fields() {
        let records = sample_records();
        let values = records_to_values(&records, None);

        assert_eq!(values[0]["symbol"], "AAPL");
        assert_eq!(values[0]["price"], 150.5);
        assert_eq!(values[0]["volume"], 1_000_000);
    }

    #[test]
    fn print_records_rejects_unknown_custom_fields() {
        let records = sample_records();
        let err = print_records(&records, &["symbol"], Some("ticker"), false, false).unwrap_err();

        assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput);
        assert!(err.to_string().contains("unknown output field"));
        assert!(err.to_string().contains("symbol"));
    }

    #[test]
    fn write_record_values_outputs_compact_json_table() {
        let records = sample_records();
        let values: Vec<serde_json::Value> = records
            .iter()
            .map(|r| serde_json::to_value(r).unwrap())
            .collect();
        let mut buf = Vec::new();

        write_record_values(&mut buf, &values, &["symbol", "price"], None, false, true).unwrap();

        let output = String::from_utf8(buf).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
        let rows = parsed.as_array().unwrap();
        assert_eq!(rows.len(), 3, "header row + 2 data rows");
        assert!(rows.iter().all(serde_json::Value::is_array));

        let headers = rows[0].as_array().unwrap();
        assert_eq!(headers.len(), 2);
        assert!(headers.contains(&serde_json::json!("symbol")));
        assert!(headers.contains(&serde_json::json!("price")));
        assert!(!headers.contains(&serde_json::json!("volume")));

        let first_row = rows[1].as_array().unwrap();
        assert!(first_row.contains(&serde_json::json!("AAPL")));
        assert!(first_row.contains(&serde_json::json!(150.5)));
    }

    #[test]
    fn write_record_values_outputs_all_fields_json_table() {
        let records = sample_records();
        let values: Vec<serde_json::Value> = records
            .iter()
            .map(|r| serde_json::to_value(r).unwrap())
            .collect();
        let mut buf = Vec::new();

        write_record_values(&mut buf, &values, &["symbol"], None, true, true).unwrap();

        let output = String::from_utf8(buf).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
        let rows = parsed.as_array().unwrap();
        assert_eq!(rows.len(), 3, "header row + 2 data rows");
        assert!(rows.iter().all(serde_json::Value::is_array));

        let headers = rows[0].as_array().unwrap();
        assert_eq!(headers.len(), 3);
        assert!(headers.contains(&serde_json::json!("symbol")));
        assert!(headers.contains(&serde_json::json!("price")));
        assert!(headers.contains(&serde_json::json!("volume")));

        let first_row = rows[1].as_array().unwrap();
        assert!(first_row.contains(&serde_json::json!("AAPL")));
        assert!(first_row.contains(&serde_json::json!(150.5)));
        assert!(first_row.contains(&serde_json::json!(1_000_000)));
    }

    #[test]
    fn write_record_values_outputs_custom_field() {
        let records = sample_records();
        let values: Vec<serde_json::Value> = records
            .iter()
            .map(|r| serde_json::to_value(r).unwrap())
            .collect();
        let mut buf = Vec::new();

        write_record_values(
            &mut buf,
            &values,
            &["symbol", "price"],
            Some("symbol"),
            false,
            false,
        )
        .unwrap();

        let output = String::from_utf8(buf).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
        assert_eq!(
            parsed,
            serde_json::json!([
                {"symbol": "AAPL"},
                {"symbol": "MSFT"}
            ])
        );
    }

    #[test]
    fn write_record_values_rejects_unknown_custom_fields() {
        let records = sample_records();
        let values: Vec<serde_json::Value> = records
            .iter()
            .map(|r| serde_json::to_value(r).unwrap())
            .collect();
        let mut buf = Vec::new();

        let err = write_record_values(
            &mut buf,
            &values,
            &["symbol", "price"],
            Some("ticker"),
            false,
            false,
        )
        .unwrap_err();

        assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput);
        assert!(err.to_string().contains("unknown output field"));
        assert!(err.to_string().contains("ticker"));
    }

    #[test]
    fn write_record_values_outputs_raw_fields_for_all_sentinel() {
        let records = sample_records();
        let values: Vec<serde_json::Value> = records
            .iter()
            .map(|r| serde_json::to_value(r).unwrap())
            .collect();
        let mut buf = Vec::new();

        write_record_values(&mut buf, &values, &["symbol"], Some("all"), false, false).unwrap();

        let output = String::from_utf8(buf).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
        assert_eq!(parsed, serde_json::Value::Array(values));
    }

    #[test]
    fn finish_output_maps_result_to_exit_code() {
        assert_eq!(finish_output(Ok(())), 0);
        assert_eq!(finish_output(Err(std::io::Error::other("broken pipe"))), 1);
    }

    #[test]
    fn values_to_table_converts_array_of_objects() {
        let records = sample_records();
        let values: Vec<serde_json::Value> = records
            .iter()
            .map(|r| serde_json::to_value(r).unwrap())
            .collect();
        let table = values_to_table(&values);
        let rows = table.as_array().unwrap();

        assert_eq!(rows.len(), 3, "header row + 2 data rows");

        let headers = rows[0].as_array().unwrap();
        assert!(headers.contains(&serde_json::Value::String("symbol".to_string())));
        assert!(headers.contains(&serde_json::Value::String("price".to_string())));
        assert!(headers.contains(&serde_json::Value::String("volume".to_string())));

        let first_row = rows[1].as_array().unwrap();
        assert_eq!(first_row.len(), headers.len());
        assert!(first_row.contains(&serde_json::json!("AAPL")));
        assert!(first_row.contains(&serde_json::json!(150.5)));
    }

    #[test]
    fn values_to_table_returns_non_object_array_unchanged() {
        let values = vec![serde_json::json!(1), serde_json::json!(2)];
        let result = values_to_table(&values);
        assert_eq!(result, serde_json::json!([1, 2]));
    }

    #[test]
    fn values_to_table_handles_empty_array() {
        let result = values_to_table(&[]);
        assert_eq!(result, serde_json::json!([]));
    }

    #[test]
    fn values_to_table_builds_union_of_all_keys() {
        use serde_json::json;

        let records = vec![
            json!({"a": 1, "b": 2}),
            json!({"a": 3, "c": 4}),
            json!({"b": 5, "d": 6}),
        ];
        let table = values_to_table(&records);
        let rows = table.as_array().unwrap();

        assert_eq!(rows.len(), 4, "header + 3 data rows");

        let headers: Vec<&str> = rows[0]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert_eq!(headers, ["a", "b", "c", "d"]);

        // Row 0: has a,b; missing c,d
        let r0 = rows[1].as_array().unwrap();
        assert_eq!(r0, &[json!(1), json!(2), json!(null), json!(null)]);

        // Row 1: has a,c; missing b,d
        let r1 = rows[2].as_array().unwrap();
        assert_eq!(r1, &[json!(3), json!(null), json!(4), json!(null)]);

        // Row 2: has b,d; missing a,c
        let r2 = rows[3].as_array().unwrap();
        assert_eq!(r2, &[json!(null), json!(5), json!(null), json!(6)]);
    }
}