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        value_name = "DBN_VERSION",
162        value_parser = clap::value_parser!(u8).range(2..=4),
163        help = "Upgrade data from previous DBN versions to DBN_VERSION. By default data is decoded as-is"
164    )]
165    pub upgrade_version: Option<u8>,
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, input_versions: &[u8]) -> anyhow::Result<VersionUpgradePolicy> {
253        let has_v4_input = input_versions.contains(&dbn::v4::DBN_VERSION);
254        match self.upgrade_version {
255            Some(version) if has_v4_input && version < dbn::v4::DBN_VERSION => Err(anyhow!(
256                "Can't downgrade DBN version 4 input to version {version}"
257            )),
258            None if has_v4_input
259                && input_versions
260                    .iter()
261                    .any(|version| *version < dbn::v4::DBN_VERSION) =>
262            {
263                Err(anyhow!(
264                    "Merging DBN version 4 with earlier versions requires `--upgrade 4`"
265                ))
266            }
267            None if has_v4_input => Ok(VersionUpgradePolicy::ExpectV4),
268            None => Ok(VersionUpgradePolicy::AsIs),
269            Some(2) => Ok(VersionUpgradePolicy::UpgradeToV2),
270            Some(3) => Ok(VersionUpgradePolicy::UpgradeToV3),
271            Some(_) => Ok(VersionUpgradePolicy::UpgradeToV4),
272        }
273    }
274
275    pub fn input_fragment_compression(&self) -> Option<Compression> {
276        if self.is_input_zstd_fragment {
277            Some(Compression::Zstd)
278        } else if self.is_input_fragment {
279            Some(Compression::None)
280        } else {
281            None
282        }
283    }
284
285    pub fn input_version(&self) -> u8 {
286        self.input_dbn_version_override.unwrap_or(dbn::DBN_VERSION)
287    }
288}
289
290pub fn infer_encoding(args: &Args) -> anyhow::Result<InferredEncoding> {
291    let (format, zstd) = if let Some(format) = OUTPUT_FORMATS.iter().find(|f| (f.flag)(args)) {
292        (format, args.zstd)
293    } else {
294        let Some(output) = args
295            .output
296            .as_ref()
297            .map(|p| p.to_string_lossy().into_owned())
298            .or_else(|| args.output_pattern.clone())
299        else {
300            return Err(anyhow!(
301                "Unable to infer output encoding when no output was specified"
302            ));
303        };
304        let Some((format, extension)) = OUTPUT_FORMATS.iter().find_map(|f| {
305            f.extensions
306                .iter()
307                .find(|ext| output.ends_with(*ext))
308                .map(|ext| (f, ext))
309        }) else {
310            return Err(anyhow!(
311                "Unable to infer output encoding from output path '{output}'",
312            ));
313        };
314        (format, args.zstd || extension.ends_with(".zst"))
315    };
316    Ok(InferredEncoding {
317        encoding: format.encoding,
318        compression: if zstd {
319            Compression::Zstd
320        } else {
321            Compression::None
322        },
323        delimiter: format.delimiter,
324        is_fragment: format.is_fragment,
325    })
326}
327
328/// Returns a writeable object where the `dbn` output will be directed.
329pub fn output_from_args(args: &Args) -> anyhow::Result<Box<dyn io::Write + Send>> {
330    output(args.output.as_deref(), args.force)
331}
332
333pub fn output(output: Option<&Path>, force: bool) -> anyhow::Result<Box<dyn io::Write + Send>> {
334    if let Some(output) = output {
335        let output_file = open_output_file(output, force)?;
336        Ok(Box::new(BufWriter::new(output_file)))
337    } else {
338        // Wrap stdout in a BufWriter so each record write doesn't re-acquire
339        // stdout's internal lock. `StdoutLock` isn't `Send`.
340        Ok(Box::new(BufWriter::new(io::stdout())))
341    }
342}
343
344/// An output format of the `dbn` command: the flag that selects it, how it's encoded,
345/// and the output path extensions it's inferred from.
346struct OutputFormat {
347    flag: fn(&Args) -> bool,
348    encoding: OutputEncoding,
349    delimiter: u8,
350    is_fragment: bool,
351    /// Extensions ending in `.zst` infer Zstd compression.
352    extensions: &'static [&'static str],
353}
354
355const OUTPUT_FORMATS: [OutputFormat; 7] = [
356    OutputFormat {
357        flag: |args| args.json,
358        encoding: OutputEncoding::Json,
359        delimiter: 0,
360        is_fragment: false,
361        extensions: &[".json", ".json.zst"],
362    },
363    OutputFormat {
364        flag: |args| args.csv,
365        encoding: OutputEncoding::Csv,
366        delimiter: b',',
367        is_fragment: false,
368        extensions: &[".csv", ".csv.zst"],
369    },
370    OutputFormat {
371        flag: |args| args.tsv,
372        encoding: OutputEncoding::Csv,
373        delimiter: b'\t',
374        is_fragment: false,
375        extensions: &[".tsv", ".xls", ".tsv.zst", ".xls.zst"],
376    },
377    OutputFormat {
378        flag: |args| args.dbn,
379        encoding: OutputEncoding::Dbn,
380        delimiter: 0,
381        is_fragment: false,
382        extensions: &[".dbn", ".dbn.zst"],
383    },
384    OutputFormat {
385        flag: |args| args.fragment,
386        encoding: OutputEncoding::Dbn,
387        delimiter: 0,
388        is_fragment: true,
389        extensions: &[".dbn.frag", ".dbn.frag.zst"],
390    },
391    OutputFormat {
392        flag: |args| args.parquet,
393        encoding: OutputEncoding::Parquet,
394        delimiter: 0,
395        is_fragment: false,
396        extensions: &[".parquet"],
397    },
398    OutputFormat {
399        flag: |args| args.arrow,
400        encoding: OutputEncoding::Arrow,
401        delimiter: 0,
402        is_fragment: false,
403        extensions: &[".arrow", ".feather"],
404    },
405];
406
407fn open_output_file(path: &Path, force: bool) -> anyhow::Result<File> {
408    let mut options = File::options();
409    options.write(true).truncate(true);
410    if force {
411        options.create(true);
412    } else if path.exists() {
413        return Err(anyhow!(
414            "Output file exists. Pass --force flag to overwrite the existing file."
415        ));
416    } else {
417        options.create_new(true);
418    }
419    options
420        .open(path)
421        .with_context(|| format!("Unable to open output file '{}'", path.display()))
422}
423
424#[cfg(test)]
425mod tests {
426    #![allow(clippy::too_many_arguments)]
427
428    use rstest::*;
429
430    use super::*;
431
432    #[rstest]
433    #[case(
434        true,
435        false,
436        false,
437        false,
438        false,
439        OutputEncoding::Json,
440        Compression::None,
441        0
442    )]
443    #[case(
444        false,
445        true,
446        false,
447        false,
448        false,
449        OutputEncoding::Csv,
450        Compression::None,
451        b','
452    )]
453    #[case(
454        false,
455        false,
456        true,
457        false,
458        false,
459        OutputEncoding::Csv,
460        Compression::None,
461        b'\t'
462    )]
463    #[case(
464        false,
465        false,
466        false,
467        true,
468        false,
469        OutputEncoding::Dbn,
470        Compression::None,
471        0
472    )]
473    #[case(
474        true,
475        false,
476        false,
477        false,
478        true,
479        OutputEncoding::Json,
480        Compression::Zstd,
481        0
482    )]
483    #[case(
484        false,
485        true,
486        false,
487        false,
488        true,
489        OutputEncoding::Csv,
490        Compression::Zstd,
491        b','
492    )]
493    #[case(
494        false,
495        false,
496        true,
497        false,
498        true,
499        OutputEncoding::Csv,
500        Compression::Zstd,
501        b'\t'
502    )]
503    #[case(
504        false,
505        false,
506        false,
507        true,
508        true,
509        OutputEncoding::Dbn,
510        Compression::Zstd,
511        0
512    )]
513    fn test_infer_encoding_and_compression_explicit(
514        #[case] json: bool,
515        #[case] csv: bool,
516        #[case] tsv: bool,
517        #[case] dbn: bool,
518        #[case] zstd: bool,
519        #[case] exp_enc: OutputEncoding,
520        #[case] exp_comp: Compression,
521        #[case] exp_sep: u8,
522    ) {
523        let args = Args {
524            json,
525            csv,
526            tsv,
527            dbn,
528            zstd,
529            ..Default::default()
530        };
531        assert_eq!(
532            infer_encoding(&args).unwrap(),
533            InferredEncoding {
534                encoding: exp_enc,
535                compression: exp_comp,
536                delimiter: exp_sep,
537                is_fragment: false,
538            }
539        );
540    }
541
542    #[rstest]
543    #[case("out.json", OutputEncoding::Json, Compression::None, 0)]
544    #[case("out.csv", OutputEncoding::Csv, Compression::None, b',')]
545    #[case("out.tsv", OutputEncoding::Csv, Compression::None, b'\t')]
546    #[case("out.xls", OutputEncoding::Csv, Compression::None, b'\t')]
547    #[case("out.dbn", OutputEncoding::Dbn, Compression::None, 0)]
548    #[case("out.json.zst", OutputEncoding::Json, Compression::Zstd, 0)]
549    #[case("out.csv.zst", OutputEncoding::Csv, Compression::Zstd, b',')]
550    #[case("out.tsv.zst", OutputEncoding::Csv, Compression::Zstd, b'\t')]
551    #[case("out.xls.zst", OutputEncoding::Csv, Compression::Zstd, b'\t')]
552    #[case("out.dbn.zst", OutputEncoding::Dbn, Compression::Zstd, 0)]
553    fn test_infer_encoding_and_compression_inference(
554        #[case] output: &str,
555        #[case] exp_enc: OutputEncoding,
556        #[case] exp_comp: Compression,
557        #[case] exp_sep: u8,
558    ) {
559        let args = Args {
560            output: Some(PathBuf::from(output)),
561            ..Default::default()
562        };
563        assert_eq!(
564            infer_encoding(&args).unwrap(),
565            InferredEncoding {
566                encoding: exp_enc,
567                compression: exp_comp,
568                delimiter: exp_sep,
569                is_fragment: false,
570            }
571        );
572    }
573
574    #[rstest]
575    #[case("out.dbn.frag", OutputEncoding::Dbn, Compression::None, true)]
576    #[case("out.dbn.frag.zst", OutputEncoding::Dbn, Compression::Zstd, true)]
577    #[case("out.parquet", OutputEncoding::Parquet, Compression::None, false)]
578    #[case("out.arrow", OutputEncoding::Arrow, Compression::None, false)]
579    #[case("out.feather", OutputEncoding::Arrow, Compression::None, false)]
580    fn test_infer_encoding_fragment_and_columnar(
581        #[case] output: &str,
582        #[case] exp_enc: OutputEncoding,
583        #[case] exp_comp: Compression,
584        #[case] exp_fragment: bool,
585    ) {
586        let args = Args {
587            output: Some(PathBuf::from(output)),
588            ..Default::default()
589        };
590        assert_eq!(
591            infer_encoding(&args).unwrap(),
592            InferredEncoding {
593                encoding: exp_enc,
594                compression: exp_comp,
595                delimiter: 0,
596                is_fragment: exp_fragment,
597            }
598        );
599    }
600
601    #[rstest]
602    #[case("out.csv", OutputEncoding::Csv)]
603    #[case("out.csv.zst", OutputEncoding::Csv)]
604    #[case("out.dbn", OutputEncoding::Dbn)]
605    #[case("out.parquet", OutputEncoding::Parquet)]
606    #[case("out.arrow", OutputEncoding::Arrow)]
607    fn test_infer_encoding_zstd_flag_with_inferred_encoding(
608        #[case] output: &str,
609        #[case] exp_enc: OutputEncoding,
610    ) {
611        let args = Args {
612            output: Some(PathBuf::from(output)),
613            zstd: true,
614            ..Default::default()
615        };
616        let inferred = infer_encoding(&args).unwrap();
617        assert_eq!(inferred.encoding, exp_enc);
618        assert_eq!(inferred.compression, Compression::Zstd);
619    }
620
621    #[rstest]
622    #[case::unknown("out.pb")]
623    #[case::columnar_zstd("out.parquet.zst")]
624    #[case::columnar_zstd("out.arrow.zst")]
625    fn test_infer_encoding_and_compression_bad(#[case] output: &str) {
626        let args = Args {
627            output: Some(PathBuf::from(output)),
628            ..Default::default()
629        };
630        assert!(
631            matches!(infer_encoding(&args), Err(e) if e.to_string().starts_with("Unable to infer"))
632        );
633    }
634}