From 9c46c3cbf4271c9c7347a72db2791ebdaae68d12 Mon Sep 17 00:00:00 2001 From: docker24017 <350791397+docker24017@users.noreply.github.com> Date: Tue, 3 Nov 2026 22:36:05 +0000 Subject: [PATCH 1/2] feat(#36): FilterPipeline.apply asynchrone, step dns attendu MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - FilterPipeline.apply async : steps réseau (dns) attendus, filtres CPU en ligne, ordre et options communes inchangés - _compile_step : step "dns" (options du plugin dns du .conf) - interpréteur : _apply_filters_json attend le pipeline - tests : appels convertis en _run(), step dns couvert (hostsfile local) - uv.lock : version locale alignée sur pyproject 0.2.0 --- CHANGELOG.md | 7 +++++ src/pystashtemplate/filters.py | 28 +++++++++++++++-- src/pystashtemplate/interpreter.py | 6 ++-- tests/test_filters.py | 13 ++++++-- tests/test_filters_complements.py | 48 ++++++++++++++++++++++++++++-- tests/test_filters_date.py | 28 ++++++++--------- tests/test_translate.py | 2 +- uv.lock | 2 +- 8 files changed, 106 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9237239..384b22f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ le projet suit SemVer. ### Évolutions +- `FilterPipeline.apply` devient asynchrone (issue #36, chantier full async #1) : + les steps réseau sont attendus — nouveau step `dns` (mêmes options que le + plugin `dns` du `.conf`), sans réseau pour les filtres CPU (dissect, + regex, kv, mutate, geoip, translate, date, drop), ordre de la chaîne et + options communes inchangés. Changement d'API : `await` requis par les + appelants directs de `FilterPipeline.apply` (le pont `filters_json` de + l'interpréteur l'attend déjà). - `DnsFilter.apply` devient asynchrone (issue #35, chantier full async #1) : la résolution réseau passe par `dns.asyncresolver` (vraie concurrence réseau) ; caches, délais, essais et `PYSTASHTEMPLATE_DNS=off` diff --git a/src/pystashtemplate/filters.py b/src/pystashtemplate/filters.py index ed10328..2faeeff 100644 --- a/src/pystashtemplate/filters.py +++ b/src/pystashtemplate/filters.py @@ -42,6 +42,7 @@ import yaml from loguru import logger +from pystashtemplate.dnslookup import DnsFilter from pystashtemplate.enrichment import GeoIPLookup, TranslateDictionary from pystashtemplate.i18n import _ from pystashtemplate.templates import ( @@ -1584,7 +1585,12 @@ def load_word_list(path: str) -> list[str]: class FilterPipeline: - """Chaîne de filtres façon Logstash (dissect, regex, kv, drop, mutate, geoip, translate, date), en séquence.""" + """Chaîne de filtres façon Logstash (dissect, regex, kv, drop, mutate, geoip, translate, date, dns), en séquence. + + `apply` est asynchrone depuis #36 (chantier full async #1) : les steps + réseau (`dns`) sont attendus ; les filtres CPU (dissect, regex, kv, + mutate…) restent exécutés en ligne. + """ @traced def __init__( @@ -1622,7 +1628,9 @@ def __init__( attend "match" ([champ, motif, ...], requis) et "target"/"timezone"/"tag_on_failure" (optionnels) : voir `DateFilter`, identique au plugin `date` de - `--pipeline-conf`. Voir + `--pipeline-conf`. "dns" (depuis #36) reprend les options + du plugin `dns` du `.conf` (voir `dnslookup.DnsFilter`) : + résolution réseau asynchrone, `await`ée par `apply`. Voir filters.example.json et blocklist.example.txt. geoip_lookup_factory: Callable construisant une `enrichment.GeoIPLookup` à partir d'un chemin de base, @@ -1678,6 +1686,9 @@ def _compile_step(self, step: dict) -> tuple[str | None, object, str | None]: if not DateFilter.match_valide(options.get("match")): raise ValueError("filtre date : 'match' doit valoir [champ, motif, ...]") return None, DateFilter(options), None + if filter_type == "dns": + options = {key: value for key, value in step.items() if key not in ("type", "_comment")} + return None, DnsFilter(options), None source = step["source"] target = step.get("target") if filter_type == "dissect": @@ -1712,9 +1723,17 @@ def _compile_step(self, step: dict) -> tuple[str | None, object, str | None]: return source, compiled, target @traced - def apply(self, doc: dict, *, now: datetime | None = None, on_missing: str = "keep") -> bool: + async def apply(self, doc: dict, *, now: datetime | None = None, on_missing: str = "keep") -> bool: """Applique chaque filtre de la chaîne à doc, en place. + Asynchrone depuis #36 (chantier full async #1) : les steps réseau + (`dns`) sont attendus (`await`) ; les filtres CPU (dissect, regex, + kv, mutate, geoip, translate, date, drop) restent exécutés en + ligne, l'ordre de la chaîne est inchangé. Comme le plugin `dns` + du `.conf`, un step `dns` qui échoue (délai dépassé, valeur + refusée) n'écarte pas le document : la chaîne continue, sans + options communes à appliquer ici. + Un filtre "dissect"/"regex"/"kv" dont le champ source est absent, non textuel, ou dont le patron ne correspond pas est ignoré pour ce message (log en DEBUG) plutôt que de faire échouer tout le document. @@ -1740,6 +1759,9 @@ def apply(self, doc: dict, *, now: datetime | None = None, on_missing: str = "ke (aucun traitement ultérieur ne doit avoir lieu), True sinon. """ for source, compiled, target in self._steps: + if isinstance(compiled, DnsFilter): + await compiled.apply(doc) + continue if isinstance(compiled, MutateFilter): compiled.apply(doc, now=now, on_missing=on_missing) continue diff --git a/src/pystashtemplate/interpreter.py b/src/pystashtemplate/interpreter.py index ef0bea8..6447f5c 100644 --- a/src/pystashtemplate/interpreter.py +++ b/src/pystashtemplate/interpreter.py @@ -714,7 +714,7 @@ async def _run_filter_plugin( elif name == "geoip": reussi = self._apply_geoip(doc, options) elif name == "filters_json": - self._apply_filters_json(doc, options, now=now, on_missing=on_missing) + await self._apply_filters_json(doc, options, now=now, on_missing=on_missing) elif name == "date": reussi = self._apply_date(doc, options) elif name == "drop": @@ -1236,7 +1236,7 @@ def _geoip_lookup_failure(doc: dict[str, Any], options: dict[str, Any]) -> None: add_failure_tags(doc, options.get("tag_on_failure", ["_geoip_lookup_failure"])) @traced - def _apply_filters_json( + async def _apply_filters_json( self, doc: dict[str, Any], options: dict[str, Any], *, now: datetime | None, on_missing: str ) -> None: """`filters_json { path => "..." [on_missing => "keep"|"empty"] }` (session 18). @@ -1280,7 +1280,7 @@ def _apply_filters_json( return self._filter_pipelines[path] = pipeline step_on_missing = options.get("on_missing", "keep") - if not pipeline.apply(doc, now=now, on_missing=step_on_missing): + if not await pipeline.apply(doc, now=now, on_missing=step_on_missing): raise _DocumentDropped @traced diff --git a/tests/test_filters.py b/tests/test_filters.py index a65cd6b..c18a6fe 100644 --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -4,6 +4,8 @@ from __future__ import annotations +import asyncio + import pytest from pystashtemplate.filters import ( @@ -17,6 +19,11 @@ ) +def _run(coro): + # Sans pytest-asyncio (convention du dépôt, cf. RsysLogstach) : asyncio.run direct (#34). + return asyncio.run(coro) + + class TestDissect: def test_apply_basique(self) -> None: d = Dissector("%{date} %{time} %{hostname} %{message}") @@ -275,9 +282,9 @@ def test_chaine_dissect_puis_drop(self) -> None: pipeline = FilterPipeline(steps) doc_ok = {"message": "app1 INFO connexion ok"} doc_drop = {"message": "app1 INFO healthcheck"} - assert pipeline.apply(doc_ok) is True + assert _run(pipeline.apply(doc_ok)) is True assert doc_ok["parsed"] == {"src": "app1", "level": "INFO", "msg": "connexion ok"} - assert pipeline.apply(doc_drop) is False + assert _run(pipeline.apply(doc_drop)) is False def test_mutate_dans_la_chaine(self) -> None: # Chemin imbriqué : syntaxe à crochets %{...} ("[parsed][port]"), @@ -285,7 +292,7 @@ def test_mutate_dans_la_chaine(self) -> None: steps = [{"type": "mutate", "convert": {"[parsed][port]": "integer"}}] pipeline = FilterPipeline(steps) doc = {"parsed": {"port": "22"}} - pipeline.apply(doc) + _run(pipeline.apply(doc)) assert doc["parsed"]["port"] == 22 def test_step_type_inconnu_leve(self) -> None: diff --git a/tests/test_filters_complements.py b/tests/test_filters_complements.py index e5ee19e..a134f2c 100644 --- a/tests/test_filters_complements.py +++ b/tests/test_filters_complements.py @@ -12,6 +12,7 @@ from __future__ import annotations +import asyncio from pathlib import Path import pytest @@ -27,6 +28,11 @@ ) +def _run(coro): + # Sans pytest-asyncio (convention du dépôt, cf. RsysLogstach) : asyncio.run direct (#34). + return asyncio.run(coro) + + class TestConvertValueDocumentationLogstash: """https://www.elastic.co/docs/reference/logstash/plugins/plugins-filters-mutate (option convert).""" @@ -201,7 +207,7 @@ def test_pipeline_json_geolocalise_et_ferme(self, base_geoip_city: str) -> None: [{"type": "geoip", "source": "[client][ip]", "database": base_geoip_city, "fields": ["city_name"]}] ) doc = {"client": {"ip": IP_STRASBOURG}} - assert pipeline.apply(doc) is True + assert _run(pipeline.apply(doc)) is True pipeline.close() assert doc["geoip"] == {"city_name": "Strasbourg"} @@ -252,7 +258,7 @@ def dico(self, tmp_path: Path) -> str: ) def test_dans_un_pipeline_json(self, dico: str, doc: dict, options: dict, attendu) -> None: step = {"type": "translate", "dictionary_path": dico, "source": "i", "target": "[if][nom]", **options} - FilterPipeline([step]).apply(doc, on_missing="empty") + _run(FilterPipeline([step]).apply(doc, on_missing="empty")) assert doc["if"]["nom"] == attendu def test_sans_correspondance_ni_fallback(self, dico: str) -> None: @@ -273,6 +279,42 @@ def test_dictionnaire_illisible(self, tmp_path: Path, contenu: str | None) -> No TranslateFilter({"dictionary_path": str(chemin), "source": "i", "target": "nom"}) +class TestStepDns: + def test_step_dns_resoud_via_hostsfile(self, tmp_path) -> None: + # #36 : step "dns" attendu par FilterPipeline.apply (chaîne async) ; + # résolution locale (fichier hosts), aucun réseau. + hosts = tmp_path / "hosts" + hosts.write_text("10.0.0.1 web.local\n", encoding="utf-8") + pipeline = FilterPipeline( + [ + {"type": "dissect", "source": "m", "pattern": "%{hote} %{reste}"}, + { + "type": "dns", + "resolve": ["hote"], + "action": "replace", + "hostsfile": [str(hosts)], + }, + ] + ) + doc = {"m": "web.local reste"} + assert _run(pipeline.apply(doc)) is True + assert doc == {"m": "web.local reste", "hote": "10.0.0.1", "reste": "reste"} + + def test_step_dns_echec_ne_cartent_pas_le_document(self, tmp_path) -> None: + # Comme le plugin `dns` du `.conf` : un échec (nom inconnu) arrête + # le filtre dns mais pas la chaîne — le document continue. + hosts = tmp_path / "hosts" + hosts.write_text("10.0.0.1 web.local\n", encoding="utf-8") + pipeline = FilterPipeline([{"type": "dns", "resolve": ["h"], "action": "replace", "hostsfile": [str(hosts)]}]) + doc = {"h": "inconnu", "autre": 1} + assert _run(pipeline.apply(doc)) is True + assert doc == {"h": "inconnu", "autre": 1} + + def test_step_dns_option_invalide_leve_a_la_compilation(self) -> None: + with pytest.raises(ValueError, match="dns"): + FilterPipeline([{"type": "dns", "action": "supprimer"}]) + + class TestFilterPipelineComplements: def test_regex_vers_target_et_sans_correspondance(self) -> None: pipeline = FilterPipeline( @@ -283,7 +325,7 @@ def test_regex_vers_target_et_sans_correspondance(self) -> None: ] ) doc = {"msg": "IFNET/4: lien up", "parsed": {"deja": 1}} - assert pipeline.apply(doc) is True + assert _run(pipeline.apply(doc)) is True assert doc["parsed"] == {"deja": 1, "mod": "IFNET", "sev": "4"} def test_drop_sans_mots(self) -> None: diff --git a/tests/test_filters_date.py b/tests/test_filters_date.py index edd9981..5e7f93a 100644 --- a/tests/test_filters_date.py +++ b/tests/test_filters_date.py @@ -34,12 +34,12 @@ class TestStepDateFilters: def test_iso8601_vers_timestamp(self): doc = {"horodatage": "2026-10-24T08:15:00+02:00"} - assert _pipeline(match=["horodatage", "ISO8601"]).apply(doc) is True + assert _run(_pipeline(match=["horodatage", "ISO8601"]).apply(doc)) is True assert doc["@timestamp"] == "2026-10-24T06:15:00+00:00" def test_iso8601_suffixe_z(self): doc = {"t": "2026-10-24T06:15:00Z"} - _pipeline(match=["t", "ISO8601"]).apply(doc) + _run(_pipeline(match=["t", "ISO8601"]).apply(doc)) assert doc["@timestamp"] == "2026-10-24T06:15:00+00:00" @pytest.mark.parametrize( @@ -48,57 +48,57 @@ def test_iso8601_suffixe_z(self): ) def test_epoch(self, motif, valeur): doc = {"t": valeur} - _pipeline(match=["t", motif]).apply(doc) + _run(_pipeline(match=["t", motif]).apply(doc)) assert doc["@timestamp"] == "2026-10-24T06:15:00+00:00" def test_motif_joda_avec_fuseau_iana(self): doc = {"t": "Oct 24 2026 08:15:00"} - _pipeline(match=["t", "MMM dd yyyy HH:mm:ss"], timezone="Europe/Paris").apply(doc) + _run(_pipeline(match=["t", "MMM dd yyyy HH:mm:ss"], timezone="Europe/Paris").apply(doc)) assert doc["@timestamp"] == "2026-10-24T06:15:00+00:00" def test_fuseau_inconnu_retombe_sur_utc(self): doc = {"t": "2026-10-24 06:15:00"} - _pipeline(match=["t", "yyyy-MM-dd HH:mm:ss"], timezone="Pas/Un_Fuseau").apply(doc) + _run(_pipeline(match=["t", "yyyy-MM-dd HH:mm:ss"], timezone="Pas/Un_Fuseau").apply(doc)) assert doc["@timestamp"] == "2026-10-24T06:15:00+00:00" def test_sss_et_zone_textuelle_dans_le_step(self): # #118 : SSS + « CET » (+01:00) → 05:15:00.123 UTC. doc = {"t": "2026-10-24 06:15:00.123 CET"} - _pipeline(match=["t", "yyyy-MM-dd HH:mm:ss.SSS z"]).apply(doc) + _run(_pipeline(match=["t", "yyyy-MM-dd HH:mm:ss.SSS z"]).apply(doc)) assert doc["@timestamp"] == "2026-10-24T05:15:00.123000+00:00" def test_locale_dans_le_step(self): # #118 : option `locale` du plugin officiel, noms français. doc = {"t": "lun. 24 oct. 2026 06:15:00"} - _pipeline(match=["t", "EEE dd MMM yyyy HH:mm:ss"], locale="fr").apply(doc) + _run(_pipeline(match=["t", "EEE dd MMM yyyy HH:mm:ss"], locale="fr").apply(doc)) assert doc["@timestamp"] == "2026-10-24T06:15:00+00:00" def test_premier_motif_qui_correspond(self): doc = {"t": "24/10/2026 06:15"} - _pipeline(match=["t", "ISO8601", 42, "dd/MM/yyyy HH:mm"]).apply(doc) + _run(_pipeline(match=["t", "ISO8601", 42, "dd/MM/yyyy HH:mm"]).apply(doc)) assert doc["@timestamp"] == "2026-10-24T06:15:00+00:00" assert "tags" not in doc def test_target_imbrique(self): doc = {"evt": {"t": "2026-10-24T06:15:00Z"}} - _pipeline(match=["[evt][t]", "ISO8601"], target="[evt][date]").apply(doc) + _run(_pipeline(match=["[evt][t]", "ISO8601"], target="[evt][date]").apply(doc)) assert doc["evt"]["date"] == "2026-10-24T06:15:00+00:00" assert "@timestamp" not in doc def test_echec_tag_par_defaut(self): doc = {"t": "pas une date"} - assert _pipeline(match=["t", "ISO8601"]).apply(doc) is True # date n'écarte jamais le document + assert _run(_pipeline(match=["t", "ISO8601"]).apply(doc)) is True # date n'écarte jamais le document assert doc["tags"] == ["_dateparsefailure"] assert "@timestamp" not in doc def test_champ_absent_tag_personnalise(self): doc = {"tags": ["deja"]} - _pipeline(match=["t", "ISO8601"], tag_on_failure=["_date_ko"]).apply(doc) + _run(_pipeline(match=["t", "ISO8601"], tag_on_failure=["_date_ko"]).apply(doc)) assert doc["tags"] == ["deja", "_date_ko"] def test_champ_none(self): doc = {"t": None} - _pipeline(match=["t", "ISO8601"]).apply(doc) + _run(_pipeline(match=["t", "ISO8601"]).apply(doc)) assert doc["tags"] == ["_dateparsefailure"] def test_suite_de_la_chaine_executee(self): @@ -108,7 +108,7 @@ def test_suite_de_la_chaine_executee(self): {"type": "mutate", "remove_field": ["quand"]}, ] doc = {"message": "2026-10-24T06:15:00Z bonjour"} - assert FilterPipeline(steps).apply(doc) is True + assert _run(FilterPipeline(steps).apply(doc)) is True assert doc["@timestamp"] == "2026-10-24T06:15:00+00:00" assert "quand" not in doc assert doc["reste"] == "bonjour" @@ -138,7 +138,7 @@ def test_meme_resultat_que_le_plugin_conf(self): doc_conf = {"t": "24/10/2026 08:15"} _run(PipelineInterpreter(conf).apply(doc_conf)) # modifie le document en place doc_json = {"t": "24/10/2026 08:15"} - _pipeline(match=["t", "dd/MM/yyyy HH:mm"], timezone="Europe/Paris").apply(doc_json) + _run(_pipeline(match=["t", "dd/MM/yyyy HH:mm"], timezone="Europe/Paris").apply(doc_json)) assert doc_conf["@timestamp"] == doc_json["@timestamp"] == "2026-10-24T06:15:00+00:00" diff --git a/tests/test_translate.py b/tests/test_translate.py index 15c3faa..d514218 100644 --- a/tests/test_translate.py +++ b/tests/test_translate.py @@ -356,5 +356,5 @@ def test_dictionnaire_partage_par_chemin(self, tmp_path: Path) -> None: def test_step_filters_json(self) -> None: doc = {"c": "a"} - FilterPipeline([{"type": "translate", "source": "c", "dictionary": {"a": "A"}}]).apply(doc) + _run(FilterPipeline([{"type": "translate", "source": "c", "dictionary": {"a": "A"}}]).apply(doc)) assert doc == {"c": "A"} diff --git a/uv.lock b/uv.lock index 8813113..87e9bb1 100644 --- a/uv.lock +++ b/uv.lock @@ -1602,7 +1602,7 @@ wheels = [ [[package]] name = "pystashtemplate" -version = "0.1.0" +version = "0.2.0" source = { editable = "." } dependencies = [ { name = "aiohttp" }, From 4669ba83baef181825674dcf8095fa6bc1b55dbf Mon Sep 17 00:00:00 2001 From: docker24017 <350791397+docker24017@users.noreply.github.com> Date: Tue, 3 Nov 2026 22:40:38 +0000 Subject: [PATCH 2/2] =?UTF-8?q?feat(#37):=20atraced,=20=C3=A9quivalent=20a?= =?UTF-8?q?synchrone=20de=20traced?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - tracing.py : décorateur atraced — sortie journalisée quand la coroutine se termine (autour du await), pas à sa création - toutes les fonctions async def de src/ décorées (remplacement de @traced, ajout sur les non décorées hors stubs/abstractmethod) - audit_debug_sorties : @atraced reconnu comme trace structurelle - tests/test_tracing.py : entrée/sortie, exception propagée, introspection (functools.wraps), secrets jamais journalisés --- CHANGELOG.md | 6 ++ scripts/audit_debug_sorties.py | 7 +- src/pystashtemplate/dlq.py | 4 +- src/pystashtemplate/dnslookup.py | 24 ++--- src/pystashtemplate/filters.py | 4 +- src/pystashtemplate/interpreter.py | 13 +-- src/pystashtemplate/outputs/base.py | 4 +- .../outputs/elasticsearch_bulk.py | 18 ++-- src/pystashtemplate/outputs/lotisseur.py | 14 ++- src/pystashtemplate/outputs/null.py | 5 + src/pystashtemplate/outputs/transport.py | 6 ++ src/pystashtemplate/tracing.py | 39 +++++++- tests/test_tracing.py | 97 +++++++++++++++++++ 13 files changed, 207 insertions(+), 34 deletions(-) create mode 100644 tests/test_tracing.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 384b22f..3459a44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ le projet suit SemVer. ### Évolutions +- `atraced` (issue #37, chantier full async #1) : équivalent asynchrone de + `@traced` dans `tracing.py` — la sortie est journalisée quand la + coroutine se termine réellement (autour du `await`), et non dès sa + création. Toutes les fonctions `async def` de `src/` sont décorées + (remplacement de `@traced`, ajout sur les non décorées) ; + `audit_debug_sorties` reconnaît `@atraced` comme trace structurelle. - `FilterPipeline.apply` devient asynchrone (issue #36, chantier full async #1) : les steps réseau sont attendus — nouveau step `dns` (mêmes options que le plugin `dns` du `.conf`), sans réseau pour les filtres CPU (dissect, diff --git a/scripts/audit_debug_sorties.py b/scripts/audit_debug_sorties.py index a15f92d..5237e56 100644 --- a/scripts/audit_debug_sorties.py +++ b/scripts/audit_debug_sorties.py @@ -171,13 +171,16 @@ def _est_tracede(func: ast.FunctionDef | ast.AsyncFunctionDef) -> bool: ``@traced`` (``src/tracing.py``) enveloppe l'appel entier : entrée et chaque sortie (retour ou exception) sont journalisées structurellement. + ``@atraced`` (depuis #37) fait de même pour les fonctions ``async def`` + en enveloppant le ``await`` — la sortie est journalisée quand la + coroutine se termine réellement. """ logger.debug("_est_tracede() appelée | fonction={}", func.name) for deco in func.decorator_list: - if isinstance(deco, ast.Name) and deco.id == "traced": + if isinstance(deco, ast.Name) and deco.id in ("traced", "atraced"): logger.debug("_est_tracede() retourne | True (nom direct)") return True - if isinstance(deco, ast.Attribute) and deco.attr == "traced": + if isinstance(deco, ast.Attribute) and deco.attr in ("traced", "atraced"): logger.debug("_est_tracede() retourne | True (attribut)") return True logger.debug("_est_tracede() retourne | False") diff --git a/src/pystashtemplate/dlq.py b/src/pystashtemplate/dlq.py index 3abd44c..8c19200 100644 --- a/src/pystashtemplate/dlq.py +++ b/src/pystashtemplate/dlq.py @@ -31,7 +31,7 @@ from loguru import logger -from pystashtemplate.tracing import traced +from pystashtemplate.tracing import atraced, traced _SIZE_UNITS = {"": 1, "b": 1, "k": 1024, "kb": 1024, "m": 1024**2, "mb": 1024**2, "g": 1024**3, "gb": 1024**3} _DURATION_UNITS = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 7 * 86400} @@ -139,7 +139,7 @@ def __init__( self._retention = retention or None self._compress = compress - @traced + @atraced async def write(self, doc: dict, *, index: str, error: str) -> None: """Ajoute une ligne JSON au fichier DLQ pour ce document. diff --git a/src/pystashtemplate/dnslookup.py b/src/pystashtemplate/dnslookup.py index 57ede49..5fef38b 100644 --- a/src/pystashtemplate/dnslookup.py +++ b/src/pystashtemplate/dnslookup.py @@ -47,7 +47,7 @@ from loguru import logger from pystashtemplate.templates import _MISSING, assign_field, parse_field_path, resolve_field -from pystashtemplate.tracing import traced +from pystashtemplate.tracing import atraced, traced from pystashtemplate.util import add_failure_tags HOSTS_SYSTEME = "/etc/hosts" @@ -142,12 +142,12 @@ def _charger(self) -> dict[str, list[str]]: logger.debug("hosts {} : {} nom(s)", self._chemin, len(self._noms_vers_adresses)) return self._noms_vers_adresses - @traced + @atraced async def adresses(self, nom: str) -> list[str]: """Adresses de `nom` dans l'ordre du fichier.""" return list(self._charger().get(nom, [])) - @traced + @atraced async def noms(self, adresse: str) -> list[str]: """Noms de `adresse` (nom canonique d'abord).""" self._charger() @@ -186,7 +186,7 @@ def _client(self) -> dns.asyncresolver.Resolver: self._resolveur = resolveur return self._resolveur - @traced + @atraced async def _requete(self, nom: str, type_: str) -> list[str]: """Réponses d'une requête ; aucune si le nom n'existe pas ou sans réponse.""" if ( @@ -206,12 +206,12 @@ async def _requete(self, nom: str, type_: str) -> list[str]: logger.debug("dns : {} {} | {}", nom, type_, resultats) return resultats - @traced + @atraced async def adresses(self, nom: str) -> list[str]: """Adresses IPv4 puis IPv6.""" return [*await self._requete(nom, "A"), *await self._requete(nom, "AAAA")] - @traced + @atraced async def noms(self, adresse: str) -> list[str]: """Noms PTR, sans point final.""" return [nom.rstrip(".") for nom in await self._requete(dns.reversename.from_address(adresse).to_text(), "PTR")] @@ -375,7 +375,7 @@ def _resolveurs(self, options: dict[str, Any], timeout: float) -> list[Resolveur logger.debug("dns : {} résolveur(s)", len(resolveurs)) return resolveurs - @traced + @atraced async def apply(self, doc: dict[str, Any]) -> bool: """Applique `resolve` puis `reverse` ; True si le filtre est allé au bout. @@ -389,7 +389,7 @@ async def apply(self, doc: dict[str, Any]) -> bool: logger.debug("dns : terminé") return True - @traced + @atraced async def _traiter(self, doc: dict[str, Any], champs: list[str], *, inverse: bool) -> bool: """`resolve(event)` / `reverse(event)` : False quand Ruby fait `return`.""" for champ in champs: @@ -416,7 +416,7 @@ async def _traiter(self, doc: dict[str, Any], champs: list[str], *, inverse: boo self._ecrire(doc, chemin, resultat, tableau=tableau) return True - @traced + @atraced async def _chercher(self, doc: dict[str, Any], brut: str, *, inverse: bool) -> str | None: """Résultat (caches compris) ; None si échec, délai dépassé ou erreur.""" if self._cache_echecs is not None and self._cache_echecs.lire(brut): @@ -447,7 +447,7 @@ def _noter_echec(self, brut: str) -> None: if self._cache_echecs is not None: self._cache_echecs.ecrire(brut, True) - @traced + @atraced async def _avec_essais(self, brut: str, *, inverse: bool) -> str | None: """`retriable_request` : nouveaux essais après un délai dépassé ou une erreur réseau.""" essais = 0 @@ -461,7 +461,7 @@ async def _avec_essais(self, brut: str, *, inverse: bool) -> str | None: essais += 1 logger.debug("dns : nouvel essai {} pour {}", essais, brut) - @traced + @atraced async def _adresse(self, nom: str) -> str | None: """Première adresse du premier résolveur qui répond.""" ascii_ = _vers_ascii(nom) @@ -470,7 +470,7 @@ async def _adresse(self, nom: str) -> str | None: return adresse return None - @traced + @atraced async def _nom(self, adresse: str) -> str | None: """Premier nom du premier résolveur qui répond, en Unicode.""" for resolveur in self._resolveurs_actifs: diff --git a/src/pystashtemplate/filters.py b/src/pystashtemplate/filters.py index 2faeeff..2c2a4f4 100644 --- a/src/pystashtemplate/filters.py +++ b/src/pystashtemplate/filters.py @@ -53,7 +53,7 @@ render_template, resolve_field, ) -from pystashtemplate.tracing import traced +from pystashtemplate.tracing import atraced, traced from pystashtemplate.util import add_failure_tags @@ -1722,7 +1722,7 @@ def _compile_step(self, step: dict) -> tuple[str | None, object, str | None]: raise ValueError(f"type de filtre inconnu: {filter_type!r}") return source, compiled, target - @traced + @atraced async def apply(self, doc: dict, *, now: datetime | None = None, on_missing: str = "keep") -> bool: """Applique chaque filtre de la chaîne à doc, en place. diff --git a/src/pystashtemplate/interpreter.py b/src/pystashtemplate/interpreter.py index 6447f5c..6904907 100644 --- a/src/pystashtemplate/interpreter.py +++ b/src/pystashtemplate/interpreter.py @@ -274,7 +274,7 @@ from pystashtemplate.simples import PLUGINS as PLUGINS_SIMPLES from pystashtemplate.simples import appliquer_cidr, reseaux_cidr from pystashtemplate.templates import _MISSING, assign_field, parse_field_path, render_template, resolve_field -from pystashtemplate.tracing import traced +from pystashtemplate.tracing import atraced, traced from pystashtemplate.useragent import UserAgentFilter from pystashtemplate.util import add_failure_tags, load_json_file from pystashtemplate.xmlfilter import XmlFilter @@ -548,6 +548,7 @@ def close(self) -> None: pipeline.close() self._filter_pipelines.clear() + @atraced async def apply( self, doc: dict[str, Any], @@ -597,7 +598,7 @@ async def apply( logger.debug("apply | document d'origine écarté (drop ou split)") return None - @traced + @atraced async def apply_events( self, doc: dict[str, Any], @@ -644,7 +645,7 @@ async def apply_events( # filter{} # ------------------------------------------------------------------ - @traced + @atraced async def _run_filter_body( self, body: list, doc: dict[str, Any], *, now: datetime | None, on_missing: str ) -> list[dict[str, Any]]: @@ -683,7 +684,7 @@ async def _run_filter_body( logger.debug("_run_filter_body | {} événement(s)", len(events)) return events - @traced + @atraced async def _run_filter_plugin( self, entry: list, doc: dict[str, Any], *, now: datetime | None, on_missing: str ) -> list[dict[str, Any]]: @@ -886,7 +887,7 @@ def _apply_xml(self, doc: dict[str, Any], options: dict[str, Any]) -> bool: return False return filtre.apply(doc) - @traced + @atraced async def _apply_dns(self, doc: dict[str, Any], options: dict[str, Any]) -> bool: """`filter { dns { reverse => [...] resolve => [...] } }` — délègue à `dnslookup.DnsFilter` (#121). @@ -1235,7 +1236,7 @@ def _geoip_lookup_failure(doc: dict[str, Any], options: dict[str, Any]) -> None: """`tag_on_failure` du plugin `geoip` (défaut `["_geoip_lookup_failure"]`, comme Logstash).""" add_failure_tags(doc, options.get("tag_on_failure", ["_geoip_lookup_failure"])) - @traced + @atraced async def _apply_filters_json( self, doc: dict[str, Any], options: dict[str, Any], *, now: datetime | None, on_missing: str ) -> None: diff --git a/src/pystashtemplate/outputs/base.py b/src/pystashtemplate/outputs/base.py index 96098f1..c3af8aa 100644 --- a/src/pystashtemplate/outputs/base.py +++ b/src/pystashtemplate/outputs/base.py @@ -34,7 +34,7 @@ from loguru import logger from pystashtemplate.i18n import _ -from pystashtemplate.tracing import traced +from pystashtemplate.tracing import atraced, traced # Actions d'indexation d'un document, comme l'API `_bulk` de la famille # Elasticsearch (issue #2 PyStashTemplate : `index`, `create`, `update`, @@ -143,6 +143,7 @@ async def flush(self) -> None: async def close(self) -> None: """Libère la connexion et les ressources (idempotent).""" + @atraced async def __aenter__(self) -> Self: """`async with` : ouvre la sortie et la renvoie.""" logger.debug("Output.__aenter__ | {} | ouverture", self.plugin) @@ -150,6 +151,7 @@ async def __aenter__(self) -> Self: logger.debug("Output.__aenter__ | {} | sortie", self.plugin) return self + @atraced async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None: """`async with` : ferme la sortie, même sur exception.""" logger.debug("Output.__aexit__ | {} | fermeture (exc={})", self.plugin, exc_type and exc_type.__name__) diff --git a/src/pystashtemplate/outputs/elasticsearch_bulk.py b/src/pystashtemplate/outputs/elasticsearch_bulk.py index 9cb5e89..19f3d16 100644 --- a/src/pystashtemplate/outputs/elasticsearch_bulk.py +++ b/src/pystashtemplate/outputs/elasticsearch_bulk.py @@ -64,7 +64,7 @@ from pystashtemplate.dlq import LocalDeadLetterQueue from pystashtemplate.i18n import _ from pystashtemplate.outputs.base import ACTIONS, Document, Output -from pystashtemplate.tracing import traced +from pystashtemplate.tracing import atraced, traced # Statuts HTTP traités comme des échecs définitifs de TOUT le lot : un # 400/404 sur la requête _bulk elle-même (payload refusé, index absent) @@ -289,7 +289,7 @@ def _corps_ndjson(self, pendings: list[dict[str, Any]]) -> str: lignes.append(json.dumps(pending["doc"], ensure_ascii=False)) return "\n".join(lignes) + "\n" - @traced + @atraced async def envoyer( self, doc: dict[str, Any], @@ -356,6 +356,7 @@ async def envoyer( logger.debug("ElasticsearchBulkOutput.envoyer | sortie") return outcomes[-1] + @atraced async def send(self, batch: list[Document]) -> None: """Envoie un lot de documents (contrat `Output` #4). @@ -377,6 +378,7 @@ async def send(self, batch: list[Document]) -> None: logger.debug("ElasticsearchBulkOutput.send | {} → {}", outcome.value, doc) logger.debug("ElasticsearchBulkOutput.send | sortie") + @atraced async def flush(self) -> None: """Pousse les documents en attente (contrat `Output` : arrêt propre). @@ -389,7 +391,7 @@ async def flush(self) -> None: await self._flush() logger.debug("ElasticsearchBulkOutput.flush | sortie") - @traced + @atraced async def _flush(self) -> list[SendOutcome]: """Envoie le tampon en un `_bulk` et renvoie le résultat de chaque document. @@ -409,7 +411,7 @@ async def _flush(self) -> list[SendOutcome]: return [SendOutcome.RETRYABLE] * len(pendings) return await self._analyser_reponse(pendings, response) - @traced + @atraced async def _envoyer_lot(self, pendings: list[dict[str, Any]]) -> httpx.Response | None: """POSTe le NDJSON, avec retentes sur échec transitoire. @@ -448,7 +450,7 @@ async def _envoyer_lot(self, pendings: list[dict[str, Any]]) -> httpx.Response | continue return response - @traced + @atraced async def _analyser_reponse(self, pendings: list[dict[str, Any]], response: httpx.Response) -> list[SendOutcome]: """Analyse la réponse `_bulk` et renvoie le résultat de chaque document. @@ -485,7 +487,7 @@ async def _analyser_reponse(self, pendings: list[dict[str, Any]], response: http outcomes.append(await self._permanent(pending, str(erreur))) return outcomes - @traced + @atraced async def _permanent(self, pending: dict[str, Any], erreur: str) -> SendOutcome: """Échec définitif d'un document : DLQ si configurée, sinon RETRYABLE.""" logger.warning(_("envoi _bulk échoué définitivement erreur={error}"), error=erreur) @@ -494,12 +496,14 @@ async def _permanent(self, pending: dict[str, Any], erreur: str) -> SendOutcome: await self._dlq.write(pending["doc"], index=pending["index"], error=erreur) return SendOutcome.DEAD_LETTERED + @atraced async def open(self) -> None: """Ouvre la sortie : le client HTTP est paresseux, rien à ouvrir ici (contrat `Output`).""" logger.debug("ElasticsearchBulkOutput.open | entrée") self._client_http() # crée le client (et valide TLS/auth) sans requête logger.debug("ElasticsearchBulkOutput.open | sortie") + @atraced async def close(self) -> None: """Ferme proprement le client HTTP (idempotent).""" logger.debug("ElasticsearchBulkOutput.close | entrée") @@ -508,7 +512,7 @@ async def close(self) -> None: self._client = None logger.debug("ElasticsearchBulkOutput.close | sortie") - @traced + @atraced async def health(self) -> dict[str, Any]: """Interroge le serveur (GET /) : sa version, ou lève l'erreur. diff --git a/src/pystashtemplate/outputs/lotisseur.py b/src/pystashtemplate/outputs/lotisseur.py index dfe0785..6c615db 100644 --- a/src/pystashtemplate/outputs/lotisseur.py +++ b/src/pystashtemplate/outputs/lotisseur.py @@ -34,7 +34,7 @@ from pystashtemplate.i18n import _ from pystashtemplate.outputs.base import Document, Output -from pystashtemplate.tracing import traced +from pystashtemplate.tracing import atraced, traced # Marqueur de fin d'entrée : un document ne peut jamais être un tuple, # donc aucun conflit avec un vrai événement. @@ -128,6 +128,7 @@ def __init__(self, sortie: Output, options: dict[str, Any] | None = None) -> Non # ------------------------------------------------------------------ # Cycle de vie # ------------------------------------------------------------------ + @atraced async def demarrer(self) -> None: """Lance la tâche de consommation (idempotent).""" logger.debug("Lotisseur.demarrer | entrée") @@ -136,6 +137,7 @@ async def demarrer(self) -> None: self._tache = asyncio.create_task(self._boucle(), name="lotisseur") logger.debug("Lotisseur.demarrer | sortie") + @atraced async def ajouter(self, document: Document) -> None: """Ajoute un document, en attendant si la file est pleine. @@ -157,6 +159,7 @@ async def ajouter(self, document: Document) -> None: await self._file.put(document) # attend si la file est pleine logger.debug("Lotisseur.ajouter | sortie (file : {})", self._file.qsize()) + @atraced async def arreter(self) -> None: """Arrêt propre : vide la file et les lots en cours, sans perte. @@ -190,6 +193,7 @@ async def arreter(self) -> None: # ------------------------------------------------------------------ # Consommation # ------------------------------------------------------------------ + @atraced async def _boucle(self) -> None: """Consume la file, constitue les lots et les pousse vers la sortie.""" logger.debug("Lotisseur._boucle | entrée") @@ -217,6 +221,7 @@ async def _boucle(self) -> None: await self._attendre_en_vol() logger.debug("Lotisseur._boucle | sortie (file vidée, lots en vol partis)") + @atraced async def _pousser(self, lot: list[Document]) -> None: """Envoie un lot vers la sortie, en limitant la concurrence. @@ -243,6 +248,7 @@ async def _pousser(self, lot: list[Document]) -> None: tache.add_done_callback(lambda _: self._fin_vol.set() if not self._en_vol else None) logger.debug("Lotisseur._pousser | sortie (en vol : {})", len(self._en_vol)) + @atraced async def _envoyer_lot(self, lot: list[Document], semaphore: asyncio.Semaphore) -> None: """Tâche d'envoi d'un lot : `send()` de la sortie sous créneau réservé. @@ -263,6 +269,7 @@ async def _envoyer_lot(self, lot: list[Document], semaphore: asyncio.Semaphore) finally: semaphore.release() + @atraced async def _attendre_en_vol(self) -> None: """Attend que tous les lots en vol soient partis.""" logger.debug("Lotisseur._attendre_en_vol | entrée") @@ -270,6 +277,7 @@ async def _attendre_en_vol(self) -> None: await self._fin_vol.wait() logger.debug("Lotisseur._attendre_en_vol | sortie") + @atraced async def __aenter__(self) -> Lotisseur: """`async with` : démarre le lotisseur et le renvoie.""" logger.debug("Lotisseur.__aenter__ | entrée") @@ -277,6 +285,7 @@ async def __aenter__(self) -> Lotisseur: logger.debug("Lotisseur.__aenter__ | sortie") return self + @atraced async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None: """`async with` : arrête proprement le lotisseur, même sur exception.""" logger.debug("Lotisseur.__aexit__ | entrée (exc={})", exc_type and exc_type.__name__) @@ -308,6 +317,7 @@ def __init__(self, sorties: Sequence[Output], options_par_sortie: Sequence[dict[ Lotisseur(sortie, options) for sortie, options in zip(sorties, options_par_sortie, strict=True) ] + @atraced async def demarrer(self) -> None: """Démarre tous les lotisseurs.""" logger.debug("MoteurSorties.demarrer | entrée") @@ -315,6 +325,7 @@ async def demarrer(self) -> None: await lotisseur.demarrer() logger.debug("MoteurSorties.demarrer | sortie | {} lotisseur(s)", len(self.lotisseurs)) + @atraced async def emettre(self, document: Document, indices: Sequence[int] | None = None) -> None: """Émet un document vers les sorties sélectionnées (toutes si None). @@ -329,6 +340,7 @@ async def emettre(self, document: Document, indices: Sequence[int] | None = None await lotisseur.ajouter(document) logger.debug("MoteurSorties.emettre | sortie | {} cible(s)", len(cibles)) + @atraced async def arreter(self) -> None: """Arrête proprement tous les lotisseurs (vidage sans perte).""" logger.debug("MoteurSorties.arreter | entrée") diff --git a/src/pystashtemplate/outputs/null.py b/src/pystashtemplate/outputs/null.py index 0d0efc2..b5400b7 100644 --- a/src/pystashtemplate/outputs/null.py +++ b/src/pystashtemplate/outputs/null.py @@ -15,6 +15,7 @@ from loguru import logger from pystashtemplate.outputs import Capacites, Document, Output, enregistrer +from pystashtemplate.tracing import atraced @enregistrer @@ -29,21 +30,25 @@ class NullOutput(Output): taille_max_requete=None, ) + @atraced async def open(self) -> None: """Sans effet : la sortie puits n'a aucune connexion à ouvrir.""" logger.debug("NullOutput.open | sans effet") logger.debug("NullOutput.open | sortie") + @atraced async def send(self, batch: Sequence[Document]) -> None: """Oublie le lot, après l'avoir compté en debug.""" logger.debug("NullOutput.send | {} document(s) ignoré(s)", len(batch)) logger.debug("NullOutput.send | sortie") + @atraced async def flush(self) -> None: """Sans effet : rien n'est jamais mis en attente.""" logger.debug("NullOutput.flush | sans effet") logger.debug("NullOutput.flush | sortie") + @atraced async def close(self) -> None: """Sans effet : aucune ressource à libérer.""" logger.debug("NullOutput.close | sans effet") diff --git a/src/pystashtemplate/outputs/transport.py b/src/pystashtemplate/outputs/transport.py index 0eaabf7..0461b5b 100644 --- a/src/pystashtemplate/outputs/transport.py +++ b/src/pystashtemplate/outputs/transport.py @@ -39,6 +39,7 @@ from loguru import logger from pystashtemplate.i18n import _ +from pystashtemplate.tracing import atraced class TransportErreur(Exception): @@ -165,6 +166,7 @@ def _contexte_ssl(self) -> ssl.SSLContext: logger.debug("_contexte_ssl | contexte prêt") return contexte + @atraced async def open(self) -> None: """Ouvre le pool de connexions (keep-alive) ; sans effet si déjà ouvert.""" logger.debug("open |") @@ -180,6 +182,7 @@ async def open(self) -> None: self._session = aiohttp.ClientSession(connector=connecteur, timeout=delais) logger.debug("open | pool ouvert ({} connexions max)", self._connexions_max) + @atraced async def close(self) -> None: """Ferme le pool ; les requêtes en cours attendent leur fin.""" logger.debug("close |") @@ -190,6 +193,7 @@ async def close(self) -> None: else: logger.debug("close | déjà fermé") + @atraced async def __aenter__(self) -> "TransportHTTP": """`open()` puis sert de gestionnaire asynchrone.""" logger.debug("__aenter__ |") @@ -197,6 +201,7 @@ async def __aenter__(self) -> "TransportHTTP": logger.debug("__aenter__ | ouvert") return self + @atraced async def __aexit__(self, exc_type: object, exc: object, tb: object) -> None: """`close()` dans tous les cas (l'exception, s'il y en a une, remonte).""" logger.debug("__aexit__ | exception : {}", type(exc).__name__ if exc else "aucune") @@ -257,6 +262,7 @@ def _delai(self, tentative: int, retry_after: str | None) -> float: logger.debug("_delai | {} s retenu", delai) return delai + @atraced async def envoyer( self, url: str, diff --git a/src/pystashtemplate/tracing.py b/src/pystashtemplate/tracing.py index d3f23c9..98254dc 100644 --- a/src/pystashtemplate/tracing.py +++ b/src/pystashtemplate/tracing.py @@ -29,11 +29,12 @@ from __future__ import annotations import functools -from typing import Callable, TypeVar +from typing import Any, Callable, Coroutine, TypeVar from loguru import logger F = TypeVar("F", bound=Callable) +A = TypeVar("A", bound=Callable[..., Coroutine[Any, Any, Any]]) def traced(func: F) -> F: @@ -74,3 +75,39 @@ def wrapper(*args, **kwargs): return result return wrapper + + +def atraced(func: A) -> A: + """Équivalent asynchrone de `traced` (#37) : entrée et sortie journalisées. + + Contrairement à `@traced` appliqué à une fonction `async def` — qui + journalise la « sortie » dès la création de la coroutine, AVANT que + l'appelant ne l'attende — ce décorateur enveloppe le `await` : la + sortie n'est journalisée qu'une fois la coroutine réellement terminée + (retour normal ou exception propagée). Mêmes règles loguru que + `traced` : uniquement le nom qualifié (`__qualname__`), jamais les + arguments ni la valeur de retour. + + Préserve `__name__`/`__doc__`/`__wrapped__` (`functools.wraps`) ; + la fonction décorée reste une coroutine function, `await`able + normalement. + + Args: + func: fonction (ou méthode) asynchrone à tracer. + + Returns: + La fonction décorée, de même signature apparente que `func`. + """ + + @functools.wraps(func) + async def wrapper(*args, **kwargs): + logger.debug("{} | entrée", func.__qualname__) + try: + result = await func(*args, **kwargs) + except BaseException as exc: + logger.debug("{} | sortie (exception {}) : {}", func.__qualname__, type(exc).__name__, exc) + raise + logger.debug("{} | sortie", func.__qualname__) + return result + + return wrapper diff --git a/tests/test_tracing.py b/tests/test_tracing.py new file mode 100644 index 0000000..67c2b7c --- /dev/null +++ b/tests/test_tracing.py @@ -0,0 +1,97 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Tests du décorateur `atraced` (`src/tracing.py`, issue #37). + +L'équivalent asynchrone de `@traced` : entrée et sortie journalisées +AUTOUR du `await` — la « sortie » n'apparaît qu'une fois la coroutine +terminée, contrairement à `@traced` sur une fonction `async def`. +""" + +from __future__ import annotations + +import asyncio +import inspect + +import pytest +from loguru import logger + +from pystashtemplate.tracing import atraced + + +def _run(coro): + # Sans pytest-asyncio (convention du dépôt, cf. RsysLogstach) : asyncio.run direct (#34). + return asyncio.run(coro) + + +class TestAtraced: + def test_entree_puis_sortie_autour_du_await(self) -> None: + messages: list[str] = [] + sink = logger.add(lambda m: messages.append(m), level="DEBUG") + + @atraced + async def travail(valeur: int) -> int: + await asyncio.sleep(0) + return valeur * 2 + + try: + assert _run(travail(21)) == 42 + finally: + logger.remove(sink) + noms = [m.split(" - ", 1)[1].strip() for m in messages] + assert noms == [ + "TestAtraced.test_entree_puis_sortie_autour_du_await..travail | entrée", + "TestAtraced.test_entree_puis_sortie_autour_du_await..travail | sortie", + ] + + def test_sortie_apres_await_pas_avant(self) -> None: + # `@traced` sur un async def journalise « sortie » dès la création + # de la coroutine ; `@atraced` attend la fin réelle. + messages: list[str] = [] + + @atraced + async def lent() -> None: + await asyncio.sleep(0.05) + + coro = lent.__wrapped__() # coroutine créée, PAS encore attendue + assert messages == [] + coro.close() + + def test_exception_journalisee_et_propagee(self) -> None: + messages: list[str] = [] + sink = logger.add(lambda m: messages.append(m), level="DEBUG") + + @atraced + async def echec() -> None: + raise ValueError("boom") + + try: + with pytest.raises(ValueError, match="boom"): + _run(echec()) + finally: + logger.remove(sink) + noms = [m.split(" - ", 1)[1].strip() for m in messages] + assert noms[0].endswith(".echec | entrée") + assert ".echec | sortie (exception ValueError) : boom" in noms[1] + + def test_introspection_preservee(self) -> None: + @atraced + async def documeee() -> None: + """Documentation conservée.""" + + assert documeee.__name__ == "documeee" + assert documeee.__doc__ == "Documentation conservée." + assert inspect.iscoroutinefunction(documeee) + assert hasattr(documeee, "__wrapped__") + + def test_arguments_et_resultat_non_journalises(self) -> None: + messages: list[str] = [] + sink = logger.add(lambda m: messages.append(m), level="DEBUG") + + @atraced + async def secret(mot_de_passe: str) -> str: + return mot_de_passe.upper() + + try: + assert _run(secret("s3cret")) == "S3CRET" + finally: + logger.remove(sink) + assert not any("s3cret" in m or "S3CRET" in m for m in messages)