boerules 1.0.0__py3-none-any.whl

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.
boerules/__init__.py ADDED
@@ -0,0 +1,29 @@
1
+ """Python client for BOE: register a ruleset and execute it."""
2
+
3
+ from ._client import BOE, _sdk_version
4
+ from ._errors import (
5
+ BOEError,
6
+ ProductionKeyCannotRegisterError,
7
+ RulesetArchivedError,
8
+ RulesetEngineModeMismatchError,
9
+ RulesetNotLiveInEnvironmentError,
10
+ SubscriptionLapsedError,
11
+ SubscriptionMissingError,
12
+ )
13
+ from ._types import ExecuteResult, RegisterResult
14
+
15
+ __version__ = _sdk_version()
16
+
17
+ __all__ = [
18
+ "__version__",
19
+ "BOE",
20
+ "BOEError",
21
+ "ExecuteResult",
22
+ "ProductionKeyCannotRegisterError",
23
+ "RegisterResult",
24
+ "RulesetArchivedError",
25
+ "RulesetEngineModeMismatchError",
26
+ "RulesetNotLiveInEnvironmentError",
27
+ "SubscriptionLapsedError",
28
+ "SubscriptionMissingError",
29
+ ]
boerules/_client.py ADDED
@@ -0,0 +1,146 @@
1
+ """Synchronous BOE client over httpx."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import time
7
+ from importlib import metadata
8
+ from types import TracebackType
9
+ from typing import Any
10
+
11
+ import httpx
12
+
13
+ from . import _wire
14
+ from ._errors import BOEError, error_from_response
15
+ from ._types import ExecuteResult, RegisterResult
16
+
17
+ DEFAULT_BASE_URL = "https://api.boerules.com/v1"
18
+ _RETRYABLE_STATUS_CODES = frozenset({500, 502, 503, 504})
19
+ _BACKOFF_BASE_SECONDS = 0.1
20
+
21
+
22
+ def _sdk_version() -> str:
23
+ try:
24
+ return metadata.version("boerules")
25
+ except metadata.PackageNotFoundError:
26
+ return "0.0.0"
27
+
28
+
29
+ def _join(base_url: str, path: str) -> str:
30
+ return base_url.rstrip("/") + "/" + path.lstrip("/")
31
+
32
+
33
+ class BOE:
34
+ """Register and execute BOE rulesets.
35
+
36
+ Reads BOE_API_KEY and BOE_BASE_URL when the arguments are omitted.
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ api_key: str | None = None,
42
+ base_url: str | None = None,
43
+ execute_base_url: str | None = None,
44
+ timeout_seconds: float = 30.0,
45
+ max_retries: int = 3,
46
+ transport: httpx.BaseTransport | None = None,
47
+ ) -> None:
48
+ resolved_key = api_key or os.environ.get("BOE_API_KEY")
49
+ if not resolved_key:
50
+ raise BOEError(
51
+ "No API key. Pass api_key=... or set the BOE_API_KEY environment variable."
52
+ )
53
+ self._base_url = (base_url or os.environ.get("BOE_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
54
+ self._execute_base_url = (execute_base_url or self._base_url).rstrip("/")
55
+ self._max_retries = max_retries
56
+ self._http = httpx.Client(
57
+ timeout=timeout_seconds,
58
+ transport=transport,
59
+ headers={
60
+ "Authorization": f"Bearer {resolved_key}",
61
+ "Content-Type": "application/json",
62
+ "X-BOE-SDK": "python",
63
+ "X-BOE-SDK-Version": _sdk_version(),
64
+ },
65
+ )
66
+
67
+ @property
68
+ def base_url(self) -> str:
69
+ return self._base_url
70
+
71
+ @property
72
+ def execute_base_url(self) -> str:
73
+ return self._execute_base_url
74
+
75
+ @property
76
+ def is_closed(self) -> bool:
77
+ return self._http.is_closed
78
+
79
+ def __enter__(self) -> BOE:
80
+ return self
81
+
82
+ def __exit__(
83
+ self,
84
+ exc_type: type[BaseException] | None,
85
+ exc: BaseException | None,
86
+ traceback: TracebackType | None,
87
+ ) -> None:
88
+ self.close()
89
+
90
+ def close(self) -> None:
91
+ self._http.close()
92
+
93
+ def register(
94
+ self,
95
+ *,
96
+ id: str,
97
+ mode: str,
98
+ definition: dict[str, Any] | None = None,
99
+ source: dict[str, Any] | None = None,
100
+ input_schema: dict[str, Any] | None = None,
101
+ ) -> RegisterResult:
102
+ body = _wire.register_body(
103
+ id=id, mode=mode, definition=definition, source=source, input_schema=input_schema
104
+ )
105
+ wire = self._send(_join(self._base_url, "/register"), body, params=None)
106
+ short_code = wire.get("shortCode", "")
107
+ return _wire.register_result(
108
+ wire, fallback_execute_url=_join(self._execute_base_url, f"/execute/{short_code}")
109
+ )
110
+
111
+ def execute(
112
+ self,
113
+ short_code: str,
114
+ *,
115
+ facts: dict[str, Any],
116
+ version: str | None = None,
117
+ lineage: bool = False,
118
+ ) -> ExecuteResult:
119
+ params = {"version": version} if version is not None else None
120
+ wire = self._send(
121
+ _join(self._execute_base_url, f"/execute/{short_code}"),
122
+ _wire.execute_body(facts=facts, lineage=lineage),
123
+ params=params,
124
+ )
125
+ return _wire.execute_result(wire)
126
+
127
+ def _send(self, url: str, body: dict[str, Any], *, params: dict[str, str] | None) -> dict[str, Any]:
128
+ attempt = 0
129
+ while True:
130
+ try:
131
+ response = self._http.post(url, json=body, params=params)
132
+ except httpx.TransportError as failure:
133
+ if attempt >= self._max_retries:
134
+ raise BOEError(f"Could not reach BOE at {url}: {failure}") from failure
135
+ else:
136
+ if response.status_code < 400:
137
+ parsed: dict[str, Any] = response.json()
138
+ return parsed
139
+ if response.status_code not in _RETRYABLE_STATUS_CODES or attempt >= self._max_retries:
140
+ try:
141
+ error_body: Any = response.json()
142
+ except ValueError:
143
+ error_body = None
144
+ raise error_from_response(response.status_code, error_body, response.text)
145
+ time.sleep(_BACKOFF_BASE_SECONDS * (2**attempt))
146
+ attempt += 1
boerules/_errors.py ADDED
@@ -0,0 +1,76 @@
1
+ """Typed errors.
2
+
3
+ Classification order: the body code, then an error value that is a known code,
4
+ then executionRefusalReason, then the status alone.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+
12
+ class BOEError(Exception):
13
+ """A refusal from BOE. Carries the server sentence, status and code."""
14
+
15
+ def __init__(self, message: str, *, status_code: int | None = None, code: str | None = None) -> None:
16
+ super().__init__(message)
17
+ self.message = message
18
+ self.status_code = status_code
19
+ self.code = code
20
+
21
+
22
+ class ProductionKeyCannotRegisterError(BOEError):
23
+ """403 from register: the key is bound to a Production environment."""
24
+
25
+
26
+ class RulesetNotLiveInEnvironmentError(BOEError):
27
+ """404 from execute: nothing is live in the key's environment."""
28
+
29
+
30
+ class RulesetEngineModeMismatchError(BOEError):
31
+ """409 from register: the ruleset holds another engine mode."""
32
+
33
+
34
+ class RulesetArchivedError(BOEError):
35
+ """409 from register or 410 from execute: the ruleset is archived."""
36
+
37
+
38
+ class SubscriptionLapsedError(BOEError):
39
+ """429 from execute: the subscription lapsed."""
40
+
41
+
42
+ class SubscriptionMissingError(BOEError):
43
+ """429 from execute: the account has no subscription."""
44
+
45
+
46
+ ERROR_CLASS_BY_CODE: dict[str, type[BOEError]] = {
47
+ "production_environment_key_cannot_register": ProductionKeyCannotRegisterError,
48
+ "ruleset_not_live_in_environment": RulesetNotLiveInEnvironmentError,
49
+ "RULESET_ENGINE_MODE_MISMATCH": RulesetEngineModeMismatchError,
50
+ "ruleset_archived": RulesetArchivedError,
51
+ "subscription_lapsed": SubscriptionLapsedError,
52
+ "subscription_missing": SubscriptionMissingError,
53
+ }
54
+
55
+
56
+ def error_from_response(status_code: int, body: Any, fallback_text: str) -> BOEError:
57
+ sentence = f"BOE answered HTTP {status_code}"
58
+ code: str | None = None
59
+ if isinstance(body, dict):
60
+ error_value = body.get("error")
61
+ if isinstance(error_value, str) and error_value:
62
+ sentence = error_value
63
+ elif isinstance(body.get("message"), str):
64
+ sentence = body["message"]
65
+ body_code = body.get("code")
66
+ refusal_reason = body.get("executionRefusalReason")
67
+ if isinstance(body_code, str):
68
+ code = body_code
69
+ elif isinstance(error_value, str) and error_value in ERROR_CLASS_BY_CODE:
70
+ code = error_value
71
+ elif isinstance(refusal_reason, str):
72
+ code = refusal_reason
73
+ elif fallback_text:
74
+ sentence = f"{sentence}: {fallback_text[:200]}"
75
+ error_class = ERROR_CLASS_BY_CODE.get(code, BOEError) if code else BOEError
76
+ return error_class(sentence, status_code=status_code, code=code)
boerules/_types.py ADDED
@@ -0,0 +1,29 @@
1
+ """Result dataclasses. Field names are snake case; _wire.py maps the wire names."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class RegisterResult:
11
+ ruleset_id: str
12
+ short_code: str
13
+ engine_mode: str
14
+ version: str
15
+ created: bool
16
+ execute_url: str
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class ExecuteResult:
21
+ execution_id: str
22
+ ruleset: str
23
+ engine_mode: str
24
+ short_code: str
25
+ version: str
26
+ result: Any
27
+ execution_time_ms: float
28
+ total_time_ms: float | None = None
29
+ lineage: dict[str, Any] | None = None
boerules/_wire.py ADDED
@@ -0,0 +1,59 @@
1
+ """The one place wire camelCase names meet Python snake case names."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from ._types import ExecuteResult, RegisterResult
8
+
9
+
10
+ def register_body(
11
+ *,
12
+ id: str,
13
+ mode: str,
14
+ definition: dict[str, Any] | None,
15
+ source: dict[str, Any] | None,
16
+ input_schema: dict[str, Any] | None,
17
+ ) -> dict[str, Any]:
18
+ body: dict[str, Any] = {"id": id, "mode": mode}
19
+ if definition is not None:
20
+ body["definition"] = definition
21
+ if source is not None:
22
+ body["source"] = source
23
+ if input_schema is not None:
24
+ body["inputSchema"] = input_schema
25
+ return body
26
+
27
+
28
+ def execute_body(*, facts: dict[str, Any], lineage: bool) -> dict[str, Any]:
29
+ body: dict[str, Any] = {"facts": facts}
30
+ if lineage:
31
+ body["options"] = {"lineage": True}
32
+ return body
33
+
34
+
35
+ def register_result(wire: dict[str, Any], *, fallback_execute_url: str) -> RegisterResult:
36
+ # A register Lambda deployed before #1114 answers no executeUrl.
37
+ execute_url = wire.get("executeUrl") or fallback_execute_url
38
+ return RegisterResult(
39
+ ruleset_id=wire["rulesetId"],
40
+ short_code=wire["shortCode"],
41
+ engine_mode=wire["engineMode"],
42
+ version=wire["version"],
43
+ created=wire["created"],
44
+ execute_url=execute_url,
45
+ )
46
+
47
+
48
+ def execute_result(wire: dict[str, Any]) -> ExecuteResult:
49
+ return ExecuteResult(
50
+ execution_id=wire["executionId"],
51
+ ruleset=wire["ruleset"],
52
+ engine_mode=wire["engineMode"],
53
+ short_code=wire["shortCode"],
54
+ version=wire["version"],
55
+ result=wire.get("result"),
56
+ execution_time_ms=wire["executionTimeMs"],
57
+ total_time_ms=wire.get("totalTimeMs"),
58
+ lineage=wire.get("lineage"),
59
+ )
boerules/py.typed ADDED
File without changes
@@ -0,0 +1,94 @@
1
+ Metadata-Version: 2.4
2
+ Name: boerules
3
+ Version: 1.0.0
4
+ Summary: Python client for the BOE business rule engine: register and execute.
5
+ Author: BOE
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://boerules.com
8
+ Keywords: boe,business rules,rule engine,decisions,scoring,eligibility,sdk
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: httpx>=0.27
21
+ Dynamic: license-file
22
+
23
+ # boerules
24
+
25
+ Python client for [BOE](https://boerules.com), the business rule engine. Register a ruleset and execute it in under ten lines.
26
+
27
+ ```python
28
+ from boerules import BOE
29
+
30
+ with BOE() as boe: # reads BOE_API_KEY and BOE_BASE_URL
31
+ registered = boe.register(
32
+ id="credit-score", mode="scoring", definition=definition,
33
+ input_schema=input_schema,
34
+ )
35
+ result = boe.execute(registered.short_code, facts={"income": 82000})
36
+ print(registered.execute_url, result.result)
37
+ ```
38
+
39
+ The wire speaks camelCase;
40
+ this client exposes snake case keyword arguments and frozen dataclasses.
41
+
42
+ ## Install
43
+
44
+ ```bash
45
+ pip install boerules
46
+ ```
47
+
48
+ Python 3.10 or later. The one
49
+ runtime dependency is `httpx`.
50
+
51
+ ## Configuration
52
+
53
+ `BOE(api_key=None, base_url=None, execute_base_url=None, timeout_seconds=30.0, max_retries=3)`
54
+
55
+ | Setting | Default |
56
+ |---|---|
57
+ | `api_key` | `BOE_API_KEY` |
58
+ | `base_url` | `BOE_BASE_URL`, else `https://api.boerules.com/v1` |
59
+ | `execute_base_url` | `base_url` |
60
+
61
+ A missing key raises `BOEError` naming `BOE_API_KEY` before any request.
62
+ Network failures, 500, 502, 503 and 504 retry with backoff of 100 ms doubling per attempt.
63
+
64
+ ## Calls
65
+
66
+ - `register(*, id, mode, definition=None, source=None, input_schema=None)` returns `RegisterResult` with `ruleset_id`, `short_code`, `engine_mode`, `version`, `created`, `execute_url`.
67
+ - `execute(short_code, *, facts, version=None, lineage=False)` returns `ExecuteResult` with `execution_id`, `ruleset`, `engine_mode`, `short_code`, `version`, `result`, `execution_time_ms`, `total_time_ms`, `lineage`.
68
+
69
+ ## Errors
70
+
71
+ Every error is a `BOEError` with `message`, `status_code` and `code` (None when the server sent none).
72
+
73
+ | Class | Status | Code |
74
+ |---|---|---|
75
+ | `ProductionKeyCannotRegisterError` | 403, register | `production_environment_key_cannot_register` |
76
+ | `RulesetNotLiveInEnvironmentError` | 404, execute | `ruleset_not_live_in_environment` |
77
+ | `RulesetEngineModeMismatchError` | 409, register | `RULESET_ENGINE_MODE_MISMATCH` |
78
+ | `RulesetArchivedError` | 409 register, 410 execute | `ruleset_archived` |
79
+ | `SubscriptionLapsedError` | 429, execute | `subscription_lapsed` |
80
+ | `SubscriptionMissingError` | 429, execute | `subscription_missing` |
81
+ | `BOEError` | any other | none, or the unknown code |
82
+
83
+ ## Tests
84
+
85
+ ```bash
86
+ python -m unittest discover -s tests
87
+ mypy --strict boerules
88
+ ```
89
+
90
+ The integration test runs when `BOE_API_KEY` is set and skips otherwise.
91
+
92
+ Documentation and API keys: https://boerules.com
93
+
94
+ License: MIT.
@@ -0,0 +1,11 @@
1
+ boerules/__init__.py,sha256=0tc5NMri4ItZkpUxU3bH1TDiiP_vi_xZJEqFmbHcPk8,733
2
+ boerules/_client.py,sha256=AXgcpL6o4pCg9QVjyolPp2NoEZkOO-oT5m5F5F5EDAs,4692
3
+ boerules/_errors.py,sha256=1m9zpCrOa7TWEFzqeaPxSEXQ1RouGQMS4ZGSSf_HjM4,2674
4
+ boerules/_types.py,sha256=fe_ZVprQzSKfEnBYHUXsZTRGycCVHH45cgwyxz51nYU,613
5
+ boerules/_wire.py,sha256=DqM5Wpmz62G8tRydogPnxBooP6VtxJwQh-2lnspK2iw,1771
6
+ boerules/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ boerules-1.0.0.dist-info/licenses/LICENSE,sha256=Pjykg-JStI2u33elR4-eI2gLGcKlMURAy5bjEiXB4-s,1060
8
+ boerules-1.0.0.dist-info/METADATA,sha256=qF9xxkVMv-AooK8BEl09fWyB8jlG_AZjCBq-N2JG8Ro,3295
9
+ boerules-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ boerules-1.0.0.dist-info/top_level.txt,sha256=LJwpldYHDhAJ41QlXroM0cMP7ZNSv8KjuVM9r6rpX6g,9
11
+ boerules-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BOE
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ boerules