From 13809387a0bada61fb1b2fa6ab3432e0980ee38d Mon Sep 17 00:00:00 2001 From: docker24001 Date: Wed, 4 Nov 2026 22:17:20 +0000 Subject: [PATCH] =?UTF-8?q?fix(#37):=20@atraced=20sur=20toutes=20les=20cor?= =?UTF-8?q?outines=20de=20src/,=20r=C3=A8gle=20v=C3=A9rifi=C3=A9e=20par=20?= =?UTF-8?q?un=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 10 +++++ src/pystashtemplate/indexer.py | 10 ++--- src/pystashtemplate/outputs/syslog.py | 6 +-- src/pystashtemplate/service.py | 6 ++- tests/test_tracing.py | 56 +++++++++++++++++++++++++++ 5 files changed, 78 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 226a2ca..b9e2123 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,16 @@ le projet suit SemVer. ## [Non publié] +### Corrections + +- Traçage asynchrone (#37, audit du 04/11) : les fonctions `async def` + arrivées après la v0.2.0 (`indexer.py`, `service.py`, + `outputs/syslog.py`) portaient `@traced`, qui journalise la sortie + avant l'`await`, ou aucun décorateur. Elles passent à `@atraced` ; un + test (`tests/test_tracing.py::TestRegleAtraced`) fait désormais + respecter la règle sur tout `src/` (seules exceptions : méthodes + abstraites, signatures de Protocol, générateurs asynchrones). + ### Documentation - README largement repris (#117, suite de #115) : architecture, démarrage diff --git a/src/pystashtemplate/indexer.py b/src/pystashtemplate/indexer.py index 72a189d..fd4514b 100644 --- a/src/pystashtemplate/indexer.py +++ b/src/pystashtemplate/indexer.py @@ -35,7 +35,7 @@ from pystashtemplate.outputs.elasticsearch_bulk import SendOutcome as _SortieOutcome from pystashtemplate.outputs.opensearch import OpenSearchOutput from pystashtemplate.templates import CompiledTemplate, compile_template, render -from pystashtemplate.tracing import traced +from pystashtemplate.tracing import atraced, traced OPENSEARCH_TIMEOUT = 3.0 # secondes, timeout socket du client OpenSearch @@ -190,7 +190,7 @@ def __init__( options["ssl_key"] = client_key self.sortie = OpenSearchOutput(options, dlq=dlq) - @traced + @atraced async def health(self) -> dict[str, Any]: """Interroge le cluster (GET /) : sa version, ou lève l'erreur. @@ -229,7 +229,7 @@ def _document_id(self, doc: dict) -> str | None: rendered = render(self._document_id_template, doc, on_missing="empty") return rendered or None - @traced + @atraced async def _client(self): """Client httpx paresseux de la sortie (couture : template d'index). @@ -239,7 +239,7 @@ async def _client(self): """ return self.sortie._client_http() - @traced + @atraced async def send( self, doc: dict, @@ -308,7 +308,7 @@ async def send( return SendOutcome.INDEXED return SendOutcome.RETRYABLE - @traced + @atraced async def close(self) -> None: """Ferme proprement la sortie (et son client HTTP).""" await self.sortie.close() diff --git a/src/pystashtemplate/outputs/syslog.py b/src/pystashtemplate/outputs/syslog.py index f94db41..81ff841 100644 --- a/src/pystashtemplate/outputs/syslog.py +++ b/src/pystashtemplate/outputs/syslog.py @@ -491,7 +491,7 @@ def __init__(self, hote: str, port: int, protocole: str, framing: str, contexte_ self._udp: Any = None logger.debug("_TransportReseau.__init__ | sortie") - @traced + @atraced async def ouvrir_udp(self) -> Any: """Ouvre un socket UDP vers la destination.""" transport, _ = await asyncio.get_event_loop().create_datagram_endpoint( @@ -500,7 +500,7 @@ async def ouvrir_udp(self) -> Any: ) return transport - @traced + @atraced async def ecrire(self, trames: list[bytes]) -> None: """Écrit les trames : datagrammes UDP, ou flux TCP reconnecté.""" if self._protocole == "udp": @@ -521,7 +521,7 @@ async def ecrire(self, trames: list[bytes]) -> None: self._writer.write(trame) await self._writer.drain() - @traced + @atraced async def fermer(self) -> None: """Ferme la connexion TCP ouverte.""" if self._writer is not None: diff --git a/src/pystashtemplate/service.py b/src/pystashtemplate/service.py index f216fb6..35c3462 100644 --- a/src/pystashtemplate/service.py +++ b/src/pystashtemplate/service.py @@ -149,7 +149,7 @@ def analyser_syslog(trame: bytes) -> dict[str, Any] | None: return None -@traced +@atraced async def _lire_trame(lecteur: asyncio.StreamReader) -> bytes | None: """Lit UNE trame syslog TCP (RFC 6587) : octet-counting ou LF. @@ -181,7 +181,7 @@ async def _lire_trame(lecteur: asyncio.StreamReader) -> bytes | None: tampon += octet -@traced +@atraced async def _lire_requete(lecteur: asyncio.StreamReader) -> tuple[list[bytes] | None, bytes]: """Lit UNE requête HTTP POST ; rend les documents du corps. @@ -247,6 +247,7 @@ def liaison(self) -> tuple[str, int]: async def demarrer(self, service: "Service") -> None: """Ouvre l'écoute : chaque connexion nourrit la file du service.""" + @atraced async def servir(lecteur: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: logger.debug("EntreeSyslogTcp.servir | connexion acceptée") self._connexions.add(writer) @@ -405,6 +406,7 @@ def liaison(self) -> tuple[str, int]: async def demarrer(self, service: "Service") -> None: """Ouvre l'écoute : chaque `POST` nourrit la file du service.""" + @atraced async def servir(lecteur: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: logger.debug("EntreeHttp.servir | connexion acceptée") self._connexions.add(writer) diff --git a/tests/test_tracing.py b/tests/test_tracing.py index 67c2b7c..accde07 100644 --- a/tests/test_tracing.py +++ b/tests/test_tracing.py @@ -8,8 +8,10 @@ from __future__ import annotations +import ast import asyncio import inspect +from pathlib import Path import pytest from loguru import logger @@ -95,3 +97,57 @@ async def secret(mot_de_passe: str) -> str: finally: logger.remove(sink) assert not any("s3cret" in m or "S3CRET" in m for m in messages) + + +def _coroutines_de_src() -> list[tuple[str, ast.AsyncFunctionDef]]: + """Toutes les fonctions `async def` de `src/pystashtemplate` (chemin, nœud).""" + racine = Path(__file__).resolve().parents[1] / "src" / "pystashtemplate" + trouvees: list[tuple[str, ast.AsyncFunctionDef]] = [] + for chemin in sorted(racine.rglob("*.py")): + arbre = ast.parse(chemin.read_text(encoding="utf-8")) + for noeud in ast.walk(arbre): + if isinstance(noeud, ast.AsyncFunctionDef): + trouvees.append((f"{chemin.relative_to(racine)}:{noeud.lineno} {noeud.name}", noeud)) + return trouvees + + +def _decorateurs(noeud: ast.AsyncFunctionDef) -> set[str]: + return {ast.unparse(d).split("(")[0].rsplit(".", 1)[-1] for d in noeud.decorator_list} + + +def _exemptee(noeud: ast.AsyncFunctionDef) -> bool: + """Méthode abstraite, signature de Protocol (corps vide), générateur asynchrone, ou `atraced` lui-même.""" + if "abstractmethod" in _decorateurs(noeud) or noeud.name == "wrapper": + return True + corps = [n for n in noeud.body if not (isinstance(n, ast.Expr) and isinstance(n.value, ast.Constant))] + if not corps: + return True + # `atraced` attend une coroutine : il ne s'applique pas à un générateur asynchrone (`yield`). + return any(isinstance(n, (ast.Yield, ast.YieldFrom)) for n in ast.walk(noeud)) + + +class TestRegleAtraced: + """Critère de #37 : toutes les fonctions `async def` de `src/` sont décorées `@atraced`.""" + + def test_inventaire_non_vide(self) -> None: + assert len(_coroutines_de_src()) > 100 + + def test_aucun_traced_sur_une_coroutine(self) -> None: + # `@traced` sur une coroutine journalise la « sortie » avant même l'`await`. + fautives = [nom for nom, noeud in _coroutines_de_src() if "traced" in _decorateurs(noeud)] + assert fautives == [] + + def test_toutes_les_coroutines_sont_atraced(self) -> None: + manquantes = [ + nom for nom, noeud in _coroutines_de_src() if not _exemptee(noeud) and "atraced" not in _decorateurs(noeud) + ] + assert manquantes == [] + + def test_exemptions(self) -> None: + source = ( + "async def protocole(self):\n '''Signature seule.'''\n" + "async def generateur(self):\n yield 1\n" + "async def normale(self):\n return 1\n" + ) + noeuds = [n for n in ast.parse(source).body if isinstance(n, ast.AsyncFunctionDef)] + assert [_exemptee(n) for n in noeuds] == [True, True, False]