sqlalchemy-audit-trail 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.
audit_trail/config.py ADDED
@@ -0,0 +1,950 @@
1
+ """Library configuration: ``AuditTrail`` and per-model ``AuditOptions``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import json
7
+ from collections.abc import Callable, Collection, Iterable, Mapping
8
+ from dataclasses import dataclass, field
9
+ from enum import IntEnum
10
+ from typing import TYPE_CHECKING, Any, Literal, NamedTuple, overload
11
+
12
+ from sqlalchemy import Engine, create_engine
13
+
14
+ from audit_trail.context import Actor, AuditContext, resolve_context
15
+ from audit_trail.context import bind as _bind
16
+ from audit_trail.context import context as _context
17
+ from audit_trail.context import set_actor as _set_actor
18
+ from audit_trail.events import (
19
+ RESERVED_PREFIXES,
20
+ AuditEvent,
21
+ EventRegistry,
22
+ Severity,
23
+ WriteFlags,
24
+ resolve_write_flags,
25
+ validate_payload,
26
+ )
27
+ from audit_trail.maintenance import PartitionManager
28
+ from audit_trail.serialization import KeyRing
29
+ from audit_trail.serialization import pseudonymize as _pseudonymize
30
+ from audit_trail.tables import build_tables
31
+
32
+ if TYPE_CHECKING:
33
+ from datetime import datetime, timedelta
34
+
35
+ from pydantic import BaseModel
36
+ from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker
37
+ from sqlalchemy.orm import Session, sessionmaker
38
+
39
+ from audit_trail.privacy import ScrubbedRecord, ScrubResult
40
+ from audit_trail.writer import Entry, TransactionValues
41
+
42
+ OnError = Literal["log", "raise"]
43
+
44
+ DURABLE_POOL_SIZE = 5
45
+ """Connections in the durable engine the library builds."""
46
+
47
+ DURABLE_POOL_TIMEOUT = 5.0
48
+ """Seconds a durable write waits for a connection of that engine."""
49
+
50
+
51
+ class Target(NamedTuple):
52
+ """A parent object referred to by type name and primary key.
53
+
54
+ Returned by the ``target`` option and accepted by ``AuditTrail.log``.
55
+ A plain ``(type, id)`` tuple works too.
56
+
57
+ Attributes:
58
+ type: Name stored in ``target_type``.
59
+ id: The primary key; a tuple for a composite key. ``None`` means no
60
+ target.
61
+ """
62
+
63
+ type: str
64
+ id: object
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class AuditOptions:
69
+ """Audit settings for one model, set as ``__audit__`` on the class.
70
+
71
+ ``label``, ``scope`` and ``target`` run while the session flushes and get
72
+ a read-only view of the instance instead of the instance itself. They may
73
+ read only attributes already loaded on it: reading an expired or unloaded
74
+ attribute emits no SQL, logs a warning on ``audit_trail.diff`` (once per
75
+ model, attribute and option) and the option falls back (``label`` and
76
+ ``target`` to ``None``, ``scope`` to the context). A column that was
77
+ never set on a new instance reads as ``None``, as stored, unless it has a
78
+ server-side default. Reading a
79
+ ``functools.cached_property`` raises ``AuditOptionError``. Any other
80
+ exception they raise propagates and aborts the flush.
81
+
82
+ Attributes:
83
+ severity: Severity of the model's ``entity.*`` entries. ``None`` uses
84
+ the configured default.
85
+ verb_severity: Per-verb severity overrides, keyed by verb
86
+ (for example ``{"entity.deleted": MySeverity.HIGH}``).
87
+ track_relationships: Relationship names whose membership changes are
88
+ recorded as ``{"added": [...], "removed": [...]}``.
89
+ snapshot_on_load: JSON columns deep-copied on load and refresh, so an
90
+ in-place mutation still has an old value.
91
+ object_type: Name stored in ``object_type``. Defaults to the class name.
92
+ label: Returns the object's label, stored in ``object_label``.
93
+ scope: Returns the scope id, stored in ``scope_id``. Returning
94
+ ``None`` means "no scope"; the scope comes from the context only
95
+ when this option is not set or it read an attribute that is not
96
+ loaded.
97
+ target: Returns the parent object as a ``Target`` (or a plain
98
+ ``(type, id)`` tuple), or ``None``. An id of ``None`` also means
99
+ no target; a tuple id is formatted as a composite ``object_id``.
100
+ """
101
+
102
+ severity: IntEnum | None = None
103
+ verb_severity: dict[str, IntEnum] = field(default_factory=dict)
104
+ track_relationships: Collection[str] = frozenset()
105
+ snapshot_on_load: Collection[str] = frozenset()
106
+ object_type: str | None = None
107
+ label: Callable[[Any], str | None] | None = None
108
+ scope: Callable[[Any], object] | None = None
109
+ target: Callable[[Any], Target | tuple[str, object] | None] | None = None
110
+
111
+
112
+ class AuditTrail:
113
+ """Entry point of the library: configuration plus the public operations.
114
+
115
+ Args:
116
+ engine: Sync or async engine used for DDL and maintenance.
117
+ schema: Database schema holding the audit tables.
118
+ severities: The application's severity ``IntEnum``. ``None`` uses the
119
+ built-in ``Severity``.
120
+ default_severity: Severity of ``entity.*`` entries whose model sets
121
+ none. ``None`` uses the lowest member of ``severities``.
122
+ system_severity: Severity of the library's own ``audit.*`` events.
123
+ ``None`` uses the highest member of ``severities``.
124
+ events: Event classes to register. ``None`` registers every
125
+ ``AuditEvent`` subclass with members defined when the
126
+ ``AuditTrail`` is created, so import them first or list them here.
127
+ durable_engine: Engine for durable writes: sync for ``log``, async
128
+ for ``alog``. Must not be configured for ``AUTOCOMMIT``. ``None``
129
+ builds one from ``engine``'s URL (only the URL: pass your own
130
+ engine for ``connect_args`` and similar settings), sync or async
131
+ like ``engine``, with its own small pool (``DURABLE_POOL_SIZE``
132
+ connections, no overflow, ``DURABLE_POOL_TIMEOUT``, pre-ping).
133
+ It connects on the first durable write; ``dispose`` or
134
+ ``adispose`` closes it.
135
+ on_error: ``"log"`` keeps the business transaction alive when an audit
136
+ write fails; ``"raise"`` propagates. ``fail_closed`` events always
137
+ raise.
138
+ pseudonymize_key: HMAC key as ``bytes`` (version 1) or
139
+ ``{version: key}``.
140
+ session_provider: Returns the current session, or ``None`` when there
141
+ is none, for hosts that keep it in a context variable. ``log`` and
142
+ ``alog`` call it when no session is passed.
143
+ context_provider: Returns the current audit context.
144
+ json_encoder: Extra encoder for types the built-in one does not handle.
145
+ indexes: Names of the indexes to create. ``None`` uses the defaults.
146
+ global_redact: Attribute keys or column names redacted in
147
+ ``entity.*`` changes when the column has no explicit policy. A
148
+ safety net, not a replacement for per-column policies.
149
+ warn_on_bulk: Log a warning when a bulk ``update()``/``delete()`` hits
150
+ an audited table.
151
+ auto_create_partitions: Let durable writes create a missing partition
152
+ and retry once. Needs DDL privileges.
153
+ allow_scrub: Enable ``scrub``/``scrub_actor``. They run on ``engine``,
154
+ whose role then needs ``UPDATE`` on the audit tables.
155
+ default_query_window: How far back ``query.list_groups`` reads when
156
+ it is not given ``since``, for example ``timedelta(days=30)``;
157
+ ``since=ALL_HISTORY`` still lists the whole log. ``None`` reads
158
+ the whole log, which gets slower as it grows.
159
+
160
+ Attributes:
161
+ severities: The severity enum in use.
162
+ registry: The registered events.
163
+ tables: The audit tables built from ``schema`` and ``indexes``.
164
+ keys: Key ring built from ``pseudonymize_key``, or ``None``.
165
+ maintenance: Partition management on ``engine``, for example
166
+ ``audit.maintenance.ensure_partitions()``.
167
+ query: Read queries, for example ``audit.query.list_groups(session)``.
168
+ durable_engine: The engine durable writes use.
169
+
170
+ Raises:
171
+ EventRegistryError: An event or a severity setting is invalid.
172
+ ValueError: A table name or an index key is invalid,
173
+ ``pseudonymize_key`` is too short, or ``default_query_window`` is
174
+ not positive.
175
+ TypeError: ``pseudonymize_key`` or ``default_query_window`` has the
176
+ wrong type.
177
+ """
178
+
179
+ context = staticmethod(_context)
180
+ set_actor = staticmethod(_set_actor)
181
+ bind = staticmethod(_bind)
182
+
183
+ def __init__(
184
+ self,
185
+ engine: Engine | AsyncEngine,
186
+ *,
187
+ schema: str = "audit",
188
+ severities: type[IntEnum] | None = None,
189
+ default_severity: IntEnum | None = None,
190
+ system_severity: IntEnum | None = None,
191
+ events: Iterable[type[AuditEvent]] | None = None,
192
+ durable_engine: Engine | AsyncEngine | None = None,
193
+ on_error: OnError = "log",
194
+ pseudonymize_key: bytes | dict[int, bytes] | None = None,
195
+ session_provider: Callable[[], Session | AsyncSession | None] | None = None,
196
+ context_provider: Callable[[], Any] | None = None,
197
+ json_encoder: type[json.JSONEncoder] | None = None,
198
+ indexes: Collection[str] | None = None,
199
+ global_redact: Collection[str] = (),
200
+ warn_on_bulk: bool = True,
201
+ auto_create_partitions: bool = False,
202
+ allow_scrub: bool = False,
203
+ default_query_window: timedelta | None = None,
204
+ ) -> None:
205
+ self.engine = engine
206
+ self.schema = schema
207
+ self.severities: type[IntEnum] = Severity if severities is None else severities
208
+ self.registry = EventRegistry(
209
+ self.severities,
210
+ events=events,
211
+ default_severity=default_severity,
212
+ system_severity=system_severity,
213
+ )
214
+ self._owns_durable_engine = durable_engine is None
215
+ self.durable_engine: Engine | AsyncEngine = (
216
+ _default_durable_engine(engine)
217
+ if durable_engine is None
218
+ else durable_engine
219
+ )
220
+ self.on_error: OnError = on_error
221
+ self.pseudonymize_key = pseudonymize_key
222
+ self.session_provider = session_provider
223
+ self.context_provider = context_provider
224
+ self.json_encoder = json_encoder
225
+ self.indexes = indexes
226
+ self.global_redact = frozenset(global_redact)
227
+ self.warn_on_bulk = warn_on_bulk
228
+ self.auto_create_partitions = auto_create_partitions
229
+ self.allow_scrub = allow_scrub
230
+ self.keys = None if pseudonymize_key is None else KeyRing(pseudonymize_key)
231
+ self.tables = build_tables(schema=schema, indexes=indexes)
232
+ self.maintenance = PartitionManager(engine, self.tables, self.severities)
233
+ from audit_trail.query import AuditQuery
234
+
235
+ self.query = AuditQuery(
236
+ self.tables, self.severities, default_window=default_query_window
237
+ )
238
+
239
+ def install(
240
+ self,
241
+ session_factory: type[Session | AsyncSession]
242
+ | sessionmaker[Any]
243
+ | async_sessionmaker[Any],
244
+ ) -> None:
245
+ """Audit the sessions of a factory.
246
+
247
+ Registers the listeners on the factory's session class only (for a
248
+ ``sessionmaker``, the class it builds), so other sessions, a second
249
+ ``sessionmaker`` and tools such as Alembic are not audited. Set
250
+ ``session.info["audit_enabled"] = False`` to switch capture off for
251
+ one session of that class.
252
+
253
+ An ``AsyncSession`` runs a sync ``Session`` in a greenlet, and the
254
+ listeners are registered on that class: give the async factory your
255
+ own ``Session`` subclass, as in
256
+ ``async_sessionmaker(engine, sync_session_class=AppSession)`` or as
257
+ ``sync_session_class`` of an ``AsyncSession`` subclass.
258
+
259
+ Args:
260
+ session_factory: A ``sessionmaker`` or ``Session`` subclass, or
261
+ an ``async_sessionmaker`` or ``AsyncSession`` subclass.
262
+
263
+ Raises:
264
+ TypeError: ``session_factory`` is none of these, or its
265
+ ``sync_session_class`` is not a ``Session`` subclass.
266
+ ValueError: The session class is the base ``Session`` (for an
267
+ async factory: no ``sync_session_class`` was given), or an
268
+ ``AuditTrail`` is already installed on it, a base class or a
269
+ subclass of it.
270
+ """
271
+ from audit_trail.listener import install
272
+
273
+ install(self, session_factory)
274
+
275
+ def pseudonymize(self, value: object, *, purpose: str) -> str:
276
+ """Replace a value with a keyed pseudonym, e.g. ``audit.<purpose>.v1:<hex>``.
277
+
278
+ Args:
279
+ value: The value. Must not be ``None``.
280
+ purpose: Snake_case name separating unrelated uses.
281
+
282
+ Returns:
283
+ The pseudonym token.
284
+
285
+ Raises:
286
+ ValueError: No ``pseudonymize_key`` is configured, or ``purpose``
287
+ is not snake_case.
288
+ TypeError: ``value`` is ``None``.
289
+ UnserializableValueError: ``value`` cannot be encoded.
290
+ """
291
+ if self.keys is None:
292
+ raise ValueError("pseudonymize needs pseudonymize_key")
293
+ return _pseudonymize(
294
+ value, purpose=purpose, keys=self.keys, json_encoder=self.json_encoder
295
+ )
296
+
297
+ def dispose(self) -> None:
298
+ """Close the pooled connections of a durable engine the library built.
299
+
300
+ A ``durable_engine`` passed in is the host's to dispose; this leaves it
301
+ alone.
302
+
303
+ Raises:
304
+ TypeError: The library's durable engine is async; use ``adispose``.
305
+ """
306
+ if not self._owns_durable_engine:
307
+ return
308
+ if not isinstance(self.durable_engine, Engine):
309
+ raise TypeError("the durable engine is async; use adispose")
310
+ self.durable_engine.dispose()
311
+
312
+ async def adispose(self) -> None:
313
+ """Async ``dispose``, for a durable engine the library built async.
314
+
315
+ Raises:
316
+ TypeError: The library's durable engine is sync; use ``dispose``.
317
+ """
318
+ if not self._owns_durable_engine:
319
+ return
320
+ if isinstance(self.durable_engine, Engine):
321
+ raise TypeError("the durable engine is sync; use dispose")
322
+ await self.durable_engine.dispose()
323
+
324
+ @overload
325
+ def log(
326
+ self,
327
+ session: Session | None,
328
+ event: AuditEvent,
329
+ /,
330
+ *,
331
+ obj: object | None = None,
332
+ target: Target | object | None = None,
333
+ payload: Mapping[str, object] | BaseModel | None = None,
334
+ actor: Actor | None = None,
335
+ durable: bool | None = None,
336
+ ) -> None: ...
337
+
338
+ @overload
339
+ def log(
340
+ self,
341
+ event: AuditEvent,
342
+ /,
343
+ *,
344
+ obj: object | None = None,
345
+ target: Target | object | None = None,
346
+ payload: Mapping[str, object] | BaseModel | None = None,
347
+ actor: Actor | None = None,
348
+ durable: bool | None = None,
349
+ ) -> None: ...
350
+
351
+ def log(
352
+ self,
353
+ session_or_event: Session | AuditEvent | None,
354
+ event: AuditEvent | None = None,
355
+ /,
356
+ *,
357
+ obj: object | None = None,
358
+ target: Target | object | None = None,
359
+ payload: Mapping[str, object] | BaseModel | None = None,
360
+ actor: Actor | None = None,
361
+ durable: bool | None = None,
362
+ ) -> None:
363
+ """Record an explicit event.
364
+
365
+ Called as ``log(session, event, ...)`` or, with a ``session_provider``
366
+ configured, as ``log(event, ...)``: without a session (or with
367
+ ``None``), the entry goes to the session ``session_provider()``
368
+ returns.
369
+
370
+ A non-durable entry is inserted immediately on the session's
371
+ connection, in the same database transaction as the session's changes:
372
+ it is committed or rolled back with them, and shares their
373
+ ``audit_transaction`` row. Write failures follow ``on_error``. With
374
+ ``obj``, the connection is the one ``obj`` is flushed on; without, the
375
+ one for the audit tables: their bind in ``Session(binds=...)``, else
376
+ the session's default bind.
377
+
378
+ A durable entry (the event's ``durable`` or ``fail_closed``, or
379
+ ``durable=True``) is written on a connection of ``durable_engine`` in
380
+ a transaction of its own, with its own ``audit_transaction`` row built
381
+ from the current context, and committed before this returns, so it
382
+ survives a rollback of the session. A failed write is logged with
383
+ ``on_error="log"``; with ``on_error="raise"``, and always for a
384
+ ``fail_closed`` event, it raises ``AuditWriteError``. With
385
+ ``auto_create_partitions``, a missing partition is created and the
386
+ write retried once. Creating a partition waits for every open
387
+ transaction that has written audit rows, including the session's own:
388
+ if it has, the retry fails after the ``ensure_partitions`` lock
389
+ timeout (about 5 to 10 seconds) and a ``fail_closed`` event raises
390
+ ``AuditWriteError``. Run ``ensure_partitions`` ahead of time rather
391
+ than relying on the retry.
392
+
393
+ Either kind is written even when ``session.info["audit_enabled"]`` is
394
+ ``False``, which only switches off the automatic ``entity.*`` entries.
395
+
396
+ Args:
397
+ session_or_event: A session of a class this ``AuditTrail`` is
398
+ installed on, followed by the event; or the event alone, or
399
+ after ``None``, to use ``session_provider``.
400
+ event: A registered host event.
401
+ obj: The object the event is about; sets ``object_type``,
402
+ ``object_id``, ``object_label`` and, through its options,
403
+ ``scope_id`` and the default target. It must have a primary
404
+ key: flush a new object first.
405
+ target: The parent object, as an instance or a ``Target`` (a
406
+ plain ``(type, id)`` tuple works too). A tuple id is formatted
407
+ as a composite ``object_id``; an id of ``None`` means no
408
+ target. Defaults to the ``target`` option of ``obj``.
409
+ payload: The payload, validated against the event's schema.
410
+ ``Pseudonymized`` fields of a schema are pseudonymized with
411
+ their field name as the purpose.
412
+ actor: The actor of this entry. It sets the entry's ``actor_id``
413
+ and the actor fields of its ``data.context``; the
414
+ ``audit_transaction`` row keeps the actor of the context.
415
+ durable: Overrides the event's ``durable`` setting; ``False``
416
+ cannot weaken a ``fail_closed`` event.
417
+
418
+ Raises:
419
+ RuntimeError: No session is passed and there is no
420
+ ``session_provider``, or it returns ``None``.
421
+ TypeError: The arguments are not ``(session, event)`` or
422
+ ``(event)``, the session is not a ``Session`` (use ``alog``
423
+ for an ``AsyncSession``), its class is not installed by this
424
+ ``AuditTrail``, or the write is durable and ``durable_engine``
425
+ is async.
426
+ ValueError: The event uses a reserved prefix, ``durable=False``
427
+ is given for a ``fail_closed`` event, ``obj`` or an instance
428
+ ``target`` has no primary key, or a ``Pseudonymized`` field
429
+ cannot be pseudonymized.
430
+ UnknownEventError: The event is not registered.
431
+ PayloadError: The payload does not match the event's schema, or a
432
+ ``Pseudonymized`` field already holds a pseudonym token.
433
+ AuditWriteError: A durable write failed and the policy says to
434
+ raise.
435
+ UnboundExecutionError: A non-durable entry without ``obj``, and
436
+ the session has neither a bind for the audit tables nor a
437
+ default bind.
438
+ """
439
+ from sqlalchemy.orm import Session
440
+
441
+ from audit_trail.listener import PendingEntry, write_entries
442
+ from audit_trail.writer import (
443
+ DURABLE_WRITE_ERRORS,
444
+ handle_durable_failure,
445
+ write_durable,
446
+ )
447
+
448
+ call = _split_call("log", session_or_event, event)
449
+ session = self._session_for("log", call.session)
450
+ if not isinstance(session, Session):
451
+ raise TypeError(
452
+ f"log() needs a Session, not {type(session).__qualname__}; "
453
+ "use alog() for an AsyncSession"
454
+ )
455
+ entry = self._prepare(session, call.event, obj, target, payload, actor, durable)
456
+ if not entry.flags.durable:
457
+ write_entries(session, self, [PendingEntry(entry.entry, obj)], entry.ctx)
458
+ return
459
+ engine = self.durable_engine
460
+ if not isinstance(engine, Engine):
461
+ raise TypeError(
462
+ "log() writes durable entries with a sync durable_engine; "
463
+ "this one is async: use alog()"
464
+ )
465
+ values = self._transaction_values(entry.ctx)
466
+ try:
467
+ with engine.connect() as conn:
468
+ write_durable(
469
+ conn,
470
+ self.tables,
471
+ self._severity_values(),
472
+ values,
473
+ [entry.entry],
474
+ auto_create_partitions=self.auto_create_partitions,
475
+ )
476
+ except DURABLE_WRITE_ERRORS as exc:
477
+ handle_durable_failure(exc, self.on_error, entry.flags.fail_closed)
478
+
479
+ @overload
480
+ async def alog(
481
+ self,
482
+ session: AsyncSession | None,
483
+ event: AuditEvent,
484
+ /,
485
+ *,
486
+ obj: object | None = None,
487
+ target: Target | object | None = None,
488
+ payload: Mapping[str, object] | BaseModel | None = None,
489
+ actor: Actor | None = None,
490
+ durable: bool | None = None,
491
+ ) -> None: ...
492
+
493
+ @overload
494
+ async def alog(
495
+ self,
496
+ event: AuditEvent,
497
+ /,
498
+ *,
499
+ obj: object | None = None,
500
+ target: Target | object | None = None,
501
+ payload: Mapping[str, object] | BaseModel | None = None,
502
+ actor: Actor | None = None,
503
+ durable: bool | None = None,
504
+ ) -> None: ...
505
+
506
+ async def alog(
507
+ self,
508
+ session_or_event: AsyncSession | AuditEvent | None,
509
+ event: AuditEvent | None = None,
510
+ /,
511
+ *,
512
+ obj: object | None = None,
513
+ target: Target | object | None = None,
514
+ payload: Mapping[str, object] | BaseModel | None = None,
515
+ actor: Actor | None = None,
516
+ durable: bool | None = None,
517
+ ) -> None:
518
+ """Async ``log``, for an ``AsyncSession`` of an installed factory.
519
+
520
+ Called as ``alog(session, event, ...)`` or, with a
521
+ ``session_provider`` configured, as ``alog(event, ...)``; see ``log``.
522
+
523
+ A non-durable entry is written in the session's transaction, a
524
+ durable one on the async ``durable_engine``; see ``log``.
525
+
526
+ Args:
527
+ session_or_event: An ``AsyncSession`` whose ``sync_session_class``
528
+ this ``AuditTrail`` is installed on, followed by the event; or
529
+ the event alone, or after ``None``, to use
530
+ ``session_provider``.
531
+ event: A registered host event.
532
+ obj: The object the event is about; see ``log``.
533
+ target: The parent object; see ``log``.
534
+ payload: The payload; see ``log``.
535
+ actor: The actor of this entry; see ``log``.
536
+ durable: Overrides the event's ``durable`` setting.
537
+
538
+ Raises:
539
+ RuntimeError: No session is passed and there is no
540
+ ``session_provider``, or it returns ``None``.
541
+ TypeError: The arguments are not ``(session, event)`` or
542
+ ``(event)``, the session is not an ``AsyncSession`` (use
543
+ ``log`` for a ``Session``), its class is not installed by this
544
+ ``AuditTrail``, or the write is durable and ``durable_engine``
545
+ is sync.
546
+ ValueError: As for ``log``.
547
+ UnknownEventError: The event is not registered.
548
+ PayloadError: The payload does not match the event's schema.
549
+ AuditWriteError: A durable write failed and the policy says to
550
+ raise.
551
+ UnboundExecutionError: As for ``log``.
552
+ """
553
+ from sqlalchemy.ext.asyncio import AsyncSession
554
+
555
+ from audit_trail.listener import PendingEntry, write_entries
556
+ from audit_trail.writer import (
557
+ DURABLE_WRITE_ERRORS,
558
+ handle_durable_failure,
559
+ write_durable,
560
+ )
561
+
562
+ call = _split_call("alog", session_or_event, event)
563
+ session = self._session_for("alog", call.session)
564
+ if not isinstance(session, AsyncSession):
565
+ raise TypeError(
566
+ f"alog() needs an AsyncSession, not {type(session).__qualname__}; "
567
+ "use log() for a Session"
568
+ )
569
+ entry = self._prepare(
570
+ session.sync_session, call.event, obj, target, payload, actor, durable
571
+ )
572
+ if not entry.flags.durable:
573
+ await session.run_sync(
574
+ lambda sync_session: write_entries(
575
+ sync_session, self, [PendingEntry(entry.entry, obj)], entry.ctx
576
+ )
577
+ )
578
+ return
579
+ engine = self.durable_engine
580
+ if isinstance(engine, Engine):
581
+ raise TypeError(
582
+ "alog() writes durable entries with an async durable_engine; "
583
+ "this one is sync: use log()"
584
+ )
585
+ values = self._transaction_values(entry.ctx)
586
+ try:
587
+ async with engine.connect() as conn:
588
+ await conn.run_sync(
589
+ write_durable,
590
+ self.tables,
591
+ self._severity_values(),
592
+ values,
593
+ [entry.entry],
594
+ auto_create_partitions=self.auto_create_partitions,
595
+ )
596
+ except DURABLE_WRITE_ERRORS as exc:
597
+ handle_durable_failure(exc, self.on_error, entry.flags.fail_closed)
598
+
599
+ def scrub(
600
+ self,
601
+ object_type: str,
602
+ object_id: str,
603
+ *,
604
+ include_targets: bool = True,
605
+ since: datetime | None = None,
606
+ ) -> ScrubResult:
607
+ """Erase the values the entries of one object hold.
608
+
609
+ Every non-null value in ``data.changes`` and ``data.payload`` of the
610
+ object's entries becomes ``"[erased]"`` (field keys stay, ``null``
611
+ stays ``null``) and ``object_label`` becomes ``NULL``. ``data.context``
612
+ is left to ``scrub_actor``. Runs in one transaction on ``engine``
613
+ together with an ``audit.scrubbed`` entry recording who scrubbed
614
+ which object and how many rows, without any erased value; nothing is
615
+ committed if either fails. With ``auto_create_partitions``, the
616
+ partitions of the current month are ensured first.
617
+
618
+ Args:
619
+ object_type: Stored ``object_type`` of the object.
620
+ object_id: Stored ``object_id`` of the object, as
621
+ ``audit_trail.diff.object_id_for`` formats it.
622
+ include_targets: Also erase entries whose target is the object,
623
+ such as changes of its children.
624
+ since: Only entries created at or after this aware datetime,
625
+ which also limits the partitions scanned. ``None`` for all.
626
+
627
+ Returns:
628
+ A ``ScrubResult``: ``activity_rows`` is the number of entries
629
+ erased (entries already erased are not counted);
630
+ ``transaction_rows`` is always ``0``.
631
+
632
+ Raises:
633
+ ScrubNotAllowedError: ``allow_scrub`` is ``False``.
634
+ TypeError: ``engine`` is async; use ``ascrub``.
635
+ ValueError: ``since`` is naive, or ``engine`` is in
636
+ ``AUTOCOMMIT`` mode.
637
+ """
638
+ from audit_trail import privacy
639
+
640
+ privacy.check_allowed(self.allow_scrub)
641
+ engine = self.engine
642
+ if not isinstance(engine, Engine):
643
+ raise TypeError("the engine is async; use ascrub")
644
+ privacy.check_since(since)
645
+ record = self._scrubbed_record()
646
+ if self.auto_create_partitions:
647
+ self.maintenance.ensure_partitions(months_ahead=0)
648
+ with engine.begin() as conn:
649
+ return privacy.scrub(
650
+ conn,
651
+ self.tables,
652
+ object_type,
653
+ object_id,
654
+ include_targets=include_targets,
655
+ since=since,
656
+ record=record,
657
+ )
658
+
659
+ async def ascrub(
660
+ self,
661
+ object_type: str,
662
+ object_id: str,
663
+ *,
664
+ include_targets: bool = True,
665
+ since: datetime | None = None,
666
+ ) -> ScrubResult:
667
+ """Async ``scrub``, for an ``AuditTrail`` built with an ``AsyncEngine``.
668
+
669
+ Args:
670
+ object_type: Stored ``object_type`` of the object.
671
+ object_id: Stored ``object_id`` of the object.
672
+ include_targets: Also erase entries whose target is the object.
673
+ since: Only entries created at or after this aware datetime.
674
+
675
+ Returns:
676
+ A ``ScrubResult``; see ``scrub``.
677
+
678
+ Raises:
679
+ ScrubNotAllowedError: ``allow_scrub`` is ``False``.
680
+ TypeError: ``engine`` is sync; use ``scrub``.
681
+ ValueError: As for ``scrub``.
682
+ """
683
+ from audit_trail import privacy
684
+
685
+ privacy.check_allowed(self.allow_scrub)
686
+ engine = self.engine
687
+ if isinstance(engine, Engine):
688
+ raise TypeError("the engine is sync; use scrub")
689
+ privacy.check_since(since)
690
+ record = self._scrubbed_record()
691
+ if self.auto_create_partitions:
692
+ await self.maintenance.aensure_partitions(months_ahead=0)
693
+ async with engine.begin() as conn:
694
+ return await conn.run_sync(
695
+ lambda sync_conn: privacy.scrub(
696
+ sync_conn,
697
+ self.tables,
698
+ object_type,
699
+ object_id,
700
+ include_targets=include_targets,
701
+ since=since,
702
+ record=record,
703
+ )
704
+ )
705
+
706
+ def scrub_actor(self, actor_id: str) -> ScrubResult:
707
+ """Clear the personal context stored for one actor.
708
+
709
+ ``audit_transaction`` rows created with this ``actor_id`` get
710
+ ``actor_label``, ``remote_addr``, ``user_agent`` and ``meta`` set to
711
+ ``NULL``, and entries with this ``actor_id`` lose those keys from
712
+ ``data.context``. ``actor_id`` stays. A transaction row keeps the
713
+ actor it was created with: a request that wrote its first entry
714
+ anonymously and called ``set_actor`` afterwards keeps its address
715
+ and user agent on that row. Runs in one transaction on ``engine``
716
+ with an ``audit.scrubbed`` entry, as ``scrub`` does.
717
+
718
+ Args:
719
+ actor_id: The actor's ``actor_id``.
720
+
721
+ Returns:
722
+ A ``ScrubResult`` with the numbers of activity and transaction
723
+ rows changed.
724
+
725
+ Raises:
726
+ ScrubNotAllowedError: ``allow_scrub`` is ``False``.
727
+ TypeError: ``engine`` is async; use ``ascrub_actor``.
728
+ ValueError: ``engine`` is in ``AUTOCOMMIT`` mode.
729
+ """
730
+ from audit_trail import privacy
731
+
732
+ privacy.check_allowed(self.allow_scrub)
733
+ engine = self.engine
734
+ if not isinstance(engine, Engine):
735
+ raise TypeError("the engine is async; use ascrub_actor")
736
+ record = self._scrubbed_record()
737
+ if self.auto_create_partitions:
738
+ self.maintenance.ensure_partitions(months_ahead=0)
739
+ with engine.begin() as conn:
740
+ return privacy.scrub_actor(conn, self.tables, actor_id, record=record)
741
+
742
+ async def ascrub_actor(self, actor_id: str) -> ScrubResult:
743
+ """Async ``scrub_actor``, for an ``AuditTrail`` built with an ``AsyncEngine``.
744
+
745
+ Args:
746
+ actor_id: The actor's ``actor_id``.
747
+
748
+ Returns:
749
+ A ``ScrubResult`` with the numbers of activity and transaction
750
+ rows changed.
751
+
752
+ Raises:
753
+ ScrubNotAllowedError: ``allow_scrub`` is ``False``.
754
+ TypeError: ``engine`` is sync; use ``scrub_actor``.
755
+ ValueError: ``engine`` is in ``AUTOCOMMIT`` mode.
756
+ """
757
+ from audit_trail import privacy
758
+
759
+ privacy.check_allowed(self.allow_scrub)
760
+ engine = self.engine
761
+ if isinstance(engine, Engine):
762
+ raise TypeError("the engine is sync; use scrub_actor")
763
+ record = self._scrubbed_record()
764
+ if self.auto_create_partitions:
765
+ await self.maintenance.aensure_partitions(months_ahead=0)
766
+ async with engine.begin() as conn:
767
+ return await conn.run_sync(
768
+ lambda sync_conn: privacy.scrub_actor(
769
+ sync_conn, self.tables, actor_id, record=record
770
+ )
771
+ )
772
+
773
+ def _scrubbed_record(self) -> ScrubbedRecord:
774
+ from audit_trail.events import AuditSystem
775
+ from audit_trail.privacy import ScrubbedRecord, scrub_context
776
+
777
+ return ScrubbedRecord(
778
+ int(self.registry.severity_of(AuditSystem.SCRUBBED)),
779
+ scrub_context(self.context_provider),
780
+ self.json_encoder,
781
+ )
782
+
783
+ def _transaction_values(self, ctx: AuditContext) -> TransactionValues:
784
+ from audit_trail.writer import transaction_values
785
+
786
+ return transaction_values(ctx, self.json_encoder)
787
+
788
+ def _severity_values(self) -> list[int]:
789
+ return [int(member) for member in self.severities]
790
+
791
+ def _session_for(
792
+ self, method: str, session: Session | AsyncSession | None
793
+ ) -> Session | AsyncSession:
794
+ # The explicit session, else the provider's; never silently nothing.
795
+ if session is not None:
796
+ return session
797
+ if self.session_provider is None:
798
+ raise RuntimeError(
799
+ f"{method}() needs a session: pass one or configure "
800
+ "AuditTrail(session_provider=...)"
801
+ )
802
+ provided = self.session_provider()
803
+ if provided is None:
804
+ raise RuntimeError(
805
+ f"{method}() got no session from session_provider "
806
+ "(is it called outside a request?): pass one"
807
+ )
808
+ return provided
809
+
810
+ def _prepare(
811
+ self,
812
+ session: Session,
813
+ event: AuditEvent,
814
+ obj: object | None,
815
+ target: Target | object | None,
816
+ payload: Mapping[str, object] | BaseModel | None,
817
+ actor: Actor | None,
818
+ durable: bool | None,
819
+ ) -> _PreparedEntry:
820
+ # Everything of log() before the write; no I/O.
821
+ from audit_trail.diff import (
822
+ USE_CONTEXT,
823
+ format_target,
824
+ object_type_of,
825
+ options_of,
826
+ resolve_label,
827
+ resolve_scope,
828
+ resolve_target,
829
+ )
830
+ from audit_trail.listener import installed_trail
831
+ from audit_trail.writer import ENVELOPE_VERSION, context_data, encode_payload
832
+
833
+ if str(event).startswith(RESERVED_PREFIXES):
834
+ raise ValueError(f"{event!s} is reserved for the library")
835
+ severity = self.registry.severity_of(event)
836
+ flags = resolve_write_flags(event, durable)
837
+ if installed_trail(session) is not self:
838
+ raise TypeError(
839
+ "log() needs a session of a class this AuditTrail is installed on"
840
+ )
841
+ encoded = encode_payload(
842
+ validate_payload(event, payload),
843
+ keys=self.keys,
844
+ json_encoder=self.json_encoder,
845
+ )
846
+
847
+ ctx = resolve_context(session, self.context_provider)
848
+ entry_ctx = ctx
849
+ if actor is not None:
850
+ entry_ctx = dataclasses.replace(
851
+ ctx, actor_type=actor.type, actor_id=actor.id, actor_label=actor.label
852
+ )
853
+
854
+ object_type = object_id = label = None
855
+ target_type: str | None = None
856
+ target_id: str | None = None
857
+ scope_id = ctx.scope_id
858
+ if obj is not None:
859
+ object_type, object_id = object_type_of(obj), _required_id(obj, "obj")
860
+ options = options_of(type(obj))
861
+ label = resolve_label(obj, options)
862
+ scope = resolve_scope(obj, options)
863
+ if scope is not USE_CONTEXT:
864
+ scope_id = scope
865
+ target_type, target_id = resolve_target(obj, options) or (None, None)
866
+ if isinstance(target, tuple):
867
+ target_type, target_id = format_target(Target(*target)) or (None, None)
868
+ elif target is not None:
869
+ target_type = object_type_of(target)
870
+ target_id = _required_id(target, "target")
871
+
872
+ return _PreparedEntry(
873
+ {
874
+ "verb": event.value,
875
+ "severity": int(severity),
876
+ "object_type": object_type,
877
+ "object_id": object_id,
878
+ "object_label": label,
879
+ "target_type": target_type,
880
+ "target_id": target_id,
881
+ "actor_id": entry_ctx.actor_id,
882
+ "scope_id": scope_id,
883
+ "data": {
884
+ "v": ENVELOPE_VERSION,
885
+ "payload": encoded,
886
+ "context": context_data(entry_ctx, self.json_encoder),
887
+ },
888
+ },
889
+ ctx,
890
+ flags,
891
+ )
892
+
893
+
894
+ class _Call(NamedTuple):
895
+ session: Session | AsyncSession | None
896
+ event: AuditEvent
897
+
898
+
899
+ def _split_call(
900
+ method: str,
901
+ first: Session | AsyncSession | AuditEvent | None,
902
+ second: AuditEvent | None,
903
+ ) -> _Call:
904
+ # log(event) or log(session, event); a session is never an AuditEvent.
905
+ match first, second:
906
+ case AuditEvent(), None:
907
+ return _Call(None, first)
908
+ case _, AuditEvent() if not isinstance(first, AuditEvent):
909
+ return _Call(first, second)
910
+ case _:
911
+ raise TypeError(f"{method}() takes (session, event) or (event)")
912
+
913
+
914
+ class _PreparedEntry(NamedTuple):
915
+ entry: Entry
916
+ ctx: AuditContext
917
+ flags: WriteFlags
918
+
919
+
920
+ def _default_durable_engine(engine: Engine | AsyncEngine) -> Engine | AsyncEngine:
921
+ # The URL object keeps the password (its string form masks it).
922
+ if isinstance(engine, Engine):
923
+ return create_engine(
924
+ engine.url,
925
+ pool_size=DURABLE_POOL_SIZE,
926
+ max_overflow=0,
927
+ pool_timeout=DURABLE_POOL_TIMEOUT,
928
+ pool_pre_ping=True,
929
+ )
930
+ # An AsyncEngine means the host has loaded asyncio support already.
931
+ from sqlalchemy.ext.asyncio import create_async_engine
932
+
933
+ return create_async_engine(
934
+ engine.url,
935
+ pool_size=DURABLE_POOL_SIZE,
936
+ max_overflow=0,
937
+ pool_timeout=DURABLE_POOL_TIMEOUT,
938
+ pool_pre_ping=True,
939
+ )
940
+
941
+
942
+ def _required_id(obj: object, name: str) -> str:
943
+ from audit_trail.diff import object_id_of
944
+
945
+ try:
946
+ return object_id_of(obj)
947
+ except ValueError:
948
+ raise ValueError(
949
+ f"{name} has no primary key yet; flush the session before logging"
950
+ ) from None