17 Commits
Author SHA1 Message Date
zemion 0f9d760bb0 Release v0.1.18
Module Package Release / publish-packages (push) Successful in 12s
2026-08-05 21:07:52 +02:00
zemion 016869aba0 Release v0.1.17
Module Package Release / publish-packages (push) Successful in 12s
2026-08-05 20:34:13 +02:00
zemion 101dc3814c Release v0.1.16
Module Package Release / publish-packages (push) Successful in 12s
2026-08-05 19:52:32 +02:00
zemion 3442b5fa4e refactor: open search from titlebar command 2026-08-05 00:03:33 +02:00
zemion e910a53def Release v0.1.15
Module Package Release / publish-packages (push) Successful in 11s
2026-08-04 15:18:13 +02:00
zemion c62f1d7a8b Make package publication retries hash-safe 2026-08-04 14:32:20 +02:00
zemion 381c206f31 Harden module package publication 2026-08-04 14:02:41 +02:00
zemion 6735e2077f Add protected package release workflow 2026-08-04 04:14:07 +02:00
zemion 1bb338117f Complete permission-aware native search indexing 2026-08-04 03:05:03 +02:00
zemion 912db10a8a docs: declare institutional architecture boundary 2026-08-01 17:48:39 +02:00
zemion 839d594331 Align Search WebUI runtime dependencies 2026-07-31 02:48:57 +02:00
zemion e6bb9d359f feat: present global search in an anchored overlay 2026-07-30 14:27:10 +02:00
zemion bed704eb7a feat(search): add global titlebar search filters 2026-07-29 22:01:18 +02:00
zemion 6fcd9e0e65 Test Search against PostgreSQL 2026-07-29 20:37:08 +02:00
zemion a156e3d4fc feat: implement durable permission-aware search 2026-07-29 18:08:52 +02:00
zemion c60ca2776e feat: implement permission-aware search baseline 2026-07-29 15:50:11 +02:00
zemion 89a4fd0874 Release v0.1.8 2026-07-11 16:49:04 +02:00
35 changed files with 6945 additions and 0 deletions
+270
View File
@@ -0,0 +1,270 @@
name: Module Package Release
on:
push:
tags:
- "v*"
workflow_dispatch:
inputs:
release_tag:
description: Existing protected version tag to publish
required: true
type: string
jobs:
publish-packages:
runs-on: ubuntu-latest
env:
GITEA_REPOSITORY: ${{ gitea.repository }}
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
with:
fetch-depth: 0
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065
with:
python-version: "3.12"
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
with:
node-version: "22"
- name: Select and validate protected release tag
shell: bash
env:
REQUESTED_TAG: ${{ inputs.release_tag }}
TRIGGER_TAG: ${{ gitea.ref_name }}
run: |
set -euo pipefail
tag="${REQUESTED_TAG:-$TRIGGER_TAG}"
case "$tag" in
v[0-9]*.[0-9]*.[0-9]*) ;;
*) echo "Release tag must start with a SemVer-shaped vX.Y.Z value" >&2; exit 1 ;;
esac
git fetch --force origin "refs/tags/$tag:refs/tags/$tag" refs/heads/main:refs/remotes/origin/main
tag_commit="$(git rev-list -n 1 "$tag")"
git merge-base --is-ancestor "$tag_commit" refs/remotes/origin/main || {
echo "Release tag is not contained in main" >&2
exit 1
}
git checkout --detach "$tag"
printf 'RELEASE_TAG=%s\n' "$tag" >> "$GITEA_ENV"
printf 'SOURCE_DATE_EPOCH=%s\n' "$(git show -s --format=%ct HEAD)" >> "$GITEA_ENV"
- name: Validate package versions
run: |
python - <<'PY'
import json
from pathlib import Path
import os
import re
import tomllib
tag = os.environ["RELEASE_TAG"]
expected = tag.removeprefix("v")
project = tomllib.loads(Path("pyproject.toml").read_text(encoding="utf-8"))["project"]
if project.get("version") != expected:
raise SystemExit(f"pyproject version {project.get('version')!r} does not match {tag}")
if re.fullmatch(r"govoplan-[a-z0-9-]+", str(project.get("name", ""))) is None:
raise SystemExit("Python distribution name must use the govoplan-* namespace")
webui = Path("webui/package.json")
if webui.is_file():
package = json.loads(webui.read_text(encoding="utf-8"))
if package.get("version") != expected:
raise SystemExit(f"WebUI version {package.get('version')!r} does not match {tag}")
if re.fullmatch(r"@govoplan/[a-z0-9-]+-webui", str(package.get("name", ""))) is None:
raise SystemExit("WebUI package name must use the @govoplan/*-webui namespace")
release = Path("webui/package.release.json")
if release.is_file():
release_package = json.loads(release.read_text(encoding="utf-8"))
if (
release_package.get("name") != package.get("name")
or release_package.get("version") != expected
):
raise SystemExit("WebUI release package identity does not match package.json and the release tag")
PY
- name: Build immutable package artifacts
shell: bash
run: |
set -euo pipefail
python -m pip install --disable-pip-version-check build==1.5.0 twine==7.0.0
rm -rf dist .package-webui
python -m build --wheel --outdir dist
python -m twine check dist/*.whl
if [[ -f webui/package.json ]]; then
mkdir .package-webui
cp -a webui/. .package-webui/
rm -rf .package-webui/node_modules .package-webui/dist
if [[ -f .package-webui/package.release.json ]]; then
cp .package-webui/package.release.json .package-webui/package.json
fi
node <<'NODE'
const fs = require("node:fs");
const path = ".package-webui/package.json";
const packageJson = JSON.parse(fs.readFileSync(path, "utf8"));
const groups = ["dependencies", "optionalDependencies", "peerDependencies"];
for (const group of groups) {
for (const [name, specifier] of Object.entries(packageJson[group] || {})) {
if (!name.startsWith("@govoplan/")) continue;
if (typeof specifier !== "string") {
throw new Error(`${group}.${name} must use a string version`);
}
const packageSlug = name.slice("@govoplan/".length);
if (!packageSlug.endsWith("-webui")) {
throw new Error(`${group}.${name} is outside the WebUI package namespace`);
}
const repository = `govoplan-${packageSlug.slice(0, -"-webui".length)}`;
const escapedRepository = repository.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const gitTag = specifier.match(
new RegExp(
`^git\\+(?:ssh://git@|https://)git\\.add-ideas\\.de/(?:GovOPlaN|add-ideas)/${escapedRepository}\\.git#v([0-9]+\\.[0-9]+\\.[0-9]+)$`,
),
);
if (gitTag) {
packageJson[group][name] = gitTag[1];
continue;
}
if (specifier.startsWith("file:") || specifier.startsWith("git+")) {
throw new Error(
`${group}.${name} must resolve to an exact registry version for publication`,
);
}
}
}
delete packageJson.private;
fs.writeFileSync(path, `${JSON.stringify(packageJson, null, 2)}\n`);
NODE
npm pkg delete private --prefix .package-webui
(cd .package-webui && npm pack --ignore-scripts --pack-destination ../dist)
fi
python - <<'PY'
import hashlib
import json
from pathlib import Path
import os
import subprocess
artifacts = []
for path in sorted(Path("dist").iterdir()):
if path.suffix not in {".whl", ".tgz"}:
continue
digest = hashlib.sha256(path.read_bytes()).hexdigest()
artifacts.append({"filename": path.name, "sha256": digest, "size": path.stat().st_size})
payload = {
"schema_version": "1",
"repository": os.environ["GITEA_REPOSITORY"],
"tag": os.environ["RELEASE_TAG"],
"commit": subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(),
"artifacts": artifacts,
}
Path("dist/package-artifacts.json").write_text(
json.dumps(payload, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
)
PY
- name: Retain package hash evidence
uses: actions/upload-artifact@a8a3f3ad30e3422c9c7b888a15615d19a852ae32
with:
name: module-packages-${{ gitea.ref_name }}
path: dist/package-artifacts.json
- name: Check immutable registry state
shell: bash
env:
PACKAGE_TOKEN: ${{ secrets.GOVOPLAN_PACKAGE_TOKEN }}
run: |
set -euo pipefail
test -n "$PACKAGE_TOKEN"
python - <<'PY'
import hashlib
import json
import os
from pathlib import Path
import tomllib
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.request import Request, urlopen
api_root = "https://git.add-ideas.de/api/v1/packages/GovOPlaN"
token = os.environ["PACKAGE_TOKEN"]
def should_publish(kind, name, version, path):
package_url = "/".join(
(api_root, kind, quote(name, safe=""), quote(version, safe=""), "files")
)
request = Request(
package_url,
headers={"Accept": "application/json", "Authorization": f"token {token}"},
)
try:
with urlopen(request, timeout=30) as response:
files = json.load(response)
except HTTPError as exc:
if exc.code == 404:
print(f"{kind} package {name}=={version} is not published yet")
return True
raise
if not isinstance(files, list) or len(files) != 1:
raise SystemExit(
f"immutable {kind} package {name}=={version} has an unexpected file set"
)
expected_sha256 = hashlib.sha256(path.read_bytes()).hexdigest()
if files[0].get("sha256") != expected_sha256:
raise SystemExit(
f"immutable {kind} package {name}=={version} already exists with a different SHA-256"
)
print(f"verified existing {kind} package {name}=={version} ({expected_sha256})")
return False
project = tomllib.loads(Path("pyproject.toml").read_text(encoding="utf-8"))["project"]
wheels = tuple(Path("dist").glob("*.whl"))
if len(wheels) != 1:
raise SystemExit("release build must contain exactly one wheel")
publish_pypi = should_publish(
"pypi", str(project["name"]), str(project["version"]), wheels[0]
)
tarballs = tuple(Path("dist").glob("*.tgz"))
if len(tarballs) > 1:
raise SystemExit("release build must contain at most one npm package")
publish_npm = False
if tarballs:
webui = json.loads(
Path(".package-webui/package.json").read_text(encoding="utf-8")
)
publish_npm = should_publish(
"npm", str(webui["name"]), str(webui["version"]), tarballs[0]
)
with Path(os.environ["GITEA_ENV"]).open("a", encoding="utf-8") as env_file:
env_file.write(f"PUBLISH_PYPI={int(publish_pypi)}\n")
env_file.write(f"PUBLISH_NPM={int(publish_npm)}\n")
PY
- name: Publish wheel and WebUI package
shell: bash
env:
PACKAGE_USERNAME: ${{ secrets.GOVOPLAN_PACKAGE_USERNAME }}
PACKAGE_TOKEN: ${{ secrets.GOVOPLAN_PACKAGE_TOKEN }}
run: |
set -euo pipefail
test -n "$PACKAGE_USERNAME"
test -n "$PACKAGE_TOKEN"
if [[ "$PUBLISH_PYPI" == 1 ]]; then
TWINE_USERNAME="$PACKAGE_USERNAME" TWINE_PASSWORD="$PACKAGE_TOKEN" \
python -m twine upload --non-interactive \
--repository-url https://git.add-ideas.de/api/packages/GovOPlaN/pypi \
dist/*.whl
else
echo "Exact wheel is already present; skipping immutable retry."
fi
shopt -s nullglob
webui_packages=(dist/*.tgz)
if (( ${#webui_packages[@]} )) && [[ "$PUBLISH_NPM" == 1 ]]; then
npmrc="$(mktemp)"
trap 'rm -f "$npmrc"' EXIT
chmod 600 "$npmrc"
printf '%s\n' \
'@govoplan:registry=https://git.add-ideas.de/api/packages/GovOPlaN/npm/' \
"//git.add-ideas.de/api/packages/GovOPlaN/npm/:_authToken=$PACKAGE_TOKEN" \
> "$npmrc"
NPM_CONFIG_USERCONFIG="$npmrc" npm publish "./${webui_packages[0]}" \
--ignore-scripts --access public \
--registry https://git.add-ideas.de/api/packages/GovOPlaN/npm/
elif (( ${#webui_packages[@]} )); then
echo "Exact WebUI package is already present; skipping immutable retry."
fi
+21
View File
@@ -0,0 +1,21 @@
# govoplan-search Codex Guide
## Documentation Contract
- Treat documentation as part of every behavior change. Update this module's manifest-driven `DocumentationTopic` contributions for affected user and administrator behavior.
- Keep feature content here; `govoplan-docs` projects it without importing Search internals.
- Maintain a static user/admin baseline and run `/mnt/DATA/git/govoplan/tools/checks/check-manifest-shapes.py` after behavior or manifest changes.
## Scope
This module owns global and contextual search aggregation, the built-in
PostgreSQL/SQLite index, indexing lifecycle, search diagnostics, and the search
WebUI. Source modules own object authorization and the content they announce.
Optional backends such as OpenSearch belong behind provider contracts.
## Rules
- Never return a result before tenant and current-principal ACL filtering.
- Do not import optional source modules.
- Keep external search engines optional.
- Never index credentials, secrets, or unrestricted raw payloads.
+235
View File
@@ -0,0 +1,235 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
govoplan-core
Copyright (C) 2026 add-ideas
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
+57
View File
@@ -0,0 +1,57 @@
# govoplan-search
<!-- govoplan-repository-type:start -->
**Repository type:** module (platform).
<!-- govoplan-repository-type:end -->
Permission-aware global and contextual search for GovOPlaN. Search is the first
command in the titlebar action group. Clicking its icon, pressing `F3`, or
pressing `Ctrl`/`Cmd`+`K` opens the same full query field and result overlay.
The titlebar command, result overlay, filters, and Search administration route
announce stable help contexts. Pressing `F1` while one of those controls is
focused opens its Search documentation, with the current page retained as a
fallback.
The route, overlay, state, accessibility, and consequence mapping is recorded in
[`docs/INTERFACE_PATTERN_MIGRATION.md`](docs/INTERFACE_PATTERN_MIGRATION.md).
The module works with its built-in database index and no external search
service. PostgreSQL uses native full-text search; SQLite provides a bounded
development fallback. Other modules may:
- register a live search provider in their module manifest
- write authorized documents through the `search.index_writer` capability
- announce context-sensitive WebUI search scopes through `search.contexts`
An optional OpenSearch adapter is a later provider, not a hard dependency.
Source modules remain responsible for defining visibility and authorization.
## Index lifecycle
Source modules register a versioned `search_sources` provider. A provider
declares its resource types and index version, returns bounded resumable
backfill pages, and batch-rechecks current authorization for sensitive
resources. A source may additionally implement the event-source extension to
translate committed platform events into `SearchIndexChange` records. The
platform event worker queues those records idempotently and applies them to the
derived index; Search never imports a source module or invents its ACL. Direct
capability callers may still use `search.index_writer.enqueue_change()` when
they already own a suitable transactional boundary.
The built-in backend exposes opaque cursor pagination and does not return
pre-authorization totals. PostgreSQL uses full-text search and will add
trigram indexes when `pg_trgm` is already installed; SQLite remains a bounded
development fallback.
Tenant search administrators can use **Administration > Search index** or the
equivalent `/api/v1/search/admin/*` endpoints to inspect source coverage,
reconcile disabled modules, process queued changes, and start or continue
bounded provider rebuilds. Quarantined changes and provider errors stay
visible. Rows requiring a source authorization recheck are omitted when their
provider is unavailable, stale, or fails to return an explicit allow decision.
Files, Campaign, Calendar, Mail, IDM, and Postbox provide native source
adapters. Mail indexes only its bounded read-only cache, and Postbox never
indexes ciphertext or key material. All six recheck current source-owned
authorization when results are returned.
+28
View File
@@ -0,0 +1,28 @@
# Search Interface Pattern Migration
This is the bounded interface-pattern evidence for GovOPlaN Search. Search owns
presentation and aggregation; source modules continue to own result data and
authorization, and optional external engines remain provider capabilities.
| Surface | Task and archetype | Consequence and state contract |
| --- | --- | --- |
| Title-bar Search command and overlay | Global or context-sensitive focused lookup | The left-most titlebar command, F3, and Ctrl/Cmd+K open the same focus-contained Core dialog with a full-width query field. Arrow keys move through the listbox, Enter opens the selected result, Escape closes it and restores focus. |
| Overlay filters | Progressive-disclosure filter popover | Module and resource filters only narrow authorized results. Active filters stay visible and removable by keyboard. |
| `/search` | Full-page search/results fallback | Query and filters are URL-stable. Loading, empty, provider-partial, failed, and paged states remain inside the result region. |
| Result entries | Permission-filtered list-detail destinations | A source module supplies the title, safe summary, breadcrumbs, and destination. Search does not infer or bypass source authorization. |
| Administration > Search index | Operator table and bounded recovery actions | Operators inspect source coverage and queue health, process pending changes, reconcile module activation, and advance one bounded rebuild page at a time. Quarantined work remains visible. |
All surfaces use Core buttons, icon buttons, dialog, alerts, loading, scrolling,
and documentation-help primitives. Provider diagnostics are partial-state
evidence: safe results remain usable and a failing provider is identified
without exposing source data. Search has no destructive action. The responsive
layout collapses filters and results at narrow widths, and result activation is
available without pointer interaction.
Verification:
- `npm run test:search-overlay`
- `npm run test:interface-pattern`
- the Core TypeScript graph, structural localization audit, theme check, module
permutations, and full-product bundle budget
- Search backend and manifest tests
+33
View File
@@ -0,0 +1,33 @@
{
"name": "@govoplan/search-webui",
"version": "0.1.18",
"private": true,
"type": "module",
"main": "webui/src/index.ts",
"module": "webui/src/index.ts",
"types": "webui/src/index.ts",
"exports": {
".": {
"types": "./webui/src/index.ts",
"import": "./webui/src/index.ts"
},
"./styles/search.css": "./webui/src/styles/search.css"
},
"files": [
"webui/src",
"README.md",
"LICENSE"
],
"peerDependencies": {
"@govoplan/core-webui": "^0.1.18",
"lucide-react": "^1.23.0",
"react": ">=19.2.7 <20",
"react-dom": ">=19.2.7 <20",
"react-router": ">=8.3.0 <9"
},
"peerDependenciesMeta": {
"@govoplan/core-webui": {
"optional": true
}
}
}
+22
View File
@@ -0,0 +1,22 @@
[build-system]
requires = ["setuptools>=69", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "govoplan-search"
version = "0.1.18"
description = "Permission-aware global and contextual search for GovOPlaN."
readme = "README.md"
requires-python = ">=3.12"
license = "AGPL-3.0-or-later"
authors = [{ name = "GovOPlaN" }]
dependencies = ["govoplan-core>=0.1.18"]
[tool.setuptools.packages.find]
where = ["src"]
[tool.setuptools.package-data]
govoplan_search = ["py.typed"]
[project.entry-points."govoplan.modules"]
search = "govoplan_search.backend.manifest:get_manifest"
+3
View File
@@ -0,0 +1,3 @@
"""GovOPlaN search module."""
__version__ = "0.1.18"
+1
View File
@@ -0,0 +1 @@
"""Search backend."""
@@ -0,0 +1 @@
"""Search persistence."""
+355
View File
@@ -0,0 +1,355 @@
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Any
from sqlalchemy import (
Boolean,
DateTime,
ForeignKey,
Index,
Integer,
JSON,
String,
Text,
UniqueConstraint,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from govoplan_core.db.base import Base, TimestampMixin, utcnow
def new_uuid() -> str:
return str(uuid.uuid4())
class SearchIndexDocument(Base, TimestampMixin):
__tablename__ = "search_index_documents"
__table_args__ = (
UniqueConstraint(
"tenant_id",
"module_id",
"resource_type",
"resource_id",
name="uq_search_document_resource",
),
Index(
"ix_search_document_scope",
"tenant_id",
"module_id",
"resource_type",
),
Index("ix_search_document_visibility", "tenant_id", "visibility"),
Index(
"ix_search_document_provider",
"tenant_id",
"provider_id",
"resource_type",
"active",
),
)
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=new_uuid)
tenant_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
module_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
provider_id: Mapped[str] = mapped_column(
String(200),
nullable=False,
index=True,
)
resource_type: Mapped[str] = mapped_column(
String(100), nullable=False, index=True
)
resource_id: Mapped[str] = mapped_column(
String(255), nullable=False, index=True
)
title: Mapped[str] = mapped_column(String(500), nullable=False)
summary: Mapped[str | None] = mapped_column(Text, nullable=True)
body: Mapped[str | None] = mapped_column(Text, nullable=True)
keywords: Mapped[list[str]] = mapped_column(JSON, default=list, nullable=False)
search_text: Mapped[str] = mapped_column(Text, nullable=False)
url: Mapped[str] = mapped_column(String(1500), nullable=False)
visibility: Mapped[str] = mapped_column(
String(20), default="restricted", nullable=False
)
external_reference: Mapped[dict[str, Any] | None] = mapped_column(
JSON, nullable=True
)
metadata_: Mapped[dict[str, Any]] = mapped_column(
"metadata", JSON, default=dict, nullable=False
)
content_hash: Mapped[str] = mapped_column(String(64), nullable=False)
source_revision: Mapped[str] = mapped_column(
String(255),
nullable=False,
)
change_cursor: Mapped[str | None] = mapped_column(
String(500),
nullable=True,
)
source_updated_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True),
nullable=True,
)
language: Mapped[str] = mapped_column(
String(32),
default="simple",
nullable=False,
)
index_version: Mapped[int] = mapped_column(
Integer,
default=1,
nullable=False,
)
requires_authorization_recheck: Mapped[bool] = mapped_column(
Boolean,
default=False,
nullable=False,
)
rebuild_id: Mapped[str | None] = mapped_column(
String(36),
nullable=True,
index=True,
)
active: Mapped[bool] = mapped_column(
Boolean,
default=True,
nullable=False,
index=True,
)
indexed_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False
)
acl_tokens: Mapped[list["SearchIndexAclToken"]] = relationship(
back_populates="document",
cascade="all, delete-orphan",
)
class SearchIndexAclToken(Base):
__tablename__ = "search_index_acl_tokens"
__table_args__ = (
UniqueConstraint(
"document_id",
"token",
name="uq_search_index_acl_document_token",
),
Index("ix_search_index_acl_token", "token", "document_id"),
)
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=new_uuid)
document_id: Mapped[str] = mapped_column(
ForeignKey("search_index_documents.id", ondelete="CASCADE"),
nullable=False,
index=True,
)
token: Mapped[str] = mapped_column(String(500), nullable=False, index=True)
document: Mapped[SearchIndexDocument] = relationship(
back_populates="acl_tokens"
)
class SearchIndexState(Base, TimestampMixin):
__tablename__ = "search_index_states"
__table_args__ = (
UniqueConstraint(
"tenant_id",
"provider_id",
"resource_type",
name="uq_search_index_state_source",
),
Index(
"ix_search_index_state_status",
"tenant_id",
"status",
),
)
id: Mapped[str] = mapped_column(
String(36),
primary_key=True,
default=new_uuid,
)
tenant_id: Mapped[str] = mapped_column(
String(36),
nullable=False,
index=True,
)
provider_id: Mapped[str] = mapped_column(
String(200),
nullable=False,
index=True,
)
module_id: Mapped[str] = mapped_column(
String(100),
nullable=False,
index=True,
)
resource_type: Mapped[str] = mapped_column(
String(100),
nullable=False,
index=True,
)
index_version: Mapped[int] = mapped_column(
Integer,
default=1,
nullable=False,
)
status: Mapped[str] = mapped_column(
String(30),
default="idle",
nullable=False,
index=True,
)
rebuild_id: Mapped[str | None] = mapped_column(
String(36),
nullable=True,
)
checkpoint_cursor: Mapped[str | None] = mapped_column(
String(500),
nullable=True,
)
high_watermark: Mapped[str | None] = mapped_column(
String(500),
nullable=True,
)
last_change_cursor: Mapped[str | None] = mapped_column(
String(500),
nullable=True,
)
indexed_documents: Mapped[int] = mapped_column(
Integer,
default=0,
nullable=False,
)
rejected_documents: Mapped[int] = mapped_column(
Integer,
default=0,
nullable=False,
)
rebuild_started_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True),
nullable=True,
)
rebuild_completed_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True),
nullable=True,
)
last_success_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True),
nullable=True,
)
last_error: Mapped[str | None] = mapped_column(Text, nullable=True)
class SearchIndexChangeQueue(Base, TimestampMixin):
__tablename__ = "search_index_change_queue"
__table_args__ = (
UniqueConstraint(
"change_id",
name="uq_search_index_change_queue_change",
),
Index(
"ix_search_index_change_queue_pending",
"status",
"available_at",
"created_at",
),
Index(
"ix_search_index_change_queue_source",
"tenant_id",
"provider_id",
"resource_type",
),
)
id: Mapped[str] = mapped_column(
String(36),
primary_key=True,
default=new_uuid,
)
change_id: Mapped[str] = mapped_column(
String(255),
nullable=False,
index=True,
)
tenant_id: Mapped[str] = mapped_column(
String(36),
nullable=False,
index=True,
)
provider_id: Mapped[str] = mapped_column(
String(200),
nullable=False,
index=True,
)
module_id: Mapped[str] = mapped_column(
String(100),
nullable=False,
index=True,
)
resource_type: Mapped[str] = mapped_column(
String(100),
nullable=False,
index=True,
)
resource_id: Mapped[str] = mapped_column(
String(255),
nullable=False,
index=True,
)
kind: Mapped[str] = mapped_column(
String(20),
nullable=False,
)
source_revision: Mapped[str] = mapped_column(
String(255),
nullable=False,
)
source_cursor: Mapped[str] = mapped_column(
String(500),
nullable=False,
)
document_: Mapped[dict[str, Any] | None] = mapped_column(
"document",
JSON,
nullable=True,
)
occurred_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True),
nullable=True,
)
status: Mapped[str] = mapped_column(
String(30),
default="queued",
nullable=False,
index=True,
)
attempts: Mapped[int] = mapped_column(
Integer,
default=0,
nullable=False,
)
available_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
default=utcnow,
nullable=False,
index=True,
)
processed_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True),
nullable=True,
)
error: Mapped[str | None] = mapped_column(Text, nullable=True)
__all__ = [
"SearchIndexAclToken",
"SearchIndexChangeQueue",
"SearchIndexDocument",
"SearchIndexState",
"new_uuid",
]
+274
View File
@@ -0,0 +1,274 @@
from __future__ import annotations
from pathlib import Path
from govoplan_core.core.access import (
CAPABILITY_AUTH_PERMISSION_EVALUATOR,
CAPABILITY_AUTH_PRINCIPAL_RESOLVER,
)
from govoplan_core.core.module_guards import (
drop_table_retirement_provider,
persistent_table_uninstall_guard,
)
from govoplan_core.core.modules import (
DocumentationLink,
DocumentationTopic,
FrontendModule,
FrontendRoute,
MigrationSpec,
ModuleContext,
ModuleInterfaceProvider,
ModuleManifest,
PermissionDefinition,
RoleTemplate,
)
from govoplan_core.core.provider_governance import declared_module_architecture
from govoplan_core.core.search import (
CAPABILITY_SEARCH_INDEX_WRITER,
SearchProviderRegistration,
)
from govoplan_core.core.views import ViewSurface
from govoplan_core.db.base import Base
from govoplan_search.backend.db import models as search_models
MODULE_ID = "search"
MODULE_NAME = "Search"
MODULE_VERSION = "0.1.18"
READ_SCOPE = "search:result:read"
INDEX_SCOPE = "search:index:write"
ADMIN_SCOPE = "search:index:admin"
def _permission(scope: str, label: str, description: str) -> PermissionDefinition:
module_id, resource, action = scope.split(":", 2)
return PermissionDefinition(
scope=scope,
label=label,
description=description,
category="Search",
level="tenant",
module_id=module_id,
resource=resource,
action=action,
)
PERMISSIONS = (
_permission(
READ_SCOPE,
"Search available content",
"Search content the current principal is authorized to read.",
),
_permission(
INDEX_SCOPE,
"Write search index entries",
"Publish and remove module-owned entries in the search index.",
),
_permission(
ADMIN_SCOPE,
"Administer search index",
"Inspect providers and rebuild tenant search indexes.",
),
)
ROLE_TEMPLATES = (
RoleTemplate(
slug="search_user",
name="Search user",
description="Search content available to the current account.",
permissions=(READ_SCOPE,),
default_authenticated=True,
),
RoleTemplate(
slug="search_manager",
name="Search manager",
description="Search content and administer indexing.",
permissions=(READ_SCOPE, INDEX_SCOPE, ADMIN_SCOPE),
),
)
def _service(context: ModuleContext):
from govoplan_search.backend.service import SearchIndexService
return SearchIndexService(context.registry)
def _router(_context: ModuleContext):
from govoplan_search.backend.router import router
return router
manifest = ModuleManifest(
id=MODULE_ID,
name=MODULE_NAME,
version=MODULE_VERSION,
optional_dependencies=(
"access",
"views",
"connectors",
"wiki",
"projects",
"tickets",
"cases",
),
required_capabilities=(
CAPABILITY_AUTH_PRINCIPAL_RESOLVER,
CAPABILITY_AUTH_PERMISSION_EVALUATOR,
),
provides_interfaces=(
ModuleInterfaceProvider(name="search.provider", version="1.0.0"),
ModuleInterfaceProvider(name="search.index_writer", version="1.1.0"),
ModuleInterfaceProvider(name="search.source", version="1.0.0"),
),
permissions=PERMISSIONS,
role_templates=ROLE_TEMPLATES,
route_factory=_router,
frontend=FrontendModule(
module_id=MODULE_ID,
package_name="@govoplan/search-webui",
routes=(
FrontendRoute(
path="/search",
component="SearchPage",
required_any=(READ_SCOPE,),
order=12,
),
),
view_surfaces=(
ViewSurface(
id="search.global",
module_id=MODULE_ID,
kind="selector",
label="Global search",
description="Search entry in the title bar.",
order=10,
),
ViewSurface(
id="search.results",
module_id=MODULE_ID,
kind="route",
label="Search results",
order=20,
),
ViewSurface(
id="search.admin.index",
module_id=MODULE_ID,
kind="section",
label="Search index administration",
order=30,
),
),
),
migration_spec=MigrationSpec(
module_id=MODULE_ID,
metadata=Base.metadata,
script_location=str(Path(__file__).with_name("migrations") / "versions"),
retirement_supported=True,
retirement_provider=drop_table_retirement_provider(
search_models.SearchIndexChangeQueue,
search_models.SearchIndexAclToken,
search_models.SearchIndexDocument,
search_models.SearchIndexState,
label="Search",
),
retirement_notes=(
"Destructive retirement removes the derived search index. "
"Source module data remains authoritative."
),
),
uninstall_guard_providers=(
persistent_table_uninstall_guard(
search_models.SearchIndexChangeQueue,
search_models.SearchIndexDocument,
search_models.SearchIndexState,
label="Search index",
),
),
capability_factories={
CAPABILITY_SEARCH_INDEX_WRITER: _service,
},
search_providers=(
SearchProviderRegistration(
id="search.index",
factory=_service,
order=10,
),
),
documentation=(
DocumentationTopic(
id="search.global-and-contextual",
title="Global and contextual search",
summary=(
"Search authorized native and connected objects from one "
"permission-aware interface."
),
body=(
"Search works with the built-in database index and can aggregate "
"optional providers. Source modules announce searchable types, "
"context scopes, and ACL-aware index entries. External engines "
"remain optional adapters. The title-bar Search command, F3, "
"or Ctrl/Cmd+K opens the "
"keyboard-navigable search overlay; filters never broaden the "
"current principal's source permissions. Provider failures are "
"shown as partial diagnostics without discarding safe results."
" Search administrators can inspect native source coverage, "
"process queued changes, reconcile enabled modules, and run "
"bounded source rebuilds from Administration. Quarantined "
"changes remain visible until repaired and reconciled."
),
layer="available",
documentation_types=("admin", "user"),
audience=("administrator", "user"),
related_modules=("connectors", "views"),
metadata={
"kind": "reference",
"help_contexts": [
"search.global",
"search.results",
"search.filters",
"search.admin.index",
],
},
links=(
DocumentationLink(
label="Search interface pattern audit",
href="govoplan-search/docs/INTERFACE_PATTERN_MIGRATION.md",
kind="repository",
),
),
order=12,
),
),
architecture=declared_module_architecture(
layer="governance_accountability",
kind="runtime",
maturity="vertical_slice",
documentation_ref="README.md",
test_ref="tests/test_postgres_search.py",
known_limits=("The built-in PostgreSQL index is implemented; optional OpenSearch target evidence is not.",),
supported_authority_modes=("external_mirror",),
owned_concepts=("derived search index", "search ACL projection", "index change queue"),
non_owned_concepts=("source object", "source authorization", "external search engine"),
recovery_docs=("README.md",),
security_docs=("README.md",),
operations_docs=("README.md",),
),
)
def get_manifest() -> ModuleManifest:
return manifest
__all__ = [
"ADMIN_SCOPE",
"INDEX_SCOPE",
"MODULE_ID",
"MODULE_VERSION",
"READ_SCOPE",
"get_manifest",
"manifest",
]
@@ -0,0 +1 @@
"""Search migrations."""
@@ -0,0 +1 @@
"""Search migration revisions."""
@@ -0,0 +1,119 @@
"""Create the built-in search index.
Revision ID: a1b2c3d4e5f6
Revises:
Create Date: 2026-07-29
"""
from __future__ import annotations
from alembic import op
import sqlalchemy as sa
revision = "a1b2c3d4e5f6"
down_revision = None
branch_labels = ("search",)
depends_on = None
def upgrade() -> None:
op.create_table(
"search_index_documents",
sa.Column("id", sa.String(length=36), nullable=False),
sa.Column("tenant_id", sa.String(length=36), nullable=False),
sa.Column("module_id", sa.String(length=100), nullable=False),
sa.Column("resource_type", sa.String(length=100), nullable=False),
sa.Column("resource_id", sa.String(length=255), nullable=False),
sa.Column("title", sa.String(length=500), nullable=False),
sa.Column("summary", sa.Text(), nullable=True),
sa.Column("body", sa.Text(), nullable=True),
sa.Column("keywords", sa.JSON(), nullable=False),
sa.Column("search_text", sa.Text(), nullable=False),
sa.Column("url", sa.String(length=1500), nullable=False),
sa.Column("visibility", sa.String(length=20), nullable=False),
sa.Column("external_reference", sa.JSON(), nullable=True),
sa.Column("metadata", sa.JSON(), nullable=False),
sa.Column("content_hash", sa.String(length=64), nullable=False),
sa.Column("indexed_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint("id", name=op.f("pk_search_index_documents")),
sa.UniqueConstraint(
"tenant_id",
"module_id",
"resource_type",
"resource_id",
name="uq_search_document_resource",
),
)
op.create_index(
"ix_search_document_scope",
"search_index_documents",
["tenant_id", "module_id", "resource_type"],
unique=False,
)
op.create_index(
"ix_search_document_visibility",
"search_index_documents",
["tenant_id", "visibility"],
unique=False,
)
for column in ("tenant_id", "module_id", "resource_type", "resource_id"):
op.create_index(
op.f(f"ix_search_index_documents_{column}"),
"search_index_documents",
[column],
unique=False,
)
op.create_table(
"search_index_acl_tokens",
sa.Column("id", sa.String(length=36), nullable=False),
sa.Column("document_id", sa.String(length=36), nullable=False),
sa.Column("token", sa.String(length=500), nullable=False),
sa.ForeignKeyConstraint(
["document_id"],
["search_index_documents.id"],
name=op.f(
"fk_search_index_acl_tokens_document_id_search_index_documents"
),
ondelete="CASCADE",
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_search_index_acl_tokens")),
sa.UniqueConstraint(
"document_id",
"token",
name="uq_search_index_acl_document_token",
),
)
op.create_index(
op.f("ix_search_index_acl_tokens_document_id"),
"search_index_acl_tokens",
["document_id"],
unique=False,
)
op.create_index(
op.f("ix_search_index_acl_tokens_token"),
"search_index_acl_tokens",
["token"],
unique=False,
)
op.create_index(
"ix_search_index_acl_token",
"search_index_acl_tokens",
["token", "document_id"],
unique=False,
)
if op.get_bind().dialect.name == "postgresql":
op.execute(
"CREATE INDEX ix_search_document_fts "
"ON search_index_documents USING gin "
"(to_tsvector('simple', search_text))"
)
def downgrade() -> None:
op.drop_table("search_index_acl_tokens")
op.drop_table("search_index_documents")
@@ -0,0 +1,311 @@
"""Add versioned search indexing lifecycle.
Revision ID: b2c3d4e5f607
Revises: a1b2c3d4e5f6
Create Date: 2026-07-29
"""
from __future__ import annotations
from alembic import op
import sqlalchemy as sa
revision = "b2c3d4e5f607"
down_revision = "a1b2c3d4e5f6"
branch_labels = None
depends_on = None
def upgrade() -> None:
for column in (
sa.Column(
"provider_id",
sa.String(length=200),
nullable=False,
server_default="legacy.index",
),
sa.Column(
"source_revision",
sa.String(length=255),
nullable=False,
server_default="1",
),
sa.Column(
"change_cursor",
sa.String(length=500),
nullable=True,
),
sa.Column(
"source_updated_at",
sa.DateTime(timezone=True),
nullable=True,
),
sa.Column(
"language",
sa.String(length=32),
nullable=False,
server_default="simple",
),
sa.Column(
"index_version",
sa.Integer(),
nullable=False,
server_default="1",
),
sa.Column(
"requires_authorization_recheck",
sa.Boolean(),
nullable=False,
server_default=sa.false(),
),
sa.Column(
"rebuild_id",
sa.String(length=36),
nullable=True,
),
sa.Column(
"active",
sa.Boolean(),
nullable=False,
server_default=sa.true(),
),
):
op.add_column("search_index_documents", column)
for column in ("provider_id", "rebuild_id", "active"):
op.create_index(
op.f(f"ix_search_index_documents_{column}"),
"search_index_documents",
[column],
)
op.create_index(
"ix_search_document_provider",
"search_index_documents",
[
"tenant_id",
"provider_id",
"resource_type",
"active",
],
)
bind = op.get_bind()
if (
bind.dialect.name == "postgresql"
and bind.scalar(
sa.text(
"SELECT EXISTS ("
"SELECT 1 FROM pg_extension "
"WHERE extname = 'pg_trgm'"
")"
)
)
):
op.execute(
"CREATE INDEX ix_search_document_title_trgm "
"ON search_index_documents USING gin "
"(lower(title) gin_trgm_ops)"
)
op.execute(
"CREATE INDEX ix_search_document_text_trgm "
"ON search_index_documents USING gin "
"(lower(search_text) gin_trgm_ops)"
)
op.create_table(
"search_index_states",
sa.Column("id", sa.String(length=36), nullable=False),
sa.Column("tenant_id", sa.String(length=36), nullable=False),
sa.Column("provider_id", sa.String(length=200), nullable=False),
sa.Column("module_id", sa.String(length=100), nullable=False),
sa.Column("resource_type", sa.String(length=100), nullable=False),
sa.Column("index_version", sa.Integer(), nullable=False),
sa.Column("status", sa.String(length=30), nullable=False),
sa.Column("rebuild_id", sa.String(length=36), nullable=True),
sa.Column(
"checkpoint_cursor",
sa.String(length=500),
nullable=True,
),
sa.Column(
"high_watermark",
sa.String(length=500),
nullable=True,
),
sa.Column(
"last_change_cursor",
sa.String(length=500),
nullable=True,
),
sa.Column("indexed_documents", sa.Integer(), nullable=False),
sa.Column("rejected_documents", sa.Integer(), nullable=False),
sa.Column(
"rebuild_started_at",
sa.DateTime(timezone=True),
nullable=True,
),
sa.Column(
"rebuild_completed_at",
sa.DateTime(timezone=True),
nullable=True,
),
sa.Column(
"last_success_at",
sa.DateTime(timezone=True),
nullable=True,
),
sa.Column("last_error", sa.Text(), nullable=True),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
nullable=False,
),
sa.Column(
"updated_at",
sa.DateTime(timezone=True),
nullable=False,
),
sa.PrimaryKeyConstraint(
"id",
name=op.f("pk_search_index_states"),
),
sa.UniqueConstraint(
"tenant_id",
"provider_id",
"resource_type",
name="uq_search_index_state_source",
),
)
for column in (
"tenant_id",
"provider_id",
"module_id",
"resource_type",
"status",
):
op.create_index(
op.f(f"ix_search_index_states_{column}"),
"search_index_states",
[column],
)
op.create_index(
"ix_search_index_state_status",
"search_index_states",
["tenant_id", "status"],
)
op.create_table(
"search_index_change_queue",
sa.Column("id", sa.String(length=36), nullable=False),
sa.Column("change_id", sa.String(length=255), nullable=False),
sa.Column("tenant_id", sa.String(length=36), nullable=False),
sa.Column("provider_id", sa.String(length=200), nullable=False),
sa.Column("module_id", sa.String(length=100), nullable=False),
sa.Column("resource_type", sa.String(length=100), nullable=False),
sa.Column("resource_id", sa.String(length=255), nullable=False),
sa.Column("kind", sa.String(length=20), nullable=False),
sa.Column(
"source_revision",
sa.String(length=255),
nullable=False,
),
sa.Column(
"source_cursor",
sa.String(length=500),
nullable=False,
),
sa.Column("document", sa.JSON(), nullable=True),
sa.Column(
"occurred_at",
sa.DateTime(timezone=True),
nullable=True,
),
sa.Column("status", sa.String(length=30), nullable=False),
sa.Column("attempts", sa.Integer(), nullable=False),
sa.Column(
"available_at",
sa.DateTime(timezone=True),
nullable=False,
),
sa.Column(
"processed_at",
sa.DateTime(timezone=True),
nullable=True,
),
sa.Column("error", sa.Text(), nullable=True),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
nullable=False,
),
sa.Column(
"updated_at",
sa.DateTime(timezone=True),
nullable=False,
),
sa.PrimaryKeyConstraint(
"id",
name=op.f("pk_search_index_change_queue"),
),
sa.UniqueConstraint(
"change_id",
name="uq_search_index_change_queue_change",
),
)
for column in (
"change_id",
"tenant_id",
"provider_id",
"module_id",
"resource_type",
"resource_id",
"status",
"available_at",
):
op.create_index(
op.f(f"ix_search_index_change_queue_{column}"),
"search_index_change_queue",
[column],
)
op.create_index(
"ix_search_index_change_queue_pending",
"search_index_change_queue",
["status", "available_at", "created_at"],
)
op.create_index(
"ix_search_index_change_queue_source",
"search_index_change_queue",
["tenant_id", "provider_id", "resource_type"],
)
def downgrade() -> None:
if op.get_bind().dialect.name == "postgresql":
op.execute(
"DROP INDEX IF EXISTS ix_search_document_text_trgm"
)
op.execute(
"DROP INDEX IF EXISTS ix_search_document_title_trgm"
)
op.drop_table("search_index_change_queue")
op.drop_table("search_index_states")
op.drop_index(
"ix_search_document_provider",
table_name="search_index_documents",
)
for column in ("active", "rebuild_id", "provider_id"):
op.drop_index(
op.f(f"ix_search_index_documents_{column}"),
table_name="search_index_documents",
)
for column in (
"active",
"rebuild_id",
"requires_authorization_recheck",
"index_version",
"language",
"source_updated_at",
"change_cursor",
"source_revision",
"provider_id",
):
op.drop_column("search_index_documents", column)
+389
View File
@@ -0,0 +1,389 @@
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
from sqlalchemy.orm import Session
from govoplan_core.auth import ApiPrincipal, get_api_principal, has_scope
from govoplan_core.audit.logging import audit_from_principal
from govoplan_core.core.search import CAPABILITY_SEARCH_INDEX_WRITER
from govoplan_core.core.registry import PlatformRegistry
from govoplan_core.core.search import SearchQuery
from govoplan_core.db.session import get_session
from govoplan_search.backend.manifest import ADMIN_SCOPE, READ_SCOPE
from govoplan_search.backend.schemas import (
SearchChangeDispatchResponse,
SearchDiagnosticsResponse,
SearchIndexStateResponse,
SearchModuleReconcileResponse,
SearchProviderListResponse,
SearchProviderResponse,
SearchRebuildResponse,
SearchResourceTypeResponse,
SearchResponse,
SearchResultResponse,
)
from govoplan_search.backend.service import (
SearchIndexService,
aggregate_search_page,
)
router = APIRouter(prefix="/search", tags=["search"])
def _registry(request: Request) -> PlatformRegistry:
registry = getattr(request.app.state, "govoplan_registry", None)
if not isinstance(registry, PlatformRegistry):
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Search registry is not available.",
)
return registry
def _require_read(principal: ApiPrincipal) -> None:
if not has_scope(principal, READ_SCOPE):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Missing scope: {READ_SCOPE}",
)
def _require_admin(principal: ApiPrincipal) -> None:
if not has_scope(principal, ADMIN_SCOPE):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Missing scope: {ADMIN_SCOPE}",
)
def _service(registry: PlatformRegistry) -> SearchIndexService:
capability = registry.capability(
CAPABILITY_SEARCH_INDEX_WRITER
)
if not isinstance(capability, SearchIndexService):
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Search index service is not available.",
)
return capability
def _search_resource_catalogue(
registry: PlatformRegistry,
) -> list[SearchResourceTypeResponse]:
resources = {
(
descriptor.module_id,
descriptor.resource_type,
descriptor.provider_id,
): SearchResourceTypeResponse(
provider_id=descriptor.provider_id,
module_id=descriptor.module_id,
resource_type=descriptor.resource_type,
label=descriptor.label,
order=registered.registration.order,
)
for registered, source in registry.search_sources()
for descriptor in source.resource_types()
}
return [
resources[key]
for key in sorted(
resources,
key=lambda item: (
resources[item].order,
resources[item].label.casefold(),
item,
),
)
]
@router.get("", response_model=SearchResponse)
def api_search(
request: Request,
q: str = Query(default="", max_length=500),
module: list[str] = Query(default=[]),
resource_type: list[str] = Query(default=[]),
context_kind: str = Query(default="global", pattern="^(global|module|resource)$"),
context_id: str | None = Query(default=None, max_length=255),
limit: int = Query(default=25, ge=1, le=100),
offset: int = Query(default=0, ge=0, le=10_000),
cursor: str | None = Query(default=None, max_length=2000),
language: str = Query(
default="simple",
max_length=32,
pattern=r"^[A-Za-z_]+$",
),
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SearchResponse:
_require_read(principal)
registry = _registry(request)
try:
query = SearchQuery(
text=q,
tenant_id=principal.tenant_id,
module_ids=tuple(dict.fromkeys(module)),
resource_types=tuple(dict.fromkeys(resource_type)),
context_kind=context_kind, # type: ignore[arg-type]
context_id=context_id,
limit=limit,
offset=offset,
cursor=cursor,
language=language.casefold(),
)
page = aggregate_search_page(
registry,
session,
principal,
query=query,
)
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
detail=str(exc),
) from exc
return SearchResponse(
query=query.text,
results=[
SearchResultResponse.model_validate(
{
"provider_id": result.provider_id,
"module_id": result.module_id,
"resource_type": result.resource_type,
"resource_id": result.resource_id,
"title": result.title,
"summary": result.summary,
"url": result.url,
"score": result.score,
"highlights": list(result.highlights),
"breadcrumbs": list(result.breadcrumbs),
"external_reference": (
result.external_reference.to_dict()
if result.external_reference is not None
else None
),
"metadata": dict(result.metadata),
"source_revision": result.source_revision,
"provenance": dict(result.provenance),
}
)
for result in page.results
],
diagnostics=list(page.diagnostics),
next_cursor=page.next_cursor,
has_more=page.next_cursor is not None,
)
@router.get("/providers", response_model=SearchProviderListResponse)
def api_search_providers(
request: Request,
principal: ApiPrincipal = Depends(get_api_principal),
) -> SearchProviderListResponse:
_require_read(principal)
registry = _registry(request)
registrations = registry.search_provider_registrations()
return SearchProviderListResponse(
providers=[
SearchProviderResponse(
id=item.registration.id,
module_id=item.module_id,
resource_types=list(item.registration.resource_types),
order=item.registration.order,
)
for item in registrations
],
resources=_search_resource_catalogue(registry),
)
@router.get(
"/admin/diagnostics",
response_model=SearchDiagnosticsResponse,
)
def api_search_diagnostics(
request: Request,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SearchDiagnosticsResponse:
_require_admin(principal)
registry = _registry(request)
return SearchDiagnosticsResponse.model_validate(
_service(registry).diagnostics(session, principal)
)
@router.post(
"/admin/reconcile-modules",
response_model=SearchModuleReconcileResponse,
)
def api_reconcile_search_modules(
request: Request,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SearchModuleReconcileResponse:
_require_admin(principal)
result = _service(_registry(request)).reconcile_active_modules(
session,
tenant_id=principal.tenant_id,
)
audit_from_principal(
session,
principal,
action="search.modules.reconciled",
scope="tenant",
object_type="search_index",
details=result,
)
session.commit()
return SearchModuleReconcileResponse(**result)
@router.post(
"/admin/changes/process",
response_model=SearchChangeDispatchResponse,
)
def api_process_search_changes(
request: Request,
limit: int = Query(default=100, ge=1, le=500),
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SearchChangeDispatchResponse:
_require_admin(principal)
result = _service(_registry(request)).process_changes(
session,
limit=limit,
tenant_id=principal.tenant_id,
)
audit_from_principal(
session,
principal,
action="search.changes.processed",
scope="tenant",
object_type="search_index",
details=result,
)
session.commit()
return SearchChangeDispatchResponse(**result)
@router.post(
"/admin/rebuilds/{provider_id}/{resource_type}/start",
response_model=SearchRebuildResponse,
)
def api_start_search_rebuild(
provider_id: str,
resource_type: str,
request: Request,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SearchRebuildResponse:
_require_admin(principal)
try:
state = _service(_registry(request)).start_rebuild(
session,
principal,
provider_id=provider_id,
resource_type=resource_type,
)
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=str(exc),
) from exc
audit_from_principal(
session,
principal,
action="search.rebuild.started",
scope="tenant",
object_type="search_index",
object_id=state.id,
details={
"provider_id": provider_id,
"resource_type": resource_type,
"rebuild_id": state.rebuild_id,
},
)
session.commit()
return SearchRebuildResponse(
state=_search_state_response(state)
)
@router.post(
"/admin/rebuilds/{provider_id}/{resource_type}/continue",
response_model=SearchRebuildResponse,
)
def api_continue_search_rebuild(
provider_id: str,
resource_type: str,
request: Request,
limit: int = Query(default=100, ge=1, le=500),
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SearchRebuildResponse:
_require_admin(principal)
service = _service(_registry(request))
try:
state = service.continue_rebuild(
session,
principal,
provider_id=provider_id,
resource_type=resource_type,
limit=limit,
)
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=str(exc),
) from exc
audit_from_principal(
session,
principal,
action="search.rebuild.continued",
scope="tenant",
object_type="search_index",
object_id=state.id,
details={
"provider_id": provider_id,
"resource_type": resource_type,
"status": state.status,
"indexed_documents": state.indexed_documents,
},
)
session.commit()
return SearchRebuildResponse(
state=_search_state_response(state)
)
def _search_state_response(state: object) -> SearchIndexStateResponse:
return SearchIndexStateResponse(
provider_id=str(getattr(state, "provider_id")),
module_id=str(getattr(state, "module_id")),
resource_type=str(getattr(state, "resource_type")),
index_version=int(getattr(state, "index_version")),
status=str(getattr(state, "status")),
checkpoint_cursor=getattr(state, "checkpoint_cursor"),
high_watermark=getattr(state, "high_watermark"),
last_change_cursor=getattr(state, "last_change_cursor"),
indexed_documents=int(
getattr(state, "indexed_documents")
),
rejected_documents=int(
getattr(state, "rejected_documents")
),
rebuild_started_at=getattr(state, "rebuild_started_at"),
rebuild_completed_at=getattr(
state,
"rebuild_completed_at",
),
last_success_at=getattr(state, "last_success_at"),
last_error=getattr(state, "last_error"),
)
__all__ = ["router"]
+128
View File
@@ -0,0 +1,128 @@
from __future__ import annotations
from datetime import datetime
from typing import Any, Literal
from pydantic import BaseModel, Field
class SearchExternalReferenceResponse(BaseModel):
system: str
object_type: str
object_id: str
maturity: str
connector_id: str | None = None
canonical_url: str | None = None
version: str | None = None
etag: str | None = None
observed_at: str | None = None
metadata: dict[str, Any] = Field(default_factory=dict)
class SearchResultResponse(BaseModel):
provider_id: str
module_id: str
resource_type: str
resource_id: str
title: str
summary: str | None = None
url: str
score: float = 0.0
highlights: list[str] = Field(default_factory=list)
breadcrumbs: list[str] = Field(default_factory=list)
external_reference: SearchExternalReferenceResponse | None = None
metadata: dict[str, Any] = Field(default_factory=dict)
source_revision: str | None = None
provenance: dict[str, Any] = Field(default_factory=dict)
class SearchProviderDiagnosticResponse(BaseModel):
provider_id: str
status: Literal["unavailable"]
message: str
class SearchResponse(BaseModel):
query: str
results: list[SearchResultResponse]
diagnostics: list[SearchProviderDiagnosticResponse] = Field(default_factory=list)
next_cursor: str | None = None
has_more: bool = False
class SearchProviderResponse(BaseModel):
id: str
module_id: str
resource_types: list[str]
order: int
class SearchResourceTypeResponse(BaseModel):
provider_id: str
module_id: str
resource_type: str
label: str
order: int
class SearchProviderListResponse(BaseModel):
providers: list[SearchProviderResponse]
resources: list[SearchResourceTypeResponse] = Field(default_factory=list)
class SearchIndexStateResponse(BaseModel):
provider_id: str
module_id: str
resource_type: str
index_version: int
status: str
checkpoint_cursor: str | None = None
high_watermark: str | None = None
last_change_cursor: str | None = None
indexed_documents: int = 0
rejected_documents: int = 0
rebuild_started_at: datetime | None = None
rebuild_completed_at: datetime | None = None
last_success_at: datetime | None = None
last_error: str | None = None
class SearchDiagnosticsResponse(BaseModel):
backend: str
trigram_available: bool
queue: dict[str, int] = Field(default_factory=dict)
queue_oldest_age_seconds: float | None = None
states: list[SearchIndexStateResponse] = Field(
default_factory=list
)
class SearchRebuildResponse(BaseModel):
state: SearchIndexStateResponse
class SearchChangeDispatchResponse(BaseModel):
selected: int
applied: int
retrying: int
quarantined: int
class SearchModuleReconcileResponse(BaseModel):
disabled_documents: int
enabled_documents: int
__all__ = [
"SearchProviderDiagnosticResponse",
"SearchProviderListResponse",
"SearchProviderResponse",
"SearchResourceTypeResponse",
"SearchChangeDispatchResponse",
"SearchDiagnosticsResponse",
"SearchIndexStateResponse",
"SearchModuleReconcileResponse",
"SearchRebuildResponse",
"SearchResponse",
"SearchResultResponse",
]
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
+20
View File
@@ -0,0 +1,20 @@
from __future__ import annotations
import unittest
from govoplan_core.core.search import CAPABILITY_SEARCH_INDEX_WRITER
from govoplan_search.backend.manifest import get_manifest
class SearchManifestTests(unittest.TestCase):
def test_manifest_exposes_optional_search_runtime(self) -> None:
manifest = get_manifest()
self.assertEqual("search", manifest.id)
self.assertIn(CAPABILITY_SEARCH_INDEX_WRITER, manifest.capability_factories)
self.assertEqual("search.index", manifest.search_providers[0].id)
self.assertEqual("/search", manifest.frontend.routes[0].path)
if __name__ == "__main__":
unittest.main()
+50
View File
@@ -0,0 +1,50 @@
from __future__ import annotations
import tempfile
import unittest
from pathlib import Path
from alembic.runtime.migration import MigrationContext
from sqlalchemy import create_engine, inspect
from govoplan_core.db.migrations import migrate_database
from govoplan_search.backend.manifest import get_manifest
class SearchMigrationTests(unittest.TestCase):
def test_migration_creates_search_tables_and_head(self) -> None:
with tempfile.TemporaryDirectory(
prefix="govoplan-search-migration-"
) as directory:
url = f"sqlite:///{Path(directory) / 'search.db'}"
migrate_database(
database_url=url,
enabled_modules=("search",),
manifest_factories=(get_manifest,),
)
engine = create_engine(url)
try:
with engine.connect() as connection:
self.assertIn(
"b2c3d4e5f607",
set(MigrationContext.configure(connection).get_current_heads()),
)
self.assertEqual(
{
"search_index_acl_tokens",
"search_index_change_queue",
"search_index_documents",
"search_index_states",
},
{
name
for name in inspect(connection).get_table_names()
if name.startswith("search_index_")
},
)
finally:
engine.dispose()
if __name__ == "__main__":
unittest.main()
+192
View File
@@ -0,0 +1,192 @@
from __future__ import annotations
import os
from types import SimpleNamespace
import unittest
import uuid
from sqlalchemy import create_engine, delete, inspect, select
from sqlalchemy.orm import Session
from govoplan_core.core.search import SearchDocument, SearchQuery
from govoplan_search.backend.db.models import (
SearchIndexAclToken,
SearchIndexChangeQueue,
SearchIndexDocument,
SearchIndexState,
)
from govoplan_search.backend.service import SearchIndexService
DATABASE_URL = os.environ.get(
"GOVOPLAN_SEARCH_POSTGRES_URL",
"",
).strip()
class _Registry:
def manifests(self):
return (
SimpleNamespace(id="search"),
SimpleNamespace(id="cases"),
)
def search_sources(self):
return ()
@unittest.skipUnless(
DATABASE_URL.startswith("postgresql"),
"GOVOPLAN_SEARCH_POSTGRES_URL is not configured",
)
class PostgreSqlSearchTests(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.engine = create_engine(DATABASE_URL)
table_names = set(inspect(cls.engine).get_table_names())
required = {
SearchIndexDocument.__tablename__,
SearchIndexAclToken.__tablename__,
SearchIndexState.__tablename__,
SearchIndexChangeQueue.__tablename__,
}
if not required.issubset(table_names):
raise RuntimeError(
"Search migrations were not applied before the "
"PostgreSQL integration test."
)
@classmethod
def tearDownClass(cls) -> None:
cls.engine.dispose()
def setUp(self) -> None:
self.tenant_id = str(uuid.uuid4())
self.other_tenant_id = str(uuid.uuid4())
self.session = Session(self.engine)
self.service = SearchIndexService(_Registry())
self.principal = SimpleNamespace(
tenant_id=self.tenant_id,
account_id="account-allowed",
membership_id="membership-allowed",
identity_id=None,
group_ids=frozenset(),
role_ids=frozenset(),
function_assignment_ids=frozenset(),
scopes=frozenset({"cases:case:read"}),
)
def tearDown(self) -> None:
document_ids = select(SearchIndexDocument.id).where(
SearchIndexDocument.tenant_id.in_(
(self.tenant_id, self.other_tenant_id)
)
)
self.session.execute(
delete(SearchIndexAclToken).where(
SearchIndexAclToken.document_id.in_(document_ids)
)
)
self.session.execute(
delete(SearchIndexChangeQueue).where(
SearchIndexChangeQueue.tenant_id.in_(
(self.tenant_id, self.other_tenant_id)
)
)
)
self.session.execute(
delete(SearchIndexState).where(
SearchIndexState.tenant_id.in_(
(self.tenant_id, self.other_tenant_id)
)
)
)
self.session.execute(
delete(SearchIndexDocument).where(
SearchIndexDocument.tenant_id.in_(
(self.tenant_id, self.other_tenant_id)
)
)
)
self.session.commit()
self.session.close()
def test_postgres_full_text_query_is_tenant_and_acl_bounded(
self,
) -> None:
self.service.upsert_document(
self.session,
self.principal,
document=SearchDocument(
tenant_id=self.tenant_id,
module_id="cases",
provider_id="cases.records",
resource_type="case",
resource_id="case-visible",
title="Monthly parking permit review",
url="/cases/case-visible",
body="Compare the permit data with the payment register.",
visibility="tenant",
),
)
self.service.upsert_document(
self.session,
self.principal,
document=SearchDocument(
tenant_id=self.tenant_id,
module_id="cases",
provider_id="cases.records",
resource_type="case",
resource_id="case-denied",
title="Restricted parking permit",
url="/cases/case-denied",
visibility="restricted",
acl_tokens=("account:someone-else",),
),
)
other_principal = SimpleNamespace(
**{
**vars(self.principal),
"tenant_id": self.other_tenant_id,
}
)
self.service.upsert_document(
self.session,
other_principal,
document=SearchDocument(
tenant_id=self.other_tenant_id,
module_id="cases",
provider_id="cases.records",
resource_type="case",
resource_id="case-other-tenant",
title="Other tenant parking permit",
url="/cases/case-other-tenant",
visibility="tenant",
),
)
self.session.commit()
page = self.service.search_page(
self.session,
self.principal,
query=SearchQuery(
text="parking permit",
tenant_id=self.tenant_id,
),
)
self.assertEqual(
("case-visible",),
tuple(item.resource_id for item in page.results),
)
self.assertEqual(
"postgresql",
self.service.diagnostics(
self.session,
self.principal,
)["backend"],
)
if __name__ == "__main__":
unittest.main()
+601
View File
@@ -0,0 +1,601 @@
from __future__ import annotations
import unittest
from types import SimpleNamespace
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from govoplan_core.core.events import EventObjectRef, EventTenantRef, PlatformEvent
from govoplan_core.core.search import (
SearchBackfillPage,
SearchDocument,
SearchIndexChange,
SearchQuery,
SearchResourceType,
SearchResult,
)
from govoplan_core.db.base import Base
from govoplan_search.backend.db.models import (
SearchIndexAclToken,
SearchIndexChangeQueue,
SearchIndexDocument,
SearchIndexState,
)
from govoplan_search.backend.router import _search_resource_catalogue
from govoplan_search.backend.service import (
SearchIndexService,
aggregate_search_page,
)
class _Registry:
def __init__(self, source=None, active_modules=("search", "cases")):
self.source = source
self.active_modules = active_modules
def manifests(self):
return tuple(
SimpleNamespace(id=module_id)
for module_id in self.active_modules
)
def search_sources(self):
if self.source is None:
return ()
return (
(
SimpleNamespace(
module_id="cases",
registration=SimpleNamespace(
id="cases.records",
order=25,
)
),
self.source,
),
)
class _Source:
def __init__(self, pages=()):
self.pages = list(pages)
self.authorized_ids = {"case-1"}
def resource_types(self):
return (
SearchResourceType(
provider_id="cases.records",
module_id="cases",
resource_type="case",
label="Cases",
requires_authorization_recheck=True,
),
)
def backfill(self, session, *, request):
del session, request
return self.pages.pop(0)
def authorize(self, session, principal, *, requests):
del session, principal
return {
request.reference.key: (
request.reference.resource_id
in self.authorized_ids
)
for request in requests
}
class _EventSource(_Source):
def index_changes_for_event(self, session, *, event, delivery_key):
del session
if (
event.module_id != "cases"
or event.tenant is None
or event.resource is None
or event.resource.type != "case"
or event.resource.id is None
):
return ()
reference = _source_document(event.resource.id).reference
document = SearchDocument(
tenant_id=event.tenant.id,
module_id="cases",
resource_type="case",
resource_id=event.resource.id,
title=f"Permit {event.resource.id}",
url=f"/cases/{event.resource.id}",
acl_tokens=("account:account-1",),
provider_id="cases.records",
source_revision="event-1",
change_cursor=event.event_id,
requires_authorization_recheck=True,
)
return (
SearchIndexChange(
change_id=f"{delivery_key}:cases.records",
provider_id="cases.records",
kind="upsert",
reference=reference,
source_revision=document.source_revision,
cursor=event.event_id,
document=document,
occurred_at=event.occurred_at,
),
)
class _ResultProvider:
def search(self, session, principal, *, query):
del session, principal
return tuple(
SearchResult(
provider_id="ignored",
module_id="cases",
resource_type="case",
resource_id=f"case-{number}",
title=f"Permit {number}",
url=f"/cases/case-{number}",
score=float(10 - number),
)
for number in range(1, 7)
)[: query.limit]
class _AggregateRegistry:
def search_providers(self):
return (
(
SimpleNamespace(
registration=SimpleNamespace(id="cases.live")
),
_ResultProvider(),
),
)
class SearchServiceTests(unittest.TestCase):
def setUp(self) -> None:
self.engine = create_engine("sqlite://")
Base.metadata.create_all(
self.engine,
tables=(
SearchIndexDocument.__table__,
SearchIndexAclToken.__table__,
SearchIndexState.__table__,
SearchIndexChangeQueue.__table__,
),
)
self.session = Session(self.engine)
self.service = SearchIndexService(_Registry())
self.principal = SimpleNamespace(
tenant_id="tenant-1",
account_id="account-1",
membership_id="membership-1",
identity_id=None,
group_ids=frozenset({"group-1"}),
role_ids=frozenset(),
function_assignment_ids=frozenset(),
scopes=frozenset({"cases:case:read"}),
)
def tearDown(self) -> None:
self.session.close()
self.engine.dispose()
def test_index_search_and_acl_filtering(self) -> None:
self.service.upsert_document(
self.session,
self.principal,
document=SearchDocument(
tenant_id="tenant-1",
module_id="cases",
resource_type="case",
resource_id="case-1",
title="Resident parking permit",
summary="Monthly permit review",
url="/cases/case-1",
acl_tokens=("group:group-1",),
),
)
self.service.upsert_document(
self.session,
self.principal,
document=SearchDocument(
tenant_id="tenant-1",
module_id="cases",
resource_type="case",
resource_id="case-2",
title="Restricted permit",
url="/cases/case-2",
acl_tokens=("account:someone-else",),
),
)
self.session.flush()
results = self.service.search(
self.session,
self.principal,
query=SearchQuery(text="permit", tenant_id="tenant-1"),
)
self.assertEqual(["case-1"], [result.resource_id for result in results])
def test_search_resource_catalogue_exposes_source_filters(self) -> None:
catalogue = _search_resource_catalogue(_Registry(_Source()))
self.assertEqual(1, len(catalogue))
self.assertEqual("cases", catalogue[0].module_id)
self.assertEqual("case", catalogue[0].resource_type)
self.assertEqual("Cases", catalogue[0].label)
self.assertEqual(25, catalogue[0].order)
def test_upsert_replaces_acl_tokens_and_delete_is_idempotent(self) -> None:
document = SearchDocument(
tenant_id="tenant-1",
module_id="cases",
resource_type="case",
resource_id="case-1",
title="Permit",
url="/cases/case-1",
acl_tokens=("group:group-1",),
)
self.service.upsert_document(
self.session, self.principal, document=document
)
self.session.flush()
self.service.upsert_document(
self.session,
self.principal,
document=SearchDocument(
**{
**{
field: getattr(document, field)
for field in (
"tenant_id",
"module_id",
"resource_type",
"resource_id",
"title",
"url",
)
},
"acl_tokens": ("account:account-1",),
}
),
)
self.session.flush()
self.assertEqual(
["account:account-1"],
[
token.token
for token in self.session.query(SearchIndexAclToken).all()
],
)
arguments = {
"tenant_id": "tenant-1",
"module_id": "cases",
"resource_type": "case",
"resource_id": "case-1",
}
self.assertTrue(
self.service.delete_document(
self.session, self.principal, **arguments
)
)
self.assertFalse(
self.service.delete_document(
self.session, self.principal, **arguments
)
)
def test_index_rejects_cross_tenant_write(self) -> None:
with self.assertRaises(PermissionError):
self.service.upsert_document(
self.session,
self.principal,
document=SearchDocument(
tenant_id="tenant-2",
module_id="cases",
resource_type="case",
resource_id="case-1",
title="Permit",
url="/cases/case-1",
visibility="tenant",
),
)
with self.assertRaisesRegex(ValueError, "secret field"):
self.service.upsert_document(
self.session,
self.principal,
document=SearchDocument(
tenant_id="tenant-1",
module_id="cases",
resource_type="case",
resource_id="case-secret",
title="Permit",
url="/cases/case-secret",
acl_tokens=("account:account-1",),
metadata={"access_token": "must-not-index"},
),
)
def test_query_rejects_cross_tenant_principal(self) -> None:
with self.assertRaises(PermissionError):
self.service.search(
self.session,
self.principal,
query=SearchQuery(
text="permit",
tenant_id="tenant-2",
),
)
def test_source_authorization_recheck_is_fail_closed(self) -> None:
source = _Source()
service = SearchIndexService(_Registry(source))
for resource_id in ("case-1", "case-2"):
service.upsert_document(
self.session,
self.principal,
document=_source_document(resource_id),
)
self.session.flush()
results = service.search(
self.session,
self.principal,
query=SearchQuery(
text="permit",
tenant_id="tenant-1",
),
)
self.assertEqual(
["case-1"],
[item.resource_id for item in results],
)
unavailable_results = SearchIndexService(
_Registry()
).search(
self.session,
self.principal,
query=SearchQuery(
text="permit",
tenant_id="tenant-1",
),
)
self.assertEqual((), unavailable_results)
def test_durable_change_queue_is_idempotent(self) -> None:
document = _source_document("case-1")
change = SearchIndexChange(
change_id="change-1",
provider_id="cases.records",
kind="upsert",
reference=document.reference,
source_revision=document.source_revision,
cursor=document.change_cursor or "",
document=document,
)
self.assertTrue(
self.service.enqueue_change(
self.session,
change=change,
)
)
self.assertFalse(
self.service.enqueue_change(
self.session,
change=change,
)
)
result = self.service.process_changes(self.session)
self.assertEqual(1, result["applied"])
self.assertEqual(
"case-1",
self.session.query(SearchIndexDocument).one().resource_id,
)
self.assertEqual(
"applied",
self.session.query(SearchIndexChangeQueue).one().status,
)
delete_change = SearchIndexChange(
change_id="change-2",
provider_id="cases.records",
kind="delete",
reference=document.reference,
source_revision="3",
cursor="cursor-2",
)
self.service.enqueue_change(
self.session,
change=delete_change,
)
self.service.process_changes(self.session)
self.assertEqual(
0,
self.session.query(SearchIndexDocument).count(),
)
def test_committed_event_ingestion_is_source_owned_and_idempotent(self) -> None:
service = SearchIndexService(_Registry(_EventSource()))
event = PlatformEvent(
type="cases.case.updated",
module_id="cases",
tenant=EventTenantRef(id="tenant-1"),
resource=EventObjectRef(type="case", id="case-1"),
)
first = service.ingest_event(
self.session,
event=event,
delivery_key="delivery-1",
)
second = service.ingest_event(
self.session,
event=event,
delivery_key="delivery-1",
)
self.assertEqual(1, first["queued"])
self.assertEqual(1, second["duplicates"])
self.assertEqual(1, service.process_changes(self.session)["applied"])
indexed = self.session.query(SearchIndexDocument).one()
self.assertEqual("tenant-1", indexed.tenant_id)
self.assertEqual("case-1", indexed.resource_id)
def test_rebuild_resumes_and_removes_stale_documents(self) -> None:
stale = _source_document("stale-case")
self.service.upsert_document(
self.session,
self.principal,
document=stale,
)
source = _Source(
pages=(
SearchBackfillPage(
documents=(_source_document("case-1"),),
next_cursor="page-2",
complete=False,
high_watermark="changes-9",
),
SearchBackfillPage(
documents=(_source_document("case-2"),),
next_cursor=None,
complete=True,
high_watermark="changes-9",
),
)
)
service = SearchIndexService(_Registry(source))
started = service.start_rebuild(
self.session,
self.principal,
provider_id="cases.records",
resource_type="case",
)
first_page = service.continue_rebuild(
self.session,
self.principal,
provider_id="cases.records",
resource_type="case",
)
self.assertEqual(started.id, first_page.id)
self.assertEqual("backfilling", first_page.status)
self.assertEqual("page-2", first_page.checkpoint_cursor)
complete = service.continue_rebuild(
self.session,
self.principal,
provider_id="cases.records",
resource_type="case",
)
self.assertEqual("ready", complete.status)
self.assertEqual("changes-9", complete.high_watermark)
self.assertEqual(
["case-1", "case-2"],
sorted(
item.resource_id
for item in self.session.query(
SearchIndexDocument
).all()
),
)
def test_module_reconciliation_disables_derived_rows(self) -> None:
self.service.upsert_document(
self.session,
self.principal,
document=SearchDocument(
tenant_id="tenant-1",
module_id="cases",
resource_type="case",
resource_id="case-1",
title="Permit",
url="/cases/case-1",
acl_tokens=("account:account-1",),
),
)
disabled_service = SearchIndexService(
_Registry(active_modules=("search",))
)
result = disabled_service.reconcile_active_modules(
self.session
)
self.assertEqual(1, result["disabled_documents"])
self.assertFalse(
self.session.query(SearchIndexDocument).one().active
)
def test_aggregate_cursor_is_stable_and_non_overlapping(self) -> None:
registry = _AggregateRegistry()
first = aggregate_search_page(
registry,
self.session,
self.principal,
query=SearchQuery(
text="permit",
tenant_id="tenant-1",
limit=2,
),
)
second = aggregate_search_page(
registry,
self.session,
self.principal,
query=SearchQuery(
text="permit",
tenant_id="tenant-1",
limit=2,
cursor=first.next_cursor,
),
)
self.assertIsNotNone(first.next_cursor)
self.assertEqual(
{"case-1", "case-2"},
{item.resource_id for item in first.results},
)
self.assertEqual(
{"case-3", "case-4"},
{item.resource_id for item in second.results},
)
with self.assertRaisesRegex(ValueError, "cursor"):
aggregate_search_page(
registry,
self.session,
self.principal,
query=SearchQuery(
text="different",
tenant_id="tenant-1",
limit=2,
cursor=first.next_cursor,
),
)
def _source_document(resource_id: str) -> SearchDocument:
return SearchDocument(
tenant_id="tenant-1",
module_id="cases",
resource_type="case",
resource_id=resource_id,
title=f"Permit {resource_id}",
url=f"/cases/{resource_id}",
acl_tokens=("account:account-1",),
provider_id="cases.records",
source_revision="2",
change_cursor=f"cursor-{resource_id}",
requires_authorization_recheck=True,
)
if __name__ == "__main__":
unittest.main()
+32
View File
@@ -0,0 +1,32 @@
{
"name": "@govoplan/search-webui",
"version": "0.1.18",
"private": true,
"type": "module",
"main": "src/index.ts",
"module": "src/index.ts",
"types": "src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"import": "./src/index.ts"
},
"./styles/search.css": "./src/styles/search.css"
},
"scripts": {
"test:search-overlay": "node scripts/test-search-overlay-structure.mjs",
"test:interface-pattern": "node scripts/test-interface-pattern.mjs"
},
"peerDependencies": {
"@govoplan/core-webui": "^0.1.18",
"lucide-react": "^1.23.0",
"react": ">=19.2.7 <20",
"react-dom": ">=19.2.7 <20",
"react-router": ">=8.3.0 <9"
},
"peerDependenciesMeta": {
"@govoplan/core-webui": {
"optional": true
}
}
}
+27
View File
@@ -0,0 +1,27 @@
import assert from "node:assert/strict";
import fs from "node:fs";
const page = fs.readFileSync("src/features/search/SearchPage.tsx", "utf8");
const overlay = fs.readFileSync("src/components/GlobalSearch.tsx", "utf8");
const admin = fs.readFileSync("src/features/search/SearchAdminPanel.tsx", "utf8");
const styles = fs.readFileSync("src/styles/search.css", "utf8");
for (const source of [page, overlay]) {
assert.ok(source.includes("DocumentationHelpLink"), "Search surfaces expose configured-system help");
assert.ok(source.includes("DismissibleAlert"), "Search failures use the shared alert contract");
assert.ok(!source.includes("window.alert("), "Search must not use browser alerts");
assert.ok(!/<(div|span|li|tr)\b[^>]*\bonClick\s*=/.test(source), "Search uses semantic interactive elements");
}
assert.ok(page.includes("PageScrollViewport"), "The full search route owns bounded result scrolling");
assert.ok(overlay.includes("<Dialog"), "The title-bar search uses the shared focus-contained dialog");
assert.ok(overlay.includes('role="listbox"'), "Overlay results expose listbox keyboard semantics");
assert.ok(overlay.includes('aria-keyshortcuts="F3 Control+K Meta+K"'), "Search announces its keyboard shortcuts");
assert.ok(styles.includes("@media (max-width: 900px)"), "Search retains a narrow-viewport layout");
assert.ok(admin.includes("AdminPageLayout"), "Search operations use the shared administration layout");
assert.ok(admin.includes("DataGrid"), "Search source coverage uses the shared data grid");
assert.ok(admin.includes("DismissibleAlert"), "Search operator failures use the shared alert contract");
assert.ok(admin.includes("DocumentationHelpLink"), "Search operators can open contextual documentation");
assert.ok(!admin.includes("window.alert("), "Search administration must not use browser alerts");
console.log("Search interface pattern contract passed.");
@@ -0,0 +1,28 @@
import { readFileSync } from "node:fs";
function assert(condition, message) {
if (!condition) throw new Error(message);
}
const source = readFileSync("src/components/GlobalSearch.tsx", "utf8");
const layoutSource = readFileSync("src/components/searchOverlayLayout.ts", "utf8");
const styles = readFileSync("src/styles/search.css", "utf8");
assert(source.includes("titlebar-icon-link titlebar-search-button"), "Search uses the shared titlebar icon-button appearance");
assert(source.includes("onClick={openOverlay}"), "clicking the titlebar Search command opens Search");
assert(!source.includes("sourceInputRef"), "the titlebar no longer reserves a persistent Search field");
assert(source.includes("<Dialog"), "Search uses the shared Dialog component");
assert(source.includes("portal"), "the Search dialog portals above the complete shell");
assert(source.includes("calculateSearchOverlayLayout"), "the overlay position is derived from the titlebar command");
assert(source.includes("listSearchProviders"), "the overlay loads the complete filter catalogue");
assert(source.includes("limit: 50"), "the overlay requests full result windows rather than titlebar suggestions");
assert(source.includes("response?.next_cursor"), "the overlay retains cursor pagination");
assert(source.includes('usePlatformUiCapabilities<SearchContextsUiCapability>("search.contexts")'), "contextual Search contributions are consumed");
assert(!source.includes("navigate(`/search"), "normal Search interaction no longer opens a page route");
assert(layoutSource.includes("const inputWidth = width"), "the opened query field spans the Search overlay");
assert(layoutSource.includes("(viewportWidth - width) / 2"), "the Search overlay is centered in the viewport");
assert(styles.includes("margin-top: 8px"), "results follow the opened query field without overlap");
assert(styles.includes(".search-overlay-results-panel"), "full Search results have a bounded overlay panel");
console.log("Search overlay structure checks passed.");
+206
View File
@@ -0,0 +1,206 @@
import {
apiFetch,
apiPath,
type ApiSettings
} from "@govoplan/core-webui";
export type SearchExternalReference = {
system: string;
object_type: string;
object_id: string;
maturity: string;
connector_id?: string | null;
canonical_url?: string | null;
};
export type SearchResult = {
provider_id: string;
module_id: string;
resource_type: string;
resource_id: string;
title: string;
summary?: string | null;
url: string;
score: number;
highlights: string[];
breadcrumbs: string[];
external_reference?: SearchExternalReference | null;
metadata: Record<string, unknown>;
source_revision?: string | null;
provenance: Record<string, unknown>;
};
export type SearchResponse = {
query: string;
results: SearchResult[];
diagnostics: Array<{
provider_id: string;
status: "unavailable";
message: string;
}>;
next_cursor?: string | null;
has_more: boolean;
};
export type SearchProvider = {
id: string;
module_id: string;
resource_types: string[];
order: number;
};
export type SearchResourceType = {
provider_id: string;
module_id: string;
resource_type: string;
label: string;
order: number;
};
export type SearchProviderListResponse = {
providers: SearchProvider[];
resources: SearchResourceType[];
};
export type SearchIndexState = {
provider_id: string;
module_id: string;
resource_type: string;
index_version: number;
status: string;
checkpoint_cursor?: string | null;
high_watermark?: string | null;
last_change_cursor?: string | null;
indexed_documents: number;
rejected_documents: number;
rebuild_started_at?: string | null;
rebuild_completed_at?: string | null;
last_success_at?: string | null;
last_error?: string | null;
};
export type SearchDiagnostics = {
backend: string;
trigram_available: boolean;
queue: Record<string, number>;
queue_oldest_age_seconds?: number | null;
states: SearchIndexState[];
};
export type SearchChangeDispatch = {
selected: number;
applied: number;
retrying: number;
quarantined: number;
};
export type SearchModuleReconcile = {
disabled_documents: number;
enabled_documents: number;
};
export type SearchRequest = {
query: string;
modules?: string[];
resourceTypes?: string[];
contextKind?: "global" | "module" | "resource";
contextId?: string;
limit?: number;
offset?: number;
cursor?: string;
language?: string;
};
export function search(
settings: ApiSettings,
request: SearchRequest,
signal?: AbortSignal
): Promise<SearchResponse> {
return apiFetch<SearchResponse>(
settings,
apiPath("/api/v1/search", {
q: request.query,
module: request.modules,
resource_type: request.resourceTypes,
context_kind: request.contextKind,
context_id: request.contextId,
limit: request.limit,
offset: request.offset,
cursor: request.cursor,
language: request.language
}),
{ signal }
);
}
export function listSearchProviders(
settings: ApiSettings,
signal?: AbortSignal
): Promise<SearchProviderListResponse> {
return apiFetch<SearchProviderListResponse>(
settings,
"/api/v1/search/providers",
{ signal }
);
}
export function getSearchDiagnostics(
settings: ApiSettings,
signal?: AbortSignal
): Promise<SearchDiagnostics> {
return apiFetch<SearchDiagnostics>(
settings,
"/api/v1/search/admin/diagnostics",
{ signal }
);
}
export function reconcileSearchModules(
settings: ApiSettings
): Promise<SearchModuleReconcile> {
return apiFetch<SearchModuleReconcile>(
settings,
"/api/v1/search/admin/reconcile-modules",
{ method: "POST" }
);
}
export function processSearchChanges(
settings: ApiSettings,
limit = 100
): Promise<SearchChangeDispatch> {
return apiFetch<SearchChangeDispatch>(
settings,
apiPath("/api/v1/search/admin/changes/process", { limit }),
{ method: "POST" }
);
}
export function startSearchRebuild(
settings: ApiSettings,
providerId: string,
resourceType: string
): Promise<{ state: SearchIndexState }> {
return apiFetch<{ state: SearchIndexState }>(
settings,
`/api/v1/search/admin/rebuilds/${encodeURIComponent(providerId)}/${encodeURIComponent(resourceType)}/start`,
{ method: "POST" }
);
}
export function continueSearchRebuild(
settings: ApiSettings,
providerId: string,
resourceType: string,
limit = 100
): Promise<{ state: SearchIndexState }> {
return apiFetch<{ state: SearchIndexState }>(
settings,
apiPath(
`/api/v1/search/admin/rebuilds/${encodeURIComponent(providerId)}/${encodeURIComponent(resourceType)}/continue`,
{ limit }
),
{ method: "POST" }
);
}
+680
View File
@@ -0,0 +1,680 @@
import { ChevronDown, ExternalLink, Filter, Search, X } from "lucide-react";
import {
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
type FormEvent,
type KeyboardEvent as ReactKeyboardEvent
} from "react";
import { useLocation } from "react-router";
import {
Button,
Dialog,
DocumentationHelpLink,
DismissibleAlert,
IconButton,
LoadingIndicator,
PageScrollViewport,
SegmentedControl,
useGuardedNavigate,
usePlatformModules,
usePlatformUiCapabilities,
type GlobalSearchProps,
type SearchContextsUiCapability
} from "@govoplan/core-webui";
import {
listSearchProviders,
search,
type SearchResourceType,
type SearchResponse,
type SearchResult
} from "../api/search";
import {
calculateSearchOverlayLayout,
selectSearchContext,
type SearchOverlayLayout
} from "./searchOverlayLayout";
const MIN_QUERY_LENGTH = 2;
type SearchScope = "global" | "context";
export default function GlobalSearch({ settings }: GlobalSearchProps) {
const navigate = useGuardedNavigate();
const location = useLocation();
const platformModules = usePlatformModules();
const contextCapabilities = usePlatformUiCapabilities<SearchContextsUiCapability>("search.contexts");
const availableContexts = useMemo(
() => contextCapabilities.flatMap((capability) => capability.contexts),
[contextCapabilities]
);
const currentContext = useMemo(
() => selectSearchContext(availableContexts, location.pathname),
[availableContexts, location.pathname]
);
const moduleLabels = useMemo(
() => new Map(platformModules.map((module) => [module.id, module.label])),
[platformModules]
);
const [query, setQuery] = useState("");
const [modules, setModules] = useState<string[]>([]);
const [resourceTypes, setResourceTypes] = useState<string[]>([]);
const [scope, setScope] = useState<SearchScope>(currentContext ? "context" : "global");
const [response, setResponse] = useState<SearchResponse | null>(null);
const [resourceCatalogue, setResourceCatalogue] = useState<SearchResourceType[]>([]);
const [open, setOpen] = useState(false);
const [layout, setLayout] = useState<SearchOverlayLayout | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [filtersOpen, setFiltersOpen] = useState(false);
const [activeIndex, setActiveIndex] = useState(-1);
const rootRef = useRef<HTMLButtonElement>(null);
const overlayInputRef = useRef<HTMLInputElement>(null);
const filtersRef = useRef<HTMLDivElement>(null);
const resultsRef = useRef<HTMLDivElement>(null);
const requestSequenceRef = useRef(0);
const loadMoreControllerRef = useRef<AbortController | null>(null);
const effectiveModules = useMemo(
() => scope === "context" && currentContext
? [currentContext.moduleId]
: modules,
[currentContext, modules, scope]
);
const effectiveResourceTypes = useMemo(() => {
if (scope !== "context" || !currentContext?.resourceTypes?.length) return resourceTypes;
if (resourceTypes.length === 0) return currentContext.resourceTypes;
return resourceTypes.filter((resourceType) => currentContext.resourceTypes?.includes(resourceType));
}, [currentContext, resourceTypes, scope]);
const effectiveModuleKey = effectiveModules.join("\u001f");
const effectiveResourceTypeKey = effectiveResourceTypes.join("\u001f");
const activeFilterCount = (scope === "global" ? modules.length : 0) + resourceTypes.length;
const moduleOptions = useMemo(() => {
const values = new Set(resourceCatalogue.map((resource) => resource.module_id));
for (const result of response?.results ?? []) values.add(result.module_id);
for (const moduleId of modules) values.add(moduleId);
return [...values]
.map((value) => ({
value,
label: moduleLabels.get(value) ?? humanizeIdentifier(value)
}))
.sort((left, right) => left.label.localeCompare(right.label));
}, [moduleLabels, modules, resourceCatalogue, response]);
const resourceTypeOptions = useMemo(() => {
const labels = new Map<string, string>();
for (const resource of resourceCatalogue) {
if (effectiveModules.length === 0 || effectiveModules.includes(resource.module_id)) {
labels.set(resource.resource_type, resource.label);
}
}
for (const result of response?.results ?? []) {
if (effectiveModules.length === 0 || effectiveModules.includes(result.module_id)) {
if (!labels.has(result.resource_type)) {
labels.set(result.resource_type, humanizeIdentifier(result.resource_type));
}
}
}
for (const resourceType of resourceTypes) {
if (!labels.has(resourceType)) {
labels.set(resourceType, humanizeIdentifier(resourceType));
}
}
return [...labels]
.map(([value, label]) => ({ value, label }))
.sort((left, right) => left.label.localeCompare(right.label));
}, [effectiveModules, resourceCatalogue, resourceTypes, response]);
const measureOverlay = useCallback(() => {
const rect = rootRef.current?.getBoundingClientRect();
if (!rect) return null;
const next = calculateSearchOverlayLayout(
{
top: rect.top,
left: rect.left,
width: rect.width,
height: rect.height
},
window.innerWidth,
window.innerHeight
);
setLayout(next);
return next;
}, []);
const closeOverlay = useCallback(() => {
loadMoreControllerRef.current?.abort();
setOpen(false);
setFiltersOpen(false);
setActiveIndex(-1);
}, []);
const openOverlay = useCallback(() => {
if (!measureOverlay()) return;
setOpen(true);
}, [measureOverlay]);
useEffect(() => {
function focusSearch(event: KeyboardEvent) {
const commandSearch =
(event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "k";
if (event.key !== "F3" && !commandSearch) return;
event.preventDefault();
openOverlay();
}
window.addEventListener("keydown", focusSearch);
return () => window.removeEventListener("keydown", focusSearch);
}, [openOverlay]);
useEffect(() => {
if (open) return;
setScope(currentContext ? "context" : "global");
}, [currentContext, open]);
useEffect(() => {
if (scope !== "context" || !currentContext?.resourceTypes?.length) return;
setResourceTypes((selected) => {
const compatible = selected.filter((resourceType) =>
currentContext.resourceTypes?.includes(resourceType)
);
return compatible.length === selected.length ? selected : compatible;
});
}, [currentContext, scope]);
useLayoutEffect(() => {
if (!open) return undefined;
measureOverlay();
const observer = typeof ResizeObserver === "undefined" || !rootRef.current
? null
: new ResizeObserver(measureOverlay);
observer?.observe(rootRef.current);
window.addEventListener("resize", measureOverlay);
return () => {
observer?.disconnect();
window.removeEventListener("resize", measureOverlay);
};
}, [measureOverlay, open]);
useEffect(() => {
if (!open) return undefined;
const controller = new AbortController();
listSearchProviders(settings, controller.signal)
.then((result) => setResourceCatalogue(result.resources ?? []))
.catch((reason) => {
if ((reason as Error).name !== "AbortError") setResourceCatalogue([]);
});
return () => controller.abort();
}, [open, settings]);
useEffect(() => {
if (!open || !filtersOpen) return undefined;
function closeFilters(event: MouseEvent) {
if (filtersRef.current && !filtersRef.current.contains(event.target as Node)) {
setFiltersOpen(false);
}
}
window.addEventListener("mousedown", closeFilters);
return () => window.removeEventListener("mousedown", closeFilters);
}, [filtersOpen, open]);
useEffect(() => {
if (!open) return undefined;
const normalizedQuery = query.trim();
requestSequenceRef.current += 1;
const sequence = requestSequenceRef.current;
if (normalizedQuery.length < MIN_QUERY_LENGTH) {
setResponse(null);
setLoading(false);
setError("");
setActiveIndex(-1);
return undefined;
}
const controller = new AbortController();
const timer = window.setTimeout(() => {
setLoading(true);
setError("");
search(
settings,
{
query: normalizedQuery,
modules: effectiveModules,
resourceTypes: effectiveResourceTypes,
contextKind: scope === "context" && currentContext ? "module" : "global",
contextId: scope === "context" ? currentContext?.id : undefined,
limit: 50
},
controller.signal
)
.then((next) => {
if (sequence !== requestSequenceRef.current) return;
setResponse(next);
setActiveIndex(-1);
})
.catch((reason) => {
if ((reason as Error).name !== "AbortError" && sequence === requestSequenceRef.current) {
setError(reason instanceof Error ? reason.message : "Search failed.");
setResponse(null);
}
})
.finally(() => {
if (sequence === requestSequenceRef.current) setLoading(false);
});
}, 180);
return () => {
window.clearTimeout(timer);
controller.abort();
};
}, [
currentContext,
effectiveModuleKey,
effectiveResourceTypeKey,
open,
query,
scope,
settings
]);
useEffect(() => {
if (activeIndex < 0) return;
resultsRef.current
?.querySelector<HTMLElement>(`[data-search-result-index="${activeIndex}"]`)
?.scrollIntoView({ block: "nearest" });
}, [activeIndex]);
function openResult(result: SearchResult) {
closeOverlay();
navigate(result.url);
}
function toggleFilter(name: "module" | "resource_type", value: string) {
if (name === "module") {
setModules((selected) =>
selected.includes(value)
? selected.filter((item) => item !== value)
: [...selected, value].sort()
);
return;
}
setResourceTypes((selected) =>
selected.includes(value)
? selected.filter((item) => item !== value)
: [...selected, value].sort()
);
}
function clearFilters() {
setModules([]);
setResourceTypes([]);
}
function handleOverlaySubmit(event: FormEvent) {
event.preventDefault();
const activeResult = activeIndex >= 0 ? response?.results[activeIndex] : null;
if (activeResult) openResult(activeResult);
}
function handleOverlayKeyDown(event: ReactKeyboardEvent<HTMLInputElement>) {
const results = response?.results ?? [];
if (event.key === "ArrowDown" && results.length > 0) {
event.preventDefault();
setActiveIndex((current) => (current + 1) % results.length);
return;
}
if (event.key === "ArrowUp" && results.length > 0) {
event.preventDefault();
setActiveIndex((current) => current <= 0 ? results.length - 1 : current - 1);
}
}
async function loadMore() {
const cursor = response?.next_cursor;
if (!cursor || loading) return;
loadMoreControllerRef.current?.abort();
const controller = new AbortController();
loadMoreControllerRef.current = controller;
setLoading(true);
setError("");
try {
const next = await search(
settings,
{
query: query.trim(),
modules: effectiveModules,
resourceTypes: effectiveResourceTypes,
contextKind: scope === "context" && currentContext ? "module" : "global",
contextId: scope === "context" ? currentContext?.id : undefined,
limit: 50,
cursor
},
controller.signal
);
setResponse((current) => current
? {
...next,
results: [...current.results, ...next.results],
diagnostics: [
...current.diagnostics,
...next.diagnostics.filter((diagnostic) =>
!current.diagnostics.some((currentDiagnostic) =>
currentDiagnostic.provider_id === diagnostic.provider_id
)
)
]
}
: next
);
} catch (reason) {
if ((reason as Error).name !== "AbortError") {
setError(reason instanceof Error ? reason.message : "Search failed.");
}
} finally {
if (loadMoreControllerRef.current === controller) {
loadMoreControllerRef.current = null;
setLoading(false);
}
}
}
return (
<>
<button
ref={rootRef}
type="button"
data-help-context-id="search.global"
data-help-module-id="search"
data-help-scope="action"
className={`titlebar-icon-link titlebar-search-button${open ? " is-context-active" : ""}`}
title="Search (F3 / Ctrl+K)"
aria-label="Global search"
aria-keyshortcuts="F3 Control+K Meta+K"
aria-haspopup="dialog"
aria-expanded={open}
onClick={openOverlay}>
<Search size={18} aria-hidden="true" />
</button>
<Dialog
open={open && Boolean(layout)}
title="Search"
helpContextId="search.results"
onClose={closeOverlay}
showCloseButton={false}
portal
className="search-overlay-dialog"
backdropClassName="search-overlay-backdrop"
headerClassName="search-overlay-dialog-header"
bodyClassName="search-overlay-dialog-body"
panelStyle={layout
? {
top: layout.top,
left: layout.left,
width: layout.width,
maxHeight: layout.maxHeight
}
: undefined}>
{layout &&
<>
<div
className="search-overlay-input-position"
style={{
width: layout.inputWidth,
height: layout.inputHeight,
marginLeft: layout.inputOffset
}}>
<form className="global-search global-search-overlay-input" onSubmit={handleOverlaySubmit}>
<Search size={16} aria-hidden="true" />
<input
ref={overlayInputRef}
autoFocus
type="search"
value={query}
placeholder={
scope === "context" && currentContext?.placeholder
? currentContext.placeholder
: "Search"
}
aria-label="Global search"
aria-keyshortcuts="F3 Control+K Meta+K"
aria-expanded={true}
aria-controls="global-search-overlay-results"
onChange={(event) => setQuery(event.target.value)}
onKeyDown={handleOverlayKeyDown}
/>
{query &&
<button
type="button"
className="global-search-clear"
aria-label="Clear search"
onClick={() => {
setQuery("");
setResponse(null);
setActiveIndex(-1);
overlayInputRef.current?.focus();
}}>
<X size={14} />
</button>
}
</form>
</div>
<section
className="search-overlay-results-panel"
style={{ height: layout.resultsHeight }}>
<div className="search-overlay-toolbar">
{currentContext &&
<SegmentedControl<SearchScope>
className="search-overlay-scope"
value={scope}
size="content"
width="inline"
ariaLabel="Search scope"
options={[
{ id: "context", label: currentContext.label },
{ id: "global", label: "Everywhere" }
]}
onChange={(value) => {
setScope(value);
setActiveIndex(-1);
}}
/>
}
<div className="search-filter-menu" ref={filtersRef}>
<Button
type="button"
variant="secondary"
className={`search-filter-trigger${activeFilterCount ? " is-active" : ""}`}
aria-haspopup="dialog"
aria-expanded={filtersOpen}
onClick={() => setFiltersOpen((current) => !current)}>
<Filter size={16} aria-hidden="true" />
<span>Filters</span>
{activeFilterCount > 0 &&
<span className="search-filter-count" aria-label={`${activeFilterCount} active filters`}>
{activeFilterCount}
</span>
}
</Button>
{filtersOpen &&
<div className="search-filter-popover" role="dialog" aria-label="Filter search results">
<div className="search-filter-popover-header">
<strong>Filter results</strong>
<IconButton
label="Close filters"
icon={<X size={16} />}
variant="ghost"
onClick={() => setFiltersOpen(false)}
/>
</div>
{scope === "global" &&
<fieldset className="search-filter-group">
<legend>Modules</legend>
<div className="search-filter-options">
{moduleOptions.map((option) =>
<label key={option.value}>
<input
type="checkbox"
checked={modules.includes(option.value)}
onChange={() => toggleFilter("module", option.value)}
/>
<span>{option.label}</span>
</label>
)}
{moduleOptions.length === 0 &&
<span className="search-filter-empty">No module filters available.</span>
}
</div>
</fieldset>
}
<fieldset className="search-filter-group">
<legend>Result types</legend>
<div className="search-filter-options">
{resourceTypeOptions.map((option) =>
<label key={option.value}>
<input
type="checkbox"
checked={resourceTypes.includes(option.value)}
onChange={() => toggleFilter("resource_type", option.value)}
/>
<span>{option.label}</span>
</label>
)}
{resourceTypeOptions.length === 0 &&
<span className="search-filter-empty">No result type filters available.</span>
}
</div>
</fieldset>
<div className="search-filter-popover-footer">
<Button
type="button"
variant="ghost"
disabled={activeFilterCount === 0}
onClick={clearFilters}>
Clear filters
</Button>
</div>
</div>
}
</div>
{loading && <LoadingIndicator size="sm" label="Searching" />}
<DocumentationHelpLink
reference={{ topicId: "search.global-and-contextual", documentationType: "user" }}
label="Open search documentation"
/>
<IconButton
label="Close search"
icon={<X size={17} />}
variant="ghost"
className="search-overlay-close"
onClick={closeOverlay}
/>
{activeFilterCount > 0 &&
<div className="search-active-filters" aria-label="Active search filters">
{scope === "global" && modules.map((moduleId) =>
<button
type="button"
key={`module:${moduleId}`}
onClick={() => toggleFilter("module", moduleId)}
aria-label={`Remove ${moduleLabels.get(moduleId) ?? moduleId} filter`}>
<span>{moduleLabels.get(moduleId) ?? humanizeIdentifier(moduleId)}</span>
<X size={13} />
</button>
)}
{resourceTypes.map((resourceType) =>
<button
type="button"
key={`resource-type:${resourceType}`}
onClick={() => toggleFilter("resource_type", resourceType)}
aria-label={`Remove ${humanizeIdentifier(resourceType)} filter`}>
<span>{humanizeIdentifier(resourceType)}</span>
<X size={13} />
</button>
)}
</div>
}
</div>
<PageScrollViewport
id="global-search-overlay-results"
ref={resultsRef}
className="search-overlay-results-viewport"
role="listbox"
aria-label="Search results">
{error &&
<DismissibleAlert tone="danger" onDismiss={() => setError("")}>
{error}
</DismissibleAlert>
}
{response?.diagnostics.map((diagnostic) =>
<DismissibleAlert
key={diagnostic.provider_id}
tone="warning"
compact>
{diagnostic.message}
</DismissibleAlert>
)}
{query.trim().length < MIN_QUERY_LENGTH &&
<div className="search-empty search-overlay-empty">
Type at least {MIN_QUERY_LENGTH} characters to search.
</div>
}
{query.trim().length >= MIN_QUERY_LENGTH && !loading && response?.results.length === 0 &&
<div className="search-empty search-overlay-empty">No results for {query.trim()}.</div>
}
<div className="search-result-list">
{response?.results.map((result, index) =>
<button
type="button"
role="option"
aria-selected={activeIndex === index}
data-search-result-index={index}
className={`search-result${activeIndex === index ? " active" : ""}`}
key={`${result.module_id}:${result.resource_type}:${result.resource_id}`}
onMouseMove={() => setActiveIndex(index)}
onClick={() => openResult(result)}>
<span className="search-result-heading">
<strong>{result.title}</strong>
{result.external_reference?.canonical_url &&
<ExternalLink size={14} aria-label="External result" />
}
</span>
{result.summary && <span className="search-result-summary">{result.summary}</span>}
<span className="search-result-meta">
{result.breadcrumbs.length > 0
? result.breadcrumbs.join(" · ")
: `${moduleLabels.get(result.module_id) ?? humanizeIdentifier(result.module_id)} · ${humanizeIdentifier(result.resource_type)}`}
</span>
</button>
)}
</div>
{response?.next_cursor &&
<Button
type="button"
variant="secondary"
className="search-load-more"
disabled={loading}
onClick={() => void loadMore()}>
<ChevronDown size={16} />
<span>Load more</span>
</Button>
}
</PageScrollViewport>
</section>
</>
}
</Dialog>
</>
);
}
function humanizeIdentifier(value: string): string {
return value
.replace(/[._:-]+/g, " ")
.replace(/\b\w/g, (character) => character.toUpperCase());
}
@@ -0,0 +1,84 @@
import type { SearchContextContribution } from "@govoplan/core-webui";
export type SearchOverlayAnchor = {
top: number;
left: number;
width: number;
height: number;
};
export type SearchOverlayLayout = {
top: number;
left: number;
width: number;
maxHeight: number;
inputOffset: number;
inputWidth: number;
inputHeight: number;
resultsHeight: number;
};
const DESKTOP_PANEL_WIDTH = 820;
const DESKTOP_MARGIN = 16;
const MOBILE_MARGIN = 12;
const MOBILE_BREAKPOINT = 900;
const RESULTS_GAP = 8;
export function calculateSearchOverlayLayout(
anchor: SearchOverlayAnchor,
viewportWidth: number,
viewportHeight: number
): SearchOverlayLayout {
const mobile = viewportWidth < MOBILE_BREAKPOINT;
const margin = mobile ? MOBILE_MARGIN : DESKTOP_MARGIN;
const width = Math.max(1, Math.min(DESKTOP_PANEL_WIDTH, viewportWidth - margin * 2));
const left = Math.max(margin, (viewportWidth - width) / 2);
const inputWidth = width;
const inputOffset = 0;
const top = Math.max(0, anchor.top);
const inputHeight = Math.max(1, anchor.height);
const availableResultsHeight = viewportHeight - top - inputHeight - RESULTS_GAP - margin;
const resultsHeight = Math.max(96, Math.min(620, availableResultsHeight));
return {
top,
left,
width,
maxHeight: inputHeight + RESULTS_GAP + resultsHeight,
inputOffset,
inputWidth,
inputHeight,
resultsHeight
};
}
export function selectSearchContext(
contexts: readonly SearchContextContribution[],
pathname: string
): SearchContextContribution | null {
const matches = contexts.flatMap((context) =>
context.pathPrefixes
.filter((prefix) => pathMatchesPrefix(pathname, prefix))
.map((prefix) => ({ context, prefixLength: normalizePath(prefix).length }))
);
matches.sort((left, right) =>
right.prefixLength - left.prefixLength
|| (left.context.order ?? 100) - (right.context.order ?? 100)
|| left.context.id.localeCompare(right.context.id)
);
return matches[0]?.context ?? null;
}
function pathMatchesPrefix(pathname: string, prefix: string): boolean {
const normalizedPath = normalizePath(pathname);
const normalizedPrefix = normalizePath(prefix);
return normalizedPrefix === "/"
|| normalizedPath === normalizedPrefix
|| normalizedPath.startsWith(`${normalizedPrefix}/`);
}
function normalizePath(value: string): string {
const normalized = `/${String(value || "").trim().replace(/^\/+|\/+$/g, "")}`;
return normalized === "/" ? normalized : normalized.replace(/\/+$/g, "");
}
@@ -0,0 +1,291 @@
import { useEffect, useMemo, useState } from "react";
import {
AdminPageLayout,
adminErrorMessage,
Button,
Card,
DataGrid,
DismissibleAlert,
DocumentationHelpLink,
MetricCard,
StatusBadge,
TableActionGroup,
type ApiSettings,
type DataGridColumn
} from "@govoplan/core-webui";
import { Play, RefreshCw, RotateCw } from "lucide-react";
import {
continueSearchRebuild,
getSearchDiagnostics,
listSearchProviders,
processSearchChanges,
reconcileSearchModules,
startSearchRebuild,
type SearchDiagnostics,
type SearchIndexState,
type SearchResourceType
} from "../../api/search";
type Props = {
settings: ApiSettings;
};
type ResourceRow = SearchResourceType & {
state?: SearchIndexState;
};
const DOCUMENTATION = {
topicId: "search.global-and-contextual",
documentationType: "admin" as const
};
export default function SearchAdminPanel({ settings }: Props) {
const [diagnostics, setDiagnostics] = useState<SearchDiagnostics | null>(null);
const [resources, setResources] = useState<SearchResourceType[]>([]);
const [loading, setLoading] = useState(true);
const [busyKey, setBusyKey] = useState("");
const [error, setError] = useState("");
const [success, setSuccess] = useState("");
useEffect(() => {
void load();
}, [settings.accessToken, settings.apiBaseUrl, settings.apiKey]);
async function load() {
setLoading(true);
setError("");
try {
const [nextDiagnostics, catalogue] = await Promise.all([
getSearchDiagnostics(settings),
listSearchProviders(settings)
]);
setDiagnostics(nextDiagnostics);
setResources(catalogue.resources);
} catch (err) {
setError(adminErrorMessage(err));
} finally {
setLoading(false);
}
}
async function runAction(key: string, action: () => Promise<string>) {
setBusyKey(key);
setError("");
setSuccess("");
try {
setSuccess(await action());
await load();
} catch (err) {
setError(adminErrorMessage(err));
} finally {
setBusyKey("");
}
}
const rows = useMemo<ResourceRow[]>(() => {
const states = new Map(
(diagnostics?.states ?? []).map((state) => [
`${state.provider_id}:${state.resource_type}`,
state
])
);
return resources.map((resource) => ({
...resource,
state: states.get(`${resource.provider_id}:${resource.resource_type}`)
}));
}, [diagnostics, resources]);
const columns = useMemo<DataGridColumn<ResourceRow>[]>(() => [
{
id: "resource",
header: "Search source",
minWidth: 250,
resizable: true,
sortable: true,
filterable: true,
value: (row) => row.label,
render: (row) => (
<div>
<strong>{row.label}</strong>
<div className="muted">{row.module_id} / {row.provider_id}</div>
</div>
)
},
{
id: "status",
header: "State",
width: 135,
minWidth: 115,
sortable: true,
filterable: true,
filterType: "list",
value: (row) => row.state?.status ?? "not built",
render: (row) => (
<StatusBadge
status={statusTone(row.state?.status)}
label={row.state?.status ?? "not built"}
/>
)
},
{
id: "documents",
header: "Documents",
width: 125,
minWidth: 105,
align: "right",
value: (row) => row.state?.indexed_documents ?? 0
},
{
id: "rejected",
header: "Rejected",
width: 105,
minWidth: 90,
align: "right",
value: (row) => row.state?.rejected_documents ?? 0
},
{
id: "lastSuccess",
header: "Last success",
width: 190,
minWidth: 165,
sortable: true,
value: (row) => row.state?.last_success_at ?? "",
render: (row) => formatDateTime(row.state?.last_success_at)
},
{
id: "actions",
header: "Actions",
width: 80,
minWidth: 80,
sticky: "end",
align: "right",
render: (row) => {
const key = `${row.provider_id}:${row.resource_type}`;
const continuing = row.state?.status === "backfilling";
return (
<TableActionGroup
minimumSlots={1}
actions={[{
id: "rebuild",
label: continuing ? "Continue bounded rebuild" : "Start clean rebuild",
icon: continuing ? <Play size={16} /> : <RotateCw size={16} />,
disabled: Boolean(busyKey),
onClick: () => void runAction(key, async () => {
const response = continuing
? await continueSearchRebuild(settings, row.provider_id, row.resource_type)
: await startSearchRebuild(settings, row.provider_id, row.resource_type);
return response.state.status === "backfilling"
? `${row.label} rebuild advanced to the next checkpoint.`
: `${row.label} rebuild completed.`;
})
}]}
/>
);
}
}
], [busyKey, settings]);
const queue = diagnostics?.queue ?? {};
const pending = (queue.queued ?? 0) + (queue.retrying ?? 0);
const quarantined = queue.quarantined ?? 0;
return (
<AdminPageLayout
title="Search index"
description="Inspect source coverage, process durable changes, and reconcile the tenant's derived index from authoritative modules."
loading={loading}
error={error}
success={success}
actions={(
<>
<Button
title="Reload search diagnostics"
aria-label="Reload search diagnostics"
onClick={() => void load()}
disabled={loading || Boolean(busyKey)}
>
<RefreshCw size={16} />
</Button>
<Button
onClick={() => void runAction("process", async () => {
const result = await processSearchChanges(settings);
return `Applied ${result.applied} queued changes; ${result.retrying} remain retryable and ${result.quarantined} were quarantined.`;
})}
disabled={Boolean(busyKey)}
>
<Play size={16} /> Process queue
</Button>
<Button
onClick={() => void runAction("reconcile", async () => {
const result = await reconcileSearchModules(settings);
return `Reconciled active modules: ${result.enabled_documents} enabled and ${result.disabled_documents} disabled documents updated.`;
})}
disabled={Boolean(busyKey)}
>
<RotateCw size={16} /> Reconcile modules
</Button>
<DocumentationHelpLink
reference={DOCUMENTATION}
label="Open Search administration documentation"
/>
</>
)}
>
<div className="metric-grid">
<MetricCard label="Search sources" value={rows.length} tone="neutral" />
<MetricCard label="Pending changes" value={pending} tone={pending ? "warning" : "good"} />
<MetricCard label="Quarantined" value={quarantined} tone={quarantined ? "danger" : "good"} />
<MetricCard label="Backend" value={diagnostics?.backend ?? "-"} tone="neutral" />
</div>
{quarantined > 0 && (
<DismissibleAlert tone="warning" dismissible={false} compact>
Quarantined changes require source or contract repair followed by a source rebuild. They are never silently discarded.
</DismissibleAlert>
)}
<Card title="Native source coverage">
<div className="admin-table-surface">
<DataGrid
id="search-index-sources-v1"
rows={rows}
columns={columns}
getRowKey={(row) => `${row.provider_id}:${row.resource_type}`}
initialFit="container"
emptyText="No active modules announce searchable resource types."
/>
</div>
</Card>
{rows.some((row) => row.state?.last_error) && (
<Card title="Latest source errors">
<div className="settings-list">
{rows.filter((row) => row.state?.last_error).map((row) => (
<DismissibleAlert
key={`${row.provider_id}:${row.resource_type}`}
tone="warning"
dismissible={false}
compact
>
<strong>{row.label}:</strong> {row.state?.last_error}
</DismissibleAlert>
))}
</div>
</Card>
)}
</AdminPageLayout>
);
}
function statusTone(status?: string): string {
if (["ready", "idle"].includes(status ?? "")) return "success";
if (["failed", "quarantined"].includes(status ?? "")) return "danger";
if (["backfilling", "stale"].includes(status ?? "")) return "warning";
return "neutral";
}
function formatDateTime(value?: string | null): string {
if (!value) return "-";
const parsed = new Date(value);
return Number.isNaN(parsed.getTime()) ? value : parsed.toLocaleString();
}
+387
View File
@@ -0,0 +1,387 @@
import { ChevronDown, ExternalLink, Filter, Search, X } from "lucide-react";
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
type FormEvent
} from "react";
import { useSearchParams } from "react-router";
import {
Button,
DocumentationHelpLink,
DismissibleAlert,
IconButton,
LoadingIndicator,
PageScrollViewport,
useGuardedNavigate,
usePlatformModules,
type PlatformRouteContext
} from "@govoplan/core-webui";
import {
listSearchProviders,
search,
type SearchResourceType,
type SearchResponse
} from "../../api/search";
export default function SearchPage({ settings }: PlatformRouteContext) {
const navigate = useGuardedNavigate();
const platformModules = usePlatformModules();
const [params, setParams] = useSearchParams();
const query = params.get("q") ?? "";
const moduleKey = params.getAll("module").join("\u001f");
const resourceTypeKey = params.getAll("resource_type").join("\u001f");
const contextId = params.get("context") ?? undefined;
const modules = useMemo(
() => moduleKey ? moduleKey.split("\u001f") : [],
[moduleKey]
);
const resourceTypes = useMemo(
() => resourceTypeKey ? resourceTypeKey.split("\u001f") : [],
[resourceTypeKey]
);
const [draft, setDraft] = useState(query);
const [response, setResponse] = useState<SearchResponse | null>(null);
const [resourceCatalogue, setResourceCatalogue] = useState<SearchResourceType[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [filtersOpen, setFiltersOpen] = useState(false);
const filtersRef = useRef<HTMLDivElement>(null);
const requestKey = useMemo(
() => JSON.stringify([query, moduleKey, resourceTypeKey, contextId]),
[contextId, moduleKey, query, resourceTypeKey]
);
useEffect(() => {
setDraft(query);
}, [query]);
useEffect(() => {
const controller = new AbortController();
listSearchProviders(settings, controller.signal).
then((result) => setResourceCatalogue(result.resources ?? [])).
catch((reason) => {
if ((reason as Error).name !== "AbortError") setResourceCatalogue([]);
});
return () => controller.abort();
}, [settings]);
useEffect(() => {
function closeFilters(event: MouseEvent) {
if (filtersRef.current && !filtersRef.current.contains(event.target as Node)) {
setFiltersOpen(false);
}
}
function closeFiltersWithKeyboard(event: KeyboardEvent) {
if (event.key === "Escape") setFiltersOpen(false);
}
window.addEventListener("mousedown", closeFilters);
window.addEventListener("keydown", closeFiltersWithKeyboard);
return () => {
window.removeEventListener("mousedown", closeFilters);
window.removeEventListener("keydown", closeFiltersWithKeyboard);
};
}, []);
const moduleLabels = useMemo(
() => new Map(platformModules.map((module) => [module.id, module.label])),
[platformModules]
);
const moduleOptions = useMemo(() => {
const values = new Set(resourceCatalogue.map((resource) => resource.module_id));
for (const result of response?.results ?? []) values.add(result.module_id);
for (const moduleId of modules) values.add(moduleId);
return [...values].
map((value) => ({
value,
label: moduleLabels.get(value) ?? humanizeIdentifier(value)
})).
sort((left, right) => left.label.localeCompare(right.label));
}, [moduleLabels, modules, resourceCatalogue, response]);
const resourceTypeOptions = useMemo(() => {
const labels = new Map<string, string>();
for (const resource of resourceCatalogue) {
if (modules.length === 0 || modules.includes(resource.module_id)) {
labels.set(resource.resource_type, resource.label);
}
}
for (const result of response?.results ?? []) {
if (modules.length === 0 || modules.includes(result.module_id)) {
if (!labels.has(result.resource_type)) {
labels.set(result.resource_type, humanizeIdentifier(result.resource_type));
}
}
}
for (const resourceType of resourceTypes) {
if (!labels.has(resourceType)) {
labels.set(resourceType, humanizeIdentifier(resourceType));
}
}
return [...labels].
map(([value, label]) => ({ value, label })).
sort((left, right) => left.label.localeCompare(right.label));
}, [modules, resourceCatalogue, resourceTypes, response]);
const activeFilterCount = modules.length + resourceTypes.length;
const loadResults = useCallback((cursor?: string) => {
const controller = new AbortController();
setLoading(true);
setError("");
search(
settings,
{
query,
modules,
resourceTypes,
contextKind: modules.length ? "module" : "global",
contextId,
limit: 50,
cursor
},
controller.signal
).
then((next) => {
setResponse((current) =>
cursor && current ?
{
...next,
results: [...current.results, ...next.results],
diagnostics: [
...current.diagnostics,
...next.diagnostics.filter((item) =>
!current.diagnostics.some(
(currentItem) => currentItem.provider_id === item.provider_id
)
)
]
} :
next
);
}).
catch((reason) => {
if ((reason as Error).name !== "AbortError") {
setError(reason instanceof Error ? reason.message : "Search failed.");
}
}).
finally(() => setLoading(false));
return controller;
}, [contextId, modules, query, resourceTypes, settings]);
useEffect(() => {
if (!query.trim()) {
setResponse(null);
return;
}
setResponse(null);
const controller = loadResults();
return () => controller.abort();
}, [loadResults, requestKey]);
function submit(event: FormEvent) {
event.preventDefault();
const next = new URLSearchParams(params);
if (draft.trim()) next.set("q", draft.trim());
else next.delete("q");
setParams(next);
}
function toggleFilter(name: "module" | "resource_type", value: string) {
const selected = name === "module" ? modules : resourceTypes;
const nextValues = selected.includes(value) ?
selected.filter((item) => item !== value) :
[...selected, value];
const next = new URLSearchParams(params);
next.delete(name);
for (const item of [...nextValues].sort()) next.append(name, item);
setParams(next);
}
function clearFilters() {
const next = new URLSearchParams(params);
next.delete("module");
next.delete("resource_type");
next.delete("context");
setParams(next);
}
return (
<main className="search-page">
<div className="search-page-toolbar">
<form className="search-page-form" onSubmit={submit}>
<Search size={18} aria-hidden="true" />
<input
value={draft}
onChange={(event) => setDraft(event.target.value)}
aria-label="Search query"
placeholder="Search"
autoFocus
/>
<Button type="submit" variant="primary">Search</Button>
</form>
<div className="search-filter-menu" ref={filtersRef}>
<Button
type="button"
className={`search-filter-trigger${activeFilterCount ? " is-active" : ""}`}
aria-haspopup="dialog"
aria-expanded={filtersOpen}
onClick={() => setFiltersOpen((current) => !current)}>
<Filter size={16} aria-hidden="true" />
<span>Filters</span>
{activeFilterCount > 0 &&
<span className="search-filter-count" aria-label={`${activeFilterCount} active filters`}>
{activeFilterCount}
</span>
}
</Button>
{filtersOpen &&
<div className="search-filter-popover" role="dialog" aria-label="Filter search results">
<div className="search-filter-popover-header">
<strong>Filter results</strong>
<IconButton
label="Close filters"
icon={<X size={16} />}
variant="ghost"
onClick={() => setFiltersOpen(false)}
/>
</div>
<fieldset className="search-filter-group">
<legend>Modules</legend>
<div className="search-filter-options">
{moduleOptions.map((option) =>
<label key={option.value}>
<input
type="checkbox"
checked={modules.includes(option.value)}
onChange={() => toggleFilter("module", option.value)}
/>
<span>{option.label}</span>
</label>
)}
{moduleOptions.length === 0 &&
<span className="search-filter-empty">No module filters available.</span>
}
</div>
</fieldset>
<fieldset className="search-filter-group">
<legend>Result types</legend>
<div className="search-filter-options">
{resourceTypeOptions.map((option) =>
<label key={option.value}>
<input
type="checkbox"
checked={resourceTypes.includes(option.value)}
onChange={() => toggleFilter("resource_type", option.value)}
/>
<span>{option.label}</span>
</label>
)}
{resourceTypeOptions.length === 0 &&
<span className="search-filter-empty">No result type filters available.</span>
}
</div>
</fieldset>
<div className="search-filter-popover-footer">
<Button
type="button"
variant="ghost"
disabled={activeFilterCount === 0}
onClick={clearFilters}>
Clear filters
</Button>
</div>
</div>
}
</div>
{loading && <LoadingIndicator size="sm" label="Searching" />}
<DocumentationHelpLink
reference={{ topicId: "search.global-and-contextual", documentationType: "user" }}
label="Open search documentation"
/>
{activeFilterCount > 0 &&
<div className="search-active-filters" aria-label="Active search filters">
{modules.map((moduleId) =>
<button
type="button"
key={`module:${moduleId}`}
onClick={() => toggleFilter("module", moduleId)}
aria-label={`Remove ${moduleLabels.get(moduleId) ?? moduleId} filter`}>
<span>{moduleLabels.get(moduleId) ?? humanizeIdentifier(moduleId)}</span>
<X size={13} />
</button>
)}
{resourceTypes.map((resourceType) =>
<button
type="button"
key={`resource-type:${resourceType}`}
onClick={() => toggleFilter("resource_type", resourceType)}
aria-label={`Remove ${humanizeIdentifier(resourceType)} filter`}>
<span>{humanizeIdentifier(resourceType)}</span>
<X size={13} />
</button>
)}
</div>
}
</div>
<PageScrollViewport className="search-results-viewport">
{error &&
<DismissibleAlert tone="danger" onDismiss={() => setError("")}>
{error}
</DismissibleAlert>
}
{response?.diagnostics.map((diagnostic) =>
<DismissibleAlert
key={diagnostic.provider_id}
tone="warning"
compact>
{diagnostic.message}
</DismissibleAlert>
)}
{query && response && response.results.length === 0 &&
<div className="search-empty">No results for {query}.</div>
}
<div className="search-result-list">
{response?.results.map((result) =>
<button
type="button"
className="search-result"
key={`${result.module_id}:${result.resource_type}:${result.resource_id}`}
onClick={() => navigate(result.url)}>
<span className="search-result-heading">
<strong>{result.title}</strong>
{result.external_reference?.canonical_url &&
<ExternalLink size={14} aria-label="External result" />
}
</span>
{result.summary && <span className="search-result-summary">{result.summary}</span>}
<span className="search-result-meta">
{result.breadcrumbs.length > 0 ?
result.breadcrumbs.join(" · ") :
`${result.module_id} · ${result.resource_type}`}
</span>
</button>
)}
</div>
{response?.next_cursor &&
<Button
type="button"
variant="secondary"
className="search-load-more"
disabled={loading}
onClick={() => loadResults(response.next_cursor ?? undefined)}>
<ChevronDown size={16} />
<span>Load more</span>
</Button>
}
</PageScrollViewport>
</main>
);
}
function humanizeIdentifier(value: string): string {
return value.
replace(/[._:-]+/g, " ").
replace(/\b\w/g, (character) => character.toUpperCase());
}
+2
View File
@@ -0,0 +1,2 @@
export { default, searchModule } from "./module";
export * from "./api/search";
+86
View File
@@ -0,0 +1,86 @@
import { createElement, lazy } from "react";
import type {
AdminSectionsUiCapability,
PlatformWebModule,
SearchRuntimeUiCapability
} from "@govoplan/core-webui";
import GlobalSearch from "./components/GlobalSearch";
import "./styles/search.css";
const SearchPage = lazy(() => import("./features/search/SearchPage"));
const SearchAdminPanel = lazy(() => import("./features/search/SearchAdminPanel"));
const searchRuntime: SearchRuntimeUiCapability = {
GlobalSearch,
anyOf: ["search:result:read"]
};
const searchAdminSections: AdminSectionsUiCapability = {
sections: [
{
id: "tenant-search-index",
moduleId: "search",
kind: "operations",
surfaceId: "search.admin.index",
label: "Search index",
group: "TENANT",
order: 69,
allOf: ["search:index:admin"],
render: ({ settings }) => createElement(SearchAdminPanel, { settings })
}
]
};
export const searchModule: PlatformWebModule = {
id: "search",
label: "Search",
version: "0.1.14",
optionalDependencies: [
"access",
"views",
"connectors",
"wiki",
"projects",
"tickets",
"cases"
],
routes: [
{
path: "/search",
anyOf: ["search:result:read"],
order: 12,
surfaceId: "search.results",
render: (context) => createElement(SearchPage, context)
}
],
viewSurfaces: [
{
id: "search.global",
moduleId: "search",
kind: "selector",
label: "Global search",
order: 10
},
{
id: "search.results",
moduleId: "search",
kind: "route",
label: "Search results",
order: 20
},
{
id: "search.admin.index",
moduleId: "search",
kind: "section",
label: "Search index administration",
order: 30
}
],
uiCapabilities: {
"search.runtime": searchRuntime,
"admin.sections": searchAdminSections
}
};
export default searchModule;
+474
View File
@@ -0,0 +1,474 @@
.global-search {
position: relative;
display: flex;
align-items: center;
width: 100%;
min-width: 0;
height: 34px;
box-sizing: border-box;
border: 1px solid var(--control-border);
border-radius: 4px;
background: var(--control-bg);
color: var(--muted);
padding: 0 8px;
box-shadow: var(--shadow-control-inset);
}
.global-search:focus-within {
border-color: var(--input-border-focus);
box-shadow: var(--focus-ring);
}
.global-search input {
min-width: 0;
flex: 1;
height: 30px;
border: 0;
outline: 0;
background: transparent;
color: var(--text-strong);
padding: 0 7px;
font: inherit;
font-size: 13px;
}
.global-search input::-webkit-search-cancel-button { display: none; }
.global-search-clear {
display: inline-flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
border: 0;
border-radius: 3px;
background: transparent;
color: var(--muted);
cursor: pointer;
padding: 0;
}
.global-search-clear:hover {
background: var(--titlebar-hover-bg);
color: var(--text-strong);
}
.search-overlay-backdrop {
display: block;
padding: 0;
backdrop-filter: blur(1px);
}
.search-overlay-dialog {
position: fixed;
display: flex;
overflow: visible;
border: 0;
border-radius: 0;
background: transparent;
box-shadow: none;
}
.search-overlay-dialog-header {
position: absolute;
width: 1px;
min-height: 0;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
clip-path: inset(50%);
border: 0;
padding: 0;
white-space: nowrap;
}
.search-overlay-dialog-body {
display: flex;
min-width: 0;
min-height: 0;
flex-direction: column;
overflow: visible;
padding: 0;
}
.search-overlay-input-position {
min-width: 0;
flex: 0 0 auto;
z-index: 1000;
}
.global-search-overlay-input {
box-shadow: var(--focus-ring);
}
.search-overlay-results-panel {
display: flex;
min-width: 0;
min-height: 0;
flex-direction: column;
margin-top: 8px;
overflow: hidden;
border: var(--border-line);
border-radius: 6px;
background: var(--surface);
box-shadow: var(--shadow-strong);
}
.search-overlay-toolbar {
position: relative;
z-index: 2;
display: flex;
align-items: center;
flex: 0 0 auto;
flex-wrap: wrap;
gap: 8px;
min-height: 48px;
border-bottom: var(--border-line);
background: var(--panel-header);
padding: 7px 10px;
}
.search-overlay-scope {
max-width: min(420px, 100%);
}
.search-overlay-close {
width: 32px;
height: 32px;
margin-left: auto;
padding: 0;
}
.search-overlay-toolbar .search-active-filters {
flex-basis: 100%;
}
.search-overlay-results-viewport {
min-height: 0;
flex: 1 1 auto;
padding: 8px 12px 14px;
}
.search-overlay-empty {
display: grid;
min-height: 120px;
place-items: center;
padding: 20px;
text-align: center;
}
.search-page {
display: flex;
min-width: 0;
min-height: 0;
height: 100%;
flex-direction: column;
background: var(--panel);
}
.search-page-toolbar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 12px;
flex: 0 0 auto;
border-bottom: var(--border-line);
background: var(--panel-header);
padding: 12px 20px;
}
.search-page-form {
display: flex;
align-items: center;
min-width: min(280px, 100%);
max-width: 760px;
height: 38px;
flex: 1 1 520px;
border: 1px solid var(--control-border);
border-radius: 4px;
background: var(--control-bg);
color: var(--muted);
padding-left: 10px;
}
.search-page-form:focus-within {
border-color: var(--input-border-focus);
box-shadow: var(--focus-ring);
}
.search-page-form input {
min-width: 0;
flex: 1;
height: 36px;
border: 0;
outline: 0;
background: transparent;
color: var(--text-strong);
padding: 0 10px;
font: inherit;
}
.search-page-form button {
align-self: stretch;
border: 0;
border-left: var(--border-line);
background: linear-gradient(var(--control-gradient-start), var(--control-gradient-end));
color: var(--control-text);
cursor: pointer;
padding: 0 16px;
font: inherit;
font-weight: 700;
}
.search-page-form button:hover {
background: linear-gradient(var(--control-gradient-start), var(--control-gradient-end-hover));
}
.search-filter-menu {
position: relative;
flex: 0 0 auto;
}
.search-filter-trigger {
min-height: 38px;
}
.search-filter-trigger.is-active {
border-color: var(--input-border-focus);
color: var(--text-strong);
}
.search-filter-count {
min-width: 19px;
height: 19px;
box-sizing: border-box;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 999px;
background: var(--accent);
color: var(--on-accent);
padding: 0 5px;
font-size: 11px;
line-height: 1;
}
.search-filter-popover {
position: absolute;
z-index: 400;
top: calc(100% + 7px);
left: 0;
display: flex;
width: min(340px, calc(100vw - 40px));
max-height: min(520px, calc(100vh - 150px));
flex-direction: column;
overflow: hidden;
border: var(--border-line);
border-radius: 6px;
background: var(--surface);
box-shadow: var(--shadow-menu);
}
.search-filter-popover-header,
.search-filter-popover-footer {
display: flex;
align-items: center;
flex: 0 0 auto;
padding: 9px 12px;
}
.search-filter-popover-header {
justify-content: space-between;
border-bottom: var(--border-line);
}
.search-filter-popover-header .icon-button {
width: 30px;
height: 30px;
padding: 0;
}
.search-filter-popover-footer {
justify-content: flex-end;
border-top: var(--border-line);
}
.search-filter-group {
min-height: 0;
margin: 0;
border: 0;
border-bottom: var(--border-line);
padding: 11px 12px 12px;
}
.search-filter-group:last-of-type {
border-bottom: 0;
}
.search-filter-group legend {
color: var(--muted);
padding: 0;
font-size: 11px;
font-weight: 800;
text-transform: uppercase;
}
.search-filter-options {
display: grid;
max-height: 150px;
gap: 2px;
overflow: auto;
margin-top: 7px;
}
.search-filter-options label {
display: flex;
align-items: center;
gap: 8px;
min-height: 31px;
border-radius: 4px;
cursor: pointer;
padding: 4px 7px;
color: var(--text);
}
.search-filter-options label:hover {
background: var(--sidebar-hover-bg);
color: var(--text-strong);
}
.search-filter-options input {
margin: 0;
accent-color: var(--accent);
}
.search-filter-empty {
color: var(--muted);
padding: 5px 7px;
font-size: 12px;
}
.search-active-filters {
display: flex;
flex: 1 0 100%;
flex-wrap: wrap;
gap: 7px;
}
.search-active-filters button {
display: inline-flex;
align-items: center;
gap: 6px;
min-height: 27px;
border: 1px solid var(--control-border);
border-radius: 4px;
background: var(--control-bg);
color: var(--text);
cursor: pointer;
padding: 3px 8px;
font: inherit;
font-size: 12px;
}
.search-active-filters button:hover {
border-color: var(--input-border-focus);
background: var(--sidebar-hover-bg);
}
.search-results-viewport {
min-height: 0;
flex: 1;
padding: 20px;
}
.search-result-list {
display: grid;
max-width: 960px;
}
.search-result {
display: grid;
gap: 6px;
width: 100%;
border: 0;
border-bottom: var(--border-line);
background: transparent;
color: var(--text);
cursor: pointer;
padding: 14px 12px;
text-align: left;
font: inherit;
}
.search-result:hover {
background: var(--sidebar-hover-bg);
}
.search-result.active {
background: var(--sidebar-hover-bg);
box-shadow: inset 3px 0 0 var(--accent);
}
.search-result-heading {
display: flex;
align-items: center;
gap: 7px;
color: var(--text-strong);
font-size: 15px;
}
.search-result-summary {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.search-result-meta,
.search-empty {
color: var(--muted);
font-size: 12px;
}
.search-load-more {
display: inline-flex;
align-items: center;
gap: 7px;
margin-top: 14px;
border: 1px solid var(--control-border);
border-radius: 4px;
background: linear-gradient(
var(--control-gradient-start),
var(--control-gradient-end)
);
color: var(--control-text);
cursor: pointer;
padding: 7px 12px;
font: inherit;
font-weight: 700;
}
.search-load-more:hover:not(:disabled) {
background: linear-gradient(
var(--control-gradient-start),
var(--control-gradient-end-hover)
);
}
.search-load-more:disabled {
cursor: default;
opacity: 0.55;
}
@media (max-width: 900px) {
.search-overlay-results-panel {
border-radius: 4px;
}
.search-overlay-toolbar {
gap: 6px;
}
.search-overlay-scope {
max-width: calc(100% - 86px);
}
}