rule-engine-mini 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,33 @@
1
+ version: 2
2
+ updates:
3
+ # Maintain Python dependencies defined in pyproject.toml
4
+ - package-ecosystem: "pip"
5
+ directory: "/"
6
+ schedule:
7
+ interval: "weekly"
8
+ day: "monday"
9
+ time: "04:00"
10
+ timezone: "Etc/UTC"
11
+ open-pull-requests-limit: 10
12
+ labels:
13
+ - "dependencies"
14
+ - "python"
15
+ commit-message:
16
+ prefix: "deps"
17
+ include: "scope"
18
+
19
+ # Maintain GitHub Actions dependencies
20
+ - package-ecosystem: "github-actions"
21
+ directory: "/"
22
+ schedule:
23
+ interval: "weekly"
24
+ day: "monday"
25
+ time: "04:00"
26
+ timezone: "Etc/UTC"
27
+ open-pull-requests-limit: 10
28
+ labels:
29
+ - "dependencies"
30
+ - "github-actions"
31
+ commit-message:
32
+ prefix: "ci"
33
+ include: "scope"
@@ -0,0 +1,43 @@
1
+ name: Run tests and upload coverage
2
+
3
+ on:
4
+ push:
5
+ branches: [main, dev]
6
+ pull_request:
7
+ branches: [main, dev]
8
+
9
+ jobs:
10
+ test:
11
+ name: Run tests and collect coverage
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ - name: Checkout
15
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.2.2
16
+ with:
17
+ fetch-depth: 2
18
+
19
+ - name: Set up Python
20
+ uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
21
+ with:
22
+ python-version: "3.11"
23
+ cache: "pip"
24
+ cache-dependency-path: "requirements.txt"
25
+
26
+ - name: Install dependencies
27
+ run: |
28
+ pip install --only-binary :all: coverage==7.6.12 iniconfig==2.0.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.4 pytest-cov==6.0.0
29
+
30
+ - name: Run tests
31
+ run: python -m pytest tests/ --cov=rule_engine_mini --cov-branch --cov-report=xml
32
+
33
+ - name: Upload results to Codecov
34
+ uses: codecov/codecov-action@0fb7174895f61a3b6b78fc075e0cd60383518dac # v5.4.0
35
+ with:
36
+ token: ${{ secrets.CODECOV_TOKEN }}
37
+ slug: buhozurdo/rule-engine-mini
38
+
39
+ - name: Upload test results to Codecov
40
+ if: ${{ !cancelled() }}
41
+ uses: codecov/test-results-action@0fa95f0e1eeaafde2c782583b36b28ad0d8c77d3 # v1.4.2
42
+ with:
43
+ token: ${{ secrets.CODECOV_TOKEN }}
@@ -0,0 +1,37 @@
1
+ name: Publish to Release
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ permissions:
8
+ contents: write
9
+
10
+ jobs:
11
+ build-and-release:
12
+ name: "Build and Attach Assets"
13
+ runs-on: "ubuntu-latest"
14
+
15
+ steps:
16
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.2.2
17
+
18
+ - name: Set up Python
19
+ uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
20
+ with:
21
+ python-version: "3.11"
22
+
23
+ - name: Install build tools and dependencies
24
+ run: |
25
+ pip install --only-binary :all: build==1.2.2.post1
26
+
27
+ - name: Build dists (.whl and .tar.gz)
28
+ run: |
29
+ SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct) \
30
+ python -m build
31
+
32
+ - name: Upload binaries to GitHub Release
33
+ uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2.2.1
34
+ with:
35
+ files: dist/*
36
+ env:
37
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -0,0 +1,34 @@
1
+ name: Publish Python Package to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ jobs:
8
+ pypi-publish:
9
+ name: Build and publish to PyPI
10
+ runs-on: ubuntu-latest
11
+ environment:
12
+ name: pypi
13
+ url: https://pypi.org/p/rule-engine-mini
14
+ permissions:
15
+ id-token: write # Obligatorio para la autenticación OIDC / Trusted Publisher
16
+
17
+ steps:
18
+ - name: Checkout repository
19
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.2.2
20
+
21
+ - name: Set up Python
22
+ uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
23
+ with:
24
+ python-version: "3.11"
25
+
26
+ - name: Install build tools
27
+ run: |
28
+ pip install --only-binary :all: build==1.2.2.post1
29
+
30
+ - name: Build package source and wheel
31
+ run: python -m build
32
+
33
+ - name: Publish package to PyPI
34
+ uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # release/v1
@@ -0,0 +1,41 @@
1
+ name: Build
2
+ on:
3
+ push:
4
+ branches:
5
+ - main
6
+ pull_request:
7
+ types: [opened, synchronize, reopened]
8
+ jobs:
9
+ sonarqube:
10
+ name: SonarQube
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
14
+ with:
15
+ fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
16
+
17
+ - name: Set up Python
18
+ uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
19
+ with:
20
+ python-version: "3.11"
21
+ cache: "pip"
22
+ cache-dependency-path: "requirements.txt"
23
+
24
+ - name: Install dependencies
25
+ run: |
26
+ pip install --only-binary :all: coverage==7.6.12 iniconfig==2.0.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.4 pytest-cov==6.0.0
27
+
28
+ - name: Run tests with coverage
29
+ run: python -m pytest tests/ --cov=rule_engine_mini --cov-branch --cov-report=xml
30
+
31
+ - name: Cache SonarQube packages
32
+ uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
33
+ with:
34
+ path: ~/.sonar/cache
35
+ key: ${{ runner.os }}-sonar
36
+ restore-keys: ${{ runner.os }}-sonar
37
+
38
+ - name: SonarQube Scan
39
+ uses: SonarSource/sonarqube-scan-action@4d1dc0c91ee400dcf8a6dddf2f705ac36542e304 # v8.4.0
40
+ env:
41
+ SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
@@ -0,0 +1,21 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # Distribution / packaging
7
+ dist/
8
+ build/
9
+ *.egg-info/
10
+
11
+ # Coverage and tests
12
+ .coverage
13
+ .coverage.*
14
+ coverage.xml
15
+ htmlcov/
16
+ .pytest_cache/
17
+
18
+ # Environments
19
+ .venv/
20
+ env/
21
+ venv/
@@ -0,0 +1,307 @@
1
+ Metadata-Version: 2.5
2
+ Name: rule-engine-mini
3
+ Version: 0.2.2
4
+ Summary: Deterministic AST business rules evaluator in pure Python — Zero eval(), sub-microsecond latency, safe JSON logic.
5
+ Project-URL: Homepage, https://buhozurdo.com/blog/rule-engine-mini-json-logic/
6
+ Project-URL: Repository, https://github.com/buhozurdo/rule-engine-mini
7
+ Author-email: Búho Zurdo <dev@buhozurdo.com>, Juan Rael Corrales Arellano <rael@buhozurdo.com>
8
+ License: MIT
9
+ Keywords: ast,deterministic,fintech,healthtech,json-logic,rule-engine,zero-eval
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Security
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.9
23
+ Provides-Extra: dev
24
+ Requires-Dist: mypy>=1.0.0; extra == 'dev'
25
+ Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
26
+ Requires-Dist: pytest>=7.0.0; extra == 'dev'
27
+ Requires-Dist: ruff>=0.1.0; extra == 'dev'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # Mini Rule Engine (rule-engine-mini)
31
+
32
+ <p align="center">
33
+ <strong>Deterministic AST business rules evaluator in pure Python.</strong><br>
34
+ Zero <code>eval()</code> • Zero dependencies • Sub-microsecond latency • Bulletproof JSON Logic.
35
+ </p>
36
+
37
+ <p align="center">
38
+ <a href="https://pypi.org/project/rule-engine-mini/"><img src="https://img.shields.io/pypi/v/rule-engine-mini.svg?style=flat-square&color=blue" alt="PyPI Version"></a>
39
+ <a href="https://pypi.org/project/rule-engine-mini/"><img src="https://img.shields.io/pypi/pyversions/rule-engine-mini.svg?style=flat-square" alt="Python Versions"></a>
40
+ <img src="https://img.shields.io/badge/coverage-100%25-brightgreen.svg?style=flat-square" alt="100% Core Coverage">
41
+ <img src="https://img.shields.io/badge/dependencies-0-brightgreen.svg?style=flat-square" alt="Zero Dependencies">
42
+ <img src="https://img.shields.io/badge/security-zero--eval-success.svg?style=flat-square" alt="Zero eval">
43
+ <img src="https://img.shields.io/badge/speed-~0.8µs-orange.svg?style=flat-square" alt="Sub-microsecond Speed">
44
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-purple.svg?style=flat-square" alt="License: MIT"></a>
45
+ </p>
46
+
47
+ ---
48
+
49
+ ## ⚡ The Problem: Business Rules Shouldn't Risk Remote Code Execution
50
+
51
+ Every backend eventually needs dynamic rules:
52
+ - **Fintech**: *"Flag transactions over \$5,000 originating outside MX or US."*
53
+ - **E-commerce**: *"Apply VIP discount if cart > \$100 and loyalty tier is Gold."*
54
+ - **Healthtech**: *"Trigger urgent triage if oxygen saturation < 90% or heart rate > 120."*
55
+
56
+ Most teams face a frustrating dilemma:
57
+
58
+ 1. **The Naive Trap (`eval()` or `exec()`)**: You store Python expressions in the database. One unescaped input later, an attacker gets a shell on your production cluster (RCE).
59
+ 2. **The Heavyweight Trap (Enterprise Rule Engines)**: You pull in massive DSLs or bloated frameworks with 50 transitive dependencies and a steep learning curve.
60
+
61
+ ### The Solution: `rule-engine-mini`
62
+
63
+ A **lightweight, auditable, pure Python** evaluator that parses declarative JSON Abstract Syntax Trees (ASTs).
64
+
65
+ - 🛡️ **Zero `eval()`, Zero `exec()`**: Immune to code injection by mathematical construction.
66
+ - 🚀 **Sub-microsecond performance**: Evaluates flat rules in **~0.8 µs** (>1,180,000 ops/sec) and composite nested rules in **~3.3 µs** (>295,000 ops/sec).
67
+ - 📦 **Zero dependencies**: Built strictly on the Python standard library. No supply-chain vulnerabilities.
68
+ - 🗄️ **Database & API Ready**: Store rules natively in PostgreSQL `JSONB`, MongoDB, Redis, or send them directly from frontend forms.
69
+ - 🧵 **Stateless & Thread-Safe**: Drop it into FastAPI, Celery, Django, or AWS Lambda without concurrency locks.
70
+ - 🧯 **DoS & Recursion Bomb Shield**: Configurable `max_depth` protects against maliciously nested payloads.
71
+ - 🧩 **Extensible**: Register custom domain operators in one line without forking.
72
+ - 🏷️ **PEP 561 Typed**: Full `py.typed` compliance for mypy, Pyright, and VS Code.
73
+
74
+ ---
75
+
76
+ ## 📊 Quick Comparison
77
+
78
+ | Feature | `eval()` / `exec()` | Heavy Rule Engines | `rule-engine-mini` |
79
+ | :--- | :---: | :---: | :---: |
80
+ | **RCE Safe** | ❌ Critical Risk | ⚠️ Complex Sandbox | ✅ **100% Deterministic** |
81
+ | **External Dependencies** | 0 | ❌ 10+ packages | ✅ **0 (Pure Standard Library)** |
82
+ | **Audit Time** | Impossible to secure | Hours / Days | ✅ **5 Minutes (Single File)** |
83
+ | **JSON-Native** | ❌ No (Raw strings) | ⚠️ Proprietary DSL | ✅ **Standard JSON-Logic AST** |
84
+ | **Execution Speed** | Medium | Slow startup | ✅ **0.8 µs – 3.3 µs per rule** |
85
+ | **Recursion Protection** | ❌ Stack overflow | ⚠️ Complex setup | ✅ **Built-in `max_depth` limit** |
86
+ | **Custom Operators** | Dangerous | Complex plugins | ✅ **`register_operator` API** |
87
+ | **Graceful Typing** | 💥 Crashes on mismatch | Configurable | ✅ **Safe fallback (`False`)** |
88
+
89
+ ---
90
+
91
+ ## 🚀 Installation
92
+
93
+ ```bash
94
+ pip install rule-engine-mini
95
+ ```
96
+
97
+ *Requirements: Python 3.9+ (Zero external dependencies).*
98
+
99
+ ---
100
+
101
+ ## 💡 Quickstart in 30 Seconds
102
+
103
+ ```python
104
+ from rule_engine_mini import RuleEvaluator
105
+
106
+ evaluator = RuleEvaluator()
107
+
108
+ # 1. Define a rule as a declarative JSON structure
109
+ fraud_prevention_rule = {
110
+ "and": [
111
+ {">": [{"var": "transaction.amount"}, 5000]},
112
+ {"in": [{"var": "transaction.country"}, ["MX", "US", "CA"]]},
113
+ {"==": [{"var": "user.is_flagged"}, False]}
114
+ ]
115
+ }
116
+
117
+ # 2. Provide the runtime context (nested dicts, lists, booleans, etc.)
118
+ context = {
119
+ "transaction": {
120
+ "amount": 7500,
121
+ "country": "MX"
122
+ },
123
+ "user": {
124
+ "id": "usr_99",
125
+ "is_flagged": False
126
+ }
127
+ }
128
+
129
+ # 3. Evaluate safely in ~3.3 microseconds
130
+ is_approved = evaluator.evaluate(fraud_prevention_rule, context)
131
+ print(is_approved) # 👉 True
132
+ ```
133
+
134
+ ---
135
+
136
+ ## 🛠️ Key Capabilities
137
+
138
+ ### 1. Deep Path Navigation (Dot Notation & Array Indices)
139
+ Traverse deeply nested dictionaries and array indexes without `KeyError` or `IndexError`:
140
+
141
+ ```python
142
+ rule = {">": [{"var": "cart.items.0.price"}, 100]}
143
+
144
+ context = {
145
+ "cart": {
146
+ "items": [
147
+ {"sku": "A1", "price": 150},
148
+ {"sku": "B2", "price": 80}
149
+ ]
150
+ }
151
+ }
152
+
153
+ evaluator.evaluate(rule, context) # True
154
+ ```
155
+
156
+ ### 2. Safe Fallbacks for Missing Variables
157
+ Pass a default fallback value if a key might be missing in production context:
158
+
159
+ ```python
160
+ # {"var": ["path.to.variable", default_value]}
161
+ rule = {"==": [{"var": ["user.membership", "standard"]}, "vip"]}
162
+
163
+ # When context has no 'membership' key, it safely evaluates to "standard"
164
+ context = {"user": {"name": "Alice"}}
165
+ evaluator.evaluate(rule, context) # False (no KeyError!)
166
+ ```
167
+
168
+ ### 3. Conditional Branching (`if` / Ternary)
169
+ Supports lazy evaluation: unexecuted branches are never calculated!
170
+
171
+ ```python
172
+ # {"if": [condition, then_value, else_value]}
173
+ tax_rule = {
174
+ "if": [
175
+ {"==": [{"var": "country"}, "MX"]},
176
+ {"*": [{"var": "subtotal"}, 0.16]},
177
+ {"*": [{"var": "subtotal"}, 0.08]}
178
+ ]
179
+ }
180
+
181
+ evaluator.evaluate(tax_rule, {"country": "MX", "subtotal": 1000}) # 160.0
182
+ ```
183
+
184
+ ### 4. Custom Operators in One Line
185
+ Extend the engine with domain-specific logic safely:
186
+
187
+ ```python
188
+ # Register a custom 'between' operator
189
+ evaluator.register_operator(
190
+ "between",
191
+ lambda args, ctx, ev: ev.evaluate(args[1], ctx) <= ev.evaluate(args[0], ctx) <= ev.evaluate(args[2], ctx)
192
+ )
193
+
194
+ rule = {"between": [{"var": "score"}, 70, 100]}
195
+ evaluator.evaluate(rule, {"score": 85}) # True
196
+ ```
197
+
198
+ ### 5. Graceful Type Safety & Zero-Division Shield
199
+ If mismatched types are compared or division by zero occurs, `rule-engine-mini` handles it safely instead of crashing your service:
200
+
201
+ ```python
202
+ evaluator.evaluate({">": [{"var": "score"}, 50]}, {"score": "invalid"}) # False
203
+ evaluator.evaluate({"/": [100, 0]}, {}) # None (ZeroDivisionError protected)
204
+ ```
205
+
206
+ ---
207
+
208
+ ## 📖 Supported Operators
209
+
210
+ | Category | Operator | Syntax Example | Description |
211
+ | :--- | :--- | :--- | :--- |
212
+ | **Variables** | `var` | `{"var": "user.age"}` | Resolves nested path via dot notation |
213
+ | | `var` *(default)* | `{"var": ["user.tier", "free"]}` | Fallback value if variable is missing |
214
+ | **Logic** | `and` | `{"and": [c1, c2, ...]}` | Short-circuit `True` if all clauses are truthy |
215
+ | | `or` | `{"or": [c1, c2, ...]}` | Short-circuit `True` if any clause is truthy |
216
+ | | `not` / `!` | `{"!": clause}` | Inverts boolean truthiness |
217
+ | | `!!` | `{"!!": clause}` | Casts value to strict boolean |
218
+ | **Branching** | `if` | `{"if": [cond, then, else]}` | Lazy ternary / multi-branch condition |
219
+ | **Comparisons** | `>`, `>=` | `{">": [{"var": "total"}, 500]}` | Greater than / Greater than or equal |
220
+ | | `<`, `<=` | `{"<": [{"var": "age"}, 18]}` | Less than / Less than or equal |
221
+ | | `==`, `===` | `{"==": [{"var": "status"}, "active"]}` | Equality check |
222
+ | | `!=`, `!==` | `{"!=": [{"var": "status"}, "banned"]}` | Inequality check |
223
+ | **Membership** | `in` | `{"in": [{"var": "country"}, ["MX", "US"]]}` | Checks item in list or substring in string |
224
+ | **Arithmetic** | `+` | `{"+": [10, 20, 5]}` | Addition / numeric sum |
225
+ | | `-` | `{"-": [100, 30]}` or `{"-": 5}` | Subtraction / unary negation |
226
+ | | `*` | `{"*": [5, 4]}` | Multiplication |
227
+ | | `/` | `{"/": [100, 4]}` | Safe division (returns `None` on 0) |
228
+ | | `%` | `{"%": [10, 3]}` | Safe modulo (returns `None` on 0) |
229
+ | | `min`, `max` | `{"min": [10, 5, 20]}` | Minimum / Maximum value |
230
+
231
+ ---
232
+
233
+ ## 🏗️ Real-World Recipe: FastAPI Dynamic Policy Engine
234
+
235
+ Store rules in your database and let business operations update logic in real time without redeploying your backend:
236
+
237
+ ```python
238
+ from fastapi import FastAPI
239
+ from pydantic import BaseModel
240
+ from rule_engine_mini import RuleEvaluator
241
+
242
+ app = FastAPI()
243
+ evaluator = RuleEvaluator()
244
+
245
+ # Imagine this rule is fetched dynamically from PostgreSQL JSONB or Redis
246
+ DISCOUNT_RULE = {
247
+ "or": [
248
+ {">=": [{"var": "cart.total"}, 1000]},
249
+ {"and": [
250
+ {"==": [{"var": "user.is_subscriber"}, True]},
251
+ {">=": [{"var": "cart.total"}, 500]}
252
+ ]}
253
+ ]
254
+ }
255
+
256
+ class CheckoutRequest(BaseModel):
257
+ user: dict
258
+ cart: dict
259
+
260
+ @app.post("/checkout/discount")
261
+ def check_discount(payload: CheckoutRequest):
262
+ context = payload.model_dump()
263
+ qualifies = evaluator.evaluate(DISCOUNT_RULE, context)
264
+ return {"discount_applied": qualifies}
265
+ ```
266
+
267
+ ---
268
+
269
+ ## ⏱️ Benchmark
270
+
271
+ Tested on x86-64 hardware with Python 3.12 (100,000 iterations):
272
+
273
+ ```
274
+ Operation Latency Throughput
275
+ -------------------------------------------------------------------------
276
+ Flat single rule (e.g. amount > 100) 0.84 µs / eval ~1,180,000 ops/sec
277
+ Composite 3-clause rule 3.37 µs / eval ~296,000 ops/sec
278
+ Memory allocations per evaluation 0 (Stack frames only)
279
+ ```
280
+
281
+ ---
282
+
283
+ ## 🧪 Testing & Coverage
284
+
285
+ Run the full test suite with Python's standard `unittest` or `coverage`:
286
+
287
+ ```bash
288
+ # Run tests
289
+ python -m unittest discover tests -v
290
+
291
+ # Run with coverage (enforces 100% core coverage)
292
+ coverage run -m unittest discover tests
293
+ coverage report -m
294
+ ```
295
+
296
+ ---
297
+
298
+ ## 🦉 Built at Búho Zurdo Labs
299
+
300
+ Designed and battle-tested for high-throughput, mission-critical systems at **Búho Zurdo Labs** ([buhozurdo.com](https://buhozurdo.com)).
301
+
302
+ ### Authors
303
+ - **Juan Rael Corrales Arellano** ([@buhozurdo](https://github.com/buhozurdo)) — `rael@buhozurdo.com`
304
+ - **Búho Zurdo Labs** — `dev@buhozurdo.com`
305
+
306
+ ### License
307
+ MIT License © 2026–2027 Búho Zurdo Labs. Free to use in commercial and open-source projects.