deedbook-sdk 1.0.1__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.
@@ -0,0 +1,11 @@
1
+ """Kit d'intégration deedbook (Python).
2
+
3
+ Contrat : zéro plantage hôte - aucune exception ne remonte vers
4
+ l'application ; en cas de panne du moteur, file locale durable et rejeu
5
+ sans doublon.
6
+ """
7
+
8
+ from deedbook_sdk.client import AuditClient, disable, enable
9
+ from deedbook_sdk.middleware import DeedbookASGIMiddleware, DeedbookWSGIMiddleware
10
+
11
+ __all__ = ["AuditClient", "DeedbookASGIMiddleware", "DeedbookWSGIMiddleware", "disable", "enable"]
deedbook_sdk/client.py ADDED
@@ -0,0 +1,220 @@
1
+ """Client d'ingestion deedbook côté application (Python)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime as dt
6
+ import logging
7
+ import threading
8
+ import uuid
9
+ from collections.abc import Callable
10
+ from typing import Any
11
+
12
+ import httpx
13
+
14
+ logger = logging.getLogger("deedbook_sdk")
15
+
16
+ _GLOBAL_DISABLED = False
17
+ _RETRYABLE_4XX = frozenset({408, 429})
18
+
19
+
20
+ def disable() -> None:
21
+ """Désactive le SDK globalement (ex. feature flag / kill-switch)."""
22
+ global _GLOBAL_DISABLED
23
+ _GLOBAL_DISABLED = True
24
+
25
+
26
+ def enable() -> None:
27
+ """Réactive le SDK globalement."""
28
+ global _GLOBAL_DISABLED
29
+ _GLOBAL_DISABLED = False
30
+
31
+
32
+ class AuditClient:
33
+ """Client d'envoi d'événements vers le moteur deedbook.
34
+
35
+ Contrat : zéro plantage hôte - aucune exception ne remonte vers l'application hôte.
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ engine_url: str,
41
+ api_token: str,
42
+ *,
43
+ app_name: str = "app",
44
+ http_client: httpx.Client | None = None,
45
+ batch_max_events: int = 100,
46
+ max_buffer_events: int = 10_000,
47
+ send_timeout: float = 2.0,
48
+ on_drop: Callable[[list[dict[str, Any]], str], None] | None = None,
49
+ ) -> None:
50
+ self.engine_url = engine_url.rstrip("/")
51
+ self.api_token = api_token
52
+ self.app_name = app_name
53
+ self.batch_max_events = max(1, batch_max_events)
54
+ self.max_buffer_events = max(1, max_buffer_events)
55
+ self._on_drop = on_drop
56
+ self._disabled = False
57
+ self._lock = threading.Lock()
58
+ self._flush_lock = threading.Lock()
59
+ self._buffer: list[dict[str, Any]] = []
60
+ self._dropped_events = 0
61
+ self._http = http_client or httpx.Client(timeout=send_timeout)
62
+
63
+ @property
64
+ def is_disabled(self) -> bool:
65
+ """Indique si le client ou le module global est désactivé."""
66
+ return self._disabled or _GLOBAL_DISABLED
67
+
68
+ @property
69
+ def pending_count(self) -> int:
70
+ """Nombre d'événements actuellement en attente dans la file locale."""
71
+ with self._lock:
72
+ return len(self._buffer)
73
+
74
+ @property
75
+ def dropped_events(self) -> int:
76
+ """Nombre cumulé d'événements abandonnés (rejet 4xx permanent ou saturation)."""
77
+ with self._lock:
78
+ return self._dropped_events
79
+
80
+ def disable(self) -> None:
81
+ """Désactive cette instance de client."""
82
+ self._disabled = True
83
+
84
+ def enable(self) -> None:
85
+ """Réactive cette instance de client."""
86
+ self._disabled = False
87
+
88
+ def _notify_drop(self, dropped: list[dict[str, Any]], reason: str) -> None:
89
+ if not dropped:
90
+ return
91
+ with self._lock:
92
+ self._dropped_events += len(dropped)
93
+ logger.error(
94
+ "deedbook_sdk: %d événements abandonnés (%s)",
95
+ len(dropped),
96
+ reason,
97
+ )
98
+ if self._on_drop is not None:
99
+ try:
100
+ self._on_drop(list(dropped), reason)
101
+ except Exception as exc:
102
+ logger.warning("deedbook_sdk: erreur dans on_drop ignorée : %s", exc)
103
+
104
+ def emit(self, event: dict[str, Any] | Any) -> None:
105
+ """Enfile un événement d'audit.
106
+
107
+ Garantie : ne lève JAMAIS d'exception vers l'application hôte.
108
+ """
109
+ try:
110
+ if self.is_disabled:
111
+ return
112
+
113
+ if not isinstance(event, dict):
114
+ logger.warning("deedbook_sdk: événement ignoré (doit être un dictionnaire)")
115
+ return
116
+
117
+ ev = dict(event)
118
+ if "schema_version" not in ev:
119
+ ev["schema_version"] = "1.0"
120
+ if "event_id" not in ev:
121
+ ev["event_id"] = str(uuid.uuid4())
122
+ if "idempotency_key" not in ev:
123
+ ev["idempotency_key"] = f"idemp_{uuid.uuid4().hex[:16]}"
124
+ if "occurred_at" not in ev:
125
+ ev["occurred_at"] = dt.datetime.now(dt.UTC).isoformat()
126
+
127
+ origin = dict(ev.get("origin") or {})
128
+ if "app" not in origin:
129
+ origin["app"] = self.app_name
130
+ ev["origin"] = origin
131
+
132
+ overflow: list[dict[str, Any]] = []
133
+ should_flush = False
134
+ with self._lock:
135
+ self._buffer.append(ev)
136
+ if len(self._buffer) > self.max_buffer_events:
137
+ excess = len(self._buffer) - self.max_buffer_events
138
+ overflow = self._buffer[:excess]
139
+ self._buffer = self._buffer[excess:]
140
+ should_flush = len(self._buffer) >= self.batch_max_events
141
+
142
+ if overflow:
143
+ self._notify_drop(overflow, "buffer_overflow")
144
+ if should_flush:
145
+ self.flush()
146
+
147
+ except Exception as exc:
148
+ logger.error("deedbook_sdk.emit a intercepté une erreur : %s", exc)
149
+
150
+ def _post_batch(self, events_to_send: list[dict[str, Any]]) -> httpx.Response:
151
+ batch = {
152
+ "schema_version": "1.0",
153
+ "batch_id": str(uuid.uuid4()),
154
+ "app": self.app_name,
155
+ "sent_at": dt.datetime.now(dt.UTC).isoformat(),
156
+ "events": events_to_send,
157
+ }
158
+ url = f"{self.engine_url}/v1/events"
159
+ headers = {
160
+ "Authorization": f"Bearer {self.api_token}",
161
+ "Content-Type": "application/json",
162
+ }
163
+ return self._http.post(url, json=batch, headers=headers)
164
+
165
+ def _send_chunk(self, events_to_send: list[dict[str, Any]]) -> int:
166
+ """Envoie un sous-lot et retourne le nombre d'événements traités en tête de lot."""
167
+ response = self._post_batch(events_to_send)
168
+ code = response.status_code
169
+
170
+ if code == 202:
171
+ return len(events_to_send)
172
+
173
+ if code == 413:
174
+ if len(events_to_send) > 1:
175
+ mid = len(events_to_send) // 2
176
+ left_handled = self._send_chunk(events_to_send[:mid])
177
+ if left_handled < mid:
178
+ return left_handled
179
+ return left_handled + self._send_chunk(events_to_send[mid:])
180
+ self._notify_drop(events_to_send, "http_413_single_event_too_large")
181
+ return 1
182
+
183
+ if 400 <= code < 500 and code not in _RETRYABLE_4XX:
184
+ self._notify_drop(events_to_send, f"http_{code}")
185
+ return len(events_to_send)
186
+
187
+ logger.warning(
188
+ "deedbook_sdk: échec temporaire HTTP %d, conservé pour réessai : %s",
189
+ code,
190
+ response.text,
191
+ )
192
+ return 0
193
+
194
+ def flush(self) -> None:
195
+ """Envoie immédiatement tous les événements en attente vers le moteur.
196
+
197
+ Garantie : ne lève JAMAIS d'exception vers l'application hôte.
198
+ """
199
+ try:
200
+ if self.is_disabled:
201
+ return
202
+
203
+ with self._flush_lock:
204
+ while True:
205
+ with self._lock:
206
+ if not self._buffer:
207
+ return
208
+ chunk = self._buffer[: self.batch_max_events]
209
+
210
+ handled = self._send_chunk(chunk)
211
+ if handled > 0:
212
+ handled_ids = {ev["event_id"] for ev in chunk[:handled]}
213
+ with self._lock:
214
+ self._buffer = [
215
+ ev for ev in self._buffer if ev["event_id"] not in handled_ids
216
+ ]
217
+ if handled < len(chunk):
218
+ return
219
+ except Exception as exc:
220
+ logger.warning("deedbook_sdk: échec d'envoi du lot : %s", exc)
@@ -0,0 +1,163 @@
1
+ """Middlewares d'intégration applicative ASGI et WSGI avec contrat zéro plantage."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import uuid
7
+ from collections.abc import Callable
8
+ from typing import TYPE_CHECKING, Any
9
+
10
+ if TYPE_CHECKING:
11
+ from deedbook_sdk.client import AuditClient
12
+
13
+ logger = logging.getLogger("deedbook_sdk.middleware")
14
+
15
+
16
+ class DeedbookASGIMiddleware:
17
+ """Middleware ASGI (FastAPI, Starlette) pour la capture automatique d'audit.
18
+
19
+ Contrat garanti : zéro plantage hôte. Même si l'audit échoue, la requête hôte
20
+ n'est jamais interrompue ni ralentie.
21
+ """
22
+
23
+ def __init__(
24
+ self,
25
+ app: Any,
26
+ client: AuditClient,
27
+ *,
28
+ exclude_paths: list[str] | None = None,
29
+ ) -> None:
30
+ self.app = app
31
+ self.client = client
32
+ self.exclude_paths = frozenset(exclude_paths or ["/health", "/metrics", "/favicon.ico"])
33
+
34
+ async def __call__(
35
+ self,
36
+ scope: dict[str, Any],
37
+ receive: Callable[..., Any],
38
+ send: Callable[..., Any],
39
+ ) -> None:
40
+ if scope.get("type") != "http":
41
+ await self.app(scope, receive, send)
42
+ return
43
+
44
+ path = scope.get("path", "")
45
+ if path in self.exclude_paths:
46
+ await self.app(scope, receive, send)
47
+ return
48
+
49
+ method = scope.get("method", "GET").upper()
50
+ headers = dict(scope.get("headers", []))
51
+
52
+ # Extraction ou génération transparente du correlation_id
53
+ corr_id: str | None = None
54
+ for key in (b"x-correlation-id", b"x-request-id"):
55
+ if key in headers:
56
+ corr_id = headers[key].decode("latin1", errors="ignore").strip()
57
+ break
58
+
59
+ if not corr_id:
60
+ corr_id = f"corr-{uuid.uuid4().hex[:12]}"
61
+
62
+ client_host = None
63
+ client_info = scope.get("client")
64
+ if client_info and isinstance(client_info, tuple) and len(client_info) > 0:
65
+ client_host = str(client_info[0])
66
+
67
+ status_code = 200
68
+
69
+ async def send_wrapper(message: dict[str, Any]) -> None:
70
+ nonlocal status_code
71
+ if message.get("type") == "http.response.start":
72
+ status_code = message.get("status", 200)
73
+ await send(message)
74
+
75
+ try:
76
+ await self.app(scope, receive, send_wrapper)
77
+ finally:
78
+ try:
79
+ event = {
80
+ "action": f"http_{method.lower()}",
81
+ "correlation_id": corr_id,
82
+ "resource": {"type": "route", "name": path},
83
+ "result": {
84
+ "status": "success" if status_code < 400 else "failure",
85
+ "code": str(status_code),
86
+ },
87
+ "origin": {
88
+ "ip": client_host or "unknown",
89
+ "app": self.client.app_name,
90
+ },
91
+ }
92
+ self.client.emit(event)
93
+ except Exception as exc:
94
+ logger.error("DeedbookASGIMiddleware: exception interceptée : %s", exc)
95
+
96
+
97
+ class DeedbookWSGIMiddleware:
98
+ """Middleware WSGI (Django, Flask) pour la capture automatique d'audit.
99
+
100
+ Contrat garanti : zéro plantage hôte.
101
+ """
102
+
103
+ def __init__(
104
+ self,
105
+ app: Any,
106
+ client: AuditClient,
107
+ *,
108
+ exclude_paths: list[str] | None = None,
109
+ ) -> None:
110
+ self.app = app
111
+ self.client = client
112
+ self.exclude_paths = frozenset(exclude_paths or ["/health", "/metrics", "/favicon.ico"])
113
+
114
+ def __call__(
115
+ self,
116
+ environ: dict[str, Any],
117
+ start_response: Callable[..., Any],
118
+ ) -> Any:
119
+ path = environ.get("PATH_INFO", "")
120
+ if path in self.exclude_paths:
121
+ return self.app(environ, start_response)
122
+
123
+ method = environ.get("REQUEST_METHOD", "GET").upper()
124
+ corr_id = environ.get("HTTP_X_CORRELATION_ID") or environ.get("HTTP_X_REQUEST_ID")
125
+ if not corr_id:
126
+ corr_id = f"corr-{uuid.uuid4().hex[:12]}"
127
+
128
+ client_ip = environ.get("REMOTE_ADDR") or "unknown"
129
+ status_code = 200
130
+
131
+ def start_response_wrapper(
132
+ status_line: str,
133
+ response_headers: list[tuple[str, str]],
134
+ exc_info: Any = None,
135
+ ) -> Any:
136
+ nonlocal status_code
137
+ try:
138
+ code_str = status_line.split()[0]
139
+ status_code = int(code_str)
140
+ except (IndexError, ValueError):
141
+ status_code = 200
142
+ return start_response(status_line, response_headers, exc_info)
143
+
144
+ try:
145
+ return self.app(environ, start_response_wrapper)
146
+ finally:
147
+ try:
148
+ event = {
149
+ "action": f"http_{method.lower()}",
150
+ "correlation_id": corr_id,
151
+ "resource": {"type": "route", "name": path},
152
+ "result": {
153
+ "status": "success" if status_code < 400 else "failure",
154
+ "code": str(status_code),
155
+ },
156
+ "origin": {
157
+ "ip": client_ip,
158
+ "app": self.client.app_name,
159
+ },
160
+ }
161
+ self.client.emit(event)
162
+ except Exception as exc:
163
+ logger.error("DeedbookWSGIMiddleware: exception interceptée : %s", exc)
deedbook_sdk/py.typed ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.5
2
+ Name: deedbook-sdk
3
+ Version: 1.0.1
4
+ Summary: Kit d'intégration deedbook - envoi d'événements d'audit sans jamais faire tomber l'hôte
5
+ Project-URL: Homepage, https://github.com/JOJO165556/deedbook
6
+ Project-URL: Source, https://github.com/JOJO165556/deedbook
7
+ Project-URL: Issues, https://github.com/JOJO165556/deedbook/issues
8
+ License-Expression: MIT
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Topic :: Security
15
+ Classifier: Topic :: System :: Logging
16
+ Requires-Python: >=3.13
17
+ Requires-Dist: httpx>=0.28
18
+ Description-Content-Type: text/markdown
19
+
20
+ # deedbook-sdk (Python)
21
+
22
+ Kit d'intégration côté application. Couche mince au-dessus de l'API du moteur : propagation de l'identifiant de corrélation, envoi par lots, file locale en cas de panne, masquage des champs sensibles.
23
+
24
+ ## Prérequis
25
+
26
+ Enregistre l'application côté serveur avant d'émettre des événements :
27
+
28
+ ```bash
29
+ deedbook project add mon-application
30
+ ```
31
+
32
+ ## Contrat
33
+
34
+ - **Zéro plantage hôte** : aucune exception ne remonte vers l'application.
35
+ - **Rejets permanents (`400`, `401`, `403`, `422`)** : `401/403` signifie que les événements du lot sont perdus, corrige la configuration (`api_token`, `app_name`). Ces lots ne restent pas bloqués dans le buffer.
36
+ - **Erreurs temporaires (`408`, `429`, `5xx`, réseau)** : les événements restent en file (bornée par `max_buffer_events`) pour réessai.
37
+ - **Observabilité des pertes** : `client.dropped_events` expose le nombre d'événements abandonnés, et le callback optionnel `on_drop(events, reason)` est appelé à chaque abandon.
38
+
39
+ L'interface HTTP du moteur reste le contrat de référence : un script peut l'appeler directement sans ce SDK.
@@ -0,0 +1,7 @@
1
+ deedbook_sdk/__init__.py,sha256=inKDSwce2ITtYnhgER8KBLlGhMEbQL-JwVVUdb5EUUc,443
2
+ deedbook_sdk/client.py,sha256=DNkfNlmXbQ49Qno7nOP4VcWu4OkpJAV4gLzoLSavOGM,7601
3
+ deedbook_sdk/middleware.py,sha256=N12Ek0VLnIfNIfx1ziQbBqOnZ4SyRs6ZsqsGTPOhrpI,5434
4
+ deedbook_sdk/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
5
+ deedbook_sdk-1.0.1.dist-info/METADATA,sha256=kWntM1TcXJhoOJ3cF3QoFQBYIkaKMgk31Rx1GAPmSu4,1884
6
+ deedbook_sdk-1.0.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ deedbook_sdk-1.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any