diff --git a/docs/decisions/0002-schema-declarations-and-adapter-contract.rst b/docs/decisions/0002-schema-declarations-and-adapter-contract.rst index 056b77b..4ce1fd1 100644 --- a/docs/decisions/0002-schema-declarations-and-adapter-contract.rst +++ b/docs/decisions/0002-schema-declarations-and-adapter-contract.rst @@ -173,9 +173,12 @@ absent. The second is ``Adapter.validate_schema()``, which covers what the first cannot: capabilities the neutral model allows but this particular adapter cannot -represent. Every adapter implements it. It is a no-op for Meilisearch and -Typesense, and the hook for an adapter with a narrower feature set, which raises -``UnsupportedSchema`` naming the parts it cannot represent. +represent. Every adapter implements it. It is a no-op for Meilisearch, and the +hook for an adapter with a narrower feature set, which raises +``UnsupportedSchema`` naming the parts it cannot represent. Typesense uses it for +two limits: it ranks ``query_by_weights`` into 16 levels, so a 17th searchable +field would lose its declared order, and its adapter reserves the names of the +hidden filter fields described with filters in "Consumers use a small API". ``register_use_case()`` does not call ``validate_schema()``; it validates the registration object and its index ownership only, so the registry never reads @@ -356,6 +359,14 @@ OR. Negation, ranges and field-to-field comparisons are out of scope until a consumer needs one; adding it extends ``FilterTerm`` rather than the expression shape. +Typesense's ``:=`` does not compare strings exactly: it compares tokenized +values, so case, punctuation and accents are ignored (``ab`` matches ``a-b`` +and ``AB``). Its adapter writes a hidden ``__exact`` companion holding +the SHA-256 digest of each value of a filterable string field, and renders +string filters against the digests. ``id`` is compared exactly and is filtered +directly. The Typesense adapter refuses a filter on a field that is neither +``id`` nor declared ``filterable``, which Meilisearch rejects at the engine. + ``mint_credential`` takes a ``CredentialScope`` of tenant filters and a positive ``expires_in`` lifetime as a ``timedelta``, and returns a ``SearchCredential``. It is derived locally (Meilisearch tenant tokens, @@ -364,6 +375,10 @@ converts ``expires_in`` to the engine's absolute expiry (Typesense's Unix timestamp, Meilisearch's expiry date). For Typesense the key embeds ``query_by`` and ``query_by_weights`` from the schema, and deliberately not ``sort_by``: embedded parameters cannot be overridden, and the sort is a per-query choice. +A Typesense scoped key cannot name a collection, and one ``search_api_key`` +serves every use case on a backend, so every document also carries a hidden +``__index`` digest of its logical index and every key filters on it. A key +minted for one index finds nothing in another. ``SearchCredential`` carries ``url``, ``index_name`` and ``api_key``. A bare key is not enough for the browser: ``url`` is the backend's ``public_url``, a diff --git a/src/openedx_search/adapters.py b/src/openedx_search/adapters.py index 4b4ba41..438446f 100644 --- a/src/openedx_search/adapters.py +++ b/src/openedx_search/adapters.py @@ -9,19 +9,22 @@ class exists so an engine contribution has one place to see the full surface. from __future__ import annotations +import threading from abc import ABC, abstractmethod -from collections.abc import Mapping, Sequence +from collections.abc import Callable, Mapping, Sequence from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any, TypeAlias -from .config import BackendConfig +from .config import BackendConfig, get_backend_config from .registry import UseCaseRegistration from .schema import FIELD_NAME_PATTERN, INDEX_NAME_PATTERN, IndexSchema __all__ = [ "Adapter", "AdapterError", + "AdapterFactory", + "AdapterNotRegistered", "CredentialScope", "Document", "DocumentBatch", @@ -37,6 +40,9 @@ class exists so an engine contribution has one place to see the full surface. "UnsupportedSchema", "WriteFailed", "WriteReceipt", + "clear_adapter_registry", + "get_adapter", + "register_adapter", ] Document: TypeAlias = Mapping[str, Any] @@ -113,6 +119,31 @@ def __post_init__(self) -> None: FilterExpression: TypeAlias = tuple[FilterGroup, ...] +def normalize_filter_expression( + filters: FilterExpression, + *, + raise_if_empty: bool = False, +) -> tuple[FilterGroup, ...]: + """ + Validate and freeze a sequence of ``FilterGroup`` values. + + Raises ``ValueError`` for a string, a non-sequence or a non-group item, and + for an empty sequence when ``raise_if_empty`` is true. + """ + if isinstance(filters, (str, bytes)): + raise ValueError("filters must be a sequence of FilterGroup, not a string") + try: + groups = tuple(filters) + except TypeError as exc: + raise ValueError("filters must be a sequence of FilterGroup") from exc + if not groups and raise_if_empty: + raise ValueError("filters must not be empty") + for group in groups: + if not isinstance(group, FilterGroup): + raise ValueError("filters must contain FilterGroup instances") + return groups + + @dataclass(frozen=True) class CredentialScope: """Tenant filters for a scoped frontend credential.""" @@ -121,13 +152,7 @@ class CredentialScope: def __post_init__(self) -> None: """Validate and freeze the filter groups.""" - if isinstance(self.filters, (str, bytes)): - raise ValueError("filters must be a sequence of FilterGroup, not a string") - filters = tuple(self.filters) - for group in filters: - if not isinstance(group, FilterGroup): - raise ValueError("filters must contain FilterGroup instances") - object.__setattr__(self, "filters", filters) + object.__setattr__(self, "filters", normalize_filter_expression(self.filters)) @dataclass(frozen=True) @@ -295,3 +320,55 @@ def search(self, query: Any) -> SearchResult: @abstractmethod def mint_credential(self, scope: CredentialScope, expires_in: timedelta) -> SearchCredential: """Mint a scoped, expiring credential and the endpoint to use it against.""" + + +AdapterFactory: TypeAlias = Callable[[UseCaseRegistration, BackendConfig], Adapter] + +_adapter_factories: dict[str, AdapterFactory] = {} +_adapter_lock = threading.RLock() + + +class AdapterNotRegistered(AdapterError): + """No adapter is registered for the backend's engine.""" + + +def register_adapter(engine: str, factory: AdapterFactory, *, replace: bool = False) -> None: + """ + Register the adapter factory for an engine. + + Raises ``ValueError`` when the engine already has a factory, unless + ``replace`` is true. + """ + if not isinstance(engine, str) or not engine: + raise ValueError("engine must be a non-empty string") + if not callable(factory): + raise ValueError("factory must be callable") + with _adapter_lock: + if engine in _adapter_factories and not replace: + raise ValueError(f"an adapter is already registered for engine {engine!r}") + _adapter_factories[engine] = factory + + +def get_adapter( + registration: UseCaseRegistration, + backend: BackendConfig | None = None, +) -> Adapter: + """ + Build the adapter for a registration and its resolved backend. + + Raises ``AdapterNotRegistered`` when the backend's engine has no factory. + """ + backend = backend or get_backend_config(registration.use_case) + factory = _adapter_factories.get(backend.engine) + if factory is None: + raise AdapterNotRegistered( + f"no adapter is registered for engine {backend.engine!r}; " + "register one with register_adapter()" + ) + return factory(registration, backend) + + +def clear_adapter_registry() -> None: + """Remove every adapter factory. Intended for tests and process shutdown.""" + with _adapter_lock: + _adapter_factories.clear() diff --git a/src/openedx_search/api.py b/src/openedx_search/api.py index 7a6379a..c3606cd 100644 --- a/src/openedx_search/api.py +++ b/src/openedx_search/api.py @@ -2,11 +2,9 @@ Consumer-facing API for openedx-search. ADR 0002, Decision 4: consumers use this module rather than talking to an -adapter. The functions resolve the registration and backend internally. The -registry helpers in ``openedx_search.registry`` are not part of this surface. - -These functions are currently signatures and contracts only; the -implementations land with the engine adapters. +adapter. The functions resolve the registration, validate the input and delegate +to the adapter for the configured backend. The registry helpers in +``openedx_search.registry`` are not part of this surface. """ from __future__ import annotations @@ -25,11 +23,16 @@ SearchCredential, SearchResult, WriteReceipt, + get_adapter, + normalize_filter_expression, ) +from .documents import DocumentError, validate_documents +from .registry import get_registration from .schema import document_id_from_key, validate_document_id __all__ = [ "CredentialScope", + "DocumentError", "DocumentSource", "RebuildInProgress", "RebuildResult", @@ -62,18 +65,20 @@ def upsert(use_case: str, documents: DocumentBatch) -> WriteReceipt: """ Submit one bounded batch of documents for upsert. - ``documents`` is a sequence, not a one-shot iterator, because a same-version - reindex in progress submits the same batch to both the live index and the - target. The returned receipt covers the live index; the reindex confirms the - target's copy before it swaps. + ``documents`` is a sequence, not a one-shot iterator. Every document is + validated against the registration's schema before it reaches the adapter, + so both engines accept and reject the same documents. - During a same-version reindex the batch is also submitted to the rebuild - target. A failure in either submission is raised to the caller. The caller - may retry with the same batch, since the operation is an upsert. A target - with a different schema version is a migration, whose writers are stopped; - submitting to it raises ``SchemaVersionMismatch``. + The rebuild target dual-write lands with the rebuild lifecycle. Until then + the batch is submitted to the live index only. """ - raise NotImplementedError("upsert is implemented with the engine adapters") # pragma: no cover + registration = get_registration(use_case) + if isinstance(documents, (str, bytes)) or not isinstance(documents, Sequence): + raise ValueError("documents must be a sequence of mappings") + if not documents: + raise ValueError("documents must not be empty") + validate_documents(registration.schema, documents) + return get_adapter(registration).upsert(documents) def _normalize_primary_keys( @@ -84,6 +89,8 @@ def _normalize_primary_keys( return None if isinstance(primary_keys, str): return (validate_document_id(primary_keys),) + if isinstance(primary_keys, (bytes, bytearray)) or not isinstance(primary_keys, Sequence): + raise ValueError("primary_keys must be a string or a sequence of strings") keys = tuple(primary_keys) if not keys: raise ValueError("primary_keys must not be empty") @@ -105,11 +112,19 @@ def delete( filter expression used by search, never a raw engine string. Exactly one of ``primary_keys`` and ``filter`` is required, and neither may - be empty, so a bare call cannot empty an index. During a same-version - reindex the delete is also submitted to the target; a target with a - different version raises ``SchemaVersionMismatch``. + be empty, so a bare call cannot empty an index. The rebuild target + dual-write lands with the rebuild lifecycle. """ - raise NotImplementedError("delete is implemented with the engine adapters") # pragma: no cover + registration = get_registration(use_case) + keys = _normalize_primary_keys(primary_keys) + expression = ( + None + if filter is None + else normalize_filter_expression(filter, raise_if_empty=True) + ) + if (keys is None) == (expression is None): + raise ValueError("exactly one of primary_keys and filter is required") + return get_adapter(registration).delete(primary_keys=keys, filter=expression) def check_write(use_case: str, receipt: WriteReceipt) -> WriteReceipt: @@ -121,7 +136,10 @@ def check_write(use_case: str, receipt: WriteReceipt) -> WriteReceipt: already-complete receipt without a request. The worker calls this until the receipt is complete and raises when the engine reports a failed write. """ - raise NotImplementedError("check_write is implemented with the engine adapters") # pragma: no cover + if not isinstance(receipt, WriteReceipt): + raise ValueError("receipt must be a WriteReceipt") + registration = get_registration(use_case) + return get_adapter(registration).check_write(receipt) def rebuild(use_case: str, document_source: DocumentSource) -> RebuildResult: @@ -174,7 +192,7 @@ def search(use_case: str, query: Any) -> SearchResult: raise NotImplementedError("search is implemented with the engine adapters") # pragma: no cover -def mint_credential( # pylint: disable=unused-argument +def mint_credential( use_case: str, scope: CredentialScope, expires_in: timedelta ) -> SearchCredential: """ @@ -191,6 +209,11 @@ def mint_credential( # pylint: disable=unused-argument connection URL, and the index name belongs to the adapter, so the browser needs all three rather than a bare key. """ + if not isinstance(scope, CredentialScope): + raise ValueError("scope must be a CredentialScope") + if not isinstance(expires_in, timedelta): + raise ValueError("expires_in must be a timedelta") if expires_in <= timedelta(0): raise ValueError("expires_in must be positive") - raise NotImplementedError("mint_credential is implemented with the engine adapters") # pragma: no cover + registration = get_registration(use_case) + return get_adapter(registration).mint_credential(scope, expires_in) diff --git a/src/openedx_search/apps.py b/src/openedx_search/apps.py index 32a4744..4abef70 100644 --- a/src/openedx_search/apps.py +++ b/src/openedx_search/apps.py @@ -13,3 +13,15 @@ class OpenEdxSearchConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "openedx_search" verbose_name = "Open edX Search" + + def ready(self) -> None: + """Register the engine adapters the library ships.""" + # Imported here so the app module stays free of engine code until the + # settings are loaded, and so a consumer cannot import an adapter by + # accident through this module. + # pylint: disable=import-outside-toplevel + from .meilisearch import register as register_meilisearch + from .typesense import register as register_typesense + + register_meilisearch() + register_typesense() diff --git a/src/openedx_search/documents.py b/src/openedx_search/documents.py new file mode 100644 index 0000000..7e8719a --- /dev/null +++ b/src/openedx_search/documents.py @@ -0,0 +1,199 @@ +""" +Document validation against an ``IndexSchema``. + +ADR 0002: the library validates every document before it reaches an adapter, so +both engines accept and reject the same documents. A violation raises +``DocumentError`` naming the document id, the field and the reason. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from datetime import datetime +from typing import Any + +from .schema import Field, FieldType, IndexSchema, validate_document_id + +__all__ = ["DocumentError", "validate_document", "validate_documents"] + +# Signed ranges of the declared integer types. A Python int is unbounded, but +# the engines narrow or reject out-of-range values differently, so the library +# rejects them before either engine sees them. +_INTEGER_RANGES: dict[FieldType, tuple[int, int]] = { + FieldType.INT32: (-(2**31), 2**31 - 1), + FieldType.INT64: (-(2**63), 2**63 - 1), +} + + +class DocumentError(ValueError): + """A document does not match its schema.""" + + +def validate_documents(schema: IndexSchema, documents: Sequence[Mapping[str, Any]]) -> None: + """Validate every document in one bounded batch.""" + for document in documents: + validate_document(schema, document) + + +def validate_document(schema: IndexSchema, document: Mapping[str, Any]) -> None: + """Validate one document against ``schema``.""" + if not isinstance(document, Mapping): + raise DocumentError("a document must be a mapping") + by_name = {field.name: field for field in schema.fields} + try: + _validate_object(by_name, document, prefix="") + except DocumentError as exc: + raise DocumentError(f"{_label(document)}: {exc}") from exc + + +def _label(document: Mapping[str, Any]) -> str: + """Name the document in an error, when it has an id.""" + doc_id = document.get("id") + if isinstance(doc_id, str) and doc_id: + return f"document {doc_id!r}" + return "document" + + +def _validate_object( + by_name: dict[str, Field], + obj: Mapping[str, Any], + *, + prefix: str, +) -> None: + """Validate one object level, including required children and free-form keys.""" + parent_name = prefix[:-1] if prefix else None + parent = by_name.get(parent_name) if parent_name else None + free_form = bool(parent and parent.additional_properties) + inside_array = bool(parent and parent.type is FieldType.OBJECT and parent.array) + + for key, value in obj.items(): + if not isinstance(key, str): + raise DocumentError("field names must be strings") + full_name = f"{prefix}{key}" + if "." in key and not free_form: + raise DocumentError(f"unknown field {full_name!r}") + field = by_name.get(full_name) + if field is None: + if free_form: + if not isinstance(value, str): + raise DocumentError(f"free-form field {full_name!r} must be a string") + continue + raise DocumentError(f"unknown field {full_name!r}") + _validate_field(by_name, field, value, inside_array=inside_array) + + _validate_required(by_name, obj, prefix=prefix, parent_name=parent_name) + if prefix == "": + try: + validate_document_id(obj.get("id")) + except ValueError as exc: + raise DocumentError(str(exc)) from exc + + +def _validate_required( + by_name: dict[str, Field], + obj: Mapping[str, Any], + *, + prefix: str, + parent_name: str | None, +) -> None: + """Require the fields declared required at this object level.""" + for name, field in by_name.items(): + if not field.required: + continue + field_parent = name.rsplit(".", 1)[0] if "." in name else None + if field_parent != parent_name: + continue + if name[len(prefix):] not in obj: + raise DocumentError(f"required field {name!r} is missing") + + +def _validate_field( + by_name: dict[str, Field], + field: Field, + value: Any, + *, + inside_array: bool, +) -> None: + """Validate one field value; array-ness is implied inside an object array.""" + if value is None: + raise DocumentError(f"field {field.name!r} cannot be null") + if field.type is FieldType.OBJECT: + _validate_object_value(by_name, field, value, inside_array=inside_array) + return + if field.array and not inside_array: + for element in _as_array(field, value): + _validate_scalar(field, element) + return + _validate_scalar(field, value) + + +def _validate_object_value( + by_name: dict[str, Field], + field: Field, + value: Any, + *, + inside_array: bool, +) -> None: + """Validate an object, an object array, or one object per parent element.""" + if inside_array and isinstance(value, Mapping): + _validate_object(by_name, value, prefix=f"{field.name}.") + return + if field.array: + for element in _as_array(field, value): + if not isinstance(element, Mapping): + raise DocumentError(f"field {field.name!r} must contain objects") + _validate_object(by_name, element, prefix=f"{field.name}.") + return + if not isinstance(value, Mapping): + raise DocumentError(f"field {field.name!r} must be an object") + _validate_object(by_name, value, prefix=f"{field.name}.") + + +def _as_array(field: Field, value: Any) -> Sequence[Any]: + """Require a list or tuple, not a string or bytes.""" + if isinstance(value, (str, bytes)) or not isinstance(value, (list, tuple)): + raise DocumentError(f"field {field.name!r} must be an array") + return value + + +def _validate_scalar(field: Field, value: Any) -> None: + """Validate one value against the field's base type and integer range.""" + if value is None: + raise DocumentError(f"field {field.name!r} cannot be null") + if not _matches_type(field.type, value): + raise DocumentError(f"field {field.name!r} must be {_type_name(field.type)}") + integer_range = _INTEGER_RANGES.get(field.type) + if integer_range is not None and not integer_range[0] <= value <= integer_range[1]: + raise DocumentError( + f"field {field.name!r} must be between {integer_range[0]} and {integer_range[1]}" + ) + + +def _matches_type(field_type: FieldType, value: Any) -> bool: + """Return whether a scalar value matches a field type.""" + if field_type is FieldType.STRING: + return isinstance(value, str) + if field_type in (FieldType.INT32, FieldType.INT64): + return isinstance(value, int) and not isinstance(value, bool) + if field_type is FieldType.FLOAT: + return isinstance(value, (int, float)) and not isinstance(value, bool) + if field_type is FieldType.BOOL: + return isinstance(value, bool) + if field_type is FieldType.DATETIME: + if isinstance(value, datetime): + return value.tzinfo is not None and value.utcoffset() is not None + return isinstance(value, (int, float)) and not isinstance(value, bool) + return False # pragma: no cover - objects are handled before the scalar check + + +def _type_name(field_type: FieldType) -> str: + """Describe a field type in an error message.""" + if field_type is FieldType.DATETIME: + return "a timezone-aware datetime or POSIX seconds" + if field_type is FieldType.FLOAT: + return "a number" + if field_type in (FieldType.INT32, FieldType.INT64): + return "an integer" + if field_type is FieldType.BOOL: + return "a boolean" + return f"a {field_type.value}" diff --git a/src/openedx_search/meilisearch.py b/src/openedx_search/meilisearch.py new file mode 100644 index 0000000..58b0519 --- /dev/null +++ b/src/openedx_search/meilisearch.py @@ -0,0 +1,469 @@ +""" +Meilisearch implementation of the adapter contract. + +The adapter owns the physical index name, the settings rendered from the +declared schema and the lifecycle tasks. It talks to the HTTP API directly, so +the library keeps Django as its only dependency. + +Meilisearch applies index changes asynchronously and answers with a task id. +The lifecycle methods wait for their tasks, because a deploy that ignores a +failed settings update would keep serving the old settings. Writes return the +task id to the caller as a ``WriteReceipt``; ``check_write`` performs one poll +and never sleeps, since scheduling belongs to the indexing worker. +""" + +from __future__ import annotations + +import base64 +import hashlib +import hmac +import json +import time +from collections.abc import Mapping, Sequence +from datetime import datetime, timedelta, timezone +from typing import Any +from urllib.parse import quote + +from .adapters import ( + Adapter, + AdapterError, + CredentialScope, + DocumentBatch, + FilterExpression, + FilterValue, + PrimaryKey, + RebuildTarget, + ReconcileResult, + SearchCredential, + SearchResult, + WriteFailed, + WriteReceipt, + register_adapter, +) +from .config import BackendConfig +from .registry import UseCaseRegistration +from .schema import Searchable +from .transport import HTTPTransport, TransportError + +__all__ = [ + "MEILISEARCH_RANKING_RULES", + "MeilisearchAdapter", + "register", + "render_filter", +] + +# `sort` first: an explicit sort must outrank relevance, and the rule is inert +# when the query carries no `sort` parameter. The remaining rules are the +# engine defaults, pinned so a deployment's own ranking changes are reverted. +MEILISEARCH_RANKING_RULES = ("sort", "words", "typo", "proximity", "attribute", "exactness") + +TASK_TIMEOUT = 30.0 +TASK_POLL_INTERVAL = 0.1 +MAX_POLL_INTERVAL = 1.0 +PAGE_SIZE = 1000 + + +class MeilisearchAdapter(Adapter): + """The adapter for one Meilisearch deployment.""" + + def __init__( + self, + registration: UseCaseRegistration, + backend: BackendConfig, + *, + transport: HTTPTransport | None = None, + ) -> None: + """Build the transport unless the caller supplies one for testing.""" + super().__init__(registration, backend) + self._transport = transport or HTTPTransport( + backend.url, + {"Authorization": f"Bearer {backend.api_key}"}, + ) + + def validate_schema(self) -> None: + """Meilisearch represents every schema the neutral model allows.""" + + def settings(self) -> dict[str, Any]: + """ + Render the declared schema as Meilisearch index settings. + + The primary key is always filterable so ``id`` filters behave the same + on both engines, where Typesense filters any declared field. + """ + searchable = sorted( + ( + ( + field.capabilities.searchable.order + if isinstance(field.capabilities.searchable, Searchable) + else None, + position, + field.name, + ) + for position, field in enumerate(self.schema.fields) + if field.capabilities.searchable + ), + key=lambda entry: (entry[0] is None, entry[0] or 0, entry[1]), + ) + filterable = ["id"] + [ + field.name for field in self.schema.fields if field.capabilities.filterable + ] + sortable = [ + field.name for field in self.schema.fields if field.capabilities.sortable + ] + return { + "searchableAttributes": [entry[2] for entry in searchable], + "filterableAttributes": list(dict.fromkeys(filterable)), + "sortableAttributes": sortable, + "rankingRules": list(MEILISEARCH_RANKING_RULES), + } + + def reconcile(self) -> ReconcileResult: + """Create the index when missing and apply settings that drifted.""" + changed = False + live_index = self._index(self.index) + if live_index is None: + self._create_index(self.index) + changed = True + else: + self._require_primary_key(self.index, live_index) + live = self._settings(self.index) + desired = self.settings() + differences = { + name: value for name, value in desired.items() if live.get(name) != value + } + if differences: + self._update_settings(self.index, differences) + changed = True + return ReconcileResult(index=self.index, version=self.schema.version, changed=changed) + + def begin_rebuild(self, target: RebuildTarget) -> None: + """Remove leftover targets and create an empty target index.""" + self._remove_leftovers(target) + self._create_index(target.name) + + def commit_rebuild(self, target: RebuildTarget) -> None: + """Swap the target into the live name and delete the old documents.""" + if self._index(self.index) is None: + self._create_index(self.index) + self._swap(self.index, target.name) + self._delete_index(target.name) + + def abort_rebuild(self, target: RebuildTarget) -> None: + """Delete the target; a target that is already gone is not an error.""" + self._delete_index(target.name, missing_ok=True) + + def upsert(self, documents: DocumentBatch, target: RebuildTarget | None = None) -> WriteReceipt: + """Submit the batch to the live index or to a rebuild target.""" + uid = self._uid(target) + payload = [_jsonable(document) for document in documents] + response = self._transport.request( + "POST", + f"/indexes/{_quote(uid)}/documents", + body=payload, + ) + return _receipt(response) + + def delete( + self, + primary_keys: Sequence[PrimaryKey] | None = None, + *, + filter: FilterExpression | None = None, # pylint: disable=redefined-builtin + target: RebuildTarget | None = None, + ) -> WriteReceipt: + """Delete by primary key or by the rendered filter expression.""" + uid = self._uid(target) + path = f"/indexes/{_quote(uid)}/documents" + if primary_keys is not None: + response = self._transport.request( + "POST", + f"{path}/delete-batch", + body=list(primary_keys), + ) + elif filter is not None: + response = self._transport.request( + "POST", + f"{path}/delete", + body={"filter": render_filter(filter)}, + ) + else: + raise ValueError("delete requires primary_keys or filter") + return _receipt(response) + + def check_write(self, receipt: WriteReceipt) -> WriteReceipt: + """Poll the task once; a failed or canceled task raises ``WriteFailed``.""" + if receipt.complete or receipt.task_id is None: + return receipt + task = self._transport.request("GET", f"/tasks/{receipt.task_id}") + return _poll_receipt(receipt, task) + + def search(self, query: Any) -> SearchResult: + """Run one search once the query model exists (FAL-4406).""" + raise NotImplementedError("Meilisearch search lands with the query API") + + def mint_credential( + self, + scope: CredentialScope, + expires_in: timedelta, + ) -> SearchCredential: + """ + Mint a tenant token for the live index. + + ADR 0002: the parent key is ``search_api_key`` when set, otherwise the + write ``api_key``; either must be listed by the engine and allow + ``search``. The master key is not listed and cannot sign a token. The + token embeds the scope's filters for the live index and expires after + ``expires_in``. + """ + parent_key = self.backend.search_api_key or self.backend.api_key + key_uid = self._tenant_key(parent_key) + search_rules: dict[str, Any] = {self.index: {}} + if scope.filters: + search_rules[self.index]["filter"] = render_filter(scope.filters) + token = _tenant_token(key_uid, parent_key, search_rules, _now() + expires_in) + return SearchCredential( + url=self.backend.public_url or self.backend.url, + index_name=self.index, + api_key=token, + ) + + def _uid(self, target: RebuildTarget | None) -> str: + """Return the index a write goes to.""" + return target.name if target is not None else self.index + + def _index(self, uid: str) -> Mapping[str, Any] | None: + """Return the index description, or ``None`` when it does not exist.""" + try: + index = self._transport.request("GET", f"/indexes/{_quote(uid)}") + except TransportError as error: + if error.not_found: + return None + raise + if not isinstance(index, Mapping): + raise AdapterError("Meilisearch returned an invalid index description") + return index + + def _require_primary_key(self, uid: str, index: Mapping[str, Any]) -> None: + """Reject an existing index whose primary key is not the declared ``id``.""" + primary_key = index.get("primaryKey") + if primary_key is not None and primary_key != "id": + raise AdapterError( + f"index {uid!r} uses primary key {primary_key!r}, expected 'id'" + ) + + def _create_index(self, uid: str) -> None: + """Create the index with the primary key and apply the settings.""" + response = self._transport.request( + "POST", + "/indexes", + body={"uid": uid, "primaryKey": "id"}, + ) + self._wait(response) + self._update_settings(uid, self.settings()) + + def _settings(self, uid: str) -> Mapping[str, Any]: + """Return the live settings of an index.""" + settings = self._transport.request("GET", f"/indexes/{_quote(uid)}/settings") + if not isinstance(settings, Mapping): + raise AdapterError("Meilisearch returned invalid index settings") + return settings + + def _update_settings(self, uid: str, settings: Mapping[str, Any]) -> None: + """Patch the given settings and wait for the task.""" + response = self._transport.request( + "PATCH", + f"/indexes/{_quote(uid)}/settings", + body=dict(settings), + ) + self._wait(response) + + def _swap(self, first: str, second: str) -> None: + """Swap two indexes and wait for the task.""" + response = self._transport.request( + "POST", + "/swap-indexes", + body=[{"indexes": [first, second]}], + ) + self._wait(response) + + def _delete_index(self, uid: str, *, missing_ok: bool = False) -> None: + """Delete an index and wait for the task.""" + try: + response = self._transport.request("DELETE", f"/indexes/{_quote(uid)}") + except TransportError as error: + if missing_ok and error.not_found: + return + raise + self._wait(response) + + def _remove_leftovers(self, target: RebuildTarget) -> None: + """Delete targets of this index and version other than ``target``.""" + prefix = f"{target.index}_v{target.version}_" + for name in self._index_names(): + if name.startswith(prefix) and name != target.name: + self._delete_index(name) + + def _index_names(self) -> list[str]: + """List every index uid, one page at a time.""" + names: list[str] = [] + offset = 0 + while True: + page = self._transport.request( + "GET", + f"/indexes?offset={offset}&limit={PAGE_SIZE}", + ) + results = page.get("results") if isinstance(page, Mapping) else None + if not isinstance(results, list): + raise AdapterError("Meilisearch returned an invalid index list") + names.extend( + entry["uid"] + for entry in results + if isinstance(entry, Mapping) and isinstance(entry.get("uid"), str) + ) + if len(results) < PAGE_SIZE: + return names + offset += len(results) + + def _tenant_key(self, key: str) -> str: + """Return the uid of the key that signs tenant tokens.""" + page = self._transport.request("GET", "/keys?limit=1000") + results = page.get("results") if isinstance(page, Mapping) else None + if not isinstance(results, list): + raise AdapterError("Meilisearch returned an invalid key list") + for entry in results: + if not isinstance(entry, Mapping) or entry.get("key") != key: + continue + uid = entry.get("uid") + if not isinstance(uid, str) or not uid: + raise AdapterError("Meilisearch returned an invalid key uid") + actions = entry.get("actions") + if not isinstance(actions, list) or ("*" not in actions and "search" not in actions): + raise AdapterError("the tenant token key must allow search") + return uid + raise AdapterError( + "Meilisearch did not list the tenant token key; use a listed API key " + "or configure search_api_key" + ) + + def _wait(self, response: object) -> None: + """Wait for a lifecycle task to succeed.""" + task_id = _task_id(response) + deadline = time.monotonic() + TASK_TIMEOUT + interval = TASK_POLL_INTERVAL + while True: + task = self._transport.request("GET", f"/tasks/{task_id}") + status = task.get("status") if isinstance(task, Mapping) else None + if status == "succeeded": + return + if status in ("failed", "canceled"): + raise AdapterError( + f"Meilisearch task {task_id} {status} ({_task_error(task)})" + ) + if time.monotonic() > deadline: + raise AdapterError( + f"Meilisearch task {task_id} did not finish within {TASK_TIMEOUT:g}s" + ) + time.sleep(interval) + interval = min(interval * 2, MAX_POLL_INTERVAL) + + +def render_filter(expression: FilterExpression) -> str: + """Render the abstract filter expression in Meilisearch syntax.""" + groups = [] + for group in expression: + terms = [ + f"{term.field} IN [{', '.join(_literal(value) for value in term.values)}]" + for term in group.terms + ] + groups.append("(" + " OR ".join(terms) + ")") + return " AND ".join(groups) + + +def register() -> None: + """Make the Meilisearch adapter the factory for its engine.""" + register_adapter("meilisearch", MeilisearchAdapter, replace=True) + + +def _quote(uid: str) -> str: + """Quote an index uid for a URL path.""" + return quote(uid, safe="") + + +def _receipt(response: object) -> WriteReceipt: + """Build a receipt from a write acknowledgment.""" + task_id = _task_id(response) + return WriteReceipt(task_id=task_id) + + +def _task_id(response: object) -> int: + """Return the task id of an asynchronous acknowledgment.""" + task_id = response.get("taskUid") if isinstance(response, Mapping) else None + if isinstance(task_id, bool) or not isinstance(task_id, int): + raise AdapterError("Meilisearch did not acknowledge the request with a task") + return task_id + + +def _task_error(task: object) -> str: + """Describe a failed task without including the response body.""" + error = task.get("error") if isinstance(task, Mapping) else None + code = error.get("code") if isinstance(error, Mapping) else None + return code if isinstance(code, str) and code else "unknown error" + + +def _poll_receipt(receipt: WriteReceipt, task: object) -> WriteReceipt: + """Map one task status to a receipt, raising when the write failed.""" + status = task.get("status") if isinstance(task, Mapping) else None + if status == "succeeded": + return WriteReceipt(task_id=receipt.task_id, complete=True) + if status in ("failed", "canceled"): + raise WriteFailed( + f"Meilisearch task {receipt.task_id} {status} ({_task_error(task)})" + ) + return WriteReceipt(task_id=receipt.task_id, complete=False) + + +def _literal(value: FilterValue) -> str: + """Render one filter value in Meilisearch syntax.""" + if isinstance(value, datetime): + return str(int(value.timestamp())) + return json.dumps(value) + + +def _jsonable(value: Any) -> Any: + """Convert datetimes to POSIX seconds so the document is JSON-safe.""" + if isinstance(value, datetime): + return int(value.timestamp()) + if isinstance(value, Mapping): + return {key: _jsonable(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_jsonable(item) for item in value] + return value + + +def _now() -> datetime: + """Return the current time in UTC.""" + return datetime.now(timezone.utc) + + +def _tenant_token( + api_key_uid: str, + api_key: str, + search_rules: Mapping[str, Any], + expires_at: datetime, +) -> str: + """Sign a Meilisearch tenant token with HMAC-SHA256.""" + header = {"typ": "JWT", "alg": "HS256"} + payload = { + "apiKeyUid": api_key_uid, + "searchRules": search_rules, + "exp": int(expires_at.timestamp()), + } + header_part = _base64url(json.dumps(header, separators=(",", ":")).encode()) + payload_part = _base64url(json.dumps(payload, separators=(",", ":")).encode()) + signing_input = f"{header_part}.{payload_part}".encode() + signature = hmac.new(api_key.encode(), signing_input, hashlib.sha256).digest() + return f"{header_part}.{payload_part}.{_base64url(signature)}" + + +def _base64url(data: bytes) -> str: + """Encode bytes as unpadded base64url.""" + return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=") diff --git a/src/openedx_search/schema.py b/src/openedx_search/schema.py index b4af605..609283b 100644 --- a/src/openedx_search/schema.py +++ b/src/openedx_search/schema.py @@ -64,6 +64,10 @@ def validate_document_id(value: object) -> str: """Return ``value`` when it is an engine-safe id, or raise ``ValueError``.""" if not isinstance(value, str) or not DOCUMENT_ID_PATTERN.match(value): raise ValueError(f"invalid document id {value!r}") + if len(value) > MAX_DOCUMENT_ID_BYTES: + raise ValueError( + f"document id is {len(value)} bytes; maximum is {MAX_DOCUMENT_ID_BYTES}" + ) return value diff --git a/src/openedx_search/transport.py b/src/openedx_search/transport.py new file mode 100644 index 0000000..3efbe70 --- /dev/null +++ b/src/openedx_search/transport.py @@ -0,0 +1,125 @@ +""" +Minimal HTTP transport shared by the engine adapters. + +No engine client library is a dependency: the Open edX platform pins its own +requirements, so a client pinned here would drift or conflict. The transport is +deliberately small. It follows no redirects, because an ``Authorization`` header +must not reach another origin; it bounds the response size; and it never puts a +credential or a response body into an exception, where it would reach a log. +""" + +from __future__ import annotations + +import json +from collections.abc import Mapping, Sequence +from urllib.error import HTTPError, URLError +from urllib.parse import urlsplit +from urllib.request import HTTPRedirectHandler, Request, build_opener + +from .adapters import AdapterError + +__all__ = ["HTTPTransport", "TransportError"] + +DEFAULT_TIMEOUT = 10.0 +MAX_RESPONSE_BYTES = 16 * 1024 * 1024 + + +class TransportError(AdapterError): + """An engine request failed before it produced a usable response.""" + + def __init__(self, message: str, *, status: int | None = None) -> None: + """Store the HTTP status, when the engine answered at all.""" + super().__init__(message) + self.status = status + + @property + def not_found(self) -> bool: + """Whether the engine reported that the resource does not exist.""" + return self.status == 404 + + @property + def retryable(self) -> bool: + """Whether the caller may retry the request unchanged.""" + return self.status is None or self.status == 429 or self.status >= 500 + + +class _NoRedirect(HTTPRedirectHandler): + """Refuse redirects so an authorization header cannot be forwarded.""" + + # urllib requires the full override signature. + def redirect_request(self, req, fp, code, msg, headers, newurl): # pylint: disable=too-many-positional-arguments + """Never produce a redirected request.""" + return None + + +class HTTPTransport: + """JSON requests to one engine endpoint with fixed credentials.""" + + def __init__( + self, + base_url: str, + headers: Mapping[str, str], + *, + timeout: float = DEFAULT_TIMEOUT, + max_response_bytes: int = MAX_RESPONSE_BYTES, + ) -> None: + """Validate the endpoint and freeze the request defaults.""" + parts = urlsplit(base_url) + if parts.scheme not in ("http", "https") or not parts.netloc or parts.username: + raise ValueError("engine URL must be an http(s) URL without credentials") + if parts.query or parts.fragment: + raise ValueError("engine URL must not carry a query or fragment") + if timeout <= 0: + raise ValueError("timeout must be positive") + if isinstance(max_response_bytes, bool) or not isinstance(max_response_bytes, int): + raise ValueError("max_response_bytes must be a positive integer") + if max_response_bytes < 1: + raise ValueError("max_response_bytes must be a positive integer") + self.base_url = base_url.rstrip("/") + self.headers = dict(headers) + self.timeout = timeout + self.max_response_bytes = max_response_bytes + self._opener = build_opener(_NoRedirect()) + + def request(self, method: str, path: str, body: object = None) -> object: + """Send one JSON request and return the decoded response, or ``None``.""" + data = None if body is None else json.dumps(body).encode("utf-8") + content = self._send(method, path, data, "application/json") + if not content: + return None + try: + return json.loads(content.decode("utf-8")) + except ValueError: + raise TransportError("engine returned an invalid JSON response") from None + + def request_lines(self, method: str, path: str, items: Sequence[object]) -> list[object]: + """ + Send ``items`` as JSON Lines and decode a JSON Lines response. + + Typesense's import endpoint takes one document per line and answers with + one result per line, so neither side is a single JSON value. + """ + data = "\n".join(json.dumps(item) for item in items).encode("utf-8") + content = self._send(method, path, data, "text/plain") + try: + return [json.loads(line) for line in content.decode("utf-8").splitlines() if line.strip()] + except ValueError: + raise TransportError("engine returned an invalid JSON Lines response") from None + + def _send(self, method: str, path: str, data: bytes | None, content_type: str) -> bytes: + """Send one request and return the raw response body.""" + headers = {"Accept": "application/json", **self.headers} + if data is not None: + headers["Content-Type"] = content_type + request = Request(self.base_url + path, data=data, headers=headers, method=method) + try: + with self._opener.open(request, timeout=self.timeout) as response: + content = response.read(self.max_response_bytes + 1) + except HTTPError as error: + error.close() + raise TransportError(f"engine returned HTTP {error.code}", status=error.code) from None + except (URLError, TimeoutError, OSError): + raise TransportError("engine request failed") from None + if len(content) > self.max_response_bytes: + raise TransportError("engine response exceeds the size limit") + return content diff --git a/src/openedx_search/typesense.py b/src/openedx_search/typesense.py new file mode 100644 index 0000000..8656e3a --- /dev/null +++ b/src/openedx_search/typesense.py @@ -0,0 +1,759 @@ +r""" +Typesense implementation of the adapter contract. + +The logical index is a Typesense alias. Each physical collection is named like +a rebuild target, ``_v_``, so the first collection +``reconcile`` creates and every later rebuild share one naming scheme and one +leftover cleanup. A rebuild creates a new collection and repoints the alias; +collections cannot be renamed, which is why Typesense needs the alias at all. + +Typesense writes are synchronous. The import endpoint answers only after every +document has been applied or rejected, so writes return a complete receipt and +``check_write`` makes no request. The import answers HTTP 200 even when it +rejects documents, so the adapter reads every result line. + +Rendering rules that are not visible in the schema, each verified against +Typesense 30.2: + +* String filters are not exact. ``:=`` compares tokenized values, so case, + punctuation and accents are ignored (``org:=[`ab`]`` matches ``a-b``, ``AB`` + and ``a_b``). Every filterable string field therefore gets a hidden + ``__exact`` companion holding the SHA-256 of each value, and filters + on that field are rendered against the digests. ``id`` is compared exactly + and is filtered directly. +* Scoped search keys cannot name a collection, and one ``search_api_key`` + serves every use case on a backend. Every document carries a hidden + ``__index`` digest of its logical index, and every minted key filters on it, + so a key minted for one index finds nothing in another. +* ``store: false`` hides a top-level field from results but not a nested one, + so minted keys also embed ``exclude_fields`` for the companions. +* An indexed child of an unindexed object is silently not indexed, so an + object is indexed whenever any of its descendants is. +* ``query_by`` on an object fails when any declared child is unindexed, so + every descendant of a searchable object is indexed. That also matches + Meilisearch, where a searchable object searches all of its leaves. +* An indexed object indexes children the schema does not name. Typesense adds + each one to the collection's fields as it first sees it. Only + ``additional_properties`` objects can carry undeclared keys, so they get a + ``\..*`` string field after the declared fields (Typesense takes the + first matching declaration), and ``reconcile`` ignores the fields it adds. +* ``query_by_weights`` are ranked into 16 levels, so a 17th searchable field + would tie with another and lose its declared order. +* ``datetime`` is ``int64``. Typesense indexes ``float`` at single precision, + where two timestamps a second apart compare equal, so float POSIX seconds + are truncated to whole seconds, as ``int(datetime.timestamp())`` does. +* ``enable_nested_fields`` cannot be changed on an existing collection, and a + ``PATCH`` that changes an object and its child together is rejected, so + ``reconcile`` sends one change per request. +""" + +from __future__ import annotations + +import base64 +import hashlib +import hmac +import json +import logging +import re +import uuid +from collections.abc import Mapping, Sequence +from datetime import datetime, timedelta, timezone +from typing import Any +from urllib.parse import quote, urlencode + +from .adapters import ( + Adapter, + AdapterError, + CredentialScope, + DocumentBatch, + FilterExpression, + FilterTerm, + FilterValue, + PrimaryKey, + RebuildTarget, + ReconcileResult, + SearchCredential, + SearchResult, + UnsupportedSchema, + WriteFailed, + WriteReceipt, + register_adapter, +) +from .config import BackendConfig +from .registry import UseCaseRegistration +from .schema import Field, FieldType, Searchable +from .transport import HTTPTransport, TransportError + +__all__ = [ + "EXACT_SUFFIX", + "INDEX_FIELD", + "MAX_SEARCHABLE_FIELDS", + "TypesenseAdapter", + "register", +] + +log = logging.getLogger(__name__) + +EXACT_SUFFIX = "__exact" +INDEX_FIELD = "__index" + +# Typesense ranks query_by_weights into 16 levels; more fields would tie. +MAX_SEARCHABLE_FIELDS = 16 +_TOP_WEIGHT = 127 + +# Primary keys go into the DELETE query string. 200 ids at the 468-byte limit +# stay near 100 KB; Typesense refused a 454 KB query. +DELETE_BATCH_SIZE = 200 + +_TYPES = { + FieldType.STRING: "string", + FieldType.INT32: "int32", + FieldType.INT64: "int64", + FieldType.FLOAT: "float", + FieldType.BOOL: "bool", + FieldType.DATETIME: "int64", + FieldType.OBJECT: "object", +} + +# The field attributes the adapter renders and compares during reconcile. The +# engine reports many more (locale, stem, infix, ...), all left at defaults. +_FIELD_ATTRIBUTES = ("type", "index", "optional", "facet", "sort", "store") + + +class TypesenseAdapter(Adapter): + """The adapter for one Typesense deployment.""" + + def __init__( + self, + registration: UseCaseRegistration, + backend: BackendConfig, + *, + transport: HTTPTransport | None = None, + ) -> None: + """Build the transport unless the caller supplies one for testing.""" + super().__init__(registration, backend) + self._transport = transport or HTTPTransport( + backend.url, + {"X-TYPESENSE-API-KEY": backend.api_key}, + ) + + def validate_schema(self) -> None: + """Reject what Typesense cannot rank or what collides with hidden fields.""" + problems = [] + searchable = len(self._searchable_fields()) + if searchable > MAX_SEARCHABLE_FIELDS: + problems.append( + f"{searchable} searchable fields (Typesense ranks at most {MAX_SEARCHABLE_FIELDS})" + ) + reserved = sorted( + field.name + for field in self.schema.fields + if field.name == INDEX_FIELD or field.name.endswith(EXACT_SUFFIX) + ) + if reserved: + problems.append(f"reserved field names {', '.join(reserved)}") + if problems: + raise UnsupportedSchema(f"typesense cannot represent: {'; '.join(problems)}") + + def fields(self) -> list[dict[str, Any]]: + """ + Render the declared schema as Typesense collection fields. + + ``id`` is omitted: Typesense reserves it as the implicit primary key. + Each filterable string field is followed by its hidden digest + companion. Free-form object keys follow every declared field, so a + declared child of the same object takes precedence over the pattern. + Hidden fields are optional so ``reconcile`` can add them to a + collection that already holds documents. + """ + indexed = self._indexed_fields() + exact = self._exact_fields() + rendered = [] + patterns = [] + for field in self.schema.fields: + if field.name == "id": + continue + field_type = _TYPES[FieldType(field.type)] + ("[]" if field.array else "") + rendered.append( + _field( + field.name, + field_type, + index=field.name in indexed, + optional=not field.required, + facet=field.capabilities.facetable, + sort=field.capabilities.sortable, + ) + ) + if field.name in exact: + rendered.append(_field(field.name + EXACT_SUFFIX, field_type, store=False)) + if field.additional_properties: + patterns.append( + _field( + re.escape(field.name) + r"\..*", + "string[]" if self._in_object_array(field) else "string", + index=field.name in indexed, + ) + ) + return rendered + [_field(INDEX_FIELD, "string", store=False)] + patterns + + def collection_schema(self, name: str) -> dict[str, Any]: + """Render the full collection definition for a physical collection.""" + return { + "name": name, + "enable_nested_fields": self._nested, + "fields": self.fields(), + } + + def search_parameters(self) -> dict[str, str]: + """ + Render the searchable fields as ``query_by`` and ``query_by_weights``. + + Fields sort by ``Searchable.order``, then declaration order, with + unordered fields last, which is the order Meilisearch ranks its + ``searchableAttributes`` in. Each later field weighs one less. + """ + names = self._searchable_fields() + if not names: + return {} + weights = range(_TOP_WEIGHT, _TOP_WEIGHT - len(names), -1) + return { + "query_by": ",".join(names), + "query_by_weights": ",".join(str(weight) for weight in weights), + } + + def render_filter(self, expression: FilterExpression) -> str: + """ + Render the abstract filter expression in Typesense ``filter_by`` syntax. + + Terms are ORed inside a group and groups are ANDed. Only ``id`` and + declared filterable fields can be filtered; string fields are matched + on their digest companions. + """ + groups = [] + for group in expression: + terms = [self._render_term(term) for term in group.terms] + groups.append("(" + " || ".join(terms) + ")") + return " && ".join(groups) + + def reconcile(self) -> ReconcileResult: + """ + Create the collection and alias when missing and apply drifted fields. + + A changed field is dropped and re-added, which Typesense applies + synchronously by reindexing that field from the stored documents. A + field the schema no longer declares is dropped. A live collection of + another schema version is left alone: ADR 0002 keeps readers on the old + index until the migration's rebuild commits. + """ + live = self._live_collection() + result = ReconcileResult(index=self.index, version=self.schema.version, changed=False) + if live is None: + name = RebuildTarget(self.index, self.schema.version, uuid.uuid4().hex).name + self._create_collection(name) + self._point_alias(name) + return replace_changed(result) + + live_version = self._version_of(live) + if live_version != self.schema.version: + log.warning( + "Index %s serves schema version %s from %s; version %s applies when its rebuild commits", + self.index, + live_version, + live, + self.schema.version, + ) + return result + + collection = self._collection(live) + if collection is None: + raise AdapterError(f"alias {self.index!r} points at missing collection {live!r}") + if bool(collection.get("enable_nested_fields")) != self._nested: + raise AdapterError( + f"collection {live!r} cannot change enable_nested_fields; rebuild the index" + ) + changes = self._field_changes(collection.get("fields")) + for change in changes: + self._transport.request("PATCH", f"/collections/{_quote(live)}", body={"fields": change}) + added_hidden = sorted( + field["name"] + for change in changes + for field in change + if not field.get("drop") and field.get("store") is False + ) + if added_hidden and collection.get("num_documents"): + log.warning( + "Index %s gained %s; documents written before now lack them until a rebuild", + self.index, + ", ".join(added_hidden), + ) + return replace_changed(result) if changes else result + + def begin_rebuild(self, target: RebuildTarget) -> None: + """ + Remove leftover targets and create an empty target collection. + + A collection any alias points at is never a leftover. Another index can + share the prefix (``x`` and ``x_v1_y``), and its live collection must + survive this index's cleanup. + """ + protected = self._alias_targets() + prefix = f"{target.index}_v{target.version}_" + for name in self._collection_names(): + if name.startswith(prefix) and name != target.name and name not in protected: + self._delete_collection(name, missing_ok=True) + self._create_collection(target.name) + + def commit_rebuild(self, target: RebuildTarget) -> None: + """ + Point the alias at the target and delete the collection it replaced. + + Typesense accepts an alias to a collection that does not exist, so the + target is checked first: a stale rebuild whose target was cleaned up by + a newer one must not repoint the alias and delete the live collection. + """ + if self._collection(target.name) is None: + raise AdapterError(f"rebuild target {target.name!r} does not exist") + previous = self._live_collection() + self._point_alias(target.name) + if previous is not None and previous != target.name: + self._delete_collection(previous, missing_ok=True) + + def abort_rebuild(self, target: RebuildTarget) -> None: + """ + Delete the target unless the alias already points at it. + + A commit that repointed the alias and then failed to delete the old + collection leaves the target live; deleting it would empty the index. + """ + if self._live_collection() == target.name: + return + self._delete_collection(target.name, missing_ok=True) + + def upsert(self, documents: DocumentBatch, target: RebuildTarget | None = None) -> WriteReceipt: + """Import the batch, replacing whole documents, and check every result.""" + results = self._transport.request_lines( + "POST", + f"/collections/{_quote(self._name(target))}/documents/import?action=upsert", + [self._serialize(document) for document in documents], + ) + _check_import(results, len(documents)) + return WriteReceipt(complete=True) + + def delete( + self, + primary_keys: Sequence[PrimaryKey] | None = None, + *, + filter: FilterExpression | None = None, # pylint: disable=redefined-builtin + target: RebuildTarget | None = None, + ) -> WriteReceipt: + """Delete by primary key, in bounded batches, or by the rendered filter expression.""" + if primary_keys is not None: + keys = tuple(primary_keys) + filters = [ + self._render_term(FilterTerm("id", keys[start:start + DELETE_BATCH_SIZE])) + for start in range(0, len(keys), DELETE_BATCH_SIZE) + ] + elif filter is not None: + filters = [self.render_filter(filter)] + else: + raise ValueError("delete requires primary_keys or filter") + path = f"/collections/{_quote(self._name(target))}/documents?" + for rendered in filters: + response = self._transport.request("DELETE", path + urlencode({"filter_by": rendered})) + deleted = response.get("num_deleted") if isinstance(response, Mapping) else None + if isinstance(deleted, bool) or not isinstance(deleted, int): + raise AdapterError("Typesense returned an invalid delete response") + return WriteReceipt(complete=True) + + def check_write(self, receipt: WriteReceipt) -> WriteReceipt: + """Return the receipt; Typesense writes are complete when they return.""" + if not receipt.complete: + raise AdapterError("Typesense writes complete synchronously; this receipt is not from Typesense") + return receipt + + def search(self, query: Any) -> SearchResult: + """Run one search once the query model exists (FAL-4406).""" + raise NotImplementedError("Typesense search lands with the query API") + + def mint_credential( + self, + scope: CredentialScope, + expires_in: timedelta, + ) -> SearchCredential: + """ + Derive a scoped search key for the live alias. + + ADR 0002: the parent is ``search_api_key``, which must allow only + ``documents:search``; Typesense refuses a scoped key derived from any + other key. The embedded parameters cannot be overridden by the browser: + the index tag and the scope's filters are ANDed with any filter it + sends, ``query_by`` and its weights are fixed, and the digest + companions stay excluded. ``sort_by`` stays a per-query choice and is + not embedded. + """ + parent_key = self.backend.search_api_key + if parent_key is None: + raise AdapterError("Typesense needs search_api_key to mint search credentials") + filter_by = f"{INDEX_FIELD}:=[`{_digest(self.index)}`]" + if scope.filters: + filter_by = f"{filter_by} && {self.render_filter(scope.filters)}" + parameters: dict[str, Any] = { + "expires_at": int((_now() + expires_in).timestamp()), + **self.search_parameters(), + "filter_by": filter_by, + } + exact = sorted(self._exact_fields()) + if exact: + parameters["exclude_fields"] = ",".join(name + EXACT_SUFFIX for name in exact) + return SearchCredential( + url=self.backend.public_url or self.backend.url, + index_name=self.index, + api_key=_scoped_key(parent_key, parameters), + ) + + @property + def _nested(self) -> bool: + """Whether the schema declares any object field.""" + return any(field.type is FieldType.OBJECT for field in self.schema.fields) + + def _exact_fields(self) -> frozenset[str]: + """Return the filterable string fields that get digest companions.""" + return frozenset( + field.name + for field in self.schema.fields + if field.type is FieldType.STRING and field.capabilities.filterable and field.name != "id" + ) + + def _render_term(self, term: FilterTerm) -> str: + """Render one term on ``id``, a digest companion or a plain field.""" + if term.field == "id": + return f"id:=[{','.join(_literal(value) for value in term.values)}]" + try: + field = self.schema.field(term.field) + except KeyError: + raise AdapterError(f"field {term.field!r} is not declared") from None + if not field.capabilities.filterable: + raise AdapterError(f"field {term.field!r} is not filterable") + if term.field not in self._exact_fields(): + return f"{term.field}:=[{','.join(_literal(value) for value in term.values)}]" + digests = [] + for value in term.values: + if not isinstance(value, str): + raise AdapterError(f"field {term.field!r} takes string filter values") + digests.append(_literal(_digest(value))) + return f"{term.field}{EXACT_SUFFIX}:=[{','.join(digests)}]" + + def _searchable_fields(self) -> list[str]: + """Return the searchable field names in ranking order.""" + ranked = sorted( + ( + ( + field.capabilities.searchable.order + if isinstance(field.capabilities.searchable, Searchable) + else None, + position, + field.name, + ) + for position, field in enumerate(self.schema.fields) + if field.capabilities.searchable + ), + key=lambda entry: (entry[0] is None, entry[0] or 0, entry[1]), + ) + return [entry[2] for entry in ranked] + + def _indexed_fields(self) -> set[str]: + """ + Return the names of the fields Typesense must index. + + A field is indexed when it has a capability, when an ancestor is + searchable, or when a descendant is indexed. + """ + names = [field.name for field in self.schema.fields] + indexed = { + field.name + for field in self.schema.fields + if field.capabilities.searchable + or field.capabilities.filterable + or field.capabilities.sortable + } + searchable_objects = [ + field.name + for field in self.schema.fields + if field.type is FieldType.OBJECT and field.capabilities.searchable + ] + indexed.update( + name + for name in names + if any(name.startswith(parent + ".") for parent in searchable_objects) + ) + for name in list(indexed): + while "." in name: + name = name.rsplit(".", 1)[0] + indexed.add(name) + return indexed + + def _in_object_array(self, field: Field) -> bool: + """Whether the field or one of its ancestors is an object array.""" + name = field.name + while True: + if self.schema.field(name).array: + return True + if "." not in name: + return False + name = name.rsplit(".", 1)[0] + + def _field_changes(self, live_fields: object) -> list[list[dict[str, Any]]]: + """ + Return the PATCH bodies that bring the live fields to the schema. + + Each dropped or changed field is its own request, parents before + children, because Typesense rejects one request that changes an object + and its child together. New fields are added in one request. + """ + if not isinstance(live_fields, list): + raise AdapterError("Typesense returned invalid collection fields") + desired = {field["name"]: field for field in self.fields()} + free_form = tuple( + field.name + "." for field in self.schema.fields if field.additional_properties + ) + replaced: list[tuple[str, list[dict[str, Any]]]] = [] + seen = set() + for live in live_fields: + name = live.get("name") if isinstance(live, Mapping) else None + if not isinstance(name, str): + raise AdapterError("Typesense returned an invalid collection field") + seen.add(name) + wanted = desired.get(name) + if wanted is None: + # Typesense adds a field for each free-form key it indexes. + if not name.startswith(free_form): + replaced.append((name, [{"name": name, "drop": True}])) + elif {key: live.get(key) for key in _FIELD_ATTRIBUTES} != { + key: wanted[key] for key in _FIELD_ATTRIBUTES + }: + replaced.append((name, [{"name": name, "drop": True}, wanted])) + changes = [change for _, change in sorted(replaced, key=lambda entry: entry[0].count("."))] + added = [field for name, field in desired.items() if name not in seen] + if added: + changes.append(added) + return changes + + def _version_of(self, collection: str) -> int: + """Return the schema version in a collection name this adapter created.""" + match = re.match(rf"{re.escape(self.index)}_v(\d+)_[A-Za-z0-9_-]+\Z", collection) + if match is None: + raise AdapterError( + f"alias {self.index!r} points at {collection!r}, which openedx-search did not create" + ) + return int(match.group(1)) + + def _serialize(self, document: Mapping[str, Any]) -> dict[str, Any]: + """Add the hidden fields and render datetime fields as whole POSIX seconds.""" + datetimes = frozenset( + field.name for field in self.schema.fields if field.type is FieldType.DATETIME + ) + prepared = _prepare(document, "", datetimes, self._exact_fields()) + prepared[INDEX_FIELD] = _digest(self.index) + return prepared + + def _name(self, target: RebuildTarget | None) -> str: + """Return the collection or alias a write goes to.""" + return target.name if target is not None else self.index + + def _live_collection(self) -> str | None: + """ + Return the collection the alias points at, or ``None`` without an alias. + + A collection named like the index blocks the alias: Typesense refuses + an alias whose name an existing collection already uses. + """ + try: + alias = self._transport.request("GET", f"/aliases/{_quote(self.index)}") + except TransportError as error: + if not error.not_found: + raise + if self._collection(self.index) is not None: + raise AdapterError( + f"collection {self.index!r} exists without an alias; " + "it was not created by openedx-search" + ) from None + return None + name = alias.get("collection_name") if isinstance(alias, Mapping) else None + if not isinstance(name, str) or not name: + raise AdapterError("Typesense returned an invalid alias") + return name + + def _alias_targets(self) -> set[str]: + """Return the collections every alias on the server points at.""" + response = self._transport.request("GET", "/aliases") + aliases = response.get("aliases") if isinstance(response, Mapping) else None + if not isinstance(aliases, list): + raise AdapterError("Typesense returned an invalid alias list") + return { + entry["collection_name"] + for entry in aliases + if isinstance(entry, Mapping) and isinstance(entry.get("collection_name"), str) + } + + def _collection(self, name: str) -> Mapping[str, Any] | None: + """Return the collection description, or ``None`` when it does not exist.""" + try: + collection = self._transport.request("GET", f"/collections/{_quote(name)}") + except TransportError as error: + if error.not_found: + return None + raise + if not isinstance(collection, Mapping): + raise AdapterError("Typesense returned an invalid collection description") + return collection + + def _collection_names(self) -> list[str]: + """List every collection name.""" + collections = self._transport.request("GET", "/collections?exclude_fields=fields") + if not isinstance(collections, list): + raise AdapterError("Typesense returned an invalid collection list") + return [ + entry["name"] + for entry in collections + if isinstance(entry, Mapping) and isinstance(entry.get("name"), str) + ] + + def _create_collection(self, name: str) -> None: + """Create a collection from the declared schema.""" + self._transport.request("POST", "/collections", body=self.collection_schema(name)) + + def _point_alias(self, name: str) -> None: + """Create or repoint the alias for the logical index.""" + self._transport.request( + "PUT", + f"/aliases/{_quote(self.index)}", + body={"collection_name": name}, + ) + + def _delete_collection(self, name: str, *, missing_ok: bool = False) -> None: + """Delete a collection.""" + try: + self._transport.request("DELETE", f"/collections/{_quote(name)}") + except TransportError as error: + if not (missing_ok and error.not_found): + raise + + +def register() -> None: + """Make the Typesense adapter the factory for its engine.""" + register_adapter("typesense", TypesenseAdapter, replace=True) + + +def replace_changed(result: ReconcileResult) -> ReconcileResult: + """Return ``result`` marked as changed.""" + return ReconcileResult(index=result.index, version=result.version, changed=True) + + +def _field( + name: str, + field_type: str, + *, + index: bool = True, + optional: bool = True, + facet: bool = False, + sort: bool = False, + store: bool = True, +) -> dict[str, Any]: + """Build one collection field with every attribute reconcile compares.""" + return { + "name": name, + "type": field_type, + "index": index, + "optional": optional, + "facet": facet, + "sort": sort, + "store": store, + } + + +def _quote(name: str) -> str: + """Quote a collection or alias name for a URL path.""" + return quote(name, safe="") + + +def _digest(value: str) -> str: + """Return the SHA-256 hex digest that stands in for a string in a filter.""" + return hashlib.sha256(value.encode("utf-8")).hexdigest() + + +def _literal(value: FilterValue) -> str: + """ + Render one filter value in Typesense syntax. + + Strings are backtick-quoted so commas, parentheses and operators inside a + value stay literal. Typesense has no escape for a backtick itself, and one + inside a value silently matches a different value, so it is refused. + Numbers and booleans must not be quoted. + """ + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, datetime): + return str(int(value.timestamp())) + if isinstance(value, (int, float)): + return repr(value) + if "`" in value: + raise AdapterError("Typesense cannot filter on a value containing a backtick") + return f"`{value}`" + + +def _check_import(results: list[object], expected: int) -> None: + """Raise ``WriteFailed`` unless every document in the batch was imported.""" + if len(results) != expected: + raise AdapterError(f"Typesense returned {len(results)} import results for {expected} documents") + failed = [ + (position, result.get("code") if isinstance(result, Mapping) else None) + for position, result in enumerate(results) + if not (isinstance(result, Mapping) and result.get("success") is True) + ] + if failed: + # Positions and status codes only: a failed result line can echo the + # document, which must not reach a log. + details = ", ".join(f"{position} (HTTP {code})" for position, code in failed) + raise WriteFailed(f"Typesense rejected {len(failed)} of {expected} documents at positions {details}") + + +def _prepare(value: Any, path: str, datetimes: frozenset[str], exact: frozenset[str]) -> Any: + """Copy ``value`` with whole-second datetimes and a digest beside each exact field.""" + if isinstance(value, Mapping): + prepared = {} + for key, item in value.items(): + child = f"{path}.{key}" if path else key + prepared[key] = _prepare(item, child, datetimes, exact) + if child in exact: + prepared[key + EXACT_SUFFIX] = ( + [_digest(entry) for entry in item] if isinstance(item, (list, tuple)) else _digest(item) + ) + return prepared + if isinstance(value, (list, tuple)): + return [_prepare(item, path, datetimes, exact) for item in value] + if path in datetimes: + if isinstance(value, datetime): + return int(value.timestamp()) + return int(value) + return value + + +def _now() -> datetime: + """Return the current time in UTC.""" + return datetime.now(timezone.utc) + + +def _scoped_key(parent_key: str, parameters: Mapping[str, Any]) -> str: + """ + Derive a Typesense scoped search key. + + The key is ``base64(base64(HMAC-SHA256(parent, params)) + parent[:4] + params)``; + Typesense finds the parent by its four-character prefix and recomputes the + digest, so no request is needed. The parameters are serialized the way the + official client does, so the key is byte-identical to its output. + """ + embedded = json.dumps(parameters) + digest = base64.b64encode( + hmac.new(parent_key.encode(), embedded.encode(), hashlib.sha256).digest() + ).decode() + return base64.b64encode(f"{digest}{parent_key[:4]}{embedded}".encode()).decode() diff --git a/tests/conftest.py b/tests/conftest.py index 3eb5f3b..dc12c35 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,12 +2,15 @@ import pytest +from openedx_search.adapters import clear_adapter_registry from openedx_search.registry import clear_registry @pytest.fixture(autouse=True) -def isolated_registry(): - """Give every test an empty use-case registry.""" +def isolated_registries(): + """Give every test empty use-case and adapter registries.""" clear_registry() + clear_adapter_registry() yield clear_registry() + clear_adapter_registry() diff --git a/tests/fakes.py b/tests/fakes.py new file mode 100644 index 0000000..ac5a58d --- /dev/null +++ b/tests/fakes.py @@ -0,0 +1,92 @@ +"""Shared test doubles for the API and adapter tests.""" + +from __future__ import annotations + +from datetime import timedelta +from typing import Any + +from openedx_search.adapters import ( + Adapter, + CredentialScope, + DocumentBatch, + RebuildTarget, + ReconcileResult, + SearchCredential, + SearchResult, + WriteReceipt, +) +from openedx_search.registry import UseCaseRegistration +from openedx_search.schema import Field, FieldType, IndexSchema + + +class FakeAdapter(Adapter): + """An adapter that records calls instead of talking to an engine.""" + + def __init__(self, registration, backend): + """Store the registration, backend and an empty call log.""" + super().__init__(registration, backend) + self.calls: list[tuple[Any, ...]] = [] + + def validate_schema(self) -> None: + """Accept every schema.""" + + def reconcile(self) -> ReconcileResult: # pragma: no cover - not called by the API tests + """Report no change.""" + return ReconcileResult(index=self.index, version=self.schema.version) + + def begin_rebuild(self, target: RebuildTarget) -> None: # pragma: no cover - not called by the API tests + """Record the target creation.""" + self.calls.append(("begin_rebuild", target)) + + def commit_rebuild(self, target: RebuildTarget) -> None: # pragma: no cover - not called by the API tests + """Record the swap.""" + self.calls.append(("commit_rebuild", target)) + + def abort_rebuild(self, target: RebuildTarget) -> None: # pragma: no cover - not called by the API tests + """Record the abort.""" + self.calls.append(("abort_rebuild", target)) + + def upsert(self, documents: DocumentBatch, target: RebuildTarget | None = None) -> WriteReceipt: + """Record the batch.""" + self.calls.append(("upsert", tuple(documents), target)) + return WriteReceipt(complete=True) + + def delete( + self, + primary_keys=None, + *, + filter=None, # pylint: disable=redefined-builtin + target: RebuildTarget | None = None, + ) -> WriteReceipt: + """Record the delete.""" + self.calls.append(("delete", primary_keys, filter, target)) + return WriteReceipt(complete=True) + + def check_write(self, receipt: WriteReceipt) -> WriteReceipt: + """Record the poll and report completion.""" + self.calls.append(("check_write", receipt)) + return WriteReceipt(complete=True) + + def search(self, query: Any) -> SearchResult: # pragma: no cover - not called by the API tests + """Return no hits.""" + return SearchResult(documents=(), total=0) + + def mint_credential(self, scope: CredentialScope, expires_in: timedelta) -> SearchCredential: + """Record the request and return a fixed credential.""" + self.calls.append(("mint_credential", scope, expires_in)) + return SearchCredential(url="http://fake", index_name=self.index, api_key="key") + + +SIMPLE_SCHEMA = IndexSchema( + name="simple", + fields=( + Field("id", FieldType.STRING, required=True), + Field("title", FieldType.STRING, required=True), + ), +) + +SIMPLE_REGISTRATION = UseCaseRegistration( + use_case="simple", + index="simple_index", + schema=SIMPLE_SCHEMA, +) diff --git a/tests/test_adapter_registry.py b/tests/test_adapter_registry.py new file mode 100644 index 0000000..d544a73 --- /dev/null +++ b/tests/test_adapter_registry.py @@ -0,0 +1,92 @@ +"""Tests for adapter registration and resolution.""" + +import pytest +from django.test import override_settings + +from openedx_search.adapters import AdapterNotRegistered, clear_adapter_registry, get_adapter, register_adapter +from openedx_search.config import BackendConfig +from tests.fakes import SIMPLE_REGISTRATION, FakeAdapter + +FAKE_BACKENDS = { + "default": {"engine": "fake", "url": "http://fake", "api_key": "secret"}, +} + + +def test_get_adapter_builds_the_backend_adapter(): + """Resolution reads the deployment backend and instantiates its factory.""" + register_adapter("fake", FakeAdapter) + with override_settings( + OPENEDX_SEARCH_BACKENDS=FAKE_BACKENDS, + OPENEDX_SEARCH_DEFAULT_BACKEND="default", + ): + adapter = get_adapter(SIMPLE_REGISTRATION) + + assert isinstance(adapter, FakeAdapter) + assert adapter.backend.engine == "fake" + assert adapter.index == "simple_index" + + +def test_get_adapter_uses_the_use_case_override(): + """A per-use-case backend wins over the default.""" + register_adapter("fake", FakeAdapter) + with override_settings( + OPENEDX_SEARCH_BACKENDS={ + "default": {"engine": "missing", "url": "http://default", "api_key": "a"}, + "fake": {"engine": "fake", "url": "http://fake", "api_key": "b"}, + }, + OPENEDX_SEARCH_DEFAULT_BACKEND="default", + OPENEDX_SEARCH_USE_CASE_BACKENDS={"simple": "fake"}, + ): + adapter = get_adapter(SIMPLE_REGISTRATION) + + assert adapter.backend.name == "fake" + + +def test_unregistered_engine_raises(): + """A configured engine without a factory fails loudly.""" + register_adapter("other", FakeAdapter) + with override_settings( + OPENEDX_SEARCH_BACKENDS=FAKE_BACKENDS, + OPENEDX_SEARCH_DEFAULT_BACKEND="default", + ): + with pytest.raises(AdapterNotRegistered, match="fake"): + get_adapter(SIMPLE_REGISTRATION) + + +def test_duplicate_registration_raises(): + """An engine has one adapter unless replacement is explicit.""" + register_adapter("fake", FakeAdapter) + with pytest.raises(ValueError, match="already registered"): + register_adapter("fake", FakeAdapter) + + +def test_replacement_is_explicit(): + """The test helper can replace a factory on purpose.""" + register_adapter("fake", FakeAdapter) + register_adapter("fake", FakeAdapter, replace=True) + assert isinstance(get_adapter(SIMPLE_REGISTRATION, backend=_fake_backend()), FakeAdapter) + + +def test_invalid_registration_inputs_raise(): + """The engine and the factory are validated.""" + with pytest.raises(ValueError, match="non-empty"): + register_adapter("", FakeAdapter) + with pytest.raises(ValueError, match="callable"): + register_adapter("fake", "not callable") + + +def test_clear_adapter_registry(): + """Clearing removes every factory.""" + register_adapter("fake", FakeAdapter) + clear_adapter_registry() + with override_settings( + OPENEDX_SEARCH_BACKENDS=FAKE_BACKENDS, + OPENEDX_SEARCH_DEFAULT_BACKEND="default", + ): + with pytest.raises(AdapterNotRegistered): + get_adapter(SIMPLE_REGISTRATION) + + +def _fake_backend(): + """Build a backend without touching Django settings.""" + return BackendConfig(name="fake", engine="fake", url="http://fake", api_key="secret") diff --git a/tests/test_adapters.py b/tests/test_adapters.py index 97d6f97..e1b68a1 100644 --- a/tests/test_adapters.py +++ b/tests/test_adapters.py @@ -1,74 +1,26 @@ """Tests for the adapter contract types.""" -from datetime import datetime, timedelta, timezone +from datetime import datetime, timezone import pytest from openedx_search.adapters import ( - Adapter, CredentialScope, FilterGroup, FilterTerm, RebuildTarget, - ReconcileResult, SearchCredential, - SearchResult, - WriteReceipt, + normalize_filter_expression, ) from openedx_search.config import BackendConfig +from tests.fakes import FakeAdapter from tests.fixtures import STUDIO_COURSE -class _StubAdapter(Adapter): # pragma: no cover - """A minimal adapter that exercises the base class.""" - - def validate_schema(self) -> None: - """Accept every schema.""" - - def reconcile(self) -> ReconcileResult: - """Report no change.""" - return ReconcileResult(index=self.index, version=self.schema.version) - - def begin_rebuild(self, target: RebuildTarget) -> None: - """Do nothing.""" - - def commit_rebuild(self, target: RebuildTarget) -> None: - """Do nothing.""" - - def abort_rebuild(self, target: RebuildTarget) -> None: - """Do nothing.""" - - def upsert(self, documents, target: RebuildTarget | None = None) -> WriteReceipt: - """Report a complete write.""" - return WriteReceipt(complete=True) - - def delete( - self, - primary_keys=None, - *, - filter=None, # pylint: disable=redefined-builtin - target: RebuildTarget | None = None, - ) -> WriteReceipt: - """Report a complete delete.""" - return WriteReceipt(complete=True) - - def check_write(self, receipt: WriteReceipt) -> WriteReceipt: - """Return the receipt.""" - return receipt - - def search(self, query) -> SearchResult: - """Return no hits.""" - return SearchResult(documents=(), total=0) - - def mint_credential(self, scope: CredentialScope, expires_in: timedelta) -> SearchCredential: - """Return a fixed credential.""" - return SearchCredential(url="http://fake", index_name=self.index, api_key="key") - - def test_adapter_exposes_its_registration(): """The base class stores the registration and exposes index and schema.""" backend = BackendConfig(name="fake", engine="meilisearch", url="http://localhost:7700", api_key="key") - adapter = _StubAdapter(STUDIO_COURSE, backend) + adapter = FakeAdapter(STUDIO_COURSE, backend) assert adapter.index == STUDIO_COURSE.index assert adapter.schema is STUDIO_COURSE.schema @@ -148,6 +100,12 @@ def test_credential_scope_requires_filter_groups(): CredentialScope(filters=("org",)) # type: ignore[arg-type] +def test_normalize_filter_expression_rejects_a_non_sequence(): + """An integer is not a sequence of groups.""" + with pytest.raises(ValueError, match="sequence of FilterGroup"): + normalize_filter_expression(1) # type: ignore[arg-type] + + def test_rebuild_target_name_includes_a_generation(): """Two rebuilds at the same version never share a target name.""" first = RebuildTarget(index="studio_content", version=2, generation="20261104") diff --git a/tests/test_api.py b/tests/test_api.py index c598cd5..1221705 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -3,45 +3,200 @@ from datetime import timedelta import pytest +from django.test import override_settings + +from openedx_search.adapters import ( + CredentialScope, + FilterGroup, + FilterTerm, + SearchCredential, + WriteReceipt, + register_adapter, +) +from openedx_search.api import DocumentError, check_write, delete, mint_credential, upsert +from openedx_search.config import BackendConfig +from openedx_search.registry import UseCaseNotRegistered, register_use_case +from tests.fakes import SIMPLE_REGISTRATION, FakeAdapter + +# The fixture name is also the argument name pytest resolves, so every test +# that takes it shadows the fixture function. +# pylint: disable=redefined-outer-name -from openedx_search.adapters import CredentialScope -from openedx_search.api import _normalize_primary_keys, mint_credential +FAKE_BACKENDS = { + "default": {"engine": "fake", "url": "http://fake", "api_key": "secret"}, +} + + +@pytest.fixture +def fake_adapter(): + """Register the simple use case and a recording adapter for it.""" + register_use_case(SIMPLE_REGISTRATION) + adapter = FakeAdapter( + SIMPLE_REGISTRATION, + BackendConfig(name="default", engine="fake", url="http://fake", api_key="secret"), + ) + register_adapter("fake", lambda registration, backend: adapter) + with override_settings( + OPENEDX_SEARCH_BACKENDS=FAKE_BACKENDS, + OPENEDX_SEARCH_DEFAULT_BACKEND="default", + ): + yield adapter + + +def test_mint_credential_delegates(fake_adapter): + """The scope and lifetime reach the adapter and its credential is returned.""" + scope = CredentialScope(filters=(FilterGroup((FilterTerm("org", ("openedx",)),)),)) + + credential = mint_credential("simple", scope, timedelta(hours=1)) + + assert credential == SearchCredential(url="http://fake", index_name="simple_index", api_key="key") + assert fake_adapter.calls[-1] == ("mint_credential", scope, timedelta(hours=1)) + + +@pytest.mark.parametrize( + ("scope", "expires_in", "message"), + [ + ((), timedelta(hours=1), "CredentialScope"), + (CredentialScope(), 3600, "timedelta"), + (CredentialScope(), timedelta(0), "must be positive"), + ], +) +def test_mint_credential_rejects_invalid_arguments(fake_adapter, scope, expires_in, message): + """Invalid input fails before the adapter is resolved.""" + with pytest.raises(ValueError, match=message): + mint_credential("simple", scope, expires_in) + + assert fake_adapter.calls == [] + + +def test_mint_credential_unknown_use_case(): + """The registration must exist.""" + with pytest.raises(UseCaseNotRegistered): + mint_credential("missing", CredentialScope(), timedelta(hours=1)) + + +def test_upsert_validates_and_sends_the_batch(fake_adapter): + """A valid batch reaches the adapter and returns its receipt.""" + receipt = upsert("simple", [{"id": "doc-1", "title": "Hello"}]) + + assert receipt.complete + assert fake_adapter.calls == [("upsert", ({"id": "doc-1", "title": "Hello"},), None)] + + +def test_upsert_rejects_invalid_documents(fake_adapter): + """Validation happens before the adapter call.""" + with pytest.raises(DocumentError, match="required field 'title'"): + upsert("simple", [{"id": "doc-1"}]) + assert fake_adapter.calls == [] -def test_mint_credential_rejects_non_positive_expiry(): - """A credential must have a positive lifetime.""" - with pytest.raises(ValueError, match="must be positive"): - mint_credential("studio_course", CredentialScope(), timedelta(0)) +@pytest.mark.usefixtures("fake_adapter") +def test_upsert_requires_a_batch(): + """A string is not a batch, and an empty batch is rejected.""" + with pytest.raises(ValueError, match="sequence"): + upsert("simple", "not a batch") + with pytest.raises(ValueError, match="not be empty"): + upsert("simple", []) + + +@pytest.mark.usefixtures("fake_adapter") +def test_upsert_unknown_use_case(): + """The registration must exist.""" + with pytest.raises(UseCaseNotRegistered): + upsert("missing", [{"id": "doc-1", "title": "Hello"}]) + + +@pytest.mark.parametrize( + ("primary_keys", "expected"), + [ + ("doc-1", ("doc-1",)), + (["doc-1", "doc-2"], ("doc-1", "doc-2")), + (("doc-1",), ("doc-1",)), + ], +) +def test_delete_by_primary_keys(fake_adapter, primary_keys, expected): + """A key or a sequence is normalized to a tuple and reaches the adapter.""" + delete("simple", primary_keys) + + assert fake_adapter.calls[-1] == ("delete", expected, None, None) -def test_normalize_single_primary_key(): - """A string is one key, not a sequence of characters.""" - assert _normalize_primary_keys("abc") == ("abc",) +@pytest.mark.parametrize( + ("primary_keys", "message"), + [ + ([], "must not be empty"), + ("a:b", "invalid document id"), + (["valid-id", "a:b"], "invalid document id"), + ({"doc-1": "x"}, "string or a sequence"), + (1, "string or a sequence"), + (b"doc-1", "string or a sequence"), + ("a" * 469, "maximum is 468"), + ], +) +def test_delete_rejects_invalid_primary_keys(fake_adapter, primary_keys, message): + """Nothing reaches the adapter when a key is invalid.""" + with pytest.raises(ValueError, match=message): + delete("simple", primary_keys) -def test_normalize_primary_key_sequence(): - """A sequence is normalized to a tuple.""" - assert _normalize_primary_keys(["a", "b"]) == ("a", "b") + assert fake_adapter.calls == [] -def test_normalize_empty_primary_keys(): - """An empty sequence cannot become a delete.""" - with pytest.raises(ValueError, match="must not be empty"): - _normalize_primary_keys([]) +def test_delete_by_filter(fake_adapter): + """The abstract filter expression reaches the adapter unchanged.""" + expression = (FilterGroup((FilterTerm("title", ("Hello",)),)),) + delete("simple", filter=expression) -def test_normalize_missing_primary_keys(): - """None means the caller used the filter form.""" - assert _normalize_primary_keys(None) is None + assert fake_adapter.calls[-1] == ("delete", None, expression, None) -def test_normalize_rejects_invalid_document_id(): - """A colon fails the engines, so it fails before the adapter call.""" - with pytest.raises(ValueError, match="invalid document id"): - _normalize_primary_keys("block-v1:edX+DemoX+type@html+block@abc") +@pytest.mark.usefixtures("fake_adapter") +def test_delete_requires_exactly_one_form(): + """A delete has keys or a filter, never both and never neither.""" + with pytest.raises(ValueError, match="exactly one"): + delete("simple") + with pytest.raises(ValueError, match="exactly one"): + delete( + "simple", + "doc-1", + filter=(FilterGroup((FilterTerm("title", ("Hello",)),)),), + ) -def test_normalize_rejects_invalid_document_id_in_sequence(): - """Every key in a batch is validated.""" - with pytest.raises(ValueError, match="invalid document id"): - _normalize_primary_keys(["valid-id", "block-v1:edX+DemoX"]) +@pytest.mark.usefixtures("fake_adapter") +def test_delete_rejects_a_string_filter(): + """A raw engine filter is not accepted.""" + with pytest.raises(ValueError, match="not a string"): + delete("simple", filter="title = Hello") + + +@pytest.mark.usefixtures("fake_adapter") +def test_delete_rejects_an_empty_filter(): + """An empty filter would match everything.""" + with pytest.raises(ValueError, match="not be empty"): + delete("simple", filter=()) + + +def test_check_write_delegates(fake_adapter): + """One poll reaches the adapter and returns its receipt.""" + receipt = WriteReceipt(task_id=7) + + result = check_write("simple", receipt) + + assert result.complete + assert fake_adapter.calls[-1] == ("check_write", receipt) + + +@pytest.mark.usefixtures("fake_adapter") +def test_check_write_rejects_a_non_receipt(): + """The function only accepts a receipt from a write.""" + with pytest.raises(ValueError, match="WriteReceipt"): + check_write("simple", "receipt") + + +@pytest.mark.usefixtures("fake_adapter") +def test_check_write_unknown_use_case(): + """The registration must exist.""" + with pytest.raises(UseCaseNotRegistered): + check_write("missing", WriteReceipt()) diff --git a/tests/test_app.py b/tests/test_app.py index 2d84c0c..37cdf92 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -2,9 +2,15 @@ Smoke tests for the openedx_search package and its Django app. """ +import pytest from django.apps import apps +from django.test import override_settings import openedx_search +from openedx_search.adapters import get_adapter +from openedx_search.meilisearch import MeilisearchAdapter +from openedx_search.typesense import TypesenseAdapter +from tests.fixtures import STUDIO_COURSE def test_version_is_set(): @@ -16,3 +22,25 @@ def test_app_is_installed(): """The Django app loads under its expected label.""" app_config = apps.get_app_config("openedx_search") assert app_config.verbose_name == "Open edX Search" + + +@pytest.mark.parametrize( + "engine, adapter_class", + [("meilisearch", MeilisearchAdapter), ("typesense", TypesenseAdapter)], +) +def test_app_ready_registers_the_engine_adapters(engine, adapter_class): + """App initialization makes every shipped engine adapter resolvable.""" + apps.get_app_config("openedx_search").ready() + with override_settings( + OPENEDX_SEARCH_BACKENDS={ + "default": { + "engine": engine, + "url": "http://engine:7700", + "api_key": "secret", + } + }, + OPENEDX_SEARCH_DEFAULT_BACKEND="default", + ): + adapter = get_adapter(STUDIO_COURSE) + + assert isinstance(adapter, adapter_class) diff --git a/tests/test_documents.py b/tests/test_documents.py new file mode 100644 index 0000000..51af95e --- /dev/null +++ b/tests/test_documents.py @@ -0,0 +1,264 @@ +"""Tests for document validation against a schema.""" + +from datetime import datetime, timezone +from typing import Any + +import pytest + +from openedx_search.documents import DocumentError, validate_document, validate_documents +from openedx_search.schema import MAX_DOCUMENT_ID_BYTES, Field, FieldType, IndexSchema + +SCHEMA = IndexSchema( + name="documents", + fields=( + Field("id", FieldType.STRING, required=True), + Field("title", FieldType.STRING, required=True), + Field("count", FieldType.INT32), + Field("big", FieldType.INT64), + Field("rating", FieldType.FLOAT), + Field("active", FieldType.BOOL), + Field("created", FieldType.DATETIME, required=True), + Field("tags", FieldType.STRING, array=True), + Field("details", FieldType.OBJECT, required=True), + Field("details.name", FieldType.STRING, required=True), + Field("breadcrumbs", FieldType.OBJECT, array=True, required=True), + Field("breadcrumbs.label", FieldType.STRING, array=True), + Field("content", FieldType.OBJECT, additional_properties=True), + Field("content.problem_types", FieldType.STRING, array=True), + ), +) + +NESTED_ARRAY_SCHEMA = IndexSchema( + name="nested_arrays", + fields=( + Field("id", FieldType.STRING, required=True), + Field("a", FieldType.OBJECT, array=True, required=True), + Field("a.b", FieldType.OBJECT, array=True), + Field("a.b.c", FieldType.STRING, array=True), + ), +) + + +def _document(**overrides: Any) -> dict[str, Any]: + """Build a valid document, with overrides for one test.""" + document = { + "id": "doc-1", + "title": "Hello", + "count": 2, + "rating": 4.5, + "active": True, + "created": datetime(2023, 4, 5, 6, 7, 8, tzinfo=timezone.utc), + "tags": ["a", "b"], + "details": {"name": "details"}, + "breadcrumbs": [{"label": "one"}, {"label": "two"}], + "content": {"problem_types": ["multiple_choice"], "html": "text"}, + } + document.update(overrides) + return document + + +def test_valid_document_passes(): + """Every declared type, array, object and free-form value is accepted.""" + validate_document(SCHEMA, _document()) + + +def test_a_document_must_be_a_mapping(): + """A string is not a document.""" + with pytest.raises(DocumentError, match="mapping"): + validate_document(SCHEMA, "not a mapping") + + +def test_error_names_the_document_once(): + """The label is applied at the validation boundary, not at every raise site.""" + document = _document() + document.pop("title") + + with pytest.raises(DocumentError, match=r"^document 'doc-1': required field 'title' is missing$"): + validate_document(SCHEMA, document) + + +def test_error_without_an_id_uses_a_generic_label(): + """A document with no usable id is still named in the error.""" + with pytest.raises(DocumentError, match=r"^document: required field 'id' is missing$"): + validate_document(SCHEMA, {}) + + +def test_missing_required_nested_field(): + """A required leaf inside a required object is checked.""" + with pytest.raises(DocumentError, match="required field 'details.name'"): + validate_document(SCHEMA, _document(details={})) + + +def test_missing_optional_fields_pass(): + """Optional fields can be omitted.""" + document = _document() + for key in ("count", "rating", "active", "tags", "content"): + document.pop(key) + validate_document(SCHEMA, document) + + +def test_null_is_rejected(): + """Null is not a value, even for an optional field.""" + with pytest.raises(DocumentError, match="cannot be null"): + validate_document(SCHEMA, _document(count=None)) + + +def test_null_array_element_is_rejected(): + """Null inside an array is rejected by the element check.""" + with pytest.raises(DocumentError, match="field 'tags' cannot be null"): + validate_document(SCHEMA, _document(tags=["a", None])) + + +def test_unknown_field_is_rejected(): + """Undeclared fields are errors, not silently dropped.""" + with pytest.raises(DocumentError, match="unknown field 'extra'"): + validate_document(SCHEMA, _document(extra="value")) + + +def test_field_names_must_be_strings(): + """A non-string key cannot be addressed by the engines.""" + document = _document() + document[1] = "value" + + with pytest.raises(DocumentError, match="field names must be strings"): + validate_document(SCHEMA, document) + + +def test_unknown_nested_field_is_rejected(): + """Undeclared fields inside a declared object are errors.""" + with pytest.raises(DocumentError, match="unknown field 'details.extra'"): + validate_document(SCHEMA, _document(details={"name": "x", "extra": "y"})) + + +def test_dotted_document_key_is_rejected(): + """A flat key with a dot is not a nested document field.""" + with pytest.raises(DocumentError, match="unknown field 'content.problem_types'"): + validate_document( + SCHEMA, + _document(**{"content.problem_types": ["multiple_choice"]}), + ) + + +def test_wrong_scalar_type(): + """Declared types are enforced.""" + with pytest.raises(DocumentError, match="must be a string"): + validate_document(SCHEMA, _document(title=1)) + + +def test_boolean_is_not_an_integer(): + """A bool is not a valid int32.""" + with pytest.raises(DocumentError, match="must be an integer"): + validate_document(SCHEMA, _document(count=True)) + + +def test_int32_range_is_enforced(): + """An int32 is bounded on both sides.""" + validate_document(SCHEMA, _document(count=2**31 - 1)) + validate_document(SCHEMA, _document(count=-(2**31))) + + for value in (2**31, -(2**31) - 1): + with pytest.raises(DocumentError, match="between -2147483648 and 2147483647"): + validate_document(SCHEMA, _document(count=value)) + + +def test_int64_range_is_enforced(): + """An int64 is bounded on both sides.""" + validate_document(SCHEMA, _document(big=2**63 - 1)) + validate_document(SCHEMA, _document(big=-(2**63))) + + for value in (2**63, -(2**63) - 1): + with pytest.raises(DocumentError, match="between -9223372036854775808 and 9223372036854775807"): + validate_document(SCHEMA, _document(big=value)) + + +def test_float_field_rejects_a_string(): + """The float type name appears in the error.""" + with pytest.raises(DocumentError, match="field 'rating' must be a number"): + validate_document(SCHEMA, _document(rating="high")) + + +def test_bool_field_rejects_a_string(): + """The bool type name appears in the error.""" + with pytest.raises(DocumentError, match="field 'active' must be a boolean"): + validate_document(SCHEMA, _document(active="yes")) + + +def test_object_field_must_be_a_mapping(): + """A declared object is not a string or an array.""" + with pytest.raises(DocumentError, match="field 'details' must be an object"): + validate_document(SCHEMA, _document(details="not an object")) + + +def test_naive_datetime_is_rejected(): + """A naive datetime depends on the local timezone.""" + with pytest.raises(DocumentError, match="timezone-aware"): + validate_document(SCHEMA, _document(created=datetime(2023, 4, 5, 6, 7, 8))) + + +def test_numeric_datetime_is_accepted(): + """POSIX seconds remain valid, which is the stored form.""" + validate_document(SCHEMA, _document(created=1680674828.0)) + + +def test_array_field_requires_an_array(): + """A bare string is not an array of strings.""" + with pytest.raises(DocumentError, match="must be an array"): + validate_document(SCHEMA, _document(tags="a")) + + +def test_array_elements_are_typed(): + """Each element is validated.""" + with pytest.raises(DocumentError, match="must be a string"): + validate_document(SCHEMA, _document(tags=["a", 2])) + + +def test_object_array_elements_are_objects(): + """An object array holds mappings.""" + with pytest.raises(DocumentError, match="must contain objects"): + validate_document(SCHEMA, _document(breadcrumbs=["one"])) + + +def test_object_array_inside_an_object_array(): + """An object array nested in an object array is iterated.""" + validate_document(NESTED_ARRAY_SCHEMA, {"id": "x", "a": [{"b": [{"c": "v"}]}]}) + + +def test_single_object_inside_an_object_array(): + """A child object can be one object per parent element.""" + validate_document(NESTED_ARRAY_SCHEMA, {"id": "x", "a": [{"b": {"c": "v"}}]}) + + +def test_object_array_children_are_scalars_per_element(): + """The array flag on a child is implied by the parent array, not the value.""" + with pytest.raises(DocumentError, match="must be a string"): + validate_document(SCHEMA, _document(breadcrumbs=[{"label": ["one"]}])) + + +def test_free_form_values_must_be_strings(): + """Free-form object values are string-only.""" + with pytest.raises(DocumentError, match="must be a string"): + validate_document(SCHEMA, _document(content={"html": 5})) + + +def test_declared_child_of_free_form_object_is_typed(): + """A declared leaf under a free-form object is validated normally.""" + with pytest.raises(DocumentError, match="must be an array"): + validate_document(SCHEMA, _document(content={"problem_types": "multiple_choice"})) + + +def test_invalid_document_id_is_rejected(): + """The id is engine-safe.""" + with pytest.raises(DocumentError, match=r"^document 'a:b': invalid document id"): + validate_document(SCHEMA, _document(id="a:b")) + + +def test_too_long_document_id_is_rejected(): + """An id above the filterable limit would fail only at the engine.""" + with pytest.raises(DocumentError, match="maximum is 468"): + validate_document(SCHEMA, _document(id="a" * (MAX_DOCUMENT_ID_BYTES + 1))) + + +def test_validate_documents_checks_every_document(): + """One bad document fails the batch.""" + with pytest.raises(DocumentError, match="must be a string"): + validate_documents(SCHEMA, [_document(), _document(title=1)]) diff --git a/tests/test_meilisearch.py b/tests/test_meilisearch.py new file mode 100644 index 0000000..df6b4dc --- /dev/null +++ b/tests/test_meilisearch.py @@ -0,0 +1,731 @@ +"""Tests for the Meilisearch adapter.""" + +import base64 +import hashlib +import hmac +import json +from datetime import datetime, timedelta, timezone + +import pytest +from django.test import override_settings + +from openedx_search.adapters import ( + AdapterError, + CredentialScope, + FilterGroup, + FilterTerm, + RebuildTarget, + SearchCredential, + WriteFailed, + WriteReceipt, + get_adapter, +) +from openedx_search.config import BackendConfig +from openedx_search.meilisearch import MEILISEARCH_RANKING_RULES, PAGE_SIZE, MeilisearchAdapter, register, render_filter +from openedx_search.registry import UseCaseRegistration +from openedx_search.schema import Capabilities, Field, FieldType, IndexSchema, Searchable +from openedx_search.transport import TransportError +from tests.fixtures import STUDIO_COURSE + +MOMENT = datetime(2026, 1, 1, tzinfo=timezone.utc) +MOMENT_SECONDS = 1767225600 +TENANT_KEY = "test-key" +TENANT_UID = "00000000-0000-4000-8000-000000000000" +TENANT_TOKEN = ( + "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" + ".eyJhcGlLZXlVaWQiOiIwMDAwMDAwMC0wMDAwLTQwMDAtODAwMC0wMDAwMDAwMDAwMDAiLCJzZWFyY2hSdWxlcyI6" + "eyJzdHVkaW9fY29udGVudCI6eyJmaWx0ZXIiOiIob3JnIElOIFtcIm9wZW5lZHhcIl0pIn19LCJleHAiOjE3OTg3NjE2MDB9" + ".tlqBwpZqVc4MbxgZuulCkLPOyJO_OdTQLahR7Swqy8g" +) + + +class FakeTransport: + """Records requests and replays queued responses.""" + + def __init__(self, responses=None, *, tasks=None): + """Start with the given responses, in order, and task statuses.""" + self.responses = list(responses or []) + self.tasks = dict(tasks or {}) + self.task_statuses = {} + self.task_errors = {} + self.requests = [] + + def request(self, method, path, body=None): + """Record the request and return the next response or task status.""" + self.requests.append((method, path, body)) + if method == "GET" and path.startswith("/tasks/"): + task_id = int(path.rsplit("/", 1)[1]) + statuses = self.task_statuses.get(task_id) + status = statuses.pop(0) if statuses else self.tasks.get(task_id, "succeeded") + return { + "taskUid": task_id, + "status": status, + "error": self.task_errors.get(task_id), + } + if not self.responses: + raise AssertionError(f"unexpected request {method} {path}") # pragma: no cover + response = self.responses.pop(0) + if isinstance(response, Exception): + raise response + return response + + def fail(self, task_id, code): + """Make the given task report a failure.""" + self.tasks[task_id] = "failed" + self.task_errors[task_id] = {"code": code} + + def paths(self): + """Return the method and path of every request, in order.""" + return [(method, path) for method, path, _ in self.requests] + + +def _adapter(registration=STUDIO_COURSE, transport=None): + """Build an adapter that talks to the given fake transport.""" + backend = BackendConfig( + name="default", + engine="meilisearch", + url="http://engine:7700", + api_key="secret", + ) + return MeilisearchAdapter(registration, backend, transport=transport or FakeTransport()) + + +def _decode_token(token): + """Decode a tenant token payload without verifying it.""" + payload = token.split(".")[1] + return json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))) + + +def _verify_token(token, key): + """Verify a tenant token signature with its parent key.""" + header, payload, signature = token.split(".") + expected = base64.urlsafe_b64encode( + hmac.new(key.encode(), f"{header}.{payload}".encode(), hashlib.sha256).digest() + ).decode("ascii").rstrip("=") + assert signature == expected + + +def _key_page(key=TENANT_KEY, *, uid=TENANT_UID, actions=("search",)): + """Build a /keys page with one key.""" + return { + "results": [{"uid": uid, "key": key, "actions": list(actions), "indexes": ["*"]}], + "offset": 0, + "limit": 1000, + "total": 1, + } + + +def _tenant_adapter(transport, *, api_key=TENANT_KEY, search_api_key=None): + """Build an adapter whose backend can mint tenant tokens.""" + backend = BackendConfig( + name="default", + engine="meilisearch", + url="http://engine:7700", + public_url="https://search.example.com", + api_key=api_key, + search_api_key=search_api_key, + ) + return MeilisearchAdapter(STUDIO_COURSE, backend, transport=transport) + + +def test_settings_render_the_schema(): + """Searchable order, filterable paths, sortable fields and ranking rules.""" + settings = _adapter().settings() + + assert settings["searchableAttributes"] == [ + "display_name", + "block_id", + "content", + "description", + "tags", + "tags.taxonomy", + "tags.level0", + "tags.level1", + "tags.level2", + "tags.level3", + ] + assert settings["filterableAttributes"] == [ + "id", + "usage_key", + "block_id", + "block_type", + "context_key", + "org", + "access_id", + "breadcrumbs.usage_key", + "tags", + "tags.taxonomy", + "tags.level0", + "tags.level1", + "tags.level2", + "tags.level3", + "content.problem_types", + ] + assert settings["sortableAttributes"] == ["display_name", "modified"] + assert settings["rankingRules"] == list(MEILISEARCH_RANKING_RULES) + assert settings["rankingRules"][0] == "sort" + + +def test_searchable_fields_without_an_order_come_last(): + """Only declared orders rank; the rest keep declaration order.""" + schema = IndexSchema( + name="order", + fields=( + Field("id", FieldType.STRING, required=True), + Field("unsorted", capabilities=Capabilities(searchable=True)), + Field("ranked", capabilities=Capabilities(searchable=Searchable(order=1))), + ), + ) + registration = UseCaseRegistration(use_case="order", index="order_index", schema=schema) + + settings = _adapter(registration).settings() + + assert settings["searchableAttributes"] == ["ranked", "unsorted"] + assert settings["filterableAttributes"] == ["id"] + + +def test_reconcile_creates_and_configures_a_missing_index(): + """A missing index is created with the primary key and the settings.""" + live = _adapter().settings() + transport = FakeTransport( + [TransportError("missing", status=404), {"taskUid": 1}, {"taskUid": 2}, live] + ) + adapter = _adapter(transport=transport) + + result = adapter.reconcile() + + assert result.changed + assert transport.paths() == [ + ("GET", "/indexes/studio_content"), + ("POST", "/indexes"), + ("GET", "/tasks/1"), + ("PATCH", "/indexes/studio_content/settings"), + ("GET", "/tasks/2"), + ("GET", "/indexes/studio_content/settings"), + ] + assert transport.requests[1][2] == {"uid": "studio_content", "primaryKey": "id"} + assert transport.requests[3][2] == live + + +def test_reconcile_reports_no_change_for_a_matching_index(): + """An index with the declared settings is left alone.""" + live = _adapter().settings() + transport = FakeTransport([{}, live]) + + result = _adapter(transport=transport).reconcile() + + assert not result.changed + assert transport.paths() == [ + ("GET", "/indexes/studio_content"), + ("GET", "/indexes/studio_content/settings"), + ] + + +def test_reconcile_rejects_a_foreign_primary_key(): + """Writes address documents by ``id``; another primary key would break them.""" + transport = FakeTransport([{"uid": "studio_content", "primaryKey": "key"}]) + + with pytest.raises(AdapterError, match="primary key"): + _adapter(transport=transport).reconcile() + + +def test_reconcile_patches_only_the_settings_that_drifted(): + """A changed ranking order is the only thing sent back.""" + live = _adapter().settings() + drifted = {**live, "rankingRules": ["words"]} + transport = FakeTransport([{}, drifted, {"taskUid": 3}]) + + result = _adapter(transport=transport).reconcile() + + assert result.changed + assert transport.requests[2] == ( + "PATCH", + "/indexes/studio_content/settings", + {"rankingRules": list(MEILISEARCH_RANKING_RULES)}, + ) + + +def test_reconcile_fails_when_the_engine_rejects_the_task(): + """A failed lifecycle task is an adapter error, not a silent success.""" + transport = FakeTransport([TransportError("missing", status=404), {"taskUid": 1}]) + transport.fail(1, "index_creation_failed") + + with pytest.raises(AdapterError, match="index_creation_failed"): + _adapter(transport=transport).reconcile() + + +def test_upsert_returns_the_task_receipt(): + """A batch reaches the live index and its task becomes the receipt.""" + transport = FakeTransport([{"taskUid": 42}]) + + receipt = _adapter(transport=transport).upsert([{"id": "doc", "usage_key": "x"}]) + + assert receipt == WriteReceipt(task_id=42) + assert transport.requests == [ + ("POST", "/indexes/studio_content/documents", [{"id": "doc", "usage_key": "x"}]), + ] + + +def test_upsert_renders_datetimes_as_posix_seconds(): + """The engine stores seconds, and the document validator accepts a datetime.""" + transport = FakeTransport([{"taskUid": 1}]) + + _adapter(transport=transport).upsert([{"id": "doc", "modified": MOMENT}]) + + assert transport.requests[0][2] == [{"id": "doc", "modified": MOMENT_SECONDS}] + + +def test_upsert_can_target_a_rebuild(): + """A rebuild batch goes to the target's physical index, not the live one.""" + target = RebuildTarget(index="studio_content", version=1, generation="gen1") + transport = FakeTransport([{"taskUid": 1}]) + + _adapter(transport=transport).upsert([{"id": "doc"}], target=target) + + assert target.name == "studio_content_v1_gen1" + assert transport.requests[0][1] == "/indexes/studio_content_v1_gen1/documents" + + +def test_delete_by_primary_keys_uses_the_batch_endpoint(): + """A list of ids is one bounded delete request.""" + transport = FakeTransport([{"taskUid": 5}]) + + receipt = _adapter(transport=transport).delete(("doc-1", "doc-2")) + + assert receipt == WriteReceipt(task_id=5) + assert transport.requests == [ + ("POST", "/indexes/studio_content/documents/delete-batch", ["doc-1", "doc-2"]), + ] + + +def test_delete_by_filter_renders_the_expression(): + """The abstract expression becomes Meilisearch filter syntax.""" + expression = ( + FilterGroup( + ( + FilterTerm("org", ("openedx",)), + FilterTerm("access_id", (1,)), + ) + ), + ) + transport = FakeTransport([{"taskUid": 6}]) + + _adapter(transport=transport).delete(filter=expression) + + assert transport.requests == [ + ( + "POST", + "/indexes/studio_content/documents/delete", + {"filter": '(org IN ["openedx"] OR access_id IN [1])'}, + ), + ] + + +def test_delete_requires_a_form(): + """The adapter refuses a delete with neither keys nor a filter.""" + with pytest.raises(ValueError, match="primary_keys or filter"): + _adapter().delete() + + +def test_render_filter_keeps_group_and_term_precedence(): + """Groups are ANDed; terms inside a group are ORed, with typed literals.""" + expression = ( + FilterGroup((FilterTerm("org", ("a", "b")),)), + FilterGroup( + ( + FilterTerm("published", (True,)), + FilterTerm("modified", (MOMENT,)), + ) + ), + ) + + assert render_filter(expression) == ( + '(org IN ["a", "b"]) AND (published IN [true] OR modified IN [1767225600])' + ) + + +def test_check_write_reports_an_unfinished_task(): + """One poll returns an incomplete receipt while the task is running.""" + transport = FakeTransport(tasks={7: "processing"}) + + receipt = _adapter(transport=transport).check_write(WriteReceipt(task_id=7)) + + assert receipt == WriteReceipt(task_id=7, complete=False) + assert transport.paths() == [("GET", "/tasks/7")] + + +def test_check_write_completes_a_succeeded_task(): + """A succeeded task marks the receipt complete.""" + transport = FakeTransport() + + receipt = _adapter(transport=transport).check_write(WriteReceipt(task_id=7)) + + assert receipt == WriteReceipt(task_id=7, complete=True) + + +def test_check_write_raises_for_a_failed_task(): + """A failed task is a write failure, not a receipt to poll again.""" + transport = FakeTransport() + transport.fail(7, "invalid_document") + + with pytest.raises(WriteFailed, match="invalid_document"): + _adapter(transport=transport).check_write(WriteReceipt(task_id=7)) + + +def test_check_write_skips_a_complete_receipt(): + """An already complete receipt costs no request.""" + transport = FakeTransport() + + result = _adapter(transport=transport).check_write(WriteReceipt(task_id=7, complete=True)) + + assert result == WriteReceipt(task_id=7, complete=True) + assert not transport.requests + + +def test_begin_rebuild_removes_leftovers_and_creates_the_target(): + """Only targets of this index and version are removed; the target is new.""" + target = RebuildTarget(index="studio_content", version=1, generation="gen1") + settings = _adapter().settings() + transport = FakeTransport( + [ + { + "results": [ + {"uid": "studio_content_v1_old"}, + {"uid": "studio_content_v1_gen1"}, + {"uid": "other"}, + ], + "offset": 0, + "limit": 1000, + "total": 3, + }, + {"taskUid": 1}, + {"taskUid": 2}, + {"taskUid": 3}, + ] + ) + + _adapter(transport=transport).begin_rebuild(target) + + assert transport.paths() == [ + ("GET", "/indexes?offset=0&limit=1000"), + ("DELETE", "/indexes/studio_content_v1_old"), + ("GET", "/tasks/1"), + ("POST", "/indexes"), + ("GET", "/tasks/2"), + ("PATCH", "/indexes/studio_content_v1_gen1/settings"), + ("GET", "/tasks/3"), + ] + assert transport.requests[3][2] == { + "uid": "studio_content_v1_gen1", + "primaryKey": "id", + } + assert transport.requests[5][2] == settings + + +def test_commit_rebuild_swaps_the_target_and_deletes_it(): + """The live name keeps the documents; the old copy is discarded.""" + target = RebuildTarget(index="studio_content", version=1, generation="gen1") + transport = FakeTransport([{}, {"taskUid": 1}, {"taskUid": 2}]) + + _adapter(transport=transport).commit_rebuild(target) + + assert transport.paths() == [ + ("GET", "/indexes/studio_content"), + ("POST", "/swap-indexes"), + ("GET", "/tasks/1"), + ("DELETE", "/indexes/studio_content_v1_gen1"), + ("GET", "/tasks/2"), + ] + assert transport.requests[1][2] == [ + {"indexes": ["studio_content", "studio_content_v1_gen1"]}, + ] + + +def test_commit_rebuild_creates_the_live_index_when_missing(): + """The first deploy has no live index to swap with, so it is created.""" + target = RebuildTarget(index="studio_content", version=1, generation="gen1") + transport = FakeTransport( + [ + TransportError("missing", status=404), + {"taskUid": 1}, + {"taskUid": 2}, + {"taskUid": 3}, + {"taskUid": 4}, + ] + ) + + _adapter(transport=transport).commit_rebuild(target) + + assert transport.paths()[:4] == [ + ("GET", "/indexes/studio_content"), + ("POST", "/indexes"), + ("GET", "/tasks/1"), + ("PATCH", "/indexes/studio_content/settings"), + ] + assert ("POST", "/swap-indexes") in transport.paths() + + +def test_abort_rebuild_ignores_a_missing_target(): + """A crash before the target existed leaves nothing to delete.""" + target = RebuildTarget(index="studio_content", version=1, generation="gen1") + transport = FakeTransport([TransportError("missing", status=404)]) + + _adapter(transport=transport).abort_rebuild(target) + + assert transport.paths() == [("DELETE", "/indexes/studio_content_v1_gen1")] + + +def test_abort_rebuild_deletes_the_target(): + """A target that exists is deleted and its task awaited.""" + target = RebuildTarget(index="studio_content", version=1, generation="gen1") + transport = FakeTransport([{"taskUid": 9}]) + + _adapter(transport=transport).abort_rebuild(target) + + assert transport.paths() == [ + ("DELETE", "/indexes/studio_content_v1_gen1"), + ("GET", "/tasks/9"), + ] + + +def test_search_is_deferred_to_the_query_api(): + """The read side lands with its own contract.""" + with pytest.raises(NotImplementedError, match="query API"): + _adapter().search("anything") + + +def test_mint_credential_matches_the_meilisearch_reference(monkeypatch): + """The token is byte-identical to the official client's output.""" + monkeypatch.setattr( + "openedx_search.meilisearch._now", + lambda: datetime(2026, 12, 31, tzinfo=timezone.utc), + ) + transport = FakeTransport([_key_page()]) + scope = CredentialScope(filters=(FilterGroup((FilterTerm("org", ("openedx",)),)),)) + + credential = _tenant_adapter(transport).mint_credential(scope, timedelta(days=1)) + + assert credential == SearchCredential( + url="https://search.example.com", + index_name="studio_content", + api_key=TENANT_TOKEN, + ) + assert transport.paths() == [("GET", "/keys?limit=1000")] + + +def test_mint_credential_without_filters_allows_the_index(monkeypatch): + """An empty scope searches the whole index but no other index.""" + monkeypatch.setattr( + "openedx_search.meilisearch._now", + lambda: datetime(2027, 1, 1, tzinfo=timezone.utc), + ) + transport = FakeTransport([_key_page()]) + + credential = _tenant_adapter(transport).mint_credential(CredentialScope(), timedelta(hours=1)) + + assert _decode_token(credential.api_key)["searchRules"] == {"studio_content": {}} + + +def test_mint_credential_signs_with_the_search_key(monkeypatch): + """search_api_key is the parent when configured and signs the token.""" + monkeypatch.setattr( + "openedx_search.meilisearch._now", + lambda: datetime(2027, 1, 1, tzinfo=timezone.utc), + ) + transport = FakeTransport([_key_page(key="search-key")]) + adapter = _tenant_adapter(transport, api_key="write-key", search_api_key="search-key") + + credential = adapter.mint_credential(CredentialScope(), timedelta(hours=1)) + + _verify_token(credential.api_key, "search-key") + assert _decode_token(credential.api_key)["apiKeyUid"] == TENANT_UID + + +def test_mint_credential_requires_a_listed_key(): + """The master key is not listed, so it cannot sign a tenant token.""" + transport = FakeTransport([{"results": [], "offset": 0, "limit": 1000, "total": 0}]) + + with pytest.raises(AdapterError, match="did not list"): + _tenant_adapter(transport).mint_credential(CredentialScope(), timedelta(hours=1)) + + +def test_mint_credential_skips_other_keys(): + """Only the configured key is used, even when it is not the first entry.""" + transport = FakeTransport( + [ + { + "results": [ + {"uid": "other", "key": "other-key", "actions": ["search"], "indexes": ["*"]}, + {"uid": TENANT_UID, "key": TENANT_KEY, "actions": ["search"], "indexes": ["*"]}, + ], + "offset": 0, + "limit": 1000, + "total": 2, + } + ] + ) + + credential = _tenant_adapter(transport).mint_credential(CredentialScope(), timedelta(hours=1)) + + assert _decode_token(credential.api_key)["apiKeyUid"] == TENANT_UID + + +def test_mint_credential_expires_after_the_requested_lifetime(): + """The token expiry is the current time plus the requested lifetime.""" + transport = FakeTransport([_key_page()]) + before = int(datetime.now(timezone.utc).timestamp()) + + credential = _tenant_adapter(transport).mint_credential(CredentialScope(), timedelta(hours=1)) + + after = int(datetime.now(timezone.utc).timestamp()) + assert before + 3600 <= _decode_token(credential.api_key)["exp"] <= after + 3600 + + +def test_mint_credential_requires_a_search_key(): + """A key without the search action cannot mint a tenant token.""" + transport = FakeTransport([_key_page(actions=("documents.add",))]) + + with pytest.raises(AdapterError, match="allow search"): + _tenant_adapter(transport).mint_credential(CredentialScope(), timedelta(hours=1)) + + +def test_mint_credential_rejects_an_invalid_key_list(): + """The key list must be an object with a results list.""" + transport = FakeTransport([{}]) + + with pytest.raises(AdapterError, match="invalid key list"): + _tenant_adapter(transport).mint_credential(CredentialScope(), timedelta(hours=1)) + + +def test_mint_credential_requires_a_valid_key_uid(): + """An entry without a uid cannot be used as the issuer.""" + transport = FakeTransport([_key_page(uid="")]) + + with pytest.raises(AdapterError, match="invalid key uid"): + _tenant_adapter(transport).mint_credential(CredentialScope(), timedelta(hours=1)) + + +def test_reconcile_propagates_a_transport_failure(): + """A non-404 failure is not treated as a missing index.""" + transport = FakeTransport([TransportError("unavailable", status=503)]) + + with pytest.raises(TransportError): + _adapter(transport=transport).reconcile() + + +def test_reconcile_rejects_an_invalid_index_response(): + """The index endpoint must return an object.""" + transport = FakeTransport(["not a mapping"]) + + with pytest.raises(AdapterError, match="invalid index description"): + _adapter(transport=transport).reconcile() + + +def test_reconcile_rejects_invalid_settings(): + """The settings endpoint must return an object.""" + transport = FakeTransport([{}, []]) + + with pytest.raises(AdapterError, match="invalid index settings"): + _adapter(transport=transport).reconcile() + + +def test_reconcile_waits_for_a_processing_task(monkeypatch): + """A task that is still running is polled again after a backoff.""" + sleeps = [] + monkeypatch.setattr("openedx_search.meilisearch.time.sleep", sleeps.append) + live = _adapter().settings() + transport = FakeTransport( + [TransportError("missing", status=404), {"taskUid": 1}, {"taskUid": 2}, live] + ) + transport.task_statuses[1] = ["processing", "succeeded"] + + result = _adapter(transport=transport).reconcile() + + assert result.changed + assert sleeps == [0.1] + + +def test_reconcile_times_out_on_a_stuck_task(monkeypatch): + """A task that never finishes fails the lifecycle call.""" + monkeypatch.setattr("openedx_search.meilisearch.TASK_TIMEOUT", 0) + monkeypatch.setattr("openedx_search.meilisearch.time.sleep", lambda seconds: None) + transport = FakeTransport( + [TransportError("missing", status=404), {"taskUid": 1}], + tasks={1: "processing"}, + ) + + with pytest.raises(AdapterError, match="did not finish"): + _adapter(transport=transport).reconcile() + + +def test_abort_rebuild_propagates_a_transport_failure(): + """Only a missing target is tolerated.""" + target = RebuildTarget(index="studio_content", version=1, generation="gen1") + transport = FakeTransport([TransportError("unavailable", status=503)]) + + with pytest.raises(TransportError): + _adapter(transport=transport).abort_rebuild(target) + + +def test_begin_rebuild_rejects_an_invalid_index_list(): + """The index list endpoint must return a results list.""" + target = RebuildTarget(index="studio_content", version=1, generation="gen1") + transport = FakeTransport([{}]) + + with pytest.raises(AdapterError, match="invalid index list"): + _adapter(transport=transport).begin_rebuild(target) + + +def test_index_list_is_paged(): + """A full page is followed by the next offset.""" + target = RebuildTarget(index="studio_content", version=1, generation="gen1") + first = {"results": [{"uid": f"other-{position}"} for position in range(PAGE_SIZE)]} + second = {"results": []} + transport = FakeTransport([first, second, {"taskUid": 1}, {"taskUid": 2}]) + + _adapter(transport=transport).begin_rebuild(target) + + assert transport.paths()[:2] == [ + ("GET", "/indexes?offset=0&limit=1000"), + ("GET", f"/indexes?offset={PAGE_SIZE}&limit=1000"), + ] + assert transport.requests[2][2] == { + "uid": "studio_content_v1_gen1", + "primaryKey": "id", + } + + +def test_upsert_rejects_an_acknowledgment_without_a_task(): + """A write must return a task id.""" + transport = FakeTransport([{}]) + + with pytest.raises(AdapterError, match="did not acknowledge"): + _adapter(transport=transport).upsert([{"id": "doc"}]) + + +def test_upsert_renders_datetimes_inside_lists(): + """A datetime nested in an array becomes POSIX seconds too.""" + transport = FakeTransport([{"taskUid": 1}]) + + _adapter(transport=transport).upsert([{"id": "doc", "tags": ["a", MOMENT]}]) + + assert transport.requests[0][2] == [{"id": "doc", "tags": ["a", MOMENT_SECONDS]}] + + +def test_register_resolves_the_adapter(): + """Registering the engine lets the library resolve it from settings.""" + register() + with override_settings( + OPENEDX_SEARCH_BACKENDS={ + "default": { + "engine": "meilisearch", + "url": "http://engine:7700", + "api_key": "secret", + } + }, + OPENEDX_SEARCH_DEFAULT_BACKEND="default", + ): + adapter = get_adapter(STUDIO_COURSE) + + assert isinstance(adapter, MeilisearchAdapter) + assert adapter.backend.engine == "meilisearch" diff --git a/tests/test_schema.py b/tests/test_schema.py index c26eff2..aba0e7e 100644 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -83,6 +83,17 @@ def test_validate_document_id_rejects_non_strings(): validate_document_id(1) +def test_validate_document_id_accepts_the_maximum_length(): + """The filterable limit itself is valid.""" + assert validate_document_id("a" * MAX_DOCUMENT_ID_BYTES) + + +def test_validate_document_id_rejects_an_id_over_the_limit(): + """A filterable id above 468 bytes would fail only at the engine.""" + with pytest.raises(ValueError, match="maximum is 468"): + validate_document_id("a" * (MAX_DOCUMENT_ID_BYTES + 1)) + + def test_library_schema_is_valid(): """The library schema is the union of the three library document shapes.""" assert STUDIO_LIBRARY_SCHEMA.name == "studio_library" diff --git a/tests/test_transport.py b/tests/test_transport.py new file mode 100644 index 0000000..bb6e94e --- /dev/null +++ b/tests/test_transport.py @@ -0,0 +1,181 @@ +"""Tests for the shared HTTP transport.""" + +import io +import json +from urllib.error import HTTPError, URLError + +import pytest + +from openedx_search.transport import HTTPTransport, TransportError, _NoRedirect + + +class _Response(io.BytesIO): + """A response body used as a context manager.""" + + def __enter__(self): + """Return the body.""" + return self + + def __exit__(self, *exc_info): + """Close the body and propagate nothing.""" + self.close() + return False + + +class _Opener: + """A stand-in for urllib's opener that replays one outcome.""" + + def __init__(self, outcome): + """Store the outcome and start recording requests.""" + self.outcome = outcome + self.requests = [] + + def open(self, request, timeout=None): # pylint: disable=unused-argument + """Record the request and return or raise the configured outcome.""" + self.requests.append(request) + if isinstance(self.outcome, Exception): + raise self.outcome + return _Response(self.outcome) + + +def _transport(monkeypatch, outcome, **kwargs): + """Build a transport whose opener replays ``outcome``.""" + opener = _Opener(outcome) + monkeypatch.setattr("openedx_search.transport.build_opener", lambda *args: opener) + transport = HTTPTransport( + "http://engine:7700", + {"Authorization": "Bearer secret"}, + **kwargs, + ) + return transport, opener + + +def test_request_sends_json_and_decodes_the_response(monkeypatch): + """The method, URL, headers and body reach the engine; JSON comes back.""" + transport, opener = _transport(monkeypatch, json.dumps({"taskUid": 3}).encode()) + + assert transport.request("POST", "/indexes", body={"uid": "course"}) == {"taskUid": 3} + + request = opener.requests[0] + assert request.full_url == "http://engine:7700/indexes" + assert request.get_method() == "POST" + assert request.headers["Authorization"] == "Bearer secret" + assert json.loads(request.data) == {"uid": "course"} + + +def test_request_without_a_body_returns_none(monkeypatch): + """An empty response means the engine returned no payload.""" + transport, opener = _transport(monkeypatch, b"") + + assert transport.request("DELETE", "/indexes/course") is None + assert opener.requests[0].data is None + + +def test_missing_resource_is_reported_as_not_found(monkeypatch): + """A 404 is distinguishable from every other transport failure.""" + error = HTTPError("http://engine/indexes/x", 404, "Not Found", {}, io.BytesIO(b"")) + transport, _ = _transport(monkeypatch, error) + + with pytest.raises(TransportError) as excinfo: + transport.request("GET", "/indexes/x") + + assert excinfo.value.status == 404 + assert excinfo.value.not_found + assert not excinfo.value.retryable + + +def test_server_error_is_retryable(monkeypatch): + """A 5xx may succeed when retried unchanged.""" + error = HTTPError("http://engine/x", 503, "Unavailable", {}, io.BytesIO(b"")) + transport, _ = _transport(monkeypatch, error) + + with pytest.raises(TransportError) as excinfo: + transport.request("GET", "/indexes/x") + + assert excinfo.value.status == 503 + assert excinfo.value.retryable + + +def test_response_over_the_limit_is_rejected(monkeypatch): + """A response larger than the configured bound is not read in full.""" + transport, _ = _transport(monkeypatch, b"0123456789", max_response_bytes=4) + + with pytest.raises(TransportError, match="size limit"): + transport.request("GET", "/indexes") + + +def test_invalid_json_is_rejected(monkeypatch): + """A body that is not JSON is a transport failure, not a result.""" + transport, _ = _transport(monkeypatch, b"oops") + + with pytest.raises(TransportError, match="invalid JSON"): + transport.request("GET", "/indexes") + + +def test_request_lines_sends_and_decodes_json_lines(monkeypatch): + """Each item is one request line and each response line is one result.""" + transport, opener = _transport(monkeypatch, b'{"success":true}\n\n{"success":false}\n') + + results = transport.request_lines("POST", "/import", [{"id": "a"}, {"id": "b"}]) + + assert results == [{"success": True}, {"success": False}] + request = opener.requests[0] + assert request.data == b'{"id": "a"}\n{"id": "b"}' + assert request.headers["Content-type"] == "text/plain" + assert request.headers["Authorization"] == "Bearer secret" + + +def test_request_lines_rejects_an_invalid_line(monkeypatch): + """One undecodable line fails the whole response.""" + transport, _ = _transport(monkeypatch, b'{"success":true}\nnot json\n') + + with pytest.raises(TransportError, match="invalid JSON Lines"): + transport.request_lines("POST", "/import", [{"id": "a"}]) + + +@pytest.mark.parametrize( + "url", + [ + "ftp://engine:7700", + "http://user:pass@engine:7700", + "http://engine:7700?query=1", + "http://engine:7700#fragment", + ], +) +def test_url_must_be_a_plain_http_endpoint(monkeypatch, url): + """Credentials, a query or a fragment in the URL are rejected up front.""" + monkeypatch.setattr("openedx_search.transport.build_opener", lambda *args: _Opener(b"{}")) + + with pytest.raises(ValueError): + HTTPTransport(url, {"Authorization": "Bearer secret"}) + + +def test_transport_failure_is_retryable(monkeypatch): + """A connection failure has no status and may be retried.""" + transport, _ = _transport(monkeypatch, URLError("refused")) + + with pytest.raises(TransportError) as excinfo: + transport.request("GET", "/indexes") + + assert excinfo.value.status is None + assert excinfo.value.retryable + + +def test_redirects_are_refused(): + """A redirect would forward the authorization header, so it is never followed.""" + handler = _NoRedirect() + + assert handler.redirect_request(None, None, 302, "Found", {}, "http://other") is None + + +def test_timeout_must_be_positive(): + """A zero or negative timeout is rejected.""" + with pytest.raises(ValueError, match="timeout"): + HTTPTransport("http://engine:7700", {}, timeout=0) + + +@pytest.mark.parametrize("value", [0, -1, True, 1.5]) +def test_response_limit_must_be_a_positive_integer(value): + """The response bound is a positive integer, not a bool or a float.""" + with pytest.raises(ValueError, match="max_response_bytes"): + HTTPTransport("http://engine:7700", {}, max_response_bytes=value) diff --git a/tests/test_typesense.py b/tests/test_typesense.py new file mode 100644 index 0000000..d74b3e0 --- /dev/null +++ b/tests/test_typesense.py @@ -0,0 +1,919 @@ +"""Tests for the Typesense adapter.""" + +import base64 +import hashlib +import json +import logging +import uuid +from datetime import datetime, timedelta, timezone +from urllib.parse import parse_qs, urlsplit + +import pytest +from django.test import override_settings + +from openedx_search.adapters import ( + AdapterError, + CredentialScope, + FilterGroup, + FilterTerm, + RebuildTarget, + SearchCredential, + UnsupportedSchema, + WriteFailed, + WriteReceipt, + get_adapter, +) +from openedx_search.config import BackendConfig +from openedx_search.registry import UseCaseRegistration +from openedx_search.schema import Capabilities, Field, FieldType, IndexSchema, Searchable +from openedx_search.transport import TransportError +from openedx_search.typesense import ( + DELETE_BATCH_SIZE, + EXACT_SUFFIX, + INDEX_FIELD, + MAX_SEARCHABLE_FIELDS, + TypesenseAdapter, + register, +) +from tests.fixtures import STUDIO_COURSE, STUDIO_LIBRARY + +MOMENT = datetime(2026, 1, 1, tzinfo=timezone.utc) +MOMENT_SECONDS = 1767225600 +SEARCH_KEY = "test-search-key" +# typesense-python 2.2.0: Client.keys.generate_scoped_search_key(SEARCH_KEY, ). +SCOPED_KEY = ( + "eTlCNlYzd1BYVkVWNEhIWGFsWlY4YS9uN21JSmtNREFRRW5BaEdNSlRoMD10ZXN0eyJleHBpcmVzX2F0IjogMTc5ODg0ODAwMCwgInF1" + "ZXJ5X2J5IjogImRpc3BsYXlfbmFtZSxibG9ja19pZCxjb250ZW50LGRlc2NyaXB0aW9uLHRhZ3MsdGFncy50YXhvbm9teSx0YWdzLmxl" + "dmVsMCx0YWdzLmxldmVsMSx0YWdzLmxldmVsMix0YWdzLmxldmVsMyIsICJxdWVyeV9ieV93ZWlnaHRzIjogIjEyNywxMjYsMTI1LDEy" + "NCwxMjMsMTIyLDEyMSwxMjAsMTE5LDExOCIsICJmaWx0ZXJfYnkiOiAiX19pbmRleDo9W2A0MWJhYmExYTNlNTU3ODU0NjAwYjU3ZDFk" + "YjQzMDgzNWRjMmM3NmQ0YTU3YmExYzFkNTU2NGM5Nzg5ZDRhYzU4YF0gJiYgKG9yZ19fZXhhY3Q6PVtgYjhjY2JlNDU2NmM2Y2RhY2Qy" + "MWRlYzY5YzJmMDMyNzYzMjE4NWVlN2VmMTEzOTc5MDgxOTcyYTAzM2ExN2M4ZmBdIHx8IGFjY2Vzc19pZDo9WzddKSIsICJleGNsdWRl" + "X2ZpZWxkcyI6ICJibG9ja19pZF9fZXhhY3QsYmxvY2tfdHlwZV9fZXhhY3QsYnJlYWRjcnVtYnMudXNhZ2Vfa2V5X19leGFjdCxjb250" + "ZW50LnByb2JsZW1fdHlwZXNfX2V4YWN0LGNvbnRleHRfa2V5X19leGFjdCxvcmdfX2V4YWN0LHRhZ3MubGV2ZWwwX19leGFjdCx0YWdz" + "LmxldmVsMV9fZXhhY3QsdGFncy5sZXZlbDJfX2V4YWN0LHRhZ3MubGV2ZWwzX19leGFjdCx0YWdzLnRheG9ub215X19leGFjdCx1c2Fn" + "ZV9rZXlfX2V4YWN0In0=" +) +LIVE = "studio_content_v1_abc" + + +def sha(value): + """Return the digest the adapter stores and filters on.""" + return hashlib.sha256(value.encode()).hexdigest() + + +STUDIO_TAG = sha("studio_content") + + +class FakeTransport: + """Records requests and replays queued responses.""" + + def __init__(self, responses=None): + """Start with the given responses, in order.""" + self.responses = list(responses or []) + self.requests = [] + + def _next(self, method, path): + """Return or raise the next queued response.""" + if not self.responses: + raise AssertionError(f"unexpected request {method} {path}") # pragma: no cover + response = self.responses.pop(0) + if isinstance(response, Exception): + raise response + return response + + def request(self, method, path, body=None): + """Record a JSON request.""" + self.requests.append((method, path, body)) + return self._next(method, path) + + def request_lines(self, method, path, items): + """Record a JSON Lines request.""" + self.requests.append((method, path, list(items))) + return self._next(method, path) + + def paths(self): + """Return the method and path of every request, in order.""" + return [(method, path) for method, path, _ in self.requests] + + +def _missing(): + """Build the engine's not-found error.""" + return TransportError("missing", status=404) + + +def _backend(**kwargs): + """Build a Typesense backend configuration.""" + return BackendConfig( + name="default", + engine="typesense", + url="http://engine:8108", + api_key="secret", + **kwargs, + ) + + +def _adapter(registration=STUDIO_COURSE, transport=None, **backend): + """Build an adapter that talks to the given fake transport.""" + return TypesenseAdapter(registration, _backend(**backend), transport=transport or FakeTransport()) + + +def _registration(*fields, version=1): + """Build a registration around the given fields plus ``id``.""" + schema = IndexSchema( + name="small", + version=version, + fields=(Field("id", FieldType.STRING, required=True),) + fields, + ) + return UseCaseRegistration(use_case="small", index="small", schema=schema) + + +FILTERABLE = _registration( + Field("org", FieldType.STRING, capabilities=Capabilities(filterable=True)), + Field("access_id", FieldType.INT64, capabilities=Capabilities(filterable=True)), + Field("published", FieldType.BOOL, capabilities=Capabilities(filterable=True)), + Field("score", FieldType.FLOAT, capabilities=Capabilities(filterable=True)), + Field("modified", FieldType.DATETIME, capabilities=Capabilities(filterable=True)), + Field("title", FieldType.STRING, capabilities=Capabilities(searchable=True)), +) + + +def _collection(adapter, name=LIVE, **overrides): + """Describe a live collection that matches the adapter's schema.""" + return {**adapter.collection_schema(name), **overrides} + + +def _filter_by(path): + """Return the decoded ``filter_by`` query parameter of a request path.""" + return parse_qs(urlsplit(path).query)["filter_by"][0] + + +def _embedded(api_key): + """Decode the parameters a scoped key embeds (after a 44-character digest and 4-character prefix).""" + return json.loads(base64.b64decode(api_key).decode()[48:]) + + +def test_fields_render_the_schema(): + """Types, requiredness, capabilities, nested paths, hidden fields and free-form keys.""" + fields = {field["name"]: field for field in _adapter().fields()} + + assert "id" not in fields + assert fields["usage_key"] == { + "name": "usage_key", + "type": "string", + "index": True, + "optional": False, + "facet": False, + "sort": False, + "store": True, + } + assert fields["display_name"]["sort"] is True + assert fields["modified"] == { + "name": "modified", + "type": "int64", + "index": True, + "optional": True, + "facet": False, + "sort": True, + "store": True, + } + assert fields["org"]["facet"] is True + assert fields["access_id"]["type"] == "int64" + assert fields["tags.level0"]["type"] == "string[]" + assert fields["breadcrumbs"]["type"] == "object[]" + assert fields["content\\..*"] == { + "name": "content\\..*", + "type": "string", + "index": True, + "optional": True, + "facet": False, + "sort": False, + "store": True, + } + assert fields[INDEX_FIELD] == { + "name": INDEX_FIELD, + "type": "string", + "index": True, + "optional": True, + "facet": False, + "sort": False, + "store": False, + } + + +def test_filterable_strings_get_hidden_digest_companions(): + """Each filterable string field is followed by its unstored, optional companion.""" + names = [field["name"] for field in _adapter().fields()] + fields = {field["name"]: field for field in _adapter().fields()} + + assert names[names.index("org") + 1] == "org" + EXACT_SUFFIX + assert fields["tags.level0" + EXACT_SUFFIX] == { + "name": "tags.level0" + EXACT_SUFFIX, + "type": "string[]", + "index": True, + "optional": True, + "facet": False, + "sort": False, + "store": False, + } + # Not a string, not filterable, or the primary key: no companion. + assert "access_id" + EXACT_SUFFIX not in fields + assert "display_name" + EXACT_SUFFIX not in fields + assert "tags" + EXACT_SUFFIX not in fields + assert "id" + EXACT_SUFFIX not in fields + + +def test_free_form_keys_follow_every_declared_field(): + """A declared child must precede the pattern that would also match it.""" + names = [field["name"] for field in _adapter(STUDIO_LIBRARY).fields()] + + assert names.index("content.problem_types" + EXACT_SUFFIX) < names.index("content\\..*") + assert names[-3:] == [INDEX_FIELD, "content\\..*", "published\\.content\\..*"] + + +def test_indexing_follows_capabilities_and_object_paths(): + """Capabilities index a field; so do a searchable ancestor and an indexed child.""" + fields = {field["name"]: field for field in _adapter(STUDIO_LIBRARY).fields()} + + # No capability anywhere on the path. + assert fields["num_children"]["index"] is False + assert fields["units"]["index"] is False + assert fields["units.key"]["index"] is False + assert fields["published.content"]["index"] is False + assert fields["published\\.content\\..*"]["index"] is False + # A filterable child indexes its object array parent, but not its sibling. + assert fields["breadcrumbs"]["index"] is True + assert fields["breadcrumbs.usage_key"]["index"] is True + assert fields["breadcrumbs.display_name"]["index"] is False + # Every child of a searchable object is searched, so it is indexed. + assert fields["content.child_usage_keys"]["index"] is True + # A searchable leaf indexes its unsearchable parent. + assert fields["published"]["index"] is True + assert fields["published.num_children"]["index"] is False + + +def test_free_form_keys_inside_an_object_array_are_arrays(): + """Typesense requires array types for every field inside an object array.""" + registration = _registration( + Field("items", FieldType.OBJECT, array=True), + Field( + "items.extra", + FieldType.OBJECT, + array=True, + additional_properties=True, + capabilities=Capabilities(searchable=True), + ), + ) + fields = {field["name"]: field for field in _adapter(registration).fields()} + + assert fields["items\\.extra\\..*"]["type"] == "string[]" + + +def test_nested_fields_are_enabled_only_for_object_schemas(): + """``enable_nested_fields`` follows whether the schema declares an object.""" + flat = _registration(Field("title", FieldType.STRING)) + + assert _adapter().collection_schema("x")["enable_nested_fields"] is True + schema = _adapter(flat).collection_schema("x") + assert schema["enable_nested_fields"] is False + assert [field["name"] for field in schema["fields"]] == ["title", INDEX_FIELD] + + +def test_search_parameters_follow_the_searchable_order(): + """Ordered fields first, unordered last in declaration order, weights descending.""" + registration = _registration( + Field("body", FieldType.STRING, capabilities=Capabilities(searchable=True)), + Field("title", FieldType.STRING, capabilities=Capabilities(searchable=Searchable(order=1))), + Field("summary", FieldType.STRING, capabilities=Capabilities(searchable=True)), + ) + + assert _adapter(registration).search_parameters() == { + "query_by": "title,body,summary", + "query_by_weights": "127,126,125", + } + + +def test_search_parameters_are_empty_without_searchable_fields(): + """A schema with nothing searchable embeds no query parameters.""" + assert not _adapter(_registration(Field("title", FieldType.STRING))).search_parameters() + + +def test_validate_schema_accepts_the_studio_schemas(): + """Both consumer schemas fit the ranking levels and use no reserved names.""" + _adapter(STUDIO_COURSE).validate_schema() + _adapter(STUDIO_LIBRARY).validate_schema() + + +def test_validate_schema_rejects_more_searchable_fields_than_ranking_levels(): + """Typesense ranks weights into 16 levels, so a 17th field would tie.""" + fields = tuple( + Field(f"f{position}", FieldType.STRING, capabilities=Capabilities(searchable=True)) + for position in range(MAX_SEARCHABLE_FIELDS + 1) + ) + + with pytest.raises(UnsupportedSchema, match="17 searchable fields"): + _adapter(_registration(*fields)).validate_schema() + + +def test_validate_schema_rejects_reserved_field_names(): + """Declared fields cannot collide with the hidden fields.""" + registration = _registration( + Field("__index", FieldType.STRING), + Field("org__exact", FieldType.STRING), + ) + + with pytest.raises(UnsupportedSchema, match="reserved field names __index, org__exact"): + _adapter(registration).validate_schema() + + +def test_reconcile_creates_a_collection_and_points_the_alias(monkeypatch): + """The first collection is named like a rebuild target and the alias points at it.""" + generation = uuid.UUID(int=0xABC) + monkeypatch.setattr("openedx_search.typesense.uuid.uuid4", lambda: generation) + transport = FakeTransport([_missing(), _missing(), {}, {}]) + adapter = _adapter(transport=transport) + + result = adapter.reconcile() + + name = f"studio_content_v1_{generation.hex}" + assert result.changed is True + assert result.version == 1 + assert transport.paths() == [ + ("GET", "/aliases/studio_content"), + ("GET", "/collections/studio_content"), + ("POST", "/collections"), + ("PUT", "/aliases/studio_content"), + ] + assert transport.requests[2][2] == adapter.collection_schema(name) + assert transport.requests[3][2] == {"collection_name": name} + + +def test_reconcile_reports_no_change_for_a_matching_collection(): + """Engine-reported extras, field order and materialized free-form keys are not drift.""" + adapter = _adapter() + collection = _collection(adapter) + collection["fields"] = [ + {**field, "locale": "", "stem": False, "infix": False} for field in reversed(collection["fields"]) + ] + [{"name": "content.html_content", "type": "string", "index": True, "optional": True}] + transport = FakeTransport([{"collection_name": LIVE}, collection]) + adapter = _adapter(transport=transport) + + assert adapter.reconcile().changed is False + assert transport.paths() == [("GET", "/aliases/studio_content"), ("GET", f"/collections/{LIVE}")] + + +def test_reconcile_patches_one_change_per_request(): + """Changed and removed fields are separate requests; new fields share one.""" + adapter = _adapter() + collection = _collection(adapter) + fields = [field for field in collection["fields"] if field["name"] != "description"] + fields = [{**field, "facet": False} if field["name"] == "org" else field for field in fields] + fields.append({"name": "legacy", "type": "string", "index": True, "optional": True}) + collection["fields"] = fields + transport = FakeTransport([{"collection_name": LIVE}, collection, {}, {}, {}]) + adapter = _adapter(transport=transport) + wanted = {field["name"]: field for field in adapter.fields()} + + assert adapter.reconcile().changed is True + assert [request[:2] for request in transport.requests[2:]] == [("PATCH", f"/collections/{LIVE}")] * 3 + assert [request[2] for request in transport.requests[2:]] == [ + {"fields": [{"name": "org", "drop": True}, wanted["org"]]}, + {"fields": [{"name": "legacy", "drop": True}]}, + {"fields": [wanted["description"]]}, + ] + + +def test_reconcile_changes_parents_before_children(): + """Typesense rejects one request that changes an object and its child.""" + registration = _registration( + Field("obj", FieldType.OBJECT), + Field("obj.a", FieldType.INT32, capabilities=Capabilities(filterable=True)), + ) + adapter = _adapter(registration) + collection = _collection(adapter, name="small_v1_g") + collection["fields"] = [ + {**field, "index": False} if field["name"] in ("obj", "obj.a") else field + for field in reversed(collection["fields"]) + ] + transport = FakeTransport([{"collection_name": "small_v1_g"}, collection, {}, {}]) + + _adapter(registration, transport).reconcile() + + assert [request[2]["fields"][0]["name"] for request in transport.requests[2:]] == ["obj", "obj.a"] + + +def test_reconcile_warns_when_hidden_fields_reach_existing_documents(caplog): + """A new companion is empty for documents written before it, until a rebuild.""" + adapter = _adapter() + collection = _collection(adapter, num_documents=3) + collection["fields"] = [field for field in collection["fields"] if field["name"] != "org" + EXACT_SUFFIX] + transport = FakeTransport([{"collection_name": LIVE}, collection, {}]) + + with caplog.at_level(logging.WARNING, logger="openedx_search.typesense"): + assert _adapter(transport=transport).reconcile().changed is True + + assert "gained org__exact" in caplog.text + + +def test_reconcile_adds_hidden_fields_quietly_to_an_empty_collection(caplog): + """Nothing needs rewriting when the collection holds no documents.""" + adapter = _adapter() + collection = _collection(adapter, num_documents=0) + collection["fields"] = [field for field in collection["fields"] if field["name"] != INDEX_FIELD] + transport = FakeTransport([{"collection_name": LIVE}, collection, {}]) + + with caplog.at_level(logging.WARNING, logger="openedx_search.typesense"): + _adapter(transport=transport).reconcile() + + assert not caplog.text + + +def test_reconcile_leaves_another_schema_version_alone(caplog): + """During a migration the old index keeps serving readers until the rebuild commits.""" + transport = FakeTransport([{"collection_name": "studio_content_v2_abc"}]) + + with caplog.at_level(logging.WARNING, logger="openedx_search.typesense"): + result = _adapter(transport=transport).reconcile() + + assert result.changed is False + assert transport.paths() == [("GET", "/aliases/studio_content")] + assert "serves schema version 2" in caplog.text + + +def test_reconcile_rejects_an_alias_it_did_not_create(): + """A collection name without the index and version prefix is not ours to patch.""" + transport = FakeTransport([{"collection_name": "hand_made"}]) + + with pytest.raises(AdapterError, match="did not create"): + _adapter(transport=transport).reconcile() + + +def test_reconcile_refuses_to_change_nested_fields(): + """``enable_nested_fields`` is fixed when a collection is created.""" + adapter = _adapter() + transport = FakeTransport([{"collection_name": LIVE}, _collection(adapter, enable_nested_fields=False)]) + + with pytest.raises(AdapterError, match="rebuild the index"): + _adapter(transport=transport).reconcile() + + +def test_reconcile_rejects_an_alias_to_a_missing_collection(): + """A dangling alias needs a person, not a new collection.""" + transport = FakeTransport([{"collection_name": LIVE}, _missing()]) + + with pytest.raises(AdapterError, match="missing collection"): + _adapter(transport=transport).reconcile() + + +def test_reconcile_refuses_a_collection_named_like_the_index(): + """Typesense cannot create an alias whose name a collection already uses.""" + transport = FakeTransport([_missing(), {"name": "studio_content", "fields": []}]) + + with pytest.raises(AdapterError, match="without an alias"): + _adapter(transport=transport).reconcile() + + +@pytest.mark.parametrize("response", [{"name": "x"}, []]) +def test_reconcile_rejects_an_invalid_alias(response): + """An alias without a collection name is not usable.""" + with pytest.raises(AdapterError, match="invalid alias"): + _adapter(transport=FakeTransport([response])).reconcile() + + +@pytest.mark.parametrize( + "collection, message", + [ + ([], "invalid collection description"), + ({"enable_nested_fields": True, "fields": None}, "invalid collection fields"), + ({"enable_nested_fields": True, "fields": [{"type": "string"}]}, "invalid collection field"), + ], +) +def test_reconcile_rejects_an_invalid_collection(collection, message): + """A collection description the adapter cannot read is an error.""" + transport = FakeTransport([{"collection_name": LIVE}, collection]) + + with pytest.raises(AdapterError, match=message): + _adapter(transport=transport).reconcile() + + +@pytest.mark.parametrize("call", ["alias", "collection"]) +def test_reconcile_propagates_transport_failures(call): + """Only a 404 means missing; any other failure surfaces.""" + failure = TransportError("engine returned HTTP 503", status=503) + responses = [failure] if call == "alias" else [_missing(), failure] + + with pytest.raises(TransportError): + _adapter(transport=FakeTransport(responses)).reconcile() + + +def test_begin_rebuild_removes_leftovers_and_creates_the_target(): + """Old targets of this version go; anything an alias points at stays.""" + target = RebuildTarget("studio_content", 1, "new") + transport = FakeTransport( + [ + { + "aliases": [ + {"name": "studio_content", "collection_name": LIVE}, + # Another index whose name extends this index's prefix. + {"name": "studio_content_v1_x", "collection_name": "studio_content_v1_x_v1_g"}, + {"name": "broken"}, + ] + }, + [ + {"name": LIVE}, + {"name": "studio_content_v1_x_v1_g"}, + {"name": "studio_content_v1_crashed"}, + {"name": "studio_content_v1_gone"}, + {"name": "studio_content_v2_other"}, + {"name": "unrelated"}, + {"num_documents": 3}, + ], + {}, + _missing(), + {}, + ] + ) + adapter = _adapter(transport=transport) + + adapter.begin_rebuild(target) + + assert transport.paths() == [ + ("GET", "/aliases"), + ("GET", "/collections?exclude_fields=fields"), + ("DELETE", "/collections/studio_content_v1_crashed"), + ("DELETE", "/collections/studio_content_v1_gone"), + ("POST", "/collections"), + ] + assert transport.requests[-1][2] == adapter.collection_schema("studio_content_v1_new") + + +@pytest.mark.parametrize( + "responses, message", + [ + ([[]], "invalid alias list"), + ([{"aliases": []}, {"collections": []}], "invalid collection list"), + ], +) +def test_begin_rebuild_rejects_invalid_listings(responses, message): + """The alias and collection listings must have the documented shape.""" + with pytest.raises(AdapterError, match=message): + _adapter(transport=FakeTransport(responses)).begin_rebuild(RebuildTarget("studio_content", 1, "new")) + + +def test_commit_rebuild_points_the_alias_and_deletes_the_old_collection(): + """Readers move to the target in one alias update.""" + target = RebuildTarget("studio_content", 1, "new") + transport = FakeTransport([{"name": target.name}, {"collection_name": LIVE}, {}, _missing()]) + + _adapter(transport=transport).commit_rebuild(target) + + assert transport.paths() == [ + ("GET", "/collections/studio_content_v1_new"), + ("GET", "/aliases/studio_content"), + ("PUT", "/aliases/studio_content"), + ("DELETE", f"/collections/{LIVE}"), + ] + assert transport.requests[2][2] == {"collection_name": "studio_content_v1_new"} + + +def test_commit_rebuild_refuses_a_missing_target(): + """A stale rebuild whose target was cleaned up must not repoint the alias.""" + transport = FakeTransport([_missing()]) + + with pytest.raises(AdapterError, match="does not exist"): + _adapter(transport=transport).commit_rebuild(RebuildTarget("studio_content", 1, "stale")) + + assert transport.paths() == [("GET", "/collections/studio_content_v1_stale")] + + +@pytest.mark.parametrize( + "responses", + [ + [{"name": "t"}, _missing(), _missing(), {}], + [{"name": "t"}, {"collection_name": "studio_content_v1_new"}, {}], + ], +) +def test_commit_rebuild_deletes_nothing_without_another_live_collection(responses): + """A first rebuild, or a retried commit, only points the alias.""" + transport = FakeTransport(responses) + + _adapter(transport=transport).commit_rebuild(RebuildTarget("studio_content", 1, "new")) + + assert transport.paths()[-1] == ("PUT", "/aliases/studio_content") + + +def test_abort_rebuild_deletes_the_target(): + """A failed rebuild discards its target, and a missing one is fine.""" + transport = FakeTransport([{"collection_name": LIVE}, _missing()]) + + _adapter(transport=transport).abort_rebuild(RebuildTarget("studio_content", 1, "new")) + + assert transport.paths()[-1] == ("DELETE", "/collections/studio_content_v1_new") + + +def test_abort_rebuild_keeps_a_target_the_alias_points_at(): + """A commit that failed after repointing the alias left the target live.""" + transport = FakeTransport([{"collection_name": "studio_content_v1_new"}]) + + _adapter(transport=transport).abort_rebuild(RebuildTarget("studio_content", 1, "new")) + + assert transport.paths() == [("GET", "/aliases/studio_content")] + + +def test_abort_rebuild_propagates_a_transport_failure(): + """Only a missing target is ignored.""" + transport = FakeTransport([_missing(), _missing(), TransportError("down")]) + + with pytest.raises(TransportError): + _adapter(transport=transport).abort_rebuild(RebuildTarget("studio_content", 1, "new")) + + +def test_upsert_imports_the_batch_and_returns_a_complete_receipt(): + """Whole documents are replaced, tagged with the index, and every result is checked.""" + transport = FakeTransport([[{"success": True}, {"success": True}]]) + + receipt = _adapter(transport=transport).upsert([{"id": "a"}, {"id": "b"}]) + + assert receipt == WriteReceipt(complete=True) + assert transport.requests == [ + ( + "POST", + "/collections/studio_content/documents/import?action=upsert", + [{"id": "a", INDEX_FIELD: STUDIO_TAG}, {"id": "b", INDEX_FIELD: STUDIO_TAG}], + ) + ] + + +def test_upsert_adds_digest_companions(): + """Scalars, arrays and fields inside object arrays each get their digests.""" + transport = FakeTransport([[{"success": True}]]) + document = { + "id": "a", + "org": "MITx", + "display_name": "Not filterable", + "tags": {"level0": ["Colors", "Colors > Red"]}, + "breadcrumbs": [{"display_name": "Course", "usage_key": "block-v1:x"}], + } + + _adapter(transport=transport).upsert([document]) + + assert transport.requests[0][2] == [ + { + "id": "a", + "org": "MITx", + "org__exact": sha("MITx"), + "display_name": "Not filterable", + "tags": {"level0": ["Colors", "Colors > Red"], "level0__exact": [sha("Colors"), sha("Colors > Red")]}, + "breadcrumbs": [ + {"display_name": "Course", "usage_key": "block-v1:x", "usage_key__exact": sha("block-v1:x")} + ], + INDEX_FIELD: STUDIO_TAG, + } + ] + + +def test_upsert_can_target_a_rebuild(): + """A rebuild batch goes to the target collection, not through the alias.""" + transport = FakeTransport([[{"success": True}]]) + + _adapter(transport=transport).upsert([{"id": "a"}], target=RebuildTarget("studio_content", 1, "new")) + + assert transport.paths() == [ + ("POST", "/collections/studio_content_v1_new/documents/import?action=upsert") + ] + + +def test_upsert_renders_datetimes_as_whole_posix_seconds(): + """Datetimes and float seconds become int64, nested and inside arrays too.""" + registration = _registration( + Field("modified", FieldType.DATETIME), + Field("events", FieldType.OBJECT, array=True), + Field("events.at", FieldType.DATETIME, array=True), + Field("events.label", FieldType.STRING, array=True), + Field("count", FieldType.FLOAT), + ) + transport = FakeTransport([[{"success": True}]]) + document = { + "id": "a", + "modified": MOMENT_SECONDS + 0.9, + "events": [{"at": MOMENT, "label": "x"}, {"at": MOMENT_SECONDS + 1, "label": "y"}], + "count": 1.5, + } + + _adapter(registration, transport).upsert([document]) + + assert transport.requests[0][2] == [ + { + "id": "a", + "modified": MOMENT_SECONDS, + "events": [{"at": MOMENT_SECONDS, "label": "x"}, {"at": MOMENT_SECONDS + 1, "label": "y"}], + "count": 1.5, + INDEX_FIELD: sha("small"), + } + ] + + +def test_upsert_raises_for_rejected_documents(): + """A 200 import with a failed line is a failed write, without echoing the document.""" + transport = FakeTransport( + [ + [ + {"success": True}, + {"success": False, "code": 400, "error": "bad", "document": '{"secret": 1}'}, + "garbage", + ] + ] + ) + + with pytest.raises(WriteFailed) as excinfo: + _adapter(transport=transport).upsert([{"id": "a"}, {"id": "b"}, {"id": "c"}]) + + assert str(excinfo.value) == ( + "Typesense rejected 2 of 3 documents at positions 1 (HTTP 400), 2 (HTTP None)" + ) + + +def test_upsert_requires_one_result_per_document(): + """A short result list means the import cannot be trusted.""" + transport = FakeTransport([[{"success": True}]]) + + with pytest.raises(AdapterError, match="1 import results for 2 documents"): + _adapter(transport=transport).upsert([{"id": "a"}, {"id": "b"}]) + + +def test_delete_by_primary_keys_filters_on_id(): + """Primary keys become one exact-match filter on the implicit id.""" + transport = FakeTransport([{"num_deleted": 1}]) + + receipt = _adapter(transport=transport).delete(["a", "b-c"]) + + assert receipt == WriteReceipt(complete=True) + method, path, body = transport.requests[0] + assert (method, urlsplit(path).path, body) == ("DELETE", "/collections/studio_content/documents", None) + assert _filter_by(path) == "id:=[`a`,`b-c`]" + + +def test_delete_by_primary_keys_is_batched(): + """The ids travel in the query string, so a long list is split.""" + keys = [f"k{position}" for position in range(DELETE_BATCH_SIZE * 2 + 1)] + transport = FakeTransport([{"num_deleted": 0}] * 3) + + _adapter(transport=transport).delete(keys) + + batches = [_filter_by(path) for _, path, _ in transport.requests] + assert [batch.count("`") // 2 for batch in batches] == [DELETE_BATCH_SIZE, DELETE_BATCH_SIZE, 1] + assert batches[2] == f"id:=[`k{DELETE_BATCH_SIZE * 2}`]" + + +def test_delete_by_filter_renders_the_expression(): + """The abstract expression reaches the engine in its own syntax, on a target.""" + transport = FakeTransport([{"num_deleted": 0}]) + expression = (FilterGroup((FilterTerm("org", ("openedx",)),)),) + + _adapter(transport=transport).delete(filter=expression, target=RebuildTarget("studio_content", 1, "new")) + + path = transport.requests[0][1] + assert urlsplit(path).path == "/collections/studio_content_v1_new/documents" + assert _filter_by(path) == f"(org__exact:=[`{sha('openedx')}`])" + + +def test_delete_requires_a_form(): + """A bare delete is refused before any request.""" + with pytest.raises(ValueError, match="primary_keys or filter"): + _adapter().delete() + + +@pytest.mark.parametrize("response", [{}, {"num_deleted": True}, None]) +def test_delete_rejects_an_invalid_response(response): + """The engine must report how many documents it deleted.""" + transport = FakeTransport([response]) + + with pytest.raises(AdapterError, match="invalid delete response"): + _adapter(transport=transport).delete(["a"]) + + +def test_render_filter_keeps_group_and_term_precedence(): + """Terms are ORed inside a group, groups are ANDed, and strings match on digests.""" + expression = ( + FilterGroup((FilterTerm("org", ("openedx", "a, (b) && c")), FilterTerm("access_id", (1, 2)))), + FilterGroup((FilterTerm("published", (True, False)), FilterTerm("score", (1.5,)))), + FilterGroup((FilterTerm("modified", (MOMENT,)), FilterTerm("id", ("x",)))), + ) + + assert _adapter(FILTERABLE).render_filter(expression) == ( + f"(org__exact:=[`{sha('openedx')}`,`{sha('a, (b) && c')}`] || access_id:=[1,2])" + " && (published:=[true,false] || score:=[1.5])" + f" && (modified:=[{MOMENT_SECONDS}] || id:=[`x`])" + ) + + +@pytest.mark.parametrize( + "term, message", + [ + (FilterTerm("missing", ("x",)), "not declared"), + (FilterTerm("title", ("x",)), "not filterable"), + (FilterTerm("org", (1,)), "takes string filter values"), + (FilterTerm("id", ("a`b",)), "backtick"), + ], +) +def test_render_filter_refuses_what_it_cannot_match_exactly(term, message): + """Undeclared, unfilterable and unquotable terms fail before reaching the engine.""" + with pytest.raises(AdapterError, match=message): + _adapter(FILTERABLE).render_filter((FilterGroup((term,)),)) + + +def test_check_write_returns_a_complete_receipt_without_a_request(): + """Typesense writes are complete when they return.""" + transport = FakeTransport() + receipt = WriteReceipt(complete=True) + + assert _adapter(transport=transport).check_write(receipt) is receipt + assert not transport.requests + + +def test_check_write_rejects_an_incomplete_receipt(): + """Only an asynchronous engine issues an incomplete receipt.""" + with pytest.raises(AdapterError, match="not from Typesense"): + _adapter().check_write(WriteReceipt(task_id=3)) + + +def test_search_is_deferred_to_the_query_api(): + """The read side lands with its own contract.""" + with pytest.raises(NotImplementedError, match="query API"): + _adapter().search("anything") + + +def test_mint_credential_matches_the_typesense_reference(monkeypatch): + """The scoped key is byte-identical to the official client's output.""" + monkeypatch.setattr( + "openedx_search.typesense._now", + lambda: datetime(2027, 1, 1, tzinfo=timezone.utc), + ) + transport = FakeTransport() + scope = CredentialScope( + filters=(FilterGroup((FilterTerm("org", ("openedx",)), FilterTerm("access_id", (7,)))),) + ) + adapter = _adapter( + transport=transport, + search_api_key=SEARCH_KEY, + public_url="https://search.example.com", + ) + + credential = adapter.mint_credential(scope, timedelta(days=1)) + + assert credential == SearchCredential( + url="https://search.example.com", + index_name="studio_content", + api_key=SCOPED_KEY, + ) + assert not transport.requests + + +def test_mint_credential_always_binds_the_index(monkeypatch): + """An empty scope still filters on the index tag; the connection URL is the fallback.""" + monkeypatch.setattr("openedx_search.typesense._now", lambda: MOMENT) + adapter = _adapter(_registration(Field("title", FieldType.STRING)), search_api_key=SEARCH_KEY) + + credential = adapter.mint_credential(CredentialScope(), timedelta(seconds=60)) + + assert _embedded(credential.api_key) == { + "expires_at": MOMENT_SECONDS + 60, + "filter_by": f"{INDEX_FIELD}:=[`{sha('small')}`]", + } + assert credential.url == "http://engine:8108" + + +def test_mint_credential_expires_after_the_requested_lifetime(): + """The embedded expiry is the current time plus ``expires_in``.""" + before = int(datetime.now(timezone.utc).timestamp()) + adapter = _adapter(_registration(Field("title", FieldType.STRING)), search_api_key=SEARCH_KEY) + + credential = adapter.mint_credential(CredentialScope(), timedelta(hours=1)) + + assert before + 3600 <= _embedded(credential.api_key)["expires_at"] <= before + 3601 + + +def test_mint_credential_requires_a_search_key(): + """Typesense refuses a scoped key derived from the write key.""" + with pytest.raises(AdapterError, match="search_api_key"): + _adapter().mint_credential(CredentialScope(), timedelta(minutes=5)) + + +def test_register_resolves_the_adapter(): + """Registering the engine lets the library resolve it from settings.""" + register() + with override_settings( + OPENEDX_SEARCH_BACKENDS={ + "default": { + "engine": "typesense", + "url": "http://engine:8108", + "api_key": "secret", + "search_api_key": SEARCH_KEY, + } + }, + OPENEDX_SEARCH_DEFAULT_BACKEND="default", + ): + adapter = get_adapter(STUDIO_COURSE) + + assert isinstance(adapter, TypesenseAdapter) + assert adapter.backend.engine == "typesense"