Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,21 @@
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.

Requires server version 3.26.20

1.5.0 (2026-10-07)
------------------

Expand Down
5 changes: 5 additions & 0 deletions datamasque/client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -177,8 +179,11 @@
__version__ = version("datamasque-python")

__all__ = [
"AiDetectionCacheClearResult",
"AsyncRulesetGenerationInProgressError",
"AsyncRulesetGenerationTaskStatus",
"AuditLog",
"AuditLogAction",
"AzureConnectionConfig",
"BooleanPreview",
"BooleanStatistics",
Expand Down
34 changes: 34 additions & 0 deletions datamasque/client/audit_logs.py
Original file line number Diff line number Diff line change
@@ -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]:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worth taking a project filter? The audit log endpoint has accepted ?project= since 3.26.22

"""
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))
2 changes: 2 additions & 0 deletions datamasque/client/dmclient.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -30,6 +31,7 @@ class DataMasqueClient(
RGConfigClient,
UserClient,
SettingsClient,
AuditLogClient,
):
"""
Client for a DataMasque server instance.
Expand Down
15 changes: 15 additions & 0 deletions datamasque/client/models/ai_detection_cache.py
Original file line number Diff line number Diff line change
@@ -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."""
45 changes: 45 additions & 0 deletions datamasque/client/models/audit_log.py
Original file line number Diff line number Diff line change
@@ -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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should an unknown action fail the whole listing? Same problem #86 just fixed for resource types

description: str
project: Optional[str] = None
"""
The project the event belongs to, as `<id>-<slug>`,
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.
"""
43 changes: 43 additions & 0 deletions datamasque/client/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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,
Expand Down
16 changes: 16 additions & 0 deletions docs/client.models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
------------------------------------------

Expand Down
8 changes: 8 additions & 0 deletions docs/client.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
-----------------------------

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "datamasque-python"
version = "1.5.0"
version = "1.6.0"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1.6.0 already went out with the projects epic, can this rebase onto main, drop the version bump and add its notes to the unreleased section in HISTORY.rst?

description = "Official Python client for the DataMasque data-masking API."
authors = [
{ name = "DataMasque Ltd" },
Expand Down
122 changes: 122 additions & 0 deletions tests/test_audit_logs.py
Original file line number Diff line number Diff line change
@@ -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
Loading