Repository: sevagh/pq Branch: master Commit: 94f09f1f693d Files: 49 Total size: 67.8 KB Directory structure: gitextract_tt0fh83e/ ├── .gitignore ├── Cargo.toml ├── LICENSE ├── Makefile ├── README.md ├── erased-serde-json/ │ ├── .gitignore │ ├── Cargo.toml │ ├── LICENSE-APACHE │ ├── LICENSE-MIT │ ├── README.md │ └── src/ │ ├── lib.rs │ └── ser.rs ├── src/ │ ├── commands.rs │ ├── decode.rs │ ├── discovery.rs │ ├── formatter.rs │ └── main.rs ├── stream-delimit/ │ ├── Cargo.toml │ ├── LICENSE │ ├── README.md │ └── src/ │ ├── byte_consumer.rs │ ├── converter.rs │ ├── error.rs │ ├── kafka_consumer.rs │ ├── lib.rs │ ├── stream.rs │ └── varint.rs ├── tests/ │ ├── README.md │ ├── fdsets/ │ │ ├── cat.fdset │ │ ├── dog.fdset │ │ └── person.fdset │ ├── fdsets-invalid/ │ │ └── .gitignore │ ├── protos/ │ │ └── dog.proto │ ├── samples/ │ │ ├── bad │ │ ├── cat │ │ ├── dog │ │ ├── dog_i32be_stream │ │ ├── dog_stream │ │ ├── person │ │ └── person_stream │ └── test_pqrs_bin.rs └── utils/ ├── .gitignore ├── GNUmakefile ├── README.txt ├── cat.proto ├── dog.proto ├── person.proto ├── proto_encoder.py └── requirements.txt ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ target rust *.tar.gz *~ *.bk pq ================================================ FILE: Cargo.toml ================================================ [package] name = "pq" version = "1.4.4" authors = ["Sevag Hanssian "] description = "jq for protobuf" repository = "https://github.com/sevagh/pq" documentation = "https://github.com/sevagh/pq" readme = "README.md" license = "MIT" keywords = ["protobuf", "serde"] exclude = ["pq-bin.tar.gz", "pq", "target/**"] edition = "2021" [dependencies] openssl = { version = "0.10", features = ["vendored"] } serde = "1.0" erased_serde_json = { path = "erased-serde-json", version = "0.1.3" } serde_json = "1.0" serde-protobuf = "0.8" protobuf = "2.3" stream_delimit = { path = "stream-delimit", version = "0.5.7" } clap = "2" libc = "0.2" dirs = "2.0" serde-transcode = ">= 1.1, <2" default-env = "0.1.1" [dev-dependencies] assert_cli = "0.6" [features] default = ["stream_delimit/with_kafka"] [workspace] members = ["stream-delimit", "erased-serde-json"] default-members = [".", "stream-delimit", "erased-serde-json"] [profile.release] debug = true lto = true panic = "abort" ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2017 Sevag Hanssian Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: Makefile ================================================ WORKSPACES="./" "./stream-delimit/" DOCKER_BIN ?= docker DOCKER_IMAGE=docker.io/clux/muslrust DOCKER_ARGS=run -v $(PWD):/volume:Z -w /volume -t $(DOCKER_IMAGE) CARGO_TOKEN:=$(shell grep 'token' ~/.cargo/credentials.toml | cut -d'"' -f2) all: debug docker: $(DOCKER_BIN) pull $(DOCKER_IMAGE) debug: docker $(DOCKER_BIN) $(DOCKER_ARGS) sh -c "cargo build --verbose" release: docker $(DOCKER_BIN) $(DOCKER_ARGS) sh -c "cargo build --verbose --release" test: docker $(DOCKER_BIN) $(DOCKER_ARGS) sh -c "cargo test --verbose" publish: docker $(DOCKER_BIN) $(DOCKER_ARGS) sh -c "cargo login $(CARGO_TOKEN) && cd stream-delimit && cargo publish ; cd ../ && cd erased-serde-json && cargo publish ; cd ../ && cargo publish" fmt: -cargo fmt --all -black utils/*.py clippy: -cargo clippy --all package: release tar -C target/x86_64-unknown-linux-musl/release -czvf pq-bin.tar.gz pq .PHONY: all debug release package ================================================ FILE: README.md ================================================ # pq [![license](https://img.shields.io/github/license/sevagh/pq.svg)](https://github.com/sevagh/pq/blob/master/LICENSE) [![Crates.io](https://img.shields.io/crates/v/pq.svg)](https://crates.io/crates/pq) ### protobuf to json deserializer, written in Rust `pq` is a tool which deserializes protobuf messages given a set of pre-compiled `.fdset` files. It can understand varint/leb128-delimited/i32be streams, and it can connect to Kafka. `pq` will pretty-print when outputting to a tty, but you should pipe it to `jq` for more fully-featured json handling. ### Download pq is on [crates.io](https://crates.io/crates/pq): `cargo install pq`. You can also download a static binary from the [releases page](https://github.com/sevagh/pq/releases). ### Usage **new** You can now pass in a proto file and have pq compile it on the fly using `protoc`: ``` $ pq --protofile ./tests/protos/dog.proto --msgtype com.example.dog.Dog <./tests/samples/dog { "breed": "gsd", "age": 3, "temperament": "excited" } ``` Use PROTOC and PROTOC_INCLUDE to control the executed protoc binary and configure the `-I=/proto/path` argument (design copied from [prost](https://github.com/danburkert/prost/blob/master/prost-build/src/lib.rs)). To set up, put your `*.fdset` files in `~/.pq`, `/etc/pq`, or a different directory specified with the `FDSET_PATH` env var: ``` $ protoc -o dog.fdset dog.proto $ protoc -o person.fdset person.proto $ cp *.fdset ~/.pq/ ``` You can specify additional fdset directories or files via options: ``` $ pq --msgtype com.example.dog.Dog --fdsetdir ./tests/fdsets <./tests/samples/dog $ pq --msgtype com.example.dog.Dog --fdsetfile ./tests/fdsets/dog.fdset <./tests/samples/dog ``` Pipe a single compiled protobuf message: ``` $ pq --msgtype com.example.dog.Dog <./tests/samples/dog { "age": 4, "breed": "poodle", "temperament": "excited" } ``` Pipe a `varint` or `leb128` delimited stream: ``` $ pq --msgtype com.example.dog.Dog --stream varint <./tests/samples/dog_stream { "age": 10, "breed": "gsd", "temperament": "aggressive" } ``` Consume from a Kafka stream: ``` $ pq kafka my_topic --brokers 192.168.0.1:9092 --beginning --count 1 --msgtype com.example.dog.Dog { "age": 10, "breed": "gsd", "temperament": "aggressive" } ``` Convert a Kafka stream to varint-delimited: ``` $ pq kafka my_topic --brokers=192.168.0.1:9092 --count 1 --convert varint |\ > pq --msgtype com.example.dog.Dog --stream varint { "age": 10, "breed": "gsd", "temperament": "aggressive" } ``` Pipe `kafkacat` output to it: ``` $ kafkacat -b 192.168.0.1:9092 -C -u -q -f "%R%s" -t my_topic |\ > pq --msgtype=com.example.dog.Dog --stream i32be { "age": 10, "breed": "gsd", "temperament": "aggressive" } ``` ### Compile without kafka To compile `pq` without kafka support, run: ``` $ cargo build --no-default-features ``` ### Compile for Windows 1. Install [Visual Studio Installer](https://visualstudio.microsoft.com/downloads/) Community edition 2. Run the installer and install `Visual Studio Build Tools 2019`. You need the `C++ Build Tools` workload. Note that you can't just install the minimal package, you also need `MSVC C++ x64/86 Build Tools` and `Windows 10 SDK`. 3. Open `x64 Native Tools Command Prompt` from the start menu. 4. Download and run [`rustup-init.exe`](https://win.rustup.rs/x86_64) 5. Close and reopen your terminal (so `cargo` will be in your path) 6. Run `cargo install --no-default-features pq` Note that this will disable the Kafka feature, which is not currently supported on Windows. ================================================ FILE: erased-serde-json/.gitignore ================================================ target/ **/*.rs.bk *.sw[po] Cargo.lock ================================================ FILE: erased-serde-json/Cargo.toml ================================================ [package] name = "erased_serde_json" version = "0.1.3" authors = ["Sevag Hanssian "] license = "MIT/Apache-2.0" description = "Type-erased Formatter trait for serde_json::ser::Formatter" repository = "https://github.com/sevagh/erased-serde-json" documentation = "https://github.com/sevagh/erased-serde-json" keywords = ["json", "serde", "serialization"] categories = ["encoding"] readme = "README.md" include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] edition = "2018" [dependencies] serde = "1.0" serde_json = "1.0.2" ================================================ FILE: erased-serde-json/LICENSE-APACHE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: erased-serde-json/LICENSE-MIT ================================================ Copyright (c) 2014 The Rust Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: erased-serde-json/README.md ================================================ Inspired by https://github.com/dtolnay/erased-serde # erased-serde-json [![Crates.io](https://img.shields.io/crates/v/erased_serde_json.svg)](https://crates.io/crates/erased_serde_json) [![Crates.io](https://img.shields.io/crates/d/erased_serde_json.svg)](https://github.com/sevagh/pq/tree/master/erased-serde-json) A helper crate for pq. ================================================ FILE: erased-serde-json/src/lib.rs ================================================ extern crate serde; extern crate serde_json; pub use self::ser::Formatter; pub mod ser; ================================================ FILE: erased-serde-json/src/ser.rs ================================================ use std::io; use serde_json::ser::CharEscape; pub trait Formatter { fn erased_write_null(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>; fn erased_write_bool( &mut self, writer: &mut dyn io::Write, value: bool, ) -> Result<(), io::Error>; fn erased_write_i8(&mut self, writer: &mut dyn io::Write, value: i8) -> Result<(), io::Error>; fn erased_write_i16(&mut self, writer: &mut dyn io::Write, value: i16) -> Result<(), io::Error>; fn erased_write_i32(&mut self, writer: &mut dyn io::Write, value: i32) -> Result<(), io::Error>; fn erased_write_i64(&mut self, writer: &mut dyn io::Write, value: i64) -> Result<(), io::Error>; fn erased_write_u8(&mut self, writer: &mut dyn io::Write, value: u8) -> Result<(), io::Error>; fn erased_write_u16(&mut self, writer: &mut dyn io::Write, value: u16) -> Result<(), io::Error>; fn erased_write_u32(&mut self, writer: &mut dyn io::Write, value: u32) -> Result<(), io::Error>; fn erased_write_u64(&mut self, writer: &mut dyn io::Write, value: u64) -> Result<(), io::Error>; fn erased_write_f32(&mut self, writer: &mut dyn io::Write, value: f32) -> Result<(), io::Error>; fn erased_write_f64(&mut self, writer: &mut dyn io::Write, value: f64) -> Result<(), io::Error>; fn erased_begin_string(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>; fn erased_end_string(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>; fn erased_write_string_fragment( &mut self, writer: &mut dyn io::Write, fragment: &str, ) -> Result<(), io::Error>; fn erased_write_char_escape( &mut self, writer: &mut dyn io::Write, char_escape: CharEscape, ) -> Result<(), io::Error>; fn erased_begin_array(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>; fn erased_end_array(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>; fn erased_begin_array_value( &mut self, writer: &mut dyn io::Write, first: bool, ) -> Result<(), io::Error>; fn erased_end_array_value(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>; fn erased_begin_object(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>; fn erased_end_object(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>; fn erased_begin_object_key( &mut self, writer: &mut dyn io::Write, first: bool, ) -> Result<(), io::Error>; fn erased_end_object_key(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>; fn erased_begin_object_value(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>; fn erased_end_object_value(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>; } impl Formatter for T where T: serde_json::ser::Formatter, { fn erased_write_null(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> { self.write_null(w) } fn erased_write_bool(&mut self, w: &mut dyn io::Write, v: bool) -> Result<(), io::Error> { self.write_bool(w, v) } fn erased_write_i8(&mut self, w: &mut dyn io::Write, v: i8) -> Result<(), io::Error> { self.write_i8(w, v) } fn erased_write_i16(&mut self, w: &mut dyn io::Write, v: i16) -> Result<(), io::Error> { self.write_i16(w, v) } fn erased_write_i32(&mut self, w: &mut dyn io::Write, v: i32) -> Result<(), io::Error> { self.write_i32(w, v) } fn erased_write_i64(&mut self, w: &mut dyn io::Write, v: i64) -> Result<(), io::Error> { self.write_i64(w, v) } fn erased_write_u8(&mut self, w: &mut dyn io::Write, v: u8) -> Result<(), io::Error> { self.write_u8(w, v) } fn erased_write_u16(&mut self, w: &mut dyn io::Write, v: u16) -> Result<(), io::Error> { self.write_u16(w, v) } fn erased_write_u32(&mut self, w: &mut dyn io::Write, v: u32) -> Result<(), io::Error> { self.write_u32(w, v) } fn erased_write_u64(&mut self, w: &mut dyn io::Write, v: u64) -> Result<(), io::Error> { self.write_u64(w, v) } fn erased_write_f32(&mut self, w: &mut dyn io::Write, v: f32) -> Result<(), io::Error> { self.write_f32(w, v) } fn erased_write_f64(&mut self, w: &mut dyn io::Write, v: f64) -> Result<(), io::Error> { self.write_f64(w, v) } fn erased_begin_string(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> { self.begin_string(w) } fn erased_end_string(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> { self.end_string(w) } fn erased_write_string_fragment( &mut self, w: &mut dyn io::Write, fragment: &str, ) -> Result<(), io::Error> { self.write_string_fragment(w, fragment) } fn erased_write_char_escape( &mut self, w: &mut dyn io::Write, char_escape: CharEscape, ) -> Result<(), io::Error> { self.write_char_escape(w, char_escape) } fn erased_begin_array(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> { self.begin_array(w) } fn erased_end_array(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> { self.end_array(w) } fn erased_begin_array_value( &mut self, w: &mut dyn io::Write, first: bool, ) -> Result<(), io::Error> { self.begin_array_value(w, first) } fn erased_end_array_value(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> { self.end_array_value(w) } fn erased_begin_object(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> { self.begin_object(w) } fn erased_end_object(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> { self.end_object(w) } fn erased_begin_object_key( &mut self, w: &mut dyn io::Write, first: bool, ) -> Result<(), io::Error> { self.begin_object_key(w, first) } fn erased_end_object_key(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> { self.end_object_key(w) } fn erased_begin_object_value(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> { self.begin_object_value(w) } fn erased_end_object_value(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> { self.end_object_value(w) } } macro_rules! impl_formatter_for_trait_object { ($ty:ty) => { impl<'a> serde_json::ser::Formatter for $ty { fn write_null( &mut self, mut w: &mut W, ) -> Result<(), io::Error> { self.erased_write_null(&mut w) } fn write_bool( &mut self, mut w: &mut W, v: bool, ) -> Result<(), io::Error> { self.erased_write_bool(&mut w, v) } fn write_i8( &mut self, mut w: &mut W, v: i8, ) -> Result<(), io::Error> { self.erased_write_i8(&mut w, v) } fn write_i16( &mut self, mut w: &mut W, v: i16, ) -> Result<(), io::Error> { self.erased_write_i16(&mut w, v) } fn write_i32( &mut self, mut w: &mut W, v: i32, ) -> Result<(), io::Error> { self.erased_write_i32(&mut w, v) } fn write_i64( &mut self, mut w: &mut W, v: i64, ) -> Result<(), io::Error> { self.erased_write_i64(&mut w, v) } fn write_u8( &mut self, mut w: &mut W, v: u8, ) -> Result<(), io::Error> { self.erased_write_u8(&mut w, v) } fn write_u16( &mut self, mut w: &mut W, v: u16, ) -> Result<(), io::Error> { self.erased_write_u16(&mut w, v) } fn write_u32( &mut self, mut w: &mut W, v: u32, ) -> Result<(), io::Error> { self.erased_write_u32(&mut w, v) } fn write_u64( &mut self, mut w: &mut W, v: u64, ) -> Result<(), io::Error> { self.erased_write_u64(&mut w, v) } fn write_f32( &mut self, mut w: &mut W, v: f32, ) -> Result<(), io::Error> { self.erased_write_f32(&mut w, v) } fn write_f64( &mut self, mut w: &mut W, v: f64, ) -> Result<(), io::Error> { self.erased_write_f64(&mut w, v) } fn begin_string( &mut self, mut w: &mut W, ) -> Result<(), io::Error> { self.erased_begin_string(&mut w) } fn end_string( &mut self, mut w: &mut W, ) -> Result<(), io::Error> { self.erased_end_string(&mut w) } fn write_string_fragment( &mut self, mut w: &mut W, fragment: &str, ) -> Result<(), io::Error> { self.erased_write_string_fragment(&mut w, fragment) } fn write_char_escape( &mut self, mut w: &mut W, char_escape: CharEscape, ) -> Result<(), io::Error> { self.erased_write_char_escape(&mut w, char_escape) } fn begin_array( &mut self, mut w: &mut W, ) -> Result<(), io::Error> { self.erased_begin_array(&mut w) } fn end_array(&mut self, mut w: &mut W) -> Result<(), io::Error> { self.erased_end_array(&mut w) } fn begin_array_value( &mut self, mut w: &mut W, first: bool, ) -> Result<(), io::Error> { self.erased_begin_array_value(&mut w, first) } fn end_array_value( &mut self, mut w: &mut W, ) -> Result<(), io::Error> { self.erased_end_array_value(&mut w) } fn begin_object( &mut self, mut w: &mut W, ) -> Result<(), io::Error> { self.erased_begin_object(&mut w) } fn end_object( &mut self, mut w: &mut W, ) -> Result<(), io::Error> { self.erased_end_object(&mut w) } fn begin_object_key( &mut self, mut w: &mut W, first: bool, ) -> Result<(), io::Error> { self.erased_begin_object_key(&mut w, first) } fn end_object_key( &mut self, mut w: &mut W, ) -> Result<(), io::Error> { self.erased_end_object_key(&mut w) } fn begin_object_value( &mut self, mut w: &mut W, ) -> Result<(), io::Error> { self.erased_begin_object_value(&mut w) } fn end_object_value( &mut self, mut w: &mut W, ) -> Result<(), io::Error> { self.erased_end_object_value(&mut w) } } }; } impl_formatter_for_trait_object!(dyn Formatter); impl_formatter_for_trait_object!(&'a mut dyn Formatter); impl_formatter_for_trait_object!(&'a mut (dyn Formatter + Send)); impl_formatter_for_trait_object!(&'a mut (dyn Formatter + Sync)); impl_formatter_for_trait_object!(&'a mut (dyn Formatter + Send + Sync)); ================================================ FILE: src/commands.rs ================================================ use clap::ArgMatches; use protobuf::descriptor::FileDescriptorSet; use serde_json::ser::Serializer; use std::io::{self, Write}; use std::path::PathBuf; use crate::decode::PqDecoder; use crate::discovery::{compile_descriptors_from_proto, get_loaded_descriptors}; use crate::formatter::CustomFormatter; use stream_delimit::byte_consumer::ByteConsumer; use stream_delimit::converter::Converter; use stream_delimit::stream::*; pub struct CommandRunner { descriptors: Vec, prettyjson: bool, } #[cfg(feature = "default")] use stream_delimit::kafka_consumer::KafkaConsumer; impl CommandRunner { pub fn new( additional_fdset_dirs: Vec, mut additional_fdset_files: Vec, additional_proto_file: Option<&str>, prettyjson: bool, ) -> Self { if let Some(x) = additional_proto_file { let compiled_descriptor_path = compile_descriptors_from_proto(x); additional_fdset_files.push(compiled_descriptor_path); } let descriptors = get_loaded_descriptors(additional_fdset_dirs, additional_fdset_files); CommandRunner { descriptors, prettyjson, } } #[cfg(feature = "default")] pub fn run_kafka(self, matches: &ArgMatches<'_>) { if let (Some(brokers), Some(topic)) = (matches.value_of("BROKERS"), matches.value_of("TOPIC")) { let consumer = match KafkaConsumer::new(brokers, topic, matches.is_present("FROMBEG")) { Ok(x) => x, Err(e) => panic!("Couldn't initialize kafka consumer: {}", e), }; decode_or_convert(consumer, matches, self.descriptors, self.prettyjson).unwrap(); } else { panic!("Kafka needs broker[s] and topic"); } } #[cfg(not(feature = "default"))] pub fn run_kafka(self, _: &ArgMatches) { unimplemented!("This version of pq has been compiled without kafka support"); } pub fn run_byte(self, matches: &ArgMatches<'_>) { if unsafe { libc::isatty(0) != 0 } { panic!("pq expects input to be piped from stdin"); } let stream_type = str_to_streamtype(matches.value_of("STREAM").unwrap_or("single")) .expect("Couldn't convert str to streamtype"); decode_or_convert( ByteConsumer::new(io::stdin(), stream_type), matches, self.descriptors, self.prettyjson, ) .unwrap() } } fn decode_or_convert> + FramedRead>( mut consumer: T, matches: &ArgMatches<'_>, descriptors: Vec, prettyjson: bool, ) -> io::Result<()> { let count = value_t!(matches, "COUNT", i32).unwrap_or(-1); let stdout = io::stdout(); let use_pretty_json = if prettyjson { prettyjson } else { unsafe { libc::isatty(1) != 0 } }; if let Some(convert_type) = matches.value_of("CONVERT") { let converter = Converter::new( &mut consumer, str_to_streamtype(convert_type).expect("Couldn't convert str to streamtype"), ); let stdout_ = &mut stdout.lock(); for (ctr, item) in converter.enumerate() { if count >= 0 && ctr >= count as usize { break; } stdout_.write_all(&item).expect("Couldn't write to stdout"); } Ok(()) } else { let msgtype = format!( ".{}", matches .value_of("MSGTYPE") .expect("Must supply --msgtype or --convert") ); let decoder = PqDecoder::new(descriptors, &msgtype); let mut formatter = CustomFormatter::new(use_pretty_json); let stdout_ = stdout.lock(); let mut serializer = Serializer::with_formatter(stdout_, &mut formatter); let mut buffer = Vec::new(); let mut ctr = 0; while let Some(item) = consumer.read_next_frame(&mut buffer)? { if count >= 0 && ctr >= count { break; } ctr += 1; decoder.transcode_message(item, &mut serializer); } Ok(()) } } ================================================ FILE: src/decode.rs ================================================ use protobuf::descriptor::FileDescriptorSet; use protobuf::CodedInputStream; use serde::Serializer; use serde_protobuf::de::Deserializer; use serde_protobuf::descriptor::Descriptors; pub struct PqDecoder<'a> { pub descriptors: Descriptors, pub message_type: &'a str, } impl<'a> PqDecoder<'a> { pub fn new(loaded_descs: Vec, message_type: &str) -> PqDecoder<'_> { let mut descriptors = Descriptors::new(); for fdset in loaded_descs { descriptors.add_file_set_proto(&fdset); } descriptors.resolve_refs(); PqDecoder { descriptors, message_type, } } pub fn transcode_message(&self, data: &[u8], out: S) { let stream = CodedInputStream::from_bytes(data); let mut deserializer = Deserializer::for_named_message(&self.descriptors, self.message_type, stream) .expect("could not init deserializer"); serde_transcode::transcode(&mut deserializer, out).unwrap(); } } ================================================ FILE: src/discovery.rs ================================================ use protobuf::descriptor::FileDescriptorSet; use protobuf::parse_from_reader; use std::{ env, fs::{read_dir, File}, path::{Path, PathBuf}, process::Command, }; pub fn get_loaded_descriptors( additional_fdset_dirs: Vec, mut additional_fdset_files: Vec, ) -> Vec { let (mut fdsets, mut tested_things) = discover_fdsets(additional_fdset_dirs); fdsets.append(&mut additional_fdset_files); tested_things.append( &mut additional_fdset_files .iter() .map(|x| format!("File: {:?}", x)) .collect::>(), ); let mut descriptors: Vec = Vec::new(); for fdset_path in fdsets { let mut fdset_file = match File::open(fdset_path.as_path()) { Ok(x) => x, Err(e) => panic!("Couldn't open fdset file: {}", e), }; match parse_from_reader(&mut fdset_file) { Err(_) => continue, Ok(x) => descriptors.push(x), } } if descriptors.is_empty() { panic!("No valid fdset files found. Checked: {:#?}", tested_things); } descriptors } fn discover_fdsets(additional_fdset_dirs: Vec) -> (Vec, Vec) { let mut tested_things = Vec::new(); let mut fdset_files = Vec::new(); if let Ok(x) = env::var("FDSET_PATH") { tested_things.push(format!("Directory: {:?}", x)); let p = PathBuf::from(x); fdset_files.append(&mut get_fdset_files_from_path(&p)); } if let Some(mut x) = dirs::home_dir() { x.push(".pq"); tested_things.push(format!("Directory: {:?}", x)); fdset_files.append(&mut get_fdset_files_from_path(&x)); } for x in additional_fdset_dirs { tested_things.push(format!("Directory: {:?}", x)); fdset_files.append(&mut get_fdset_files_from_path(&x)); } let x = PathBuf::from("/etc/pq"); tested_things.push(format!("Directory: {:?}", x)); fdset_files.append(&mut get_fdset_files_from_path(&x)); (fdset_files, tested_things) } pub fn compile_descriptors_from_proto(proto_file: &str) -> PathBuf { let fdset_path = env::temp_dir().join("tmp-pq.fdset"); let mut cmd = Command::new(protoc()); cmd.arg("--include_imports") .arg("--include_source_info") .arg("-o") .arg(&fdset_path) .arg(proto_file); cmd.arg("-I").arg(protoc_include()); let output = cmd.output().expect("failed to execute protoc"); if !output.status.success() { panic!("protoc failed: {}", String::from_utf8_lossy(&output.stderr)); } fdset_path } fn get_fdset_files_from_path(path: &Path) -> Vec { let mut ret = vec![]; if let Ok(paths) = read_dir(path) { for p in paths { let path = p.expect("error iterating through paths").path(); if !path.is_dir() { ret.push(path); } } } ret } fn protoc() -> PathBuf { match env::var_os("PROTOC") { Some(protoc) => PathBuf::from(protoc), None => PathBuf::from(default_env!("PROTOC", "protoc")), } } fn protoc_include() -> PathBuf { match env::var_os("PROTOC_INCLUDE") { Some(include) => PathBuf::from(include), None => PathBuf::from(default_env!("PROTOC_INCLUDE", "")), } } ================================================ FILE: src/formatter.rs ================================================ use erased_serde_json::Formatter as ErasedFormatter; use serde_json::ser::{CompactFormatter, Formatter, PrettyFormatter}; use std::boxed::Box; use std::io::{self, Write}; pub struct CustomFormatter { formatter: Box, depth: usize, } impl CustomFormatter { pub fn new(use_pretty_json: bool) -> Self { let f: Box = if use_pretty_json { Box::>::default() } else { Box::new(CompactFormatter) }; CustomFormatter { formatter: f, depth: 0, } } } impl<'a> Formatter for &'a mut CustomFormatter { fn begin_array(&mut self, w: &mut W) -> io::Result<()> { self.formatter.begin_array(w) } fn end_array(&mut self, w: &mut W) -> io::Result<()> { self.formatter.end_array(w) } fn begin_array_value(&mut self, w: &mut W, first: bool) -> io::Result<()> { self.formatter.begin_array_value(w, first) } fn end_array_value(&mut self, w: &mut W) -> io::Result<()> { self.formatter.end_array_value(w) } fn begin_object(&mut self, w: &mut W) -> io::Result<()> { self.depth += 1; self.formatter.begin_object(w) } fn end_object(&mut self, w: &mut W) -> io::Result<()> { self.formatter.end_object(w).and_then(|()| { self.depth -= 1; if self.depth == 0 { w.write_all(b"\n") } else { Ok(()) } }) } fn begin_object_key(&mut self, w: &mut W, first: bool) -> io::Result<()> { self.formatter.begin_object_key(w, first) } fn begin_object_value(&mut self, w: &mut W) -> io::Result<()> { self.formatter.begin_object_value(w) } fn end_object_value(&mut self, w: &mut W) -> io::Result<()> { self.formatter.end_object_value(w) } } ================================================ FILE: src/main.rs ================================================ #![crate_type = "bin"] #[macro_use] extern crate clap; #[macro_use] extern crate default_env; mod commands; mod decode; mod discovery; mod formatter; use crate::commands::*; fn main() { let matches = clap_app!( @app (app_from_crate!()) (@arg MSGTYPE: --msgtype +takes_value +global conflicts_with[CONVERT] "Sets protobuf message type") (@arg STREAM: --stream +takes_value "Enables stream + sets stream type") (@arg COUNT: --count +takes_value +global "Stop after count messages") (@arg CONVERT: --convert +takes_value +global "Convert to different stream type") (@arg EXTRA_FDSET_DIRS: --fdsetdir +takes_value +global +multiple "[repeatable] Specify dirs to load fdset files from") (@arg EXTRA_FDSET_FILES: --fdsetfile +takes_value +global +multiple "[repeatable] Specify an fdset file") (@arg EXTRA_PROTO_FILE: --protofile +takes_value +global "Specify a proto file") (@arg PRETTY_JSON: --prettyjson +global "Force pretty json formatter. Default is pretty for a tty, otherwise compact") (@subcommand kafka => (@arg TOPIC: +required "Sets the kafka topic") (@arg BROKERS: +required --brokers +takes_value "Comma-separated kafka brokers") (@arg FROMBEG: --beginning "Consume topic from beginning") ) ) .get_matches(); let extra_fdset_dirs = match matches.values_of("EXTRA_FDSET_DIRS") { Some(dirs) => dirs.map(std::path::PathBuf::from).collect::>(), None => vec![], }; let extra_fdset_files = match matches.values_of("EXTRA_FDSET_FILES") { Some(files) => files.map(std::path::PathBuf::from).collect::>(), None => vec![], }; let extra_proto_file = matches.value_of("EXTRA_PROTO_FILE"); let prettyjson = matches.is_present("PRETTY_JSON"); let cmd = CommandRunner::new( extra_fdset_dirs, extra_fdset_files, extra_proto_file, prettyjson, ); match matches.subcommand() { ("kafka", Some(m)) => cmd.run_kafka(m), _ => cmd.run_byte(&matches), } } ================================================ FILE: stream-delimit/Cargo.toml ================================================ [package] name = "stream_delimit" version = "0.5.7" authors = ["Sevag Hanssian "] description = "length delimited protobuf stream separator" repository = "https://github.com/sevagh/pq/tree/master/stream_delimit" documentation = "http://docs.rs/stream_delimit/" readme = "README.md" license = "MIT" keywords = ["protobuf", "serde"] edition = "2018" [dependencies] kafka = { version = "0.8", optional = true } byteorder = "1.3" [features] default = [] with_kafka = ["kafka"] ================================================ FILE: stream-delimit/LICENSE ================================================ MIT License Copyright (c) 2017 Sevag Hanssian Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: stream-delimit/README.md ================================================ # stream_delimit [![Crates.io](https://img.shields.io/crates/v/stream_delimit.svg)](https://crates.io/crates/stream_delimit) [![Crates.io](https://img.shields.io/crates/d/stream_delimit.svg)](https://github.com/sevagh/pq/tree/master/stream-delimit) A helper crate for pq. ### Varints https://developers.google.com/protocol-buffers/docs/encoding#varints ================================================ FILE: stream-delimit/src/byte_consumer.rs ================================================ #![deny(missing_docs)] use crate::stream::*; use crate::{error::StreamDelimitError, varint::decode_varint}; use byteorder::{BigEndian, ReadBytesExt}; use std::{ io::{self, Read}, num::NonZeroUsize, }; /// A consumer for a byte stream pub struct ByteConsumer { read: T, type_: StreamType, } impl ByteConsumer { /// Return a ByteConsumer from for single messages, varint or leb128-delimited pub fn new(read: T, type_: StreamType) -> ByteConsumer { ByteConsumer { read, type_ } } fn read_next_frame_length(&mut self) -> io::Result> { let r = match self.type_ { StreamType::Leb128 | StreamType::Varint => decode_varint(&mut self.read) .map_err(|e| { // For unified error handling we force everything into io::Error match e { StreamDelimitError::VarintDecodeError(i) => i, e => io::Error::new(io::ErrorKind::InvalidData, format!("{}", e)), } }) .map(|v| NonZeroUsize::new(v as usize)), StreamType::I32BE => self .read .read_i32::() .map(|v| NonZeroUsize::new(v as usize)), StreamType::Single => Ok(None), }; // In the cases where we have hit the end of the stream, read_i32 will return UnexpectedEof // we treat this as no more data match r { Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => Ok(None), a => a, } } } impl Iterator for ByteConsumer { type Item = Vec; fn next(&mut self) -> Option { let mut buffer = Vec::new(); self.read_next_frame(&mut buffer).ok()??; Some(buffer) } } impl FramedRead for ByteConsumer { fn read_next_frame<'a>(&mut self, buffer: &'a mut Vec) -> io::Result> { let r = match self.read_next_frame_length()? { Some(length) => { buffer.clear(); let mut take = (&mut self.read).take(length.get() as u64); take.read_to_end(buffer)?; Some(&buffer[..]) } // the single stream type does not have a defined length, so read_next_frame_length will return None // and we catch that special case here None if self.type_ == StreamType::Single => { buffer.clear(); if self.read.read_to_end(buffer)? > 0 { Some(&buffer[..]) } else { None } } _ => None, }; Ok(r) } } ================================================ FILE: stream-delimit/src/converter.rs ================================================ #![deny(missing_docs)] use crate::stream::*; use crate::varint::encode_varint; /// A Converter struct to convert from a stream iterator to another `StreamType` /// Useful for example to dump Kafka messages to a varint-delimited text file pub struct Converter<'a> { stream_src: &'a mut dyn Iterator>, stream_dest: StreamType, } impl<'a> Converter<'a> { /// Return a converter from a stream iterator pub fn new>>( stream_src: &'a mut T, stream_dest: StreamType, ) -> Converter<'a> { Converter { stream_src, stream_dest, } } } impl<'a> Iterator for Converter<'a> { type Item = Vec; fn next(&mut self) -> Option> { match self.stream_dest { StreamType::Varint | StreamType::Leb128 => match self.stream_src.next() { Some(ref mut x) => { let mut lead_varint = encode_varint(x.len() as u64); lead_varint.append(x); Some(lead_varint) } None => None, }, _ => unimplemented!(), } } } ================================================ FILE: stream-delimit/src/error.rs ================================================ use std::error::Error; use std::fmt; use std::io; use std::result; pub type Result = result::Result; #[derive(Debug)] pub enum StreamDelimitError { #[cfg(feature = "with_kafka")] KafkaInitializeError(::kafka::error::Error), VarintDecodeError(io::Error), InvalidStreamTypeError(String), VarintDecodeMaxBytesError, } impl fmt::Display for StreamDelimitError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { #[cfg(feature = "with_kafka")] StreamDelimitError::KafkaInitializeError(ref e) => { write!(f, "Couldn't initialize kafka consumer: {}", e) } StreamDelimitError::VarintDecodeError(ref e) => { write!(f, "Couldn't decode leading varint: {}", e) } StreamDelimitError::InvalidStreamTypeError(ref t) => write!( f, "Invalid stream type: {} (only support single,leb128,varint)", t ), StreamDelimitError::VarintDecodeMaxBytesError => { write!(f, "Exceeded max attempts to decode leading varint") } } } } impl Error for StreamDelimitError { fn description(&self) -> &str { match *self { #[cfg(feature = "with_kafka")] StreamDelimitError::KafkaInitializeError(_) => "couldn't initialize kafka consumer", StreamDelimitError::VarintDecodeError(_) | StreamDelimitError::VarintDecodeMaxBytesError => "couldn't decode leading varint", StreamDelimitError::InvalidStreamTypeError(_) => "invalid stream type", } } fn cause(&self) -> Option<&dyn Error> { match *self { #[cfg(feature = "with_kafka")] StreamDelimitError::KafkaInitializeError(ref e) => Some(e), StreamDelimitError::VarintDecodeError(ref e) => Some(e), StreamDelimitError::InvalidStreamTypeError(_) | StreamDelimitError::VarintDecodeMaxBytesError => None, } } } ================================================ FILE: stream-delimit/src/kafka_consumer.rs ================================================ #![deny(missing_docs)] use crate::error::*; use crate::stream::FramedRead; use kafka::consumer::{Consumer, FetchOffset}; use std::collections::VecDeque; /// A consumer from Kafka pub struct KafkaConsumer { consumer: Consumer, messages: VecDeque>, } impl FramedRead for KafkaConsumer { fn read_next_frame<'a>( &mut self, buffer: &'a mut Vec, ) -> std::io::Result> { let res = self.next().map(move |mut v| { std::mem::swap(&mut v, buffer); &buffer[..] }); Ok(res) } } impl Iterator for KafkaConsumer { type Item = Vec; fn next(&mut self) -> Option> { if self.messages.is_empty() { let kafka_consumer = &mut self.consumer; loop { match kafka_consumer.poll() { Ok(mss) => { for ms in mss.iter() { self.messages.append( &mut ms .messages() .iter() .map(|z| z.value.to_vec()) .collect::>(), ); kafka_consumer .consume_messageset(ms) .expect("Couldn't mark messageset as consumed"); } kafka_consumer .commit_consumed() .expect("Couldn't commit consumption"); if !self.messages.is_empty() { break; } } Err(e) => { eprintln!("{}", e); return None; } } } } self.messages.pop_front() } } impl KafkaConsumer { /// Return a KafkaConsumer with some basic kafka connection properties pub fn new(brokers: &str, topic: &str, from_beginning: bool) -> Result { let fetch_offset = if from_beginning { FetchOffset::Earliest } else { FetchOffset::Latest }; match Consumer::from_hosts( brokers .split(',') .map(std::borrow::ToOwned::to_owned) .collect::>(), ) .with_topic(topic.to_owned()) .with_fallback_offset(fetch_offset) .with_fetch_max_bytes_per_partition(1024 * 1024) .create() { Ok(consumer) => Ok(KafkaConsumer { consumer, messages: VecDeque::new(), }), Err(e) => Err(StreamDelimitError::KafkaInitializeError(e)), } } } ================================================ FILE: stream-delimit/src/lib.rs ================================================ extern crate byteorder; #[cfg(feature = "with_kafka")] extern crate kafka; mod varint; pub mod error; /// Utilities to consume from a byte stream pub mod byte_consumer; /// Utilities to convert between stream types pub mod converter; /// Define stream types pub mod stream; #[cfg(feature = "with_kafka")] /// Utilities to consume from Kafka pub mod kafka_consumer; ================================================ FILE: stream-delimit/src/stream.rs ================================================ #![deny(missing_docs)] use std::io; use crate::error::*; /// An enum type for byte streams #[derive(PartialEq, Eq)] pub enum StreamType { /// Protobuf messages with leading length encoded in leb128 Leb128, /// Protobuf messages with leading length encoded in varint Varint, /// Protobuf messages with leading length encoded as /// binary big endian 32-bit signed integer I32BE, /// Single protobuf messages with no separators/delimiters Single, } /// Convert &str to associated `StreamType` pub fn str_to_streamtype(input: &str) -> Result { match input { "single" => Ok(StreamType::Single), "varint" => Ok(StreamType::Varint), "leb128" => Ok(StreamType::Leb128), "i32be" => Ok(StreamType::I32BE), _ => Err(StreamDelimitError::InvalidStreamTypeError( input.to_string(), )), } } /// A trait for a stream that can be read in clearly defined chunks pub trait FramedRead { /// should read the next available frame into the provided buffer. /// clear() will be called before the buffer is filled fn read_next_frame<'a>(&mut self, buffer: &'a mut Vec) -> io::Result>; } ================================================ FILE: stream-delimit/src/varint.rs ================================================ #![deny(missing_docs)] use crate::error::*; use std::io::Read; const VARINT_MAX_BYTES: usize = 10; pub fn decode_varint(read: &mut dyn Read) -> Result { let mut varint_buf: Vec = Vec::new(); for i in 0..VARINT_MAX_BYTES { varint_buf.push(0u8); match read.read_exact(&mut varint_buf[i..]) { Ok(_) => (), Err(e) => return Err(StreamDelimitError::VarintDecodeError(e)), } if (varint_buf[i] & 0x80) == 0 { let mut concat: u64 = 0; for (j, &byte) in varint_buf[..=i].iter().enumerate() { concat |= u64::from(byte & 0x7f) << (j * 7); } return Ok(concat); } } Err(StreamDelimitError::VarintDecodeMaxBytesError) } pub fn encode_varint(mut value: u64) -> Vec { let mut ret = vec![0u8; VARINT_MAX_BYTES]; let mut n = 0; while value > 127 { ret[n] = 0x80 | (value & 0x7F) as u8; value >>= 7; n += 1 } ret[n] = value as u8; n += 1; ret[0..n].to_vec() } #[cfg(test)] mod tests { use super::*; use std::io::Cursor; #[test] fn test_simple() { assert_eq!( 1, decode_varint(&mut Cursor::new(encode_varint(1))).unwrap() ); } #[test] fn test_two_byte_varint() { assert_eq!( 300, decode_varint(&mut Cursor::new(encode_varint(300))).unwrap() ); } #[test] fn test_decode_known_varint_bytes() { let cases: &[(u64, &[u8])] = &[ (0, &[0x00]), (1, &[0x01]), (127, &[0x7f]), (128, &[0x80, 0x01]), (300, &[0xac, 0x02]), (16384, &[0x80, 0x80, 0x01]), (2097152, &[0x80, 0x80, 0x80, 0x01]), (u32::MAX as u64, &[0xff, 0xff, 0xff, 0xff, 0x0f]), ( u64::MAX, &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01], ), ]; for &(expected, bytes) in cases { assert_eq!(expected, decode_varint(&mut Cursor::new(bytes)).unwrap()); } } #[test] fn test_three_byte_varint() { // 16384 requires 3 bytes: 0x80 0x80 0x01 // This would fail with the old buggy shift formula assert_eq!( 16384, decode_varint(&mut Cursor::new(encode_varint(16384))).unwrap() ); assert_eq!( 100000, decode_varint(&mut Cursor::new(encode_varint(100000))).unwrap() ); } #[test] fn test_four_byte_varint() { // 2097152 requires 4 bytes assert_eq!( 2097152, decode_varint(&mut Cursor::new(encode_varint(2097152))).unwrap() ); assert_eq!( 10000000, decode_varint(&mut Cursor::new(encode_varint(10000000))).unwrap() ); } #[test] fn test_large_varints() { assert_eq!( u32::MAX as u64, decode_varint(&mut Cursor::new(encode_varint(u32::MAX as u64))).unwrap() ); assert_eq!( u64::MAX, decode_varint(&mut Cursor::new(encode_varint(u64::MAX))).unwrap() ); } } ================================================ FILE: tests/README.md ================================================ Samples and fdset files compiled from the tools in the https://github.com/sevagh/protobuf-test-utils repo. ================================================ FILE: tests/fdsets/cat.fdset ================================================ < cat.protocom.example.cat" Cat is_lazy (RisLazy ================================================ FILE: tests/fdsets/dog.fdset ================================================ m dog.protocom.example.dog"O Dog breed ( Rbreed age (Rage temperament ( R temperament ================================================ FILE: tests/fdsets/person.fdset ================================================ P person.protocom.example.person", Person name ( Rname id (Rid ================================================ FILE: tests/fdsets-invalid/.gitignore ================================================ * !.gitignore ================================================ FILE: tests/protos/dog.proto ================================================ package com.example.dog; message Dog { required string breed = 1; required int32 age = 2; optional string temperament = 3; } ================================================ FILE: tests/samples/bad ================================================ thisisnotprotobuf ================================================ FILE: tests/samples/dog ================================================ gsdexcited ================================================ FILE: tests/samples/dog_stream ================================================  rottweilerchill ================================================ FILE: tests/test_pqrs_bin.rs ================================================ use assert_cli; use std::env; fn get_test_dir(final_piece: &str) -> String { let mut cwd = env::current_dir().unwrap(); cwd.push("tests"); cwd.push(final_piece); String::from(cwd.to_str().unwrap()) } #[test] fn test_dog_decode() { assert_cli::Assert::main_binary() .with_env(assert_cli::Environment::inherit().insert("FDSET_PATH", get_test_dir("fdsets"))) .with_args(&["--msgtype=com.example.dog.Dog"]) .stdin(include_str!("samples/dog")) .succeeds() .and() .stdout() .contains("{\"breed\":\"gsd\",\"age\":3,\"temperament\":\"excited\"}") .unwrap(); } #[test] fn test_dog_decode_stream() { assert_cli::Assert::main_binary() .with_env(assert_cli::Environment::inherit().insert("FDSET_PATH", get_test_dir("fdsets"))) .with_args(&["--msgtype=com.example.dog.Dog", "--stream=varint"]) .stdin(include_str!("samples/dog_stream")) .succeeds() .and() .stdout() .contains("{\"breed\":\"rottweiler\",\"age\":2,\"temperament\":\"chill\"}") .unwrap(); } #[test] fn test_dog_decode_i32be_stream() { assert_cli::Assert::main_binary() .with_env(assert_cli::Environment::inherit().insert("FDSET_PATH", get_test_dir("fdsets"))) .with_args(&["--msgtype=com.example.dog.Dog", "--stream=i32be"]) .stdin(include_str!("samples/dog_i32be_stream")) .succeeds() .and() .stdout() .contains("{\"breed\":\"gsd\",\"age\":3,\"temperament\":\"excited\"}") .unwrap(); } #[test] fn test_nonexistent_fdset_dir() { assert_cli::Assert::main_binary() .with_env( assert_cli::Environment::inherit() .insert("FDSET_PATH", get_test_dir("fdsets-doesnt-exist")), ) .with_args(&["--msgtype=com.example.dog.Dog"]) .stdin(include_str!("samples/dog")) .fails() .and() .stderr() .contains("No valid fdset files found. Checked:") .unwrap(); } #[test] fn test_no_fdset_files() { assert_cli::Assert::main_binary() .with_env( assert_cli::Environment::inherit().insert("FDSET_PATH", get_test_dir("fdsets-invalid")), ) .with_args(&["--msgtype=com.example.dog.Dog"]) .stdin(include_str!("samples/dog")) .fails() .and() .stderr() .contains("No valid fdset files found. Checked:") .unwrap(); } #[test] fn test_person_decode() { assert_cli::Assert::main_binary() .with_env(assert_cli::Environment::inherit().insert("FDSET_PATH", get_test_dir("fdsets"))) .with_args(&["--msgtype=com.example.person.Person"]) .stdin(include_str!("samples/person")) .succeeds() .and() .stdout() .contains("{\"name\":\"khosrov\",\"id\":0}") .unwrap(); } #[test] fn test_bad_input() { assert_cli::Assert::main_binary() .with_env(assert_cli::Environment::inherit().insert("FDSET_PATH", get_test_dir("fdsets"))) .with_args(&["--msgtype=com.example.dog.Dog"]) .stdin(include_str!("samples/bad")) .fails() .and() .stderr() .contains("protobuf error") .unwrap(); } #[test] fn test_person_decode_with_command_line_fdset_dir() { assert_cli::Assert::main_binary() .with_args(&[ "--msgtype=com.example.person.Person", &format!("--fdsetdir={0}", get_test_dir("fdsets")), ]) .stdin(include_str!("samples/person")) .succeeds() .and() .stdout() .contains("{\"name\":\"khosrov\",\"id\":0}") .unwrap(); } #[test] fn test_person_decode_with_command_line_fdset_file() { assert_cli::Assert::main_binary() .with_args(&[ "--msgtype=com.example.person.Person", &format!("--fdsetfile={0}", get_test_dir("fdsets/person.fdset")), ]) .stdin(include_str!("samples/person")) .succeeds() .and() .stdout() .contains("{\"name\":\"khosrov\",\"id\":0}") .unwrap(); } #[test] fn test_no_args() { assert_cli::Assert::main_binary() .fails() .and() .stderr() .contains("No valid fdset files found") .unwrap(); } #[test] fn test_cat_noncanonical_decode() { assert_cli::Assert::main_binary() .with_args(&[ "--msgtype=com.example.cat.Cat", &format!("--fdsetfile={0}", get_test_dir("fdsets/cat.fdset")), ]) .stdin(include_str!("samples/cat")) .succeeds() .and() .stdout() .contains("{\"is_lazy\":false}") .unwrap(); } #[test] #[ignore] fn test_cat_canonical_decode() { assert_cli::Assert::main_binary() .with_args(&[ "--msgtype=com.example.cat.Cat", &format!("--fdsetfile={0}", get_test_dir("fdsets/cat.fdset")), ]) .stdin(include_str!("samples/cat")) .succeeds() .and() .stdout() .contains("{\"isLazy\":false}") .unwrap(); } #[test] fn test_dog_decode_from_proto() { assert_cli::Assert::main_binary() .with_env( assert_cli::Environment::inherit().insert("PROTOC_INCLUDE", get_test_dir("protos")), ) .with_args(&[ "--msgtype=com.example.dog.Dog", &format!("--protofile={0}", get_test_dir("protos/dog.proto")), ]) .stdin(include_str!("samples/dog")) .succeeds() .and() .stdout() .contains("{\"breed\":\"gsd\",\"age\":3,\"temperament\":\"excited\"}") .unwrap(); } ================================================ FILE: utils/.gitignore ================================================ *_pb2.py *.fdset __pycache__ *.pyc ================================================ FILE: utils/GNUmakefile ================================================ PROTOS := $(wildcard *.proto) FDSETS := $(patsubst %.proto,%.fdset,$(PROTOS)) all: $(FDSETS) py: @protoc --python_out . ./*.proto -I./ %.fdset: %.proto @protoc -o ./$@ ./$^ -I./ .PHONY: clean clean: -rm -rf ./*.fdset ./*_pb2.py ./*_pb3.py __pycache__ ================================================ FILE: utils/README.txt ================================================ Protobuf sample files and generators for pq testing. ================================================ FILE: utils/cat.proto ================================================ package com.example.cat; message Cat { required bool is_lazy = 1; } ================================================ FILE: utils/dog.proto ================================================ package com.example.dog; message Dog { required string breed = 1; required int32 age = 2; optional string temperament = 3; } ================================================ FILE: utils/person.proto ================================================ package com.example.person; message Person { required string name = 1; required int32 id = 2; } ================================================ FILE: utils/proto_encoder.py ================================================ #!/usr/bin/env python3 import dog_pb2 import person_pb2 import cat_pb2 import sys import random from google.protobuf.internal import encoder from optparse import OptionParser def single(msgtype, stream=False): if msgtype == "cat": obj = cat_pb2.Cat(is_lazy=bool(random.getrandbits(1))) elif msgtype == "dog": obj = dog_pb2.Dog( age=random.choice(range(0, 20)), breed=["rottweiler", "gsd", "poodle"][random.choice(range(0, 3))], temperament=["chill", "aggressive", "excited"][random.choice(range(0, 3))], ) elif msgtype == "person": obj = person_pb2.Person( id=random.choice(range(0, 4)), name=["raffi", "khosrov", "vahaken"][random.choice(range(0, 3))], ) else: usage() obj = obj.SerializeToString() varint_ = encoder._VarintBytes(len(obj)) if stream else b"" sys.stdout.buffer.write(varint_ + obj) def stream(msgtype, limit): for _ in range(limit): single(msgtype, stream=True) def usage(): print( "Usage: {0} " " [--count c]".format(sys.argv[0]), file=sys.stderr, ) sys.exit(1) if __name__ == "__main__": parser = OptionParser() parser.add_option("--count", dest="count", help="stream count", metavar="COUNT") (options, args) = parser.parse_args(args=sys.argv) if len(args) != 3: usage() if args[1] == "single": single(args[2]) elif args[1] == "stream": stream(args[2], int(options.count)) ================================================ FILE: utils/requirements.txt ================================================ protobuf