ark-watch-client 0.1.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.
- ark_watch_client/__init__.py +6 -0
- ark_watch_client/_pii.py +74 -0
- ark_watch_client/_spool.py +163 -0
- ark_watch_client/_ulid.py +24 -0
- ark_watch_client/client.py +652 -0
- ark_watch_client/conformance.py +104 -0
- ark_watch_client-0.1.0.dist-info/METADATA +56 -0
- ark_watch_client-0.1.0.dist-info/RECORD +10 -0
- ark_watch_client-0.1.0.dist-info/WHEEL +4 -0
- ark_watch_client-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -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__"]
|
ark_watch_client/_pii.py
ADDED
|
@@ -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))
|
|
@@ -0,0 +1,652 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The ARK-RAPID Watch Python client (brief 2.1; ADR 0019). ``log`` appends to a bounded in-memory ring and returns. A drainer
|
|
3
|
+
thread batches (by size or time), compresses and hands batches to a sender thread, or spills them to the disk spool when
|
|
4
|
+
the server is unreachable, the breaker is open or the ring is past its high-water mark; the sender replays the spool in
|
|
5
|
+
order. When ring and spool are both full the drop policy applies, and every drop is counted and reported to the server
|
|
6
|
+
with the next delivered batch. Nothing in here ever raises into the caller. The behaviour and the wire format are the .NET
|
|
7
|
+
SDK's; the conformance suite (tests/Ark.Watch.Conformance.Tests) runs the same scenarios against both.
|
|
8
|
+
"""
|
|
9
|
+
import collections
|
|
10
|
+
import gzip
|
|
11
|
+
import http.client
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import platform
|
|
15
|
+
import queue
|
|
16
|
+
import random
|
|
17
|
+
import socket
|
|
18
|
+
import threading
|
|
19
|
+
import time
|
|
20
|
+
import urllib.parse
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
from datetime import datetime, timezone
|
|
23
|
+
from enum import Enum
|
|
24
|
+
from typing import Any, Dict, List, Mapping, Optional, Tuple
|
|
25
|
+
|
|
26
|
+
from ._pii import PiiPolicy
|
|
27
|
+
from ._spool import Spool, SpoolRecord
|
|
28
|
+
from ._ulid import new_ulid
|
|
29
|
+
|
|
30
|
+
SDK_NAME = "ark-watch-client-python"
|
|
31
|
+
try: # the installed distribution's version (the release stamps it); "0.0.0+source" when run from a checkout
|
|
32
|
+
from importlib.metadata import version as _dist_version
|
|
33
|
+
|
|
34
|
+
SDK_VERSION = _dist_version("ark-watch-client")
|
|
35
|
+
except Exception: # noqa: BLE001
|
|
36
|
+
SDK_VERSION = "0.0.0+source"
|
|
37
|
+
DROPPED_HEADER = "Ark-Watch-Dropped"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class AuditLevel(Enum):
|
|
41
|
+
TRACE = "Trace"
|
|
42
|
+
DEBUG = "Debug"
|
|
43
|
+
INFO = "Info"
|
|
44
|
+
NOTICE = "Notice"
|
|
45
|
+
WARNING = "Warning"
|
|
46
|
+
ERROR = "Error"
|
|
47
|
+
CRITICAL = "Critical"
|
|
48
|
+
SECURITY = "Security"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
_LEVEL_ORDER = {lvl: i for i, lvl in enumerate(AuditLevel)}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Outcome(Enum):
|
|
55
|
+
SUCCESS = "Success"
|
|
56
|
+
FAILURE = "Failure"
|
|
57
|
+
DENIED = "Denied"
|
|
58
|
+
UNKNOWN = "Unknown"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class DropPolicy(Enum):
|
|
62
|
+
"""What happens when the ring and the spool are both full. Never blocks."""
|
|
63
|
+
|
|
64
|
+
DROP_OLDEST = "DropOldest"
|
|
65
|
+
DROP_NEWEST = "DropNewest"
|
|
66
|
+
SAMPLE_DEBUG = "SampleDebug"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class DropReason:
|
|
70
|
+
RING_FULL_NEWEST = "ring_full_newest"
|
|
71
|
+
RING_FULL_OLDEST = "ring_full_oldest"
|
|
72
|
+
SAMPLED_DEBUG = "sampled_debug"
|
|
73
|
+
SPOOL_FULL_OLDEST = "spool_full_oldest"
|
|
74
|
+
SPOOL_FULL_NEWEST = "spool_full_newest"
|
|
75
|
+
AFTER_CLOSE = "after_dispose"
|
|
76
|
+
RETRY_LIMIT = "retry_limit"
|
|
77
|
+
INTERNAL = "internal_error"
|
|
78
|
+
ALL = (RING_FULL_NEWEST, RING_FULL_OLDEST, SAMPLED_DEBUG, SPOOL_FULL_OLDEST, SPOOL_FULL_NEWEST, AFTER_CLOSE, RETRY_LIMIT, INTERNAL)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass
|
|
82
|
+
class ClientStats:
|
|
83
|
+
logged: int = 0
|
|
84
|
+
sent: int = 0
|
|
85
|
+
duplicates: int = 0
|
|
86
|
+
spooled: int = 0
|
|
87
|
+
replayed: int = 0
|
|
88
|
+
rejected: int = 0
|
|
89
|
+
dropped: int = 0
|
|
90
|
+
dropped_by_reason: Dict[str, int] = field(default_factory=dict)
|
|
91
|
+
internal_errors: int = 0
|
|
92
|
+
send_failures: int = 0
|
|
93
|
+
ring_count: int = 0
|
|
94
|
+
spool_bytes: int = 0
|
|
95
|
+
spool_batches: int = 0
|
|
96
|
+
breaker_state: str = "Closed"
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass
|
|
100
|
+
class _Batch:
|
|
101
|
+
body: bytes
|
|
102
|
+
count: int
|
|
103
|
+
attempts: int = 0
|
|
104
|
+
record: Optional[SpoolRecord] = None
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class _Breaker:
|
|
108
|
+
"""Opens after repeated failures, with exponential backoff and jitter; honours Retry-After."""
|
|
109
|
+
|
|
110
|
+
def __init__(self, threshold: int, base: float, maximum: float):
|
|
111
|
+
self._threshold = max(1, threshold)
|
|
112
|
+
self._base = base
|
|
113
|
+
self._max = maximum
|
|
114
|
+
self._failures = 0
|
|
115
|
+
self._open_until = 0.0
|
|
116
|
+
self._lock = threading.Lock()
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def state(self) -> str:
|
|
120
|
+
with self._lock:
|
|
121
|
+
if self._failures >= self._threshold or time.monotonic() < self._open_until:
|
|
122
|
+
return "Open" if time.monotonic() < self._open_until else "HalfOpen"
|
|
123
|
+
return "Closed"
|
|
124
|
+
|
|
125
|
+
@property
|
|
126
|
+
def closed(self) -> bool:
|
|
127
|
+
return self.state == "Closed"
|
|
128
|
+
|
|
129
|
+
def allow(self) -> bool:
|
|
130
|
+
with self._lock:
|
|
131
|
+
return time.monotonic() >= self._open_until
|
|
132
|
+
|
|
133
|
+
def open_for(self) -> float:
|
|
134
|
+
with self._lock:
|
|
135
|
+
return max(0.0, self._open_until - time.monotonic())
|
|
136
|
+
|
|
137
|
+
def success(self) -> None:
|
|
138
|
+
with self._lock:
|
|
139
|
+
self._failures = 0
|
|
140
|
+
self._open_until = 0.0
|
|
141
|
+
|
|
142
|
+
def failure(self, retry_after: Optional[float]) -> None:
|
|
143
|
+
with self._lock:
|
|
144
|
+
self._failures += 1
|
|
145
|
+
delay = 0.0
|
|
146
|
+
if self._failures >= self._threshold:
|
|
147
|
+
exponent = min(16, self._failures - self._threshold)
|
|
148
|
+
delay = min(self._max, self._base * (2 ** exponent))
|
|
149
|
+
delay = delay * (0.8 + random.random() * 0.4)
|
|
150
|
+
if retry_after is not None:
|
|
151
|
+
delay = max(delay, min(retry_after, self._max))
|
|
152
|
+
if delay > 0:
|
|
153
|
+
self._open_until = time.monotonic() + delay
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class _Transport:
|
|
157
|
+
"""POST /v1/events over HTTP/1.1 keep-alive, gzip, bearer key."""
|
|
158
|
+
|
|
159
|
+
def __init__(self, endpoint: str, api_key: Optional[str], timeout: float):
|
|
160
|
+
url = urllib.parse.urlsplit(endpoint if endpoint.endswith("/") else endpoint + "/")
|
|
161
|
+
self._https = url.scheme == "https"
|
|
162
|
+
self._host = url.hostname or "localhost"
|
|
163
|
+
self._port = url.port or (443 if self._https else 80)
|
|
164
|
+
self._path = (url.path or "/") + "v1/events"
|
|
165
|
+
self._key = api_key
|
|
166
|
+
self._timeout = timeout
|
|
167
|
+
self._conn: Optional[http.client.HTTPConnection] = None
|
|
168
|
+
|
|
169
|
+
def _connection(self) -> http.client.HTTPConnection:
|
|
170
|
+
if self._conn is None:
|
|
171
|
+
cls = http.client.HTTPSConnection if self._https else http.client.HTTPConnection
|
|
172
|
+
self._conn = cls(self._host, self._port, timeout=self._timeout)
|
|
173
|
+
return self._conn
|
|
174
|
+
|
|
175
|
+
def close(self) -> None:
|
|
176
|
+
if self._conn is not None:
|
|
177
|
+
try:
|
|
178
|
+
self._conn.close()
|
|
179
|
+
except Exception: # noqa: BLE001
|
|
180
|
+
pass
|
|
181
|
+
self._conn = None
|
|
182
|
+
|
|
183
|
+
def send(self, body: bytes, dropped: Optional[str]) -> Tuple[str, int, Optional[float], Optional[dict]]:
|
|
184
|
+
"""Returns (outcome, status, retry_after, parsed body): outcome is delivered, retry or reject."""
|
|
185
|
+
headers = {"Content-Type": "application/json", "Content-Encoding": "gzip", "User-Agent": SDK_NAME + "/" + SDK_VERSION}
|
|
186
|
+
if self._key:
|
|
187
|
+
headers["Authorization"] = "Bearer " + self._key
|
|
188
|
+
if dropped:
|
|
189
|
+
headers[DROPPED_HEADER] = dropped
|
|
190
|
+
try:
|
|
191
|
+
conn = self._connection()
|
|
192
|
+
conn.request("POST", self._path, body=body, headers=headers)
|
|
193
|
+
response = conn.getresponse()
|
|
194
|
+
payload = response.read()
|
|
195
|
+
status = response.status
|
|
196
|
+
except Exception: # noqa: BLE001 - refused, reset, timeout: all mean "try again later"
|
|
197
|
+
self.close()
|
|
198
|
+
return "retry", 0, None, None
|
|
199
|
+
retry_after = _parse_retry_after(response.getheader("Retry-After"))
|
|
200
|
+
if 200 <= status < 300:
|
|
201
|
+
try:
|
|
202
|
+
return "delivered", status, None, json.loads(payload.decode("utf-8")) if payload else None
|
|
203
|
+
except ValueError:
|
|
204
|
+
return "delivered", status, None, None
|
|
205
|
+
if status in (401, 403, 408, 425, 429) or status >= 500:
|
|
206
|
+
return "retry", status, retry_after, None
|
|
207
|
+
return "reject", status, None, None
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
class _PerThreadCounter:
|
|
211
|
+
"""A counter each caller thread increments in its own cell: no lock and no lost update on the hot path."""
|
|
212
|
+
|
|
213
|
+
def __init__(self) -> None:
|
|
214
|
+
self._local = threading.local()
|
|
215
|
+
self._cells: List[List[int]] = []
|
|
216
|
+
self._lock = threading.Lock()
|
|
217
|
+
|
|
218
|
+
def inc(self) -> None:
|
|
219
|
+
cell = getattr(self._local, "cell", None)
|
|
220
|
+
if cell is None:
|
|
221
|
+
cell = [0]
|
|
222
|
+
self._local.cell = cell
|
|
223
|
+
with self._lock:
|
|
224
|
+
self._cells.append(cell)
|
|
225
|
+
cell[0] += 1
|
|
226
|
+
|
|
227
|
+
@property
|
|
228
|
+
def value(self) -> int:
|
|
229
|
+
with self._lock:
|
|
230
|
+
return sum(c[0] for c in self._cells)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _parse_retry_after(value: Optional[str]) -> Optional[float]:
|
|
234
|
+
if not value:
|
|
235
|
+
return None
|
|
236
|
+
try:
|
|
237
|
+
return max(0.0, float(value))
|
|
238
|
+
except ValueError:
|
|
239
|
+
return None
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _primary_ip() -> str:
|
|
243
|
+
try:
|
|
244
|
+
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
|
|
245
|
+
s.connect(("10.255.255.255", 1)) # no packet is sent: this only picks the outgoing interface
|
|
246
|
+
return s.getsockname()[0]
|
|
247
|
+
except OSError:
|
|
248
|
+
return "127.0.0.1"
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
class AuditClient:
|
|
252
|
+
"""
|
|
253
|
+
Buffers audit events and ships them to an ARK-RAPID Watch node. ``log`` never blocks and never raises.
|
|
254
|
+
|
|
255
|
+
>>> audit = AuditClient("https://audit.example.com", api_key=os.environ["ARK_WATCH_API_KEY"], application="orders-api",
|
|
256
|
+
... spool_directory="/var/lib/orders-api/audit-spool")
|
|
257
|
+
>>> audit.log(AuditLevel.NOTICE, "invoice.approve", participant_id="u-42", resource_type="invoice", resource_id="inv-7")
|
|
258
|
+
"""
|
|
259
|
+
|
|
260
|
+
_QUEUE_CAPACITY = 8
|
|
261
|
+
_MAX_RETRY_ATTEMPTS = 10
|
|
262
|
+
|
|
263
|
+
def __init__(self, endpoint: str = "http://localhost:5080/", api_key: Optional[str] = None, application: str = "",
|
|
264
|
+
app_version: Optional[str] = None, environment: Optional[str] = None, default_domain: str = "General",
|
|
265
|
+
default_system: Optional[str] = None, ring_capacity: int = 8192, high_water_mark: float = 0.75,
|
|
266
|
+
batch_size: int = 500, flush_interval: float = 0.2, spool_directory: Optional[str] = None,
|
|
267
|
+
spool_max_bytes: int = 256 * 1024 * 1024, spool_segment_bytes: int = 8 * 1024 * 1024,
|
|
268
|
+
drop_policy: DropPolicy = DropPolicy.DROP_OLDEST, request_timeout: float = 10.0,
|
|
269
|
+
breaker_failure_threshold: int = 3, breaker_base_delay: float = 0.5, breaker_max_delay: float = 60.0,
|
|
270
|
+
pii: Optional[PiiPolicy] = None):
|
|
271
|
+
self._application = application
|
|
272
|
+
self._app_version = app_version
|
|
273
|
+
self._environment = environment
|
|
274
|
+
self._default_domain = default_domain
|
|
275
|
+
self._system = default_system or os.path.basename(os.path.abspath(__import__("sys").argv[0] or "python")) or "python"
|
|
276
|
+
self._capacity = max(2, ring_capacity)
|
|
277
|
+
self._high_water = int(self._capacity * min(1.0, max(0.1, high_water_mark)))
|
|
278
|
+
self._batch_size = min(5000, max(1, batch_size))
|
|
279
|
+
self._flush_interval = max(0.01, flush_interval)
|
|
280
|
+
self._policy = drop_policy
|
|
281
|
+
self._pii = pii or PiiPolicy()
|
|
282
|
+
self._host = platform.node() or "unknown"
|
|
283
|
+
self._ip = _primary_ip()
|
|
284
|
+
self._ring: collections.deque = collections.deque()
|
|
285
|
+
self._lock = threading.Lock() # counters and the drop path only; the common path takes no lock
|
|
286
|
+
self._logged = _PerThreadCounter()
|
|
287
|
+
self._counters = collections.Counter() # background threads (and the rare error path), under _lock
|
|
288
|
+
self._unreported = collections.Counter()
|
|
289
|
+
self._dropped = collections.Counter()
|
|
290
|
+
self._inflight = 0 # events taken from the ring and not yet delivered, spooled or dropped; background threads only
|
|
291
|
+
self._closed = False
|
|
292
|
+
self._spool: Optional[Spool] = None
|
|
293
|
+
if spool_directory:
|
|
294
|
+
try:
|
|
295
|
+
self._spool = Spool(spool_directory, spool_max_bytes, spool_segment_bytes)
|
|
296
|
+
except Exception: # noqa: BLE001 - no spool is better than a crash
|
|
297
|
+
self._add("internal_errors")
|
|
298
|
+
self._breaker = _Breaker(breaker_failure_threshold, breaker_base_delay, breaker_max_delay)
|
|
299
|
+
self._transport = _Transport(endpoint, api_key, request_timeout)
|
|
300
|
+
self._queue: "queue.Queue[_Batch]" = queue.Queue(self._QUEUE_CAPACITY)
|
|
301
|
+
self._retry: Optional[_Batch] = None
|
|
302
|
+
self._wake_drainer = threading.Event()
|
|
303
|
+
self._wake_sender = threading.Event()
|
|
304
|
+
self._stop = threading.Event()
|
|
305
|
+
self._drainer = threading.Thread(target=self._drain_loop, name="ark-watch-client-drainer", daemon=True)
|
|
306
|
+
self._sender = threading.Thread(target=self._send_loop, name="ark-watch-client-sender", daemon=True)
|
|
307
|
+
self._drainer.start()
|
|
308
|
+
self._sender.start()
|
|
309
|
+
|
|
310
|
+
# ------------------------------------------------------------------ caller side
|
|
311
|
+
|
|
312
|
+
def log(self, level: AuditLevel, action: str, message: Optional[str] = None, participant_id: Optional[str] = None,
|
|
313
|
+
outcome: Outcome = Outcome.SUCCESS, correlation_id: Optional[str] = None, attributes: Optional[Mapping[str, Any]] = None,
|
|
314
|
+
domain: Optional[str] = None, system: Optional[str] = None, resource_type: Optional[str] = None,
|
|
315
|
+
resource_id: Optional[str] = None, participant_type: Optional[str] = None, participant_name: Optional[str] = None,
|
|
316
|
+
ip: Optional[str] = None, trace_id: Optional[str] = None, span_id: Optional[str] = None) -> str:
|
|
317
|
+
"""Buffers one event and returns its id at once. Never blocks, never raises (an empty id means it was refused)."""
|
|
318
|
+
try:
|
|
319
|
+
self._logged.inc()
|
|
320
|
+
event_id = new_ulid()
|
|
321
|
+
if self._closed:
|
|
322
|
+
self._drop(DropReason.AFTER_CLOSE, 1)
|
|
323
|
+
return event_id
|
|
324
|
+
entry = (event_id, time.time_ns(), level, action, message, participant_id, outcome, correlation_id, attributes,
|
|
325
|
+
domain, system, resource_type, resource_id, participant_type, participant_name, ip, trace_id, span_id)
|
|
326
|
+
ring = self._ring
|
|
327
|
+
if self._policy is DropPolicy.SAMPLE_DEBUG and _LEVEL_ORDER.get(level, 2) <= 1 and len(ring) >= self._high_water:
|
|
328
|
+
self._drop(DropReason.SAMPLED_DEBUG, 1)
|
|
329
|
+
return event_id
|
|
330
|
+
if len(ring) >= self._capacity:
|
|
331
|
+
if self._policy is DropPolicy.DROP_NEWEST or (self._policy is DropPolicy.SAMPLE_DEBUG and _LEVEL_ORDER.get(level, 2) <= 1):
|
|
332
|
+
self._drop(DropReason.RING_FULL_NEWEST, 1)
|
|
333
|
+
return event_id
|
|
334
|
+
try:
|
|
335
|
+
evicted = ring.popleft()
|
|
336
|
+
self._drop(DropReason.SAMPLED_DEBUG if self._policy is DropPolicy.SAMPLE_DEBUG and _LEVEL_ORDER.get(evicted[2], 2) <= 1
|
|
337
|
+
else DropReason.RING_FULL_OLDEST, 1)
|
|
338
|
+
except IndexError:
|
|
339
|
+
pass
|
|
340
|
+
ring.append(entry)
|
|
341
|
+
if len(ring) >= self._batch_size:
|
|
342
|
+
self._wake_drainer.set()
|
|
343
|
+
return event_id
|
|
344
|
+
except Exception: # noqa: BLE001
|
|
345
|
+
self._add("internal_errors")
|
|
346
|
+
return ""
|
|
347
|
+
|
|
348
|
+
def _drop(self, reason: str, count: int) -> None:
|
|
349
|
+
with self._lock:
|
|
350
|
+
self._dropped[reason] += count
|
|
351
|
+
self._unreported[reason] += count
|
|
352
|
+
|
|
353
|
+
def _add(self, name: str, n: int = 1) -> None:
|
|
354
|
+
with self._lock:
|
|
355
|
+
self._counters[name] += n
|
|
356
|
+
|
|
357
|
+
def _settle(self, n: int) -> None:
|
|
358
|
+
"""Events that left the in-flight set (delivered, spooled or dropped)."""
|
|
359
|
+
with self._lock:
|
|
360
|
+
self._inflight -= n
|
|
361
|
+
|
|
362
|
+
def stats(self) -> ClientStats:
|
|
363
|
+
with self._lock:
|
|
364
|
+
by_reason = {k: v for k, v in self._dropped.items() if v > 0}
|
|
365
|
+
c = dict(self._counters)
|
|
366
|
+
spool = self._spool
|
|
367
|
+
return ClientStats(
|
|
368
|
+
logged=self._logged.value, sent=c.get("sent", 0), duplicates=c.get("duplicates", 0),
|
|
369
|
+
spooled=c.get("spooled", 0), replayed=c.get("replayed", 0), rejected=c.get("rejected", 0),
|
|
370
|
+
dropped=sum(by_reason.values()), dropped_by_reason=by_reason, internal_errors=c.get("internal_errors", 0),
|
|
371
|
+
send_failures=c.get("send_failures", 0), ring_count=len(self._ring),
|
|
372
|
+
spool_bytes=spool.bytes if spool else 0, spool_batches=spool.pending_batches if spool else 0,
|
|
373
|
+
breaker_state=self._breaker.state)
|
|
374
|
+
|
|
375
|
+
def flush(self, timeout: float = 10.0) -> bool:
|
|
376
|
+
"""Ships what is buffered; True if everything was delivered or spooled within the timeout."""
|
|
377
|
+
deadline = time.monotonic() + timeout
|
|
378
|
+
self._wake_drainer.set()
|
|
379
|
+
while time.monotonic() < deadline:
|
|
380
|
+
if not self._ring and self._inflight <= 0 and (self._spool is None or not self._spool.has_pending or not self._breaker.closed):
|
|
381
|
+
return True
|
|
382
|
+
self._wake_sender.set()
|
|
383
|
+
time.sleep(0.01)
|
|
384
|
+
return False
|
|
385
|
+
|
|
386
|
+
def close(self, timeout: float = 5.0) -> None:
|
|
387
|
+
"""Flushes, then stops the background threads. Events logged after close are counted as dropped."""
|
|
388
|
+
if self._closed:
|
|
389
|
+
return
|
|
390
|
+
self.flush(timeout)
|
|
391
|
+
self._closed = True
|
|
392
|
+
self._stop.set()
|
|
393
|
+
self._wake_drainer.set()
|
|
394
|
+
self._wake_sender.set()
|
|
395
|
+
self._drainer.join(timeout)
|
|
396
|
+
self._sender.join(timeout)
|
|
397
|
+
if not self._sender.is_alive():
|
|
398
|
+
# As the .NET SDK: what could not be sent in time goes to the spool for the next start, or is counted.
|
|
399
|
+
leftovers = [self._retry] if self._retry is not None else []
|
|
400
|
+
self._retry = None
|
|
401
|
+
while True:
|
|
402
|
+
try:
|
|
403
|
+
leftovers.append(self._queue.get_nowait())
|
|
404
|
+
except queue.Empty:
|
|
405
|
+
break
|
|
406
|
+
for batch in leftovers:
|
|
407
|
+
if self._spool is not None:
|
|
408
|
+
self._spool_append(batch)
|
|
409
|
+
else:
|
|
410
|
+
self._drop(DropReason.AFTER_CLOSE, batch.count)
|
|
411
|
+
self._settle(batch.count)
|
|
412
|
+
self._transport.close()
|
|
413
|
+
|
|
414
|
+
def __enter__(self) -> "AuditClient":
|
|
415
|
+
return self
|
|
416
|
+
|
|
417
|
+
def __exit__(self, *_: Any) -> None:
|
|
418
|
+
self.close()
|
|
419
|
+
|
|
420
|
+
# ------------------------------------------------------------------ drainer thread
|
|
421
|
+
|
|
422
|
+
def _drain_loop(self) -> None:
|
|
423
|
+
while True:
|
|
424
|
+
try:
|
|
425
|
+
self._wake_drainer.wait(self._flush_interval)
|
|
426
|
+
self._wake_drainer.clear()
|
|
427
|
+
stopping = self._stop.is_set()
|
|
428
|
+
self._drain_once(stopping)
|
|
429
|
+
if stopping and not self._ring:
|
|
430
|
+
return
|
|
431
|
+
except Exception: # noqa: BLE001
|
|
432
|
+
self._add("internal_errors")
|
|
433
|
+
time.sleep(0.05)
|
|
434
|
+
|
|
435
|
+
def _drain_once(self, stopping: bool) -> None:
|
|
436
|
+
while self._ring:
|
|
437
|
+
if self._spool is None and self._queue.qsize() >= self._QUEUE_CAPACITY and not stopping:
|
|
438
|
+
return # no spool and the sender is behind: callers get the drop policy
|
|
439
|
+
entries = []
|
|
440
|
+
while len(entries) < self._batch_size:
|
|
441
|
+
try:
|
|
442
|
+
entries.append(self._ring.popleft())
|
|
443
|
+
except IndexError:
|
|
444
|
+
break
|
|
445
|
+
if not entries:
|
|
446
|
+
return
|
|
447
|
+
with self._lock:
|
|
448
|
+
self._inflight += len(entries)
|
|
449
|
+
body = self._serialize(entries)
|
|
450
|
+
if body is not None:
|
|
451
|
+
self._route(_Batch(body, len(entries)))
|
|
452
|
+
|
|
453
|
+
def _serialize(self, entries: List[tuple]) -> Optional[bytes]:
|
|
454
|
+
events = []
|
|
455
|
+
for e in entries:
|
|
456
|
+
try:
|
|
457
|
+
events.append(self._event(e))
|
|
458
|
+
except Exception: # noqa: BLE001 - one bad entry (an attribute that cannot be written) never costs the batch
|
|
459
|
+
self._add("internal_errors")
|
|
460
|
+
self._drop(DropReason.INTERNAL, 1)
|
|
461
|
+
self._settle(1)
|
|
462
|
+
if not events:
|
|
463
|
+
return None
|
|
464
|
+
payload = {"sdk": {"name": SDK_NAME, "version": SDK_VERSION}, "events": events}
|
|
465
|
+
try:
|
|
466
|
+
# "replace": a lone surrogate (text decoded with surrogateescape) becomes '?' rather than failing the batch.
|
|
467
|
+
return gzip.compress(json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8", "replace"), compresslevel=1)
|
|
468
|
+
except Exception: # noqa: BLE001 - never leave events counted as in flight
|
|
469
|
+
self._add("internal_errors")
|
|
470
|
+
self._drop(DropReason.INTERNAL, len(events))
|
|
471
|
+
self._settle(len(events))
|
|
472
|
+
return None
|
|
473
|
+
|
|
474
|
+
def _event(self, e: tuple) -> dict:
|
|
475
|
+
(event_id, ts, level, action, message, participant_id, outcome, correlation_id, attributes, domain, system,
|
|
476
|
+
resource_type, resource_id, participant_type, participant_name, ip, trace_id, span_id) = e
|
|
477
|
+
redactions: List[str] = []
|
|
478
|
+
participant = {"id": participant_id or self._system,
|
|
479
|
+
"type": participant_type or ("user" if participant_id else "service")}
|
|
480
|
+
if participant_name:
|
|
481
|
+
participant["display_name"] = participant_name
|
|
482
|
+
out: Dict[str, Any] = {
|
|
483
|
+
"event_id": event_id,
|
|
484
|
+
"schema_version": 1,
|
|
485
|
+
"occurred_at": datetime.fromtimestamp(ts / 1e9, tz=timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z"),
|
|
486
|
+
"level": level.value if isinstance(level, AuditLevel) else str(level),
|
|
487
|
+
"application": self._application,
|
|
488
|
+
"domain": domain or self._default_domain,
|
|
489
|
+
"system": system or self._system,
|
|
490
|
+
"host": self._host,
|
|
491
|
+
"ip": ip or self._ip,
|
|
492
|
+
"participant": participant,
|
|
493
|
+
"outcome": outcome.value if isinstance(outcome, Outcome) else str(outcome),
|
|
494
|
+
}
|
|
495
|
+
if self._app_version:
|
|
496
|
+
out["app_version"] = self._app_version
|
|
497
|
+
if self._environment:
|
|
498
|
+
out["environment"] = self._environment
|
|
499
|
+
if action:
|
|
500
|
+
out["action"] = action
|
|
501
|
+
if resource_type or resource_id:
|
|
502
|
+
out["resource"] = {"type": resource_type or "unknown", "id": resource_id or ""}
|
|
503
|
+
if correlation_id:
|
|
504
|
+
out["correlation_id"] = correlation_id
|
|
505
|
+
if trace_id:
|
|
506
|
+
out["trace_id"] = trace_id
|
|
507
|
+
if span_id:
|
|
508
|
+
out["span_id"] = span_id
|
|
509
|
+
if message is not None:
|
|
510
|
+
masked = self._pii.text(message)
|
|
511
|
+
if masked != message:
|
|
512
|
+
redactions.append("message")
|
|
513
|
+
out["message"] = masked
|
|
514
|
+
if attributes:
|
|
515
|
+
out["attributes"] = self._pii.attributes(dict(attributes), "attributes", redactions)
|
|
516
|
+
if redactions:
|
|
517
|
+
out["redactions"] = redactions
|
|
518
|
+
return out
|
|
519
|
+
|
|
520
|
+
def _route(self, batch: _Batch) -> None:
|
|
521
|
+
spill = self._spool is not None and (self._spool.has_pending or not self._breaker.closed
|
|
522
|
+
or self._queue.qsize() >= 2 or len(self._ring) > self._high_water)
|
|
523
|
+
if not spill:
|
|
524
|
+
try:
|
|
525
|
+
self._queue.put_nowait(batch)
|
|
526
|
+
self._wake_sender.set()
|
|
527
|
+
return
|
|
528
|
+
except queue.Full:
|
|
529
|
+
pass
|
|
530
|
+
if self._spool is not None:
|
|
531
|
+
self._spool_append(batch)
|
|
532
|
+
else:
|
|
533
|
+
while not self._stop.is_set(): # without a spool the drainer waits for the sender; callers never do
|
|
534
|
+
try:
|
|
535
|
+
self._queue.put(batch, timeout=0.05)
|
|
536
|
+
break
|
|
537
|
+
except queue.Full:
|
|
538
|
+
continue
|
|
539
|
+
else:
|
|
540
|
+
self._drop(DropReason.AFTER_CLOSE, batch.count)
|
|
541
|
+
self._settle(batch.count)
|
|
542
|
+
self._wake_sender.set()
|
|
543
|
+
|
|
544
|
+
def _spool_append(self, batch: _Batch) -> None:
|
|
545
|
+
self._settle(batch.count)
|
|
546
|
+
stored, dropped_oldest = self._spool.append(batch.body, batch.count, self._policy is not DropPolicy.DROP_NEWEST)
|
|
547
|
+
if dropped_oldest:
|
|
548
|
+
self._drop(DropReason.SPOOL_FULL_OLDEST, dropped_oldest)
|
|
549
|
+
if stored:
|
|
550
|
+
self._add("spooled", batch.count)
|
|
551
|
+
else:
|
|
552
|
+
self._drop(DropReason.SPOOL_FULL_NEWEST, batch.count)
|
|
553
|
+
|
|
554
|
+
# ------------------------------------------------------------------ sender thread
|
|
555
|
+
|
|
556
|
+
def _send_loop(self) -> None:
|
|
557
|
+
# Stops as soon as close() says so: close() has flushed already, and hands what is left to the spool.
|
|
558
|
+
while not self._stop.is_set():
|
|
559
|
+
try:
|
|
560
|
+
batch = self._retry
|
|
561
|
+
if batch is None:
|
|
562
|
+
try:
|
|
563
|
+
batch = self._queue.get_nowait()
|
|
564
|
+
except queue.Empty:
|
|
565
|
+
batch = None
|
|
566
|
+
if batch is None and self._spool is not None and (self._breaker.closed or self._breaker.allow()):
|
|
567
|
+
record = self._spool.peek()
|
|
568
|
+
if record is not None:
|
|
569
|
+
batch = _Batch(record.body, record.count, record=record)
|
|
570
|
+
if batch is None:
|
|
571
|
+
if self._stop.is_set():
|
|
572
|
+
return
|
|
573
|
+
self._wake_sender.wait(0.25)
|
|
574
|
+
self._wake_sender.clear()
|
|
575
|
+
continue
|
|
576
|
+
if not self._breaker.allow():
|
|
577
|
+
if batch.record is None:
|
|
578
|
+
self._retry = batch
|
|
579
|
+
self._wake_sender.wait(min(1.0, max(0.01, self._breaker.open_for())))
|
|
580
|
+
self._wake_sender.clear()
|
|
581
|
+
continue
|
|
582
|
+
self._send_one(batch)
|
|
583
|
+
except Exception: # noqa: BLE001
|
|
584
|
+
self._add("internal_errors")
|
|
585
|
+
time.sleep(0.05)
|
|
586
|
+
|
|
587
|
+
def _dropped_header(self) -> Tuple[Optional[str], Dict[str, int]]:
|
|
588
|
+
with self._lock:
|
|
589
|
+
snapshot = {r: self._unreported[r] for r in DropReason.ALL if self._unreported[r] > 0}
|
|
590
|
+
return (";".join("%s=%d" % kv for kv in snapshot.items()) or None), snapshot
|
|
591
|
+
|
|
592
|
+
def _send_one(self, batch: _Batch) -> None:
|
|
593
|
+
header, snapshot = self._dropped_header()
|
|
594
|
+
outcome, status, retry_after, body = self._transport.send(batch.body, header)
|
|
595
|
+
if outcome == "delivered":
|
|
596
|
+
with self._lock:
|
|
597
|
+
for reason, n in snapshot.items():
|
|
598
|
+
self._unreported[reason] -= n
|
|
599
|
+
if batch.record is not None:
|
|
600
|
+
self._spool.ack(batch.record)
|
|
601
|
+
self._add("replayed", batch.count)
|
|
602
|
+
else:
|
|
603
|
+
if self._retry is batch:
|
|
604
|
+
self._retry = None
|
|
605
|
+
self._settle(batch.count)
|
|
606
|
+
rejected = (body or {}).get("rejected") or []
|
|
607
|
+
retryable = [r["index"] for r in rejected if r.get("retryable") and isinstance(r.get("index"), int) and r["index"] < batch.count]
|
|
608
|
+
self._add("sent", batch.count - len(rejected))
|
|
609
|
+
self._add("duplicates", int((body or {}).get("duplicates") or 0))
|
|
610
|
+
self._add("rejected", sum(1 for r in rejected if not r.get("retryable")))
|
|
611
|
+
if retryable:
|
|
612
|
+
self._breaker.failure(None)
|
|
613
|
+
again = _Batch(_subset(batch.body, retryable), len(retryable), batch.attempts + 1)
|
|
614
|
+
with self._lock:
|
|
615
|
+
self._inflight += again.count
|
|
616
|
+
if again.attempts > self._MAX_RETRY_ATTEMPTS:
|
|
617
|
+
if self._spool is not None:
|
|
618
|
+
again.attempts = 0
|
|
619
|
+
self._spool_append(again)
|
|
620
|
+
else:
|
|
621
|
+
self._drop(DropReason.RETRY_LIMIT, again.count)
|
|
622
|
+
self._settle(again.count)
|
|
623
|
+
else:
|
|
624
|
+
self._retry = again
|
|
625
|
+
else:
|
|
626
|
+
self._breaker.success()
|
|
627
|
+
elif outcome == "retry":
|
|
628
|
+
self._add("send_failures")
|
|
629
|
+
self._breaker.failure(retry_after)
|
|
630
|
+
if batch.record is None:
|
|
631
|
+
if self._spool is not None:
|
|
632
|
+
# The server is not taking batches: what left the ring goes to disk now, so a crash loses nothing.
|
|
633
|
+
if self._retry is batch:
|
|
634
|
+
self._retry = None
|
|
635
|
+
self._spool_append(batch)
|
|
636
|
+
else:
|
|
637
|
+
self._retry = batch
|
|
638
|
+
else:
|
|
639
|
+
self._add("rejected", batch.count)
|
|
640
|
+
if batch.record is not None:
|
|
641
|
+
self._spool.ack(batch.record)
|
|
642
|
+
else:
|
|
643
|
+
if self._retry is batch:
|
|
644
|
+
self._retry = None
|
|
645
|
+
self._settle(batch.count)
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def _subset(gzip_body: bytes, indices: List[int]) -> bytes:
|
|
649
|
+
root = json.loads(gzip.decompress(gzip_body).decode("utf-8"))
|
|
650
|
+
keep = set(indices)
|
|
651
|
+
root["events"] = [e for i, e in enumerate(root["events"]) if i in keep]
|
|
652
|
+
return gzip.compress(json.dumps(root, ensure_ascii=False, separators=(",", ":")).encode("utf-8"), compresslevel=1)
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The conformance driver (ADR 0019): ``python -m ark_watch_client.conformance`` reads one JSON command per line on stdin and
|
|
3
|
+
answers one JSON line on stdout. tests/Ark.Watch.Conformance.Tests drives the .NET, Python and Dart SDKs through the
|
|
4
|
+
same commands, against the same scripted server.
|
|
5
|
+
"""
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
import threading
|
|
9
|
+
import time
|
|
10
|
+
from dataclasses import asdict
|
|
11
|
+
|
|
12
|
+
from .client import AuditClient, AuditLevel, DropPolicy, Outcome
|
|
13
|
+
|
|
14
|
+
_client = None
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _policy(name):
|
|
18
|
+
return {"DropOldest": DropPolicy.DROP_OLDEST, "DropNewest": DropPolicy.DROP_NEWEST, "SampleDebug": DropPolicy.SAMPLE_DEBUG}[name]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _start(c):
|
|
22
|
+
global _client
|
|
23
|
+
_client = AuditClient(
|
|
24
|
+
endpoint=c["endpoint"], api_key=c.get("apiKey"), application=c.get("application", "conformance"),
|
|
25
|
+
environment=c.get("environment"), app_version=c.get("appVersion"), spool_directory=c.get("spoolDirectory"),
|
|
26
|
+
ring_capacity=c.get("ringCapacity", 8192), batch_size=c.get("batchSize", 500),
|
|
27
|
+
flush_interval=c.get("flushIntervalMs", 200) / 1000.0, request_timeout=c.get("requestTimeoutMs", 10000) / 1000.0,
|
|
28
|
+
breaker_base_delay=c.get("breakerBaseDelayMs", 500) / 1000.0, breaker_max_delay=c.get("breakerMaxDelayMs", 60000) / 1000.0,
|
|
29
|
+
spool_max_bytes=c.get("spoolMaxBytes", 256 * 1024 * 1024), spool_segment_bytes=c.get("spoolSegmentBytes", 8 * 1024 * 1024),
|
|
30
|
+
drop_policy=_policy(c.get("dropPolicy", "DropOldest")))
|
|
31
|
+
return {}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _log(c):
|
|
35
|
+
ids = []
|
|
36
|
+
level = AuditLevel(c.get("level", "Info"))
|
|
37
|
+
outcome = Outcome(c.get("outcome", "Success"))
|
|
38
|
+
for i in range(c.get("count", 1)):
|
|
39
|
+
ids.append(_client.log(level, c.get("action", "conformance.test"), message=c.get("message"),
|
|
40
|
+
participant_id=c["participantId"].replace("{i}", str(i)) if c.get("participantId") else None,
|
|
41
|
+
correlation_id=c["correlationId"].replace("{i}", str(i // 10)) if c.get("correlationId") else None,
|
|
42
|
+
attributes=c.get("attributes"), outcome=outcome, resource_type=c.get("resourceType"),
|
|
43
|
+
resource_id=c.get("resourceId")))
|
|
44
|
+
return {"ids": ids if c.get("returnIds", True) else []}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _measure(c):
|
|
48
|
+
"""Times log() on the caller's thread: count calls on `threads` threads, in bursts of 8 then a 1 ms sleep."""
|
|
49
|
+
count, threads, paced = c.get("count", 100_000), c.get("threads", 1), c.get("paced", True)
|
|
50
|
+
samples = [[] for _ in range(threads)]
|
|
51
|
+
|
|
52
|
+
def run(t):
|
|
53
|
+
out = samples[t]
|
|
54
|
+
log = _client.log
|
|
55
|
+
level = AuditLevel.INFO
|
|
56
|
+
for i in range(count // threads):
|
|
57
|
+
start = time.perf_counter_ns()
|
|
58
|
+
log(level, "invoice.approve", "Invoice approved", participant_id="u-1", correlation_id="c-1")
|
|
59
|
+
out.append(time.perf_counter_ns() - start)
|
|
60
|
+
if paced and i % 8 == 7:
|
|
61
|
+
time.sleep(0.001)
|
|
62
|
+
|
|
63
|
+
workers = [threading.Thread(target=run, args=(t,)) for t in range(threads)]
|
|
64
|
+
for w in workers:
|
|
65
|
+
w.start()
|
|
66
|
+
for w in workers:
|
|
67
|
+
w.join()
|
|
68
|
+
allv = sorted(v for s in samples for v in s)
|
|
69
|
+
|
|
70
|
+
def pct(p):
|
|
71
|
+
return allv[min(len(allv) - 1, int(len(allv) * p))] / 1000.0 if allv else 0.0
|
|
72
|
+
|
|
73
|
+
return {"calls": len(allv), "p50Us": pct(0.50), "p99Us": pct(0.99), "p999Us": pct(0.999), "maxUs": allv[-1] / 1000.0 if allv else 0.0}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _stats(_):
|
|
77
|
+
s = asdict(_client.stats())
|
|
78
|
+
return {"stats": {"logged": s["logged"], "sent": s["sent"], "duplicates": s["duplicates"], "spooled": s["spooled"],
|
|
79
|
+
"replayed": s["replayed"], "rejected": s["rejected"], "dropped": s["dropped"],
|
|
80
|
+
"droppedByReason": s["dropped_by_reason"], "internalErrors": s["internal_errors"],
|
|
81
|
+
"sendFailures": s["send_failures"], "breaker": s["breaker_state"]}}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def main():
|
|
85
|
+
ops = {"start": _start, "log": _log, "measure": _measure, "flush": lambda c: {"flushed": _client.flush(c.get("timeoutMs", 10000) / 1000.0)},
|
|
86
|
+
"stats": _stats, "close": lambda c: (_client.close(c.get("timeoutMs", 5000) / 1000.0), {})[1]}
|
|
87
|
+
for line in sys.stdin:
|
|
88
|
+
line = line.strip()
|
|
89
|
+
if not line:
|
|
90
|
+
continue
|
|
91
|
+
try:
|
|
92
|
+
command = json.loads(line)
|
|
93
|
+
if command.get("op") == "exit":
|
|
94
|
+
print(json.dumps({"ok": True}), flush=True)
|
|
95
|
+
return
|
|
96
|
+
result = ops[command["op"]](command)
|
|
97
|
+
result["ok"] = True
|
|
98
|
+
except Exception as ex: # noqa: BLE001 - a driver error is reported, never raised
|
|
99
|
+
result = {"ok": False, "error": "%s: %s" % (type(ex).__name__, ex)}
|
|
100
|
+
print(json.dumps(result), flush=True)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
if __name__ == "__main__":
|
|
104
|
+
main()
|
|
@@ -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,10 @@
|
|
|
1
|
+
ark_watch_client/__init__.py,sha256=BOtQMmTOK7vt6EswLMHQv3LONF_NZA4NhSk4KolR_oA,399
|
|
2
|
+
ark_watch_client/_pii.py,sha256=LZYlDd8zucA-jmfspuELMoG7BZ7a_Ihw0I1EQhaTlnI,2960
|
|
3
|
+
ark_watch_client/_spool.py,sha256=L8vGaRIQVP4_7pzOJjlZ6lqifaWZGNFpvvBRswEz-DY,6529
|
|
4
|
+
ark_watch_client/_ulid.py,sha256=Z7_tYhRisaMtsaoWvtsIuGxBkqTQvpL3NQk9TcOTEeM,765
|
|
5
|
+
ark_watch_client/client.py,sha256=eiupdnehOcZeaEQ05x0vJ887J8hblJ1sFzjb3j0yLr0,28092
|
|
6
|
+
ark_watch_client/conformance.py,sha256=5Lz-iOrzhWsqadWqF7Oj6bATaMXNSwdzKXgAYjpjx_g,4701
|
|
7
|
+
ark_watch_client-0.1.0.dist-info/METADATA,sha256=UosCtdG4CrfcXoWP78cTWksh8Sw8mp6uwOZZOhOWeAQ,3069
|
|
8
|
+
ark_watch_client-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
ark_watch_client-0.1.0.dist-info/licenses/LICENSE,sha256=hoqxAqr1oZ1MV-HsnrPagUHPWPTNcOHua6FQn-MkpXc,1067
|
|
10
|
+
ark_watch_client-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|