ark-watch-client 0.1.0__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,4 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ dist/
4
+ build/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Immanuel R
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,56 @@
1
+ Metadata-Version: 2.5
2
+ Name: ark-watch-client
3
+ Version: 0.1.0
4
+ Summary: ARK-RAPID Watch client: log() never blocks and never raises; batches, compresses, spools to disk and replays.
5
+ Project-URL: Homepage, https://github.com/ir-dev/ark-net-audit/tree/main/Ark.Audit.v2
6
+ Author: Immanuel R
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Keywords: ark-watch-client,audit,audit-log,audit-trail,tamper-evident
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: System :: Logging
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+
16
+ # ark-watch-client (Python)
17
+
18
+ The ARK-RAPID Watch client for Python 3.9+, with no dependencies. `log()` puts the event in a bounded in-memory ring and
19
+ returns: it never blocks on the network and never raises. Background threads batch events, compress them and send them to
20
+ `POST /v1/events`; while the server is unreachable they go to a disk spool and are replayed in order when it is back.
21
+ When ring and spool are both full, the drop policy applies and every drop is counted and reported to the server.
22
+
23
+ ```bash
24
+ pip install ark-watch-client # or: uv add ark-watch-client
25
+ ```
26
+
27
+ ```python
28
+ import os
29
+ from ark_watch_client import AuditClient, AuditLevel, Outcome
30
+
31
+ audit = AuditClient(
32
+ "https://audit.example.com",
33
+ api_key=os.environ["ARK_WATCH_API_KEY"], # a secret key from Admin -> Applications; never in source
34
+ application="orders-api", environment="prod", app_version="2.3.1",
35
+ spool_directory="/var/lib/orders-api/audit-spool", # optional, recommended: survives restarts and outages
36
+ )
37
+
38
+ audit.log(AuditLevel.NOTICE, "invoice.approve", "Invoice approved",
39
+ participant_id="u-42", resource_type="invoice", resource_id="inv-1001",
40
+ correlation_id=request_id, attributes={"amount": 125.5, "currency": "EUR"})
41
+
42
+ audit.close() # at shutdown: flushes what is buffered (also `with AuditClient(...) as audit:`)
43
+ ```
44
+
45
+ - **Fields filled in for you:** event id (a ULID), time, host, IP, application, version, environment, and the participant
46
+ (this process as a `service` when you give none).
47
+ - **Privacy:** secret-looking attribute keys (`password`, `token`, `api_key`, ...) are masked to `***`, card numbers and
48
+ bearer tokens in text are replaced, and the event lists what was masked (`redactions`); the server applies its policy too.
49
+ - **Options** (keyword arguments): `ring_capacity` (8192), `batch_size` (500), `flush_interval` (0.2 s),
50
+ `spool_max_bytes` (256 MB), `drop_policy` (`DropPolicy.DROP_OLDEST`, `DROP_NEWEST`, `SAMPLE_DEBUG`), `request_timeout`
51
+ (10 s), `breaker_failure_threshold`, `breaker_base_delay`, `breaker_max_delay`.
52
+ - **Health:** `audit.stats()` returns logged, sent, spooled, replayed, dropped (by reason), rejected, internal errors and
53
+ the breaker's state.
54
+
55
+ It behaves like the .NET SDK, and the shared conformance suite (`tests/Ark.Watch.Conformance.Tests`) runs the same
56
+ scenarios against both through `python -m ark_watch_client.conformance`. Unit tests: `python3 -m unittest discover tests`.
@@ -0,0 +1,41 @@
1
+ # ark-watch-client (Python)
2
+
3
+ The ARK-RAPID Watch client for Python 3.9+, with no dependencies. `log()` puts the event in a bounded in-memory ring and
4
+ returns: it never blocks on the network and never raises. Background threads batch events, compress them and send them to
5
+ `POST /v1/events`; while the server is unreachable they go to a disk spool and are replayed in order when it is back.
6
+ When ring and spool are both full, the drop policy applies and every drop is counted and reported to the server.
7
+
8
+ ```bash
9
+ pip install ark-watch-client # or: uv add ark-watch-client
10
+ ```
11
+
12
+ ```python
13
+ import os
14
+ from ark_watch_client import AuditClient, AuditLevel, Outcome
15
+
16
+ audit = AuditClient(
17
+ "https://audit.example.com",
18
+ api_key=os.environ["ARK_WATCH_API_KEY"], # a secret key from Admin -> Applications; never in source
19
+ application="orders-api", environment="prod", app_version="2.3.1",
20
+ spool_directory="/var/lib/orders-api/audit-spool", # optional, recommended: survives restarts and outages
21
+ )
22
+
23
+ audit.log(AuditLevel.NOTICE, "invoice.approve", "Invoice approved",
24
+ participant_id="u-42", resource_type="invoice", resource_id="inv-1001",
25
+ correlation_id=request_id, attributes={"amount": 125.5, "currency": "EUR"})
26
+
27
+ audit.close() # at shutdown: flushes what is buffered (also `with AuditClient(...) as audit:`)
28
+ ```
29
+
30
+ - **Fields filled in for you:** event id (a ULID), time, host, IP, application, version, environment, and the participant
31
+ (this process as a `service` when you give none).
32
+ - **Privacy:** secret-looking attribute keys (`password`, `token`, `api_key`, ...) are masked to `***`, card numbers and
33
+ bearer tokens in text are replaced, and the event lists what was masked (`redactions`); the server applies its policy too.
34
+ - **Options** (keyword arguments): `ring_capacity` (8192), `batch_size` (500), `flush_interval` (0.2 s),
35
+ `spool_max_bytes` (256 MB), `drop_policy` (`DropPolicy.DROP_OLDEST`, `DROP_NEWEST`, `SAMPLE_DEBUG`), `request_timeout`
36
+ (10 s), `breaker_failure_threshold`, `breaker_base_delay`, `breaker_max_delay`.
37
+ - **Health:** `audit.stats()` returns logged, sent, spooled, replayed, dropped (by reason), rejected, internal errors and
38
+ the breaker's state.
39
+
40
+ It behaves like the .NET SDK, and the shared conformance suite (`tests/Ark.Watch.Conformance.Tests`) runs the same
41
+ scenarios against both through `python -m ark_watch_client.conformance`. Unit tests: `python3 -m unittest discover tests`.
@@ -0,0 +1,33 @@
1
+ # ark-watch-client (Python SDK) -> PyPI. Verified 2026-11-22 with uv 0.12.7 and Python 3.9.6.
2
+ #
3
+ # Normal path: the release workflow (.github/workflows/ark-watch-release.yml) builds this package at the release
4
+ # version and publishes it with PyPI Trusted Publishing (OIDC): no token exists anywhere. One-time setup on pypi.org:
5
+ # Account -> Publishing -> Add a new pending publisher
6
+ # PyPI project name ark-watch-client
7
+ # Owner ir-dev
8
+ # Repository name ark-net-audit
9
+ # Workflow name ark-watch-release.yml
10
+ # Environment name release
11
+ #
12
+ # Everything below is for checking a build locally; none of it publishes.
13
+
14
+ cd /Users/Immanuel.Raj/Immi/git_src/ark-net-audit/Ark.Audit.v2/sdks/python
15
+
16
+ # 1. Tests (stdlib unittest; no dependencies). The latency test needs a quiet machine.
17
+ python3 -m unittest discover -s tests -v
18
+
19
+ # 2. The conformance suite (all three SDKs, from Ark.Audit.v2):
20
+ # dotnet test --project tests/Ark.Watch.Conformance.Tests
21
+
22
+ # 3. Build the sdist and the wheel outside the tree. The version in pyproject.toml is the one that ships: every package
23
+ # shares it, set with `scripts/version.sh set X.Y.Z` from Ark.Audit.v2 and checked by the release workflow (ADR 0021).
24
+ uv build --out-dir /tmp/ark-watch-client-pypi
25
+
26
+ # 4. Install the wheel in a throwaway venv and import it.
27
+ uv venv /tmp/ark-watch-client-venv -p python3
28
+ uv pip install --python /tmp/ark-watch-client-venv/bin/python /tmp/ark-watch-client-pypi/ark_watch_client-*.whl
29
+ /tmp/ark-watch-client-venv/bin/python -I -c "import ark_watch_client as a; print(a.__version__)"
30
+
31
+ # Manual publish (only if Trusted Publishing is not set up yet, and with a token you enter at the prompt; never write
32
+ # it into a file in this repository):
33
+ # uv publish /tmp/ark-watch-client-pypi/*
@@ -0,0 +1,25 @@
1
+ [project]
2
+ name = "ark-watch-client"
3
+ version = "0.1.0"
4
+ description = "ARK-RAPID Watch client: log() never blocks and never raises; batches, compresses, spools to disk and replays."
5
+ readme = "README.md"
6
+ requires-python = ">=3.9"
7
+ license = "MIT"
8
+ authors = [{ name = "Immanuel R" }]
9
+ keywords = ["audit", "audit-log", "audit-trail", "tamper-evident", "ark-watch-client"]
10
+ classifiers = [
11
+ "Programming Language :: Python :: 3",
12
+ "Operating System :: OS Independent",
13
+ "Topic :: System :: Logging",
14
+ ]
15
+ dependencies = []
16
+
17
+ [project.urls]
18
+ Homepage = "https://github.com/ir-dev/ark-net-audit/tree/main/Ark.Audit.v2"
19
+
20
+ [build-system]
21
+ requires = ["hatchling>=1.26"]
22
+ build-backend = "hatchling.build"
23
+
24
+ [tool.hatch.build.targets.wheel]
25
+ packages = ["src/ark_watch_client"]
@@ -0,0 +1,6 @@
1
+ """ARK-RAPID Watch client for Python: ``log`` never blocks and never raises; events ship in the background."""
2
+ from ._pii import PiiPolicy
3
+ from .client import SDK_VERSION as __version__
4
+ from .client import AuditClient, AuditLevel, ClientStats, DropPolicy, DropReason, Outcome
5
+
6
+ __all__ = ["AuditClient", "AuditLevel", "ClientStats", "DropPolicy", "DropReason", "Outcome", "PiiPolicy", "__version__"]
@@ -0,0 +1,74 @@
1
+ """The client-side PII policy, the same defaults as the .NET SDK and the server (brief 3: masked at the SDK and the server)."""
2
+ import hashlib
3
+ import re
4
+ from typing import Any, List, Optional, Tuple
5
+
6
+ MASK = "***"
7
+ _KEY = re.compile(
8
+ r"^(password|passwd|pwd|pass_phrase|passphrase|secret|client_secret|token|access_token|refresh_token|id_token"
9
+ r"|api[_-]?key|authorization|cookie|set-cookie|ssn|card_?number|cvv|cvc)$",
10
+ re.IGNORECASE,
11
+ )
12
+ _CARD = re.compile(r"\b(?:\d[ -]?){12,18}\d\b")
13
+ _BEARER = re.compile(r"\bbearer\s+[a-z0-9._~+/\-]+=*", re.IGNORECASE)
14
+
15
+
16
+ def _luhn(candidate: str) -> bool:
17
+ digits = [int(c) for c in candidate if c.isdigit()]
18
+ if len(digits) < 13:
19
+ return False
20
+ total = 0
21
+ for i, d in enumerate(reversed(digits)):
22
+ if i % 2 == 1:
23
+ d *= 2
24
+ if d > 9:
25
+ d -= 9
26
+ total += d
27
+ return total % 10 == 0
28
+
29
+
30
+ def pseudonym(value: str) -> str:
31
+ return "sha256:" + hashlib.sha256(value.encode("utf-8")).hexdigest()[:32]
32
+
33
+
34
+ class PiiPolicy:
35
+ """Masks secret-looking keys anywhere in attributes, and card numbers and bearer tokens in text; records what it masked."""
36
+
37
+ def __init__(self, key_pattern: Optional[str] = None, use_defaults: bool = True):
38
+ self._key = re.compile(key_pattern, re.IGNORECASE) if key_pattern else (_KEY if use_defaults else None)
39
+ self._patterns: List[Tuple[re.Pattern, str, bool]] = (
40
+ [(_CARD, "[card]", True), (_BEARER, "Bearer [redacted]", False)] if use_defaults else []
41
+ )
42
+
43
+ def text(self, value: str) -> str:
44
+ current = value
45
+ for regex, replacement, luhn in self._patterns:
46
+ current = regex.sub(lambda m: replacement if (not luhn or _luhn(m.group(0))) else m.group(0), current)
47
+ return current
48
+
49
+ def attributes(self, value: Any, path: str, redactions: List[str], depth: int = 0) -> Any:
50
+ if depth > 16:
51
+ return "[depth limit]"
52
+ if isinstance(value, dict):
53
+ out = {}
54
+ for k, v in value.items():
55
+ key = str(k)
56
+ child = path + "." + key
57
+ if self._key is not None and self._key.match(key):
58
+ redactions.append(child)
59
+ out[key] = MASK
60
+ else:
61
+ out[key] = self.attributes(v, child, redactions, depth + 1)
62
+ return out
63
+ if isinstance(value, (list, tuple)):
64
+ return [self.attributes(v, path + "[]", redactions, depth + 1) for v in value]
65
+ if isinstance(value, str):
66
+ masked = self.text(value)
67
+ if masked != value:
68
+ redactions.append(path)
69
+ return masked
70
+ if isinstance(value, bool) or value is None or isinstance(value, (int, float)):
71
+ if isinstance(value, float) and (value != value or value in (float("inf"), float("-inf"))):
72
+ return None
73
+ return value
74
+ return str(value)
@@ -0,0 +1,163 @@
1
+ """
2
+ The disk spool (brief 2.1): append-only segment files, a CRC per record, a size cap, replay in order. It is used only by the
3
+ SDK's background threads, never by the caller's.
4
+
5
+ Record: length (u32 LE), CRC-32 of the body (u32 LE), event count (u32 LE), then the body (a gzip batch). The position of
6
+ the oldest record not yet delivered is kept in ``ack`` (written to a temporary file, fsynced, then renamed). A record cut
7
+ short by a crash fails its length or CRC check and is truncated away on open.
8
+ """
9
+ import os
10
+ import struct
11
+ import threading
12
+ import zlib
13
+ from dataclasses import dataclass
14
+ from typing import List, Optional, Tuple
15
+
16
+ _HEADER = struct.Struct("<III")
17
+
18
+
19
+ @dataclass
20
+ class SpoolRecord:
21
+ segment: int
22
+ offset: int
23
+ size: int
24
+ count: int
25
+ body: bytes
26
+
27
+
28
+ class Spool:
29
+ def __init__(self, directory: str, max_bytes: int, segment_bytes: int):
30
+ self._dir = directory
31
+ self._max = max(64 * 1024, max_bytes)
32
+ self._segment_bytes = max(16 * 1024, segment_bytes)
33
+ self._lock = threading.Lock()
34
+ self._records: List[Tuple[int, int, int, int]] = [] # (segment, offset, size on disk, count), unacked, oldest first
35
+ self._segments: List[int] = []
36
+ os.makedirs(directory, exist_ok=True)
37
+ self._open()
38
+
39
+ # ------------------------------------------------------------------ state
40
+
41
+ @property
42
+ def has_pending(self) -> bool:
43
+ with self._lock:
44
+ return bool(self._records)
45
+
46
+ @property
47
+ def pending_batches(self) -> int:
48
+ with self._lock:
49
+ return len(self._records)
50
+
51
+ @property
52
+ def bytes(self) -> int:
53
+ with self._lock:
54
+ return sum(r[2] for r in self._records)
55
+
56
+ def _path(self, segment: int) -> str:
57
+ return os.path.join(self._dir, "spool-%012d.seg" % segment)
58
+
59
+ def _open(self) -> None:
60
+ segments = sorted(int(n[6:18]) for n in os.listdir(self._dir) if n.startswith("spool-") and n.endswith(".seg") and n[6:18].isdigit())
61
+ ack_segment, ack_offset = self._read_ack()
62
+ for segment in segments:
63
+ path = self._path(segment)
64
+ offset = 0
65
+ with open(path, "r+b") as f:
66
+ data = f.read()
67
+ while offset + _HEADER.size <= len(data):
68
+ length, crc, count = _HEADER.unpack_from(data, offset)
69
+ end = offset + _HEADER.size + length
70
+ if end > len(data) or zlib.crc32(data[offset + _HEADER.size:end]) & 0xFFFFFFFF != crc:
71
+ break
72
+ if (segment, offset) >= (ack_segment, ack_offset):
73
+ self._records.append((segment, offset, end - offset, count))
74
+ offset = end
75
+ if offset < len(data):
76
+ f.truncate(offset) # a record a crash cut short was never accepted
77
+ self._segments.append(segment)
78
+ self._delete_acked_segments()
79
+
80
+ def _read_ack(self) -> Tuple[int, int]:
81
+ try:
82
+ with open(os.path.join(self._dir, "ack"), "r", encoding="ascii") as f:
83
+ segment, offset = f.read().split()
84
+ return int(segment), int(offset)
85
+ except (OSError, ValueError):
86
+ return 0, 0
87
+
88
+ def _write_ack(self) -> None:
89
+ segment, offset = (self._records[0][0], self._records[0][1]) if self._records else (self._segments[-1] + 1 if self._segments else 0, 0)
90
+ tmp = os.path.join(self._dir, "ack.tmp")
91
+ with open(tmp, "w", encoding="ascii") as f:
92
+ f.write("%d %d" % (segment, offset))
93
+ f.flush()
94
+ os.fsync(f.fileno())
95
+ os.replace(tmp, os.path.join(self._dir, "ack"))
96
+
97
+ def _delete_acked_segments(self) -> None:
98
+ live = {r[0] for r in self._records}
99
+ current = self._segments[-1] if self._segments else None
100
+ for segment in list(self._segments):
101
+ if segment not in live and segment != current:
102
+ try:
103
+ os.remove(self._path(segment))
104
+ except OSError:
105
+ pass
106
+ self._segments.remove(segment)
107
+
108
+ # ------------------------------------------------------------------ write
109
+
110
+ def append(self, body: bytes, count: int, drop_oldest: bool) -> Tuple[bool, int]:
111
+ """Writes a batch durably. Returns (stored, events dropped from the oldest records to make room)."""
112
+ size = _HEADER.size + len(body)
113
+ dropped = 0
114
+ with self._lock:
115
+ if size > self._max:
116
+ return False, 0
117
+ total = sum(r[2] for r in self._records)
118
+ if total + size > self._max:
119
+ if not drop_oldest:
120
+ return False, 0
121
+ while self._records and total + size > self._max:
122
+ old = self._records.pop(0)
123
+ total -= old[2]
124
+ dropped += old[3]
125
+ self._write_ack()
126
+ if not self._segments or self._segment_size(self._segments[-1]) + size > self._segment_bytes:
127
+ self._segments.append((self._segments[-1] + 1) if self._segments else 1)
128
+ segment = self._segments[-1]
129
+ path = self._path(segment)
130
+ with open(path, "ab") as f:
131
+ offset = f.tell()
132
+ f.write(_HEADER.pack(len(body), zlib.crc32(body) & 0xFFFFFFFF, count))
133
+ f.write(body)
134
+ f.flush()
135
+ os.fsync(f.fileno())
136
+ self._records.append((segment, offset, size, count))
137
+ self._delete_acked_segments()
138
+ return True, dropped
139
+
140
+ def _segment_size(self, segment: int) -> int:
141
+ try:
142
+ return os.path.getsize(self._path(segment))
143
+ except OSError:
144
+ return 0
145
+
146
+ # ------------------------------------------------------------------ replay
147
+
148
+ def peek(self) -> Optional[SpoolRecord]:
149
+ with self._lock:
150
+ if not self._records:
151
+ return None
152
+ segment, offset, size, count = self._records[0]
153
+ with open(self._path(segment), "rb") as f:
154
+ f.seek(offset + _HEADER.size)
155
+ body = f.read(size - _HEADER.size)
156
+ return SpoolRecord(segment, offset, size, count, body)
157
+
158
+ def ack(self, record: SpoolRecord) -> None:
159
+ with self._lock:
160
+ if self._records and self._records[0][:2] == (record.segment, record.offset):
161
+ self._records.pop(0)
162
+ self._write_ack()
163
+ self._delete_acked_segments()
@@ -0,0 +1,24 @@
1
+ """Monotonic ULIDs, generated on the caller's thread without a lock (ADR 0004 and its M6 amendment)."""
2
+ import os
3
+ import threading
4
+ import time
5
+
6
+ _CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
7
+ _state = threading.local()
8
+
9
+
10
+ def new_ulid() -> str:
11
+ """A 26-character ULID. Within one millisecond one thread's ids increase strictly; threads never wait for each other."""
12
+ ms = time.time_ns() // 1_000_000
13
+ last_ms = getattr(_state, "ms", -1)
14
+ if ms > last_ms:
15
+ value = (ms << 80) | int.from_bytes(os.urandom(10), "big")
16
+ _state.ms = ms
17
+ else:
18
+ value = _state.value + 1
19
+ _state.value = value
20
+ chars = []
21
+ for _ in range(26):
22
+ chars.append(_CROCKFORD[value & 31])
23
+ value >>= 5
24
+ return "".join(reversed(chars))