├── .github └── workflows │ └── test.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── Makefile ├── README.md ├── rustfmt.toml ├── schema.json ├── src ├── condition.rs ├── constraint.rs ├── error.rs ├── event │ ├── email_notification.rs │ ├── mod.rs │ └── post_callback.rs ├── lib.rs ├── rule.rs └── status.rs └── tests └── tests.rs /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | test: 7 | name: Test 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v2 11 | - uses: actions-rs/toolchain@v1 12 | with: 13 | toolchain: stable 14 | - uses: actions/cache@v2 15 | id: cache 16 | with: 17 | path: | 18 | ~/.cargo/registry 19 | ~/.cargo/git 20 | ~/.cargo/bin 21 | target/ 22 | key: cargo 23 | restore-keys: | 24 | cargo 25 | - run: make install-requirements test 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 0.9.4 (2021-08-06) 4 | ## Added 5 | - Support adding custom events. (Check the tests/tests.rs file for an example.) 6 | - Support `path` property of a condition. 7 | ## Changed 8 | ## Removed 9 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = [ 3 | "Cheng JIANG ", 4 | "Benn Sundsrud ", 5 | ] 6 | description = "json rules engine" 7 | edition = "2018" 8 | keywords = ["json", "rule", "rules", "engine"] 9 | license = "MIT/Apache-2.0" 10 | name = "json-rules-engine" 11 | repository = "https://github.com/GopherJ/json-rules-engine-rs" 12 | version = "0.9.4" 13 | 14 | [dependencies] 15 | async-trait = "0.1" 16 | erased-serde = "0.4.1" 17 | futures-util = { version = "0.3", optional = true } 18 | jsonpath_lib = { version = "0.3.0", optional = true } 19 | mustache = "0.9" 20 | reqwest = { version = "0.11", features = ["json", "rustls-tls"], optional = true } 21 | rhai = { version = "1.16.3", features = [ 22 | "sync", 23 | "f32_float", 24 | "no_function", 25 | "no_optimize", 26 | "no_module", 27 | "no_closure", 28 | "serde", 29 | "unchecked", 30 | ], optional = true } 31 | sendgrid = { version = "0.19.2", default-features = false, features = ["async", "rustls"], optional = true } 32 | serde = { version = "1.0", features = ["derive"] } 33 | serde_json = { version = "1.0" } 34 | strum = "0.25.0" 35 | strum_macros = "0.25.3" 36 | thiserror = "1.0" 37 | 38 | [dev-dependencies] 39 | tokio = { version = "1", features = ["full"] } 40 | 41 | [features] 42 | default = [] 43 | 44 | callback = ["reqwest"] 45 | email = ["sendgrid", "futures-util"] 46 | 47 | eval = ["rhai"] 48 | path = ["jsonpath_lib"] 49 | 50 | [package.metadata.cargo-all-features] 51 | skip_optional_dependencies = true 52 | -------------------------------------------------------------------------------- /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 | Copyright (c) 2020 Cheng JIANG 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | install-requirements: 2 | @rustup component add clippy-preview || true 3 | @cargo install cargo-outdated || true 4 | @cargo install cargo-all-features || true 5 | @cargo install cargo-udeps || true 6 | 7 | check: 8 | @cargo check-all-features 9 | @cargo +nightly fmt 10 | @cargo clippy 11 | @cargo +nightly udeps --all-targets 12 | @cargo outdated -wR 13 | @cargo update --dry-run 14 | 15 | test: 16 | @echo -e '\e[1;31mTest in all different combination of features...\e[0m' 17 | @cargo test-all-features -- --report-time -Z unstable-options 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # json-rules-engine 2 | 3 | ## Installation 4 | 5 | Add this package to `Cargo.toml` of your project. (Check https://crates.io/crates/json-rules-engine for right version) 6 | 7 | ```toml 8 | [dependencies] 9 | json-rules-engine = { version = "0.9", features = ["email", "eval"] } 10 | tokio = { version = "0.3.3", features = ["macros"] } 11 | serde_json = { version = "*" } 12 | anyhow = { version = "*" } 13 | ``` 14 | 15 | ## Features 16 | 17 | - Built in operators 18 | - Full support for `ALL`, `OR`, `Not`, `AtLeast` boolean operators, including recursive nesting 19 | - Type Safe 20 | - Load rules from json 21 | - Built in Moustache render 22 | - Safe script 23 | - Custom function 24 | - Custom event 25 | - Coalescence Group 26 | - Existing events: 27 | - HTTP POST to callback url 28 | - Email notifications based on `SendGrid` 29 | 30 | ## Get started 31 | 32 | ```rust 33 | use json_rules_engine::{Engine, Rule, Map, from_dynamic}; 34 | use serde_json::json; 35 | use serde::{Serialize, Deserialize}; 36 | 37 | #[derive(Deserialize, Serialize)] 38 | struct Facts { 39 | name: String, 40 | age: u8, 41 | action: String 42 | } 43 | 44 | fn age_greater_than20_less_than_inclusive25(p: Map) -> bool { 45 | let facts: Facts = from_dynamic(&p.into()).unwrap(); 46 | facts.age > 20 && facts.age <= 25 47 | } 48 | 49 | #[tokio::main] 50 | async fn main() -> anyhow::Result<()> { 51 | let sendgrid_api_key = "kjsldkjslkjlwkjkjew"; 52 | 53 | let rule_json = json!({ 54 | "conditions": { 55 | "and": [ 56 | { 57 | "field": "name", 58 | "operator": "string_equals", 59 | "value": "Cheng JIANG" 60 | }, 61 | { 62 | "field": "age", 63 | "operator": "int_in_range", 64 | "value": [20, 25] 65 | }, 66 | { 67 | "and": [ 68 | { 69 | "expr": "facts.age > 20 && facts.age <= 25", 70 | }, 71 | { 72 | "expr": "my_function(facts)", 73 | }, 74 | ] 75 | }, 76 | { 77 | "field": "action", 78 | "operator": "string_equals", 79 | "value": "coding in rust" 80 | } 81 | ] 82 | }, 83 | "events": [ 84 | { 85 | "type": "post_to_callback_url", 86 | "params": { 87 | "callback_url": "http://example.com/peoples/conding_in_rust", 88 | "type": "info", 89 | "title": "Another person is coding in rust", 90 | "message": "Name: {{ name }}, Age: {{ age }}, Action: {{ action }}" 91 | } 92 | }, 93 | { 94 | "type": "email_notification", 95 | "params": { 96 | "from": "alex_cj96@foxmail.com", 97 | "to": ["abc.def@gmail.com"], 98 | "type": "info", 99 | "title": "Another person is coding in rust", 100 | "message": "Name: {{ name }}, Age: {{ age }}, Action: {{ action }}," 101 | } 102 | } 103 | ] 104 | }); 105 | 106 | let rule: Rule = serde_json::from_str::(&serde_json::to_string(&rule_json).unwrap()).unwrap(); 107 | 108 | let mut engine = Engine::new(); 109 | engine.add_rule(rule); 110 | engine.add_function("my_function", age_greater_than20_less_than_inclusive25); 111 | 112 | let facts = json!({ 113 | "name": "Cheng JIANG", 114 | "age": 24, 115 | "action": "coding in rust", 116 | }); 117 | 118 | let rule_results = engine.run(&facts).await?; 119 | 120 | println!("{:#?}", rule_results); 121 | } 122 | ``` 123 | 124 | ## Special Thanks 125 | 126 | - [bsundsrud](https://github.com/bsundsrud) for its basic implementation [ruuls-rs](https://github.com/bsundsrud/ruuls-rs) 127 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | max_width = 80 2 | imports_granularity = "Crate" 3 | space_after_colon = true 4 | -------------------------------------------------------------------------------- /schema.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json-schema.org/draft-07/schema#", 3 | "title": "Array_of_Rule", 4 | "type": "array", 5 | "items": { 6 | "$ref": "#/definitions/Rule" 7 | }, 8 | "definitions": { 9 | "CoalescenceEvent": { 10 | "type": "object", 11 | "anyOf": [ 12 | { 13 | "type": "object", 14 | "required": ["params", "type"], 15 | "properties": { 16 | "params": { 17 | "$ref": "#/definitions/EventParams" 18 | }, 19 | "type": { 20 | "type": "string", 21 | "enum": ["message"] 22 | } 23 | } 24 | }, 25 | { 26 | "type": "object", 27 | "required": ["params", "type"], 28 | "properties": { 29 | "params": { 30 | "type": "object", 31 | "required": [ 32 | "callback_url", 33 | "message", 34 | "title", 35 | "type" 36 | ], 37 | "properties": { 38 | "app_data": { 39 | "default": {}, 40 | "type": "object", 41 | "additionalProperties": true 42 | }, 43 | "callback_url": { 44 | "type": "string" 45 | }, 46 | "message": { 47 | "type": "string" 48 | }, 49 | "title": { 50 | "type": "string" 51 | }, 52 | "type": { 53 | "type": "string" 54 | } 55 | } 56 | }, 57 | "type": { 58 | "type": "string", 59 | "enum": ["post_to_callback_url"] 60 | } 61 | } 62 | }, 63 | { 64 | "type": "object", 65 | "required": ["params", "type"], 66 | "properties": { 67 | "params": { 68 | "type": "object", 69 | "required": [ 70 | "from", 71 | "message", 72 | "title", 73 | "to", 74 | "type" 75 | ], 76 | "properties": { 77 | "from": { 78 | "type": "string" 79 | }, 80 | "message": { 81 | "type": "string" 82 | }, 83 | "title": { 84 | "type": "string" 85 | }, 86 | "to": { 87 | "type": "array", 88 | "items": { 89 | "type": "string" 90 | } 91 | }, 92 | "type": { 93 | "type": "string" 94 | } 95 | } 96 | }, 97 | "type": { 98 | "type": "string", 99 | "enum": ["email_notification"] 100 | } 101 | } 102 | } 103 | ], 104 | "properties": { 105 | "coalescence": { 106 | "type": ["integer", "null"], 107 | "format": "uint64", 108 | "minimum": 0.0 109 | }, 110 | "coalescence_group": { 111 | "type": ["string", "null"] 112 | } 113 | } 114 | }, 115 | "Condition": { 116 | "description": "Representation of a node in the rules tree\n\nIt is unnecessary to interact with this type outside of calling `Rule::check()`, to construct the rules tree use the [convenience functions][1] in the module root.\n\n[1]: index.html#functions", 117 | "anyOf": [ 118 | { 119 | "type": "object", 120 | "required": ["and"], 121 | "properties": { 122 | "and": { 123 | "type": "array", 124 | "items": { 125 | "$ref": "#/definitions/Condition" 126 | } 127 | } 128 | } 129 | }, 130 | { 131 | "type": "object", 132 | "required": ["or"], 133 | "properties": { 134 | "or": { 135 | "type": "array", 136 | "items": { 137 | "$ref": "#/definitions/Condition" 138 | } 139 | } 140 | } 141 | }, 142 | { 143 | "type": "object", 144 | "required": ["not"], 145 | "properties": { 146 | "not": { 147 | "$ref": "#/definitions/Condition" 148 | } 149 | } 150 | }, 151 | { 152 | "type": "object", 153 | "required": ["conditions", "should_minimum_meet"], 154 | "properties": { 155 | "conditions": { 156 | "type": "array", 157 | "items": { 158 | "$ref": "#/definitions/Condition" 159 | } 160 | }, 161 | "should_minimum_meet": { 162 | "type": "integer", 163 | "format": "uint", 164 | "minimum": 0.0 165 | } 166 | } 167 | }, 168 | { 169 | "type": "object", 170 | "anyOf": [ 171 | { 172 | "type": "object", 173 | "required": ["operator", "value"], 174 | "properties": { 175 | "operator": { 176 | "type": "string", 177 | "enum": ["string_equals"] 178 | }, 179 | "value": { 180 | "type": "string" 181 | } 182 | } 183 | }, 184 | { 185 | "type": "object", 186 | "required": ["operator", "value"], 187 | "properties": { 188 | "operator": { 189 | "type": "string", 190 | "enum": ["string_not_equals"] 191 | }, 192 | "value": { 193 | "type": "string" 194 | } 195 | } 196 | }, 197 | { 198 | "type": "object", 199 | "required": ["operator", "value"], 200 | "properties": { 201 | "operator": { 202 | "type": "string", 203 | "enum": ["string_contains"] 204 | }, 205 | "value": { 206 | "type": "string" 207 | } 208 | } 209 | }, 210 | { 211 | "type": "object", 212 | "required": ["operator", "value"], 213 | "properties": { 214 | "operator": { 215 | "type": "string", 216 | "enum": ["string_contains_all"] 217 | }, 218 | "value": { 219 | "type": "array", 220 | "items": { 221 | "type": "string" 222 | } 223 | } 224 | } 225 | }, 226 | { 227 | "type": "object", 228 | "required": ["operator", "value"], 229 | "properties": { 230 | "operator": { 231 | "type": "string", 232 | "enum": ["string_contains_any"] 233 | }, 234 | "value": { 235 | "type": "array", 236 | "items": { 237 | "type": "string" 238 | } 239 | } 240 | } 241 | }, 242 | { 243 | "type": "object", 244 | "required": ["operator", "value"], 245 | "properties": { 246 | "operator": { 247 | "type": "string", 248 | "enum": ["string_does_not_contain"] 249 | }, 250 | "value": { 251 | "type": "string" 252 | } 253 | } 254 | }, 255 | { 256 | "type": "object", 257 | "required": ["operator", "value"], 258 | "properties": { 259 | "operator": { 260 | "type": "string", 261 | "enum": ["string_does_not_contain_any"] 262 | }, 263 | "value": { 264 | "type": "array", 265 | "items": { 266 | "type": "string" 267 | } 268 | } 269 | } 270 | }, 271 | { 272 | "type": "object", 273 | "required": ["operator", "value"], 274 | "properties": { 275 | "operator": { 276 | "type": "string", 277 | "enum": ["string_in"] 278 | }, 279 | "value": { 280 | "type": "array", 281 | "items": { 282 | "type": "string" 283 | } 284 | } 285 | } 286 | }, 287 | { 288 | "type": "object", 289 | "required": ["operator", "value"], 290 | "properties": { 291 | "operator": { 292 | "type": "string", 293 | "enum": ["string_not_in"] 294 | }, 295 | "value": { 296 | "type": "array", 297 | "items": { 298 | "type": "string" 299 | } 300 | } 301 | } 302 | }, 303 | { 304 | "type": "object", 305 | "required": ["operator", "value"], 306 | "properties": { 307 | "operator": { 308 | "type": "string", 309 | "enum": ["int_equals"] 310 | }, 311 | "value": { 312 | "type": "integer", 313 | "format": "int64" 314 | } 315 | } 316 | }, 317 | { 318 | "type": "object", 319 | "required": ["operator", "value"], 320 | "properties": { 321 | "operator": { 322 | "type": "string", 323 | "enum": ["int_not_equals"] 324 | }, 325 | "value": { 326 | "type": "integer", 327 | "format": "int64" 328 | } 329 | } 330 | }, 331 | { 332 | "type": "object", 333 | "required": ["operator", "value"], 334 | "properties": { 335 | "operator": { 336 | "type": "string", 337 | "enum": ["int_contains"] 338 | }, 339 | "value": { 340 | "type": "integer", 341 | "format": "int64" 342 | } 343 | } 344 | }, 345 | { 346 | "type": "object", 347 | "required": ["operator", "value"], 348 | "properties": { 349 | "operator": { 350 | "type": "string", 351 | "enum": ["int_contains_all"] 352 | }, 353 | "value": { 354 | "type": "array", 355 | "items": { 356 | "type": "integer", 357 | "format": "int64" 358 | } 359 | } 360 | } 361 | }, 362 | { 363 | "type": "object", 364 | "required": ["operator", "value"], 365 | "properties": { 366 | "operator": { 367 | "type": "string", 368 | "enum": ["int_contains_any"] 369 | }, 370 | "value": { 371 | "type": "array", 372 | "items": { 373 | "type": "integer", 374 | "format": "int64" 375 | } 376 | } 377 | } 378 | }, 379 | { 380 | "type": "object", 381 | "required": ["operator", "value"], 382 | "properties": { 383 | "operator": { 384 | "type": "string", 385 | "enum": ["int_does_not_contain"] 386 | }, 387 | "value": { 388 | "type": "integer", 389 | "format": "int64" 390 | } 391 | } 392 | }, 393 | { 394 | "type": "object", 395 | "required": ["operator", "value"], 396 | "properties": { 397 | "operator": { 398 | "type": "string", 399 | "enum": ["int_does_not_contain_any"] 400 | }, 401 | "value": { 402 | "type": "array", 403 | "items": { 404 | "type": "integer", 405 | "format": "int64" 406 | } 407 | } 408 | } 409 | }, 410 | { 411 | "type": "object", 412 | "required": ["operator", "value"], 413 | "properties": { 414 | "operator": { 415 | "type": "string", 416 | "enum": ["int_in"] 417 | }, 418 | "value": { 419 | "type": "array", 420 | "items": { 421 | "type": "integer", 422 | "format": "int64" 423 | } 424 | } 425 | } 426 | }, 427 | { 428 | "type": "object", 429 | "required": ["operator", "value"], 430 | "properties": { 431 | "operator": { 432 | "type": "string", 433 | "enum": ["int_not_in"] 434 | }, 435 | "value": { 436 | "type": "array", 437 | "items": { 438 | "type": "integer", 439 | "format": "int64" 440 | } 441 | } 442 | } 443 | }, 444 | { 445 | "type": "object", 446 | "required": ["operator", "value"], 447 | "properties": { 448 | "operator": { 449 | "type": "string", 450 | "enum": ["int_in_range"] 451 | }, 452 | "value": { 453 | "type": "array", 454 | "items": [ 455 | { 456 | "type": "integer", 457 | "format": "int64" 458 | }, 459 | { 460 | "type": "integer", 461 | "format": "int64" 462 | } 463 | ], 464 | "maxItems": 2, 465 | "minItems": 2 466 | } 467 | } 468 | }, 469 | { 470 | "type": "object", 471 | "required": ["operator", "value"], 472 | "properties": { 473 | "operator": { 474 | "type": "string", 475 | "enum": ["int_not_in_range"] 476 | }, 477 | "value": { 478 | "type": "array", 479 | "items": [ 480 | { 481 | "type": "integer", 482 | "format": "int64" 483 | }, 484 | { 485 | "type": "integer", 486 | "format": "int64" 487 | } 488 | ], 489 | "maxItems": 2, 490 | "minItems": 2 491 | } 492 | } 493 | }, 494 | { 495 | "type": "object", 496 | "required": ["operator", "value"], 497 | "properties": { 498 | "operator": { 499 | "type": "string", 500 | "enum": ["int_less_than"] 501 | }, 502 | "value": { 503 | "type": "integer", 504 | "format": "int64" 505 | } 506 | } 507 | }, 508 | { 509 | "type": "object", 510 | "required": ["operator", "value"], 511 | "properties": { 512 | "operator": { 513 | "type": "string", 514 | "enum": ["int_less_than_inclusive"] 515 | }, 516 | "value": { 517 | "type": "integer", 518 | "format": "int64" 519 | } 520 | } 521 | }, 522 | { 523 | "type": "object", 524 | "required": ["operator", "value"], 525 | "properties": { 526 | "operator": { 527 | "type": "string", 528 | "enum": ["int_greater_than"] 529 | }, 530 | "value": { 531 | "type": "integer", 532 | "format": "int64" 533 | } 534 | } 535 | }, 536 | { 537 | "type": "object", 538 | "required": ["operator", "value"], 539 | "properties": { 540 | "operator": { 541 | "type": "string", 542 | "enum": ["int_greater_than_inclusive"] 543 | }, 544 | "value": { 545 | "type": "integer", 546 | "format": "int64" 547 | } 548 | } 549 | }, 550 | { 551 | "type": "object", 552 | "required": ["operator", "value"], 553 | "properties": { 554 | "operator": { 555 | "type": "string", 556 | "enum": ["float_equals"] 557 | }, 558 | "value": { 559 | "type": "number", 560 | "format": "double" 561 | } 562 | } 563 | }, 564 | { 565 | "type": "object", 566 | "required": ["operator", "value"], 567 | "properties": { 568 | "operator": { 569 | "type": "string", 570 | "enum": ["float_not_equals"] 571 | }, 572 | "value": { 573 | "type": "number", 574 | "format": "double" 575 | } 576 | } 577 | }, 578 | { 579 | "type": "object", 580 | "required": ["operator", "value"], 581 | "properties": { 582 | "operator": { 583 | "type": "string", 584 | "enum": ["float_contains"] 585 | }, 586 | "value": { 587 | "type": "number", 588 | "format": "double" 589 | } 590 | } 591 | }, 592 | { 593 | "type": "object", 594 | "required": ["operator", "value"], 595 | "properties": { 596 | "operator": { 597 | "type": "string", 598 | "enum": ["float_does_not_contain"] 599 | }, 600 | "value": { 601 | "type": "number", 602 | "format": "double" 603 | } 604 | } 605 | }, 606 | { 607 | "type": "object", 608 | "required": ["operator", "value"], 609 | "properties": { 610 | "operator": { 611 | "type": "string", 612 | "enum": ["float_in"] 613 | }, 614 | "value": { 615 | "type": "array", 616 | "items": { 617 | "type": "number", 618 | "format": "double" 619 | } 620 | } 621 | } 622 | }, 623 | { 624 | "type": "object", 625 | "required": ["operator", "value"], 626 | "properties": { 627 | "operator": { 628 | "type": "string", 629 | "enum": ["float_not_in"] 630 | }, 631 | "value": { 632 | "type": "array", 633 | "items": { 634 | "type": "number", 635 | "format": "double" 636 | } 637 | } 638 | } 639 | }, 640 | { 641 | "type": "object", 642 | "required": ["operator", "value"], 643 | "properties": { 644 | "operator": { 645 | "type": "string", 646 | "enum": ["float_in_range"] 647 | }, 648 | "value": { 649 | "type": "array", 650 | "items": [ 651 | { 652 | "type": "number", 653 | "format": "double" 654 | }, 655 | { 656 | "type": "number", 657 | "format": "double" 658 | } 659 | ], 660 | "maxItems": 2, 661 | "minItems": 2 662 | } 663 | } 664 | }, 665 | { 666 | "type": "object", 667 | "required": ["operator", "value"], 668 | "properties": { 669 | "operator": { 670 | "type": "string", 671 | "enum": ["float_not_in_range"] 672 | }, 673 | "value": { 674 | "type": "array", 675 | "items": [ 676 | { 677 | "type": "number", 678 | "format": "double" 679 | }, 680 | { 681 | "type": "number", 682 | "format": "double" 683 | } 684 | ], 685 | "maxItems": 2, 686 | "minItems": 2 687 | } 688 | } 689 | }, 690 | { 691 | "type": "object", 692 | "required": ["operator", "value"], 693 | "properties": { 694 | "operator": { 695 | "type": "string", 696 | "enum": ["float_less_than"] 697 | }, 698 | "value": { 699 | "type": "number", 700 | "format": "double" 701 | } 702 | } 703 | }, 704 | { 705 | "type": "object", 706 | "required": ["operator", "value"], 707 | "properties": { 708 | "operator": { 709 | "type": "string", 710 | "enum": ["float_less_than_inclusive"] 711 | }, 712 | "value": { 713 | "type": "number", 714 | "format": "double" 715 | } 716 | } 717 | }, 718 | { 719 | "type": "object", 720 | "required": ["operator", "value"], 721 | "properties": { 722 | "operator": { 723 | "type": "string", 724 | "enum": ["float_greater_than"] 725 | }, 726 | "value": { 727 | "type": "number", 728 | "format": "double" 729 | } 730 | } 731 | }, 732 | { 733 | "type": "object", 734 | "required": ["operator", "value"], 735 | "properties": { 736 | "operator": { 737 | "type": "string", 738 | "enum": ["float_greater_than_inclusive"] 739 | }, 740 | "value": { 741 | "type": "number", 742 | "format": "double" 743 | } 744 | } 745 | }, 746 | { 747 | "type": "object", 748 | "required": ["operator", "value"], 749 | "properties": { 750 | "operator": { 751 | "type": "string", 752 | "enum": ["bool_equals"] 753 | }, 754 | "value": { 755 | "type": "boolean" 756 | } 757 | } 758 | } 759 | ], 760 | "required": ["field"], 761 | "properties": { 762 | "field": { 763 | "type": "string" 764 | } 765 | } 766 | } 767 | ] 768 | }, 769 | "EventParams": { 770 | "type": "object", 771 | "required": ["message", "title", "type"], 772 | "properties": { 773 | "message": { 774 | "type": "string" 775 | }, 776 | "title": { 777 | "type": "string" 778 | }, 779 | "type": { 780 | "type": "string" 781 | } 782 | } 783 | }, 784 | "Rule": { 785 | "type": "object", 786 | "required": ["conditions", "events"], 787 | "properties": { 788 | "conditions": { 789 | "$ref": "#/definitions/Condition" 790 | }, 791 | "events": { 792 | "type": "array", 793 | "items": { 794 | "$ref": "#/definitions/CoalescenceEvent" 795 | } 796 | } 797 | } 798 | } 799 | } 800 | } 801 | -------------------------------------------------------------------------------- /src/condition.rs: -------------------------------------------------------------------------------- 1 | use crate::{status::Status, Constraint}; 2 | #[cfg(feature = "eval")] 3 | use rhai::{serde::to_dynamic, Engine, Scope}; 4 | use serde::{Deserialize, Serialize}; 5 | use serde_json::Value; 6 | 7 | #[derive(Clone, Debug, Serialize, Deserialize)] 8 | #[serde(untagged)] 9 | pub enum Condition { 10 | And { 11 | and: Vec, 12 | }, 13 | Or { 14 | or: Vec, 15 | }, 16 | Not { 17 | not: Box, 18 | }, 19 | AtLeast { 20 | should_minimum_meet: usize, 21 | conditions: Vec, 22 | }, 23 | Condition { 24 | field: String, 25 | #[serde(flatten)] 26 | constraint: Constraint, 27 | path: Option, 28 | }, 29 | #[cfg(feature = "eval")] 30 | Eval { 31 | expr: String, 32 | }, 33 | } 34 | 35 | impl Condition { 36 | /// Starting at this node, recursively check (depth-first) any child nodes and 37 | /// aggregate the results 38 | pub fn check_value( 39 | &self, 40 | info: &Value, 41 | #[cfg(feature = "eval")] rhai_engine: &Engine, 42 | ) -> ConditionResult { 43 | match *self { 44 | Condition::And { ref and } => { 45 | let mut status = Status::Met; 46 | let children = and 47 | .iter() 48 | .map(|c| { 49 | c.check_value( 50 | info, 51 | #[cfg(feature = "eval")] 52 | rhai_engine, 53 | ) 54 | }) 55 | .inspect(|r| status = status & r.status) 56 | .collect::>(); 57 | 58 | ConditionResult { 59 | name: "And".into(), 60 | status, 61 | children, 62 | } 63 | } 64 | Condition::Not { not: ref c } => { 65 | let res = c.check_value( 66 | info, 67 | #[cfg(feature = "eval")] 68 | rhai_engine, 69 | ); 70 | 71 | ConditionResult { 72 | name: "Not".into(), 73 | status: !res.status, 74 | children: res.children, 75 | } 76 | } 77 | Condition::Or { ref or } => { 78 | let mut status = Status::NotMet; 79 | let children = or 80 | .iter() 81 | .map(|c| { 82 | c.check_value( 83 | info, 84 | #[cfg(feature = "eval")] 85 | rhai_engine, 86 | ) 87 | }) 88 | .inspect(|r| status = status | r.status) 89 | .collect::>(); 90 | 91 | ConditionResult { 92 | name: "Or".into(), 93 | status, 94 | children, 95 | } 96 | } 97 | Condition::AtLeast { 98 | should_minimum_meet, 99 | ref conditions, 100 | } => { 101 | let mut met_count = 0; 102 | let children = conditions 103 | .iter() 104 | .map(|c| { 105 | c.check_value( 106 | info, 107 | #[cfg(feature = "eval")] 108 | rhai_engine, 109 | ) 110 | }) 111 | .inspect(|r| { 112 | if r.status == Status::Met { 113 | met_count += 1; 114 | } 115 | }) 116 | .collect::>(); 117 | 118 | let status = if met_count >= should_minimum_meet { 119 | Status::Met 120 | } else { 121 | Status::NotMet 122 | }; 123 | 124 | ConditionResult { 125 | name: format!( 126 | "At least meet {} of {}", 127 | should_minimum_meet, 128 | conditions.len() 129 | ), 130 | status, 131 | children, 132 | } 133 | } 134 | #[allow(unused_variables)] 135 | Condition::Condition { 136 | ref field, 137 | ref constraint, 138 | ref path, 139 | } => { 140 | let node_path = if field.starts_with('/') { 141 | field.to_owned() 142 | } else { 143 | format!("/{}", field) 144 | }; 145 | 146 | let mut status = Status::Unknown; 147 | 148 | #[allow(unused_mut)] 149 | if let Some(mut node) = info.pointer(&node_path).cloned() { 150 | #[cfg(feature = "path")] 151 | { 152 | if let Some(p) = path { 153 | let x = jsonpath_lib::select(&node, p) 154 | .unwrap() 155 | .into_iter() 156 | .cloned() 157 | .collect(); 158 | node = Value::Array(x); 159 | } 160 | } 161 | 162 | status = constraint.check_value(&node); 163 | } 164 | 165 | ConditionResult { 166 | name: field.to_owned(), 167 | status, 168 | children: Vec::new(), 169 | } 170 | } 171 | #[cfg(feature = "eval")] 172 | Condition::Eval { ref expr } => { 173 | let mut scope = Scope::new(); 174 | if let Ok(val) = to_dynamic(info) { 175 | scope.push_dynamic("facts", val); 176 | } 177 | let status = if rhai_engine 178 | .eval_with_scope::(&mut scope, expr) 179 | .unwrap_or(false) 180 | { 181 | Status::Met 182 | } else { 183 | Status::NotMet 184 | }; 185 | 186 | ConditionResult { 187 | name: "Eval".to_owned(), 188 | status, 189 | children: Vec::new(), 190 | } 191 | } 192 | } 193 | } 194 | } 195 | 196 | /// Result of checking a rules tree. 197 | #[derive(Debug, Serialize, Deserialize)] 198 | pub struct ConditionResult { 199 | /// Human-friendly description of the rule 200 | pub name: String, 201 | /// top-level status of this result 202 | pub status: Status, 203 | /// Results of any sub-rules 204 | pub children: Vec, 205 | } 206 | 207 | /// Creates a `Rule` where all child `Rule`s must be `Met` 208 | /// 209 | /// * If any are `NotMet`, the result will be `NotMet` 210 | /// * If the results contain only `Met` and `Unknown`, the result will be `Unknown` 211 | /// * Only results in `Met` if all children are `Met` 212 | pub fn and(and: Vec) -> Condition { 213 | Condition::And { and } 214 | } 215 | 216 | /// Creates a `Rule` where any child `Rule` must be `Met` 217 | /// 218 | /// * If any are `Met`, the result will be `Met` 219 | /// * If the results contain only `NotMet` and `Unknown`, the result will be `Unknown` 220 | /// * Only results in `NotMet` if all children are `NotMet` 221 | pub fn or(or: Vec) -> Condition { 222 | Condition::Or { or } 223 | } 224 | 225 | /// Creates a `Rule` where `n` child `Rule`s must be `Met` 226 | /// 227 | /// * If `>= n` are `Met`, the result will be `Met`, otherwise it'll be `NotMet` 228 | pub fn at_least( 229 | should_minimum_meet: usize, 230 | conditions: Vec, 231 | ) -> Condition { 232 | Condition::AtLeast { 233 | should_minimum_meet, 234 | conditions, 235 | } 236 | } 237 | 238 | /// Creates a rule for string comparison 239 | pub fn string_equals(field: &str, val: &str) -> Condition { 240 | Condition::Condition { 241 | field: field.into(), 242 | constraint: Constraint::StringEquals(val.into()), 243 | path: None, 244 | } 245 | } 246 | 247 | pub fn string_not_equals(field: &str, val: &str) -> Condition { 248 | Condition::Condition { 249 | field: field.into(), 250 | constraint: Constraint::StringNotEquals(val.into()), 251 | path: None, 252 | } 253 | } 254 | 255 | pub fn string_contains(field: &str, val: &str) -> Condition { 256 | Condition::Condition { 257 | field: field.into(), 258 | constraint: Constraint::StringContains(val.into()), 259 | path: None, 260 | } 261 | } 262 | 263 | pub fn string_contains_all(field: &str, val: Vec<&str>) -> Condition { 264 | Condition::Condition { 265 | field: field.into(), 266 | constraint: Constraint::StringContainsAll( 267 | val.into_iter().map(ToOwned::to_owned).collect(), 268 | ), 269 | path: None, 270 | } 271 | } 272 | 273 | pub fn string_contains_any(field: &str, val: Vec<&str>) -> Condition { 274 | Condition::Condition { 275 | field: field.into(), 276 | constraint: Constraint::StringContainsAny( 277 | val.into_iter().map(ToOwned::to_owned).collect(), 278 | ), 279 | path: None, 280 | } 281 | } 282 | 283 | pub fn string_does_not_contain(field: &str, val: &str) -> Condition { 284 | Condition::Condition { 285 | field: field.into(), 286 | constraint: Constraint::StringDoesNotContain(val.into()), 287 | path: None, 288 | } 289 | } 290 | 291 | pub fn string_does_not_contain_any(field: &str, val: Vec<&str>) -> Condition { 292 | Condition::Condition { 293 | field: field.into(), 294 | constraint: Constraint::StringDoesNotContainAny( 295 | val.into_iter().map(ToOwned::to_owned).collect(), 296 | ), 297 | path: None, 298 | } 299 | } 300 | 301 | pub fn string_in(field: &str, val: Vec<&str>) -> Condition { 302 | Condition::Condition { 303 | field: field.into(), 304 | constraint: Constraint::StringIn( 305 | val.into_iter().map(ToOwned::to_owned).collect(), 306 | ), 307 | path: None, 308 | } 309 | } 310 | 311 | pub fn string_not_in(field: &str, val: Vec<&str>) -> Condition { 312 | Condition::Condition { 313 | field: field.into(), 314 | constraint: Constraint::StringNotIn( 315 | val.into_iter().map(ToOwned::to_owned).collect(), 316 | ), 317 | path: None, 318 | } 319 | } 320 | 321 | /// Creates a rule for int comparison. 322 | pub fn int_equals(field: &str, val: i64) -> Condition { 323 | Condition::Condition { 324 | field: field.into(), 325 | constraint: Constraint::IntEquals(val), 326 | path: None, 327 | } 328 | } 329 | 330 | pub fn int_not_equals(field: &str, val: i64) -> Condition { 331 | Condition::Condition { 332 | field: field.into(), 333 | constraint: Constraint::IntNotEquals(val), 334 | path: None, 335 | } 336 | } 337 | 338 | pub fn int_contains(field: &str, val: i64) -> Condition { 339 | Condition::Condition { 340 | field: field.into(), 341 | constraint: Constraint::IntContains(val), 342 | path: None, 343 | } 344 | } 345 | 346 | pub fn int_contains_all(field: &str, val: Vec) -> Condition { 347 | Condition::Condition { 348 | field: field.into(), 349 | constraint: Constraint::IntContainsAll(val), 350 | path: None, 351 | } 352 | } 353 | 354 | pub fn int_contains_any(field: &str, val: Vec) -> Condition { 355 | Condition::Condition { 356 | field: field.into(), 357 | constraint: Constraint::IntContainsAny(val), 358 | path: None, 359 | } 360 | } 361 | 362 | pub fn int_does_not_contain(field: &str, val: i64) -> Condition { 363 | Condition::Condition { 364 | field: field.into(), 365 | constraint: Constraint::IntDoesNotContain(val), 366 | path: None, 367 | } 368 | } 369 | 370 | pub fn int_does_not_contain_any(field: &str, val: Vec) -> Condition { 371 | Condition::Condition { 372 | field: field.into(), 373 | constraint: Constraint::IntDoesNotContainAny(val), 374 | path: None, 375 | } 376 | } 377 | 378 | pub fn int_in(field: &str, val: Vec) -> Condition { 379 | Condition::Condition { 380 | field: field.into(), 381 | constraint: Constraint::IntIn(val), 382 | path: None, 383 | } 384 | } 385 | 386 | pub fn int_not_in(field: &str, val: Vec) -> Condition { 387 | Condition::Condition { 388 | field: field.into(), 389 | constraint: Constraint::IntNotIn(val), 390 | path: None, 391 | } 392 | } 393 | 394 | pub fn int_in_range(field: &str, start: i64, end: i64) -> Condition { 395 | Condition::Condition { 396 | field: field.into(), 397 | constraint: Constraint::IntInRange(start, end), 398 | path: None, 399 | } 400 | } 401 | 402 | pub fn int_not_in_range(field: &str, start: i64, end: i64) -> Condition { 403 | Condition::Condition { 404 | field: field.into(), 405 | constraint: Constraint::IntNotInRange(start, end), 406 | path: None, 407 | } 408 | } 409 | 410 | pub fn int_less_than(field: &str, val: i64) -> Condition { 411 | Condition::Condition { 412 | field: field.into(), 413 | constraint: Constraint::IntLessThan(val), 414 | path: None, 415 | } 416 | } 417 | 418 | pub fn int_less_than_inclusive(field: &str, val: i64) -> Condition { 419 | Condition::Condition { 420 | field: field.into(), 421 | constraint: Constraint::IntLessThanInclusive(val), 422 | path: None, 423 | } 424 | } 425 | 426 | pub fn int_greater_than(field: &str, val: i64) -> Condition { 427 | Condition::Condition { 428 | field: field.into(), 429 | constraint: Constraint::IntGreaterThan(val), 430 | path: None, 431 | } 432 | } 433 | 434 | pub fn int_greater_than_inclusive(field: &str, val: i64) -> Condition { 435 | Condition::Condition { 436 | field: field.into(), 437 | constraint: Constraint::IntGreaterThanInclusive(val), 438 | path: None, 439 | } 440 | } 441 | 442 | /// Creates a rule for float comparison. 443 | pub fn float_equals(field: &str, val: f64) -> Condition { 444 | Condition::Condition { 445 | field: field.into(), 446 | constraint: Constraint::FloatEquals(val), 447 | path: None, 448 | } 449 | } 450 | 451 | pub fn float_not_equals(field: &str, val: f64) -> Condition { 452 | Condition::Condition { 453 | field: field.into(), 454 | constraint: Constraint::FloatNotEquals(val), 455 | path: None, 456 | } 457 | } 458 | 459 | pub fn float_contains(field: &str, val: f64) -> Condition { 460 | Condition::Condition { 461 | field: field.into(), 462 | constraint: Constraint::FloatContains(val), 463 | path: None, 464 | } 465 | } 466 | 467 | pub fn float_does_not_contain(field: &str, val: f64) -> Condition { 468 | Condition::Condition { 469 | field: field.into(), 470 | constraint: Constraint::FloatDoesNotContain(val), 471 | path: None, 472 | } 473 | } 474 | 475 | pub fn float_in(field: &str, val: Vec) -> Condition { 476 | Condition::Condition { 477 | field: field.into(), 478 | constraint: Constraint::FloatIn(val), 479 | path: None, 480 | } 481 | } 482 | 483 | pub fn float_not_in(field: &str, val: Vec) -> Condition { 484 | Condition::Condition { 485 | field: field.into(), 486 | constraint: Constraint::FloatNotIn(val), 487 | path: None, 488 | } 489 | } 490 | 491 | pub fn float_in_range(field: &str, start: f64, end: f64) -> Condition { 492 | Condition::Condition { 493 | field: field.into(), 494 | constraint: Constraint::FloatInRange(start, end), 495 | path: None, 496 | } 497 | } 498 | 499 | pub fn float_not_in_range(field: &str, start: f64, end: f64) -> Condition { 500 | Condition::Condition { 501 | field: field.into(), 502 | constraint: Constraint::FloatNotInRange(start, end), 503 | path: None, 504 | } 505 | } 506 | 507 | pub fn float_less_than(field: &str, val: f64) -> Condition { 508 | Condition::Condition { 509 | field: field.into(), 510 | constraint: Constraint::FloatLessThan(val), 511 | path: None, 512 | } 513 | } 514 | 515 | pub fn float_less_than_inclusive(field: &str, val: f64) -> Condition { 516 | Condition::Condition { 517 | field: field.into(), 518 | constraint: Constraint::FloatLessThanInclusive(val), 519 | path: None, 520 | } 521 | } 522 | 523 | pub fn float_greater_than(field: &str, val: f64) -> Condition { 524 | Condition::Condition { 525 | field: field.into(), 526 | constraint: Constraint::FloatGreaterThan(val), 527 | path: None, 528 | } 529 | } 530 | 531 | pub fn float_greater_than_inclusive(field: &str, val: f64) -> Condition { 532 | Condition::Condition { 533 | field: field.into(), 534 | constraint: Constraint::FloatGreaterThanInclusive(val), 535 | path: None, 536 | } 537 | } 538 | 539 | /// Creates a rule for boolean comparison. 540 | pub fn bool_equals(field: &str, val: bool) -> Condition { 541 | Condition::Condition { 542 | field: field.into(), 543 | constraint: Constraint::BoolEquals(val), 544 | path: None, 545 | } 546 | } 547 | 548 | #[cfg(not(feature = "eval"))] 549 | #[cfg(test)] 550 | mod tests { 551 | use super::{ 552 | and, at_least, bool_equals, int_equals, int_in_range, or, string_equals, 553 | }; 554 | use crate::status::Status; 555 | use serde_json::{json, Value}; 556 | 557 | fn get_test_data() -> Value { 558 | json!({ 559 | "foo": 1, 560 | "bar": "bar", 561 | "baz": true 562 | }) 563 | } 564 | 565 | #[test] 566 | fn and_rules() { 567 | let map = get_test_data(); 568 | // Met & Met == Met 569 | let mut root = 570 | and(vec![int_equals("foo", 1), string_equals("bar", "bar")]); 571 | let mut res = root.check_value(&map); 572 | 573 | assert_eq!(res.status, Status::Met); 574 | 575 | // Met & NotMet == NotMet 576 | root = and(vec![int_equals("foo", 2), string_equals("bar", "bar")]); 577 | res = root.check_value(&map); 578 | 579 | assert_eq!(res.status, Status::NotMet); 580 | 581 | // Met & Unknown == Unknown 582 | root = and(vec![int_equals("quux", 2), string_equals("bar", "bar")]); 583 | res = root.check_value(&map); 584 | 585 | assert_eq!(res.status, Status::Unknown); 586 | 587 | // NotMet & Unknown == NotMet 588 | root = and(vec![int_equals("quux", 2), string_equals("bar", "baz")]); 589 | res = root.check_value(&map); 590 | 591 | assert_eq!(res.status, Status::NotMet); 592 | 593 | // Unknown & Unknown == Unknown 594 | root = and(vec![int_equals("quux", 2), string_equals("fizz", "bar")]); 595 | res = root.check_value(&map); 596 | 597 | assert_eq!(res.status, Status::Unknown); 598 | } 599 | 600 | #[test] 601 | fn or_rules() { 602 | let map = get_test_data(); 603 | // Met | Met == Met 604 | let mut root = 605 | or(vec![int_equals("foo", 1), string_equals("bar", "bar")]); 606 | let mut res = root.check_value(&map); 607 | 608 | assert_eq!(res.status, Status::Met); 609 | 610 | // Met | NotMet == Met 611 | root = or(vec![int_equals("foo", 2), string_equals("bar", "bar")]); 612 | res = root.check_value(&map); 613 | 614 | assert_eq!(res.status, Status::Met); 615 | 616 | // Met | Unknown == Met 617 | root = or(vec![int_equals("quux", 2), string_equals("bar", "bar")]); 618 | res = root.check_value(&map); 619 | 620 | assert_eq!(res.status, Status::Met); 621 | 622 | // NotMet | Unknown == Unknown 623 | root = or(vec![int_equals("quux", 2), string_equals("bar", "baz")]); 624 | res = root.check_value(&map); 625 | 626 | assert_eq!(res.status, Status::Unknown); 627 | 628 | // Unknown | Unknown == Unknown 629 | root = or(vec![int_equals("quux", 2), string_equals("fizz", "bar")]); 630 | res = root.check_value(&map); 631 | 632 | assert_eq!(res.status, Status::Unknown); 633 | } 634 | 635 | #[test] 636 | fn n_of_rules() { 637 | let map = get_test_data(); 638 | // 2 Met, 1 NotMet == Met 639 | let mut root = at_least( 640 | 2, 641 | vec![ 642 | int_equals("foo", 1), 643 | string_equals("bar", "bar"), 644 | bool_equals("baz", false), 645 | ], 646 | ); 647 | let mut res = root.check_value(&map); 648 | 649 | assert_eq!(res.status, Status::Met); 650 | 651 | // 1 Met, 1 NotMet, 1 Unknown == NotMet 652 | root = at_least( 653 | 2, 654 | vec![ 655 | int_equals("foo", 1), 656 | string_equals("quux", "bar"), 657 | bool_equals("baz", false), 658 | ], 659 | ); 660 | res = root.check_value(&map); 661 | 662 | assert_eq!(res.status, Status::NotMet); 663 | 664 | // 2 NotMet, 1 Unknown == Unknown 665 | root = at_least( 666 | 2, 667 | vec![ 668 | int_equals("foo", 2), 669 | string_equals("quux", "baz"), 670 | bool_equals("baz", false), 671 | ], 672 | ); 673 | res = root.check_value(&map); 674 | 675 | assert_eq!(res.status, Status::NotMet); 676 | } 677 | 678 | #[test] 679 | fn string_equals_rule() { 680 | let map = get_test_data(); 681 | let mut rule = string_equals("bar", "bar"); 682 | let mut res = rule.check_value(&map); 683 | assert_eq!(res.status, Status::Met); 684 | 685 | rule = string_equals("bar", "baz"); 686 | res = rule.check_value(&map); 687 | assert_eq!(res.status, Status::NotMet); 688 | } 689 | 690 | #[test] 691 | fn int_equals_rule() { 692 | let map = get_test_data(); 693 | let mut rule = int_equals("foo", 1); 694 | let mut res = rule.check_value(&map); 695 | assert_eq!(res.status, Status::Met); 696 | 697 | rule = int_equals("foo", 2); 698 | res = rule.check_value(&map); 699 | assert_eq!(res.status, Status::NotMet); 700 | 701 | // Values not convertible to int should be NotMet 702 | rule = int_equals("bar", 2); 703 | res = rule.check_value(&map); 704 | assert_eq!(res.status, Status::NotMet); 705 | } 706 | 707 | #[test] 708 | fn int_range_rule() { 709 | let map = get_test_data(); 710 | let mut rule = int_in_range("foo", 1, 3); 711 | let mut res = rule.check_value(&map); 712 | assert_eq!(res.status, Status::Met); 713 | 714 | rule = int_in_range("foo", 2, 3); 715 | res = rule.check_value(&map); 716 | assert_eq!(res.status, Status::NotMet); 717 | 718 | // Values not convertible to int should be NotMet 719 | rule = int_in_range("bar", 1, 3); 720 | res = rule.check_value(&map); 721 | assert_eq!(res.status, Status::NotMet); 722 | } 723 | 724 | #[test] 725 | fn boolean_rule() { 726 | let mut map = get_test_data(); 727 | let mut rule = bool_equals("baz", true); 728 | let mut res = rule.check_value(&map); 729 | assert_eq!(res.status, Status::Met); 730 | 731 | rule = bool_equals("baz", false); 732 | res = rule.check_value(&map); 733 | assert_eq!(res.status, Status::NotMet); 734 | 735 | rule = bool_equals("bar", true); 736 | res = rule.check_value(&map); 737 | assert_eq!(res.status, Status::NotMet); 738 | 739 | rule = bool_equals("bar", false); 740 | res = rule.check_value(&map); 741 | assert_eq!(res.status, Status::NotMet); 742 | 743 | map["quux".to_owned()] = json!("tRuE"); 744 | rule = bool_equals("quux", true); 745 | res = rule.check_value(&map); 746 | assert_eq!(res.status, Status::NotMet); 747 | } 748 | } 749 | -------------------------------------------------------------------------------- /src/constraint.rs: -------------------------------------------------------------------------------- 1 | use crate::status::Status; 2 | use serde::{Deserialize, Serialize}; 3 | use serde_json::Value; 4 | use strum::VariantNames; 5 | use strum_macros::EnumVariantNames; 6 | 7 | #[derive(Clone, Debug, Serialize, Deserialize, EnumVariantNames)] 8 | #[serde(rename_all = "snake_case")] 9 | #[strum(serialize_all = "snake_case")] 10 | #[serde(tag = "operator", content = "value")] 11 | pub enum Constraint { 12 | StringEquals(String), 13 | StringNotEquals(String), 14 | StringContains(String), 15 | StringContainsAll(Vec), 16 | StringContainsAny(Vec), 17 | StringDoesNotContain(String), 18 | StringDoesNotContainAny(Vec), 19 | StringIn(Vec), 20 | StringNotIn(Vec), 21 | IntEquals(i64), 22 | IntNotEquals(i64), 23 | IntContains(i64), 24 | IntContainsAll(Vec), 25 | IntContainsAny(Vec), 26 | IntDoesNotContain(i64), 27 | IntDoesNotContainAny(Vec), 28 | IntIn(Vec), 29 | IntNotIn(Vec), 30 | IntInRange(i64, i64), 31 | IntNotInRange(i64, i64), 32 | IntLessThan(i64), 33 | IntLessThanInclusive(i64), 34 | IntGreaterThan(i64), 35 | IntGreaterThanInclusive(i64), 36 | FloatEquals(f64), 37 | FloatNotEquals(f64), 38 | FloatContains(f64), 39 | FloatDoesNotContain(f64), 40 | FloatIn(Vec), 41 | FloatNotIn(Vec), 42 | FloatInRange(f64, f64), 43 | FloatNotInRange(f64, f64), 44 | FloatLessThan(f64), 45 | FloatLessThanInclusive(f64), 46 | FloatGreaterThan(f64), 47 | FloatGreaterThanInclusive(f64), 48 | BoolEquals(bool), 49 | } 50 | 51 | impl Constraint { 52 | fn value_as_str_array(v: &Value) -> Option> { 53 | v.as_array() 54 | .map(|x| x.iter().filter_map(|y| y.as_str()).collect::>()) 55 | } 56 | 57 | fn value_as_i64_array(v: &Value) -> Option> { 58 | v.as_array() 59 | .map(|x| x.iter().filter_map(|y| y.as_i64()).collect::>()) 60 | } 61 | 62 | fn value_as_f64_array(v: &Value) -> Option> { 63 | v.as_array() 64 | .map(|x| x.iter().filter_map(|y| y.as_f64()).collect::>()) 65 | } 66 | 67 | pub fn check_value(&self, v: &Value) -> Status { 68 | match *self { 69 | Constraint::StringEquals(ref s) => match v.as_str() { 70 | None => Status::NotMet, 71 | Some(v) => { 72 | if v == s { 73 | Status::Met 74 | } else { 75 | Status::NotMet 76 | } 77 | } 78 | }, 79 | Constraint::StringNotEquals(ref s) => match v.as_str() { 80 | None => Status::NotMet, 81 | Some(v) => { 82 | if v != s { 83 | Status::Met 84 | } else { 85 | Status::NotMet 86 | } 87 | } 88 | }, 89 | Constraint::StringContains(ref s) => { 90 | match Self::value_as_str_array(v) { 91 | None => Status::NotMet, 92 | Some(v) => { 93 | if v.contains(&s.as_str()) { 94 | Status::Met 95 | } else { 96 | Status::NotMet 97 | } 98 | } 99 | } 100 | } 101 | Constraint::StringContainsAll(ref s) => { 102 | match Self::value_as_str_array(v) { 103 | None => Status::NotMet, 104 | Some(v) => { 105 | if s.iter().all(|y| v.contains(&y.as_str())) { 106 | Status::Met 107 | } else { 108 | Status::NotMet 109 | } 110 | } 111 | } 112 | } 113 | Constraint::StringContainsAny(ref s) => { 114 | match Self::value_as_str_array(v) { 115 | None => Status::NotMet, 116 | Some(v) => { 117 | if s.iter().any(|y| v.contains(&y.as_str())) { 118 | Status::Met 119 | } else { 120 | Status::NotMet 121 | } 122 | } 123 | } 124 | } 125 | Constraint::StringDoesNotContain(ref s) => { 126 | match Self::value_as_str_array(v) { 127 | None => Status::NotMet, 128 | Some(v) => { 129 | if !v.contains(&s.as_str()) { 130 | Status::Met 131 | } else { 132 | Status::NotMet 133 | } 134 | } 135 | } 136 | } 137 | Constraint::StringDoesNotContainAny(ref s) => { 138 | match Self::value_as_str_array(v) { 139 | None => Status::NotMet, 140 | Some(v) => { 141 | if s.iter().all(|y| !v.contains(&y.as_str())) { 142 | Status::Met 143 | } else { 144 | Status::NotMet 145 | } 146 | } 147 | } 148 | } 149 | Constraint::StringIn(ref ss) => match v.as_str() { 150 | None => Status::NotMet, 151 | Some(v) => { 152 | if ss.iter().any(|s| s == v) { 153 | Status::Met 154 | } else { 155 | Status::NotMet 156 | } 157 | } 158 | }, 159 | Constraint::StringNotIn(ref ss) => match v.as_str() { 160 | None => Status::NotMet, 161 | Some(v) => { 162 | if ss.iter().all(|s| s != v) { 163 | Status::Met 164 | } else { 165 | Status::NotMet 166 | } 167 | } 168 | }, 169 | Constraint::IntEquals(num) => match v.as_i64() { 170 | None => Status::NotMet, 171 | Some(v) => { 172 | if v == num { 173 | Status::Met 174 | } else { 175 | Status::NotMet 176 | } 177 | } 178 | }, 179 | Constraint::IntNotEquals(num) => match v.as_i64() { 180 | None => Status::NotMet, 181 | Some(v) => { 182 | if v != num { 183 | Status::Met 184 | } else { 185 | Status::NotMet 186 | } 187 | } 188 | }, 189 | Constraint::IntContains(num) => match Self::value_as_i64_array(v) { 190 | None => Status::NotMet, 191 | Some(v) => { 192 | if v.contains(&num) { 193 | Status::Met 194 | } else { 195 | Status::NotMet 196 | } 197 | } 198 | }, 199 | Constraint::IntContainsAll(ref nums) => { 200 | match Self::value_as_i64_array(v) { 201 | None => Status::NotMet, 202 | Some(v) => { 203 | if nums.iter().all(|num| v.contains(&num)) { 204 | Status::Met 205 | } else { 206 | Status::NotMet 207 | } 208 | } 209 | } 210 | } 211 | Constraint::IntContainsAny(ref nums) => { 212 | match Self::value_as_i64_array(v) { 213 | None => Status::NotMet, 214 | Some(v) => { 215 | if nums.iter().any(|num| v.contains(&num)) { 216 | Status::Met 217 | } else { 218 | Status::NotMet 219 | } 220 | } 221 | } 222 | } 223 | Constraint::IntDoesNotContain(num) => { 224 | match Self::value_as_i64_array(v) { 225 | None => Status::NotMet, 226 | Some(v) => { 227 | if !v.contains(&num) { 228 | Status::Met 229 | } else { 230 | Status::NotMet 231 | } 232 | } 233 | } 234 | } 235 | Constraint::IntDoesNotContainAny(ref nums) => { 236 | match Self::value_as_i64_array(v) { 237 | None => Status::NotMet, 238 | Some(v) => { 239 | if nums.iter().all(|num| !v.contains(&num)) { 240 | Status::Met 241 | } else { 242 | Status::NotMet 243 | } 244 | } 245 | } 246 | } 247 | Constraint::IntIn(ref nums) => match v.as_i64() { 248 | None => Status::NotMet, 249 | Some(v) => { 250 | if nums.iter().any(|&num| num == v) { 251 | Status::Met 252 | } else { 253 | Status::NotMet 254 | } 255 | } 256 | }, 257 | Constraint::IntNotIn(ref nums) => match v.as_i64() { 258 | None => Status::NotMet, 259 | Some(v) => { 260 | if nums.iter().all(|&num| num != v) { 261 | Status::Met 262 | } else { 263 | Status::NotMet 264 | } 265 | } 266 | }, 267 | Constraint::IntInRange(start, end) => match v.as_i64() { 268 | None => Status::NotMet, 269 | Some(v) => { 270 | if start <= v && v <= end { 271 | Status::Met 272 | } else { 273 | Status::NotMet 274 | } 275 | } 276 | }, 277 | Constraint::IntNotInRange(start, end) => match v.as_i64() { 278 | None => Status::NotMet, 279 | Some(v) => { 280 | if start <= v && v <= end { 281 | Status::NotMet 282 | } else { 283 | Status::Met 284 | } 285 | } 286 | }, 287 | Constraint::IntLessThan(num) => match v.as_i64() { 288 | None => Status::NotMet, 289 | Some(v) => { 290 | if v < num { 291 | Status::Met 292 | } else { 293 | Status::NotMet 294 | } 295 | } 296 | }, 297 | Constraint::IntLessThanInclusive(num) => match v.as_i64() { 298 | None => Status::NotMet, 299 | Some(v) => { 300 | if v <= num { 301 | Status::Met 302 | } else { 303 | Status::NotMet 304 | } 305 | } 306 | }, 307 | Constraint::IntGreaterThan(num) => match v.as_i64() { 308 | None => Status::NotMet, 309 | Some(v) => { 310 | if v > num { 311 | Status::Met 312 | } else { 313 | Status::NotMet 314 | } 315 | } 316 | }, 317 | Constraint::IntGreaterThanInclusive(num) => match v.as_i64() { 318 | None => Status::NotMet, 319 | Some(v) => { 320 | if v >= num { 321 | Status::Met 322 | } else { 323 | Status::NotMet 324 | } 325 | } 326 | }, 327 | Constraint::FloatEquals(num) => match v.as_f64() { 328 | None => Status::NotMet, 329 | Some(v) => { 330 | if (v - num).abs() < f64::EPSILON { 331 | Status::Met 332 | } else { 333 | Status::NotMet 334 | } 335 | } 336 | }, 337 | Constraint::FloatNotEquals(num) => match v.as_f64() { 338 | None => Status::NotMet, 339 | Some(v) => { 340 | if (v - num).abs() > f64::EPSILON { 341 | Status::Met 342 | } else { 343 | Status::NotMet 344 | } 345 | } 346 | }, 347 | Constraint::FloatContains(num) => { 348 | match Self::value_as_f64_array(v) { 349 | None => Status::NotMet, 350 | Some(v) => { 351 | if v.contains(&num) { 352 | Status::Met 353 | } else { 354 | Status::NotMet 355 | } 356 | } 357 | } 358 | } 359 | Constraint::FloatDoesNotContain(num) => { 360 | match Self::value_as_f64_array(v) { 361 | None => Status::NotMet, 362 | Some(v) => { 363 | if !v.contains(&num) { 364 | Status::Met 365 | } else { 366 | Status::NotMet 367 | } 368 | } 369 | } 370 | } 371 | Constraint::FloatIn(ref nums) => match v.as_f64() { 372 | None => Status::NotMet, 373 | Some(v) => { 374 | if nums.iter().any(|&num| (v - num).abs() < f64::EPSILON) { 375 | Status::Met 376 | } else { 377 | Status::NotMet 378 | } 379 | } 380 | }, 381 | Constraint::FloatNotIn(ref nums) => match v.as_f64() { 382 | None => Status::NotMet, 383 | Some(v) => { 384 | if nums.iter().all(|&num| (v - num).abs() > f64::EPSILON) { 385 | Status::Met 386 | } else { 387 | Status::NotMet 388 | } 389 | } 390 | }, 391 | Constraint::FloatInRange(start, end) => match v.as_f64() { 392 | None => Status::NotMet, 393 | Some(v) => { 394 | if start <= v && v <= end { 395 | Status::Met 396 | } else { 397 | Status::NotMet 398 | } 399 | } 400 | }, 401 | Constraint::FloatNotInRange(start, end) => match v.as_f64() { 402 | None => Status::NotMet, 403 | Some(v) => { 404 | if start <= v && v <= end { 405 | Status::NotMet 406 | } else { 407 | Status::Met 408 | } 409 | } 410 | }, 411 | Constraint::FloatLessThan(num) => match v.as_f64() { 412 | None => Status::NotMet, 413 | Some(v) => { 414 | if v < num { 415 | Status::Met 416 | } else { 417 | Status::NotMet 418 | } 419 | } 420 | }, 421 | Constraint::FloatLessThanInclusive(num) => match v.as_f64() { 422 | None => Status::NotMet, 423 | Some(v) => { 424 | if v <= num { 425 | Status::Met 426 | } else { 427 | Status::NotMet 428 | } 429 | } 430 | }, 431 | Constraint::FloatGreaterThan(num) => match v.as_f64() { 432 | None => Status::NotMet, 433 | Some(v) => { 434 | if v > num { 435 | Status::Met 436 | } else { 437 | Status::NotMet 438 | } 439 | } 440 | }, 441 | Constraint::FloatGreaterThanInclusive(num) => match v.as_f64() { 442 | None => Status::NotMet, 443 | Some(v) => { 444 | if v >= num { 445 | Status::Met 446 | } else { 447 | Status::NotMet 448 | } 449 | } 450 | }, 451 | Constraint::BoolEquals(b) => match v.as_bool() { 452 | None => Status::NotMet, 453 | Some(v) => { 454 | if v == b { 455 | Status::Met 456 | } else { 457 | Status::NotMet 458 | } 459 | } 460 | }, 461 | } 462 | } 463 | 464 | pub fn operators() -> &'static [&'static str] { 465 | Constraint::VARIANTS 466 | } 467 | } 468 | 469 | #[cfg(test)] 470 | mod tests { 471 | use super::Constraint; 472 | 473 | #[test] 474 | fn available_operators() { 475 | assert_eq!(Constraint::operators().len(), 37); 476 | } 477 | } 478 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use serde_json::error::Error as SerializeJsonError; 2 | use thiserror::Error as ThisError; 3 | 4 | #[cfg(feature = "email")] 5 | use sendgrid::error::SendgridError; 6 | 7 | #[cfg(feature = "callback")] 8 | use reqwest::{header::InvalidHeaderValue, Error as ReqwestError}; 9 | 10 | #[derive(ThisError, Debug)] 11 | pub enum Error { 12 | #[cfg(feature = "callback")] 13 | #[error("Reqwest Error: `{0:?}`")] 14 | ReqwestError(#[from] ReqwestError), 15 | #[cfg(feature = "callback")] 16 | #[error("Reqwest Invalid Header Error: `{0:?}`")] 17 | ReqwestInvalidHeaderError(#[from] InvalidHeaderValue), 18 | #[error("Serialize Json Error: `{0:?}`")] 19 | SerializeJsonError(#[from] SerializeJsonError), 20 | #[cfg(feature = "email")] 21 | #[error("Send grid error: `{0:?}`")] 22 | SendgridError(#[from] SendgridError), 23 | // TODO make this error nicer! 24 | #[error("Event error: `{0}`")] 25 | EventError(String), 26 | } 27 | 28 | pub type Result = std::result::Result; 29 | -------------------------------------------------------------------------------- /src/event/email_notification.rs: -------------------------------------------------------------------------------- 1 | use crate::{event::EventTrait, Error}; 2 | 3 | use async_trait::async_trait; 4 | use erased_serde::Serialize; 5 | use futures_util::TryFutureExt; 6 | use sendgrid::v3::{ 7 | Content, Email as SendGridEmail, Message, Personalization, Sender, 8 | }; 9 | use serde_json::Value; 10 | 11 | use std::collections::HashMap; 12 | 13 | #[derive(Debug, Clone)] 14 | pub struct EmailNotification { 15 | ty: String, 16 | } 17 | 18 | #[async_trait] 19 | impl EventTrait for EmailNotification { 20 | fn new() -> Self { 21 | Self { 22 | ty: "email_notification".to_string(), 23 | } 24 | } 25 | 26 | fn get_type(&self) -> &str { 27 | &self.ty 28 | } 29 | 30 | fn validate(&self, params: &HashMap) -> Result<(), String> { 31 | if !(params.contains_key("to") 32 | && params.contains_key("from") 33 | && params.contains_key("title") 34 | && params.contains_key("message")) 35 | { 36 | return Err( 37 | "At least one of 'to', 'from', 'title', 'message' is missing." 38 | .to_string(), 39 | ); 40 | } 41 | 42 | Ok(()) 43 | } 44 | 45 | async fn trigger( 46 | &mut self, 47 | params: &HashMap, 48 | facts: &(dyn Serialize + Sync), 49 | ) -> Result<(), Error> { 50 | let api_key = ::std::env::var("SENDGRID_API_KEY") 51 | .expect("You must set 'SENDGRID_API_KEY' environment variable"); 52 | 53 | let sender = Sender::new(api_key); 54 | 55 | let tos = params.get("to").unwrap().as_array().unwrap(); 56 | let from = params.get("from").unwrap().to_string(); 57 | let mut title = params.get("title").unwrap().to_string(); 58 | let mut message = params.get("message").unwrap().to_string(); 59 | 60 | let value = serde_json::from_str::( 61 | &serde_json::to_string(facts).unwrap(), 62 | ) 63 | .unwrap(); 64 | if let Ok(tmpl) = mustache::compile_str(&message) 65 | .and_then(|template| template.render_to_string(&value)) 66 | { 67 | message = tmpl; 68 | } 69 | 70 | if let Ok(tmpl) = mustache::compile_str(&title) 71 | .and_then(|template| template.render_to_string(&value)) 72 | { 73 | title = tmpl; 74 | } 75 | 76 | let personalization = { 77 | let mut p = 78 | Personalization::new(SendGridEmail::new(&tos[0].to_string())); 79 | for to in tos.iter().skip(1) { 80 | p = p.add_to(SendGridEmail::new(to.to_string())); 81 | } 82 | p 83 | }; 84 | 85 | let m = Message::new(SendGridEmail::new(from)) 86 | .set_subject(&title) 87 | .add_content( 88 | Content::new() 89 | .set_content_type("text/plain") 90 | .set_value(message), 91 | ) 92 | .add_personalization(personalization); 93 | 94 | sender.send(&m).map_err(Error::from).await?; 95 | 96 | Ok(()) 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/event/mod.rs: -------------------------------------------------------------------------------- 1 | use crate::error::Error; 2 | 3 | use async_trait::async_trait; 4 | use erased_serde::Serialize as ErasedSerialize; 5 | use serde::{Deserialize, Serialize}; 6 | use serde_json::Value; 7 | 8 | use std::collections::HashMap; 9 | 10 | #[cfg(feature = "email")] 11 | pub mod email_notification; 12 | #[cfg(feature = "callback")] 13 | pub mod post_callback; 14 | 15 | #[derive(Clone, Debug, Serialize, Deserialize)] 16 | pub struct CoalescenceEvent { 17 | pub(crate) coalescence: Option, 18 | pub(crate) coalescence_group: Option, 19 | #[serde(flatten)] 20 | pub(crate) event: Event, 21 | } 22 | 23 | #[derive(Clone, Debug, Serialize, Deserialize)] 24 | pub struct Event { 25 | #[serde(rename = "type")] 26 | pub ty: String, 27 | pub params: HashMap, 28 | } 29 | 30 | #[async_trait] 31 | pub trait EventTrait { 32 | fn new() -> Self 33 | where 34 | Self: Sized; 35 | 36 | fn get_type(&self) -> &str; 37 | 38 | fn validate(&self, params: &HashMap) -> Result<(), String>; 39 | 40 | async fn trigger( 41 | &mut self, 42 | params: &HashMap, 43 | facts: &(dyn ErasedSerialize + Sync), 44 | ) -> Result<(), Error>; 45 | } 46 | -------------------------------------------------------------------------------- /src/event/post_callback.rs: -------------------------------------------------------------------------------- 1 | use crate::{event::EventTrait, Error}; 2 | 3 | use async_trait::async_trait; 4 | use erased_serde::Serialize; 5 | use reqwest::Client; 6 | use serde_json::{json, Value}; 7 | 8 | use std::collections::HashMap; 9 | 10 | #[derive(Debug, Clone)] 11 | pub struct PostCallback { 12 | ty: String, 13 | client: Client, 14 | } 15 | 16 | #[async_trait] 17 | impl EventTrait for PostCallback { 18 | fn new() -> Self { 19 | Self { 20 | ty: "post_to_callback_url".to_string(), 21 | client: Client::new(), 22 | } 23 | } 24 | 25 | fn get_type(&self) -> &str { 26 | &self.ty 27 | } 28 | 29 | fn validate(&self, params: &HashMap) -> Result<(), String> { 30 | if !params.contains_key("callback_url") { 31 | return Err("'callback_url' is missing.".to_string()); 32 | } 33 | 34 | Ok(()) 35 | } 36 | 37 | async fn trigger( 38 | &mut self, 39 | params: &HashMap, 40 | facts: &(dyn Serialize + Sync), 41 | ) -> Result<(), Error> { 42 | let mut callback_url = params 43 | .get("callback_url") 44 | .unwrap() 45 | .as_str() 46 | .unwrap() 47 | .to_string(); 48 | 49 | let value = serde_json::from_str::( 50 | &serde_json::to_string(facts).unwrap(), 51 | ) 52 | .unwrap(); 53 | if let Ok(tmpl) = mustache::compile_str(&callback_url) 54 | .and_then(|template| template.render_to_string(&value)) 55 | { 56 | callback_url = tmpl; 57 | } 58 | 59 | self.client 60 | .post(callback_url) 61 | .json(&json!({ 62 | "event": params, 63 | "facts": facts, 64 | })) 65 | .send() 66 | .await?; 67 | 68 | Ok(()) 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![allow(dead_code)] 2 | //! Simple rules engine that represents requirements as a tree, with each node having one or more requirements in order to be "Met". 3 | //! 4 | //! A tree of rules is constructed, and then the `.check_json()` method is called. 5 | //! `json` is a nested `field: value` that will be given to each node in the tree for testing. 6 | //! 7 | //! Status output can be either `Met`, `NotMet`, or `Unknown` if the tested field is not present in the json. 8 | //! 9 | //! To construct a tree, see the following methods. 10 | //! 11 | //! ## Example 12 | //! 13 | //! ```rust 14 | //! extern crate json_rules_engine; 15 | //! use serde_json::json; 16 | //! 17 | //! let tree = json_rules_engine::and(vec![ 18 | //! json_rules_engine::string_equals("name", "John Doe"), 19 | //! json_rules_engine::or(vec![ 20 | //! json_rules_engine::int_equals("fav_number", 5), 21 | //! json_rules_engine::int_in_range("thinking_of", 5, 10) 22 | //! ]) 23 | //! ]); 24 | //! let mut facts = json!({ 25 | //! "name": "John Doe", 26 | //! "fav_number": 5 27 | //! }); 28 | //! #[cfg(not(feature = "eval"))] 29 | //! { 30 | //! let result = tree.check_value(&facts); 31 | //! println!("{:?}", result); 32 | //! assert!(result.status == json_rules_engine::Status::Met); 33 | //! } 34 | //! // result = ConditionResult { name: "And", status: Met, children: [ConditionResult { name: "Name is John Doe", status: Met, children: [] }, ConditionResult { name: "Or", status: Met, children: [ConditionResult { name: "Favorite number is 5", status: Met, children: [] }, ConditionResult { name: "Thinking of a number between 5 and 10", status: Unknown, children: [] }] }] } 35 | //! ``` 36 | //! 37 | //! This creates a tree like the following: 38 | //! 39 | //! ```text 40 | //! +---------+ 41 | //! | AND | 42 | //! +---------+ 43 | //! _____________________/\_______________ 44 | //! | | 45 | //! V V 46 | //! +-------------------+ +--------+ 47 | //! | Name is John Doe | | OR | 48 | //! +-------------------+ +--------+ 49 | //! | field: "name" | ______________/\___________ 50 | //! | value: "John Doe" | | | 51 | //! +-------------------+ V V 52 | //! +----------------------+ +-------------------------+ 53 | //! | Favorite number is 5 | | Number between 5 and 10 | 54 | //! +----------------------+ +-------------------------+ 55 | //! | field: "fav_number" | | field: "thinking_of" | 56 | //! | value: 5 | | start: 5 | 57 | //! +----------------------+ | end: 10 | 58 | //! +-------------------------+ 59 | //! ``` 60 | //! 61 | //! [1]: enum.Rule.html#method.check 62 | 63 | mod condition; 64 | mod constraint; 65 | mod error; 66 | mod event; 67 | mod rule; 68 | mod status; 69 | 70 | pub use crate::{condition::*, constraint::*, event::*, rule::*, status::*}; 71 | 72 | #[cfg(feature = "eval")] 73 | pub use rhai::{serde::from_dynamic, Map}; 74 | 75 | #[cfg(feature = "eval")] 76 | use rhai::{ 77 | def_package, 78 | packages::{ 79 | ArithmeticPackage, BasicArrayPackage, BasicMapPackage, LogicPackage, 80 | Package, 81 | }, 82 | Engine as RhaiEngine, 83 | }; 84 | use serde_json::value::to_value; 85 | use std::{collections::HashMap, time::Instant}; 86 | 87 | #[cfg(feature = "email")] 88 | use crate::event::email_notification::EmailNotification; 89 | #[cfg(feature = "callback")] 90 | use crate::event::post_callback::PostCallback; 91 | 92 | pub use crate::error::*; 93 | use serde::Serialize; 94 | use std::{rc::Rc, sync::RwLock}; 95 | 96 | #[cfg(feature = "eval")] 97 | def_package!(rhai:JsonRulesEnginePackage:"Package for json-rules-engine", lib, { 98 | ArithmeticPackage::init(lib); 99 | LogicPackage::init(lib); 100 | BasicArrayPackage::init(lib); 101 | BasicMapPackage::init(lib); 102 | }); 103 | 104 | #[derive(Default)] 105 | pub struct Engine { 106 | rules: Vec, 107 | events: HashMap>>, 108 | #[cfg(feature = "eval")] 109 | rhai_engine: RhaiEngine, 110 | coalescences: HashMap, 111 | } 112 | 113 | impl Engine { 114 | pub fn new() -> Self { 115 | #[allow(unused_mut)] 116 | let mut events: HashMap<_, Rc>> = HashMap::new(); 117 | 118 | #[cfg(feature = "callback")] 119 | { 120 | let event = Rc::new(RwLock::new(PostCallback::new())); 121 | let key = event.read().unwrap().get_type().to_string(); 122 | events.insert(key, event); 123 | } 124 | 125 | #[cfg(feature = "email")] 126 | { 127 | let event = Rc::new(RwLock::new(EmailNotification::new())); 128 | let key = event.read().unwrap().get_type().to_string(); 129 | events.insert(key, event); 130 | } 131 | 132 | Self { 133 | rules: Vec::new(), 134 | #[cfg(feature = "eval")] 135 | rhai_engine: { 136 | let mut engine = RhaiEngine::new_raw(); 137 | engine.register_global_module( 138 | JsonRulesEnginePackage::new().as_shared_module(), 139 | ); 140 | engine 141 | }, 142 | coalescences: HashMap::new(), 143 | events, 144 | } 145 | } 146 | 147 | pub fn add_rule(&mut self, rule: Rule) { 148 | self.rules.push(rule) 149 | } 150 | 151 | pub fn add_rules(&mut self, rules: Vec) { 152 | self.rules.extend(rules) 153 | } 154 | 155 | pub fn load_rules(&mut self, rules: Vec) { 156 | self.rules = rules; 157 | } 158 | 159 | pub fn clear(&mut self) { 160 | self.rules.clear(); 161 | } 162 | 163 | #[cfg(feature = "eval")] 164 | pub fn add_function(&mut self, fname: &str, f: fn(Map) -> bool) { 165 | self.rhai_engine.register_fn(fname, f); 166 | } 167 | 168 | pub fn add_event(&mut self, f: Rc>) { 169 | let key = f.read().unwrap().get_type().to_string(); 170 | self.events.insert(key, f); 171 | } 172 | 173 | pub async fn run( 174 | &mut self, 175 | facts: &T, 176 | ) -> Result> { 177 | let facts = to_value(facts)?; 178 | let mut met_rule_results: Vec = self 179 | .rules 180 | .iter() 181 | .map(|rule| { 182 | rule.check_value( 183 | &facts, 184 | #[cfg(feature = "eval")] 185 | &self.rhai_engine, 186 | ) 187 | }) 188 | .filter(|rule_result| { 189 | rule_result.condition_result.status == Status::Met 190 | }) 191 | .collect(); 192 | 193 | self.coalescences.retain(|_k, (start, expiration)| { 194 | start.elapsed().as_secs() < *expiration 195 | }); 196 | 197 | for rule_result in met_rule_results.iter_mut() { 198 | // filter the events 199 | let mut cole = self.coalescences.clone(); 200 | rule_result.events.retain(|event| { 201 | if let (Some(coalescence_group), Some(coalescence)) = 202 | (&event.coalescence_group, event.coalescence) 203 | { 204 | if cole.contains_key(coalescence_group) { 205 | return false; 206 | } else { 207 | cole.insert( 208 | coalescence_group.clone(), 209 | (Instant::now(), coalescence), 210 | ); 211 | } 212 | } 213 | 214 | true 215 | }); 216 | 217 | self.coalescences = cole; 218 | 219 | // TODO run all the async events in parallel 220 | // run the events 221 | for event in &rule_result.events { 222 | let e = 223 | self.events.get_mut(&event.event.ty).ok_or_else(|| { 224 | Error::EventError( 225 | "Event type doesn't exist".to_string(), 226 | ) 227 | })?; 228 | 229 | e.read() 230 | .unwrap() 231 | .validate(&event.event.params) 232 | .map_err(Error::EventError)?; 233 | e.write() 234 | .unwrap() 235 | .trigger(&event.event.params, &facts) 236 | .await?; 237 | } 238 | } 239 | 240 | Ok(met_rule_results) 241 | } 242 | } 243 | -------------------------------------------------------------------------------- /src/rule.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | condition::{Condition, ConditionResult}, 3 | event::CoalescenceEvent, 4 | }; 5 | #[cfg(feature = "eval")] 6 | use rhai::Engine; 7 | use serde::{Deserialize, Serialize}; 8 | use serde_json::Value; 9 | 10 | #[derive(Clone, Debug, Serialize, Deserialize)] 11 | pub struct Rule { 12 | pub conditions: Condition, 13 | pub events: Vec, 14 | } 15 | 16 | impl Rule { 17 | pub fn check_value( 18 | &self, 19 | info: &Value, 20 | #[cfg(feature = "eval")] rhai_engine: &Engine, 21 | ) -> RuleResult { 22 | let condition_result = self.conditions.check_value( 23 | info, 24 | #[cfg(feature = "eval")] 25 | rhai_engine, 26 | ); 27 | 28 | let mut events = self.events.clone(); 29 | 30 | for CoalescenceEvent { 31 | coalescence_group, .. 32 | } in &mut events 33 | { 34 | if let Some(coalescence_group) = coalescence_group { 35 | if let Ok(new_coalescence_group) = 36 | &mut mustache::compile_str(coalescence_group) 37 | .and_then(|template| template.render_to_string(info)) 38 | { 39 | *coalescence_group = new_coalescence_group.clone(); 40 | } 41 | } 42 | } 43 | 44 | RuleResult { 45 | condition_result, 46 | events, 47 | } 48 | } 49 | } 50 | 51 | #[derive(Debug, Serialize, Deserialize)] 52 | pub struct RuleResult { 53 | pub condition_result: ConditionResult, 54 | pub events: Vec, 55 | } 56 | -------------------------------------------------------------------------------- /src/status.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | use std::ops::{BitAnd, BitOr, Not}; 3 | 4 | /// The status of a rule check 5 | #[derive(Debug, Eq, PartialEq, Copy, Clone, Serialize, Deserialize)] 6 | pub enum Status { 7 | /// Rule was satisfied 8 | Met, 9 | /// Rule was not satisfied 10 | NotMet, 11 | /// There was not enough information to evaluate 12 | Unknown, 13 | } 14 | 15 | impl BitAnd for Status { 16 | type Output = Status; 17 | fn bitand(self, rhs: Status) -> Status { 18 | match (self, rhs) { 19 | (Status::Met, Status::Met) => Status::Met, 20 | (Status::NotMet, _) | (_, Status::NotMet) => Status::NotMet, 21 | (_, _) => Status::Unknown, 22 | } 23 | } 24 | } 25 | 26 | impl BitOr for Status { 27 | type Output = Status; 28 | fn bitor(self, rhs: Status) -> Status { 29 | match (self, rhs) { 30 | (Status::NotMet, Status::NotMet) => Status::NotMet, 31 | (Status::Met, _) | (_, Status::Met) => Status::Met, 32 | (_, _) => Status::Unknown, 33 | } 34 | } 35 | } 36 | 37 | impl Not for Status { 38 | type Output = Status; 39 | 40 | fn not(self) -> Self::Output { 41 | match self { 42 | Status::Met => Status::NotMet, 43 | Status::NotMet => Status::Met, 44 | Status::Unknown => Status::Unknown, 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /tests/tests.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use erased_serde::Serialize as ErasedSerialize; 3 | #[cfg(feature = "eval")] 4 | use json_rules_engine::{from_dynamic, Map}; 5 | use json_rules_engine::{Engine, Error, EventTrait, Rule, Status}; 6 | use serde::{Deserialize, Serialize}; 7 | use serde_json::{json, Value}; 8 | use std::{collections::HashMap, rc::Rc, sync::RwLock}; 9 | 10 | #[tokio::test] 11 | async fn basic_met() { 12 | #[derive(Deserialize, Serialize)] 13 | struct Facts { 14 | name: String, 15 | age: u8, 16 | action: String, 17 | } 18 | 19 | let rule_json = json!({ 20 | "conditions": { 21 | "and": [ 22 | { 23 | "field": "name", 24 | "operator": "string_equals", 25 | "value": "Cheng JIANG" 26 | }, 27 | { 28 | "field": "age", 29 | "operator": "int_in_range", 30 | "value": [20, 25] 31 | }, 32 | { 33 | "field": "action", 34 | "operator": "string_equals", 35 | "value": "coding in rust" 36 | } 37 | ] 38 | }, 39 | "events": [ 40 | ] 41 | }); 42 | 43 | let rule: Rule = serde_json::from_str::( 44 | &serde_json::to_string(&rule_json).unwrap(), 45 | ) 46 | .unwrap(); 47 | 48 | let mut engine = Engine::new(); 49 | engine.add_rule(rule); 50 | 51 | let facts = json!({ 52 | "name": "Cheng JIANG", 53 | "age": 24, 54 | "action": "coding in rust", 55 | }); 56 | 57 | let rule_results = engine.run(&facts).await.unwrap(); 58 | 59 | assert_eq!(rule_results[0].condition_result.status, Status::Met) 60 | } 61 | 62 | #[tokio::test] 63 | async fn basic_not_met() { 64 | #[derive(Deserialize, Serialize)] 65 | struct Facts { 66 | name: String, 67 | age: u8, 68 | action: String, 69 | } 70 | 71 | let rule_json = json!({ 72 | "conditions": { 73 | "and": [ 74 | { 75 | "field": "age", 76 | "operator": "int_in_range", 77 | "value": [20, 25] 78 | }, 79 | ] 80 | }, 81 | "events": [ 82 | ] 83 | }); 84 | 85 | let rule: Rule = serde_json::from_str::( 86 | &serde_json::to_string(&rule_json).unwrap(), 87 | ) 88 | .unwrap(); 89 | 90 | let mut engine = Engine::new(); 91 | engine.add_rule(rule); 92 | 93 | let facts = json!({ 94 | "name": "Cheng JIANG", 95 | "age": 18, 96 | "action": "coding in rust", 97 | }); 98 | 99 | let rule_results = engine.run(&facts).await.unwrap(); 100 | 101 | assert_eq!(rule_results.len(), 0); 102 | } 103 | 104 | #[cfg(feature = "eval")] 105 | #[tokio::test] 106 | async fn custom_function() { 107 | #[derive(Deserialize, Serialize)] 108 | struct Facts { 109 | name: String, 110 | age: u8, 111 | action: String, 112 | } 113 | 114 | fn age_greater_than20_less_than_inclusive25(p: Map) -> bool { 115 | let facts: Facts = from_dynamic(&p.into()).unwrap(); 116 | facts.age > 20 && facts.age <= 25 117 | } 118 | 119 | let rule_json = json!({ 120 | "conditions": { 121 | "and": [ 122 | { 123 | "field": "name", 124 | "operator": "string_equals", 125 | "value": "Cheng JIANG" 126 | }, 127 | { 128 | "field": "age", 129 | "operator": "int_in_range", 130 | "value": [20, 25] 131 | }, 132 | { 133 | "and": [ 134 | { 135 | "expr": "facts.age > 20 && facts.age <= 25", 136 | }, 137 | { 138 | "expr": "my_function(facts)", 139 | }, 140 | ] 141 | }, 142 | { 143 | "field": "action", 144 | "operator": "string_equals", 145 | "value": "coding in rust" 146 | } 147 | ] 148 | }, 149 | "events": [ 150 | ] 151 | }); 152 | 153 | let rule: Rule = serde_json::from_str::( 154 | &serde_json::to_string(&rule_json).unwrap(), 155 | ) 156 | .unwrap(); 157 | 158 | let mut engine = Engine::new(); 159 | engine.add_rule(rule); 160 | engine 161 | .add_function("my_function", age_greater_than20_less_than_inclusive25); 162 | 163 | let facts = json!({ 164 | "name": "Cheng JIANG", 165 | "age": 24, 166 | "action": "coding in rust", 167 | }); 168 | 169 | let rule_results = engine.run(&facts).await.unwrap(); 170 | 171 | assert_eq!(rule_results[0].condition_result.status, Status::Met) 172 | } 173 | 174 | #[cfg(feature = "callback")] 175 | #[tokio::test] 176 | async fn post_callback_event() { 177 | #[derive(Deserialize, Serialize)] 178 | struct Facts { 179 | name: String, 180 | age: u8, 181 | action: String, 182 | } 183 | 184 | let rule_json = json!({ 185 | "conditions": { 186 | "and": [ 187 | { 188 | "field": "name", 189 | "operator": "string_equals", 190 | "value": "Cheng JIANG" 191 | }, 192 | { 193 | "field": "age", 194 | "operator": "int_in_range", 195 | "value": [20, 25] 196 | }, 197 | { 198 | "field": "action", 199 | "operator": "string_equals", 200 | "value": "coding in rust" 201 | } 202 | ] 203 | }, 204 | "events": [ 205 | { 206 | "type": "post_to_callback_url", 207 | "params": { 208 | "callback_url": "https://example.com/whatever", 209 | "type": "info", 210 | "title": "Another person is coding in rust", 211 | "message": "Name: {{ name }}, Age: {{ age }}, Action: {{ action }}" 212 | } 213 | } 214 | ] 215 | }); 216 | 217 | let rule: Rule = serde_json::from_str::( 218 | &serde_json::to_string(&rule_json).unwrap(), 219 | ) 220 | .unwrap(); 221 | 222 | let mut engine = Engine::new(); 223 | engine.add_rule(rule); 224 | 225 | let facts = json!({ 226 | "name": "Cheng JIANG", 227 | "age": 24, 228 | "action": "coding in rust", 229 | }); 230 | 231 | let rule_results = engine.run(&facts).await.unwrap(); 232 | 233 | assert_eq!(rule_results[0].condition_result.status, Status::Met) 234 | } 235 | 236 | #[tokio::test] 237 | async fn custom_event() { 238 | #[derive(Deserialize, Serialize)] 239 | struct Facts { 240 | name: String, 241 | age: u8, 242 | action: String, 243 | } 244 | 245 | #[derive(Debug, Clone)] 246 | struct CustomEvent { 247 | ty: String, 248 | res: String, 249 | } 250 | 251 | #[async_trait] 252 | impl EventTrait for CustomEvent { 253 | fn new() -> Self { 254 | Self { 255 | ty: "custom_event".to_string(), 256 | res: String::new(), 257 | } 258 | } 259 | 260 | fn get_type(&self) -> &str { 261 | &self.ty 262 | } 263 | 264 | fn validate( 265 | &self, 266 | params: &HashMap, 267 | ) -> Result<(), String> { 268 | if !params.contains_key("name") { 269 | return Err("'name' is missing.".to_string()); 270 | } 271 | 272 | Ok(()) 273 | } 274 | 275 | async fn trigger( 276 | &mut self, 277 | params: &HashMap, 278 | facts: &(dyn ErasedSerialize + Sync), 279 | ) -> Result<(), Error> { 280 | let mut name = 281 | params.get("name").unwrap().as_str().unwrap().to_string(); 282 | 283 | let value = serde_json::from_str::( 284 | &serde_json::to_string(facts).unwrap(), 285 | ) 286 | .unwrap(); 287 | if let Ok(tmpl) = mustache::compile_str(&name) 288 | .and_then(|template| template.render_to_string(&value)) 289 | { 290 | name = tmpl; 291 | } 292 | 293 | self.res = format!("name is: {}", &name); 294 | 295 | Ok(()) 296 | } 297 | } 298 | 299 | let rule_json = json!({ 300 | "conditions": { 301 | "and": [ 302 | { 303 | "field": "name", 304 | "operator": "string_equals", 305 | "value": "Cheng JIANG" 306 | }, 307 | { 308 | "field": "age", 309 | "operator": "int_in_range", 310 | "value": [20, 25] 311 | }, 312 | { 313 | "field": "action", 314 | "operator": "string_equals", 315 | "value": "coding in rust" 316 | } 317 | ] 318 | }, 319 | "events": [ 320 | { 321 | "type": "custom_event", 322 | "params": { 323 | "name": "Cheng JIANG", 324 | } 325 | } 326 | ] 327 | }); 328 | 329 | let rule: Rule = serde_json::from_str::( 330 | &serde_json::to_string(&rule_json).unwrap(), 331 | ) 332 | .unwrap(); 333 | 334 | let mut engine = Engine::new(); 335 | engine.add_rule(rule); 336 | 337 | let custom_event = Rc::new(RwLock::new(CustomEvent::new())); 338 | engine.add_event(custom_event.clone()); 339 | 340 | let facts = json!({ 341 | "name": "Cheng JIANG", 342 | "age": 24, 343 | "action": "coding in rust", 344 | }); 345 | 346 | engine.run(&facts).await.unwrap(); 347 | 348 | assert_eq!(&custom_event.read().unwrap().res, "name is: Cheng JIANG"); 349 | } 350 | 351 | #[tokio::test] 352 | async fn test_a_pointer() { 353 | #[derive(Deserialize, Serialize)] 354 | struct Facts { 355 | name: String, 356 | age: u8, 357 | action: String, 358 | } 359 | 360 | let rule_json = json!({ 361 | "conditions": { 362 | "and": [ 363 | { 364 | "field": "person/name", 365 | "operator": "string_equals", 366 | "value": "Cheng JIANG" 367 | }, 368 | { 369 | "field": "person/age", 370 | "operator": "int_in_range", 371 | "value": [20, 25] 372 | }, 373 | ] 374 | }, 375 | "events": [ 376 | ] 377 | }); 378 | 379 | let rule: Rule = serde_json::from_str::( 380 | &serde_json::to_string(&rule_json).unwrap(), 381 | ) 382 | .unwrap(); 383 | 384 | let mut engine = Engine::new(); 385 | engine.add_rule(rule); 386 | 387 | let facts = json!({ 388 | "person": { 389 | "name": "Cheng JIANG", 390 | "age": 24, 391 | } 392 | }); 393 | 394 | let rule_results = engine.run(&facts).await.unwrap(); 395 | 396 | assert_eq!(rule_results[0].condition_result.status, Status::Met) 397 | } 398 | 399 | #[cfg(feature = "path")] 400 | #[tokio::test] 401 | async fn test_a_pointer_and_path() { 402 | #[derive(Deserialize, Serialize)] 403 | struct Facts { 404 | name: String, 405 | age: u8, 406 | action: String, 407 | } 408 | 409 | let rule_json = json!({ 410 | "conditions": { 411 | "and": [ 412 | { 413 | "field": "people", 414 | "operator": "string_contains", 415 | "value": "Cheng JIANG", 416 | "path": "$..name" 417 | } 418 | ] 419 | }, 420 | "events": [ 421 | ] 422 | }); 423 | 424 | let rule: Rule = serde_json::from_str::( 425 | &serde_json::to_string(&rule_json).unwrap(), 426 | ) 427 | .unwrap(); 428 | 429 | let mut engine = Engine::new(); 430 | engine.add_rule(rule); 431 | 432 | let facts = json!({ 433 | "people": [ 434 | { 435 | "name": "Cheng JIANG", 436 | "age": 24, 437 | }, 438 | { 439 | "name": "Omid Rad", 440 | "age": 23, 441 | }, 442 | ] 443 | }); 444 | 445 | let rule_results = engine.run(&facts).await.unwrap(); 446 | 447 | assert_eq!(rule_results[0].condition_result.status, Status::Met) 448 | } 449 | --------------------------------------------------------------------------------