|
| 1 | +use std::{ |
| 2 | + error::Error, |
| 3 | + fmt, fs, |
| 4 | + io::{self, BufReader, BufWriter, Read, Write}, |
| 5 | + path::PathBuf, |
| 6 | +}; |
| 7 | + |
| 8 | +use clap::{Args, Parser, Subcommand}; |
| 9 | +use errors::Errors; |
| 10 | +use git_version::git_version; |
| 11 | +use streambed::commit_log::{ConsumerOffset, Subscription}; |
| 12 | +use streambed_logged::FileLog; |
| 13 | + |
| 14 | +pub mod errors; |
| 15 | +pub mod producer; |
| 16 | +pub mod subscriber; |
| 17 | + |
| 18 | +/// A utility for conveniently operating on file-based commit logs. |
| 19 | +/// Functions such as the ability to consume a JSON file of records, |
| 20 | +/// or produce them, are available. |
| 21 | +/// No assumptions are made regarding the structure of a record's |
| 22 | +/// value (payload), or whether it is encrypted or not. The expectation |
| 23 | +/// is that a separate tool for that concern is used in a pipeline. |
| 24 | +#[derive(Parser, Debug)] |
| 25 | +#[clap(author, about, long_about = None, version = git_version ! ())] |
| 26 | +struct ProgramArgs { |
| 27 | + /// The location of all topics in the Commit Log |
| 28 | + #[clap(env, long, default_value = "/var/lib/logged")] |
| 29 | + pub root_path: PathBuf, |
| 30 | + |
| 31 | + #[command(subcommand)] |
| 32 | + pub command: Command, |
| 33 | +} |
| 34 | + |
| 35 | +#[derive(Subcommand, Debug)] |
| 36 | +enum Command { |
| 37 | + Produce(ProduceCommand), |
| 38 | + Subscribe(SubscribeCommand), |
| 39 | +} |
| 40 | + |
| 41 | +/// Consume JSON records from a stream until EOF and append them to the log. |
| 42 | +#[derive(Args, Debug)] |
| 43 | +struct ProduceCommand { |
| 44 | + /// The file to consume records from, or `-` to indicate STDIN. |
| 45 | + #[clap(env, short, long)] |
| 46 | + pub file: PathBuf, |
| 47 | +} |
| 48 | + |
| 49 | +/// Subscribe to topics and consume from them producing JSON records to a stream. |
| 50 | +#[derive(Args, Debug)] |
| 51 | +struct SubscribeCommand { |
| 52 | + /// The amount of time to indicate that no more events are immediately |
| 53 | + /// available from the Commit Log endpoint. If unspecified then the |
| 54 | + /// CLI will wait indefinitely for records to appear. |
| 55 | + #[clap(env, long)] |
| 56 | + pub idle_timeout: Option<humantime::Duration>, |
| 57 | + |
| 58 | + /// In the case that an offset is supplied, it is |
| 59 | + /// associated with their respective topics such that any |
| 60 | + /// subsequent subscription will source from the offset. |
| 61 | + /// The fields are topic name, partition and offset which |
| 62 | + /// are separated by commas with no spaces e.g. "--offset=my-topic,0,1000". |
| 63 | + #[clap(env, long)] |
| 64 | + #[arg(value_parser = parse_offset)] |
| 65 | + pub offset: Vec<Offset>, |
| 66 | + |
| 67 | + /// By default, records of the topic are consumed and output to STDOUT. |
| 68 | + /// This option can be used to write to a file. Records are output as JSON. |
| 69 | + #[clap(env, short, long)] |
| 70 | + pub output: Option<PathBuf>, |
| 71 | + |
| 72 | + /// In the case where a subscription topic names are supplied, the consumer |
| 73 | + /// instance will subscribe and reply with a stream of records |
| 74 | + /// ending only when the connection to the topic is severed. |
| 75 | + /// Topics may be namespaced by prefixing with characters followed by |
| 76 | + /// a `:`. For example, "my-ns:my-topic". |
| 77 | + #[clap(env, long, required = true)] |
| 78 | + pub subscription: Vec<String>, |
| 79 | +} |
| 80 | + |
| 81 | +#[derive(Clone, Debug)] |
| 82 | +struct Offset { |
| 83 | + pub topic: String, |
| 84 | + pub partition: u32, |
| 85 | + pub offset: u64, |
| 86 | +} |
| 87 | + |
| 88 | +impl From<Offset> for ConsumerOffset { |
| 89 | + fn from(value: Offset) -> Self { |
| 90 | + ConsumerOffset { |
| 91 | + topic: value.topic.into(), |
| 92 | + partition: value.partition, |
| 93 | + offset: value.offset, |
| 94 | + } |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +#[derive(Debug)] |
| 99 | +enum OffsetParseError { |
| 100 | + MissingTopic, |
| 101 | + MissingPartition, |
| 102 | + InvalidPartition, |
| 103 | + MissingOffset, |
| 104 | + InvalidOffset, |
| 105 | +} |
| 106 | + |
| 107 | +impl fmt::Display for OffsetParseError { |
| 108 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 109 | + match self { |
| 110 | + OffsetParseError::MissingTopic => { |
| 111 | + f.write_str("Missing the topic as the first part of the argument") |
| 112 | + } |
| 113 | + OffsetParseError::MissingPartition => { |
| 114 | + f.write_str("Missing the partition number as the second part to the argument") |
| 115 | + } |
| 116 | + OffsetParseError::InvalidPartition => { |
| 117 | + f.write_str("An invalid partition number was provided") |
| 118 | + } |
| 119 | + OffsetParseError::MissingOffset => { |
| 120 | + f.write_str("Missing the offset as the third part to the argument") |
| 121 | + } |
| 122 | + OffsetParseError::InvalidOffset => f.write_str("An invalid offset number was provided"), |
| 123 | + } |
| 124 | + } |
| 125 | +} |
| 126 | + |
| 127 | +impl Error for OffsetParseError {} |
| 128 | + |
| 129 | +fn parse_offset(arg: &str) -> Result<Offset, OffsetParseError> { |
| 130 | + let mut iter = arg.split(','); |
| 131 | + let Some(topic) = iter.next().map(|s| s.to_string()) else { |
| 132 | + return Err(OffsetParseError::MissingTopic); |
| 133 | + }; |
| 134 | + let Some(partition) = iter.next() else { |
| 135 | + return Err(OffsetParseError::MissingPartition); |
| 136 | + }; |
| 137 | + let Ok(partition) = partition.parse() else { |
| 138 | + return Err(OffsetParseError::InvalidPartition); |
| 139 | + }; |
| 140 | + let Some(offset) = iter.next() else { |
| 141 | + return Err(OffsetParseError::MissingOffset); |
| 142 | + }; |
| 143 | + let Ok(offset) = offset.parse() else { |
| 144 | + return Err(OffsetParseError::InvalidOffset); |
| 145 | + }; |
| 146 | + Ok(Offset { |
| 147 | + topic, |
| 148 | + partition, |
| 149 | + offset, |
| 150 | + }) |
| 151 | +} |
| 152 | + |
| 153 | +#[tokio::main] |
| 154 | +async fn main() -> Result<(), Box<dyn Error>> { |
| 155 | + let args = ProgramArgs::parse(); |
| 156 | + |
| 157 | + env_logger::builder().format_timestamp_millis().init(); |
| 158 | + |
| 159 | + let cl = FileLog::new(args.root_path); |
| 160 | + |
| 161 | + let task = tokio::spawn(async move { |
| 162 | + match args.command { |
| 163 | + Command::Produce(command) => { |
| 164 | + let input: Box<dyn Read + Send> = if command.file.as_os_str() == "-" { |
| 165 | + Box::new(io::stdin()) |
| 166 | + } else { |
| 167 | + Box::new(BufReader::new( |
| 168 | + fs::File::open(command.file).map_err(Errors::from)?, |
| 169 | + )) |
| 170 | + }; |
| 171 | + producer::produce(cl, input).await |
| 172 | + } |
| 173 | + Command::Subscribe(command) => { |
| 174 | + let output: Box<dyn Write + Send> = if let Some(output) = command.output { |
| 175 | + Box::new(BufWriter::new( |
| 176 | + fs::File::create(output).map_err(Errors::from)?, |
| 177 | + )) |
| 178 | + } else { |
| 179 | + Box::new(io::stdout()) |
| 180 | + }; |
| 181 | + subscriber::subscribe( |
| 182 | + cl, |
| 183 | + command.idle_timeout.map(|d| d.into()), |
| 184 | + command.offset.into_iter().map(|o| o.into()).collect(), |
| 185 | + output, |
| 186 | + command |
| 187 | + .subscription |
| 188 | + .into_iter() |
| 189 | + .map(|s| Subscription { topic: s.into() }) |
| 190 | + .collect(), |
| 191 | + ) |
| 192 | + .await |
| 193 | + } |
| 194 | + } |
| 195 | + }); |
| 196 | + |
| 197 | + task.await |
| 198 | + .map_err(|e| e.into()) |
| 199 | + .and_then(|r: Result<(), Errors>| r.map_err(|e| e.into())) |
| 200 | +} |
0 commit comments