django-admin-api-mcp 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.
Files changed (73) hide show
  1. admin_api_mcp/__init__.py +9 -0
  2. admin_api_mcp/actions.py +197 -0
  3. admin_api_mcp/admin.py +131 -0
  4. admin_api_mcp/apps.py +10 -0
  5. admin_api_mcp/auth.py +62 -0
  6. admin_api_mcp/changelist.py +261 -0
  7. admin_api_mcp/checks.py +35 -0
  8. admin_api_mcp/confirm.py +97 -0
  9. admin_api_mcp/contrib/__init__.py +1 -0
  10. admin_api_mcp/contrib/search/__init__.py +0 -0
  11. admin_api_mcp/contrib/search/apps.py +21 -0
  12. admin_api_mcp/contrib/search/backend.py +121 -0
  13. admin_api_mcp/contrib/search/checks.py +12 -0
  14. admin_api_mcp/contrib/search/conf.py +42 -0
  15. admin_api_mcp/contrib/search/engines/__init__.py +0 -0
  16. admin_api_mcp/contrib/search/engines/base.py +99 -0
  17. admin_api_mcp/contrib/search/engines/db.py +265 -0
  18. admin_api_mcp/contrib/search/fold.py +41 -0
  19. admin_api_mcp/contrib/search/indexer.py +364 -0
  20. admin_api_mcp/contrib/search/management/__init__.py +0 -0
  21. admin_api_mcp/contrib/search/management/commands/__init__.py +0 -0
  22. admin_api_mcp/contrib/search/management/commands/rebuild_search_index.py +29 -0
  23. admin_api_mcp/contrib/search/management/commands/search_index.py +25 -0
  24. admin_api_mcp/contrib/search/migrations/0001_initial.py +83 -0
  25. admin_api_mcp/contrib/search/migrations/__init__.py +0 -0
  26. admin_api_mcp/contrib/search/models.py +43 -0
  27. admin_api_mcp/contrib/subadmin.py +37 -0
  28. admin_api_mcp/custom_views.py +471 -0
  29. admin_api_mcp/decorators.py +26 -0
  30. admin_api_mcp/deletion.py +58 -0
  31. admin_api_mcp/detail.py +115 -0
  32. admin_api_mcp/encoders.py +72 -0
  33. admin_api_mcp/errors.py +82 -0
  34. admin_api_mcp/jsonschema.py +225 -0
  35. admin_api_mcp/management/__init__.py +0 -0
  36. admin_api_mcp/management/commands/__init__.py +0 -0
  37. admin_api_mcp/management/commands/create_api_token.py +40 -0
  38. admin_api_mcp/management/commands/mcp_serve.py +86 -0
  39. admin_api_mcp/management/commands/migrate_from_admin_api.py +153 -0
  40. admin_api_mcp/mcp/__init__.py +7 -0
  41. admin_api_mcp/mcp/bridge.py +71 -0
  42. admin_api_mcp/mcp/handlers.py +771 -0
  43. admin_api_mcp/mcp/resolve.py +410 -0
  44. admin_api_mcp/mcp/server.py +76 -0
  45. admin_api_mcp/mcp/sites.py +284 -0
  46. admin_api_mcp/mcp/stdio.py +53 -0
  47. admin_api_mcp/mcp/tools.py +84 -0
  48. admin_api_mcp/mcp/views.py +74 -0
  49. admin_api_mcp/middleware.py +18 -0
  50. admin_api_mcp/migrations/0001_initial.py +40 -0
  51. admin_api_mcp/migrations/0002_mcp_confirmation.py +27 -0
  52. admin_api_mcp/migrations/0003_mcp_user_instructions.py +28 -0
  53. admin_api_mcp/migrations/__init__.py +0 -0
  54. admin_api_mcp/mixins.py +173 -0
  55. admin_api_mcp/models.py +145 -0
  56. admin_api_mcp/nested.py +122 -0
  57. admin_api_mcp/resolver.py +95 -0
  58. admin_api_mcp/scopes.py +142 -0
  59. admin_api_mcp/sensitive.py +67 -0
  60. admin_api_mcp/services.py +652 -0
  61. admin_api_mcp/sites.py +242 -0
  62. admin_api_mcp/templates/admin_api_mcp/token_created.html +17 -0
  63. admin_api_mcp/views/__init__.py +0 -0
  64. admin_api_mcp/views/changelist.py +70 -0
  65. admin_api_mcp/views/custom.py +33 -0
  66. admin_api_mcp/views/detail.py +50 -0
  67. admin_api_mcp/views/nested.py +73 -0
  68. admin_api_mcp/views/registry.py +15 -0
  69. admin_api_mcp/writes.py +530 -0
  70. django_admin_api_mcp-0.1.0.dist-info/METADATA +280 -0
  71. django_admin_api_mcp-0.1.0.dist-info/RECORD +73 -0
  72. django_admin_api_mcp-0.1.0.dist-info/WHEEL +4 -0
  73. django_admin_api_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,265 @@
