├── .appveyor.yml ├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── batch-codegen ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT └── src │ ├── error.rs │ ├── job.rs │ └── lib.rs ├── batch-rabbitmq-codegen ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT └── src │ ├── error.rs │ ├── lib.rs │ └── queues.rs ├── batch-rabbitmq ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── src │ ├── connection.rs │ ├── consumer.rs │ ├── declare.rs │ ├── delivery.rs │ ├── exchange.rs │ ├── export.rs │ ├── lib.rs │ ├── queue.rs │ └── stream.rs └── tests │ └── consume.rs ├── batch-stub ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT └── src │ ├── client.rs │ └── lib.rs ├── batch-test ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT └── src │ └── lib.rs ├── ci └── install.ps1 ├── examples ├── rabbitmq-simple │ ├── Cargo.toml │ └── src │ │ ├── bin │ │ ├── client.rs │ │ └── worker.rs │ │ └── lib.rs └── rabbitmq-warp │ ├── Cargo.toml │ └── src │ ├── bin │ ├── server.rs │ └── worker.rs │ └── lib.rs ├── guide ├── book.toml └── src │ ├── SUMMARY.md │ ├── batch.md │ ├── concepts.md │ ├── jobs.md │ ├── rabbitmq │ ├── exchanges.md │ ├── getting-started.md │ ├── index.md │ └── queues.md │ └── worker │ └── index.md └── src ├── client.rs ├── delivery.rs ├── dispatch.rs ├── export.rs ├── factory.rs ├── job.rs ├── lib.rs ├── query.rs ├── queue.rs └── worker.rs /.appveyor.yml: -------------------------------------------------------------------------------- 1 | version: '0.1.{build}' 2 | 3 | platform: x64 4 | 5 | environment: 6 | matrix: 7 | - APPVEYOR_RUST_CHANNEL: stable 8 | - APPVEYOR_RUST_CHANNEL: beta 9 | - APPVEYOR_RUST_CHANNEL: nightly 10 | 11 | matrix: 12 | allow_failures: 13 | - APPVEYOR_RUST_CHANNEL: nightly 14 | 15 | install: 16 | # Install RabbitMQ 17 | - ps: .\ci\install.ps1 18 | # Install rust and cargo 19 | - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe 20 | - rustup-init.exe -y --default-host x86_64-pc-windows-msvc --default-toolchain %APPVEYOR_RUST_CHANNEL% 21 | - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin 22 | # Debug information 23 | - rustc -V 24 | - cargo -V 25 | 26 | build: false 27 | 28 | test_script: 29 | - cargo build --all --all-features 30 | - cargo test --all --all-features 31 | 32 | cache: 33 | - C:\Users\appveyor\.cargo\registry -> Cargo.lock 34 | # Note: this must match the $rabbitmq_installer_path value in 35 | # .\ci\install.ps1 36 | - "%HOMEDRIVE%%HOMEPATH%\rabbitmq-server-3.7.4.exe" 37 | 38 | branches: 39 | only: 40 | - master 41 | - /^v\d+\.\d+(\.\d+)?(-\S*)?$/ 42 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | 5 | --- 6 | 7 | **Describe the bug** 8 | A clear and concise description of what the bug is. 9 | 10 | **To Reproduce** 11 | Steps to reproduce the behavior, ideally a standalone 12 | 13 | **Expected behavior** 14 | A clear and concise description of what you expected to happen. 15 | 16 | **Logs** 17 | If applicable, add logs to help explain your problem. 18 | 19 | **Environment (please complete the following information):** 20 | - OS [e.g. Windows, macOS, Linux] 21 | - Rust Version [e.g. stable, beta, nightly-2018-11-30] 22 | - Broker Software & Version [e.g. RabbitMQ 3.7] 23 | 24 | **Additional context** 25 | Add any other context about the problem here. 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | 5 | --- 6 | 7 | **Is your feature request related to a problem? Please describe.** 8 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 9 | 10 | **Describe the solution you'd like** 11 | A clear and concise description of what you want to happen. 12 | 13 | **Describe alternatives you've considered** 14 | A clear and concise description of any alternative solutions or features you've considered. 15 | 16 | **Additional context** 17 | Add any other context or screenshots about the feature request here. 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | **/*.rs.bk 3 | Cargo.lock 4 | /guide/book 5 | !/guide/book/.gitkeep 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | dist: trusty 3 | sudo: required 4 | cache: cargo 5 | 6 | branches: 7 | only: 8 | - master 9 | - /^v\d+\.\d+(\.\d+)?(-\S*)?$/ 10 | 11 | addons: 12 | apt: 13 | sources: 14 | - sourceline: deb https://packages.erlang-solutions.com/ubuntu trusty contrib 15 | key_url: https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc 16 | - sourceline: deb https://dl.bintray.com/rabbitmq/debian trusty main 17 | key_url: https://dl.bintray.com/rabbitmq/Keys/rabbitmq-release-signing-key.asc 18 | packages: 19 | - esl-erlang 20 | 21 | os: 22 | - linux 23 | - osx 24 | 25 | rust: 26 | - stable 27 | - beta 28 | - nightly 29 | 30 | matrix: 31 | fast_finish: true 32 | allow_failures: 33 | - rust: nightly 34 | include: 35 | - rust: stable 36 | env: ROLE=format 37 | script: 38 | - rustup component add rustfmt-preview 39 | - cargo fmt --all -- --check 40 | - rust: nightly 41 | env: ROLE=guide 42 | script: 43 | - export MDBOOK_VERSION=0.2.1 44 | - "wget -O mdbook.tar.gz https://github.com/rust-lang-nursery/mdBook/releases/download/v$MDBOOK_VERSION/mdbook-v$MDBOOK_VERSION-x86_64-unknown-linux-gnu.tar.gz" 45 | - tar xf mdbook.tar.gz 46 | - cargo build --all --all-features 47 | - ./mdbook test ./guide -L target/debug/deps 48 | 49 | before_install: 50 | - | 51 | if [ "$TRAVIS_OS_NAME" = osx ] 52 | then 53 | brew update 54 | brew install rabbitmq 55 | brew services run rabbitmq 56 | fi 57 | - | 58 | if [ "$TRAVIS_OS_NAME" = linux ] 59 | then 60 | sudo mv /opt/jdk_switcher/jdk_switcher.sh /tmp 61 | sudo apt-get install rabbitmq-server 62 | sudo mv /tmp/jdk_switcher.sh /opt/jdk_switcher/ 63 | sudo service rabbitmq-server start 64 | fi 65 | 66 | script: 67 | - cargo build --all --all-features 68 | - cargo test --all --all-features 69 | 70 | before_deploy: 71 | - export MDBOOK_VERSION=0.2.1 72 | - "wget -O mdbook.tar.gz https://github.com/rust-lang-nursery/mdBook/releases/download/v$MDBOOK_VERSION/mdbook-v$MDBOOK_VERSION-x86_64-unknown-linux-gnu.tar.gz" 73 | - tar xf mdbook.tar.gz 74 | - ./mdbook build ./guide 75 | 76 | deploy: 77 | provider: pages 78 | skip_cleanup: true 79 | github_token: $GH_TOKEN 80 | target_branch: gh-pages 81 | local_dir: guide/book/html 82 | on: 83 | repo: kureuil/batch-rs 84 | branch: master 85 | rust: nightly 86 | condition: "$ROLE == guide && $TRAVIS_OS_NAME == linux" 87 | 88 | notifications: 89 | email: 90 | on_success: never 91 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog] and this project adheres to 5 | [Semantic Versioning]. 6 | 7 | [Keep a Changelog]: http://keepachangelog.com/en/1.0.0/ 8 | [Semantic Versioning]: http://semver.org/spec/v2.0.0.html 9 | 10 | ## [Unreleased] 11 | ### Changed 12 | - Batch is now split up in multiple crates, making it a lot more modular. 13 | - Batch is now built on top of the new Tokio runtime. 14 | - **all**: The terminology was changed from "task" to "job". 15 | 16 | ### Added 17 | - **codegen**: The `job` procedural macro to declare jobs. 18 | - **core**: Added support for job priorities, with 5 levels of granularity: `trivial`, `low`, `normal` (default), `high`, `critical`. 19 | - **core**: A brand new `Query` interface, more strongly typed. 20 | - **core:** The `Client` trait allows the use of other message brokers than RabbitMQ. 21 | - **core**: The `Properties` struct, store the metadata associated to a job (timeout, priority, name, etc). 22 | - **rabbitmq**: The `queues` procedural macro, used to declare RabbitMQ exchanges and queues. 23 | - **rabbitmq**: Two new examples (standalone & warp) to help users set up the library in their project. 24 | 25 | ### Fixed 26 | - **rabbitmq:** Exchange name not being used when publishing a task to RabbitMQ. 27 | - **all**: No more `.unwrap()` in documentation examples. 28 | - **all**: Removed last occurences of dangerous `.unwrap()` in the library. 29 | 30 | ### Removed 31 | - **codegen**: The custom derive for the `Task` trait has been removed, use the `job` procedural macro instead. 32 | 33 | ## [0.1.1] - 2018-02-22 34 | ### Added 35 | - A guide used to document everything that doesn't fit into the API docs. 36 | 37 | ## 0.1.0 - 2018-02-20 38 | ### Added 39 | - Initial release. 40 | 41 | [Unreleased]: https://github.com/kureuil/batch-rs/compare/v0.1.1...HEAD 42 | [0.1.1]: https://github.com/kureuil/batch-rs/compare/v0.1.0...v0.1.1 43 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "./", 4 | "batch-codegen", 5 | "batch-rabbitmq", 6 | "batch-rabbitmq-codegen", 7 | "batch-stub", 8 | "batch-test", 9 | "examples/rabbitmq-simple", 10 | "examples/rabbitmq-warp", 11 | ] 12 | 13 | [package] 14 | edition = "2018" 15 | name = "batch" 16 | description = "Safe & extensible background job library supporting RabbitMQ" 17 | homepage = "https://kureuil.github.io/batch-rs/" 18 | repository = "https://github.com/kureuil/batch-rs" 19 | version = "0.2.0" # remember to update html_root_url 20 | license = "MIT/Apache-2.0" 21 | authors = ["Louis Person "] 22 | readme = "README.md" 23 | keywords = ["task", "queue", "job", "background", "rabbitmq"] 24 | categories = ["asynchronous"] 25 | 26 | [badges] 27 | travis-ci = { repository = "kureuil/batch-rs" } 28 | appveyor = { repository = "kureuil/batch-rs", id = "p8390hfhs1ndmrv9" } 29 | 30 | [dependencies] 31 | batch-codegen = { version = "0.2", path = "./batch-codegen", optional = true } 32 | failure = "0.1" 33 | futures = "0.1.20" 34 | log = "0.4" 35 | serde = { version = "1.0", features = ["derive"] } 36 | serde_json = "1.0" 37 | tokio-executor = "0.1" 38 | uuid = { version = "0.6", features = ["v4", "serde"] } 39 | wait-timeout = "0.1.5" 40 | 41 | [dev-dependencies] 42 | batch-rabbitmq = { version = "0.2", path = "./batch-rabbitmq" } 43 | batch-stub = { version = "0.2", path = "./batch-stub" } 44 | tokio = { version = "0.1" } 45 | 46 | [features] 47 | default = ["codegen"] 48 | codegen = ["batch-codegen"] 49 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Batch [![Crates.io][crates-badge]][crates-url] [![API Docs][docs-badge]][docs-url] [![Travis Build Status][travis-badge]][travis-url] [![Appveyor Build status][appveyor-badge]][appveyor-url] 2 | 3 | [crates-badge]: https://img.shields.io/crates/v/batch.svg 4 | [crates-url]: https://crates.io/crates/batch 5 | [docs-badge]: https://docs.rs/batch/badge.svg?version=0.1 6 | [docs-url]: https://docs.rs/batch/0.1 7 | [travis-badge]: https://travis-ci.org/kureuil/batch-rs.svg?branch=master 8 | [travis-url]: https://travis-ci.org/kureuil/batch-rs 9 | [appveyor-badge]: https://ci.appveyor.com/api/projects/status/p8390hfhs1ndmrv9/branch/master?svg=true 10 | [appveyor-url]: https://ci.appveyor.com/project/kureuil/batch-rs/branch/master 11 | 12 | A background job library written in Rust. 13 | 14 | Batch allows you to defer jobs to worker processes, by sending messages to a broker. It is a type-safe library that favors safety over performance in order to minimize risk and avoid mistakes. It is completely asynchronous and is based on the [`tokio`] runtime. 15 | 16 | [`tokio`]: https://crates.io/crates/tokio 17 | 18 | ## Installation 19 | 20 | **Minimum Rust Version:** 1.31 21 | 22 | Add this to your `Cargo.toml`: 23 | 24 | ```toml 25 | [dependencies] 26 | batch = "0.2" 27 | ``` 28 | 29 | **Only if you're using Rust 2015 edition** 30 | Then add this to your crate root: 31 | 32 | ```rust 33 | extern crate batch; 34 | ``` 35 | 36 | ## Batch in action 37 | 38 | ```rust 39 | use batch::job; 40 | use batch_rabbitmq::{queues, Connection}; 41 | use std::path::PathBuf; 42 | use tokio::prelude::Future; 43 | 44 | queues! { 45 | Transcoding { 46 | name = "transcoding", 47 | bindings = [ 48 | self::transcode, 49 | ] 50 | } 51 | } 52 | 53 | #[job(name = "batch-example.transcode")] 54 | fn transcode(path: PathBuf) { 55 | // ... 56 | } 57 | 58 | fn main() { 59 | let fut = Connection::build("amqp://guest:guest@localhost:5672/%2f") 60 | .declare(Transcoding) 61 | .connect() 62 | .and_then(|mut client| { 63 | let job = transcode("./video.mp4".into()); 64 | Transcoding(job).dispatch(&mut client) 65 | }) 66 | .map_err(|e| eprintln!("An error occured: {}", e)); 67 | tokio::run(fut); 68 | } 69 | ``` 70 | 71 | More examples are available on [GitHub][gh-examples] and in the [guide][user-guide]. 72 | 73 | [gh-examples]: https://github.com/kureuil/batch-rs/tree/master/examples 74 | [user-guide]: https://kureuil.github.io/batch-rs/ 75 | 76 | ## Features 77 | 78 | * `codegen`: *(enabled by default)*: Enables the use of the `job` procedural macro. 79 | 80 | ## License 81 | 82 | Licensed under either of 83 | 84 | * Apache License, Version 2.0 85 | ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 86 | * MIT license 87 | ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 88 | 89 | at your option. 90 | 91 | ## Contribution 92 | 93 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. 94 | -------------------------------------------------------------------------------- /batch-codegen/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | edition = "2018" 3 | name = "batch-codegen" 4 | description = "Batch's procedural macros" 5 | repository = "https://github.com/kureuil/batch-rs" 6 | version = "0.2.0" # remember to update html_root_url 7 | license = "MIT/Apache-2.0" 8 | authors = ["Louis Person "] 9 | 10 | [lib] 11 | proc-macro = true 12 | 13 | [dependencies] 14 | humantime = "1.1.1" 15 | proc-macro2 = "0.4" 16 | quote = "0.6" 17 | syn = { version = "0.15", features = ["full", "visit-mut"] } 18 | -------------------------------------------------------------------------------- /batch-codegen/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /batch-codegen/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /batch-codegen/src/error.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; 2 | use quote::ToTokens; 3 | 4 | #[derive(Clone)] 5 | pub(crate) struct Error { 6 | message: String, 7 | start: Span, 8 | end: Span, 9 | } 10 | 11 | impl Error { 12 | pub(crate) fn new(message: impl Into) -> Self { 13 | Error::spanned(message, Span::call_site()) 14 | } 15 | 16 | pub(crate) fn spanned(message: impl Into, span: Span) -> Self { 17 | Error { 18 | message: message.into(), 19 | start: span, 20 | end: span, 21 | } 22 | } 23 | } 24 | 25 | impl ToTokens for Error { 26 | fn to_tokens(&self, dst: &mut TokenStream) { 27 | fn into_iter(token: impl Into) -> impl Iterator { 28 | let tree = token.into(); 29 | Some(tree).into_iter() 30 | } 31 | dst.extend(into_iter(Ident::new("compile_error", self.start))); 32 | dst.extend(into_iter(Punct::new('!', Spacing::Alone))); 33 | let mut message = TokenStream::new(); 34 | message.extend(into_iter(Literal::string(&self.message))); 35 | let mut group = Group::new(Delimiter::Brace, message); 36 | group.set_span(self.end); 37 | dst.extend(into_iter(group)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /batch-codegen/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Batch procedural macros 2 | //! 3 | //! This crate exposes general purpose macros for the Batch background job library. There are 4 | //! currently one macro exported by this crate: 5 | //! 6 | //! * [`job`]: a macro used to generate Batch compliant `Job` implementations from raw functions 7 | //! 8 | //! [`job`]: fn.job.html 9 | 10 | #![recursion_limit = "256"] 11 | #![doc(html_root_url = "https://docs.rs/batch-codegen/0.2.0")] 12 | #![deny(missing_debug_implementations)] 13 | 14 | // Still needed despite Rust 2018 edition. 15 | extern crate proc_macro; 16 | 17 | mod error; 18 | mod job; 19 | 20 | use proc_macro::TokenStream; 21 | 22 | /// A procedural macro to declare job based on functions. 23 | /// 24 | /// This attribute is meant to be used to annotate functions and transform them in `Job`s. It 25 | /// applies the following modifications to the annotated function: 26 | /// 27 | /// - It creates a structure with the exact same name as the function, storing all the fields 28 | /// that will be sent through the message broker. This structure then implements the `Job` 29 | /// trait. 30 | /// - It removes the parameters marked as injected from the function signature and changes the 31 | /// return type to the generated job structure created as stated above. 32 | /// 33 | /// If you wish to execute a job without going through a message broker, you can call the 34 | /// `perform_now` method on the job returned by the annotated function. This method takes as 35 | /// parameter all of the injected parameters. 36 | /// 37 | /// This macro takes parameters in the form `$key = $value` where `$key` is the name of the 38 | /// parameter written as an identifier (which means no quotes around it name), and where `$value` 39 | /// is the value associated to the given key and can be either an integer, a string, an identifier 40 | /// or an array of any of the previous types. 41 | /// 42 | /// # Parameters 43 | /// 44 | /// - `name`: `Identifier` 45 | /// This parameter is used to set the name of the job. 46 | /// - `wrapper`: `Option` 47 | /// This parameter is used to set the name of the job structure that will be generated. By 48 | /// default the wrapper is named after the annotated function. 49 | /// - `inject`: `Option<[Identifier]>` 50 | /// A list of the parameters that will be injected at run-time. By default, none of the 51 | /// parameters are to be injected. 52 | /// - `retries`: `Option` 53 | /// Number of times this job will be retried. 54 | /// - `timeout`: `Option` 55 | /// A string representing the duration the job will be allowed to run. Must in a format 56 | /// accepted by the [`humantime`] crate. 57 | /// - `priority`: `Option` 58 | /// The priority associated to the job. Can be any of `trivial`, `low`, `normal`, `high`, 59 | /// `critical`. Default is `normal`. 60 | /// 61 | /// [`humantime`]: https://docs.rs/humantime/1/humantime/fn.parse_duration.html 62 | /// 63 | /// # Example 64 | /// 65 | /// ```ignore 66 | /// #[job(name = "batch-example.say-hello", timeout = "5min 30sec", priority = low)] 67 | /// fn say_hello(name: String) { 68 | /// println!("Hello {}", name); 69 | /// } 70 | /// ``` 71 | #[proc_macro_attribute] 72 | pub fn job(args: TokenStream, input: TokenStream) -> TokenStream { 73 | job::impl_macro(args, input) 74 | } 75 | -------------------------------------------------------------------------------- /batch-rabbitmq-codegen/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | edition = "2018" 3 | name = "batch-rabbitmq-codegen" 4 | description = "Batch's RabbitMQ specific procedural macros" 5 | repository = "https://github.com/kureuil/batch-rs" 6 | version = "0.2.0" # remember to update html_root_url 7 | license = "MIT/Apache-2.0" 8 | authors = ["Louis Person "] 9 | 10 | [lib] 11 | proc-macro = true 12 | 13 | [dependencies] 14 | proc-macro2 = { version = "0.4", features = ["nightly"] } 15 | quote = "0.6" 16 | syn = { version = "0.15", features = ["full"] } 17 | -------------------------------------------------------------------------------- /batch-rabbitmq-codegen/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /batch-rabbitmq-codegen/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /batch-rabbitmq-codegen/src/error.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; 2 | use quote::ToTokens; 3 | 4 | pub(crate) struct Error { 5 | message: String, 6 | start: Span, 7 | end: Span, 8 | } 9 | 10 | impl Error { 11 | pub(crate) fn spanned(message: impl Into, span: Span) -> Self { 12 | Error { 13 | message: message.into(), 14 | start: span, 15 | end: span, 16 | } 17 | } 18 | } 19 | 20 | impl ToTokens for Error { 21 | fn to_tokens(&self, dst: &mut TokenStream) { 22 | fn into_iter(token: impl Into) -> impl Iterator { 23 | let tree = token.into(); 24 | Some(tree).into_iter() 25 | } 26 | dst.extend(into_iter(Ident::new("compile_error", self.start))); 27 | dst.extend(into_iter(Punct::new('!', Spacing::Alone))); 28 | let mut message = TokenStream::new(); 29 | message.extend(into_iter(Literal::string(&self.message))); 30 | let mut group = Group::new(Delimiter::Brace, message); 31 | group.set_span(self.end); 32 | dst.extend(into_iter(group)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /batch-rabbitmq-codegen/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Procedural macros for the batch_rabbitmq crate. 2 | 3 | #![recursion_limit = "256"] 4 | #![doc(html_root_url = "https://docs.rs/batch-rabbitmq-codegen/0.2.0")] 5 | #![deny(missing_debug_implementations)] 6 | 7 | // Still needed despite Rust 2018 edition. 8 | extern crate proc_macro; 9 | 10 | use proc_macro::TokenStream; 11 | 12 | mod error; 13 | mod queues; 14 | 15 | /// A procedural macro to declare queues. 16 | /// 17 | /// This macro should be written as a top-level item in a module, as it expands to statements. For 18 | /// each declared queue, it will create a structure and a function named after the given 19 | /// identifier, and implementations for the `batch::Queue` and `batch_rabbitmq::Declare`. 20 | /// 21 | /// # Example 22 | /// 23 | /// ```ignore 24 | /// queues! { 25 | /// Maintenance { 26 | /// name = "maintenance", 27 | /// bindings = [ 28 | /// super::jobs::prune_database, 29 | /// ], 30 | /// } 31 | /// 32 | /// Transcoding { 33 | /// name = "transcoding", 34 | /// exchange = "my-example", 35 | /// bindings = [ 36 | /// super::jobs::convert_video_file, 37 | /// ], 38 | /// } 39 | /// } 40 | /// ``` 41 | #[proc_macro] 42 | pub fn queues(input: TokenStream) -> TokenStream { 43 | queues::impl_macro(input) 44 | } 45 | -------------------------------------------------------------------------------- /batch-rabbitmq-codegen/src/queues.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::{Span, TokenStream}; 2 | use quote::{quote, ToTokens}; 3 | use syn::parse; 4 | use syn::punctuated::Punctuated; 5 | use syn::{braced, bracketed, Token}; 6 | 7 | use crate::error::Error; 8 | 9 | struct QueueAttrsList(Vec); 10 | 11 | #[derive(Clone)] 12 | struct QueueAttrs { 13 | ident: syn::Ident, 14 | attrs: Vec, 15 | } 16 | 17 | #[derive(Clone)] 18 | enum QueueAttr { 19 | Name(syn::LitStr), 20 | WithPriorities(syn::LitBool), 21 | Exclusive(syn::LitBool), 22 | Bindings(QueueBindings), 23 | Exchange(syn::LitStr), 24 | } 25 | 26 | #[derive(Clone, Default)] 27 | struct QueueBindings { 28 | bindings: Vec, 29 | } 30 | 31 | #[derive(Clone)] 32 | struct Queue { 33 | ident: syn::Ident, 34 | name: syn::LitStr, 35 | with_priorities: bool, 36 | exclusive: bool, 37 | bindings: QueueBindings, 38 | exchange: Option, 39 | } 40 | 41 | impl IntoIterator for QueueAttrsList { 42 | type Item = QueueAttrs; 43 | type IntoIter = ::std::vec::IntoIter; 44 | 45 | fn into_iter(self) -> Self::IntoIter { 46 | self.0.into_iter() 47 | } 48 | } 49 | 50 | impl QueueAttrs { 51 | fn name(&self) -> Option { 52 | self.attrs 53 | .iter() 54 | .filter_map(|a| match a { 55 | QueueAttr::Name(s) => Some(s.clone()), 56 | _ => None, 57 | }) 58 | .next() 59 | } 60 | 61 | fn with_priorities(&self) -> bool { 62 | self.attrs 63 | .iter() 64 | .filter_map(|a| match a { 65 | QueueAttr::WithPriorities(p) => Some(p.value), 66 | _ => None, 67 | }) 68 | .next() 69 | .unwrap_or(false) 70 | } 71 | 72 | fn exclusive(&self) -> bool { 73 | self.attrs 74 | .iter() 75 | .filter_map(|a| match a { 76 | QueueAttr::Exclusive(e) => Some(e.value), 77 | _ => None, 78 | }) 79 | .next() 80 | .unwrap_or(false) 81 | } 82 | 83 | fn bindings(&self) -> QueueBindings { 84 | self.attrs 85 | .iter() 86 | .filter_map(|a| match a { 87 | QueueAttr::Bindings(b) => Some(b.clone()), 88 | _ => None, 89 | }) 90 | .next() 91 | .unwrap_or_else(QueueBindings::default) 92 | } 93 | 94 | fn exchange(&self) -> Option { 95 | self.attrs 96 | .iter() 97 | .filter_map(|a| match a { 98 | QueueAttr::Exchange(s) => Some(s.clone()), 99 | _ => None, 100 | }) 101 | .next() 102 | } 103 | } 104 | 105 | impl parse::Parse for QueueAttrsList { 106 | fn parse(input: parse::ParseStream) -> parse::Result { 107 | let mut attrs = Vec::new(); 108 | while input.is_empty() == false { 109 | attrs.push(input.parse()?); 110 | } 111 | Ok(QueueAttrsList(attrs)) 112 | } 113 | } 114 | 115 | impl parse::Parse for QueueAttrs { 116 | fn parse(input: parse::ParseStream) -> parse::Result { 117 | let ident = input.parse()?; 118 | let content; 119 | let _ = braced!(content in input); 120 | let attrs: Punctuated<_, Token![,]> = content.parse_terminated(QueueAttr::parse)?; 121 | Ok(QueueAttrs { 122 | ident, 123 | attrs: attrs.into_iter().collect(), 124 | }) 125 | } 126 | } 127 | 128 | mod kw { 129 | syn::custom_keyword!(name); 130 | syn::custom_keyword!(with_priorities); 131 | syn::custom_keyword!(exclusive); 132 | syn::custom_keyword!(bindings); 133 | syn::custom_keyword!(exchange); 134 | } 135 | 136 | impl parse::Parse for QueueAttr { 137 | fn parse(input: parse::ParseStream) -> parse::Result { 138 | let lookahead = input.lookahead1(); 139 | if lookahead.peek(kw::name) { 140 | input.parse::()?; 141 | input.parse::()?; 142 | Ok(QueueAttr::Name(input.parse()?)) 143 | } else if lookahead.peek(kw::with_priorities) { 144 | input.parse::()?; 145 | input.parse::()?; 146 | Ok(QueueAttr::WithPriorities(input.parse()?)) 147 | } else if lookahead.peek(kw::exclusive) { 148 | input.parse::()?; 149 | input.parse::()?; 150 | Ok(QueueAttr::Exclusive(input.parse()?)) 151 | } else if lookahead.peek(kw::bindings) { 152 | input.parse::()?; 153 | input.parse::()?; 154 | Ok(QueueAttr::Bindings(input.parse()?)) 155 | } else if lookahead.peek(kw::exchange) { 156 | input.parse::()?; 157 | input.parse::()?; 158 | Ok(QueueAttr::Exchange(input.parse()?)) 159 | } else { 160 | Err(lookahead.error()) 161 | } 162 | } 163 | } 164 | 165 | impl parse::Parse for QueueBindings { 166 | fn parse(input: parse::ParseStream) -> parse::Result { 167 | let content; 168 | let _ = bracketed!(content in input); 169 | let bindings: Punctuated<_, Token![,]> = content.parse_terminated(syn::Path::parse)?; 170 | Ok(QueueBindings { 171 | bindings: bindings.into_iter().collect(), 172 | }) 173 | } 174 | } 175 | 176 | impl ToTokens for QueueBindings { 177 | fn to_tokens(&self, dst: &mut TokenStream) { 178 | let output = self 179 | .bindings 180 | .iter() 181 | .fold(TokenStream::new(), |mut acc, job| { 182 | let output = quote! { 183 | .bind::<#job>() 184 | }; 185 | acc.extend(output); 186 | acc 187 | }); 188 | dst.extend(output); 189 | } 190 | } 191 | 192 | impl Queue { 193 | fn new(attrs: QueueAttrs) -> Result { 194 | const ERR_MISSING_NAME: &str = "missing mandatory name attribute"; 195 | 196 | let queue = Queue { 197 | ident: attrs.ident.clone(), 198 | name: match attrs.name() { 199 | Some(name) => name, 200 | None => return Err(Error::spanned(ERR_MISSING_NAME, attrs.ident.span())), 201 | }, 202 | with_priorities: attrs.with_priorities(), 203 | exclusive: attrs.exclusive(), 204 | bindings: attrs.bindings(), 205 | exchange: attrs.exchange(), 206 | }; 207 | Ok(queue) 208 | } 209 | } 210 | 211 | impl ToTokens for Queue { 212 | fn to_tokens(&self, dst: &mut TokenStream) { 213 | let ident = &self.ident; 214 | let name = &self.name; 215 | let bindings = &self.bindings; 216 | let exchange = self.exchange.as_ref().unwrap_or(name); 217 | let krate = quote!(::batch_rabbitmq); 218 | let export = quote!(#krate::export); 219 | 220 | let dummy_const = syn::Ident::new( 221 | &format!("__IMPL_BATCH_QUEUE_FOR_{}", ident.to_string()), 222 | Span::call_site(), 223 | ); 224 | 225 | let output = quote! { 226 | pub struct #ident { 227 | inner: #krate::Queue 228 | } 229 | 230 | #[doc(hidden)] 231 | #[allow(non_snake_case)] 232 | pub fn #ident(job: J) -> #export::Query 233 | where 234 | J: #export::Job 235 | { 236 | #export::Query::new(job) 237 | } 238 | 239 | const #dummy_const: () = { 240 | fn queue() -> #krate::Queue { 241 | #krate::Queue::build(#name) 242 | .exchange(#krate::Exchange::new(#exchange)) 243 | #bindings 244 | .finish() 245 | } 246 | 247 | impl #export::Queue for #ident { 248 | const SOURCE: &'static str = #name; 249 | 250 | const DESTINATION: &'static str = #exchange; 251 | 252 | type CallbacksIterator = #export::Box<#export::Iterator #export::Box<#export::Future + Send> 255 | )>>; 256 | 257 | fn callbacks() -> Self::CallbacksIterator { 258 | Box::new(queue().callbacks()) 259 | } 260 | } 261 | 262 | impl #krate::Declare for #ident { 263 | fn declare(conn: &mut #krate::ConnectionBuilder) { 264 | queue().register(conn); 265 | } 266 | } 267 | }; 268 | }; 269 | dst.extend(output); 270 | } 271 | } 272 | 273 | fn do_parse(attrs: impl Iterator) -> Result, Error> { 274 | let mut queues = Vec::new(); 275 | for attr in attrs { 276 | queues.push(Queue::new(attr)?); 277 | } 278 | Ok(queues) 279 | } 280 | 281 | pub(crate) fn impl_macro(input: proc_macro::TokenStream) -> proc_macro::TokenStream { 282 | let attrs = syn::parse_macro_input!(input as QueueAttrsList); 283 | let queues = match do_parse(attrs.into_iter()) { 284 | Ok(queues) => queues, 285 | Err(e) => { 286 | return quote!( #e ).into(); 287 | } 288 | }; 289 | let mut output = quote!(); 290 | for queue in queues.into_iter().map(|ex| ex.into_token_stream()) { 291 | output = quote! { 292 | #output 293 | #queue 294 | }; 295 | } 296 | output.into() 297 | } 298 | -------------------------------------------------------------------------------- /batch-rabbitmq/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | edition = "2018" 3 | name = "batch-rabbitmq" 4 | description = "Rabbitmq adapter for batch" 5 | repository = "https://github.com/kureuil/batch-rs" 6 | version = "0.2.0" # remember to update html_root_url 7 | license = "MIT/Apache-2.0" 8 | authors = ["Louis Person "] 9 | 10 | [dependencies] 11 | amq-protocol = "0.22" 12 | batch = { version = "0.2", path = "../" } 13 | batch-rabbitmq-codegen = { version = "0.2", path = "../batch-rabbitmq-codegen", optional = true } 14 | bytes = "0.4" 15 | failure = "0.1" 16 | futures = "0.1" 17 | lapin-async = "0.14" 18 | lapin = { version = "0.14", package = "lapin-futures" } 19 | log = "0.4" 20 | native-tls = "0.1" 21 | serde = { version = "1.0", features = ["derive"] } 22 | serde_json = "1.0" 23 | tokio-executor = "0.1" 24 | tokio-io = "0.1" 25 | tokio-reactor = "0.1" 26 | tokio-tcp = "0.1" 27 | tokio-tls = "0.1" 28 | uuid = "0.6" 29 | 30 | [dev-dependencies] 31 | env_logger = "0.5" 32 | tokio = "0.1" 33 | 34 | [features] 35 | default = ["codegen"] 36 | codegen = ["batch-rabbitmq-codegen"] 37 | -------------------------------------------------------------------------------- /batch-rabbitmq/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /batch-rabbitmq/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /batch-rabbitmq/src/consumer.rs: -------------------------------------------------------------------------------- 1 | use batch; 2 | use failure::Error; 3 | use futures::{task, Async, Poll, Stream}; 4 | use lapin::channel; 5 | use lapin::message; 6 | use std::fmt; 7 | 8 | use crate::delivery::Delivery; 9 | use crate::stream; 10 | 11 | #[must_use = "streams do nothing unless polled"] 12 | pub struct Consumer { 13 | inner: Box + Send>, 14 | channel: channel::Channel, 15 | } 16 | 17 | impl Consumer { 18 | pub(crate) fn new( 19 | channel: channel::Channel, 20 | inner: Box + Send + 'static>, 21 | ) -> Self { 22 | Consumer { inner, channel } 23 | } 24 | } 25 | 26 | impl fmt::Debug for Consumer { 27 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 28 | f.debug_struct("Consumer").finish() 29 | } 30 | } 31 | 32 | impl batch::Consumer for Consumer { 33 | type Delivery = Delivery; 34 | } 35 | 36 | impl Stream for Consumer { 37 | type Item = Delivery; 38 | 39 | type Error = Error; 40 | 41 | fn poll(&mut self) -> Poll, Self::Error> { 42 | let delivery = match futures::try_ready!(self.inner.poll()) { 43 | Some(delivery) => delivery, 44 | None => return Ok(Async::Ready(None)), 45 | }; 46 | let delivery = match Delivery::new(delivery, self.channel.clone()) { 47 | Ok(delivery) => delivery, 48 | Err(e) => { 49 | log::error!("Couldn't handle incoming delivery: {}", e); 50 | task::current().notify(); 51 | return Ok(Async::NotReady); 52 | } 53 | }; 54 | Ok(Async::Ready(Some(delivery))) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /batch-rabbitmq/src/declare.rs: -------------------------------------------------------------------------------- 1 | use crate::ConnectionBuilder; 2 | 3 | /// A trait used to declare queues to RabbitMQ. 4 | pub trait Declare { 5 | /// Declare the current type to the given [`ConnectionBuilder`]. 6 | fn declare(conn: &mut ConnectionBuilder); 7 | } 8 | -------------------------------------------------------------------------------- /batch-rabbitmq/src/delivery.rs: -------------------------------------------------------------------------------- 1 | use batch; 2 | use failure::{bail, Error}; 3 | use futures::{Future, Poll}; 4 | use lapin::channel; 5 | use lapin::message; 6 | use lapin::types::AMQPValue; 7 | use log::warn; 8 | use std::collections::BTreeMap; 9 | use std::fmt; 10 | use std::time::Duration; 11 | use uuid::Uuid; 12 | 13 | use crate::stream; 14 | 15 | /// A delivery is a message received from RabbitMQ. 16 | /// 17 | /// Deliveries must be either acked or rejected before being dropped to signal RabbitMQ of the 18 | /// status of the associated job. If RabbitMQ doesn't get a response once the Time To Live of 19 | /// the delivery has expired, the delivery is marked as rejected and set to be retried. You can do 20 | /// so using the methods provided by the [`batch::Delivery`] trait. 21 | pub struct Delivery { 22 | payload: Vec, 23 | delivery_tag: u64, 24 | properties: batch::Properties, 25 | channel: channel::Channel, 26 | } 27 | 28 | impl fmt::Debug for Delivery { 29 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 30 | f.debug_struct("Delivery") 31 | .field("payload", &self.payload) 32 | .field("delivery_tag", &self.delivery_tag) 33 | .field("properties", &self.properties) 34 | .finish() 35 | } 36 | } 37 | 38 | impl Delivery { 39 | pub(crate) fn new( 40 | delivery: message::Delivery, 41 | channel: channel::Channel, 42 | ) -> Result { 43 | let payload = delivery.data; 44 | let delivery_tag = delivery.delivery_tag; 45 | let properties = { 46 | let empty = BTreeMap::new(); 47 | let headers = delivery.properties.headers().as_ref().unwrap_or(&empty); 48 | let task = match headers.get("task") { 49 | Some(AMQPValue::LongString(v)) => v, 50 | Some(_) => bail!("Incorrect type for `task` header from delivery"), 51 | None => bail!("Missing `task` header from delivery"), 52 | }; 53 | let mut props = batch::Properties::new(task); 54 | props.id = match delivery.properties.correlation_id() { 55 | Some(raw_id) => Uuid::parse_str(&raw_id).map_err(Error::from)?, 56 | None => bail!("Missing `correlation_id` property from delivery"), 57 | }; 58 | props.content_type = match delivery.properties.content_type().as_ref() { 59 | Some(v) if v == "application/json" => v.to_string(), 60 | Some(_) => bail!("Invalid value for `content_type` property from delivery"), 61 | None => bail!("Missing `content_type` property from delivery"), 62 | }; 63 | props.content_encoding = match delivery.properties.content_encoding().as_ref() { 64 | Some(v) if v == "utf-8" => v.to_string(), 65 | Some(_) => bail!("Invalid value for `content_encoding` property from delivery"), 66 | None => bail!("Missing `content_encoding` property from delivery"), 67 | }; 68 | props.lang = match headers.get("lang") { 69 | Some(AMQPValue::LongString(v)) => v.to_string(), 70 | Some(_) => bail!("Incorrect type for `lang` header from delivery"), 71 | None => bail!("Missing `lang` header from delivery"), 72 | }; 73 | props.root_id = match headers.get("root_id") { 74 | Some(AMQPValue::LongString(raw_id)) => { 75 | Some(Uuid::parse_str(&raw_id).map_err(Error::from)?) 76 | } 77 | Some(AMQPValue::Void) => None, 78 | Some(_) => bail!("Incorrect type for `root_id` header from delivery"), 79 | None => bail!("Missing `root_id` header from delivery"), 80 | }; 81 | props.parent_id = match headers.get("parent_id") { 82 | Some(AMQPValue::LongString(raw_id)) => { 83 | Some(Uuid::parse_str(&raw_id).map_err(Error::from)?) 84 | } 85 | Some(AMQPValue::Void) => None, 86 | Some(_) => bail!("Incorrect type for `parent_id` header from delivery"), 87 | None => bail!("Missing `parent_id` header from delivery"), 88 | }; 89 | props.group = match headers.get("group") { 90 | Some(AMQPValue::LongString(raw_id)) => { 91 | Some(Uuid::parse_str(&raw_id).map_err(Error::from)?) 92 | } 93 | Some(AMQPValue::Void) => None, 94 | Some(_) => bail!("Incorrect type for `group` header from delivery"), 95 | None => bail!("Missing `group` header from delivery"), 96 | }; 97 | props.timelimit = match headers.get("timelimit") { 98 | Some(AMQPValue::FieldArray(array)) => match array.as_slice() { 99 | [softlimit, hardlimit] => { 100 | let softlimit = match softlimit { 101 | AMQPValue::Void => None, 102 | AMQPValue::Timestamp(ms) => Some(Duration::from_millis(*ms)), 103 | _ => bail!("Incorrect type for first value of `timelimit` header from delivery"), 104 | }; 105 | let hardlimit = match hardlimit { 106 | AMQPValue::Void => None, 107 | AMQPValue::Timestamp(ms) => Some(Duration::from_millis(*ms)), 108 | _ => bail!("Incorrect type for second value of `timelimit` header from delivery"), 109 | }; 110 | if hardlimit < softlimit { 111 | warn!( 112 | "hardlimit is less than softlimit, replacing with softlimit; id={} job={} delivery_tag={}", 113 | props.id, 114 | props.task, 115 | delivery_tag 116 | ); 117 | (softlimit, softlimit) 118 | } else { 119 | (softlimit, hardlimit) 120 | } 121 | } 122 | _ => bail!("Invalid value for `timelimit` header from delivery"), 123 | }, 124 | Some(_) => bail!("Incorrect type for `timelimit` header from delivery"), 125 | None => (None, None), 126 | }; 127 | props 128 | }; 129 | Ok(Delivery { 130 | payload, 131 | delivery_tag, 132 | properties, 133 | channel, 134 | }) 135 | } 136 | } 137 | 138 | /// Future returned when acking a [`Delivery`] with [`batch::Delivery::ack`]. 139 | #[must_use = "futures do nothing unless polled"] 140 | pub struct AcknowledgeFuture(Box + Send>); 141 | 142 | impl fmt::Debug for AcknowledgeFuture { 143 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 144 | f.debug_struct("AcknowledgeFuture").finish() 145 | } 146 | } 147 | 148 | impl Future for AcknowledgeFuture { 149 | type Item = (); 150 | 151 | type Error = Error; 152 | 153 | fn poll(&mut self) -> Poll { 154 | self.0.poll() 155 | } 156 | } 157 | 158 | /// Future returned when rejecting a [`Delivery`] with [`batch::Delivery::reject`]. 159 | #[must_use = "futures do nothing unless polled"] 160 | pub struct RejectFuture(Box + Send>); 161 | 162 | impl fmt::Debug for RejectFuture { 163 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 164 | f.debug_struct("RejectFuture").finish() 165 | } 166 | } 167 | 168 | impl Future for RejectFuture { 169 | type Item = (); 170 | 171 | type Error = Error; 172 | 173 | fn poll(&mut self) -> Poll { 174 | self.0.poll() 175 | } 176 | } 177 | 178 | impl batch::Delivery for Delivery { 179 | type AckFuture = AcknowledgeFuture; 180 | 181 | type RejectFuture = RejectFuture; 182 | 183 | fn payload(&self) -> &[u8] { 184 | &self.payload 185 | } 186 | 187 | fn properties(&self) -> &batch::Properties { 188 | &self.properties 189 | } 190 | 191 | fn ack(self) -> Self::AckFuture { 192 | let id = self.properties().id; 193 | let job = &self.properties().task; 194 | let delivery_tag = self.delivery_tag; 195 | log::debug!( 196 | "ack; id={} job={:?} delivery_tag={:?}", 197 | id, 198 | job, 199 | delivery_tag 200 | ); 201 | let task = self 202 | .channel 203 | .basic_ack(self.delivery_tag, false) 204 | .map_err(Error::from); 205 | AcknowledgeFuture(Box::new(task)) 206 | } 207 | 208 | fn reject(self) -> Self::RejectFuture { 209 | let id = self.properties().id; 210 | let job = &self.properties().task; 211 | let delivery_tag = self.delivery_tag; 212 | log::debug!( 213 | "reject; id={} job={:?} delivery_tag={:?}", 214 | id, 215 | job, 216 | delivery_tag 217 | ); 218 | let task = self 219 | .channel 220 | .basic_reject(self.delivery_tag, false) 221 | .map_err(Error::from); 222 | RejectFuture(Box::new(task)) 223 | } 224 | } 225 | -------------------------------------------------------------------------------- /batch-rabbitmq/src/exchange.rs: -------------------------------------------------------------------------------- 1 | /// Allowed types for RabbitMQ's exchanges. 2 | /// 3 | /// Built-in types are represented as dedicated enum variants, and you can specify other exchange types using the 4 | /// `Kind::Custom` variant. 5 | #[derive(Debug, Clone, Eq, PartialEq)] 6 | pub enum Kind { 7 | /// RabbitMQ's direct exchange type 8 | Direct, 9 | /// RabbitMQ's fanout exchange type 10 | Fanout, 11 | /// RabbitMQ's topic exchange type 12 | Topic, 13 | /// RabbitMQ's headers exchange type 14 | Headers, 15 | /// A custom exchange type 16 | Custom(String), 17 | } 18 | 19 | impl Default for Kind { 20 | /// The default exchange type is `direct`. 21 | fn default() -> Kind { 22 | Kind::Direct 23 | } 24 | } 25 | 26 | impl AsRef for Kind { 27 | fn as_ref(&self) -> &str { 28 | match *self { 29 | Kind::Direct => "direct", 30 | Kind::Fanout => "fanout", 31 | Kind::Topic => "topic", 32 | Kind::Headers => "headers", 33 | Kind::Custom(ref name) => name.as_ref(), 34 | } 35 | } 36 | } 37 | 38 | /// A builder for the `Exchange` type. 39 | /// 40 | /// You should not have to construct values of this type yourself, and should instead let 41 | /// `batch_rabbitmq`'s procedural macros generate the necessary invocations. 42 | #[derive(Debug, Clone)] 43 | pub struct Builder { 44 | pub(crate) name: String, 45 | pub(crate) kind: Kind, 46 | } 47 | 48 | impl Builder { 49 | /// Sets the kind of the exchange that will be created. 50 | /// 51 | /// # Example 52 | /// 53 | /// ``` 54 | /// use batch_rabbitmq::{Exchange, ExchangeKind}; 55 | /// 56 | /// let kind = ExchangeKind::Topic; 57 | /// let builder = Exchange::build("batch-exchange") 58 | /// .kind(kind); 59 | /// ``` 60 | pub fn kind(mut self, kind: Kind) -> Self { 61 | self.kind = kind; 62 | self 63 | } 64 | 65 | /// Consume the builder and create the exchange. 66 | /// 67 | /// # Example 68 | /// 69 | /// ``` 70 | /// use batch_rabbitmq::Exchange; 71 | /// 72 | /// let exchange = Exchange::build("batch-example").finish(); 73 | /// ``` 74 | pub fn finish(self) -> Exchange { 75 | Exchange { 76 | name: self.name, 77 | kind: self.kind, 78 | } 79 | } 80 | } 81 | 82 | /// A RabbitMQ exchange. 83 | /// 84 | /// You should not have to construct values of this type yourself, and should instead let 85 | /// `batch_rabbitmq`'s procedural macros generate the necessary invocations. 86 | #[derive(Debug, Clone)] 87 | pub struct Exchange { 88 | name: String, 89 | kind: Kind, 90 | } 91 | 92 | impl Exchange { 93 | /// Create a new `Exchange` with the default exchange type (direct). 94 | /// 95 | /// # Example 96 | /// 97 | /// ``` 98 | /// use batch_rabbitmq::Exchange; 99 | /// 100 | /// let exchange = Exchange::new("batch-example"); 101 | /// ``` 102 | pub fn new(name: impl Into) -> Self { 103 | Exchange { 104 | name: name.into(), 105 | kind: Kind::default(), 106 | } 107 | } 108 | 109 | /// Create a builder for a new `Exchange` named `name`. 110 | /// 111 | /// # Example 112 | /// 113 | /// ``` 114 | /// use batch_rabbitmq::{Exchange}; 115 | /// 116 | /// let builder = Exchange::build("batch-example"); 117 | /// ``` 118 | pub fn build(name: impl Into) -> Builder { 119 | Builder { 120 | name: name.into(), 121 | kind: Kind::Direct, 122 | } 123 | } 124 | 125 | /// The name of this exchange. 126 | /// 127 | /// # Example 128 | /// 129 | /// ``` 130 | /// use batch_rabbitmq::Exchange; 131 | /// 132 | /// let exchange = Exchange::new("batch-example"); 133 | /// assert!(exchange.name() == "batch-example"); 134 | /// ``` 135 | pub fn name(&self) -> &str { 136 | &self.name 137 | } 138 | 139 | /// The type of this exchange. 140 | /// 141 | /// This method is named `kind` instead of `type` because it conflicts with the `type` keyword 142 | /// of the Rust language. 143 | /// 144 | /// # Example 145 | /// 146 | /// ``` 147 | /// use batch_rabbitmq::{Exchange, ExchangeKind}; 148 | /// 149 | /// let exchange = Exchange::new("batch-example"); 150 | /// assert!(exchange.kind() == &ExchangeKind::Direct); 151 | /// 152 | /// let exchange = Exchange::build("batch-example") 153 | /// .kind(ExchangeKind::Custom("x-delay-exchange".into())) 154 | /// .finish(); 155 | /// assert!(exchange.kind() == &ExchangeKind::Custom("x-delay-exchange".into())); 156 | /// ``` 157 | pub fn kind(&self) -> &Kind { 158 | &self.kind 159 | } 160 | } 161 | 162 | #[cfg(test)] 163 | mod test { 164 | use super::*; 165 | 166 | #[test] 167 | fn test_exchange_kind_as_ref_str() { 168 | struct TestCase { 169 | kind: Kind, 170 | expected: &'static str, 171 | } 172 | 173 | let cases = vec![ 174 | TestCase { 175 | kind: Kind::Direct, 176 | expected: "direct", 177 | }, 178 | TestCase { 179 | kind: Kind::Fanout, 180 | expected: "fanout", 181 | }, 182 | TestCase { 183 | kind: Kind::Topic, 184 | expected: "topic", 185 | }, 186 | TestCase { 187 | kind: Kind::Headers, 188 | expected: "headers", 189 | }, 190 | TestCase { 191 | kind: Kind::Custom("".into()), 192 | expected: "", 193 | }, 194 | TestCase { 195 | kind: Kind::Custom("x-delay-exchange".into()), 196 | expected: "x-delay-exchange", 197 | }, 198 | TestCase { 199 | kind: Kind::Custom("direct".into()), 200 | expected: "direct", 201 | }, 202 | ]; 203 | 204 | for case in cases { 205 | assert_eq!(case.kind.as_ref(), case.expected); 206 | } 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /batch-rabbitmq/src/export.rs: -------------------------------------------------------------------------------- 1 | pub use batch::{Factory, Job, Query, Queue}; 2 | pub use failure::Error; 3 | pub use futures::Future; 4 | pub use std::boxed::Box; 5 | pub use std::iter::Iterator; 6 | pub use std::marker::Send; 7 | -------------------------------------------------------------------------------- /batch-rabbitmq/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! RabbitMQ adapter for the `batch` library. 2 | 3 | #![doc(html_root_url = "https://docs.rs/batch-rabbitmq/0.2.0")] 4 | #![deny(missing_debug_implementations)] 5 | #![deny(missing_docs)] 6 | 7 | mod connection; 8 | mod consumer; 9 | mod declare; 10 | mod delivery; 11 | mod exchange; 12 | /// Not public API. This module is exempt from any semver guarantees. 13 | #[doc(hidden)] 14 | pub mod export; 15 | mod queue; 16 | mod stream; 17 | 18 | pub use crate::connection::{Builder as ConnectionBuilder, ConnectFuture, Connection, SendFuture}; 19 | pub use crate::declare::Declare; 20 | pub use crate::delivery::{AcknowledgeFuture, Delivery, RejectFuture}; 21 | pub use crate::exchange::{Builder as ExchangeBuilder, Exchange, Kind as ExchangeKind}; 22 | pub use crate::queue::{Builder as QueueBuilder, Queue}; 23 | #[cfg(feature = "codegen")] 24 | pub use batch_rabbitmq_codegen::queues; 25 | -------------------------------------------------------------------------------- /batch-rabbitmq/src/queue.rs: -------------------------------------------------------------------------------- 1 | use batch; 2 | use failure::Error; 3 | use futures::{future, Future}; 4 | use serde_json; 5 | use std::collections::BTreeMap; 6 | use std::fmt; 7 | 8 | use crate::{ConnectionBuilder, Exchange}; 9 | 10 | /// A builder for the [`Queue`] type. 11 | /// 12 | /// You should not have to construct values of this type yourself, and should instead let 13 | /// `batch_rabbitmq`'s procedural macros generate the necessary invocations. 14 | pub struct Builder { 15 | name: String, 16 | exchange: Exchange, 17 | callbacks: BTreeMap< 18 | &'static str, 19 | fn(&[u8], &batch::Factory) -> Box + Send>, 20 | >, 21 | } 22 | 23 | impl fmt::Debug for Builder { 24 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 25 | f.debug_struct("Builder") 26 | .field("name", &self.name) 27 | .field("exchange", &self.exchange) 28 | .field("callbacks", &self.callbacks.keys()) 29 | .finish() 30 | } 31 | } 32 | 33 | impl Builder { 34 | /// Binds the given job type and its associated callbacks to this queue. 35 | pub fn bind(mut self) -> Self 36 | where 37 | J: batch::Job, 38 | { 39 | let callback = |payload: &[u8], context: &batch::Factory| // TODO: try to remote type annotations 40 | -> Box + Send> { 41 | let job: J = match serde_json::from_slice(payload) { 42 | Ok(job) => job, 43 | Err(e) => return Box::new(future::err(Error::from(e))), 44 | }; 45 | Box::new(job.perform(context)) 46 | }; 47 | self.callbacks.insert(J::NAME, callback); 48 | self 49 | } 50 | 51 | /// Set the exchange for the [`Queue`] that will be created. 52 | pub fn exchange(mut self, exchange: Exchange) -> Self { 53 | self.exchange = exchange; 54 | self 55 | } 56 | 57 | /// Create the [`Queue`] from the builder fields. 58 | pub fn finish(self) -> Queue { 59 | Queue { 60 | name: self.name, 61 | exchange: self.exchange, 62 | callbacks: self.callbacks, 63 | } 64 | } 65 | } 66 | 67 | /// A RabbitMQ Queue. 68 | /// 69 | /// You should not have to construct values of this type yourself, and should instead let 70 | /// `batch_rabbitmq`'s procedural macros generate the necessary invocations. 71 | #[derive(Clone)] 72 | pub struct Queue { 73 | name: String, 74 | exchange: Exchange, 75 | callbacks: BTreeMap< 76 | &'static str, 77 | fn(&[u8], &batch::Factory) -> Box + Send>, 78 | >, 79 | } 80 | 81 | impl fmt::Debug for Queue { 82 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 83 | f.debug_struct("Builder") 84 | .field("name", &self.name) 85 | .field("exchange", &self.exchange) 86 | .field("callbacks", &self.callbacks.keys()) 87 | .finish() 88 | } 89 | } 90 | 91 | impl Queue { 92 | /// Create a [`Builder`] for a [`Queue`] named `name`. 93 | pub fn build(name: impl Into) -> Builder { 94 | let name = name.into(); 95 | Builder { 96 | name: name.clone(), 97 | exchange: Exchange::new(name), 98 | callbacks: BTreeMap::new(), 99 | } 100 | } 101 | 102 | /// The name of this queue. 103 | /// 104 | /// # Example 105 | /// 106 | /// ``` 107 | /// use batch_rabbitmq::Queue; 108 | /// 109 | /// let queue = Queue::build("batch-queue").finish(); 110 | /// assert!(queue.name() == "batch-queue"); 111 | /// ``` 112 | pub fn name(&self) -> &str { 113 | &self.name 114 | } 115 | 116 | /// The exchange associated to this queue. 117 | pub fn exchange(&self) -> &Exchange { 118 | &self.exchange 119 | } 120 | 121 | /// The callbacks associated to this queue. 122 | pub fn callbacks( 123 | &self, 124 | ) -> impl Iterator< 125 | Item = ( 126 | &'static str, 127 | fn(&[u8], &batch::Factory) -> Box + Send>, 128 | ), 129 | > { 130 | self.callbacks.clone().into_iter() // TODO: remove clone 131 | } 132 | 133 | /// Register this queue to the given [`ConnectionBuilder`]. 134 | pub fn register(self, conn: &mut ConnectionBuilder) { 135 | conn.queues.insert(self.name().into(), self); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /batch-rabbitmq/src/stream.rs: -------------------------------------------------------------------------------- 1 | use amq_protocol::uri::{AMQPScheme, AMQPUri}; 2 | use bytes::{Buf, BufMut}; 3 | use failure::Error; 4 | use futures::{Future, IntoFuture, Poll}; 5 | use native_tls::TlsConnector; 6 | use std::io::{self, Read, Write}; 7 | use std::net; 8 | use tokio_io::{AsyncRead, AsyncWrite}; 9 | use tokio_reactor::Handle; 10 | use tokio_tcp::TcpStream; 11 | use tokio_tls::TlsConnectorExt; 12 | 13 | #[derive(Debug)] 14 | pub enum Stream { 15 | Raw(::tokio_tcp::TcpStream), 16 | Tls(::tokio_tls::TlsStream<::tokio_tcp::TcpStream>), 17 | } 18 | 19 | impl Stream { 20 | pub(crate) fn new(uri: AMQPUri) -> impl Future { 21 | log::trace!("Establishing TCP connection"); 22 | net::TcpStream::connect((uri.authority.host.clone().as_ref(), uri.authority.port)) 23 | .map_err(Error::from) 24 | .into_future() 25 | .and_then(move |stream| { 26 | let task = if uri.scheme == AMQPScheme::AMQP { 27 | log::trace!("Wrapping TCP connection into tokio-tcp"); 28 | let handle = Handle::current(); 29 | let task = TcpStream::from_std(stream, &handle) 30 | .map(Stream::Raw) 31 | .map_err(|e| e.into()) 32 | .into_future(); 33 | Box::new(task) as Box + Send> 34 | } else { 35 | log::trace!("Wrapping TCP connection into tokio-tls"); 36 | let host = uri.authority.host.clone(); 37 | let task = TlsConnector::builder() 38 | .map_err(|e| e.into()) 39 | .into_future() 40 | .and_then(|builder| builder.build().map_err(|e| e.into())) 41 | .and_then(move |connector| { 42 | let handle = Handle::current(); 43 | TcpStream::from_std(stream, &handle) 44 | .map_err(|e| e.into()) 45 | .into_future() 46 | .map(|s| (s, connector)) 47 | }) 48 | .and_then(move |(stream, connector)| { 49 | connector 50 | .connect_async(&host, stream) 51 | .map(Stream::Tls) 52 | .map_err(|e| e.into()) 53 | }); 54 | Box::new(task) as Box + Send> 55 | }; 56 | task 57 | }) 58 | } 59 | } 60 | 61 | impl Read for Stream { 62 | fn read(&mut self, buf: &mut [u8]) -> io::Result { 63 | match *self { 64 | Stream::Raw(ref mut raw) => raw.read(buf), 65 | Stream::Tls(ref mut raw) => raw.read(buf), 66 | } 67 | } 68 | } 69 | 70 | impl AsyncRead for Stream { 71 | unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool { 72 | match *self { 73 | Stream::Raw(ref raw) => raw.prepare_uninitialized_buffer(buf), 74 | Stream::Tls(ref raw) => raw.prepare_uninitialized_buffer(buf), 75 | } 76 | } 77 | 78 | fn read_buf(&mut self, buf: &mut B) -> Poll { 79 | match *self { 80 | Stream::Raw(ref mut raw) => raw.read_buf(buf), 81 | Stream::Tls(ref mut raw) => raw.read_buf(buf), 82 | } 83 | } 84 | } 85 | 86 | impl Write for Stream { 87 | fn write(&mut self, buf: &[u8]) -> io::Result { 88 | match *self { 89 | Stream::Raw(ref mut raw) => raw.write(buf), 90 | Stream::Tls(ref mut raw) => raw.write(buf), 91 | } 92 | } 93 | 94 | fn flush(&mut self) -> io::Result<()> { 95 | match *self { 96 | Stream::Raw(ref mut raw) => raw.flush(), 97 | Stream::Tls(ref mut raw) => raw.flush(), 98 | } 99 | } 100 | } 101 | 102 | impl AsyncWrite for Stream { 103 | fn shutdown(&mut self) -> Poll<(), io::Error> { 104 | match *self { 105 | Stream::Raw(ref mut raw) => raw.shutdown(), 106 | Stream::Tls(ref mut raw) => raw.shutdown(), 107 | } 108 | } 109 | 110 | fn write_buf(&mut self, buf: &mut B) -> Poll { 111 | match *self { 112 | Stream::Raw(ref mut raw) => raw.write_buf(buf), 113 | Stream::Tls(ref mut raw) => raw.write_buf(buf), 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /batch-rabbitmq/tests/consume.rs: -------------------------------------------------------------------------------- 1 | extern crate batch; 2 | extern crate batch_rabbitmq; 3 | extern crate env_logger; 4 | extern crate log; 5 | extern crate tokio; 6 | 7 | use batch::job; 8 | use batch_rabbitmq::queues; 9 | 10 | #[job(name = "convert-video-file")] 11 | fn convert_video_file(path: String) { 12 | println!("Converting {}...", path); 13 | } 14 | 15 | #[job(name = "say-hello")] 16 | fn say_hello(name: String) { 17 | println!("Hello: {}", name); 18 | } 19 | 20 | queues! { 21 | Transcoding { 22 | name = "tests-consume.transcoding", 23 | bindings = [ 24 | convert_video_file, 25 | say_hello, 26 | ], 27 | } 28 | } 29 | 30 | #[test] 31 | fn consume_from_basic_queue() { 32 | use batch::{Client, Delivery, Job, Queue}; 33 | use batch_rabbitmq::Connection; 34 | use log::info; 35 | use std::collections::VecDeque; 36 | use tokio::prelude::*; 37 | 38 | let _ = ::env_logger::try_init(); 39 | let mut runtime = tokio::runtime::current_thread::Runtime::new().unwrap(); 40 | let mut conn = { 41 | let f = Connection::build("amqp://guest:guest@localhost:5672/%2f") 42 | .declare(Transcoding) 43 | .connect(); 44 | runtime.block_on(f).unwrap() 45 | }; 46 | let consumer = { 47 | let f = conn.to_consumer(vec![Transcoding::SOURCE]); 48 | runtime.block_on(f).unwrap() 49 | }; 50 | info!("Connected to RabbitMQ"); 51 | { 52 | let job = convert_video_file("./westworld-2x06.mkv".into()); 53 | let f = Transcoding(job).dispatch(&mut conn); 54 | let _ = runtime.block_on(f).unwrap(); 55 | } 56 | info!("Published first message"); 57 | { 58 | let job = say_hello("Ferris".into()); 59 | let f = Transcoding(job).dispatch(&mut conn); 60 | let _ = runtime.block_on(f).unwrap(); 61 | } 62 | info!("Published second message"); 63 | info!("Published all messages"); 64 | let expected = VecDeque::from(vec![convert_video_file::NAME, say_hello::NAME]); 65 | let mut consumer = consumer.into_future(); 66 | info!("Iterating over consumer deliveries"); 67 | for job in expected { 68 | info!("expecting: {:?}", job); 69 | let (delivery, next) = runtime.block_on(consumer).unwrap(); 70 | assert_eq!(true, delivery.is_some()); 71 | let delivery = delivery.unwrap(); 72 | assert_eq!(delivery.properties().task, job); 73 | let _ = runtime.block_on(delivery.ack()).unwrap(); 74 | consumer = next.into_future(); 75 | } 76 | { 77 | info!("Dropping RabbitMQ connection in order to stop background task"); 78 | drop(conn); 79 | } 80 | // FIXME: we're not checking whether deliveries have been ack'ed correctly. 81 | // Calling basic.get on tests-consume.transcoding using lapin should be enough. 82 | runtime.run().unwrap(); 83 | } 84 | -------------------------------------------------------------------------------- /batch-stub/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | edition = "2018" 3 | name = "batch-stub" 4 | description = "Testing utilities for the Batch library" 5 | repository = "https://github.com/kureuil/batch-rs" 6 | version = "0.2.0" # remember to update html_root_url 7 | license = "MIT/Apache-2.0" 8 | authors = ["Louis Person "] 9 | 10 | [dependencies] 11 | batch = { version = "0.2", path = "../" } 12 | failure = "0.1" 13 | futures = "0.1" 14 | serde = "1.0" 15 | 16 | [dev-dependencies] 17 | serde = { version = "1.0", features = ["derive"] } 18 | tokio = "0.1" 19 | -------------------------------------------------------------------------------- /batch-stub/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /batch-stub/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /batch-stub/src/client.rs: -------------------------------------------------------------------------------- 1 | use failure::Error; 2 | use futures::future; 3 | use std::collections::HashMap; 4 | use std::sync::{Arc, Mutex}; 5 | 6 | mod sealed { 7 | use failure::Error; 8 | use futures::future; 9 | use serde::{Deserialize, Serialize}; 10 | 11 | /// Stub job used to trick the type system in `Connection::declare`. 12 | #[derive(Debug, Deserialize, Serialize)] 13 | pub struct StubJob; 14 | 15 | impl batch::Job for StubJob { 16 | const NAME: &'static str = ""; 17 | 18 | type PerformFuture = future::FutureResult<(), Error>; 19 | 20 | fn perform(self, _ctx: &batch::Factory) -> Self::PerformFuture { 21 | future::ok(()) 22 | } 23 | } 24 | } 25 | 26 | use self::sealed::StubJob; 27 | 28 | /// A stub implentation of [`batch::Client`]. 29 | /// 30 | /// This client implementation is made to be used in tests, to check that your code is correctly 31 | /// enqueuing the correct number of jobs in the right queues. It is not meant to be used as a real 32 | /// [`batch::Client`] implementation in a production app. 33 | /// 34 | /// The `Consumer` returned by this client is completely useless and should not be used in tests 35 | /// now. 36 | #[derive(Clone, Debug)] 37 | pub struct Client { 38 | inner: Arc>, 39 | } 40 | 41 | #[derive(Debug)] 42 | struct Inner { 43 | dispatches: HashMap>, 44 | } 45 | 46 | impl Client { 47 | /// Create a new stub client instance. 48 | /// 49 | /// # Example 50 | /// 51 | /// ``` 52 | /// use batch_stub::Client; 53 | /// 54 | /// let client = Client::new(); 55 | /// ``` 56 | pub fn new() -> Self { 57 | let inner = Inner { 58 | dispatches: HashMap::new(), 59 | }; 60 | Client { 61 | inner: Arc::new(Mutex::new(inner)), 62 | } 63 | } 64 | 65 | /// Count the number of jobs in the given queue. 66 | /// 67 | /// If the given queue is unknown the function returns 0. 68 | /// 69 | /// **Note:** the function takes a function returning a `Query` as parameter but you're not 70 | /// supposed to write this function yourself, it should be provided by your Batch adapter. 71 | /// 72 | /// # Panics 73 | /// 74 | /// This function can panic if its inner [`Mutex`] has been poisonned and cannot be locked. 75 | pub fn count(&self, _ctor: impl Fn(StubJob) -> batch::Query) -> usize 76 | where 77 | Q: batch::Queue, 78 | { 79 | let inner = self.inner.lock().unwrap(); 80 | inner 81 | .dispatches 82 | .get(Q::DESTINATION.into()) 83 | .map(|v| v.len()) 84 | .unwrap_or(0) 85 | } 86 | } 87 | 88 | #[derive(Debug)] 89 | pub struct Delivery; 90 | 91 | impl batch::Delivery for Delivery { 92 | fn properties(&self) -> &batch::Properties { 93 | unimplemented!(); 94 | } 95 | 96 | fn payload(&self) -> &[u8] { 97 | unimplemented!(); 98 | } 99 | 100 | type AckFuture = Box + Send>; 101 | 102 | fn ack(self) -> Self::AckFuture { 103 | unimplemented!(); 104 | } 105 | 106 | type RejectFuture = Box + Send>; 107 | 108 | fn reject(self) -> Self::RejectFuture { 109 | unimplemented!(); 110 | } 111 | } 112 | 113 | #[derive(Debug)] 114 | pub struct Consumer; 115 | 116 | impl futures::Stream for Consumer { 117 | type Item = Delivery; 118 | 119 | type Error = Error; 120 | 121 | fn poll(&mut self) -> futures::Poll, Self::Error> { 122 | unimplemented!(); 123 | } 124 | } 125 | 126 | impl batch::Consumer for Consumer { 127 | type Delivery = Delivery; 128 | } 129 | 130 | impl batch::Client for Client { 131 | type SendFuture = future::FutureResult<(), Error>; 132 | 133 | fn send(&mut self, dispatch: batch::Dispatch) -> Self::SendFuture { 134 | let mut inner = self.inner.lock().unwrap(); 135 | inner 136 | .dispatches 137 | .entry(dispatch.destination().into()) 138 | .or_insert_with(Vec::new) 139 | .push(dispatch); 140 | future::ok(()) 141 | } 142 | 143 | type Consumer = Consumer; 144 | 145 | type ToConsumerFuture = Box + Send>; 146 | 147 | fn to_consumer( 148 | &mut self, 149 | _queues: impl IntoIterator>, 150 | ) -> Self::ToConsumerFuture { 151 | unimplemented!(); 152 | } 153 | } 154 | 155 | #[cfg(test)] 156 | mod tests { 157 | use super::*; 158 | 159 | use batch::{Client as BatchClient, Queue}; 160 | use futures::Future; 161 | use serde::{Deserialize, Serialize}; 162 | use std::vec; 163 | 164 | struct MaintenanceQueue {} 165 | 166 | #[allow(non_snake_case)] 167 | fn MaintenanceQueue(job: J) -> batch::Query 168 | where 169 | J: batch::Job, 170 | { 171 | batch::Query::new(job) 172 | } 173 | 174 | impl batch::Queue for MaintenanceQueue { 175 | const SOURCE: &'static str = "maintenance"; 176 | 177 | const DESTINATION: &'static str = "maintenance"; 178 | 179 | type CallbacksIterator = std::vec::IntoIter<( 180 | &'static str, 181 | fn(&[u8], &batch::Factory) -> Box + Send>, 182 | )>; 183 | 184 | fn callbacks() -> Self::CallbacksIterator { 185 | vec![].into_iter() 186 | } 187 | } 188 | 189 | struct TranscodingQueue {} 190 | 191 | #[allow(non_snake_case)] 192 | fn TranscodingQueue(job: J) -> batch::Query 193 | where 194 | J: batch::Job, 195 | { 196 | batch::Query::new(job) 197 | } 198 | 199 | impl batch::Queue for TranscodingQueue { 200 | const SOURCE: &'static str = "transcoding"; 201 | 202 | const DESTINATION: &'static str = "transcoding"; 203 | 204 | type CallbacksIterator = std::vec::IntoIter<( 205 | &'static str, 206 | fn(&[u8], &batch::Factory) -> Box + Send>, 207 | )>; 208 | 209 | fn callbacks() -> Self::CallbacksIterator { 210 | vec![].into_iter() 211 | } 212 | } 213 | 214 | #[derive(Deserialize, Serialize)] 215 | struct ConvertVideoFile {} 216 | 217 | impl batch::Job for ConvertVideoFile { 218 | const NAME: &'static str = "convert-video-file"; 219 | 220 | type PerformFuture = future::FutureResult<(), Error>; 221 | 222 | fn perform(self, _ctx: &batch::Factory) -> Self::PerformFuture { 223 | future::ok(()) 224 | } 225 | } 226 | 227 | #[test] 228 | fn test_client_count_published_jobs_correctly() { 229 | let mut runtime = tokio::runtime::current_thread::Runtime::new().unwrap(); 230 | let mut client = Client::new(); 231 | assert_eq!(client.count(MaintenanceQueue), 0); 232 | assert_eq!(client.count(TranscodingQueue), 0); 233 | { 234 | let job = ConvertVideoFile {}; 235 | let fut = MaintenanceQueue(job).dispatch(&mut client); 236 | let _ = runtime.block_on(fut).unwrap(); 237 | assert_eq!(client.count(MaintenanceQueue), 1); 238 | assert_eq!(client.count(TranscodingQueue), 0); 239 | } 240 | { 241 | let job = ConvertVideoFile {}; 242 | let fut = TranscodingQueue(job).dispatch(&mut client); 243 | let _ = runtime.block_on(fut).unwrap(); 244 | assert_eq!(client.count(MaintenanceQueue), 1); 245 | assert_eq!(client.count(TranscodingQueue), 1); 246 | } 247 | } 248 | 249 | #[test] 250 | #[should_panic] 251 | fn test_creating_a_consumer_should_panic() { 252 | let mut client = Client::new(); 253 | let _ = client.to_consumer(vec![MaintenanceQueue::SOURCE, TranscodingQueue::SOURCE]); 254 | } 255 | } 256 | -------------------------------------------------------------------------------- /batch-stub/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Testing utilities for the Batch library. 2 | //! 3 | //! This crate exists to help you test your code depending on Batch. For now it only contains a 4 | //! [`batch::Client`] implementation but we'd like to have more testing facilities in the 5 | //! future. 6 | 7 | #![doc(html_root_url = "https://docs.rs/batch-stub/0.2.0")] 8 | #![deny(missing_debug_implementations)] 9 | #![deny(missing_docs)] 10 | 11 | mod client; 12 | 13 | pub use crate::client::Client; 14 | -------------------------------------------------------------------------------- /batch-test/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | edition = "2018" 3 | name = "batch-test" 4 | description = "Testing utilities for Batch adapters" 5 | repository = "https://github.com/kureuil/batch-rs" 6 | version = "0.0.0" # remember to update html_root_url 7 | license = "MIT/Apache-2.0" 8 | authors = ["Louis Person "] 9 | 10 | [dependencies] 11 | batch = { version = "0.2", path = "../" } 12 | -------------------------------------------------------------------------------- /batch-test/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /batch-test/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /batch-test/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Testing utilities for Batch. 2 | 3 | #![doc(html_root_url = "https://docs.rs/batch-test/0.2.0")] 4 | #![deny(missing_debug_implementations)] 5 | #![deny(missing_docs)] 6 | 7 | #[cfg(test)] 8 | mod tests { 9 | #[test] 10 | fn it_works() { 11 | assert_eq!(2 + 2, 4); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /ci/install.ps1: -------------------------------------------------------------------------------- 1 | $ProgressPreference = 'SilentlyContinue' 2 | $ErrorActionPreference = 'Stop' 3 | Set-StrictMode -Version 2.0 4 | 5 | [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 'Tls12' 6 | 7 | $rabbitmq_installer_download_url = 'https://github.com/rabbitmq/rabbitmq-server/releases/download/v3.7.4/rabbitmq-server-3.7.4.exe' 8 | $rabbitmq_installer_path = Join-Path -Path $HOME -ChildPath 'rabbitmq-server-3.7.4.exe' 9 | 10 | $erlang_reg_path = 'HKLM:\SOFTWARE\Ericsson\Erlang' 11 | if (Test-Path 'HKLM:\SOFTWARE\WOW6432Node\') 12 | { 13 | $erlang_reg_path = 'HKLM:\SOFTWARE\WOW6432Node\Ericsson\Erlang' 14 | } 15 | $erlang_erts_version = Get-ChildItem -Path $erlang_reg_path -Name 16 | $erlang_home = (Get-ItemProperty -LiteralPath $erlang_reg_path\$erlang_erts_version).'(default)' 17 | 18 | $env:ERLANG_HOME = $erlang_home 19 | [Environment]::SetEnvironmentVariable('ERLANG_HOME', $erlang_home, 'Machine') 20 | 21 | Write-Host '[INFO] Downloading RabbitMQ' 22 | 23 | if (-Not (Test-Path $rabbitmq_installer_path)) 24 | { 25 | Invoke-WebRequest -UseBasicParsing -Uri $rabbitmq_installer_download_url -OutFile $rabbitmq_installer_path 26 | } 27 | else 28 | { 29 | Write-Host "[INFO] Found $rabbitmq_installer_path in cache." 30 | } 31 | 32 | Write-Host '[INFO] Creating Erlang cookie files' 33 | 34 | function Set-ErlangCookie { 35 | Param($Path, $Value = 'RABBITMQ-COOKIE') 36 | Remove-Item -Force $Path -ErrorAction SilentlyContinue 37 | [System.IO.File]::WriteAllText($Path, $Value, [System.Text.Encoding]::ASCII) 38 | } 39 | 40 | $erlang_cookie_user = Join-Path -Path $HOME -ChildPath '.erlang.cookie' 41 | $erlang_cookie_system = Join-Path -Path $env:SystemRoot -ChildPath 'System32\config\systemprofile\.erlang.cookie' 42 | 43 | Set-ErlangCookie -Path $erlang_cookie_user 44 | Set-ErlangCookie -Path $erlang_cookie_system 45 | 46 | Write-Host '[INFO] Installing and starting RabbitMQ with default config' 47 | 48 | & $rabbitmq_installer_path '/S' | Out-Null 49 | (Get-Service -Name RabbitMQ).Status 50 | 51 | Write-Host '[INFO] Setting RABBITMQ_RABBITMQCTL_PATH' 52 | 53 | $regPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\RabbitMQ' 54 | if (Test-Path 'HKLM:\SOFTWARE\WOW6432Node\') 55 | { 56 | $regPath = 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\RabbitMQ' 57 | } 58 | $path = Split-Path -Parent (Get-ItemProperty $regPath 'UninstallString').UninstallString 59 | $rabbitmq_version = (Get-ItemProperty $regPath "DisplayVersion").DisplayVersion 60 | 61 | $rabbitmq_home = "$path\rabbitmq_server-$rabbitmq_version" 62 | [Environment]::SetEnvironmentVariable('RABBITMQ_HOME', $rabbitmq_home, 'Machine') 63 | $env:RABBITMQ_HOME = $rabbitmq_home 64 | 65 | $rabbitmqctl_path = "$path\rabbitmq_server-$rabbitmq_version\sbin\rabbitmqctl.bat" 66 | [Environment]::SetEnvironmentVariable('RABBITMQ_RABBITMQCTL_PATH', $rabbitmqctl_path, 'Machine') 67 | $env:RABBITMQ_RABBITMQCTL_PATH = $rabbitmqctl_path 68 | 69 | Write-Host '[INFO] Waiting for epmd to report that RabbitMQ has started' 70 | 71 | $epmd_running = $false 72 | [int]$count = 1 73 | 74 | $epmd = [System.IO.Path]::Combine($erlang_home, "erts-$erlang_erts_version", "bin", "epmd.exe") 75 | 76 | Do { 77 | $epmd_running = & $epmd -names | Select-String -CaseSensitive -SimpleMatch -Quiet -Pattern 'name rabbit at port 25672' 78 | if ($epmd_running -eq $true) { 79 | Write-Host '[INFO] epmd reports that RabbitMQ is at port 25672' 80 | break 81 | } 82 | 83 | if ($count -gt 60) { 84 | throw '[ERROR] too many tries waiting for epmd to report RabbitMQ on port 25672' 85 | } 86 | 87 | Write-Host "[INFO] epmd NOT reporting yet that RabbitMQ is at port 25672, count: $count" 88 | $count = $count + 1 89 | Start-Sleep -Seconds 5 90 | 91 | } While ($true) 92 | 93 | [int]$count = 1 94 | 95 | Do { 96 | $proc_id = (Get-Process -Name erl).Id 97 | if (-Not ($proc_id -is [array])) { 98 | & $rabbitmqctl_path wait -t 300000 -P $proc_id 99 | if ($LASTEXITCODE -ne 0) { 100 | throw "[ERROR] rabbitmqctl wait returned error: $LASTEXITCODE" 101 | } 102 | break 103 | } 104 | 105 | if ($count -gt 120) { 106 | throw '[ERROR] too many tries waiting for just one erl process to be running' 107 | } 108 | 109 | Write-Host '[INFO] multiple erl instances running still' 110 | $count = $count + 1 111 | Start-Sleep -Seconds 5 112 | 113 | } While ($true) 114 | 115 | Write-Host '[INFO] Getting RabbitMQ status' 116 | & $rabbitmqctl_path status -------------------------------------------------------------------------------- /examples/rabbitmq-simple/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | edition = "2018" 3 | name = "batch-example-rabbitmq-standalone" 4 | version = "0.2.0" 5 | authors = ["Louis Person "] 6 | publish = false 7 | 8 | [[bin]] 9 | name = "client" 10 | doc = false 11 | 12 | [[bin]] 13 | name = "worker" 14 | doc = false 15 | 16 | [dependencies] 17 | batch = { version = "0.2", path = "../../" } 18 | batch-rabbitmq = { version = "0.2", path = "../../batch-rabbitmq" } 19 | env_logger = "0.5" 20 | failure = "0.1" 21 | futures = "0.1" 22 | tokio = "0.1" 23 | serde = "1" 24 | -------------------------------------------------------------------------------- /examples/rabbitmq-simple/src/bin/client.rs: -------------------------------------------------------------------------------- 1 | extern crate batch_example_rabbitmq_standalone as example; 2 | 3 | use tokio::prelude::Future; 4 | 5 | use crate::example::{jobs, queues}; 6 | 7 | fn main() { 8 | env_logger::init(); 9 | let task = batch_rabbitmq::Connection::build("amqp://guest:guest@localhost:5672/%2f") 10 | .declare(queues::Transcoding) 11 | .connect() 12 | .and_then(|mut client| { 13 | let filepath = "./westworld-2x06.mkv".into(); 14 | let job = jobs::convert_video_file(filepath, jobs::VideoFormat::Mpeg4); 15 | queues::Transcoding(job).dispatch(&mut client) 16 | }) 17 | .map_err(|e| eprintln!("An error occured: {}", e)); 18 | tokio::run(task); 19 | } 20 | -------------------------------------------------------------------------------- /examples/rabbitmq-simple/src/bin/worker.rs: -------------------------------------------------------------------------------- 1 | extern crate batch_example_rabbitmq_standalone as example; 2 | 3 | use tokio::prelude::Future; 4 | 5 | use crate::example::queues; 6 | 7 | fn main() { 8 | env_logger::init(); 9 | let task = batch_rabbitmq::Connection::build("amqp://guest:guest@localhost:5672/%2f") 10 | .declare(queues::Transcoding) 11 | .connect() 12 | .map(|connection| batch::Worker::new(connection).queue(queues::Transcoding)) 13 | .and_then(|worker| worker.work()) 14 | .map_err(|e| eprintln!("An error occured: {}", e)); 15 | tokio::run(task); 16 | } 17 | -------------------------------------------------------------------------------- /examples/rabbitmq-simple/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod queues { 2 | use batch_rabbitmq::queues; 3 | 4 | queues! { 5 | Transcoding { 6 | name = "transcoding", 7 | bindings = [ 8 | super::jobs::convert_video_file 9 | ] 10 | } 11 | } 12 | } 13 | 14 | pub mod jobs { 15 | use batch::export::Error; 16 | use batch::job; 17 | use serde::{Deserialize, Serialize}; 18 | 19 | #[derive(Debug, Serialize, Deserialize)] 20 | pub enum VideoFormat { 21 | Matroska, 22 | Mpeg4, 23 | } 24 | 25 | #[job(name = "batch-example.convert-video-file")] 26 | pub fn convert_video_file(path: String, to: VideoFormat) { 27 | println!("Converting video file {:?} to {:?}...", path, to); 28 | } 29 | 30 | #[derive(Serialize, Deserialize)] 31 | pub enum Event { 32 | ConvertStarted(String), 33 | } 34 | 35 | pub type Mail = (); 36 | 37 | #[job(name = "batch-example.notify", inject = [ _mailer ])] 38 | pub fn notify(_mailer: Mail, _user: String, _event: String) -> Result<(), Error> { 39 | println!("Notifying user..."); 40 | Ok(()) 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /examples/rabbitmq-warp/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | edition = "2018" 3 | name = "batch-example-rabbitmq-warp" 4 | version = "0.2.0" 5 | authors = ["Louis Person "] 6 | publish = false 7 | 8 | [[bin]] 9 | name = "server" 10 | doc = false 11 | 12 | [[bin]] 13 | name = "worker" 14 | doc = false 15 | 16 | [dependencies] 17 | batch = { version = "0.2", path = "../../" } 18 | batch-rabbitmq = { version = "0.2", path = "../../batch-rabbitmq" } 19 | batch-stub = { version = "0.2", path = "../../batch-stub" } 20 | env_logger = "0.5" 21 | failure = "0.1" 22 | futures = "0.1" 23 | serde = { version = "1.0", features = ["derive"] } 24 | tokio = "0.1" 25 | warp = "0.1.2" 26 | -------------------------------------------------------------------------------- /examples/rabbitmq-warp/src/bin/server.rs: -------------------------------------------------------------------------------- 1 | extern crate batch_example_rabbitmq_warp as example; 2 | 3 | use tokio::prelude::Future; 4 | 5 | use crate::example::{endpoints, queues}; 6 | 7 | fn main() { 8 | let task = batch_rabbitmq::Connection::build("amqp://guest:guest@localhost/%2f") 9 | .declare(queues::Transcoding) 10 | .connect() 11 | .map_err(|e| eprintln!("An error occured: {}", e)) 12 | .and_then(|conn| warp::serve(endpoints::endpoints(conn)).bind(([127, 0, 0, 1], 3030))); 13 | 14 | tokio::run(task); 15 | } 16 | -------------------------------------------------------------------------------- /examples/rabbitmq-warp/src/bin/worker.rs: -------------------------------------------------------------------------------- 1 | extern crate batch_example_rabbitmq_warp as example; 2 | 3 | use tokio::prelude::Future; 4 | 5 | use crate::example::queues; 6 | 7 | fn main() { 8 | env_logger::init(); 9 | let task = batch_rabbitmq::Connection::build("amqp://guest:guest@localhost:5672/%2f") 10 | .declare(queues::Transcoding) 11 | .connect() 12 | .map(|connection| batch::Worker::new(connection).queue(queues::Transcoding)) 13 | .and_then(|worker| worker.work()) 14 | .map_err(|e| eprintln!("An error occured: {}", e)); 15 | tokio::run(task); 16 | } 17 | -------------------------------------------------------------------------------- /examples/rabbitmq-warp/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod queues { 2 | use batch_rabbitmq::queues; 3 | 4 | queues! { 5 | Transcoding { 6 | name = "transcoding", 7 | exclusive = true, 8 | bindings = [ 9 | super::jobs::convert_video_file 10 | ] 11 | } 12 | } 13 | } 14 | 15 | pub mod jobs { 16 | use batch::job; 17 | use serde::{Deserialize, Serialize}; 18 | 19 | #[derive(Serialize, Deserialize)] 20 | pub enum VideoFormat { 21 | Matroska, 22 | Mpeg4, 23 | } 24 | 25 | #[job(name = "batch-example.convert-video-file")] 26 | pub fn convert_video_file(_path: String, _to: VideoFormat) { 27 | println!("Converting video file..."); 28 | } 29 | 30 | #[derive(Serialize, Deserialize)] 31 | pub enum Event { 32 | ConvertStarted(String), 33 | } 34 | 35 | pub type Mail = (); 36 | 37 | #[job(name = "batch-example.notify", inject = [ _mailer ])] 38 | pub fn notify(_mailer: Mail, _user: String, _event: Event) { 39 | println!("Notifying user..."); 40 | } 41 | } 42 | 43 | pub mod endpoints { 44 | use super::{jobs, queues}; 45 | use futures::Future; 46 | use warp::{Filter, Rejection, Reply}; 47 | 48 | fn transcode( 49 | mut client: impl batch::Client, 50 | ) -> impl Future { 51 | let job = jobs::convert_video_file("./westworld-2x06.mkv".into(), jobs::VideoFormat::Mpeg4); 52 | queues::Transcoding(job) 53 | .dispatch(&mut client) 54 | .map(|_| warp::reply()) 55 | .map_err(|_e| warp::reject::server_error()) 56 | } 57 | 58 | pub fn endpoints( 59 | client: batch_rabbitmq::Connection, 60 | ) -> impl Filter { 61 | let client = warp::any().map(move || client.clone()); 62 | warp::get2() 63 | .and(warp::path("transcode")) 64 | .and(client) 65 | .and_then(transcode) 66 | } 67 | 68 | #[cfg(test)] 69 | mod test { 70 | use super::*; 71 | use tokio::runtime::current_thread::Runtime; 72 | 73 | #[test] 74 | fn test_transcode_endpoint() { 75 | let _ = env_logger::try_init(); 76 | let mut runtime = Runtime::new().unwrap(); 77 | let client = batch_stub::Client::new(); 78 | let fut = transcode(client.clone()); 79 | let r = runtime.block_on(fut); 80 | assert!(r.is_ok()); 81 | assert_eq!(1, client.count(queues::Transcoding)); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /guide/book.toml: -------------------------------------------------------------------------------- 1 | [book] 2 | title = "Batch Guide" 3 | description = "User guide for the batch-rs library." 4 | authors = [ 5 | "Louis Person ", 6 | ] 7 | multilingual = false 8 | src = "src" 9 | 10 | [output.html] 11 | 12 | [output.linkcheck] 13 | -------------------------------------------------------------------------------- /guide/src/SUMMARY.md: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | [Batch](./batch.md) 4 | - [Concepts](./concepts.md) 5 | - [Jobs](./jobs.md) 6 | - [RabbitMQ](./rabbitmq/index.md) 7 | - [Getting Started](./rabbitmq/getting-started.md) 8 | - [Exchanges](./rabbitmq/exchanges.md) 9 | - [Queues](./rabbitmq/queues.md) 10 | - [Worker](./worker/index.md) 11 | -------------------------------------------------------------------------------- /guide/src/batch.md: -------------------------------------------------------------------------------- 1 | # Batch 2 | 3 | A background job library written in Rust. 4 | 5 | Batch allows you to defer jobs to worker processes, by sending messages to a broker. It is a type-safe library that favors safety over performance in order to minimize risk and avoid mistakes. It leverages the [`futures`] & [`tokio`] crates to provide asynchronous operations to the user. 6 | 7 | Batch doesn't tie you to a particular message broker implementation: a bunch of adapters are bundled in the library but you are free to write your own to accomodate your requirements. As of today batch provides adapters for the following message brokers: 8 | 9 | * [RabbitMQ]: [Go to the associated guide section](./rabbitmq/index.html) 10 | * Stub: [Go to the associated guide section](./batch.html) 11 | 12 | Examples are available on [GitHub][examples] or you can continue and read the Getting Started guide for the message broker of your choice. 13 | 14 | 15 | [`futures`]: https://crates.io/crates/futures 16 | [`tokio`]: https://crates.io/crates/tokio 17 | [RabbitMQ]: https://www.rabbitmq.com/ 18 | [Faktory]: https://contribsys.com/faktory/ 19 | [Amazon SQS]: https://aws.amazon.com/sqs/ 20 | [examples]: https://github.com/kureuil/batch-rs/tree/master/examples 21 | -------------------------------------------------------------------------------- /guide/src/concepts.md: -------------------------------------------------------------------------------- 1 | # Concepts 2 | 3 | If you're not familiar with Rust or background job libraries, some aspects of batch can feel opaque. Hopefully this page will help clear this up and let you enjoy your projects to the fullest. 4 | 5 | ## Job 6 | 7 | A job is a unit of work that you want to defer to a *Worker* process. For example, imagine you're building a shiny new web application and you want to send the user an email when they sign up. You could send the email synchronously, but this often lead to a poor user experience: maybe the email could take a few seconds to send, making the application feel not very responsive, or maybe the email couldn't be sent because of a spurious network error, or maybe your email provider is down for maintenance. Instead, to guarantee an optimal user experience you will send the job to execute to a message broker which will then be sent to a *Worker* process that will execute it. If the execution fails, the job can be retried either until its retries limit is reached or until it succeeds. 8 | 9 | More generally there are two kinds of work you'll want defer: 10 | 11 | * Work that has a dependency on an external service, external meaning "on which you have no control, especially in regard to downtime" (e.g: sending emails, etc). 12 | * Work that might take more than a few seconds to complete (e.g: compressing uploaded image files, re-encode video files, etc). 13 | 14 | ### At-least once delivery & idempotency 15 | 16 | One thing that you must keep in mind when you write a job is that it can be executed multimes times, even if it previously succeeded. Writing software is hard, but writing distributed software is even harder: it is possible that because of multiple message broker servers not synchronizing fast enough, or because a connection to a worker gets lost, the same job is given to two different workers. The best you can do to protect yourself is to make your jobs idempotent: meaning your job should *always produce the same output* regardless of how many times it is performed. 17 | 18 | ### Serialization 19 | 20 | In order to send your jobs to message brokers, Batch uses a technic known as serialization: it transforms your in-memory structures with unstable representations into a stable representations that can be used to create a structure that should be identical to the original. Because of this, there's some points you should keep in mind when using batch / declaring jobs: 21 | 22 | * **Try to send the minimum amount of information.** Serialization is a linear process, to serialize a structure you have to analyze all of its contents, so the fewer and smaller elements, the faster. For example, instead of sending your `User` struct to your job, send the user's ID and fetch it from the database in the job. 23 | * **Do not send sensible information.** There's no guarantee of privacy / secrecy on message brokers, so you really don't want to put API credentials or user passwords in your job payloads. Instead, you should try to use the [inject] feature of Batch for some of these cases. 24 | 25 | ## Queue 26 | 27 | A queue is the source of jobs for worker processes. It is represented as a never-ending stream of incoming deliveries stating which job should be executed and the environment they should be executed in. In order to consume from a queue, you have to explicitely declare it to your message broker. Instead of using external configuration files, Batch leverages Rust's powerful macro system to ensure your code complies with your expectations (e.g: you shouldn't be able to set a priority on your job if your message broker doesn't support it, with Batch this becomes a compile-time error). 28 | 29 | ## Worker 30 | 31 | A worker is the name given to the process that will subscribe to queues and execute the associated code. It is a long running process that should not crash. 32 | 33 | [inject]: jobs.html#injecting-external-values 34 | -------------------------------------------------------------------------------- /guide/src/jobs.md: -------------------------------------------------------------------------------- 1 | # Jobs 2 | 3 | ## Declaring a job 4 | 5 | The simplest way to declare a job is to create a function, and then annotate it with Batch's [`job`] procedural macro: 6 | 7 | ```rust 8 | extern crate batch; 9 | 10 | use batch::job; 11 | 12 | #[job(name = "batch-example.say-hello")] 13 | fn say_hello(name: String) { 14 | println!("Hello {}!", name); 15 | } 16 | ``` 17 | 18 | ## Return value of a job 19 | 20 | As of today, the [`job`] macro only supports two types of return values: 21 | 22 | * either the function return a unit value (the `()` type); 23 | * either the function return a value that implements the [`IntoFuture`] trait (amongst others, it is implemented for both `Future` and `Result`) 24 | 25 | The macro not being capable of determining whether the function complies with the above requirements means that if you made a mistake, the compiler will error and the message might not be the clearest, so keep that in mind if you encounter a compile error on one of your job. 26 | 27 | ## Injecting external values 28 | 29 | More often than not, your job will need values that can't or shouldn't be transfered in their message payload. For example, you might need a connection handle to your database, or a mail API client instance, or even the contents of a configuration file. To solve this problem, Batch allow you to mark arguments as *"injected"*. This is done by using the `inject` parameter of the `job` attribute: 30 | 31 | ```rust 32 | extern crate batch; 33 | 34 | use batch::job; 35 | # 36 | # struct UserRepository; 37 | # struct Mailer; 38 | 39 | #[job(name = "batch-example.send-hello", inject = [ repository, mailer ])] 40 | fn send_hello(user_id: i32, repository: UserRepository, mailer: Mailer) { 41 | # drop(user_id); 42 | # drop(repository); 43 | # drop(mailer); 44 | // ... 45 | } 46 | ``` 47 | 48 | In the example above, Batch will only put the `user_id` parameter in the underlying structure, and will fetch the values for the `repository` and the `mailer` values when performing the job. These values are registered on the executor of the job which more often than not will be Batch's own [`Worker`]. 49 | 50 | ## Configuring the job 51 | 52 | ### Changing the number of retries 53 | 54 | By default, a job will be tried 25 times before being declared failed and dropped into a dead-letter queue. This gives you plenty of time to fix your job's implementation. If you wish to change this number, you can do so by using the `retries` parameter of the job procedural macro: 55 | 56 | ```rust 57 | extern crate batch; 58 | 59 | use batch::job; 60 | 61 | #[job(name = "batch-example.send-hello", retries = 10)] 62 | fn send_hello(to: String) { 63 | println!("Hello {}", to); 64 | } 65 | 66 | #[job(name = "batch-example.send-goodbye", retries = 50)] 67 | fn send_goodbye(to: String) { 68 | println!("Goodbye {}", to); 69 | } 70 | ``` 71 | 72 | ### Changing the timeout for the job's execution 73 | 74 | By default, a job is given 30 minutes to complete. If you wish to change this number, you can do so by using the `timeout` parameter of the `job` procedural macro with the number of seconds the job should be allowed to run: 75 | 76 | ```rust 77 | extern crate batch; 78 | 79 | use batch::job; 80 | 81 | // This job will have 1 minute to complete. 82 | #[job(name = "batch-example.send-hello", timeout = "1minute")] 83 | fn send_hello(to: String) { 84 | println!("Hello {}", to); 85 | } 86 | 87 | // This job will have 3 hours and 30 minutes to complete. 88 | #[job(name = "batch-example.send-goodbye", timeout = "3hours 30mins")] 89 | fn send_goodbye(to: String) { 90 | println!("Goodbye {}", to); 91 | } 92 | ``` 93 | 94 | The timeout parser supports the given suffixes: 95 | 96 | * `nsec`, `ns` *-- microseconds* 97 | * `usec`, `us` *-- microseconds* 98 | * `msec`, `ms` *-- milliseconds* 99 | * `seconds`, `second`, `sec`, `s` 100 | * `minutes`, `minute`, `min`, `m` 101 | * `hours`, `hour`, `hr`, `h` 102 | * `days`, `day`, `d` 103 | * `weeks`, `week`, `w` 104 | * `months`, `month`, `M` *-- defined as 30.44 days* 105 | * `years`, `year`, `y` *-- defined as 365.25 days* 106 | 107 | 108 | ### Changing the job priority 109 | 110 | By default, a job is assigned the `Normal` priority. If you wish to change this, you can use the `priority` parameter of the `job` procedural macro with one of `trivial`, `low`, `normal`, `high`, `critical`: 111 | 112 | ```rust 113 | extern crate batch; 114 | 115 | use batch::job; 116 | 117 | // This job will be assigned the `low` priority. 118 | #[job(name = "batch-example.send-hello", priority = low)] 119 | fn send_hello(to: String) { 120 | println!("Hello {}", to); 121 | } 122 | 123 | // This job will be assigned the `critical` priority. 124 | #[job(name = "batch-example.send-goodbye", priority = critical)] 125 | fn send_goodbye(to: String) { 126 | println!("Goodbye {}", to); 127 | } 128 | ``` 129 | 130 | --- 131 | 132 | ## Under the hood 133 | 134 | Annotating a function with the [`job`] procedural macro will do two things: 135 | 136 | * Create a new structure deriving Serde's [`Serialize`] & [`Deserialize`] traits, that stores all of the *non-provided* (see below) function arguments. This implies that all of the arguments must also implement Serde's [`Serialize`] & [`Deserialize`] traits. More importantly, this new structure also implements Batch's [`Job`] trait. 137 | * Change the annotated function to return an instance of the newly defined structure (see previous bullet point), allowing for easy scheduling of the job. 138 | 139 | ## Get or set the underlying struct of a job 140 | 141 | When invoked, [`job`] procedural macro will generate a new structure declaration containing the arguments for the job, and implementing the [`Job`] trait. The name of this structure is the same as the function is comes from. This is made possible by the fact that in Rust, structures and functions don't share the same namespace: 142 | 143 | ```rust 144 | extern crate batch; 145 | 146 | use batch::job; 147 | 148 | #[job(name = "batch-example.say-hello")] 149 | fn say_hello(name: String) { 150 | // ... 151 | } 152 | 153 | // Would generate code roughly equivalent to: 154 | 155 | # mod generated_do_not_copy_paste_this_please { 156 | struct say_hello { 157 | name: String 158 | } 159 | # } 160 | ``` 161 | 162 | Hopefully, this simple naming scheme should not conflict with already existing code. If you ever happen to be in this situation, Batch allows you to set the name of the structure that will be generated, by using the `wrapper` parameter: 163 | 164 | ```rust 165 | extern crate batch; 166 | 167 | use batch::job; 168 | 169 | #[job(name = "batch-example.say-hello", wrapper = MySuperAwesomeJob)] 170 | fn say_hello(name: String) { 171 | // ... 172 | } 173 | 174 | // Would generate code roughly equivalent to: 175 | 176 | # mod generated_do_not_copy_paste_this_please { 177 | struct MySuperAwesomeJob { 178 | name: String 179 | } 180 | # } 181 | ``` 182 | 183 | 184 | [`job`]: https://docs.rs/batch/0.2/index.html 185 | [`IntoFuture`]: https://docs.rs/futures/0.1/futures/future/trait.IntoFuture.html 186 | [`Worker`]: ./worker/index.html 187 | [`Serialize`]: https://docs.serde.rs/serde/trait.Serialize.html 188 | [`Deserialize`]: https://docs.serde.rs/serde/trait.Deserialize.html 189 | [`Job`]: https://docs.rs/batch/0.2/index.html 190 | -------------------------------------------------------------------------------- /guide/src/rabbitmq/exchanges.md: -------------------------------------------------------------------------------- 1 | # Exchanges 2 | 3 | In RabbitMQ parlance you don't publish messages to a queue but to an exchange. Batch abstracts away this behavior behind a unified `Queue` trait. When you declare your queue, an exchange with the same name is implicitly declared. But sometimes you want to have control about what example declared and how. To do that, you can use the `exchange` property of the `queues!` macro: 4 | 5 | ```rust 6 | extern crate batch; 7 | extern crate batch_rabbitmq; 8 | extern crate tokio; 9 | 10 | use batch_rabbitmq::queues; 11 | use tokio::prelude::*; 12 | 13 | queues! { 14 | Example { 15 | name = "batch.example", 16 | exchange = "batch.example-exchange", 17 | } 18 | } 19 | 20 | fn main() { 21 | let fut = batch_rabbitmq::Connection::build("amqp://guest:guest@localhost:5672/%2f") 22 | .declare(Example) 23 | .connect() 24 | .and_then(|client| { 25 | # drop(client); 26 | /* The `batch.example-exchange` exchange is now declared. */ 27 | Ok(()) 28 | }) 29 | .map_err(|e| eprintln!("An error occured while declaring the queue: {}", e)); 30 | 31 | # if false { 32 | tokio::run(fut); 33 | # } 34 | } 35 | ``` 36 | -------------------------------------------------------------------------------- /guide/src/rabbitmq/getting-started.md: -------------------------------------------------------------------------------- 1 | # Getting started 2 | 3 | The first thing you'll want to do once you've installed `batch` is connect to a message broker. Batch provides a few adapters for popular choices amongst message brokers, but you can also write your own adapter if you want to. In this guide we'll use the RabbitMQ adapter (don't forget to enable the `rabbitmq` feature when installing batch). 4 | 5 | Let's begin by connection to a broker: 6 | 7 | ```rust 8 | extern crate batch; 9 | extern crate batch_rabbitmq; 10 | extern crate tokio; 11 | 12 | use tokio::prelude::*; 13 | 14 | fn main() { 15 | let f = batch_rabbitmq::Connection::open("amqp://guest:guest@localhost:5672/%2f") 16 | .map(|conn| { 17 | # drop(conn); 18 | println!("We're connected to RabbitMQ!"); 19 | }) 20 | .map_err(|e| eprintln!("An error occured while connecting to RabbitMQ: {}", e)); 21 | 22 | # if false { 23 | tokio::run(f); 24 | # } 25 | } 26 | ``` 27 | 28 | Now that we've acquired a connection to our RabbitMQ server, we'll write our first [job]. There are two ways of defining a job with batch: the high-level one consists of writing a function and annotate it with the `job` attribute, the low-level one consists of declaring a structure and implementing `batch::Job` manually. For now we'll use the high-level way: 29 | 30 | ```rust 31 | extern crate batch; 32 | extern crate batch_rabbitmq; 33 | extern crate tokio; 34 | 35 | use batch::job; 36 | use tokio::prelude::*; 37 | 38 | #[job(name = "batch-example.say-hello")] 39 | fn say_hello(name: String) { 40 | println!("Hello {}!", name); 41 | } 42 | 43 | fn main() { 44 | let f = batch_rabbitmq::Connection::open("amqp://guest:guest@localhost:5672/%2f") 45 | .map(|conn| { 46 | # drop(conn); 47 | println!("We're connected to RabbitMQ!"); 48 | }) 49 | .map_err(|e| eprintln!("An error occured while connecting to RabbitMQ: {}", e)); 50 | 51 | # if false { 52 | tokio::run(f); 53 | # } 54 | } 55 | ``` 56 | 57 | > **Note**: the `job` procedural macro will generate a structure that derives Serde's `Serialize` & `Deserialize`. That means that the arguments of your function must implement these traits. 58 | 59 | > **Note**: The string given to the `job` procedural macro as a parameter of the name of the job. You should strive for unique job names, ideally structured by domain (e.g: prefix all jobs related to media files compression by `"media-compress."`). 60 | 61 | Now that we have our job, we want to send it to our RabbitMQ server. To do that we need to declare a queue, using the `queues!` macro: 62 | 63 | ```rust 64 | extern crate batch; 65 | extern crate batch_rabbitmq; 66 | extern crate tokio; 67 | 68 | use batch::job; 69 | use batch_rabbitmq::queues; 70 | use tokio::prelude::*; 71 | 72 | queues! { 73 | Example { 74 | name = "batch-example.exchange", 75 | bindings = [ 76 | say_hello, 77 | ], 78 | } 79 | } 80 | 81 | #[job(name = "batch-example.say-hello")] 82 | fn say_hello(name: String) { 83 | println!("Hello {}!", name); 84 | } 85 | 86 | fn main() { 87 | let f = batch_rabbitmq::Connection::build("amqp://guest:guest@localhost:5672/%2f") 88 | .declare(Example) 89 | .connect() 90 | .and_then(|mut client| { 91 | let job = say_hello("Ferris".to_string()); 92 | Example(job).dispatch(&mut client) 93 | }) 94 | .map_err(|e| eprintln!("An error occured while connecting to RabbitMQ: {}", e)); 95 | 96 | # if false { 97 | tokio::run(f); 98 | # } 99 | } 100 | ``` 101 | 102 | > Note how we're declaring the exchange by giving its name as a parameter and not by using the infamous turbofish syntax. 103 | 104 | Now that our job has been published to our broker, we'll need to fetch it and assign a function to this job. To do this, we'll create a new program, a *[worker]*. 105 | 106 | [worker]: ../worker/index.html -------------------------------------------------------------------------------- /guide/src/rabbitmq/index.md: -------------------------------------------------------------------------------- 1 | # RabbitMQ 2 | 3 | [RabbitMQ] is a popular message broker that implements the AMQP/0.9.1 protocol often used in enterprise settings thanks to its replication & clustering capabilities. 4 | 5 | Batch provides an official adapter for RabbitMQ by enabling the `rabbitmq` feature in your `Cargo.toml`: 6 | 7 | ```toml 8 | [dependencies] 9 | batch = { version = "0.2", features = ["rabbitmq"] } 10 | ``` 11 | 12 | Batch only supports versions of RabbitMQ that are officially supported by Pivotal, which means RabbitMQ 3.7+. If you encounter an problem using batch with an older version of RabbitMQ we won't be able to fix it. You are free to submit a bug fix but we reserve ourselves the right to refuse it if we think it will induce too much work to maintain it. 13 | 14 | [RabbitMQ]: https://www.rabbitmq.com 15 | -------------------------------------------------------------------------------- /guide/src/rabbitmq/queues.md: -------------------------------------------------------------------------------- 1 | # Queues 2 | -------------------------------------------------------------------------------- /guide/src/worker/index.md: -------------------------------------------------------------------------------- 1 | # Worker 2 | 3 | As explained in the *[Concepts]* chapter, a worker consumes & executes jobs delivered by a message broker. Batch comes with a worker implementation with semantics heavily inspired by the [Resque] project. Like Resque, it assumes chaos: eventually your jobs will crash, or get stuck computing a value, or will be unable to contact an external service, in any way the `Worker` process shouldn't be affected by the execution of the jobs it is responsible for and be as resilient as possible against failure. 4 | 5 | Maintaining such guarantees means that this `Worker` implementation isn't the most performant one, it is however one of the safest if you're not sure that your jobs are infallible. For example, because this implementation supports job timeouts it has to execute the job in a new process which is considered an expensive operation compared to spawning a thread. Due to this behavior (spawning a new process for each job execution), we will refer to this implementation as a *"Forking Worker"*. 6 | 7 | ## Adding a worker to your project 8 | 9 | The easiest way to integrate the forking worker is to create a new binary (e.g: `src/bin/worker.rs`). This makes sure that your main command-line interface will not conflict with the worker, and vice-versa. The `Worker` struct is built using a `Client` instance, this makes it possible to use the same `Worker` implementation with any message broker adapter. In this example, we will be using the RabbitMQ adapter: 10 | 11 | ```rust 12 | extern crate batch; 13 | extern crate batch_rabbitmq; 14 | extern crate tokio; 15 | 16 | use batch::job; 17 | use batch_rabbitmq::queues; 18 | use batch::Worker; 19 | use tokio::prelude::*; 20 | 21 | queues! { 22 | Example { 23 | name = "example", 24 | bindings = [ 25 | say_hello 26 | ] 27 | } 28 | } 29 | 30 | #[job(name = "batch-example.say-hello")] 31 | fn say_hello(name: String) { 32 | println!("Hello {}!", name); 33 | } 34 | 35 | fn main() { 36 | // First, we configure the connection to our message broker 37 | let f = batch_rabbitmq::Connection::build("amqp://guest:guest@localhost:5672/%2f") 38 | // We declare our queue & exchange against RabbitMQ 39 | .declare(Example) 40 | // We establish the connection 41 | .connect() 42 | // Then, we create our worker instance & register the queue we will consume from 43 | .map(|client| Worker::new(client).queue(Example)) 44 | // And finally, we consume incoming jobs 45 | .and_then(|worker| worker.work()) 46 | .map_err(|e| eprintln!("An error occured: {}", e)); 47 | 48 | # if false { 49 | tokio::run(f); 50 | # } 51 | } 52 | ``` 53 | 54 | ## Worker-provided values 55 | 56 | Some of your jobs will undoubtly have to depend on values that can't be serialized (e.g: a connection to a database or credentials for your third party services). On one hand, you can't really easily serialize them, on the other hand you don't want to re-instantiate every time you need them. Batch gives you a solution to this problem: you provide a callback returning an instance of a resource to your worker, and your worker will use them to fill out values marked as *"injected"* on your jobs. 57 | 58 | ```rust 59 | extern crate batch; 60 | extern crate batch_rabbitmq; 61 | extern crate tokio; 62 | 63 | use batch::job; 64 | use batch_rabbitmq::queues; 65 | use tokio::prelude::*; 66 | # 67 | # mod diesel { 68 | # pub struct PgConn; 69 | # } 70 | 71 | queues! { 72 | Maintenance { 73 | name = "maintenance", 74 | bindings = [ 75 | count_active_users 76 | ] 77 | } 78 | } 79 | 80 | #[job(name = "batch-example.count-active-users", inject = [ db ])] 81 | fn count_active_users(db: diesel::PgConn) { 82 | # drop(db); 83 | // ... 84 | } 85 | 86 | fn init_database_conn() -> diesel::PgConn { 87 | // ... 88 | # diesel::PgConn 89 | } 90 | 91 | fn main() { 92 | let f = batch_rabbitmq::Connection::build("amqp://guest:guest@localhost:5672/%2f") 93 | .declare(Maintenance) 94 | .connect() 95 | .map(|conn| 96 | batch::Worker::new(conn) 97 | .provide(init_database_conn) 98 | .queue(Maintenance) 99 | ) 100 | .and_then(|worker| worker.work()) 101 | .map_err(|e| eprintln!("An error occured while executing the worker: {}", e)); 102 | 103 | # if false { 104 | tokio::run(f); 105 | # } 106 | } 107 | ``` 108 | 109 | [Concepts]: ../concepts.html 110 | [Resque]: https://github.com/resque/resque 111 | -------------------------------------------------------------------------------- /src/client.rs: -------------------------------------------------------------------------------- 1 | use failure::Error; 2 | use futures::{Future, Stream}; 3 | 4 | use crate::{Delivery, Dispatch}; 5 | 6 | /// A message broker client. 7 | /// 8 | /// A `Clone` implementation is required by the `Client` trait and, due to the 9 | /// current implementation of async I/O in Rust, should be as cheap as possible 10 | /// (first-party implementations commonly use an `Arc` to fulfill this 11 | /// requirement). As soon as async/await will be available in the language, this 12 | /// performance constraint could be relaxed. 13 | pub trait Client: Clone { 14 | /// The type of the future returned by `send`. 15 | type SendFuture: Future + Send; 16 | 17 | /// Send a dispatch to the message broker. 18 | fn send(&mut self, dispatch: Dispatch) -> Self::SendFuture; 19 | 20 | /// The type of `Consumer` returned by `to_consumer`. 21 | type Consumer: Consumer; 22 | 23 | /// The return type of the `to_consumer` method. 24 | type ToConsumerFuture: Future + Send; 25 | 26 | /// Create a consumer of deliveries coming from the given sources. 27 | fn to_consumer( 28 | &mut self, 29 | sources: impl IntoIterator>, 30 | ) -> Self::ToConsumerFuture; 31 | } 32 | 33 | /// A consumer of deliveries coming from a message broker. 34 | pub trait Consumer: Stream::Delivery, Error = Error> + Send { 35 | /// The type of message yielded by the consumer. 36 | type Delivery: Delivery; 37 | } 38 | -------------------------------------------------------------------------------- /src/delivery.rs: -------------------------------------------------------------------------------- 1 | use failure::Error; 2 | use futures::Future; 3 | 4 | use crate::job::Properties; 5 | 6 | /// A message that can be received from a broker. 7 | pub trait Delivery: Send { 8 | /// The return type of the `ack` method. 9 | type AckFuture: Future + Send; 10 | 11 | /// The return type of the `reject` method. 12 | type RejectFuture: Future + Send; 13 | 14 | /// The serialized `Job` instance associated to this delivery. 15 | fn payload(&self) -> &[u8]; 16 | 17 | /// The `Properties` instance associated to this delivery. 18 | fn properties(&self) -> &Properties; 19 | 20 | /// Ack the delivery. 21 | /// 22 | /// Acking a delivery marks its associated job as completed. 23 | fn ack(self) -> Self::AckFuture; 24 | 25 | /// Reject the delivery. 26 | /// 27 | /// Rejecting a delivery means its associated job hasn't completed successfully and should be retried (if possible). 28 | /// A job cannot be retried if it has reached its retries limit. 29 | fn reject(self) -> Self::RejectFuture; 30 | } 31 | -------------------------------------------------------------------------------- /src/dispatch.rs: -------------------------------------------------------------------------------- 1 | use failure::Error; 2 | use serde_json::to_vec; 3 | 4 | use crate::{Job, Properties}; 5 | 6 | /// A message that will be sent to a broker. 7 | /// 8 | /// A dispatch stores a serialized job, its properties and the key used to publish 9 | /// it (e.g: the name of the queue it willbe published to). 10 | /// 11 | /// Instances of dispatch are internally created when you dispatch a `Query`, so you only need 12 | /// to know about them if you're writing an adapter for Batch. 13 | #[derive(Debug)] 14 | pub struct Dispatch { 15 | destination: String, 16 | payload: Vec, 17 | properties: Properties, 18 | } 19 | 20 | impl Dispatch { 21 | pub(crate) fn new( 22 | destination: String, 23 | job: impl Job, 24 | properties: Properties, 25 | ) -> Result { 26 | Ok(Dispatch { 27 | payload: to_vec(&job).map_err(|e| Error::from(e))?, 28 | destination, 29 | properties, 30 | }) 31 | } 32 | 33 | /// An indicator on where should this message be dispatched, typically the queue's name. 34 | /// 35 | /// # Example 36 | /// 37 | /// ``` 38 | /// use batch::Dispatch; 39 | /// 40 | /// fn example(dispatch: Dispatch) { 41 | /// println!("dispatch destination: {:?}", dispatch.destination()); 42 | /// } 43 | /// ``` 44 | pub fn destination(&self) -> &str { 45 | &self.destination 46 | } 47 | 48 | /// Get a reference to the serialized `Job` instance associated to this delivery. 49 | /// 50 | /// # Example 51 | /// 52 | /// ``` 53 | /// use batch::Dispatch; 54 | /// 55 | /// fn example(dispatch: Dispatch) { 56 | /// println!("dispatch payload: {:?}", dispatch.payload()); 57 | /// } 58 | /// ``` 59 | pub fn payload(&self) -> &[u8] { 60 | &self.payload 61 | } 62 | 63 | /// Get a reference to the `Properties` instance associated to this delivery. 64 | /// 65 | /// # Example 66 | /// 67 | /// ``` 68 | /// use batch::Dispatch; 69 | /// 70 | /// fn example(dispatch: Dispatch) { 71 | /// println!("dispatch properties: {:?}", dispatch.properties()); 72 | /// } 73 | /// ``` 74 | pub fn properties(&self) -> &Properties { 75 | &self.properties 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/export.rs: -------------------------------------------------------------------------------- 1 | pub use failure::Error; 2 | pub use futures::future::ok; 3 | pub use futures::Future; 4 | pub use futures::IntoFuture; 5 | pub use serde::{Deserialize, Deserializer, Serialize, Serializer}; 6 | pub use std::boxed::Box; 7 | pub use std::marker::Send; 8 | pub use std::result::Result; 9 | pub use std::time::Duration; 10 | 11 | #[allow(non_camel_case_types)] 12 | pub type str = help::Str; 13 | 14 | mod help { 15 | pub type Str = str; 16 | } 17 | -------------------------------------------------------------------------------- /src/factory.rs: -------------------------------------------------------------------------------- 1 | use std::any::{Any, TypeId}; 2 | use std::collections::HashMap; 3 | use std::fmt; 4 | 5 | /// A type-aware factory. 6 | /// 7 | /// It is used to provide job author with something that resemble Dependency Injection. 8 | pub struct Factory { 9 | inner: HashMap>, 10 | } 11 | 12 | impl fmt::Debug for Factory { 13 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 14 | f.debug_struct("Factory").finish() 15 | } 16 | } 17 | 18 | struct Constructor(Box T + Send + Sync + 'static>); 19 | 20 | impl Constructor { 21 | fn instantiate(&self) -> T { 22 | (self.0)() 23 | } 24 | } 25 | 26 | impl Factory { 27 | /// Create a new `Factory` instance. 28 | /// 29 | /// # Examples 30 | /// 31 | /// ```rust 32 | /// use batch::Factory; 33 | /// 34 | /// let factory = Factory::new(); 35 | /// ``` 36 | pub fn new() -> Self { 37 | Factory { 38 | inner: HashMap::new(), 39 | } 40 | } 41 | 42 | /// Provide a constructor for a given type to the factory. 43 | /// 44 | /// # Examples 45 | /// 46 | /// ```rust 47 | /// use batch::Factory; 48 | /// # struct PgConn; 49 | /// 50 | /// fn init_pg_conn() -> PgConn { 51 | /// // ... 52 | /// # PgConn 53 | /// } 54 | /// 55 | /// let mut factory = Factory::new(); 56 | /// factory.provide(init_pg_conn); 57 | /// ``` 58 | pub fn provide(&mut self, ctor: impl Fn() -> T + Send + Sync + 'static) { 59 | let ctor = Constructor(Box::new(ctor)); 60 | self.inner.insert(TypeId::of::(), Box::new(ctor)); 61 | } 62 | 63 | /// Instantiate a value of type `T` if a constructor was provided. 64 | /// # Examples 65 | /// 66 | /// ```rust 67 | /// use batch::Factory; 68 | /// # struct PgConn; 69 | /// 70 | /// let factory = Factory::new(); 71 | /// // ... 72 | /// # if false { 73 | /// let conn: PgConn = factory.instantiate().unwrap(); 74 | /// # } 75 | /// ``` 76 | pub fn instantiate(&self) -> Option { 77 | self.inner 78 | .get(&TypeId::of::()) 79 | .and_then(|raw| raw.downcast_ref::>()) 80 | .map(|ctor| ctor.instantiate()) 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/job.rs: -------------------------------------------------------------------------------- 1 | //! A trait representing a job. 2 | 3 | use std::fmt; 4 | use std::time::Duration; 5 | 6 | use failure::Error; 7 | use futures::Future; 8 | use serde::{Deserialize, Serialize}; 9 | use uuid::Uuid; 10 | 11 | use crate::Factory; 12 | 13 | /// A job and its related metadata (name, queue, timeout, etc.) 14 | /// 15 | /// In most cases, you should be using the `job` proc-macro instead of implementing it manually yourself. 16 | /// 17 | /// # Examples 18 | /// 19 | /// ```rust 20 | /// # extern crate batch; 21 | /// use batch::job; 22 | /// 23 | /// #[job(name = "batch-example.send-confirmation-email")] 24 | /// fn send_confirmation_email(email: String) { 25 | /// # drop(email); 26 | /// // ... 27 | /// } 28 | /// # 29 | /// # fn main() {} 30 | /// ``` 31 | pub trait Job: Serialize + for<'de> Deserialize<'de> { 32 | /// A should-be-unique human-readable ID for this job. 33 | const NAME: &'static str; 34 | 35 | /// The return type of the `perform` method. 36 | type PerformFuture: Future + Send + 'static; 37 | 38 | /// Perform the background job. 39 | fn perform(self, context: &Factory) -> Self::PerformFuture; 40 | 41 | /// The number of times this job must be retried in case of error. 42 | /// 43 | /// This function is meant to be overriden by the user to return a value different from the associated 44 | /// constant depending on the contents of the actual job. 45 | /// 46 | /// By default, a job will be retried 25 times. 47 | fn retries(&self) -> u32 { 48 | 25 49 | } 50 | 51 | /// An optional duration representing the time allowed for this job's handler to complete. 52 | /// 53 | /// This function is meant to be overriden by the user to return a value different from the associated 54 | /// constant depending on the contents of the actual job. 55 | /// 56 | /// By default, a job is allowed to run 30 minutes. 57 | fn timeout(&self) -> Duration { 58 | Duration::from_secs(30 * 60) 59 | } 60 | } 61 | 62 | /// Various metadata for a job. 63 | #[derive(Clone, Serialize, Deserialize)] 64 | pub struct Properties { 65 | /// The language in which the job was created. 66 | pub lang: String, 67 | /// The name of the job. 68 | pub task: String, 69 | /// The ID of this job. 70 | /// 71 | /// To guarantee the uniqueness of this ID, a UUID version 4 used. 72 | pub id: Uuid, 73 | /// The ID of the greatest ancestor of this job, if there is one. 74 | pub root_id: Option, 75 | /// The ID of the direct ancestor of this job, if there is one. 76 | pub parent_id: Option, 77 | /// The ID of the group this job is part of, if there is one. 78 | pub group: Option, 79 | /// Timelimits for this job. 80 | /// 81 | /// The first duration represents the soft timelimit while the second duration represents the hard timelimit. 82 | pub timelimit: (Option, Option), 83 | /// The content type of the job once serialized. 84 | pub content_type: String, 85 | /// The content encoding of the job once serialized. 86 | pub content_encoding: String, 87 | __non_exhaustive: (), 88 | } 89 | 90 | impl Properties { 91 | /// Create a new `Properties` instance from a task name. 92 | pub fn new(task: T) -> Self { 93 | Properties { 94 | lang: "rs".to_string(), 95 | task: task.to_string(), 96 | id: Uuid::new_v4(), 97 | root_id: None, 98 | parent_id: None, 99 | group: None, 100 | timelimit: (None, None), 101 | content_type: "application/json".to_string(), 102 | content_encoding: "utf-8".to_string(), 103 | __non_exhaustive: (), 104 | } 105 | } 106 | } 107 | 108 | impl fmt::Debug for Properties { 109 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 110 | f.debug_struct("Properties") 111 | .field("content_encoding", &self.content_encoding) 112 | .field("content_type", &self.content_type) 113 | .field("lang", &self.lang) 114 | .field("task", &self.task) 115 | .field("id", &self.id) 116 | .field("timelimit", &self.timelimit) 117 | .field("root_id", &self.root_id) 118 | .field("parent_id", &self.parent_id) 119 | .field("group", &self.group) 120 | .finish() 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Batch is a background job library. 2 | //! 3 | //! Batch allow a program (the *"Client"*) to defer a unit of work (the *"Job"*), until a background process (the 4 | //! *"Worker"*) picks it up and executes it. This is very common in web development where you don't want to slow down 5 | //! an HTTP request for a behaviour that doesn't has to be done synchronously (e.g: sending a mail when a user signs 6 | //! up). Batch is compatible and should run correctly on Windows, macOS and Linux. 7 | //! 8 | //! Batch can work with any message broker as long as a `Client` can be implemented for it. The Batch project is 9 | //! responsible for the development & maintenance of the following adapters: 10 | //! 11 | //! * [RabbitMQ](https://docs.rs/batch-rabbitmq/0.2) 12 | //! * [Stub](https://docs.rs/batch-stub/0.2) 13 | //! 14 | //! Batch provides a worker implementation with sensible defaults that supports parallelism and job timeouts out of 15 | //! the box, on all supported platforms. 16 | //! 17 | //! # Example 18 | //! 19 | //! ```rust 20 | //! extern crate batch; 21 | //! extern crate batch_rabbitmq; 22 | //! extern crate tokio; 23 | //! 24 | //! use batch::{job, Query}; 25 | //! use batch_rabbitmq::queues; 26 | //! use tokio::prelude::*; 27 | //! 28 | //! queues! { 29 | //! Notifications { 30 | //! name = "notifications", 31 | //! bindings = [ 32 | //! self::say_hello, 33 | //! ] 34 | //! } 35 | //! } 36 | //! 37 | //! #[job(name = "batch-example.say-hello")] 38 | //! fn say_hello(name: String) { 39 | //! println!("Hello {}!", name); 40 | //! } 41 | //! 42 | //! fn main() { 43 | //! let fut = batch_rabbitmq::Connection::build("amqp://guest:guest@localhost/%2f") 44 | //! .declare(Notifications) 45 | //! .connect() 46 | //! .and_then(|mut client| { 47 | //! let job = say_hello(String::from("Ferris")); 48 | //! Notifications(job).dispatch(&mut client) 49 | //! }); 50 | //! 51 | //! # if false { 52 | //! tokio::run( 53 | //! fut.map_err(|e| eprintln!("Couldn't publish message: {}", e)) 54 | //! ); 55 | //! # } 56 | //! } 57 | //! ``` 58 | 59 | #![doc(html_root_url = "https://docs.rs/batch/0.2.0")] 60 | #![deny(missing_debug_implementations)] 61 | #![deny(missing_docs)] 62 | 63 | mod client; 64 | mod delivery; 65 | mod dispatch; 66 | /// Not public API. This module is exempt from any semver guarantees. 67 | #[doc(hidden)] 68 | pub mod export; 69 | mod factory; 70 | mod job; 71 | mod query; 72 | mod queue; 73 | mod worker; 74 | 75 | pub use crate::client::{Client, Consumer}; 76 | pub use crate::delivery::Delivery; 77 | pub use crate::dispatch::Dispatch; 78 | pub use crate::factory::Factory; 79 | pub use crate::job::{Job, Properties}; 80 | pub use crate::query::{DispatchFuture, Query}; 81 | pub use crate::queue::Queue; 82 | pub use crate::worker::{Work, Worker}; 83 | #[cfg(feature = "codegen")] 84 | pub use batch_codegen::job; 85 | -------------------------------------------------------------------------------- /src/query.rs: -------------------------------------------------------------------------------- 1 | use failure::Error; 2 | use futures::{Async, Future, Poll}; 3 | use log::debug; 4 | use std::marker::PhantomData; 5 | 6 | use crate::dispatch::Dispatch; 7 | 8 | use crate::{Client, Job, Properties, Queue}; 9 | 10 | /// A fluent interface to configure jobs before dispatching them. 11 | /// 12 | /// A `Query` is generic on both the job that will be published and the queue it will be published 13 | /// to. This makes it possible to annotate the queue with marker traits that communicates about 14 | /// the features it supports on a per job basis (e.g: per job priorities, per job time-to-live). 15 | #[derive(Debug)] 16 | pub struct Query { 17 | job: J, 18 | properties: Properties, 19 | _marker: PhantomData, 20 | } 21 | 22 | impl Query 23 | where 24 | J: Job, 25 | Q: Queue, 26 | { 27 | /// Create a new `Query` instance from a `Job`. 28 | /// 29 | /// This function is typically called from a wrapper generated by your adapter, but remains 30 | /// accessible if you ever need to write generic code. 31 | /// 32 | /// # Example 33 | /// 34 | /// ``` 35 | /// # extern crate batch; 36 | /// # extern crate failure; 37 | /// # extern crate futures; 38 | /// # 39 | /// # use batch::{Factory, Queue}; 40 | /// # use failure::Error; 41 | /// # use futures::Future; 42 | /// # 43 | /// # struct ExampleQueue; 44 | /// # 45 | /// # impl Queue for ExampleQueue { 46 | /// # const SOURCE: &'static str = "example-queue"; 47 | /// # 48 | /// # const DESTINATION: &'static str = "example-queue"; 49 | /// # 50 | /// # type CallbacksIterator = Box Box + Send>, 54 | /// # ), 55 | /// # >>; 56 | /// # 57 | /// # fn callbacks() -> Self::CallbacksIterator { 58 | /// # unimplemented!() 59 | /// # } 60 | /// # } 61 | /// use batch::{job, Query}; 62 | /// 63 | /// #[job(name = "batch-example.say-hello")] 64 | /// fn say_hello(name: String) { 65 | /// println!("Hello {}", name); 66 | /// } 67 | /// 68 | /// let query = Query::<_, ExampleQueue>::new(say_hello("Ferris".into())); 69 | /// ``` 70 | pub fn new(job: J) -> Self { 71 | Query { 72 | job, 73 | properties: Properties::new(J::NAME), 74 | _marker: PhantomData, 75 | } 76 | } 77 | 78 | /// Dispatch the job using the given `Client`. 79 | /// 80 | /// # Example 81 | /// 82 | /// ``` 83 | /// # extern crate batch; 84 | /// # extern crate batch_stub; 85 | /// # extern crate failure; 86 | /// # extern crate futures; 87 | /// # extern crate tokio; 88 | /// # 89 | /// # use batch::{Factory, Queue}; 90 | /// # use failure::Error; 91 | /// # use futures::Future; 92 | /// # 93 | /// # struct ExampleQueue; 94 | /// # 95 | /// # impl Queue for ExampleQueue { 96 | /// # const SOURCE: &'static str = "example-queue"; 97 | /// # 98 | /// # const DESTINATION: &'static str = "example-queue"; 99 | /// # 100 | /// # type CallbacksIterator = Box Box + Send>, 104 | /// # ), 105 | /// # >>; 106 | /// # 107 | /// # fn callbacks() -> Self::CallbacksIterator { 108 | /// # unimplemented!() 109 | /// # } 110 | /// # } 111 | /// # 112 | /// # fn make_client() -> impl batch::Client { 113 | /// # ::batch_stub::Client::new() 114 | /// # } 115 | /// use batch::{job, Query}; 116 | /// 117 | /// #[job(name = "batch-example.say-hello")] 118 | /// fn say_hello(name: String) { 119 | /// println!("Hello {}", name); 120 | /// } 121 | /// 122 | /// let mut client = make_client(); 123 | /// let f = Query::<_, ExampleQueue>::new(say_hello("Ferris".into())) 124 | /// .dispatch(&mut client) 125 | /// .map_err(|e| eprintln!("An error occured: {}", e)); 126 | /// 127 | /// # if false { 128 | /// // We're probably already in a tokio context so we use `spawn` instead of `run`. 129 | /// tokio::spawn(f); 130 | /// # } 131 | /// ``` 132 | pub fn dispatch(self, client: &mut C) -> DispatchFuture 133 | where 134 | C: Client, 135 | { 136 | debug!("dispatch; job={} queue={}", J::NAME, Q::DESTINATION); 137 | let client = client.clone(); 138 | DispatchFuture { 139 | client, 140 | state: DispatchState::Raw(Q::DESTINATION, Some(self.job), Some(self.properties)), 141 | } 142 | } 143 | } 144 | 145 | /// The future returned when a message is dispatched to a message broker. 146 | #[derive(Debug)] 147 | #[must_use = "futures do nothing unless polled"] 148 | pub struct DispatchFuture 149 | where 150 | C: Client, 151 | { 152 | client: C, 153 | state: DispatchState, 154 | } 155 | 156 | #[derive(Debug)] 157 | enum DispatchState { 158 | Raw(&'static str, Option, Option), 159 | Polling(F), 160 | } 161 | 162 | impl Future for DispatchFuture 163 | where 164 | C: Client, 165 | J: Job, 166 | { 167 | type Item = (); 168 | 169 | type Error = Error; 170 | 171 | fn poll(&mut self) -> Poll { 172 | match self.state { 173 | DispatchState::Raw(destination, ref mut job, ref mut props) => { 174 | let dispatch = Dispatch::new( 175 | destination.into(), 176 | job.take().unwrap(), 177 | props.take().unwrap(), 178 | )?; 179 | self.state = DispatchState::Polling(self.client.send(dispatch)); 180 | self.poll() 181 | } 182 | DispatchState::Polling(ref mut f) => { 183 | let _ = futures::try_ready!(f.poll()); 184 | Ok(Async::Ready(())) 185 | } 186 | } 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /src/queue.rs: -------------------------------------------------------------------------------- 1 | //! Utilities for declaring resources 2 | 3 | use failure::Error; 4 | use futures::Future; 5 | 6 | use crate::Factory; 7 | 8 | /// A resource that has to be declared to be used. 9 | /// 10 | /// This trait is meant to be implemented by adapters to message brokers. 11 | pub trait Queue: Sized { 12 | /// The key used when publishing a job to this queue. 13 | const SOURCE: &'static str; 14 | 15 | /// The key used when consuming jobs from this queue. 16 | const DESTINATION: &'static str; 17 | 18 | /// The return type of the `callbacks` method. 19 | type CallbacksIterator: Iterator< 20 | Item = ( 21 | &'static str, 22 | fn(&[u8], &Factory) -> Box + Send>, 23 | ), 24 | >; 25 | 26 | /// Get the callbacks associated to this queue. 27 | /// 28 | /// A callback is represented by a `(&str, Fn(&[u8], Factory) -> Future)` tuple. The first element is 29 | /// the key associated to the callback, typically this is the name of the job. The second element is the proper 30 | /// callback function. A callback function takes two parameters: 31 | /// * `payload`: A slice of bytes, it is the serialized representation of the to be handled job. 32 | /// * `container`: A type-map containing the types provided by the executor (usually some kind `Worker`). 33 | fn callbacks() -> Self::CallbacksIterator; 34 | } 35 | -------------------------------------------------------------------------------- /src/worker.rs: -------------------------------------------------------------------------------- 1 | //! Batch Worker. 2 | 3 | use failure::{self, Error}; 4 | use futures::{self, future, Future, Poll, Stream}; 5 | use log::{debug, error, warn}; 6 | use std::collections::{HashMap, HashSet}; 7 | use std::env; 8 | use std::fmt; 9 | use std::io::{self, Read}; 10 | use std::process; 11 | use std::result::Result; 12 | use std::sync::mpsc; 13 | use tokio_executor; 14 | use wait_timeout::ChildExt; 15 | 16 | use crate::{Client, Delivery, Factory, Query, Queue}; 17 | 18 | mod sealed { 19 | use crate::{Factory, Job}; 20 | use failure::Error; 21 | use futures::future; 22 | use serde::{Deserialize, Serialize}; 23 | 24 | /// Stub job used to trick the type system in `Connection::declare`. 25 | #[derive(Debug, Deserialize, Serialize)] 26 | pub struct StubJob; 27 | 28 | impl Job for StubJob { 29 | const NAME: &'static str = ""; 30 | 31 | type PerformFuture = future::FutureResult<(), Error>; 32 | 33 | fn perform(self, _ctx: &Factory) -> Self::PerformFuture { 34 | future::ok(()) 35 | } 36 | } 37 | } 38 | 39 | use self::sealed::StubJob; 40 | 41 | /// A worker executes jobs fetched by consuming from a client. 42 | /// 43 | /// The worker is responsible for polling the broker for jobs, deserializing them and execute 44 | /// them. It should never ever crash and sould be resilient to panic-friendly job handlers. Its 45 | /// `Broker` implementation is completely customizable by the user. 46 | /// 47 | /// The most important thing to know about the worker is that it favours safety over performance. 48 | /// For each incoming job, it will spawn a new process whose only goal is to perform the job. 49 | /// Even if this is slower than just executing the function in a threadpool, it allows much more 50 | /// control: timeouts wouldn't even be possible if we were running the jobs in-process. It also 51 | /// protects against unpredictable crashes. 52 | pub struct Worker { 53 | client: C, 54 | queues: HashSet, 55 | factory: Factory, 56 | callbacks: HashMap< 57 | String, 58 | fn(&[u8], &crate::Factory) -> Box + Send>, 59 | >, 60 | } 61 | 62 | impl fmt::Debug for Worker 63 | where 64 | C: fmt::Debug, 65 | { 66 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 67 | f.debug_struct("Worker") 68 | .field("client", &self.client) 69 | .field("queues", &self.queues) 70 | .field("callbacks", &self.callbacks.keys()) 71 | .finish() 72 | } 73 | } 74 | 75 | impl Worker 76 | where 77 | C: Client + Send + 'static, 78 | { 79 | /// Create a new `Worker` from a `Client` implementation. 80 | /// 81 | /// # Example 82 | /// 83 | /// ``` 84 | /// # extern crate batch; 85 | /// # extern crate batch_stub; 86 | /// # 87 | /// # use batch::Client; 88 | /// # 89 | /// # fn make_client() -> impl Client { 90 | /// # ::batch_stub::Client::new() 91 | /// # } 92 | /// use batch::Worker; 93 | /// 94 | /// let client = make_client(); 95 | /// let worker = Worker::new(client); 96 | /// ``` 97 | pub fn new(client: C) -> Self { 98 | Worker { 99 | client, 100 | factory: Factory::new(), 101 | queues: HashSet::new(), 102 | callbacks: HashMap::new(), 103 | } 104 | } 105 | 106 | /// Provide a constructor for a given type. 107 | /// 108 | /// See [`Factory::provide`]. 109 | pub fn provide(mut self, init: F) -> Self 110 | where 111 | T: 'static, 112 | F: Fn() -> T + Send + Sync + 'static, 113 | { 114 | self.factory.provide(init); 115 | self 116 | } 117 | 118 | /// Instruct the worker to consume jobs from the given queue. 119 | /// 120 | /// Note how the function takes a function returning a `Query` as parameter: you're not 121 | /// supposed to write this function yourself, it should be provided by your Batch adapter. 122 | /// 123 | /// # Panics 124 | /// 125 | /// If the given provides a callback for a job already registered, and the callbacks don't 126 | /// point to the same function, this method will panic. 127 | pub fn queue(mut self, _ctor: impl Fn(StubJob) -> Query) -> Self 128 | where 129 | Q: Queue, 130 | { 131 | self.queues.insert(Q::SOURCE.into()); 132 | for (job, callback) in Q::callbacks() { 133 | if let Some(previous) = self.callbacks.insert(job.into(), callback) { 134 | if previous as fn(_, _) -> _ != callback as fn(_, _) -> _ { 135 | panic!( 136 | "Two different callbacks were registered for the `{}` job.", 137 | job 138 | ); 139 | } 140 | } 141 | } 142 | self 143 | } 144 | 145 | /// Consume deliveries from all of the declared resources. 146 | pub fn work(self) -> Work { 147 | if let Ok(job) = env::var("BATCHRS_WORKER_IS_EXECUTOR") { 148 | let (tx, rx) = mpsc::channel::>(); 149 | let tx2 = tx.clone(); 150 | let f = self 151 | .execute(job) 152 | .map(move |_| tx.send(Ok(())).unwrap()) 153 | .map_err(move |e| tx2.send(Err(e)).unwrap()); 154 | tokio_executor::spawn(f); 155 | rx.recv().unwrap().unwrap(); 156 | process::exit(0); 157 | } 158 | Work(Box::new(self.supervise())) 159 | } 160 | 161 | fn supervise(mut self) -> impl Future + Send { 162 | self.client 163 | .to_consumer(self.queues.clone().into_iter()) 164 | .and_then(move |consumer| { 165 | consumer.for_each(move |delivery| { 166 | debug!("delivery; job_id={}", delivery.properties().id); 167 | // TODO: use tokio_threadpool::blocking instead of spawn a task for each execution? 168 | let task = futures::lazy( 169 | move || -> Box + Send> { 170 | match spawn(&delivery) { 171 | Err(e) => { 172 | error!("spawn: {}; job_id={}", e, delivery.properties().id); 173 | Box::new(delivery.reject()) 174 | } 175 | Ok(ExecutionStatus::Failed(f)) => { 176 | warn!( 177 | "execution; status={:?} job_id={}", 178 | ExecutionStatus::Failed(f), 179 | delivery.properties().id 180 | ); 181 | Box::new(delivery.reject()) 182 | } 183 | Ok(ExecutionStatus::Success) => { 184 | debug!( 185 | "execution; status={:?} job_id={}", 186 | ExecutionStatus::Success, 187 | delivery.properties().id 188 | ); 189 | Box::new(delivery.ack()) 190 | } 191 | } 192 | }, 193 | ).map_err(|e| { 194 | error!("An error occured while informing the broker of the execution status: {}", e) 195 | }); 196 | tokio_executor::spawn(task); 197 | Ok(()) 198 | }) 199 | }) 200 | .map(|_| ()) 201 | } 202 | 203 | fn execute(self, job: String) -> impl Future + Send { 204 | let mut input = vec![]; 205 | match io::stdin().read_to_end(&mut input).map_err(Error::from) { 206 | Ok(_) => (), 207 | Err(e) => { 208 | return Box::new(future::err(e)) as Box + Send> 209 | } 210 | }; 211 | let handler = match self.callbacks.get(&job) { 212 | Some(handler) => handler, 213 | None => { 214 | return Box::new(future::err(failure::err_msg(format!( 215 | "No handler registered for {}", 216 | job 217 | )))) as Box + Send> 218 | } 219 | }; 220 | Box::new((*handler)(&input, &self.factory)) as Box + Send> 221 | } 222 | } 223 | 224 | /// The future returned when calling `Worker::work`. 225 | #[must_use = "futures do nothing unless polled"] 226 | pub struct Work(Box + Send>); 227 | 228 | impl fmt::Debug for Work { 229 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 230 | f.debug_struct("Work").finish() 231 | } 232 | } 233 | 234 | impl Future for Work { 235 | type Item = (); 236 | 237 | type Error = Error; 238 | 239 | fn poll(&mut self) -> Poll { 240 | self.0.poll() 241 | } 242 | } 243 | 244 | #[derive(Debug)] 245 | enum ExecutionStatus { 246 | Success, 247 | Failed(ExecutionFailure), 248 | } 249 | 250 | #[derive(Debug)] 251 | enum ExecutionFailure { 252 | Timeout, 253 | Crash, 254 | Error, 255 | } 256 | 257 | fn spawn(delivery: &impl Delivery) -> Result { 258 | use std::io::Write; 259 | 260 | let current_exe = env::current_exe()?; 261 | let mut child = process::Command::new(¤t_exe) 262 | .env("BATCHRS_WORKER_IS_EXECUTOR", &delivery.properties().task) 263 | .stdin(process::Stdio::piped()) 264 | .spawn()?; 265 | { 266 | let stdin = child.stdin.as_mut().expect("failed to get stdin"); 267 | stdin.write_all(delivery.payload())?; 268 | stdin.flush()?; 269 | } 270 | let (_, timeout) = delivery.properties().timelimit; 271 | if let Some(duration) = timeout { 272 | drop(child.stdin.take()); 273 | if let Some(status) = child.wait_timeout(duration)? { 274 | if status.success() { 275 | Ok(ExecutionStatus::Success) 276 | } else if status.unix_signal().is_some() { 277 | Ok(ExecutionStatus::Failed(ExecutionFailure::Crash)) 278 | } else { 279 | Ok(ExecutionStatus::Failed(ExecutionFailure::Error)) 280 | } 281 | } else { 282 | child.kill()?; 283 | child.wait()?; 284 | Ok(ExecutionStatus::Failed(ExecutionFailure::Timeout)) 285 | } 286 | } else { 287 | let status = child.wait()?; 288 | if status.success() { 289 | Ok(ExecutionStatus::Success) 290 | } else if status.code().is_some() { 291 | Ok(ExecutionStatus::Failed(ExecutionFailure::Error)) 292 | } else { 293 | Ok(ExecutionStatus::Failed(ExecutionFailure::Crash)) 294 | } 295 | } 296 | } 297 | --------------------------------------------------------------------------------