ankusa 0.2.4__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.
ankusa/__init__.py ADDED
@@ -0,0 +1,46 @@
1
+ """The ``ankusa`` PyPI package: everything a non-Elixir consumer needs to talk
2
+ to an Ankusa deployment. Today that's the claim-check gateway client
3
+ (``ankusa.claim_check``), the route-management client (``ankusa.routes``), the
4
+ operator client (``ankusa.admin``), and a webhook-receiving header helper
5
+ (``ankusa.webhook``); more clients (ingest) land here as they're built.
6
+ """
7
+
8
+ from .admin import AdminClient, AdminError, AdminRejectedError, AdminUnavailableError, RoleNotEnabledError
9
+ from .claim_check import (
10
+ ClaimCheckClient,
11
+ ClaimCheckError,
12
+ ClaimCheckUnavailableError,
13
+ ClaimIntegrityError,
14
+ ClaimNotFoundError,
15
+ ClaimRejectedError,
16
+ InvalidClaimRefError,
17
+ ParsedClaimRef,
18
+ parse_claim_ref,
19
+ )
20
+ from .routes import RouteNotFoundError, RoutesClient, RoutesError, RoutesRejectedError, RoutesUnavailableError
21
+ from .webhook import HookHeaders, MissingHookIdError, parse_headers
22
+
23
+ __all__ = [
24
+ "AdminClient",
25
+ "AdminError",
26
+ "AdminUnavailableError",
27
+ "RoleNotEnabledError",
28
+ "AdminRejectedError",
29
+ "ClaimCheckClient",
30
+ "ClaimCheckError",
31
+ "ClaimCheckUnavailableError",
32
+ "ClaimIntegrityError",
33
+ "ClaimNotFoundError",
34
+ "ClaimRejectedError",
35
+ "InvalidClaimRefError",
36
+ "ParsedClaimRef",
37
+ "parse_claim_ref",
38
+ "RoutesClient",
39
+ "RoutesError",
40
+ "RoutesUnavailableError",
41
+ "RouteNotFoundError",
42
+ "RoutesRejectedError",
43
+ "HookHeaders",
44
+ "MissingHookIdError",
45
+ "parse_headers",
46
+ ]
@@ -0,0 +1,10 @@
1
+ from .client import AdminClient
2
+ from .errors import AdminError, AdminRejectedError, AdminUnavailableError, RoleNotEnabledError
3
+
4
+ __all__ = [
5
+ "AdminClient",
6
+ "AdminError",
7
+ "AdminUnavailableError",
8
+ "RoleNotEnabledError",
9
+ "AdminRejectedError",
10
+ ]
ankusa/admin/client.py ADDED
@@ -0,0 +1,153 @@
1
+ """Client for the operator listener (``admin.port``, default 4002).
2
+
3
+ This is ``Ankusa.Admin.Router``: health, Prometheus metrics, the redacted
4
+ configuration, the dead-letter queue, and the quarantine list. Responses are
5
+ node-local by design, so a fleet operator scrapes every node's admin port.
6
+
7
+ Like the claim-check client, the listener itself performs no authentication --
8
+ ``headers`` is for whatever a deployer's own boundary (service mesh, an API
9
+ gateway) expects in front of it.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Mapping
15
+ from types import TracebackType
16
+ from typing import Any, Self
17
+
18
+ import httpx
19
+
20
+ from .errors import AdminRejectedError, AdminUnavailableError, RoleNotEnabledError
21
+
22
+ __all__ = ["AdminClient"]
23
+
24
+
25
+ class AdminClient:
26
+ """Operate against the operator API: health, metrics, config, DLQ, quarantine."""
27
+
28
+ def __init__(
29
+ self,
30
+ base_url: str,
31
+ *,
32
+ headers: Mapping[str, str] | None = None,
33
+ timeout: float = 10.0,
34
+ transport: httpx.BaseTransport | None = None,
35
+ ) -> None:
36
+ self._http = httpx.Client(
37
+ base_url=base_url,
38
+ headers=dict(headers) if headers else None,
39
+ timeout=timeout,
40
+ transport=transport,
41
+ )
42
+
43
+ def close(self) -> None:
44
+ self._http.close()
45
+
46
+ def __enter__(self) -> Self:
47
+ return self
48
+
49
+ def __exit__(
50
+ self,
51
+ exc_type: type[BaseException] | None,
52
+ exc: BaseException | None,
53
+ tb: TracebackType | None,
54
+ ) -> None:
55
+ self.close()
56
+
57
+ def health(self) -> dict[str, Any]:
58
+ """Liveness probe: ``GET /health`` -> ``{status, instance, roles}``."""
59
+ return self._json(self._request("GET", "/health"))
60
+
61
+ def metrics(self) -> str:
62
+ """``GET /metrics`` -> the Prometheus text exposition body."""
63
+ return self._request("GET", "/metrics").text
64
+
65
+ def config(self) -> dict[str, Any]:
66
+ """``GET /v1/config`` -> the effective, redacted configuration."""
67
+ return self._json(self._request("GET", "/v1/config"))
68
+
69
+ def list_dead_letters(
70
+ self,
71
+ params: Mapping[str, Any] | None = None,
72
+ ) -> dict[str, Any]:
73
+ """``GET /v1/dlq`` -> a page of dead-lettered hooks, newest first.
74
+
75
+ ``params`` may carry ``source_id``, ``since`` and ``limit``; absent keys
76
+ are omitted from the query string rather than sent as ``=undefined``.
77
+ """
78
+ return self._json(self._request("GET", "/v1/dlq", params=_query(params)))
79
+
80
+ def replay_dead_letters(
81
+ self,
82
+ filter: Mapping[str, Any] | None = None,
83
+ ) -> dict[str, Any]:
84
+ """``POST /v1/dlq/replay`` -> ``{replayed}``.
85
+
86
+ ``filter`` is a filter, not a payload; omitted or empty (``{}``)
87
+ replays everything.
88
+ """
89
+ return self._json(self._request("POST", "/v1/dlq/replay", json=dict(filter or {})))
90
+
91
+ def list_quarantined(
92
+ self,
93
+ params: Mapping[str, Any] | None = None,
94
+ ) -> dict[str, Any]:
95
+ """``GET /v1/quarantine`` -> recent quarantined hooks, newest first.
96
+
97
+ ``params`` may carry ``limit``; absent keys are omitted from the query
98
+ string rather than sent as ``=undefined``.
99
+ """
100
+ return self._json(self._request("GET", "/v1/quarantine", params=_query(params)))
101
+
102
+ def _request(
103
+ self,
104
+ method: str,
105
+ path: str,
106
+ *,
107
+ params: Mapping[str, Any] | None = None,
108
+ json: Mapping[str, Any] | None = None,
109
+ ) -> httpx.Response:
110
+ try:
111
+ response = self._http.request(method, path, params=params, json=json)
112
+ except httpx.HTTPError as err:
113
+ raise AdminUnavailableError(f"admin listener unreachable: {err}", err) from err
114
+ _raise_for_status(response)
115
+ return response
116
+
117
+ @staticmethod
118
+ def _json(response: httpx.Response) -> dict[str, Any]:
119
+ try:
120
+ data: dict[str, Any] = response.json()
121
+ except ValueError as err:
122
+ raise AdminUnavailableError(
123
+ f"admin listener returned a non-JSON body ({response.status_code})", err
124
+ ) from err
125
+ return data
126
+
127
+
128
+ def _query(params: Mapping[str, Any] | None) -> Mapping[str, Any] | None:
129
+ """Drop absent query parameters; ``None`` is not sent at all."""
130
+ if params is None:
131
+ return None
132
+ return {key: value for key, value in params.items() if value is not None}
133
+
134
+
135
+ def _raise_for_status(response: httpx.Response) -> None:
136
+ status = response.status_code
137
+ if 200 <= status < 300:
138
+ return
139
+ body = _error_body(response)
140
+ code = body.get("error") if isinstance(body, dict) else None
141
+ if status == 409 and code == "role_not_enabled":
142
+ role = body.get("role") if isinstance(body, dict) else None
143
+ raise RoleNotEnabledError(f"role not enabled on this node: {role!r}", role)
144
+ if 400 <= status < 500:
145
+ raise AdminRejectedError(f"admin listener rejected the request ({status}): {body!r}", status, code)
146
+ raise AdminUnavailableError(f"admin listener error ({status}): {body!r}")
147
+
148
+
149
+ def _error_body(response: httpx.Response) -> Any:
150
+ try:
151
+ return response.json()
152
+ except ValueError:
153
+ return response.text
ankusa/admin/errors.py ADDED
@@ -0,0 +1,57 @@
1
+ """Every failure the admin client can raise.
2
+
3
+ ``retryable`` is the whole point of this hierarchy, exactly as in the
4
+ claim-check client: a caller (an operator script, a dashboard) needs one bit --
5
+ retry, or surface the rejection -- and nothing here requires it to know the
6
+ operator API's status codes to get that right.
7
+
8
+ Non-retryable: the listener said ``409 role_not_enabled`` (ask another node)
9
+ or another ``4xx`` (a rejected filter). Retryable: the listener said ``5xx``,
10
+ or the request never completed (network error, timeout).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from typing import Any
16
+
17
+
18
+ class AdminError(Exception):
19
+ """Base for every error this client raises. See module docstring."""
20
+
21
+ retryable: bool = False
22
+
23
+
24
+ class AdminUnavailableError(AdminError):
25
+ """The listener is unreachable, or answered ``5xx``. Safe to retry."""
26
+
27
+ retryable = True
28
+
29
+ def __init__(self, message: str, cause: BaseException | None = None) -> None:
30
+ super().__init__(message)
31
+ self.cause = cause
32
+
33
+
34
+ class RoleNotEnabledError(AdminError):
35
+ """The listener returned ``409 role_not_enabled``: this node does not run
36
+ the role the operation needs. Ask another node; ``role`` names it."""
37
+
38
+ retryable = False
39
+
40
+ def __init__(self, message: str, role: Any = None) -> None:
41
+ super().__init__(message)
42
+ self.role = role
43
+
44
+
45
+ class AdminRejectedError(AdminError):
46
+ """The listener rejected the request (any other ``4xx``).
47
+
48
+ ``status`` is the HTTP status; ``code`` is the body's ``error`` field
49
+ (``invalid_filter``, ...).
50
+ """
51
+
52
+ retryable = False
53
+
54
+ def __init__(self, message: str, status: int, code: str | None) -> None:
55
+ super().__init__(message)
56
+ self.status = status
57
+ self.code = code
@@ -0,0 +1,22 @@
1
+ from .client import ClaimCheckClient
2
+ from .errors import (
3
+ ClaimCheckError,
4
+ ClaimCheckUnavailableError,
5
+ ClaimIntegrityError,
6
+ ClaimNotFoundError,
7
+ ClaimRejectedError,
8
+ InvalidClaimRefError,
9
+ )
10
+ from .ref import ParsedClaimRef, parse_claim_ref
11
+
12
+ __all__ = [
13
+ "ClaimCheckClient",
14
+ "ClaimCheckError",
15
+ "ClaimCheckUnavailableError",
16
+ "ClaimIntegrityError",
17
+ "ClaimNotFoundError",
18
+ "ClaimRejectedError",
19
+ "InvalidClaimRefError",
20
+ "ParsedClaimRef",
21
+ "parse_claim_ref",
22
+ ]
@@ -0,0 +1,129 @@
1
+ """Client for the ``:claim_check`` role's read-only byte transport."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import re
7
+ from collections.abc import Mapping
8
+ from types import TracebackType
9
+ from typing import Any, Self
10
+
11
+ import httpx
12
+
13
+ from .errors import (
14
+ ClaimCheckUnavailableError,
15
+ ClaimIntegrityError,
16
+ ClaimNotFoundError,
17
+ ClaimRejectedError,
18
+ InvalidClaimRefError,
19
+ )
20
+ from .ref import ParsedClaimRef, parse_claim_ref
21
+
22
+ __all__ = ["ClaimCheckClient"]
23
+
24
+ _SHA256_PATTERN = re.compile(r"[0-9a-f]{64}")
25
+
26
+
27
+ class ClaimCheckClient:
28
+ """Redeem claim-check refs against a deployment's claim-check gateway.
29
+
30
+ The gateway itself does no authentication or authorization (see
31
+ "docs/claim-check.md") -- ``headers`` is for whatever a deployer's own
32
+ boundary (service mesh, an API gateway) expects in front of it.
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ base_url: str,
38
+ *,
39
+ headers: Mapping[str, str] | None = None,
40
+ timeout: float = 10.0,
41
+ transport: httpx.BaseTransport | None = None,
42
+ ) -> None:
43
+ self._http = httpx.Client(
44
+ base_url=base_url,
45
+ headers=dict(headers) if headers else None,
46
+ timeout=timeout,
47
+ transport=transport,
48
+ )
49
+
50
+ def close(self) -> None:
51
+ self._http.close()
52
+
53
+ def __enter__(self) -> Self:
54
+ return self
55
+
56
+ def __exit__(
57
+ self,
58
+ exc_type: type[BaseException] | None,
59
+ exc: BaseException | None,
60
+ tb: TracebackType | None,
61
+ ) -> None:
62
+ self.close()
63
+
64
+ def redeem(self, ref: str, sha256: str) -> bytes:
65
+ """Redeem a claim-check ref: fetch its bytes and verify them against
66
+ ``sha256`` (the queue message's ``sha256`` field, 64-char lowercase
67
+ hex) before returning. The gateway does
68
+ not check integrity itself -- see "Redeem a claim" in
69
+ docs/claim-check.md -- so this end-to-end check always runs here.
70
+
71
+ Raises a ``ClaimCheckError``; check ``.retryable`` to sort a failure
72
+ into dead-letter (``False``) or retry (``True``).
73
+ """
74
+ parsed = parse_claim_ref(ref)
75
+ if not isinstance(sha256, str) or _SHA256_PATTERN.fullmatch(sha256) is None:
76
+ raise InvalidClaimRefError(f"invalid claim sha256: {sha256!r}")
77
+ body = self._fetch_bytes(parsed)
78
+ _verify_integrity(parsed, sha256, body)
79
+ return body
80
+
81
+ def health(self) -> dict[str, Any]:
82
+ """Liveness probe: ``GET /health``."""
83
+ try:
84
+ response = self._http.get("/health")
85
+ except httpx.HTTPError as err:
86
+ raise ClaimCheckUnavailableError(f"claim-check gateway unreachable: {err}", err) from err
87
+
88
+ if response.status_code != 200:
89
+ raise ClaimCheckUnavailableError(f"claim-check gateway health check failed ({response.status_code})")
90
+ try:
91
+ data: dict[str, Any] = response.json()
92
+ except ValueError as err:
93
+ raise ClaimCheckUnavailableError(
94
+ f"claim-check gateway health check returned a non-JSON body ({response.status_code})", err
95
+ ) from err
96
+ return data
97
+
98
+ def _fetch_bytes(self, parsed: ParsedClaimRef) -> bytes:
99
+ try:
100
+ response = self._http.get(parsed.path)
101
+ except httpx.HTTPError as err:
102
+ raise ClaimCheckUnavailableError(f"claim-check gateway unreachable: {err}", err) from err
103
+
104
+ status = response.status_code
105
+ if status == 404:
106
+ raise ClaimNotFoundError(f"claim not found: {parsed.tenant_id}/{parsed.claim_id}")
107
+ if 400 <= status < 500:
108
+ raise ClaimRejectedError(
109
+ f"claim-check rejected redeem ({status}): {_error_body(response)!r}", status, _error_body(response)
110
+ )
111
+ if status != 200:
112
+ raise ClaimCheckUnavailableError(f"claim-check gateway error ({status}): {_error_body(response)!r}")
113
+ return response.content
114
+
115
+
116
+ def _error_body(response: httpx.Response) -> Any:
117
+ try:
118
+ return response.json()
119
+ except ValueError:
120
+ return response.text
121
+
122
+
123
+ def _verify_integrity(parsed: ParsedClaimRef, expected_sha256: str, body: bytes) -> None:
124
+ """Integrity is checked here, end to end, by the actual redeemer -- never
125
+ trusted from the gateway. Same discipline ``Ankusa.ClaimCheck.redeem/3``
126
+ applies on the Elixir side. A matching sha256 implies the size.
127
+ """
128
+ if hashlib.sha256(body).hexdigest() != expected_sha256:
129
+ raise ClaimIntegrityError(f"claim sha256 mismatch for {parsed.tenant_id}/{parsed.claim_id}")
@@ -0,0 +1,66 @@
1
+ """Every failure the claim-check client can raise.
2
+
3
+ ``retryable`` is the whole point of this hierarchy: a caller (a queue
4
+ consumer, typically) needs exactly one bit -- dead-letter or retry -- and
5
+ nothing here requires it to know the gateway's status codes to get that
6
+ right.
7
+
8
+ Non-retryable: the ref or expected sha256 is malformed, the gateway said
9
+ ``404``/other ``4xx``, or the bytes that came back don't match the sha256.
10
+ Retryable: the gateway said ``5xx``/``503``, or the request never completed
11
+ (network error, timeout).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from typing import Any
17
+
18
+
19
+ class ClaimCheckError(Exception):
20
+ """Base for every error this client raises. See module docstring."""
21
+
22
+ retryable: bool = False
23
+
24
+
25
+ class InvalidClaimRefError(ClaimCheckError):
26
+ """The ref string isn't a ``urn:ankusa:claim:v1:<tenant>:<claim_id>``
27
+ claim-check ref, or the expected sha256 isn't 64-char lowercase hex."""
28
+
29
+ retryable = False
30
+
31
+
32
+ class ClaimNotFoundError(ClaimCheckError):
33
+ """The gateway returned ``404``: no such object, expired by retention or never written."""
34
+
35
+ retryable = False
36
+
37
+
38
+ class ClaimRejectedError(ClaimCheckError):
39
+ """The gateway rejected the request (``400`` or any other non-404 ``4xx``)."""
40
+
41
+ retryable = False
42
+
43
+ def __init__(self, message: str, status: int, body: Any) -> None:
44
+ super().__init__(message)
45
+ self.status = status
46
+ self.body = body
47
+
48
+
49
+ class ClaimIntegrityError(ClaimCheckError):
50
+ """The sha256 of the bytes the gateway returned doesn't match the expected
51
+ sha256 the queue message carries. The gateway itself never checks this -- see
52
+ "Redeem a claim" in docs/claim-check.md -- so this is the reader's own
53
+ end-to-end check, always run before ``redeem()`` returns.
54
+ """
55
+
56
+ retryable = False
57
+
58
+
59
+ class ClaimCheckUnavailableError(ClaimCheckError):
60
+ """The gateway is unreachable, or answered ``5xx``/``503``. Safe to retry."""
61
+
62
+ retryable = True
63
+
64
+ def __init__(self, message: str, cause: BaseException | None = None) -> None:
65
+ super().__init__(message)
66
+ self.cause = cause
@@ -0,0 +1,42 @@
1
+ """Parse a claim-check ref into the path a redeem request needs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+
8
+ from .errors import InvalidClaimRefError
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class ParsedClaimRef:
13
+ """A parsed claim-check ref, ready to become a ``GET /v1/claims/...`` request."""
14
+
15
+ tenant_id: str
16
+ # Canonical (uppercase) ULID.
17
+ claim_id: str
18
+ # ``/v1/claims/{tenant_id}/{claim_id}``.
19
+ path: str
20
+
21
+
22
+ # Mirrors `#/components/schemas/Ref` in priv/openapi/claim_check.v1.yaml --
23
+ # keep the two in sync. A ref is one string:
24
+ # urn:ankusa:claim:v1:<tenant>:<claim_id>
25
+ _REF_PATTERN = re.compile(
26
+ r"^urn:ankusa:claim:v1:"
27
+ r"(?P<tenant_id>[A-Za-z0-9_-]{1,64}):"
28
+ r"(?P<claim_id>[0-7][0-9A-HJKMNP-TV-Z]{25})$"
29
+ )
30
+
31
+
32
+ def parse_claim_ref(ref: str) -> ParsedClaimRef:
33
+ """Parse a claim-check ref (the ``claim`` field of a queue message) into
34
+ the tenant id, claim id, and ``GET /v1/claims/{tenant_id}/{claim_id}``
35
+ path. Raises ``InvalidClaimRefError`` -- never worth retrying -- if
36
+ ``ref`` isn't a well-formed ref.
37
+ """
38
+ match = _REF_PATTERN.fullmatch(ref)
39
+ if match is None:
40
+ raise InvalidClaimRefError(f"invalid claim-check ref: {ref}")
41
+ tenant_id, claim_id = match["tenant_id"], match["claim_id"]
42
+ return ParsedClaimRef(tenant_id=tenant_id, claim_id=claim_id, path=f"/v1/claims/{tenant_id}/{claim_id}")
ankusa/py.typed ADDED
File without changes
@@ -0,0 +1,15 @@
1
+ from .client import RoutesClient
2
+ from .errors import (
3
+ RouteNotFoundError,
4
+ RoutesError,
5
+ RoutesRejectedError,
6
+ RoutesUnavailableError,
7
+ )
8
+
9
+ __all__ = [
10
+ "RoutesClient",
11
+ "RoutesError",
12
+ "RoutesUnavailableError",
13
+ "RouteNotFoundError",
14
+ "RoutesRejectedError",
15
+ ]
@@ -0,0 +1,162 @@
1
+ """Client for the route-management listener (``routes.admin.port``, default 4003).
2
+
3
+ This is the operator surface for the route table the edge enforces:
4
+ ``Ankusa.Routes.Router``. It manages route definitions and the global IP rules,
5
+ and offers a dry run that replays the guard's decision without capturing
6
+ anything.
7
+
8
+ Like the claim-check client, the listener itself performs no authentication --
9
+ ``headers`` is for whatever a deployer's own boundary (service mesh, an API
10
+ gateway) expects in front of it.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from collections.abc import Mapping
16
+ from types import TracebackType
17
+ from typing import Any, Self
18
+
19
+ import httpx
20
+
21
+ from .errors import RouteNotFoundError, RoutesRejectedError, RoutesUnavailableError
22
+
23
+ __all__ = ["RoutesClient"]
24
+
25
+
26
+ class RoutesClient:
27
+ """Manage routes and global IP rules on the route-management listener."""
28
+
29
+ def __init__(
30
+ self,
31
+ base_url: str,
32
+ *,
33
+ headers: Mapping[str, str] | None = None,
34
+ timeout: float = 10.0,
35
+ transport: httpx.BaseTransport | None = None,
36
+ ) -> None:
37
+ self._http = httpx.Client(
38
+ base_url=base_url,
39
+ headers=dict(headers) if headers else None,
40
+ timeout=timeout,
41
+ transport=transport,
42
+ )
43
+
44
+ def close(self) -> None:
45
+ self._http.close()
46
+
47
+ def __enter__(self) -> Self:
48
+ return self
49
+
50
+ def __exit__(
51
+ self,
52
+ exc_type: type[BaseException] | None,
53
+ exc: BaseException | None,
54
+ tb: TracebackType | None,
55
+ ) -> None:
56
+ self.close()
57
+
58
+ def health(self) -> dict[str, Any]:
59
+ """Liveness probe: ``GET /health`` -> ``{status, routes}``."""
60
+ return self._json(self._request("GET", "/health"))
61
+
62
+ def list_routes(
63
+ self,
64
+ params: Mapping[str, Any] | None = None,
65
+ ) -> dict[str, Any]:
66
+ """``GET /admin/routes`` -> a page of route definitions.
67
+
68
+ ``params`` may carry ``enabled``, ``limit`` and ``cursor``; absent keys
69
+ are omitted from the query string rather than sent as ``=undefined``.
70
+ """
71
+ return self._json(self._request("GET", "/admin/routes", params=_query(params)))
72
+
73
+ def create_route(self, input: Mapping[str, Any]) -> dict[str, Any]:
74
+ """``POST /admin/routes`` -> the stored route, timestamps included."""
75
+ return self._json(self._request("POST", "/admin/routes", json=dict(input)))
76
+
77
+ def get_route(self, id: str) -> dict[str, Any]:
78
+ """``GET /admin/routes/{id}`` -> the route."""
79
+ return self._json(self._request("GET", f"/admin/routes/{id}"))
80
+
81
+ def replace_route(self, id: str, input: Mapping[str, Any]) -> dict[str, Any]:
82
+ """``PUT /admin/routes/{id}`` -> the replaced (or created) route."""
83
+ return self._json(self._request("PUT", f"/admin/routes/{id}", json=dict(input)))
84
+
85
+ def update_route(self, id: str, patch: Mapping[str, Any]) -> dict[str, Any]:
86
+ """``PATCH /admin/routes/{id}`` -> the patched route."""
87
+ return self._json(self._request("PATCH", f"/admin/routes/{id}", json=dict(patch)))
88
+
89
+ def delete_route(self, id: str) -> None:
90
+ """``DELETE /admin/routes/{id}`` (``204``, no body)."""
91
+ self._request("DELETE", f"/admin/routes/{id}")
92
+
93
+ def get_ip_rules(self) -> dict[str, Any]:
94
+ """``GET /admin/ip-rules`` -> the global IP rules."""
95
+ return self._json(self._request("GET", "/admin/ip-rules"))
96
+
97
+ def put_ip_rules(self, rules: Mapping[str, Any]) -> dict[str, Any]:
98
+ """``PUT /admin/ip-rules`` -> the stored rules, as parsed."""
99
+ return self._json(self._request("PUT", "/admin/ip-rules", json=dict(rules)))
100
+
101
+ def test_route(self, request: Mapping[str, Any]) -> dict[str, Any]:
102
+ """``POST /admin/routes/test`` -> the dry-run decision for ``request``."""
103
+ return self._json(self._request("POST", "/admin/routes/test", json=dict(request)))
104
+
105
+ def _request(
106
+ self,
107
+ method: str,
108
+ path: str,
109
+ *,
110
+ params: Mapping[str, Any] | None = None,
111
+ json: Mapping[str, Any] | None = None,
112
+ ) -> httpx.Response:
113
+ try:
114
+ response = self._http.request(method, path, params=params, json=json)
115
+ except httpx.HTTPError as err:
116
+ raise RoutesUnavailableError(f"routes listener unreachable: {err}", err) from err
117
+ _raise_for_status(response)
118
+ return response
119
+
120
+ @staticmethod
121
+ def _json(response: httpx.Response) -> dict[str, Any]:
122
+ try:
123
+ data: dict[str, Any] = response.json()
124
+ except ValueError as err:
125
+ raise RoutesUnavailableError(
126
+ f"routes listener returned a non-JSON body ({response.status_code})", err
127
+ ) from err
128
+ return data
129
+
130
+
131
+ def _query(params: Mapping[str, Any] | None) -> Mapping[str, Any] | None:
132
+ """Drop absent query parameters; ``None`` is not sent at all."""
133
+ if params is None:
134
+ return None
135
+ return {key: value for key, value in params.items() if value is not None}
136
+
137
+
138
+ def _raise_for_status(response: httpx.Response) -> None:
139
+ status = response.status_code
140
+ if 200 <= status < 300:
141
+ return
142
+ if status == 404:
143
+ raise RouteNotFoundError(f"route not found ({status})")
144
+ if 400 <= status < 500:
145
+ body = _error_body(response)
146
+ raise RoutesRejectedError(
147
+ f"routes listener rejected the request ({status}): {body!r}",
148
+ status,
149
+ body.get("error") if isinstance(body, dict) else None,
150
+ field=body.get("field") if isinstance(body, dict) else None,
151
+ detail=body.get("message") if isinstance(body, dict) else None,
152
+ conflicting_id=body.get("conflicting_id") if isinstance(body, dict) else None,
153
+ max_routes=body.get("max_routes") if isinstance(body, dict) else None,
154
+ )
155
+ raise RoutesUnavailableError(f"routes listener error ({status}): {_error_body(response)!r}")
156
+
157
+
158
+ def _error_body(response: httpx.Response) -> Any:
159
+ try:
160
+ return response.json()
161
+ except ValueError:
162
+ return response.text
@@ -0,0 +1,69 @@
1
+ """Every failure the routes client can raise.
2
+
3
+ ``retryable`` is the whole point of this hierarchy, exactly as in the
4
+ claim-check client: a caller (an operator script, a controller loop) needs one
5
+ bit -- leave the table alone and retry, or surface the rejection -- and nothing
6
+ here requires it to know the listener's status codes to get that right.
7
+
8
+ Non-retryable: the listener said ``404`` (no such route) or another ``4xx``
9
+ (a rejected write, a duplicate, the cap). Retryable: the listener said
10
+ ``5xx``/``503 store_unavailable``, or the request never completed (network
11
+ error, timeout).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from typing import Any
17
+
18
+
19
+ class RoutesError(Exception):
20
+ """Base for every error this client raises. See module docstring."""
21
+
22
+ retryable: bool = False
23
+
24
+
25
+ class RoutesUnavailableError(RoutesError):
26
+ """The listener is unreachable, or answered ``5xx``/``503``. Safe to retry."""
27
+
28
+ retryable = True
29
+
30
+ def __init__(self, message: str, cause: BaseException | None = None) -> None:
31
+ super().__init__(message)
32
+ self.cause = cause
33
+
34
+
35
+ class RouteNotFoundError(RoutesError):
36
+ """The listener returned ``404``: no such route."""
37
+
38
+ retryable = False
39
+
40
+
41
+ class RoutesRejectedError(RoutesError):
42
+ """The listener rejected the request (``400`` or any other non-404 ``4xx``).
43
+
44
+ ``code`` is the body's ``error`` field (``invalid_route``,
45
+ ``duplicate_route``, ``too_many_routes``, ...); ``field``, ``message``,
46
+ ``conflicting_id`` and ``max_routes`` are carried through when the body
47
+ supplies them.
48
+ """
49
+
50
+ retryable = False
51
+
52
+ def __init__(
53
+ self,
54
+ message: str,
55
+ status: int,
56
+ code: str | None,
57
+ *,
58
+ field: Any = None,
59
+ detail: Any = None,
60
+ conflicting_id: Any = None,
61
+ max_routes: Any = None,
62
+ ) -> None:
63
+ super().__init__(message)
64
+ self.status = status
65
+ self.code = code
66
+ self.field = field
67
+ self.message = detail
68
+ self.conflicting_id = conflicting_id
69
+ self.max_routes = max_routes
ankusa/webhook.py ADDED
@@ -0,0 +1,73 @@
1
+ """Parse the headers Ankusa's HTTP sink attaches to every delivery.
2
+
3
+ See "HTTP handoff" in docs/integrations.md for the full contract this
4
+ mirrors: the raw body arrives verbatim, and identity travels in
5
+ ``x-ankusa-id``, ``x-ankusa-source``, ``x-ankusa-seq``, ``x-ankusa-tenant``
6
+ (only when the source has a tenant), and ``content-type``. A receiver must
7
+ dedupe on ``x-ankusa-id``: delivery is at-least-once, so the same hook can
8
+ arrive twice after a retry.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from collections.abc import Mapping
15
+ from dataclasses import dataclass
16
+
17
+ __all__ = ["HookHeaders", "MissingHookIdError", "parse_headers"]
18
+
19
+ # ``str.isdigit()`` accepts non-ASCII digits (``"²".isdigit()`` is True) that
20
+ # ``int()`` then rejects. The header is a sequence number, so only ASCII
21
+ # digits count.
22
+ _SEQ_PATTERN = re.compile(r"[0-9]+")
23
+
24
+
25
+ class MissingHookIdError(ValueError):
26
+ """Raised by ``parse_headers`` when ``x-ankusa-id`` is absent.
27
+
28
+ Every other Ankusa header is optional; this one is the identity a
29
+ receiver dedupes on, so a delivery without it is a framework bug, not a
30
+ malformed but tolerable request.
31
+ """
32
+
33
+
34
+ @dataclass(frozen=True, slots=True)
35
+ class HookHeaders:
36
+ """The identity of one HTTP-sink delivery."""
37
+
38
+ id: str
39
+ source: str
40
+ # 1-based, monotonically increasing per source. ``None`` if the header
41
+ # was absent or not an integer.
42
+ seq: int | None
43
+ # Only present when the source has a tenant.
44
+ tenant: str | None
45
+ content_type: str | None
46
+
47
+
48
+ def parse_headers(headers: Mapping[str, str]) -> HookHeaders:
49
+ """Parse the ``x-ankusa-*`` headers of one delivery.
50
+
51
+ ``headers`` may be any case-insensitive-or-not header mapping --
52
+ ``http.server.BaseHTTPRequestHandler.headers``, an ``httpx.Headers``, a
53
+ plain ``dict`` from a WSGI/ASGI framework -- lookup here is always
54
+ case-insensitive regardless of what the mapping itself does.
55
+
56
+ Raises ``MissingHookIdError`` if ``x-ankusa-id`` is absent.
57
+ """
58
+ lowered = {key.lower(): value for key, value in headers.items()}
59
+
60
+ hook_id = lowered.get("x-ankusa-id")
61
+ if not hook_id:
62
+ raise MissingHookIdError("missing x-ankusa-id header")
63
+
64
+ seq_raw = lowered.get("x-ankusa-seq")
65
+ seq = int(seq_raw) if seq_raw is not None and _SEQ_PATTERN.fullmatch(seq_raw) else None
66
+
67
+ return HookHeaders(
68
+ id=hook_id,
69
+ source=lowered.get("x-ankusa-source", ""),
70
+ seq=seq,
71
+ tenant=lowered.get("x-ankusa-tenant"),
72
+ content_type=lowered.get("content-type"),
73
+ )
@@ -0,0 +1,223 @@
1
+ Metadata-Version: 2.5
2
+ Name: ankusa
3
+ Version: 0.2.4
4
+ Summary: Client SDK for Ankusa deployments. Bundles the claim-check gateway client, the route-management and operator (admin) clients, and a webhook-receiving header helper; more clients (ingest) land here as they're built.
5
+ Project-URL: Repository, https://github.com/jamescarr/ankusa
6
+ Project-URL: Homepage, https://github.com/jamescarr/ankusa/tree/main/packages/sdk-python
7
+ Project-URL: Issues, https://github.com/jamescarr/ankusa/issues
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: admin,ankusa,claim-check,routes,webhook
11
+ Requires-Python: >=3.11
12
+ Requires-Dist: httpx>=0.27
13
+ Description-Content-Type: text/markdown
14
+
15
+ # ankusa
16
+
17
+ The client SDK for [Ankusa](https://github.com/jamescarr/ankusa) deployments:
18
+ one PyPI package meant to bundle everything a non-Elixir consumer needs to
19
+ talk to an Ankusa deployment. Today that's the
20
+ [claim-check gateway](https://github.com/jamescarr/ankusa/blob/main/docs/claim-check.md)
21
+ client and a webhook-receiving header helper; more clients (ingest, admin)
22
+ land here as they're built.
23
+
24
+ ## Install
25
+
26
+ Not published yet. Until the first release, depend on it as a local path,
27
+ the same way the Elixir packages in this monorepo depend on `ankusa` core
28
+ before their first Hex release, and `packages/sdk-typescript` depends on
29
+ itself via `file:`.
30
+
31
+ With [`uv`](https://docs.astral.sh/uv/):
32
+
33
+ ```toml
34
+ [project]
35
+ dependencies = ["ankusa"]
36
+
37
+ [tool.uv.sources]
38
+ ankusa = { path = "../../packages/sdk-python" }
39
+ ```
40
+
41
+ Or with plain `pip`:
42
+
43
+ ```sh
44
+ pip install -e ../../packages/sdk-python
45
+ ```
46
+
47
+ ## Claim-check client
48
+
49
+ Redeem a claim-check ref, verify the bytes it returns against the message's
50
+ `sha256`, and classify failures into dead-letter vs. retry,
51
+ without holding any object-store credentials. Conforms to the framework's
52
+ own contract, [`priv/openapi/claim_check.v1.yaml`](../ankusa/priv/openapi/claim_check.v1.yaml):
53
+ the spec is the source of truth, this package conforms to it, not the
54
+ reverse.
55
+
56
+ ```python
57
+ import os
58
+
59
+ from ankusa import ClaimCheckClient, ClaimCheckError
60
+
61
+ claim_check = ClaimCheckClient(os.environ.get("CLAIM_CHECK_URL", "http://localhost:4001"))
62
+
63
+ # A queue message that carries a claim also carries its sha256:
64
+ # "claim": "urn:ankusa:claim:v1:<tenant>:<claim_id>" (claim_id: uppercase ULID)
65
+ # "sha256": 64-char lowercase hex of the claim's bytes
66
+ def resolve_body(message: dict) -> bytes:
67
+ try:
68
+ return claim_check.redeem(message["claim"], message["sha256"])
69
+ except ClaimCheckError as err:
70
+ if not err.retryable:
71
+ # bad ref/sha256, 404, or an integrity mismatch: dead-letter, don't requeue
72
+ raise
73
+ # gateway unreachable or 5xx: safe to retry
74
+ raise
75
+ ```
76
+
77
+ `redeem()` does three things `GET /v1/claims/...` alone doesn't:
78
+
79
+ 1. Parses the ref into its tenant id, claim id, and gateway path
80
+ (`GET /v1/claims/{tenant_id}/{claim_id}`) (`parse_claim_ref`, also
81
+ exported standalone).
82
+ 2. Fetches the bytes.
83
+ 3. Verifies them against the message's `sha256` (the gateway
84
+ itself does not check this, see "Redeem a claim" in
85
+ [`docs/claim-check.md`](https://github.com/jamescarr/ankusa/blob/main/docs/claim-check.md))
86
+ before ever returning them to you.
87
+
88
+ Every failure is a `ClaimCheckError` subclass with a `retryable` attribute,
89
+ so a consumer needs exactly one bit to decide dead-letter vs. retry:
90
+
91
+ | Class | `retryable` | Cause |
92
+ | --- | --- | --- |
93
+ | `InvalidClaimRefError` | `False` | `ref` isn't a well-formed claim-check URN, or `sha256` isn't 64-char lowercase hex |
94
+ | `ClaimNotFoundError` | `False` | gateway `404`: expired by retention, or never written |
95
+ | `ClaimRejectedError` | `False` | gateway `4xx` other than `404` (`.status`, `.body`) |
96
+ | `ClaimIntegrityError` | `False` | sha256 of the returned bytes doesn't match |
97
+ | `ClaimCheckUnavailableError` | `True` | gateway `5xx`/`503`, or unreachable |
98
+
99
+ `health()` hits `GET /health` for a liveness probe.
100
+
101
+ `ClaimCheckClient` owns an `httpx.Client`; use it as a context manager
102
+ (`with ClaimCheckClient(...) as claim_check:`) or call `.close()` yourself
103
+ when done.
104
+
105
+ ## Webhook receiver helper
106
+
107
+ Every receiver of Ankusa's HTTP sink needs the same handful of headers off
108
+ each request; `parse_headers` replaces the hand-rolled `self.headers.get(...)`
109
+ calls with one call and a typed result:
110
+
111
+ ```python
112
+ from ankusa import MissingHookIdError, parse_headers
113
+
114
+ def do_POST(self):
115
+ try:
116
+ hook = parse_headers(self.headers)
117
+ except MissingHookIdError:
118
+ self.send_response(400)
119
+ self.end_headers()
120
+ return
121
+
122
+ body = self.rfile.read(int(self.headers.get("content-length", "0")))
123
+ # hook.id, hook.source, hook.seq, hook.tenant, hook.content_type
124
+ ...
125
+ ```
126
+
127
+ `HookHeaders.id` is what a receiver dedupes on: delivery is at-least-once
128
+ (see "HTTP handoff" in
129
+ [`docs/integrations.md`](https://github.com/jamescarr/ankusa/blob/main/docs/integrations.md)),
130
+ so the same hook can arrive twice after a retry. Header lookup is always
131
+ case-insensitive, regardless of whether the mapping passed in already is.
132
+
133
+ [`examples/quickstart/worker.py`](https://github.com/jamescarr/ankusa/tree/main/examples/quickstart/worker.py)
134
+ uses this.
135
+
136
+ ## Routes client
137
+
138
+ Manage route definitions and the global IP rules on the route-management
139
+ listener (`routes.admin.port`, default 4003) — the `routes` tag of
140
+ [`priv/openapi/admin.v1.yaml`](../ankusa/priv/openapi/admin.v1.yaml).
141
+
142
+ ```python
143
+ import os
144
+
145
+ from ankusa import RoutesClient
146
+
147
+ routes = RoutesClient(os.environ.get("ROUTES_URL", "http://localhost:4003"))
148
+
149
+ routes.create_route({"id": "stripe", "path": "/webhooks/stripe"})
150
+ routes.get_ip_rules() # {"default": "allow", "rules": []}
151
+ routes.test_route({"method": "POST", "path": "/webhooks/stripe", "ip": "203.0.113.7"})
152
+ ```
153
+
154
+ Methods: `health()`, `list_routes()`, `create_route()`, `get_route()`,
155
+ `replace_route()`, `update_route()`, `delete_route()`, `get_ip_rules()`,
156
+ `put_ip_rules()`, `test_route()`. Failures are `RoutesError` subclasses with a
157
+ `retryable` attribute: `RouteNotFoundError` (404), `RoutesRejectedError`
158
+ (400/409, carrying `code`, `field`, `message`, `conflicting_id`,
159
+ `max_routes`), and `RoutesUnavailableError` (5xx/unreachable, retryable).
160
+
161
+ ## Admin client
162
+
163
+ The operator API on `admin.port` (default 4002): health, Prometheus metrics,
164
+ the redacted config, the DLQ, and the quarantine list — the `operations`,
165
+ `dlq`, and `quarantine` tags of `admin.v1.yaml`.
166
+
167
+ ```python
168
+ import os
169
+
170
+ from ankusa import AdminClient
171
+
172
+ admin = AdminClient(os.environ.get("ADMIN_URL", "http://localhost:4002"))
173
+
174
+ admin.health() # {"status": "ok", "instance": ..., "roles": [...]}
175
+ admin.list_dead_letters(limit=10)
176
+ admin.replay_dead_letters({"source_id": "demo"})
177
+ admin.list_quarantined()
178
+ ```
179
+
180
+ Methods: `health()`, `metrics()` (Prometheus text), `config()`,
181
+ `list_dead_letters()`, `replay_dead_letters()`, `list_quarantined()`. Failures
182
+ are `AdminError` subclasses: `RoleNotEnabledError` (409, carrying `role`),
183
+ `AdminRejectedError` (400, carrying `code`), and `AdminUnavailableError`
184
+ (5xx/unreachable, retryable).
185
+
186
+ ## Layout
187
+
188
+ ```
189
+ src/ankusa/
190
+ __init__.py # umbrella barrel: re-exports every client this package bundles
191
+ py.typed
192
+ webhook.py # x-ankusa-* header parsing for HTTP-sink receivers
193
+ claim_check/ # the claim-check gateway client
194
+ __init__.py # barrel for this client
195
+ client.py
196
+ ref.py
197
+ errors.py
198
+ routes/ # the route-management client (routes.admin.port)
199
+ __init__.py
200
+ client.py
201
+ errors.py
202
+ admin/ # the operator client (admin.port)
203
+ __init__.py
204
+ client.py
205
+ errors.py
206
+ tests/
207
+ test_client.py
208
+ test_ref.py
209
+ test_webhook.py
210
+ test_routes.py
211
+ test_admin.py
212
+ ```
213
+
214
+ A future client (say, an ingest helper) gets its own `src/ankusa/<name>/`
215
+ directory with the same shape, re-exported from `src/ankusa/__init__.py`.
216
+
217
+ ## Develop
218
+
219
+ ```sh
220
+ uv sync
221
+ uv run pytest
222
+ uv run mypy
223
+ ```
@@ -0,0 +1,17 @@
1
+ ankusa/__init__.py,sha256=z9SDL67EU4gOZcVlQCd2ocVc_XS-_4iMW46GGUqO7jA,1463
2
+ ankusa/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ ankusa/webhook.py,sha256=jB8v9_5GBEk7xOJkJryXOhbVA8Mkvbdar1_GfYkF8Xc,2538
4
+ ankusa/admin/__init__.py,sha256=kU6Wvuj56TymuYHUeApjkEn1ZYbHlTUg8URN3jIa3sE,261
5
+ ankusa/admin/client.py,sha256=a5lZ6sxEQJhKrZNA1Glzb6BMhC0kERBtCzRj-ZU-O6w,5223
6
+ ankusa/admin/errors.py,sha256=7I2vzKQaq8oH_1wipAbmAzBGjTQelTMp68S-cvv_dgw,1758
7
+ ankusa/claim_check/__init__.py,sha256=5dNdSHFZHTu2ZdTXSkwNyQOdvsXmRndz31jDPu6AdAo,510
8
+ ankusa/claim_check/client.py,sha256=ZVW_BzpG7MQNqpRE4rLN_ZgeRpbpKy3FDPqiDQVEHFQ,4569
9
+ ankusa/claim_check/errors.py,sha256=Hcm2nuI0G1pKELntTIwf7zJ2naX5qc5fuq1M_EPxfc8,2097
10
+ ankusa/claim_check/ref.py,sha256=Iwtfrzbj8TRAn8WKRObtG-zS0k9fxW5F-JkhEX9w4ZI,1411
11
+ ankusa/routes/__init__.py,sha256=4eoeDOxA5b2L2CduhmZn0u9uUJBz2tzx05HB-3zP5g0,288
12
+ ankusa/routes/client.py,sha256=4-_s8fd8g2O1kBkzb0ftigJpKuPHoN1KGR9YIUSfuoY,6065
13
+ ankusa/routes/errors.py,sha256=GD8R2IJn41TL0CcqzW6c1uTKMjQMWXC3xoDmmrjhpiE,2067
14
+ ankusa-0.2.4.dist-info/METADATA,sha256=laTRaVu7fQsPYWitVo8KnUq_Mr9FMD1OibgJ5j_9S7Q,7934
15
+ ankusa-0.2.4.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
16
+ ankusa-0.2.4.dist-info/licenses/LICENSE,sha256=ZUmR1tsfqQz1HvqUaYpc0YWYuvsgBGBg6TLP373Kbd8,10768
17
+ ankusa-0.2.4.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,190 @@
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
44
+ purposes of this License, Derivative Works shall not include works
45
+ that remain separable from, or merely link (or bind by name) to the
46
+ interfaces of, the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including the
49
+ 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
141
+ the 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
+ Copyright 2026 The Ankusa Contributors
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.