1
+ """The built-in ``db`` engine: rows in the ``admin_api_mcp_search_entry`` table, scoped inside the query
2
+ by an ``EXISTS`` against each admin's ``get_queryset(request)``. Pass 1 matches ``norm`` exactly, by
3
+ prefix, word or substring; pass 2 (Postgres with ``pg_trgm``) adds ``word_similarity`` hits.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from functools import reduce
9
+ from operator import or_
10
+
11
+ from django.core import checks
12
+ from django.db import connection, models, transaction
13
+ from django.db.models import Case, Exists, F, FloatField, Max, OuterRef, Q, Value, When
14
+ from django.db.models.expressions import RawSQL
15
+ from django.db.models.functions import Cast, Lower, Replace
16
+ from django.utils import timezone
17
+
18
+ from ....mcp.resolve import CONFIDENCE
19
+ from .base import MODEL, OBJECT, Hit, SearchEngine, SearchQuery
20
+
21
+ UNSAFE_CTYPES = ("C", "POSIX")
22
+ UPSERT_VENDORS = ("postgresql", "sqlite")
23
+ UPSERT_BATCH = 500
24
+
25
+
26
+ def database_ctype() -> str | None:
27
+ """``LC_CTYPE`` of the default database on Postgres, else ``None``."""
28
+ if connection.vendor != "postgresql":
29
+ return None
30
+ with connection.cursor() as cursor:
31
+ cursor.execute("SELECT datctype FROM pg_database WHERE datname = current_database()")
32
+ return cursor.fetchone()[0]
33
+
34
+
35
+ def _any(conditions) -> Q:
36
+ conditions = list(conditions)
37
+ return reduce(or_, conditions) if conditions else Q(pk__in=[])
38
+
39
+
40
+ def _pk_field(model):
41
+ field = model._meta.pk
42
+ while field.is_relation: # multi-table inheritance: the parent link
43
+ field = field.target_field
44
+ return field
45
+
46
+
47
+ class DatabaseEngine(SearchEngine):
48
+ scope_pushdown = True
49
+
50
+ def __init__(self, name: str = "db", options: dict | None = None):
51
+ super().__init__(name, options)
52
+ self.threshold = float(self.options.get("TRIGRAM_THRESHOLD", 0.4))
53
+ self._trigram = None
54
+
55
+ @property
56
+ def model(self):
57
+ from ..models import SearchEntry
58
+
59
+ return SearchEntry
60
+
61
+ @property
62
+ def fuzzy(self) -> bool:
63
+ """Postgres with ``pg_trgm`` installed (checked once per process)."""
64
+ if self._trigram is None:
65
+ self._trigram = False
66
+ if connection.vendor == "postgresql":
67
+ with connection.cursor() as cursor:
68
+ cursor.execute("SELECT 1 FROM pg_extension WHERE extname = 'pg_trgm'")
69
+ self._trigram = cursor.fetchone() is not None
70
+ return self._trigram
71
+
72
+ # --- writes ---------------------------------------------------------------------------------
73
+ def upsert(self, entries) -> None:
74
+ rows = list({(e.content_type.pk, e.object_pk, e.field, e.language): e for e in entries}.values())
75
+ if not rows:
76
+ return
77
+ now = timezone.now()
78
+ if connection.vendor not in UPSERT_VENDORS:
79
+ self._upsert_portable(rows, now)
80
+ return
81
+ table = connection.ops.quote_name(self.model._meta.db_table)
82
+ columns = "kind, content_type_id, object_pk, field, language, text, norm, updated_at, indexed_at"
83
+ stamp = connection.ops.adapt_datetimefield_value(now)
84
+ with connection.cursor() as cursor:
85
+ for start in range(0, len(rows), UPSERT_BATCH):
86
+ chunk = rows[start : start + UPSERT_BATCH]
87
+ values = ", ".join(["(%s, %s, %s, %s, %s, %s, %s, %s, %s)"] * len(chunk))
88
+ params = []
89
+ for e in chunk:
90
+ params += [
91
+ e.kind,
92
+ e.content_type.pk,
93
+ e.object_pk,
94
+ e.field,
95
+ e.language,
96
+ e.text,
97
+ e.norm,
98
+ stamp,
99
+ stamp,
100
+ ]
101
+ cursor.execute(
102
+ f"INSERT INTO {table} ({columns}) VALUES {values} "
103
+ "ON CONFLICT (content_type_id, object_pk, field, language) DO UPDATE SET "
104
+ "kind = excluded.kind, text = excluded.text, "
105
+ f"updated_at = CASE WHEN {table}.norm = excluded.norm THEN {table}.updated_at "
106
+ "ELSE excluded.updated_at END, "
107
+ "norm = excluded.norm, indexed_at = excluded.indexed_at",
108
+ params,
109
+ )
110
+
111
+ def _upsert_portable(self, rows, now) -> None:
112
+ for e in rows:
113
+ current = self.model.objects.filter(
114
+ content_type=e.content_type, object_pk=e.object_pk, field=e.field, language=e.language
115
+ ).first()
116
+ if current is None:
117
+ self.model.objects.create(**vars(e), updated_at=now, indexed_at=now)
118
+ continue
119
+ if current.norm != e.norm:
120
+ current.updated_at = now
121
+ current.kind, current.text, current.norm, current.indexed_at = e.kind, e.text, e.norm, now
122
+ current.save()
123
+
124
+ def delete_rows(self, content_type, object_pk, fields) -> None:
125
+ self.model.objects.filter(content_type=content_type, object_pk=object_pk, field__in=list(fields)).delete()
126
+
127
+ def replace_model_rows(self, rows) -> None:
128
+ now = timezone.now()
129
+ with transaction.atomic():
130
+ self.model.objects.filter(kind=MODEL).delete()
131
+ self.model.objects.bulk_create(
132
+ [self.model(**vars(e), updated_at=now, indexed_at=now) for e in rows], batch_size=UPSERT_BATCH
133
+ )
134
+
135
+ def prune(self, content_types, older_than) -> int:
136
+ rows = self.model.objects.filter(kind=OBJECT, content_type__in=list(content_types), indexed_at__lt=older_than)
137
+ return rows.delete()[0]
138
+
139
+ # --- search ---------------------------------------------------------------------------------
140
+ def _scoped(self, query: SearchQuery):
141
+ """Rows of ``query.kind`` the scopes allow, with the ``EXISTS`` checks for object rows."""
142
+ rows, conditions, aliases = self.model.objects.filter(kind=query.kind), [], {}
143
+ for i, scope in enumerate(query.scopes):
144
+ ct_ids = [ct.pk for ct in scope.content_types]
145
+ condition = Q(content_type_id__in=ct_ids)
146
+ if query.kind == OBJECT:
147
+ condition &= Q(field__in=list(scope.fields))
148
+ condition &= self._exists(scope.queryset, ct_ids, f"_pk{i}", aliases)
149
+ conditions.append(condition)
150
+ return rows.alias(**aliases).filter(_any(conditions))
151
+
152
+ @staticmethod
153
+ def _exists(queryset, ct_ids, alias, aliases):
154
+ """``EXISTS`` of the row's object in ``queryset``. The text pk is cast on the outer side
155
+ (the inner pk index stays usable), guarded by the content type."""
156
+ pk = _pk_field(queryset.model)
157
+ if isinstance(pk, models.IntegerField):
158
+ target = models.BigIntegerField()
159
+ elif isinstance(pk, models.UUIDField) and connection.vendor == "postgresql":
160
+ target = models.UUIDField()
161
+ elif isinstance(pk, models.UUIDField): # stored as 32 hex digits outside Postgres
162
+ aliases[alias] = Case(
163
+ When(content_type_id__in=ct_ids, then=Lower(Replace(F("object_pk"), Value("-"), Value(""))))
164
+ )
165
+ return Exists(queryset.filter(pk=OuterRef(alias)))
166
+ elif isinstance(pk, (models.CharField, models.TextField)):
167
+ return Exists(queryset.filter(pk=OuterRef("object_pk")))
168
+ else:
169
+ inner = queryset.alias(_pk_text=Cast("pk", models.TextField()))
170
+ return Exists(inner.filter(_pk_text=OuterRef("object_pk")))
171
+ aliases[alias] = Case(When(content_type_id__in=ct_ids, then=Cast("object_pk", target)))
172
+ return Exists(queryset.filter(pk=OuterRef(alias)))
173
+
174
+ @staticmethod
175
+ def _rank(query: SearchQuery):
176
+ q = query.text
177
+ code = _any(
178
+ Q(content_type_id__in=[ct.pk for ct in s.content_types], field__in=list(s.code_fields))
179
+ for s in query.scopes
180
+ if s.code_fields
181
+ )
182
+ word = Q(norm__startswith=f"{q} ") | Q(norm__endswith=f" {q}") | Q(norm__contains=f" {q} ")
183
+ return Case(
184
+ When(Q(norm=q) & code, then=Value(CONFIDENCE["exact_code"])),
185
+ When(norm=q, then=Value(CONFIDENCE["exact"])),
186
+ When(norm__startswith=q, then=Value(CONFIDENCE["prefix"])),
187
+ When(word, then=Value(CONFIDENCE["word"])),
188
+ When(norm__contains=f" {q}", then=Value(CONFIDENCE["word_prefix"])),
189
+ default=Value(CONFIDENCE["contains"]),
190
+ output_field=FloatField(),
191
+ )
192
+
193
+ @staticmethod
194
+ def _matches(q: str) -> Q:
195
+ # terms under 3 characters: exact and prefix only (the trigram index needs 3)
196
+ return Q(norm__contains=q) if len(q) >= 3 else Q(norm=q) | Q(norm__startswith=q)
197
+
198
+ @staticmethod
199
+ def _top(rows, score, limit: int, offset: int = 0) -> list[tuple]:
200
+ top = (
201
+ rows.values("content_type_id", "object_pk")
202
+ .annotate(best=Max(score), seen=Max("updated_at"))
203
+ .order_by("-best", "-seen", "content_type_id", "object_pk")[offset : offset + limit]
204
+ )
205
+ return [(r["content_type_id"], r["object_pk"]) for r in top]
206
+
207
+ @staticmethod
208
+ def _rows_of(rows, keys, score):
209
+ """The rows of the candidates ``keys``, in candidate order, best row first."""
210
+ if not keys:
211
+ return []
212
+ found = rows.filter(_any(Q(content_type_id=ct, object_pk=pk) for ct, pk in keys)).annotate(score=score)
213
+ order = {key: i for i, key in enumerate(keys)}
214
+ return sorted(
215
+ found.values("content_type_id", "object_pk", "field", "norm", "score"),
216
+ key=lambda r: (order[(r["content_type_id"], r["object_pk"])], -r["score"]),
217
+ )
218
+
219
+ def search(self, query: SearchQuery) -> list[Hit]:
220
+ from django.contrib.contenttypes.models import ContentType
221
+
222
+ q = query.text
223
+ if not q or not query.scopes:
224
+ return []
225
+ scoped = self._scoped(query)
226
+ rank = self._rank(query)
227
+ matched = scoped.filter(self._matches(q))
228
+ keys = self._top(matched, rank, query.limit, query.offset)
229
+ rows = self._rows_of(matched, keys, rank)
230
+ if len(keys) < query.limit and self.fuzzy and len(q) >= 3:
231
+ rows += self._fuzzy_rows(scoped, q, keys, query.limit - len(keys))
232
+ return [
233
+ Hit(
234
+ content_type=ContentType.objects.get_for_id(r["content_type_id"]),
235
+ object_pk=r["object_pk"],
236
+ field=r["field"],
237
+ norm=r["norm"],
238
+ engine_score=float(r["score"]),
239
+ )
240
+ for r in rows
241
+ ]
242
+
243
+ def _fuzzy_rows(self, scoped, q: str, found_keys, limit: int) -> list[dict]:
244
+ column = f"{connection.ops.quote_name(self.model._meta.db_table)}.{connection.ops.quote_name('norm')}"
245
+ similar = RawSQL(f"%s <%% {column}", (q,), output_field=models.BooleanField())
246
+ score = RawSQL(f"word_similarity(%s, {column})", (q,), output_field=FloatField())
247
+ rows = scoped.filter(similar)
248
+ if found_keys:
249
+ rows = rows.exclude(_any(Q(content_type_id=ct, object_pk=pk) for ct, pk in found_keys))
250
+ with transaction.atomic(), connection.cursor() as cursor:
251
+ cursor.execute("SELECT set_config('pg_trgm.word_similarity_threshold', %s, true)", [str(self.threshold)])
252
+ keys = self._top(rows, score, limit)
253
+ return self._rows_of(rows, keys, score)
254
+
255
+ def check(self) -> list:
256
+ ctype = database_ctype()
257
+ if ctype in UNSAFE_CTYPES:
258
+ return [
259
+ checks.Warning(
260
+ f"The database LC_CTYPE is {ctype!r}: pg_trgm finds no trigrams in non-ASCII words.",
261
+ hint="Create the database with a UTF-8 locale such as C.UTF-8 or en_US.UTF-8.",
262
+ id="admin_api_mcp_search.W001",
263
+ )
264
+ ]
265
+ return []
@@ -0,0 +1,41 @@
1
+ """``fold()``: the one normalization applied to indexed text and to the search term."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import unicodedata
6
+
7
+ ARABIC_MAP = str.maketrans(
8
+ {
9
+ "أ": "ا",
10
+ "إ": "ا",
11
+ "آ": "ا",
12
+ "ٱ": "ا",
13
+ "ى": "ي",
14
+ "ة": "ه",
15
+ "ؤ": "و",
16
+ "ئ": "ي",
17
+ "ـ": None, # tatweel
18
+ "ک": "ك", # Persian kaf
19
+ "ی": "ي", # Persian yeh
20
+ **{chr(0x0660 + d): str(d) for d in range(10)}, # Arabic-Indic digits
21
+ **{chr(0x06F0 + d): str(d) for d in range(10)}, # Persian digits
22
+ }
23
+ )
24
+ ARTICLE = "ال"
25
+
26
+
27
+ def _strip_article(word: str) -> str:
28
+ if word.startswith(ARTICLE) and len(word) - len(ARTICLE) >= 2:
29
+ return word[len(ARTICLE) :]
30
+ return word
31
+
32
+
33
+ def fold(text) -> str:
34
+ """Folded ``text``: NFKC, Arabic letter and digit variants unified, combining marks dropped,
35
+ casefolded, whitespace collapsed, and a leading "ال" stripped from each Arabic word."""
36
+ if text is None:
37
+ return ""
38
+ value = unicodedata.normalize("NFKC", str(text)).translate(ARABIC_MAP)
39
+ value = "".join(c for c in unicodedata.normalize("NFKD", value) if not unicodedata.combining(c))
40
+ value = unicodedata.normalize("NFC", value).casefold()
41
+ return " ".join(_strip_article(word) for word in value.split())
@@ -0,0 +1,364 @@
1
+ """Which rows exist: object rows from the admins' search fields, model rows from ``Meta`` labels.
2
+
3
+ Indexed models are the admins exposed by every ``AdminMcpSite`` minus its ``excluded_models``.
4
+ Rows stay current through ``post_save`` and ``post_delete`` (on commit), ``post_migrate`` (model
5
+ rows) and the batched rebuild behind ``rebuild_search_index`` and ``search_index ensure``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import hashlib
12
+ import json
13
+ import logging
14
+ from contextvars import ContextVar
15
+ from functools import cached_property
16
+
17
+ from django.apps import apps
18
+ from django.contrib.contenttypes.models import ContentType
19
+ from django.core.exceptions import FieldDoesNotExist
20
+ from django.db import DEFAULT_DB_ALIAS, models, transaction
21
+ from django.utils import timezone, translation
22
+
23
+ from ...mcp.resolve import _languages, is_excluded
24
+ from ...sensitive import Redactor
25
+ from .conf import get_engine, search_settings
26
+ from .engines.base import MODEL, OBJECT, Entry
27
+ from .fold import fold
28
+
29
+ logger = logging.getLogger("admin_api_mcp.search")
30
+
31
+ # bump when fold() or the row derivation changes: `search_index ensure` then rebuilds every model
32
+ INDEX_FORMAT = 1
33
+ INDEXED_FIELD_TYPES = (models.CharField, models.TextField, models.IntegerField, models.DecimalField)
34
+ LABEL_FIELDS = ("verbose_name", "verbose_name_plural", "model_name")
35
+ _suspended = ContextVar("admin_api_mcp_search_suspended", default=False)
36
+
37
+
38
+ def local_field_name(model, search_field: str) -> str | None:
39
+ """The local field a search field reads (``^name`` and ``name__iexact`` -> ``name``), or ``None``
40
+ for relation paths and fields whose values are not indexed (dates, booleans, relations)."""
41
+ name = search_field.lstrip("^=@").split("__", 1)[0]
42
+ try:
43
+ field = model._meta.pk if name == "pk" else model._meta.get_field(name)
44
+ except FieldDoesNotExist:
45
+ return None
46
+ if field.is_relation or not field.concrete or not isinstance(field, INDEXED_FIELD_TYPES):
47
+ return None
48
+ if "__" in search_field and field.get_lookup(search_field.split("__", 1)[1].split("__")[0]) is None:
49
+ return None # a transform or a path, not a lookup on this field
50
+ return field.name
51
+
52
+
53
+ def local_fields(model, search_fields) -> tuple[str, ...]:
54
+ return tuple(dict.fromkeys(f for f in (local_field_name(model, s) for s in search_fields or ()) if f))
55
+
56
+
57
+ def nearest_model(model, registered) -> type[models.Model] | None:
58
+ """``model`` or its nearest ancestor in ``registered`` (the admin a row of ``model`` belongs to)."""
59
+ return next((m for m in model.__mro__ if m in registered), None)
60
+
61
+
62
+ def owned_models(model, registered) -> list:
63
+ """``model`` and the subclasses without an admin in ``registered`` whose rows belong to it."""
64
+ others = (m for m in apps.get_models() if m is not model and issubclass(m, model))
65
+ return [model, *(m for m in others if nearest_model(m, registered) is model)]
66
+
67
+
68
+ def model_names(model, model_admins, language) -> list[tuple[str, str]]:
69
+ """``(field, text)`` of the model's verbose name, plural, model name and admins' ``search_aliases``."""
70
+ with translation.override(language):
71
+ names = [(f, str(getattr(model._meta, f))) for f in LABEL_FIELDS]
72
+ aliases = [a for ma in model_admins for a in (getattr(ma, "search_aliases", None) or {}).get(language, ())]
73
+ return names + [(f"alias.{i}", str(alias)) for i, alias in enumerate(aliases)]
74
+
75
+
76
+ def content_type_of(model) -> ContentType:
77
+ return ContentType.objects.get_for_model(model, for_concrete_model=False)
78
+
79
+
80
+ def default_sites():
81
+ """Every ``AdminMcpSite``, after the URLconf that creates them is imported."""
82
+ from django.urls import get_resolver
83
+
84
+ from ...mcp.sites import all_mcp_sites
85
+
86
+ get_resolver().url_patterns # noqa: B018
87
+ return all_mcp_sites()
88
+
89
+
90
+ class Indexer:
91
+ """Builds and writes the rows of the indexed models of ``sites`` (default: every MCP site)."""
92
+
93
+ def __init__(self, sites=None):
94
+ self._sites = sites
95
+
96
+ @property
97
+ def engine(self):
98
+ return get_engine()
99
+
100
+ @cached_property
101
+ def admins(self) -> dict:
102
+ """``{model: [api admin, ...]}``, one admin per site that indexes the model."""
103
+ out: dict = {}
104
+ for site in default_sites() if self._sites is None else self._sites:
105
+ for model, model_admin in site.api_site.exposed_admins():
106
+ if site.is_exposed(model_admin) and not is_excluded(site, model):
107
+ out.setdefault(model, []).append(model_admin)
108
+ return out
109
+
110
+ def index_fields(self, model) -> tuple[str, ...]:
111
+ """Union over the model's admins of ``get_search_index_fields()``, else the local fields of
112
+ ``search_fields`` and ``api_search_fields``, minus the fields any of those admins redacts."""
113
+ names: list = []
114
+ model_admins = self.admins.get(model, ())
115
+ for model_admin in model_admins:
116
+ hook = getattr(model_admin, "get_search_index_fields", None)
117
+ if hook is not None:
118
+ names.extend(hook())
119
+ else:
120
+ names.extend(getattr(model_admin, "search_fields", None) or ())
121
+ names.extend(getattr(model_admin, "api_search_fields", None) or ())
122
+ redactors = [Redactor(model_admin, None) for model_admin in model_admins]
123
+ return tuple(f for f in local_fields(model, names) if not any(redact(f) for redact in redactors))
124
+
125
+ def admin_model(self, model):
126
+ return nearest_model(model, self.admins)
127
+
128
+ # --- object rows --------------------------------------------------------------------------
129
+ def row_target(self, obj):
130
+ """``(content type, admin model)`` of ``obj``'s rows: the django-polymorphic leaf when the
131
+ model has one, else the model of the admin the object belongs to."""
132
+ ctype_id = getattr(obj, "polymorphic_ctype_id", None)
133
+ leaf = ContentType.objects.get_for_id(ctype_id).model_class() if ctype_id else type(obj)
134
+ admin_model = self.admin_model(leaf) if leaf else None
135
+ if admin_model is None:
136
+ return None, None
137
+ return content_type_of(leaf if ctype_id else admin_model), admin_model
138
+
139
+ def object_entries(self, obj, content_type, admin_model) -> tuple[list[Entry], list[str]]:
140
+ """The rows of ``obj`` and the index fields it leaves empty."""
141
+ entries, empty = [], []
142
+ object_pk = str(obj.pk)
143
+ for name in self.index_fields(admin_model):
144
+ value = getattr(obj, obj._meta.get_field(name).attname, None)
145
+ norm = fold(value) if value is not None else ""
146
+ if not norm:
147
+ empty.append(name)
148
+ continue
149
+ entries.append(Entry(OBJECT, content_type, object_pk, name, "", str(value), norm))
150
+ return entries, empty
151
+
152
+ def index_object(self, obj) -> None:
153
+ content_type, admin_model = self.row_target(obj)
154
+ if content_type is None:
155
+ return
156
+ entries, empty = self.object_entries(obj, content_type, admin_model)
157
+ with transaction.atomic():
158
+ if entries:
159
+ self.engine.upsert(entries)
160
+ if empty:
161
+ self.engine.delete_rows(content_type, str(obj.pk), fields=empty)
162
+
163
+ def delete_targets(self, obj) -> dict:
164
+ """``{content type: index fields}`` that can hold ``obj``'s rows: its row target and every
165
+ indexed model on the same concrete model (proxies with their own admin)."""
166
+ content_type, admin_model = self.row_target(obj)
167
+ targets = {content_type: self.index_fields(admin_model)} if content_type else {}
168
+ concrete = obj._meta.concrete_model
169
+ for model in self.admins:
170
+ if model._meta.concrete_model is concrete:
171
+ targets[content_type_of(model)] = self.index_fields(model)
172
+ return {ct: fields for ct, fields in targets.items() if fields}
173
+
174
+ def unindex_object(self, targets: dict, object_pk: str) -> None:
175
+ """Delete the rows of a deleted object from each of its ``delete_targets``."""
176
+ with transaction.atomic():
177
+ for content_type, fields in targets.items():
178
+ self.engine.delete_rows(content_type, object_pk, fields=fields)
179
+
180
+ # --- model rows ---------------------------------------------------------------------------
181
+ def model_entries(self) -> list[Entry]:
182
+ """Each indexed model's verbose name, plural and model name under every language, plus the
183
+ admin's ``search_aliases``; one row per (model, folded text)."""
184
+ rows, languages = [], _languages()
185
+ for model, model_admins in self.admins.items():
186
+ content_type, seen = content_type_of(model), set()
187
+ for language in languages:
188
+ for field, text in model_names(model, model_admins, language):
189
+ norm = fold(text)
190
+ if norm and norm not in seen:
191
+ seen.add(norm)
192
+ rows.append(Entry(MODEL, content_type, None, field, language, text, norm))
193
+ return rows
194
+
195
+ def refresh_model_rows(self) -> int:
196
+ rows = self.model_entries()
197
+ self.engine.replace_model_rows(rows)
198
+ return len(rows)
199
+
200
+ # --- rebuild --------------------------------------------------------------------------------
201
+ def rebuild_model(self, model, *, batch_size: int = 1000, stdout=None) -> int:
202
+ """Rewrite every row of ``model``, one transaction per batch, then prune rows this run did
203
+ not write. Returns the number of objects processed."""
204
+ started = timezone.now()
205
+ owned_types = [content_type_of(m) for m in owned_models(model, self.admins)]
206
+ if not self.index_fields(model):
207
+ self.engine.prune(owned_types, older_than=started)
208
+ return 0
209
+ queryset = model._base_manager.order_by("pk")
210
+ total, done, label = queryset.count(), 0, model._meta.label_lower
211
+ batch: list = []
212
+
213
+ def flush():
214
+ entries = []
215
+ for obj in batch:
216
+ content_type, admin_model = self.row_target(obj)
217
+ if admin_model is model: # a polymorphic leaf with its own admin is rebuilt there
218
+ entries.extend(self.object_entries(obj, content_type, admin_model)[0])
219
+ with transaction.atomic():
220
+ self.engine.upsert(entries)
221
+ batch.clear()
222
+ if stdout:
223
+ stdout.write(f"processed {done}/{total} {label}")
224
+ stdout.flush()
225
+
226
+ for obj in queryset.iterator(chunk_size=batch_size):
227
+ batch.append(obj)
228
+ done += 1
229
+ if len(batch) >= batch_size:
230
+ flush()
231
+ if batch:
232
+ flush()
233
+ self.engine.prune(owned_types, older_than=started)
234
+ return done
235
+
236
+ def fingerprint(self, model) -> str:
237
+ """What the rows of ``model`` derive from: its index fields, the languages, the engine."""
238
+ conf = search_settings()
239
+ engine = conf["DEFAULT_ENGINE"]
240
+ payload = [
241
+ INDEX_FORMAT,
242
+ model._meta.label_lower,
243
+ self.index_fields(model),
244
+ _languages(),
245
+ engine,
246
+ conf["ENGINES"].get(engine, {}).get("BACKEND"),
247
+ ]
248
+ return hashlib.sha256(json.dumps(payload, default=str).encode()).hexdigest()
249
+
250
+ def rebuild(self, labels=None, *, batch_size: int = 1000, force: bool = True, stdout=None) -> list[str]:
251
+ """Rebuild the indexed models (``labels`` narrows them; without ``force``, only those whose
252
+ fingerprint changed), record fingerprints and drop models no longer indexed. Returns the
253
+ labels rebuilt."""
254
+ from .models import SearchIndexState
255
+
256
+ indexed = {m._meta.label_lower: m for m in self.admins}
257
+ state = dict(SearchIndexState.objects.values_list("label", "fingerprint"))
258
+ rebuilt = []
259
+ for label, model in indexed.items():
260
+ if labels is not None and label not in labels:
261
+ continue
262
+ fingerprint = self.fingerprint(model)
263
+ if not force and state.get(label) == fingerprint:
264
+ continue
265
+ self.rebuild_model(model, batch_size=batch_size, stdout=stdout)
266
+ SearchIndexState.objects.update_or_create(label=label, defaults={"fingerprint": fingerprint})
267
+ rebuilt.append(label)
268
+ if labels is None:
269
+ self.drop_stale(set(state) - set(indexed), stdout=stdout)
270
+ return rebuilt
271
+
272
+ def drop_stale(self, labels, stdout=None) -> None:
273
+ """Delete the rows and state of models that are no longer indexed."""
274
+ from .models import SearchIndexState
275
+
276
+ for label in sorted(labels):
277
+ try:
278
+ model = apps.get_model(label)
279
+ except LookupError:
280
+ model = None
281
+ if model is not None:
282
+ self.engine.prune([content_type_of(model)], older_than=timezone.now())
283
+ SearchIndexState.objects.filter(label=label).delete()
284
+ if stdout:
285
+ stdout.write(f"dropped {label}")
286
+
287
+
288
+ _indexer: Indexer | None = None
289
+
290
+
291
+ def get_indexer() -> Indexer:
292
+ global _indexer
293
+ if _indexer is None:
294
+ _indexer = Indexer()
295
+ return _indexer
296
+
297
+
298
+ def set_indexer(indexer: Indexer | None) -> None:
299
+ """Replace the indexer the signals use (``None``: rebuild it from every MCP site on next use)."""
300
+ global _indexer
301
+ _indexer = indexer
302
+
303
+
304
+ def _index_saved(indexer: Indexer, obj) -> None:
305
+ try:
306
+ indexer.index_object(obj)
307
+ except Exception:
308
+ logger.exception("search index: could not index %s %r", obj._meta.label_lower, obj.pk)
309
+
310
+
311
+ def _unindex_deleted(indexer: Indexer, targets: dict, label: str, object_pk: str) -> None:
312
+ """Delete a deleted object's rows, logging a failure."""
313
+ try:
314
+ indexer.unindex_object(targets, object_pk)
315
+ except Exception:
316
+ logger.exception("search index: could not unindex %s %r", label, object_pk)
317
+
318
+
319
+ @contextlib.contextmanager
320
+ def indexing_suspended():
321
+ """Saves and deletes inside the block (this thread or task only) skip the index, for bulk loads.
322
+ Run ``rebuild_search_index`` after the load."""
323
+ token = _suspended.set(True)
324
+ try:
325
+ yield
326
+ finally:
327
+ _suspended.reset(token)
328
+
329
+
330
+ def on_post_save(sender, instance, raw=False, using=DEFAULT_DB_ALIAS, **kwargs):
331
+ if raw or _suspended.get():
332
+ return
333
+ try:
334
+ indexer = get_indexer()
335
+ if indexer.admin_model(sender) is None:
336
+ return
337
+ except Exception:
338
+ logger.exception("search index: could not load the indexed models")
339
+ return
340
+ transaction.on_commit(lambda: _index_saved(indexer, instance), using=using)
341
+
342
+
343
+ def on_post_delete(sender, instance, using=DEFAULT_DB_ALIAS, **kwargs):
344
+ """Delete the rows of an indexed object on commit."""
345
+ if _suspended.get():
346
+ return
347
+ try:
348
+ indexer = get_indexer()
349
+ targets = indexer.delete_targets(instance)
350
+ except Exception:
351
+ logger.exception("search index: could not load the indexed models")
352
+ return
353
+ if targets: # read now: the pk is None once the delete finishes
354
+ label, object_pk = instance._meta.label_lower, str(instance.pk)
355
+ transaction.on_commit(lambda: _unindex_deleted(indexer, targets, label, object_pk), using=using)
356
+
357
+
358
+ def on_post_migrate(using=DEFAULT_DB_ALIAS, **kwargs):
359
+ if using != DEFAULT_DB_ALIAS:
360
+ return
361
+ try:
362
+ get_indexer().refresh_model_rows()
363
+ except Exception:
364
+ logger.exception("search index: could not refresh the model rows")
File without changes