From 2917d80368bbbe0995e84cdf9d1b58bc65dad072 Mon Sep 17 00:00:00 2001 From: Ben Shaw Date: Mon, 19 Oct 2026 17:18:28 +1300 Subject: [PATCH 1/2] feat(client): add AI detection cache and audit log methods Add get_ai_detection_cache_size_bytes and clear_ai_detection_cache (returning AiDetectionCacheClearResult) to SettingsClient, and an AuditLogClient with iter_audit_logs and list_audit_logs returning AuditLog models newest first. Bump the version to 1.6.0. --- HISTORY.rst | 13 ++ datamasque/client/__init__.py | 5 + datamasque/client/audit_logs.py | 34 +++++ datamasque/client/dmclient.py | 2 + .../client/models/ai_detection_cache.py | 15 +++ datamasque/client/models/audit_log.py | 45 +++++++ datamasque/client/settings.py | 43 ++++++ docs/client.models.rst | 16 +++ docs/client.rst | 8 ++ pyproject.toml | 2 +- tests/test_audit_logs.py | 122 ++++++++++++++++++ tests/test_settings.py | 65 +++++++++- uv.lock | 2 +- 13 files changed, 369 insertions(+), 3 deletions(-) create mode 100644 datamasque/client/audit_logs.py create mode 100644 datamasque/client/models/ai_detection_cache.py create mode 100644 datamasque/client/models/audit_log.py create mode 100644 tests/test_audit_logs.py diff --git a/HISTORY.rst b/HISTORY.rst index 1786d5a..419d812 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -2,6 +2,19 @@ History ======= +1.6.0 (2026-10-19) +------------------ + +* Added ``get_ai_detection_cache_size_bytes`` and ``clear_ai_detection_cache`` + to read the size of the AI detection cache and delete its entries: + all of them, or with ``unused_for_days`` only those no masking run has used in that many days. + ``clear_ai_detection_cache`` returns an ``AiDetectionCacheClearResult`` + with the bytes freed and the size of the cache after the clear. +* Added ``list_audit_logs`` and ``iter_audit_logs``, which return audit log entries newest first + as ``AuditLog`` models, with ``action`` typed by the new ``AuditLogAction`` enum. + ``list_audit_logs`` takes an optional ``limit`` to return only the newest entries. + ``project`` and ``project_name`` are ``None`` on servers older than 3.26.20. + 1.5.0 (2026-10-07) ------------------ diff --git a/datamasque/client/__init__.py b/datamasque/client/__init__.py index 2122c6d..abd75ba 100644 --- a/datamasque/client/__init__.py +++ b/datamasque/client/__init__.py @@ -27,6 +27,8 @@ RunNotCancellableError, ) from datamasque.client.ifm import DataMasqueIfmClient +from datamasque.client.models.ai_detection_cache import AiDetectionCacheClearResult +from datamasque.client.models.audit_log import AuditLog, AuditLogAction from datamasque.client.models.connection import ( AzureConnectionConfig, CassandraConnectionConfig, @@ -177,8 +179,11 @@ __version__ = version("datamasque-python") __all__ = [ + "AiDetectionCacheClearResult", "AsyncRulesetGenerationInProgressError", "AsyncRulesetGenerationTaskStatus", + "AuditLog", + "AuditLogAction", "AzureConnectionConfig", "BooleanPreview", "BooleanStatistics", diff --git a/datamasque/client/audit_logs.py b/datamasque/client/audit_logs.py new file mode 100644 index 0000000..d9abdad --- /dev/null +++ b/datamasque/client/audit_logs.py @@ -0,0 +1,34 @@ +from itertools import islice +from typing import Iterator, Optional + +from datamasque.client.base import BaseClient +from datamasque.client.models.audit_log import AuditLog + + +class AuditLogClient(BaseClient): + """Audit log API methods. Mixed into `DataMasqueClient`.""" + + def iter_audit_logs(self) -> Iterator[AuditLog]: + """ + Lazily iterate audit log entries, newest first, via the paginated endpoint. + + Requires an admin user. + """ + + return self._iter_paginated("/api/audit-logs/", model=AuditLog) + + def list_audit_logs(self, *, limit: Optional[int] = None) -> list[AuditLog]: + """ + Lists audit log entries, newest first. + + When `limit` is given, returns at most that many of the newest entries, + and fetches only the pages they are on. + When it is `None` (the default), returns every entry. + Requires an admin user. + """ + + entries = self.iter_audit_logs() + if limit is None: + return list(entries) + + return list(islice(entries, limit)) diff --git a/datamasque/client/dmclient.py b/datamasque/client/dmclient.py index 7e8cc7f..31e82d0 100644 --- a/datamasque/client/dmclient.py +++ b/datamasque/client/dmclient.py @@ -1,3 +1,4 @@ +from datamasque.client.audit_logs import AuditLogClient from datamasque.client.base import FileOrContent, UploadFile from datamasque.client.connections import ConnectionClient from datamasque.client.discovery import DiscoveryClient @@ -30,6 +31,7 @@ class DataMasqueClient( RGConfigClient, UserClient, SettingsClient, + AuditLogClient, ): """ Client for a DataMasque server instance. diff --git a/datamasque/client/models/ai_detection_cache.py b/datamasque/client/models/ai_detection_cache.py new file mode 100644 index 0000000..5b457c1 --- /dev/null +++ b/datamasque/client/models/ai_detection_cache.py @@ -0,0 +1,15 @@ +"""Typed response shape for clearing the AI detection cache.""" + +from pydantic import BaseModel, ConfigDict + + +class AiDetectionCacheClearResult(BaseModel): + """Result of `clear_ai_detection_cache`.""" + + model_config = ConfigDict(extra="allow") + + freed_bytes: int + """The disk space the clear freed, in bytes.""" + + size_bytes: int + """The size of the cache on disk after the clear, in bytes.""" diff --git a/datamasque/client/models/audit_log.py b/datamasque/client/models/audit_log.py new file mode 100644 index 0000000..68231db --- /dev/null +++ b/datamasque/client/models/audit_log.py @@ -0,0 +1,45 @@ +"""Typed response shape for the audit log endpoint.""" + +from datetime import datetime +from enum import Enum +from typing import Optional + +from pydantic import BaseModel, ConfigDict + + +class AuditLogAction(str, Enum): + """What the user did in an audited event.""" + + created = "created" + modified = "modified" + deleted = "deleted" + logged_in = "logged_in" + logged_out = "logged_out" + started = "started" + cancelled = "cancelled" + + +class AuditLog(BaseModel): + """One audit log entry.""" + + model_config = ConfigDict(extra="allow") + + id: int + timestamp: datetime + username: str + category: str + """The area the event belongs to, such as `auth`, `run` or `settings`, or the kind of object it changed.""" + + action: AuditLogAction + description: str + project: Optional[str] = None + """ + The project the event belongs to, as `-`, + or `None` for an event outside any project or from a server older than 3.26.20. + """ + + project_name: Optional[str] = None + """ + The project's name when the event was logged, + or `None` for an event outside any project or from a server older than 3.26.20. + """ diff --git a/datamasque/client/settings.py b/datamasque/client/settings.py index 3b837c9..3d65463 100644 --- a/datamasque/client/settings.py +++ b/datamasque/client/settings.py @@ -4,6 +4,7 @@ from datamasque.client.base import BaseClient from datamasque.client.exceptions import DataMasqueUserError +from datamasque.client.models.ai_detection_cache import AiDetectionCacheClearResult class SettingsClient(BaseClient): @@ -23,6 +24,48 @@ def set_locality(self, locality: str) -> None: self.make_request("PATCH", path="api/settings/", data={"locality": locality}) + def get_ai_detection_cache_size_bytes(self) -> int: + """ + Returns the size on disk of the AI detection cache, in bytes. + + The cache holds the `ai_detect` results that tasks with `cache_ai_detect_spans` set to `true` + reuse on later runs. + Requires an admin user. + + Raises: + DataMasqueApiError: the caller is not an admin user, + or the server could not read the cache directory. + """ + + response = self.make_request("GET", "/api/ai-detection-cache/") + return response.json()["size_bytes"] + + def clear_ai_detection_cache(self, unused_for_days: Optional[int] = None) -> AiDetectionCacheClearResult: + """ + Deletes entries from the AI detection cache. + + `unused_for_days`, from 1 to 36500, + deletes only the entries that no masking run has used in that many days. + `None` (the default) deletes every entry. + On the next run, DataMasque sends the texts of the deleted entries to the AI Engine again. + Requires an admin user. + + Returns the bytes freed and the size of the cache after the clear. + + Raises: + DataMasqueApiError: `unused_for_days` is out of range, + the caller is not an admin user, + or the server could not clear the cache. + A failed clear may have deleted some entries before it failed. + """ + + response = self.make_request( + "POST", + "/api/ai-detection-cache/clear/", + data={"unused_for_days": unused_for_days}, + ) + return AiDetectionCacheClearResult.model_validate(response.json()) + def admin_install( self, email: str, diff --git a/docs/client.models.rst b/docs/client.models.rst index e98789b..a6108ff 100644 --- a/docs/client.models.rst +++ b/docs/client.models.rst @@ -4,6 +4,22 @@ datamasque.client.models package Submodules ---------- +datamasque.client.models.ai_detection_cache module +-------------------------------------------------- + +.. automodule:: datamasque.client.models.ai_detection_cache + :members: + :undoc-members: + :show-inheritance: + +datamasque.client.models.audit_log module +----------------------------------------- + +.. automodule:: datamasque.client.models.audit_log + :members: + :undoc-members: + :show-inheritance: + datamasque.client.models.connection module ------------------------------------------ diff --git a/docs/client.rst b/docs/client.rst index f013c64..999c345 100644 --- a/docs/client.rst +++ b/docs/client.rst @@ -12,6 +12,14 @@ Subpackages Submodules ---------- +datamasque.client.audit_logs module +----------------------------------- + +.. automodule:: datamasque.client.audit_logs + :members: + :undoc-members: + :show-inheritance: + datamasque.client.base module ----------------------------- diff --git a/pyproject.toml b/pyproject.toml index b3183ec..6f3eaed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "datamasque-python" -version = "1.5.0" +version = "1.6.0" description = "Official Python client for the DataMasque data-masking API." authors = [ { name = "DataMasque Ltd" }, diff --git a/tests/test_audit_logs.py b/tests/test_audit_logs.py new file mode 100644 index 0000000..6e12f8c --- /dev/null +++ b/tests/test_audit_logs.py @@ -0,0 +1,122 @@ +"""Tests for `AuditLogClient` (listing audit log entries).""" + +from datetime import datetime, timezone + +import requests_mock + +from datamasque.client.models.audit_log import AuditLog, AuditLogAction + +AUDIT_LOGS_URL = "http://test-server/api/audit-logs/" + + +def audit_log_json(id, *, action="created", project=None, project_name=None): + return { + "id": id, + "timestamp": f"2026-10-{id:02d}T09:30:00Z", + "username": "admin", + "category": "settings", + "action": action, + "description": f"admin made change {id}", + "project": project, + "project_name": project_name, + } + + +def test_list_audit_logs_parses_fields(client): + page = { + "count": 1, + "next": None, + "previous": None, + "results": [audit_log_json(7, action="deleted", project="3-payments", project_name="Payments")], + } + with requests_mock.Mocker() as m: + m.get(AUDIT_LOGS_URL, json=page, status_code=200) + audit_logs = client.list_audit_logs() + + assert audit_logs == [ + AuditLog( + id=7, + timestamp=datetime(2026, 10, 7, 9, 30, tzinfo=timezone.utc), + username="admin", + category="settings", + action=AuditLogAction.deleted, + description="admin made change 7", + project="3-payments", + project_name="Payments", + ) + ] + assert audit_logs[0].action is AuditLogAction.deleted + assert audit_logs[0].action == "deleted" + + +def test_list_audit_logs_accepts_entries_without_project_fields(client): + entry = audit_log_json(1, action="logged_in") + del entry["project"] + del entry["project_name"] + with requests_mock.Mocker() as m: + m.get(AUDIT_LOGS_URL, json={"count": 1, "next": None, "previous": None, "results": [entry]}) + audit_logs = client.list_audit_logs() + + assert audit_logs[0].action is AuditLogAction.logged_in + assert audit_logs[0].project is None + assert audit_logs[0].project_name is None + + +def test_list_audit_logs_follows_pages_newest_first(client): + page1 = { + "count": 3, + "next": f"{AUDIT_LOGS_URL}?limit=100&offset=100", + "previous": None, + "results": [audit_log_json(3), audit_log_json(2)], + } + page2 = { + "count": 3, + "next": None, + "previous": f"{AUDIT_LOGS_URL}?limit=100", + "results": [audit_log_json(1)], + } + with requests_mock.Mocker() as m: + m.get(AUDIT_LOGS_URL, [{"json": page1, "status_code": 200}, {"json": page2, "status_code": 200}]) + audit_logs = client.list_audit_logs() + + assert [audit_log.id for audit_log in audit_logs] == [3, 2, 1] + assert m.request_history[0].qs == {"limit": ["100"], "offset": ["0"]} + assert m.request_history[1].qs == {"limit": ["100"], "offset": ["100"]} + + +def test_list_audit_logs_with_limit_stops_fetching_pages(client): + page1 = { + "count": 3, + "next": f"{AUDIT_LOGS_URL}?limit=100&offset=100", + "previous": None, + "results": [audit_log_json(3), audit_log_json(2)], + } + with requests_mock.Mocker() as m: + m.get(AUDIT_LOGS_URL, json=page1, status_code=200) + audit_logs = client.list_audit_logs(limit=1) + + assert [audit_log.id for audit_log in audit_logs] == [3] + assert m.call_count == 1 + + +def test_list_audit_logs_with_zero_limit_sends_no_request(client): + with requests_mock.Mocker() as m: + audit_logs = client.list_audit_logs(limit=0) + + assert audit_logs == [] + assert m.call_count == 0 + + +def test_iter_audit_logs_is_lazy(client): + page1 = { + "count": 2, + "next": f"{AUDIT_LOGS_URL}?limit=100&offset=100", + "previous": None, + "results": [audit_log_json(2)], + } + with requests_mock.Mocker() as m: + m.get(AUDIT_LOGS_URL, json=page1, status_code=200) + newest = next(client.iter_audit_logs()) + + assert newest.id == 2 + assert m.call_count == 1 diff --git a/tests/test_settings.py b/tests/test_settings.py index 6df4e38..fa55e7e 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -1,10 +1,11 @@ -"""Tests for `SettingsClient` (admin install bootstrap, application logs, locality).""" +"""Tests for `SettingsClient` (admin install bootstrap, application logs, locality, AI detection cache).""" import pytest import requests_mock from datamasque.client import DataMasqueClient from datamasque.client.exceptions import DataMasqueApiError, DataMasqueUserError +from datamasque.client.models.ai_detection_cache import AiDetectionCacheClearResult from datamasque.client.models.dm_instance import DataMasqueInstanceConfig from tests.helpers import fake @@ -105,3 +106,65 @@ def test_set_locality_sends_patch(client): client.set_locality("en_GB") assert m.last_request.json() == {"locality": "en_GB"} + + +def test_get_ai_detection_cache_size_bytes(client): + with requests_mock.Mocker() as m: + m.get("http://test-server/api/ai-detection-cache/", json={"size_bytes": 4096}, status_code=200) + size_bytes = client.get_ai_detection_cache_size_bytes() + + assert size_bytes == 4096 + assert m.last_request.method == "GET" + + +def test_get_ai_detection_cache_size_bytes_raises_when_server_cannot_read_cache(client): + with requests_mock.Mocker() as m: + m.get( + "http://test-server/api/ai-detection-cache/", + json={"message": "Could not measure the AI detection cache: permission denied"}, + status_code=500, + ) + with pytest.raises(DataMasqueApiError) as exc_info: + client.get_ai_detection_cache_size_bytes() + + assert exc_info.value.response.status_code == 500 + + +def test_clear_ai_detection_cache_sends_null_unused_for_days_by_default(client): + with requests_mock.Mocker() as m: + m.post( + "http://test-server/api/ai-detection-cache/clear/", + json={"freed_bytes": 2048, "size_bytes": 0}, + status_code=200, + ) + result = client.clear_ai_detection_cache() + + assert m.last_request.json() == {"unused_for_days": None} + assert result == AiDetectionCacheClearResult(freed_bytes=2048, size_bytes=0) + + +def test_clear_ai_detection_cache_sends_unused_for_days(client): + with requests_mock.Mocker() as m: + m.post( + "http://test-server/api/ai-detection-cache/clear/", + json={"freed_bytes": 1024, "size_bytes": 3072}, + status_code=200, + ) + result = client.clear_ai_detection_cache(unused_for_days=30) + + assert m.last_request.json() == {"unused_for_days": 30} + assert result.freed_bytes == 1024 + assert result.size_bytes == 3072 + + +def test_clear_ai_detection_cache_raises_when_server_refuses_unused_for_days(client): + with requests_mock.Mocker() as m: + m.post( + "http://test-server/api/ai-detection-cache/clear/", + json={"unused_for_days": ["Ensure this value is greater than or equal to 1."]}, + status_code=400, + ) + with pytest.raises(DataMasqueApiError) as exc_info: + client.clear_ai_detection_cache(unused_for_days=0) + + assert exc_info.value.response.status_code == 400 diff --git a/uv.lock b/uv.lock index 7164d65..0fb45ec 100644 --- a/uv.lock +++ b/uv.lock @@ -419,7 +419,7 @@ toml = [ [[package]] name = "datamasque-python" -version = "1.5.0" +version = "1.6.0" source = { editable = "." } dependencies = [ { name = "pydantic" }, From ac2fe5ceea4de548245bc8b7e9f9938e00e80332 Mon Sep 17 00:00:00 2001 From: Ben Shaw Date: Tue, 20 Oct 2026 20:09:47 +1300 Subject: [PATCH 2/2] docs: no-ticket: note that 1.6.0 requires server version 3.26.20 --- HISTORY.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/HISTORY.rst b/HISTORY.rst index 419d812..7aa9940 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -15,6 +15,8 @@ History ``list_audit_logs`` takes an optional ``limit`` to return only the newest entries. ``project`` and ``project_name`` are ``None`` on servers older than 3.26.20. +Requires server version 3.26.20 + 1.5.0 (2026-10-07) ------------------