Skip to main content

dbn_cli/
lib.rs

1use std::{
2    fs::File,
3    io::{self, BufWriter},
4    num::NonZeroU64,
5    path::{Path, PathBuf},
6};
7
8use anyhow::{anyhow, Context};
9use clap::{ArgAction, Parser, ValueEnum};
10
11use dbn::{
12    encode::{OutputEncoding, SplitDuration},
13    enums::Compression,
14    Schema, VersionUpgradePolicy,
15};
16
17pub mod encode;
18pub mod filter;
19
20/// How to split a DBN file
21#[derive(Clone, Copy, Debug, ValueEnum)]
22pub enum SplitBy {
23    Symbol,
24    Schema,
25    Day,
26    Week,
27    Month,
28    Year,
29}
30
31impl SplitBy {
32    pub fn duration(self) -> Option<SplitDuration> {
33        match self {
34            SplitBy::Day => Some(SplitDuration::Day),
35            SplitBy::Week => Some(SplitDuration::Week),
36            SplitBy::Month => Some(SplitDuration::Month),
37            SplitBy::Year => Some(SplitDuration::Year),
38            SplitBy::Symbol | SplitBy::Schema => None,
39        }
40    }
41}
42
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub struct InferredEncoding {
45    pub encoding: OutputEncoding,
46    pub compression: Compression,
47    pub delimiter: u8,
48    pub is_fragment: bool,
49}
50
51#[derive(Debug, Parser)]
52#[clap(name = "dbn", version, about)]
53#[cfg_attr(test, derive(Default))]
54pub struct Args {
55    #[clap(
56        help = "One or more DBN or legacy DBZ files to decode. Passing multiple files will result in a merge. Pass '-' to read from standard input",
57        value_name = "FILE...",
58        value_delimiter = ' ',
59        num_args = 1..,
60        required = true,
61    )]
62    pub input: Vec<PathBuf>,
63    #[clap(
64        short,
65        long,
66        help = "Saves the result to FILE. If no path is specified, the output will be written to standard output",
67        value_name = "FILE"
68    )]
69    pub output: Option<PathBuf>,
70    #[clap(
71        short = 'O',
72        long,
73        help = "Saves the result of file splitting to paths according to PATTERN",
74        requires = "split_by",
75        conflicts_with = "output",
76        value_name = "PATTERN"
77    )]
78    pub output_pattern: Option<String>,
79    #[clap(
80        short = 'S',
81        long,
82        help = "How to optionally split the output across files",
83        requires = "output_pattern",
84        value_name = "SPLIT_BY"
85    )]
86    pub split_by: Option<SplitBy>,
87    #[clap(
88        short = 'J',
89        long,
90        action = ArgAction::SetTrue,
91        default_value = "false",
92        group = "output_encoding",
93        help = "Output the result as JSON lines"
94    )]
95    pub json: bool,
96    #[clap(
97        short = 'C',
98        long,
99        action = ArgAction::SetTrue,
100        default_value = "false",
101        group = "output_encoding",
102        help = "Output the result as CSV"
103    )]
104    pub csv: bool,
105    #[clap(
106        short = 'T',
107        long,
108        action = ArgAction::SetTrue,
109        default_value = "false",
110        group = "output_encoding",
111        help = "Output the result as tab-separated values (TSV)"
112    )]
113    pub tsv: bool,
114    #[clap(
115        short = 'D',
116        long,
117        action = ArgAction::SetTrue,
118        default_value = "false",
119        group = "output_encoding",
120        help = "Output the result as DBN"
121    )]
122    pub dbn: bool,
123    #[clap(
124        short = 'P',
125        long,
126        action = ArgAction::SetTrue,
127        default_value = "false",
128        group = "output_encoding",
129        help = "Output the result as Apache Parquet"
130    )]
131    pub parquet: bool,
132    #[clap(
133        short = 'A',
134        long,
135        action = ArgAction::SetTrue,
136        default_value = "false",
137        group = "output_encoding",
138        help = "Output the result as Apache Arrow IPC (Feather v2)"
139    )]
140    pub arrow: bool,
141    #[clap(
142        short = 'F',
143        long,
144        action = ArgAction::SetTrue,
145        default_value = "false",
146        group = "output_encoding",
147        help = "Output the result as a DBN fragment (no metadata)"
148    )]
149    pub fragment: bool,
150    #[clap(
151        short,
152        long,
153        action = ArgAction::SetTrue,
154        default_value = "false",
155        help = "Zstd compress the output"
156    )]
157    pub zstd: bool,
158    #[clap(
159        short = 'u',
160        long = "upgrade",
161        default_value = "false",
162        action = ArgAction::SetTrue,
163        help = "Upgrade data when decoding previous DBN versions. By default data is decoded as-is."
164    )]
165    pub should_upgrade: bool,
166    #[clap(
167        short,
168        long,
169        action = ArgAction::SetTrue,
170        default_value = "false",
171        help = "Allow overwriting of existing files, such as the output file"
172    )]
173    pub force: bool,
174    #[clap(
175        short = 'm',
176        long = "metadata",
177        action = ArgAction::SetTrue,
178        default_value = "false",
179        conflicts_with_all = ["csv", "tsv", "dbn", "fragment", "parquet", "arrow"],
180        help = "Output the metadata section instead of the body of the DBN file. Only valid for JSON output encoding"
181    )]
182    pub should_output_metadata: bool,
183    #[clap(
184         short = 'p',
185         long = "pretty",
186         action = ArgAction::SetTrue,
187         default_value = "false",
188         conflicts_with_all = ["dbn", "fragment"],
189         help ="Make the CSV, JSON, Parquet, or Arrow output easier to read by converting prices to decimals and, for CSV and JSON, timestamps to ISO 8601"
190    )]
191    pub should_pretty_print: bool,
192    #[clap(
193         short = 's',
194         long = "map-symbols",
195         action = ArgAction::SetTrue,
196         default_value = "false",
197         conflicts_with_all = ["input_fragment", "dbn", "fragment"],
198         help ="Use symbology mappings from the metadata to create a 'symbol' field mapping the instrument ID to its requested symbol."
199    )]
200    pub map_symbols: bool,
201    #[clap(
202        short = 'l',
203        long = "limit",
204        value_name = "NUM_RECORDS",
205        help = "Limit the number of records in the output to the specified number"
206    )]
207    pub limit: Option<NonZeroU64>,
208    // Fragment arguments
209    #[clap(
210        long = "input-fragment",
211        action = ArgAction::SetTrue,
212        default_value = "false",
213        group = "input_fragment",
214        conflicts_with_all = ["is_input_zstd_fragment", "should_output_metadata", "dbn", "parquet", "arrow"],
215        help = "Interpret the input as an uncompressed DBN fragment, i.e. records without metadata. Only valid with text or DBN fragment output encodings"
216    )]
217    pub is_input_fragment: bool,
218    #[clap(
219        long = "input-zstd-fragment",
220        action = ArgAction::SetTrue,
221        default_value = "false",
222        group = "input_fragment",
223        conflicts_with_all = ["should_output_metadata", "dbn", "parquet", "arrow"],
224        help = "Interpret the input as a Zstd-compressed DBN fragment, i.e. records without metadata. Only valid with text or DBN fragment output encodings"
225    )]
226    pub is_input_zstd_fragment: bool,
227    #[clap(
228        long = "input-dbn-version",
229        help = "Specify the DBN version of the fragment. By default the fragment is assumed to be of the current version",
230        value_name = "DBN_VERSION",
231        value_parser = clap::value_parser!(u8).range(1..=3),
232        requires = "input_fragment"
233    )]
234    pub input_dbn_version_override: Option<u8>,
235    #[clap(
236        long = "schema",
237        help = "Only encode records of this schema. This is particularly useful for transcoding mixed-schema DBN to CSV, which doesn't support mixing schemas",
238        value_name = "SCHEMA"
239    )]
240    pub schema_filter: Option<Schema>,
241    #[clap(
242        long = "omit-header",
243        action = ArgAction::SetFalse,
244        default_value = "true",
245        conflicts_with_all = ["json", "dbn", "fragment", "parquet", "arrow"],
246        help = "Skip encoding the header. Only valid when encoding CSV or TSV."
247    )]
248    pub write_header: bool,
249}
250
251impl Args {
252    pub fn upgrade_policy(&self) -> VersionUpgradePolicy {
253        if self.should_upgrade {
254            VersionUpgradePolicy::UpgradeToV3
255        } else {
256            VersionUpgradePolicy::AsIs
257        }
258    }
259
260    pub fn input_version(&self) -> u8 {
261        self.input_dbn_version_override.unwrap_or(dbn::DBN_VERSION)
262    }
263}
264
265pub fn infer_encoding(args: &Args) -> anyhow::Result<InferredEncoding> {
266    let (format, zstd) = if let Some(format) = OUTPUT_FORMATS.iter().find(|f| (f.flag)(args)) {
267        (format, args.zstd)
268    } else {
269        let Some(output) = args
270            .output
271            .as_ref()
272            .map(|p| p.to_string_lossy().into_owned())
273            .or_else(|| args.output_pattern.clone())
274        else {
275            return Err(anyhow!(
276                "Unable to infer output encoding when no output was specified"
277            ));
278        };
279        let Some((format, extension)) = OUTPUT_FORMATS.iter().find_map(|f| {
280            f.extensions
281                .iter()
282                .find(|ext| output.ends_with(*ext))
283                .map(|ext| (f, ext))
284        }) else {
285            return Err(anyhow!(
286                "Unable to infer output encoding from output path '{output}'",
287            ));
288        };
289        (format, extension.ends_with(".zst"))
290    };
291    Ok(InferredEncoding {
292        encoding: format.encoding,
293        compression: if zstd {
294            Compression::Zstd
295        } else {
296            Compression::None
297        },
298        delimiter: format.delimiter,
299        is_fragment: format.is_fragment,
300    })
301}
302
303/// Returns a writeable object where the `dbn` output will be directed.
304pub fn output_from_args(args: &Args) -> anyhow::Result<Box<dyn io::Write + Send>> {
305    output(args.output.as_deref(), args.force)
306}
307
308pub fn output(output: Option<&Path>, force: bool) -> anyhow::Result<Box<dyn io::Write + Send>> {
309    if let Some(output) = output {
310        let output_file = open_output_file(output, force)?;
311        Ok(Box::new(BufWriter::new(output_file)))
312    } else {
313        // Wrap stdout in a BufWriter so each record write doesn't re-acquire
314        // stdout's internal lock. `StdoutLock` isn't `Send`.
315        Ok(Box::new(BufWriter::new(io::stdout())))
316    }
317}
318
319/// An output format of the `dbn` command: the flag that selects it, how it's encoded,
320/// and the output path extensions it's inferred from.
321struct OutputFormat {
322    flag: fn(&Args) -> bool,
323    encoding: OutputEncoding,
324    delimiter: u8,
325    is_fragment: bool,
326    /// Extensions ending in `.zst` infer Zstd compression.
327    extensions: &'static [&'static str],
328}
329
330const OUTPUT_FORMATS: [OutputFormat; 7] = [
331    OutputFormat {
332        flag: |args| args.json,
333        encoding: OutputEncoding::Json,
334        delimiter: 0,
335        is_fragment: false,
336        extensions: &[".json", ".json.zst"],
337    },
338    OutputFormat {
339        flag: |args| args.csv,
340        encoding: OutputEncoding::Csv,
341        delimiter: b',',
342        is_fragment: false,
343        extensions: &[".csv", ".csv.zst"],
344    },
345    OutputFormat {
346        flag: |args| args.tsv,
347        encoding: OutputEncoding::Csv,
348        delimiter: b'\t',
349        is_fragment: false,
350        extensions: &[".tsv", ".xls", ".tsv.zst", ".xls.zst"],
351    },
352    OutputFormat {
353        flag: |args| args.dbn,
354        encoding: OutputEncoding::Dbn,
355        delimiter: 0,
356        is_fragment: false,
357        extensions: &[".dbn", ".dbn.zst"],
358    },
359    OutputFormat {
360        flag: |args| args.fragment,
361        encoding: OutputEncoding::Dbn,
362        delimiter: 0,
363        is_fragment: true,
364        extensions: &[".dbn.frag", ".dbn.frag.zst"],
365    },
366    OutputFormat {
367        flag: |args| args.parquet,
368        encoding: OutputEncoding::Parquet,
369        delimiter: 0,
370        is_fragment: false,
371        extensions: &[".parquet"],
372    },
373    OutputFormat {
374        flag: |args| args.arrow,
375        encoding: OutputEncoding::Arrow,
376        delimiter: 0,
377        is_fragment: false,
378        extensions: &[".arrow", ".feather"],
379    },
380];
381
382fn open_output_file(path: &Path, force: bool) -> anyhow::Result<File> {
383    let mut options = File::options();
384    options.write(true).truncate(true);
385    if force {
386        options.create(true);
387    } else if path.exists() {
388        return Err(anyhow!(
389            "Output file exists. Pass --force flag to overwrite the existing file."
390        ));
391    } else {
392        options.create_new(true);
393    }
394    options
395        .open(path)
396        .with_context(|| format!("Unable to open output file '{}'", path.display()))
397}
398
399#[cfg(test)]
400mod tests {
401    #![allow(clippy::too_many_arguments)]
402
403    use rstest::*;
404
405    use super::*;
406
407    #[rstest]
408    #[case(
409        true,
410        false,
411        false,
412        false,
413        false,
414        OutputEncoding::Json,
415        Compression::None,
416        0
417    )]
418    #[case(
419        false,
420        true,
421        false,
422        false,
423        false,
424        OutputEncoding::Csv,
425        Compression::None,
426        b','
427    )]
428    #[case(
429        false,
430        false,
431        true,
432        false,
433        false,
434        OutputEncoding::Csv,
435        Compression::None,
436        b'\t'
437    )]
438    #[case(
439        false,
440        false,
441        false,
442        true,
443        false,
444        OutputEncoding::Dbn,
445        Compression::None,
446        0
447    )]
448    #[case(
449        true,
450        false,
451        false,
452        false,
453        true,
454        OutputEncoding::Json,
455        Compression::Zstd,
456        0
457    )]
458    #[case(
459        false,
460        true,
461        false,
462        false,
463        true,
464        OutputEncoding::Csv,
465        Compression::Zstd,
466        b','
467    )]
468    #[case(
469        false,
470        false,
471        true,
472        false,
473        true,
474        OutputEncoding::Csv,
475        Compression::Zstd,
476        b'\t'
477    )]
478    #[case(
479        false,
480        false,
481        false,
482        true,
483        true,
484        OutputEncoding::Dbn,
485        Compression::Zstd,
486        0
487    )]
488    fn test_infer_encoding_and_compression_explicit(
489        #[case] json: bool,
490        #[case] csv: bool,
491        #[case] tsv: bool,
492        #[case] dbn: bool,
493        #[case] zstd: bool,
494        #[case] exp_enc: OutputEncoding,
495        #[case] exp_comp: Compression,
496        #[case] exp_sep: u8,
497    ) {
498        let args = Args {
499            json,
500            csv,
501            tsv,
502            dbn,
503            zstd,
504            ..Default::default()
505        };
506        assert_eq!(
507            infer_encoding(&args).unwrap(),
508            InferredEncoding {
509                encoding: exp_enc,
510                compression: exp_comp,
511                delimiter: exp_sep,
512                is_fragment: false,
513            }
514        );
515    }
516
517    #[rstest]
518    #[case("out.json", OutputEncoding::Json, Compression::None, 0)]
519    #[case("out.csv", OutputEncoding::Csv, Compression::None, b',')]
520    #[case("out.tsv", OutputEncoding::Csv, Compression::None, b'\t')]
521    #[case("out.xls", OutputEncoding::Csv, Compression::None, b'\t')]
522    #[case("out.dbn", OutputEncoding::Dbn, Compression::None, 0)]
523    #[case("out.json.zst", OutputEncoding::Json, Compression::Zstd, 0)]
524    #[case("out.csv.zst", OutputEncoding::Csv, Compression::Zstd, b',')]
525    #[case("out.tsv.zst", OutputEncoding::Csv, Compression::Zstd, b'\t')]
526    #[case("out.xls.zst", OutputEncoding::Csv, Compression::Zstd, b'\t')]
527    #[case("out.dbn.zst", OutputEncoding::Dbn, Compression::Zstd, 0)]
528    fn test_infer_encoding_and_compression_inference(
529        #[case] output: &str,
530        #[case] exp_enc: OutputEncoding,
531        #[case] exp_comp: Compression,
532        #[case] exp_sep: u8,
533    ) {
534        let args = Args {
535            output: Some(PathBuf::from(output)),
536            ..Default::default()
537        };
538        assert_eq!(
539            infer_encoding(&args).unwrap(),
540            InferredEncoding {
541                encoding: exp_enc,
542                compression: exp_comp,
543                delimiter: exp_sep,
544                is_fragment: false,
545            }
546        );
547    }
548
549    #[rstest]
550    #[case("out.dbn.frag", OutputEncoding::Dbn, Compression::None, true)]
551    #[case("out.dbn.frag.zst", OutputEncoding::Dbn, Compression::Zstd, true)]
552    #[case("out.parquet", OutputEncoding::Parquet, Compression::None, false)]
553    #[case("out.arrow", OutputEncoding::Arrow, Compression::None, false)]
554    #[case("out.feather", OutputEncoding::Arrow, Compression::None, false)]
555    fn test_infer_encoding_fragment_and_columnar(
556        #[case] output: &str,
557        #[case] exp_enc: OutputEncoding,
558        #[case] exp_comp: Compression,
559        #[case] exp_fragment: bool,
560    ) {
561        let args = Args {
562            output: Some(PathBuf::from(output)),
563            ..Default::default()
564        };
565        assert_eq!(
566            infer_encoding(&args).unwrap(),
567            InferredEncoding {
568                encoding: exp_enc,
569                compression: exp_comp,
570                delimiter: 0,
571                is_fragment: exp_fragment,
572            }
573        );
574    }
575
576    #[rstest]
577    #[case::unknown("out.pb")]
578    #[case::columnar_zstd("out.parquet.zst")]
579    #[case::columnar_zstd("out.arrow.zst")]
580    fn test_infer_encoding_and_compression_bad(#[case] output: &str) {
581        let args = Args {
582            output: Some(PathBuf::from(output)),
583            ..Default::default()
584        };
585        assert!(
586            matches!(infer_encoding(&args), Err(e) if e.to_string().starts_with("Unable to infer"))
587        );
588    }
589}