Runway 1.0.0
This commit is contained in:
commit
dcf819146b
1372 files changed
+188168
No files matched your search
@@ -0,0 +1,53 @@
|
||||
# Runway plugins
|
||||
|
||||
This folder holds **Runway plugin projects**. Each plugin is a **standalone project** (its own build) that
|
||||
compiles against the Runway SPI only (`mx.quest:runway-spi`, plus `runway-spi-testkit` for its tests) from the local Maven repository and deploys as a
|
||||
folder under a Runway install's `external/plugins/<id>/`. The contract is **SPI `1.0.0`** (Runway `1.0.0`): the
|
||||
kernel blocks a plugin that links its internal classes. The SPI jars are not yet published to a Maven repository — see the authoring
|
||||
guide, §2.
|
||||
|
||||
Each Runway release on the releases page (<https://g.quest.mx/quest/runway/releases>) carries the zips of these
|
||||
plugins built for it, beside the kernel's own files and listed in the same `SHA256SUMS`.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
plugins/
|
||||
├── docs/PLUGIN-AUTHORING-GUIDE.md # THE canonical guide: build any Runway plugin from scratch
|
||||
├── demo/ # the reference "kitchen-sink" plugin — exercises EVERY seam
|
||||
├── search/ # on-site search: box widget + /search + /search/api + a published SiteSearchEngine SPI
|
||||
├── search-lucene/ # a Lucene engine for `search` (requires: search + lucene-provider; per-locale analyzers, heap or disk)
|
||||
└── lucene-provider/ # CODE-LESS library provider: bundles Apache Lucene under lib/ (no mainClass)
|
||||
```
|
||||
|
||||
The essential **protection** plugin is not here: it is `runway-plugin-protection` at the root of the repository,
|
||||
and ships inside the Runway installer.
|
||||
|
||||
Each plugin carries a `README.md` and a `plugin.yml` (and, when it has code, its unit tests), and versions independently (its
|
||||
version is in its `plugin.yml`). Each also carries a `docs/<NAME>-PLUGIN.md`, and most a
|
||||
`scripts/verify-against-host.sh` that checks it against the packaged host. One does not have the verify script:
|
||||
**`lucene-provider`** has `docs/LUCENE-PROVIDER-PLUGIN.md` but no verify script — it is a code-less library bundle
|
||||
with no code of its own to verify.
|
||||
|
||||
## Start here
|
||||
|
||||
- **Building a new plugin?** Read [`docs/PLUGIN-AUTHORING-GUIDE.md`](docs/PLUGIN-AUTHORING-GUIDE.md) — it covers
|
||||
the project setup, the `plugin.yml` descriptor, every SPI, settings, permissions, resources, build/install,
|
||||
and the pitfalls. Then **copy the closest existing plugin** as your starting template and strip what you don't
|
||||
need.
|
||||
- **Reference plugins by pattern:**
|
||||
- Every seam at once → [`demo/`](demo/).
|
||||
- Publishing your **own** SPI for other plugins → [`search/`](search/) (`SiteSearchEngine`).
|
||||
- Implementing another plugin's SPI (`requires:`) + **consuming a library-provider** (Lucene) → [`search-lucene/`](search-lucene/).
|
||||
- A **code-less library-provider** plugin (bundle a shared library under `lib/`, no `mainClass`) →
|
||||
[`lucene-provider/`](lucene-provider/) (Apache Lucene) — consumed by a `requires:` plugin (`search-lucene`).
|
||||
|
||||
## Conventions
|
||||
|
||||
- Each plugin project is self-contained, with no external dependencies beyond the host artifacts in `~/.m2`. The
|
||||
authoring guide lives at the top level (`docs/PLUGIN-AUTHORING-GUIDE.md`) and nowhere else is current:
|
||||
`demo/docs/PLUGIN-AUTHORING-GUIDE.md` is only a pointer to it.
|
||||
- Plugin **id** (and its install-folder name) is short and path-safe (e.g. `runway-demo`); the Maven artifactId
|
||||
is **`runway-plugin-<id>`** (so `runway-plugin-runway-demo`), because the release zip is named after it,
|
||||
`runway-plugin-<id>-<version>.zip`; the Java package lives **outside** `mx.quest.runway`.
|
||||
- Build with JDK 25 (point `JAVA_HOME` at it) and Maven.
|
||||
@@ -0,0 +1,6 @@
|
||||
target/
|
||||
*.class
|
||||
.idea/
|
||||
*.iml
|
||||
.vscode/
|
||||
.DS_Store
|
||||
@@ -0,0 +1,9 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [2.1.0] — 2026-10-21
|
||||
|
||||
First public release of `runway-demo`, the reference ("kitchen-sink") plugin: it exercises every extension axis and
|
||||
every service of the Runway SPI, and is meant to be copied as the start of a new plugin. Requires SPI `1.0.0`
|
||||
(Runway `1.0.0` or later). Licensed under the Apache License 2.0 (`LICENSE`, `NOTICE`).
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,6 @@
|
||||
runway-demo — the Runway reference plugin
|
||||
Copyright 2026 Quest ICT SAS de CV
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the file LICENSE). Unlike the Runway kernel, which is
|
||||
licensed under the GNU Affero General Public License version 3, this plugin is offered under a
|
||||
permissive license so that it can be copied as the starting point of a plugin under any terms.
|
||||
@@ -0,0 +1,84 @@
|
||||
# runway-demo — the Runway kitchen-sink reference plugin
|
||||
|
||||
One plugin that **exercises the whole Runway plugin contract**: every extension axis (head contributor, content
|
||||
widgets, endpoints including an anonymous form `POST`, a page-quality check, a content source) and **every service
|
||||
and callback of the SPI service tier** (SPI `1.0.0`: `PluginSettings`, `PluginInfo`/`PluginLifecycle`,
|
||||
`PluginSiteFiles`, `Sites`, `RequestContext`, `AccessCheck`, `Messages`, `SitePages`, `ContentCatalogView`,
|
||||
`ContentChanges`, `SiteEventListener`, `@ConsoleScreen`), plus every setting type, personal-data declaration,
|
||||
permissions, a menu entry, a dashboard card, an admin fragment, static assets, templates and i18n. It links **only
|
||||
the Runway SPI**. It is the worked reference for the canonical
|
||||
[authoring guide](../docs/PLUGIN-AUTHORING-GUIDE.md) and the template to copy when starting a new plugin.
|
||||
|
||||
- **The walkthrough — every service, what the demo does with it, when you would use it:**
|
||||
[`docs/DEMO-PLUGIN.md`](docs/DEMO-PLUGIN.md)
|
||||
- **How to build any Runway plugin:** [`../docs/PLUGIN-AUTHORING-GUIDE.md`](../docs/PLUGIN-AUTHORING-GUIDE.md)
|
||||
- **Release history:** [`CHANGELOG.md`](CHANGELOG.md)
|
||||
|
||||
## Requirements
|
||||
|
||||
A Runway kernel carrying **SPI `1.0.0`** or later: every `1.x` kernel (`requiresSpi: ">=1.0.0"` counts as a 1.x
|
||||
floor; a kernel whose SPI is below it blocks the plugin at startup with a reason). The build needs
|
||||
`mx.quest:runway-spi` and `runway-spi-testkit` in `~/.m2`.
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
export JAVA_HOME=<a JDK 25>
|
||||
mvn verify
|
||||
```
|
||||
|
||||
The first build downloads its Maven dependencies, and needs the `runway-spi` jars installed in `~/.m2` as the
|
||||
[authoring guide §2](../docs/PLUGIN-AUTHORING-GUIDE.md#2-prerequisites) describes.
|
||||
|
||||
Runs 82 unit tests (over the SPI testkit's fakes, plus a scan proving the compiled classes link nothing of the host
|
||||
but the SPI) and produces the thin `target/runway-plugin-demo.jar` and **both** installable forms:
|
||||
`target/runway-demo/` (the install-ready folder) and `target/runway-plugin-runway-demo-<version>.zip` (the archive
|
||||
the management UI upload expects). Two builds produce byte-identical artifacts. The zip is named after the plugin id,
|
||||
`runway-plugin-<id>-<version>.zip`, like every plugin's; the jar inside it is `runway-plugin-demo.jar`.
|
||||
|
||||
## Install (either path, then restart the host)
|
||||
|
||||
```bash
|
||||
cp -r target/runway-demo <runway-external>/plugins/ # 1. filesystem (or scripts/install-into.sh <external>)
|
||||
# 2. app console → /__app/plugins → install → upload runway-plugin-runway-demo-<version>.zip
|
||||
```
|
||||
|
||||
The plugin loads only once the host is in **ACTIVE** mode (after first-run setup); it is skipped in WIZARD mode.
|
||||
|
||||
## Verify (one command)
|
||||
|
||||
```bash
|
||||
HOST_JAR=<runway checkout>/runway-app/target/runway-app-<version>-exec.jar \
|
||||
JAVA_HOME=/path/to/jdk-25 VERIFY_TMPDIR=<scratch dir> VERIFY_LOG_DIR=<evidence dir> scripts/verify-against-host.sh
|
||||
```
|
||||
|
||||
It builds the plugin (offline, never `mvn install`), drops it into a throwaway Runway deployment, runs the
|
||||
first-run wizard to reach ACTIVE mode and checks 58 things live — from "zero host-linkage and bean-name warnings"
|
||||
through a `GET` writing nothing, the anonymous feedback `POST`, the console screen's CSRF-checked actions, the showcase page appearing and
|
||||
disappearing, to a transfer copy leaving `notes.yml` out. `HOST_JAR` defaults to the host checkout's jar matching
|
||||
its pom version.
|
||||
|
||||
## Try it
|
||||
|
||||
- Tenant console → **Runway demo** (needs `runway-demo|manage-notes`; administrators hold it): the demo screen.
|
||||
Add a note, install the demo page, publish a showcase, check a path, watch *Recent changes*.
|
||||
- `/demo` — the demo page (after installing it): the notice widget and the public feedback form.
|
||||
- `/demo/showcase` — the showcase page, while one is published.
|
||||
- `GET /demo/hello.txt` — a per-site greeting in the visitor's language.
|
||||
- `GET /demo/echo.json?q=1` — what the platform tells an endpoint about your request.
|
||||
- `GET /demo/notes.json` — the notes as JSON, gated by `manage-notes` (`403` without it).
|
||||
- Any public page's `<head>` — a generator meta and the plugin's stylesheet.
|
||||
- The plugin's per-site settings page — every setting type, and the admin fragment below the form.
|
||||
|
||||
## Starting a new plugin from it
|
||||
|
||||
Copy this folder, rename the descriptor `id`, the Maven `artifactId`, the Java package (`mx.quest.demo`) and the
|
||||
bean-name prefix (`runwayDemo…` → your id in lowerCamelCase), and delete what you do not need. Keep the tests that
|
||||
check the contract (`DemoPluginConfigTest`, `DemoTemplatesTest`) — they are the cheapest way to stay inside it.
|
||||
|
||||
_Java package `mx.quest.demo` · plugin id `runway-demo` · version 2.1.0 · `requiresSpi: ">=1.0.0"`._
|
||||
|
||||
## License
|
||||
|
||||
Apache License 2.0 (`LICENSE`, `NOTICE`), copyright Quest ICT SAS de CV. You are free to copy this plugin as the
|
||||
start of your own plugin and to release yours under any terms.
|
||||
@@ -0,0 +1,431 @@
|
||||
# The `runway-demo` plugin — a walkthrough of the Runway plugin contract
|
||||
|
||||
> The **kitchen-sink reference plugin**. Every extension axis and every service of the SPI service tier
|
||||
> is used here once, in the place a real plugin would use it, with a comment in the code saying
|
||||
> **when you would use it**. Read this document top to bottom to learn the contract; copy the folder to start a
|
||||
> plugin. The canonical rules live in the authoring guide (`../../docs/PLUGIN-AUTHORING-GUIDE.md`); this document
|
||||
> shows them working.
|
||||
|
||||
- **id** `runway-demo` · **install folder** `external/plugins/runway-demo/` · **Java package** `mx.quest.demo`
|
||||
- **version** `2.1.0` · **`requiresSpi`** `">=1.0.0"` · links **only** `mx.quest.runway.spi`
|
||||
- **jar** `runway-plugin-demo.jar` (thin: 18 top-level classes, nothing bundled) · **Maven artifactId**
|
||||
`runway-plugin-runway-demo` · **release zip** `runway-plugin-runway-demo-<version>.zip`
|
||||
- **Verified** live against the packaged kernel (§9) and by 82 unit tests with 20 mutation checks (§8).
|
||||
|
||||
---
|
||||
|
||||
## 1. What it does
|
||||
|
||||
| Feature | Who sees it | Built on |
|
||||
|---|---|---|
|
||||
| A generator `<meta>`, the plugin stylesheet and an inert analytics `<script>` in every page's `<head>` | visitors | `HeadContributor` + `PluginSettings` |
|
||||
| A notice callout at `data-widget="demo-notice/<instance>"` | visitors | `ContentWidget` + `PluginSettings` + `Messages.site` |
|
||||
| A "leave a message" form at `data-widget="demo-feedback/<instance>"`, posting without a CSRF token | visitors | `ContentWidget` + an **anonymous** `POST` route |
|
||||
| `/demo/hello.txt`, `/demo/echo.json`, `/demo/notes.json` (permission-gated) | visitors / operators | `EndpointContributor` + `AccessCheck` + `Messages.site` |
|
||||
| SEO advice in the page editor (long title, no description, no `<h1>`) | site managers | `PageQualityCheck` + `PluginSettings` |
|
||||
| Per-site **notes** (operator notes, visitors' messages, a settings audit note), personal data | operators | `PluginSiteFiles` + `siteData.personal` |
|
||||
| A **showcase** page at `/demo/showcase`, published from the console | visitors | `ContentSource` + `ContentChanges` + a `SOURCE` listener |
|
||||
| A **demo page** at `/demo` installed in one click | site managers | `SitePages` + `AccessCheck` |
|
||||
| The demo's **console screen** (`/__admin/runway-demo`) | operators | `@ConsoleScreen` + `RequestContext` + `Messages.console` + `ContentCatalogView` |
|
||||
| *Recent changes* on that screen, with URLs before and after | operators | `SiteEventListener` (`CONSUMER`) + `Sites` |
|
||||
| A dashboard card and an admin fragment under the settings form | operators | descriptor + templates + `Sites`, `SitePages.pathOf`, `PluginSettings.secret`, `PluginInfo` |
|
||||
| A start/stop hook logging the built-against and running SPI | the boot log | `PluginLifecycle` + `PluginInfo` |
|
||||
|
||||
---
|
||||
|
||||
## 2. The files
|
||||
|
||||
```
|
||||
demo/
|
||||
├── plugin.yml the descriptor: floor, personal data, permissions, both settings schemas, menu, card
|
||||
├── pom.xml runway-spi (+ runway-spi-testkit for tests) and platform libraries, all provided
|
||||
├── CHANGELOG.md · README.md
|
||||
├── scripts/verify-against-host.sh build → throwaway Runway → boot ACTIVE → 58 live checks
|
||||
├── scripts/install-into.sh copy the assembled plugin into an external/ tree
|
||||
├── i18n/messages[_es].properties console AND public text (add-only)
|
||||
├── static/ css/demo.css · js/demo-analytics.js · notes-help.html (/__plugin/runway-demo/static/…)
|
||||
├── templates/ decoupled Thymeleaf (.html markup + .th.xml logic)
|
||||
│ ├── console.* the @ConsoleScreen content
|
||||
│ ├── showcase.* the content source's body template
|
||||
│ ├── dashboard.* the dashboard card
|
||||
│ └── admin.* the fragment under the settings form (filename convention)
|
||||
└── src/main/java/mx/quest/demo/
|
||||
├── DemoPluginConfig mainClass: every bean, wired explicitly, named runwayDemo…
|
||||
├── DemoAppProps app-level settings (@ConfigurationProperties via @Bean)
|
||||
├── DemoAnalyticsHead HeadContributor
|
||||
├── DemoNoticeWidget ContentWidget "demo-notice"
|
||||
├── DemoFeedbackWidget ContentWidget "demo-feedback" (the anonymous form)
|
||||
├── DemoMetaLengthCheck PageQualityCheck
|
||||
├── DemoEndpoints EndpointContributor (3 GETs + the anonymous POST)
|
||||
├── DemoNotesStore · Note · NotesFile PluginSiteFiles: notes.yml
|
||||
├── DemoShowcaseStore · Showcase PluginSiteFiles + ContentChanges: showcase.yml
|
||||
├── DemoShowcaseSource ContentSource + SiteEventListener (SOURCE)
|
||||
├── DemoActivity SiteEventListener (CONSUMER) + Sites
|
||||
├── DemoLifecycle PluginLifecycle + PluginInfo
|
||||
├── DemoAdminModel backs the card and the admin fragment
|
||||
├── DemoConsoleController @ConsoleScreen: RequestContext, AccessCheck, Messages.console, SitePages, ContentCatalogView
|
||||
└── Html escaping (every axis that returns HTML owns its escaping)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Wiring: how a plugin gets the kernel's services (`DemoPluginConfig`)
|
||||
|
||||
The kernel registers `mainClass` into its Spring context **before refresh**; the plugin's `@Bean` methods receive
|
||||
the services as ordinary parameters. There is nothing else to learn — no lookup, no handle, no host class.
|
||||
|
||||
```java
|
||||
@Bean
|
||||
public DemoShowcaseStore runwayDemoShowcaseStore(PluginSiteFiles files, ContentChanges changes) {
|
||||
return new DemoShowcaseStore(files, changes);
|
||||
}
|
||||
```
|
||||
|
||||
- **Plugin-scoped services** — `PluginSettings`, `PluginSiteFiles`, `ContentChanges`, `PluginInfo` — are bound to
|
||||
*this* plugin by **the jar the injecting class was loaded from** (`DemoPluginConfig` is in the plugin's own jar).
|
||||
No method takes a plugin id, so a plugin can never read another's settings or files. Inject them in your own
|
||||
classes: injection from a `lib/` jar, from kernel code, or through a bare `getBean(...)` fails at startup.
|
||||
- **Kernel singletons** — `Sites`, `RequestContext`, `AccessCheck`, `Messages`, `SitePages`, `ContentCatalogView`.
|
||||
- **Bean names start with the plugin id in lowerCamelCase** (`runwayDemo…`); the kernel
|
||||
blocks a plugin with any other name. The demo's app-level settings bean is therefore a
|
||||
`@Bean @ConfigurationProperties("runway.plugin.runway-demo")` method, **not** `@EnableConfigurationProperties`
|
||||
(which names the bean `runway.plugin.runway-demo-mx.quest.demo.DemoAppProps`).
|
||||
- **What a plugin may contribute to Spring:** SPI implementations, plain beans, and `@Controller`s mapped under
|
||||
`/__admin/<id>` or `/__app/<id>`. **Not:** servlet `Filter`s, `SecurityFilterChain`s, bean (factory)
|
||||
post-processors, unrestricted `@ControllerAdvice`. Return the **concrete** class from a `@Bean` method so Spring
|
||||
sees every interface it implements (`DemoShowcaseSource` is a content source *and* a listener).
|
||||
|
||||
---
|
||||
|
||||
## 4. The service tier, one service at a time
|
||||
|
||||
Each subsection: what the demo does, where, and **when you would use it**.
|
||||
|
||||
### 4.1 `PluginSettings` — my per-site settings
|
||||
|
||||
*Where:* `DemoAnalyticsHead`, `DemoNoticeWidget`, `DemoFeedbackWidget`, `DemoMetaLengthCheck`, `DemoEndpoints`,
|
||||
`DemoAdminModel`.
|
||||
|
||||
```java
|
||||
SettingsView site = settings.site(view.site().id());
|
||||
if (!site.bool("notice.enabled", true)) { return RenderFragment.empty(); }
|
||||
int maxChars = (int) site.integer("notice.max-chars", 280, 1, 2000); // clamped
|
||||
```
|
||||
|
||||
`site(siteId)` returns the descriptor's `siteSettings:` defaults overlaid by what the operator saved; the typed
|
||||
accessors never throw (a bad value yields the fallback). `secret(siteId, key)` hands a `type: secret` value back in
|
||||
clear — `DemoAdminModel.siteTokenConfigured` only asks whether `analytics.site-token` is set and never shows it.
|
||||
**Use it** for every per-site setting read; a save applies at once on every node. App-level (platform) settings
|
||||
are not here: they bind through `@ConfigurationProperties` under `runway.plugin.<id>.*` and apply on restart
|
||||
(`DemoAppProps`).
|
||||
|
||||
### 4.2 `PluginInfo` and `PluginLifecycle` — who am I, and the start/stop hook
|
||||
|
||||
*Where:* `DemoLifecycle` (and `PluginInfo` injected into `DemoAdminModel` and the console controller).
|
||||
|
||||
`started(PluginInfo self)` runs once the platform is up, in plugin load order; `stopping()` at shutdown, in reverse
|
||||
order, only if `started` returned normally. Both block the host's thread — keep them short. The demo logs
|
||||
`runway-demo 2.1.0 started — install dir …; built against SPI 1.0.0, running on SPI 1.0.0`:
|
||||
`RunwaySpi.VERSION` is a compile-time constant (what the plugin was **built against**, copied into the plugin's
|
||||
classes), `RunwaySpi.runtimeVersion()` is the running kernel's. **Use it** to open an
|
||||
index, start your own executor, warm a cache — and to close them again.
|
||||
|
||||
### 4.3 `PluginSiteFiles` and `siteData.personal` — my per-site data
|
||||
|
||||
*Where:* `DemoNotesStore` (`notes.yml`), `DemoShowcaseStore` (`showcase.yml`).
|
||||
|
||||
The plugin's folder of a site, `sites/<id>/plugins/runway-demo/`: inside the site folder, so **full backups carry it
|
||||
and a deleted site takes it along** — no `BackupParticipant` needed. Paths are relative, confined (no `..`, no
|
||||
symlink escape), each write is atomic; a **read-modify-write** (append a note) is the plugin's to serialize, which
|
||||
the store does per site. A write for a site whose folder does not exist fails rather than creating it.
|
||||
|
||||
**A `GET` never writes.** Opening the console screen, the settings page or `/demo/notes.json` only reads. A site
|
||||
with no notes yet shows a welcome note, but the store does not save it then: the site has no `notes.yml` until the
|
||||
first write — a console note, a visitor's message or the settings audit note. That first write saves the welcome
|
||||
note together with the new note, so the note the operator saw stays in the list (it gets the time of that write).
|
||||
**Rule:** a page that only shows data must not change a site. Show defaults from memory; write on the first `POST`.
|
||||
(2.0.0 wrote the welcome note on the first read, so each site got a `notes.yml` as soon as someone opened the
|
||||
screen.)
|
||||
|
||||
`notes.yml` holds what people typed, so `plugin.yml` declares it:
|
||||
|
||||
```yaml
|
||||
siteData:
|
||||
personal:
|
||||
- notes.yml
|
||||
```
|
||||
|
||||
A **transfer copy** of the site (for someone outside the organisation) leaves it out and lists it in the
|
||||
manifest; a full backup keeps it. **Rule:** any file holding visitor or user input is personal. The showcase is
|
||||
published content and is not declared.
|
||||
|
||||
### 4.4 `Sites` — a site's view from its id, off-request
|
||||
|
||||
*Where:* `DemoAdminModel.siteName` (a console fragment only has `tenantSiteId`), `DemoActivity.onSiteLifecycle`
|
||||
(a listener only has the event's site id).
|
||||
|
||||
**Use it** whenever code that knows only an id — a listener, a background task, a fragment — needs the site's
|
||||
name, locales or base URL. Empty for an unknown id; an unsafe id throws.
|
||||
|
||||
### 4.5 `RequestContext` — which site is this console request about?
|
||||
|
||||
*Where:* `DemoConsoleController.boundSite()`.
|
||||
|
||||
A console screen has no `RouteRequest`; `RequestContext.site()` is how it learns the tenancy. It is **empty on the
|
||||
application console** (`/__app/…`), so the screen answers `404` there. An endpoint does not need it: its
|
||||
`RouteRequest` already carries the site.
|
||||
|
||||
### 4.6 `AccessCheck` — may the current user do this?
|
||||
|
||||
*Where:* `DemoEndpoints` (`/demo/notes.json` → `403` without `runway-demo|manage-notes`), every console handler
|
||||
(`@PreAuthorize("@authz.may('runway-demo|manage-notes')")`), the starter-page install (`may("EDIT_PAGES")`, a
|
||||
kernel permission), and the admin fragment (`${@authz.may('runway-demo|manage-notes')}` shows the screen link).
|
||||
|
||||
One bean, three spellings: inject `AccessCheck` in Java, `@authz` in `@PreAuthorize` and templates. Fail-closed:
|
||||
no request, no principal, an undeclared key, or an anonymous route → `false`. **Use it** every time your code
|
||||
decides; a menu entry's or card's `permission:` only hides UI (and must be the full key `<id>|<permission>`).
|
||||
|
||||
### 4.7 `Messages` — localized text for visitors and for operators
|
||||
|
||||
*Where:* `Messages.site` in `DemoEndpoints.hello`, both widgets, the showcase title, the starter page title;
|
||||
`Messages.console` for the console screen's flash messages.
|
||||
|
||||
`site(siteId, locale, code, fallback, args…)` resolves the site's own bundle first, then every plugin's `i18n/`
|
||||
(add-only), in the **visitor's** locale; `console(code, fallback, args…)` resolves the console bundles in the
|
||||
**operator's** UI language. With arguments the text is a `MessageFormat` pattern (write `''` for an apostrophe).
|
||||
Templates use `#{…}` for the same console bundle.
|
||||
|
||||
### 4.8 `SitePages` — install my starter page
|
||||
|
||||
*Where:* `DemoConsoleController.installPage` (and `pathOf` in `DemoAdminModel` and the screen).
|
||||
|
||||
The demo page (`/demo`, slug `runway-demo`, `noindex`) carries both widget anchors and pulls the site's chrome
|
||||
through `${master}`. `install` never overwrites and **never publishes around the site's editorial level**:
|
||||
|
||||
| Outcome | When | The demo says |
|
||||
|---|---|---|
|
||||
| `PUBLISHED` | Advisory site; Enforced/Reviewed with the checks passing and the right to approve | "Demo page published at /demo." |
|
||||
| `PENDING_REVIEW` | Reviewed site, the user lacks `APPROVE_PAGES` | "… waiting in the review queue." |
|
||||
| `DRAFT_BLOCKED` | the quality checks blocked publishing | "… as a draft: the quality checks blocked publishing." + the findings |
|
||||
| `ALREADY_EXISTS` | the slug exists (any state) | "A demo page already exists at /demo; nothing changed." |
|
||||
|
||||
The `switch` has a `default` branch (the enum may grow). The plugin checks the caller may edit pages **before**
|
||||
calling — `SitePages` leaves that to the plugin. `pathOf` finds the page wherever an operator moved it.
|
||||
|
||||
### 4.9 `ContentCatalogView` — the site's published content surface
|
||||
|
||||
*Where:* the console screen's *Content surface* card.
|
||||
|
||||
`entries(siteId)` lists every published page and content item with the URLs **the host computed** (the same
|
||||
computation as the page `<head>`, so a listing never disagrees with the pages). `pageAt(siteId, path, locale)`
|
||||
answers which published page owns a path; `servablePath(siteId, path)` whether content may live there at all (not
|
||||
`/__…`, `/login`, an endpoint route…). `refresh(siteId)` drops the cached listing — a manual reindex; ordinary
|
||||
changes never need it. **Use it** for a sitemap, a search index, an "is this path taken?" check.
|
||||
|
||||
### 4.10 `ContentSource` + `ContentChanges` — my own routable content
|
||||
|
||||
*Where:* `DemoShowcaseSource` (the source), `DemoShowcaseStore.publish/unpublish` (the announcements).
|
||||
|
||||
The source serves `/demo/showcase` through the kernel's routing, the site's chrome, the sitemap and on-site search
|
||||
(`CAP_INDEXABLE_TEXT`). `enumerate` is metadata-only (it runs on anonymous requests); `resolve` is a cheap path
|
||||
comparison; `body` renders the escaped text into `templates/showcase.*`, which may rely only on `${master}`,
|
||||
`${content.*}`, `${locale}` and `${urls[…]}`. Every publish moves `updatedAt`, which the page's `ETag` folds.
|
||||
|
||||
After every write, the store announces it — after the write, outside its own lock:
|
||||
|
||||
```java
|
||||
files.writeText(siteId, FILE, yaml.writeValueAsString(...));
|
||||
changes.changed(siteId, DemoShowcaseSource.SOURCE_KEY, DemoShowcaseSource.ID);
|
||||
```
|
||||
|
||||
On return, routing, the listing, sitemaps and search have been evicted on every node and every listener on this
|
||||
node has run. The kernel refuses a source key the plugin does not own, and a call from inside a
|
||||
`SiteEventListener` callback (a test proves the second).
|
||||
|
||||
### 4.11 `SiteEventListener` — react to changes
|
||||
|
||||
*Where:* `DemoShowcaseSource` (phase `SOURCE`) and `DemoActivity` (phase `CONSUMER`, the default).
|
||||
|
||||
- **`SOURCE`** is for a content source dropping its own state. All `SOURCE` listeners run first, the kernel evicts
|
||||
its listing again, then the `CONSUMER`s — so a consumer that re-reads the listing never sees a source's stale
|
||||
state. The showcase source evicts its cached read on its own `CONTENT` changes (a change **replayed from another
|
||||
node** is the only way this node learns the file changed) and on wholesale lifecycle events (`DELETED`,
|
||||
`RESTORED`).
|
||||
- **`CONSUMER`** reacts to everything else. `DemoActivity`:
|
||||
- `onSettingsChanged` — a save of **this plugin's own** settings; appends the audit note **only when
|
||||
`change.local()`**, so a cluster writes it once, not once per node;
|
||||
- `onCatalogChanged` — records each change (`page`, `content`, `site`, `settings`) with `previousUrls` (where
|
||||
the item was — a deleted page still names its old address) and `currentUrls` (where it is now); the console's
|
||||
*Recent changes* shows them;
|
||||
- `onSiteLifecycle` — logs the event with the site's name (`Sites`) and drops what it recorded on a wholesale
|
||||
event.
|
||||
|
||||
The kernel guarantees: every kernel cache is already evicted when a callback runs; no host lock is held (calling
|
||||
any service is safe); a throwing callback is logged and counted, never propagated. Callbacks run on the writer's
|
||||
thread: **evict, record or enqueue** — anything slow belongs on your own executor.
|
||||
|
||||
### 4.12 `@ConsoleScreen` — a screen inside the console
|
||||
|
||||
*Where:* `DemoConsoleController` + `templates/console.*`; the menu entry opens it.
|
||||
|
||||
```java
|
||||
@Controller
|
||||
@ConsoleScreen
|
||||
@RequestMapping("/__admin/runway-demo")
|
||||
public class DemoConsoleController {
|
||||
@GetMapping
|
||||
@PreAuthorize("@authz.may('runway-demo|manage-notes')")
|
||||
public String screen(...) {
|
||||
model.addAttribute(ConsoleScreen.CONTENT_TEMPLATE, "__plugin__/runway-demo/console");
|
||||
model.addAttribute(ConsoleScreen.PAGE_TITLE_KEY, "runwaydemo.console.title");
|
||||
return ConsoleScreen.LAYOUT_VIEW;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The kernel fills the shell (topbar, menus, language switcher, footer); the plugin needs no `@ControllerAdvice`.
|
||||
Every mapping lies under `/__admin/runway-demo`, so the console's sign-in, realm security and CSRF apply. The
|
||||
content template may rely on `tenantSiteId`, `_csrf`, `${@<own bean>…}`, `${@authz.may(…)}`, `#{…}` — and on
|
||||
what the controller itself put in the model (`rd`). The screen renders its own flash (`runwayDemoFlash`,
|
||||
`runwayDemoError`); the shell's flash region is not promised to plugins.
|
||||
|
||||
**The `POST` rule.** The `GET` only reads. Everything that changes state — add a note, install the page, publish or
|
||||
unpublish the showcase, refresh the listing — is a `<form method="post">` carrying the session's token
|
||||
(`<input class="rd-csrf" type="hidden" name="_csrf">`, bound in `console.th.xml` to `${_csrf}`), followed by a
|
||||
redirect (post/redirect/get). A link or an `<img>` on another web site can therefore never act through a signed-in
|
||||
operator's browser. Spring MVC binds the form fields (`@RequestParam`).
|
||||
|
||||
### 4.13 The anonymous `POST` route — a public form without a token
|
||||
|
||||
*Where:* `DemoEndpoints` (`Route.anonymousPost("/demo/feedback", …)`) + `DemoFeedbackWidget`.
|
||||
|
||||
A form on a page every visitor shares (and caches) cannot carry a per-session CSRF token, and an anonymous visitor
|
||||
has no session. Declaring the route `anonymous` exempts **exactly that method and path** from CSRF; the kernel
|
||||
makes that safe by running the handler with **no principal** (`AccessCheck.may` is `false` even for a signed-in
|
||||
administrator) and accepting only an `application/x-www-form-urlencoded` body (`415` otherwise). The handler keeps
|
||||
its own guards — a honeypot field, a length cap, five messages per minute per `req.clientIp()` (the address after
|
||||
the kernel's trusted-proxy gate; never a header) — reads the fields from `req.form()` only (personal text never in
|
||||
a URL), and answers `303` back with only an outcome flag the widget renders. **Use it** only for a form any visitor
|
||||
may submit with no account; never for an action on something a signed-in user owns.
|
||||
|
||||
---
|
||||
|
||||
## 5. The axes (pure functions of their inputs)
|
||||
|
||||
| Axis | Class | Notes |
|
||||
|---|---|---|
|
||||
| `HeadContributor` | `DemoAnalyticsHead` | `@Order(200)`; returns `""`, never `null`; `headInputs` names `plugins/runway-demo.yml` so a settings change moves the page `ETag`; emits plain `<script src>` (the kernel stamps the CSP nonce) |
|
||||
| `ContentWidget` | `DemoNoticeWidget`, `DemoFeedbackWidget` | anchor `<div id="…" data-widget="<key>/<instance>">`; `RenderFragment.empty()` to stay silent; reads only its view (the query, the path) |
|
||||
| `PageQualityCheck` | `DemoMetaLengthCheck` | an `ERROR` blocks publishing on Enforced/Reviewed sites — the demo's `h1.missing` is an `ERROR` on purpose |
|
||||
| `EndpointContributor` | `DemoEndpoints` | exact paths, tenant realm; `RouteRequest` carries locale, query, form, lowercase headers, `clientIp`, `origin` |
|
||||
| `ContentSource` | `DemoShowcaseSource` | §4.10 |
|
||||
|
||||
A throwing axis is contained by the kernel (empty head/widget output served `no-store`, a `500` for an endpoint)
|
||||
and counted on the plugins screen.
|
||||
|
||||
---
|
||||
|
||||
## 6. What the demo deliberately does not do
|
||||
|
||||
- **No servlet filter.** **Servlet filters are outside the Runway 1.0 plugin contract:** a filter needs servlet types the SPI does not
|
||||
carry, runs on every request of every site, and no feature plugin needs one. `FilterBand` stays a kernel concept
|
||||
(it places the kernel's and the essential protection plugin's filters). A plugin that wants to shape a response
|
||||
uses an axis — a head contributor, a widget, an endpoint. The kernel blocks a plugin with
|
||||
a `Filter` bean.
|
||||
- **No `BackupParticipant`.** The notes live in the site's folder, which backups carry. The axis remains for data a
|
||||
plugin keeps *outside* the site folder (none in 1.0).
|
||||
- **No `@Primary`.** That is for the singleton kernel seams the essential `protection` plugin arms; every demo
|
||||
contribution is collected by type.
|
||||
- **No `requires:` / `conflicts:`** (a hard dependency would stop the demo from always loading); the forms are in
|
||||
the descriptor's comments.
|
||||
- **`essential` is not claimed** — only kernel security-floor ids on the allowlist may.
|
||||
- **No per-instance widget config** (`widgetSettings:`): the `search` plugin is the example of that.
|
||||
|
||||
---
|
||||
|
||||
## 7. Templates and i18n
|
||||
|
||||
- **Decoupled Thymeleaf**: markup in `.html` with zero `th:*`, logic in the sibling `.th.xml`. A repeated `id` in a
|
||||
`.html` is a hard error (a test forbids it); iterated rows use classes and `//` selectors. Form actions are
|
||||
constants in the markup (`th:action`/`th:attr` run in a restricted context).
|
||||
- **Fragments** (`dashboard`, `admin`) are bare (a root element, no `<html>`) and read the plugin's own bean
|
||||
`${@runwayDemoAdminModel…}` with `tenantSiteId`.
|
||||
- **The body template** (`showcase`) pulls the site's chrome by the `${master}` variable, never a literal name.
|
||||
- **i18n**: `i18n/messages[_es].properties` is appended to the console's and every site's message sources
|
||||
(add-only). The descriptor's labels, the console templates' `#{…}` and both `Messages` calls read it. A test
|
||||
keeps English and Spanish in step and fails on a key used but missing.
|
||||
|
||||
---
|
||||
|
||||
## 8. Tests
|
||||
|
||||
`mvn verify` runs 82 tests over `runway-spi-testkit` (no kernel, no Spring Boot):
|
||||
|
||||
| Class | Covers |
|
||||
|---|---|
|
||||
| `DemoSpiUnitTest` | head, both widgets, quality check, every endpoint route incl. the anonymous feedback POST (honeypot, blank, query ignored, rate limit, foreign return path), lowercase header names |
|
||||
| `DemoNotesStoreTest` | the notes over `TempDirSiteFiles`: a read shows the welcome and writes nothing, the first append keeps it, order, caps, isolation, lenient reads, an unreadable file never overwritten, a missing site, unsafe ids |
|
||||
| `DemoShowcaseTest` | publish/unpublish announce through `EventDispatch`, the source's refs/body/resolve, `updatedAt`, the TTL backstop, eviction on a replayed change and on wholesale events only, the kernel's refusal from inside a callback |
|
||||
| `DemoActivityTest` | own vs other plugins' settings, `local`, URLs before/after, the bound, wholesale drops, failures contained |
|
||||
| `DemoConsoleControllerTest` | the screen and each action through MockMvc: the shell model, opening the screen writes no file, 404 on the app console, every flash, `EDIT_PAGES`, every install outcome, a failed install, the path check, refresh |
|
||||
| `DemoTemplatesTest` | every `POST` action has a form carrying the CSRF field; no link points at an action; no repeated id; every selector matches |
|
||||
| `DemoPluginConfigTest` | wiring from SPI fakes alone, bean names, forbidden Spring types, the controller's gates and mappings, template bean references, descriptor (floor, version, personal data, menu, secrets), i18n, **the compiled classes link no `mx.quest.runway` class outside `.spi`**, the removed classes are gone |
|
||||
|
||||
Mutation-checked: 20 deliberate breaks (the `local` gate, each eviction, each announcement, the honeypot, the rate
|
||||
limit boundary, the permission gates, body-only fields, a missing `@PreAuthorize`, the notes bound, the
|
||||
personal-data declaration, the TTL boundary, escaping, the open-redirect guard, a form's CSRF field, an
|
||||
unprefixed bean name, the clamp) — each makes a test fail.
|
||||
|
||||
---
|
||||
|
||||
## 9. Build, install, verify
|
||||
|
||||
```bash
|
||||
export JAVA_HOME=<a JDK 25>
|
||||
cd demo && mvn verify
|
||||
# target/runway-demo/ the install-ready folder
|
||||
# target/runway-plugin-runway-demo-<version>.zip the archive the management UI upload expects (byte-reproducible)
|
||||
JAVA_HOME=/path/to/jdk-25 HOST_JAR=…/runway-app-1.0.0-exec.jar VERIFY_TMPDIR=… VERIFY_LOG_DIR=… scripts/verify-against-host.sh
|
||||
```
|
||||
|
||||
The first build downloads its Maven dependencies, and needs the `runway-spi` jars installed in `~/.m2` as the
|
||||
[authoring guide §2](../../docs/PLUGIN-AUTHORING-GUIDE.md#2-prerequisites) describes.
|
||||
|
||||
The verify script never runs `mvn install`. Its result for 2.1.0: **58 passed, 0 failed**.
|
||||
From the host log:
|
||||
|
||||
```
|
||||
plugins: 1 registered, 0 blocked
|
||||
runway-demo 2.1.0 started — install dir …/plugins/runway-demo; built against SPI 1.0.0, running on SPI 1.0.0
|
||||
runway-demo settings changed for site 'default': audit note appended (now 4 notes)
|
||||
transfer export: blanked 1 secret value(s) in runway-demo.yml: [analytics.site-token]
|
||||
```
|
||||
|
||||
Four notes: the welcome note (stored by the first write, a visitor's message), that message, the operator's note
|
||||
and the audit note. Before the first write, the signed-in site user (`owner`) opened the screen, `notes.json` and the settings page, and
|
||||
the site still had no `notes.yml`.
|
||||
|
||||
The log shows no host-linkage ("uses host internals"), bean-name or surface finding — each would block the plugin,
|
||||
which the script's `is blocked` check catches. *Recent changes* after installing the page and publishing then
|
||||
unpublishing the showcase (newest first):
|
||||
|
||||
```
|
||||
content runway-demo:showcase before /demo/showcase after —
|
||||
content runway-demo:showcase before — after /demo/showcase
|
||||
page pages:runway-demo before — after /demo
|
||||
page pages:runway-demo before — after /demo
|
||||
```
|
||||
|
||||
(The install is two page writes — the draft, then its publication.)
|
||||
|
||||
---
|
||||
|
||||
## 10. Known limits
|
||||
|
||||
- A non-anonymous `EndpointContributor` `POST` is not limited to header tokens: it reads every form field whether
|
||||
the CSRF token travels as a form **field** or in the `X-CSRF-TOKEN` header. The demo keeps its operator actions in a
|
||||
`@ConsoleScreen` controller by choice.
|
||||
- *Recent changes* is per node and in memory (it is a demonstration of the callback, not an audit log); it starts
|
||||
empty after a restart.
|
||||
- Changes nobody announces (a file edited by hand) reach the showcase within its 60-second cache lifetime and the
|
||||
content listing within its own 30 seconds.
|
||||
@@ -0,0 +1,9 @@
|
||||
# Writing a Runway plugin — moved
|
||||
|
||||
The authoring guide is maintained in **one place**: [`../../docs/PLUGIN-AUTHORING-GUIDE.md`](../../docs/PLUGIN-AUTHORING-GUIDE.md)
|
||||
at `plugins/docs/`.
|
||||
|
||||
This file used to hold a copy of it. The copy had drifted (it still described host-coupled seams — `RunwayPlugin`,
|
||||
`FilterContribution`, `SitePluginConfigService` — that the SPI service tier replaced), and a stale copy beside the
|
||||
reference plugin is worse than none. For how the demo itself uses every service, read
|
||||
[`DEMO-PLUGIN.md`](DEMO-PLUGIN.md).
|
||||
@@ -0,0 +1,118 @@
|
||||
# =============================================================================
|
||||
# runway-demo plugin i18n bundle (English).
|
||||
#
|
||||
# The Runway kernel appends this bundle to the operator console's MessageSource AND to every site's public
|
||||
# MessageSource (add-only: a plugin may add keys but never override a core or site key). Console text is read
|
||||
# with #{...} in the console templates and Messages.console(...) in Java; visitor-facing text with
|
||||
# Messages.site(siteId, locale, ...). A message that takes arguments ({0}) is a java.text.MessageFormat pattern:
|
||||
# write a literal apostrophe as ''. Keys live WITH the plugin, never in core. Keep messages_es.properties in step
|
||||
# (a test checks both define the same keys).
|
||||
# =============================================================================
|
||||
|
||||
# --- Control-point permission labels ---
|
||||
runwaydemo.perm.settings=Configure the Runway Demo plugin
|
||||
runwaydemo.perm.manageNotes=Manage Runway Demo notes
|
||||
|
||||
# --- App-level settings labels ---
|
||||
runwaydemo.settings.bannerEnabled=Show the site-wide banner
|
||||
runwaydemo.settings.bannerText=Site-wide banner text
|
||||
runwaydemo.settings.cacheMax=Cache size (entries)
|
||||
runwaydemo.settings.generatorLabel=Generator meta-tag label
|
||||
runwaydemo.settings.writeKey=Analytics write key (secret)
|
||||
|
||||
# --- Per-site settings labels ---
|
||||
runwaydemo.settings.noticeEnabled=Show the notice widget
|
||||
runwaydemo.settings.noticeStyle=Notice style
|
||||
runwaydemo.settings.noticeMax=Notice maximum length
|
||||
runwaydemo.settings.analyticsEnabled=Enable analytics head tags
|
||||
runwaydemo.settings.siteToken=Per-site analytics token (secret)
|
||||
runwaydemo.settings.feedbackEnabled=Accept messages from the public feedback form
|
||||
runwaydemo.settings.titleRatio=Title-length warning ratio
|
||||
runwaydemo.settings.ignoreCodes=Suppressed quality-check codes
|
||||
|
||||
# --- Menu ---
|
||||
runwaydemo.menu.console=Runway demo
|
||||
|
||||
# --- Public (site) text: Messages.site ---
|
||||
runwaydemo.hello=Hello from the runway-demo plugin!
|
||||
runwaydemo.notice.body=This is the runway-demo notice widget (instance "{0}") on site "{1}".
|
||||
runwaydemo.feedback.label=Leave a message
|
||||
runwaydemo.feedback.send=Send
|
||||
runwaydemo.feedback.thanks=Thank you — your message was kept.
|
||||
runwaydemo.feedback.invalid=Please write a message first.
|
||||
runwaydemo.feedback.limited=Too many messages from your address — please try again in a minute.
|
||||
runwaydemo.showcase.title=Showcase
|
||||
runwaydemo.page.title=Runway demo
|
||||
|
||||
# --- Dashboard card and admin fragment ---
|
||||
runwaydemo.card.notes=Notes: {0}
|
||||
runwaydemo.card.versions=Plugin {0} · built against SPI {1} · running on SPI {2}
|
||||
runwaydemo.card.console=Open the demo screen
|
||||
runwaydemo.admin.title=Runway Demo — status and notes
|
||||
runwaydemo.admin.notes=Notes for this site: {0}
|
||||
runwaydemo.admin.banner=App-level banner enabled: {0}
|
||||
runwaydemo.admin.writeKey=App-level analytics key configured: {0}
|
||||
runwaydemo.admin.siteToken=Per-site analytics token configured: {0}
|
||||
runwaydemo.admin.page=Demo page at {0}
|
||||
runwaydemo.admin.page.none=The demo page is not installed.
|
||||
|
||||
# --- Console screen (@ConsoleScreen): #{...} and Messages.console ---
|
||||
runwaydemo.console.title=Runway demo
|
||||
runwaydemo.console.heading=Runway demo
|
||||
runwaydemo.console.help=Help
|
||||
runwaydemo.console.yes=yes
|
||||
runwaydemo.console.no=no
|
||||
runwaydemo.console.ioError=The change could not be saved.
|
||||
runwaydemo.console.about=This plugin
|
||||
runwaydemo.console.version=Version
|
||||
runwaydemo.console.builtSpi=Built against SPI
|
||||
runwaydemo.console.runningSpi=Running on SPI
|
||||
runwaydemo.console.page=Demo page
|
||||
runwaydemo.console.page.desc=A ready-made page carrying the notice and feedback widgets. It is installed through the site's editorial rules and then belongs to the site like any other page.
|
||||
runwaydemo.console.page.at=Installed at
|
||||
runwaydemo.console.page.install=Install the demo page
|
||||
runwaydemo.console.page.forbidden=Installing a page needs the permission to edit pages.
|
||||
runwaydemo.console.page.failed=The demo page could not be installed.
|
||||
runwaydemo.console.page.published=Demo page published at {0}.
|
||||
runwaydemo.console.page.pending=Demo page created at {0} and waiting in the review queue.
|
||||
runwaydemo.console.page.blocked=Demo page created at {0} as a draft: the quality checks blocked publishing.
|
||||
runwaydemo.console.page.exists=A demo page already exists at {0}; nothing changed.
|
||||
runwaydemo.console.page.other=Demo page install finished: {0} {1}
|
||||
runwaydemo.console.notes=Notes
|
||||
runwaydemo.console.notes.desc=Kept in the plugin's own folder of this site. They hold what people typed, so they are declared personal data and transfer copies leave them out.
|
||||
runwaydemo.console.note.new=New note
|
||||
runwaydemo.console.note.add=Add note
|
||||
runwaydemo.console.note.blank=Write something first.
|
||||
runwaydemo.console.note.added=Note added.
|
||||
runwaydemo.console.showcase=Showcase page
|
||||
runwaydemo.console.showcase.desc=Served by the plugin's content source. Publishing or unpublishing announces the change, so routing, sitemaps and search follow at once.
|
||||
runwaydemo.console.showcase.at=Published at
|
||||
runwaydemo.console.showcase.text=Showcase text
|
||||
runwaydemo.console.showcase.publish=Publish
|
||||
runwaydemo.console.showcase.unpublish=Unpublish
|
||||
runwaydemo.console.showcase.empty=Nothing is published.
|
||||
runwaydemo.console.showcase.blank=Write something first.
|
||||
runwaydemo.console.showcase.published=Showcase published at {0}.
|
||||
runwaydemo.console.showcase.unpublished=Showcase unpublished.
|
||||
runwaydemo.console.showcase.none=No showcase was published.
|
||||
runwaydemo.console.catalog=Content surface
|
||||
runwaydemo.console.catalog.source=Source
|
||||
runwaydemo.console.catalog.item=Item
|
||||
runwaydemo.console.catalog.path=Path
|
||||
runwaydemo.console.catalog.refresh=Refresh the listing
|
||||
runwaydemo.console.catalog.refreshed=Content listing refreshed.
|
||||
runwaydemo.console.check=Check a path
|
||||
runwaydemo.console.check.path=Path
|
||||
runwaydemo.console.check.unsafe=unsafe path
|
||||
runwaydemo.console.check.servable=content may live here
|
||||
runwaydemo.console.check.reserved=reserved: no content may live here
|
||||
runwaydemo.console.check.owner=owned by the published page {0}
|
||||
runwaydemo.console.check.free=no published page owns it
|
||||
runwaydemo.console.activity=Recent changes
|
||||
runwaydemo.console.activity.empty=No change seen since the platform started.
|
||||
runwaydemo.console.activity.at=When
|
||||
runwaydemo.console.activity.cause=Cause
|
||||
runwaydemo.console.activity.item=Item
|
||||
runwaydemo.console.activity.before=URLs before
|
||||
runwaydemo.console.activity.after=URLs after
|
||||
runwaydemo.console.activity.local=On this node
|
||||
@@ -0,0 +1,108 @@
|
||||
# =============================================================================
|
||||
# Paquete i18n del plugin runway-demo (Español).
|
||||
# El kernel de Runway añade este paquete al MessageSource de la consola Y al MessageSource público de cada sitio
|
||||
# (solo añade: un plugin puede agregar claves pero nunca sobrescribir una del núcleo o del sitio). Un mensaje con
|
||||
# argumentos ({0}) es un patrón java.text.MessageFormat: un apóstrofo literal se escribe ''. Debe definir las
|
||||
# mismas claves que messages.properties (lo comprueba una prueba).
|
||||
# =============================================================================
|
||||
|
||||
runwaydemo.perm.settings=Configurar el plugin Runway Demo
|
||||
runwaydemo.perm.manageNotes=Gestionar las notas de Runway Demo
|
||||
|
||||
runwaydemo.settings.bannerEnabled=Mostrar el aviso de todo el sitio
|
||||
runwaydemo.settings.bannerText=Texto del aviso de todo el sitio
|
||||
runwaydemo.settings.cacheMax=Tamaño de caché (entradas)
|
||||
runwaydemo.settings.generatorLabel=Etiqueta de la meta-etiqueta generator
|
||||
runwaydemo.settings.writeKey=Clave de escritura de analítica (secreto)
|
||||
|
||||
runwaydemo.settings.noticeEnabled=Mostrar el widget de aviso
|
||||
runwaydemo.settings.noticeStyle=Estilo del aviso
|
||||
runwaydemo.settings.noticeMax=Longitud máxima del aviso
|
||||
runwaydemo.settings.analyticsEnabled=Activar etiquetas de analítica en head
|
||||
runwaydemo.settings.siteToken=Token de analítica del sitio (secreto)
|
||||
runwaydemo.settings.feedbackEnabled=Aceptar mensajes del formulario público de comentarios
|
||||
runwaydemo.settings.titleRatio=Ratio de aviso por longitud de título
|
||||
runwaydemo.settings.ignoreCodes=Códigos de comprobación suprimidos
|
||||
|
||||
runwaydemo.menu.console=Demo de Runway
|
||||
|
||||
runwaydemo.hello=¡Hola desde el plugin runway-demo!
|
||||
runwaydemo.notice.body=Este es el widget de aviso de runway-demo (instancia "{0}") en el sitio "{1}".
|
||||
runwaydemo.feedback.label=Deja un mensaje
|
||||
runwaydemo.feedback.send=Enviar
|
||||
runwaydemo.feedback.thanks=Gracias — guardamos tu mensaje.
|
||||
runwaydemo.feedback.invalid=Escribe un mensaje primero.
|
||||
runwaydemo.feedback.limited=Demasiados mensajes desde tu dirección — inténtalo de nuevo en un minuto.
|
||||
runwaydemo.showcase.title=Escaparate
|
||||
runwaydemo.page.title=Demo de Runway
|
||||
|
||||
runwaydemo.card.notes=Notas: {0}
|
||||
runwaydemo.card.versions=Plugin {0} · compilado con SPI {1} · ejecutándose en SPI {2}
|
||||
runwaydemo.card.console=Abrir la pantalla de la demo
|
||||
runwaydemo.admin.title=Runway Demo — estado y notas
|
||||
runwaydemo.admin.notes=Notas de este sitio: {0}
|
||||
runwaydemo.admin.banner=Aviso de la aplicación activado: {0}
|
||||
runwaydemo.admin.writeKey=Clave de analítica de la aplicación configurada: {0}
|
||||
runwaydemo.admin.siteToken=Token de analítica del sitio configurado: {0}
|
||||
runwaydemo.admin.page=Página de la demo en {0}
|
||||
runwaydemo.admin.page.none=La página de la demo no está instalada.
|
||||
|
||||
runwaydemo.console.title=Demo de Runway
|
||||
runwaydemo.console.heading=Demo de Runway
|
||||
runwaydemo.console.help=Ayuda
|
||||
runwaydemo.console.yes=sí
|
||||
runwaydemo.console.no=no
|
||||
runwaydemo.console.ioError=No se pudo guardar el cambio.
|
||||
runwaydemo.console.about=Este plugin
|
||||
runwaydemo.console.version=Versión
|
||||
runwaydemo.console.builtSpi=Compilado con SPI
|
||||
runwaydemo.console.runningSpi=Ejecutándose en SPI
|
||||
runwaydemo.console.page=Página de la demo
|
||||
runwaydemo.console.page.desc=Una página lista para usar con los widgets de aviso y de comentarios. Se instala según las reglas editoriales del sitio y después pertenece al sitio como cualquier otra página.
|
||||
runwaydemo.console.page.at=Instalada en
|
||||
runwaydemo.console.page.install=Instalar la página de la demo
|
||||
runwaydemo.console.page.forbidden=Instalar una página requiere el permiso de editar páginas.
|
||||
runwaydemo.console.page.failed=No se pudo instalar la página de la demo.
|
||||
runwaydemo.console.page.published=Página de la demo publicada en {0}.
|
||||
runwaydemo.console.page.pending=Página de la demo creada en {0}, en espera en la cola de revisión.
|
||||
runwaydemo.console.page.blocked=Página de la demo creada en {0} como borrador: las comprobaciones de calidad bloquearon la publicación.
|
||||
runwaydemo.console.page.exists=Ya existe una página de la demo en {0}; no se cambió nada.
|
||||
runwaydemo.console.page.other=Instalación de la página de la demo terminada: {0} {1}
|
||||
runwaydemo.console.notes=Notas
|
||||
runwaydemo.console.notes.desc=Se guardan en la carpeta propia del plugin en este sitio. Contienen lo que la gente escribió, así que se declaran datos personales y las copias de transferencia las omiten.
|
||||
runwaydemo.console.note.new=Nota nueva
|
||||
runwaydemo.console.note.add=Agregar nota
|
||||
runwaydemo.console.note.blank=Escribe algo primero.
|
||||
runwaydemo.console.note.added=Nota agregada.
|
||||
runwaydemo.console.showcase=Página escaparate
|
||||
runwaydemo.console.showcase.desc=La sirve la fuente de contenido del plugin. Publicar o retirar anuncia el cambio, así que el enrutamiento, los sitemaps y la búsqueda se actualizan al instante.
|
||||
runwaydemo.console.showcase.at=Publicada en
|
||||
runwaydemo.console.showcase.text=Texto del escaparate
|
||||
runwaydemo.console.showcase.publish=Publicar
|
||||
runwaydemo.console.showcase.unpublish=Retirar
|
||||
runwaydemo.console.showcase.empty=No hay nada publicado.
|
||||
runwaydemo.console.showcase.blank=Escribe algo primero.
|
||||
runwaydemo.console.showcase.published=Escaparate publicado en {0}.
|
||||
runwaydemo.console.showcase.unpublished=Escaparate retirado.
|
||||
runwaydemo.console.showcase.none=No había ningún escaparate publicado.
|
||||
runwaydemo.console.catalog=Superficie de contenido
|
||||
runwaydemo.console.catalog.source=Fuente
|
||||
runwaydemo.console.catalog.item=Elemento
|
||||
runwaydemo.console.catalog.path=Ruta
|
||||
runwaydemo.console.catalog.refresh=Actualizar el listado
|
||||
runwaydemo.console.catalog.refreshed=Listado de contenido actualizado.
|
||||
runwaydemo.console.check=Comprobar una ruta
|
||||
runwaydemo.console.check.path=Ruta
|
||||
runwaydemo.console.check.unsafe=ruta no segura
|
||||
runwaydemo.console.check.servable=puede haber contenido aquí
|
||||
runwaydemo.console.check.reserved=reservada: no puede haber contenido aquí
|
||||
runwaydemo.console.check.owner=pertenece a la página publicada {0}
|
||||
runwaydemo.console.check.free=ninguna página publicada la ocupa
|
||||
runwaydemo.console.activity=Cambios recientes
|
||||
runwaydemo.console.activity.empty=No se ha visto ningún cambio desde que arrancó la plataforma.
|
||||
runwaydemo.console.activity.at=Cuándo
|
||||
runwaydemo.console.activity.cause=Causa
|
||||
runwaydemo.console.activity.item=Elemento
|
||||
runwaydemo.console.activity.before=URL antes
|
||||
runwaydemo.console.activity.after=URL después
|
||||
runwaydemo.console.activity.local=En este nodo
|
||||
@@ -0,0 +1,74 @@
|
||||
# =============================================================================
|
||||
# Runway Demo Plugin — descriptor
|
||||
# The kitchen-sink REFERENCE plugin: it exercises every extension axis and every
|
||||
# service of the SPI service tier, each the way a real plugin should
|
||||
# use it. Copy it to start a new plugin. Links ONLY the Runway SPI.
|
||||
# The install folder name MUST equal this `id`: external/plugins/runway-demo/.
|
||||
# =============================================================================
|
||||
id: runway-demo
|
||||
name: Runway Demo (Kitchen-Sink Plugin)
|
||||
version: 2.1.0
|
||||
|
||||
# The lowest SPI level this plugin needs; a kernel below it BLOCKS the plugin at startup with a reason. Declare the
|
||||
# floor of the NEWEST type you use: without it, an older kernel would load the plugin and fail at the first request
|
||||
# that touches a missing type. SPI 1.0.0 is the frozen 1.x contract.
|
||||
requiresSpi: ">=1.0.0"
|
||||
|
||||
# The @Configuration registered into the host context before refresh. Its package lives OUTSIDE
|
||||
# mx.quest.runway (mx.quest.demo) so the host never scans it, and every bean it defines is named runwayDemo…
|
||||
mainClass: mx.quest.demo.DemoPluginConfig
|
||||
|
||||
# `enabled` (optional, default true) is the operator's disable switch — omit to stay enabled.
|
||||
# `essential` is honored ONLY for kernel security-floor ids on the EssentialAllowlist (only 'protection'); a
|
||||
# normal plugin must NOT claim it.
|
||||
# `requires:` / `conflicts:` — this demo has no hard dependency, so it always loads. Forms (documented in
|
||||
# docs/DEMO-PLUGIN.md): requires: [ some-id ], [ some-id >= 1.2.0 ], [ some-id == 1.2.0 ]; conflicts: [ id ].
|
||||
|
||||
# --- Personal data ---------------------------------------------------------------------------------------
|
||||
# notes.yml holds what people typed: operator notes from the console AND visitors' messages from the public
|
||||
# feedback form. A TRANSFER copy of a site (the one handed to someone outside the organisation) leaves it out
|
||||
# and lists it in the archive's manifest; a FULL backup keeps it. Paths are relative to
|
||||
# sites/<id>/plugins/runway-demo/ (end a folder with "/"). showcase.yml is published content, not personal.
|
||||
siteData:
|
||||
personal:
|
||||
- notes.yml
|
||||
|
||||
# --- Grantable control-point permissions (namespaced <id>|<declId> in the catalog) -------------------
|
||||
# `settings` is the reserved id that gates this plugin's per-tenant settings form.
|
||||
# `manage-notes` gates the demo's console screen, its actions and /demo/notes.json (enforced server-side with
|
||||
# AccessCheck / @authz.may on the FULL key "runway-demo|manage-notes"; the menu and card use the full key too).
|
||||
# defaultRoles is EMPTY: control points start ungranted. Administrators hold them via the wildcard tier; a
|
||||
# tenant superadmin grants them explicitly to the seed OPERATOR role or a custom role.
|
||||
permissions:
|
||||
- { id: settings, realm: tenant, label: runwaydemo.perm.settings, defaultRoles: [] }
|
||||
- { id: manage-notes, realm: tenant, label: runwaydemo.perm.manageNotes, defaultRoles: [] }
|
||||
|
||||
# --- App-level settings (PLATFORM concerns; bound as runway.plugin.runway-demo.* from -------------------
|
||||
# external/plugin-settings/runway-demo.yml; applied on RESTART; read via the DemoAppProps bean)
|
||||
settings:
|
||||
- { key: banner.enabled, type: boolean, default: true, label: runwaydemo.settings.bannerEnabled }
|
||||
- { key: banner.text, type: text, label: runwaydemo.settings.bannerText }
|
||||
- { key: cache.max-entries, type: int, default: 500, range: "1..100000", label: runwaydemo.settings.cacheMax }
|
||||
- { key: generator.label, type: string, default: "Runway Demo", label: runwaydemo.settings.generatorLabel }
|
||||
- { key: analytics.write-key, type: secret, label: runwaydemo.settings.writeKey }
|
||||
|
||||
# --- Per-tenant settings (tenant-owned BEHAVIOUR; stored in sites/<id>/plugins/runway-demo.yml; applied ----
|
||||
# IMMEDIATELY; read with PluginSettings.site(siteId), a `secret` with PluginSettings.secret(siteId, key))
|
||||
siteSettings:
|
||||
- { key: notice.enabled, type: boolean, default: true, label: runwaydemo.settings.noticeEnabled }
|
||||
- { key: notice.style, type: enum, default: info, range: "info,warning,danger", label: runwaydemo.settings.noticeStyle }
|
||||
- { key: notice.max-chars, type: int, default: 280, range: "1..2000", label: runwaydemo.settings.noticeMax }
|
||||
- { key: analytics.enabled, type: boolean, default: false, label: runwaydemo.settings.analyticsEnabled }
|
||||
- { key: analytics.site-token, type: secret, label: runwaydemo.settings.siteToken }
|
||||
- { key: feedback.enabled, type: boolean, default: true, label: runwaydemo.settings.feedbackEnabled }
|
||||
- { key: quality.title-warn-ratio, type: decimal, default: 1.0, label: runwaydemo.settings.titleRatio }
|
||||
- { key: quality.ignore-codes, type: list, default: "", label: runwaydemo.settings.ignoreCodes }
|
||||
|
||||
# --- Tenant-console menu entry: the demo's own console screen (@ConsoleScreen), gated by the FULL key -------
|
||||
menu:
|
||||
- { realm: tenant, region: menu, order: 60, label: runwaydemo.menu.console,
|
||||
path: "/__admin/runway-demo", permission: "runway-demo|manage-notes", icon: "fa-solid fa-flask" }
|
||||
|
||||
# --- Tenant dashboard card (fragment resolves to __plugin__/runway-demo/dashboard = templates/dashboard.*) --
|
||||
dashboardCards:
|
||||
- { realm: tenant, order: 20, fragment: dashboard, permission: "runway-demo|manage-notes" }
|
||||
@@ -0,0 +1,184 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<!--
|
||||
Inherit the SAME managed dependency versions the Runway kernel uses (Spring Boot 4.0.6), so every
|
||||
`provided` Spring / Jackson type the plugin compiles against is byte-identical to the class the host
|
||||
loads at runtime. A plugin is NOT a Spring Boot application — there is NO spring-boot-maven-plugin
|
||||
repackage here; `mvn package` produces a THIN jar of only this plugin's own classes.
|
||||
-->
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>4.0.6</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>mx.quest</groupId>
|
||||
<!-- runway-plugin-<plugin id>, as for every plugin in this repository: the release zip is named after it
|
||||
(runway-plugin-runway-demo-<version>.zip under the tag runway-demo-<version>). -->
|
||||
<artifactId>runway-plugin-runway-demo</artifactId>
|
||||
<version>2.1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>Runway Demo Plugin</name>
|
||||
<licenses>
|
||||
<license>
|
||||
<name>Apache License, Version 2.0</name>
|
||||
<url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
|
||||
<distribution>repo</distribution>
|
||||
</license>
|
||||
</licenses>
|
||||
<description>
|
||||
The kitchen-sink REFERENCE plugin for Runway: every extension axis (head, widget, endpoint incl. an
|
||||
anonymous form POST, page-quality check, content source) and every service of the SPI service tier
|
||||
(PluginSettings, PluginInfo/PluginLifecycle, PluginSiteFiles, Sites, RequestContext, AccessCheck, Messages,
|
||||
SitePages, ContentCatalogView, ContentChanges, SiteEventListener, @ConsoleScreen), app-level and per-tenant
|
||||
settings, personal-data declaration, permissions, a menu entry, a dashboard card, an admin fragment, static
|
||||
assets, templates and i18n. Links only the Runway SPI.
|
||||
</description>
|
||||
|
||||
<properties>
|
||||
<java.version>25</java.version>
|
||||
<maven.compiler.release>25</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<!-- Reproducible builds: pins every archive entry's timestamp so two builds of the same source
|
||||
produce byte-identical artifacts. Without it a jar embeds the build time, so a rebuild can
|
||||
never match what was published. Bump at each release. -->
|
||||
<project.build.outputTimestamp>2026-10-21T17:23:00Z</project.build.outputTimestamp>
|
||||
<!-- The Runway SPI this plugin compiles against: a RELEASED kernel (its SPI jars installed
|
||||
from that release's assets). The plugin's runtime floor is plugin.yml's
|
||||
requiresSpi, not this number. -->
|
||||
<runway.version>1.0.0</runway.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!--
|
||||
The dependency-free extension API: the axis interfaces, the service tier and the immutable model
|
||||
records. COMPILE scope — it is the host's own stable artifact, resolved parent-first from the shared
|
||||
classloader at runtime. This is the ONLY Runway artifact a plugin depends on.
|
||||
-->
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-spi</artifactId>
|
||||
<version>${runway.version}</version>
|
||||
</dependency>
|
||||
<!-- NO runway-app dependency, in any scope: a host import no longer compiles, and the
|
||||
kernel's host-linkage scanner finds nothing to report. -->
|
||||
|
||||
<!-- In-memory fakes of every SPI service with the kernel's input rules (TempDirSiteFiles, FakePluginSettings,
|
||||
FakeSiteServices, FakeContentCatalog, EventDispatch). Tests only. -->
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-spi-testkit</artifactId>
|
||||
<version>${runway.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- The PLATFORM libraries the host provides at runtime (the kernel's MAJOR line pins their MAJOR lines):
|
||||
compile against them, never bundle them. -->
|
||||
<!-- Spring context/Boot: @Configuration, @Bean, @ConfigurationProperties. -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- Spring MVC: the @ConsoleScreen @Controller (DemoConsoleController). -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- Spring Security: @PreAuthorize("@authz.may('…')") on the console handlers. -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-core</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- Jackson 3 (tools.jackson) YAML: the plugin's own serializer for notes.yml and showcase.yml. -->
|
||||
<dependency>
|
||||
<groupId>tools.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-yaml</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Unit tests run against the compiled classes (NEVER spring-boot:run — DevTools' restart classloader
|
||||
loads ZERO plugins). The servlet API lets MockMvc drive the console controller in-process. -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.servlet</groupId>
|
||||
<artifactId>jakarta.servlet-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<!-- Stable deployed filename (no version/classifier): target/runway-plugin-demo.jar. It deliberately keeps
|
||||
its pre-2.0.1 name although the artifactId changed: the kernel loads EVERY *.jar in the plugin's folder
|
||||
(plugin.yml names no jar), so a filesystem upgrade that copies the new folder over the old one would
|
||||
otherwise leave the old jar beside the new and load both. The console upload replaces the whole
|
||||
folder; a copy does not. -->
|
||||
<finalName>runway-plugin-demo</finalName>
|
||||
<plugins>
|
||||
<!--
|
||||
After the jar is built, assemble the plugin in BOTH installable forms the platform accepts:
|
||||
1. target/runway-demo/ — the install-ready folder for a FILESYSTEM install
|
||||
(`cp -r target/runway-demo <runway-external>/plugins/` + restart).
|
||||
2. target/runway-plugin-runway-demo-<version>.zip — the archive the MANAGEMENT UI upload expects
|
||||
(/__app/plugins → install): plugin.yml under a single wrapping dir (runway-demo/) alongside
|
||||
the jar + static/ templates/ i18n/. The host validates the descriptor and lays it into
|
||||
external/plugins/<id>/ (id from the descriptor), then applies on restart.
|
||||
-->
|
||||
<plugin>
|
||||
<artifactId>maven-antrun-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>assemble-plugin-folder</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>run</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<target>
|
||||
<property name="stage" value="${project.build.directory}/runway-demo"/>
|
||||
<delete dir="${stage}"/>
|
||||
<mkdir dir="${stage}"/>
|
||||
<copy file="${project.basedir}/plugin.yml" todir="${stage}"/>
|
||||
<copy file="${project.basedir}/LICENSE" todir="${stage}"/>
|
||||
<copy file="${project.basedir}/NOTICE" todir="${stage}"/>
|
||||
<copy file="${project.build.directory}/runway-plugin-demo.jar" todir="${stage}"/>
|
||||
<copy todir="${stage}/static">
|
||||
<fileset dir="${project.basedir}/static"/>
|
||||
</copy>
|
||||
<copy todir="${stage}/templates">
|
||||
<fileset dir="${project.basedir}/templates"/>
|
||||
</copy>
|
||||
<copy todir="${stage}/i18n">
|
||||
<fileset dir="${project.basedir}/i18n"/>
|
||||
</copy>
|
||||
<!-- The UI-uploadable archive: plugin.yml under a single wrapping dir. -->
|
||||
<touch datetime="${project.build.outputTimestamp}"
|
||||
pattern="yyyy-MM-dd'T'HH:mm:ss'Z'">
|
||||
<fileset dir="${stage}"/>
|
||||
<dirset dir="${stage}"/>
|
||||
<dirset dir="${project.build.directory}" includes="runway-demo"/>
|
||||
</touch>
|
||||
<zip destfile="${project.build.directory}/${project.artifactId}-${project.version}.zip">
|
||||
<zipfileset dir="${project.build.directory}" includes="runway-demo/**"/>
|
||||
</zip>
|
||||
<echo message="Staged install folder: ${stage}"/>
|
||||
<echo message="UI-uploadable archive: ${project.build.directory}/${project.artifactId}-${project.version}.zip"/>
|
||||
</target>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
Executable
+21
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# install-into.sh — copy the assembled runway-demo plugin into a Runway deployment's external tree.
|
||||
# The host must be RESTARTED afterwards for the plugin to load (restart-to-install; no hot reload).
|
||||
#
|
||||
# Usage: scripts/install-into.sh <runway-external-dir>
|
||||
# e.g. scripts/install-into.sh /opt/runway-data/external
|
||||
set -euo pipefail
|
||||
|
||||
EXTERNAL="${1:?usage: install-into.sh <runway-external-dir>}"
|
||||
PROJECT_DIR="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
|
||||
STAGE="$PROJECT_DIR/target/runway-demo"
|
||||
|
||||
[ -d "$STAGE" ] || { echo "ERROR: $STAGE not built — run 'mvn package' first"; exit 1; }
|
||||
[ -d "$EXTERNAL" ] || { echo "ERROR: not a directory: $EXTERNAL"; exit 1; }
|
||||
|
||||
mkdir -p "$EXTERNAL/plugins"
|
||||
rm -rf "$EXTERNAL/plugins/runway-demo"
|
||||
cp -a "$STAGE" "$EXTERNAL/plugins/runway-demo"
|
||||
echo "installed runway-demo → $EXTERNAL/plugins/runway-demo"
|
||||
echo "RESTART the Runway host for it to load (plugins load only in ACTIVE mode)."
|
||||
Executable
+269
@@ -0,0 +1,269 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build the runway-demo plugin, drop it into a THROWAWAY Runway deployment, boot the PACKAGED host in ACTIVE mode, and
|
||||
# prove the demo's contract end to end:
|
||||
# - it loads with ZERO host-linkage and bean-name/surface warnings, and its PluginLifecycle hook runs;
|
||||
# - head injection, the static assets, /demo/hello.txt and /demo/echo.json (lowercase headers, clientIp, origin);
|
||||
# no timing header any more (servlet filters are outside the 1.0 plugin contract);
|
||||
# - /demo/notes.json is permission-gated (AccessCheck): 403 anonymous, 200 for the signed-in owner;
|
||||
# - a GET writes nothing: the owner opening the screen, notes.json and the settings page leaves the site with no
|
||||
# notes.yml, though the screen shows the welcome note;
|
||||
# - the anonymous feedback POST (no session, no CSRF token) is stored as a note and 303s back with only an outcome;
|
||||
# honeypot, blank, query-string fields and a non-form body are refused; a GET submits nothing;
|
||||
# - the @ConsoleScreen renders inside the console shell for the owner, is refused to an anonymous caller, and its
|
||||
# actions are CSRF-checked POSTs (403 without the token); with the token: a note is added, the starter page is
|
||||
# installed through SitePages and serves both widgets, the showcase ContentSource publishes (ContentChanges) and
|
||||
# unpublishes, and the SiteEventListener shows each change with its URLs before and after;
|
||||
# - saving the per-site settings appends the audit note (onSettingsChanged) and a per-site secret is read back
|
||||
# (PluginSettings.secret) without being shown;
|
||||
# - a FULL backup carries notes.yml and a TRANSFER copy leaves it out (siteData.personal) and lists it.
|
||||
# Verify ONLY against the packaged jar — never spring-boot:run (its restart classloader loads ZERO plugins).
|
||||
#
|
||||
# Usage: scripts/verify-against-host.sh [--keep] [--port N]
|
||||
# JAVA_HOME=/path/to/jdk-25 required: the JDK that builds the plugin and runs the host
|
||||
# MVN=/path/to/mvn Maven (default: mvn on the PATH)
|
||||
# HOST_TARGET=/path/to/runway/runway-app/target the host build (default: the kernel this plugin sits in, else ../runway)
|
||||
# HOST_JAR=/path/to/runway-app-<ver>-exec.jar the kernel to verify against (default: the host checkout's
|
||||
# runway-app/target jar MATCHING its pom version)
|
||||
# VERIFY_TMPDIR=/dir where the throwaway deployment goes (default: $TMPDIR or /tmp)
|
||||
# VERIFY_LOG_DIR=/dir keep copies of the host logs, the backup manifests and the fetched
|
||||
# pages there (evidence)
|
||||
# The script never runs `mvn install` (nothing is written to ~/.m2): it packages this plugin offline against whatever
|
||||
# runway-spi is already in the local repository.
|
||||
set -uo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
|
||||
VER="$(sed -n 's/^version: *//p' "$HERE/plugin.yml")" # the release under test
|
||||
# JAVA_HOME must name a JDK 25. MVN (default: `mvn` on the PATH) and HOST_TARGET (default: see above) can be set in the environment.
|
||||
if [ -z "${JAVA_HOME:-}" ] || [ ! -x "$JAVA_HOME/bin/java" ]; then echo "set JAVA_HOME to a JDK 25"; exit 2; fi
|
||||
export JAVA_HOME
|
||||
JAVA="$JAVA_HOME/bin/java"
|
||||
MVN="${MVN:-mvn}"
|
||||
# Default host: the kernel at the root of the repository this plugin sits in (plugins/<name>/), else a kernel
|
||||
# checkout named `runway` beside the plugins checkout.
|
||||
if [ -z "${HOST_TARGET:-}" ]; then
|
||||
if [ -f "$HERE/../../../runway-app/pom.xml" ]; then HOST_TARGET="$HERE/../../../runway-app/target"
|
||||
else HOST_TARGET="$HERE/../../runway/runway-app/target"; fi
|
||||
fi
|
||||
|
||||
KEEP="no"; PORT=""
|
||||
while [ $# -gt 0 ]; do case "$1" in
|
||||
--keep) KEEP="yes"; shift ;;
|
||||
--port) PORT="${2:?}"; shift 2 ;;
|
||||
*) echo "unknown arg: $1"; exit 2 ;;
|
||||
esac; done
|
||||
|
||||
APP_USER=root; APP_PW=Demo-Admin-2026; SITE_USER=owner; SITE_PW=Demo-Site-2026
|
||||
SECRET_KEY=demo-verify-master-key-2026
|
||||
free_port() { python3 -I -c 'import socket;s=socket.socket();s.bind(("127.0.0.1",0));print(s.getsockname()[1]);s.close()'; }
|
||||
[ -n "$PORT" ] || PORT="$(free_port)"
|
||||
BASE="http://localhost:$PORT"
|
||||
|
||||
echo "[verify] building the plugin ..."
|
||||
( cd "$HERE" && "$MVN" -o -q -DskipTests package ) || { echo "plugin build failed"; exit 1; }
|
||||
|
||||
# The host jar MATCHING the host pom's version — never "the newest file": every reproducible jar carries the same
|
||||
# fixed timestamp, so `ls -t` cannot tell a leftover release jar from the SNAPSHOT under test.
|
||||
if [ -n "${HOST_JAR:-}" ]; then
|
||||
JAR="$HOST_JAR"
|
||||
else
|
||||
HOST_VERSION="$(sed -n 's:.*<version>\(.*\)</version>.*:\1:p' "$HOST_TARGET/../pom.xml" | head -1)"
|
||||
JAR="$HOST_TARGET/runway-app-$HOST_VERSION-exec.jar"
|
||||
fi
|
||||
[ -f "$JAR" ] || { echo "no host exec jar $JAR — build the host (mvn -pl runway-app package) or set HOST_JAR"; exit 1; }
|
||||
echo "[verify] host jar: $JAR"
|
||||
|
||||
mkdir -p "${VERIFY_TMPDIR:-${TMPDIR:-/tmp}}"
|
||||
SCRATCH="$(mktemp -d "${VERIFY_TMPDIR:-${TMPDIR:-/tmp}}/runway-demo-verify.XXXXXX")"
|
||||
cleanup() {
|
||||
[ -z "${VERIFY_LOG_DIR:-}" ] || { mkdir -p "$VERIFY_LOG_DIR" \
|
||||
&& cp "$SCRATCH"/*.log "$SCRATCH"/*-manifest.yml "$SCRATCH"/*.html "$SCRATCH"/*.json "$VERIFY_LOG_DIR"/ 2>/dev/null; }
|
||||
# Wait for the host to exit before deleting: a JVM still shutting down rewrites files under external/ and makes
|
||||
# `rm -rf` leave the scratch folder behind.
|
||||
[ "$KEEP" = "yes" ] || { kill "${PID:-0}" 2>/dev/null; wait "${PID:-0}" 2>/dev/null; rm -rf "$SCRATCH"; }
|
||||
}
|
||||
trap cleanup EXIT
|
||||
EXT="$SCRATCH/external"
|
||||
mkdir -p "$EXT/plugins"
|
||||
cp -r "$HERE/target/runway-demo" "$EXT/plugins/runway-demo"
|
||||
|
||||
wait_for() { for _ in $(seq 1 "$3"); do grep -q "$2" "$1" 2>/dev/null && return 0; sleep 1; done; return 1; }
|
||||
PASS=0; FAIL=0
|
||||
ck() { if eval "$2" >/dev/null 2>&1; then echo " PASS $1"; PASS=$((PASS+1)); else echo " FAIL $1"; FAIL=$((FAIL+1)); fi; }
|
||||
boot() { ( cd "$SCRATCH" && exec "$JAVA" -jar "$JAR" --server.port="$PORT" --runway.storage.external="$EXT" \
|
||||
--runway.security.secret-key="$SECRET_KEY" ) >"$1" 2>&1 & PID=$!; }
|
||||
|
||||
echo "[verify] booting host (wizard) on :$PORT ..."
|
||||
boot "$SCRATCH/wizard.log"
|
||||
wait_for "$SCRATCH/wizard.log" "Started RunwayApplication" 90 || { echo "wizard did not start"; tail -20 "$SCRATCH/wizard.log"; exit 1; }
|
||||
curl -s -o /dev/null -X POST "$BASE/setup" --data-urlencode "username=$APP_USER" --data-urlencode "password=$APP_PW" \
|
||||
--data-urlencode "displayName=Root" --data-urlencode "siteAdminUsername=$SITE_USER" --data-urlencode "siteAdminPassword=$SITE_PW"
|
||||
for _ in $(seq 1 30); do kill -0 "$PID" 2>/dev/null || break; sleep 1; done
|
||||
|
||||
echo "[verify] booting host (ACTIVE) ..."
|
||||
boot "$SCRATCH/active.log"
|
||||
wait_for "$SCRATCH/active.log" "Started RunwayApplication" 90 || { echo "ACTIVE did not start"; tail -20 "$SCRATCH/active.log"; exit 1; }
|
||||
LOG="$SCRATCH/active.log"
|
||||
SITES="$EXT/sites"
|
||||
NOTES="$SITES/default/plugins/runway-demo/notes.yml"
|
||||
code() { curl -s -o /dev/null -w '%{http_code}' "$@"; }
|
||||
|
||||
echo "== plugin load (SPI 0.6.0 contract) =="
|
||||
ck "plugins registered (1), 0 blocked" "grep -qE 'plugins: 1 registered, 0 blocked' '$LOG'"
|
||||
ck "not blocked / quarantined" "! grep -qE \"plugin 'runway-demo' is blocked|plugin-quarantine\" '$LOG'"
|
||||
ck "ZERO host-linkage warnings" "! grep -q 'uses host internals' '$LOG'"
|
||||
ck "ZERO bean-name/surface warnings" "! grep -qE \"plugin 'runway-demo': .*allowed until Runway 1.0\" '$LOG'"
|
||||
ck "no WARN/ERROR names the plugin" "! grep -E ' (WARN|ERROR) ' '$LOG' | grep -qiE 'runway-demo|mx.quest.demo'"
|
||||
ck "no key collision / degraded" "! grep -qiE 'collision|duplicate key|degraded' '$LOG'"
|
||||
# The running SPI is the host's (0.6.0 on beta14, 1.0.0 on rc1): accept any, as the plugin itself reports both.
|
||||
ck "PluginLifecycle.started ran with PluginInfo" \
|
||||
"grep -qE 'runway-demo $VER started — install dir .*runway-demo; built against SPI [0-9]+\\.[0-9]+\\.[0-9]+, running on SPI [0-9]+\\.[0-9]+\\.[0-9]+' '$LOG'"
|
||||
|
||||
echo "== public surfaces =="
|
||||
ck "static css, script and help page served" \
|
||||
"[ \"\$(code '$BASE/__plugin/runway-demo/static/css/demo.css')\" = 200 ] && [ \"\$(code '$BASE/__plugin/runway-demo/static/js/demo-analytics.js')\" = 200 ] && [ \"\$(code '$BASE/__plugin/runway-demo/static/notes-help.html')\" = 200 ]"
|
||||
curl -s -D "$SCRATCH/home-headers.txt" "$BASE/" > "$SCRATCH/home.html"
|
||||
ck "head injection on / (generator meta + stylesheet)" \
|
||||
"grep -q 'name=\"generator\" content=\"Runway Demo\"' '$SCRATCH/home.html' && grep -q '/__plugin/runway-demo/static/css/demo.css' '$SCRATCH/home.html'"
|
||||
ck "no X-Demo-Plugin header (the servlet filter is gone)" "! grep -qi '^X-Demo-Plugin' '$SCRATCH/home-headers.txt'"
|
||||
ck "GET /demo/hello.txt = 200, localized greeting" \
|
||||
"curl -s '$BASE/demo/hello.txt' | grep -q '^Hello from the runway-demo plugin!'"
|
||||
curl -s -H 'X-Test: Yes' "$BASE/demo/echo.json?q=1" > "$SCRATCH/echo.json"
|
||||
ck "echo.json: lowercase header names, gated clientIp, origin, query" \
|
||||
"grep -q '\"x-test\":\"Yes\"' '$SCRATCH/echo.json' && grep -qE '\"clientIp\":\"(127.0.0.1|\\[0:0:0:0:0:0:0:1\\])\"' '$SCRATCH/echo.json' && grep -q '\"origin\":\"http://localhost:$PORT\"' '$SCRATCH/echo.json' && grep -q '\"param.q\":\"1\"' '$SCRATCH/echo.json'"
|
||||
ck "GET /demo/notes.json anonymous = 403 (AccessCheck)" "[ \"\$(code '$BASE/demo/notes.json')\" = 403 ]"
|
||||
|
||||
echo "== a GET writes nothing: the welcome note is shown, not stored =="
|
||||
JAR_C="$SCRATCH/cookies.txt"
|
||||
sc() { curl -s -H 'Accept-Language: en' -c "$JAR_C" -b "$JAR_C" "$@"; }
|
||||
token() { grep -o 'name="_csrf" value="[^"]*"' | head -1 | sed 's/.*value="//; s/"$//'; }
|
||||
sc -o /dev/null -X POST "$BASE/login" --data-urlencode "username=$SITE_USER" --data-urlencode "password=$SITE_PW" \
|
||||
--data-urlencode "_csrf=$(sc "$BASE/login" | token)"
|
||||
sc "$BASE/__admin/runway-demo" > "$SCRATCH/screen-first.html"
|
||||
sc -o /dev/null "$BASE/demo/notes.json"
|
||||
sc -o /dev/null "$BASE/__admin/plugins/runway-demo/settings"
|
||||
ck "the owner's screen shows the welcome note" "grep -q 'this note is data the runway-demo plugin' '$SCRATCH/screen-first.html'"
|
||||
ck "…yet the screen, notes.json and the settings page wrote no notes.yml" "[ ! -e '$NOTES' ]"
|
||||
|
||||
echo "== the anonymous feedback POST (no session, no CSRF token) =="
|
||||
post() { curl -s -o /dev/null -w '%{http_code} %{redirect_url}' -X POST "$@"; }
|
||||
R="$(post "$BASE/demo/feedback" --data-urlencode 'return=/demo' --data-urlencode 'message=Hello from a visitor' \
|
||||
--data-urlencode 'website=')"
|
||||
ck "valid POST -> 303 back with ?demo-feedback=thanks" "[ \"\${R%% *}\" = 303 ] && echo '$R' | grep -q '/demo?demo-feedback=thanks'"
|
||||
ck "the redirect carries no submitted value" "! echo '$R' | grep -qi 'visitor'"
|
||||
ck "stored in sites/default/plugins/runway-demo/notes.yml as a visitor note" \
|
||||
"grep -q 'Hello from a visitor' '$NOTES' && grep -q 'origin: \"\\?visitor' '$NOTES'"
|
||||
ck "a GET submits nothing (404)" "[ \"\$(code '$BASE/demo/feedback?message=via-get')\" = 404 ] && ! grep -q 'via-get' '$NOTES'"
|
||||
ck "a filled honeypot fakes success and stores nothing" \
|
||||
"post '$BASE/demo/feedback' -d 'message=bot-spam&website=http://spam' | grep -q 'demo-feedback=thanks' && ! grep -q 'bot-spam' '$NOTES'"
|
||||
ck "a blank message -> ?demo-feedback=invalid" "post '$BASE/demo/feedback' -d 'message=%20' | grep -q 'demo-feedback=invalid'"
|
||||
ck "fields in the query string are ignored" \
|
||||
"post '$BASE/demo/feedback?message=in-the-url' -d 'x=1' | grep -q 'demo-feedback=invalid' && ! grep -q 'in-the-url' '$NOTES'"
|
||||
ck "a multipart body is refused 415 by the kernel" \
|
||||
"[ \"\$(curl -s -o /dev/null -w '%{http_code}' -X POST '$BASE/demo/feedback' -F 'message=multi')\" = 415 ]"
|
||||
ck "notes.yml is never served publicly" \
|
||||
"( for u in '/plugins/runway-demo/notes.yml' '/__plugin/runway-demo/static/../../notes.yml'; do curl -s --path-as-is '$BASE'\$u | grep -q 'Hello from a visitor' && exit 1; done; exit 0 )"
|
||||
|
||||
echo "== the @ConsoleScreen and its CSRF-checked actions =="
|
||||
ck "anonymous GET /__admin/runway-demo is refused (sign-in required)" \
|
||||
"[ \"\$(code '$BASE/__admin/runway-demo')\" != 200 ]"
|
||||
ck "anonymous POST without a token -> 403" "[ \"\$(code -X POST '$BASE/__admin/runway-demo/notes' -d text=x)\" = 403 ]"
|
||||
# The owner signed in above (the GET-writes-nothing checks); the session is in $JAR_C.
|
||||
SCREEN="$BASE/__admin/runway-demo"
|
||||
sc "$SCREEN" > "$SCRATCH/screen-0.html"
|
||||
ck "the owner sees the screen inside the console shell" \
|
||||
"grep -q 'id=\"op-main\"' '$SCRATCH/screen-0.html' && grep -q 'id=\"rd-heading\"' '$SCRATCH/screen-0.html' && grep -q '<title id=\"op-title\">Runway demo · ' '$SCRATCH/screen-0.html'"
|
||||
ck "…showing the plugin version and both SPI versions" \
|
||||
"grep -q 'id=\"rd-version\">$VER<' '$SCRATCH/screen-0.html' && grep -qE 'id=\"rd-running\">[0-9]+\\.[0-9]+\\.[0-9]+<' '$SCRATCH/screen-0.html'"
|
||||
ck "…and its actions as POST forms carrying a non-empty CSRF token" \
|
||||
"grep -q 'method=\"post\" action=\"/__admin/runway-demo/install-page\"' '$SCRATCH/screen-0.html' && grep -qE 'class=\"rd-csrf\" type=\"hidden\" name=\"_csrf\" value=\"[^\"]+\"' '$SCRATCH/screen-0.html'"
|
||||
ck "the owner's POST without the token -> 403, nothing added" \
|
||||
"[ \"\$(sc -o /dev/null -w '%{http_code}' -X POST '$SCREEN/notes' -d text=forged)\" = 403 ] && ! grep -q forged '$NOTES'"
|
||||
ck "a GET on an action path changes nothing" \
|
||||
"[ \"\$(sc -o /dev/null -w '%{http_code}' '$SCREEN/install-page')\" != 302 ] && [ ! -e '$SITES/default/templates/runway-demo.html' ]"
|
||||
act() { # path [curl args...] -> follows the redirect, prints the screen
|
||||
local p="$1"; shift
|
||||
# No -X POST: with -L it would also turn the redirect's follow-up GET into a POST. --data-urlencode makes it a POST.
|
||||
sc -L "$SCREEN$p" --data-urlencode "_csrf=$(sc "$SCREEN" | token)" "$@"
|
||||
}
|
||||
act /notes --data-urlencode 'text=An operator note' > "$SCRATCH/screen-note.html"
|
||||
ck "add a note: flash, listed, stored as a console note" \
|
||||
"grep -q 'Note added.' '$SCRATCH/screen-note.html' && grep -q 'An operator note' '$SCRATCH/screen-note.html' && grep -q 'An operator note' '$NOTES'"
|
||||
ck "the owner reads /demo/notes.json (200)" "[ \"\$(sc -o /dev/null -w '%{http_code}' '$BASE/demo/notes.json')\" = 200 ]"
|
||||
act /install-page > "$SCRATCH/screen-page.html"
|
||||
ck "install the starter page through SitePages (Advisory site -> published)" \
|
||||
"grep -q 'Demo page published at /demo.' '$SCRATCH/screen-page.html'"
|
||||
curl -s "$BASE/demo" > "$SCRATCH/demo-page.html"
|
||||
ck "/demo serves both widgets inside the site's chrome" \
|
||||
"grep -q 'rw-demo-notice' '$SCRATCH/demo-page.html' && grep -q 'action=\"/demo/feedback\"' '$SCRATCH/demo-page.html' && grep -q 'name=\"return\" value=\"/demo\"' '$SCRATCH/demo-page.html'"
|
||||
ck "…and shows a feedback outcome from the query flag" \
|
||||
"curl -s '$BASE/demo?demo-feedback=thanks' | grep -q 'Thank you'"
|
||||
act /install-page > "$SCRATCH/screen-page2.html"
|
||||
ck "a second install changes nothing" "grep -q 'A demo page already exists at /demo; nothing changed.' '$SCRATCH/screen-page2.html'"
|
||||
ck "the path check: /demo is owned by the published page runway-demo" \
|
||||
"sc '$SCREEN?path=/demo' | grep -q 'owned by the published page runway-demo'"
|
||||
ck "the path check: /__admin is reserved" "sc '$SCREEN?path=/__admin' | grep -q 'reserved: no content may live here'"
|
||||
|
||||
echo "== the showcase ContentSource, ContentChanges and the SiteEventListener =="
|
||||
ck "nothing at /demo/showcase before publishing" "[ \"\$(code '$BASE/demo/showcase')\" = 404 ]"
|
||||
act /showcase --data-urlencode 'text=Showcase <live> text' > "$SCRATCH/screen-show.html"
|
||||
ck "publish: flash and live block" \
|
||||
"grep -q 'Showcase published at /demo/showcase.' '$SCRATCH/screen-show.html' && grep -q 'Showcase <live> text' '$SCRATCH/screen-show.html'"
|
||||
curl -s "$BASE/demo/showcase" > "$SCRATCH/showcase.html"
|
||||
ck "/demo/showcase serves the escaped text inside the site's chrome" \
|
||||
"grep -q '<h1 id=\"showcase-title\">Showcase</h1>' '$SCRATCH/showcase.html' && grep -q 'Showcase <live> text' '$SCRATCH/showcase.html'"
|
||||
ck "the content listing shows the source's entry" "grep -q '<td class=\"rd-cat-source\">runway-demo</td>' '$SCRATCH/screen-show.html'"
|
||||
ck "the listener saw the CONTENT change with its URL after" \
|
||||
"grep -A4 '<td class=\"rd-act-item\">runway-demo:showcase</td>' '$SCRATCH/screen-show.html' | grep -q '<td class=\"rd-act-after\">/demo/showcase</td>'"
|
||||
act /showcase/unpublish > "$SCRATCH/screen-unshow.html"
|
||||
ck "unpublish: flash, and /demo/showcase is gone at once" \
|
||||
"grep -q 'Showcase unpublished.' '$SCRATCH/screen-unshow.html' && [ \"\$(code '$BASE/demo/showcase')\" = 404 ]"
|
||||
ck "the listener saw the removal with the URL before (previousUrls)" \
|
||||
"grep -A3 '<td class=\"rd-act-item\">runway-demo:showcase</td>' '$SCRATCH/screen-unshow.html' | head -4 | grep -q '<td class=\"rd-act-before\">/demo/showcase</td>'"
|
||||
|
||||
echo "== per-site settings: the audit note (onSettingsChanged) and a secret (PluginSettings.secret) =="
|
||||
SETTINGS="$BASE/__admin/plugins/runway-demo/settings"
|
||||
BEFORE="$(grep -c 'Per-site settings saved at' "$NOTES" || true)"
|
||||
sc -o /dev/null -X POST "$SETTINGS" --data-urlencode "notice.enabled=true" --data-urlencode "notice.style=warning" \
|
||||
--data-urlencode "notice.max-chars=280" --data-urlencode "feedback.enabled=true" \
|
||||
--data-urlencode "quality.title-warn-ratio=1.0" --data-urlencode "analytics.site-token=verify-token-42" \
|
||||
--data-urlencode "_csrf=$(sc "$SETTINGS" | token)"
|
||||
CFG="$SITES/default/plugins/runway-demo.yml"
|
||||
ck "the save appended one audit note" "[ \"\$(grep -c 'Per-site settings saved at' '$NOTES')\" = \$(( $BEFORE + 1 )) ]"
|
||||
ck "the secret is stored ENC(...), never in clear" "grep -q 'analytics.site-token: .*ENC(' '$CFG' && ! grep -q verify-token-42 '$CFG'"
|
||||
sc "$SETTINGS" > "$SCRATCH/settings.html"
|
||||
ck "the admin fragment reads it back as configured, without the value" \
|
||||
"grep -q 'Per-site analytics token configured: true' '$SCRATCH/settings.html' && ! grep -q verify-token-42 '$SCRATCH/settings.html'"
|
||||
ck "…and links the screen for a user who may open it (@authz.may)" "grep -q 'id=\"rd-admin-console\"' '$SCRATCH/settings.html'"
|
||||
ck "the saved style applies at once" "curl -s '$BASE/demo' | grep -q 'rw-demo-notice-warning'"
|
||||
|
||||
echo "== backups: a full backup keeps notes.yml, a transfer copy leaves it out =="
|
||||
sc -o "$SCRATCH/full.zip" "$BASE/__admin/backups/download"
|
||||
sc -o "$SCRATCH/transfer.zip" "$BASE/__admin/backups/download-transfer"
|
||||
zipq() { # zip mode [suffix] -> exit status / prints
|
||||
python3 -I - "$@" <<'PY'
|
||||
import sys, zipfile
|
||||
z = zipfile.ZipFile(sys.argv[1]); mode = sys.argv[2]
|
||||
names = z.namelist()
|
||||
if mode == "has":
|
||||
sys.exit(0 if any(n.endswith(sys.argv[3]) for n in names) else 1)
|
||||
if mode == "read":
|
||||
n = next(n for n in names if n.endswith(sys.argv[3])); sys.stdout.write(z.read(n).decode("utf-8"))
|
||||
PY
|
||||
}
|
||||
zipq "$SCRATCH/full.zip" read manifest.yml > "$SCRATCH/full-manifest.yml" 2>/dev/null
|
||||
zipq "$SCRATCH/transfer.zip" read manifest.yml > "$SCRATCH/transfer-manifest.yml" 2>/dev/null
|
||||
ck "the full backup carries plugins/runway-demo/notes.yml with the notes" \
|
||||
"zipq '$SCRATCH/full.zip' read plugins/runway-demo/notes.yml | grep -q 'Hello from a visitor'"
|
||||
ck "the transfer copy has NO plugins/runway-demo/notes.yml" "! zipq '$SCRATCH/transfer.zip' has plugins/runway-demo/notes.yml"
|
||||
ck "…and its manifest lists the omission" "grep -q 'plugins/runway-demo/notes.yml' '$SCRATCH/transfer-manifest.yml'"
|
||||
ck "…while the settings file travels with the secret blanked" \
|
||||
"zipq '$SCRATCH/transfer.zip' has plugins/runway-demo.yml && ! zipq '$SCRATCH/transfer.zip' read plugins/runway-demo.yml | grep -q 'ENC('"
|
||||
ck "the full backup's manifest omits nothing of the demo" "! grep -q 'plugins/runway-demo/notes.yml' '$SCRATCH/full-manifest.yml'"
|
||||
|
||||
echo "== nothing went wrong along the way =="
|
||||
ck "no WARN/ERROR names the plugin after the run" "! grep -E ' (WARN|ERROR) ' '$LOG' | grep -qiE 'runway-demo|mx.quest.demo'"
|
||||
ck "no contribution failure was counted" "! grep -qiE 'contribution .*fail|listener .*threw' '$LOG'"
|
||||
|
||||
echo; echo "RESULT: $PASS passed, $FAIL failed"
|
||||
if [ "$KEEP" = "yes" ]; then echo "[verify] kept at $BASE (scratch $SCRATCH; kill $PID to stop)"; wait "$PID"; fi
|
||||
exit "$FAIL"
|
||||
@@ -0,0 +1,137 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import mx.quest.runway.spi.model.CatalogChange;
|
||||
import mx.quest.runway.spi.model.LocalizedUrl;
|
||||
import mx.quest.runway.spi.model.SettingsChange;
|
||||
import mx.quest.runway.spi.model.SiteLifecycleEvent;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
import mx.quest.runway.spi.service.Sites;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* {@code SiteEventListener} in the default {@link Phase#CONSUMER CONSUMER} phase — what a plugin that reacts to
|
||||
* changes it does not own implements (a sitemap, a search index, a change notifier). It replaces listening to the
|
||||
* host's internal Spring events, whose order against the kernel's caches was never a contract.
|
||||
*
|
||||
* <p><b>When each callback is for:</b>
|
||||
* <ul>
|
||||
* <li>{@link #onSettingsChanged} — a save of <b>this plugin's own</b> per-site settings (and nothing else);
|
||||
* {@code PluginSettings.site()} already returns the new values. The demo writes an audit note, as 1.x did —
|
||||
* but only when {@link SettingsChange#local()} is true: on a cluster every node receives the change (the
|
||||
* others as a replay, {@code local == false}), and a side effect must happen once, not once per node.</li>
|
||||
* <li>{@link #onCatalogChanged} — anything that may reshape a site's content surface: a page write ({@code PAGE}),
|
||||
* a {@code ContentChanges} call ({@code CONTENT}), a lifecycle event ({@code SITE}) or any plugin's settings
|
||||
* save ({@code SETTINGS}). A {@code PAGE} or {@code CONTENT} change carries the item's URLs <b>before</b>
|
||||
* ({@code previousUrls}, so a deleted or moved item still names its old address) and <b>after</b>
|
||||
* ({@code currentUrls}). The demo keeps the last {@value #KEEP} per site in memory and shows them on its
|
||||
* console screen — an IndexNow-style notifier would submit the union of both lists.</li>
|
||||
* <li>{@link #onSiteLifecycle} — created, updated, suspended, resumed, deleted, restored. On a <b>wholesale</b>
|
||||
* event (deleted, restored) drop everything derived from the site's files; here, the recorded activity.</li>
|
||||
* </ul>
|
||||
* <b>Guarantees you can rely on:</b> every kernel cache the change affects is already evicted (reads see the new
|
||||
* state); no host lock is held (calling any service is safe); one throwing callback is logged and counted, never
|
||||
* propagated. <b>Duty:</b> callbacks run on the writer's thread — evict, record or enqueue; anything slow (a network
|
||||
* call, an index rebuild) belongs on your own executor. The audit note is one small, bounded file write.
|
||||
*
|
||||
* <p>It also shows {@link Sites}: the way code that knows a site only by id — a listener, a background task — gets
|
||||
* the site's {@link SiteView}, off-request.
|
||||
*/
|
||||
public class DemoActivity implements SiteEventListener {
|
||||
|
||||
/** How many recent changes are kept per site. */
|
||||
static final int KEEP = 10;
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(DemoActivity.class);
|
||||
|
||||
/**
|
||||
* One recorded change, as the console screen shows it.
|
||||
*
|
||||
* @param at when this node received it
|
||||
* @param cause {@code PAGE}, {@code CONTENT}, {@code SITE}, {@code SETTINGS} (lower case)
|
||||
* @param item {@code <sourceKey>:<id>}, the plugin for a settings change, or {@code ""}
|
||||
* @param previousUrls the item's paths before the change
|
||||
* @param currentUrls the item's paths after it
|
||||
* @param local whether the change happened on this node
|
||||
*/
|
||||
public record Entry(Instant at, String cause, String item, List<String> previousUrls, List<String> currentUrls,
|
||||
boolean local) {
|
||||
}
|
||||
|
||||
private final DemoNotesStore notes;
|
||||
private final Sites sites;
|
||||
private final ConcurrentMap<String, Deque<Entry>> recent = new ConcurrentHashMap<>();
|
||||
|
||||
public DemoActivity(DemoNotesStore notes, Sites sites) {
|
||||
this.notes = notes;
|
||||
this.sites = sites;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSiteLifecycle(SiteLifecycleEvent event) {
|
||||
String name = sites.find(event.siteId()).map(SiteView::displayName).orElse("(gone)");
|
||||
log.info("runway-demo saw site '{}' ({}) {}{}", event.siteId(), name, event.kind(),
|
||||
event.fromBackup() ? " from a backup" : "");
|
||||
if (event.wholesale()) {
|
||||
recent.remove(event.siteId());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSettingsChanged(SettingsChange change) {
|
||||
if (!change.local()) {
|
||||
return; // replayed from another node: that node already wrote the note
|
||||
}
|
||||
try {
|
||||
int count = notes.append(change.siteId(), "Per-site settings saved at " + Instant.now(),
|
||||
Note.ORIGIN_SYSTEM);
|
||||
log.info("runway-demo settings changed for site '{}': audit note appended (now {} notes)",
|
||||
change.siteId(), count);
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("runway-demo could not append the settings audit note for site '{}': {}", change.siteId(),
|
||||
e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCatalogChanged(CatalogChange change) {
|
||||
String item = switch (change.cause()) {
|
||||
case PAGE, CONTENT -> (change.sourceKey() == null ? "?" : change.sourceKey()) + ":"
|
||||
+ (change.id() == null ? "*" : change.id());
|
||||
case SETTINGS -> change.pluginId() == null ? "" : change.pluginId();
|
||||
default -> ""; // SITE, and any cause a later SPI adds
|
||||
};
|
||||
Entry entry = new Entry(Instant.now(), change.cause().name().toLowerCase(Locale.ROOT), item,
|
||||
paths(change.previousUrls()), paths(change.currentUrls()), change.local());
|
||||
Deque<Entry> entries = recent.computeIfAbsent(change.siteId(), id -> new ArrayDeque<>());
|
||||
synchronized (entries) {
|
||||
entries.addFirst(entry);
|
||||
while (entries.size() > KEEP) {
|
||||
entries.removeLast();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The site's recent changes, newest first. */
|
||||
public List<Entry> recent(String siteId) {
|
||||
Deque<Entry> entries = recent.get(siteId);
|
||||
if (entries == null) {
|
||||
return List.of();
|
||||
}
|
||||
synchronized (entries) {
|
||||
return List.copyOf(entries);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> paths(List<LocalizedUrl> urls) {
|
||||
return urls.stream().map(LocalizedUrl::path).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import java.util.List;
|
||||
import mx.quest.runway.spi.RunwaySpi;
|
||||
import mx.quest.runway.spi.model.PluginInfo;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.SitePages;
|
||||
import mx.quest.runway.spi.service.Sites;
|
||||
|
||||
/**
|
||||
* Backs the plugin's console fragments — the dashboard card ({@code templates/dashboard.*}) and the admin fragment
|
||||
* under the settings form ({@code templates/admin.*}). The host does not push data into a fragment; the fragment's
|
||||
* decoupled logic reads this bean by name, {@code ${@runwayDemoAdminModel.noteCount(tenantSiteId)}}, with
|
||||
* {@code tenantSiteId} supplied by the console (and {@code null} on the application console, so every accessor is
|
||||
* null-safe and a fragment never errors).
|
||||
*
|
||||
* <p>What a fragment may rely on is a contract: the variables {@code tenantSiteId} and {@code _csrf}, the expressions
|
||||
* {@code ${@<own bean>…}} and {@code ${@authz.may('…')}}, and {@code #{…}} messages. Nothing else in the console's
|
||||
* model is promised — so anything else a fragment shows comes from a bean like this one.
|
||||
*
|
||||
* <p>It shows three services in their read-only roles: {@link Sites} (a site's view from its id, off-request — the
|
||||
* fragment only has the id), {@link SitePages#pathOf} (where "our" starter page lives now, whatever its state, even
|
||||
* after an operator moved it) and {@link PluginSettings#secret} (whether a per-site secret is set — answered without
|
||||
* ever exposing the value). {@link PluginInfo} is this plugin's identity.
|
||||
*/
|
||||
public class DemoAdminModel {
|
||||
|
||||
private static final int RECENT = 5;
|
||||
|
||||
private final DemoNotesStore notes;
|
||||
private final DemoAppProps props;
|
||||
private final PluginSettings settings;
|
||||
private final Sites sites;
|
||||
private final SitePages pages;
|
||||
private final PluginInfo self;
|
||||
|
||||
public DemoAdminModel(DemoNotesStore notes, DemoAppProps props, PluginSettings settings, Sites sites,
|
||||
SitePages pages, PluginInfo self) {
|
||||
this.notes = notes;
|
||||
this.props = props;
|
||||
this.settings = settings;
|
||||
this.sites = sites;
|
||||
this.pages = pages;
|
||||
this.self = self;
|
||||
}
|
||||
|
||||
private static boolean noSite(String siteId) {
|
||||
return siteId == null || siteId.isBlank();
|
||||
}
|
||||
|
||||
public int noteCount(String siteId) {
|
||||
return noSite(siteId) ? 0 : notes.count(siteId);
|
||||
}
|
||||
|
||||
/** The newest notes, newest first, for the admin fragment's list. */
|
||||
public List<Note> recentNotes(String siteId) {
|
||||
return noSite(siteId) ? List.of() : notes.recent(siteId, RECENT);
|
||||
}
|
||||
|
||||
/** The site's display name, from {@link Sites#find}; the id itself when the site is unknown. */
|
||||
public String siteName(String siteId) {
|
||||
return noSite(siteId) ? "" : sites.find(siteId).map(SiteView::displayName).orElse(siteId);
|
||||
}
|
||||
|
||||
/** Where the demo's starter page lives now (any state), or {@code ""} when it is not installed. */
|
||||
public String demoPagePath(String siteId) {
|
||||
return noSite(siteId) ? "" : pages.pathOf(siteId, DemoConsoleController.STARTER_SLUG).orElse("");
|
||||
}
|
||||
|
||||
/** Whether the per-site {@code analytics.site-token} secret is set; the value itself never leaves the plugin. */
|
||||
public boolean siteTokenConfigured(String siteId) {
|
||||
return !noSite(siteId) && settings.secret(siteId, "analytics.site-token").isPresent();
|
||||
}
|
||||
|
||||
/** This plugin's version, from {@code plugin.yml} (via {@link PluginInfo}). */
|
||||
public String pluginVersion() {
|
||||
return self.version();
|
||||
}
|
||||
|
||||
/** The SPI version this plugin was compiled against (a constant the compiler inlined). */
|
||||
public String builtSpi() {
|
||||
return RunwaySpi.VERSION;
|
||||
}
|
||||
|
||||
/** The SPI version of the kernel this plugin is running on. */
|
||||
public String runningSpi() {
|
||||
return RunwaySpi.runtimeVersion();
|
||||
}
|
||||
|
||||
public boolean bannerEnabled() {
|
||||
return props.getBanner().isEnabled();
|
||||
}
|
||||
|
||||
public boolean analyticsKeyConfigured() {
|
||||
return props.getAnalytics().hasKey();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import java.util.List;
|
||||
import mx.quest.runway.spi.HeadContributor;
|
||||
import mx.quest.runway.spi.RunwaySpi;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
import mx.quest.runway.spi.model.SettingsView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* {@code HeadContributor} — splices markup into every page's {@code <head>} at the response edge, so it lands on every
|
||||
* page without any edit to a tenant's templates. Ordered {@code @Order(200)} in {@link DemoPluginConfig}, after the
|
||||
* kernel's own SEO ({@code @Order(100)}) and icon ({@code @Order(90)}) contributors.
|
||||
*
|
||||
* <p>Emits an escaped {@code <meta name="generator">} from the app-level {@code generator.label} setting, the plugin's
|
||||
* stylesheet while the per-site notice is enabled, and — only when the per-site {@code analytics.enabled} flag is on
|
||||
* and the app-level {@code analytics.write-key} secret is set — an inert analytics {@code <script>} (plain
|
||||
* {@code <script src>}: the kernel stamps the CSP nonce on it). Returns {@code ""}, never {@code null}, when it has
|
||||
* nothing to add.
|
||||
*
|
||||
* <p><b>{@code PluginSettings}</b> is how a plugin reads its own per-site settings: {@code site(siteId)} returns a
|
||||
* {@link SettingsView} with the {@code siteSettings:} defaults already applied and the saved values over them, so the
|
||||
* code fallback only matters for undeclared keys. It is bound to this plugin by the jar it was injected into.
|
||||
*/
|
||||
public class DemoAnalyticsHead implements HeadContributor {
|
||||
|
||||
private final DemoAppProps props;
|
||||
private final PluginSettings settings;
|
||||
|
||||
public DemoAnalyticsHead(DemoAppProps props, PluginSettings settings) {
|
||||
this.props = props;
|
||||
this.settings = settings;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "runway-demo/analytics";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String render(HeadContext ctx) {
|
||||
SettingsView site = settings.site(ctx.site().id());
|
||||
StringBuilder out = new StringBuilder();
|
||||
// A provenance comment: the SPI this plugin was built against (a constant), and an input the host hands in.
|
||||
out.append("\n<!-- runway-demo ").append(Html.escape(RunwaySpi.VERSION))
|
||||
.append(ctx.noindex() ? " (noindex)" : "").append(" -->");
|
||||
out.append("\n<meta name=\"generator\" content=\"").append(Html.escape(props.getGenerator().getLabel()))
|
||||
.append("\">");
|
||||
if (site.bool("notice.enabled", true)) {
|
||||
// The plugin's own stylesheet, from its static-asset namespace, so the widgets are styled.
|
||||
out.append("\n<link rel=\"stylesheet\" href=\"/__plugin/runway-demo/static/css/demo.css\">");
|
||||
}
|
||||
if (site.bool("analytics.enabled", false) && props.getAnalytics().hasKey()) {
|
||||
// Inert placeholder — a real plugin would emit its vendor's snippet here. No key goes into the page.
|
||||
out.append("\n<script data-demo-analytics=\"1\" src=\"/__plugin/runway-demo/static/js/demo-analytics.js\"")
|
||||
.append(" data-site=\"").append(Html.escape(ctx.site().id())).append("\" defer></script>");
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("head.per-locale");
|
||||
}
|
||||
|
||||
/**
|
||||
* This contributor's whole per-site input: its own settings file. Head markup is spliced in after a page's
|
||||
* {@code ETag} has been computed, so the host folds the files listed here into the validator — without it, a
|
||||
* settings change would alter the delivered page but not its {@code ETag}, and clients would keep the old head.
|
||||
*/
|
||||
@Override
|
||||
public List<String> headInputs(String siteId) {
|
||||
return List.of("plugins/runway-demo.yml");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
||||
|
||||
/**
|
||||
* The demo's <b>app-level</b> settings, bound from {@code external/plugin-settings/runway-demo.yml} (keys under
|
||||
* {@code runway.plugin.runway-demo.*}) — the plugin.yml {@code settings:} schema. App-level settings are PLATFORM
|
||||
* concerns and apply on <b>restart</b>; a plugin reads them through its own Spring {@code @ConfigurationProperties}
|
||||
* binding (descriptor contract), never through host machinery. Field defaults mirror the schema defaults so the
|
||||
* plugin behaves sensibly when the file is absent.
|
||||
*
|
||||
* <p>Registered by the {@code @Bean @ConfigurationProperties("runway.plugin.runway-demo")} method
|
||||
* {@code DemoPluginConfig#runwayDemoAppProps}, <b>not</b> by {@code @EnableConfigurationProperties}: that annotation
|
||||
* names the bean {@code "<prefix>-<class name>"}, which breaks the kernel's rule that every plugin bean name starts
|
||||
* with the plugin id ({@code runwayDemo…}).
|
||||
*
|
||||
* <p>The {@code analytics.write-key} is a {@code secret}-typed <i>app-level</i> setting: in the property map it is the
|
||||
* {@code ENC(...)} ciphertext the host stores, so this demo uses it as presence only. (A <i>per-site</i> secret is
|
||||
* read in clear with {@code PluginSettings.secret} — see {@link DemoAdminModel#siteTokenConfigured}.)
|
||||
*/
|
||||
public class DemoAppProps {
|
||||
|
||||
@NestedConfigurationProperty
|
||||
private final Banner banner = new Banner();
|
||||
@NestedConfigurationProperty
|
||||
private final Cache cache = new Cache();
|
||||
@NestedConfigurationProperty
|
||||
private final Generator generator = new Generator();
|
||||
@NestedConfigurationProperty
|
||||
private final Analytics analytics = new Analytics();
|
||||
|
||||
public Banner getBanner() {
|
||||
return banner;
|
||||
}
|
||||
|
||||
public Cache getCache() {
|
||||
return cache;
|
||||
}
|
||||
|
||||
public Generator getGenerator() {
|
||||
return generator;
|
||||
}
|
||||
|
||||
public Analytics getAnalytics() {
|
||||
return analytics;
|
||||
}
|
||||
|
||||
/** {@code banner.enabled} / {@code banner.text} — a site-wide chrome banner (text is verbatim/multi-line). */
|
||||
public static class Banner {
|
||||
private boolean enabled = true;
|
||||
private String text = "";
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = (text == null) ? "" : text;
|
||||
}
|
||||
}
|
||||
|
||||
/** {@code cache.max-entries} — a platform tuning knob (int, range-checked by the console form). */
|
||||
public static class Cache {
|
||||
private int maxEntries = 500;
|
||||
|
||||
public int getMaxEntries() {
|
||||
return maxEntries;
|
||||
}
|
||||
|
||||
public void setMaxEntries(int maxEntries) {
|
||||
this.maxEntries = maxEntries;
|
||||
}
|
||||
}
|
||||
|
||||
/** {@code generator.label} — the value emitted in the {@code <meta name="generator">} head tag. */
|
||||
public static class Generator {
|
||||
private String label = "Runway Demo";
|
||||
|
||||
public String getLabel() {
|
||||
return label;
|
||||
}
|
||||
|
||||
public void setLabel(String label) {
|
||||
this.label = (label == null || label.isBlank()) ? "Runway Demo" : label;
|
||||
}
|
||||
}
|
||||
|
||||
/** {@code analytics.write-key} — a {@code secret}; opaque ENC(...) ciphertext in the property map. */
|
||||
public static class Analytics {
|
||||
private String writeKey = "";
|
||||
|
||||
public String getWriteKey() {
|
||||
return writeKey;
|
||||
}
|
||||
|
||||
public void setWriteKey(String writeKey) {
|
||||
this.writeKey = (writeKey == null) ? "" : writeKey;
|
||||
}
|
||||
|
||||
public boolean hasKey() {
|
||||
return !writeKey.isBlank();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import mx.quest.runway.spi.RunwaySpi;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.InstallResult;
|
||||
import mx.quest.runway.spi.model.PluginInfo;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.model.StarterPage;
|
||||
import mx.quest.runway.spi.service.AccessCheck;
|
||||
import mx.quest.runway.spi.service.ConsoleScreen;
|
||||
import mx.quest.runway.spi.service.ContentCatalogView;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.RequestContext;
|
||||
import mx.quest.runway.spi.service.SitePages;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* The demo's own screen inside the tenant console, {@value #BASE} — a {@code @Controller} annotated
|
||||
* {@link ConsoleScreen}. <b>When to use {@code @ConsoleScreen}:</b> whenever a plugin needs more than the settings form
|
||||
* and the admin fragment below it — a list to manage, an action to run. The kernel fills the console shell (topbar,
|
||||
* menus, language switcher, footer) for every request this class handles, so the plugin needs no
|
||||
* {@code @ControllerAdvice} and no host class. A handler sets {@link ConsoleScreen#CONTENT_TEMPLATE} and
|
||||
* {@link ConsoleScreen#PAGE_TITLE_KEY} and returns {@link ConsoleScreen#LAYOUT_VIEW}.
|
||||
*
|
||||
* <p><b>The rules this class follows:</b>
|
||||
* <ul>
|
||||
* <li>Every mapping lies under {@code /__admin/runway-demo} (the kernel refuses a plugin controller elsewhere), so
|
||||
* the tenant console's sign-in, realm security and CSRF protection apply unchanged.</li>
|
||||
* <li>Every handler is gated with {@code @PreAuthorize("@authz.may('runway-demo|manage-notes')")} — the
|
||||
* {@link AccessCheck} bean under its expression name. The menu entry's {@code permission:} only hides the
|
||||
* link.</li>
|
||||
* <li>Everything that <b>changes state is a {@code POST}</b> from a form carrying the console's CSRF token
|
||||
* ({@code ${_csrf}}); the {@code GET} only reads, so a link or an {@code <img>} on another web site can never
|
||||
* trigger an action through a signed-in operator's browser. Each {@code POST} redirects back (post/redirect/get)
|
||||
* with a flash message, so a reload never repeats it. Spring MVC binds the form fields, so no SPI type is
|
||||
* needed to read them.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>It is also where four services are used in their natural place:
|
||||
* <ul>
|
||||
* <li>{@link RequestContext#site()} — <b>which site this console request manages</b>. A console screen has no
|
||||
* {@code RouteRequest}; this is how it learns the tenancy. It is empty on the application console
|
||||
* ({@code /__app}), which this screen does not serve (404).</li>
|
||||
* <li>{@link Messages#console} — console text in the <b>operator's</b> UI language (the flash messages), as opposed
|
||||
* to {@link Messages#site}, which is for what a site's visitors read.</li>
|
||||
* <li>{@link SitePages#install} — "install my starter page" through the site's editorial rules: never overwrites,
|
||||
* never publishes around an Enforced or Reviewed site, and reports one of four outcomes the operator is told in
|
||||
* words. The plugin checks the caller may edit pages first ({@link AccessCheck#may} with the kernel permission
|
||||
* {@code EDIT_PAGES}).</li>
|
||||
* <li>{@link ContentCatalogView} — <b>the site's published content surface</b> with the URLs the host computed:
|
||||
* {@code entries} (what a sitemap or search index lists), {@code pageAt} (which published page owns a path),
|
||||
* {@code servablePath} (may content live at a path at all) and {@code refresh} (a manual reindex).</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Controller
|
||||
@ConsoleScreen
|
||||
@RequestMapping(DemoConsoleController.BASE)
|
||||
public class DemoConsoleController {
|
||||
|
||||
static final String BASE = "/__admin/runway-demo";
|
||||
static final String GATE = "@authz.may('runway-demo|manage-notes')";
|
||||
static final String CONTENT = "__plugin__/runway-demo/console";
|
||||
static final String TITLE_KEY = "runwaydemo.console.title";
|
||||
/** The starter page's slug and path. */
|
||||
static final String STARTER_SLUG = "runway-demo";
|
||||
static final String STARTER_PATH = "/demo";
|
||||
/** The flash attributes this screen renders itself (the shell's own flash region is not promised to plugins). */
|
||||
static final String FLASH = "runwayDemoFlash";
|
||||
static final String FLASH_ERROR = "runwayDemoError";
|
||||
/** The most catalog rows the screen lists. */
|
||||
static final int CATALOG_ROWS = 50;
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(DemoConsoleController.class);
|
||||
|
||||
/** One row of the content-surface table. */
|
||||
public record CatalogRow(String source, String id, String path, boolean own) {
|
||||
}
|
||||
|
||||
/** The answer of the path check: servable at all, and the published page that owns it, if any. */
|
||||
public record PathCheck(String path, boolean safe, boolean servable, String ownerSlug) {
|
||||
}
|
||||
|
||||
/** Everything the screen shows, built per request. */
|
||||
public record Screen(SiteView site, String pluginVersion, String builtSpi, String runningSpi,
|
||||
int noteCount, List<Note> notes, String showcaseText, String showcasePath,
|
||||
String starterPath, int catalogTotal, List<CatalogRow> catalog,
|
||||
List<DemoActivity.Entry> activity, PathCheck pathCheck) {
|
||||
}
|
||||
|
||||
private final RequestContext request;
|
||||
private final AccessCheck access;
|
||||
private final Messages messages;
|
||||
private final SitePages pages;
|
||||
private final ContentCatalogView catalog;
|
||||
private final DemoNotesStore notes;
|
||||
private final DemoShowcaseStore showcase;
|
||||
private final DemoActivity activity;
|
||||
private final PluginInfo self;
|
||||
|
||||
public DemoConsoleController(RequestContext request, AccessCheck access, Messages messages, SitePages pages,
|
||||
ContentCatalogView catalog, DemoNotesStore notes, DemoShowcaseStore showcase,
|
||||
DemoActivity activity, PluginInfo self) {
|
||||
this.request = request;
|
||||
this.access = access;
|
||||
this.messages = messages;
|
||||
this.pages = pages;
|
||||
this.catalog = catalog;
|
||||
this.notes = notes;
|
||||
this.showcase = showcase;
|
||||
this.activity = activity;
|
||||
this.self = self;
|
||||
}
|
||||
|
||||
/** The screen. Read-only: it changes nothing, so it is a {@code GET}. {@code ?path=} runs the path check. */
|
||||
@GetMapping
|
||||
@PreAuthorize(GATE)
|
||||
public String screen(@RequestParam(name = "path", required = false) String path, Model model) {
|
||||
SiteView site = boundSite();
|
||||
String siteId = site.id();
|
||||
List<CatalogEntry> entries = catalog.entries(siteId);
|
||||
List<CatalogRow> rows = new ArrayList<>();
|
||||
for (CatalogEntry entry : entries.subList(0, Math.min(CATALOG_ROWS, entries.size()))) {
|
||||
rows.add(new CatalogRow(entry.sourceKey(), entry.ref().id(), entry.pathFor(site.defaultLocale()),
|
||||
DemoShowcaseSource.SOURCE_KEY.equals(entry.sourceKey())));
|
||||
}
|
||||
Optional<Showcase> current = showcase.current(siteId);
|
||||
model.addAttribute("rd", new Screen(site, self.version(), RunwaySpi.VERSION,
|
||||
RunwaySpi.runtimeVersion(), notes.count(siteId), notes.recent(siteId, 10),
|
||||
current.map(Showcase::text).orElse(null), DemoShowcaseSource.PATH,
|
||||
pages.pathOf(siteId, STARTER_SLUG).orElse(""), entries.size(), rows, activity.recent(siteId),
|
||||
path == null || path.isBlank() ? null : check(site, path.strip())));
|
||||
model.addAttribute(ConsoleScreen.CONTENT_TEMPLATE, CONTENT);
|
||||
model.addAttribute(ConsoleScreen.PAGE_TITLE_KEY, TITLE_KEY);
|
||||
return ConsoleScreen.LAYOUT_VIEW;
|
||||
}
|
||||
|
||||
private PathCheck check(SiteView site, String path) {
|
||||
try {
|
||||
boolean servable = catalog.servablePath(site.id(), path);
|
||||
String owner = catalog.pageAt(site.id(), path, site.defaultLocale()).orElse(null);
|
||||
return new PathCheck(path, true, servable, owner);
|
||||
} catch (IllegalArgumentException unsafe) {
|
||||
return new PathCheck(path, false, false, null);
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds an operator note (a field of the form body). */
|
||||
@PostMapping("/notes")
|
||||
@PreAuthorize(GATE)
|
||||
public String addNote(@RequestParam(name = "text", defaultValue = "") String text, RedirectAttributes flash) {
|
||||
String siteId = boundSite().id();
|
||||
if (text.isBlank()) {
|
||||
return back(flash, FLASH_ERROR, console("runwaydemo.console.note.blank", "Write something first."));
|
||||
}
|
||||
try {
|
||||
notes.append(siteId, text, Note.ORIGIN_CONSOLE);
|
||||
} catch (UncheckedIOException e) {
|
||||
log.warn("runway-demo could not add a note for site {}: {}", siteId, e.toString());
|
||||
return back(flash, FLASH_ERROR, console("runwaydemo.console.ioError", "The change could not be saved."));
|
||||
}
|
||||
return back(flash, FLASH, console("runwaydemo.console.note.added", "Note added."));
|
||||
}
|
||||
|
||||
/** Publishes the showcase page; the store announces the change with {@code ContentChanges}. */
|
||||
@PostMapping("/showcase")
|
||||
@PreAuthorize(GATE)
|
||||
public String publishShowcase(@RequestParam(name = "text", defaultValue = "") String text,
|
||||
RedirectAttributes flash) {
|
||||
String siteId = boundSite().id();
|
||||
if (text.isBlank()) {
|
||||
return back(flash, FLASH_ERROR, console("runwaydemo.console.showcase.blank", "Write something first."));
|
||||
}
|
||||
try {
|
||||
showcase.publish(siteId, text);
|
||||
} catch (UncheckedIOException e) {
|
||||
log.warn("runway-demo could not publish the showcase of site {}: {}", siteId, e.toString());
|
||||
return back(flash, FLASH_ERROR, console("runwaydemo.console.ioError", "The change could not be saved."));
|
||||
}
|
||||
return back(flash, FLASH, console("runwaydemo.console.showcase.published", "Showcase published at {0}.",
|
||||
DemoShowcaseSource.PATH));
|
||||
}
|
||||
|
||||
/** Unpublishes the showcase page; announced like a publish. */
|
||||
@PostMapping("/showcase/unpublish")
|
||||
@PreAuthorize(GATE)
|
||||
public String unpublishShowcase(RedirectAttributes flash) {
|
||||
String siteId = boundSite().id();
|
||||
boolean was;
|
||||
try {
|
||||
was = showcase.unpublish(siteId);
|
||||
} catch (UncheckedIOException e) {
|
||||
log.warn("runway-demo could not unpublish the showcase of site {}: {}", siteId, e.toString());
|
||||
return back(flash, FLASH_ERROR, console("runwaydemo.console.ioError", "The change could not be saved."));
|
||||
}
|
||||
return was
|
||||
? back(flash, FLASH, console("runwaydemo.console.showcase.unpublished", "Showcase unpublished."))
|
||||
: back(flash, FLASH, console("runwaydemo.console.showcase.none", "No showcase was published."));
|
||||
}
|
||||
|
||||
/** Installs the starter page carrying the demo's two widgets, through the site's editorial rules. */
|
||||
@PostMapping("/install-page")
|
||||
@PreAuthorize(GATE)
|
||||
public String installPage(RedirectAttributes flash) {
|
||||
SiteView site = boundSite();
|
||||
if (!access.may("EDIT_PAGES")) {
|
||||
return back(flash, FLASH_ERROR, console("runwaydemo.console.page.forbidden",
|
||||
"Installing a page needs the permission to edit pages."));
|
||||
}
|
||||
String title = messages.site(site.id(), site.defaultLocale(), "runwaydemo.page.title", "Runway demo");
|
||||
StarterPage page = new StarterPage(STARTER_SLUG, STARTER_PATH,
|
||||
Map.of(site.defaultLocale().getLanguage(), title), starterHtml(title), starterLogic(), true);
|
||||
InstallResult result;
|
||||
try {
|
||||
result = pages.install(site.id(), page);
|
||||
} catch (RuntimeException e) {
|
||||
// IllegalStateException: another page serves the path, the master is missing, a write failed (no stray
|
||||
// draft is left behind). IllegalArgumentException would mean our own slug/path is unsafe — a bug here.
|
||||
log.warn("runway-demo starter page install failed for site {}: {}", site.id(), e.toString());
|
||||
return back(flash, FLASH_ERROR, console("runwaydemo.console.page.failed",
|
||||
"The demo page could not be installed."));
|
||||
}
|
||||
return back(flash, FLASH, describe(result));
|
||||
}
|
||||
|
||||
/** Drops the site's cached content listing — the "reindex" button; ordinary changes never need it. */
|
||||
@PostMapping("/catalog/refresh")
|
||||
@PreAuthorize(GATE)
|
||||
public String refreshCatalog(RedirectAttributes flash) {
|
||||
catalog.refresh(boundSite().id());
|
||||
return back(flash, FLASH, console("runwaydemo.console.catalog.refreshed", "Content listing refreshed."));
|
||||
}
|
||||
|
||||
/** The operator's words for each install outcome; an outcome added in a later SPI MINOR gets a neutral line. */
|
||||
String describe(InstallResult result) {
|
||||
String path = result.path();
|
||||
return switch (result.outcome()) {
|
||||
case PUBLISHED -> console("runwaydemo.console.page.published", "Demo page published at {0}.", path);
|
||||
case PENDING_REVIEW -> console("runwaydemo.console.page.pending",
|
||||
"Demo page created at {0} and waiting in the review queue.", path);
|
||||
case DRAFT_BLOCKED -> {
|
||||
StringBuilder text = new StringBuilder(console("runwaydemo.console.page.blocked",
|
||||
"Demo page created at {0} as a draft: the quality checks blocked publishing.", path));
|
||||
for (Finding finding : result.blocking()) {
|
||||
text.append(' ').append(finding.code()).append(": ").append(finding.message());
|
||||
}
|
||||
yield text.toString();
|
||||
}
|
||||
case ALREADY_EXISTS -> console("runwaydemo.console.page.exists",
|
||||
"A demo page already exists at {0}; nothing changed.", path);
|
||||
default -> console("runwaydemo.console.page.other", "Demo page install finished: {0} {1}",
|
||||
result.outcome(), path);
|
||||
};
|
||||
}
|
||||
|
||||
/** The site this console request manages; 404 when there is none (the application console). */
|
||||
private SiteView boundSite() {
|
||||
return request.site().orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
|
||||
}
|
||||
|
||||
private String console(String code, String fallback, Object... args) {
|
||||
return messages.console(code, fallback, args);
|
||||
}
|
||||
|
||||
private static String back(RedirectAttributes flash, String kind, String text) {
|
||||
flash.addFlashAttribute(kind, text);
|
||||
return "redirect:" + BASE;
|
||||
}
|
||||
|
||||
/**
|
||||
* The starter page: the master's chrome seams, a heading, and the two widget anchors (an {@code id} and a
|
||||
* {@code data-widget} on one element each). An {@code <h1>} keeps the page clear of the demo's own quality check.
|
||||
*/
|
||||
static String starterHtml(String title) {
|
||||
String t = Html.escape(title);
|
||||
return "<!DOCTYPE html>\n<html>\n<head><title>" + t + "</title></head>\n<body>\n"
|
||||
+ "<header id=\"site-header\"></header>\n<main id=\"content\">\n"
|
||||
+ " <h1 id=\"demo-page-title\">" + t + "</h1>\n"
|
||||
+ " <div id=\"demo-notice\" data-widget=\"demo-notice/page\"></div>\n"
|
||||
+ " <div id=\"demo-feedback\" data-widget=\"demo-feedback/page\"></div>\n"
|
||||
+ "</main>\n<footer id=\"site-footer\"></footer>\n</body>\n</html>\n";
|
||||
}
|
||||
|
||||
/** The starter page's decoupled logic: the master's chrome by the {@code ${master}} variable, never a literal. */
|
||||
static String starterLogic() {
|
||||
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<thlogic>\n"
|
||||
+ " <attr sel=\"head\" th:replace=\"~{${master} :: head}\"/>\n"
|
||||
+ " <attr sel=\"#site-header\" th:replace=\"~{${master} :: #site-header}\"/>\n"
|
||||
+ " <attr sel=\"#site-footer\" th:replace=\"~{${master} :: #site-footer}\"/>\n"
|
||||
+ " <attr sel=\"#demo-page-title\" th:text=\"${pageTitle}\"/>\n"
|
||||
+ "</thlogic>\n";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.LongSupplier;
|
||||
import mx.quest.runway.spi.EndpointContributor;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import mx.quest.runway.spi.model.Route;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.SurfacePosture;
|
||||
import mx.quest.runway.spi.service.AccessCheck;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/**
|
||||
* {@code EndpointContributor} — plugin HTTP routes on a site's public host, without touching a servlet. The frozen
|
||||
* {@link RouteRequest} carries the resolved site, the negotiated locale, the query, the form body, lowercase headers,
|
||||
* the gated client IP and the request origin; each route declares a {@link SurfacePosture}. Routes are exact paths
|
||||
* on the tenant realm and must avoid the reserved kernel prefixes ({@code /__…}, {@code /login}, …).
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code GET /demo/hello.txt} — public, {@code discoverable()}: a greeting localized with
|
||||
* {@link Messages#site} in the request's negotiated locale.</li>
|
||||
* <li>{@code GET /demo/echo.json} — public: echoes what the host put in the {@code RouteRequest}.</li>
|
||||
* <li>{@code GET /demo/notes.json} — <b>permission-gated</b> with {@link AccessCheck}: only a signed-in user holding
|
||||
* {@code runway-demo|manage-notes} gets the notes; anyone else gets {@code 403}. <b>When to use
|
||||
* {@code AccessCheck}:</b> every time your code must decide whether the current user may do something — the
|
||||
* menu and dashboard-card {@code permission:} keys only hide UI. It is fail-closed (no request, no principal,
|
||||
* an undeclared key → {@code false}) and is the same bean as {@code @authz} in {@code @PreAuthorize} and
|
||||
* templates.</li>
|
||||
* <li>{@code POST /demo/feedback} — an <b>anonymous form route</b> ({@link Route#anonymousPost}): the public
|
||||
* feedback form of {@link DemoFeedbackWidget} posts here with <b>no CSRF token</b>. <b>When to use the
|
||||
* anonymous flag:</b> only for a form any visitor may submit with no account, placed on a page every visitor
|
||||
* shares, which therefore cannot carry a per-session token (a contact form, a newsletter sign-up). The kernel
|
||||
* exempts exactly this method and path from CSRF and makes that safe by running the handler with <b>no
|
||||
* principal</b> ({@code AccessCheck.may} is {@code false} even for a signed-in administrator) and accepting only
|
||||
* an {@code application/x-www-form-urlencoded} body. Keep your own abuse guards: here a honeypot field, a length
|
||||
* cap and a per-address rate limit keyed by {@link RouteRequest#clientIp()} (the address after the kernel's
|
||||
* trusted-proxy gate — never a header). Never use the flag for an action on something a signed-in user owns;
|
||||
* those are CSRF-checked {@code POST}s (the demo's console screen, {@link DemoConsoleController}).</li>
|
||||
* </ul>
|
||||
*/
|
||||
public class DemoEndpoints implements EndpointContributor {
|
||||
|
||||
static final String HELLO_PATH = "/demo/hello.txt";
|
||||
static final String ECHO_PATH = "/demo/echo.json";
|
||||
static final String NOTES_PATH = "/demo/notes.json";
|
||||
static final String FEEDBACK_PATH = "/demo/feedback";
|
||||
static final String PERMISSION = "runway-demo|manage-notes";
|
||||
/** Feedback messages one client address may send per {@link #WINDOW_MILLIS}. */
|
||||
static final int FEEDBACK_PER_WINDOW = 5;
|
||||
static final long WINDOW_MILLIS = TimeUnit.MINUTES.toMillis(1);
|
||||
/** Above this many tracked addresses, stale ones are swept (bounds the limiter's memory). */
|
||||
private static final int MAX_TRACKED = 10_000;
|
||||
|
||||
private final AccessCheck access;
|
||||
private final DemoNotesStore notes;
|
||||
private final Messages messages;
|
||||
private final PluginSettings settings;
|
||||
private final LongSupplier clockMillis;
|
||||
private final JsonMapper json = JsonMapper.builder().build();
|
||||
private final ConcurrentMap<String, Deque<Long>> recentFeedback = new ConcurrentHashMap<>();
|
||||
|
||||
public DemoEndpoints(AccessCheck access, DemoNotesStore notes, Messages messages, PluginSettings settings) {
|
||||
this(access, notes, messages, settings, System::currentTimeMillis);
|
||||
}
|
||||
|
||||
DemoEndpoints(AccessCheck access, DemoNotesStore notes, Messages messages, PluginSettings settings,
|
||||
LongSupplier clockMillis) {
|
||||
this.access = access;
|
||||
this.notes = notes;
|
||||
this.messages = messages;
|
||||
this.settings = settings;
|
||||
this.clockMillis = clockMillis;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "runway-demo/endpoints";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Route> routes() {
|
||||
return List.of(
|
||||
new Route("GET", HELLO_PATH, Realm.TENANT, SurfacePosture.discoverable()),
|
||||
new Route("GET", ECHO_PATH, Realm.TENANT, SurfacePosture.safeDefault()),
|
||||
new Route("GET", NOTES_PATH, Realm.TENANT, SurfacePosture.safeDefault()),
|
||||
Route.anonymousPost(FEEDBACK_PATH, SurfacePosture.safeDefault()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public RouteResponse handle(RouteRequest req) {
|
||||
// The kernel dispatches by method + path; checking the method again is the second line of defence.
|
||||
return switch (req.method().toUpperCase(Locale.ROOT) + " " + req.path()) {
|
||||
case "GET " + HELLO_PATH -> hello(req);
|
||||
case "GET " + ECHO_PATH -> echo(req);
|
||||
case "GET " + NOTES_PATH -> notes(req);
|
||||
case "POST " + FEEDBACK_PATH -> feedback(req);
|
||||
default -> RouteResponse.notFound();
|
||||
};
|
||||
}
|
||||
|
||||
private RouteResponse hello(RouteRequest req) {
|
||||
String greeting = messages.site(req.site().id(), req.locale(), "runwaydemo.hello",
|
||||
"Hello from the runway-demo plugin!") + "\n"
|
||||
+ "site: " + req.site().displayName() + " (" + req.site().id() + ")\n"
|
||||
+ "locale: " + req.locale().toLanguageTag() + "\n"
|
||||
+ "baseUrl: " + (req.site().baseUrl() == null ? "(derived)" : req.site().baseUrl()) + "\n"
|
||||
+ "origin: " + (req.origin().isEmpty() ? "(unknown)" : req.origin()) + "\n";
|
||||
return RouteResponse.text(200, greeting);
|
||||
}
|
||||
|
||||
private RouteResponse echo(RouteRequest req) {
|
||||
Map<String, Object> payload = new LinkedHashMap<>();
|
||||
payload.put("method", req.method());
|
||||
payload.put("path", req.path());
|
||||
payload.put("site", req.site().id());
|
||||
payload.put("locale", req.locale().toLanguageTag()); // negotiated: ?lang → cookie → Accept-Language → default
|
||||
payload.put("query", req.query()); // the URL query string only
|
||||
payload.put("form", req.form()); // a url-encoded body's fields (empty on a GET)
|
||||
payload.put("param.q", req.param("q").orElse(null)); // query first, then form
|
||||
payload.put("headers", req.headers()); // lowercase names; no X-Forwarded-* ever
|
||||
payload.put("clientIp", req.clientIp()); // after the trusted-proxy gate; null when unknown
|
||||
payload.put("origin", req.origin()); // scheme://host[:port]; "" when unknown
|
||||
return jsonResponse(200, payload);
|
||||
}
|
||||
|
||||
private RouteResponse notes(RouteRequest req) {
|
||||
if (!access.may(PERMISSION)) {
|
||||
return RouteResponse.text(403, "Forbidden — requires the runway-demo \"manage-notes\" permission.\n");
|
||||
}
|
||||
List<Note> siteNotes = notes.list(req.site().id());
|
||||
Map<String, Object> payload = new LinkedHashMap<>();
|
||||
payload.put("site", req.site().id());
|
||||
payload.put("count", siteNotes.size());
|
||||
payload.put("notes", siteNotes);
|
||||
return jsonResponse(200, payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a visitor's message as a note, then answers {@code 303} back to the form's page with an outcome flag
|
||||
* (never a submitted value). Fields are read from the form <b>body</b> only, so personal text never has to
|
||||
* travel in a URL. A failure to store propagates: the kernel answers {@code 500}, logs and counts it.
|
||||
*/
|
||||
private RouteResponse feedback(RouteRequest req) {
|
||||
String siteId = req.site().id();
|
||||
if (!settings.site(siteId).bool("feedback.enabled", true)) {
|
||||
return RouteResponse.notFound();
|
||||
}
|
||||
String back = safeLocalPath(formField(req, "return"));
|
||||
if (!formField(req, "website").isEmpty()) {
|
||||
return redirect(back, "thanks"); // a bot filled the honeypot: pretend success, keep nothing
|
||||
}
|
||||
String message = formField(req, "message");
|
||||
if (message.isEmpty()) {
|
||||
return redirect(back, "invalid");
|
||||
}
|
||||
if (!allow(req.clientIp())) {
|
||||
return redirect(back, "limited");
|
||||
}
|
||||
notes.append(siteId, message, Note.ORIGIN_VISITOR);
|
||||
return redirect(back, "thanks");
|
||||
}
|
||||
|
||||
/** A sliding-window limit per gated client address; an unknown address shares one bucket (fail-safe). */
|
||||
boolean allow(String clientIp) {
|
||||
long now = clockMillis.getAsLong();
|
||||
if (recentFeedback.size() > MAX_TRACKED) {
|
||||
recentFeedback.entrySet().removeIf(e -> {
|
||||
synchronized (e.getValue()) {
|
||||
return e.getValue().isEmpty() || now - e.getValue().peekLast() >= WINDOW_MILLIS;
|
||||
}
|
||||
});
|
||||
}
|
||||
Deque<Long> times = recentFeedback.computeIfAbsent(clientIp == null ? "unknown" : clientIp,
|
||||
k -> new ArrayDeque<>());
|
||||
synchronized (times) {
|
||||
while (!times.isEmpty() && now - times.peekFirst() >= WINDOW_MILLIS) {
|
||||
times.pollFirst();
|
||||
}
|
||||
if (times.size() >= FEEDBACK_PER_WINDOW) {
|
||||
return false;
|
||||
}
|
||||
times.addLast(now);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private static String formField(RouteRequest req, String name) {
|
||||
List<String> values = req.form().get(name);
|
||||
return values == null || values.isEmpty() ? "" : values.get(0).strip();
|
||||
}
|
||||
|
||||
/** A same-origin local path (one leading "/", no scheme, backslash, whitespace or control character), else "/". */
|
||||
static String safeLocalPath(String path) {
|
||||
if (path == null || !path.startsWith("/") || path.startsWith("//") || path.contains("://")) {
|
||||
return "/";
|
||||
}
|
||||
for (int i = 0; i < path.length(); i++) {
|
||||
char c = path.charAt(i);
|
||||
if (c <= 0x20 || c == '\\' || c == 0x7f) {
|
||||
return "/";
|
||||
}
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
private static RouteResponse redirect(String path, String outcome) {
|
||||
String location = path + (path.contains("?") ? "&" : "?") + DemoFeedbackWidget.OUTCOME_PARAM + "=" + outcome;
|
||||
return new RouteResponse(303, Map.of("Location", location), new byte[0]);
|
||||
}
|
||||
|
||||
private RouteResponse jsonResponse(int status, Object payload) {
|
||||
byte[] body = json.writeValueAsString(payload).getBytes(StandardCharsets.UTF_8);
|
||||
return new RouteResponse(status, Map.of("Content-Type", "application/json; charset=utf-8"), body);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("endpoint.tenant", "endpoint.json", "endpoint.anonymous-form");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import java.util.Locale;
|
||||
import mx.quest.runway.spi.ContentWidget;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.RenderFragment;
|
||||
import mx.quest.runway.spi.model.WidgetView;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* {@code ContentWidget} — a public "leave a message" form at a {@code data-widget="demo-feedback/<instance>"} anchor.
|
||||
* It posts to the demo's <b>anonymous</b> route {@code POST /demo/feedback} ({@link DemoEndpoints}), which stores the
|
||||
* message as a note and answers {@code 303} back to this page with a {@code ?demo-feedback=<outcome>} flag; the widget
|
||||
* reads that flag from {@link WidgetView#query()} and shows the outcome (post/redirect/get, so a reload never
|
||||
* resubmits).
|
||||
*
|
||||
* <p>The form carries <b>no CSRF token</b> on purpose: it sits on a page every visitor shares (and caches), and an
|
||||
* anonymous visitor has no session. That is exactly the case the anonymous-route flag exists for — see
|
||||
* {@link DemoEndpoints}. Its abuse guards are a honeypot field (hidden from people, filled by naive bots), a length
|
||||
* cap and a per-address rate limit on the server.
|
||||
*
|
||||
* <p>A widget stays a pure function of its view: it only <i>reads</i> the query; storing the message is the
|
||||
* endpoint's job. All text comes from {@link Messages#site} in the visitor's locale and is escaped here.
|
||||
*/
|
||||
public class DemoFeedbackWidget implements ContentWidget {
|
||||
|
||||
/** The query flag the endpoint redirects back with. */
|
||||
static final String OUTCOME_PARAM = "demo-feedback";
|
||||
|
||||
private final PluginSettings settings;
|
||||
private final Messages messages;
|
||||
|
||||
public DemoFeedbackWidget(PluginSettings settings, Messages messages) {
|
||||
this.settings = settings;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "demo-feedback";
|
||||
}
|
||||
|
||||
@Override
|
||||
public RenderFragment render(WidgetView view) {
|
||||
String siteId = view.site().id();
|
||||
if (!settings.site(siteId).bool("feedback.enabled", true)) {
|
||||
return RenderFragment.empty();
|
||||
}
|
||||
Locale locale = view.locale();
|
||||
String fieldId = "rw-demo-feedback-" + view.instanceId().replaceAll("[^A-Za-z0-9_-]", "-");
|
||||
String back = view.path().isBlank() ? "/" : view.path();
|
||||
StringBuilder html = new StringBuilder()
|
||||
.append("<link rel=\"stylesheet\" href=\"/__plugin/runway-demo/static/css/demo.css\">")
|
||||
.append("<div class=\"rw-demo-feedback\">");
|
||||
String outcome = outcomeText(siteId, locale, view.query().get(OUTCOME_PARAM));
|
||||
if (!outcome.isEmpty()) {
|
||||
html.append("<p class=\"rw-demo-notice rw-demo-notice-info\" role=\"status\">")
|
||||
.append(Html.escape(outcome)).append("</p>");
|
||||
}
|
||||
html.append("<form method=\"post\" action=\"").append(DemoEndpoints.FEEDBACK_PATH).append("\">")
|
||||
.append("<input type=\"hidden\" name=\"return\" value=\"").append(Html.escape(back)).append("\">")
|
||||
.append("<label for=\"").append(fieldId).append("\">")
|
||||
.append(Html.escape(text(siteId, locale, "runwaydemo.feedback.label", "Leave a message")))
|
||||
.append("</label>")
|
||||
.append("<textarea id=\"").append(fieldId).append("\" name=\"message\" rows=\"3\" maxlength=\"")
|
||||
.append(DemoNotesStore.MAX_TEXT).append("\" required></textarea>")
|
||||
// The honeypot: off-screen for people and assistive technology, tempting for a form-filling bot.
|
||||
.append("<div class=\"rw-demo-hp\" aria-hidden=\"true\"><label>Website <input type=\"text\" ")
|
||||
.append("name=\"website\" tabindex=\"-1\" autocomplete=\"off\"></label></div>")
|
||||
.append("<button type=\"submit\">")
|
||||
.append(Html.escape(text(siteId, locale, "runwaydemo.feedback.send", "Send")))
|
||||
.append("</button></form></div>");
|
||||
return RenderFragment.of(html.toString());
|
||||
}
|
||||
|
||||
private String outcomeText(String siteId, Locale locale, String outcome) {
|
||||
if (outcome == null) {
|
||||
return "";
|
||||
}
|
||||
return switch (outcome) {
|
||||
case "thanks" -> text(siteId, locale, "runwaydemo.feedback.thanks", "Thank you — your message was kept.");
|
||||
case "invalid" -> text(siteId, locale, "runwaydemo.feedback.invalid", "Please write a message first.");
|
||||
case "limited" -> text(siteId, locale, "runwaydemo.feedback.limited",
|
||||
"Too many messages from your address — please try again in a minute.");
|
||||
default -> "";
|
||||
};
|
||||
}
|
||||
|
||||
private String text(String siteId, Locale locale, String code, String fallback) {
|
||||
return messages.site(siteId, locale, code, fallback);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("widget.form");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import mx.quest.runway.spi.RunwaySpi;
|
||||
import mx.quest.runway.spi.model.PluginInfo;
|
||||
import mx.quest.runway.spi.service.PluginLifecycle;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* {@code PluginLifecycle} — the optional start/stop hook. <b>When to use it:</b> to run code once the platform is up
|
||||
* (warm a cache, open an index, start your own executor) or when it shuts down (close what you opened). A plugin that
|
||||
* only contributes beans needs none.
|
||||
*
|
||||
* <p>The host collects every {@code PluginLifecycle} bean by type and matches it to its plugin by the jar its class was
|
||||
* loaded from — there is no {@code id()} to keep in sync with {@code plugin.yml}. {@link #started} runs once, after
|
||||
* every singleton exists, in plugin load order; {@link #stopping} runs at shutdown in reverse order, only if
|
||||
* {@code started} returned normally. Both block the host's startup/shutdown thread, so keep them short; a throw is
|
||||
* logged and counted on the plugins screen and the platform keeps booting.
|
||||
*
|
||||
* <p>{@link PluginInfo} is this plugin's own identity — its id, the version from {@code plugin.yml} and its install
|
||||
* folder. It arrives here and can also be injected into any bean.
|
||||
*
|
||||
* <p>{@link RunwaySpi#VERSION} is a compile-time constant, so in plugin code it is the SPI version the plugin was
|
||||
* <b>built against</b>; {@link RunwaySpi#runtimeVersion()} is the SPI of the kernel it is <b>running on</b>.
|
||||
*/
|
||||
public class DemoLifecycle implements PluginLifecycle {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(DemoLifecycle.class);
|
||||
|
||||
private volatile PluginInfo self;
|
||||
|
||||
@Override
|
||||
public void started(PluginInfo self) {
|
||||
this.self = self;
|
||||
log.info("{} {} started — install dir {}; built against SPI {}, running on SPI {}", self.id(),
|
||||
self.version(), self.installDir(), RunwaySpi.VERSION, RunwaySpi.runtimeVersion());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopping() {
|
||||
PluginInfo info = self;
|
||||
log.info("{} stopping", info == null ? "runway-demo" : info.id());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import mx.quest.runway.spi.PageQualityCheck;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.PageView;
|
||||
import mx.quest.runway.spi.model.SettingsView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* {@code PageQualityCheck} — read-only SEO checks over a page as it would render. Tuned per site through
|
||||
* {@link PluginSettings}: {@code quality.title-warn-ratio} (a {@code decimal}) scales the 60-character title threshold;
|
||||
* {@code quality.ignore-codes} (a {@code list}) suppresses finding codes. Returns an empty list (never {@code null})
|
||||
* for a clean page.
|
||||
*
|
||||
* <p>Severity is a decision with consequences: on a site set to <i>Enforced</i> or <i>Reviewed</i> any {@code ERROR}
|
||||
* refuses publishing. This demo's {@code h1.missing} is an {@code ERROR} on purpose, to show that path; a real plugin
|
||||
* keeps {@code ERROR} for something clearly broken and uses {@code WARNING} for advice.
|
||||
*/
|
||||
public class DemoMetaLengthCheck implements PageQualityCheck {
|
||||
|
||||
private static final int BASE_TITLE_LIMIT = 60;
|
||||
|
||||
private final PluginSettings settings;
|
||||
|
||||
public DemoMetaLengthCheck(PluginSettings settings) {
|
||||
this.settings = settings;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "runway-demo/meta-length";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Finding> inspect(PageView page) {
|
||||
SettingsView site = settings.site(page.site().id());
|
||||
double ratio = site.decimal("quality.title-warn-ratio", BigDecimal.ONE).doubleValue();
|
||||
int titleLimit = (int) Math.max(1, Math.round(BASE_TITLE_LIMIT * ratio));
|
||||
List<String> ignore = site.list("quality.ignore-codes");
|
||||
|
||||
List<Finding> findings = new ArrayList<>();
|
||||
String title = page.page().title();
|
||||
if (title != null && title.length() > titleLimit) {
|
||||
findings.add(Finding.warning("title.too-long",
|
||||
"Title is " + title.length() + " chars; keep it under " + titleLimit + " for search results."));
|
||||
}
|
||||
if (page.page().description() == null || page.page().description().isBlank()) {
|
||||
findings.add(Finding.info("description.missing",
|
||||
"This page has no meta description; add one for better search snippets."));
|
||||
}
|
||||
if (!hasH1(page.resolvedHtml())) {
|
||||
findings.add(Finding.error("h1.missing", "The rendered page has no <h1> heading."));
|
||||
}
|
||||
return findings.stream().filter(f -> !ignore.contains(f.code())).toList();
|
||||
}
|
||||
|
||||
private static boolean hasH1(String html) {
|
||||
return html != null && html.toLowerCase(Locale.ROOT).contains("<h1");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("quality.seo");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import mx.quest.runway.spi.service.PluginSiteFiles;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import tools.jackson.core.JacksonException;
|
||||
import tools.jackson.databind.DeserializationFeature;
|
||||
import tools.jackson.dataformat.yaml.YAMLMapper;
|
||||
|
||||
/**
|
||||
* The demo's per-site "sticky notes" — data the plugin <b>generates for a site</b>, kept in the plugin's own per-site
|
||||
* folder through the kernel's {@link PluginSiteFiles}: {@value #FILE} under {@code sites/<id>/plugins/runway-demo/}.
|
||||
*
|
||||
* <p><b>When to use {@code PluginSiteFiles}.</b> For anything your plugin stores per site. The folder lives inside the
|
||||
* site's folder, so a full backup carries it, a deleted site takes it along, and nobody else's code can reach it — no
|
||||
* {@code BackupParticipant} is needed (1.x kept the notes outside the site folder and needed one; 2.0.0 does not).
|
||||
* The service is bound to <i>this</i> plugin by the jar the injecting class came from, so no method takes a plugin id.
|
||||
*
|
||||
* <p><b>Personal data.</b> The notes hold what people typed — an operator's notes from the console and a visitor's
|
||||
* message from the public feedback form — so {@code plugin.yml} declares {@value #FILE} under
|
||||
* {@code siteData.personal}: a transfer copy of the site leaves it out. Rule of thumb: any file holding visitor or
|
||||
* user input is personal.
|
||||
*
|
||||
* <p><b>Concurrency.</b> Each kernel write is atomic (readers never see half a file), but an append is a
|
||||
* read-modify-write, which the service leaves to the plugin: it is serialized here per site. The file is bounded to
|
||||
* the newest {@value #MAX_NOTES} notes, far below the kernel's per-write cap.
|
||||
*
|
||||
* <p><b>A {@code GET} never writes.</b> A site with no notes yet shows a welcome note, but the welcome is not stored
|
||||
* until something else is: the first {@link #append} (a console note, a visitor's message, the settings audit note)
|
||||
* writes the welcome and the new note together, so the note an operator saw stays in the list. Until then the site
|
||||
* has no {@value #FILE} at all. Reads ({@link #list}, {@link #count}, {@link #recent}) never create a file — opening
|
||||
* a console screen or the settings page must not change a site.
|
||||
*
|
||||
* <p><b>Failure.</b> A read failure during {@link #append} aborts the append (rewriting the file from nothing would
|
||||
* lose every note); the console reads ({@link #list}, {@link #count}) degrade to empty with a warning, so an
|
||||
* unreadable file never takes a console screen down. The YAML goes through the plugin's own Jackson (a platform
|
||||
* library), lenient about keys it does not know, so a later version can add fields without breaking this one.
|
||||
*/
|
||||
public class DemoNotesStore {
|
||||
|
||||
/** The notes file, relative to the plugin's per-site folder; declared personal in {@code plugin.yml}. */
|
||||
static final String FILE = "notes.yml";
|
||||
/** The most notes a site keeps (the oldest are dropped). */
|
||||
static final int MAX_NOTES = 200;
|
||||
/** The longest note text kept, in characters. */
|
||||
static final int MAX_TEXT = 1000;
|
||||
/**
|
||||
* The welcome note's fixed id (never one {@code newId} makes), so the welcome a site shows is the note its first
|
||||
* write keeps.
|
||||
*/
|
||||
static final String WELCOME_ID = "welcome";
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(DemoNotesStore.class);
|
||||
|
||||
private final PluginSiteFiles files;
|
||||
private final YAMLMapper yaml = YAMLMapper.builder()
|
||||
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
|
||||
.build();
|
||||
private final ConcurrentMap<String, Object> locks = new ConcurrentHashMap<>();
|
||||
|
||||
public DemoNotesStore(PluginSiteFiles files) {
|
||||
this.files = files;
|
||||
}
|
||||
|
||||
private Object lockFor(String siteId) {
|
||||
return locks.computeIfAbsent(siteId, k -> new Object());
|
||||
}
|
||||
|
||||
/**
|
||||
* The site's notes, oldest first. A site with no notes yet reads as the one {@linkplain #welcome() welcome note},
|
||||
* which is <b>not written</b> (see the class comment). Empty, with a warning, when the file cannot be read.
|
||||
*/
|
||||
public List<Note> list(String siteId) {
|
||||
synchronized (lockFor(siteId)) {
|
||||
NotesFile file;
|
||||
try {
|
||||
file = read(siteId);
|
||||
} catch (IOException | JacksonException e) {
|
||||
log.warn("runway-demo notes of site {} could not be read: {}", siteId, e.toString());
|
||||
return List.of();
|
||||
}
|
||||
return file.notes().isEmpty() ? List.of(welcome()) : file.notes();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The note a site with no notes shows. Its id is fixed and it has no time ({@code createdAt} is empty) while it is
|
||||
* only shown; the first {@link #append} stores it with that write's time.
|
||||
*/
|
||||
static Note welcome() {
|
||||
return new Note(WELCOME_ID, "Welcome — this note is data the runway-demo plugin keeps for this site in its "
|
||||
+ "own folder; it travels in full backups and is left out of transfer copies.", "",
|
||||
Note.ORIGIN_SYSTEM);
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends a note (its text stripped and capped at {@value #MAX_TEXT} characters) and returns the new count. The
|
||||
* first append to a site with no notes also stores the {@linkplain #welcome() welcome note}, before the new one.
|
||||
*
|
||||
* @param origin who wrote it: {@link Note#ORIGIN_CONSOLE}, {@link Note#ORIGIN_VISITOR} or {@link Note#ORIGIN_SYSTEM}
|
||||
* @throws UncheckedIOException when the file cannot be read or written (an unreadable file is left untouched)
|
||||
*/
|
||||
public int append(String siteId, String text, String origin) {
|
||||
String clean = text == null ? "" : text.strip();
|
||||
if (clean.length() > MAX_TEXT) {
|
||||
clean = clean.substring(0, MAX_TEXT);
|
||||
}
|
||||
synchronized (lockFor(siteId)) {
|
||||
try {
|
||||
List<Note> notes = new ArrayList<>(read(siteId).notes());
|
||||
String now = Instant.now().toString();
|
||||
if (notes.isEmpty()) {
|
||||
// The first write keeps the welcome the site was showing, stamped with this write's time.
|
||||
Note shown = welcome();
|
||||
notes.add(new Note(shown.id(), shown.text(), now, shown.origin()));
|
||||
}
|
||||
notes.add(new Note(newId(), clean, now, origin));
|
||||
if (notes.size() > MAX_NOTES) {
|
||||
notes = new ArrayList<>(notes.subList(notes.size() - MAX_NOTES, notes.size()));
|
||||
}
|
||||
write(siteId, new NotesFile(notes));
|
||||
return notes.size();
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("storing a runway-demo note for site " + siteId, e);
|
||||
} catch (JacksonException unparsable) {
|
||||
// Jackson 3 exceptions are unchecked; an unparsable file is as unreadable as an I/O failure.
|
||||
throw new UncheckedIOException("storing a runway-demo note for site " + siteId,
|
||||
new IOException(unparsable));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The number of notes the site shows (1, the unsaved welcome, for a site with none yet; as {@link #list}). */
|
||||
public int count(String siteId) {
|
||||
return list(siteId).size();
|
||||
}
|
||||
|
||||
/** The newest {@code limit} notes, newest first. */
|
||||
public List<Note> recent(String siteId, int limit) {
|
||||
List<Note> all = list(siteId);
|
||||
return all.subList(Math.max(0, all.size() - limit), all.size()).reversed();
|
||||
}
|
||||
|
||||
private NotesFile read(String siteId) throws IOException {
|
||||
Optional<String> text = files.readText(siteId, FILE);
|
||||
if (text.isEmpty() || text.get().isBlank()) {
|
||||
return NotesFile.empty();
|
||||
}
|
||||
NotesFile parsed = yaml.readValue(text.get(), NotesFile.class);
|
||||
return parsed == null ? NotesFile.empty() : parsed;
|
||||
}
|
||||
|
||||
private void write(String siteId, NotesFile file) throws IOException {
|
||||
files.writeText(siteId, FILE, yaml.writeValueAsString(file));
|
||||
}
|
||||
|
||||
private static String newId() {
|
||||
return "n-" + Long.toString(System.nanoTime(), 36);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.spi.ContentWidget;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.RenderFragment;
|
||||
import mx.quest.runway.spi.model.SettingsView;
|
||||
import mx.quest.runway.spi.model.WidgetView;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* {@code ContentWidget} — renders a styled callout wherever a tenant page carries the anchor
|
||||
* {@code <div id="..." data-widget="demo-notice/<instance>">} (the {@code id} AND {@code data-widget} on the same
|
||||
* element). {@link #key()} {@code "demo-notice"} is the {@code <type>} half of that anchor.
|
||||
*
|
||||
* <p>Reads the per-site {@code notice.*} settings through {@link PluginSettings}: disabled →
|
||||
* {@link RenderFragment#empty()}; {@code notice.style} picks the CSS class; {@code notice.max-chars} truncates (read
|
||||
* with the clamped accessor, so a hand-edited out-of-range value can never break rendering). A chrome-scoped
|
||||
* instance ({@link WidgetView#isChrome()}) shows the app-level {@code banner.text} instead.
|
||||
*
|
||||
* <p><b>{@code Messages.site}</b> is how visitor-facing text is localized: it resolves against the site's own bundle
|
||||
* first, then every plugin's {@code i18n/} bundle, in the visitor's locale ({@code view.locale()}), and formats the
|
||||
* arguments. Pure; never throws; owns its HTML escaping (the host splices the fragment unescaped).
|
||||
*/
|
||||
public class DemoNoticeWidget implements ContentWidget {
|
||||
|
||||
private static final Set<String> STYLES = Set.of("info", "warning", "danger");
|
||||
|
||||
private final DemoAppProps props;
|
||||
private final PluginSettings settings;
|
||||
private final Messages messages;
|
||||
|
||||
public DemoNoticeWidget(DemoAppProps props, PluginSettings settings, Messages messages) {
|
||||
this.props = props;
|
||||
this.settings = settings;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "demo-notice";
|
||||
}
|
||||
|
||||
@Override
|
||||
public RenderFragment render(WidgetView view) {
|
||||
SettingsView site = settings.site(view.site().id());
|
||||
if (!site.bool("notice.enabled", true)) {
|
||||
return RenderFragment.empty();
|
||||
}
|
||||
String style = site.string("notice.style", "info");
|
||||
if (!STYLES.contains(style)) {
|
||||
style = "info";
|
||||
}
|
||||
int maxChars = (int) site.integer("notice.max-chars", 280, 1, 2000);
|
||||
|
||||
String body;
|
||||
if (view.isChrome() && props.getBanner().isEnabled() && !props.getBanner().getText().isBlank()) {
|
||||
body = props.getBanner().getText();
|
||||
} else {
|
||||
body = messages.site(view.site().id(), view.locale(), "runwaydemo.notice.body",
|
||||
"This is the runway-demo notice widget (instance \"{0}\") on site \"{1}\".",
|
||||
view.instanceId(), view.site().displayName());
|
||||
}
|
||||
if (body.length() > maxChars) {
|
||||
body = body.substring(0, maxChars) + "…";
|
||||
}
|
||||
return RenderFragment.of("<div class=\"rw-demo-notice rw-demo-notice-" + style + "\" role=\"note\">"
|
||||
+ Html.escape(body) + "</div>");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("widget.configurable");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import mx.quest.runway.spi.model.PluginInfo;
|
||||
import mx.quest.runway.spi.service.AccessCheck;
|
||||
import mx.quest.runway.spi.service.ContentCatalogView;
|
||||
import mx.quest.runway.spi.service.ContentChanges;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.PluginSiteFiles;
|
||||
import mx.quest.runway.spi.service.RequestContext;
|
||||
import mx.quest.runway.spi.service.SitePages;
|
||||
import mx.quest.runway.spi.service.Sites;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.annotation.Order;
|
||||
|
||||
/**
|
||||
* The plugin's {@code mainClass} — the single {@code @Configuration} the host registers into its context before
|
||||
* refresh (as the bean {@code plugin:runway-demo}). Every bean is declared <b>explicitly</b> here; no
|
||||
* {@code @ComponentScan} of the plugin's own package. The package ({@code mx.quest.demo}) lies outside
|
||||
* {@code mx.quest.runway}, so the host never scans it.
|
||||
*
|
||||
* <h2>Everything from the kernel arrives as an SPI service</h2>
|
||||
* The plugin links nothing of the host but {@code mx.quest.runway.spi} (a test proves it on the compiled classes).
|
||||
* Services are ordinary Spring beans, received as {@code @Bean} method parameters:
|
||||
* <ul>
|
||||
* <li><b>plugin-scoped</b> — {@link PluginSettings}, {@link PluginSiteFiles}, {@link ContentChanges},
|
||||
* {@link PluginInfo}: the host binds each to <i>this</i> plugin by the jar the injecting class
|
||||
* ({@code DemoPluginConfig}) was loaded from. Inject them in a class of your own jar — never from a {@code lib/}
|
||||
* jar, and never with a bare {@code getBean}, both of which fail at startup;</li>
|
||||
* <li><b>kernel singletons</b> — {@link Sites}, {@link RequestContext}, {@link AccessCheck}, {@link Messages},
|
||||
* {@link SitePages}, {@link ContentCatalogView}.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Rules the kernel checks</h2>
|
||||
* <ul>
|
||||
* <li><b>Bean names start with the plugin id in lowerCamelCase</b> ({@code runway-demo} → {@code runwayDemo…}):
|
||||
* plugins share one bean namespace with the kernel and each other. The templates follow
|
||||
* ({@code ${@runwayDemoAdminModel…}}).</li>
|
||||
* <li><b>Allowed Spring surface</b>: SPI implementations, plain beans, and {@code @Controller}s mapped under
|
||||
* {@code /__admin/runway-demo} or {@code /__app/runway-demo}. <b>Not allowed</b>: servlet {@code Filter}s (1.x's
|
||||
* timing filter is gone — servlet filters are outside the 1.0 plugin contract), {@code SecurityFilterChain}s,
|
||||
* bean (factory) post-processors, unrestricted {@code @ControllerAdvice}.</li>
|
||||
* <li>Axis implementations ({@code HeadContributor}, {@code ContentWidget}, {@code EndpointContributor},
|
||||
* {@code PageQualityCheck}, {@code ContentSource}) and callbacks ({@code SiteEventListener},
|
||||
* {@code PluginLifecycle}) are collected <b>by type</b> — plain {@code @Bean}s, never {@code @Primary}. A bean
|
||||
* method returns the <b>concrete</b> class, so Spring sees every interface it implements before creating it
|
||||
* ({@link DemoShowcaseSource} is both a content source and a listener).</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class DemoPluginConfig {
|
||||
|
||||
// --- app-level settings ---------------------------------------------------------------------------------
|
||||
|
||||
/** Bound from {@code runway.plugin.runway-demo.*} (the descriptor's {@code settings:}); applied on restart. */
|
||||
@Bean
|
||||
@ConfigurationProperties("runway.plugin.runway-demo")
|
||||
public DemoAppProps runwayDemoAppProps() {
|
||||
return new DemoAppProps();
|
||||
}
|
||||
|
||||
// --- per-site data -----------------------------------------------------------------------------------------
|
||||
|
||||
@Bean
|
||||
public DemoNotesStore runwayDemoNotesStore(PluginSiteFiles files) {
|
||||
return new DemoNotesStore(files);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DemoShowcaseStore runwayDemoShowcaseStore(PluginSiteFiles files, ContentChanges changes) {
|
||||
return new DemoShowcaseStore(files, changes);
|
||||
}
|
||||
|
||||
// --- callbacks ---------------------------------------------------------------------------------------------
|
||||
|
||||
@Bean
|
||||
public DemoLifecycle runwayDemoLifecycle() {
|
||||
return new DemoLifecycle();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DemoActivity runwayDemoActivity(DemoNotesStore notes, Sites sites) {
|
||||
return new DemoActivity(notes, sites);
|
||||
}
|
||||
|
||||
// --- axis implementations ----------------------------------------------------------------------------------
|
||||
|
||||
@Bean
|
||||
@Order(200) // after the kernel's SEO (@Order 100) and icon (@Order 90) head contributors
|
||||
public DemoAnalyticsHead runwayDemoAnalyticsHead(DemoAppProps props, PluginSettings settings) {
|
||||
return new DemoAnalyticsHead(props, settings);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DemoNoticeWidget runwayDemoNoticeWidget(DemoAppProps props, PluginSettings settings, Messages messages) {
|
||||
return new DemoNoticeWidget(props, settings, messages);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DemoFeedbackWidget runwayDemoFeedbackWidget(PluginSettings settings, Messages messages) {
|
||||
return new DemoFeedbackWidget(settings, messages);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DemoMetaLengthCheck runwayDemoMetaLengthCheck(PluginSettings settings) {
|
||||
return new DemoMetaLengthCheck(settings);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DemoEndpoints runwayDemoEndpoints(AccessCheck access, DemoNotesStore notes, Messages messages,
|
||||
PluginSettings settings) {
|
||||
return new DemoEndpoints(access, notes, messages, settings);
|
||||
}
|
||||
|
||||
/** A content source AND a SOURCE-phase listener (it drops its own cache before consumers re-read). */
|
||||
@Bean
|
||||
public DemoShowcaseSource runwayDemoShowcaseSource(DemoShowcaseStore store, Messages messages) {
|
||||
return new DemoShowcaseSource(store, messages);
|
||||
}
|
||||
|
||||
// --- console -------------------------------------------------------------------------------------------------
|
||||
|
||||
@Bean
|
||||
public DemoAdminModel runwayDemoAdminModel(DemoNotesStore notes, DemoAppProps props, PluginSettings settings,
|
||||
Sites sites, SitePages pages, PluginInfo self) {
|
||||
return new DemoAdminModel(notes, props, settings, sites, pages, self);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DemoConsoleController runwayDemoConsoleController(RequestContext request, AccessCheck access,
|
||||
Messages messages, SitePages pages,
|
||||
ContentCatalogView catalog, DemoNotesStore notes,
|
||||
DemoShowcaseStore showcase, DemoActivity activity,
|
||||
PluginInfo self) {
|
||||
return new DemoConsoleController(request, access, messages, pages, catalog, notes, showcase, activity, self);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import mx.quest.runway.spi.ContentSource;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.CatalogChange;
|
||||
import mx.quest.runway.spi.model.ContentBody;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.SiteLifecycleEvent;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
|
||||
/**
|
||||
* {@code ContentSource} — serves the site's {@link Showcase} as a real public page at {@value #PATH}, through the
|
||||
* kernel's own routing, the tenant's master chrome, the {@code <head>} treatment, {@code ETag}/{@code 304}, the
|
||||
* sitemap/llms.txt listing and on-site search. Nothing is served until an operator publishes a showcase from the
|
||||
* demo's console screen.
|
||||
*
|
||||
* <p>It is also a {@link SiteEventListener} in the {@link Phase#SOURCE SOURCE} phase. <b>When to use a
|
||||
* {@code SOURCE} listener:</b> when you are a content source that keeps derived state of your own (here, the
|
||||
* {@link DemoShowcaseStore}'s cached read). The kernel runs every {@code SOURCE} listener first, evicts its content
|
||||
* listing again, and only then runs the {@code CONSUMER}s (sitemaps, search indexes) — so a consumer that re-reads
|
||||
* the listing never sees a source's stale state. This one drops its cache on:
|
||||
* <ul>
|
||||
* <li>a {@code CONTENT} change of its own source — on this node the store already holds the new value, but a change
|
||||
* <b>replayed from another node</b> ({@code local == false}) is the only way this node learns the file
|
||||
* changed;</li>
|
||||
* <li>a <b>wholesale</b> lifecycle event ({@code DELETED}, {@code RESTORED}): the site's files were replaced or
|
||||
* removed under it.</li>
|
||||
* </ul>
|
||||
* A callback only evicts — cheap and synchronous, as the contract asks (heavy work belongs on your own executor).
|
||||
*/
|
||||
public class DemoShowcaseSource implements ContentSource, SiteEventListener {
|
||||
|
||||
/** This source's key: the namespace of its content ids ({@code runway-demo:showcase}). */
|
||||
static final String SOURCE_KEY = "runway-demo";
|
||||
/** The id of the one item this source serves per site. */
|
||||
static final String ID = "showcase";
|
||||
/** Where the showcase is served. */
|
||||
static final String PATH = "/demo/showcase";
|
||||
/** The body template: this plugin's {@code templates/showcase.html} + {@code .th.xml}. */
|
||||
static final String BODY_TEMPLATE = "__plugin__/runway-demo/showcase";
|
||||
|
||||
private static final int DESCRIPTION_CHARS = 150;
|
||||
|
||||
private final DemoShowcaseStore store;
|
||||
private final Messages messages;
|
||||
|
||||
public DemoShowcaseSource(DemoShowcaseStore store, Messages messages) {
|
||||
this.store = store;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return SOURCE_KEY;
|
||||
}
|
||||
|
||||
/** Metadata only and published only — it runs on anonymous public requests (the sitemap). */
|
||||
@Override
|
||||
public List<ContentRef> enumerate(SiteView site) {
|
||||
return store.current(site.id()).map(showcase -> List.of(ref(site, showcase))).orElse(List.of());
|
||||
}
|
||||
|
||||
/** The cheap routing probe: one string comparison before anything is read. */
|
||||
@Override
|
||||
public Optional<ContentRef> resolve(SiteView site, String path, Locale locale) {
|
||||
if (!PATH.equals(path)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return enumerate(site).stream().filter(ref -> ref.hasLocale(locale, site.defaultLocale())).findFirst();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ContentBody body(SiteView site, String id, Locale locale) {
|
||||
if (!ID.equals(id)) {
|
||||
return ContentBody.empty();
|
||||
}
|
||||
return store.current(site.id()).map(showcase -> ContentBody.of(html(showcase.text())))
|
||||
.orElse(ContentBody.empty());
|
||||
}
|
||||
|
||||
/** Declared with {@link #CAP_INDEXABLE_TEXT}, so on-site search indexes the showcase's text too. */
|
||||
@Override
|
||||
public String indexableText(SiteView site, String id, Locale locale) {
|
||||
return ID.equals(id) ? store.current(site.id()).map(s -> html(s.text())).orElse("") : "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of(CAP_INDEXABLE_TEXT);
|
||||
}
|
||||
|
||||
private ContentRef ref(SiteView site, Showcase showcase) {
|
||||
String language = site.defaultLocale().getLanguage();
|
||||
String title = messages.site(site.id(), site.defaultLocale(), "runwaydemo.showcase.title", "Showcase");
|
||||
String text = showcase.text().strip();
|
||||
String description = text.length() > DESCRIPTION_CHARS ? text.substring(0, DESCRIPTION_CHARS) + "…" : text;
|
||||
// No locales listed: the item exists in the site's default language only. updatedAt moves on every
|
||||
// publish — the render ETag folds it, so a client revalidating gets the new text, not a stale 304.
|
||||
return ContentRef.of(ID, PATH, Map.of(), List.of(), Map.of(language, title), Map.of(language, description),
|
||||
BODY_TEMPLATE, showcase.updatedAt());
|
||||
}
|
||||
|
||||
/** The plain text as HTML: escaped, one paragraph, line breaks kept. */
|
||||
static String html(String text) {
|
||||
return "<p>" + Html.escape(text.replace("\r\n", "\n")).replace("\n", "<br>\n") + "</p>";
|
||||
}
|
||||
|
||||
// --- SiteEventListener (SOURCE phase) ----------------------------------------------------------------------
|
||||
|
||||
@Override
|
||||
public Phase phase() {
|
||||
return Phase.SOURCE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSiteLifecycle(SiteLifecycleEvent event) {
|
||||
if (event.wholesale()) {
|
||||
store.evict(event.siteId());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCatalogChanged(CatalogChange change) {
|
||||
if (change.cause() == CatalogChange.Cause.CONTENT && SOURCE_KEY.equals(change.sourceKey())) {
|
||||
store.evict(change.siteId());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.function.LongSupplier;
|
||||
import mx.quest.runway.spi.service.ContentChanges;
|
||||
import mx.quest.runway.spi.service.PluginSiteFiles;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import tools.jackson.core.JacksonException;
|
||||
import tools.jackson.databind.DeserializationFeature;
|
||||
import tools.jackson.dataformat.yaml.YAMLMapper;
|
||||
|
||||
/**
|
||||
* Reads and writes the site's {@link Showcase} ({@value #FILE} in the plugin's per-site folder) and — the point of
|
||||
* this class — <b>announces every write with {@link ContentChanges}</b>.
|
||||
*
|
||||
* <p><b>When to use {@code ContentChanges}.</b> After every mutation of content your {@code ContentSource} serves:
|
||||
* an item created, edited, deleted, published, unpublished, or the whole corpus replaced (pass a {@code null} id).
|
||||
* The host cannot see your files change; the call evicts routing, the content listing, sitemaps and search indexes on
|
||||
* every node of a cluster and notifies every {@code SiteEventListener} before it returns. Call it from the code that
|
||||
* made the change, <b>after</b> the write and outside your own locks (listeners run synchronously on this thread),
|
||||
* and never from a {@code SiteEventListener} callback — the kernel refuses that. It is plugin-scoped like
|
||||
* {@code PluginSettings}: it only accepts a source key this plugin contributes.
|
||||
*
|
||||
* <p>The parsed file is cached per site, because {@code enumerate} runs on every catalog rebuild and routing miss.
|
||||
* The cache is dropped by this store's own writes, by {@link DemoShowcaseSource}'s {@code SOURCE}-phase listener
|
||||
* (a change replayed from another node, a restored or deleted site), and after {@link #TTL} at the latest — the
|
||||
* backstop for a file edited by hand, which nobody announces.
|
||||
*/
|
||||
public class DemoShowcaseStore {
|
||||
|
||||
/** The showcase file, relative to the plugin's per-site folder. */
|
||||
static final String FILE = "showcase.yml";
|
||||
/** The longest showcase text kept, in characters. */
|
||||
static final int MAX_TEXT = 2000;
|
||||
/** How long a cached read is trusted without any announcement. */
|
||||
static final Duration TTL = Duration.ofSeconds(60);
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(DemoShowcaseStore.class);
|
||||
|
||||
/** The on-disk shape; the instant is written as ISO-8601 text. */
|
||||
record ShowcaseFile(String text, String updatedAt) {
|
||||
}
|
||||
|
||||
private record Cached(Optional<Showcase> value, long loadedAtNanos) {
|
||||
}
|
||||
|
||||
private final PluginSiteFiles files;
|
||||
private final ContentChanges changes;
|
||||
private final LongSupplier nanoClock;
|
||||
private final YAMLMapper yaml = YAMLMapper.builder()
|
||||
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
|
||||
.build();
|
||||
private final ConcurrentMap<String, Cached> cache = new ConcurrentHashMap<>();
|
||||
private final ConcurrentMap<String, Object> locks = new ConcurrentHashMap<>();
|
||||
|
||||
public DemoShowcaseStore(PluginSiteFiles files, ContentChanges changes) {
|
||||
this(files, changes, System::nanoTime);
|
||||
}
|
||||
|
||||
DemoShowcaseStore(PluginSiteFiles files, ContentChanges changes, LongSupplier nanoClock) {
|
||||
this.files = files;
|
||||
this.changes = changes;
|
||||
this.nanoClock = nanoClock;
|
||||
}
|
||||
|
||||
/** The site's published showcase; empty when none is published or the file cannot be read (logged). */
|
||||
public Optional<Showcase> current(String siteId) {
|
||||
Cached cached = cache.get(siteId);
|
||||
if (fresh(cached)) {
|
||||
return cached.value();
|
||||
}
|
||||
// Load under the site's lock, so a read racing a publish can never put the old file back into the cache.
|
||||
synchronized (locks.computeIfAbsent(siteId, k -> new Object())) {
|
||||
cached = cache.get(siteId);
|
||||
if (fresh(cached)) {
|
||||
return cached.value();
|
||||
}
|
||||
Optional<Showcase> loaded = load(siteId);
|
||||
cache.put(siteId, new Cached(loaded, nanoClock.getAsLong()));
|
||||
return loaded;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean fresh(Cached cached) {
|
||||
return cached != null && nanoClock.getAsLong() - cached.loadedAtNanos() < TTL.toNanos();
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes {@code text} (stripped, capped at {@value #MAX_TEXT} characters) as the site's showcase, replacing
|
||||
* any previous one, then announces the change.
|
||||
*
|
||||
* @throws IllegalArgumentException when the text is blank
|
||||
* @throws UncheckedIOException when the file cannot be written (nothing is announced)
|
||||
*/
|
||||
public Showcase publish(String siteId, String text) {
|
||||
String clean = text == null ? "" : text.strip();
|
||||
if (clean.isEmpty()) {
|
||||
throw new IllegalArgumentException("the showcase text is blank");
|
||||
}
|
||||
if (clean.length() > MAX_TEXT) {
|
||||
clean = clean.substring(0, MAX_TEXT);
|
||||
}
|
||||
Showcase showcase = new Showcase(clean, Instant.now());
|
||||
synchronized (locks.computeIfAbsent(siteId, k -> new Object())) {
|
||||
try {
|
||||
files.writeText(siteId, FILE, yaml.writeValueAsString(
|
||||
new ShowcaseFile(showcase.text(), showcase.updatedAt().toString())));
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("publishing the runway-demo showcase of site " + siteId, e);
|
||||
}
|
||||
cache.put(siteId, new Cached(Optional.of(showcase), nanoClock.getAsLong()));
|
||||
}
|
||||
// Written; now tell the host — outside our lock, because every listener runs on this thread before it returns.
|
||||
changes.changed(siteId, DemoShowcaseSource.SOURCE_KEY, DemoShowcaseSource.ID);
|
||||
return showcase;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unpublishes the site's showcase (deletes the file) and announces the change, so the page, the sitemap entry
|
||||
* and any search hit disappear at once.
|
||||
*
|
||||
* @return {@code true} if a showcase was published; {@code false} (and nothing announced) when there was none
|
||||
* @throws UncheckedIOException when the file cannot be deleted
|
||||
*/
|
||||
public boolean unpublish(String siteId) {
|
||||
boolean deleted;
|
||||
synchronized (locks.computeIfAbsent(siteId, k -> new Object())) {
|
||||
try {
|
||||
deleted = files.delete(siteId, FILE);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("unpublishing the runway-demo showcase of site " + siteId, e);
|
||||
}
|
||||
cache.put(siteId, new Cached(Optional.empty(), nanoClock.getAsLong()));
|
||||
}
|
||||
if (deleted) {
|
||||
changes.changed(siteId, DemoShowcaseSource.SOURCE_KEY, DemoShowcaseSource.ID);
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
|
||||
/** Drops the cached read of {@code siteId}, so the next {@link #current} reads the file again. */
|
||||
public void evict(String siteId) {
|
||||
cache.remove(siteId);
|
||||
}
|
||||
|
||||
private Optional<Showcase> load(String siteId) {
|
||||
try {
|
||||
Optional<String> text = files.readText(siteId, FILE);
|
||||
if (text.isEmpty() || text.get().isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
ShowcaseFile file = yaml.readValue(text.get(), ShowcaseFile.class);
|
||||
if (file == null || file.text() == null || file.text().isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(new Showcase(file.text(), parseInstant(file.updatedAt())));
|
||||
} catch (IOException | JacksonException | IllegalArgumentException e) {
|
||||
// IllegalArgumentException: an unsafe site id or a path escaping the folder. Serve nothing, never a 500.
|
||||
log.warn("runway-demo showcase of site {} could not be read: {}", siteId, e.toString());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private static Instant parseInstant(String value) {
|
||||
try {
|
||||
return value == null ? Instant.EPOCH : Instant.parse(value);
|
||||
} catch (DateTimeParseException e) {
|
||||
return Instant.EPOCH;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
/**
|
||||
* Minimal HTML-text escaping. Every SPI that returns raw HTML (head markup, widget fragments) OWNS its
|
||||
* escaping — the host splices the output unescaped. Sufficient for element-text and double-quoted-attribute
|
||||
* contexts, which is all this demo emits.
|
||||
*/
|
||||
final class Html {
|
||||
|
||||
private Html() {
|
||||
}
|
||||
|
||||
static String escape(String s) {
|
||||
if (s == null || s.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
return s.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
.replace("\"", """)
|
||||
.replace("'", "'");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
/**
|
||||
* One per-site "sticky note". Immutable; serialized to {@code notes.yml} by {@link DemoNotesStore}.
|
||||
*
|
||||
* @param id stable note id (a timestamp-derived token)
|
||||
* @param text the note body (plain text; escaped wherever it is rendered)
|
||||
* @param createdAt ISO-8601 creation instant
|
||||
* @param origin who wrote it: {@value #ORIGIN_CONSOLE}, {@value #ORIGIN_VISITOR} or {@value #ORIGIN_SYSTEM}
|
||||
* ({@code null} in a file written before the field existed reads as {@value #ORIGIN_SYSTEM})
|
||||
*/
|
||||
public record Note(String id, String text, String createdAt, String origin) {
|
||||
|
||||
/** Written by an operator on the demo's console screen. */
|
||||
public static final String ORIGIN_CONSOLE = "console";
|
||||
/** Sent by a visitor through the public feedback form (the anonymous POST route). */
|
||||
public static final String ORIGIN_VISITOR = "visitor";
|
||||
/** Written by the plugin itself (the welcome note, the settings-saved audit note). */
|
||||
public static final String ORIGIN_SYSTEM = "system";
|
||||
|
||||
public Note {
|
||||
text = text == null ? "" : text;
|
||||
origin = origin == null || origin.isBlank() ? ORIGIN_SYSTEM : origin;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The on-disk shape of {@code notes.yml} — a wrapper around the note list so the format can grow new top-level keys
|
||||
* without breaking older readers (the store reads with unknown keys ignored).
|
||||
*
|
||||
* @param notes the site's notes, oldest first; never {@code null}
|
||||
*/
|
||||
public record NotesFile(List<Note> notes) {
|
||||
|
||||
public NotesFile {
|
||||
notes = (notes == null) ? List.of() : List.copyOf(notes);
|
||||
}
|
||||
|
||||
public static NotesFile empty() {
|
||||
return new NotesFile(List.of());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* The demo's one piece of <b>routable content</b> per site: a short message an operator publishes from the demo's
|
||||
* console screen, served by {@link DemoShowcaseSource} as a page at {@value DemoShowcaseSource#PATH}. Stored as
|
||||
* {@code showcase.yml} in the plugin's per-site folder (published content — not personal data).
|
||||
*
|
||||
* @param text the message (plain text; escaped when rendered)
|
||||
* @param updatedAt when it was last published — the {@code ContentRef.updatedAt} the page's {@code ETag} folds, so a
|
||||
* republished message is never answered with a stale {@code 304}
|
||||
*/
|
||||
public record Showcase(String text, Instant updatedAt) {
|
||||
|
||||
public Showcase {
|
||||
text = text == null ? "" : text;
|
||||
updatedAt = updatedAt == null ? Instant.EPOCH : updatedAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.spi.model.CatalogChange;
|
||||
import mx.quest.runway.spi.model.LocalizedUrl;
|
||||
import mx.quest.runway.spi.model.SettingsChange;
|
||||
import mx.quest.runway.spi.model.SiteLifecycleEvent;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
import mx.quest.runway.spi.testkit.EventDispatch;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/** The CONSUMER listener, driven by the testkit's {@link EventDispatch} in the kernel's order. */
|
||||
class DemoActivityTest {
|
||||
|
||||
@TempDir
|
||||
Path sites;
|
||||
private DemoNotesStore notes;
|
||||
private DemoActivity activity;
|
||||
private EventDispatch events;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
Files.createDirectories(sites.resolve("acme"));
|
||||
notes = new DemoNotesStore(new TempDirSiteFiles(sites, "runway-demo"));
|
||||
activity = new DemoActivity(notes, new FakeSiteServices()
|
||||
.site(new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null)));
|
||||
events = new EventDispatch("runway-demo", Set.of("runway-demo")).listener(activity);
|
||||
}
|
||||
|
||||
private static LocalizedUrl url(String path) {
|
||||
return new LocalizedUrl(Locale.ENGLISH, path, path);
|
||||
}
|
||||
|
||||
@Test
|
||||
void itIsAConsumer() {
|
||||
assertEquals(SiteEventListener.Phase.CONSUMER, activity.phase());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSaveOfItsOwnSettingsAppendsOneAuditNote() {
|
||||
int before = notes.count("acme");
|
||||
events.settings("acme", "runway-demo");
|
||||
List<Note> after = notes.list("acme");
|
||||
assertEquals(before + 1, after.size());
|
||||
assertTrue(after.getLast().text().startsWith("Per-site settings saved at "), after.getLast().text());
|
||||
assertEquals(Note.ORIGIN_SYSTEM, after.getLast().origin());
|
||||
assertTrue(events.failures().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherPluginsSettingsSaveWritesNoNoteButIsRecordedAsACatalogChange() {
|
||||
int before = notes.count("acme");
|
||||
events.settings("acme", "contact");
|
||||
assertEquals(before, notes.count("acme"), "onSettingsChanged is for this plugin's own settings only");
|
||||
DemoActivity.Entry entry = activity.recent("acme").getFirst();
|
||||
assertEquals("settings", entry.cause());
|
||||
assertEquals("contact", entry.item());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChangeReplayedFromAnotherNodeWritesNoSecondNote() {
|
||||
int before = notes.count("acme");
|
||||
activity.onSettingsChanged(new SettingsChange("acme", "runway-demo", false));
|
||||
assertEquals(before, notes.count("acme"), "the node where the save happened wrote the note");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPageChangeIsRecordedWithItsUrlsBeforeAndAfter() {
|
||||
events.page("acme", "about", List.of(url("/about")), List.of(url("/about-us")));
|
||||
DemoActivity.Entry entry = activity.recent("acme").getFirst();
|
||||
assertEquals("page", entry.cause());
|
||||
assertEquals("pages:about", entry.item());
|
||||
assertEquals(List.of("/about"), entry.previousUrls());
|
||||
assertEquals(List.of("/about-us"), entry.currentUrls());
|
||||
assertTrue(entry.local());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeletionStillNamesTheOldAddressAndAWholeSourceChangeShowsAStar() {
|
||||
events.page("acme", "gone", List.of(url("/gone")), List.of());
|
||||
events.catalog(new CatalogChange("acme", CatalogChange.Cause.CONTENT, "blog", null, "blog", null, null,
|
||||
false));
|
||||
List<DemoActivity.Entry> recent = activity.recent("acme");
|
||||
assertEquals("blog:*", recent.get(0).item(), "newest first; a null id is the whole corpus");
|
||||
assertFalse(recent.get(0).local());
|
||||
assertEquals(List.of("/gone"), recent.get(1).previousUrls());
|
||||
assertEquals(List.of(), recent.get(1).currentUrls());
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyTheNewestChangesAreKept() {
|
||||
for (int i = 0; i < DemoActivity.KEEP + 4; i++) {
|
||||
events.page("acme", "p" + i, List.of(), List.of());
|
||||
}
|
||||
List<DemoActivity.Entry> recent = activity.recent("acme");
|
||||
assertEquals(DemoActivity.KEEP, recent.size());
|
||||
assertEquals("pages:p" + (DemoActivity.KEEP + 3), recent.getFirst().item());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWholesaleEventDropsWhatWasRecordedForTheSite() {
|
||||
events.page("acme", "about", List.of(), List.of());
|
||||
events.lifecycle("acme", SiteLifecycleEvent.Kind.DELETED, false);
|
||||
List<DemoActivity.Entry> recent = activity.recent("acme");
|
||||
assertEquals(1, recent.size(), "only the deletion's own SITE change remains (lifecycle runs first)");
|
||||
assertEquals("site", recent.getFirst().cause());
|
||||
events.lifecycle("acme", SiteLifecycleEvent.Kind.SUSPENDED, false);
|
||||
assertEquals(2, activity.recent("acme").size(), "a non-wholesale event keeps the record");
|
||||
assertTrue(events.failures().isEmpty(), "an unknown site in Sites is handled: " + events.failures());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownSiteHasNoActivityAndANoteFailureNeverPropagates() {
|
||||
assertEquals(List.of(), activity.recent("nobody"));
|
||||
activity.onSettingsChanged(new SettingsChange("ghost", "runway-demo", true)); // no folder: logged only
|
||||
events.lifecycle("ghost", SiteLifecycleEvent.Kind.CREATED, false); // unknown to Sites
|
||||
assertTrue(events.failures().isEmpty(), events.failures().toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.InstallResult;
|
||||
import mx.quest.runway.spi.model.LocalizedUrl;
|
||||
import mx.quest.runway.spi.model.PluginInfo;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.model.StarterPage;
|
||||
import mx.quest.runway.spi.service.ConsoleScreen;
|
||||
import mx.quest.runway.spi.service.SitePages;
|
||||
import mx.quest.runway.spi.testkit.EventDispatch;
|
||||
import mx.quest.runway.spi.testkit.FakeContentCatalog;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
/**
|
||||
* The console screen driven through Spring MVC in-process (MockMvc), over the testkit's fakes. The
|
||||
* {@code @PreAuthorize} gates are enforced by the host's method security, which a standalone MockMvc does not have:
|
||||
* {@link DemoPluginConfigTest} proves every handler carries one, and the live verify script proves a request without
|
||||
* the permission or the CSRF token is refused.
|
||||
*/
|
||||
class DemoConsoleControllerTest {
|
||||
|
||||
private static final SiteView SITE = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null);
|
||||
private static final String BASE = "/__admin/runway-demo";
|
||||
|
||||
@TempDir
|
||||
Path sites;
|
||||
private FakeSiteServices kernel;
|
||||
private FakeContentCatalog catalog;
|
||||
private EventDispatch events;
|
||||
private DemoNotesStore notes;
|
||||
private DemoShowcaseStore showcase;
|
||||
private DemoActivity activity;
|
||||
private MockMvc mvc;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
Files.createDirectories(sites.resolve("acme"));
|
||||
kernel = new FakeSiteServices().site(SITE).current("acme");
|
||||
catalog = new FakeContentCatalog().site("acme");
|
||||
TempDirSiteFiles files = new TempDirSiteFiles(sites, "runway-demo");
|
||||
events = new EventDispatch("runway-demo", Set.of("runway-demo"));
|
||||
notes = new DemoNotesStore(files);
|
||||
showcase = new DemoShowcaseStore(files, events);
|
||||
activity = new DemoActivity(notes, kernel);
|
||||
events.listener(new DemoShowcaseSource(showcase, kernel)).listener(activity);
|
||||
mvc = mvcFor(kernel);
|
||||
}
|
||||
|
||||
private MockMvc mvcFor(FakeSiteServices services) {
|
||||
DemoConsoleController controller = new DemoConsoleController(services, services, services, services,
|
||||
catalog, notes, showcase, activity, new PluginInfo("runway-demo", "2.0.1", sites));
|
||||
return MockMvcBuilders.standaloneSetup(controller).build();
|
||||
}
|
||||
|
||||
private DemoConsoleController.Screen screen(MvcResult result) {
|
||||
return (DemoConsoleController.Screen) result.getModelAndView().getModel().get("rd");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theScreenRendersInsideTheConsoleShell() throws Exception {
|
||||
catalog.entry("acme", new CatalogEntry("pages", ContentRef.of("about", "/about", Map.of(), List.of(),
|
||||
Map.of("en", "About"), Map.of(), "about", null), List.of(new LocalizedUrl(Locale.ENGLISH, "/about",
|
||||
"/about")), "/about"));
|
||||
MvcResult result = mvc.perform(get(BASE))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(view().name(ConsoleScreen.LAYOUT_VIEW))
|
||||
.andExpect(model().attribute(ConsoleScreen.CONTENT_TEMPLATE, "__plugin__/runway-demo/console"))
|
||||
.andExpect(model().attribute(ConsoleScreen.PAGE_TITLE_KEY, "runwaydemo.console.title"))
|
||||
.andReturn();
|
||||
DemoConsoleController.Screen screen = screen(result);
|
||||
assertEquals("acme", screen.site().id(), "the site comes from RequestContext");
|
||||
assertEquals("2.0.1", screen.pluginVersion());
|
||||
assertEquals(1, screen.noteCount(), "the welcome note");
|
||||
assertEquals(1, screen.catalogTotal());
|
||||
assertEquals("/about", screen.catalog().getFirst().path());
|
||||
assertNull(screen.showcaseText());
|
||||
assertEquals("", screen.starterPath());
|
||||
assertNull(screen.pathCheck());
|
||||
}
|
||||
|
||||
@Test
|
||||
void openingTheScreenWritesNothingAndTheFirstNoteKeepsTheWelcome() throws Exception {
|
||||
Path pluginFolder = sites.resolve("acme").resolve("plugins").resolve("runway-demo");
|
||||
mvc.perform(get(BASE)).andExpect(status().isOk());
|
||||
mvc.perform(get(BASE)).andExpect(status().isOk());
|
||||
assertFalse(Files.exists(pluginFolder), "a GET created no notes.yml, not even the plugin's folder");
|
||||
|
||||
mvc.perform(post(BASE + "/notes").param("text", "First")).andExpect(redirectedUrl(BASE));
|
||||
List<Note> stored = notes.list("acme");
|
||||
assertEquals(List.of(DemoNotesStore.WELCOME_ID, stored.get(1).id()), stored.stream().map(Note::id).toList(),
|
||||
"the first POST writes the welcome the screen was showing, then the new note");
|
||||
assertTrue(Files.isRegularFile(pluginFolder.resolve(DemoNotesStore.FILE)));
|
||||
assertEquals(2, screen(mvc.perform(get(BASE)).andReturn()).noteCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theApplicationConsoleHasNoSiteSoTheScreenIsNotFound() throws Exception {
|
||||
mvcFor(new FakeSiteServices().site(SITE)).perform(get(BASE)).andExpect(status().isNotFound());
|
||||
mvcFor(new FakeSiteServices().site(SITE)).perform(post(BASE + "/notes").param("text", "x"))
|
||||
.andExpect(status().isNotFound());
|
||||
assertEquals(1, notes.count("acme"), "nothing was written");
|
||||
}
|
||||
|
||||
@Test
|
||||
void addANote() throws Exception {
|
||||
mvc.perform(post(BASE + "/notes").param("text", "Remember the milk"))
|
||||
.andExpect(redirectedUrl(BASE))
|
||||
.andExpect(flash().attribute(DemoConsoleController.FLASH, "Note added."));
|
||||
Note last = notes.list("acme").getLast();
|
||||
assertEquals("Remember the milk", last.text());
|
||||
assertEquals(Note.ORIGIN_CONSOLE, last.origin());
|
||||
mvc.perform(post(BASE + "/notes").param("text", " "))
|
||||
.andExpect(redirectedUrl(BASE))
|
||||
.andExpect(flash().attribute(DemoConsoleController.FLASH_ERROR, "Write something first."));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishAndUnpublishTheShowcaseAnnounceAndReachTheListener() throws Exception {
|
||||
mvc.perform(post(BASE + "/showcase").param("text", "Fresh"))
|
||||
.andExpect(flash().attribute(DemoConsoleController.FLASH, "Showcase published at /demo/showcase."));
|
||||
assertEquals(1, events.announced().size(), "ContentChanges.changed was called");
|
||||
assertEquals("content", activity.recent("acme").getFirst().cause(), "…and the CONSUMER listener saw it");
|
||||
assertEquals("Fresh", screen(mvc.perform(get(BASE)).andReturn()).showcaseText());
|
||||
|
||||
mvc.perform(post(BASE + "/showcase/unpublish"))
|
||||
.andExpect(flash().attribute(DemoConsoleController.FLASH, "Showcase unpublished."));
|
||||
mvc.perform(post(BASE + "/showcase/unpublish"))
|
||||
.andExpect(flash().attribute(DemoConsoleController.FLASH, "No showcase was published."));
|
||||
assertEquals(2, events.announced().size(), "an unpublish of nothing announces nothing");
|
||||
mvc.perform(post(BASE + "/showcase").param("text", ""))
|
||||
.andExpect(flash().attribute(DemoConsoleController.FLASH_ERROR, "Write something first."));
|
||||
}
|
||||
|
||||
@Test
|
||||
void installingTheStarterPageNeedsEditPagesAndReportsTheOutcome() throws Exception {
|
||||
mvc.perform(post(BASE + "/install-page"))
|
||||
.andExpect(flash().attribute(DemoConsoleController.FLASH_ERROR,
|
||||
"Installing a page needs the permission to edit pages."));
|
||||
assertTrue(kernel.installs().isEmpty(), "nothing installed without EDIT_PAGES");
|
||||
|
||||
kernel.grant("EDIT_PAGES");
|
||||
mvc.perform(post(BASE + "/install-page"))
|
||||
.andExpect(flash().attribute(DemoConsoleController.FLASH, "Demo page published at /demo."));
|
||||
StarterPage page = kernel.installs().getFirst();
|
||||
assertEquals("runway-demo", page.slug());
|
||||
assertEquals("/demo", page.path());
|
||||
assertTrue(page.noindex(), "a demo page is kept out of search engines");
|
||||
assertTrue(page.html().contains("data-widget=\"demo-notice/page\"")
|
||||
&& page.html().contains("data-widget=\"demo-feedback/page\""), page.html());
|
||||
assertTrue(page.logic().contains("~{${master} :: head}"), "chrome by the ${master} variable");
|
||||
|
||||
mvc.perform(post(BASE + "/install-page"))
|
||||
.andExpect(flash().attribute(DemoConsoleController.FLASH,
|
||||
"A demo page already exists at /demo; nothing changed."));
|
||||
assertEquals("/demo", screen(mvc.perform(get(BASE)).andReturn()).starterPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyInstallOutcomeHasWords() {
|
||||
DemoConsoleController controller = new DemoConsoleController(kernel, kernel, kernel, kernel, catalog, notes,
|
||||
showcase, activity, new PluginInfo("runway-demo", "2.0.1", sites));
|
||||
assertEquals("Demo page created at /demo and waiting in the review queue.", controller.describe(
|
||||
new InstallResult(InstallResult.Outcome.PENDING_REVIEW, "/demo", List.of())));
|
||||
assertEquals("Demo page created at /demo as a draft: the quality checks blocked publishing."
|
||||
+ " h1.missing: No heading", controller.describe(new InstallResult(
|
||||
InstallResult.Outcome.DRAFT_BLOCKED, "/demo", List.of(Finding.error("h1.missing", "No heading")))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedInstallIsReportedNotThrown() throws Exception {
|
||||
kernel.grant("EDIT_PAGES");
|
||||
SitePages failing = new SitePages() {
|
||||
@Override
|
||||
public Optional<String> pathOf(String siteId, String slug) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public InstallResult install(String siteId, StarterPage page) {
|
||||
throw new IllegalStateException("another page serves /demo");
|
||||
}
|
||||
};
|
||||
DemoConsoleController controller = new DemoConsoleController(kernel, kernel, kernel, failing, catalog, notes,
|
||||
showcase, activity, new PluginInfo("runway-demo", "2.0.1", sites));
|
||||
MockMvcBuilders.standaloneSetup(controller).build().perform(post(BASE + "/install-page"))
|
||||
.andExpect(flash().attribute(DemoConsoleController.FLASH_ERROR, "The demo page could not be installed."));
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePathCheckAsksTheCatalog() throws Exception {
|
||||
catalog.page("acme", "/about", Locale.ENGLISH, "about").route("/sitemap.xml");
|
||||
DemoConsoleController.PathCheck owned = screen(mvc.perform(get(BASE).param("path", " /about "))
|
||||
.andReturn()).pathCheck();
|
||||
assertEquals(new DemoConsoleController.PathCheck("/about", true, true, "about"), owned);
|
||||
DemoConsoleController.PathCheck route = screen(mvc.perform(get(BASE).param("path", "/sitemap.xml"))
|
||||
.andReturn()).pathCheck();
|
||||
assertEquals(new DemoConsoleController.PathCheck("/sitemap.xml", true, false, null), route);
|
||||
DemoConsoleController.PathCheck reserved = screen(mvc.perform(get(BASE).param("path", "/__admin"))
|
||||
.andReturn()).pathCheck();
|
||||
assertEquals(false, reserved.servable());
|
||||
}
|
||||
|
||||
@Test
|
||||
void refreshDropsTheCachedListing() throws Exception {
|
||||
mvc.perform(post(BASE + "/catalog/refresh"))
|
||||
.andExpect(flash().attribute(DemoConsoleController.FLASH, "Content listing refreshed."));
|
||||
assertEquals(List.of("acme"), catalog.refreshed());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/** The notes store over the kernel's per-site files (the testkit's {@code TempDirSiteFiles}, with its confinement). */
|
||||
class DemoNotesStoreTest {
|
||||
|
||||
@TempDir
|
||||
Path sites;
|
||||
private DemoNotesStore store;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
Files.createDirectories(sites.resolve("acme"));
|
||||
store = new DemoNotesStore(new TempDirSiteFiles(sites, "runway-demo"));
|
||||
}
|
||||
|
||||
private Path file(String site) {
|
||||
return sites.resolve(site).resolve("plugins").resolve("runway-demo").resolve(DemoNotesStore.FILE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theNotesLiveInThePluginsOwnFolderOfTheSite() {
|
||||
store.append("acme", "hello", Note.ORIGIN_CONSOLE);
|
||||
assertTrue(Files.isRegularFile(file("acme")), "sites/acme/plugins/runway-demo/notes.yml");
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsShowTheWelcomeNoteButNeverWriteAFile() {
|
||||
assertEquals(1, store.count("acme"));
|
||||
Note welcome = store.list("acme").getFirst();
|
||||
assertEquals(DemoNotesStore.WELCOME_ID, welcome.id());
|
||||
assertEquals(Note.ORIGIN_SYSTEM, welcome.origin());
|
||||
assertEquals("", welcome.createdAt(), "a note that is only shown has no time");
|
||||
assertEquals(List.of(welcome), store.recent("acme", 10));
|
||||
assertFalse(Files.exists(file("acme")), "a read wrote nothing");
|
||||
assertFalse(Files.exists(file("acme").getParent()), "not even the plugin's folder");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theFirstAppendKeepsTheWelcomeNoteTheSiteWasShowing() {
|
||||
assertEquals(2, store.append("acme", "first", Note.ORIGIN_CONSOLE), "the welcome and the new note");
|
||||
assertTrue(Files.isRegularFile(file("acme")));
|
||||
List<Note> notes = store.list("acme");
|
||||
assertEquals(2, notes.size());
|
||||
Note welcome = notes.getFirst();
|
||||
assertEquals(DemoNotesStore.WELCOME_ID, welcome.id(), "the same note the site was showing");
|
||||
assertEquals(DemoNotesStore.welcome().text(), welcome.text());
|
||||
assertFalse(welcome.createdAt().isEmpty(), "stored with the time of the first write");
|
||||
assertEquals(welcome.createdAt(), notes.get(1).createdAt());
|
||||
assertEquals("first", notes.get(1).text());
|
||||
assertEquals(3, store.append("acme", "second", Note.ORIGIN_CONSOLE), "the welcome is written once");
|
||||
}
|
||||
|
||||
@Test
|
||||
void appendKeepsOrderOriginAndStripsAndCapsTheText() {
|
||||
store.append("acme", " first ", Note.ORIGIN_CONSOLE);
|
||||
store.append("acme", "x".repeat(DemoNotesStore.MAX_TEXT + 50), Note.ORIGIN_VISITOR);
|
||||
List<Note> notes = store.list("acme");
|
||||
assertEquals(3, notes.size(), "the welcome, then the two notes");
|
||||
assertEquals("first", notes.get(1).text());
|
||||
assertEquals(Note.ORIGIN_CONSOLE, notes.get(1).origin());
|
||||
assertEquals(DemoNotesStore.MAX_TEXT, notes.get(2).text().length());
|
||||
assertEquals(Note.ORIGIN_VISITOR, notes.get(2).origin());
|
||||
assertEquals(List.of(notes.get(2), notes.get(1), notes.get(0)), store.recent("acme", 5),
|
||||
"recent is newest first");
|
||||
assertEquals(List.of(notes.get(2)), store.recent("acme", 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theFileIsBoundedToTheNewestNotes() {
|
||||
for (int i = 0; i < DemoNotesStore.MAX_NOTES + 3; i++) {
|
||||
store.append("acme", "note " + i, Note.ORIGIN_CONSOLE);
|
||||
}
|
||||
List<Note> notes = store.list("acme");
|
||||
assertEquals(DemoNotesStore.MAX_NOTES, notes.size());
|
||||
assertEquals("note 3", notes.getFirst().text(), "the oldest were dropped");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sitesAreIsolated() throws IOException {
|
||||
Files.createDirectories(sites.resolve("other"));
|
||||
store.append("acme", "only acme", Note.ORIGIN_CONSOLE);
|
||||
assertFalse(store.list("other").stream().anyMatch(n -> n.text().equals("only acme")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownKeyInTheFileIsIgnoredAndAMissingOriginReadsAsSystem() throws IOException {
|
||||
Files.createDirectories(file("acme").getParent());
|
||||
Files.writeString(file("acme"), "notes:\n- id: n-1\n text: old\n createdAt: '2026-01-01T00:00:00Z'\n"
|
||||
+ " colour: blue\nfutureKey: 1\n", StandardCharsets.UTF_8);
|
||||
List<Note> notes = store.list("acme");
|
||||
assertEquals(1, notes.size());
|
||||
assertEquals("old", notes.getFirst().text());
|
||||
assertEquals(Note.ORIGIN_SYSTEM, notes.getFirst().origin());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnreadableFileDegradesReadsButNeverLetsAnAppendOverwriteIt() throws IOException {
|
||||
Files.createDirectories(file("acme").getParent());
|
||||
Files.writeString(file("acme"), "notes: [ this is: not: valid", StandardCharsets.UTF_8);
|
||||
assertEquals(List.of(), store.list("acme"), "a console read degrades to empty");
|
||||
assertEquals(0, store.count("acme"));
|
||||
assertThrows(UncheckedIOException.class, () -> store.append("acme", "x", Note.ORIGIN_CONSOLE),
|
||||
"an append refuses rather than rewriting the file from nothing");
|
||||
assertEquals("notes: [ this is: not: valid", Files.readString(file("acme")), "the file is untouched");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSiteWhoseFolderIsGoneCannotBeWrittenAndReadsTheUnsavedWelcome() {
|
||||
assertThrows(UncheckedIOException.class, () -> store.append("ghost", "x", Note.ORIGIN_CONSOLE));
|
||||
assertEquals(List.of(DemoNotesStore.welcome()), store.list("ghost"), "the welcome is shown, unsaved");
|
||||
assertFalse(Files.exists(sites.resolve("ghost")), "nothing was created for a site that does not exist");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnsafeSiteIdIsRefusedBeforeAnyIo() {
|
||||
assertThrows(IllegalArgumentException.class, () -> store.append("../acme", "x", Note.ORIGIN_CONSOLE));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Deque;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import mx.quest.runway.spi.ContentSource;
|
||||
import mx.quest.runway.spi.ContentWidget;
|
||||
import mx.quest.runway.spi.EndpointContributor;
|
||||
import mx.quest.runway.spi.HeadContributor;
|
||||
import mx.quest.runway.spi.PageQualityCheck;
|
||||
import mx.quest.runway.spi.model.PluginInfo;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.ConsoleScreen;
|
||||
import mx.quest.runway.spi.service.ContentChanges;
|
||||
import mx.quest.runway.spi.service.PluginLifecycle;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.PluginSiteFiles;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
import mx.quest.runway.spi.testkit.EventDispatch;
|
||||
import mx.quest.runway.spi.testkit.FakeContentCatalog;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.core.annotation.AnnotatedElementUtils;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
|
||||
/**
|
||||
* The plugin's contract with the host, checked at build time — the same things the kernel's load-time checks warn
|
||||
* about (and refuse from Runway 1.0): wiring over SPI services only, the bean-name rule, the allowed Spring surface,
|
||||
* the console controller's mappings and gates, the bean names the templates reference, the descriptor (SPI floor,
|
||||
* release version, personal data), the i18n bundles, and that the compiled classes link nothing of the host but the
|
||||
* SPI.
|
||||
*/
|
||||
class DemoPluginConfigTest {
|
||||
|
||||
private static final String PREFIX = "runwayDemo";
|
||||
|
||||
private static Set<String> beanMethodNames() {
|
||||
return Arrays.stream(DemoPluginConfig.class.getDeclaredMethods())
|
||||
.filter(m -> m.isAnnotationPresent(Bean.class))
|
||||
.map(Method::getName)
|
||||
.collect(Collectors.toCollection(TreeSet::new));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> descriptor() throws IOException {
|
||||
try (Reader in = Files.newBufferedReader(Path.of("plugin.yml"), StandardCharsets.UTF_8)) {
|
||||
return (Map<String, Object>) new Yaml().load(in);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void wiresEverythingFromSpiServicesAlone(@TempDir Path sites) throws IOException {
|
||||
Files.createDirectories(sites.resolve("acme"));
|
||||
FakeSiteServices kernel = new FakeSiteServices()
|
||||
.site(new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null))
|
||||
.page("acme", DemoConsoleController.STARTER_SLUG, "/demo-moved");
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
|
||||
ctx.registerBean(PluginSettings.class, () -> new FakePluginSettings()
|
||||
.secret("acme", "analytics.site-token", "t0k3n"));
|
||||
ctx.registerBean(PluginSiteFiles.class, () -> new TempDirSiteFiles(sites, "runway-demo"));
|
||||
ctx.registerBean(ContentChanges.class, () -> new EventDispatch("runway-demo", Set.of("runway-demo")));
|
||||
ctx.registerBean(PluginInfo.class, () -> new PluginInfo("runway-demo", "2.0.1", sites));
|
||||
ctx.registerBean(FakeSiteServices.class, () -> kernel);
|
||||
ctx.registerBean(FakeContentCatalog.class, () -> new FakeContentCatalog().site("acme"));
|
||||
ctx.register(DemoPluginConfig.class);
|
||||
ctx.refresh();
|
||||
|
||||
assertEquals(Set.of("runwayDemoAnalyticsHead"), ctx.getBeansOfType(HeadContributor.class).keySet());
|
||||
assertEquals(Set.of("runwayDemoNoticeWidget", "runwayDemoFeedbackWidget"),
|
||||
ctx.getBeansOfType(ContentWidget.class).keySet());
|
||||
assertEquals(Set.of("runwayDemoMetaLengthCheck"), ctx.getBeansOfType(PageQualityCheck.class).keySet());
|
||||
assertEquals(Set.of("runwayDemoEndpoints"), ctx.getBeansOfType(EndpointContributor.class).keySet());
|
||||
assertEquals(Set.of("runwayDemoShowcaseSource"), ctx.getBeansOfType(ContentSource.class).keySet());
|
||||
assertEquals(Set.of("runwayDemoShowcaseSource", "runwayDemoActivity"),
|
||||
ctx.getBeansOfType(SiteEventListener.class).keySet(), "one SOURCE and one CONSUMER listener");
|
||||
assertEquals(Set.of("runwayDemoLifecycle"), ctx.getBeansOfType(PluginLifecycle.class).keySet());
|
||||
assertNotNull(ctx.getBean("runwayDemoConsoleController", DemoConsoleController.class));
|
||||
assertNotNull(ctx.getBean("runwayDemoAppProps", DemoAppProps.class));
|
||||
|
||||
DemoAdminModel model = ctx.getBean("runwayDemoAdminModel", DemoAdminModel.class);
|
||||
assertEquals(1, model.noteCount("acme"), "the notes store works over the injected site files");
|
||||
assertEquals("Acme", model.siteName("acme"), "…the site name comes from Sites");
|
||||
assertEquals("/demo-moved", model.demoPagePath("acme"), "…the page path from SitePages");
|
||||
assertTrue(model.siteTokenConfigured("acme"), "…the secret's presence from PluginSettings");
|
||||
assertEquals("2.0.1", model.pluginVersion(), "…the version from PluginInfo");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAdminModelIsNullSafeForTheApplicationConsole(@TempDir Path sites) {
|
||||
DemoAdminModel model = new DemoAdminModel(new DemoNotesStore(new TempDirSiteFiles(sites, "runway-demo")),
|
||||
new DemoAppProps(), new FakePluginSettings(), new FakeSiteServices(), new FakeSiteServices(),
|
||||
new PluginInfo("runway-demo", "2.0.1", sites));
|
||||
assertEquals(0, model.noteCount(null));
|
||||
assertEquals(List.of(), model.recentNotes(" "));
|
||||
assertEquals("", model.siteName(null));
|
||||
assertEquals("", model.demoPagePath(null));
|
||||
assertFalse(model.siteTokenConfigured(null));
|
||||
assertEquals("ghost", model.siteName("ghost"), "an unknown site shows its id");
|
||||
assertEquals(mx.quest.runway.spi.RunwaySpi.VERSION, model.builtSpi());
|
||||
assertEquals(mx.quest.runway.spi.RunwaySpi.runtimeVersion(), model.runningSpi());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyBeanNameStartsWithThePluginIdInLowerCamelCase() {
|
||||
Set<String> names = beanMethodNames();
|
||||
assertEquals(Set.of("runwayDemoAppProps", "runwayDemoNotesStore", "runwayDemoShowcaseStore",
|
||||
"runwayDemoLifecycle", "runwayDemoActivity", "runwayDemoAnalyticsHead", "runwayDemoNoticeWidget",
|
||||
"runwayDemoFeedbackWidget", "runwayDemoMetaLengthCheck", "runwayDemoEndpoints",
|
||||
"runwayDemoShowcaseSource", "runwayDemoAdminModel", "runwayDemoConsoleController"), names);
|
||||
for (Method m : DemoPluginConfig.class.getDeclaredMethods()) {
|
||||
Bean bean = m.getAnnotation(Bean.class);
|
||||
if (bean != null) {
|
||||
assertEquals(0, bean.name().length + bean.value().length, "the method name is the bean name: " + m);
|
||||
}
|
||||
}
|
||||
assertFalse(AnnotatedElementUtils.hasAnnotation(DemoPluginConfig.class,
|
||||
org.springframework.boot.context.properties.EnableConfigurationProperties.class),
|
||||
"@EnableConfigurationProperties would register a '<prefix>-<class>' bean name");
|
||||
}
|
||||
|
||||
/** Servlet filters, security chains and post-processors are outside what a plugin may contribute. */
|
||||
@Test
|
||||
void noBeanIsOfAForbiddenSpringType() {
|
||||
Set<String> forbidden = Set.of("jakarta.servlet.Filter", "org.springframework.security.web.SecurityFilterChain",
|
||||
"org.springframework.boot.web.servlet.FilterRegistrationBean",
|
||||
"org.springframework.beans.factory.config.BeanPostProcessor",
|
||||
"org.springframework.beans.factory.config.BeanFactoryPostProcessor");
|
||||
for (Method m : DemoPluginConfig.class.getDeclaredMethods()) {
|
||||
if (!m.isAnnotationPresent(Bean.class)) {
|
||||
continue;
|
||||
}
|
||||
Deque<Class<?>> queue = new ArrayDeque<>(List.of(m.getReturnType()));
|
||||
Set<Class<?>> seen = new HashSet<>();
|
||||
while (!queue.isEmpty()) {
|
||||
Class<?> type = queue.pop();
|
||||
if (!seen.add(type)) {
|
||||
continue;
|
||||
}
|
||||
assertFalse(forbidden.contains(type.getName()), m.getName() + " is a " + type.getName());
|
||||
if (type.getSuperclass() != null) {
|
||||
queue.add(type.getSuperclass());
|
||||
}
|
||||
queue.addAll(List.of(type.getInterfaces()));
|
||||
}
|
||||
assertFalse(AnnotatedElementUtils.hasAnnotation(m.getReturnType(),
|
||||
org.springframework.web.bind.annotation.ControllerAdvice.class), "no @ControllerAdvice needed");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theConsoleControllerIsAConsoleScreenGatedAndMappedUnderItsOwnPrefix() {
|
||||
Class<?> type = DemoConsoleController.class;
|
||||
assertTrue(AnnotatedElementUtils.hasAnnotation(type, Controller.class));
|
||||
assertTrue(type.isAnnotationPresent(ConsoleScreen.class), "the kernel fills the console shell for it");
|
||||
assertEquals(List.of("/__admin/runway-demo"),
|
||||
List.of(AnnotatedElementUtils.findMergedAnnotation(type, RequestMapping.class).path()));
|
||||
int handlers = 0;
|
||||
int gets = 0;
|
||||
for (Method m : type.getDeclaredMethods()) {
|
||||
RequestMapping mapping = AnnotatedElementUtils.findMergedAnnotation(m, RequestMapping.class);
|
||||
if (mapping == null) {
|
||||
continue;
|
||||
}
|
||||
handlers++;
|
||||
PreAuthorize gate = m.getAnnotation(PreAuthorize.class);
|
||||
assertNotNull(gate, m.getName() + " must be gated");
|
||||
assertEquals("@authz.may('runway-demo|manage-notes')", gate.value());
|
||||
for (String path : mapping.path()) {
|
||||
assertTrue(path.isEmpty() || path.startsWith("/"), path);
|
||||
}
|
||||
if (m.isAnnotationPresent(GetMapping.class)) {
|
||||
gets++;
|
||||
assertEquals("screen", m.getName(), "only the read-only screen answers GET");
|
||||
}
|
||||
}
|
||||
assertEquals(6, handlers, "the screen and five POST actions");
|
||||
assertEquals(1, gets);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTemplatesReferenceOnlyOurOwnBeansAndAuthz() throws IOException {
|
||||
Set<String> referenced = new TreeSet<>();
|
||||
try (Stream<Path> files = Files.list(Path.of("templates"))) {
|
||||
for (Path file : files.filter(p -> p.toString().endsWith(".th.xml")).toList()) {
|
||||
String live = Files.readString(file, StandardCharsets.UTF_8).replaceAll("(?s)<!--.*?-->", "");
|
||||
Matcher m = Pattern.compile("@(\\w+)\\.").matcher(live);
|
||||
while (m.find()) {
|
||||
referenced.add(m.group(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
assertEquals(Set.of("authz", "runwayDemoAdminModel"), referenced);
|
||||
assertTrue(beanMethodNames().contains("runwayDemoAdminModel"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDescriptorDeclaresTheSpiFloorTheReleaseVersionAndTheConsoleMenu() throws IOException {
|
||||
Map<String, Object> yml = descriptor();
|
||||
assertEquals(">=1.0.0", yml.get("requiresSpi"), "built for the frozen SPI 1.0.0 contract");
|
||||
String pom = Files.readString(Path.of("pom.xml"), StandardCharsets.UTF_8);
|
||||
Matcher version = Pattern.compile("<artifactId>runway-plugin-runway-demo</artifactId>\\s*<version>([^<]+)")
|
||||
.matcher(pom);
|
||||
assertTrue(version.find());
|
||||
assertEquals("2.1.0", version.group(1));
|
||||
assertEquals(version.group(1), String.valueOf(yml.get("version")), "plugin.yml and pom.xml agree");
|
||||
assertFalse(pom.contains("<artifactId>runway-app</artifactId>"), "no runway-app dependency in any scope");
|
||||
assertTrue(pom.contains("<project.build.outputTimestamp>2026-10-21T17:23:00Z</project.build.outputTimestamp>"));
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, Object>> menu = (List<Map<String, Object>>) yml.get("menu");
|
||||
assertEquals(DemoConsoleController.BASE, menu.get(0).get("path"), "the menu opens the console screen");
|
||||
assertEquals(DemoEndpoints.PERMISSION, menu.get(0).get("permission"), "the FULL namespaced key");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theReleaseZipIsNamedAfterThePluginIdLikeEveryOtherPluginAndTheJarKeepsItsName() throws IOException {
|
||||
String id = String.valueOf(descriptor().get("id"));
|
||||
String pom = Files.readString(Path.of("pom.xml"), StandardCharsets.UTF_8).replaceAll("(?s)<!--.*?-->", "");
|
||||
// publish-plugin-release.sh uploads target/runway-plugin-<id>-<version>.zip under the tag <id>-<version>.
|
||||
assertTrue(pom.contains("<artifactId>runway-plugin-" + id + "</artifactId>"), "artifactId runway-plugin-" + id);
|
||||
assertTrue(pom.contains("<zip destfile=\"${project.build.directory}/${project.artifactId}-${project.version}"
|
||||
+ ".zip\">"), "the zip is named after the artifactId");
|
||||
// The kernel loads every *.jar in the plugin's folder: a renamed jar copied over a 2.0.0 folder would load
|
||||
// beside the old one. So the jar keeps the name 2.0.0 shipped.
|
||||
assertTrue(pom.contains("<finalName>runway-plugin-demo</finalName>"), "the jar keeps its 2.0.0 name");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void theNotesFileIsDeclaredPersonalDataSoTransferCopiesLeaveItOut() throws IOException {
|
||||
Map<String, Object> siteData = (Map<String, Object>) descriptor().get("siteData");
|
||||
assertNotNull(siteData, "plugin.yml declares siteData");
|
||||
assertEquals(List.of(DemoNotesStore.FILE), siteData.get("personal"),
|
||||
"exactly the file holding what people typed; the showcase is published content");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void theSiteTokenIsDeclaredASecretAndEveryReadSettingIsDeclared() throws IOException {
|
||||
List<Map<String, Object>> schema = (List<Map<String, Object>>) descriptor().get("siteSettings");
|
||||
Map<String, Object> types = schema.stream()
|
||||
.collect(Collectors.toMap(s -> (String) s.get("key"), s -> s.get("type")));
|
||||
assertEquals("secret", types.get("analytics.site-token"),
|
||||
"PluginSettings.secret hands out only keys declared type: secret");
|
||||
String code = readAll(Path.of("src/main/java"));
|
||||
Matcher reads = Pattern.compile("\\.(?:bool|string|integer|decimal|list)\\(\"([a-z.-]+)\"").matcher(code);
|
||||
int count = 0;
|
||||
while (reads.find()) {
|
||||
count++;
|
||||
assertTrue(types.containsKey(reads.group(1)), "read but not declared: " + reads.group(1));
|
||||
}
|
||||
assertTrue(count >= 8, "the per-site reads were found (" + count + ")");
|
||||
}
|
||||
|
||||
private static String readAll(Path root) throws IOException {
|
||||
StringBuilder all = new StringBuilder();
|
||||
try (Stream<Path> files = Files.walk(root)) {
|
||||
for (Path f : files.filter(Files::isRegularFile).toList()) {
|
||||
all.append(Files.readString(f, StandardCharsets.UTF_8)).append('\n');
|
||||
}
|
||||
}
|
||||
return all.toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEnglishAndSpanishBundlesDefineTheSameKeysAndEveryKeyUsedExists() throws IOException {
|
||||
Set<String> en = keys("i18n/messages.properties");
|
||||
assertEquals(en, keys("i18n/messages_es.properties"));
|
||||
Set<String> used = new TreeSet<>();
|
||||
Matcher code = Pattern.compile("\"(runwaydemo\\.[A-Za-z.]+)\"").matcher(readAll(Path.of("src/main/java")));
|
||||
while (code.find()) {
|
||||
used.add(code.group(1));
|
||||
}
|
||||
Matcher template = Pattern.compile("#\\{(runwaydemo\\.[A-Za-z.]+)").matcher(readAll(Path.of("templates")));
|
||||
while (template.find()) {
|
||||
used.add(template.group(1));
|
||||
}
|
||||
Matcher descriptor = Pattern.compile("label: (runwaydemo\\.[A-Za-z.]+)")
|
||||
.matcher(Files.readString(Path.of("plugin.yml"), StandardCharsets.UTF_8));
|
||||
while (descriptor.find()) {
|
||||
used.add(descriptor.group(1));
|
||||
}
|
||||
used.removeIf(en::contains);
|
||||
assertEquals(Set.of(), used, "keys used but missing from the bundle");
|
||||
}
|
||||
|
||||
private static Set<String> keys(String file) throws IOException {
|
||||
Properties p = new Properties();
|
||||
try (Reader in = Files.newBufferedReader(Path.of(file), StandardCharsets.UTF_8)) {
|
||||
p.load(in);
|
||||
}
|
||||
return new TreeSet<>(p.stringPropertyNames());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCompiledClassesLinkNoHostInternals() throws IOException {
|
||||
Path classes = Path.of("target", "classes");
|
||||
Pattern host = Pattern.compile("mx[/.]quest[/.]runway[/.](?!spi[/.])[\\w/.$]*");
|
||||
List<String> problems = new ArrayList<>();
|
||||
int scanned = 0;
|
||||
try (Stream<Path> files = Files.walk(classes)) {
|
||||
for (Path file : files.filter(p -> p.toString().endsWith(".class")).toList()) {
|
||||
scanned++;
|
||||
String rel = classes.relativize(file).toString().replace('\\', '/');
|
||||
if (rel.startsWith("mx/quest/runway/")) {
|
||||
problems.add(rel + " lives under mx.quest.runway");
|
||||
}
|
||||
// The constant pool holds class names and descriptors as (modified) UTF-8; Latin-1 keeps every byte
|
||||
// as one char, so an ASCII pattern finds them without parsing the class file.
|
||||
Matcher m = host.matcher(new String(Files.readAllBytes(file), StandardCharsets.ISO_8859_1));
|
||||
while (m.find()) {
|
||||
problems.add(rel + " → " + m.group());
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(scanned >= 18, "the compiled classes were found (" + scanned + ")");
|
||||
assertTrue(problems.isEmpty(), "host linkage: " + problems);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRemovedSeamsAreGone() {
|
||||
for (String gone : List.of("DemoTimingFilter", "DemoNotesBackup", "DemoConfigReactor", "SiteConfig")) {
|
||||
assertNull(classOrNull("mx.quest.demo." + gone), gone + " was removed in 2.0.0");
|
||||
}
|
||||
assertInstanceOf(PluginLifecycle.class, new DemoLifecycle());
|
||||
}
|
||||
|
||||
private static Class<?> classOrNull(String name) {
|
||||
try {
|
||||
return Class.forName(name);
|
||||
} catch (ClassNotFoundException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import mx.quest.runway.spi.ContentSource;
|
||||
import mx.quest.runway.spi.model.CatalogChange;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.SiteLifecycleEvent;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
import mx.quest.runway.spi.testkit.EventDispatch;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* The showcase content source and its store: writes are announced with {@code ContentChanges} (the testkit's
|
||||
* {@link EventDispatch}, which applies the kernel's refusal rules and phase order), the source serves what was
|
||||
* published, and its {@code SOURCE}-phase listener drops the cache on the events that mean the file changed under it.
|
||||
*/
|
||||
class DemoShowcaseTest {
|
||||
|
||||
private static final SiteView SITE = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null);
|
||||
|
||||
@TempDir
|
||||
Path sites;
|
||||
private EventDispatch events;
|
||||
private AtomicLong nanos;
|
||||
private DemoShowcaseStore store;
|
||||
private DemoShowcaseSource source;
|
||||
private FakeSiteServices kernel;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
Files.createDirectories(sites.resolve("acme"));
|
||||
events = new EventDispatch("runway-demo", Set.of(DemoShowcaseSource.SOURCE_KEY));
|
||||
nanos = new AtomicLong();
|
||||
store = new DemoShowcaseStore(new TempDirSiteFiles(sites, "runway-demo"), events, nanos::get);
|
||||
kernel = new FakeSiteServices().site(SITE);
|
||||
source = new DemoShowcaseSource(store, kernel);
|
||||
events.listener(source);
|
||||
}
|
||||
|
||||
private Path file() {
|
||||
return sites.resolve("acme/plugins/runway-demo").resolve(DemoShowcaseStore.FILE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nothingIsServedUntilAShowcaseIsPublished() {
|
||||
assertEquals(List.of(), source.enumerate(SITE));
|
||||
assertTrue(source.resolve(SITE, DemoShowcaseSource.PATH, Locale.ENGLISH).isEmpty());
|
||||
assertTrue(source.body(SITE, DemoShowcaseSource.ID, Locale.ENGLISH).bodyHtml().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishWritesTheFileThenAnnouncesTheChangeOfItsOwnSource() {
|
||||
store.publish("acme", " Hello <world> ");
|
||||
assertTrue(Files.isRegularFile(file()));
|
||||
List<CatalogChange> announced = events.announced();
|
||||
assertEquals(1, announced.size());
|
||||
assertEquals(CatalogChange.Cause.CONTENT, announced.getFirst().cause());
|
||||
assertEquals("runway-demo", announced.getFirst().sourceKey());
|
||||
assertEquals("showcase", announced.getFirst().id());
|
||||
assertEquals("runway-demo", announced.getFirst().pluginId());
|
||||
assertTrue(events.failures().isEmpty(), events.failures().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePublishedShowcaseIsServedAsAPageOfTheSite() {
|
||||
kernel.message("acme", "runwaydemo.showcase.title", "Our showcase");
|
||||
store.publish("acme", "Line one\r\nLine <two> & three");
|
||||
List<ContentRef> refs = source.enumerate(SITE);
|
||||
assertEquals(1, refs.size());
|
||||
ContentRef ref = refs.getFirst();
|
||||
assertEquals("showcase", ref.id());
|
||||
assertEquals("/demo/showcase", ref.path());
|
||||
assertEquals("__plugin__/runway-demo/showcase", ref.bodyTemplate());
|
||||
assertTrue(ref.published());
|
||||
assertEquals("Our showcase", ref.titleFor(Locale.ENGLISH), "the title comes from Messages.site");
|
||||
assertEquals("Line one\r\nLine <two> & three", ref.descriptionFor(Locale.ENGLISH));
|
||||
assertEquals(ref, source.resolve(SITE, "/demo/showcase", Locale.ENGLISH).orElseThrow());
|
||||
assertTrue(source.resolve(SITE, "/demo/showcase", Locale.of("es")).isEmpty(), "default language only");
|
||||
assertTrue(source.resolve(SITE, "/demo/other", Locale.ENGLISH).isEmpty());
|
||||
assertEquals("<p>Line one<br>\nLine <two> & three</p>",
|
||||
source.body(SITE, "showcase", Locale.ENGLISH).bodyHtml(), "escaped; line breaks kept");
|
||||
assertEquals("", source.body(SITE, "other", Locale.ENGLISH).bodyHtml());
|
||||
assertTrue(source.indexableText(SITE, "showcase", Locale.ENGLISH).contains("Line <two>"));
|
||||
assertTrue(source.capabilities().has(ContentSource.CAP_INDEXABLE_TEXT), "search indexes it");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRepublishMovesUpdatedAtSoTheEtagChanges() throws InterruptedException {
|
||||
store.publish("acme", "one");
|
||||
ContentRef first = source.enumerate(SITE).getFirst();
|
||||
Thread.sleep(5);
|
||||
store.publish("acme", "two");
|
||||
ContentRef second = source.enumerate(SITE).getFirst();
|
||||
assertTrue(second.updatedAt().isAfter(first.updatedAt()), first.updatedAt() + " → " + second.updatedAt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLongDescriptionIsCutAndALongTextCapped() {
|
||||
store.publish("acme", "y".repeat(DemoShowcaseStore.MAX_TEXT + 10));
|
||||
ContentRef ref = source.enumerate(SITE).getFirst();
|
||||
assertEquals(151, ref.descriptionFor(Locale.ENGLISH).length(), "150 chars and an ellipsis");
|
||||
assertEquals(DemoShowcaseStore.MAX_TEXT + 7,
|
||||
source.body(SITE, "showcase", Locale.ENGLISH).bodyHtml().length(), "<p>…</p> around the capped text");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlankShowcaseIsRefusedAndAnnouncesNothing() {
|
||||
assertThrows(IllegalArgumentException.class, () -> store.publish("acme", " "));
|
||||
assertTrue(events.announced().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unpublishDeletesAndAnnouncesOnlyWhenSomethingWasPublished() {
|
||||
assertFalse(store.unpublish("acme"), "nothing to unpublish");
|
||||
assertTrue(events.announced().isEmpty(), "and nothing announced");
|
||||
store.publish("acme", "live");
|
||||
assertTrue(store.unpublish("acme"));
|
||||
assertEquals(2, events.announced().size());
|
||||
assertFalse(Files.exists(file()));
|
||||
assertEquals(List.of(), source.enumerate(SITE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCacheServesWithinTheTtlAndRereadsAfterIt() throws IOException {
|
||||
store.publish("acme", "cached");
|
||||
store.current("acme"); // the own announcement evicted the cache; this read fills it again
|
||||
Files.writeString(file(), "text: edited by hand\nupdatedAt: '2026-01-01T00:00:00Z'\n", StandardCharsets.UTF_8);
|
||||
source.onCatalogChanged(noChange()); // an unrelated change does not evict
|
||||
assertEquals("cached", store.current("acme").orElseThrow().text(), "no announcement: the cache holds");
|
||||
nanos.addAndGet(DemoShowcaseStore.TTL.toNanos());
|
||||
assertEquals("edited by hand", store.current("acme").orElseThrow().text(), "the TTL is the backstop");
|
||||
}
|
||||
|
||||
private static CatalogChange noChange() {
|
||||
return new CatalogChange("acme", CatalogChange.Cause.PAGE, "pages", "about", null, null, null, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChangeReplayedFromAnotherNodeEvictsThisNodesCache() throws IOException {
|
||||
store.publish("acme", "before");
|
||||
Files.writeString(file(), "text: from the peer\nupdatedAt: '2026-01-01T00:00:00Z'\n", StandardCharsets.UTF_8);
|
||||
events.catalog(new CatalogChange("acme", CatalogChange.Cause.CONTENT, "runway-demo", "showcase",
|
||||
"runway-demo", null, null, false));
|
||||
assertEquals("from the peer", store.current("acme").orElseThrow().text());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWholesaleLifecycleEventEvictsAndOthersDoNot() throws IOException {
|
||||
store.publish("acme", "before");
|
||||
store.current("acme");
|
||||
Files.writeString(file(), "text: restored\nupdatedAt: '2026-01-01T00:00:00Z'\n", StandardCharsets.UTF_8);
|
||||
source.onSiteLifecycle(new SiteLifecycleEvent("acme", SiteLifecycleEvent.Kind.UPDATED, false, true));
|
||||
assertEquals("before", store.current("acme").orElseThrow().text(), "an UPDATED site keeps its files");
|
||||
events.lifecycle("acme", SiteLifecycleEvent.Kind.RESTORED, true);
|
||||
assertEquals("restored", store.current("acme").orElseThrow().text(), "a RESTORED site replaced them");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSourceListensInTheSourcePhase() {
|
||||
assertEquals(SiteEventListener.Phase.SOURCE, source.phase());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCorruptOrForeignFileServesNothing() throws IOException {
|
||||
Files.createDirectories(file().getParent());
|
||||
Files.writeString(file(), "text: [ unclosed", StandardCharsets.UTF_8);
|
||||
assertTrue(store.current("acme").isEmpty());
|
||||
assertTrue(store.current("../x").isEmpty(), "an unsafe id answers nothing rather than throwing on a request");
|
||||
}
|
||||
|
||||
@Test
|
||||
void announcingFromInsideACallbackIsRefusedByTheKernelRule() {
|
||||
EventDispatch strict = new EventDispatch("runway-demo", Set.of("runway-demo"));
|
||||
DemoShowcaseStore inner = new DemoShowcaseStore(new TempDirSiteFiles(sites, "runway-demo"), strict);
|
||||
strict.listener(new SiteEventListener() {
|
||||
@Override
|
||||
public void onSiteLifecycle(SiteLifecycleEvent event) {
|
||||
inner.publish("acme", "from a callback");
|
||||
}
|
||||
});
|
||||
strict.lifecycle("acme", SiteLifecycleEvent.Kind.UPDATED, false);
|
||||
assertEquals(1, strict.failures().size());
|
||||
assertTrue(strict.failures().getFirst() instanceof IllegalStateException);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
import mx.quest.runway.spi.model.PageMeta;
|
||||
import mx.quest.runway.spi.model.PageView;
|
||||
import mx.quest.runway.spi.model.RenderFragment;
|
||||
import mx.quest.runway.spi.model.Route;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.model.WidgetView;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* The demo's axis implementations as pure functions of their SPI inputs: no Spring, no host — the services come from
|
||||
* {@code runway-spi-testkit}, whose fakes apply the kernel's input rules.
|
||||
*/
|
||||
class DemoSpiUnitTest {
|
||||
|
||||
private static final SiteView SITE = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH),
|
||||
"https://acme.test");
|
||||
private static final PageMeta PAGE = new PageMeta("about", "About us", "A description",
|
||||
List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
|
||||
|
||||
@TempDir
|
||||
Path sites;
|
||||
private DemoNotesStore notes;
|
||||
private FakeSiteServices kernel;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
Files.createDirectories(sites.resolve("acme"));
|
||||
notes = new DemoNotesStore(new TempDirSiteFiles(sites, "runway-demo"));
|
||||
kernel = new FakeSiteServices().site(SITE);
|
||||
}
|
||||
|
||||
private static FakePluginSettings settings(Map<String, ?> stored) {
|
||||
return new FakePluginSettings().site("acme", stored);
|
||||
}
|
||||
|
||||
// --- HeadContributor -------------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void headEmitsGeneratorAndGatesAnalyticsOnTheSiteFlagAndTheAppKey() {
|
||||
DemoAppProps props = new DemoAppProps();
|
||||
props.getGenerator().setLabel("My Site");
|
||||
props.getAnalytics().setWriteKey("ENC(opaque)");
|
||||
HeadContext ctx = new HeadContext(SITE, PAGE, Locale.ENGLISH, "https://acme.test/about", null,
|
||||
List.of(), false, false);
|
||||
String on = new DemoAnalyticsHead(props, settings(Map.of("analytics.enabled", true))).render(ctx);
|
||||
assertTrue(on.contains("<meta name=\"generator\" content=\"My Site\">"), on);
|
||||
assertTrue(on.contains("data-demo-analytics") && on.contains("demo-analytics.js"), on);
|
||||
assertFalse(on.contains("ENC(opaque)"), "the key never reaches the page");
|
||||
|
||||
String off = new DemoAnalyticsHead(props, settings(Map.of())).render(ctx);
|
||||
assertFalse(off.contains("data-demo-analytics"), "analytics script absent when the site flag is off");
|
||||
assertTrue(off.contains("demo.css"), "stylesheet linked (the notice defaults on)");
|
||||
|
||||
DemoAppProps noKey = new DemoAppProps();
|
||||
assertFalse(new DemoAnalyticsHead(noKey, settings(Map.of("analytics.enabled", true))).render(ctx)
|
||||
.contains("data-demo-analytics"), "no app-level key, no script");
|
||||
assertFalse(new DemoAnalyticsHead(props, settings(Map.of("notice.enabled", false))).render(ctx)
|
||||
.contains("demo.css"), "notice off, no stylesheet");
|
||||
}
|
||||
|
||||
@Test
|
||||
void headEscapesTheGeneratorLabelAndDeclaresItsSettingsFile() {
|
||||
DemoAppProps props = new DemoAppProps();
|
||||
props.getGenerator().setLabel("<script>x</script>");
|
||||
HeadContext ctx = new HeadContext(SITE, PAGE, Locale.ENGLISH, null, null, List.of(), false, false);
|
||||
DemoAnalyticsHead head = new DemoAnalyticsHead(props, settings(Map.of()));
|
||||
String out = head.render(ctx);
|
||||
assertTrue(out.contains("<script>"), "label escaped");
|
||||
assertFalse(out.contains("<script>x</script>"), "raw label not emitted");
|
||||
assertEquals(List.of("plugins/runway-demo.yml"), head.headInputs("acme"));
|
||||
}
|
||||
|
||||
// --- ContentWidget: notice -------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void noticeRendersWhenEnabledAndIsEmptyWhenDisabled() {
|
||||
WidgetView view = new WidgetView(SITE, PAGE, Locale.ENGLISH, "n1", false, Map.of());
|
||||
RenderFragment f = new DemoNoticeWidget(new DemoAppProps(),
|
||||
settings(Map.of("notice.enabled", true, "notice.style", "warning")), kernel).render(view);
|
||||
assertFalse(f.isEmpty());
|
||||
assertTrue(f.html().contains("rw-demo-notice-warning"), f.html());
|
||||
assertTrue(f.html().contains("instance "n1"") && f.html().contains("site "Acme""),
|
||||
"the fallback text formats its arguments: " + f.html());
|
||||
|
||||
assertTrue(new DemoNoticeWidget(new DemoAppProps(), settings(Map.of("notice.enabled", false)), kernel)
|
||||
.render(view).isEmpty(), "disabled notice renders empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
void noticeUsesTheSitesMessageInTheVisitorsLocaleAndEscapesIt() {
|
||||
kernel.message("acme", "runwaydemo.notice.body", "<b>Aviso</b> {0} en {1}");
|
||||
WidgetView view = new WidgetView(SITE, PAGE, Locale.of("es"), "n1", false, Map.of());
|
||||
String html = new DemoNoticeWidget(new DemoAppProps(), settings(Map.of()), kernel).render(view).html();
|
||||
assertTrue(html.contains("<b>Aviso</b> n1 en Acme"), html);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noticeFallsBackToInfoForAnUnknownStyleAndClampsMaxChars() {
|
||||
WidgetView view = new WidgetView(SITE, PAGE, Locale.ENGLISH, "n1", false, Map.of());
|
||||
String bad = new DemoNoticeWidget(new DemoAppProps(), settings(Map.of("notice.style", "x\" onclick=\"y")),
|
||||
kernel).render(view).html();
|
||||
assertTrue(bad.contains("rw-demo-notice-info\""), bad);
|
||||
String truncated = new DemoNoticeWidget(new DemoAppProps(), settings(Map.of("notice.max-chars", 10L)), kernel)
|
||||
.render(view).html();
|
||||
assertTrue(truncated.contains(">This is th…<"), "truncated with an ellipsis: " + truncated);
|
||||
String clamped = new DemoNoticeWidget(new DemoAppProps(), settings(Map.of("notice.max-chars", -5L)), kernel)
|
||||
.render(view).html();
|
||||
assertTrue(clamped.contains(">T…<"), "a hand-edited negative cap is clamped to 1: " + clamped);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChromeNoticeShowsTheAppLevelBanner() {
|
||||
DemoAppProps props = new DemoAppProps();
|
||||
props.getBanner().setText("Maintenance tonight");
|
||||
WidgetView chrome = new WidgetView(SITE, PAGE, Locale.ENGLISH, "top", true, Map.of());
|
||||
assertTrue(new DemoNoticeWidget(props, settings(Map.of()), kernel).render(chrome).html()
|
||||
.contains("Maintenance tonight"));
|
||||
props.getBanner().setEnabled(false);
|
||||
assertFalse(new DemoNoticeWidget(props, settings(Map.of()), kernel).render(chrome).html()
|
||||
.contains("Maintenance tonight"), "a disabled banner leaves the ordinary notice text");
|
||||
}
|
||||
|
||||
// --- ContentWidget: feedback form ------------------------------------------------------------------
|
||||
|
||||
private static WidgetView feedbackView(Map<String, String> query, String path) {
|
||||
return new WidgetView(SITE, PAGE, Locale.ENGLISH, "page", false, Map.of(), query, path);
|
||||
}
|
||||
|
||||
@Test
|
||||
void feedbackFormPostsToTheAnonymousRouteWithReturnPathHoneypotAndNoCsrfField() {
|
||||
String html = new DemoFeedbackWidget(settings(Map.of()), kernel).render(feedbackView(Map.of(), "/demo"))
|
||||
.html();
|
||||
assertTrue(html.contains("<form method=\"post\" action=\"/demo/feedback\">"), html);
|
||||
assertTrue(html.contains("name=\"return\" value=\"/demo\""), html);
|
||||
assertTrue(html.contains("name=\"message\""), html);
|
||||
assertTrue(html.contains("name=\"website\"") && html.contains("rw-demo-hp"), "honeypot present");
|
||||
assertFalse(html.contains("_csrf"), "a shared, cacheable page carries no per-session token");
|
||||
assertFalse(html.contains("role=\"status\""), "no outcome without the flag");
|
||||
}
|
||||
|
||||
@Test
|
||||
void feedbackShowsTheOutcomeFlagAndEscapesTheReturnPath() {
|
||||
DemoFeedbackWidget widget = new DemoFeedbackWidget(settings(Map.of()), kernel);
|
||||
assertTrue(widget.render(feedbackView(Map.of("demo-feedback", "thanks"), "/x")).html()
|
||||
.contains("Thank you"));
|
||||
assertTrue(widget.render(feedbackView(Map.of("demo-feedback", "invalid"), "/x")).html()
|
||||
.contains("Please write a message first."));
|
||||
assertTrue(widget.render(feedbackView(Map.of("demo-feedback", "limited"), "/x")).html()
|
||||
.contains("Too many messages"));
|
||||
assertFalse(widget.render(feedbackView(Map.of("demo-feedback", "<b>"), "/x")).html()
|
||||
.contains("role=\"status\""), "an unknown flag shows nothing");
|
||||
String html = widget.render(feedbackView(Map.of(), "/a\"b")).html();
|
||||
assertTrue(html.contains("value=\"/a"b\""), html);
|
||||
assertTrue(widget.render(feedbackView(Map.of(), "")).html().contains("name=\"return\" value=\"/\""),
|
||||
"an unknown path returns to the home page");
|
||||
}
|
||||
|
||||
@Test
|
||||
void feedbackIsEmptyWhenTheSiteTurnedItOff() {
|
||||
assertTrue(new DemoFeedbackWidget(settings(Map.of("feedback.enabled", false)), kernel)
|
||||
.render(feedbackView(Map.of(), "/demo")).isEmpty());
|
||||
}
|
||||
|
||||
// --- PageQualityCheck ------------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void qualityFlagsLongTitleMissingDescriptionAndMissingH1() {
|
||||
PageMeta longTitle = new PageMeta("p", "x".repeat(80), "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
|
||||
PageView page = new PageView(SITE, longTitle, Locale.ENGLISH, "u", "<html><body>no heading</body></html>");
|
||||
List<String> codes = new DemoMetaLengthCheck(settings(Map.of())).inspect(page).stream()
|
||||
.map(Finding::code).toList();
|
||||
assertEquals(List.of("title.too-long", "description.missing", "h1.missing"), codes);
|
||||
}
|
||||
|
||||
@Test
|
||||
void qualityRatioScalesTheTitleLimitAndIgnoreCodesSuppress() {
|
||||
PageMeta title70 = new PageMeta("p", "x".repeat(70), "d", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
|
||||
PageView page = new PageView(SITE, title70, Locale.ENGLISH, "u", "<h1>t</h1>");
|
||||
assertTrue(new DemoMetaLengthCheck(settings(Map.of("quality.title-warn-ratio", "1.5"))).inspect(page)
|
||||
.isEmpty(), "70 chars is under 60 × 1.5");
|
||||
assertEquals(1, new DemoMetaLengthCheck(settings(Map.of())).inspect(page).size());
|
||||
PageView noH1 = new PageView(SITE, title70, Locale.ENGLISH, "u", "<p>no h1</p>");
|
||||
List<String> codes = new DemoMetaLengthCheck(settings(Map.of("quality.ignore-codes",
|
||||
"title.too-long, h1.missing"))).inspect(noH1).stream().map(Finding::code).toList();
|
||||
assertTrue(codes.isEmpty(), "a comma-separated ignore list (with spaces) suppresses both: " + codes);
|
||||
}
|
||||
|
||||
@Test
|
||||
void qualityCleanPageHasNoFindings() {
|
||||
PageView page = new PageView(SITE, PAGE, Locale.ENGLISH, "u", "<html><H1>About</H1></html>");
|
||||
assertTrue(new DemoMetaLengthCheck(settings(Map.of())).inspect(page).isEmpty());
|
||||
}
|
||||
|
||||
// --- EndpointContributor ---------------------------------------------------------------------------
|
||||
|
||||
private DemoEndpoints endpoints(FakePluginSettings settings, AtomicLong clock) {
|
||||
return new DemoEndpoints(kernel, notes, kernel, settings, clock::get);
|
||||
}
|
||||
|
||||
private static RouteRequest get(String path) {
|
||||
return new RouteRequest(SITE, Locale.ENGLISH, "GET", path, Map.of("q", List.of("1")),
|
||||
Map.of("X-Test", "yes"), null, null, "203.0.113.9", "https://acme.test");
|
||||
}
|
||||
|
||||
private static RouteRequest post(String path, Map<String, List<String>> form, String clientIp) {
|
||||
return new RouteRequest(SITE, Locale.ENGLISH, "POST", path, Map.of(), Map.of(), null, form, clientIp,
|
||||
"https://acme.test");
|
||||
}
|
||||
|
||||
private static String body(RouteResponse r) {
|
||||
return new String(r.body(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@Test
|
||||
void routesAreThreeGetsAndOneAnonymousPost() {
|
||||
List<Route> routes = endpoints(settings(Map.of()), new AtomicLong()).routes();
|
||||
assertEquals(List.of("GET /demo/hello.txt", "GET /demo/echo.json", "GET /demo/notes.json",
|
||||
"POST /demo/feedback"), routes.stream().map(r -> r.method() + " " + r.pathPattern()).toList());
|
||||
assertEquals(List.of(false, false, false, true), routes.stream().map(Route::anonymous).toList(),
|
||||
"only the visitor form is anonymous");
|
||||
}
|
||||
|
||||
@Test
|
||||
void helloIsLocalizedForTheRequestLocale() {
|
||||
kernel.message("acme", "runwaydemo.hello", "¡Hola!");
|
||||
RouteResponse hello = endpoints(settings(Map.of()), new AtomicLong()).handle(get("/demo/hello.txt"));
|
||||
assertEquals(200, hello.status());
|
||||
assertTrue(body(hello).startsWith("¡Hola!\nsite: Acme (acme)"), body(hello));
|
||||
assertTrue(body(hello).contains("origin: https://acme.test"), body(hello));
|
||||
}
|
||||
|
||||
@Test
|
||||
void echoShowsWhatTheHostPutInTheRequestWithLowercaseHeaderNames() {
|
||||
RouteResponse echo = endpoints(settings(Map.of()), new AtomicLong()).handle(get("/demo/echo.json"));
|
||||
assertEquals(200, echo.status());
|
||||
String json = body(echo);
|
||||
assertTrue(json.contains("\"path\":\"/demo/echo.json\""), json);
|
||||
// Since SPI 0.5.0 the host hands header names in lower case (lookups ignore case).
|
||||
assertTrue(json.contains("\"x-test\":\"yes\""), "headers echoed by their lowercase name: " + json);
|
||||
assertFalse(json.contains("X-Test"), json);
|
||||
assertTrue(json.contains("\"clientIp\":\"203.0.113.9\"") && json.contains("\"origin\":\"https://acme.test\""),
|
||||
json);
|
||||
assertTrue(json.contains("\"form\":{}") && json.contains("\"param.q\":\"1\""), json);
|
||||
}
|
||||
|
||||
@Test
|
||||
void notesEndpointIsPermissionGated() {
|
||||
DemoEndpoints ep = endpoints(settings(Map.of()), new AtomicLong());
|
||||
assertEquals(403, ep.handle(get("/demo/notes.json")).status(), "denied without the permission");
|
||||
kernel.grant("runway-demo|manage-notes");
|
||||
RouteResponse ok = ep.handle(get("/demo/notes.json"));
|
||||
assertEquals(200, ok.status());
|
||||
assertTrue(body(ok).contains("\"count\":1"), "the welcome note: " + body(ok));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWrongMethodOrUnknownPathIsNotFound() {
|
||||
DemoEndpoints ep = endpoints(settings(Map.of()), new AtomicLong());
|
||||
assertEquals(404, ep.handle(post("/demo/hello.txt", Map.of(), null)).status());
|
||||
assertEquals(404, ep.handle(get("/demo/feedback")).status(), "a GET submits nothing");
|
||||
assertEquals(404, ep.handle(get("/demo/other")).status());
|
||||
}
|
||||
|
||||
@Test
|
||||
void feedbackStoresTheMessageAsAVisitorNoteAndRedirectsWithOnlyTheOutcome() {
|
||||
DemoEndpoints ep = endpoints(settings(Map.of()), new AtomicLong());
|
||||
RouteResponse r = ep.handle(post("/demo/feedback", Map.of("message", List.of(" Nice site! "),
|
||||
"return", List.of("/demo"), "website", List.of("")), "198.51.100.1"));
|
||||
assertEquals(303, r.status());
|
||||
assertEquals("/demo?demo-feedback=thanks", r.headers().get("Location"));
|
||||
Note last = notes.list("acme").getLast();
|
||||
assertEquals("Nice site!", last.text());
|
||||
assertEquals(Note.ORIGIN_VISITOR, last.origin());
|
||||
}
|
||||
|
||||
@Test
|
||||
void feedbackHoneypotBlankAndForeignReturnAreHandled() {
|
||||
DemoEndpoints ep = endpoints(settings(Map.of()), new AtomicLong());
|
||||
int before = notes.count("acme");
|
||||
RouteResponse bot = ep.handle(post("/demo/feedback", Map.of("message", List.of("spam"),
|
||||
"website", List.of("http://spam")), "198.51.100.2"));
|
||||
assertEquals("/?demo-feedback=thanks", bot.headers().get("Location"), "a bot is told it worked");
|
||||
RouteResponse blank = ep.handle(post("/demo/feedback", Map.of("message", List.of(" "),
|
||||
"return", List.of("//evil.example/x")), "198.51.100.2"));
|
||||
assertEquals("/?demo-feedback=invalid", blank.headers().get("Location"), "never an off-site redirect");
|
||||
assertEquals(before, notes.count("acme"), "neither was stored");
|
||||
}
|
||||
|
||||
@Test
|
||||
void feedbackReadsTheBodyOnlyNeverTheQueryString() {
|
||||
DemoEndpoints ep = endpoints(settings(Map.of()), new AtomicLong());
|
||||
RouteRequest viaQuery = new RouteRequest(SITE, Locale.ENGLISH, "POST", "/demo/feedback",
|
||||
Map.of("message", List.of("in the URL")), Map.of(), null, Map.of(), "198.51.100.3", "");
|
||||
assertEquals("/?demo-feedback=invalid", ep.handle(viaQuery).headers().get("Location"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void feedbackIsRateLimitedPerClientAddressWithASlidingWindow() {
|
||||
AtomicLong clock = new AtomicLong(1_000_000);
|
||||
DemoEndpoints ep = endpoints(settings(Map.of()), clock);
|
||||
Map<String, List<String>> form = Map.of("message", List.of("hi"));
|
||||
for (int i = 0; i < DemoEndpoints.FEEDBACK_PER_WINDOW; i++) {
|
||||
assertEquals("/?demo-feedback=thanks", ep.handle(post("/demo/feedback", form, "192.0.2.7"))
|
||||
.headers().get("Location"));
|
||||
}
|
||||
assertEquals("/?demo-feedback=limited", ep.handle(post("/demo/feedback", form, "192.0.2.7"))
|
||||
.headers().get("Location"), "the sixth in the window is refused");
|
||||
assertEquals("/?demo-feedback=thanks", ep.handle(post("/demo/feedback", form, "192.0.2.8"))
|
||||
.headers().get("Location"), "another address has its own budget");
|
||||
clock.addAndGet(DemoEndpoints.WINDOW_MILLIS);
|
||||
assertEquals("/?demo-feedback=thanks", ep.handle(post("/demo/feedback", form, "192.0.2.7"))
|
||||
.headers().get("Location"), "the window slides");
|
||||
}
|
||||
|
||||
@Test
|
||||
void feedbackIsNotFoundWhenTheSiteTurnedItOff() {
|
||||
RouteResponse r = endpoints(settings(Map.of("feedback.enabled", false)), new AtomicLong())
|
||||
.handle(post("/demo/feedback", Map.of("message", List.of("hi")), "192.0.2.9"));
|
||||
assertEquals(404, r.status());
|
||||
}
|
||||
|
||||
@Test
|
||||
void safeLocalPathRefusesEverythingButALocalPath() {
|
||||
assertEquals("/a/b?c=1", DemoEndpoints.safeLocalPath("/a/b?c=1"));
|
||||
for (String bad : new String[] {null, "", "a", "//x", "/x://y", "/a b", "/a\\b", "/a\nb", "https://x"}) {
|
||||
assertEquals("/", DemoEndpoints.safeLocalPath(bad), String.valueOf(bad));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package mx.quest.demo;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
|
||||
/**
|
||||
* The shipped templates as files: every state-changing action of the console screen is reached by a
|
||||
* {@code <form method="post">} that carries the console session's CSRF token, no link points at one (a link is a
|
||||
* {@code GET}), every form action is a real handler, and no decoupled template repeats an {@code id} (a hard
|
||||
* Thymeleaf error that would 500 the screen).
|
||||
*/
|
||||
class DemoTemplatesTest {
|
||||
|
||||
private static final Pattern FORM = Pattern.compile("(?s)<form\\b([^>]*)>(.*?)</form>");
|
||||
private static final String TOKEN_BINDING =
|
||||
"th:attr=\"name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}\"";
|
||||
|
||||
private static String read(String file) throws IOException {
|
||||
return Files.readString(Path.of("templates", file), StandardCharsets.UTF_8).replaceAll("(?s)<!--.*?-->", "");
|
||||
}
|
||||
|
||||
private static Set<String> postActions() {
|
||||
Set<String> paths = new TreeSet<>();
|
||||
for (Method m : DemoConsoleController.class.getDeclaredMethods()) {
|
||||
PostMapping post = m.getAnnotation(PostMapping.class);
|
||||
if (post != null) {
|
||||
for (String p : post.value()) {
|
||||
paths.add(DemoConsoleController.BASE + p);
|
||||
}
|
||||
}
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyPostActionHasAPostFormCarryingTheCsrfToken() throws IOException {
|
||||
assertEquals(Set.of("/__admin/runway-demo/notes", "/__admin/runway-demo/showcase",
|
||||
"/__admin/runway-demo/showcase/unpublish", "/__admin/runway-demo/install-page",
|
||||
"/__admin/runway-demo/catalog/refresh"), postActions());
|
||||
String html = read("console.html");
|
||||
Set<String> formed = new HashSet<>();
|
||||
Matcher form = FORM.matcher(html);
|
||||
while (form.find()) {
|
||||
String attrs = form.group(1);
|
||||
Matcher action = Pattern.compile("action=\"([^\"]+)\"").matcher(attrs);
|
||||
assertTrue(action.find(), "every form names its action: " + attrs);
|
||||
if (attrs.contains("method=\"get\"")) {
|
||||
assertEquals(DemoConsoleController.BASE, action.group(1), "the only GET form is the read-only check");
|
||||
assertFalse(form.group(2).contains("_csrf"), "a GET form must not put the token in a URL");
|
||||
continue;
|
||||
}
|
||||
assertTrue(attrs.contains("method=\"post\""), attrs);
|
||||
assertTrue(postActions().contains(action.group(1)), "a form posts to a real handler: " + action.group(1));
|
||||
assertTrue(form.group(2).contains("class=\"rd-csrf\" type=\"hidden\" name=\"_csrf\""),
|
||||
action.group(1) + "'s form carries the hidden CSRF field");
|
||||
formed.add(action.group(1));
|
||||
}
|
||||
assertEquals(postActions(), formed, "every action is reachable from the screen");
|
||||
assertTrue(read("console.th.xml").contains("<attr sel=\".rd-csrf\"\n " + TOKEN_BINDING + "/>"),
|
||||
"the .rd-csrf fields are bound to the console session's token");
|
||||
}
|
||||
|
||||
@Test
|
||||
void noLinkPointsAtAnAction() throws IOException {
|
||||
try (Stream<Path> files = Files.list(Path.of("templates"))) {
|
||||
for (Path file : files.filter(p -> p.toString().endsWith(".html")).toList()) {
|
||||
String html = read(file.getFileName().toString());
|
||||
for (String action : postActions()) {
|
||||
assertFalse(html.contains("href=\"" + action), file + " links to " + action);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void noTemplateRepeatsAnId() throws IOException {
|
||||
try (Stream<Path> files = Files.list(Path.of("templates"))) {
|
||||
for (Path file : files.filter(p -> p.toString().endsWith(".html")).toList()) {
|
||||
Matcher ids = Pattern.compile("\\bid=\"([^\"]+)\"").matcher(read(file.getFileName().toString()));
|
||||
Set<String> seen = new HashSet<>();
|
||||
while (ids.find()) {
|
||||
assertTrue(seen.add(ids.group(1)), file + ": duplicate id " + ids.group(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everySelectorInTheLogicMatchesTheMarkup() throws IOException {
|
||||
try (Stream<Path> files = Files.list(Path.of("templates"))) {
|
||||
for (Path logic : files.filter(p -> p.toString().endsWith(".th.xml")).toList()) {
|
||||
String name = logic.getFileName().toString().replace(".th.xml", "");
|
||||
String html = read(name + ".html");
|
||||
Matcher sel = Pattern.compile("sel=\"([^\"]+)\"").matcher(read(name + ".th.xml"));
|
||||
while (sel.find()) {
|
||||
for (String part : sel.group(1).split("//")) {
|
||||
String token = part.startsWith("#") ? "id=\"" + part.substring(1) + "\""
|
||||
: part.startsWith(".") ? part.substring(1) : "<" + part;
|
||||
assertTrue(html.contains(token), name + ": selector " + sel.group(1) + " matches nothing");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* runway-demo plugin styles — served at /__plugin/runway-demo/static/css/demo.css.
|
||||
* Injected into tenant pages by the DemoAnalyticsHead HeadContributor (when the notice is enabled) and linked by
|
||||
* the feedback form itself; styles the notice and feedback widgets. Served from the plugin's own namespace — never copied
|
||||
* into a tenant.
|
||||
*/
|
||||
.rw-demo-notice {
|
||||
border-radius: 6px;
|
||||
padding: 0.75rem 1rem;
|
||||
margin: 0.75rem 0;
|
||||
border: 1px solid transparent;
|
||||
font: 0.95rem/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||
}
|
||||
|
||||
.rw-demo-notice-info {
|
||||
background: #e7f5ff;
|
||||
border-color: #a5d8ff;
|
||||
color: #1864ab;
|
||||
}
|
||||
|
||||
.rw-demo-notice-warning {
|
||||
background: #fff9db;
|
||||
border-color: #ffe066;
|
||||
color: #997404;
|
||||
}
|
||||
|
||||
.rw-demo-notice-danger {
|
||||
background: #fff5f5;
|
||||
border-color: #ffc9c9;
|
||||
color: #c92a2a;
|
||||
}
|
||||
|
||||
/* The public feedback form (DemoFeedbackWidget). */
|
||||
.rw-demo-feedback form {
|
||||
display: grid;
|
||||
gap: 0.5rem;
|
||||
max-width: 36rem;
|
||||
font: 0.95rem/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||
}
|
||||
|
||||
.rw-demo-feedback textarea {
|
||||
font: inherit;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.rw-demo-feedback button {
|
||||
justify-self: start;
|
||||
font: inherit;
|
||||
padding: 0.4rem 1rem;
|
||||
}
|
||||
|
||||
/* The honeypot: off-screen for people (and aria-hidden for assistive technology); a naive bot still fills it. */
|
||||
.rw-demo-hp {
|
||||
position: absolute;
|
||||
left: -10000px;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/*
|
||||
* runway-demo — an inert demo script served at /__plugin/runway-demo/static/js/demo-analytics.js.
|
||||
* Referenced by the DemoAnalyticsHead <script> tag (only when per-site analytics is enabled AND the app-level write
|
||||
* key is set) purely to demonstrate the per-plugin static-asset seam. It does nothing but log; a real analytics
|
||||
* plugin would emit the vendor snippet here. A plain <script src> is all a plugin emits: the kernel stamps the CSP
|
||||
* nonce on it at the response edge.
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
var el = document.currentScript;
|
||||
var site = el && el.getAttribute("data-site");
|
||||
console.debug("[runway-demo] analytics placeholder loaded for site:", site || "(unknown)");
|
||||
})();
|
||||
@@ -0,0 +1,51 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Runway Demo — help</title>
|
||||
<link rel="stylesheet" href="/__plugin/runway-demo/static/css/demo.css">
|
||||
<style>
|
||||
body { font: 1rem/1.6 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; max-width: 44rem;
|
||||
margin: 2rem auto; padding: 0 1rem; color: #333; }
|
||||
code { background: #f1f3f5; padding: 0.1em 0.35em; border-radius: 4px; }
|
||||
h1 { font-size: 1.4rem; }
|
||||
h2 { font-size: 1.1rem; margin-top: 1.5rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Runway Demo — help</h1>
|
||||
<div class="rw-demo-notice rw-demo-notice-info">
|
||||
This page is a <strong>static asset</strong> served from the plugin's own namespace at
|
||||
<code>/__plugin/runway-demo/static/notes-help.html</code>. Runway Demo is the reference plugin: everything it does
|
||||
is there to show plugin authors how a feature is built.
|
||||
</div>
|
||||
|
||||
<h2>The demo screen</h2>
|
||||
<p>The <em>Runway demo</em> entry of the console menu opens the plugin's own screen (it needs the
|
||||
<code>manage-notes</code> permission). From there you can add notes, install a ready-made demo page, publish a
|
||||
short <em>showcase</em> page, look at the site's published content and check whether a path is free, and see the
|
||||
changes the plugin has been told about.</p>
|
||||
|
||||
<h2>Notes</h2>
|
||||
<p>The demo keeps a small set of per-site notes in its own folder of the site. Notes are:</p>
|
||||
<ul>
|
||||
<li>seeded with a welcome note the first time a site's notes are read;</li>
|
||||
<li>added from the demo screen, and by visitors through the public feedback form;</li>
|
||||
<li>appended automatically whenever this plugin's per-site settings are saved;</li>
|
||||
<li>readable as JSON at <code>/demo/notes.json</code> — only with the <code>manage-notes</code> permission (anyone
|
||||
else gets <code>403</code>);</li>
|
||||
<li>kept in full backups, and <strong>left out of transfer copies</strong>: they hold what people typed, so the
|
||||
plugin declares them personal data.</li>
|
||||
</ul>
|
||||
|
||||
<h2>Pages and endpoints</h2>
|
||||
<ul>
|
||||
<li><code>/demo</code> — the demo page, once installed from the demo screen. It is an ordinary site page: edit,
|
||||
move or delete it under Pages.</li>
|
||||
<li><code>/demo/showcase</code> — the showcase page, while one is published.</li>
|
||||
<li><code>/demo/hello.txt</code> — a per-site greeting in the visitor's language.</li>
|
||||
<li><code>/demo/echo.json</code> — echoes what the platform tells the plugin about your request.</li>
|
||||
</ul>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,17 @@
|
||||
<div id="rd-admin" class="card mt-3">
|
||||
<div class="card-header">
|
||||
<h3 id="rd-admin-title" class="card-title">Runway Demo — status & notes</h3>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<p id="rd-admin-count" class="mb-1">Notes: 0</p>
|
||||
<p id="rd-admin-banner" class="text-secondary mb-1">Banner: —</p>
|
||||
<p id="rd-admin-key" class="text-secondary mb-1">Analytics key: —</p>
|
||||
<p id="rd-admin-token" class="text-secondary mb-1">Site token: —</p>
|
||||
<p id="rd-admin-page" class="text-secondary mb-2">Demo page: —</p>
|
||||
<ul id="rd-admin-list" class="mb-2">
|
||||
<li id="rd-admin-note">note</li>
|
||||
</ul>
|
||||
<a id="rd-admin-console" href="/__admin/runway-demo" class="btn btn-sm btn-primary">Open the demo screen</a>
|
||||
<a id="rd-admin-api" href="/demo/notes.json" class="btn btn-sm btn-outline-primary">Open /demo/notes.json</a>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
Decoupled logic for the admin fragment. The host renders it automatically BELOW the per-site settings form because
|
||||
templates/admin.html exists (a filename convention — no descriptor entry). Fed by the plugin's own bean; tenantSiteId
|
||||
comes from the console. The link to the demo screen shows only to a user who may open it: ${@authz.may(..)} is the
|
||||
AccessCheck bean, the same check the screen's @PreAuthorize makes (hiding a link is UX; the screen still checks).
|
||||
-->
|
||||
<thlogic>
|
||||
<attr sel="#rd-admin-title" th:text="#{runwaydemo.admin.title}"/>
|
||||
<attr sel="#rd-admin-count" th:text="#{runwaydemo.admin.notes(${@runwayDemoAdminModel.noteCount(tenantSiteId)})}"/>
|
||||
<attr sel="#rd-admin-banner" th:text="#{runwaydemo.admin.banner(${@runwayDemoAdminModel.bannerEnabled()})}"/>
|
||||
<attr sel="#rd-admin-key" th:text="#{runwaydemo.admin.writeKey(${@runwayDemoAdminModel.analyticsKeyConfigured()})}"/>
|
||||
<attr sel="#rd-admin-token" th:text="#{runwaydemo.admin.siteToken(${@runwayDemoAdminModel.siteTokenConfigured(tenantSiteId)})}"/>
|
||||
<attr sel="#rd-admin-page" th:text="${@runwayDemoAdminModel.demoPagePath(tenantSiteId).isEmpty()} ? #{runwaydemo.admin.page.none} : #{runwaydemo.admin.page(${@runwayDemoAdminModel.demoPagePath(tenantSiteId)})}"/>
|
||||
<attr sel="#rd-admin-note" th:each="n : ${@runwayDemoAdminModel.recentNotes(tenantSiteId)}" th:text="${n.text()}"/>
|
||||
<attr sel="#rd-admin-console" th:if="${@authz.may('runway-demo|manage-notes')}" th:text="#{runwaydemo.card.console}"/>
|
||||
</thlogic>
|
||||
@@ -0,0 +1,194 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><title>Runway demo</title></head>
|
||||
<body>
|
||||
<!-- The demo's console screen content (@ConsoleScreen). The kernel's shell layout pulls in #content by name. Markup
|
||||
only: every binding is in console.th.xml. Every state-changing action is a POST form carrying the console's CSRF
|
||||
token (.rd-csrf); the path check is a GET form because it only reads. -->
|
||||
<div id="content">
|
||||
<div class="page-header d-print-none mb-3">
|
||||
<div class="row align-items-center">
|
||||
<div class="col">
|
||||
<div class="page-pretitle" id="rd-pretitle">Site</div>
|
||||
<h2 class="page-title" id="rd-heading">Runway demo</h2>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="rd-flash" class="alert alert-success" role="status"><span id="rd-flash-text">done</span></div>
|
||||
<div id="rd-error" class="alert alert-danger" role="alert"><span id="rd-error-text">error</span></div>
|
||||
|
||||
<div class="row row-cards">
|
||||
<!-- PluginInfo + RunwaySpi: who am I, built against what, running on what. -->
|
||||
<div class="col-md-6">
|
||||
<div class="card">
|
||||
<div class="card-header"><h3 class="card-title" id="rd-about-title">This plugin</h3></div>
|
||||
<div class="card-body">
|
||||
<p class="mb-1"><span id="rd-version-label">Version</span>: <code id="rd-version">2.0.1</code></p>
|
||||
<p class="mb-1"><span id="rd-built-label">Built against SPI</span>: <code id="rd-built">0.6.0</code></p>
|
||||
<p class="mb-0"><span id="rd-running-label">Running on SPI</span>: <code id="rd-running">0.6.0</code></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- SitePages: the starter page, installed through the site's editorial rules. -->
|
||||
<div class="col-md-6">
|
||||
<div class="card">
|
||||
<div class="card-header"><h3 class="card-title" id="rd-page-title">Demo page</h3></div>
|
||||
<div class="card-body">
|
||||
<p class="text-secondary" id="rd-page-desc">A ready-made page carrying the notice and feedback
|
||||
widgets.</p>
|
||||
<p id="rd-page-installed" class="mb-0"><span id="rd-page-at">Installed at</span>
|
||||
<a id="rd-page-link" href="/demo"><code id="rd-page-path">/demo</code></a></p>
|
||||
<form id="rd-page-form" method="post" action="/__admin/runway-demo/install-page" class="m-0">
|
||||
<input class="rd-csrf" type="hidden" name="_csrf" value="">
|
||||
<button type="submit" class="btn btn-primary" id="rd-page-install">Install the demo page</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- PluginSiteFiles (+ siteData.personal): the per-site notes. -->
|
||||
<div class="col-md-6">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h3 class="card-title" id="rd-notes-title">Notes</h3>
|
||||
<span class="ms-auto text-secondary" id="rd-notes-count">0</span>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<p class="text-secondary small" id="rd-notes-desc">Kept in the plugin's own folder of this site;
|
||||
declared personal data, so transfer copies leave them out.</p>
|
||||
<form id="rd-note-form" method="post" action="/__admin/runway-demo/notes" class="mb-3">
|
||||
<input class="rd-csrf" type="hidden" name="_csrf" value="">
|
||||
<label class="form-label" for="rd-note-text" id="rd-note-label">New note</label>
|
||||
<textarea class="form-control mb-2" id="rd-note-text" name="text" rows="2"
|
||||
maxlength="1000"></textarea>
|
||||
<button type="submit" class="btn btn-outline-primary" id="rd-note-add">Add note</button>
|
||||
</form>
|
||||
<ul class="list-unstyled mb-0" id="rd-note-list">
|
||||
<li id="rd-note-row" class="mb-2">
|
||||
<span class="badge bg-secondary-lt rd-note-origin">console</span>
|
||||
<span class="rd-note-text">text</span>
|
||||
<div class="text-secondary small rd-note-at">time</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ContentSource + ContentChanges: the showcase page. -->
|
||||
<div class="col-md-6">
|
||||
<div class="card">
|
||||
<div class="card-header"><h3 class="card-title" id="rd-show-title">Showcase page</h3></div>
|
||||
<div class="card-body">
|
||||
<p class="text-secondary small" id="rd-show-desc">Served by the plugin's content source. Publishing
|
||||
or unpublishing announces the change, so routing, sitemaps and search follow at once.</p>
|
||||
<div id="rd-show-live" class="mb-3">
|
||||
<p class="mb-1"><span id="rd-show-at">Published at</span>
|
||||
<a id="rd-show-link" href="/demo/showcase"><code id="rd-show-path">/demo/showcase</code></a></p>
|
||||
<blockquote class="text-secondary" id="rd-show-text">text</blockquote>
|
||||
<form id="rd-show-unpublish" method="post" action="/__admin/runway-demo/showcase/unpublish"
|
||||
class="m-0">
|
||||
<input class="rd-csrf" type="hidden" name="_csrf" value="">
|
||||
<button type="submit" class="btn btn-outline-danger btn-sm" id="rd-show-unpublish-btn">Unpublish</button>
|
||||
</form>
|
||||
</div>
|
||||
<p class="text-secondary" id="rd-show-none">Nothing is published.</p>
|
||||
<form id="rd-show-form" method="post" action="/__admin/runway-demo/showcase" class="m-0">
|
||||
<input class="rd-csrf" type="hidden" name="_csrf" value="">
|
||||
<label class="form-label" for="rd-show-input" id="rd-show-label">Showcase text</label>
|
||||
<textarea class="form-control mb-2" id="rd-show-input" name="text" rows="2"
|
||||
maxlength="2000"></textarea>
|
||||
<button type="submit" class="btn btn-outline-primary" id="rd-show-publish">Publish</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ContentCatalogView: the site's published content surface, the path check, the manual refresh. -->
|
||||
<div class="col-12">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h3 class="card-title" id="rd-cat-title">Content surface</h3>
|
||||
<span class="ms-auto text-secondary" id="rd-cat-total">0</span>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<form id="rd-check-form" method="get" action="/__admin/runway-demo" class="row g-2 mb-3">
|
||||
<div class="col-auto">
|
||||
<label class="visually-hidden" for="rd-check-path" id="rd-check-label">Path</label>
|
||||
<input class="form-control" id="rd-check-path" name="path" placeholder="/about">
|
||||
</div>
|
||||
<div class="col-auto">
|
||||
<button type="submit" class="btn btn-outline-secondary" id="rd-check-btn">Check a path</button>
|
||||
</div>
|
||||
</form>
|
||||
<p id="rd-check-result" class="mb-3"><code id="rd-check-echo">/about</code>
|
||||
<span id="rd-check-unsafe" class="badge bg-red-lt">unsafe</span>
|
||||
<span id="rd-check-servable" class="badge bg-green-lt">servable</span>
|
||||
<span id="rd-check-reserved" class="badge bg-yellow-lt">not servable</span>
|
||||
<span id="rd-check-owner">owned by page</span>
|
||||
<span id="rd-check-free">no published page owns it</span></p>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th id="rd-cat-h-source">Source</th>
|
||||
<th id="rd-cat-h-id">Item</th>
|
||||
<th id="rd-cat-h-path">Path</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr id="rd-cat-row">
|
||||
<td class="rd-cat-source">pages</td>
|
||||
<td class="rd-cat-id">about</td>
|
||||
<td class="rd-cat-path">/about</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<form id="rd-cat-refresh" method="post" action="/__admin/runway-demo/catalog/refresh" class="m-0">
|
||||
<input class="rd-csrf" type="hidden" name="_csrf" value="">
|
||||
<button type="submit" class="btn btn-sm btn-outline-secondary" id="rd-cat-refresh-btn">Refresh the listing</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- SiteEventListener: what this node saw change, with the URLs before and after. -->
|
||||
<div class="col-12">
|
||||
<div class="card">
|
||||
<div class="card-header"><h3 class="card-title" id="rd-act-title">Recent changes</h3></div>
|
||||
<div class="card-body">
|
||||
<p class="text-secondary" id="rd-act-empty">No change seen since the platform started.</p>
|
||||
<div class="table-responsive" id="rd-act-table">
|
||||
<table class="table table-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th id="rd-act-h-at">When</th>
|
||||
<th id="rd-act-h-cause">Cause</th>
|
||||
<th id="rd-act-h-item">Item</th>
|
||||
<th id="rd-act-h-before">URLs before</th>
|
||||
<th id="rd-act-h-after">URLs after</th>
|
||||
<th id="rd-act-h-local">Here</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr id="rd-act-row">
|
||||
<td class="rd-act-at text-nowrap">time</td>
|
||||
<td class="rd-act-cause">page</td>
|
||||
<td class="rd-act-item">pages:about</td>
|
||||
<td class="rd-act-before">/about</td>
|
||||
<td class="rd-act-after">/about</td>
|
||||
<td class="rd-act-local">yes</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p class="mt-3"><a id="rd-help" href="/__plugin/runway-demo/static/notes-help.html" target="_blank" rel="noopener">Help</a></p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,108 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
Decoupled logic of the demo's console screen. `rd` is the Screen record the controller put in the model; besides it,
|
||||
the template uses only what a console screen may rely on: tenantSiteId, _csrf, ${@authz.may(..)} and #{..} messages.
|
||||
`//` reaches nested elements of an iterated row. Form actions are constants in the markup (th:action and th:attr run
|
||||
in a restricted context); every POST form's hidden .rd-csrf field carries the console session's CSRF token.
|
||||
-->
|
||||
<thlogic>
|
||||
<attr sel="#rd-pretitle" th:text="${rd.site().displayName()}"/>
|
||||
<attr sel="#rd-heading" th:text="#{runwaydemo.console.heading}"/>
|
||||
|
||||
<attr sel="#rd-flash" th:if="${runwayDemoFlash != null}"/>
|
||||
<attr sel="#rd-flash-text" th:text="${runwayDemoFlash}"/>
|
||||
<attr sel="#rd-error" th:if="${runwayDemoError != null}"/>
|
||||
<attr sel="#rd-error-text" th:text="${runwayDemoError}"/>
|
||||
|
||||
<attr sel=".rd-csrf"
|
||||
th:attr="name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}"/>
|
||||
|
||||
<!-- This plugin -->
|
||||
<attr sel="#rd-about-title" th:text="#{runwaydemo.console.about}"/>
|
||||
<attr sel="#rd-version-label" th:text="#{runwaydemo.console.version}"/>
|
||||
<attr sel="#rd-version" th:text="${rd.pluginVersion()}"/>
|
||||
<attr sel="#rd-built-label" th:text="#{runwaydemo.console.builtSpi}"/>
|
||||
<attr sel="#rd-built" th:text="${rd.builtSpi()}"/>
|
||||
<attr sel="#rd-running-label" th:text="#{runwaydemo.console.runningSpi}"/>
|
||||
<attr sel="#rd-running" th:text="${rd.runningSpi()}"/>
|
||||
|
||||
<!-- Demo page (SitePages) -->
|
||||
<attr sel="#rd-page-title" th:text="#{runwaydemo.console.page}"/>
|
||||
<attr sel="#rd-page-desc" th:text="#{runwaydemo.console.page.desc}"/>
|
||||
<attr sel="#rd-page-installed" th:if="${!rd.starterPath().isEmpty()}"/>
|
||||
<attr sel="#rd-page-at" th:text="#{runwaydemo.console.page.at}"/>
|
||||
<attr sel="#rd-page-link" th:href="${rd.starterPath()}"/>
|
||||
<attr sel="#rd-page-path" th:text="${rd.starterPath()}"/>
|
||||
<attr sel="#rd-page-form" th:if="${rd.starterPath().isEmpty()}"/>
|
||||
<attr sel="#rd-page-install" th:text="#{runwaydemo.console.page.install}"/>
|
||||
|
||||
<!-- Notes (PluginSiteFiles) -->
|
||||
<attr sel="#rd-notes-title" th:text="#{runwaydemo.console.notes}"/>
|
||||
<attr sel="#rd-notes-count" th:text="${rd.noteCount()}"/>
|
||||
<attr sel="#rd-notes-desc" th:text="#{runwaydemo.console.notes.desc}"/>
|
||||
<attr sel="#rd-note-label" th:text="#{runwaydemo.console.note.new}"/>
|
||||
<attr sel="#rd-note-add" th:text="#{runwaydemo.console.note.add}"/>
|
||||
<attr sel="#rd-note-row" th:each="n : ${rd.notes()}"/>
|
||||
<attr sel="#rd-note-row//.rd-note-origin" th:text="${n.origin()}"/>
|
||||
<attr sel="#rd-note-row//.rd-note-text" th:text="${n.text()}"/>
|
||||
<attr sel="#rd-note-row//.rd-note-at" th:text="${n.createdAt()}"/>
|
||||
|
||||
<!-- Showcase (ContentSource + ContentChanges) -->
|
||||
<attr sel="#rd-show-title" th:text="#{runwaydemo.console.showcase}"/>
|
||||
<attr sel="#rd-show-desc" th:text="#{runwaydemo.console.showcase.desc}"/>
|
||||
<attr sel="#rd-show-live" th:if="${rd.showcaseText() != null}"/>
|
||||
<attr sel="#rd-show-at" th:text="#{runwaydemo.console.showcase.at}"/>
|
||||
<attr sel="#rd-show-path" th:text="${rd.showcasePath()}"/>
|
||||
<attr sel="#rd-show-text" th:text="${rd.showcaseText()}"/>
|
||||
<attr sel="#rd-show-unpublish-btn" th:text="#{runwaydemo.console.showcase.unpublish}"/>
|
||||
<attr sel="#rd-show-none" th:if="${rd.showcaseText() == null}" th:text="#{runwaydemo.console.showcase.empty}"/>
|
||||
<attr sel="#rd-show-label" th:text="#{runwaydemo.console.showcase.text}"/>
|
||||
<attr sel="#rd-show-publish" th:text="#{runwaydemo.console.showcase.publish}"/>
|
||||
|
||||
<!-- Content surface (ContentCatalogView) -->
|
||||
<attr sel="#rd-cat-title" th:text="#{runwaydemo.console.catalog}"/>
|
||||
<attr sel="#rd-cat-total" th:text="${rd.catalogTotal()}"/>
|
||||
<attr sel="#rd-check-label" th:text="#{runwaydemo.console.check.path}"/>
|
||||
<attr sel="#rd-check-path" th:value="${rd.pathCheck() != null ? rd.pathCheck().path() : ''}"/>
|
||||
<attr sel="#rd-check-btn" th:text="#{runwaydemo.console.check}"/>
|
||||
<attr sel="#rd-check-result" th:if="${rd.pathCheck() != null}"/>
|
||||
<attr sel="#rd-check-echo" th:text="${rd.pathCheck() != null ? rd.pathCheck().path() : ''}"/>
|
||||
<attr sel="#rd-check-unsafe" th:if="${rd.pathCheck() != null and !rd.pathCheck().safe()}"
|
||||
th:text="#{runwaydemo.console.check.unsafe}"/>
|
||||
<attr sel="#rd-check-servable" th:if="${rd.pathCheck() != null and rd.pathCheck().servable()}"
|
||||
th:text="#{runwaydemo.console.check.servable}"/>
|
||||
<attr sel="#rd-check-reserved" th:if="${rd.pathCheck() != null and rd.pathCheck().safe() and !rd.pathCheck().servable()}"
|
||||
th:text="#{runwaydemo.console.check.reserved}"/>
|
||||
<attr sel="#rd-check-owner" th:if="${rd.pathCheck() != null and rd.pathCheck().ownerSlug() != null}"
|
||||
th:text="#{runwaydemo.console.check.owner(${rd.pathCheck() != null ? rd.pathCheck().ownerSlug() : ''})}"/>
|
||||
<attr sel="#rd-check-free" th:if="${rd.pathCheck() != null and rd.pathCheck().safe() and rd.pathCheck().ownerSlug() == null}"
|
||||
th:text="#{runwaydemo.console.check.free}"/>
|
||||
<attr sel="#rd-cat-h-source" th:text="#{runwaydemo.console.catalog.source}"/>
|
||||
<attr sel="#rd-cat-h-id" th:text="#{runwaydemo.console.catalog.item}"/>
|
||||
<attr sel="#rd-cat-h-path" th:text="#{runwaydemo.console.catalog.path}"/>
|
||||
<attr sel="#rd-cat-row" th:each="c : ${rd.catalog()}" th:classappend="${c.own() ? 'table-active' : ''}"/>
|
||||
<attr sel="#rd-cat-row//.rd-cat-source" th:text="${c.source()}"/>
|
||||
<attr sel="#rd-cat-row//.rd-cat-id" th:text="${c.id()}"/>
|
||||
<attr sel="#rd-cat-row//.rd-cat-path" th:text="${c.path()}"/>
|
||||
<attr sel="#rd-cat-refresh-btn" th:text="#{runwaydemo.console.catalog.refresh}"/>
|
||||
|
||||
<!-- Recent changes (SiteEventListener) -->
|
||||
<attr sel="#rd-act-title" th:text="#{runwaydemo.console.activity}"/>
|
||||
<attr sel="#rd-act-empty" th:if="${rd.activity().isEmpty()}" th:text="#{runwaydemo.console.activity.empty}"/>
|
||||
<attr sel="#rd-act-table" th:if="${!rd.activity().isEmpty()}"/>
|
||||
<attr sel="#rd-act-h-at" th:text="#{runwaydemo.console.activity.at}"/>
|
||||
<attr sel="#rd-act-h-cause" th:text="#{runwaydemo.console.activity.cause}"/>
|
||||
<attr sel="#rd-act-h-item" th:text="#{runwaydemo.console.activity.item}"/>
|
||||
<attr sel="#rd-act-h-before" th:text="#{runwaydemo.console.activity.before}"/>
|
||||
<attr sel="#rd-act-h-after" th:text="#{runwaydemo.console.activity.after}"/>
|
||||
<attr sel="#rd-act-h-local" th:text="#{runwaydemo.console.activity.local}"/>
|
||||
<attr sel="#rd-act-row" th:each="a : ${rd.activity()}"/>
|
||||
<attr sel="#rd-act-row//.rd-act-at" th:text="${a.at()}"/>
|
||||
<attr sel="#rd-act-row//.rd-act-cause" th:text="${a.cause()}"/>
|
||||
<attr sel="#rd-act-row//.rd-act-item" th:text="${a.item()}"/>
|
||||
<attr sel="#rd-act-row//.rd-act-before" th:text="${#strings.listJoin(a.previousUrls(), ', ')}"/>
|
||||
<attr sel="#rd-act-row//.rd-act-after" th:text="${#strings.listJoin(a.currentUrls(), ', ')}"/>
|
||||
<attr sel="#rd-act-row//.rd-act-local" th:text="${a.local()} ? #{runwaydemo.console.yes} : #{runwaydemo.console.no}"/>
|
||||
|
||||
<attr sel="#rd-help" th:text="#{runwaydemo.console.help}"/>
|
||||
</thlogic>
|
||||
@@ -0,0 +1,9 @@
|
||||
<div id="rd-card" class="card">
|
||||
<div class="card-body">
|
||||
<h3 id="rd-card-title" class="card-title">Runway Demo</h3>
|
||||
<p id="rd-card-notes" class="mb-1">Notes: 0</p>
|
||||
<p id="rd-card-spi" class="text-secondary small mb-2">SPI —</p>
|
||||
<a id="rd-card-console" href="/__admin/runway-demo" class="btn btn-sm btn-primary">Open the demo screen</a>
|
||||
<a id="rd-card-link" href="/demo/hello.txt" class="btn btn-sm btn-outline-primary">Try /demo/hello.txt</a>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
Decoupled logic for the tenant dashboard card (gated in plugin.yml by "runway-demo|manage-notes"). A fragment may rely
|
||||
on tenantSiteId, _csrf, ${@<own bean>…}, ${@authz.may('…')} and #{…} messages — nothing else in the console's model —
|
||||
so everything it shows comes from this plugin's own bean, ${@runwayDemoAdminModel…}. Zero Thymeleaf in the .html.
|
||||
-->
|
||||
<thlogic>
|
||||
<attr sel="#rd-card-title" th:text="|Runway Demo · ${@runwayDemoAdminModel.siteName(tenantSiteId)}|"/>
|
||||
<attr sel="#rd-card-notes" th:text="#{runwaydemo.card.notes(${@runwayDemoAdminModel.noteCount(tenantSiteId)})}"/>
|
||||
<attr sel="#rd-card-spi" th:text="#{runwaydemo.card.versions(${@runwayDemoAdminModel.pluginVersion()},${@runwayDemoAdminModel.builtSpi()},${@runwayDemoAdminModel.runningSpi()})}"/>
|
||||
<attr sel="#rd-card-console" th:text="#{runwaydemo.card.console}"/>
|
||||
</thlogic>
|
||||
@@ -0,0 +1,22 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Showcase</title>
|
||||
<!-- Static preview head only — replaced at render by the TENANT's master head (the seam contract). -->
|
||||
</head>
|
||||
<body>
|
||||
<header id="site-header">Site header (from the master at render)</header>
|
||||
|
||||
<main id="content">
|
||||
<article class="rw-demo-showcase">
|
||||
<h1 id="showcase-title">Showcase</h1>
|
||||
<div id="showcase-body">
|
||||
<p>The showcase text renders here.</p>
|
||||
</div>
|
||||
</article>
|
||||
</main>
|
||||
|
||||
<footer id="site-footer">Site footer (from the master at render)</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
The body template of the demo's ContentSource (ContentRef.bodyTemplate = __plugin__/runway-demo/showcase). It may rely
|
||||
on exactly the documented render model: ${master} (the tenant's master to wrap in), ${content.*} (id, sourceKey,
|
||||
title, description, bodyHtml, attributes, updatedAt), ${locale} and ${urls[..]}. The tenant's chrome comes from the
|
||||
master through its seams, by the ${master} VARIABLE (never a literal __plugin__/… or master name), so this file is
|
||||
byte-identical for every tenant. bodyHtml is already escaped by DemoShowcaseSource, hence th:utext.
|
||||
-->
|
||||
<thlogic>
|
||||
<attr sel="head" th:replace="~{${master} :: head}"/>
|
||||
<attr sel="#site-header" th:replace="~{${master} :: #site-header}"/>
|
||||
<attr sel="#site-footer" th:replace="~{${master} :: #site-footer}"/>
|
||||
|
||||
<attr sel="#showcase-title" th:text="${content.title}"/>
|
||||
<attr sel="#showcase-body" th:utext="${content.bodyHtml}"/>
|
||||
</thlogic>
|
||||
@@ -0,0 +1,721 @@
|
||||
# Writing a Runway plugin — the authoring guide
|
||||
|
||||
> **Audience:** a developer starting a **new Runway plugin from scratch**.
|
||||
> **Scope:** the complete plugin contract of the Runway kernel at **SPI `1.0.0`** (Runway `1.0.0`; frozen —
|
||||
> within `1.x` it changes only additively, see the kernel's `docs/SPI-STABILITY.md`) — the descriptor, every extension
|
||||
> axis, the **service tier** through which a plugin reaches the kernel, the `POST`/CSRF rules, the build, the
|
||||
> install, how to verify, and the traps. Everything here is grounded in the kernel as built and verified against the
|
||||
> packaged host jar; a gap is called a gap.
|
||||
>
|
||||
> **A plugin links only the Runway SPI** (`mx.quest.runway.spi.*`). The kernel **blocks** a plugin that links its
|
||||
> internal classes, breaks the Spring-context rules (§5) or declares no `requiresSpi` floor of at least `0.4.0` (§4)
|
||||
> — the plugin is skipped with the reason in the log and on the Plugins screen; the platform still boots. Every
|
||||
> first-party plugin under `plugins/` is on the service tier; this guide describes only that contract.
|
||||
>
|
||||
> The **`demo`** plugin (`../demo/`, walkthrough in `../demo/docs/DEMO-PLUGIN.md`) is the worked reference: it uses
|
||||
> every axis and every service once, where a real plugin would, with a comment saying when to use it. Copying
|
||||
> `demo/` and deleting what you don't need is the fastest correct start. The kernel's own developer guide is
|
||||
> [`docs/PLUGIN-DEVELOPMENT.md`](../../docs/PLUGIN-DEVELOPMENT.md) at the root of the repository.
|
||||
|
||||
---
|
||||
|
||||
## 1. What a Runway plugin *is*
|
||||
|
||||
- **A folder**, deployed under the host's external tree at `external/plugins/<id>/`, containing:
|
||||
- `plugin.yml` — the declarative descriptor (required, at the folder root);
|
||||
- one **thin** `*.jar` — only *your* classes (never the kernel, never Spring; see §3);
|
||||
- optional `lib/` (bundled third-party jars, scanned one level deep), `static/`, `templates/`, `i18n/`.
|
||||
- **Trusted first-party code, not a sandbox.** Plugin jars load into one shared child classloader whose parent is the
|
||||
application classloader; your `mainClass` `@Configuration` is registered into the host Spring context *before*
|
||||
refresh, so your beans wire like the kernel's — and receive the kernel's **services** (§7) by ordinary injection.
|
||||
- **Restart-to-install, degrade-don't-crash.** Install / upgrade / remove = change the folder and **restart** (no hot
|
||||
reload). A malformed, disabled or broken plugin is logged and skipped; a plugin that breaks the boot is
|
||||
**quarantined** (the kernel writes `external/plugin-quarantine/<id>.yml`, relaunches, and the next boot shows it
|
||||
Blocked); the platform always comes up.
|
||||
- **Your package MUST live outside `mx.quest.runway`** (e.g. `com.acme.myplugin`): the host would scan it, and the
|
||||
kernel treats a plugin class under `mx.quest.runway` as host linkage.
|
||||
|
||||
---
|
||||
|
||||
## 2. Prerequisites
|
||||
|
||||
- **JDK 25**.
|
||||
- **Maven**.
|
||||
- **`mx.quest:runway-spi` and `mx.quest:runway-spi-testkit` in your `~/.m2`**, at the version of the kernel you build
|
||||
for (`ls ~/.m2/repository/mx/quest/runway-spi/`). That is all of Runway a plugin compiles against. Their Maven
|
||||
version is the **kernel's release version**, not the SPI level: `1.0.0` carries SPI `1.0.0` (the jar's
|
||||
`RunwaySpi.VERSION` says which), and a later kernel such as `1.0.1` may carry the same SPI.
|
||||
- **Where those jars come from: the kernel release's assets.** No Maven repository serves them. Every kernel
|
||||
release on the releases page (<https://g.quest.mx/quest/runway/releases>)
|
||||
attaches, for its version `<ver>`, `runway-spi-<ver>.jar`, `runway-spi-testkit-<ver>.jar`, their `-sources.jar`
|
||||
and a standalone pom for each (no parent, versions resolved — the testkit's names `runway-spi` at the same
|
||||
version), all listed in that release's `SHA256SUMS`. Install them once per kernel version you build against:
|
||||
|
||||
```sh
|
||||
V=1.0.0
|
||||
# Download the six runway-spi* files and SHA256SUMS from the v$V release page.
|
||||
sha256sum -c --ignore-missing SHA256SUMS # each of the six must print OK; fails if none was verified
|
||||
mvn install:install-file -Dfile=runway-spi-$V.jar -DpomFile=runway-spi-$V.pom \
|
||||
-Dsources=runway-spi-$V-sources.jar
|
||||
mvn install:install-file -Dfile=runway-spi-testkit-$V.jar -DpomFile=runway-spi-testkit-$V.pom \
|
||||
-Dsources=runway-spi-testkit-$V-sources.jar
|
||||
```
|
||||
|
||||
**Do not skip the checksum:** a download that returns an HTML page (a sign-in or error page) with HTTP 200 instead
|
||||
of the asset passes `curl -f`, and `install:install-file` would install it as a "jar". **Install with the pom**
|
||||
(`-DpomFile`), not `-DgroupId/-DartifactId`, so Maven knows the testkit needs `runway-spi`. A local build of the
|
||||
kernel's source puts the same artifacts in `~/.m2` too — but a release of your plugin is built
|
||||
against a **released** kernel version, never the kernel's `-SNAPSHOT` (§3, point 4). The kernel's
|
||||
`docs/PLUGIN-DEVELOPMENT.md` §3, *Getting the jars*, says the same.
|
||||
|
||||
---
|
||||
|
||||
## 3. The project (pom.xml)
|
||||
|
||||
A plugin is an ordinary Maven `jar` project:
|
||||
|
||||
1. **Depend on `runway-spi` (`provided`) and `runway-spi-testkit` (`test`) — never on `runway-app`, in any scope.**
|
||||
A host import then does not compile, which is the point. `provided` says what is true: the kernel supplies the
|
||||
SPI at runtime and the plugin never ships it (the kernel docs recommend the same). The plugins in this repo
|
||||
declare it with the default `compile` scope, which is harmless here: `runway-spi` is resolved parent-first at
|
||||
runtime, and their zips are built from an explicit file list that never includes a dependency jar.
|
||||
2. **Platform libraries are `provided`.** The host supplies Spring Framework 7, Spring Boot 4, Spring MVC, Spring
|
||||
Security, Thymeleaf, Jackson 3 (incl. `jackson-dataformat-yaml`) and the Jakarta EE 11 APIs; the kernel's MAJOR
|
||||
line pins their MAJOR lines. Compile against the ones you use; never bundle them (a second copy is a second
|
||||
`Class` identity, and by-type collection of your beans silently breaks).
|
||||
3. **No `spring-boot-maven-plugin` repackage** — `mvn package` produces a thin jar of only your classes. Inherit
|
||||
`spring-boot-starter-parent` to get the host's managed versions.
|
||||
4. **Reproducible builds**: set `project.build.outputTimestamp` (bump it per release) so two builds are
|
||||
byte-identical. Build a release against a **released** kernel artifact, never a `-SNAPSHOT`: a snapshot changes
|
||||
under the same version, and so does your jar — compile-time constants such as `RunwaySpi.VERSION` are copied into
|
||||
your classes, and the jar embeds your `pom.xml` (`META-INF/maven/…`). The same holds for any pom edit, the kernel
|
||||
version included: a rebuild with it no longer matches the published archive, so it ships as a new version.
|
||||
|
||||
```xml
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>4.0.6</version><relativePath/>
|
||||
</parent>
|
||||
<groupId>com.acme</groupId><artifactId>runway-plugin-myplugin</artifactId><version>1.0.0</version>
|
||||
<properties>
|
||||
<maven.compiler.release>25</maven.compiler.release>
|
||||
<project.build.outputTimestamp>2026-10-18T00:00:00Z</project.build.outputTimestamp>
|
||||
<runway.version>1.0.0</runway.version> <!-- the kernel RELEASE you build against (SPI 1.0.0) -->
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency><groupId>mx.quest</groupId><artifactId>runway-spi</artifactId><version>${runway.version}</version></dependency>
|
||||
<dependency><groupId>mx.quest</groupId><artifactId>runway-spi-testkit</artifactId><version>${runway.version}</version>
|
||||
<scope>test</scope></dependency>
|
||||
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId>
|
||||
<scope>provided</scope></dependency>
|
||||
<!-- only what you use, all provided: spring-webmvc (a @ConsoleScreen controller), spring-security-core
|
||||
(@PreAuthorize), tools.jackson.dataformat:jackson-dataformat-yaml (your own files), … -->
|
||||
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope></dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<finalName>runway-plugin-myplugin</finalName>
|
||||
<!-- an antrun step that assembles target/<id>/ and target/<artifactId>-<version>.zip — copy demo/pom.xml.
|
||||
The artifactId is runway-plugin-<id> (here the id is myplugin): the release asset is
|
||||
runway-plugin-<id>-<version>.zip. -->
|
||||
</build>
|
||||
```
|
||||
|
||||
(A plugin release pins a **released** kernel in `runway.version` — one published on the kernel's releases page —
|
||||
never a `-SNAPSHOT` (point 4). Moving the pin is a new plugin version; a plugin that needs nothing new from the kernel
|
||||
keeps its pin until its next release. When you copy a first-party pom, `demo/pom.xml` included, set `runway.version`
|
||||
to the release you build against.)
|
||||
|
||||
---
|
||||
|
||||
## 4. The descriptor (plugin.yml)
|
||||
|
||||
Parsed with unknown keys ignored (forward/backward compatible). The **install folder name MUST equal `id`**.
|
||||
|
||||
```yaml
|
||||
id: myplugin # REQUIRED. Path-safe (/[A-Za-z0-9][A-Za-z0-9._-]*/). == install-dir name.
|
||||
name: My Plugin # REQUIRED. Shown in the management UI.
|
||||
version: 1.0.0 # REQUIRED. STRICT plain MAJOR.MINOR.PATCH — no qualifiers.
|
||||
mainClass: com.acme.myplugin.MyPluginConfig # the @Configuration; omit for a code-less library/asset plugin.
|
||||
|
||||
# The LOWEST SPI level whose types you use (the newest type decides): ">=0.4.0" PluginSettings/PluginInfo/
|
||||
# PluginLifecycle; ">=0.5.0" PluginSiteFiles, Sites, RequestContext, AccessCheck, Messages, SitePages, anonymous
|
||||
# routes, siteData; ">=0.6.0" ContentCatalogView, ContentChanges, SiteEventListener, @ConsoleScreen; ">=1.0.0"
|
||||
# HeadContext.origin(). All four are 1.x floors: a plugin declaring any of them loads on every 1.x kernel. A kernel
|
||||
# below it BLOCKS the plugin with a reason. A plugin with a mainClass MUST declare a floor >= 0.4.0: without one it is
|
||||
# blocked as "built for the pre-1.0 plugin contract" (a code-less library plugin is exempt).
|
||||
requiresSpi: ">=0.6.0"
|
||||
|
||||
enabled: true # optional (default true) — the operator's disable switch.
|
||||
essential: false # honored ONLY for kernel security-floor ids on the allowlist ('protection').
|
||||
requires: [ other >= 1.2.0 ] # optional. Forms: `id`, `id >= v`, `id == v` (single space). Never an essential id.
|
||||
conflicts: [ legacy ] # optional. The declaring plugin steps aside if a listed id is installed and enabled.
|
||||
|
||||
# Personal data in your per-site folder (sites/<id>/plugins/<pluginId>/): left OUT of a site's transfer copy and
|
||||
# listed in its manifest; full backups keep it. A trailing "/" names a folder. Rule: any file holding visitor or
|
||||
# user input is personal.
|
||||
siteData:
|
||||
personal:
|
||||
- submissions.tsv
|
||||
|
||||
# Grantable control points, namespaced <id>|<declId>. defaultRoles: leave EMPTY — a control point starts ungranted;
|
||||
# administrators hold it via the wildcard tier and a superadmin grants it explicitly. A reserved/master tier in
|
||||
# defaultRoles is a hard startup failure. The reserved id `settings` gates the per-site settings form.
|
||||
permissions:
|
||||
- { id: settings, realm: tenant, label: myplugin.perm.settings, defaultRoles: [] }
|
||||
- { id: manage, realm: tenant, label: myplugin.perm.manage, defaultRoles: [] }
|
||||
|
||||
# App-level settings (PLATFORM concerns): bound as runway.plugin.<id>.<key> from external/plugin-settings/<id>.yml,
|
||||
# applied on RESTART, read through your own @ConfigurationProperties bean (§7.2).
|
||||
settings:
|
||||
- { key: some.flag, type: boolean, default: true, label: myplugin.settings.flag }
|
||||
|
||||
# Per-site settings (tenant-owned BEHAVIOUR): sites/<siteId>/plugins/<id>.yml, applied IMMEDIATELY, read with
|
||||
# PluginSettings (§7.2). `settings` gates the form.
|
||||
siteSettings:
|
||||
- { key: enabled, type: boolean, default: true, label: myplugin.settings.enabled }
|
||||
- { key: style, type: enum, default: info, range: "info,warning,danger", label: myplugin.settings.style }
|
||||
- { key: apiKey, type: secret, label: myplugin.settings.apiKey }
|
||||
|
||||
# Per-placement widget settings, keyed by the ContentWidget key(): sites/<siteId>/widget-instances.yml; the values
|
||||
# reach the widget as WidgetView.config(). Keep defaults in code.
|
||||
widgetSettings:
|
||||
myhero:
|
||||
- { key: heading, type: string, label: myplugin.widget.heading }
|
||||
|
||||
# Console menu entry. `permission` is the FULL key; visibility is UX only. `icon`: a Font Awesome class.
|
||||
menu:
|
||||
- { realm: tenant, region: menu, order: 60, label: myplugin.menu.link,
|
||||
path: "/__admin/myplugin", permission: "myplugin|manage", icon: "fa-solid fa-feather-pointed" }
|
||||
|
||||
# Dashboard card: `fragment` resolves to __plugin__/<id>/<fragment> = templates/<fragment>.html.
|
||||
dashboardCards:
|
||||
- { realm: tenant, order: 20, fragment: dashboard, permission: "myplugin|manage" }
|
||||
```
|
||||
|
||||
Also understood: `settingGroups` (titled sections of the settings forms) and `helpUrl` — see the kernel's
|
||||
PLUGIN-DEVELOPMENT §5.
|
||||
|
||||
### 4.1 Setting types (and their traps)
|
||||
|
||||
| `type` | Java value | Notes / trap |
|
||||
|-----------|-------------------|--------------|
|
||||
| `string` | `String` | trimmed; blank ⇒ null. Also the fallback for an unknown/misspelled `type` (silent!). |
|
||||
| `secret` | `String` | stored **encrypted** `ENC(...)`. Per-site: absent from `PluginSettings.site()`, read in clear only with `PluginSettings.secret(site, key)`. App-level: the property map carries the ciphertext. |
|
||||
| `text` | `String` | **verbatim** — NOT trimmed, blank NOT nulled (whitespace significant). The only such type. |
|
||||
| `int` | `Long` | `range: "min..max"` / `"min.."` / `"..max"` enforced by the form. Read with `SettingsView.integer(key, fallback, min, max)` to clamp a hand-edited value too. |
|
||||
| `decimal` | `BigDecimal` | **`range` is IGNORED** for decimal. Non-numeric ⇒ form error. |
|
||||
| `boolean` | `Boolean` | truthy iff value ∈ {`true`,`on`,`yes`,`1`} (case-insensitive). |
|
||||
| `enum` | `String` | `range: "a,b,c"` or `"a|b|c"`; value must be a member. |
|
||||
| `list` | `List<String>` | split on comma **or** newline; trimmed; empties dropped. |
|
||||
|
||||
---
|
||||
|
||||
## 5. The mainClass @Configuration
|
||||
|
||||
Register **every** bean **explicitly** with `@Bean` — no `@ComponentScan` of your own package. The kernel's services
|
||||
(§7) arrive as `@Bean` method parameters:
|
||||
|
||||
```java
|
||||
package com.acme.myplugin; // OUTSIDE mx.quest.runway
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class MyPluginConfig {
|
||||
|
||||
@Bean
|
||||
@ConfigurationProperties("runway.plugin.myplugin") // app-level settings (not @EnableConfigurationProperties)
|
||||
public MyAppProps myPluginAppProps() { return new MyAppProps(); }
|
||||
|
||||
@Bean
|
||||
public MyWidget myPluginWidget(PluginSettings settings, Messages messages) { // plugin-scoped + kernel singleton
|
||||
return new MyWidget(settings, messages);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MyEndpoints myPluginEndpoints(AccessCheck access, PluginSiteFiles files) {
|
||||
return new MyEndpoints(access, files);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The kernel checks these rules **before and after refresh**. Before refresh a violation **blocks** the plugin
|
||||
(`plugin '<id>' is blocked: breaks the plugin rules for Runway's shared Spring context (SPI 1.0): bean name '…' does
|
||||
not start with '<prefix>' …`); one that only shows after refresh (a bean the pre-check cannot see) **quarantines** it
|
||||
(§1) with the same reason:
|
||||
|
||||
- **Bean names start with your id in lowerCamelCase** (`my-plugin` → `myPlugin…`). Plugins share one bean namespace
|
||||
with the kernel and each other. The host registers `mainClass` itself as `plugin:<id>`. Use the method name as
|
||||
the bean name. `@EnableConfigurationProperties(X.class)` names its bean `<prefix>-<class name>` and breaks the rule
|
||||
— declare the properties bean with `@Bean @ConfigurationProperties(...)` instead. Templates follow the names
|
||||
(`${@myPluginAdminModel…}`).
|
||||
- **Allowed Spring surface:** SPI implementations and plain beans; `@Controller`s whose every mapping lies under
|
||||
`/__admin/<id>` or `/__app/<id>`; `@ControllerAdvice` restricted to your own packages, types or annotations.
|
||||
**Not allowed:** servlet `Filter`s / `FilterRegistrationBean`s (§6.6), `SecurityFilterChain`s,
|
||||
`BeanPostProcessor`s / `BeanFactoryPostProcessor`s, an unrestricted `@ControllerAdvice`.
|
||||
- **No host linkage.** At startup the kernel reads the constant pool of every class in your jars and **blocks** the
|
||||
plugin, before wiring, for any reference to an `mx.quest.runway` class outside `mx.quest.runway.spi` or a class of
|
||||
yours under `mx.quest.runway` (`plugin '<id>' linkage scan: uses Runway's internal classes, which the plugin
|
||||
contract (SPI 1.0) does not allow (links N kernel classes: …)`), and for a reference to an **SPI type this kernel
|
||||
does not have** (`… needs SPI types this Runway does not have: …`) — then `plugin '<id>' is blocked: …`.
|
||||
- **Collected contributions are plain `@Bean`s — never `@Primary`.** `@Primary` is only for the singleton kernel
|
||||
seams the essential `protection` plugin arms. Return the **concrete** class from a `@Bean` method, so Spring sees
|
||||
every interface it implements before creating it (a class that is both a `ContentSource` and a
|
||||
`SiteEventListener` is collected as both).
|
||||
|
||||
---
|
||||
|
||||
## 6. The extension axes
|
||||
|
||||
All live in `mx.quest.runway.spi`; their immutable model records in `mx.quest.runway.spi.model`. Each has a
|
||||
**`String key()`** that must be **unique and namespaced** (`"myplugin/thing"`): a blank or colliding plugin key is
|
||||
**refused** (logged as an ERROR naming both sides, the plugin marked degraded; its other contributions load). Each
|
||||
has a `default Capabilities capabilities()` — lowercase-dotted flags the host may branch on. Implementations are
|
||||
**functions of their immutable inputs plus the services they were given**: thread-safe, no request objects, return
|
||||
plain values.
|
||||
|
||||
**Containment.** A `RuntimeException`/`LinkageError` from your code on a request path is caught, logged (the first
|
||||
time with the stack, then at most once a minute) and counted on the plugins screen: a head or widget failure yields
|
||||
empty output and the page is served `no-store`; a quality check yields one `WARNING` `check.failed`; an endpoint
|
||||
answers `500` `no-store`; a listener or lifecycle callback is skipped. `BackupParticipant.export` is **not**
|
||||
contained: its failure fails the backup.
|
||||
|
||||
### 6.1 `HeadContributor` — edge `<head>` injection
|
||||
```java
|
||||
String key();
|
||||
String render(HeadContext ctx); // "" (never null) for nothing
|
||||
default List<String> headInputs(String siteId) // site-relative files you read: "plugins/<id>.yml"
|
||||
```
|
||||
Collected (`@Order`-honored), spliced before `</head>` on every rendered page — no tenant template edit. Order after
|
||||
the kernel's own (SEO `@Order(100)`, icons `@Order(90)`) with e.g. `@Order(200)`. You own HTML escaping. Head markup
|
||||
is spliced *after* the page `ETag` is computed: list the per-site files you read in `headInputs` so a change to them
|
||||
moves the validator. Emit plain `<script src>` tags — the kernel stamps the CSP nonce. For an absolute URL (a
|
||||
JSON-LD `@id`, an `og:url`) use **`HeadContext.origin()`** (SPI `1.0.0` — declare `requiresSpi: ">=1.0.0"`): the
|
||||
trusted `scheme://host[:port]` the page is served under — the site's base URL, or, on a host-less site, the request's
|
||||
origin as the trusted-proxy gate left it. Never read the `Host` header.
|
||||
|
||||
### 6.2 `ContentWidget` — a body-content render block
|
||||
```java
|
||||
String key(); // the <type> half of data-widget="<type>/<instance>"
|
||||
RenderFragment render(WidgetView view); // RenderFragment.of(html) / RenderFragment.empty()
|
||||
```
|
||||
Rendered wherever a page carries `<div id="x" data-widget="<key>/<instance>">` (the `id` **and** `data-widget` on the
|
||||
**same** element). `WidgetView` gives `site()`, `page()`, `locale()`, `instanceId()`, `isChrome()`, `config()` (the
|
||||
placement's `widgetSettings:` values; absent key = your default), `query()` (first value per name — read a
|
||||
`?sent`-style flag) and `path()` (the public path being rendered — use it for a return path, never the slug). A
|
||||
widget only *reads*; storing a submission is an endpoint's job.
|
||||
|
||||
### 6.3 `EndpointContributor` — HTTP routes (servlet-free)
|
||||
```java
|
||||
String key();
|
||||
List<Route> routes(); // new Route("GET", "/my/path", Realm.TENANT, SurfacePosture.discoverable())
|
||||
RouteResponse handle(RouteRequest r);
|
||||
```
|
||||
Dispatched on a site's public host. A route is an **exact** path (`*`, `{`, `}` reserved), realm `TENANT`, and must
|
||||
avoid the kernel's surface (`/__app`, `/__admin`, `/__plugin`, `/__assets`, `/__preview`, `/__csp-report`,
|
||||
`/__ui-lang`, `/__health`, `/actuator`, `/app/`, `/login`, `/logout`, `/error`, `/forgot-password`, `/reset`); a
|
||||
route that breaks a rule is refused on its own. `RouteRequest` (frozen) carries:
|
||||
|
||||
- `site()` (a `SiteView`), `locale()` (negotiated: `?lang` → the site's language cookie → `Accept-Language` → site
|
||||
default; always a site locale), `method()`, `path()`;
|
||||
- `query()` — the URL query string only; `form()` — the fields of an `application/x-www-form-urlencoded` body;
|
||||
`param(name)` — query first, then form (`Optional`);
|
||||
- `headers()` — **lowercase** names (lookups ignore case); forwarded headers never reach you;
|
||||
- `clientIp()` — the client address **after** the kernel's trusted-proxy gate (use it for rate limits; never read an
|
||||
`X-Forwarded-For`); `origin()` — `scheme://host[:port]` after the same gate (absolute URLs when the site has no base
|
||||
URL); `body()`.
|
||||
|
||||
Answer with `RouteResponse.text(...)`, `RouteResponse.notFound()` or `new RouteResponse(status, headers, bytes)`.
|
||||
There is no principal in the request; the dispatch runs inside the security chain, so check a permission with
|
||||
`AccessCheck` (§8).
|
||||
|
||||
**`POST` routes and CSRF** (the full rules are §8.1):
|
||||
|
||||
- A **`GET`** route must not change anything. Anything that changes state is a `POST`.
|
||||
- An ordinary (non-anonymous) `POST` route is **CSRF-checked** by the tenant chain: the caller must send the
|
||||
session's token. From your console fragment that is a `<form method="post">` with a hidden field bound to
|
||||
`${_csrf}` (§8.1). `form()` carries **every** body field, whether the token travels as that form field or in
|
||||
the `X-CSRF-TOKEN` header (the `_csrf` field itself is in `form()` too; ignore it), and never a query-string value
|
||||
of the same name. Both a route like this and a `@ConsoleScreen` controller (§7.11) can take an operator's form fields.
|
||||
- A **public form any visitor may submit without an account** (contact, feedback, newsletter) declares an
|
||||
**anonymous** route: `Route.anonymousPost("/my/submit", SurfacePosture.safeDefault())` (§8.1).
|
||||
|
||||
### 6.4 `PageQualityCheck` — content/SEO checks
|
||||
```java
|
||||
String key();
|
||||
List<Finding> inspect(PageView page); // Finding.info/warning/error(code, message); empty list = clean
|
||||
```
|
||||
Never mutates. **Severity has consequences:** on a site set to *Enforced* or *Reviewed* any `ERROR` refuses
|
||||
publishing; keep `ERROR` for something clearly broken the author can fix, `WARNING` for advice. The `PageView` may be
|
||||
a candidate not yet live — judge only the view. `Finding.code()` is looked up as the console message
|
||||
`quality.<code>` (ship it in your `i18n/` to localize).
|
||||
|
||||
### 6.5 `BackupParticipant` — only for data outside the site folder
|
||||
```java
|
||||
String key();
|
||||
void export(BackupWriter out, SiteRef site) throws IOException;
|
||||
void importInto(BackupReader in, SiteRef site) throws IOException;
|
||||
```
|
||||
**You almost certainly do not need it.** Data you keep with `PluginSiteFiles` (§7.3) lives in the site folder,
|
||||
which full backups already carry. The axis stays for data a plugin keeps elsewhere (none of the first-party plugins
|
||||
in 1.0). If you use it: `importInto` must be idempotent and tolerate a missing entry; read and write whole byte arrays
|
||||
(never let a serializer auto-close the archive stream); a failing `export` fails the whole backup.
|
||||
|
||||
### 6.6 Servlet filters — not a plugin seam
|
||||
|
||||
**A plugin cannot contribute a servlet filter.** Servlet filters are outside the Runway 1.0 plugin contract: a
|
||||
filter needs servlet types the SPI does not carry, runs on every request of every site ahead of the kernel's own
|
||||
handling, and no feature plugin needs one. The kernel's `FilterContribution` and its `FilterBand` placement stay
|
||||
kernel concepts (they place the kernel's filters and the essential `protection` plugin's floor). A plugin `Filter`,
|
||||
`FilterRegistrationBean` or `FilterContribution` bean blocks the plugin (§5). To shape a
|
||||
response, use an axis: `<head>` markup (§6.1), a widget (§6.2), an endpoint (§6.3). (A separate
|
||||
`runway-spi-servlet` module could add a filter seam in a later 1.x if a real consumer appears.)
|
||||
|
||||
### 6.7 `ContentSource` — routable content ("virtual pages")
|
||||
```java
|
||||
String key(); // stable; namespaces ids
|
||||
List<ContentRef> enumerate(SiteView site); // published-only, METADATA-ONLY, cheap
|
||||
ContentBody body(SiteView site, String id, Locale locale); // lazy — only for a 200 render
|
||||
default Optional<ContentRef> resolve(SiteView, String path, Locale); // override with an O(1) probe
|
||||
default String indexableText(SiteView, String id, Locale); // HTML/plain text for search (CAP_INDEXABLE_TEXT)
|
||||
default Capabilities capabilities();
|
||||
```
|
||||
Your plugin serves **whole pages at site URLs** (blog entries, product pages) as peers of kernel pages: the
|
||||
locale-dispatch ladder, the tenant's master chrome around your body template, `<head>` treatment, `ETag`/`304`,
|
||||
**sitemap.xml + llms.txt**, by-id links (`${urls['<key>:<id>']}`) and — with `CAP_INDEXABLE_TEXT` — on-site search.
|
||||
The host re-filters your output fail-closed (unpublished items, unsafe paths and reserved URLs are dropped).
|
||||
|
||||
- **`enumerate()` never reads bodies** and returns published content only — it runs on anonymous requests.
|
||||
- **Announce every change with `ContentChanges.changed(siteId, key, id)`** (§7.9) after each mutation (`id` `null`
|
||||
= the whole corpus). It evicts routing, the listing, sitemaps and search on every node.
|
||||
- **`updatedAt` is load-bearing for HTTP caching**: the render `ETag` folds the ref's metadata, never the body —
|
||||
bump `updatedAt` whenever what `body()` returns changes.
|
||||
- **If you cache, drop it from a `SOURCE`-phase `SiteEventListener`** (§7.10): on your own `CONTENT` changes (a
|
||||
replay from another node is how this node learns), on wholesale lifecycle events (`DELETED`, `RESTORED`), on your
|
||||
own settings changes if they reshape URLs. The kernel runs sources before consumers and re-evicts in between.
|
||||
- **`resolve()` must be cheap** — keep an in-memory `path|lang → id` index (printable `|`, never a control char).
|
||||
- **Validate a custom prefix with `ContentCatalogView.servablePath`, and before publishing at a path ask
|
||||
`pageAt`** (§7.8): a real page always wins a contested URL.
|
||||
- **The body template** (`ContentRef.bodyTemplate`, `__plugin__/<id>/<name>`) may rely on exactly: `${master}` (the
|
||||
master to wrap in — pull the chrome with `~{${master} :: head}`, `#site-header`, `#site-footer`, never a literal),
|
||||
`${content.*}` (`id`, `sourceKey`, `title`, `description`, `bodyHtml`, `attributes`, `updatedAt`), `${locale}`,
|
||||
`${urls[…]}`. The file must be byte-identical for every tenant.
|
||||
- **Read only your own data**: your per-site folder (`PluginSiteFiles`) and your per-site settings.
|
||||
|
||||
---
|
||||
|
||||
## 7. The service tier — how a plugin reaches the kernel
|
||||
|
||||
Package `mx.quest.runway.spi.service`: narrow interfaces the **kernel implements** and your plugin **receives by
|
||||
ordinary Spring injection**. They are the only way to reach what the host's own classes hold; a plugin never injects
|
||||
those classes themselves (`SitePluginConfigService`, `SecretCipher`, `StorageLayout`/`SiteFileStore`, `SiteResolver`,
|
||||
`AuthzExpressions`, `SiteAwareMessageSource`, `PageWriteService`, `ContentCatalog`, the host's Spring events,
|
||||
`OperatorShellModel`, `RunwayPlugin`/`PluginContext`) — the linkage scan blocks a jar that links them (§5).
|
||||
Rules for all: no method returns `null`; an unsafe site id, slug or path throws `IllegalArgumentException` before any
|
||||
I/O (a well-formed unknown id is not an error); every service is thread-safe; enums may grow in a MINOR release (give
|
||||
a `switch` a `default`).
|
||||
|
||||
### 7.1 How you get one, and the binding
|
||||
|
||||
| Kind | Services | Bound to |
|
||||
|---|---|---|
|
||||
| **plugin-scoped** | `PluginSettings`, `PluginSiteFiles`, `ContentChanges`, `PluginInfo` | **your plugin, by the jar the injecting class was loaded from** — no method takes a plugin id, so you can only reach your own settings, files and sources |
|
||||
| **kernel singletons** | `Sites`, `RequestContext`, `AccessCheck`, `Messages`, `SitePages`, `ContentCatalogView` | — |
|
||||
| **callbacks you implement** | `PluginLifecycle`, `SiteEventListener` | collected by type; matched to your plugin by jar |
|
||||
|
||||
Inject a plugin-scoped service into a class from your **own top-level jar** (a `@Bean` parameter, a constructor, a
|
||||
field, or an `ObjectProvider<…>`). Injection **fails at startup** from a class in your `lib/` folder (a library is
|
||||
shared by every plugin that bundles it), from kernel code, and through a bare `getBean(PluginSettings.class)`.
|
||||
|
||||
### 7.2 `PluginSettings` — your per-site settings (0.4.0)
|
||||
```java
|
||||
SettingsView site = settings.site(siteId); // defaults overlaid by saved values; secrets absent
|
||||
boolean on = site.bool("enabled", true);
|
||||
long n = site.integer("interval", 5, 1, 60); // clamped
|
||||
Optional<String> key = settings.secret(siteId, "apiKey"); // a type: secret value in clear (ENC decrypted)
|
||||
```
|
||||
Precedence: saved value › descriptor `default` › your code fallback (which matters only for undeclared keys — keep
|
||||
them equal). Accessors never throw: a value that does not parse yields the fallback. A save applies **immediately**
|
||||
on every node. Nested structures: parse `values()` yourself. **Three settings surfaces:**
|
||||
|
||||
- **App-level (`settings:`)** — platform concerns, `runway.plugin.<id>.*`, applied on **restart**, read through your
|
||||
own `@ConfigurationProperties` bean (§5). A `secret` there is ciphertext.
|
||||
- **Per-site (`siteSettings:`)** — `PluginSettings`; react to a save with `SiteEventListener.onSettingsChanged`.
|
||||
- **Per-placement (`widgetSettings:`)** — nothing to read: they arrive as `WidgetView.config()`.
|
||||
|
||||
### 7.3 `PluginSiteFiles` — your per-site data, and personal data (0.5.0)
|
||||
```java
|
||||
Optional<String> text = files.readText(siteId, "notes.yml");
|
||||
files.writeText(siteId, "notes.yml", yaml); // atomic; creates parent folders
|
||||
files.delete(siteId, "x.tsv"); files.deleteTree(siteId, "entries/old"); files.list(siteId, ""); files.stat(...);
|
||||
```
|
||||
Your folder `sites/<id>/plugins/<yourId>/`: inside the site, so full backups carry it and a deleted site takes it
|
||||
along. Paths are relative with `/`; `..`, empty segments, backslashes and symlink escapes are refused. One write is
|
||||
capped (`runway.plugins.site-files.max-write-bytes`, 16 MiB); `readText` refuses a bigger file. Each write is atomic
|
||||
but a **read-modify-write is yours to serialize** (a lock per site). A write for a site whose folder does not exist
|
||||
fails. YAML/JSON go through your own Jackson (a platform library) — read leniently (unknown keys ignored) so a later
|
||||
version can add fields. Writing a file announces nothing: if it shapes routable content, call `ContentChanges`.
|
||||
**Declare personal data** in `siteData.personal` (§4): any file holding visitor or user input.
|
||||
|
||||
### 7.4 `Sites` and `RequestContext` (0.5.0)
|
||||
|
||||
- `Sites.find(siteId)` → `Optional<SiteView>` (suspended sites included), **off-request too**: the way a listener, a
|
||||
background task or a console fragment (which only has `tenantSiteId`) gets a site's name, locales or base URL.
|
||||
- `RequestContext.site()` → the site the **current request** is bound to (a public page or the tenant console);
|
||||
**empty on the application console** and off a request. A console screen uses it to learn which site it manages;
|
||||
an endpoint does not need it (`RouteRequest.site()`).
|
||||
|
||||
### 7.5 `AccessCheck` (0.5.0)
|
||||
|
||||
`access.may("myplugin|manage")` (or a kernel permission: `may("EDIT_PAGES")`) for the current principal, in its realm
|
||||
and tenancy; fail-closed. The same bean is `@authz` in `@PreAuthorize("@authz.may('…')")` and in templates
|
||||
(`${@authz.may('…')}`). See §8.
|
||||
|
||||
### 7.6 `Messages` (0.5.0)
|
||||
|
||||
- `messages.site(siteId, locale, code, fallback, args…)` — **visitor-facing** text: the site's own bundle first,
|
||||
then every plugin's `i18n/` (add-only), in the visitor's locale. Works off-request.
|
||||
- `messages.console(code, fallback, args…)` — **console** text in the **operator's** UI language (the fallback off a
|
||||
request).
|
||||
|
||||
With arguments the text is a `MessageFormat` pattern (write `''` for an apostrophe). A `null` fallback yields the code.
|
||||
|
||||
### 7.7 `SitePages` — install a starter page (0.5.0)
|
||||
```java
|
||||
InstallResult r = pages.install(siteId, new StarterPage(slug, "/contact", Map.of("en", "Contact"), html, logic, false));
|
||||
Optional<String> where = pages.pathOf(siteId, slug); // any state; follows an operator's move
|
||||
```
|
||||
Idempotent, **never overwrites**, and follows the site's editorial level: `PUBLISHED`, `PENDING_REVIEW` (Reviewed
|
||||
site, no `APPROVE_PAGES`), `DRAFT_BLOCKED` (the quality checks blocked it; `blocking()` has the findings),
|
||||
`ALREADY_EXISTS`. Tell the operator which, in words, with a `default` branch. **Check the caller's permission first**
|
||||
(`AccessCheck`) — `SitePages` does not. An unsafe or reserved path throws `IllegalArgumentException`; a path another
|
||||
page serves, an unknown site or a write failure throws `IllegalStateException` (no stray draft is left). The page's
|
||||
logic pulls the chrome through `${master}`.
|
||||
|
||||
### 7.8 `ContentCatalogView` — the site's published content surface (0.6.0)
|
||||
```java
|
||||
List<CatalogEntry> entries = catalog.entries(siteId); // pages ("pages" source; id = slug) + every source's items
|
||||
String path = entry.pathFor(locale); // the URL to link in that locale (never builds one yourself)
|
||||
Optional<String> owner = catalog.pageAt(siteId, "/blog", locale); // the published page that owns a path
|
||||
boolean ok = catalog.servablePath(siteId, "/blog"); // may content live there at all?
|
||||
catalog.refresh(siteId); // a manual reindex only
|
||||
```
|
||||
What a sitemap, an llms.txt or a search index reads. Each `CatalogEntry` carries its `ContentRef`, one
|
||||
`LocalizedUrl(locale, path, canonical)` per available locale (`absolute(origin)`, `alternate(origin)`) and an
|
||||
`xDefaultPath` — computed by the same code as the page `<head>`, so they cannot disagree. Cached per site, evicted
|
||||
by every change that can reshape it (30-second backstop). Metadata only — safe on anonymous paths.
|
||||
|
||||
### 7.9 `ContentChanges` — announce that your content changed (0.6.0)
|
||||
|
||||
`changes.changed(siteId, yourSourceKey, id)` after every mutation of content your `ContentSource` serves (`id`
|
||||
`null` = the whole corpus). Call it **after** the write, outside your own locks (listeners run on your thread before
|
||||
it returns). Refused (`IllegalArgumentException`) for a source key your plugin does not contribute, and
|
||||
(`IllegalStateException`) from inside a `SiteEventListener` callback. It does not refresh HTTP validators — bump
|
||||
`updatedAt`.
|
||||
|
||||
### 7.10 `SiteEventListener` — react to changes (0.6.0)
|
||||
```java
|
||||
public class MyIndex implements SiteEventListener {
|
||||
@Override public Phase phase() { return Phase.CONSUMER; } // SOURCE if you are a content source
|
||||
@Override public void onSiteLifecycle(SiteLifecycleEvent e) { if (e.wholesale()) drop(e.siteId()); }
|
||||
@Override public void onSettingsChanged(SettingsChange c) { … } // YOUR plugin's settings only
|
||||
@Override public void onCatalogChanged(CatalogChange c) { … } // PAGE, CONTENT, SITE, SETTINGS
|
||||
}
|
||||
```
|
||||
- **Order:** all `SOURCE` listeners, then the kernel evicts its listing again, then all `CONSUMER`s; per listener and
|
||||
event: lifecycle, settings, catalog.
|
||||
- **URLs before and after:** a `PAGE`/`CONTENT` change with an id carries `previousUrls` (where the item was — a
|
||||
deleted item still names its old address) and `currentUrls` (where it is now; always empty for `SOURCE`
|
||||
listeners). A notifier submits the union.
|
||||
- **`local`:** `false` for a change replayed from another node. Do external side effects (an e-mail, an IndexNow
|
||||
POST, a file append) only when `local`; evict caches either way.
|
||||
- **Guarantees:** every kernel cache is already evicted; no host lock is held (calling any service is safe); a throw
|
||||
is logged and counted, never propagated. **Duty:** evict, record or enqueue on the writer's thread — slow work goes
|
||||
to your own executor. Changes nobody announces and changes before startup completes are not delivered.
|
||||
|
||||
### 7.11 `@ConsoleScreen` — your own screen in the console (0.6.0)
|
||||
```java
|
||||
@Controller
|
||||
@ConsoleScreen
|
||||
@RequestMapping("/__admin/myplugin")
|
||||
public class MyAdminController {
|
||||
@GetMapping
|
||||
@PreAuthorize("@authz.may('myplugin|manage')")
|
||||
public String list(Model model) {
|
||||
model.addAttribute(ConsoleScreen.CONTENT_TEMPLATE, "__plugin__/myplugin/admin-list");
|
||||
model.addAttribute(ConsoleScreen.PAGE_TITLE_KEY, "myplugin.admin.title");
|
||||
return ConsoleScreen.LAYOUT_VIEW; // "operator/op-layout"
|
||||
}
|
||||
}
|
||||
```
|
||||
The kernel fills the shell (topbar, menus, language switcher, footer) — no `@ControllerAdvice`, no host class. Every
|
||||
mapping under `/__admin/<id>` (tenant console) or `/__app/<id>` (application console), each handler gated with
|
||||
`@authz.may(…)`, every state change a CSRF-checked `POST` (§8.1). Use `RequestContext.site()` for the managed site.
|
||||
The content template's root is `#content`; it may rely on `tenantSiteId`, `_csrf`, `${@<own bean>…}`,
|
||||
`${@authz.may('…')}`, `#{…}`, and what your controller put in the model — nothing else of the shell's model is
|
||||
promised (render your own flash attribute rather than relying on the shell's).
|
||||
|
||||
### 7.12 `PluginInfo` and `PluginLifecycle` (0.4.0)
|
||||
|
||||
`PluginInfo(id, version, installDir)` is your identity — injectable anywhere, and handed to
|
||||
`PluginLifecycle.started(self)`. `started` runs once the platform is up, in plugin load order; `stopping()` at
|
||||
shutdown, reverse order, only if `started` returned. Both block the host's thread: keep them short. Use them to start
|
||||
and stop your own executor, open an index, warm a cache. `RunwaySpi.VERSION` is the SPI you **built against** (a
|
||||
compile-time constant); `RunwaySpi.runtimeVersion()` the kernel's you **run on**.
|
||||
|
||||
### 7.13 Testing with `runway-spi-testkit`
|
||||
|
||||
In-memory fakes with the kernel's input rules, so plugin tests need no kernel and no Spring Boot:
|
||||
|
||||
| Fake | For |
|
||||
|---|---|
|
||||
| `FakePluginSettings` | `.defaults(…)`, `.site(id, values)`, `.secret(id, key, clear)` |
|
||||
| `TempDirSiteFiles(sitesRoot, pluginId)` | `PluginSiteFiles` over a temp folder, with the kernel's three confinement layers, the caps and the missing-site rule |
|
||||
| `FakeSiteServices` | `Sites`, `RequestContext` (`.current(id)`), `AccessCheck` (`.grant(key)`), `Messages` (`.message(…)`), `SitePages` (`.page(…)`, `.nextInstall(outcome)`, `.installs()`) |
|
||||
| `FakeContentCatalog` | `ContentCatalogView`: `.entry(…)`, `.page(…)`, `.route(…)`, `.refreshed()` |
|
||||
| `EventDispatch(pluginId, ownSourceKeys)` | delivers lifecycle/settings/page/catalog events to your listeners in the kernel's phase order with its isolation, and **is** your `ContentChanges` (refusing what the kernel refuses; `.announced()`) |
|
||||
|
||||
Wire your `mainClass` in a plain `AnnotationConfigApplicationContext` with these beans registered to prove the wiring
|
||||
uses services only; drive a `@ConsoleScreen` controller with a standalone `MockMvc`. Add a test that scans your
|
||||
compiled classes for `mx/quest/runway/` outside `spi/` (see `demo`'s `DemoPluginConfigTest`).
|
||||
|
||||
---
|
||||
|
||||
## 8. Control points (permissions) and the `POST` rules
|
||||
|
||||
Declared in `plugin.yml` `permissions:`, merged into the catalog as the **full key `<id>|<declId>`**. Enforce in code
|
||||
with `AccessCheck` — there is no `hasControl(...)`:
|
||||
|
||||
```java
|
||||
if (!access.may("myplugin|manage")) { return RouteResponse.text(403, "Forbidden\n"); } // endpoint
|
||||
@PreAuthorize("@authz.may('myplugin|manage')") // console handler
|
||||
<attr sel="#link" th:if="${@authz.may('myplugin|manage')}"/> // template (UX only)
|
||||
```
|
||||
|
||||
- **Menu/card `permission:` fields must be the FULL key**; a bare decl id resolves to nothing and **hides the entry
|
||||
from everyone**. Menu/card gating is **UX only** — the handler still checks.
|
||||
- `defaultRoles` stays **empty**; a reserved/wildcard tier there is a hard startup failure.
|
||||
- If you declare the reserved `settings` permission (tenant realm), the kernel requires it to open your per-site
|
||||
settings form.
|
||||
|
||||
### 8.1 The `POST` rules
|
||||
|
||||
1. **A `GET` never changes anything.** A link or an `<img>` on another web site can make a signed-in user's browser
|
||||
send any `GET`; the CSRF defence does not cover `GET`.
|
||||
2. **Every state change is a `POST` the kernel CSRF-checks.** Operator actions go in a `@ConsoleScreen` controller
|
||||
(§7.11) — Spring MVC binds the fields — or, for an action on your admin fragment, a non-anonymous endpoint
|
||||
route, which reads the fields with `form()` (§6.3). Either way
|
||||
the console page submits a form carrying the session's token:
|
||||
|
||||
```html
|
||||
<!-- .html (markup only) -->
|
||||
<form id="mp-run-form" method="post" action="/__admin/myplugin/run">
|
||||
<input class="mp-csrf" type="hidden" name="_csrf" value="">
|
||||
<button type="submit" id="mp-run">Run</button>
|
||||
</form>
|
||||
```
|
||||
```xml
|
||||
<!-- .th.xml (logic) -->
|
||||
<attr sel=".mp-csrf"
|
||||
th:attr="name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}"/>
|
||||
```
|
||||
Keep the `action` a constant in the markup (`th:action`/`th:attr` run in a restricted context that forbids
|
||||
`${@bean}`). Answer with a redirect (post/redirect/get) so a reload never repeats the action.
|
||||
3. **A public form that any visitor may submit without an account** — and that sits on a page every visitor shares,
|
||||
so it cannot carry a per-session token — declares an **anonymous** route:
|
||||
`Route.anonymousPost("/myplugin/submit", SurfacePosture.safeDefault())`. The kernel exempts exactly that method
|
||||
and path from CSRF and takes away what a forged submission could use: the handler runs with **no principal**
|
||||
(`AccessCheck.may` is `false`), and only an `application/x-www-form-urlencoded` body is accepted (`415`
|
||||
otherwise). Your duties: read fields from `form()` only (personal text never in a URL); keep abuse guards — a
|
||||
honeypot field, a length cap, a rate limit keyed by `req.clientIp()`, a CAPTCHA through `CaptchaService` when the
|
||||
site has one; answer `303` back with an outcome flag, never a submitted value; declare what you store as personal
|
||||
data. **Never** use it for an action on something a signed-in user owns.
|
||||
|
||||
---
|
||||
|
||||
## 9. Resources — static, templates, admin fragment, i18n
|
||||
|
||||
- **Static assets** — `static/`, served at `/__plugin/<id>/static/**`. Reference by that URL; never copied into
|
||||
tenants.
|
||||
- **Templates** — `templates/`, Thymeleaf **decoupled logic**: `<name>.html` with **zero `th:*`** and a sibling
|
||||
`<name>.th.xml` with every binding; resolved as `__plugin__/<id>/<name>`. A **repeated `id`** in a `.html` is a hard
|
||||
error (a 500); iterated rows use classes and `//` selectors. Fragments (dashboard card, admin fragment) are
|
||||
**bare** — a root element, no `<html>`/`<body>`. A fragment may rely on `tenantSiteId` (null on the application
|
||||
console), `_csrf`, `${@<own bean>…}`, `${@authz.may('…')}` and `#{…}` — nothing else in the console model.
|
||||
- **Admin fragment** — a filename convention: ship `templates/admin.html` and the host renders it **below** your
|
||||
per-site settings form.
|
||||
- **i18n** — `i18n/messages[_xx].properties`, appended (add-only) to the console's **and** every site's message
|
||||
source. Console labels (menu, settings, permissions) and `#{…}` resolve automatically; public text through
|
||||
`Messages.site` (§7.6). Keys live with the plugin; keep every bundle's keys in step.
|
||||
|
||||
---
|
||||
|
||||
## 10. Capabilities
|
||||
|
||||
`Capabilities.of("thing.flag")` from each axis's `capabilities()`. Only host-recognised flags do anything (today
|
||||
`ContentSource.CAP_INDEXABLE_TEXT`; `CAP_ARBITRARY_PATHS` is reserved); the vocabulary is open. The lifecycle hook is
|
||||
§7.12.
|
||||
|
||||
---
|
||||
|
||||
## 11. Build → install → verify
|
||||
|
||||
```bash
|
||||
mvn -o verify # JAVA_HOME on a JDK 25 (§2)
|
||||
# target/<id>/ the install-ready FOLDER
|
||||
# target/<artifactId>-<version>.zip the UI-uploadable ARCHIVE (antrun step; build twice → identical)
|
||||
```
|
||||
|
||||
- **Filesystem install:** `cp -r target/<id> <runway-external>/plugins/`, then **restart** the host. To upgrade,
|
||||
delete the old `<runway-external>/plugins/<id>/` first: `cp -r` over it keeps files the new version no longer
|
||||
has, and the kernel loads **every** `*.jar` in the folder (`plugin.yml` names no jar), so an old jar left beside
|
||||
the new one loads too. The console upload replaces the whole folder.
|
||||
- **Management-UI install:** app console → `/__app/plugins` → install → upload the `.zip` (`plugin.yml` at the root
|
||||
or under one wrapping directory); applied on restart.
|
||||
|
||||
**Verify against the PACKAGED host jar, never `spring-boot:run`** (DevTools' restart classloader loads ZERO plugins),
|
||||
in **ACTIVE** mode (plugins are skipped in WIZARD mode). Each plugin ships `scripts/verify-against-host.sh`
|
||||
(`demo`'s is the model): build offline (never `mvn install`), install into a throwaway deployment
|
||||
(`VERIFY_TMPDIR`), boot the kernel named by `HOST_JAR`, run the first-run wizard,
|
||||
reboot ACTIVE, then check — and keep the logs (`VERIFY_LOG_DIR`):
|
||||
|
||||
1. **Loads cleanly:** `plugins: N registered, 0 blocked`; **no** `plugin '<id>' linkage scan:` line, no
|
||||
`plugin '<id>' is blocked:` line (linkage, `requiresSpi` floor, or `breaks the plugin rules for Runway's shared
|
||||
Spring context`), no `QUARANTINED`, no collision (`contribution refused`) or degraded warning.
|
||||
2. **Serves:** your endpoints, `/__plugin/<id>/static/**`, head injection, widgets on a page, the console screen and
|
||||
card as a signed-in user, permission refusals (`403`), `POST`s refused without the CSRF token, an anonymous route
|
||||
accepting a form with none, a transfer copy omitting your personal data.
|
||||
|
||||
---
|
||||
|
||||
## 12. Pitfalls (paid for already)
|
||||
|
||||
1. **WIZARD mode = ZERO plugins.** Before first-run setup completes, discovery is skipped entirely.
|
||||
2. **Never depend on or bundle `runway-app`; never repackage.** Only `runway-spi` (+ the testkit for tests); platform
|
||||
libraries `provided`; jar thin. A plugin linking host classes is blocked.
|
||||
3. **Plugin-scoped services bind by jar.** Inject `PluginSettings`/`PluginSiteFiles`/`ContentChanges`/`PluginInfo`
|
||||
in your own top-level classes — not from `lib/`, not with `getBean`.
|
||||
4. **Bean names start with your id** (lowerCamelCase); no `@EnableConfigurationProperties`; no `@Primary` on collected
|
||||
contributions; a colliding or blank `key()` is refused.
|
||||
5. **No servlet filters, security chains or post-processors** — not part of the plugin contract.
|
||||
6. **Two config surfaces differ:** app-level = property source, restart-only, your `@ConfigurationProperties`;
|
||||
per-site = `PluginSettings`, immediate, `onSettingsChanged`.
|
||||
7. **Setting-type traps:** `text` isn't trimmed; `decimal` ignores `range`; an unknown `type` is silently `string`.
|
||||
8. **`POST` rules:** a `GET` changes nothing; state changes are CSRF-checked `POST`s from forms carrying `${_csrf}`
|
||||
(§8.1); a non-anonymous endpoint `POST` reads every form field with `form()` (§6.3);
|
||||
`Route.anonymousPost` only for public visitor forms, with your own abuse guards.
|
||||
9. **Announce content changes** with `ContentChanges` after every write — never from a listener callback — and bump
|
||||
`updatedAt` when a body changes.
|
||||
10. **Listeners:** side effects only when `local`; evict on wholesale events; never heavy work on the writer's thread.
|
||||
11. **Thymeleaf:** decoupled `.th.xml`; no repeated `id`; fragments bare; `id` + `data-widget` on one element; never
|
||||
a literal `__plugin__/…` inside `~{…}` (pass it through a variable, e.g. `${master}`).
|
||||
12. **Menu/card `permission` = full namespaced key**, or the entry is hidden from everyone; handlers still check.
|
||||
13. **Personal data is declared** (`siteData.personal`), or a transfer copy hands it to an outsider.
|
||||
14. **Install/upgrade/remove is RESTART-ONLY**; declare `requiresSpi` so an older kernel blocks you with a reason
|
||||
instead of failing at the first request.
|
||||
|
||||
---
|
||||
|
||||
*Grounded in the Runway kernel at SPI `1.0.0` (Runway `1.0.0`: the log lines quoted in §5 and §11 are its
|
||||
`HostLinkageScanner`, `PluginContextInitializer` and `PluginResolution` texts) and verified against the packaged host
|
||||
jar. When the kernel
|
||||
adds or changes a seam, update this guide in the same change.*
|
||||
@@ -0,0 +1,10 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [10.4.0] — 2026-10-21
|
||||
|
||||
First public release of `lucene-provider`: one deployment-wide copy of Apache Lucene 10.4.0 for the plugins that use
|
||||
it (`search-lucene`). Its version is the Lucene version it ships. The plugin's packaging is licensed under the GNU
|
||||
AGPL v3.0 with an additional permission for plugins (`LICENSE`, `LICENSE-EXCEPTION`); the bundled Lucene jars stay
|
||||
under the Apache License 2.0, each with its own LICENSE and NOTICE.
|
||||
@@ -0,0 +1,661 @@
|
||||
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.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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/>.
|
||||
@@ -0,0 +1,44 @@
|
||||
Runway — additional permission for plugins
|
||||
(an additional permission under section 7 of the GNU Affero General Public License, version 3)
|
||||
|
||||
Copyright (C) 2026 Quest ICT SAS de CV
|
||||
|
||||
Runway 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, version 3
|
||||
(the file LICENSE), with the additional permission below. Runway 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.
|
||||
|
||||
1. Definitions
|
||||
|
||||
"Runway" means the Runway kernel and every Runway plugin whose source carries this file.
|
||||
|
||||
"Published SPI" means the public classes and interfaces of the runway-spi artifact
|
||||
(the package mx.quest.runway.spi and its subpackages), together with the public classes
|
||||
and interfaces of any package named "spi" that a part of Runway publishes for other
|
||||
plugins to use (for example mx.quest.search.spi).
|
||||
|
||||
"Plugin" means an independent module that Runway loads as a plugin, that interacts with
|
||||
Runway only through the Published SPI, and that is not based on any part of Runway other
|
||||
than the Published SPI.
|
||||
|
||||
2. Permission
|
||||
|
||||
As an additional permission, the copyright holder gives you permission to combine Runway
|
||||
with Plugins, and to convey and run the resulting combination, without the terms of the
|
||||
GNU Affero General Public License applying to those Plugins. You may license, convey and
|
||||
run your Plugins under terms of your choice, provided that you continue to meet the terms
|
||||
of the GNU Affero General Public License for Runway itself, including offering the
|
||||
Corresponding Source of Runway, and of any modification you make to it, as that license
|
||||
requires.
|
||||
|
||||
3. Testing
|
||||
|
||||
Compiling a Plugin's tests against the runway-spi-testkit artifact, and running them, does
|
||||
not by itself make the Plugin subject to the GNU Affero General Public License.
|
||||
|
||||
4. Modified versions
|
||||
|
||||
If you modify Runway, you may extend this additional permission to your version, but you
|
||||
are not obliged to do so. If you do not wish to, delete this file from your version.
|
||||
@@ -0,0 +1,98 @@
|
||||
# Runway Lucene Libraries Provider (`lucene-provider`)
|
||||
|
||||
A **code-less library-provider plugin** for [Runway](../README.md). It ships **no Java code and no `mainClass`** —
|
||||
only the **Apache Lucene** stack under `lib/`, so it loads **once** onto the shared plugin classloader as the
|
||||
**single, deployment-wide** copy of Lucene. Any plugin that needs full-text search (e.g.
|
||||
[`search-lucene`](../search-lucene)) compiles Lucene as `provided` and declares a hard dependency on this provider.
|
||||
|
||||
- **Plugin id:** `lucene-provider` — install folder `external/plugins/lucene-provider/`
|
||||
- **Version:** `10.4.0` — the plugin version **IS** the Lucene version (the *version tracks the principal
|
||||
library* convention taken literally: a `lucene-provider 10.4.0` *is* Apache Lucene 10.4.0).
|
||||
- **Bundled jars (`lib/`):**
|
||||
- `lucene-core-10.4.0.jar` — the Lucene core (index, `IndexWriter`/`IndexSearcher`, the query classes:
|
||||
`TermQuery`, `PhraseQuery`, `FuzzyQuery`, `BooleanQuery`, `ConstantScoreQuery`, `BoostQuery`; the
|
||||
directories: `ByteBuffersDirectory` (heap) and `MMapDirectory` (disk); BM25 similarity).
|
||||
- `lucene-analysis-common-10.4.0.jar` — analysis: the per-language `Analyzer`s and stemmers
|
||||
(`EnglishAnalyzer`, `SpanishAnalyzer`, …), `StandardAnalyzer`, `CustomAnalyzer`, the token-filter factories.
|
||||
- `lucene-highlighter-10.4.0.jar` — query-focused highlighting (`UnifiedHighlighter`,
|
||||
`DefaultPassageFormatter`) for `<mark>`-wrapped result snippets.
|
||||
- `lucene-memory-10.4.0.jar` — the in-memory index used by the highlighter (transitive of highlighter).
|
||||
- `lucene-queries-10.4.0.jar` — extra query support used by the highlighter (transitive of highlighter).
|
||||
|
||||
## Why a standalone provider
|
||||
|
||||
Lucene ships as a **first-class shared provider** rather than following the default
|
||||
"a bundled library stays private until a *second* consumer exists" rule. The reasoning: the shared plugin
|
||||
classloader holds exactly **one** version of any library deployment-wide, so every plugin that needs full-text
|
||||
search binds to **one agreed** Lucene version here, never its own private (and possibly clashing) copy.
|
||||
|
||||
`search-lucene` (currently the only consumer) binds to this provider: its `pom.xml` marks Lucene `provided` and
|
||||
it declares:
|
||||
|
||||
```yaml
|
||||
requires: [ "lucene-provider == 10.4.0" ]
|
||||
```
|
||||
|
||||
`==` (exact) rather than `>=` because a consumer is **compiled against these binaries** — a Lucene major/minor
|
||||
can move or rename internal classes, so a consumer must run against the very version it was built with. If
|
||||
`lucene-provider` is missing, disabled, or a different version, the consumer is **not loaded** (skipped with a
|
||||
precise reason and shown "Blocked" in the management UI) — so it never wires against a class the classloader
|
||||
can't supply.
|
||||
|
||||
## Consuming it (for plugin authors)
|
||||
|
||||
1. In your `plugin.yml`: `requires: [ "lucene-provider == 10.4.0" ]` (pin the exact version you compiled against).
|
||||
2. In your `pom.xml`: depend on the Lucene artifacts you use (`org.apache.lucene:lucene-core`,
|
||||
`lucene-analysis-common`, `lucene-highlighter`, …) at **`provided`** scope — the provider supplies them at
|
||||
runtime. **Never** bundle Lucene into your own plugin's `lib/` (that would be a second copy on the shared
|
||||
classloader).
|
||||
3. At runtime, use plain Lucene (`IndexWriter`, `IndexSearcher`, the query classes, the analyzers, the
|
||||
`UnifiedHighlighter`). All five bundled jars are on the shared classloader.
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
export JAVA_HOME=<path to a JDK 25>
|
||||
mvn -DskipTests package
|
||||
# → target/lucene-provider/ the install-ready FOLDER (plugin.yml + lib/)
|
||||
# → target/runway-plugin-lucene-provider-10.4.0.zip the UI-uploadable ARCHIVE (/__app/plugins)
|
||||
```
|
||||
|
||||
The first build downloads its Maven dependencies, the Lucene jars included. It needs nothing of Runway in `~/.m2`.
|
||||
|
||||
- **Filesystem install:** `cp -r target/lucene-provider <runway-external>/plugins/` then **restart** the host.
|
||||
- **Management-UI install:** `/__app/plugins` → install → upload the `.zip`, then restart.
|
||||
|
||||
There are no tests: a code-less bundle has nothing to unit-test. Its correctness is "the five jars are present
|
||||
and the descriptor has no `mainClass`" — verified by the `package` output above.
|
||||
|
||||
## Bumping the Lucene version
|
||||
|
||||
Edit `pom.xml`: change `lucene.version`, then set **both** the `<version>` element **and** `plugin.yml`'s
|
||||
`version:` to the new Lucene version (they must stay identical). Rebuild. Every consumer pinned with
|
||||
`== <version>` must be **recompiled and re-cut** against the new version — that is the deliberate cost of the
|
||||
exact pin, and the price of a single shared Lucene copy.
|
||||
|
||||
## Log messages you can ignore
|
||||
|
||||
Once per start of the host, the first time a consumer (`search-lucene`) uses Lucene, the log shows:
|
||||
|
||||
```
|
||||
WARN … o.a.l.i.v.VectorizationProvider : Java vector incubator module is not readable. For optimal vector performance, pass '--add-modules jdk.incubator.vector' to enable Vector API.
|
||||
```
|
||||
|
||||
It comes from the Lucene jars in this bundle. Nothing is wrong. **Leave it off**:
|
||||
the flag only speeds up Lucene's vector maths, which serves mainly k-nearest-neighbour vector search, and Runway's
|
||||
search is keyword search over small indexes; and `jdk.incubator.vector` is an incubator module, so the JVM would
|
||||
print `WARNING: Using incubator modules: jdk.incubator.vector` at every start and depend on a JDK API that is not
|
||||
final. To turn it on anyway, use a `JAVA_OPTS` drop-in, never the main unit: the steps are in
|
||||
[`search-lucene`'s README](../search-lucene/README.md#log-messages-you-can-ignore).
|
||||
|
||||
## License
|
||||
|
||||
GNU Affero General Public License v3.0 with an additional permission for plugins (`LICENSE`, `LICENSE-EXCEPTION`),
|
||||
copyright Quest ICT SAS de CV. The permission means that a plugin which uses only the published SPI, including
|
||||
search's own SPI for engines, may carry any license.
|
||||
|
||||
The zip bundles Apache Lucene, which stays under the Apache License 2.0: each Lucene jar in `lib/` carries its own
|
||||
`LICENSE` and `NOTICE` (under `META-INF/`). The AGPL applies to this plugin's own packaging.
|
||||
@@ -0,0 +1,97 @@
|
||||
# Runway Lucene Libraries Provider — design & reference
|
||||
|
||||
> A **code-less library-provider plugin**: a `plugin.yml` with **no `mainClass`** plus `lib/*.jar`, whose only
|
||||
> job is to place Apache Lucene **once** on the shared plugin classloader for other plugins to consume. Grounded
|
||||
> in the Runway kernel as built — the reference code-less library provider.
|
||||
|
||||
## 1. What it is
|
||||
|
||||
`lucene-provider` ships **no Java code**. Its bundle is exactly:
|
||||
|
||||
```
|
||||
lucene-provider/
|
||||
├── plugin.yml # id, name, version — NO mainClass
|
||||
└── lib/
|
||||
├── lucene-core-10.4.0.jar # index + queries + directories + BM25 (the principal library)
|
||||
├── lucene-analysis-common-10.4.0.jar # per-language analyzers + stemmers + token filters
|
||||
├── lucene-highlighter-10.4.0.jar # UnifiedHighlighter → <mark>-wrapped query-focused snippets
|
||||
├── lucene-memory-10.4.0.jar # in-memory index the highlighter needs (transitive)
|
||||
└── lucene-queries-10.4.0.jar # extra query support the highlighter needs (transitive)
|
||||
```
|
||||
|
||||
The kernel scans `lib/` one level deep and loads every jar into the **one** shared child classloader, so the
|
||||
Lucene stack is available deployment-wide as a single copy. A code-less plugin (no `mainClass`) is first-class:
|
||||
nothing is registered into the Spring context; it only contributes libraries.
|
||||
|
||||
## 2. Why a standalone provider (a deliberate divergence)
|
||||
|
||||
The general rule is "a bundled library stays **private** inside its one consumer until a **second** consumer
|
||||
exists, then it graduates to a provider plugin." Here Lucene is a **standalone provider** even though
|
||||
`search-lucene` is still the only consumer. The reasoning holds regardless of
|
||||
consumer count: the shared classloader permits exactly **one** version of any library deployment-wide, so Lucene
|
||||
belongs in **one agreed place** that every full-text plugin binds to with `requires:` — never a private copy per
|
||||
plugin that could clash. (`search-lucene` binds here.)
|
||||
|
||||
## 3. Version tracks the principal library — literally
|
||||
|
||||
The plugin `version` is **`10.4.0`**: the plugin version *is* the Lucene version. Consumers gate on it with the
|
||||
**exact** operator:
|
||||
|
||||
- `requires: [ "lucene-provider == 10.4.0" ]` — the only correct form for a Lucene consumer.
|
||||
|
||||
Why `==` and not `>=`: a consumer is **compiled against these binaries**. Lucene does not promise cross-version
|
||||
binary stability for the internal classes plugins touch (index formats, analysis, query internals), so a
|
||||
consumer must run against the very version it was built with. `>=` would let a newer, binary-incompatible Lucene
|
||||
satisfy the gate and blow up at wire/run time.
|
||||
|
||||
Bumping: change `lucene.version` in `pom.xml`, then set **both** the pom `<version>` and `plugin.yml` `version:`
|
||||
to the new Lucene version (identical), and rebuild. Every `==` consumer must be **recompiled and re-cut** — the
|
||||
deliberate cost of one shared Lucene copy.
|
||||
|
||||
## 4. Consuming it (the `provided` rule)
|
||||
|
||||
A consumer plugin (see [`../../search-lucene`](../../search-lucene) for the worked example):
|
||||
|
||||
1. `plugin.yml`: `requires: [ "lucene-provider == 10.4.0" ]` — a **hard load gate**. If the provider is missing,
|
||||
disabled, or a different version, the consumer is **not loaded** (skipped with a reason; "Blocked" in the
|
||||
management UI), so it never wires against a class the classloader can't supply.
|
||||
2. `pom.xml`: the Lucene artifacts at **`provided`** scope (compile-only). **Never** bundle Lucene into the
|
||||
consumer's own `lib/` — that would be a second copy on the shared classloader.
|
||||
3. Runtime: plain Lucene (`IndexWriter`, `IndexSearcher`, the query classes, the analyzers, the
|
||||
`UnifiedHighlighter`). All five bundled jars are on the shared classloader.
|
||||
|
||||
## 5. Build & install
|
||||
|
||||
```bash
|
||||
export JAVA_HOME=<path to a JDK 25>
|
||||
mvn -DskipTests package
|
||||
# → target/lucene-provider/ the install-ready FOLDER (plugin.yml + lib/)
|
||||
# → target/runway-plugin-lucene-provider-10.4.0.zip the UI-uploadable ARCHIVE
|
||||
```
|
||||
|
||||
The first build downloads its Maven dependencies, the Lucene jars included. It needs nothing of Runway in `~/.m2`.
|
||||
|
||||
- **Filesystem:** `cp -r target/lucene-provider <runway-external>/plugins/` then **restart**.
|
||||
- **Management UI:** `/__app/plugins` → install → upload the `.zip`, then restart.
|
||||
|
||||
## 6. Verify
|
||||
|
||||
There is nothing to unit-test in a code-less bundle. Correctness = "the descriptor has no `mainClass` and the
|
||||
five Lucene jars are present in `lib/`", which the `package` output shows. Functionally it is verified **through a
|
||||
consumer**: install `lucene-provider` + `search` + `search-lucene`, boot the host in ACTIVE mode, and confirm the
|
||||
startup log shows all three plugins `registered, 0 blocked` (i.e. `search-lucene`'s
|
||||
`requires: lucene-provider == 10.4.0` was satisfied) and that `/search` returns Lucene-ranked results.
|
||||
|
||||
## 7. Pitfalls
|
||||
|
||||
- **A code-less plugin has NO `mainClass` and NO thin jar** — do not add one. The pom packaging is `pom` and
|
||||
produces only the assembled bundle.
|
||||
- **One Lucene version deployment-wide.** Never let a second plugin bundle Lucene privately; add it as a
|
||||
`requires:` consumer of this provider instead.
|
||||
- **Keep the plugin version == the Lucene version** and consumers pinned with `==`. A drift defeats the whole
|
||||
"version tracks the principal library" contract, and a `>=` consumer would risk a binary-incompatible Lucene.
|
||||
- **The `jdk.incubator.vector` log line is expected.** Lucene logs `Java vector incubator module is not readable.
|
||||
For optimal vector performance, pass '--add-modules jdk.incubator.vector' to enable Vector API.` once per start.
|
||||
Runway leaves the flag off: its search uses no vectors, and the module is an incubating JDK API that
|
||||
makes the JVM warn at every start. See the lucene-provider [README](../README.md#log-messages-you-can-ignore) and
|
||||
search-lucene's [design doc §8](../../search-lucene/docs/SEARCH-LUCENE-PLUGIN.md#8-log-messages-you-can-ignore).
|
||||
@@ -0,0 +1,31 @@
|
||||
# =============================================================================
|
||||
# Runway Lucene Libraries Provider — descriptor (CODE-LESS library-provider plugin)
|
||||
#
|
||||
# This plugin ships NO code and NO mainClass. It carries the Apache Lucene stack
|
||||
# (core + analysis-common + highlighter + memory + queries) under lib/*.jar so it
|
||||
# loads once onto the shared plugin classloader — the SINGLE, deployment-wide
|
||||
# copy of Lucene. Consumer plugins (e.g. `search-lucene`) compile Lucene as
|
||||
# `provided` and declare an EXACT dependency:
|
||||
# requires: [ "lucene-provider == 10.4.0" ]
|
||||
# `==` (exact) because they are compiled against THESE binaries — a Lucene major
|
||||
# can move/rename internal classes, so a consumer must run against the very
|
||||
# version it was built with.
|
||||
#
|
||||
# Why a standalone provider: Lucene ships as a first-class shared provider so
|
||||
# any plugin needing full-text search binds to ONE agreed Lucene version, never
|
||||
# its own private (and possibly clashing) copy on the shared classloader.
|
||||
#
|
||||
# Version tracks the PRINCIPAL library taken literally: the plugin version IS the
|
||||
# Lucene version (10.4.0). Bump this `version` and the pom's ${lucene.version}
|
||||
# together on a Lucene upgrade, and re-cut every consumer pinned to `== <ver>`.
|
||||
#
|
||||
# The install folder name MUST equal this `id`: external/plugins/lucene-provider/.
|
||||
# =============================================================================
|
||||
id: lucene-provider
|
||||
name: Lucene Libraries Provider (Apache Lucene)
|
||||
version: 10.4.0
|
||||
enabled: true
|
||||
|
||||
# No mainClass → code-less: nothing is registered into the Spring context.
|
||||
# No requires → always loads (it only provides libraries).
|
||||
# NOT essential → a normal optional provider; if absent, dependents are skipped.
|
||||
@@ -0,0 +1,176 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<!--
|
||||
A CODE-LESS library-provider plugin: there is NO Java source and NO mainClass. `mvn package` produces NO
|
||||
thin jar of its own; it only assembles the installable bundle = plugin.yml + lib/*.jar (the Apache Lucene
|
||||
stack). Inherit spring-boot-starter-parent purely for its dependency-plugin/antrun defaults; the Lucene
|
||||
versions are pinned explicitly below (Lucene is NOT on the Spring Boot BOM), so the jars we bundle are the
|
||||
exact 10.4.0 artifacts every consumer compiles against.
|
||||
|
||||
The plugin VERSION *is* the Lucene version (10.4.0) — the "version tracks the principal library"
|
||||
convention taken to its literal conclusion: a lucene-provider 10.4.0 IS Apache Lucene 10.4.0. Consumers
|
||||
declare `requires: [ "lucene-provider == 10.4.0" ]` (EXACT: they are compiled against these binaries) and
|
||||
compile Lucene as `provided`. Bump this pom's <version> AND the ${lucene.version} together on a Lucene
|
||||
upgrade, and re-cut every consumer that pins `== <new version>`.
|
||||
-->
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>4.0.6</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-plugin-lucene-provider</artifactId>
|
||||
<version>10.4.0</version>
|
||||
<packaging>pom</packaging>
|
||||
<name>Runway Lucene Libraries Provider (Apache Lucene)</name>
|
||||
<licenses>
|
||||
<license>
|
||||
<name>GNU Affero General Public License v3.0, with the Runway additional permission for plugins</name>
|
||||
<url>https://www.gnu.org/licenses/agpl-3.0.txt</url>
|
||||
<distribution>repo</distribution>
|
||||
<comments>See LICENSE and LICENSE-EXCEPTION.</comments>
|
||||
</license>
|
||||
</licenses>
|
||||
<description>
|
||||
A code-less Runway library-provider plugin bundling the Apache Lucene stack (core + analysis-common +
|
||||
highlighter + memory + queries) under lib/, so it loads once onto the shared plugin classloader as the
|
||||
single deployment-wide copy of Lucene. Consumers declare `requires: [ "lucene-provider == 10.4.0" ]`
|
||||
and compile Lucene as `provided`. No mainClass, no code. The plugin version IS the Lucene version.
|
||||
</description>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<!-- Reproducible builds: pins every archive entry's timestamp so two builds of the same source
|
||||
produce byte-identical artifacts. Without it a jar embeds the build time, so a rebuild can
|
||||
never match what was published. Bump at each release. -->
|
||||
<project.build.outputTimestamp>2026-08-24T00:00:00Z</project.build.outputTimestamp>
|
||||
<maven.compiler.release>25</maven.compiler.release>
|
||||
<!-- The PRINCIPAL library this provider tracks; the plugin version above mirrors it exactly. -->
|
||||
<lucene.version>10.4.0</lucene.version>
|
||||
</properties>
|
||||
|
||||
<!-- Declared only so `dependency:copy` resolves them from the local repo (all are already installed). None
|
||||
is compiled against here — there is no code. They ship in the bundle's lib/, NOT on the app classpath.
|
||||
lucene-highlighter pulls in lucene-memory + lucene-queries transitively; we bundle all three explicitly
|
||||
so the install folder is self-documenting and self-contained (no transitive surprises at run time). -->
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-core</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-analysis-common</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-highlighter</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-memory</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-queries</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<!-- 1. Copy EXACTLY the five Lucene jars (version pinned above) into the staged bundle's lib/.
|
||||
stripVersion=false keeps the versioned filenames (self-documenting the Lucene stack). -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>bundle-lucene-libs</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>copy</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<artifactItems>
|
||||
<artifactItem>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-core</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
</artifactItem>
|
||||
<artifactItem>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-analysis-common</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
</artifactItem>
|
||||
<artifactItem>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-highlighter</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
</artifactItem>
|
||||
<artifactItem>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-memory</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
</artifactItem>
|
||||
<artifactItem>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-queries</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
</artifactItem>
|
||||
</artifactItems>
|
||||
<outputDirectory>${project.build.directory}/lucene-provider/lib</outputDirectory>
|
||||
<stripVersion>false</stripVersion>
|
||||
<overWriteReleases>true</overWriteReleases>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<!-- 2. Assemble both installable forms: target/lucene-provider/ (folder = plugin.yml + lib/) and the
|
||||
UI-uploadable target/runway-plugin-lucene-provider-<version>.zip (a single wrapping dir). -->
|
||||
<plugin>
|
||||
<artifactId>maven-antrun-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>assemble-plugin-folder</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>run</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<target>
|
||||
<property name="stage" value="${project.build.directory}/lucene-provider"/>
|
||||
<!-- lib/ was populated by dependency:copy above; add only the descriptor. -->
|
||||
<copy file="${project.basedir}/plugin.yml" todir="${stage}"/>
|
||||
<copy file="${project.basedir}/LICENSE" todir="${stage}"/>
|
||||
<copy file="${project.basedir}/LICENSE-EXCEPTION" todir="${stage}"/>
|
||||
<touch datetime="${project.build.outputTimestamp}"
|
||||
pattern="yyyy-MM-dd'T'HH:mm:ss'Z'">
|
||||
<fileset dir="${stage}"/>
|
||||
<dirset dir="${stage}"/>
|
||||
<dirset dir="${project.build.directory}" includes="lucene-provider"/>
|
||||
</touch>
|
||||
<zip destfile="${project.build.directory}/runway-plugin-lucene-provider-${project.version}.zip">
|
||||
<zipfileset dir="${project.build.directory}" includes="lucene-provider/**"/>
|
||||
</zip>
|
||||
<echo message="Staged install folder (plugin.yml + lib/): ${stage}"/>
|
||||
<echo message="UI-uploadable archive: ${project.build.directory}/runway-plugin-lucene-provider-${project.version}.zip"/>
|
||||
</target>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,10 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [3.3.0] — 2026-10-21
|
||||
|
||||
First public release of `search-lucene`: an Apache Lucene engine for the `search` plugin — one index per site and
|
||||
language, language analyzers (stemming), tiered ranking over BM25, fuzzy matching and highlighting. Requires SPI `1.0.0` (Runway `1.0.0` or later),
|
||||
`search >= 2.2.0` and `lucene-provider == 10.4.0`. Licensed under the GNU AGPL v3.0 with an additional permission for
|
||||
plugins (`LICENSE`, `LICENSE-EXCEPTION`).
|
||||
@@ -0,0 +1,661 @@
|
||||
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.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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/>.
|
||||
@@ -0,0 +1,44 @@
|
||||
Runway — additional permission for plugins
|
||||
(an additional permission under section 7 of the GNU Affero General Public License, version 3)
|
||||
|
||||
Copyright (C) 2026 Quest ICT SAS de CV
|
||||
|
||||
Runway 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, version 3
|
||||
(the file LICENSE), with the additional permission below. Runway 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.
|
||||
|
||||
1. Definitions
|
||||
|
||||
"Runway" means the Runway kernel and every Runway plugin whose source carries this file.
|
||||
|
||||
"Published SPI" means the public classes and interfaces of the runway-spi artifact
|
||||
(the package mx.quest.runway.spi and its subpackages), together with the public classes
|
||||
and interfaces of any package named "spi" that a part of Runway publishes for other
|
||||
plugins to use (for example mx.quest.search.spi).
|
||||
|
||||
"Plugin" means an independent module that Runway loads as a plugin, that interacts with
|
||||
Runway only through the Published SPI, and that is not based on any part of Runway other
|
||||
than the Published SPI.
|
||||
|
||||
2. Permission
|
||||
|
||||
As an additional permission, the copyright holder gives you permission to combine Runway
|
||||
with Plugins, and to convey and run the resulting combination, without the terms of the
|
||||
GNU Affero General Public License applying to those Plugins. You may license, convey and
|
||||
run your Plugins under terms of your choice, provided that you continue to meet the terms
|
||||
of the GNU Affero General Public License for Runway itself, including offering the
|
||||
Corresponding Source of Runway, and of any modification you make to it, as that license
|
||||
requires.
|
||||
|
||||
3. Testing
|
||||
|
||||
Compiling a Plugin's tests against the runway-spi-testkit artifact, and running them, does
|
||||
not by itself make the Plugin subject to the GNU Affero General Public License.
|
||||
|
||||
4. Modified versions
|
||||
|
||||
If you modify Runway, you may extend this additional permission to your version, but you
|
||||
are not obliged to do so. If you do not wish to, delete this file from your version.
|
||||
@@ -0,0 +1,92 @@
|
||||
# Runway Search — Lucene engine
|
||||
|
||||
A Lucene-backed `SiteSearchEngine` for the [`search`](../search) plugin: a full-text index over the search
|
||||
plugin's `SearchCorpus` — every published page and content-source item the site has not excluded
|
||||
from search — each item's
|
||||
**title, description and body** with **per-locale stemming analysis**, a **tiered constant-score** relevance
|
||||
model (exact phrase → near phrase → all terms → any term), **fuzzy** (typo-tolerant) matching, and query-focused
|
||||
`<mark>` highlighting. Install it alongside `search` and it **transparently upgrades** the search box + `/search`
|
||||
results page — no change to that query surface.
|
||||
|
||||
- **Plugin id:** `search-lucene` (v`3.3.0`) — install folder `external/plugins/search-lucene/`
|
||||
- **Requires:** a Runway kernel with SPI `1.0.0` or later (`requiresSpi: ">=1.0.0"`, a floor every `1.x` kernel meets), `search >= 2.2.0` **and**
|
||||
`lucene-provider == 10.4.0`. With search 2.1.x, keep 3.1.0; with search 2.0.0, keep 3.0.0.
|
||||
- **Links:** only the Runway SPI (`mx.quest.runway.spi`) and the search SPI (`mx.quest.search.spi`)
|
||||
- **Java package:** `mx.quest.searchlucene` · **Lucene:** supplied by the [`lucene-provider`](../lucene-provider)
|
||||
plugin (compiled `provided`, **not** bundled here)
|
||||
|
||||
## Why a separate plugin
|
||||
|
||||
`search` splits search into a **query surface** (box + `/search`) and a swappable **engine** (`SiteSearchEngine`).
|
||||
The built-in engine matches with plain substrings; this one indexes with Lucene analysis and
|
||||
ranks by relevance, registering at a higher `priority()` so it wins wherever installed. It indexes the same
|
||||
`SearchCorpus` the built-in engine does — so the `search` plugin's per-site **`exclude`** list applies without this
|
||||
plugin reading it — drops a site's index the moment the kernel announces a change (a `SiteEventListener`), and
|
||||
implements the SPI's manual **reindex** hook so the operator's rebuild-index button rebuilds this index too. Lucene itself
|
||||
lives in the shared [`lucene-provider`](../lucene-provider) plugin (one copy deployment-wide). See
|
||||
[`docs/SEARCH-LUCENE-PLUGIN.md`](docs/SEARCH-LUCENE-PLUGIN.md) and [`CHANGELOG.md`](CHANGELOG.md).
|
||||
|
||||
## Tuning (per-site `siteSettings:`)
|
||||
|
||||
`fuzzy`, `fuzzyBoost`, `titleBoost`, `descriptionBoost`, and the four tier scores (`tierPhraseTitle`,
|
||||
`tierPhraseBody`, `tierNearPhrase`, `tierAllTerms`). App-level `settings:` choose index `storage` (heap/disk) and
|
||||
the disk `indexRoot`. Defaults reproduce the historical ranking, so an unconfigured site behaves as before.
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
export JAVA_HOME=/path/to/jdk-25
|
||||
(cd ../search && mvn -DskipTests install) # the jar this compiles against, into ~/.m2
|
||||
mvn verify # 72 unit tests + the package
|
||||
# → target/runway-plugin-search-lucene.jar (thin jar — NO bundled Lucene)
|
||||
# target/search-lucene/ (folder — cp -r into <external>/plugins/ + restart)
|
||||
# target/runway-plugin-search-lucene-3.3.0.zip (upload at /__app/plugins → install)
|
||||
JAVA_HOME=/path/to/jdk-25 HOST_JAR=/path/to/runway-app-<ver>-exec.jar VERIFY_TMPDIR=/some/scratch scripts/verify-against-host.sh
|
||||
```
|
||||
|
||||
The build compiles against the search plugin, `provided` from `~/.m2`: install it first with
|
||||
`mvn -DskipTests install` in `../search` (the verify script does). The first build downloads its Maven dependencies,
|
||||
and needs the `runway-spi` jars installed in `~/.m2` as the
|
||||
[authoring guide §2](../docs/PLUGIN-AUTHORING-GUIDE.md#2-prerequisites) describes. This plugin itself is never installed. At runtime the deployment must also carry the `search` plugin (2.2.0 or later) **and**
|
||||
the `lucene-provider` plugin (the Lucene binaries): drop all three folders into `external/plugins/`.
|
||||
|
||||
## Log messages you can ignore
|
||||
|
||||
### `Java vector incubator module is not readable`
|
||||
|
||||
Once per start of the host, the first time Lucene is used (usually the first search, on a request thread), the log
|
||||
shows:
|
||||
|
||||
```
|
||||
WARN … o.a.l.i.v.VectorizationProvider : Java vector incubator module is not readable. For optimal vector performance, pass '--add-modules jdk.incubator.vector' to enable Vector API.
|
||||
```
|
||||
|
||||
Lucene prints it (the library the `lucene-provider` plugin supplies). Nothing is wrong. **Leave it off**, for three
|
||||
reasons.
|
||||
|
||||
- The flag makes Lucene's vector maths faster. Lucene needs that mainly for k-nearest-neighbour *vector* search.
|
||||
Runway's search is keyword search (terms, phrases, typo-tolerant matches) and uses no vectors.
|
||||
- A site's index is small (its published pages and items), so there is no time to win.
|
||||
- `jdk.incubator.vector` is an *incubator* module, a JDK API that is not final. With it, the JVM prints
|
||||
`WARNING: Using incubator modules: jdk.incubator.vector` at every start, and a later JDK may change or drop the
|
||||
module.
|
||||
|
||||
If you want it anyway, add `--add-modules jdk.incubator.vector` to `JAVA_OPTS` in a systemd **drop-in** under
|
||||
`/etc/systemd/system/runway.service.d/`. Never edit the main unit, `runway.service`: the installer rewrites it at
|
||||
every upgrade. `Environment=` sets the whole variable, so the line must also carry your heap flags:
|
||||
|
||||
```ini
|
||||
# /etc/systemd/system/runway.service.d/20-heap.conf
|
||||
[Service]
|
||||
Environment="JAVA_OPTS=-Xms256m -Xmx1g --add-modules jdk.incubator.vector"
|
||||
```
|
||||
|
||||
Then run `sudo systemctl daemon-reload && sudo systemctl restart runway`. The installer's `--heap` rewrites
|
||||
`20-heap.conf` whole and drops the flag, so add it again after each `--heap`. Runway's administration manual
|
||||
(§15, *Memory tuning*) explains the drop-ins.
|
||||
|
||||
## License
|
||||
|
||||
GNU Affero General Public License v3.0 with an additional permission for plugins (`LICENSE`, `LICENSE-EXCEPTION`),
|
||||
copyright Quest ICT SAS de CV. The permission means that a plugin which uses only the published SPI, including
|
||||
search's own SPI for engines, may carry any license.
|
||||
@@ -0,0 +1,224 @@
|
||||
# Runway Search — Lucene engine — design & reference
|
||||
|
||||
> The companion engine for the `../search` plugin, and the workspace's reference for **two** hard-to-get-right
|
||||
> plugin patterns at once: implementing another plugin's **published SPI** (`requires:`), and **consuming a
|
||||
> shared library-provider plugin** (`../lucene-provider`) instead of bundling the library privately. Grounded in
|
||||
> the Runway kernel as built. Since 3.0.0 it links **only the Runway SPI and the search plugin's SPI**.
|
||||
|
||||
## 1. What it does
|
||||
|
||||
Implements `search`'s `SiteSearchEngine` SPI with Apache Lucene. Where the built-in engine substring-matches,
|
||||
this one builds a full-text index over each searchable item's **title**, **description**, and **body text**
|
||||
(extracted from the item's indexable material via `HtmlText`), analyzes queries with a **per-locale stemming
|
||||
analyzer**, and ranks with a **tiered constant-score** model layered on Lucene's BM25. It registers at
|
||||
`priority()` 100, so the shared search box and the results page transparently use it wherever it is installed —
|
||||
and fall back to the built-in engine if this plugin is removed.
|
||||
|
||||
What it indexes is the search plugin's **`SearchCorpus`** (search 2.0.0): every published page and content-source
|
||||
item of the kernel's listing **minus the site's search exclusions**. The built-in engine builds from the same
|
||||
corpus, so which items are searchable never depends on which engine serves the query, and the `exclude` rule lives
|
||||
in exactly one place — this plugin never reads the search plugin's settings.
|
||||
|
||||
## 2. The two `requires:` gates and the SPI floor
|
||||
|
||||
`plugin.yml` declares `requires: [ "search >= 2.2.0", "lucene-provider == 10.4.0" ]` and `requiresSpi: ">=1.0.0"`:
|
||||
|
||||
- **`search >= 2.2.0`** publishes the `SiteSearchEngine` interface this plugin implements and the `SearchCorpus` it
|
||||
indexes (both in `mx.quest.search.spi`). This plugin compiles against the search plugin as a `provided`
|
||||
dependency from `~/.m2` (installed from `../search`; never bundled). Both plugin jars load into ONE shared classloader, so the SPI types have a single `Class` identity and
|
||||
Spring collects this engine into `search`'s `List<SiteSearchEngine>`. `>=` (not exact) because the search SPI is
|
||||
API-stable — it grows by `default` methods and kept constructors only; **2.2.0** is the floor (since 3.2.0)
|
||||
because this plugin keeps one index per language, which a visitor reaches only when the search box on a
|
||||
localized page submits to the results page in that language — search 2.2.0 does that, while 2.1.x always
|
||||
submitted to the default-language results page. (3.1.x needed 2.1.0, the first with the `SearchHit`
|
||||
constructor that carries the matched words; 2.0.0 was the first to publish `SearchCorpus`.) Only the `spi` package is a contract: a build-time test fails if this plugin links any
|
||||
other search class.
|
||||
- **`lucene-provider == 10.4.0`** is the standalone code-less provider (`../lucene-provider`) that places the
|
||||
single deployment-wide copy of Lucene on the shared classloader. **`==` (exact)** because this plugin is
|
||||
**compiled against the 10.4.0 binaries** — a different Lucene could be binary-incompatible.
|
||||
- **`requiresSpi: ">=1.0.0"`** — the frozen 1.x contract, which carries the services it uses: `PluginSettings`
|
||||
(0.4.0), `Sites` (0.5.0), `SiteEventListener` and `CatalogEntry` (0.6.0).
|
||||
|
||||
If a gate is unsatisfied (missing/disabled/wrong version, or an older kernel), the host **does not load** this
|
||||
plugin (skipped with a reason, shown "Blocked" in the console) — so the SPI types AND every Lucene class are
|
||||
guaranteed present when this plugin's beans wire.
|
||||
|
||||
## 2a. What it uses, and nothing else
|
||||
|
||||
| Need | Published service |
|
||||
|------|-------------------|
|
||||
| what to index, its indexable text, the manual refresh | `SearchCorpus.corpus` / `indexableText` / `refresh` (search) |
|
||||
| a site's default locale (the analyzer) | `Sites.find` (kernel SPI) |
|
||||
| the per-site ranking knobs | `PluginSettings.site` (kernel SPI; descriptor defaults applied under the stored values) |
|
||||
| drop an index when content changes | `SiteEventListener.onCatalogChanged` (kernel SPI; one `CONSUMER` listener) |
|
||||
| app-level storage settings | its own `@ConfigurationProperties` bean under `runway.plugin.search-lucene` |
|
||||
|
||||
Beans: `searchLuceneStorageProps`, `searchLuceneEngine`, `searchLuceneSiteEvents`, `searchLuceneAdminModel` — every
|
||||
name starts with the plugin id in lowerCamelCase (the kernel's rule for the bean namespace plugins share).
|
||||
`SearchLuceneConfigTest` scans the compiled classes' constant pools: nothing of `mx.quest.runway` outside `.spi`,
|
||||
nothing of `mx.quest.search` outside `.spi`, no Caffeine.
|
||||
|
||||
## 3. Graduated from private bundling to the provider
|
||||
|
||||
search-lucene **used to** bundle Lucene privately in its own `lib/` (it was the only consumer). Lucene has
|
||||
**graduated** to the standalone `lucene-provider` (whose version IS the Lucene version):
|
||||
|
||||
- `pom.xml` now marks `lucene-core` + `lucene-analysis-common` + `lucene-highlighter` (and their transitives
|
||||
`lucene-memory` + `lucene-queries`) as **`provided`** — compile-only, supplied by the provider at runtime.
|
||||
- **Nothing** is copied into this plugin's own `lib/`. The staged install folder is the thin jar + templates +
|
||||
i18n only; a `clean package` verifies no Lucene jar appears in `target/search-lucene/`.
|
||||
- The search jar is compile-only too (never bundled — a second `Class` identity would break by-type SPI
|
||||
collection).
|
||||
|
||||
One Lucene version deployment-wide; no silent classpath clash. On a Lucene upgrade, bump `../lucene-provider` and
|
||||
this plugin's `${lucene.version}` + `requires:` pin together, then re-cut.
|
||||
|
||||
## 4. Ranking model
|
||||
|
||||
`buildQuery` composes a **tiered, additive constant-score** query — the tiers are `SHOULD` clauses, so a hit
|
||||
scores the **sum** of the tiers it satisfies, giving a deterministic ordering:
|
||||
|
||||
| Tier | What it matches | Score |
|
||||
|------|-----------------|-------|
|
||||
| any-terms | each term across title (× `titleBoost`), description (× `descriptionBoost`), body; **+ fuzzy** clauses when `fuzzy` is on | BM25 (× boosts) — the base layer that separates hits *within* a tier |
|
||||
| near phrase (body) | the query as a body `PhraseQuery` with slop 1 (lightly reordered / 1 gap) | constant `tierNearPhrase` |
|
||||
| exact phrase (body) | the query as an exact (slop 0) body phrase | constant `tierPhraseBody` |
|
||||
| exact phrase (title) | the query as an exact title phrase | constant `tierPhraseTitle` |
|
||||
| all-terms-anywhere | every term appears in some field (`MUST` across fields) | constant `tierAllTerms` |
|
||||
|
||||
Defaults reproduce the historical ranking constants (`tierPhraseTitle 4000 > tierPhraseBody 2000 > tierNearPhrase
|
||||
800 > tierAllTerms 300`; `titleBoost 8`, `descriptionBoost 4`; `fuzzy` on, `fuzzyBoost 0.4`). The phrase tiers
|
||||
are skipped for a single-term query (a lone term IS its own phrase — no double-count).
|
||||
|
||||
- **Fuzzy** (`FuzzyQuery`): typo tolerance with a length-aware edit budget (`maxEdits`: 0 for ≤2 chars, 1 for
|
||||
≤5, 2 beyond), fixed 1-char prefix, transpositions on. Fuzzy operates on the **analyzed (stemmed)** term.
|
||||
- **Per-locale analyzers** (`LocaleAnalyzers`): a Lucene language `Analyzer` (with that language's stopwords +
|
||||
stemmer) chosen by the **site's default locale** where one exists (en, es, fr, de, it, pt, ru, …), else
|
||||
`StandardAnalyzer`. The **same** analyzer is used at index and query time — stemming is analysis-time, so the
|
||||
two must never drift (or a stemmed query term would never match a stemmed indexed term).
|
||||
- **Highlighting** (`UnifiedHighlighter` + `DefaultPassageFormatter`): a query-focused body passage with hits
|
||||
wrapped in `<mark>…</mark>`. Private control-char markers are used internally; the passage is **HTML-escaped
|
||||
first, THEN** the markers become real `<mark>` tags — so page content can't inject markup while the highlight
|
||||
tags survive. Falls back to the description / a leading body slice when there is no highlightable passage.
|
||||
This is the `SearchHit` snippet contract (escape everything, wrap only hits in `<mark>`), and the search surface
|
||||
renders the snippet as raw HTML on that basis.
|
||||
- **Matched words** (since 3.1.0, `MatchedForms`): each returned hit also carries `SearchHit.terms`, the words the
|
||||
query matched **as the page writes them**, which search 2.1.0 hands to the page the result opens for
|
||||
highlighting. The stored title, description and body go through the same analyzer; a token whose term is a query
|
||||
term (or, with `fuzzy` on, within the fuzzy edit distance, same rule as the clauses) is kept as the text its
|
||||
offsets cover. So `maestría` (term `maestr`) reports `maestrías` from the page. At most 20 words; the first
|
||||
64 KiB of each text are read, so a long page costs a fixed amount per hit. Stop words match nothing and are never
|
||||
reported.
|
||||
|
||||
## 5. Index lifecycle & storage
|
||||
|
||||
- **Source:** `SearchCorpus.corpus(siteId)` — every published item minus the site's exclusions — and
|
||||
`SearchCorpus.indexableText(siteId, entry, locale)` for its body material (stripped to text) — the page
|
||||
as rendered in that language, so strings from the site's bundles are in it.
|
||||
- **One index per language (since 3.2.0).** Each item is indexed once per language it exists in: title,
|
||||
description, body in that language, and the hit's URL `CatalogEntry.pathFor(locale)` — its real address there.
|
||||
A site has one index per language it speaks, analyzed with **that language's analyzer**: the language's own
|
||||
documents plus, for an item that does not exist in it, the item's **primary-locale** document (the site default
|
||||
when the item has it, else its own first language), so a page published in one language only is still found
|
||||
from every other. A query searches its own language's index (`SearchQuery.locale()` — the results page's
|
||||
language, or the API's `?lang=`) with that analyzer; a language the site does not speak searches the site
|
||||
default's. A fallback document is analyzed with the index's analyzer, not its own language's, so it matches on
|
||||
exact and lightly stemmed forms rather than every inflection. Before 3.2.0 a site had one index of
|
||||
primary-locale documents with the default language's analyzer, so every language searched default-language
|
||||
text. The console's count is of items, not per-language documents.
|
||||
- **Store (app-level `settings:`, `LuceneStorageProps`, restart-only — a PLATFORM concern, not per-site, because
|
||||
a tenant-editable path is an isolation/abuse risk):**
|
||||
- `heap` (default) — an in-memory `ByteBuffersDirectory` per language; rebuilt on first use after boot.
|
||||
- `disk` — a memory-mapped `MMapDirectory` per language under `indexRoot/<siteId>/<language>` (since 3.2.0;
|
||||
the site id and the language are validated and the resolved path is asserted to stay under the normalized
|
||||
index root — traversal-safe). The index files a 3.1.x build left directly under `indexRoot/<siteId>` are
|
||||
deleted on the first rebuild — only files Lucene names (`segments*`, `write.lock`, codec files `_*.*`), once
|
||||
per site per process, so a misdirected `indexRoot` loses nothing else.
|
||||
- **Freshness:** each index is **cached per site** and dropped by the plugin's `SiteEventListener`
|
||||
(`LuceneSiteEvents`, phase `CONSUMER`) on **every** catalog change of the site — a page write, a content source's
|
||||
change, a site lifecycle event, any plugin's settings save (the search plugin's `exclude` list and a source's
|
||||
own settings both reshape the corpus). The kernel delivers it after its own caches are evicted and after every
|
||||
content source has dropped its state, so the next query rebuilds from the new content. A build that a change
|
||||
overtook (it may have read the old corpus) is kept as already stale: it answers the query that built it, and the
|
||||
next query rebuilds. A 30 s TTL remains as the backstop for changes no event announces, and the SPI's
|
||||
`reindex(siteId)` hook (the operator's rebuild-index button) refreshes the kernel's listing through
|
||||
`SearchCorpus.refresh`, then drops and rebuilds eagerly, returning the fresh document count. The build is
|
||||
rebuild-from-scratch (`deleteAll` then re-add), so a disk index is never left stale.
|
||||
- **Safety:** `search(...)` **never throws** — a Lucene/store/corpus failure logs and returns no results, so the
|
||||
query surface degrades to "no results", never a 500. Every surface is scoped to the queried `siteId`.
|
||||
- **No personal data.** The index is derived from published content and lives in heap or under `indexRoot`, not in
|
||||
the site folder; the plugin declares no `siteData.personal`.
|
||||
|
||||
## 6. Console & settings
|
||||
|
||||
- **App-level** `settings:` — `storage` (enum heap/disk) + `indexRoot` (string). Superadmin-only; applied on
|
||||
restart.
|
||||
- **Per-tenant** `siteSettings:` — the 8 ranking knobs (`fuzzy`, `fuzzyBoost`, `titleBoost`, `descriptionBoost`,
|
||||
`tierPhraseTitle`, `tierPhraseBody`, `tierNearPhrase`, `tierAllTerms`), read per query (a save applies to the
|
||||
next query) through `PluginSettings`. The editor is gated by the `settings` control point. `decimal` ignores `range`
|
||||
(authoring guide §4.1), so `RankingConfig` defaults + clamps every value defensively.
|
||||
- A dashboard card + admin fragment (bean `searchLuceneAdminModel`) show the active engine key, the site's indexed
|
||||
item count, the storage mode, and the effective title boost.
|
||||
|
||||
## 7. Verify
|
||||
|
||||
- **Offline unit tests** (`mvn verify`, 72 tests, on the `runway-spi-testkit` fakes and search's own
|
||||
`SiteSearchCorpus`): SPI contract (never-throws, empty index, unsafe/unknown site, limit, tie order), the search
|
||||
plugin's exclusions reaching the index through its corpus, the primary-locale title/body/URL, one index per
|
||||
language (`LucenePerLanguageTest`: each language's own text, analyzer and address, the primary-locale fallback,
|
||||
an unknown language, the item count, the per-language disk folders, only Lucene-named 3.1.x files deleted, a
|
||||
search from inside the site's own build answering nothing), `reindex`
|
||||
(listing refresh + immediate rebuild inside the TTL), the listener dropping the index for every cause (page,
|
||||
content, settings of another plugin, lifecycle, a replayed change) and only for its site, the mid-build change,
|
||||
tiering (exact phrase > scattered; title phrase > body phrase; the documented tier sum), fuzzy on/off applied on
|
||||
the next query, per-locale stemming (English `running`↔`run`; Spanish `producto`↔`productos`; unknown locale →
|
||||
StandardAnalyzer), heap and disk answering identically, `<mark>` highlighting (incl. page-markup escaping), each
|
||||
tuning knob, defensive config parsing, and the contract test (wiring from published services only, bean names,
|
||||
template bean references, descriptor floors and version, code fallbacks = descriptor defaults, i18n, the
|
||||
constant-pool scan).
|
||||
- **Live** (`scripts/verify-against-host.sh`; honours `HOST_JAR`, `VERIFY_TMPDIR`, `VERIFY_LOG_DIR`; packages
|
||||
everything offline and never `mvn install`s): boots the packaged host twice on the same fixture site — first
|
||||
search 2.0.0 + search-lucene 3.0.0 (built from git at `BASELINE_REF`, a commit carrying those two versions; when
|
||||
`BASELINE_REF` is unset, the default, or `SKIP_BASELINE=1`, the script prints a note and runs only the checks on the
|
||||
current pair), then the current search + this release with the index on disk — and asserts that twelve queries
|
||||
answer **byte-identically** (order, URLs, titles, snippets, scores) once the `link` and `terms` fields 3.0.0 never had are set aside; those it checks on
|
||||
their own: each hit carries its marked link and at least every word its snippet marks. (Until 3.1.0 the baseline
|
||||
was 2.2.1, which a Runway 1.0 kernel blocks for linking kernel internals; 3.0.0 had matched it byte for byte.) On
|
||||
the current pair it asserts `3 registered, 0 blocked` with zero host-linkage and bean-name/surface warnings, the
|
||||
console card and admin fragment, a save of search's `exclude` list and of this plugin's knobs reaching the next
|
||||
query without a reindex, and the rebuild-index POST reporting this engine's count.
|
||||
|
||||
## 8. Log messages you can ignore
|
||||
|
||||
### `Java vector incubator module is not readable`
|
||||
|
||||
Once per start of the host, the first time Lucene is used (usually the first search, on a request thread), the log
|
||||
shows:
|
||||
|
||||
```
|
||||
WARN … o.a.l.i.v.VectorizationProvider : Java vector incubator module is not readable. For optimal vector performance, pass '--add-modules jdk.incubator.vector' to enable Vector API.
|
||||
```
|
||||
|
||||
Lucene prints it (the library the `lucene-provider` plugin supplies). Nothing is wrong. **Leave it off**, for three
|
||||
reasons.
|
||||
|
||||
- The flag makes Lucene's vector maths faster. Lucene needs that mainly for k-nearest-neighbour *vector* search.
|
||||
Runway's search is keyword search (terms, phrases, typo-tolerant matches) and uses no vectors.
|
||||
- A site's index is small (its published pages and items), so there is no time to win.
|
||||
- `jdk.incubator.vector` is an *incubator* module, a JDK API that is not final. With it, the JVM prints
|
||||
`WARNING: Using incubator modules: jdk.incubator.vector` at every start, and a later JDK may change or drop the
|
||||
module.
|
||||
|
||||
If you want it anyway, add `--add-modules jdk.incubator.vector` to `JAVA_OPTS` in a systemd **drop-in** under
|
||||
`/etc/systemd/system/runway.service.d/`. Never edit the main unit, `runway.service`: the installer rewrites it at
|
||||
every upgrade. `Environment=` sets the whole variable, so the line must also carry your heap flags:
|
||||
|
||||
```ini
|
||||
# /etc/systemd/system/runway.service.d/20-heap.conf
|
||||
[Service]
|
||||
Environment="JAVA_OPTS=-Xms256m -Xmx1g --add-modules jdk.incubator.vector"
|
||||
```
|
||||
|
||||
Then run `sudo systemctl daemon-reload && sudo systemctl restart runway`. The installer's `--heap` rewrites
|
||||
`20-heap.conf` whole and drops the flag, so add it again after each `--heap`. Runway's administration manual
|
||||
(§15, *Memory tuning*) explains the drop-ins.
|
||||
@@ -0,0 +1,30 @@
|
||||
# Runway Search — Lucene engine — English strings.
|
||||
|
||||
# Grantable permission (permissions matrix label)
|
||||
searchlucene.perm.settings=Configure Lucene search
|
||||
|
||||
# App-level settings form labels (superadmin — platform storage)
|
||||
searchlucene.set.storage=Index storage
|
||||
searchlucene.set.indexRoot=Disk index root folder
|
||||
|
||||
# Per-tenant settings form labels (site ranking tuning)
|
||||
searchlucene.set.fuzzy=Typo-tolerant (fuzzy) matching
|
||||
searchlucene.set.fuzzyBoost=Fuzzy match weight
|
||||
searchlucene.set.titleBoost=Title match boost
|
||||
searchlucene.set.descriptionBoost=Description match boost
|
||||
searchlucene.set.tierPhraseTitle=Exact phrase in title — score
|
||||
searchlucene.set.tierPhraseBody=Exact phrase in body — score
|
||||
searchlucene.set.tierNearPhrase=Near phrase in body — score
|
||||
searchlucene.set.tierAllTerms=All terms present — score
|
||||
|
||||
# Dashboard card
|
||||
searchlucene.card.title=Lucene search index
|
||||
searchlucene.card.pages=indexed items
|
||||
|
||||
# Admin status fragment
|
||||
searchlucene.admin.title=Lucene index status
|
||||
searchlucene.admin.engine=Engine
|
||||
searchlucene.admin.pages=Indexed items
|
||||
searchlucene.admin.storage=Storage
|
||||
searchlucene.admin.boost=Title boost
|
||||
searchlucene.admin.note=This engine supersedes the built-in search whenever it is installed. It ranks results in tiers (exact phrase, near phrase, all terms, any term), tolerates typos, and stems per the site language. The index refreshes automatically as content changes; no manual rebuild is needed.
|
||||
@@ -0,0 +1,30 @@
|
||||
# Runway Search — motor Lucene — cadenas en español.
|
||||
|
||||
# Permiso otorgable (etiqueta de la matriz de permisos)
|
||||
searchlucene.perm.settings=Configurar búsqueda Lucene
|
||||
|
||||
# Etiquetas del formulario de configuración a nivel de aplicación (superadmin — almacenamiento)
|
||||
searchlucene.set.storage=Almacenamiento del índice
|
||||
searchlucene.set.indexRoot=Carpeta raíz del índice en disco
|
||||
|
||||
# Etiquetas del formulario de configuración por sitio (ajuste de relevancia)
|
||||
searchlucene.set.fuzzy=Coincidencia tolerante a errores (difusa)
|
||||
searchlucene.set.fuzzyBoost=Peso de coincidencia difusa
|
||||
searchlucene.set.titleBoost=Refuerzo de coincidencia en título
|
||||
searchlucene.set.descriptionBoost=Refuerzo de coincidencia en descripción
|
||||
searchlucene.set.tierPhraseTitle=Frase exacta en título — puntuación
|
||||
searchlucene.set.tierPhraseBody=Frase exacta en cuerpo — puntuación
|
||||
searchlucene.set.tierNearPhrase=Frase cercana en cuerpo — puntuación
|
||||
searchlucene.set.tierAllTerms=Todos los términos presentes — puntuación
|
||||
|
||||
# Tarjeta del panel
|
||||
searchlucene.card.title=Índice de búsqueda Lucene
|
||||
searchlucene.card.pages=elementos indexados
|
||||
|
||||
# Fragmento de estado (admin)
|
||||
searchlucene.admin.title=Estado del índice Lucene
|
||||
searchlucene.admin.engine=Motor
|
||||
searchlucene.admin.pages=Elementos indexados
|
||||
searchlucene.admin.storage=Almacenamiento
|
||||
searchlucene.admin.boost=Refuerzo de título
|
||||
searchlucene.admin.note=Este motor sustituye a la búsqueda integrada siempre que está instalado. Ordena los resultados por niveles (frase exacta, frase cercana, todos los términos, cualquier término), tolera erratas y lematiza según el idioma del sitio. El índice se actualiza automáticamente cuando cambian las páginas; no hace falta reconstruirlo a mano.
|
||||
@@ -0,0 +1,78 @@
|
||||
# =============================================================================
|
||||
# Runway Search — Lucene engine
|
||||
# A full-text SiteSearchEngine (title + description + body) with per-locale
|
||||
# analysis (stemming), a TIERED constant-score ranking (exact phrase → near
|
||||
# phrase → all-terms → any-terms), FUZZY matching, and query-focused <mark>
|
||||
# highlighting — a real upgrade over the built-in substring engine.
|
||||
#
|
||||
# Indexes the search plugin's SearchCorpus (the site's published pages and
|
||||
# content items minus the site's search exclusions — the same corpus the
|
||||
# built-in engine indexes), drops a site's index on every change the kernel
|
||||
# announces (a SiteEventListener), and implements the engine SPI's manual
|
||||
# reindex hook. Since 3.0.0 it links only the Runway SPI and the search SPI.
|
||||
#
|
||||
# Lucene lives in the standalone `lucene-provider` plugin: this plugin does not
|
||||
# bundle Lucene in its own lib/. It declares two hard dependencies:
|
||||
# - requires: search >= 2.2.0 — publishes SiteSearchEngine, SearchCorpus and SearchHit.terms
|
||||
# - requires: lucene-provider == 10.4.0 — the exact Lucene binaries it is compiled against
|
||||
#
|
||||
# The install folder name MUST equal this `id`: external/plugins/search-lucene/.
|
||||
# =============================================================================
|
||||
id: search-lucene
|
||||
name: Search — Lucene engine
|
||||
version: 3.3.0
|
||||
|
||||
# The @Configuration registered before refresh. Package mx.quest.searchlucene lives OUTSIDE mx.quest.runway.
|
||||
mainClass: mx.quest.searchlucene.SearchLuceneConfig
|
||||
|
||||
# HARD dependencies (both must be satisfied or this plugin is skipped with a reason, shown "Blocked" in the UI):
|
||||
# - search >= 2.1.0: publishes the SiteSearchEngine SPI this plugin implements and the SearchCorpus it indexes.
|
||||
# `>=` (not exact) because the search SPI is API-stable (it grows by default methods and kept constructors only);
|
||||
# 2.2.0 is the floor (3.2.0): this plugin keeps one index per language, which a visitor reaches only when the
|
||||
# search box on a localized page submits to the results page in that language — search 2.2.0 does that (2.1.x
|
||||
# always submitted to the default-language results page, so every query arrived in the default language).
|
||||
# Before 3.2.0 the floor was 2.1.0, the first search with the SearchHit constructor carrying the matched words.
|
||||
# - lucene-provider == 10.4.0: EXACT pin — this plugin is compiled against the 10.4.0 Lucene binaries the
|
||||
# provider ships; a different Lucene could be binary-incompatible, so `==` (not `>=`).
|
||||
requires: [ "search >= 2.2.0", "lucene-provider == 10.4.0" ]
|
||||
|
||||
# The lowest Runway SPI whose services this plugin uses (PluginSettings, Sites, SiteEventListener and the
|
||||
# CatalogEntry the corpus hands out). A kernel below SPI 1.0.0 BLOCKS this plugin at startup with a reason.
|
||||
requiresSpi: ">=1.0.0"
|
||||
|
||||
# --- Grantable control-point permission (gates the per-tenant tuning editor) -----------------------------
|
||||
permissions:
|
||||
- { id: settings, realm: tenant, label: searchlucene.perm.settings, defaultRoles: [] }
|
||||
|
||||
# --- App-level settings (superadmin): PLATFORM concerns only — WHERE the index bytes live. -----------------
|
||||
# A tenant-editable filesystem path would be an isolation/abuse risk, so storage is app-level, not per-site.
|
||||
# Applied on RESTART (bound by the plugin's own @ConfigurationProperties bean from
|
||||
# external/plugin-settings/search-lucene.yml).
|
||||
# storage : heap → in-memory ByteBuffersDirectory (default; no disk, rebuilt on boot)
|
||||
# disk → MMapDirectory under indexRoot/<siteId> (survives restart, memory-mapped)
|
||||
# indexRoot : the root folder for disk indexes (per-site subfolders created under it, traversal-guarded)
|
||||
settings:
|
||||
- { key: storage, type: enum, values: [heap, disk], default: heap, label: searchlucene.set.storage }
|
||||
- { key: indexRoot, type: string, default: "./external/plugins/search-lucene/index", label: searchlucene.set.indexRoot }
|
||||
|
||||
# --- Per-tenant settings (tenant-owned ranking tuning; over sites/<id>/plugins/search-lucene.yml) ----------
|
||||
# Applied IMMEDIATELY (read per query through the SPI's PluginSettings). `decimal` IGNORES range
|
||||
# (authoring guide §4.1), so the engine clamps every knob to a sane range itself. Defaults reproduce the
|
||||
# historical constants, so an unconfigured site ranks exactly as before this schema existed.
|
||||
siteSettings:
|
||||
# Fuzzy (typo-tolerant) matching — on/off + how much a fuzzy hit is worth relative to an exact term hit.
|
||||
- { key: fuzzy, type: boolean, default: true, label: searchlucene.set.fuzzy }
|
||||
- { key: fuzzyBoost, type: decimal, default: 0.4, label: searchlucene.set.fuzzyBoost }
|
||||
# Per-field term boosts (applied to the any-terms tier's term matches).
|
||||
- { key: titleBoost, type: decimal, default: 8.0, label: searchlucene.set.titleBoost }
|
||||
- { key: descriptionBoost, type: decimal, default: 4.0, label: searchlucene.set.descriptionBoost }
|
||||
# Tier scores — the constant score a document earns for matching each tier (bigger = stronger relevance
|
||||
# signal). exact-phrase-in-title ≫ exact-phrase-in-body ≫ near-phrase-in-body ≫ all-terms-anywhere.
|
||||
- { key: tierPhraseTitle, type: decimal, default: 4000, label: searchlucene.set.tierPhraseTitle }
|
||||
- { key: tierPhraseBody, type: decimal, default: 2000, label: searchlucene.set.tierPhraseBody }
|
||||
- { key: tierNearPhrase, type: decimal, default: 800, label: searchlucene.set.tierNearPhrase }
|
||||
- { key: tierAllTerms, type: decimal, default: 300, label: searchlucene.set.tierAllTerms }
|
||||
|
||||
# --- Tenant dashboard card (fragment resolves to __plugin__/search-lucene/dashboard) ----------------------
|
||||
dashboardCards:
|
||||
- { realm: tenant, order: 41, fragment: dashboard, permission: "search-lucene|settings" }
|
||||
@@ -0,0 +1,195 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<!--
|
||||
Inherit the SAME managed versions the Runway kernel uses (Spring Boot 4.0.6) so every `provided` Spring type
|
||||
is byte-identical at runtime. A plugin is NOT a Boot application — NO repackage; `mvn package` produces a THIN
|
||||
jar of only this plugin's classes.
|
||||
|
||||
SPI only (3.0.0): the plugin links nothing of the kernel but `runway-spi` (no runway-app, in any scope), and
|
||||
nothing of the search plugin but its published SPI package `mx.quest.search.spi` (SiteSearchEngine,
|
||||
SearchCorpus, SearchQuery, SearchHit). Lucene comes from the `lucene-provider` plugin (`provided` here,
|
||||
`requires: lucene-provider == 10.4.0` in plugin.yml), so this pom bundles NOTHING into a lib/ folder.
|
||||
-->
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>4.0.6</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-plugin-search-lucene</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>Runway Search — Lucene engine</name>
|
||||
<licenses>
|
||||
<license>
|
||||
<name>GNU Affero General Public License v3.0, with the Runway additional permission for plugins</name>
|
||||
<url>https://www.gnu.org/licenses/agpl-3.0.txt</url>
|
||||
<distribution>repo</distribution>
|
||||
<comments>See LICENSE and LICENSE-EXCEPTION.</comments>
|
||||
</license>
|
||||
</licenses>
|
||||
<description>
|
||||
A Lucene-backed SiteSearchEngine for the Runway `search` plugin: a full-text index over each page's
|
||||
title, description and body with per-locale analysis (stemming) and a tiered constant-score ranking —
|
||||
exact phrase, near phrase, all-terms, any-terms — plus fuzzy matching and query-focused snippet
|
||||
highlighting. It indexes the search plugin's SearchCorpus, declares `requires: search >= 2.2.0` and
|
||||
`requires: lucene-provider == 10.4.0`, registers at a higher priority than the built-in engine, and
|
||||
transparently upgrades the search box and results page. Links only the Runway SPI and the search SPI;
|
||||
Lucene is supplied by the lucene-provider plugin (provided).
|
||||
</description>
|
||||
|
||||
<properties>
|
||||
<java.version>25</java.version>
|
||||
<maven.compiler.release>25</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<!-- Reproducible builds: pins every archive entry's timestamp so two builds of the same source
|
||||
produce byte-identical artifacts. Without it a jar embeds the build time, so a rebuild can
|
||||
never match what was published. Bump at each release. -->
|
||||
<project.build.outputTimestamp>2026-10-21T17:23:00Z</project.build.outputTimestamp>
|
||||
<!-- The runway-spi (and runway-spi-testkit) version this plugin compiles and tests against, from ~/.m2. -->
|
||||
<runway.version>1.0.0</runway.version>
|
||||
<!-- The search plugin this engine compiles against, `provided` from ~/.m2 (install it first:
|
||||
`mvn -o -DskipTests install` in ../search — the verify script does). plugin.yml declares
|
||||
`search >= 2.2.0` (3.2.0: the box submits to the results page in its page's language, so a
|
||||
language's index is reached); 2.1.0 was the first whose SearchHit carries the matched words (the
|
||||
constructor this engine calls), and an older search does not compile this plugin. Provided, never bundled: a second copy of the search SPI classes would break by-type lookup. -->
|
||||
<search.version>2.3.0</search.version>
|
||||
<!-- The EXACT Lucene version this plugin is compiled against; lucene-provider must ship the same one
|
||||
(plugin.yml pins `lucene-provider == 10.4.0`). Keep these two in lock-step. -->
|
||||
<lucene.version>10.4.0</lucene.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- The dependency-free extension API (SPI interfaces, services and immutable model records). -->
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-spi</artifactId>
|
||||
<version>${runway.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- NO runway-app dependency, in any scope: the plugin links only the SPI, so a host
|
||||
import no longer compiles and the kernel's host-linkage scanner finds nothing to report. -->
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-spi-testkit</artifactId>
|
||||
<version>${runway.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- The `search` plugin publishes the SiteSearchEngine SPI this plugin implements and the SearchCorpus it
|
||||
indexes. Compile-only: at runtime the shared plugin classloader supplies search's classes (both
|
||||
plugin jars load into ONE classloader, so the SPI has one Class identity), and `requires: search`
|
||||
in plugin.yml makes it a HARD load gate. `provided` from ~/.m2 (install ../search first), and never
|
||||
bundled: the assembly below copies this plugin's own jar only. -->
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-plugin-search</artifactId>
|
||||
<version>${search.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Lucene — supplied at RUNTIME by the lucene-provider plugin on the shared classloader. PROVIDED here:
|
||||
compile-only, never bundled into this plugin's own lib/ (that would be a second copy on the shared
|
||||
classloader). requires: lucene-provider == 10.4.0 in plugin.yml guarantees the exact binaries. -->
|
||||
<dependency>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-core</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-analysis-common</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-highlighter</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Tests DO run the real Lucene: at test time it must be on the classpath, so the same jars come in as
|
||||
`test` scope too (provided is not visible to the test classpath on its own). These are the exact
|
||||
10.4.0 artifacts lucene-provider ships, so the tests exercise the runtime binaries faithfully. -->
|
||||
<dependency>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-memory</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-queries</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>runway-plugin-search-lucene</finalName>
|
||||
<plugins>
|
||||
<!-- Assemble both installable forms: target/search-lucene/ (folder) and the UI zip. NOTE: NO lib/ —
|
||||
Lucene is NOT bundled here; it comes from the lucene-provider plugin at runtime. -->
|
||||
<plugin>
|
||||
<artifactId>maven-antrun-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>assemble-plugin-folder</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>run</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<target>
|
||||
<property name="stage" value="${project.build.directory}/search-lucene"/>
|
||||
<delete dir="${stage}"/>
|
||||
<mkdir dir="${stage}"/>
|
||||
<copy file="${project.basedir}/plugin.yml" todir="${stage}"/>
|
||||
<copy file="${project.basedir}/LICENSE" todir="${stage}"/>
|
||||
<copy file="${project.basedir}/LICENSE-EXCEPTION" todir="${stage}"/>
|
||||
<copy file="${project.build.directory}/runway-plugin-search-lucene.jar" todir="${stage}"/>
|
||||
<copy todir="${stage}/templates">
|
||||
<fileset dir="${project.basedir}/templates"/>
|
||||
</copy>
|
||||
<copy todir="${stage}/i18n">
|
||||
<fileset dir="${project.basedir}/i18n"/>
|
||||
</copy>
|
||||
<touch datetime="${project.build.outputTimestamp}"
|
||||
pattern="yyyy-MM-dd'T'HH:mm:ss'Z'">
|
||||
<fileset dir="${stage}"/>
|
||||
<dirset dir="${stage}"/>
|
||||
<dirset dir="${project.build.directory}" includes="search-lucene"/>
|
||||
</touch>
|
||||
<zip destfile="${project.build.directory}/runway-plugin-search-lucene-${project.version}.zip">
|
||||
<zipfileset dir="${project.build.directory}" includes="search-lucene/**"/>
|
||||
</zip>
|
||||
<echo message="Staged install folder (thin jar, NO bundled Lucene — from lucene-provider): ${stage}"/>
|
||||
<echo message="UI-uploadable archive: ${project.build.directory}/runway-plugin-search-lucene-${project.version}.zip"/>
|
||||
</target>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
#!/usr/bin/env bash
|
||||
# Prove this release's contract end to end on the PACKAGED Runway host, together with the two plugins it
|
||||
# requires — the current search (publishes SiteSearchEngine, SearchCorpus and SearchHit.terms) and the code-less
|
||||
# lucene-provider (the Lucene binaries) — and, when BASELINE_REF is set, prove that it ranks exactly as the baseline:
|
||||
#
|
||||
# 1. BASELINE (only when BASELINE_REF is set): search 2.0.0 + search-lucene 3.0.0 (built from git, BASELINE_REF) +
|
||||
# lucene-provider on the same host jar, a fixture site (pages written for the tiers, stemming, fuzzy and the
|
||||
# exclusion list, a stored ranking knob), and a fixed set of queries answered by the JSON API.
|
||||
# 2. CURRENT: the current search + this release + lucene-provider, the same fixture and queries, with the index on
|
||||
# DISK this time (the app-level settings bind). Every answer — order, URLs, titles, snippets, scores — must be
|
||||
# byte-identical to the baseline's (the link and terms fields 3.0.0 never had are set aside for the comparison;
|
||||
# they are checked on their own: each hit carries the words it matched, as the page writes them).
|
||||
# 3. On the current deployment: the three plugins load with ZERO host-linkage and bean-name/surface warnings, the
|
||||
# console card and admin fragment render (bean @searchLuceneAdminModel), a settings save of the search plugin's
|
||||
# exclude list and of this plugin's own knobs reach the next query without a reindex, and the operator's reindex
|
||||
# POST rebuilds this index and reports its size.
|
||||
#
|
||||
# Only the search plugin is installed to ~/.m2 (it is this plugin's compile-time dependency, as in 2.x); everything
|
||||
# else is PACKAGED offline. Formerly: this plugin compiled against the
|
||||
# search jar its sibling folder just built. Verify ONLY against the packaged jar — never spring-boot:run (its restart
|
||||
# classloader loads ZERO plugins).
|
||||
#
|
||||
# Usage: scripts/verify-against-host.sh [--keep] [--port N]
|
||||
# JAVA_HOME=/path/to/jdk-25 required: the JDK that builds the plugin and runs the host
|
||||
# MVN=/path/to/mvn Maven (default: mvn on the PATH)
|
||||
# HOST_TARGET=/path/to/runway/runway-app/target the host build (default: the kernel this plugin sits in, else ../runway)
|
||||
# HOST_JAR=/path/to/runway-app-<ver>-exec.jar the kernel to verify against (default: the host checkout's
|
||||
# runway-app/target jar MATCHING its pom version)
|
||||
# VERIFY_TMPDIR=/dir where the throwaway deployments go (default: this plugin's target/)
|
||||
# VERIFY_LOG_DIR=/dir keep the host logs, the query answers and the diff there (evidence)
|
||||
# BASELINE_REF=<git ref> the commit carrying search 2.0.0 + search-lucene 3.0.0 (default:
|
||||
# empty, which skips the before/after comparison with a note);
|
||||
# SKIP_BASELINE=1 skips it too
|
||||
set -uo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
|
||||
VER="$(sed -n 's/^version: *//p' "$HERE/plugin.yml")" # the release under test
|
||||
REPO="$(cd "$HERE/.." && pwd)"
|
||||
SEARCH="$REPO/search"
|
||||
LUCENE_PROVIDER="$REPO/lucene-provider"
|
||||
# JAVA_HOME must name a JDK 25. MVN (default: `mvn` on the PATH) and HOST_TARGET (default: see above) can be set in the environment.
|
||||
if [ -z "${JAVA_HOME:-}" ] || [ ! -x "$JAVA_HOME/bin/java" ]; then echo "set JAVA_HOME to a JDK 25"; exit 2; fi
|
||||
export JAVA_HOME
|
||||
JAVA="$JAVA_HOME/bin/java"
|
||||
MVN="${MVN:-mvn}"
|
||||
# Default host: the kernel at the root of the repository this plugin sits in (plugins/<name>/), else a kernel
|
||||
# checkout named `runway` beside the plugins checkout.
|
||||
if [ -z "${HOST_TARGET:-}" ]; then
|
||||
if [ -f "$HERE/../../../runway-app/pom.xml" ]; then HOST_TARGET="$HERE/../../../runway-app/target"
|
||||
else HOST_TARGET="$HERE/../../runway/runway-app/target"; fi
|
||||
fi
|
||||
BASELINE_REF="${BASELINE_REF:-}"
|
||||
if [ -z "$BASELINE_REF" ] && [ "${SKIP_BASELINE:-0}" != 1 ]; then
|
||||
echo "[verify] BASELINE_REF is not set: skipping the comparison with search 2.0.0 + search-lucene 3.0.0" \
|
||||
"(set BASELINE_REF to a commit carrying those two versions to run it)"
|
||||
SKIP_BASELINE=1
|
||||
fi
|
||||
M2="${HOME}/.m2/repository/mx/quest"
|
||||
|
||||
KEEP="no"; PORT=""
|
||||
while [ $# -gt 0 ]; do case "$1" in
|
||||
--keep) KEEP="yes"; shift ;;
|
||||
--port) PORT="${2:?}"; shift 2 ;;
|
||||
*) echo "unknown arg: $1"; exit 2 ;;
|
||||
esac; done
|
||||
|
||||
APP_USER=root; APP_PW=Lucene-Admin-2026; SITE_USER=owner; SITE_PW=Lucene-Site-2026
|
||||
free_port() { python3 -I -c 'import socket;s=socket.socket();s.bind(("127.0.0.1",0));print(s.getsockname()[1]);s.close()'; }
|
||||
[ -n "$PORT" ] || PORT="$(free_port)"
|
||||
BASE="http://localhost:$PORT"
|
||||
|
||||
m2_before="$(ls -d "$M2"/runway-plugin-search-lucene/"$VER" 2>/dev/null)"
|
||||
|
||||
echo "[verify] packaging search (the plugin this one requires and compiles against) ..."
|
||||
( cd "$SEARCH" && "$MVN" -o -q -DskipTests install ) || { echo "search build/install failed"; exit 1; }
|
||||
echo "[verify] packaging lucene-provider ..."
|
||||
( cd "$LUCENE_PROVIDER" && "$MVN" -o -q -DskipTests package ) || { echo "lucene-provider build failed"; exit 1; }
|
||||
echo "[verify] packaging this plugin ..."
|
||||
( cd "$HERE" && "$MVN" -o -q -DskipTests package ) || { echo "search-lucene build failed"; exit 1; }
|
||||
|
||||
# The host jar MATCHING the host pom's version — never "the newest file": every reproducible jar carries the same
|
||||
# fixed timestamp, so `ls -t` cannot tell a leftover release jar from the SNAPSHOT under test.
|
||||
if [ -n "${HOST_JAR:-}" ]; then
|
||||
JAR="$HOST_JAR"
|
||||
else
|
||||
HOST_VERSION="$(sed -n 's:.*<version>\(.*\)</version>.*:\1:p' "$HOST_TARGET/../pom.xml" | head -1)"
|
||||
JAR="$HOST_TARGET/runway-app-$HOST_VERSION-exec.jar"
|
||||
fi
|
||||
[ -f "$JAR" ] || { echo "no host exec jar $JAR — build the host (mvn -pl runway-app package) or set HOST_JAR"; exit 1; }
|
||||
echo "[verify] host jar: $JAR"
|
||||
|
||||
mkdir -p "${VERIFY_TMPDIR:-$HERE/target}"
|
||||
SCRATCH="$(mktemp -d "${VERIFY_TMPDIR:-$HERE/target}/lucene-verify.XXXXXX")"
|
||||
PID=""
|
||||
stop_host() { [ -z "$PID" ] || { kill "$PID" 2>/dev/null; wait "$PID" 2>/dev/null; PID=""; }; }
|
||||
cleanup() {
|
||||
if [ -n "${VERIFY_LOG_DIR:-}" ]; then
|
||||
mkdir -p "$VERIFY_LOG_DIR"
|
||||
for run in before after; do
|
||||
[ -d "$SCRATCH/$run" ] || continue
|
||||
mkdir -p "$VERIFY_LOG_DIR/$run"
|
||||
cp "$SCRATCH/$run"/*.log "$VERIFY_LOG_DIR/$run/" 2>/dev/null
|
||||
[ -d "$SCRATCH/$run/answers" ] && cp -r "$SCRATCH/$run/answers" "$VERIFY_LOG_DIR/$run/"
|
||||
done
|
||||
cp "$SCRATCH"/*.txt "$VERIFY_LOG_DIR/" 2>/dev/null
|
||||
fi
|
||||
# Wait for the host to exit before deleting: a JVM still shutting down rewrites files under external/.
|
||||
[ "$KEEP" = "yes" ] || { stop_host; rm -rf "$SCRATCH"; }
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
wait_for() { for _ in $(seq 1 "$3"); do grep -q "$2" "$1" 2>/dev/null && return 0; sleep 1; done; return 1; }
|
||||
PASS=0; FAIL=0
|
||||
ck() { if eval "$2" >/dev/null 2>&1; then echo " PASS $1"; PASS=$((PASS+1)); else echo " FAIL $1"; FAIL=$((FAIL+1)); fi; }
|
||||
code() { curl -s -o /dev/null -w '%{http_code}' "$@"; }
|
||||
|
||||
# --- The fixture: pages written for the tiers, stemming, fuzzy, highlighting and the exclusion list ------------------
|
||||
page() { # sites-dir slug title description body-html
|
||||
local t="$1/default/templates"
|
||||
printf 'path: /%s\ntemplate: _master\ntitle:\n en: "%s"\ndescription:\n en: "%s"\n' "$2" "$3" "$4" > "$t/$2.meta.yml"
|
||||
printf '<!DOCTYPE html>\n<html lang="en">\n<head><title>%s</title></head>\n<body>\n<header id="site-header"></header>\n<main id="content">\n%s\n</main>\n<footer id="site-footer"></footer>\n</body>\n</html>\n' \
|
||||
"$3" "$5" > "$t/$2.html"
|
||||
cp "$t/about.th.xml" "$t/$2.th.xml"
|
||||
}
|
||||
fixture() { # sites-dir
|
||||
page "$1" guide "Runway Deployment Guide" "How to deploy Runway in production." \
|
||||
"<p>This guide covers the deployment of runway on a single server. Read the runway deployment guide first.</p>"
|
||||
page "$1" manual "Manual" "" "<p>The cloud deployment guide explains everything about the cloud.</p>"
|
||||
page "$1" notes "Notes" "Miscellaneous" \
|
||||
"<p>cloud infrastructure. a long unrelated paragraph about many topics. deployment pipelines. yet another sentence entirely. a helpful guide to nothing.</p>"
|
||||
page "$1" athletics "Athletics" "Sports club" "<p>They run every morning and they ran yesterday.</p>"
|
||||
page "$1" handbook "Lucene Handbook" "Search internals" "<p>All about lucene, analyzers and <mark> tags.</p>"
|
||||
page "$1" pricing "Pricing" "Plans for runway hosting" "<p>Runway hosting plans start small. Deployment support included.</p>"
|
||||
page "$1" privacy "Privacy" "Runway privacy policy" "<p>runway runway privacy deployment guide</p>"
|
||||
# A bilingual page whose copy comes ONLY from the site's bundles (decoupled th:text; the template's element is
|
||||
# empty) -- the kernel indexes it as rendered per language, and this plugin keeps one index per
|
||||
# language. Its words appear in none of QUERIES, so the 3.0.0 comparison is unaffected.
|
||||
sed -i '/^locales:/a - "es"' "$1/default/site.yml"
|
||||
local t="$1/default/templates"
|
||||
printf 'path: /faculty\nlocalizedPaths:\n es: /facultad\nlocales: [en, es]\ntemplate: _master\ntitle:\n en: Faculty\n es: Profesores\n' > "$t/faculty.meta.yml"
|
||||
printf '<!DOCTYPE html>\n<html lang="en">\n<head><title>Faculty</title></head>\n<body>\n<header id="site-header"></header>\n<main id="content"><p id="faculty-copy"></p></main>\n<footer id="site-footer"></footer>\n</body>\n</html>\n' > "$t/faculty.html"
|
||||
sed 's#</thlogic># <attr sel="\#faculty-copy" th:text="\#{verify.faculty}"/>\n</thlogic>#' "$t/about.th.xml" > "$t/faculty.th.xml"
|
||||
mkdir -p "$1/default/i18n"
|
||||
printf '\nverify.faculty=Our students learn from researchers.\n' >> "$1/default/i18n/messages.properties"
|
||||
printf '\nverify.faculty=Nuestros alumnos aprenden con una facultad de excelencia.\n' >> "$1/default/i18n/messages_es.properties"
|
||||
mkdir -p "$1/default/plugins"
|
||||
printf 'exclude:\n - privacy\n' > "$1/default/plugins/search.yml"
|
||||
printf 'titleBoost: 9.5\n' > "$1/default/plugins/search-lucene.yml"
|
||||
}
|
||||
QUERIES=("runway" "deployment" "cloud%20deployment%20guide" "runway%20deployment%20guide" "running" "lucane"
|
||||
"privacy" "hosting%20plans" "mark" "about" "home" "xyzzy%20nothing")
|
||||
ask_all() { # out-dir
|
||||
mkdir -p "$1"
|
||||
local i=0
|
||||
for q in "${QUERIES[@]}"; do
|
||||
curl -s "$BASE/search/api?q=$q" > "$1/$(printf '%02d' "$i")-${q//%20/_}.json"
|
||||
i=$((i + 1))
|
||||
done
|
||||
}
|
||||
|
||||
# --- One throwaway deployment: wizard, fixture, ACTIVE boot ----------------------------------------------------------
|
||||
boot() { # log-file (uses DEPLOY_DIR and EXT)
|
||||
( cd "$DEPLOY_DIR" && exec "$JAVA" -jar "$JAR" --server.port="$PORT" --runway.storage.external="$EXT" ) >"$1" 2>&1 &
|
||||
PID=$!
|
||||
}
|
||||
deploy() { # run-name search-folder lucene-folder [app-level search-lucene.yml]
|
||||
DEPLOY_DIR="$SCRATCH/$1"; EXT="$DEPLOY_DIR/external"; SITES="$EXT/sites"; LOG="$DEPLOY_DIR/active.log"
|
||||
mkdir -p "$EXT/plugins" "$EXT/plugin-settings"
|
||||
cp -r "$2" "$EXT/plugins/search"
|
||||
cp -r "$LUCENE_PROVIDER/target/lucene-provider" "$EXT/plugins/lucene-provider"
|
||||
cp -r "$3" "$EXT/plugins/search-lucene"
|
||||
echo "[verify] $1: booting host (wizard) on :$PORT ..."
|
||||
boot "$DEPLOY_DIR/wizard.log"
|
||||
wait_for "$DEPLOY_DIR/wizard.log" "Started RunwayApplication" 90 \
|
||||
|| { echo "wizard did not start"; tail -20 "$DEPLOY_DIR/wizard.log"; exit 1; }
|
||||
curl -s -o /dev/null -X POST "$BASE/setup" --data-urlencode "username=$APP_USER" --data-urlencode "password=$APP_PW" \
|
||||
--data-urlencode "displayName=Root" --data-urlencode "siteAdminUsername=$SITE_USER" \
|
||||
--data-urlencode "siteAdminPassword=$SITE_PW"
|
||||
for _ in $(seq 1 30); do kill -0 "$PID" 2>/dev/null || break; sleep 1; done
|
||||
stop_host
|
||||
[ -f "$SITES/default/templates/about.th.xml" ] || { echo "the wizard did not seed $SITES/default"; exit 1; }
|
||||
fixture "$SITES"
|
||||
# A generous query ceiling: the comparison asks the same questions on both deployments.
|
||||
printf 'runway:\n plugin:\n search:\n "rate-limit.per-ip-per-minute": 100000\n "rate-limit.per-ip-per-hour": 100000\n' \
|
||||
> "$EXT/plugin-settings/search.yml"
|
||||
[ -z "${4:-}" ] || printf '%s\n' "$4" > "$EXT/plugin-settings/search-lucene.yml"
|
||||
echo "[verify] $1: booting host (ACTIVE) ..."
|
||||
boot "$LOG"
|
||||
wait_for "$LOG" "Started RunwayApplication" 90 || { echo "ACTIVE did not start"; tail -20 "$LOG"; exit 1; }
|
||||
}
|
||||
|
||||
# --- 1. The baseline: search 2.0.0 + search-lucene 3.0.0 -------------------------------------------------------------
|
||||
if [ "${SKIP_BASELINE:-0}" != 1 ]; then
|
||||
echo "[verify] building the baseline (search + search-lucene at $BASELINE_REF) offline ..."
|
||||
SRC="$SCRATCH/baseline-src"
|
||||
mkdir -p "$SRC"
|
||||
git -C "$REPO" archive "$BASELINE_REF" search search-lucene | tar -x -C "$SRC" \
|
||||
|| { echo "cannot read $BASELINE_REF from git"; exit 1; }
|
||||
grep -q '^version: 3.0.0' "$SRC/search-lucene/plugin.yml" && grep -q '^version: 2.0.0' "$SRC/search/plugin.yml" \
|
||||
|| { echo "$BASELINE_REF does not carry search 2.0.0 + search-lucene 3.0.0"; exit 1; }
|
||||
( cd "$SRC/search" && "$MVN" -o -q -DskipTests package ) >"$SCRATCH/baseline-build.txt" 2>&1 \
|
||||
&& ( cd "$SRC/search-lucene" && "$MVN" -o -q -DskipTests package ) >>"$SCRATCH/baseline-build.txt" 2>&1 \
|
||||
|| { echo "baseline build failed (see baseline-build.txt)"; tail -20 "$SCRATCH/baseline-build.txt"; exit 1; }
|
||||
deploy before "$SRC/search/target/search" "$SRC/search-lucene/target/search-lucene"
|
||||
ck "baseline: 3 plugins registered, 0 blocked" "grep -qE 'plugins: 3 registered, 0 blocked' '$LOG'"
|
||||
ck "baseline: the fixture pages serve" "[ \"\$(code '$BASE/guide')\" = 200 ] && [ \"\$(code '$BASE/handbook')\" = 200 ]"
|
||||
ask_all "$SCRATCH/before/answers"
|
||||
grep -E ' WARN ' "$LOG" | grep -E "plugin 'search-lucene'|uses host internals" > "$SCRATCH/baseline-warnings.txt"
|
||||
echo " (search-lucene 3.0.0 drew $(grep -c "search-lucene" "$SCRATCH/baseline-warnings.txt") warning line(s) naming it)"
|
||||
stop_host
|
||||
fi
|
||||
|
||||
# --- 2. The release under test: the current search + this release, index on disk -----------------------------------
|
||||
INDEX_ROOT="$SCRATCH/after/lucene-index"
|
||||
deploy after "$SEARCH/target/search" "$HERE/target/search-lucene" \
|
||||
"$(printf 'runway:\n plugin:\n search-lucene:\n storage: disk\n indexRoot: "%s"' "$INDEX_ROOT")"
|
||||
|
||||
echo "== plugin load (this release's contract) =="
|
||||
ck "3 plugins registered, 0 blocked" "grep -qE 'plugins: 3 registered, 0 blocked' '$LOG'"
|
||||
ck "search-lucene not blocked / quarantined" "! grep -qE \"plugin 'search-lucene' is blocked|plugin-quarantine\" '$LOG'"
|
||||
# Host linkage and the surface rules, in both kernels' words: SPI 0.6.0 WARNed ("uses host internals", "… allowed until
|
||||
# Runway 1.0"); from SPI 1.0.0 the kernel BLOCKS and logs "linkage scan: <reason>" / the surface reason — a grep for the
|
||||
# 0.6.0 wording alone can never fail on a 1.0 kernel.
|
||||
ck "ZERO host-linkage findings" "! grep -qE \"uses host internals|plugin '(search-lucene|search)' linkage scan\" '$LOG'"
|
||||
ck "ZERO bean-name/surface findings" "! grep -qE \"plugin '(search-lucene|search)'.*(allowed until Runway 1.0|bean name|may not contribute)\" '$LOG'"
|
||||
ck "no WARN/ERROR names the plugin" "! grep -E ' (WARN|ERROR) ' '$LOG' | grep -qiE \"search-lucene|mx\\.quest\\.searchlucene\""
|
||||
ck "no collision / degraded / missing class" "! grep -qiE 'collision|duplicate key|degraded|NoClassDefFound|ClassNotFound' '$LOG'"
|
||||
ck "Lucene is NOT bundled in search-lucene" "[ ! -d '$EXT/plugins/search-lucene/lib' ]"
|
||||
ck "the fixture pages serve" "[ \"\$(code '$BASE/guide')\" = 200 ] && [ \"\$(code '$BASE/handbook')\" = 200 ]"
|
||||
ck "no plugin-owned /search page (404)" "[ \"\$(code '$BASE/search?q=runway')\" = 404 ]"
|
||||
|
||||
echo "== ranking: the same answers as 3.0.0 =="
|
||||
ask_all "$SCRATCH/after/answers"
|
||||
ck "the Lucene engine serves (a 1-edit typo finds the handbook)" "grep -q '\"url\":\"/handbook\"' '$SCRATCH/after/answers/05-lucane.json'"
|
||||
ck "the search plugin's exclusion applies through SearchCorpus (no /privacy for 'runway')" \
|
||||
"grep -q '\"url\":\"/guide\"' '$SCRATCH/after/answers/00-runway.json' && ! grep -q '/privacy' '$SCRATCH/after/answers/00-runway.json'"
|
||||
ck "each hit carries the words it matched and a link marked with them" \
|
||||
"grep -qE '\"link\":\"/[^\"]*#rw-hl=[^\"]+\",\"terms\":\\[\"[^\"]+' '$SCRATCH/after/answers/04-running.json'"
|
||||
ck "…as the page writes them, at least every word its snippet marks (running: run, and ran within one edit)" \
|
||||
"python3 -I -c 'import json,re,sys; r=json.load(open(sys.argv[1]))[\"results\"]; ok=all(h[\"terms\"] and set(m.lower() for m in re.findall(\"<mark>(.*?)</mark>\", h[\"snippet\"])) <= set(h[\"terms\"]) for h in r); sys.exit(0 if r and ok else 1)' '$SCRATCH/after/answers/04-running.json'"
|
||||
if [ "${SKIP_BASELINE:-0}" != 1 ]; then
|
||||
# 3.0.0 predates link/terms (search 2.1.0): compare everything else, byte for byte.
|
||||
mkdir -p "$SCRATCH/after/compared"
|
||||
for f in "$SCRATCH"/after/answers/*.json; do
|
||||
python3 -I -c 'import re,sys; s=open(sys.argv[1],encoding="utf-8").read(); sys.stdout.write(re.sub(r",\"link\":\"(?:[^\"\\\\]|\\\\.)*\",\"terms\":\[(?:\"(?:[^\"\\\\]|\\\\.)*\",?)*\]", "", s))' \
|
||||
"$f" > "$SCRATCH/after/compared/$(basename "$f")"
|
||||
done
|
||||
diff -r "$SCRATCH/before/answers" "$SCRATCH/after/compared" > "$SCRATCH/ranking-diff.txt"
|
||||
ck "every answer (order, URLs, titles, snippets, scores) is byte-identical to 3.0.0's (${#QUERIES[@]} queries)" \
|
||||
"[ ! -s '$SCRATCH/ranking-diff.txt' ] && [ \$(ls '$SCRATCH/after/answers' | wc -l) = ${#QUERIES[@]} ]"
|
||||
ck "…and the answers are not trivially empty" "[ \$(cat '$SCRATCH'/after/answers/*.json | grep -o '\"url\"' | wc -l) -ge 15 ]"
|
||||
fi
|
||||
|
||||
echo "== one index per language, bundle strings included =="
|
||||
ck "the page's Spanish copy is rendered from the bundle (fixture)" "curl -s '$BASE/es/facultad' | grep -q 'facultad de excelencia'"
|
||||
curl -s "$BASE/search/api?q=excelencia&lang=es" > "$SCRATCH/after/es.json"
|
||||
ck "a Spanish bundle string is found in Spanish, at the Spanish address, with the Spanish title" \
|
||||
"grep -q '\"url\":\"/es/facultad\"' '$SCRATCH/after/es.json' && grep -q '\"title\":\"Profesores\"' '$SCRATCH/after/es.json'"
|
||||
ck "the Spanish analyzer stems ('facultades' finds 'facultad')" \
|
||||
"curl -s '$BASE/search/api?q=facultades&lang=es' | grep -q '\"url\":\"/es/facultad\"'"
|
||||
ck "the English analyzer stems ('researcher' finds 'researchers')" \
|
||||
"curl -s '$BASE/search/api?q=researcher&lang=en' | grep -q '\"url\":\"/faculty\"'"
|
||||
ck "English does not search the Spanish text" "! curl -s '$BASE/search/api?q=excelencia&lang=en' | grep -q '/faculty'"
|
||||
ck "a page in English only is still found from Spanish" \
|
||||
"curl -s '$BASE/search/api?q=lucene&lang=es' | grep -q '\"url\":\"/handbook\"'"
|
||||
|
||||
echo "== storage: the app-level settings bind (disk) =="
|
||||
ck "the site's index lives on disk under indexRoot/default, one folder per language" \
|
||||
"[ -d '$INDEX_ROOT/default/en' ] && [ -d '$INDEX_ROOT/default/es' ] && ls '$INDEX_ROOT/default/es' | grep -q ."
|
||||
|
||||
echo "== the console (signed in as the site owner) =="
|
||||
token() { grep -o 'name="_csrf" value="[^"]*"' | head -1 | sed 's/.*value="//; s/"$//'; }
|
||||
sc() { curl -s -H 'Accept-Language: en' -c "$SCRATCH/cookies.jar" -b "$SCRATCH/cookies.jar" "$@"; }
|
||||
sc -o /dev/null -X POST "$BASE/login" --data-urlencode "username=$SITE_USER" --data-urlencode "password=$SITE_PW" \
|
||||
--data-urlencode "_csrf=$(sc "$BASE/login" | token)"
|
||||
LS="$BASE/__admin/plugins/search-lucene/settings"
|
||||
sc "$LS" > "$SCRATCH/lucene-settings-0.html"
|
||||
DOCS="$(sed -n 's:.*id="la-pages"[^>]*>\([0-9]*\)<.*:\1:p' "$SCRATCH/lucene-settings-0.html" | head -1)"
|
||||
ck "the admin fragment renders (bean @searchLuceneAdminModel): engine search/lucene" \
|
||||
"grep -q 'id=\"la-engine\"[^>]*>search/lucene<' '$SCRATCH/lucene-settings-0.html'"
|
||||
ck "…the indexed-item count (${DOCS:-none})" "[ -n '$DOCS' ] && [ '$DOCS' -ge 8 ]"
|
||||
ck "…the storage mode (disk)" "grep -q 'id=\"la-storage\"[^>]*>disk<' '$SCRATCH/lucene-settings-0.html'"
|
||||
ck "…and the stored title boost (9.5)" "grep -q 'id=\"la-boost\"[^>]*>9.5<' '$SCRATCH/lucene-settings-0.html'"
|
||||
sc -L "$BASE/__admin" > "$SCRATCH/dashboard.html"
|
||||
ck "the dashboard card renders the count" "grep -q 'id=\"lc-pages\"[^>]*>$DOCS<' '$SCRATCH/dashboard.html'"
|
||||
|
||||
echo "== settings saves reach the next query, without a reindex =="
|
||||
SS="$BASE/__admin/plugins/search/settings"
|
||||
sc -o /dev/null -X POST "$SS" --data-urlencode "enabled=true" --data-urlencode "exclude=guide" \
|
||||
--data-urlencode "_csrf=$(sc "$SS" | token)"
|
||||
curl -s "$BASE/search/api?q=runway%20deployment%20guide" > "$SCRATCH/after-exclude.json"
|
||||
ck "search's exclude list saved (guide in, privacy out of the list)" \
|
||||
"grep -q 'guide' '$SITES/default/plugins/search.yml' && ! grep -q 'privacy' '$SITES/default/plugins/search.yml'"
|
||||
ck "…the newly excluded page leaves this index at once" "! grep -q '\"url\":\"/guide\"' '$SCRATCH/after-exclude.json'"
|
||||
ck "…and the no-longer-excluded page joins it" "grep -q '\"url\":\"/privacy\"' '$SCRATCH/after-exclude.json'"
|
||||
sc -o /dev/null -X POST "$LS" --data-urlencode "fuzzy=false" --data-urlencode "titleBoost=9.5" \
|
||||
--data-urlencode "_csrf=$(token < "$SCRATCH/lucene-settings-0.html")"
|
||||
ck "this plugin's knobs saved (fuzzy off)" "grep -q 'fuzzy: false' '$SITES/default/plugins/search-lucene.yml'"
|
||||
ck "…the typo no longer matches on the next query" "curl -s '$BASE/search/api?q=lucane' | grep -q '\"count\":0'"
|
||||
ck "…while the exact term still does" "curl -s '$BASE/search/api?q=lucene' | grep -q '\"url\":\"/handbook\"'"
|
||||
|
||||
echo "== the operator's reindex rebuilds this index =="
|
||||
sc "$SS" > "$SCRATCH/search-settings.html"
|
||||
sc -X POST "$BASE/search/reindex" --data-urlencode "_csrf=$(token < "$SCRATCH/search-settings.html")" > "$SCRATCH/reindex.txt"
|
||||
ck "POST /search/reindex reports this engine's fresh count (${DOCS:-none})" "grep -qx 'Search index rebuilt\\. ($DOCS)' '$SCRATCH/reindex.txt'"
|
||||
ck "a GET does not reindex (404)" "[ \"\$(sc -o /dev/null -w '%{http_code}' '$BASE/search/reindex')\" = 404 ]"
|
||||
|
||||
echo "== the build wrote nothing to the local Maven repository =="
|
||||
m2_after="$(ls -d "$M2"/runway-plugin-search-lucene/"$VER" 2>/dev/null)"
|
||||
ck "search-lucene itself is never installed to ~/.m2 (only its compile dependency, search, is)" "[ -z '$m2_after' ] || [ '$m2_after' = '$m2_before' ]"
|
||||
|
||||
ck "still no WARN/ERROR names the plugin after the run" "! grep -E ' (WARN|ERROR) ' '$LOG' | grep -qiE \"search-lucene|mx\\.quest\\.searchlucene\""
|
||||
|
||||
echo; echo "RESULT: $PASS passed, $FAIL failed"
|
||||
if [ "$KEEP" = "yes" ]; then echo "[verify] kept at $BASE (scratch $SCRATCH; kill $PID to stop)"; wait "$PID"; fi
|
||||
exit "$FAIL"
|
||||
@@ -0,0 +1,33 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Reduces a page's raw HTML source to indexable plain text: drops {@code <script>}/{@code <style>} blocks and
|
||||
* comments, strips the remaining tags, decodes a handful of common entities, and collapses whitespace. This is
|
||||
* a best-effort text extraction for full-text indexing — not a strict HTML parser — so a malformed page still
|
||||
* yields reasonable searchable text.
|
||||
*/
|
||||
final class HtmlText {
|
||||
|
||||
private static final Pattern SCRIPT_STYLE =
|
||||
Pattern.compile("(?is)<(script|style)\\b[^>]*>.*?</\\1>");
|
||||
private static final Pattern COMMENT = Pattern.compile("(?s)<!--.*?-->");
|
||||
private static final Pattern TAG = Pattern.compile("<[^>]+>");
|
||||
private static final Pattern WS = Pattern.compile("\\s+");
|
||||
|
||||
private HtmlText() {
|
||||
}
|
||||
|
||||
static String toText(String html) {
|
||||
if (html == null || html.isBlank()) {
|
||||
return "";
|
||||
}
|
||||
String s = SCRIPT_STYLE.matcher(html).replaceAll(" ");
|
||||
s = COMMENT.matcher(s).replaceAll(" ");
|
||||
s = TAG.matcher(s).replaceAll(" ");
|
||||
s = s.replace(" ", " ").replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
.replace(""", "\"").replace("'", "'").replace("'", "'");
|
||||
return WS.matcher(s).replaceAll(" ").strip();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.function.Supplier;
|
||||
import org.apache.lucene.analysis.Analyzer;
|
||||
import org.apache.lucene.analysis.ar.ArabicAnalyzer;
|
||||
import org.apache.lucene.analysis.bg.BulgarianAnalyzer;
|
||||
import org.apache.lucene.analysis.ca.CatalanAnalyzer;
|
||||
import org.apache.lucene.analysis.cz.CzechAnalyzer;
|
||||
import org.apache.lucene.analysis.da.DanishAnalyzer;
|
||||
import org.apache.lucene.analysis.de.GermanAnalyzer;
|
||||
import org.apache.lucene.analysis.el.GreekAnalyzer;
|
||||
import org.apache.lucene.analysis.en.EnglishAnalyzer;
|
||||
import org.apache.lucene.analysis.es.SpanishAnalyzer;
|
||||
import org.apache.lucene.analysis.eu.BasqueAnalyzer;
|
||||
import org.apache.lucene.analysis.fi.FinnishAnalyzer;
|
||||
import org.apache.lucene.analysis.fr.FrenchAnalyzer;
|
||||
import org.apache.lucene.analysis.gl.GalicianAnalyzer;
|
||||
import org.apache.lucene.analysis.hi.HindiAnalyzer;
|
||||
import org.apache.lucene.analysis.hu.HungarianAnalyzer;
|
||||
import org.apache.lucene.analysis.hy.ArmenianAnalyzer;
|
||||
import org.apache.lucene.analysis.id.IndonesianAnalyzer;
|
||||
import org.apache.lucene.analysis.it.ItalianAnalyzer;
|
||||
import org.apache.lucene.analysis.lt.LithuanianAnalyzer;
|
||||
import org.apache.lucene.analysis.lv.LatvianAnalyzer;
|
||||
import org.apache.lucene.analysis.nl.DutchAnalyzer;
|
||||
import org.apache.lucene.analysis.no.NorwegianAnalyzer;
|
||||
import org.apache.lucene.analysis.pt.PortugueseAnalyzer;
|
||||
import org.apache.lucene.analysis.ro.RomanianAnalyzer;
|
||||
import org.apache.lucene.analysis.ru.RussianAnalyzer;
|
||||
import org.apache.lucene.analysis.standard.StandardAnalyzer;
|
||||
import org.apache.lucene.analysis.sv.SwedishAnalyzer;
|
||||
import org.apache.lucene.analysis.th.ThaiAnalyzer;
|
||||
import org.apache.lucene.analysis.tr.TurkishAnalyzer;
|
||||
|
||||
/**
|
||||
* Chooses a Lucene {@link Analyzer} per content/query language, so a site's pages are tokenized <b>and
|
||||
* stemmed</b> for the language they are written in — a query for {@code "running"} matches a page that says
|
||||
* {@code "run"}, a Spanish query for {@code "corriendo"} matches {@code "correr"}, and so on. Where Lucene ships
|
||||
* a language-specific analyzer (which bundles that language's stopword list and stemmer), that analyzer is used;
|
||||
* for any language Lucene has no analyzer for — or an unknown/blank language — it falls back to
|
||||
* {@link StandardAnalyzer} (tokenize + lowercase, no stemming), which is always correct, just less clever.
|
||||
*
|
||||
* <p><b>Why the same analyzer must be used at index and query time:</b> stemming is an analysis-time transform.
|
||||
* If the index stemmed {@code "running" → "run"} but the query analyzer did not, the query term {@code "running"}
|
||||
* would never match the indexed term {@code "run"}. This class is the single source of truth for "the analyzer
|
||||
* for language X", called from both the indexer and the searcher, so the two can never drift.
|
||||
*
|
||||
* <p>Analyzers are <b>immutable and thread-safe</b> once built, and building one is not free (it reads a
|
||||
* stopword resource), so instances are cached per language key. The lookup key is the lowercased ISO language
|
||||
* code (e.g. {@code "en"}, {@code "es"}); a full {@link Locale} is reduced to its language.
|
||||
*/
|
||||
final class LocaleAnalyzers {
|
||||
|
||||
/** Language code → a factory for that language's analyzer. Absent code ⇒ StandardAnalyzer fallback. */
|
||||
private static final Map<String, Supplier<Analyzer>> BY_LANGUAGE = Map.ofEntries(
|
||||
Map.entry("ar", ArabicAnalyzer::new),
|
||||
Map.entry("bg", BulgarianAnalyzer::new),
|
||||
Map.entry("ca", CatalanAnalyzer::new),
|
||||
Map.entry("cs", CzechAnalyzer::new),
|
||||
Map.entry("da", DanishAnalyzer::new),
|
||||
Map.entry("de", GermanAnalyzer::new),
|
||||
Map.entry("el", GreekAnalyzer::new),
|
||||
Map.entry("en", EnglishAnalyzer::new),
|
||||
Map.entry("es", SpanishAnalyzer::new),
|
||||
Map.entry("eu", BasqueAnalyzer::new),
|
||||
Map.entry("fi", FinnishAnalyzer::new),
|
||||
Map.entry("fr", FrenchAnalyzer::new),
|
||||
Map.entry("gl", GalicianAnalyzer::new),
|
||||
Map.entry("hi", HindiAnalyzer::new),
|
||||
Map.entry("hu", HungarianAnalyzer::new),
|
||||
Map.entry("hy", ArmenianAnalyzer::new),
|
||||
Map.entry("id", IndonesianAnalyzer::new),
|
||||
Map.entry("it", ItalianAnalyzer::new),
|
||||
Map.entry("lt", LithuanianAnalyzer::new),
|
||||
Map.entry("lv", LatvianAnalyzer::new),
|
||||
Map.entry("nl", DutchAnalyzer::new),
|
||||
Map.entry("no", NorwegianAnalyzer::new),
|
||||
Map.entry("pt", PortugueseAnalyzer::new),
|
||||
Map.entry("ro", RomanianAnalyzer::new),
|
||||
Map.entry("ru", RussianAnalyzer::new),
|
||||
Map.entry("sv", SwedishAnalyzer::new),
|
||||
Map.entry("th", ThaiAnalyzer::new),
|
||||
Map.entry("tr", TurkishAnalyzer::new));
|
||||
|
||||
/** Built analyzers, cached by language key. Analyzers are thread-safe, so caching is a pure win. */
|
||||
private final ConcurrentMap<String, Analyzer> cache = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* The analyzer for {@code locale}'s language — a stemming language analyzer where Lucene ships one, else
|
||||
* {@link StandardAnalyzer}. Never {@code null}. The returned analyzer is shared and must not be closed by the
|
||||
* caller (the engine owns lifecycle via {@link #close()}).
|
||||
*
|
||||
* @param locale the content/query locale; a {@code null} locale is treated as the standard fallback
|
||||
*/
|
||||
Analyzer forLocale(Locale locale) {
|
||||
String lang = (locale == null) ? "" : locale.getLanguage().toLowerCase(Locale.ROOT);
|
||||
return forLanguage(lang);
|
||||
}
|
||||
|
||||
/** As {@link #forLocale(Locale)} but keyed directly by an ISO language code (blank/unknown ⇒ standard). */
|
||||
Analyzer forLanguage(String language) {
|
||||
String lang = (language == null) ? "" : language.toLowerCase(Locale.ROOT);
|
||||
return cache.computeIfAbsent(lang, k -> {
|
||||
Supplier<Analyzer> factory = BY_LANGUAGE.get(k);
|
||||
return (factory != null) ? factory.get() : new StandardAnalyzer();
|
||||
});
|
||||
}
|
||||
|
||||
/** Whether a genuine language analyzer (with stemming) exists for {@code language} — for the console/tests. */
|
||||
static boolean hasLanguageAnalyzer(String language) {
|
||||
return language != null && BY_LANGUAGE.containsKey(language.toLowerCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
/** Release every cached analyzer (called when the engine is disposed). Idempotent. */
|
||||
void close() {
|
||||
cache.values().forEach(Analyzer::close);
|
||||
cache.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
/**
|
||||
* Read-only status model for the plugin's console surfaces (dashboard card + admin fragment), read by template
|
||||
* bean name, e.g. {@code ${@searchLuceneAdminModel.indexedPages(tenantSiteId)}}. It delegates to the live
|
||||
* {@link LuceneSearchEngine} so the numbers reflect the actual per-site index and effective ranking config.
|
||||
*/
|
||||
public class LuceneAdminModel {
|
||||
|
||||
private final LuceneSearchEngine engine;
|
||||
|
||||
public LuceneAdminModel(LuceneSearchEngine engine) {
|
||||
this.engine = engine;
|
||||
}
|
||||
|
||||
/** How many pages are in this site's Lucene index right now. */
|
||||
public int indexedPages(String siteId) {
|
||||
return engine.indexedDocuments(siteId);
|
||||
}
|
||||
|
||||
/** The engine key (constant) — shown so an operator can confirm which engine is active. */
|
||||
public String engineKey() {
|
||||
return LuceneSearchEngine.KEY;
|
||||
}
|
||||
|
||||
/** The effective title boost applied to this site's queries. */
|
||||
public String titleBoost(String siteId) {
|
||||
return String.valueOf(engine.effectiveTitleBoost(siteId));
|
||||
}
|
||||
|
||||
/** The active index storage mode ({@code heap} or {@code disk}) — an app-level (platform) setting. */
|
||||
public String storageMode() {
|
||||
return engine.storageMode();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,690 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.regex.Pattern;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.Sites;
|
||||
import mx.quest.search.spi.SearchCorpus;
|
||||
import mx.quest.search.spi.SearchHit;
|
||||
import mx.quest.search.spi.SearchQuery;
|
||||
import mx.quest.search.spi.SiteSearchEngine;
|
||||
import org.apache.lucene.analysis.Analyzer;
|
||||
import org.apache.lucene.analysis.TokenStream;
|
||||
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
|
||||
import org.apache.lucene.document.Document;
|
||||
import org.apache.lucene.document.Field;
|
||||
import org.apache.lucene.document.StoredField;
|
||||
import org.apache.lucene.document.TextField;
|
||||
import org.apache.lucene.index.DirectoryReader;
|
||||
import org.apache.lucene.index.IndexWriter;
|
||||
import org.apache.lucene.index.IndexWriterConfig;
|
||||
import org.apache.lucene.index.StoredFields;
|
||||
import org.apache.lucene.index.Term;
|
||||
import org.apache.lucene.search.BooleanClause;
|
||||
import org.apache.lucene.search.BooleanQuery;
|
||||
import org.apache.lucene.search.BoostQuery;
|
||||
import org.apache.lucene.search.ConstantScoreQuery;
|
||||
import org.apache.lucene.search.FuzzyQuery;
|
||||
import org.apache.lucene.search.IndexSearcher;
|
||||
import org.apache.lucene.search.PhraseQuery;
|
||||
import org.apache.lucene.search.Query;
|
||||
import org.apache.lucene.search.ScoreDoc;
|
||||
import org.apache.lucene.search.TermQuery;
|
||||
import org.apache.lucene.search.TopDocs;
|
||||
import org.apache.lucene.search.uhighlight.DefaultPassageFormatter;
|
||||
import org.apache.lucene.search.uhighlight.UnifiedHighlighter;
|
||||
import org.apache.lucene.store.ByteBuffersDirectory;
|
||||
import org.apache.lucene.store.Directory;
|
||||
import org.apache.lucene.store.MMapDirectory;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* A Lucene-backed {@link SiteSearchEngine} — the {@code search-lucene} plugin's contribution to the {@code search}
|
||||
* plugin's engine SPI. It builds a per-site full-text index over the search plugin's {@link SearchCorpus} — every
|
||||
* published page and content-source item (the entries plugins publish, …) the site has not excluded from search — indexing each
|
||||
* item's <b>title</b>,
|
||||
* <b>description</b> and <b>body text</b> (extracted from the item's indexable material with {@link HtmlText})
|
||||
* and answers a
|
||||
* query with a <b>tiered, constant-score</b> relevance model layered on top of Lucene's BM25 term matching:
|
||||
*
|
||||
* <ol>
|
||||
* <li><b>any-terms</b> — each analyzed query term as a {@code SHOULD} {@link TermQuery} across title (boosted),
|
||||
* description (boosted) and body, plus optional typo-tolerant {@link FuzzyQuery} clauses. This is the
|
||||
* BM25-scored base layer that separates documents <em>within</em> a tier.</li>
|
||||
* <li><b>near phrase (body)</b> — the query terms as a {@link PhraseQuery} with a small slop, a
|
||||
* {@code ConstantScoreQuery} worth {@code tierNearPhrase}: proximity beats scattered terms.</li>
|
||||
* <li><b>exact phrase (body)</b> — the query as an exact ({@code slop=0}) body phrase, worth
|
||||
* {@code tierPhraseBody}.</li>
|
||||
* <li><b>exact phrase (title)</b> — the query as an exact title phrase, worth {@code tierPhraseTitle}: a page
|
||||
* whose <em>title</em> is the query is the strongest possible match.</li>
|
||||
* <li><b>all-terms-anywhere</b> — a {@code ConstantScoreQuery} worth {@code tierAllTerms} that fires only when
|
||||
* every query term appears somewhere in the document, lifting complete matches above partial ones.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>The tiers are additive {@code SHOULD} clauses, so a hit's score is the sum of the tiers it satisfies — an
|
||||
* exact-title-phrase hit outranks a near-phrase hit, which outranks a scattered-terms hit, deterministically.
|
||||
* Analysis (tokenization + <b>stemming</b>) is <b>per-locale</b> via {@link LocaleAnalyzers}, so a query matches
|
||||
* a stemmed surface form (an English query {@code running} matches {@code run}); the <em>same</em> analyzer is
|
||||
* used at index and query time so the two never drift. Result snippets are <b>query-focused and highlighted</b>:
|
||||
* {@link UnifiedHighlighter} wraps the matched terms in {@code <mark>…</mark>} within the best-matching body
|
||||
* passage, falling back to a plain leading snippet if highlighting yields nothing. Each hit also carries the words
|
||||
* the query matched as the page writes them ({@link MatchedForms}), which the page the result opens highlights.
|
||||
*
|
||||
* <p>The index covers the {@link SearchCorpus} the search plugin publishes — every published item, pages and
|
||||
* content-source items alike, minus the site's search exclusions. It is the same corpus the built-in engine
|
||||
* indexes, so what is searchable never depends on which engine serves the query, and the exclusion rule lives in
|
||||
* one place (the search plugin).
|
||||
*
|
||||
* <p><b>One index per language (since 3.2.0).</b> Each item is indexed once per language it exists in — its title,
|
||||
* description and body in that language (the body is the page as the kernel renders it there, bundle strings
|
||||
* included), linked at {@link CatalogEntry#pathFor} that language. A site has one index per language it speaks,
|
||||
* analyzed with that language's analyzer: the language's own documents plus, for an item that does not exist in
|
||||
* it, the item's <b>primary-locale</b> document (the site's default language when the item exists in it, else its
|
||||
* first language), so a page published in one language only is still found from every other. A query searches
|
||||
* the index of its own language ({@link SearchQuery#locale()}), with that index's analyzer; a language the site
|
||||
* does not speak searches the site default's. A fallback document is analyzed with the index's analyzer, not its
|
||||
* own language's — so it matches on exact and lightly stemmed forms, not on every inflection. Before 3.2.0 a site
|
||||
* had one index of primary-locale documents analyzed with the default language's analyzer, so every language
|
||||
* searched default-language text.
|
||||
*
|
||||
* <p>The index lives in heap ({@link ByteBuffersDirectory}) or on disk ({@link MMapDirectory}) per the app-level
|
||||
* {@link LuceneStorageProps}. It is cached per site, dropped by {@link #invalidate} — which the plugin's
|
||||
* {@code SiteEventListener} calls for every change that may reshape the corpus (a page write, a content source's
|
||||
* change, a site lifecycle event, any plugin's settings save) — rebuilt eagerly by the operator's {@link #reindex}
|
||||
* action, and additionally refreshed by a short TTL (the backstop for changes no event announces). The engine registers at {@link #priority()}
|
||||
* 100 (it supersedes the built-in engine) and is always {@link #available(String) available} — it builds on
|
||||
* demand. Per the SPI contract, {@link #search(SearchQuery)} <b>never throws</b>: any failure (I/O, a corrupt
|
||||
* index) is logged and returns no results.
|
||||
*/
|
||||
public class LuceneSearchEngine implements SiteSearchEngine, AutoCloseable {
|
||||
|
||||
static final String KEY = "search/lucene";
|
||||
private static final Logger log = LoggerFactory.getLogger(LuceneSearchEngine.class);
|
||||
|
||||
/** Indexed + query field names. */
|
||||
private static final String F_TITLE = "title";
|
||||
private static final String F_DESCRIPTION = "description";
|
||||
private static final String F_BODY = "body";
|
||||
/** Stored (display-only) field names. */
|
||||
private static final String S_URL = "s_url";
|
||||
private static final String S_TITLE = "s_title";
|
||||
private static final String S_DESCRIPTION = "s_description";
|
||||
private static final String S_BODY = "s_body";
|
||||
|
||||
private static final long FRESHNESS_MILLIS = 30_000L;
|
||||
private static final int SNIPPET_MAX = 200;
|
||||
private static final int MAX_QUERY_TERMS = 32;
|
||||
/** Slop for the "near phrase" tier — terms may be up to this far apart / lightly reordered. */
|
||||
private static final int NEAR_SLOP = 1;
|
||||
/** Private markers the {@link UnifiedHighlighter} wraps hits in; rewritten to {@code <mark>}/{@code </mark>}
|
||||
* only after the surrounding passage has been HTML-escaped, so a page's own {@code <} can't forge a tag. */
|
||||
private static final char MARK_OPEN_CH = '\u0001';
|
||||
private static final char MARK_CLOSE_CH = '\u0002';
|
||||
private static final String MARK_OPEN = String.valueOf(MARK_OPEN_CH);
|
||||
private static final String MARK_CLOSE = String.valueOf(MARK_CLOSE_CH);
|
||||
/** Guards the per-site subfolder used for a disk index (path-traversal / injection safe). */
|
||||
private static final Pattern SAFE_SITE_ID = Pattern.compile("[a-z0-9][a-z0-9._-]{0,63}");
|
||||
/** A language subdirectory name: an ISO 639 code as {@link Locale#getLanguage()} returns it. */
|
||||
private static final Pattern SAFE_LANGUAGE = Pattern.compile("[a-z]{2,8}");
|
||||
|
||||
private final SearchCorpus corpus;
|
||||
private final Sites sites;
|
||||
private final PluginSettings settings;
|
||||
private final LuceneStorageProps storage;
|
||||
private final LocaleAnalyzers analyzers = new LocaleAnalyzers();
|
||||
|
||||
private final Map<String, CachedIndex> cache = new ConcurrentHashMap<>();
|
||||
private final Map<String, Object> locks = new ConcurrentHashMap<>();
|
||||
/**
|
||||
* Bumped by every {@link #invalidate}. A build that started before an invalidation may have read the old corpus,
|
||||
* so it is kept only as already-stale: it answers the query that built it, and the next query rebuilds.
|
||||
*/
|
||||
private final AtomicLong generation = new AtomicLong();
|
||||
/** Site index folders already checked for a 3.1.x index (see {@link #deleteOldLayout}). */
|
||||
private final java.util.Set<Path> oldLayoutChecked = ConcurrentHashMap.newKeySet();
|
||||
/**
|
||||
* The sites whose index this thread is building. A build renders pages, and a page's widget that searched
|
||||
* the same site would re-enter the build (the per-site lock is reentrant) and recurse; such a search answers
|
||||
* nothing instead.
|
||||
*/
|
||||
private static final ThreadLocal<java.util.Set<String>> BUILDING = ThreadLocal.withInitial(java.util.HashSet::new);
|
||||
|
||||
/**
|
||||
* @param corpus what to index: the search plugin's corpus (the content listing minus the site's exclusions)
|
||||
* @param sites the kernel's site lookup (a site's default locale chooses the analyzer)
|
||||
* @param settings this plugin's per-site settings (the ranking knobs), read per query
|
||||
* @param storage the app-level storage settings (heap or disk)
|
||||
*/
|
||||
public LuceneSearchEngine(SearchCorpus corpus, Sites sites, PluginSettings settings, LuceneStorageProps storage) {
|
||||
this.corpus = Objects.requireNonNull(corpus, "corpus");
|
||||
this.sites = Objects.requireNonNull(sites, "sites");
|
||||
this.settings = Objects.requireNonNull(settings, "settings");
|
||||
this.storage = Objects.requireNonNull(storage, "storage");
|
||||
}
|
||||
|
||||
/** One language's index: its directory, the analyzer used to build it (reused at query time) and its size. */
|
||||
private record LanguageIndex(Directory dir, Analyzer analyzer, int documents) {
|
||||
}
|
||||
|
||||
/**
|
||||
* A built per-site index: one {@link LanguageIndex} per language the site speaks, the site default's language
|
||||
* (the index a query in another language searches), the number of items indexed, and when it was built.
|
||||
*/
|
||||
private record CachedIndex(Map<String, LanguageIndex> languages, String defaultLanguage, int items,
|
||||
long builtAtMillis) {
|
||||
|
||||
/** The same index, marked as already past its freshness window. */
|
||||
CachedIndex stale() {
|
||||
return new CachedIndex(languages, defaultLanguage, items, 0L);
|
||||
}
|
||||
|
||||
/** The index a query in {@code locale} searches; the site default's when the site lacks that language. */
|
||||
LanguageIndex forQuery(Locale locale) {
|
||||
LanguageIndex index = languages.get(locale.getLanguage());
|
||||
return index != null ? index : languages.get(defaultLanguage);
|
||||
}
|
||||
|
||||
void close() {
|
||||
languages.values().forEach(l -> closeQuietly(l.dir()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return KEY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int priority() {
|
||||
return 100; // supersede the built-in engine wherever this plugin is installed
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<SearchHit> search(SearchQuery query) {
|
||||
if (BUILDING.get().contains(query.siteId())) {
|
||||
return List.of(); // a search from inside this site's own index build (see BUILDING)
|
||||
}
|
||||
LanguageIndex index;
|
||||
try {
|
||||
index = index(query.siteId()).forQuery(query.locale());
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("lucene index unavailable for site '{}': {}", query.siteId(), e.toString());
|
||||
return List.of();
|
||||
}
|
||||
if (index == null || index.documents() == 0) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> terms = analyze(index.analyzer(), query.text());
|
||||
if (terms.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
RankingConfig ranking = ranking(query.siteId());
|
||||
Query q = buildQuery(terms, ranking);
|
||||
try (DirectoryReader reader = DirectoryReader.open(index.dir())) {
|
||||
IndexSearcher searcher = new IndexSearcher(reader);
|
||||
TopDocs top = searcher.search(q, Math.max(1, query.limit()));
|
||||
String[] highlights = highlight(searcher, index.analyzer(), q, top);
|
||||
StoredFields stored = searcher.storedFields();
|
||||
MatchedForms matched = MatchedForms.forQuery(index.analyzer(), terms, ranking.fuzzy());
|
||||
List<SearchHit> hits = new ArrayList<>(top.scoreDocs.length);
|
||||
for (int i = 0; i < top.scoreDocs.length; i++) {
|
||||
ScoreDoc sd = top.scoreDocs[i];
|
||||
Document d = stored.document(sd.doc);
|
||||
String snippet = snippet(highlights[i], d);
|
||||
List<String> forms = matched.in(
|
||||
List.of(nonNull(d.get(S_TITLE)), nonNull(d.get(S_DESCRIPTION)), nonNull(d.get(S_BODY))));
|
||||
hits.add(new SearchHit(d.get(S_URL), d.get(S_TITLE), snippet, sd.score, forms));
|
||||
}
|
||||
return List.copyOf(hits);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
log.warn("lucene search failed for site '{}': {}", query.siteId(), e.toString());
|
||||
return List.of(); // an SPI never throws for a query; fall back to no results
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The SPI's manual-reindex hook: drops the cached index and rebuilds it <b>now</b> from current content,
|
||||
* returning the fresh document count — so the operator's reindex action rebuilds this engine too, not only
|
||||
* the built-in one. A failed rebuild logs and reports {@code 0}, per the SPI's never-throw posture.
|
||||
*/
|
||||
@Override
|
||||
public int reindex(String siteId) {
|
||||
corpus.refresh(siteId); // out-of-band edits fire no event; refresh the shared listing before rebuilding
|
||||
invalidate(siteId);
|
||||
return indexedDocuments(siteId);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------- console
|
||||
|
||||
/**
|
||||
* The number of items (pages and content) currently in this site's index — items, not per-language documents
|
||||
* (builds/refreshes it if needed) — for the console.
|
||||
*/
|
||||
public int indexedDocuments(String siteId) {
|
||||
try {
|
||||
return index(siteId).items();
|
||||
} catch (RuntimeException e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/** The effective per-tenant title boost (for the console). */
|
||||
public float effectiveTitleBoost(String siteId) {
|
||||
return ranking(siteId).titleBoost();
|
||||
}
|
||||
|
||||
/** The active storage mode ({@code heap}/{@code disk}) — for the console. */
|
||||
public String storageMode() {
|
||||
return storage.isDisk() ? "disk" : "heap";
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------------------- lifecycle
|
||||
|
||||
/**
|
||||
* Drops the site's cached index, so the next query rebuilds it from the current corpus. Called from the plugin's
|
||||
* {@code SiteEventListener} for every change that may reshape the corpus, after the kernel has evicted its own
|
||||
* caches — so the rebuild reads the new state.
|
||||
*/
|
||||
void invalidate(String siteId) {
|
||||
generation.incrementAndGet();
|
||||
evict(siteId);
|
||||
}
|
||||
|
||||
private void evict(String siteId) {
|
||||
CachedIndex removed = cache.remove(siteId);
|
||||
if (removed != null) {
|
||||
removed.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** Release every cached directory and analyzer (Spring calls this on context shutdown). */
|
||||
@Override
|
||||
public void close() {
|
||||
cache.values().forEach(CachedIndex::close);
|
||||
cache.clear();
|
||||
analyzers.close();
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------------- index build
|
||||
|
||||
private CachedIndex index(String siteId) {
|
||||
long now = System.currentTimeMillis();
|
||||
CachedIndex cached = cache.get(siteId);
|
||||
if (cached != null && now - cached.builtAtMillis() < FRESHNESS_MILLIS) {
|
||||
return cached;
|
||||
}
|
||||
synchronized (locks.computeIfAbsent(siteId, k -> new Object())) {
|
||||
cached = cache.get(siteId);
|
||||
if (cached != null && System.currentTimeMillis() - cached.builtAtMillis() < FRESHNESS_MILLIS) {
|
||||
return cached;
|
||||
}
|
||||
long started = generation.get();
|
||||
CachedIndex fresh;
|
||||
BUILDING.get().add(siteId);
|
||||
try {
|
||||
fresh = build(siteId);
|
||||
} finally {
|
||||
BUILDING.get().remove(siteId);
|
||||
}
|
||||
if (generation.get() != started) {
|
||||
fresh = fresh.stale(); // a change arrived mid-build: this one may hold the old corpus
|
||||
}
|
||||
CachedIndex prev = cache.put(siteId, fresh);
|
||||
if (prev != null) {
|
||||
prev.close();
|
||||
}
|
||||
return fresh;
|
||||
}
|
||||
}
|
||||
|
||||
/** One item's indexed fields in one language. */
|
||||
private record IndexedText(String url, String title, String description, String body) {
|
||||
}
|
||||
|
||||
/** An item's primary-locale fields and the languages it has its own documents in, while views are assembled. */
|
||||
private record Item(IndexedText primary, java.util.Set<String> languages) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds every language index of a site (see the class comment). Each item's text is read once per language it
|
||||
* exists in and reused by every index that holds it. An unknown site gets one empty index for English.
|
||||
*/
|
||||
private CachedIndex build(String siteId) {
|
||||
SiteView site = sites.find(siteId).orElse(null);
|
||||
Locale siteDefault = site == null ? Locale.ENGLISH : site.defaultLocale();
|
||||
Map<String, List<IndexedText>> own = new java.util.LinkedHashMap<>();
|
||||
List<Item> items = new ArrayList<>();
|
||||
try {
|
||||
for (CatalogEntry entry : corpus.corpus(siteId)) { // empty for an unknown site
|
||||
Locale primary = entry.ref().primaryLocale(siteDefault);
|
||||
java.util.Set<String> languages = new java.util.LinkedHashSet<>();
|
||||
IndexedText primaryText = null;
|
||||
List<Locale> locales = entry.ref().locales().isEmpty() ? List.of(siteDefault) : entry.ref().locales();
|
||||
for (Locale locale : locales) {
|
||||
if (!languages.add(locale.getLanguage())) {
|
||||
continue;
|
||||
}
|
||||
IndexedText text = text(siteId, entry, locale);
|
||||
own.computeIfAbsent(locale.getLanguage(), k -> new ArrayList<>()).add(text);
|
||||
if (locale.getLanguage().equals(primary.getLanguage())) {
|
||||
primaryText = text;
|
||||
}
|
||||
}
|
||||
items.add(new Item(primaryText != null ? primaryText : text(siteId, entry, primary),
|
||||
java.util.Set.copyOf(languages)));
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("lucene corpus read failed for site '{}': {}", siteId, e.toString());
|
||||
}
|
||||
java.util.Set<String> viewLanguages = new java.util.LinkedHashSet<>();
|
||||
viewLanguages.add(siteDefault.getLanguage());
|
||||
if (site != null) {
|
||||
site.locales().forEach(l -> viewLanguages.add(l.getLanguage()));
|
||||
}
|
||||
viewLanguages.addAll(own.keySet());
|
||||
Map<String, LanguageIndex> indexes = new java.util.HashMap<>();
|
||||
for (String language : viewLanguages) {
|
||||
List<IndexedText> view = new ArrayList<>(own.getOrDefault(language, List.of()));
|
||||
for (Item item : items) {
|
||||
if (!item.languages().contains(language)) {
|
||||
view.add(item.primary());
|
||||
}
|
||||
}
|
||||
indexes.put(language, write(siteId, language, view));
|
||||
}
|
||||
return new CachedIndex(Map.copyOf(indexes), siteDefault.getLanguage(), items.size(),
|
||||
System.currentTimeMillis());
|
||||
}
|
||||
|
||||
/** The item's fields in {@code locale}: title, description and body in that language, at its address there. */
|
||||
private IndexedText text(String siteId, CatalogEntry entry, Locale locale) {
|
||||
String title = localized(entry.ref().title(), locale, entry.ref().id());
|
||||
String description = localized(entry.ref().description(), locale, "");
|
||||
String body = HtmlText.toText(corpus.indexableText(siteId, entry, locale));
|
||||
return new IndexedText(entry.pathFor(locale), title, description, body);
|
||||
}
|
||||
|
||||
/** Writes one language's index with that language's analyzer; a failed write leaves what was added so far. */
|
||||
private LanguageIndex write(String siteId, String language, List<IndexedText> texts) {
|
||||
Analyzer analyzer = analyzers.forLanguage(language);
|
||||
Directory dir;
|
||||
try {
|
||||
dir = newDirectory(siteId, language);
|
||||
} catch (IOException e) {
|
||||
log.warn("lucene directory init failed for site '{}' ({}), falling back to heap: {}", siteId, language,
|
||||
e.toString());
|
||||
dir = new ByteBuffersDirectory();
|
||||
}
|
||||
int docs = 0;
|
||||
try (IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(analyzer))) {
|
||||
writer.deleteAll(); // rebuild-from-scratch semantics for a disk directory that already had content
|
||||
for (IndexedText text : texts) {
|
||||
Document doc = new Document();
|
||||
doc.add(new TextField(F_TITLE, text.title(), Field.Store.NO));
|
||||
doc.add(new TextField(F_DESCRIPTION, text.description(), Field.Store.NO));
|
||||
// Body is BOTH analyzed (for matching) and stored (so the highlighter can re-analyze the source).
|
||||
doc.add(new TextField(F_BODY, text.body(), Field.Store.YES));
|
||||
doc.add(new StoredField(S_URL, text.url()));
|
||||
doc.add(new StoredField(S_TITLE, text.title()));
|
||||
doc.add(new StoredField(S_DESCRIPTION, text.description()));
|
||||
doc.add(new StoredField(S_BODY, text.body()));
|
||||
writer.addDocument(doc);
|
||||
docs++;
|
||||
}
|
||||
} catch (IOException | RuntimeException e) {
|
||||
log.warn("lucene index build failed for site '{}' ({}): {}", siteId, language, e.toString());
|
||||
}
|
||||
return new LanguageIndex(dir, analyzer, docs);
|
||||
}
|
||||
|
||||
/**
|
||||
* A directory for one language of {@code siteId}: an in-memory {@link ByteBuffersDirectory} in heap mode, or a
|
||||
* memory-mapped {@link MMapDirectory} under {@code indexRoot/<siteId>/<language>} in disk mode. The site id is
|
||||
* validated against {@link #SAFE_SITE_ID}, the language against {@link #SAFE_LANGUAGE}, and the resolved path is
|
||||
* asserted to stay under the (normalized, absolute) index root, so a crafted id can never escape the index tree
|
||||
* — even though site ids are already path-safe upstream, storage paths get their own guard (defense in depth for
|
||||
* an operator-set root). Index files a 3.1.x build left directly under {@code indexRoot/<siteId>} (one index per
|
||||
* site) are deleted, so the old index does not linger beside the new ones.
|
||||
*/
|
||||
static boolean isLuceneFile(String name) {
|
||||
return name.startsWith(org.apache.lucene.index.IndexFileNames.SEGMENTS) || name.equals("write.lock")
|
||||
|| org.apache.lucene.index.IndexFileNames.CODEC_FILE_PATTERN.matcher(name).matches();
|
||||
}
|
||||
|
||||
private Directory newDirectory(String siteId, String language) throws IOException {
|
||||
if (!storage.isDisk()) {
|
||||
return new ByteBuffersDirectory();
|
||||
}
|
||||
if (!SAFE_SITE_ID.matcher(siteId).matches()) {
|
||||
throw new IOException("unsafe site id for a disk index: '" + siteId + "'");
|
||||
}
|
||||
if (!SAFE_LANGUAGE.matcher(language).matches()) {
|
||||
throw new IOException("unsafe language for a disk index: '" + language + "'");
|
||||
}
|
||||
Path root = Path.of(storage.getIndexRoot()).toAbsolutePath().normalize();
|
||||
Path siteDir = root.resolve(siteId).normalize();
|
||||
Path languageDir = siteDir.resolve(language).normalize();
|
||||
if (!languageDir.startsWith(root) || !languageDir.getParent().equals(siteDir)) {
|
||||
throw new IOException("index path escapes the index root: " + languageDir);
|
||||
}
|
||||
Files.createDirectories(languageDir);
|
||||
deleteOldLayout(siteDir);
|
||||
return new MMapDirectory(languageDir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a 3.1.x single index left directly under a site's index directory — only files Lucene names
|
||||
* ({@code segments*}, {@code write.lock}, codec files such as {@code _0.cfs}), so an {@code indexRoot} pointed by
|
||||
* mistake at a folder holding other files loses none of them — once per site per process.
|
||||
*/
|
||||
private void deleteOldLayout(Path siteDir) {
|
||||
if (!oldLayoutChecked.add(siteDir)) {
|
||||
return;
|
||||
}
|
||||
try (java.util.stream.Stream<Path> files = Files.list(siteDir)) {
|
||||
files.filter(Files::isRegularFile).filter(f -> isLuceneFile(f.getFileName().toString())).forEach(file -> {
|
||||
try {
|
||||
Files.deleteIfExists(file);
|
||||
} catch (IOException ignored) {
|
||||
// a file that cannot be deleted is harmless: no index reads it any more
|
||||
}
|
||||
});
|
||||
} catch (IOException ignored) {
|
||||
// same: leftovers are never read
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------------- query build
|
||||
|
||||
/**
|
||||
* Composes the tiered constant-score query from the analyzed terms and the site's ranking config. See the
|
||||
* class doc for the tier semantics; the tiers are additive {@code SHOULD} clauses so a document's score is
|
||||
* the sum of the tiers it matches.
|
||||
*/
|
||||
Query buildQuery(List<String> terms, RankingConfig cfg) {
|
||||
BooleanQuery.Builder root = new BooleanQuery.Builder();
|
||||
|
||||
// Tier 1: any-terms (BM25-scored base) — each term across the three fields, with per-field boosts, plus
|
||||
// optional fuzzy variants. This layer separates documents WITHIN the higher constant-score tiers.
|
||||
BooleanQuery.Builder anyTerms = new BooleanQuery.Builder();
|
||||
for (String term : terms) {
|
||||
anyTerms.add(new BoostQuery(new TermQuery(new Term(F_TITLE, term)), cfg.titleBoost()),
|
||||
BooleanClause.Occur.SHOULD);
|
||||
anyTerms.add(new BoostQuery(new TermQuery(new Term(F_DESCRIPTION, term)), cfg.descriptionBoost()),
|
||||
BooleanClause.Occur.SHOULD);
|
||||
anyTerms.add(new TermQuery(new Term(F_BODY, term)), BooleanClause.Occur.SHOULD);
|
||||
if (cfg.fuzzy()) {
|
||||
int edits = maxEdits(term);
|
||||
if (edits > 0) {
|
||||
anyTerms.add(new BoostQuery(fuzzy(F_BODY, term, edits), cfg.fuzzyBoost()),
|
||||
BooleanClause.Occur.SHOULD);
|
||||
anyTerms.add(new BoostQuery(fuzzy(F_TITLE, term, edits), cfg.fuzzyBoost()),
|
||||
BooleanClause.Occur.SHOULD);
|
||||
}
|
||||
}
|
||||
}
|
||||
root.add(anyTerms.build(), BooleanClause.Occur.SHOULD);
|
||||
|
||||
// Tiers 2–4: phrase tiers (only meaningful for a multi-term query; a single term IS its own phrase, so
|
||||
// the phrase tiers would just double-count — skip them for one term).
|
||||
if (terms.size() > 1) {
|
||||
root.add(constant(phrase(F_TITLE, terms, 0), cfg.tierPhraseTitle()), BooleanClause.Occur.SHOULD);
|
||||
root.add(constant(phrase(F_BODY, terms, 0), cfg.tierPhraseBody()), BooleanClause.Occur.SHOULD);
|
||||
root.add(constant(phrase(F_BODY, terms, NEAR_SLOP), cfg.tierNearPhrase()), BooleanClause.Occur.SHOULD);
|
||||
}
|
||||
|
||||
// Tier 5: all-terms-anywhere — every term must appear in some field; a constant lift for complete matches.
|
||||
root.add(constant(allTermsAnywhere(terms), cfg.tierAllTerms()), BooleanClause.Occur.SHOULD);
|
||||
|
||||
return root.build();
|
||||
}
|
||||
|
||||
/** Wraps {@code q} so it contributes a flat, position-independent {@code score} (the tier's constant). */
|
||||
private static Query constant(Query q, float score) {
|
||||
return new BoostQuery(new ConstantScoreQuery(q), score);
|
||||
}
|
||||
|
||||
/** A {@link PhraseQuery} over {@code field} for the ordered {@code terms}, allowing {@code slop} reordering. */
|
||||
private static Query phrase(String field, List<String> terms, int slop) {
|
||||
PhraseQuery.Builder b = new PhraseQuery.Builder().setSlop(slop);
|
||||
for (String term : terms) {
|
||||
b.add(new Term(field, term));
|
||||
}
|
||||
return b.build();
|
||||
}
|
||||
|
||||
/** A {@code MUST}-across-fields query: every term must match in title, description or body (in any position). */
|
||||
private static Query allTermsAnywhere(List<String> terms) {
|
||||
BooleanQuery.Builder all = new BooleanQuery.Builder();
|
||||
for (String term : terms) {
|
||||
BooleanQuery.Builder anyField = new BooleanQuery.Builder();
|
||||
anyField.add(new TermQuery(new Term(F_TITLE, term)), BooleanClause.Occur.SHOULD);
|
||||
anyField.add(new TermQuery(new Term(F_DESCRIPTION, term)), BooleanClause.Occur.SHOULD);
|
||||
anyField.add(new TermQuery(new Term(F_BODY, term)), BooleanClause.Occur.SHOULD);
|
||||
all.add(anyField.build(), BooleanClause.Occur.MUST);
|
||||
}
|
||||
return all.build();
|
||||
}
|
||||
|
||||
/** A typo-tolerant {@link FuzzyQuery}: {@code edits} max, 1-char prefix fixed, 50 expansions, transpositions. */
|
||||
private static FuzzyQuery fuzzy(String field, String term, int edits) {
|
||||
return new FuzzyQuery(new Term(field, term), edits, 1, 50, true);
|
||||
}
|
||||
|
||||
/** The Levenshtein edit budget for a term: none for very short terms, 1 for short, 2 for longer — so a fuzzy
|
||||
* match never turns a 3-letter word into an unrelated one. */
|
||||
static int maxEdits(String term) {
|
||||
int len = term.length();
|
||||
if (len <= 2) {
|
||||
return 0;
|
||||
}
|
||||
return (len <= 5) ? 1 : 2;
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------------- highlighting
|
||||
|
||||
/**
|
||||
* Query-focused highlighting over the stored body field: {@link UnifiedHighlighter} finds the best passage
|
||||
* for each top doc and wraps the matched terms in the private markers (rewritten to {@code <mark>} later).
|
||||
* Returns one snippet per top doc (aligned by index), each possibly {@code null} when the doc has no
|
||||
* highlightable body. Any highlighter failure degrades to an all-{@code null} array — the caller then falls
|
||||
* back to a plain leading snippet, so highlighting never breaks a search.
|
||||
*/
|
||||
private static String[] highlight(IndexSearcher searcher, Analyzer analyzer, Query query, TopDocs top) {
|
||||
if (top.scoreDocs.length == 0) {
|
||||
return new String[0];
|
||||
}
|
||||
try {
|
||||
UnifiedHighlighter highlighter = UnifiedHighlighter.builder(searcher, analyzer)
|
||||
.withFormatter(new DefaultPassageFormatter(MARK_OPEN, MARK_CLOSE, " … ", false))
|
||||
.build();
|
||||
return highlighter.highlight(F_BODY, query, top, 1);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
log.debug("lucene highlighting failed, falling back to plain snippets: {}", e.toString());
|
||||
return new String[top.scoreDocs.length];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The snippet for a hit: prefer the highlighter's query-focused, {@code <mark>}-wrapped passage; if there is
|
||||
* none, fall back to the page description, else a leading slice of the body — always plain (no markers). The
|
||||
* highlighted passage is produced by first HTML-escaping the raw passage, THEN turning the private markers
|
||||
* into real {@code <mark>} tags, so page content can never inject markup while the highlight tags survive.
|
||||
*/
|
||||
private static String snippet(String highlighted, Document doc) {
|
||||
if (highlighted != null && (highlighted.indexOf(MARK_OPEN_CH) >= 0)) {
|
||||
return markup(highlighted);
|
||||
}
|
||||
String description = doc.get(S_DESCRIPTION);
|
||||
String base = (description != null && !description.isBlank()) ? description : doc.get(S_BODY);
|
||||
if (base == null || base.isBlank()) {
|
||||
return "";
|
||||
}
|
||||
base = base.strip();
|
||||
return base.length() <= SNIPPET_MAX ? base : base.substring(0, SNIPPET_MAX).stripTrailing() + "…";
|
||||
}
|
||||
|
||||
/** Escapes the passage's HTML metacharacters, then rewrites the private markers to {@code <mark>} tags. */
|
||||
private static String markup(String passage) {
|
||||
String escaped = passage.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
.replace("\"", """).replace("'", "'");
|
||||
return escaped.replace(MARK_OPEN, "<mark>").replace(MARK_CLOSE, "</mark>").strip();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------------------- shared
|
||||
|
||||
/** Analyzes free text into its terms with {@code analyzer} (same transform used at index time), capped. */
|
||||
private static List<String> analyze(Analyzer analyzer, String text) {
|
||||
List<String> out = new ArrayList<>();
|
||||
try (TokenStream ts = analyzer.tokenStream(F_BODY, text)) {
|
||||
CharTermAttribute term = ts.addAttribute(CharTermAttribute.class);
|
||||
ts.reset();
|
||||
while (ts.incrementToken() && out.size() < MAX_QUERY_TERMS) {
|
||||
out.add(term.toString());
|
||||
}
|
||||
ts.end();
|
||||
} catch (IOException e) {
|
||||
return List.of();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** This plugin's ranking knobs for the site, from its per-site settings (declared defaults applied). */
|
||||
private RankingConfig ranking(String siteId) {
|
||||
return RankingConfig.from(settings.site(siteId).values());
|
||||
}
|
||||
|
||||
/** A map value for {@code locale}'s language, else any present value, else {@code fallback}. */
|
||||
private static String localized(Map<String, String> byLocale, Locale locale, String fallback) {
|
||||
String v = byLocale.get(locale.getLanguage());
|
||||
if (v == null || v.isBlank()) {
|
||||
v = byLocale.values().stream().filter(x -> x != null && !x.isBlank()).findFirst().orElse(null);
|
||||
}
|
||||
return (v == null || v.isBlank()) ? fallback : v;
|
||||
}
|
||||
|
||||
private static String nonNull(String value) {
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
|
||||
private static void closeQuietly(Directory dir) {
|
||||
try {
|
||||
dir.close();
|
||||
} catch (IOException | UncheckedIOException e) {
|
||||
log.debug("failed to close a lucene directory: {}", e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import java.util.Objects;
|
||||
import mx.quest.runway.spi.model.CatalogChange;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
|
||||
/**
|
||||
* The plugin's one {@link SiteEventListener}, a {@link Phase#CONSUMER CONSUMER}: it reads the content listing (through
|
||||
* the search plugin's {@code SearchCorpus}) and contributes none. The kernel delivers it after every kernel cache the
|
||||
* change affects has been evicted and every content source has dropped its own state, so the rebuild it triggers reads
|
||||
* the new state.
|
||||
*
|
||||
* <p>{@link #onCatalogChanged} drops the site's index for <b>every</b> cause — a page write, a content source's change,
|
||||
* a site lifecycle event, and <b>any</b> plugin's settings save: a source reshapes its items from its settings (its
|
||||
* URL prefix, say), and the search plugin's {@code exclude} list reshapes the corpus. No {@code pluginId} scoping is
|
||||
* needed. This plugin's own settings (the ranking knobs) are read per query, so they need nothing here. The callback
|
||||
* only evicts; the rebuild happens lazily on the next query. It runs on every node, for local and replayed changes
|
||||
* alike: it only drops local state.
|
||||
*/
|
||||
final class LuceneSiteEvents implements SiteEventListener {
|
||||
|
||||
private final LuceneSearchEngine engine;
|
||||
|
||||
LuceneSiteEvents(LuceneSearchEngine engine) {
|
||||
this.engine = Objects.requireNonNull(engine, "engine");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Phase phase() {
|
||||
return Phase.CONSUMER;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCatalogChanged(CatalogChange change) {
|
||||
engine.invalidate(change.siteId());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* The plugin's <b>app-level</b> settings — where the index bytes live — bound from
|
||||
* {@code external/plugin-settings/search-lucene.yml} (keys under {@code runway.plugin.search-lucene.*}), the
|
||||
* plugin.yml {@code settings:} schema. Storage is a <b>platform</b> concern, not a tenant one: a filesystem path
|
||||
* a tenant could edit would be an isolation/abuse risk, so it is app-level and applied on <b>restart</b> (a
|
||||
* plugin reads its app-level settings through its own {@code @ConfigurationProperties}, never host machinery). The
|
||||
* binding is declared on the {@code @Bean} method ({@code searchLuceneStorageProps} in {@link SearchLuceneConfig}), so
|
||||
* the bean carries the plugin-id prefix every plugin bean name needs.
|
||||
*
|
||||
* <p>Field defaults mirror the schema defaults, so the plugin behaves sensibly (heap storage) when the file is
|
||||
* absent — degrade-don't-crash.
|
||||
*
|
||||
* @see Storage the two storage modes and their trade-offs
|
||||
*/
|
||||
public class LuceneStorageProps {
|
||||
|
||||
/**
|
||||
* Where a per-site Lucene index is held.
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@link #HEAP} — an in-memory {@code ByteBuffersDirectory}: no disk footprint, but the index is
|
||||
* rebuilt from the page store after every restart. The default; ideal for small/medium sites.</li>
|
||||
* <li>{@link #DISK} — a memory-mapped {@code MMapDirectory} under {@link #getIndexRoot()}{@code /<siteId>}:
|
||||
* survives restarts and lets the OS page large indexes in/out of memory. Choose for large corpora.</li>
|
||||
* </ul>
|
||||
*/
|
||||
public enum Storage { HEAP, DISK }
|
||||
|
||||
private Storage storage = Storage.HEAP;
|
||||
private String indexRoot = "./external/plugins/search-lucene/index";
|
||||
|
||||
/** The configured storage mode; never {@code null} (defaults to {@link Storage#HEAP}). */
|
||||
public Storage getStorage() {
|
||||
return storage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Binds the {@code storage} setting. Tolerant of case and blanks: an unrecognized or blank value falls back
|
||||
* to {@link Storage#HEAP} rather than failing the context (degrade-don't-crash for a hand-edited file).
|
||||
*/
|
||||
public void setStorage(String storage) {
|
||||
if (storage == null || storage.isBlank()) {
|
||||
this.storage = Storage.HEAP;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
this.storage = Storage.valueOf(storage.trim().toUpperCase(Locale.ROOT));
|
||||
} catch (IllegalArgumentException ex) {
|
||||
this.storage = Storage.HEAP;
|
||||
}
|
||||
}
|
||||
|
||||
/** The root folder for disk indexes (per-site subfolders are created under it); never blank. */
|
||||
public String getIndexRoot() {
|
||||
return indexRoot;
|
||||
}
|
||||
|
||||
/** Binds the {@code indexRoot} setting; a blank value restores the default so the path is never empty. */
|
||||
public void setIndexRoot(String indexRoot) {
|
||||
this.indexRoot = (indexRoot == null || indexRoot.isBlank())
|
||||
? "./external/plugins/search-lucene/index" : indexRoot.trim();
|
||||
}
|
||||
|
||||
/** Whether disk (MMap) storage is selected. */
|
||||
public boolean isDisk() {
|
||||
return storage == Storage.DISK;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import mx.quest.search.spi.SearchHit;
|
||||
import org.apache.lucene.analysis.Analyzer;
|
||||
import org.apache.lucene.analysis.TokenStream;
|
||||
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
|
||||
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
|
||||
import org.apache.lucene.search.FuzzyQuery;
|
||||
import org.apache.lucene.util.automaton.ByteRunnable;
|
||||
import org.apache.lucene.util.automaton.CompiledAutomaton;
|
||||
|
||||
/**
|
||||
* The words a query matched in one document, as they are written there, for {@link SearchHit#terms()}: the page a
|
||||
* result opens highlights these, so they must be the <em>surface</em> forms, not the analyzed terms. The query
|
||||
* {@code maestría} is the term {@code maestr} after Spanish stemming; the page says {@code maestrías}, and that is
|
||||
* the word to highlight.
|
||||
*
|
||||
* <p>Each stored text (title, description, body) is run through the same analyzer as the index, and a token whose
|
||||
* term is a query term is kept with the characters its offsets point at. When the site has typo tolerance on, a
|
||||
* token within the query's fuzzy edit distance of a term counts too, by the same rule as the fuzzy clauses
|
||||
* ({@link LuceneSearchEngine#maxEdits}, a one-character fixed prefix, transpositions). The fuzzy clauses expand to at
|
||||
* most 50 index terms, so on a large site a word within the distance may be highlighted although it did not add to
|
||||
* the score; it is still a word the query nearly spelled.
|
||||
*
|
||||
* <p>Bounded: at most {@link SearchHit#MAX_TERMS} forms, and only the first {@value #MAX_SCAN_CHARS} characters of
|
||||
* a text are read, so a very long page costs a fixed amount per hit. Any analysis failure returns what was found.
|
||||
*/
|
||||
final class MatchedForms {
|
||||
|
||||
/** Characters of one text read per hit; the forms of a real page appear well before this. */
|
||||
static final int MAX_SCAN_CHARS = 64 * 1024;
|
||||
|
||||
private final Analyzer analyzer;
|
||||
private final Set<String> exact;
|
||||
private final List<ByteRunnable> near;
|
||||
|
||||
private MatchedForms(Analyzer analyzer, List<String> terms, boolean fuzzy) {
|
||||
this.analyzer = analyzer;
|
||||
this.exact = new HashSet<>(terms);
|
||||
this.near = fuzzy ? automata(terms) : List.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* The matcher for one query, built once and used for every hit: the fuzzy automata cost about half a millisecond
|
||||
* per term to build, so building them per hit made a long query over many hits cost seconds of CPU.
|
||||
*
|
||||
* @param analyzer the analyzer the index was built with
|
||||
* @param terms the analyzed query terms
|
||||
* @param fuzzy whether the site's ranking adds fuzzy clauses
|
||||
*/
|
||||
static MatchedForms forQuery(Analyzer analyzer, List<String> terms, boolean fuzzy) {
|
||||
return new MatchedForms(analyzer, terms, fuzzy);
|
||||
}
|
||||
|
||||
/** The forms found in one hit's stored texts, the most visible first (title, description, body). */
|
||||
List<String> in(List<String> texts) {
|
||||
Set<String> forms = new LinkedHashSet<>();
|
||||
for (String text : texts) {
|
||||
if (text == null || text.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
collect(analyzer, text.length() > MAX_SCAN_CHARS ? text.substring(0, MAX_SCAN_CHARS) : text,
|
||||
exact, near, forms);
|
||||
if (forms.size() >= SearchHit.MAX_TERMS) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return List.copyOf(forms);
|
||||
}
|
||||
|
||||
private static List<ByteRunnable> automata(List<String> terms) {
|
||||
List<ByteRunnable> out = new ArrayList<>();
|
||||
for (String term : terms) {
|
||||
int edits = LuceneSearchEngine.maxEdits(term);
|
||||
if (edits > 0) {
|
||||
CompiledAutomaton automaton = FuzzyQuery.getFuzzyAutomaton(term, edits, 1, true);
|
||||
ByteRunnable runnable = automaton.getByteRunnable();
|
||||
if (runnable != null) {
|
||||
out.add(runnable);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static void collect(Analyzer analyzer, String text, Set<String> exact, List<ByteRunnable> near,
|
||||
Set<String> forms) {
|
||||
try (TokenStream ts = analyzer.tokenStream("body", text)) {
|
||||
CharTermAttribute term = ts.addAttribute(CharTermAttribute.class);
|
||||
OffsetAttribute offset = ts.addAttribute(OffsetAttribute.class);
|
||||
ts.reset();
|
||||
while (ts.incrementToken() && forms.size() < SearchHit.MAX_TERMS) {
|
||||
String t = term.toString();
|
||||
if (exact.contains(t) || accepted(near, t)) {
|
||||
int start = offset.startOffset();
|
||||
int end = offset.endOffset();
|
||||
if (start >= 0 && end <= text.length() && start < end) {
|
||||
forms.add(text.substring(start, end).toLowerCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
}
|
||||
ts.end();
|
||||
} catch (IOException | RuntimeException e) {
|
||||
// Highlighting is a convenience: keep what was found rather than fail the search.
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean accepted(List<ByteRunnable> near, String term) {
|
||||
if (near.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
byte[] bytes = term.getBytes(StandardCharsets.UTF_8);
|
||||
for (ByteRunnable automaton : near) {
|
||||
if (automaton.run(bytes, 0, bytes.length)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The per-tenant ranking tuning for one site, resolved from the plugin's per-site settings
|
||||
* ({@code sites/<id>/plugins/search-lucene.yml}, read live per query through the SPI's {@code PluginSettings}, which
|
||||
* applies the descriptor's declared defaults under the stored values). It
|
||||
* carries the ~8 knobs the {@code siteSettings:} schema exposes; each is read defensively (a missing, blank, or
|
||||
* malformed value falls back to the historical default, and every value is clamped to a sane range) so a
|
||||
* hand-edited or partial file can never produce a broken query — <b>degrade-don't-crash</b>.
|
||||
*
|
||||
* <p>All values are resolved <b>once per query</b> in {@link #from(Map)} and then used as plain immutable data by
|
||||
* the query builder — the config map is never touched during query construction.
|
||||
*
|
||||
* @param fuzzy whether typo-tolerant {@code FuzzyQuery} clauses are added (default {@code true})
|
||||
* @param fuzzyBoost weight of a fuzzy term match relative to an exact one (default {@code 0.4})
|
||||
* @param titleBoost term-match boost on the title field in the any-terms tier (default {@code 8.0})
|
||||
* @param descriptionBoost term-match boost on the description field in the any-terms tier (default {@code 4.0})
|
||||
* @param tierPhraseTitle constant score for an exact query phrase found in the title (default {@code 4000})
|
||||
* @param tierPhraseBody constant score for an exact query phrase found in the body (default {@code 2000})
|
||||
* @param tierNearPhrase constant score for a near (slop=1) query phrase in the body (default {@code 800})
|
||||
* @param tierAllTerms constant score for a document containing all query terms anywhere (default {@code 300})
|
||||
*/
|
||||
record RankingConfig(boolean fuzzy, float fuzzyBoost, float titleBoost, float descriptionBoost,
|
||||
float tierPhraseTitle, float tierPhraseBody, float tierNearPhrase, float tierAllTerms) {
|
||||
|
||||
static final boolean DEF_FUZZY = true;
|
||||
static final float DEF_FUZZY_BOOST = 0.4f;
|
||||
static final float DEF_TITLE_BOOST = 8.0f;
|
||||
static final float DEF_DESCRIPTION_BOOST = 4.0f;
|
||||
static final float DEF_TIER_PHRASE_TITLE = 4000f;
|
||||
static final float DEF_TIER_PHRASE_BODY = 2000f;
|
||||
static final float DEF_TIER_NEAR_PHRASE = 800f;
|
||||
static final float DEF_TIER_ALL_TERMS = 300f;
|
||||
|
||||
/** Upper bound applied to every boost/tier score — generous, but stops a fat-fingered value from overflowing
|
||||
* the score math or drowning every other signal. */
|
||||
private static final float MAX = 1_000_000f;
|
||||
|
||||
/** The historical defaults — used when a site has no per-tenant config at all (or an empty map). */
|
||||
static RankingConfig defaults() {
|
||||
return from(Map.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the ranking config from a site's plugin config map. Each knob is read with
|
||||
* {@link #decimal}/{@link #flag}, which coerce {@link Number}/{@link String} values, ignore blanks and
|
||||
* garbage, and fall back to the default; boosts and tier scores are clamped to {@code [0, MAX]}.
|
||||
*
|
||||
* @param cfg the effective per-tenant values ({@code SettingsView.values()}; may be empty; never {@code null})
|
||||
*/
|
||||
static RankingConfig from(Map<String, Object> cfg) {
|
||||
return new RankingConfig(
|
||||
flag(cfg, "fuzzy", DEF_FUZZY),
|
||||
decimal(cfg, "fuzzyBoost", DEF_FUZZY_BOOST),
|
||||
decimal(cfg, "titleBoost", DEF_TITLE_BOOST),
|
||||
decimal(cfg, "descriptionBoost", DEF_DESCRIPTION_BOOST),
|
||||
decimal(cfg, "tierPhraseTitle", DEF_TIER_PHRASE_TITLE),
|
||||
decimal(cfg, "tierPhraseBody", DEF_TIER_PHRASE_BODY),
|
||||
decimal(cfg, "tierNearPhrase", DEF_TIER_NEAR_PHRASE),
|
||||
decimal(cfg, "tierAllTerms", DEF_TIER_ALL_TERMS));
|
||||
}
|
||||
|
||||
/** Reads a non-negative decimal knob, clamped to {@code [0, MAX]}; missing/blank/garbage ⇒ {@code def}. */
|
||||
private static float decimal(Map<String, Object> cfg, String key, float def) {
|
||||
Object v = cfg.get(key);
|
||||
float raw;
|
||||
if (v instanceof Number n) {
|
||||
raw = n.floatValue();
|
||||
} else if (v instanceof String s && !s.isBlank()) {
|
||||
try {
|
||||
raw = Float.parseFloat(s.trim());
|
||||
} catch (NumberFormatException ex) {
|
||||
return def;
|
||||
}
|
||||
} else {
|
||||
return def;
|
||||
}
|
||||
if (Float.isNaN(raw) || Float.isInfinite(raw)) {
|
||||
return def;
|
||||
}
|
||||
return Math.max(0f, Math.min(MAX, raw));
|
||||
}
|
||||
|
||||
/** Reads a boolean knob; accepts {@link Boolean} and the strings true/on/yes/1 (case-insensitive). */
|
||||
private static boolean flag(Map<String, Object> cfg, String key, boolean def) {
|
||||
Object v = cfg.get(key);
|
||||
if (v instanceof Boolean b) {
|
||||
return b;
|
||||
}
|
||||
if (v instanceof String s && !s.isBlank()) {
|
||||
String t = s.trim().toLowerCase(java.util.Locale.ROOT);
|
||||
return t.equals("true") || t.equals("on") || t.equals("yes") || t.equals("1");
|
||||
}
|
||||
return def;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
import mx.quest.runway.spi.service.Sites;
|
||||
import mx.quest.search.spi.SearchCorpus;
|
||||
import mx.quest.search.spi.SiteSearchEngine;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* The plugin's {@code mainClass} — the single {@code @Configuration} the host registers into its context before
|
||||
* refresh. Every bean is wired EXPLICITLY (no {@code @ComponentScan}); the package {@code mx.quest.searchlucene} lives
|
||||
* OUTSIDE {@code mx.quest.runway} so the host never double-scans it.
|
||||
*
|
||||
* <p><b>SPI only.</b> Everything this plugin needs arrives as a published service: {@link PluginSettings} (this
|
||||
* plugin's per-site ranking knobs, bound to this plugin by the jar this class was loaded from) and {@link Sites} (a
|
||||
* site's default locale) from the kernel's SPI 0.6.0, and {@link SearchCorpus} (what to index — the content listing
|
||||
* minus the site's search exclusions) from the {@code search} plugin's own SPI (search 2.0.0). Nothing outside
|
||||
* {@code mx.quest.runway.spi} and {@code mx.quest.search.spi} is linked. Every bean name starts with the plugin id in
|
||||
* lowerCamelCase ({@code searchLucene…}), the kernel's rule for the bean namespace plugins share.
|
||||
*
|
||||
* <p>{@code requires: search >= 2.0.0} and {@code requires: lucene-provider == 10.4.0} in {@code plugin.yml} are HARD
|
||||
* gates: without the search plugin (which publishes {@link SiteSearchEngine} and {@link SearchCorpus}) or the
|
||||
* provider (which supplies the exact Lucene binaries) this plugin is not loaded — so both are present at wire time.
|
||||
*
|
||||
* <p>App-level storage settings bind from {@code external/plugin-settings/search-lucene.yml} into
|
||||
* {@link LuceneStorageProps} through the {@code @ConfigurationProperties} on {@link #searchLuceneStorageProps()} —
|
||||
* not {@code @EnableConfigurationProperties}, which would name the bean {@code runway.plugin.search-lucene-…} and break
|
||||
* the bean-name rule.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class SearchLuceneConfig {
|
||||
|
||||
/** The app-level settings ({@code runway.plugin.search-lucene.*}: storage, indexRoot), applied on restart. */
|
||||
@Bean
|
||||
@ConfigurationProperties(prefix = "runway.plugin.search-lucene")
|
||||
public LuceneStorageProps searchLuceneStorageProps() {
|
||||
return new LuceneStorageProps();
|
||||
}
|
||||
|
||||
/**
|
||||
* The engine, registered as its concrete type — which IS-A {@link SiteSearchEngine}, so the search plugin's
|
||||
* {@code List<SiteSearchEngine>} collects it (one definition, no duplicate; NEVER {@code @Primary}), while the
|
||||
* admin model and the listener inject the concrete type. Spring closes the engine's cached Lucene directories on
|
||||
* shutdown through {@code destroyMethod}.
|
||||
*/
|
||||
@Bean(destroyMethod = "close")
|
||||
public LuceneSearchEngine searchLuceneEngine(SearchCorpus corpus, Sites sites, PluginSettings settings,
|
||||
LuceneStorageProps storage) {
|
||||
return new LuceneSearchEngine(corpus, sites, settings, storage);
|
||||
}
|
||||
|
||||
/** Drops a site's index on every change that may reshape what it holds (a CONSUMER listener). */
|
||||
@Bean
|
||||
public SiteEventListener searchLuceneSiteEvents(LuceneSearchEngine engine) {
|
||||
return new LuceneSiteEvents(engine);
|
||||
}
|
||||
|
||||
/** Read-only status for the dashboard card and the admin fragment ({@code @searchLuceneAdminModel}). */
|
||||
@Bean
|
||||
public LuceneAdminModel searchLuceneAdminModel(LuceneSearchEngine engine) {
|
||||
return new LuceneAdminModel(engine);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.LocalizedUrl;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.testkit.FakeContentCatalog;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import mx.quest.search.SiteSearchCorpus;
|
||||
import mx.quest.search.spi.SearchCorpus;
|
||||
import mx.quest.search.spi.SearchHit;
|
||||
import mx.quest.search.spi.SearchQuery;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* One index per language (3.2.0): each item is indexed in every language it exists in, with that language's
|
||||
* analyzer, and a query searches its own language's index — plus the primary-locale document of an item missing
|
||||
* from that language. The corpus answers each language's own body, as the kernel does since 1.0.0-rc6 (a page's
|
||||
* copy comes from the site's bundles in the requested language).
|
||||
*/
|
||||
class LucenePerLanguageTest {
|
||||
|
||||
private static final String SITE = "acme";
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final Locale ES = Locale.of("es");
|
||||
private static final Locale FR = Locale.FRENCH;
|
||||
|
||||
private FakeContentCatalog catalog;
|
||||
private FakePluginSettings searchSettings;
|
||||
private FakeSiteServices sites;
|
||||
private LuceneStorageProps storage;
|
||||
private LuceneSearchEngine engine;
|
||||
private Map<String, Map<String, String>> bodies = Map.of();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
catalog = new FakeContentCatalog().site(SITE);
|
||||
searchSettings = new FakePluginSettings();
|
||||
sites = new FakeSiteServices().site(new SiteView(SITE, "Acme", EN, List.of(EN, ES, FR), null));
|
||||
storage = new LuceneStorageProps();
|
||||
newEngine();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
engine.close();
|
||||
}
|
||||
|
||||
private void newEngine() {
|
||||
if (engine != null) {
|
||||
engine.close();
|
||||
}
|
||||
SearchCorpus base = new SiteSearchCorpus(catalog, searchSettings);
|
||||
SearchCorpus perLanguage = new SearchCorpus() {
|
||||
@Override
|
||||
public List<CatalogEntry> corpus(String siteId) {
|
||||
return base.corpus(siteId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String indexableText(String siteId, CatalogEntry entry, Locale locale) {
|
||||
return bodies.getOrDefault(entry.ref().id(), Map.of()).getOrDefault(locale.getLanguage(), "");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void refresh(String siteId) {
|
||||
base.refresh(siteId);
|
||||
}
|
||||
};
|
||||
engine = new LuceneSearchEngine(perLanguage, sites, new FakePluginSettings(), storage);
|
||||
}
|
||||
|
||||
private static CatalogEntry about() {
|
||||
ContentRef ref = new ContentRef("about", "/about", Map.of("es", "/acerca", "fr", "/a-propos"),
|
||||
List.of(EN, ES, FR), Map.of("en", "About", "es", "Acerca", "fr", "À propos"), Map.of(), "", "tpl",
|
||||
true, Instant.EPOCH, false, null, null, Map.of());
|
||||
return new CatalogEntry("pages", ref, List.of(new LocalizedUrl(EN, "/about", null),
|
||||
new LocalizedUrl(ES, "/es/acerca", null), new LocalizedUrl(FR, "/fr/a-propos", null)), "/about");
|
||||
}
|
||||
|
||||
private static CatalogEntry englishOnly() {
|
||||
ContentRef ref = new ContentRef("news", "/news", Map.of(), List.of(EN), Map.of("en", "News"), Map.of(), "",
|
||||
"tpl", true, Instant.EPOCH, false, null, null, Map.of());
|
||||
return new CatalogEntry("pages", ref, List.of(new LocalizedUrl(EN, "/news", null)), "/news");
|
||||
}
|
||||
|
||||
private void corpus(CatalogEntry... entries) {
|
||||
catalog.clear(SITE);
|
||||
for (CatalogEntry e : entries) {
|
||||
catalog.entry(SITE, e);
|
||||
}
|
||||
}
|
||||
|
||||
private List<SearchHit> search(String q, Locale locale) {
|
||||
return engine.search(new SearchQuery(SITE, q, locale, 20));
|
||||
}
|
||||
|
||||
private void trilingualAbout() {
|
||||
bodies = Map.of("about", Map.of(
|
||||
"en", "<p>A roastery that stays up late, roasting every night.</p>",
|
||||
"es", "<p>Una tostaduría que trasnocha. Nuestros alumnos aprenden con una facultad de excelencia.</p>",
|
||||
"fr", "<p>Une torréfaction nocturne.</p>"));
|
||||
corpus(about());
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachLanguageSearchesItsOwnIndexAtItsOwnAddress() {
|
||||
trilingualAbout();
|
||||
List<SearchHit> es = search("trasnocha", ES);
|
||||
assertEquals(1, es.size(), "the Spanish text is searchable from a Spanish results page");
|
||||
assertEquals("/es/acerca", es.get(0).url());
|
||||
assertEquals("Acerca", es.get(0).title());
|
||||
assertTrue(es.get(0).snippet().contains("<mark>"), es.get(0).snippet());
|
||||
|
||||
assertTrue(search("trasnocha", EN).isEmpty(), "English searches the English index only");
|
||||
assertTrue(search("roastery", ES).isEmpty(), "Spanish searches the Spanish index only");
|
||||
assertEquals("/about", search("roastery", EN).get(0).url());
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachIndexUsesItsLanguagesAnalyzer() {
|
||||
trilingualAbout();
|
||||
// French light stemming folds the accent: an unaccented query finds the accented word.
|
||||
List<SearchHit> fr = search("torrefaction", FR);
|
||||
assertEquals(1, fr.size(), "the French analyzer matches 'torrefaction' to 'torréfaction'");
|
||||
assertEquals("/fr/a-propos", fr.get(0).url());
|
||||
// Spanish stemming: an inflected form finds the page.
|
||||
assertEquals(1, search("facultades", ES).size(), "the Spanish analyzer stems 'facultades' to 'facultad'");
|
||||
assertEquals(1, search("roasted", EN).size(), "the English analyzer stems 'roasted' to 'roast'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theMatchedFormsAreTheTargetLanguagesWords() {
|
||||
trilingualAbout();
|
||||
List<SearchHit> hits = search("facultades", ES);
|
||||
assertEquals(1, hits.size());
|
||||
assertTrue(hits.get(0).terms().contains("facultad"), () -> "terms: " + hits.get(0).terms());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anItemMissingFromTheQueryLanguageIsFoundInItsPrimaryLanguage() {
|
||||
bodies = Map.of("about", Map.of("es", "<p>tostaduría</p>"), "news", Map.of("en", "<p>harvest report</p>"));
|
||||
corpus(about(), englishOnly());
|
||||
List<SearchHit> hits = search("harvest", ES);
|
||||
assertEquals(1, hits.size(), "a page the site publishes in English only is still found from Spanish");
|
||||
assertEquals("/news", hits.get(0).url());
|
||||
assertEquals(1, search("tostaduría", ES).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLanguageTheSiteDoesNotSpeakSearchesTheDefaultLanguage() {
|
||||
trilingualAbout();
|
||||
List<SearchHit> hits = search("roastery", Locale.GERMAN);
|
||||
assertEquals(1, hits.size());
|
||||
assertEquals("/about", hits.get(0).url());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theConsoleCountsItemsNotLanguages() {
|
||||
trilingualAbout();
|
||||
corpus(about(), englishOnly());
|
||||
assertEquals(2, engine.indexedDocuments(SITE));
|
||||
assertEquals(2, engine.reindex(SITE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void onDiskEachLanguageHasItsOwnFolderAndTheOldSingleIndexIsRemoved(@TempDir Path tmp) throws IOException {
|
||||
Path siteDir = tmp.resolve(SITE);
|
||||
Files.createDirectories(siteDir);
|
||||
Files.writeString(siteDir.resolve("segments_1"), "a 3.1.x index file"); // the old one-index-per-site layout
|
||||
Files.writeString(siteDir.resolve("_0.cfs"), "a 3.1.x codec file");
|
||||
Files.writeString(siteDir.resolve("notes.txt"), "not Lucene's"); // indexRoot pointed at the wrong folder
|
||||
storage.setStorage("disk");
|
||||
storage.setIndexRoot(tmp.toString());
|
||||
newEngine();
|
||||
trilingualAbout();
|
||||
|
||||
assertEquals("/es/acerca", search("trasnocha", ES).get(0).url());
|
||||
for (String language : List.of("en", "es", "fr")) {
|
||||
assertTrue(Files.isDirectory(siteDir.resolve(language)), "a folder for " + language);
|
||||
}
|
||||
assertFalse(Files.exists(siteDir.resolve("segments_1")), "the 3.1.x index file is deleted");
|
||||
assertFalse(Files.exists(siteDir.resolve("_0.cfs")), "…and its codec files");
|
||||
assertTrue(Files.exists(siteDir.resolve("notes.txt")), "a file Lucene did not name is never deleted");
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyLuceneFileNamesCountAsAnOldIndex() {
|
||||
for (String name : List.of("segments_1", "segments_a", "segments.gen", "write.lock", "_0.cfs", "_0.si",
|
||||
"_1_Lucene90_0.dvd")) {
|
||||
assertTrue(LuceneSearchEngine.isLuceneFile(name), name);
|
||||
}
|
||||
for (String name : List.of("site.yml", "notes.txt", "messages.properties", "index.html")) {
|
||||
assertFalse(LuceneSearchEngine.isLuceneFile(name), name);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSearchFromInsideTheSitesOwnIndexBuildAnswersNothingInsteadOfRecursing() {
|
||||
bodies = Map.of();
|
||||
corpus(about());
|
||||
engine.close();
|
||||
SearchCorpus base = new SiteSearchCorpus(catalog, searchSettings);
|
||||
LuceneSearchEngine[] self = new LuceneSearchEngine[1];
|
||||
java.util.concurrent.atomic.AtomicInteger inner = new java.util.concurrent.atomic.AtomicInteger(-1);
|
||||
SearchCorpus reentrant = new SearchCorpus() { // a page whose widget searches while it is being rendered
|
||||
@Override
|
||||
public List<CatalogEntry> corpus(String siteId) {
|
||||
return base.corpus(siteId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String indexableText(String siteId, CatalogEntry entry, Locale locale) {
|
||||
inner.set(self[0].search(new SearchQuery(SITE, "roastery", locale, 5)).size());
|
||||
return "<p>roastery</p>";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void refresh(String siteId) {
|
||||
base.refresh(siteId);
|
||||
}
|
||||
};
|
||||
engine = new LuceneSearchEngine(reentrant, sites, new FakePluginSettings(), storage);
|
||||
self[0] = engine;
|
||||
assertEquals(1, search("roastery", EN).size(), "the outer search is answered");
|
||||
assertEquals(0, inner.get(), "the search from inside the build answered nothing (and did not recurse)");
|
||||
}
|
||||
}
|
||||
+668
@@ -0,0 +1,668 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import mx.quest.runway.spi.model.CatalogChange;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.LocalizedUrl;
|
||||
import mx.quest.runway.spi.model.SiteLifecycleEvent;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.testkit.EventDispatch;
|
||||
import mx.quest.runway.spi.testkit.FakeContentCatalog;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import mx.quest.search.SiteSearchCorpus;
|
||||
import mx.quest.search.spi.SearchCorpus;
|
||||
import mx.quest.search.spi.SearchHit;
|
||||
import mx.quest.search.spi.SearchQuery;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* The Lucene engine: tiered constant-score ranking (exact phrase > near > scattered), fuzzy matching,
|
||||
* per-locale stemming analyzers, heap and disk storage, {@code <mark>} highlighting, the 8 per-tenant tuning knobs
|
||||
* (read per query through {@code PluginSettings}), the index's freshness (the plugin's {@code SiteEventListener}, the
|
||||
* reindex hook) and the {@code SiteSearchEngine} SPI contract (never throws, empty index ⇒ no results, limit honored).
|
||||
*
|
||||
* <p>The corpus is the search plugin's own {@link SiteSearchCorpus} (search 2.0.0) over the testkit's
|
||||
* {@link FakeContentCatalog}, with the search plugin's settings in a second {@link FakePluginSettings} — so the
|
||||
* exclusion rule exercised here is the one the search plugin applies on a real deployment, not a copy of it.
|
||||
*/
|
||||
class LuceneSearchEngineTest {
|
||||
|
||||
private static final String SITE = "acme";
|
||||
|
||||
private FakeContentCatalog catalog;
|
||||
private FakePluginSettings searchSettings;
|
||||
private FakePluginSettings luceneSettings;
|
||||
private FakeSiteServices sites;
|
||||
private SearchCorpus corpus;
|
||||
private LuceneStorageProps storage;
|
||||
private LuceneSearchEngine engine;
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ fixtures
|
||||
|
||||
/** A published English page (source {@code pages}, id = slug) at {@code /<id>}. */
|
||||
static CatalogEntry item(String id, String title, String description) {
|
||||
return item("pages", id, "en", title, description);
|
||||
}
|
||||
|
||||
/** A published item of {@code source}, available in {@code lang} only, at {@code /<id>}. */
|
||||
static CatalogEntry item(String source, String id, String lang, String title, String description) {
|
||||
Locale locale = Locale.forLanguageTag(lang);
|
||||
ContentRef ref = new ContentRef(id, "/" + id, Map.of(), List.of(locale), Map.of(lang, title),
|
||||
Map.of(lang, description), "", "tpl", true, Instant.EPOCH, false, null, null, Map.of());
|
||||
return new CatalogEntry(source, ref, List.of(new LocalizedUrl(locale, "/" + id, null)), null);
|
||||
}
|
||||
|
||||
private void site(String id, Locale defaultLocale) {
|
||||
sites.site(new SiteView(id, id, defaultLocale, List.of(defaultLocale), null));
|
||||
catalog.site(id);
|
||||
}
|
||||
|
||||
/** Replaces the site's listing. */
|
||||
private void corpus(String siteId, CatalogEntry... items) {
|
||||
catalog.clear(siteId);
|
||||
for (CatalogEntry item : items) {
|
||||
catalog.entry(siteId, item);
|
||||
}
|
||||
}
|
||||
|
||||
private void corpus(CatalogEntry... items) {
|
||||
corpus(SITE, items);
|
||||
}
|
||||
|
||||
/** The item's raw indexable material — what the catalog's {@code indexableText} answers for it. */
|
||||
private void body(CatalogEntry item, String html) {
|
||||
catalog.text(SITE, item.compositeId(), html);
|
||||
}
|
||||
|
||||
private void newEngine() {
|
||||
if (engine != null) {
|
||||
engine.close();
|
||||
}
|
||||
engine = new LuceneSearchEngine(corpus, sites, luceneSettings, storage);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
catalog = new FakeContentCatalog();
|
||||
searchSettings = new FakePluginSettings();
|
||||
luceneSettings = new FakePluginSettings();
|
||||
sites = new FakeSiteServices();
|
||||
corpus = new SiteSearchCorpus(catalog, searchSettings);
|
||||
storage = new LuceneStorageProps(); // heap by default
|
||||
site(SITE, Locale.ENGLISH);
|
||||
newEngine();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
engine.close();
|
||||
}
|
||||
|
||||
private List<SearchHit> search(String q, int limit) {
|
||||
return engine.search(new SearchQuery(SITE, q, Locale.ENGLISH, limit));
|
||||
}
|
||||
|
||||
private static List<String> urls(List<SearchHit> hits) {
|
||||
return hits.stream().map(SearchHit::url).toList();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------ SPI contract
|
||||
|
||||
@Test
|
||||
void keyPriorityAndAvailability() {
|
||||
assertEquals("search/lucene", engine.key());
|
||||
assertEquals(100, engine.priority(), "outranks the built-in engine");
|
||||
assertTrue(engine.available(SITE), "always available — builds on demand");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyIndexReturnsNoResultsAndNeverThrows() {
|
||||
assertTrue(search("anything", 20).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCorpusFailureDegradesToNoResultsRatherThanThrowing() {
|
||||
// The corpus blowing up must not propagate out of search() — the SPI never throws for a query.
|
||||
SearchCorpus failing = new SearchCorpus() {
|
||||
@Override
|
||||
public List<CatalogEntry> corpus(String siteId) {
|
||||
throw new IllegalStateException("catalog down");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String indexableText(String siteId, CatalogEntry entry, Locale locale) {
|
||||
throw new IllegalStateException("catalog down");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void refresh(String siteId) {
|
||||
throw new IllegalStateException("catalog down");
|
||||
}
|
||||
};
|
||||
try (LuceneSearchEngine broken = new LuceneSearchEngine(failing, sites, luceneSettings, storage)) {
|
||||
assertTrue(broken.search(new SearchQuery(SITE, "runway", Locale.ENGLISH, 20)).isEmpty(),
|
||||
"a failure returns no results, not an exception");
|
||||
assertEquals(0, broken.indexedDocuments(SITE));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnsafeOrUnknownSiteAnswersNothingAndNeverThrows() {
|
||||
corpus(item("guide", "Runway Guide", ""));
|
||||
assertTrue(engine.search(new SearchQuery("../etc", "runway", Locale.ENGLISH, 20)).isEmpty(),
|
||||
"an unsafe site id is refused by the services; the engine answers no results");
|
||||
assertEquals(0, engine.indexedDocuments("../etc"));
|
||||
assertTrue(engine.search(new SearchQuery("ghost", "runway", Locale.ENGLISH, 20)).isEmpty(),
|
||||
"an unknown site has an empty index");
|
||||
assertEquals(0, engine.reindex("ghost"));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------- matched words (since 3.1.0)
|
||||
|
||||
@Test
|
||||
void aHitCarriesTheSurfaceFormsTheStemmedQueryMatched() {
|
||||
site("es-site", Locale.forLanguageTag("es"));
|
||||
CatalogEntry mba = item("pages", "mba", "es", "Maestrías ejecutivas", "");
|
||||
corpus("es-site", mba, item("pages", "otra", "es", "Contacto", ""));
|
||||
catalog.text("es-site", mba.compositeId(), "<p>Nuestra maestría dura dos años.</p>");
|
||||
List<SearchHit> hits = engine.search(new SearchQuery("es-site", "maestría", Locale.forLanguageTag("es"), 10));
|
||||
assertEquals(List.of("/mba"), urls(hits));
|
||||
assertEquals(List.of("maestrías", "maestría"), hits.get(0).terms(),
|
||||
"the words as the page writes them, title first, so the target page can highlight them");
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopWordsOfTheQueryAreNotReported() {
|
||||
CatalogEntry guide = item("guide", "The Guide", "");
|
||||
corpus(guide);
|
||||
body(guide, "<p>The art of the deployment.</p>");
|
||||
List<SearchHit> hits = search("the deployment", 10);
|
||||
assertEquals(List.of("deployment"), hits.get(0).terms(), "'the' is a stop word: it matched nothing");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTypoToleratedMatchReportsTheWordItFound() {
|
||||
CatalogEntry guide = item("guide", "Guide", "");
|
||||
corpus(guide);
|
||||
body(guide, "<p>A small framework.</p>");
|
||||
List<SearchHit> hits = search("framewrok", 10);
|
||||
assertEquals(List.of("/guide"), urls(hits), "fuzzy matching is on by default");
|
||||
assertEquals(List.of("framework"), hits.get(0).terms(), "the page's own spelling is the word to highlight");
|
||||
}
|
||||
|
||||
@Test
|
||||
void typoToleranceDecidesWhetherNearTermsAreReported() {
|
||||
CatalogEntry guide = item("guide", "Guide", "");
|
||||
corpus(guide);
|
||||
body(guide, "<p>Deploy the deployment; deployer.</p>");
|
||||
// English stemming: deployment and deployer are "deploy", while deploy itself is "deploi", one edit away.
|
||||
assertEquals(List.of("deploy", "deployment", "deployer"), search("deployment", 10).get(0).terms(),
|
||||
"fuzzy on (the default): the near term is a match, so its word is reported");
|
||||
luceneSettings.site(SITE, Map.of("fuzzy", false));
|
||||
assertEquals(List.of("deployment", "deployer"), search("deployment", 10).get(0).terms(),
|
||||
"fuzzy off: only the words whose stem is the query's");
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchesTitleAndLinksToThePage() {
|
||||
corpus(item("guide", "Runway Guide", "How to deploy."),
|
||||
item("about", "About", "Our team."));
|
||||
List<SearchHit> hits = search("runway", 20);
|
||||
assertEquals(1, hits.size());
|
||||
assertEquals("Runway Guide", hits.get(0).title());
|
||||
assertEquals("/guide", hits.get(0).url(), "the hit links to the URL the kernel computed for the entry");
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchesBodyTextNotJustMetadata() {
|
||||
CatalogEntry post = item("post", "Weekly Notes", "News.");
|
||||
corpus(post);
|
||||
body(post, "<h1>Weekly Notes</h1><p>We shipped the new <b>lucene</b> engine.</p>");
|
||||
List<SearchHit> hits = search("lucene", 20);
|
||||
assertEquals(1, hits.size(), "a body-only term matches — full-text, not metadata-only");
|
||||
assertEquals("Weekly Notes", hits.get(0).title());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aContentSourceItemIsIndexedAlongsidePages() {
|
||||
// A blog entry (any content source's item) enters the SAME Lucene index as pages — same corpus, same
|
||||
// tiers, no engine-side special case.
|
||||
CatalogEntry entry = item("blog", "hello-world", "en", "Hello World", "The first entry.");
|
||||
corpus(item("guide", "Runway Guide", "Deploy runway."), entry);
|
||||
body(entry, "Runway makes multi-tenant hosting simple.");
|
||||
List<SearchHit> hits = search("runway", 20);
|
||||
assertEquals(2, hits.size(), "the blog entry and the page are both indexed");
|
||||
assertTrue(urls(hits).contains("/hello-world"), "the entry's hit links to the entry's own URL");
|
||||
}
|
||||
|
||||
@Test
|
||||
void analysisIsTokenizedAndCaseInsensitive() {
|
||||
corpus(item("p", "The Runway Platform", ""));
|
||||
assertFalse(search("RUNWAY", 20).isEmpty(), "matching is case-insensitive (analyzed)");
|
||||
assertFalse(search("platform runway", 20).isEmpty(), "multi-term matches");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonMatchesReturnNothing() {
|
||||
corpus(item("live", "Contact", "reach us"));
|
||||
assertTrue(search("runway", 20).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSearchPluginsExclusionsReachTheIndexThroughItsCorpus() {
|
||||
// The exclude list is the SEARCH plugin's per-site setting, applied by its SearchCorpus — this engine never
|
||||
// reads it. "/Privacy" exercises the tolerated leading slash and the case fold; "hello-world" matches a
|
||||
// content-source item's own id, so it drops the blog entry too.
|
||||
searchSettings.site(SITE, Map.of("exclude", List.of("/Privacy", "hello-world")));
|
||||
CatalogEntry privacy = item("privacy", "Privacy", "Runway privacy policy.");
|
||||
corpus(privacy, item("guide", "Runway Guide", "Deploy runway."),
|
||||
item("blog", "hello-world", "en", "Runway Hello", "About runway."));
|
||||
body(privacy, "runway runway runway");
|
||||
List<SearchHit> hits = search("runway", 20);
|
||||
assertEquals(List.of("/guide"), urls(hits),
|
||||
"the excluded page AND the excluded source item are left out of the index");
|
||||
assertEquals(1, engine.indexedDocuments(SITE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theLimitIsHonored() {
|
||||
corpus(item("a", "Runway A", ""), item("b", "Runway B", ""), item("c", "Runway C", ""));
|
||||
assertEquals(2, search("runway", 2).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void equalScoresKeepTheCorpusOrder() {
|
||||
// Lucene breaks a score tie by document number, i.e. the order the corpus listed the entries in.
|
||||
corpus(item("c", "Runway", ""), item("a", "Runway", ""), item("b", "Runway", ""));
|
||||
assertEquals(List.of("/c", "/a", "/b"), urls(search("runway", 20)));
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------- locale and URL
|
||||
|
||||
@Test
|
||||
void anItemMissingFromTheSiteDefaultLanguageIsIndexedAndLinkedInItsOwnLanguage() {
|
||||
// A Spanish-only entry on an English site: its title, body and URL are its Spanish ones (CatalogEntry.pathFor
|
||||
// its primary locale) — never an unprefixed default-language path, which 404s for such an item.
|
||||
ContentRef ref = new ContentRef("receta", "/receta", Map.of("es", "/es/receta"), List.of(Locale.forLanguageTag("es")),
|
||||
Map.of("es", "Receta de tamales"), Map.of("es", "Cocina"), "", "tpl", true, Instant.EPOCH, false,
|
||||
null, null, Map.of());
|
||||
CatalogEntry spanish = new CatalogEntry("blog", ref,
|
||||
List.of(new LocalizedUrl(Locale.forLanguageTag("es"), "/es/receta", null)), null);
|
||||
corpus(spanish);
|
||||
catalog.text(SITE, spanish.compositeId(), "<p>tamales verdes</p>");
|
||||
List<SearchHit> hits = search("tamales", 20);
|
||||
assertEquals(1, hits.size());
|
||||
assertEquals("/es/receta", hits.get(0).url(), "linked at the item's real (Spanish) address");
|
||||
assertEquals("Receta de tamales", hits.get(0).title());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anItemWithoutATitleIsShownUnderItsId() {
|
||||
ContentRef ref = new ContentRef("untitled-note", "/untitled-note", Map.of(), List.of(Locale.ENGLISH), Map.of(),
|
||||
Map.of(), "", "tpl", true, Instant.EPOCH, false, null, null, Map.of());
|
||||
CatalogEntry untitled = new CatalogEntry("blog", ref,
|
||||
List.of(new LocalizedUrl(Locale.ENGLISH, "/untitled-note", null)), null);
|
||||
corpus(untitled);
|
||||
body(untitled, "<p>zeppelin</p>");
|
||||
assertEquals("untitled-note", search("zeppelin", 20).get(0).title());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theIndexableTextIsAskedForInTheItemsPrimaryLocale() {
|
||||
List<Locale> asked = new ArrayList<>();
|
||||
SearchCorpus recording = new SearchCorpus() {
|
||||
@Override
|
||||
public List<CatalogEntry> corpus(String siteId) {
|
||||
return List.of(item("guide", "Guide", ""), item("blog", "nota", "es", "Nota", ""));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String indexableText(String siteId, CatalogEntry entry, Locale locale) {
|
||||
asked.add(locale);
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void refresh(String siteId) {
|
||||
}
|
||||
};
|
||||
try (LuceneSearchEngine e = new LuceneSearchEngine(recording, sites, luceneSettings, storage)) {
|
||||
assertEquals(2, e.indexedDocuments(SITE));
|
||||
}
|
||||
assertEquals(List.of(Locale.ENGLISH, Locale.forLanguageTag("es")), asked,
|
||||
"the site default for an item that has it, else the item's own first language");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------------- index freshness
|
||||
|
||||
@Test
|
||||
void reindexRefreshesTheListingAndRebuildsFromCurrentContentImmediately() {
|
||||
corpus(item("a", "Runway", ""));
|
||||
assertEquals(1, engine.indexedDocuments(SITE));
|
||||
// The corpus grows; the cached index (fresh for 30 s) would still report 1 until reindex.
|
||||
corpus(item("a", "Runway", ""), item("b", "Runway Two", ""));
|
||||
assertEquals(1, engine.indexedDocuments(SITE), "the cached index still serves inside the TTL");
|
||||
assertEquals(2, engine.reindex(SITE),
|
||||
"the SPI reindex hook drops the cache and rebuilds NOW, returning the fresh count");
|
||||
assertEquals(List.of(SITE), catalog.refreshed(),
|
||||
"…after refreshing the shared listing through the corpus (out-of-band edits announce nothing)");
|
||||
}
|
||||
|
||||
/** Proves that delivering {@code deliver} drops the cached index: before it the old index serves. */
|
||||
private void assertTheIndexIsDroppedBy(Runnable deliver) {
|
||||
corpus(item("a", "Runway", ""));
|
||||
assertEquals(1, search("runway", 20).size());
|
||||
corpus(item("a", "Runway", ""), item("b", "Runway Two", ""));
|
||||
assertEquals(1, search("runway", 20).size(), "before any change the cached index still serves");
|
||||
deliver.run();
|
||||
assertEquals(2, search("runway", 20).size(), "the change drops the index; the next query rebuilds");
|
||||
}
|
||||
|
||||
private EventDispatch events() {
|
||||
return new EventDispatch("search-lucene", Set.of()).listener(new LuceneSiteEvents(engine));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPageChangeDropsTheSiteIndex() {
|
||||
EventDispatch events = events();
|
||||
assertTheIndexIsDroppedBy(() -> events.page(SITE, "b", List.of(),
|
||||
List.of(new LocalizedUrl(Locale.ENGLISH, "/b", null))));
|
||||
assertTrue(events.failures().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aContentSourceChangeDropsTheSiteIndex() {
|
||||
EventDispatch events = events();
|
||||
assertTheIndexIsDroppedBy(() -> events.catalog(new CatalogChange(SITE, CatalogChange.Cause.CONTENT, "blog",
|
||||
"second", "blog", List.of(), List.of(), true)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherPluginsSettingsSaveDropsTheSiteIndex() {
|
||||
// Any plugin's settings may reshape the corpus — the blog's prefix, the search plugin's exclude list — so
|
||||
// a SETTINGS change of a plugin other than this one drops the index too (no pluginId scoping).
|
||||
EventDispatch events = events();
|
||||
assertTheIndexIsDroppedBy(() -> events.settings(SITE, "search"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSiteLifecycleEventDropsTheSiteIndex() {
|
||||
EventDispatch events = events();
|
||||
assertTheIndexIsDroppedBy(() -> events.lifecycle(SITE, SiteLifecycleEvent.Kind.RESTORED, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReplayedChangeFromAnotherNodeDropsTheLocalIndexToo() {
|
||||
EventDispatch events = events();
|
||||
assertTheIndexIsDroppedBy(() -> events.catalog(new CatalogChange(SITE, CatalogChange.Cause.PAGE, "pages",
|
||||
"b", null, List.of(), List.of(), false)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChangeOnAnotherSiteLeavesThisSitesIndexAlone() {
|
||||
corpus(item("a", "Runway", ""));
|
||||
assertEquals(1, search("runway", 20).size());
|
||||
corpus(item("a", "Runway", ""), item("b", "Runway Two", ""));
|
||||
events().page("other", "x", List.of(), List.of());
|
||||
assertEquals(1, search("runway", 20).size(), "only the changed site's index is dropped");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theListenerIsAConsumer() {
|
||||
assertEquals(LuceneSiteEvents.Phase.CONSUMER, new LuceneSiteEvents(engine).phase(),
|
||||
"it reads the listing after every source has dropped its state");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChangeThatArrivesWhileTheIndexIsBeingBuiltIsNotLostToTheTtl() {
|
||||
// A change announced while a build is reading the corpus: the build may hold the old corpus, so it must not be
|
||||
// cached as fresh for 30 s — the next query rebuilds.
|
||||
AtomicBoolean changeMidBuild = new AtomicBoolean(true);
|
||||
List<List<CatalogEntry>> listings = new ArrayList<>(List.of(
|
||||
List.of(item("a", "Runway", "")),
|
||||
List.of(item("a", "Runway", ""), item("b", "Runway Two", ""))));
|
||||
LuceneSearchEngine[] self = new LuceneSearchEngine[1];
|
||||
SearchCorpus racing = new SearchCorpus() {
|
||||
@Override
|
||||
public List<CatalogEntry> corpus(String siteId) {
|
||||
List<CatalogEntry> current = listings.size() > 1 ? listings.remove(0) : listings.get(0);
|
||||
if (changeMidBuild.getAndSet(false)) {
|
||||
self[0].invalidate(siteId); // the listener runs on another thread in real life
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String indexableText(String siteId, CatalogEntry entry, Locale locale) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void refresh(String siteId) {
|
||||
}
|
||||
};
|
||||
try (LuceneSearchEngine e = new LuceneSearchEngine(racing, sites, luceneSettings, storage)) {
|
||||
self[0] = e;
|
||||
assertEquals(1, e.search(new SearchQuery(SITE, "runway", Locale.ENGLISH, 20)).size(),
|
||||
"the query that built the index is answered from it");
|
||||
assertEquals(2, e.search(new SearchQuery(SITE, "runway", Locale.ENGLISH, 20)).size(),
|
||||
"the next query rebuilds, because a change arrived during the first build");
|
||||
assertEquals(2, e.search(new SearchQuery(SITE, "runway", Locale.ENGLISH, 20)).size());
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------- tiering
|
||||
|
||||
@Test
|
||||
void exactPhraseHitOutranksScatteredTermsHit() {
|
||||
CatalogEntry scattered = item("scattered", "Notes", "");
|
||||
CatalogEntry exact = item("exact", "Manual", "");
|
||||
corpus(scattered, exact);
|
||||
body(exact, "<p>The cloud deployment guide explains everything.</p>");
|
||||
body(scattered, "<p>cloud infrastructure. a long unrelated paragraph about many topics. "
|
||||
+ "deployment pipelines. yet another sentence entirely. a helpful guide to nothing.</p>");
|
||||
List<SearchHit> hits = search("cloud deployment guide", 20);
|
||||
assertEquals(2, hits.size(), "both pages contain all terms");
|
||||
assertEquals("Manual", hits.get(0).title(), "the exact-phrase page ranks first (phrase tier)");
|
||||
assertTrue(hits.get(0).score() > hits.get(1).score(), "exact-phrase score strictly higher");
|
||||
}
|
||||
|
||||
@Test
|
||||
void titlePhraseHitOutranksBodyPhraseHit() {
|
||||
CatalogEntry bodyHit = item("body", "Some Article", "");
|
||||
corpus(bodyHit, item("title", "Runway Deployment Guide", ""));
|
||||
body(bodyHit, "<p>Here is the runway deployment guide in the body text.</p>");
|
||||
List<SearchHit> hits = search("runway deployment guide", 20);
|
||||
assertEquals("Runway Deployment Guide", hits.get(0).title(),
|
||||
"the title-phrase page wins (tierPhraseTitle > tierPhraseBody)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTierScoresAddUpAsDocumented() {
|
||||
// One title-phrase hit for a three-term query: any-terms (BM25, small) + exact title phrase (4000) +
|
||||
// all terms anywhere (300). The body has no phrase, so neither body tier fires.
|
||||
corpus(item("p", "Runway Deployment Guide", ""));
|
||||
double score = search("runway deployment guide", 20).get(0).score();
|
||||
assertTrue(score > 4300 && score < 4300 + 100, "4000 + 300 + a BM25 base, was " + score);
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------------------- fuzzy
|
||||
|
||||
@Test
|
||||
void fuzzyQueryToleratesATypo() {
|
||||
CatalogEntry p = item("p", "Lucene Handbook", "");
|
||||
corpus(p);
|
||||
body(p, "<p>All about lucene.</p>");
|
||||
// "lucane" is 1 edit from "lucene" (and stays within the fuzzy budget after analysis).
|
||||
assertFalse(search("lucane", 20).isEmpty(), "a 1-edit typo still matches with fuzzy on");
|
||||
}
|
||||
|
||||
@Test
|
||||
void fuzzyCanBeTurnedOffPerSiteAndTheSaveAppliesToTheNextQuery() {
|
||||
CatalogEntry p = item("p", "Lucene Handbook", "");
|
||||
corpus(p);
|
||||
body(p, "<p>All about lucene.</p>");
|
||||
assertFalse(search("lucane", 20).isEmpty());
|
||||
luceneSettings.site(SITE, Map.of("fuzzy", false));
|
||||
assertTrue(search("lucane", 20).isEmpty(), "with fuzzy off, the typo no longer matches — no rebuild needed");
|
||||
assertFalse(search("lucene", 20).isEmpty(), "the exact term still matches with fuzzy off");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------ per-locale analyzers
|
||||
|
||||
@Test
|
||||
void englishAnalyzerStemsSoAQueryMatchesAStemmedForm() {
|
||||
CatalogEntry p = item("p", "Athletics", "");
|
||||
corpus(p);
|
||||
body(p, "<p>They run every morning.</p>");
|
||||
assertFalse(search("running", 20).isEmpty(), "English stemming: 'running' matches 'run'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void spanishAnalyzerIsSelectedForASpanishSiteAndStems() {
|
||||
// A Spanish-default site: the SpanishAnalyzer stems "productos" and "producto" to the same root.
|
||||
site("tienda", Locale.forLanguageTag("es"));
|
||||
CatalogEntry cat = item("pages", "cat", "es", "Catálogo", "");
|
||||
corpus("tienda", cat);
|
||||
catalog.text("tienda", cat.compositeId(), "<p>Todos nuestros productos en oferta.</p>");
|
||||
List<SearchHit> hits = engine.search(new SearchQuery("tienda", "producto", Locale.forLanguageTag("es"), 20));
|
||||
assertFalse(hits.isEmpty(), "Spanish stemming: singular 'producto' matches plural 'productos'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownLocaleFallsBackToStandardAnalyzerAndStillMatches() {
|
||||
site("kl", Locale.forLanguageTag("tlh"));
|
||||
corpus("kl", item("pages", "p", "tlh", "Qapla", "victory"));
|
||||
assertFalse(engine.search(new SearchQuery("kl", "victory", Locale.forLanguageTag("tlh"), 20)).isEmpty(),
|
||||
"unknown locale still searches via the StandardAnalyzer fallback");
|
||||
assertFalse(LocaleAnalyzers.hasLanguageAnalyzer("tlh"), "no language analyzer for Klingon");
|
||||
assertTrue(LocaleAnalyzers.hasLanguageAnalyzer("es"), "Spanish has a language analyzer");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------ heap vs disk
|
||||
|
||||
@Test
|
||||
void diskStorageIndexesAndSearchesLikeHeap(@TempDir Path tmp) {
|
||||
corpus(item("guide", "Runway Guide", "How to deploy."), item("other", "Runway Other", "Runway runway."));
|
||||
List<SearchHit> heap = search("runway guide", 20);
|
||||
storage.setStorage("disk");
|
||||
storage.setIndexRoot(tmp.toString());
|
||||
newEngine();
|
||||
List<SearchHit> disk = search("runway guide", 20);
|
||||
assertEquals("disk", engine.storageMode());
|
||||
assertEquals(heap, disk, "disk (MMapDirectory) answers exactly what heap answers, scores included");
|
||||
assertTrue(Files.isDirectory(tmp.resolve(SITE)), "a per-site index folder was created on disk");
|
||||
}
|
||||
|
||||
@Test
|
||||
void heapIsTheDefaultStorageMode() {
|
||||
assertEquals("heap", engine.storageMode());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------ highlighting
|
||||
|
||||
@Test
|
||||
void highlightingWrapsTheHitInMarkTags() {
|
||||
CatalogEntry p = item("p", "Guide", "");
|
||||
corpus(p);
|
||||
body(p, "<p>Configuring the deployment pipeline is the first step of any release.</p>");
|
||||
List<SearchHit> hits = search("deployment", 20);
|
||||
assertEquals(1, hits.size());
|
||||
String snippet = hits.get(0).snippet();
|
||||
assertTrue(snippet.contains("<mark>deployment</mark>"),
|
||||
"the matched term is wrapped in <mark> in the query-focused snippet, was: " + snippet);
|
||||
}
|
||||
|
||||
@Test
|
||||
void highlightSnippetEscapesPageMarkupSoOnlyMarkTagsSurvive() {
|
||||
CatalogEntry p = item("p", "Guide", "");
|
||||
corpus(p);
|
||||
body(p, "<p>Use the <deployment> token and the deployment button to ship.</p>");
|
||||
String snippet = search("deployment", 20).get(0).snippet();
|
||||
assertTrue(snippet.contains("<mark>"), "a mark tag is present");
|
||||
assertFalse(snippet.contains("<deployment>"), "raw page angle brackets are escaped, not rendered as a tag");
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutABodyHitTheSnippetIsTheDescription() {
|
||||
corpus(item("p", "Runway", "A short summary."), item("q", "Lone Title", ""));
|
||||
assertEquals("A short summary.", search("runway", 20).get(0).snippet());
|
||||
assertEquals("", search("lone", 20).get(0).snippet(), "no body and no description: an empty snippet");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------------- tuning knobs
|
||||
|
||||
@Test
|
||||
void titleBoostKnobRaisesATitleMatchOverABodyMatch() {
|
||||
CatalogEntry bodyHit = item("bodyhit", "Other", "");
|
||||
corpus(item("titlehit", "alpha", ""), bodyHit);
|
||||
body(bodyHit, "<p>alpha appears only in the body here.</p>");
|
||||
// Single-term query so the phrase tiers don't fire — the any-terms tier (where titleBoost applies) decides.
|
||||
luceneSettings.site(SITE, Map.of("titleBoost", 50.0));
|
||||
List<SearchHit> hits = search("alpha", 20);
|
||||
assertEquals(2, hits.size());
|
||||
assertEquals("alpha", hits.get(0).title(), "with a high titleBoost the title-match page ranks first");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tierScoreKnobsChangeTheAbsoluteScore() {
|
||||
corpus(item("p", "Runway Deployment Guide", ""));
|
||||
double defaultScore = search("runway deployment guide", 20).get(0).score();
|
||||
luceneSettings.site(SITE, Map.of("tierPhraseTitle", 40000.0));
|
||||
double boostedScore = search("runway deployment guide", 20).get(0).score();
|
||||
assertTrue(boostedScore > defaultScore,
|
||||
"raising tierPhraseTitle raises the exact-title-phrase score: " + boostedScore + " > " + defaultScore);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDeclaredDefaultsRankExactlyLikeNoSettingsAtAll() {
|
||||
// PluginSettings hands the engine the descriptor's defaults under the stored values; they equal the code
|
||||
// fallbacks, so a site that never saved the form ranks as the engine's own defaults do.
|
||||
CatalogEntry p = item("p", "Runway Deployment Guide", "deploy");
|
||||
corpus(p, item("q", "Notes", "runway"));
|
||||
body(p, "<p>runway deployment guide and more</p>");
|
||||
List<SearchHit> bare = search("runway deployment guide", 20);
|
||||
luceneSettings.defaults(Map.of("fuzzy", true, "fuzzyBoost", 0.4, "titleBoost", 8.0, "descriptionBoost", 4.0,
|
||||
"tierPhraseTitle", 4000, "tierPhraseBody", 2000, "tierNearPhrase", 800, "tierAllTerms", 300));
|
||||
assertEquals(bare, search("runway deployment guide", 20));
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedKnobValuesFallBackToDefaultsAndStillSearch() {
|
||||
corpus(item("p", "Runway Guide", ""));
|
||||
luceneSettings.site(SITE, Map.of(
|
||||
"titleBoost", "not-a-number", "fuzzyBoost", "", "tierPhraseTitle", "abc", "fuzzy", "maybe"));
|
||||
assertFalse(search("runway", 20).isEmpty(), "malformed config degrades to defaults, never breaks search");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- console
|
||||
|
||||
@Test
|
||||
void consoleModelReportsIndexSizeTitleBoostAndStorageMode() {
|
||||
corpus(item("a", "A", ""), item("b", "B", ""));
|
||||
LuceneAdminModel model = new LuceneAdminModel(engine);
|
||||
assertEquals(2, model.indexedPages(SITE), "the corpus is what the console reports");
|
||||
assertEquals("heap", model.storageMode());
|
||||
assertEquals("search/lucene", model.engineKey());
|
||||
assertEquals("8.0", model.titleBoost(SITE));
|
||||
luceneSettings.site(SITE, Map.of("titleBoost", 9.5));
|
||||
assertEquals("9.5", model.titleBoost(SITE), "the effective, per-site value");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** The app-level storage settings: default heap, tolerant enum binding, and a never-blank index root. */
|
||||
class LuceneStoragePropsTest {
|
||||
|
||||
@Test
|
||||
void defaultsToHeapWithADefaultIndexRoot() {
|
||||
LuceneStorageProps p = new LuceneStorageProps();
|
||||
assertEquals(LuceneStorageProps.Storage.HEAP, p.getStorage());
|
||||
assertFalse(p.isDisk());
|
||||
assertFalse(p.getIndexRoot().isBlank());
|
||||
}
|
||||
|
||||
@Test
|
||||
void storageBindingIsCaseInsensitiveAndTolerant() {
|
||||
LuceneStorageProps p = new LuceneStorageProps();
|
||||
p.setStorage("disk");
|
||||
assertTrue(p.isDisk());
|
||||
p.setStorage("HEAP");
|
||||
assertFalse(p.isDisk());
|
||||
p.setStorage("DISK");
|
||||
assertTrue(p.isDisk());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownOrBlankStorageFallsBackToHeap() {
|
||||
LuceneStorageProps p = new LuceneStorageProps();
|
||||
p.setStorage("disk");
|
||||
p.setStorage("nonsense"); // degrade-don't-crash: not a crash, resets to HEAP
|
||||
assertEquals(LuceneStorageProps.Storage.HEAP, p.getStorage());
|
||||
p.setStorage("disk");
|
||||
p.setStorage("");
|
||||
assertEquals(LuceneStorageProps.Storage.HEAP, p.getStorage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankIndexRootRestoresTheDefault() {
|
||||
LuceneStorageProps p = new LuceneStorageProps();
|
||||
p.setIndexRoot("/data/idx");
|
||||
assertEquals("/data/idx", p.getIndexRoot());
|
||||
p.setIndexRoot(" ");
|
||||
assertFalse(p.getIndexRoot().isBlank(), "blank restores the default, never leaves an empty path");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Defensive resolution of the per-tenant ranking knobs: defaults, coercion, clamping, and garbage tolerance. */
|
||||
class RankingConfigTest {
|
||||
|
||||
@Test
|
||||
void emptyConfigYieldsTheHistoricalDefaults() {
|
||||
RankingConfig c = RankingConfig.defaults();
|
||||
assertTrue(c.fuzzy());
|
||||
assertEquals(RankingConfig.DEF_FUZZY_BOOST, c.fuzzyBoost());
|
||||
assertEquals(RankingConfig.DEF_TITLE_BOOST, c.titleBoost());
|
||||
assertEquals(RankingConfig.DEF_DESCRIPTION_BOOST, c.descriptionBoost());
|
||||
assertEquals(RankingConfig.DEF_TIER_PHRASE_TITLE, c.tierPhraseTitle());
|
||||
assertEquals(RankingConfig.DEF_TIER_PHRASE_BODY, c.tierPhraseBody());
|
||||
assertEquals(RankingConfig.DEF_TIER_NEAR_PHRASE, c.tierNearPhrase());
|
||||
assertEquals(RankingConfig.DEF_TIER_ALL_TERMS, c.tierAllTerms());
|
||||
}
|
||||
|
||||
@Test
|
||||
void numericAndStringValuesAreBothCoerced() {
|
||||
RankingConfig c = RankingConfig.from(Map.of("titleBoost", 12.5, "descriptionBoost", "3.25"));
|
||||
assertEquals(12.5f, c.titleBoost());
|
||||
assertEquals(3.25f, c.descriptionBoost());
|
||||
}
|
||||
|
||||
@Test
|
||||
void booleanFlagAcceptsBooleanAndTruthyStrings() {
|
||||
assertTrue(RankingConfig.from(Map.of("fuzzy", true)).fuzzy());
|
||||
assertFalse(RankingConfig.from(Map.of("fuzzy", false)).fuzzy());
|
||||
assertTrue(RankingConfig.from(Map.of("fuzzy", "on")).fuzzy());
|
||||
assertTrue(RankingConfig.from(Map.of("fuzzy", "1")).fuzzy());
|
||||
assertFalse(RankingConfig.from(Map.of("fuzzy", "off")).fuzzy());
|
||||
}
|
||||
|
||||
@Test
|
||||
void garbageAndBlanksFallBackToDefaults() {
|
||||
Map<String, Object> cfg = new HashMap<>();
|
||||
cfg.put("titleBoost", "not-a-number");
|
||||
cfg.put("fuzzyBoost", "");
|
||||
cfg.put("tierPhraseBody", "NaN");
|
||||
RankingConfig c = RankingConfig.from(cfg);
|
||||
assertEquals(RankingConfig.DEF_TITLE_BOOST, c.titleBoost());
|
||||
assertEquals(RankingConfig.DEF_FUZZY_BOOST, c.fuzzyBoost());
|
||||
assertEquals(RankingConfig.DEF_TIER_PHRASE_BODY, c.tierPhraseBody());
|
||||
}
|
||||
|
||||
@Test
|
||||
void negativeValuesAreClampedToZeroAndHugeValuesAreCapped() {
|
||||
RankingConfig c = RankingConfig.from(Map.of("titleBoost", -5.0, "tierAllTerms", 9.9e12));
|
||||
assertEquals(0f, c.titleBoost(), "negative boost clamped to 0");
|
||||
assertTrue(c.tierAllTerms() <= 1_000_001f, "a huge value is capped, not left to overflow the score math");
|
||||
}
|
||||
}
|
||||
+291
@@ -0,0 +1,291 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
import mx.quest.runway.spi.service.Sites;
|
||||
import mx.quest.runway.spi.testkit.FakeContentCatalog;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import mx.quest.search.SiteSearchCorpus;
|
||||
import mx.quest.search.spi.SearchCorpus;
|
||||
import mx.quest.search.spi.SiteSearchEngine;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.MapPropertySource;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
|
||||
/**
|
||||
* The plugin's contract with the host and with the search plugin, checked at build time: the wiring over published
|
||||
* services only (SPI services from the kernel, {@link SearchCorpus} from search) including the app-level storage
|
||||
* settings bound under {@code runway.plugin.search-lucene}; the bean-name rule; the bean names the templates reference;
|
||||
* the descriptor (SPI floor, release version, the {@code requires:} gates); the code fallbacks equal to the descriptor
|
||||
* defaults; the i18n bundles; and that the compiled classes link nothing of the host but the SPI and nothing of the
|
||||
* search plugin but its SPI package — the same things the kernel's load-time checks warn about (and refuse from
|
||||
* Runway 1.0).
|
||||
*/
|
||||
class SearchLuceneConfigTest {
|
||||
|
||||
private static final String PREFIX = "searchLucene";
|
||||
|
||||
/** Stands in for the host's Spring Boot auto-configuration: the binder behind {@code @ConfigurationProperties}. */
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableConfigurationProperties
|
||||
static class HostBinding {
|
||||
}
|
||||
|
||||
private static Set<String> beanMethodNames() {
|
||||
return Arrays.stream(SearchLuceneConfig.class.getDeclaredMethods())
|
||||
.filter(m -> m.isAnnotationPresent(Bean.class))
|
||||
.map(Method::getName)
|
||||
.collect(Collectors.toCollection(TreeSet::new));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> descriptor() throws IOException {
|
||||
try (Reader in = Files.newBufferedReader(Path.of("plugin.yml"), StandardCharsets.UTF_8)) {
|
||||
return (Map<String, Object>) new Yaml().load(in);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> declaredDefaults(String section) throws IOException {
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
for (Map<String, Object> s : (List<Map<String, Object>>) descriptor().get(section)) {
|
||||
if (s.containsKey("default")) {
|
||||
out.put((String) s.get("key"), s.get("default"));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@Test
|
||||
void wiresEverythingFromPublishedServicesUnderPrefixedNames(@org.junit.jupiter.api.io.TempDir Path index)
|
||||
throws IOException {
|
||||
FakeSiteServices kernel = new FakeSiteServices()
|
||||
.site(new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null));
|
||||
FakeContentCatalog catalog = new FakeContentCatalog()
|
||||
.entry("acme", LuceneSearchEngineTest.item("home", "Runway home", ""))
|
||||
.entry("acme", LuceneSearchEngineTest.item("privacy", "Runway privacy", ""));
|
||||
SearchCorpus corpus = new SiteSearchCorpus(catalog,
|
||||
new FakePluginSettings().site("acme", Map.of("exclude", List.of("privacy"))));
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
|
||||
ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource("plugin-settings", Map.of(
|
||||
"runway.plugin.search-lucene.storage", "disk",
|
||||
"runway.plugin.search-lucene.indexRoot", index.toString())));
|
||||
ctx.registerBean(PluginSettings.class, () -> new FakePluginSettings()
|
||||
.site("acme", Map.of("titleBoost", 9.5)));
|
||||
ctx.registerBean(Sites.class, () -> kernel);
|
||||
ctx.registerBean(SearchCorpus.class, () -> corpus);
|
||||
ctx.register(HostBinding.class, SearchLuceneConfig.class);
|
||||
ctx.refresh();
|
||||
|
||||
LuceneStorageProps props = ctx.getBean("searchLuceneStorageProps", LuceneStorageProps.class);
|
||||
assertTrue(props.isDisk(), "the app-level settings bind under runway.plugin.search-lucene");
|
||||
assertEquals(index.toString(), props.getIndexRoot());
|
||||
|
||||
LuceneSearchEngine engine = ctx.getBean("searchLuceneEngine", LuceneSearchEngine.class);
|
||||
assertEquals(List.of(engine), List.copyOf(ctx.getBeansOfType(SiteSearchEngine.class).values()),
|
||||
"one engine, collected by the search plugin's List<SiteSearchEngine>");
|
||||
assertEquals(1, engine.indexedDocuments("acme"), "the engine indexes the corpus (privacy is excluded)");
|
||||
assertEquals("disk", engine.storageMode());
|
||||
assertTrue(Files.isDirectory(index.resolve("acme")));
|
||||
|
||||
Map<String, SiteEventListener> listeners = ctx.getBeansOfType(SiteEventListener.class);
|
||||
assertEquals(Set.of("searchLuceneSiteEvents"), listeners.keySet(), "one listener, collected by type");
|
||||
assertEquals(SiteEventListener.Phase.CONSUMER, listeners.get("searchLuceneSiteEvents").phase());
|
||||
|
||||
LuceneAdminModel model = ctx.getBean("searchLuceneAdminModel", LuceneAdminModel.class);
|
||||
assertEquals("9.5", model.titleBoost("acme"), "the knobs come from the injected PluginSettings");
|
||||
assertSame(engine, readEngine(model));
|
||||
|
||||
for (String name : ctx.getBeanDefinitionNames()) {
|
||||
Class<?> type = ctx.getType(name);
|
||||
if (type != null && type.getPackageName().equals("mx.quest.searchlucene")
|
||||
&& !name.equals(SearchLuceneConfig.class.getName())
|
||||
&& !name.equals("searchLuceneConfig")) {
|
||||
assertTrue(name.startsWith(PREFIX), "every plugin bean name starts with 'searchLucene': " + name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Object readEngine(LuceneAdminModel model) {
|
||||
try {
|
||||
var field = LuceneAdminModel.class.getDeclaredField("engine");
|
||||
field.setAccessible(true);
|
||||
return field.get(model);
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyBeanNameStartsWithThePluginIdInLowerCamelCase() {
|
||||
assertEquals(Set.of("searchLuceneStorageProps", "searchLuceneEngine", "searchLuceneSiteEvents",
|
||||
"searchLuceneAdminModel"), beanMethodNames());
|
||||
for (Method m : SearchLuceneConfig.class.getDeclaredMethods()) {
|
||||
Bean bean = m.getAnnotation(Bean.class);
|
||||
if (bean != null) {
|
||||
for (String alias : bean.name()) {
|
||||
assertTrue(alias.startsWith(PREFIX), "an explicit bean name must start with " + PREFIX + ": " + alias);
|
||||
}
|
||||
}
|
||||
}
|
||||
assertFalse(SearchLuceneConfig.class.isAnnotationPresent(EnableConfigurationProperties.class),
|
||||
"@EnableConfigurationProperties names its bean '<prefix>-<class>', which breaks the bean-name rule");
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyBeanTheTemplatesReferenceIsOneOfOurs() throws IOException {
|
||||
Set<String> referenced = new TreeSet<>();
|
||||
try (Stream<Path> files = Files.list(Path.of("templates"))) {
|
||||
for (Path file : files.filter(p -> p.toString().endsWith(".th.xml")).toList()) {
|
||||
String live = Files.readString(file, StandardCharsets.UTF_8).replaceAll("(?s)<!--.*?-->", "");
|
||||
Matcher m = Pattern.compile("@(\\w+)\\.").matcher(live);
|
||||
while (m.find()) {
|
||||
referenced.add(m.group(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
assertEquals(Set.of("searchLuceneAdminModel"), referenced, "the console templates read the admin model only");
|
||||
assertTrue(beanMethodNames().containsAll(referenced), "templates reference unknown beans: " + referenced);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDescriptorDeclaresTheFloorsAndTheReleaseVersion() throws IOException {
|
||||
Map<String, Object> yml = descriptor();
|
||||
assertEquals(">=1.0.0", yml.get("requiresSpi"), "built for the frozen SPI 1.0.0 contract");
|
||||
assertEquals(List.of("search >= 2.2.0", "lucene-provider == 10.4.0"), yml.get("requires"),
|
||||
"search 2.2.0 submits a localized box to the localized results page, which reaches a language's index"
|
||||
+ " (2.1.0 was the first with the matched-words SearchHit); Lucene is pinned to the binaries");
|
||||
assertEquals("mx.quest.searchlucene.SearchLuceneConfig", yml.get("mainClass"));
|
||||
String pom = Files.readString(Path.of("pom.xml"), StandardCharsets.UTF_8);
|
||||
Matcher version = Pattern.compile("<artifactId>runway-plugin-search-lucene</artifactId>\\s*<version>([^<]+)")
|
||||
.matcher(pom);
|
||||
assertTrue(version.find());
|
||||
assertEquals(version.group(1), String.valueOf(yml.get("version")), "plugin.yml and pom.xml agree on the version");
|
||||
assertEquals("3.3.0", version.group(1));
|
||||
assertFalse(pom.contains("<artifactId>runway-app</artifactId>"), "no runway-app dependency in any scope");
|
||||
assertTrue(pom.contains("<project.build.outputTimestamp>2026-10-21T17:23:00Z</project.build.outputTimestamp>"));
|
||||
assertTrue(pom.contains("<lucene.version>10.4.0</lucene.version>"),
|
||||
"the compiled-against Lucene equals the lucene-provider pin");
|
||||
assertFalse(yml.containsKey("siteData"), "the plugin keeps no per-site data (the index is derived)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCodeFallbacksEqualTheDescriptorDefaults() throws IOException {
|
||||
Map<String, Object> site = declaredDefaults("siteSettings");
|
||||
RankingConfig code = RankingConfig.defaults();
|
||||
assertEquals(site.get("fuzzy"), code.fuzzy());
|
||||
assertEquals(((Number) site.get("fuzzyBoost")).floatValue(), code.fuzzyBoost());
|
||||
assertEquals(((Number) site.get("titleBoost")).floatValue(), code.titleBoost());
|
||||
assertEquals(((Number) site.get("descriptionBoost")).floatValue(), code.descriptionBoost());
|
||||
assertEquals(((Number) site.get("tierPhraseTitle")).floatValue(), code.tierPhraseTitle());
|
||||
assertEquals(((Number) site.get("tierPhraseBody")).floatValue(), code.tierPhraseBody());
|
||||
assertEquals(((Number) site.get("tierNearPhrase")).floatValue(), code.tierNearPhrase());
|
||||
assertEquals(((Number) site.get("tierAllTerms")).floatValue(), code.tierAllTerms());
|
||||
assertEquals(8, site.size(), "every declared default is checked above");
|
||||
assertEquals(code, RankingConfig.from(site), "the declared defaults resolve to the code defaults");
|
||||
|
||||
Map<String, Object> app = declaredDefaults("settings");
|
||||
LuceneStorageProps props = new LuceneStorageProps();
|
||||
assertEquals(app.get("storage"), props.getStorage().name().toLowerCase(Locale.ROOT));
|
||||
assertEquals(app.get("indexRoot"), props.getIndexRoot());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEnglishAndSpanishBundlesDefineTheSameKeys() throws IOException {
|
||||
Set<String> en = keys("i18n/messages.properties");
|
||||
assertEquals(en, keys("i18n/messages_es.properties"));
|
||||
Set<String> labels = new TreeSet<>();
|
||||
for (String section : List.of("settings", "siteSettings", "permissions")) {
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, Object>> entries = (List<Map<String, Object>>) descriptor().get(section);
|
||||
entries.forEach(e -> labels.add((String) e.get("label")));
|
||||
}
|
||||
assertTrue(en.containsAll(labels), "every descriptor label has words: " + labels);
|
||||
}
|
||||
|
||||
private static Set<String> keys(String file) throws IOException {
|
||||
Properties p = new Properties();
|
||||
try (Reader in = Files.newBufferedReader(Path.of(file), StandardCharsets.UTF_8)) {
|
||||
p.load(in);
|
||||
}
|
||||
return new TreeSet<>(p.stringPropertyNames());
|
||||
}
|
||||
|
||||
/** Every class file this plugin ships, with its constant pool as text (Latin-1 keeps one char per byte). */
|
||||
private static Map<String, String> compiledClasses() throws IOException {
|
||||
Path classes = Path.of("target", "classes");
|
||||
Map<String, String> out = new LinkedHashMap<>();
|
||||
try (Stream<Path> files = Files.walk(classes)) {
|
||||
for (Path file : files.filter(p -> p.toString().endsWith(".class")).sorted().toList()) {
|
||||
out.put(classes.relativize(file).toString().replace('\\', '/'),
|
||||
new String(Files.readAllBytes(file), StandardCharsets.ISO_8859_1));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCompiledClassesLinkNoHostInternalsAndOnlyTheSearchSpi() throws IOException {
|
||||
Pattern host = Pattern.compile("mx[/.]quest[/.]runway[/.](?!spi[/.])[\\w/.$]*");
|
||||
// search's own classes (SiteSearchCorpus, SearchSiteConfig, …) are its internals: only its SPI package is a
|
||||
// contract, and only the SPI package is guaranteed to keep its shape across search releases.
|
||||
Pattern searchInternals = Pattern.compile("mx[/.]quest[/.]search[/.](?!spi[/.])[\\w/.$]*");
|
||||
List<String> problems = new ArrayList<>();
|
||||
Map<String, String> classes = compiledClasses();
|
||||
classes.forEach((rel, pool) -> {
|
||||
if (!rel.startsWith("mx/quest/searchlucene/")) {
|
||||
problems.add(rel + " lives outside mx.quest.searchlucene");
|
||||
}
|
||||
for (Pattern p : List.of(host, searchInternals)) {
|
||||
Matcher m = p.matcher(pool);
|
||||
while (m.find()) {
|
||||
problems.add(rel + " → " + m.group());
|
||||
}
|
||||
}
|
||||
});
|
||||
assertTrue(classes.size() >= 8, "the compiled classes were found (" + classes.size() + ")");
|
||||
assertTrue(problems.isEmpty(), "linkage outside the published contracts: " + problems);
|
||||
assertTrue(classes.values().stream().anyMatch(pool -> pool.contains("mx/quest/search/spi/SearchCorpus")),
|
||||
"the engine reads the search plugin's SearchCorpus");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCompiledClassesLinkNoCaffeine() throws IOException {
|
||||
// Caffeine is a kernel implementation detail, not one of the platform libraries the kernel promises
|
||||
// (Spring, Spring Boot, Spring Security, Thymeleaf, Jackson, Jakarta EE): a plugin must not link it.
|
||||
compiledClasses().forEach((rel, pool) ->
|
||||
assertFalse(pool.contains("com/github/benmanes"), rel + " links Caffeine"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<!-- Admin status fragment — the filename `admin` makes the host render it below this plugin's per-tenant
|
||||
settings form (the titleBoost tuning). Bare fragment; binding in admin.th.xml. -->
|
||||
<div class="card mt-3">
|
||||
<div class="card-header"><h3 class="card-title" id="la-title">Lucene index status</h3></div>
|
||||
<div class="card-body">
|
||||
<div class="datagrid">
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="la-l-engine">Engine</div>
|
||||
<div class="datagrid-content" id="la-engine">search/lucene</div>
|
||||
</div>
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="la-l-pages">Indexed pages</div>
|
||||
<div class="datagrid-content" id="la-pages">0</div>
|
||||
</div>
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="la-l-storage">Storage</div>
|
||||
<div class="datagrid-content" id="la-storage">heap</div>
|
||||
</div>
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="la-l-boost">Title boost</div>
|
||||
<div class="datagrid-content" id="la-boost">8.0</div>
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-secondary small mt-2 mb-0" id="la-note">
|
||||
This engine supersedes the built-in search whenever it is installed. The index refreshes
|
||||
automatically as pages change; no manual rebuild is needed.</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Admin fragment logic. Values from ${@searchLuceneAdminModel...(tenantSiteId)}. -->
|
||||
<thlogic>
|
||||
<attr sel="#la-title" th:text="#{searchlucene.admin.title}"/>
|
||||
<attr sel="#la-l-engine" th:text="#{searchlucene.admin.engine}"/>
|
||||
<attr sel="#la-engine" th:text="${@searchLuceneAdminModel.engineKey()}"/>
|
||||
<attr sel="#la-l-pages" th:text="#{searchlucene.admin.pages}"/>
|
||||
<attr sel="#la-pages" th:text="${@searchLuceneAdminModel.indexedPages(tenantSiteId)}"/>
|
||||
<attr sel="#la-l-storage" th:text="#{searchlucene.admin.storage}"/>
|
||||
<attr sel="#la-storage" th:text="${@searchLuceneAdminModel.storageMode()}"/>
|
||||
<attr sel="#la-l-boost" th:text="#{searchlucene.admin.boost}"/>
|
||||
<attr sel="#la-boost" th:text="${@searchLuceneAdminModel.titleBoost(tenantSiteId)}"/>
|
||||
<attr sel="#la-note" th:text="#{searchlucene.admin.note}"/>
|
||||
</thlogic>
|
||||
@@ -0,0 +1,16 @@
|
||||
<!-- Tenant dashboard card fragment — __plugin__/search-lucene/dashboard. Bare fragment; binding in .th.xml. -->
|
||||
<div class="card">
|
||||
<div class="card-status-start bg-purple"></div>
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center">
|
||||
<span class="bg-purple-lt avatar"><i class="fa-solid fa-layer-group"></i></span>
|
||||
<div class="ms-3">
|
||||
<div class="fw-bold" id="lc-title">Lucene search index</div>
|
||||
<div class="text-secondary small">
|
||||
<span id="lc-pages">0</span> <span id="lc-pages-lbl">indexed pages</span>
|
||||
· <span id="lc-engine">search/lucene</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Dashboard card logic. Values from ${@searchLuceneAdminModel...(tenantSiteId)}. -->
|
||||
<thlogic>
|
||||
<attr sel="#lc-title" th:text="#{searchlucene.card.title}"/>
|
||||
<attr sel="#lc-pages" th:text="${@searchLuceneAdminModel.indexedPages(tenantSiteId)}"/>
|
||||
<attr sel="#lc-pages-lbl" th:text="#{searchlucene.card.pages}"/>
|
||||
<attr sel="#lc-engine" th:text="${@searchLuceneAdminModel.engineKey()}"/>
|
||||
</thlogic>
|
||||
@@ -0,0 +1,12 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [2.3.0] — 2026-10-21
|
||||
|
||||
First public release of `search`: on-site search with a search-box widget that renders results on an editable
|
||||
page, a JSON API, highlighted
|
||||
matches and a no-results log; each language searches its own text. Publishes its own SPI (`SearchCorpus`,
|
||||
`SiteSearchEngine`) so an engine plugin such as `search-lucene` can replace the built-in engine. Requires SPI
|
||||
`1.0.0` (Runway `1.0.0` or later). Licensed under the GNU AGPL v3.0 with an additional permission for plugins
|
||||
(`LICENSE`, `LICENSE-EXCEPTION`).
|
||||
@@ -0,0 +1,661 @@
|
||||
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.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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/>.
|
||||
@@ -0,0 +1,44 @@
|
||||
Runway — additional permission for plugins
|
||||
(an additional permission under section 7 of the GNU Affero General Public License, version 3)
|
||||
|
||||
Copyright (C) 2026 Quest ICT SAS de CV
|
||||
|
||||
Runway 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, version 3
|
||||
(the file LICENSE), with the additional permission below. Runway 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.
|
||||
|
||||
1. Definitions
|
||||
|
||||
"Runway" means the Runway kernel and every Runway plugin whose source carries this file.
|
||||
|
||||
"Published SPI" means the public classes and interfaces of the runway-spi artifact
|
||||
(the package mx.quest.runway.spi and its subpackages), together with the public classes
|
||||
and interfaces of any package named "spi" that a part of Runway publishes for other
|
||||
plugins to use (for example mx.quest.search.spi).
|
||||
|
||||
"Plugin" means an independent module that Runway loads as a plugin, that interacts with
|
||||
Runway only through the Published SPI, and that is not based on any part of Runway other
|
||||
than the Published SPI.
|
||||
|
||||
2. Permission
|
||||
|
||||
As an additional permission, the copyright holder gives you permission to combine Runway
|
||||
with Plugins, and to convey and run the resulting combination, without the terms of the
|
||||
GNU Affero General Public License applying to those Plugins. You may license, convey and
|
||||
run your Plugins under terms of your choice, provided that you continue to meet the terms
|
||||
of the GNU Affero General Public License for Runway itself, including offering the
|
||||
Corresponding Source of Runway, and of any modification you make to it, as that license
|
||||
requires.
|
||||
|
||||
3. Testing
|
||||
|
||||
Compiling a Plugin's tests against the runway-spi-testkit artifact, and running them, does
|
||||
not by itself make the Plugin subject to the GNU Affero General Public License.
|
||||
|
||||
4. Modified versions
|
||||
|
||||
If you modify Runway, you may extend this additional permission to your version, but you
|
||||
are not obliged to do so. If you do not wish to, delete this file from your version.
|
||||
@@ -0,0 +1,56 @@
|
||||
# Runway Search plugin
|
||||
|
||||
On-site search for [Runway](../README.md) sites: an embeddable **search box**, an installable, editable
|
||||
**`/search`** results page (created `noindex` — the canonical opt-out for search results), a **`/search/api`**
|
||||
JSON endpoint, and a built-in **full-text** engine over the site's published content — your pages AND any
|
||||
content source's items (blog entries, product pages, …), titles, descriptions and bodies alike — backed by the
|
||||
plugin's own SPI, so a companion plugin (`../search-lucene`) can upgrade the engine with no change to the search UX.
|
||||
Since 2.0.0 it links **only the Runway SPI** (needs a kernel whose SPI is `1.0.0` or later).
|
||||
|
||||
- **Plugin id:** `search` — install folder `external/plugins/search/`
|
||||
- **Java package:** `mx.quest.search` · **Published SPI:** `mx.quest.search.spi.SearchCorpus` (what every engine
|
||||
indexes) and `mx.quest.search.spi.SiteSearchEngine` (the engine extension point)
|
||||
|
||||
## What it adds
|
||||
|
||||
| Surface | Where |
|
||||
|---|---|
|
||||
| Search box widget | `<div id="x" data-widget="search/box"></div>` on any page/master |
|
||||
| Results page | an installed, editable tenant page at `/search` carrying the query-aware box widget (created `noindex`; styled by `/__plugin/search/static/search.css`); installed through the kernel's `SitePages`, so it follows the site's editorial level (published, waiting for review, or a draft the quality checks blocked) |
|
||||
| JSON API | `GET /search/api?q=…` → `{query,count,results:[{url,title,snippet,score,link,terms}]}` (rate-limited per client IP as the kernel's trusted-proxy gate resolved it, `noindex`) |
|
||||
| Corpus | `SearchCorpus`: every published page and content item of the kernel's `ContentCatalogView`, minus the site's exclude list — what the built-in engine and `search-lucene` both index |
|
||||
| Built-in engine | full-text match over each item's title + description + **body**, in the item's own language, linked at its real URL |
|
||||
| Highlighted snippets | `<mark>`-wrapped, length-bounded, XSS-safe (escape-then-mark) |
|
||||
| Highlight on the result page (2.1.0) | a result link carries the matched words (`#rw-hl=…`); the page it opens highlights them and scrolls to the first (CSS Custom Highlight API, restyle with `::highlight(rw-search)`); per-site switch `highlight` |
|
||||
| Box only in the chrome (2.1.0) | a header/footer box no longer repeats the results on the results page; per-placement `results` setting (`auto`/`always`/`never`) on Site → Content widgets |
|
||||
| Instant freshness | any page write, content-source change, site lifecycle event or plugin settings save drops that site's index at once (the plugin's `SiteEventListener`); the TTL is only the backstop |
|
||||
| Operator actions | the **Rebuild index** and **Install search page** buttons and **Clear list** — CSRF-checked `POST /search/reindex`, `/search/install-page`, `/search/no-results/clear`, gated by the `search|settings` control point |
|
||||
| Searches with no results | opt-in per site (**off by default** — terms can be personal data): term + count + last seen, bounded (500 terms, 90-day retention by default), never an IP or a user; listed on the settings page with a Clear action; **declared personal data**, so a site's transfer copy leaves it out |
|
||||
| App settings | index freshness + per-client rate limit (`runway.plugin.search.*`) |
|
||||
| Per-site settings | enable, max results, results page path, placeholder, exclude list, snippet length, highlight on the result page, ranking weights, no-result recording + its retention |
|
||||
| Console | a tenant dashboard card + an admin status panel (searchable items, active engine, the two buttons) + the no-result searches card |
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
export JAVA_HOME=/path/to/jdk-25
|
||||
mvn -q verify
|
||||
# → target/runway-plugin-search.jar
|
||||
# target/search/ (cp -r into <external>/plugins/ and restart)
|
||||
# target/runway-plugin-search-2.3.0.zip (upload at /__app/plugins → install)
|
||||
HOST_JAR=/path/to/runway/runway-app/target/runway-app-<version>-exec.jar \
|
||||
JAVA_HOME=/path/to/jdk-25 scripts/verify-against-host.sh # boots the PACKAGED host and proves the contract live
|
||||
```
|
||||
|
||||
The first build downloads its Maven dependencies, and needs the `runway-spi` jars installed in `~/.m2` as the
|
||||
[authoring guide §2](../docs/PLUGIN-AUTHORING-GUIDE.md#2-prerequisites) describes.
|
||||
|
||||
The build is reproducible: two builds of the same source give a byte-identical zip.
|
||||
|
||||
See [`docs/SEARCH-PLUGIN.md`](docs/SEARCH-PLUGIN.md) for the design and the SPI contract.
|
||||
|
||||
## License
|
||||
|
||||
GNU Affero General Public License v3.0 with an additional permission for plugins (`LICENSE`, `LICENSE-EXCEPTION`),
|
||||
copyright Quest ICT SAS de CV. The permission means that a plugin which uses only the published SPI, including
|
||||
search's own SPI for engines, may carry any license.
|
||||
@@ -0,0 +1,332 @@
|
||||
# Runway Search plugin — design & reference
|
||||
|
||||
> On-site search as a **query surface + a swappable engine over one corpus**. `search` publishes its own SPI —
|
||||
> `SearchCorpus` (what every engine indexes) and `SiteSearchEngine` (the engine extension point); `../search-lucene`
|
||||
> implements the second and reads the first. Since 2.0.0 the plugin links **only the Runway SPI** (service tier,
|
||||
> SPI `1.0.0`). See the shared `../docs/PLUGIN-AUTHORING-GUIDE.md` and
|
||||
> [`docs/PLUGIN-DEVELOPMENT.md`](../../../docs/PLUGIN-DEVELOPMENT.md) at the root of the repository for the seams.
|
||||
|
||||
## 1. What it does
|
||||
|
||||
- **Query-aware search box** — a `ContentWidget` (`key = "search"`). A site manager drops
|
||||
`<div id="site-search" data-widget="search/box"></div>` on any page or the master chrome; the widget renders a
|
||||
GET form that submits `?q=` to the site's results page (the `resultsPath` setting, default `/search`). It is
|
||||
**query-aware** (kernel `WidgetView.query()`): when the page carrying it is opened with a non-blank `q`, it
|
||||
renders the ranked results **inline below the box** (referencing the plugin's own `/__plugin/search/static/search.css`,
|
||||
which a site overrides to match its theme). So the results page is a **normal, editable tenant page**, not a
|
||||
plugin-owned surface. Its words come from `Messages.site` (the site's bundle first, then this plugin's) for the
|
||||
request locale. **Where results are listed (2.1.0):** each placement has a `results` setting (Site → Content
|
||||
widgets, `widgetSettings` in `plugin.yml`): `auto` (the default) lists them unless the box sits in the **master
|
||||
chrome** (`WidgetView.isChrome()`), so a header or footer box does not repeat the results page's list; `always`
|
||||
and `never` override that. Before 2.1.0 every box on a page opened with `?q=` listed the results.
|
||||
- **Result highlighting (2.1.0)** — the page a result opens highlights the words the search matched there and
|
||||
scrolls to the first visible one. How it travels:
|
||||
1. The engine reports the matched words **as the page writes them** (`SearchHit.terms`, §2): the built-in engine
|
||||
the whole words around each match, `search-lucene` the surface forms its analyzer matched (stemming and typo
|
||||
tolerance included: `maestría` finds `maestrías`).
|
||||
2. Each result link (inline results and the API's `link`) carries them in the fragment:
|
||||
`/mba#rw-hl=maestr%C3%ADas%20maestr%C3%ADa` (`HighlightMarker`). A fragment never reaches the server, so the
|
||||
target page is served and cached exactly as without it.
|
||||
3. `SearchHighlightHead` (a `HeadContributor`) puts one `<script src=".../highlight-loader.js" defer>` on every
|
||||
page of a site with search and `highlight` on. The loader (~500 bytes) does nothing unless the address carries
|
||||
the marker; then it loads `highlight.js`, which highlights every whole-word occurrence (ignoring case) inside
|
||||
`<main id="content">` (else `<main>`, else `<body>`) with the **CSS Custom Highlight API** (no DOM change), at
|
||||
most 200, scrolls to the first visible one, and removes the marker with `history.replaceState`. A
|
||||
`hashchange` re-runs it. It adds `highlight.css` before the site's own stylesheets, so a site restyles it with
|
||||
its own `::highlight(rw-search) { … }`.
|
||||
- **Why an external loader and not an inline script:** the kernel stamps the CSP nonce only on scripts its host
|
||||
allowlist would also run, so an inline script stays blocked under `enforce`. **Cost:** the loader is referenced
|
||||
by every page. A browser keeps it for an hour (`runway.http-cache.plugin-assets`) and then revalidates it
|
||||
against its ETag. Every plugin file URL ends in `?v=<version>` (`SearchConfig.VERSION`), so the next release's
|
||||
files are fetched at once. Turning `highlight` off removes the loader.
|
||||
- **Browsers:** the Highlight API is in Chrome/Edge 105+, Safari 17.2+ and Firefox 140+. Elsewhere nothing is
|
||||
highlighted and the marker is still removed.
|
||||
- **Limits:** a match split across inline elements (`<b>mae</b>stría`) is not found. Text outside the content
|
||||
slot is not highlighted, by design: with no `#content` or `<main>`, the script searches `<body>` but skips
|
||||
`<header>`, `<nav>`, `<footer>` and `<aside>`, so it never scrolls to a menu item. Java lowercases the Turkish
|
||||
capital `İ` to `i` plus a combining dot, which a browser never matches case-insensitively, so the script lets
|
||||
every `i` match `İ` (`src/test/js/highlight-pattern.js`).
|
||||
- **JSON API** — `GET /search/api?q=…` (`EndpointContributor`, tenant realm, `noindex`) returns the results as
|
||||
JSON (`{query,count,results:[{url,title,snippet,score,link,terms}]}`) for a site's own scripts (e.g. an
|
||||
autocomplete box). `link` (2.1.0) is the URL with the highlight marker (the plain URL when `highlight` is off);
|
||||
`terms` the matched words as plain text.
|
||||
Rate-limited per client (`SearchRateLimiter`, §4). Every string is JSON-escaped and the angle brackets are
|
||||
unicode-escaped so a payload embedded in an HTML `<script>` can't break out. (The HTML results rendering lives
|
||||
in the widget; rendered during page render it carries no search-specific limiter — the kernel's edge
|
||||
protection and `resultLimit` bound a flood — while the JSON API keeps its dedicated limiter.)
|
||||
- **The corpus** — `SearchCorpus` (§2): the kernel's content listing (`ContentCatalogView.entries`: every
|
||||
**published** real page and every content source's item — blog entries, … — re-filtered fail-closed by the
|
||||
host, with host-computed URLs) **minus the site's `exclude` list and its results page** (the page at
|
||||
`resultsPath`, in all its languages; since 2.1.1, because it matched the subjects it describes and was listed
|
||||
among its own results). Every engine builds from it, so the exclusion rule lives in one place.
|
||||
- **Built-in engine** — `SimpleSearchEngine`, a dependency-free full-text matcher. Since 2.2.0, **one document per
|
||||
corpus entry and language it exists in**: localized **title**, **description**, and the plain-text **body**
|
||||
(`SearchCorpus.indexableText` for that language — the page as rendered there, bundle strings included —
|
||||
reduced by `HtmlText`), linked at `CatalogEntry.pathFor` that language — the item's real address there.
|
||||
A query searches the documents of its own language (`SearchQuery.locale()`: the results page's
|
||||
language, or the API's `?lang=`) plus, for an item that does not exist in that language, the item's
|
||||
**primary-locale** document (the site's default language when the item exists in it, else its first language),
|
||||
so a page in one language only is still found from every other; a language the site does not speak searches the
|
||||
site default's documents. (Before 2.2.0 only the primary-locale document existed.) It holds a small
|
||||
per-site index (at most 512 sites, least recently used dropped first), **dropped the moment anything that may
|
||||
reshape the corpus changes** (§3), with the freshness TTL kept as the backstop for changes nobody announces (a
|
||||
file edited by hand). Always available; no external index.
|
||||
- **Configurable ranking** (per-site): `titleWeight` (8), `descriptionWeight` (4), `bodyWeight` (1 per
|
||||
occurrence, capped at 20 occurrences per term), plus flat bonuses for containing **all** terms
|
||||
(`allTermsBonus`) and the whole query as a **phrase** in the title/body (`phraseTitleBonus`/`phraseBodyBonus`).
|
||||
All data — a site tunes ranking with no code change.
|
||||
- **Highlighted snippets** built by `SearchSnippet` from the body (falling back to the description),
|
||||
honouring the frozen `SearchHit.snippet` contract (see §5).
|
||||
- **Operator maintenance** — three **CSRF-checked `POST`s** reached from buttons on the plugin's settings page,
|
||||
each gated by the `search|settings` control point (`AccessCheck`), fail-closed to `404`, answered in the
|
||||
operator's language (`Messages.console`):
|
||||
- `POST /search/reindex` — rebuilds this site's index on **every** registered engine via the SPI's `reindex`
|
||||
hook (the built-in and any contributed engine alike), reporting the fresh document count of the engine that
|
||||
actually serves the site's queries. The built-in engine first refreshes the kernel's listing
|
||||
(`SearchCorpus.refresh`): the button exists for changes no event announced. The settings page's **Rebuild
|
||||
index** button submits it (the plain-text answer opens in a new tab).
|
||||
- `POST /search/install-page` — installs a first-class, master-wrapped tenant page at `/search` carrying the
|
||||
query-aware search-box widget anchor, through the kernel's `SitePages.install`, which **never overwrites** and
|
||||
follows the site's **editorial level**. The operator is told what happened: *installed at /search*
|
||||
(`PUBLISHED`), *waiting in the review queue* (`PENDING_REVIEW`: a Reviewed site and a user without
|
||||
`APPROVE_PAGES`), *created as a draft because the quality checks blocked publishing* with each blocking
|
||||
finding listed (`DRAFT_BLOCKED`: an Enforced site, or a Reviewed one with approval, whose checks fail), or
|
||||
*already exists at <path>* (`ALREADY_EXISTS`, wherever the page now lives). Once installed it is an ordinary
|
||||
site page — listed under Pages, restyleable, movable — so the operator owns the results page. It is created
|
||||
**`noindex`** — the canonical index opt-*out* for internal search results (thin/duplicate/infinite crawl
|
||||
space); since the page is the operator's own after install, the setting can be flipped in the page meta.
|
||||
- `POST /search/no-results/clear` — forgets the site's recorded no-result terms (below), then `303`s back to
|
||||
the settings page.
|
||||
- **Searches with no results** (since 2.0.0; `NoResultsLog`) — the platform's own content-gap signal: a per-site list of what visitors searched for and did not find, shown on the settings page
|
||||
with a **Clear list** action. Both the widget (inline results) and the JSON API hand a query that found nothing
|
||||
to `NoResultsLog.record`.
|
||||
- **Why it is off by default.** A search term is free text a visitor typed; people search for names, email
|
||||
addresses, order or phone numbers. Recording is therefore an explicit per-site choice (`recordNoResults`,
|
||||
default `false`) rather than something an upgrade turns on silently. When it is on, the list holds **only a
|
||||
normalized term, a count, and a last-seen time** — no IP, no user, no session, no per-search timestamp — and
|
||||
a term that looks like an email address (an `@` followed by a dot) or a phone / ID number (seven or more
|
||||
digits in a run, ignoring spaces, dashes, dots, slashes, parentheses and `+`) is dropped unrecorded. The
|
||||
term never appears in an application log line (a failure logs the site and the exception class only).
|
||||
- **Declared personal data (2.0.0).** `plugin.yml` declares `siteData.personal: [no-results.tsv]`, so a
|
||||
site's **transfer copy** (the one meant for someone outside the organisation) leaves the file out and lists it
|
||||
under `omitted:` in the archive's `manifest.yml`; a **full backup** keeps it. A restored transfer copy simply
|
||||
starts with an empty list.
|
||||
- **Normalization.** Unicode NFC, control/format characters removed, whitespace runs collapsed to one space,
|
||||
trimmed, lower-cased (`Locale.ROOT`), cut at 100 characters without splitting a surrogate pair — so
|
||||
"Opening Hours" and "opening hours" are one entry.
|
||||
- **Bounds.** At most **500** terms per site: admitting a new term to a full list evicts the least frequent one
|
||||
(the longest-unseen among equals), so a flood of one-off junk churns only the bottom and recurring gaps
|
||||
survive. A term not searched for `noResultsRetentionDays` (default 90) drops off listings and the next
|
||||
write. The same term on the same site within one second counts once — a page with a box in the master
|
||||
chrome *and* one in the content renders (and would record) the same empty result twice per request.
|
||||
- **Storage.** In memory per site, loaded lazily from `no-results.tsv` in the plugin's own per-site folder
|
||||
(`PluginSiteFiles`: `sites/<id>/plugins/search/no-results.tsv`); written atomically by
|
||||
a background flush every 30 s when something changed and on shutdown, never synchronously on the public search
|
||||
path. A crash loses at most the last 30 s. On a site lifecycle event that replaces the site wholesale
|
||||
(`RESTORED` / `DELETED`) the in-memory copy is dropped **unwritten**, so the restored file is what is read
|
||||
next and a deleted site's list is never written back (a late write for a missing site folder fails rather than
|
||||
creating it). A file over 512 KiB is ignored rather than read. A file that **cannot be read** (an I/O error) is
|
||||
never overwritten: the site's list stays unloaded — nothing is recorded for it — until a read succeeds.
|
||||
- **What it does not see.** Searches served from an engine that returns results are not recorded; a site whose
|
||||
search is disabled records nothing; a search box rendered from a cached page response (if a proxy caches
|
||||
`?q=` pages) never reaches the plugin.
|
||||
|
||||
## 2. The plugin's own SPI (`mx.quest.search.spi`)
|
||||
|
||||
```java
|
||||
public interface SearchCorpus { // since 2.0.0 — one bean, `searchCorpus`, injected by type
|
||||
List<CatalogEntry> corpus(String siteId); // the kernel's listing minus the site's `exclude` list
|
||||
String indexableText(String siteId, CatalogEntry entry, Locale locale); // "" for an excluded entry
|
||||
void refresh(String siteId); // drop the kernel's cached listing (manual reindex)
|
||||
}
|
||||
|
||||
public interface SiteSearchEngine { // unchanged since 1.2.0
|
||||
String key(); // stable, namespaced, e.g. "search/simple"
|
||||
List<SearchHit> search(SearchQuery query); // best-first, ≤ query.limit(); empty = no matches
|
||||
default int priority() { return 0; } // higher wins
|
||||
default boolean available(String siteId) { return true; } // false ⇒ fall back to the next engine
|
||||
default int reindex(String siteId) { return 0; } // rebuild derived state NOW; returns the fresh doc count
|
||||
}
|
||||
record SearchQuery(String siteId, String text, Locale locale, int limit) {}
|
||||
record SearchHit(String url, String title, String snippet, double score, List<String> terms) {
|
||||
SearchHit(String url, String title, String snippet, double score) // the 2.0.0 form: no terms
|
||||
}
|
||||
```
|
||||
|
||||
**Why `SearchCorpus` exists.** Before 2.0.0, `search-lucene` read the kernel's
|
||||
`ContentCatalog` and **this plugin's settings** (`SitePluginConfigService.config(site, "search")`) to apply the
|
||||
`exclude` list itself — host linkage, and a cross-plugin settings read the service tier forbids
|
||||
(`PluginSettings` only ever returns the *calling* plugin's settings). Now `search` reads its own settings and
|
||||
publishes the filtered corpus; an engine never touches either.
|
||||
|
||||
- **Exclusion rule.** An entry is left out when its **own id** (`entry.ref().id()`: a page's slug, a content
|
||||
source's item id — never the composite `source:id`) equals, ignoring case, one of the `exclude` values; a leading
|
||||
`/` and blanks around a value are ignored. A YAML list or a comma/newline-separated string.
|
||||
- **Freshness.** Nothing is cached on the plugin side: every call reads the kernel's listing (cached per site by the
|
||||
kernel, evicted by every change that can reshape it) and the current settings. An engine with an index of its own
|
||||
drops it from a `SiteEventListener.onCatalogChanged` callback for **every** cause — a page write, a content
|
||||
change, a site lifecycle event, and any plugin's settings save (this plugin's `exclude` list included).
|
||||
- **Rules.** Every method takes a site id; an unsafe id throws `IllegalArgumentException`, an unknown site answers
|
||||
empty or `""`; thread-safe; never `null`.
|
||||
|
||||
Both interfaces are **binary API**: they evolve by adding `default` methods only — `reindex` (added in 1.2.0)
|
||||
defaults to a no-op returning `0`, so an engine compiled against an earlier SPI keeps loading unchanged.
|
||||
`SiteSearchEngine`, `SearchQuery` and `SearchHit` did not change in 2.0.0: an engine built against 1.x links and
|
||||
behaves the same. **2.1.0 adds `SearchHit.terms`** — the words the engine matched, as the item writes them;
|
||||
lowercase, distinct, at most 20 of at most 64 characters (the record normalizes them). The four-argument
|
||||
constructor stays, so an engine built before 2.1.0 still links and its hits simply carry no words (no highlight on
|
||||
the target page). An engine that fills `terms` calls the five-argument constructor and must therefore declare
|
||||
`requires: search >= 2.1.0` (`search-lucene` 3.1.0 does).
|
||||
|
||||
The `SearchEndpoint` and the widget inject `List<SiteSearchEngine>` and, per request, select the
|
||||
highest-`priority()` engine whose `available(siteId)` is true. So:
|
||||
|
||||
- **Installing `search-lucene`** (which registers an engine at priority 100 and is available once its index
|
||||
exists) **transparently upgrades** search — the widget and endpoint are untouched.
|
||||
- If the Lucene index isn't built yet (`available()` false), the surface **falls back** to the built-in engine —
|
||||
a not-yet-built index never breaks search.
|
||||
|
||||
`search-lucene` compiles against this plugin's jar as a `provided` dependency and declares `requires: search`; at
|
||||
runtime both plugin jars share one classloader, so the SPI types have one `Class` identity.
|
||||
|
||||
## 3. Freshness: the plugin's change listener
|
||||
|
||||
`SearchSiteEvents` is the plugin's one `SiteEventListener` (phase `CONSUMER`: it reads the listing, contributes
|
||||
none). The kernel delivers it **after** every kernel cache the change affects has been evicted and after every
|
||||
content source dropped its own state, and never while the host holds a write lock.
|
||||
|
||||
| Callback | What the plugin does |
|
||||
|---|---|
|
||||
| `onCatalogChanged` (every cause: `PAGE`, `CONTENT`, `SITE`, `SETTINGS`) | drops the built-in engine's index for the site; the next query rebuilds from the new state |
|
||||
| `onSiteLifecycle` with `wholesale()` (`RESTORED`, `DELETED`) | `NoResultsLog` forgets the site's in-memory list unwritten |
|
||||
|
||||
Both run on every node, for local and replayed changes alike — they only drop local state. A query that was
|
||||
building the index while a change arrived (another thread) answers its own caller but is **not cached**, so a
|
||||
build that may have read the old state never outlives the change.
|
||||
|
||||
## 4. Settings
|
||||
|
||||
### App-level (`settings`, superadmin, applied on restart — platform concerns only)
|
||||
|
||||
Bound from `external/plugin-settings/search.yml` (prefix `runway.plugin.search`) into `SearchProperties`, through
|
||||
the `@ConfigurationProperties` on the `searchProperties` `@Bean` (not `@EnableConfigurationProperties`, whose
|
||||
generated bean name would break the plugin bean-name rule).
|
||||
|
||||
| Key | Type | Default | Effect |
|
||||
|---|---|---|---|
|
||||
| `refresh-minutes` | int (1–1440) | `60` | Freshness TTL of a built-in per-site index before the next query rebuilds it. Changes the kernel announces are reflected immediately (§3); the TTL re-captures what nobody announces. |
|
||||
| `rate-limit.per-ip-per-minute` | int (0 = off) | `30` | Per-client query ceiling on the JSON API, per minute. |
|
||||
| `rate-limit.per-ip-per-hour` | int (0 = off) | `600` | Per-client query ceiling on the JSON API, per hour. |
|
||||
|
||||
These are deliberately **not** per-tenant — a tenant must not set a global timer or an abuse limit.
|
||||
|
||||
### Per-tenant (`siteSettings`, applied immediately)
|
||||
|
||||
| Key | Type | Default | Effect |
|
||||
|---|---|---|---|
|
||||
| `enabled` | boolean | `true` | Off ⇒ the box (and its inline results) render nothing and the JSON API 404s (opt out without uninstalling). |
|
||||
| `resultLimit` | int (1–100) | `20` | Max hits shown inline / returned by the API. |
|
||||
| `resultsPath` | string | `/search` | Where the box submits `?q=` — the results page carrying this widget, by any of its addresses; set it if you move/rename that page. Since 2.2.0 a box on a localized page submits to that page's address in the box's language (`/es/buscar` from a Spanish page), else to this value as written. |
|
||||
| `placeholder` | string | — | The search box's greyed prompt (falls back to a localized default). |
|
||||
| `exclude` | list | — | Ids kept out of every engine's corpus: page slugs and content-source item ids. |
|
||||
| `snippetLength` | int (40–400) | `160` | Characters of context per result snippet. |
|
||||
| `highlight` | boolean | `true` | Result links carry the matched words and the site's pages highlight them (§1, 2.1.0). Off: plain links, no loader on the pages. |
|
||||
| `titleWeight` / `descriptionWeight` / `bodyWeight` | int | `8` / `4` / `1` | Ranking weight per field. |
|
||||
| `allTermsBonus` / `phraseTitleBonus` / `phraseBodyBonus` | int | `1000` / `400` / `300` | Flat ranking bonuses. |
|
||||
| `recordNoResults` | boolean | `false` | Keep the "Searches with no results" list (§1). Off by default because terms can be personal data. |
|
||||
| `noResultsRetentionDays` | int (1–365) | `90` | A recorded term nobody searched for in this many days drops off the list. |
|
||||
|
||||
Read live through the kernel's `PluginSettings.site(siteId)` (bound to this plugin by its jar): the stored value,
|
||||
else the descriptor default, else the code fallback — and every code fallback in `SearchSiteConfig` equals its
|
||||
descriptor default (`SearchConfigTest` holds them equal). The `settings` control point gates the editor **and**
|
||||
the operator maintenance actions.
|
||||
|
||||
## 5. Boundaries & safety
|
||||
|
||||
- **Every state change is a CSRF-checked `POST`.** Reindex, install-page and clear change state (an index is
|
||||
rebuilt, a page is created, data is deleted), so each is an ordinary, non-anonymous `POST` route. The plugin
|
||||
endpoint is servlet-free, but it is dispatched *inside* the tenant security chain, whose CSRF filter checks the
|
||||
`_csrf` field the admin fragment's forms render from the console page (`${_csrf}`). A `GET` on those paths
|
||||
matches no route (the kernel answers `404`), so another web site cannot trigger them through a signed-in
|
||||
operator's browser with a link or an `<img>` — which 1.x's `GET /search/reindex` and `GET /search/install-page`
|
||||
allowed. `scripts/verify-against-host.sh` proves it live: `GET` 404, no token 403, forged token 403, an
|
||||
anonymous caller with a valid token 404 (the permission check), the console's token accepted. The only `GET`s are
|
||||
the JSON API (a read) and the box's own form (a `GET` to the results page — an ordinary tenant page).
|
||||
- **No-result terms are visitor text.** The admin card binds them with `th:text` only; they never reach a log
|
||||
line; recording is opt-in per site; the file is declared personal data (§1).
|
||||
- **The `snippet` safety contract (frozen).** A `SearchHit.snippet` is **pre-escaped, highlight-bearing HTML**:
|
||||
the engine HTML-escapes every character from the page and leaves `<mark>…</mark>` — and nothing else — as raw
|
||||
markup around the matched terms. The widget therefore renders the snippet as **raw HTML** (so the
|
||||
highlight shows as emphasis, not literal `<mark>`), which is XSS-safe precisely because escaping happened
|
||||
at the engine — a crafted page title or body cannot forge a tag. `SearchSnippet` does escape-then-mark; both the
|
||||
built-in engine and `search-lucene` honour the contract, so the one raw-render serves both.
|
||||
- **Output safety.** The query, page titles, and every non-snippet value are escaped by `Html.escape`; the JSON
|
||||
API escapes strings and unicode-escapes angle brackets. The JSON API is `noindex`; the results page is a normal
|
||||
tenant page **installed with `noindex` on**, and the operator owns its page meta and can flip it.
|
||||
- **Abuse guard.** `SearchRateLimiter` caps the **JSON API** per client with two fixed windows (a minute and an
|
||||
hour, each starting at the client's first query in it); over the ceiling ⇒ `429` with
|
||||
`{"error":"rate_limited"}`. A blank query is not counted. **The key is `RouteRequest.clientIp()`** — the client
|
||||
address after the kernel's **trusted-proxy gate**: a forwarded header counts only when the
|
||||
immediate peer is a configured trusted proxy. 1.x keyed on the first `X-Forwarded-For` hop it read itself, so a
|
||||
visitor could send a made-up header per request and never be limited. A request with no client IP shares one
|
||||
`shared` bucket rather than escaping. The table holds at most 50,000 clients: when full, clients whose windows
|
||||
have expired are dropped first, and if all are active the table restarts (fails open — this is a courtesy limit;
|
||||
the kernel edge guard is the platform's DoS floor beneath it, and also bounds the inline results the widget
|
||||
renders during page render).
|
||||
- **No host internals.** The compiled classes reference nothing under `mx.quest.runway` but `mx.quest.runway.spi`
|
||||
(`SearchConfigTest` scans the bytecode; the kernel's load-time scanner reports nothing), and nothing of Caffeine
|
||||
either: it is a kernel implementation detail, not one of the platform libraries a plugin may rely on.
|
||||
- **Isolation.** Every surface is scoped to the bound tenancy (`req.site().id()` / `view.site().id()`); the index
|
||||
is keyed per site, so one tenant never sees another's content; the plugin's files are confined by the kernel to
|
||||
`sites/<id>/plugins/search/`.
|
||||
|
||||
## 6. Inventory
|
||||
|
||||
| Piece | Type | File |
|
||||
|---|---|---|
|
||||
| `mainClass` `@Configuration` | `SearchConfig` | wires every bean explicitly over SPI services; every bean name starts with `search` |
|
||||
| **Published SPI** | `spi/SearchCorpus`, `spi/SiteSearchEngine` + `SearchQuery` + `SearchHit` | the corpus and the extension point |
|
||||
| Corpus | `SiteSearchCorpus` | `ContentCatalogView` minus the `exclude` list (`PluginSettings`) |
|
||||
| Built-in engine | `SimpleSearchEngine` | full-text over title/description/body, bounded per-site index cache |
|
||||
| Change listener | `SearchSiteEvents` (`SiteEventListener`, `CONSUMER`) | drops the index on every catalog change; forgets the no-result list on a wholesale lifecycle event |
|
||||
| Body extraction | `HtmlText` | HTML → plain text for indexing (strips script/style/comments/tags) |
|
||||
| Snippet builder | `SearchSnippet` | escape-then-mark; honours the frozen snippet contract |
|
||||
| Indexed document | `SearchDocument` | one per item: display + pre-lowercased match fields |
|
||||
| Request endpoint | `SearchEndpoint` (`EndpointContributor`) | `GET /search/api`; `POST /search/reindex`, `/search/install-page`, `/search/no-results/clear` (no `/search` page) |
|
||||
| No-result terms | `NoResultsLog` | opt-in per-site content-gap list over `PluginSiteFiles` (`no-results.tsv`, declared personal) |
|
||||
| Rate limiter | `SearchRateLimiter` + `SearchClientId` | per-client two-window courtesy cap (JSON API), keyed on the gated client IP |
|
||||
| Query-aware search box | `SearchBoxWidget` (`ContentWidget` `search`) | embeddable GET form + inline results when `?q=` (per-placement `results`) |
|
||||
| Result highlighting | `MatchedWords`, `HighlightMarker`, `SearchHighlightHead` (`HeadContributor`), `static/highlight-loader.js`, `static/highlight.js`, `static/highlight.css` | the matched words, the `#rw-hl=` link marker, the page script |
|
||||
| App settings | `SearchProperties` | `runway.plugin.search.*` (refresh + rate-limit) |
|
||||
| Per-site settings | `SearchSiteConfig` | typed accessors over `SettingsView` |
|
||||
| Console model | `SearchAdminModel` + `templates/` | dashboard card + admin status (searchable items = the corpus size) + the forms |
|
||||
| i18n (EN/ES), static (help + CSS) | `i18n/`, `static/` | console + public strings |
|
||||
|
||||
## 7. Verify
|
||||
|
||||
`scripts/verify-against-host.sh` builds the plugin offline (never `mvn install`), drops it into a throwaway
|
||||
deployment (`VERIFY_TMPDIR`), boots the **packaged** host (`HOST_JAR`, else the host checkout's jar matching its pom
|
||||
version) in ACTIVE mode via the first-run wizard, with three sites (Advisory, Enforced, Reviewed) and loopback made
|
||||
an **untrusted** peer, and proves the 2.1.1 contract: zero host-linkage and bean-name/surface warnings in the boot
|
||||
log; the app settings bind; the JSON API serves and there is no `/search` page until one is installed; the three
|
||||
operator actions are CSRF-checked POSTs (GET 404, no token 403, forged 403, anonymous-with-token 404) offered as POST
|
||||
forms by the console; reindex reports a count; the starter page installs on all three editorial levels, renders
|
||||
results inline and is `noindex`, and a second install changes nothing; the `exclude` list applies on the save; the
|
||||
no-result list is off by default, records when on (never an email-like term), is flushed to the plugin's file,
|
||||
carried by a full backup and **omitted (and listed) by a transfer copy**, and cleared only by the CSRF-checked POST;
|
||||
made-up `X-Forwarded-For` headers do not evade the API's per-client ceiling while another address keeps its own
|
||||
budget; result links (page and API) carry `#rw-hl=<words>`, every page carries the loader script stamped with the
|
||||
nonce its CSP allows, and the loader, `highlight.js` and `highlight.css` are served. `VERIFY_LOG_DIR` keeps the host logs, the install answers and both backup manifests. Never
|
||||
`spring-boot:run`.
|
||||
|
||||
Unit tests run on `runway-spi-testkit` (`FakePluginSettings`, `TempDirSiteFiles`, `FakeSiteServices`,
|
||||
`FakeContentCatalog`, `EventDispatch`): `SearchConfigTest` (wiring over SPI services only, bean names, template
|
||||
beans, descriptor floor/version/personal data, code fallbacks = descriptor defaults, bundles, the bytecode scan),
|
||||
`SearchAdminTemplateTest` (every operator action is a POST form carrying the token; no link), `SiteSearchCorpusTest`,
|
||||
`SimpleSearchEngineTest` (matching, ranking, exclusion, the primary-locale URL, every change cause dropping the
|
||||
index, the raced build not kept, the bounded cache), `SearchEndpointTest` (routes, JSON API, rate-limit key, gated
|
||||
reindex and install with every outcome), `SearchBoxWidgetTest`, `SearchAdminModelTest`, `NoResultsLogTest`,
|
||||
`NoResultsRecordingTest`, `SearchRateLimiterTest`, `SearchSnippetTest`, `HtmlTextTest`, `HighlightTest` (matched words, the link marker, the
|
||||
loader, the JSON fields, and the page script agreeing with the Java side) — 155 in all. The page script itself was
|
||||
checked in Chrome under an enforcing CSP: highlights on arrival and on `hashchange`, the marker removed
|
||||
with the query kept, no console error.
|
||||
@@ -0,0 +1,92 @@
|
||||
# Runway Search plugin — English strings. Appended LAST to the operator-console and every per-site message
|
||||
# source (may ADD keys, never override a core key). Console labels resolve automatically; public-facing strings
|
||||
# (search.box.*, search.results.*, search.page.title) are resolved with Messages.site for the site and the request
|
||||
# locale; the operator actions' answers with Messages.console, in the operator's language.
|
||||
|
||||
# Grantable permission (permissions matrix label)
|
||||
search.perm.settings=Configure search
|
||||
|
||||
# App-level settings form labels (superadmin; platform concerns)
|
||||
search.set.refresh=Index freshness (minutes)
|
||||
search.set.perMinute=Max searches per IP per minute (0 = no limit)
|
||||
search.set.perHour=Max searches per IP per hour (0 = no limit)
|
||||
|
||||
# Per-tenant settings form labels
|
||||
search.set.enabled=Enable search
|
||||
search.set.resultLimit=Maximum results
|
||||
search.set.resultsPath=Results page path
|
||||
search.set.placeholder=Search box placeholder
|
||||
search.set.exclude=Excluded content (one page slug or entry id per line)
|
||||
search.set.snippetLength=Snippet length (characters)
|
||||
search.set.highlight=Highlight the matches on the page a result opens
|
||||
search.set.titleWeight=Title match weight
|
||||
search.set.descriptionWeight=Description match weight
|
||||
search.set.bodyWeight=Body match weight (per occurrence)
|
||||
search.set.allTermsBonus=All-terms bonus
|
||||
search.set.phraseTitleBonus=Title phrase bonus
|
||||
search.set.phraseBodyBonus=Body phrase bonus
|
||||
search.set.recordNoResults=Record searches with no results
|
||||
search.set.noResultsRetention=Keep unrepeated terms for (days)
|
||||
search.help.recordNoResults=Lists what visitors searched for and did not find, so you can see which content is missing. Off by default: search terms are typed by visitors and can contain personal data. Only the term, how often, and when it was last searched are kept — never an IP address or a user. Terms that look like an email address or a phone number are not kept.
|
||||
search.help.highlight=A result link carries the words the search matched, and the page it opens highlights them and scrolls to the first one. The words travel after the # of the address, so they never reach the server, and they are removed from the address once the page has read them. Off: plain result links, and the small script that does this is not added to your pages.
|
||||
search.help.noResultsRetention=A term nobody has searched for in this many days is dropped from the list.
|
||||
|
||||
# Dashboard card
|
||||
search.card.title=Search
|
||||
search.card.pages=searchable items
|
||||
|
||||
# Admin status fragment
|
||||
search.admin.title=Search status
|
||||
search.admin.enabled=Enabled
|
||||
search.admin.engine=Active engine
|
||||
search.admin.pages=Searchable items
|
||||
search.admin.note=Add a search box to any page with a data-widget anchor; when a page is opened with ?q= it shows the results inline.
|
||||
search.admin.help=Search help & reference
|
||||
|
||||
# "Search page" install card (admin fragment)
|
||||
search.page.card.desc=Install a ready-made search results page carrying the box. It becomes a normal site page — edit, restyle, move or rename it from Pages.
|
||||
search.page.card.install=Install search page
|
||||
search.page.card.install.tip=Seed a ready-made, editable search results page (idempotent — it never overwrites an existing page)
|
||||
search.page.card.badge=Installed
|
||||
search.page.card.at=Installed at
|
||||
search.page.card.edit=— edit it under Pages.
|
||||
|
||||
# Shared on/off
|
||||
search.on=on
|
||||
search.off=off
|
||||
|
||||
# Public-facing (search box widget + /search results page)
|
||||
search.box.placeholder=Search…
|
||||
search.box.submit=Search
|
||||
search.results.heading=Search
|
||||
search.results.none=No results for
|
||||
search.results.count=result(s) for
|
||||
search.rate.limited=Too many searches — please try again shortly.
|
||||
|
||||
# Maintenance actions + installed page (operator-only)
|
||||
search.reindex.done=Search index rebuilt.
|
||||
search.reindex.desc=Changed files outside the console? Rebuild the index now.
|
||||
search.reindex.button=Rebuild index
|
||||
search.reindex.tip=Re-read every page and content item and rebuild the search index of every engine now
|
||||
search.page.title=Search
|
||||
search.page.installed=Search page installed at
|
||||
search.page.pending=The search page was created and is waiting in the review queue:
|
||||
search.page.blocked=The search page was created as a draft because the quality checks blocked publishing; fix it in the page editor:
|
||||
search.page.exists=A search page already exists at
|
||||
search.page.failed=Could not install the search page.
|
||||
search.page.other=The search page install finished:
|
||||
|
||||
# "Searches with no results" card (admin fragment)
|
||||
search.noresults.title=Searches with no results
|
||||
search.noresults.intro=What visitors searched for on this site and did not find — candidates for new pages, better titles or descriptions, or a redirect.
|
||||
search.noresults.off=Recording is off for this site. Turn on "Record searches with no results" above to start the list.
|
||||
search.noresults.col.term=Search term
|
||||
search.noresults.col.count=Searches
|
||||
search.noresults.col.lastSeen=Last searched
|
||||
search.noresults.empty=No searches without results recorded yet.
|
||||
search.noresults.retention=Terms nobody searched for in {0} days drop off the list; at most {1} terms are kept, the most frequent first.
|
||||
search.noresults.clear=Clear list
|
||||
search.noresults.clear.tip=Forget every recorded term for this site (it cannot be undone)
|
||||
search.noresults.clearFailed=Could not clear the list of searches with no results.
|
||||
search.widget.results=List the results here
|
||||
search.widget.help.results=What this box shows when its page is opened with a search (?q=). auto: the results, unless the box is in the master template (a header or footer box), so the results page does not list them twice. always: the results, wherever the box is. never: only the box.
|
||||
@@ -0,0 +1,89 @@
|
||||
# Runway Search plugin — cadenas en español.
|
||||
|
||||
# Permiso otorgable (etiqueta de la matriz de permisos)
|
||||
search.perm.settings=Configurar búsqueda
|
||||
|
||||
# Etiquetas de configuración a nivel de aplicación (superadmin; asuntos de plataforma)
|
||||
search.set.refresh=Frescura del índice (minutos)
|
||||
search.set.perMinute=Máx. búsquedas por IP por minuto (0 = sin límite)
|
||||
search.set.perHour=Máx. búsquedas por IP por hora (0 = sin límite)
|
||||
|
||||
# Etiquetas del formulario de configuración por sitio
|
||||
search.set.enabled=Activar búsqueda
|
||||
search.set.resultLimit=Máximo de resultados
|
||||
search.set.resultsPath=Ruta de la página de resultados
|
||||
search.set.placeholder=Marcador del cuadro de búsqueda
|
||||
search.set.exclude=Contenido excluido (un slug de página o id de entrada por línea)
|
||||
search.set.highlight=Resaltar las coincidencias en la página que abre un resultado
|
||||
search.set.snippetLength=Longitud del fragmento (caracteres)
|
||||
search.set.titleWeight=Peso de coincidencia en el título
|
||||
search.set.descriptionWeight=Peso de coincidencia en la descripción
|
||||
search.set.bodyWeight=Peso de coincidencia en el cuerpo (por aparición)
|
||||
search.set.allTermsBonus=Bonificación por todos los términos
|
||||
search.set.phraseTitleBonus=Bonificación por frase en el título
|
||||
search.set.phraseBodyBonus=Bonificación por frase en el cuerpo
|
||||
search.set.recordNoResults=Registrar búsquedas sin resultados
|
||||
search.set.noResultsRetention=Conservar términos no repetidos durante (días)
|
||||
search.help.recordNoResults=Muestra lo que los visitantes buscaron y no encontraron, para ver qué contenido falta. Desactivado por omisión: los términos los escriben los visitantes y pueden contener datos personales. Solo se guarda el término, cuántas veces y cuándo se buscó por última vez — nunca una dirección IP ni un usuario. Los términos que parecen un correo electrónico o un número de teléfono no se guardan.
|
||||
search.help.highlight=El enlace de cada resultado lleva las palabras que encontró la búsqueda, y la página que abre las resalta y se desplaza a la primera. Las palabras van después del # de la dirección, así que nunca llegan al servidor, y se quitan de la dirección en cuanto la página las lee. Desactivado: enlaces simples, y el pequeño script que hace esto no se agrega a tus páginas.
|
||||
search.help.noResultsRetention=Un término que nadie ha buscado en estos días se quita de la lista.
|
||||
|
||||
# Tarjeta del panel
|
||||
search.card.title=Búsqueda
|
||||
search.card.pages=elementos indexables
|
||||
|
||||
# Fragmento de estado (admin)
|
||||
search.admin.title=Estado de la búsqueda
|
||||
search.admin.enabled=Activada
|
||||
search.admin.engine=Motor activo
|
||||
search.admin.pages=Elementos indexables
|
||||
search.admin.note=Añade un cuadro de búsqueda a cualquier página con un ancla data-widget; cuando la página se abre con ?q= muestra los resultados en línea.
|
||||
search.admin.help=Ayuda y referencia de búsqueda
|
||||
|
||||
# Tarjeta de instalación de la «Página de búsqueda» (fragmento admin)
|
||||
search.page.card.desc=Instala una página de resultados de búsqueda lista para usar con el cuadro. Se convierte en una página normal del sitio: edítala, cámbiale el estilo, muévela o renómbrala desde Páginas.
|
||||
search.page.card.install=Instalar página de búsqueda
|
||||
search.page.card.install.tip=Crea una página de resultados de búsqueda lista y editable (idempotente: nunca sobrescribe una página existente)
|
||||
search.page.card.badge=Instalada
|
||||
search.page.card.at=Instalada en
|
||||
search.page.card.edit=— edítala desde Páginas.
|
||||
|
||||
# on/off compartido
|
||||
search.on=activada
|
||||
search.off=desactivada
|
||||
|
||||
# De cara al público (widget de cuadro de búsqueda + página de resultados /search)
|
||||
search.box.placeholder=Buscar…
|
||||
search.box.submit=Buscar
|
||||
search.results.heading=Búsqueda
|
||||
search.results.none=Sin resultados para
|
||||
search.results.count=resultado(s) para
|
||||
search.rate.limited=Demasiadas búsquedas — inténtalo de nuevo en un momento.
|
||||
|
||||
# Acciones de mantenimiento + página instalada (solo operador)
|
||||
search.reindex.done=Índice de búsqueda reconstruido.
|
||||
search.reindex.desc=¿Cambiaste archivos fuera de la consola? Reconstruye el índice ahora.
|
||||
search.reindex.button=Reconstruir índice
|
||||
search.reindex.tip=Volver a leer cada página y contenido y reconstruir ahora el índice de búsqueda de todos los motores
|
||||
search.page.title=Búsqueda
|
||||
search.page.installed=Página de búsqueda instalada en
|
||||
search.page.pending=La página de búsqueda se creó y está esperando en la cola de revisión:
|
||||
search.page.blocked=La página de búsqueda se creó como borrador porque los controles de calidad bloquearon la publicación; corrígela en el editor de páginas:
|
||||
search.page.exists=Ya existe una página de búsqueda en
|
||||
search.page.failed=No se pudo instalar la página de búsqueda.
|
||||
search.page.other=La instalación de la página de búsqueda terminó:
|
||||
|
||||
# Tarjeta "Búsquedas sin resultados" (fragmento de administración)
|
||||
search.noresults.title=Búsquedas sin resultados
|
||||
search.noresults.intro=Lo que los visitantes buscaron en este sitio y no encontraron — candidatos para nuevas páginas, mejores títulos o descripciones, o una redirección.
|
||||
search.noresults.off=El registro está desactivado para este sitio. Active "Registrar búsquedas sin resultados" arriba para empezar la lista.
|
||||
search.noresults.col.term=Término buscado
|
||||
search.noresults.col.count=Búsquedas
|
||||
search.noresults.col.lastSeen=Última búsqueda
|
||||
search.noresults.empty=Aún no hay búsquedas sin resultados registradas.
|
||||
search.noresults.retention=Los términos que nadie buscó en {0} días salen de la lista; se conservan como máximo {1} términos, los más frecuentes primero.
|
||||
search.noresults.clear=Vaciar lista
|
||||
search.noresults.clear.tip=Olvidar todos los términos registrados de este sitio (no se puede deshacer)
|
||||
search.noresults.clearFailed=No se pudo vaciar la lista de búsquedas sin resultados.
|
||||
search.widget.results=Mostrar aquí los resultados
|
||||
search.widget.help.results=Lo que muestra este cuadro cuando su página se abre con una búsqueda (?q=). auto: los resultados, salvo que el cuadro esté en la plantilla maestra (un cuadro del encabezado o del pie), para que la página de resultados no los muestre dos veces. always: los resultados, esté donde esté el cuadro. never: solo el cuadro.
|
||||
@@ -0,0 +1,94 @@
|
||||
# =============================================================================
|
||||
# Runway Search Plugin — descriptor
|
||||
# On-site search: a built-in full-text engine over page title/description/body,
|
||||
# delivered as a query-aware CONTENT WIDGET (data-widget="search/box") on a
|
||||
# normal editable page — it renders the box, and when the page is opened with
|
||||
# ?q= it renders the results inline. The operator installs a ready-made,
|
||||
# editable results page in one click from the settings (then it behaves like
|
||||
# any site page). The endpoint owns only GET /search/api (JSON) and three
|
||||
# operator-gated, CSRF-checked POSTs: /search/reindex, /search/install-page and
|
||||
# /search/no-results/clear. Publishes its own SPI — the SearchCorpus every engine
|
||||
# builds from, and the SiteSearchEngine a companion plugin (search-lucene) can
|
||||
# implement to upgrade the engine. Links ONLY the Runway SPI (service tier).
|
||||
# The install folder name MUST equal this `id`: external/plugins/search/.
|
||||
# =============================================================================
|
||||
id: search
|
||||
name: Search
|
||||
version: 2.3.0
|
||||
|
||||
# The @Configuration registered into the host context before refresh. Its package (mx.quest.search) lives
|
||||
# OUTSIDE mx.quest.runway so the host never double-scans it. Beans are wired EXPLICITLY (no @ComponentScan).
|
||||
mainClass: mx.quest.search.SearchConfig
|
||||
|
||||
# Built against the SPI service tier: PluginSettings, PluginSiteFiles, Sites, Messages, AccessCheck, SitePages,
|
||||
# ContentCatalogView and SiteEventListener. A kernel below SPI 1.0.0 BLOCKS this plugin at startup with a reason.
|
||||
requiresSpi: ">=1.0.0"
|
||||
|
||||
# --- Personal data ---------------------------------------------------------------------------------------
|
||||
# no-results.tsv holds search terms visitors typed (recorded only when a site opts in). A TRANSFER copy of a
|
||||
# site (the one meant for someone outside the organisation) leaves it out and lists it in the archive's
|
||||
# manifest; a FULL backup keeps it. Path relative to sites/<id>/plugins/search/.
|
||||
siteData:
|
||||
personal:
|
||||
- no-results.tsv
|
||||
|
||||
# No hard dependency (always loads); NOT essential. Adds a public /search surface + an embeddable box, backed by
|
||||
# a pluggable engine. The built-in engine needs no external index, so search works the moment it is installed.
|
||||
|
||||
# --- Grantable control-point permission -----------------------------------------------------------------
|
||||
# `settings` is the reserved id that gates this plugin's per-tenant config editor AND the operator-only
|
||||
# maintenance actions (reindex, install-page, clear the no-result list). defaultRoles is EMPTY: the control point
|
||||
# starts ungranted — admins hold it via the wildcard tier; a tenant superadmin grants it to OPERATOR or a custom role.
|
||||
permissions:
|
||||
- { id: settings, realm: tenant, label: search.perm.settings, defaultRoles: [] }
|
||||
|
||||
# --- App-level settings (superadmin; PLATFORM concerns only) ----------------------------------------------
|
||||
# Over external/plugin-settings/search.yml, bound to runway.plugin.search.* into SearchProperties; applied
|
||||
# on restart. Only platform knobs live here — the index freshness timer and the per-IP abuse guard. Every
|
||||
# tenant-owned knob (enable, ranking, exclusions, snippet) is per-site below (a tenant must not set a global
|
||||
# timer or an abuse limit).
|
||||
settings:
|
||||
- { key: refresh-minutes, type: int, default: 60, range: "1..1440", label: search.set.refresh }
|
||||
- { key: rate-limit.per-ip-per-minute, type: int, default: 30, range: "0..100000", label: search.set.perMinute }
|
||||
- { key: rate-limit.per-ip-per-hour, type: int, default: 600, range: "0..1000000", label: search.set.perHour }
|
||||
|
||||
# --- Per-tenant settings (tenant-owned BEHAVIOUR; over sites/<id>/plugins/search.yml; applied IMMEDIATELY) --
|
||||
# The whole tenant-owned surface: enable/limit/placeholder, the ranking weights, the exclude list, and the
|
||||
# snippet length. Every default here MUST match a default in SearchSiteConfig.
|
||||
siteSettings:
|
||||
- { key: enabled, type: boolean, default: true, label: search.set.enabled }
|
||||
- { key: resultLimit, type: int, default: 20, range: "1..100", label: search.set.resultLimit }
|
||||
# Where the box submits ?q= to — the results page carrying this widget (install it from the card below). The
|
||||
# box widget falls back to /search when unset; set this if you move/rename the results page.
|
||||
- { key: resultsPath, type: string, default: /search, label: search.set.resultsPath }
|
||||
- { key: placeholder, type: string, label: search.set.placeholder }
|
||||
- { key: exclude, type: list, label: search.set.exclude }
|
||||
- { key: snippetLength, type: int, default: 160, range: "40..400", label: search.set.snippetLength }
|
||||
# Since 2.1.0: a result link carries the words the engine matched (#rw-hl=…), and the page it opens highlights
|
||||
# them (static/highlight.js, loaded only when the marker is present). Off: plain links and no loader on the pages.
|
||||
- { key: highlight, type: boolean, default: true, label: search.set.highlight, help: search.help.highlight }
|
||||
- { key: titleWeight, type: int, default: 8, range: "0..1000000", label: search.set.titleWeight }
|
||||
- { key: descriptionWeight, type: int, default: 4, range: "0..1000000", label: search.set.descriptionWeight }
|
||||
- { key: bodyWeight, type: int, default: 1, range: "0..1000000", label: search.set.bodyWeight }
|
||||
- { key: allTermsBonus, type: int, default: 1000, range: "0..1000000000", label: search.set.allTermsBonus }
|
||||
- { key: phraseTitleBonus, type: int, default: 400, range: "0..1000000000", label: search.set.phraseTitleBonus }
|
||||
- { key: phraseBodyBonus, type: int, default: 300, range: "0..1000000000", label: search.set.phraseBodyBonus }
|
||||
# Searches with no results (since 2.0.0; developed as the unreleased 1.4.0) — a content-gap list shown on this
|
||||
# page. OFF by default: a search term is free text a visitor typed and may be personal data, so a site opts in. Only term + count + last seen are kept (no IP,
|
||||
# no user); email- and phone-number-like terms are never stored. Every default here MUST match NoResultsLog.
|
||||
- { key: recordNoResults, type: boolean, default: false, label: search.set.recordNoResults,
|
||||
help: search.help.recordNoResults }
|
||||
- { key: noResultsRetentionDays, type: int, default: 90, range: "1..365", label: search.set.noResultsRetention,
|
||||
help: search.help.noResultsRetention, showWhen: recordNoResults }
|
||||
|
||||
# --- Per-placement settings of the search box (since 2.1.0; Site → Content widgets, one form per data-widget) ---
|
||||
# results: whether this box lists the results when its page is opened with ?q=. auto (the default) lists them
|
||||
# unless the box is in the master chrome, so a header or footer box does not repeat the results page's list.
|
||||
widgetSettings:
|
||||
search:
|
||||
- { key: results, type: enum, default: auto, range: "auto,always,never", label: search.widget.results,
|
||||
help: search.widget.help.results }
|
||||
|
||||
# --- Tenant dashboard card (fragment resolves to __plugin__/search/dashboard = templates/dashboard.*) -----
|
||||
dashboardCards:
|
||||
- { realm: tenant, order: 40, fragment: dashboard, permission: "search|settings" }
|
||||
@@ -0,0 +1,137 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<!--
|
||||
Inherit the SAME managed versions the Runway kernel uses (Spring Boot 4.0.6), so every `provided`
|
||||
Spring type the plugin compiles against is byte-identical to the class the host loads. A plugin is NOT
|
||||
a Spring Boot application — NO spring-boot-maven-plugin repackage; `mvn package` produces a THIN jar of
|
||||
only this plugin's own classes (including its published SPI — SiteSearchEngine, SearchCorpus, SearchQuery,
|
||||
SearchHit — which search-lucene compiles against as `provided`).
|
||||
-->
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>4.0.6</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-plugin-search</artifactId>
|
||||
<version>2.3.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>Runway Search Plugin</name>
|
||||
<licenses>
|
||||
<license>
|
||||
<name>GNU Affero General Public License v3.0, with the Runway additional permission for plugins</name>
|
||||
<url>https://www.gnu.org/licenses/agpl-3.0.txt</url>
|
||||
<distribution>repo</distribution>
|
||||
<comments>See LICENSE and LICENSE-EXCEPTION.</comments>
|
||||
</license>
|
||||
</licenses>
|
||||
<description>
|
||||
On-site search for Runway: a built-in full-text engine over the site's published pages and content items,
|
||||
an embeddable query-aware search-box content widget, and a JSON API — all backed by a published
|
||||
SiteSearchEngine SPI (and the SearchCorpus every engine builds from) that a companion plugin (search-lucene)
|
||||
can implement to transparently upgrade the engine. Links only the Runway SPI.
|
||||
</description>
|
||||
|
||||
<properties>
|
||||
<java.version>25</java.version>
|
||||
<maven.compiler.release>25</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<!-- Reproducible builds: pins every archive entry's timestamp so two builds of the same source
|
||||
produce byte-identical artifacts. Without it a jar embeds the build time, so a rebuild can
|
||||
never match what was published. Bump at each release. -->
|
||||
<project.build.outputTimestamp>2026-10-21T17:23:00Z</project.build.outputTimestamp>
|
||||
<!-- The runway-spi (and runway-spi-testkit) version this plugin compiles and tests against, from ~/.m2. -->
|
||||
<runway.version>1.0.0</runway.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- The dependency-free extension API (SPI interfaces + immutable model records). COMPILE. -->
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-spi</artifactId>
|
||||
<version>${runway.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- NO runway-app dependency, in any scope: the plugin links only the SPI, so a host
|
||||
import no longer compiles and the kernel's host-linkage scanner finds nothing to report. -->
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-spi-testkit</artifactId>
|
||||
<version>${runway.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring context/Boot for @Configuration/@Bean at compile time; host-provided at runtime. -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Wiring/unit tests run against the compiled classes (NEVER spring-boot:run). -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<!-- Stable deployed filename (no version/classifier): target/runway-plugin-search.jar. -->
|
||||
<finalName>runway-plugin-search</finalName>
|
||||
<plugins>
|
||||
<!-- After the jar is built, assemble BOTH installable forms the platform accepts:
|
||||
1. target/search/ — the install-ready folder (cp -r into external/plugins/ + restart).
|
||||
2. target/runway-plugin-search-<version>.zip — the UI-uploadable archive (/__app/plugins). -->
|
||||
<plugin>
|
||||
<artifactId>maven-antrun-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>assemble-plugin-folder</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>run</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<target>
|
||||
<property name="stage" value="${project.build.directory}/search"/>
|
||||
<delete dir="${stage}"/>
|
||||
<mkdir dir="${stage}"/>
|
||||
<copy file="${project.basedir}/plugin.yml" todir="${stage}"/>
|
||||
<copy file="${project.basedir}/LICENSE" todir="${stage}"/>
|
||||
<copy file="${project.basedir}/LICENSE-EXCEPTION" todir="${stage}"/>
|
||||
<copy file="${project.build.directory}/runway-plugin-search.jar" todir="${stage}"/>
|
||||
<copy todir="${stage}/static">
|
||||
<fileset dir="${project.basedir}/static"/>
|
||||
</copy>
|
||||
<copy todir="${stage}/templates">
|
||||
<fileset dir="${project.basedir}/templates"/>
|
||||
</copy>
|
||||
<copy todir="${stage}/i18n">
|
||||
<fileset dir="${project.basedir}/i18n"/>
|
||||
</copy>
|
||||
<touch datetime="${project.build.outputTimestamp}"
|
||||
pattern="yyyy-MM-dd'T'HH:mm:ss'Z'">
|
||||
<fileset dir="${stage}"/>
|
||||
<dirset dir="${stage}"/>
|
||||
<dirset dir="${project.build.directory}" includes="search"/>
|
||||
</touch>
|
||||
<zip destfile="${project.build.directory}/runway-plugin-search-${project.version}.zip">
|
||||
<zipfileset dir="${project.build.directory}" includes="search/**"/>
|
||||
</zip>
|
||||
<echo message="Staged install folder: ${stage}"/>
|
||||
<echo message="UI-uploadable archive: ${project.build.directory}/runway-plugin-search-${project.version}.zip"/>
|
||||
</target>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
+375
@@ -0,0 +1,375 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build this plugin, drop it into a throwaway Runway deployment, boot the PACKAGED host in ACTIVE mode, and prove
|
||||
# the search 2.1.1 contract end to end (SPI 0.6.0):
|
||||
# - it loads with ZERO host-linkage and bean-name/surface warnings, and its app-level settings bind;
|
||||
# - the JSON API serves results anonymously; there is no plugin-owned /search page until one is installed;
|
||||
# - the three operator actions are CSRF-protected POSTs: a GET (a cross-site link or <img>) changes nothing even
|
||||
# for a signed-in owner, a POST without the console's CSRF token is refused 403, and an anonymous caller holding
|
||||
# a token is still refused by the permission check (404);
|
||||
# - signed in as the site owner: the rebuild-index and install-page buttons are POST forms carrying the token;
|
||||
# the starter page installs through SitePages on an Advisory, an Enforced and a Reviewed site (each outcome
|
||||
# reported), renders results inline, and a second install changes nothing;
|
||||
# - the `exclude` setting reaches the index on the save (through the kernel's change event), without a reindex;
|
||||
# - searches with no results: off by default, recorded once turned on (email-like terms never), written to the
|
||||
# plugin's own per-site file; a FULL backup carries no-results.tsv and a TRANSFER copy leaves it out and lists it
|
||||
# in its manifest; the clear POST is CSRF-checked;
|
||||
# - the API's rate limit keys on the kernel-gated client IP: made-up X-Forwarded-For headers do not evade it;
|
||||
# - the result highlighter: result links (page and API) carry #rw-hl=<words>, every page carries the loader
|
||||
# script stamped with the nonce its CSP allows, and the loader, highlight.js and highlight.css are served;
|
||||
# - the installed results page is never among its own results (2.1.1).
|
||||
# The deployment holds three sites copied from the wizard's default one before the ACTIVE boot: default (Advisory),
|
||||
# enforced, reviewed — addressed by Host name through curl --resolve. Verify ONLY against the packaged jar — never
|
||||
# spring-boot:run (its restart classloader loads ZERO plugins).
|
||||
#
|
||||
# Usage: scripts/verify-against-host.sh [--keep] [--port N]
|
||||
# JAVA_HOME=/path/to/jdk-25 required: the JDK that builds the plugin and runs the host
|
||||
# MVN=/path/to/mvn Maven (default: mvn on the PATH)
|
||||
# HOST_TARGET=/path/to/runway/runway-app/target the host build (default: the kernel this plugin sits in, else ../runway)
|
||||
# HOST_JAR=/path/to/runway-app-<ver>-exec.jar the kernel to verify against (default: the host checkout's
|
||||
# runway-app/target jar MATCHING its pom version)
|
||||
# VERIFY_TMPDIR=/dir where the throwaway deployment goes (default: $TMPDIR or /tmp)
|
||||
# VERIFY_LOG_DIR=/dir keep copies of the host logs, the install answers and the two
|
||||
# backup manifests there (evidence)
|
||||
# The script never runs `mvn install` (nothing is written to ~/.m2): it packages this plugin offline against
|
||||
# whatever runway-spi is already in the local repository.
|
||||
set -uo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
|
||||
# JAVA_HOME must name a JDK 25. MVN (default: `mvn` on the PATH) and HOST_TARGET (default: see above) can be set in the environment.
|
||||
if [ -z "${JAVA_HOME:-}" ] || [ ! -x "$JAVA_HOME/bin/java" ]; then echo "set JAVA_HOME to a JDK 25"; exit 2; fi
|
||||
export JAVA_HOME
|
||||
JAVA="$JAVA_HOME/bin/java"
|
||||
MVN="${MVN:-mvn}"
|
||||
# Default host: the kernel at the root of the repository this plugin sits in (plugins/<name>/), else a kernel
|
||||
# checkout named `runway` beside the plugins checkout.
|
||||
if [ -z "${HOST_TARGET:-}" ]; then
|
||||
if [ -f "$HERE/../../../runway-app/pom.xml" ]; then HOST_TARGET="$HERE/../../../runway-app/target"
|
||||
else HOST_TARGET="$HERE/../../runway/runway-app/target"; fi
|
||||
fi
|
||||
|
||||
KEEP="no"; PORT=""
|
||||
while [ $# -gt 0 ]; do case "$1" in
|
||||
--keep) KEEP="yes"; shift ;;
|
||||
--port) PORT="${2:?}"; shift 2 ;;
|
||||
*) echo "unknown arg: $1"; exit 2 ;;
|
||||
esac; done
|
||||
|
||||
APP_USER=root; APP_PW=Search-Admin-2026; SITE_USER=owner; SITE_PW=Search-Site-2026
|
||||
PER_MINUTE=25
|
||||
free_port() { python3 -I -c 'import socket;s=socket.socket();s.bind(("127.0.0.1",0));print(s.getsockname()[1]);s.close()'; }
|
||||
[ -n "$PORT" ] || PORT="$(free_port)"
|
||||
BASE="http://localhost:$PORT"
|
||||
|
||||
echo "[verify] building the plugin ..."
|
||||
( cd "$HERE" && "$MVN" -o -q -DskipTests package ) || { echo "plugin build failed"; exit 1; }
|
||||
|
||||
# The host jar MATCHING the host pom's version — never "the newest file": every reproducible jar carries the same
|
||||
# fixed timestamp, so `ls -t` cannot tell a leftover release jar from the SNAPSHOT under test.
|
||||
if [ -n "${HOST_JAR:-}" ]; then
|
||||
JAR="$HOST_JAR"
|
||||
else
|
||||
HOST_VERSION="$(sed -n 's:.*<version>\(.*\)</version>.*:\1:p' "$HOST_TARGET/../pom.xml" | head -1)"
|
||||
JAR="$HOST_TARGET/runway-app-$HOST_VERSION-exec.jar"
|
||||
fi
|
||||
[ -f "$JAR" ] || { echo "no host exec jar $JAR — build the host (mvn -pl runway-app package) or set HOST_JAR"; exit 1; }
|
||||
echo "[verify] host jar: $JAR"
|
||||
|
||||
SCRATCH="$(mktemp -d "${VERIFY_TMPDIR:-${TMPDIR:-/tmp}}/search-verify.XXXXXX")"
|
||||
cleanup() {
|
||||
[ -z "${VERIFY_LOG_DIR:-}" ] || { mkdir -p "$VERIFY_LOG_DIR" \
|
||||
&& cp "$SCRATCH"/*.log "$SCRATCH"/*-manifest.yml "$SCRATCH"/install-*.txt "$VERIFY_LOG_DIR"/ 2>/dev/null; }
|
||||
# Wait for the host to exit before deleting: a JVM still shutting down rewrites files under external/ (the
|
||||
# no-result list is flushed on shutdown) and makes `rm -rf` leave the scratch folder behind.
|
||||
[ "$KEEP" = "yes" ] || { kill "${PID:-0}" 2>/dev/null; wait "${PID:-0}" 2>/dev/null; rm -rf "$SCRATCH"; }
|
||||
}
|
||||
trap cleanup EXIT
|
||||
EXT="$SCRATCH/external"
|
||||
mkdir -p "$EXT/plugins"
|
||||
cp -r "$HERE/target/search" "$EXT/plugins/search"
|
||||
|
||||
wait_for() { for _ in $(seq 1 "$3"); do grep -q "$2" "$1" 2>/dev/null && return 0; sleep 1; done; return 1; }
|
||||
PASS=0; FAIL=0
|
||||
ck() { if eval "$2" >/dev/null 2>&1; then echo " PASS $1"; PASS=$((PASS+1)); else echo " FAIL $1"; FAIL=$((FAIL+1)); fi; }
|
||||
# The shipped application.yml trusts loopback as a same-host reverse proxy. This deployment trusts only a TEST-NET
|
||||
# address instead, so curl on loopback is an untrusted peer: a forwarded header it sends must be ignored.
|
||||
boot() { ( cd "$SCRATCH" && exec "$JAVA" -jar "$JAR" --server.port="$PORT" --runway.storage.external="$EXT" \
|
||||
--runway.proxy.trusted-cidrs=192.0.2.1/32 ) >"$1" 2>&1 & PID=$!; }
|
||||
|
||||
echo "[verify] booting host (wizard) on :$PORT ..."
|
||||
boot "$SCRATCH/wizard.log"
|
||||
wait_for "$SCRATCH/wizard.log" "Started RunwayApplication" 90 || { echo "wizard did not start"; tail -20 "$SCRATCH/wizard.log"; exit 1; }
|
||||
curl -s -o /dev/null -X POST "$BASE/setup" --data-urlencode "username=$APP_USER" --data-urlencode "password=$APP_PW" \
|
||||
--data-urlencode "displayName=Root" --data-urlencode "siteAdminUsername=$SITE_USER" --data-urlencode "siteAdminPassword=$SITE_PW"
|
||||
for _ in $(seq 1 30); do kill -0 "$PID" 2>/dev/null || break; sleep 1; done
|
||||
|
||||
# --- Two more sites, copied from the seeded default one (same owner), before the ACTIVE boot reads them ----------
|
||||
SITES="$EXT/sites"
|
||||
[ -f "$SITES/default/site.yml" ] || { echo "the wizard did not seed $SITES/default"; exit 1; }
|
||||
make_site() { # id editorial-level
|
||||
cp -r "$SITES/default" "$SITES/$1"
|
||||
sed -i -e "s/^id: .*/id: \"$1\"/" -e "s/^- \"localhost\"/- \"$1.test\"/" -e "s/^editorial: .*/editorial: \"$2\"/" \
|
||||
"$SITES/$1/site.yml"
|
||||
}
|
||||
make_site enforced enforced
|
||||
make_site reviewed reviewed
|
||||
sed -i 's/^ - "default"$/ - "default"\n - "enforced"\n - "reviewed"/' "$EXT/site-users.yml"
|
||||
# A bilingual page whose visible copy comes ONLY from the site's bundles (decoupled th:text): the template holds an
|
||||
# empty element. Kernel 1.0.0-rc6+ indexes the page as rendered in each language; search 2.2.0+ searches each
|
||||
# language's own documents (on 2.1.1 + rc5, "facultad" found nothing).
|
||||
sed -i '/^locales:/a - "es"' "$SITES/default/site.yml"
|
||||
T="$SITES/default/templates"
|
||||
cat > "$T/faculty.html" <<'HTML'
|
||||
<!DOCTYPE html><html><head><title>Faculty</title></head>
|
||||
<body><main id="content"><h1>Faculty</h1><p id="faculty-copy"></p></main></body></html>
|
||||
HTML
|
||||
cat > "$T/faculty.th.xml" <<'XML'
|
||||
<?xml version="1.0"?>
|
||||
<thlogic>
|
||||
<attr sel="#faculty-copy" th:text="#{verify.faculty}"/>
|
||||
</thlogic>
|
||||
XML
|
||||
printf 'path: /faculty\nlocalizedPaths:\n es: /facultad\nlocales: [en, es]\ntitle:\n en: Faculty\n es: Profesores\n' > "$T/faculty.meta.yml"
|
||||
mkdir -p "$SITES/default/i18n"
|
||||
printf '\nverify.faculty=Our students learn from a faculty of researchers.\n' >> "$SITES/default/i18n/messages.properties"
|
||||
printf '\nverify.faculty=Nuestros alumnos aprenden con una facultad de excelencia.\n' >> "$SITES/default/i18n/messages_es.properties"
|
||||
|
||||
# The app-level settings, in the file the plugins screen writes: a low per-minute ceiling the last section floods.
|
||||
mkdir -p "$EXT/plugin-settings"
|
||||
cat > "$EXT/plugin-settings/search.yml" <<YML
|
||||
runway:
|
||||
plugin:
|
||||
search:
|
||||
refresh-minutes: 60
|
||||
"rate-limit.per-ip-per-minute": $PER_MINUTE
|
||||
"rate-limit.per-ip-per-hour": 100000
|
||||
YML
|
||||
|
||||
echo "[verify] booting host (ACTIVE) ..."
|
||||
boot "$SCRATCH/active.log"
|
||||
wait_for "$SCRATCH/active.log" "Started RunwayApplication" 90 || { echo "ACTIVE did not start"; tail -20 "$SCRATCH/active.log"; exit 1; }
|
||||
LOG="$SCRATCH/active.log"
|
||||
|
||||
echo "== plugin load (SPI 0.6.0 contract) =="
|
||||
ck "plugins registered (1), 0 blocked" "grep -qE 'plugins: 1 registered, 0 blocked' '$LOG'"
|
||||
ck "not blocked / quarantined" "! grep -qE \"plugin 'search' is blocked|plugin-quarantine\" '$LOG'"
|
||||
# Host linkage and the surface rules, in both kernels' words: SPI 0.6.0 WARNed ("uses host internals", "… allowed until
|
||||
# Runway 1.0"); from SPI 1.0.0 the kernel BLOCKS and logs "linkage scan: <reason>" / the surface reason — a grep for the
|
||||
# 0.6.0 wording alone can never fail on a 1.0 kernel.
|
||||
ck "ZERO host-linkage findings" "! grep -qE \"uses host internals|plugin 'search' linkage scan\" '$LOG'"
|
||||
ck "ZERO bean-name/surface findings" "! grep -qE \"plugin 'search'.*(allowed until Runway 1.0|bean name|may not contribute)\" '$LOG'"
|
||||
ck "no WARN/ERROR names the plugin" "! grep -E ' (WARN|ERROR) ' '$LOG' | grep -qiE \"plugin 'search'|mx\\.quest\\.search\""
|
||||
ck "no key collision / degraded" "! grep -qiE 'collision|duplicate key|degraded' '$LOG'"
|
||||
|
||||
echo "== static assets =="
|
||||
ck "search.css served" "curl -s -o /dev/null -w '%{http_code}' '$BASE/__plugin/search/static/search.css' | grep -q 200"
|
||||
ck "help page served" "curl -s -o /dev/null -w '%{http_code}' '$BASE/__plugin/search/static/search-help.html' | grep -q 200"
|
||||
ck "highlight.js served as JavaScript" \
|
||||
"curl -s -D - -o /dev/null '$BASE/__plugin/search/static/highlight.js' | grep -qiE '^content-type: (text|application)/javascript'"
|
||||
ck "highlight.css served" "curl -s -o /dev/null -w '%{http_code}' '$BASE/__plugin/search/static/highlight.css' | grep -q 200"
|
||||
|
||||
PLUGIN_VERSION="$(sed -n 's/^version: //p' "$HERE/plugin.yml")"
|
||||
echo "== the result highlighter (since 2.1.0) =="
|
||||
if command -v node >/dev/null 2>&1; then
|
||||
ck "the page scripts parse (node --check)" "node --check '$HERE/static/highlight.js' && node --check '$HERE/static/highlight-loader.js'"
|
||||
ck "the word pattern folds as the server lowercases (Turkish İ, accents, symbols)" \
|
||||
"node '$HERE/src/test/js/highlight-pattern.js' '$HERE/static/highlight.js'"
|
||||
else
|
||||
echo " SKIP node not found: the page scripts were not parsed"
|
||||
fi
|
||||
curl -s -D "$SCRATCH/home.headers" "$BASE/" > "$SCRATCH/home.html"
|
||||
ck "every page carries the loader script, stamped with the nonce the kernel's CSP allows" \
|
||||
"n=\$(grep -oE '<script [^>]*src=\"/__plugin/search/static/highlight-loader.js[?]v=[0-9.]+\"[^>]*>' '$SCRATCH/home.html' | grep -oE 'nonce=\"[^\"]+\"' | sed -E 's/nonce=\"(.*)\"/\\1/'); [ -n \"\$n\" ] && grep -i '^content-security-policy' '$SCRATCH/home.headers' | grep -q \"nonce-\$n\""
|
||||
ck "plugin files are cacheable with a content ETag (kernel 1.0.0-rc5+; rc4 and earlier send no-store)" \
|
||||
"curl -s -D - -o /dev/null '$BASE/__plugin/search/static/highlight-loader.js?v=$PLUGIN_VERSION' | grep -qiE '^etag: ' || [ \"\${HOST_BEFORE_RC5:-0}\" = 1 ]"
|
||||
ck "highlight-loader.js served as JavaScript" \
|
||||
"curl -s -D - -o /dev/null '$BASE/__plugin/search/static/highlight-loader.js' | grep -qiE '^content-type: (text|application)/javascript'"
|
||||
|
||||
echo "== the public surfaces (anonymous) =="
|
||||
code() { curl -s -o /dev/null -w '%{http_code}' "$@"; }
|
||||
ck "no /search page until one is installed (404)" "[ \"\$(code '$BASE/search?q=about')\" = 404 ]"
|
||||
curl -s "$BASE/search/api?q=about" > "$SCRATCH/api-1.json"
|
||||
ck "the JSON API serves results from the catalog" \
|
||||
"grep -q '\"query\":\"about\"' '$SCRATCH/api-1.json' && grep -q '\"url\":\"/about\"' '$SCRATCH/api-1.json'"
|
||||
ck "…each result with its matched words and a link carrying them (2.1.0)" \
|
||||
"grep -q '\"link\":\"/about#rw-hl=about\"' '$SCRATCH/api-1.json' && grep -q '\"terms\":\\[\"about\"' '$SCRATCH/api-1.json'"
|
||||
ck "the JSON API answers JSON" \
|
||||
"curl -s -D - -o /dev/null '$BASE/search/api?q=about' | grep -qi '^content-type: application/json'"
|
||||
|
||||
echo "== every language searches its own text, bundle strings included (kernel 1.0.0-rc6+, search 2.2.0+) =="
|
||||
ck "the default site speaks Spanish too (fixture)" "grep -q '^- \"es\"' '$SITES/default/site.yml'"
|
||||
ck "the page's copy is rendered from the bundle (fixture)" \
|
||||
"curl -s '$BASE/es/facultad' | grep -q 'facultad de excelencia'"
|
||||
curl -s "$BASE/search/api?q=researchers&lang=en" > "$SCRATCH/api-en.json"
|
||||
curl -s "$BASE/search/api?q=excelencia&lang=es" > "$SCRATCH/api-es.json"
|
||||
ck "an English bundle string is searchable in English, at the English address" \
|
||||
"grep -q '\"url\":\"/faculty\"' '$SCRATCH/api-en.json'"
|
||||
ck "a Spanish bundle string is searchable in Spanish, at the Spanish address, with the Spanish title" \
|
||||
"grep -q '\"url\":\"/es/facultad\"' '$SCRATCH/api-es.json' && grep -q '\"title\":\"Profesores\"' '$SCRATCH/api-es.json'"
|
||||
ck "…and its snippet is the Spanish text (JSON writes < as \\u003c)" \
|
||||
"grep -qF 'facultad de \u003cmark\u003eexcelencia' '$SCRATCH/api-es.json'"
|
||||
ck "English does not search the Spanish text" \
|
||||
"! curl -s '$BASE/search/api?q=excelencia&lang=en' | grep -q '/faculty'"
|
||||
ck "Spanish does not search the English text" \
|
||||
"! curl -s '$BASE/search/api?q=researchers&lang=es' | grep -q 'facultad'"
|
||||
ck "a page in the default language only is still found from Spanish (its primary document)" \
|
||||
"curl -s '$BASE/search/api?q=about&lang=es' | grep -q '\"url\":\"/about\"'"
|
||||
|
||||
echo "== the operator actions are CSRF-protected POSTs (a link or an <img> changes nothing) =="
|
||||
token() { grep -o 'name="_csrf" value="[^"]*"' | head -1 | sed 's/.*value="//; s/"$//'; }
|
||||
site_url() { [ "$1" = default ] && echo "$BASE" || echo "http://$1.test:$PORT"; }
|
||||
sc() { # site curl-args... (one cookie jar per site host; --resolve maps <site>.test to the local host)
|
||||
local site="$1"; shift
|
||||
curl -s -H 'Accept-Language: en' --resolve "$site.test:$PORT:127.0.0.1" \
|
||||
-c "$SCRATCH/cookies-$site.txt" -b "$SCRATCH/cookies-$site.txt" "$@"
|
||||
}
|
||||
login() {
|
||||
local u; u="$(site_url "$1")"
|
||||
sc "$1" -o /dev/null -X POST "$u/login" --data-urlencode "username=$SITE_USER" --data-urlencode "password=$SITE_PW" \
|
||||
--data-urlencode "_csrf=$(sc "$1" "$u/login" | token)"
|
||||
}
|
||||
no_page() { ! ls "$SITES/$1/templates"/search.* >/dev/null 2>&1; }
|
||||
ck "anonymous GET of reindex / install-page -> 404 (no GET route)" \
|
||||
"[ \"\$(code '$BASE/search/reindex')\" = 404 ] && [ \"\$(code '$BASE/search/install-page')\" = 404 ]"
|
||||
ck "anonymous POST without a CSRF token -> 403 (the tenant chain's CSRF check)" \
|
||||
"[ \"\$(code -X POST '$BASE/search/reindex' -d x=1)\" = 403 ] && [ \"\$(code -X POST '$BASE/search/install-page' -d x=1)\" = 403 ] && [ \"\$(code -X POST '$BASE/search/no-results/clear' -d x=1)\" = 403 ]"
|
||||
ANON_JAR="$SCRATCH/cookies-anon.txt"
|
||||
ANON_TOKEN="$(curl -s -c "$ANON_JAR" -b "$ANON_JAR" "$BASE/login" | token)"
|
||||
ck "anonymous POST WITH a valid session token -> 404 (the permission check still applies)" \
|
||||
"[ -n '$ANON_TOKEN' ] && [ \"\$(code -c '$ANON_JAR' -b '$ANON_JAR' -X POST '$BASE/search/install-page' --data-urlencode '_csrf=$ANON_TOKEN')\" = 404 ] && [ \"\$(code -c '$ANON_JAR' -b '$ANON_JAR' -X POST '$BASE/search/reindex' --data-urlencode '_csrf=$ANON_TOKEN')\" = 404 ]"
|
||||
ck "…and nothing was installed by any of that" "no_page default"
|
||||
for site in default enforced reviewed; do login "$site"; done
|
||||
ck "signed-in owner: GET /search/install-page -> 404 and no page (a cross-site link installs nothing)" \
|
||||
"[ \"\$(sc default -o /dev/null -w '%{http_code}' '$BASE/search/install-page')\" = 404 ] && no_page default"
|
||||
ck "signed-in owner: GET /search/reindex -> 404" \
|
||||
"[ \"\$(sc default -o /dev/null -w '%{http_code}' '$BASE/search/reindex')\" = 404 ]"
|
||||
ck "signed-in owner: POST without the CSRF token -> 403 and no page" \
|
||||
"[ \"\$(sc default -o /dev/null -w '%{http_code}' -X POST '$BASE/search/install-page' -d x=1)\" = 403 ] && no_page default"
|
||||
ck "signed-in owner: POST with a forged CSRF token -> 403 and no page" \
|
||||
"[ \"\$(sc default -o /dev/null -w '%{http_code}' -X POST '$BASE/search/install-page' -d _csrf=forged-token)\" = 403 ] && no_page default"
|
||||
SETTINGS="$BASE/__admin/plugins/search/settings"
|
||||
sc default "$SETTINGS" > "$SCRATCH/settings-0.html"
|
||||
ck "the settings page offers the install as a POST form carrying a non-empty CSRF token" \
|
||||
"grep -q 'id=\"sp-install-form\" method=\"post\" action=\"/search/install-page\"' '$SCRATCH/settings-0.html' && grep -qE 'id=\"sp-csrf\" type=\"hidden\" name=\"_csrf\" value=\"[^\"]+\"' '$SCRATCH/settings-0.html'"
|
||||
ck "…and the index rebuild as a POST form carrying a non-empty CSRF token" \
|
||||
"grep -q 'id=\"sr-reindex-form\" method=\"post\" action=\"/search/reindex\"' '$SCRATCH/settings-0.html' && grep -qE 'id=\"sr-csrf\" type=\"hidden\" name=\"_csrf\" value=\"[^\"]+\"' '$SCRATCH/settings-0.html'"
|
||||
ck "…and no link points at either action" "! grep -qE 'href=\"/search/(install-page|reindex)' '$SCRATCH/settings-0.html'"
|
||||
ck "…and counts the searchable items (pages and content items)" "grep -qE 'id=\"sa-pages\">[1-9][0-9]*<' '$SCRATCH/settings-0.html'"
|
||||
sc default -X POST "$BASE/search/reindex" --data-urlencode "_csrf=$(token < "$SCRATCH/settings-0.html")" > "$SCRATCH/reindex.txt"
|
||||
ck "POST /search/reindex with the page's token rebuilds and reports the count" \
|
||||
"grep -qE '^Search index rebuilt\. \([1-9][0-9]*\)$' '$SCRATCH/reindex.txt'"
|
||||
|
||||
echo "== the starter page through SitePages (Advisory, Enforced, Reviewed) =="
|
||||
install() { # site -> the install action's answer, POSTed with the token from that site's settings page
|
||||
local u; u="$(site_url "$1")"
|
||||
sc "$1" -X POST "$u/search/install-page" --data-urlencode "_csrf=$(sc "$1" "$u/__admin/plugins/search/settings" | token)"
|
||||
}
|
||||
install default > "$SCRATCH/install-default.txt"
|
||||
ck "Advisory: POST with the token installs and publishes at /search" "grep -qx 'Search page installed at /search' '$SCRATCH/install-default.txt'"
|
||||
curl -s -D "$SCRATCH/search-page.headers" "$BASE/search?q=about" > "$SCRATCH/search-page.html"
|
||||
ck "…the installed page renders the box and the results inline" \
|
||||
"grep -q 'class=\"rw-search-box\"' '$SCRATCH/search-page.html' && grep -q 'href=\"/about#rw-hl=about\"' '$SCRATCH/search-page.html'"
|
||||
ck "…and is noindex (a search-results page is the canonical index opt-out)" \
|
||||
"grep -qi 'noindex' '$SCRATCH/search-page.html' '$SCRATCH/search-page.headers'"
|
||||
ck "…and is never among its own results, though its title matches the query (2.1.1)" \
|
||||
"grep -qiE '<title[^>]*>[^<]*search' '$SCRATCH/search-page.html' && ! curl -s '$BASE/search/api?q=search' | grep -q '\"url\":\"/search\"'"
|
||||
install default > "$SCRATCH/install-again.txt"
|
||||
ck "a second install changes nothing and says where the page is" "grep -qx 'A search page already exists at /search' '$SCRATCH/install-again.txt'"
|
||||
for site in enforced reviewed; do
|
||||
install "$site" > "$SCRATCH/install-$site.txt"
|
||||
echo " $site says: $(head -c 300 "$SCRATCH/install-$site.txt" | tr '\n' ' ')"
|
||||
done
|
||||
ck "Enforced: a documented outcome, never an error" \
|
||||
"grep -qE '^(Search page installed at /search|The search page was created as a draft because the quality checks blocked publishing; fix it in the page editor: /search)' '$SCRATCH/install-enforced.txt'"
|
||||
ck "Reviewed (as the owner, who may approve): a documented outcome" \
|
||||
"grep -qE '^(Search page installed at /search|The search page was created and is waiting in the review queue: /search|The search page was created as a draft)' '$SCRATCH/install-reviewed.txt'"
|
||||
ck "the installed pages exist on every site" \
|
||||
"( for s in default enforced reviewed; do ls \"$SITES/\$s/templates\"/search.* >/dev/null || exit 1; done )"
|
||||
sc default "$SETTINGS" > "$SCRATCH/settings-1.html"
|
||||
ck "the settings page shows the installed page's live path" "grep -q 'id=\"sp-path\"[^>]*>/search<' '$SCRATCH/settings-1.html'"
|
||||
|
||||
echo "== settings: the exclude list reaches the index on the save; no-result terms are opt-in =="
|
||||
NR_FILE="$SITES/default/plugins/search/no-results.tsv"
|
||||
curl -s -o /dev/null "$BASE/search/api?q=zebra%20crossing%20xyzzy"
|
||||
ck "off by default: the card says so and a no-result search is not recorded" \
|
||||
"grep -q 'id=\"nr-off\"' '$SCRATCH/settings-1.html' && ! sc default '$SETTINGS' | grep -q 'zebra crossing xyzzy'"
|
||||
sc default -o /dev/null -X POST "$SETTINGS" --data-urlencode "enabled=true" --data-urlencode "exclude=about" \
|
||||
--data-urlencode "recordNoResults=true" --data-urlencode "_csrf=$(token < "$SCRATCH/settings-1.html")"
|
||||
ck "the settings save is stored (exclude + recording on)" \
|
||||
"grep -q 'about' '$SITES/default/plugins/search.yml' && grep -q 'recordNoResults: true' '$SITES/default/plugins/search.yml'"
|
||||
ck "an excluded page leaves the results at once (no reindex)" "! curl -s '$BASE/search/api?q=about' | grep -q '\"url\":\"/about\"'"
|
||||
curl -s -o /dev/null "$BASE/search/api?q=Zebra%20%20Crossing%20XYZZY"
|
||||
curl -s -o /dev/null "$BASE/search/api?q=someone%40example.com"
|
||||
sc default "$SETTINGS" > "$SCRATCH/settings-2.html"
|
||||
ck "on: the normalized no-result term is listed" "grep -q '>zebra crossing xyzzy<' '$SCRATCH/settings-2.html'"
|
||||
ck "on: an email-like term is never kept" "! grep -q 'someone@example.com' '$SCRATCH/settings-2.html'"
|
||||
echo " waiting for the background flush of the no-result list (every 30 s) ..."
|
||||
for _ in $(seq 1 45); do [ -s "$NR_FILE" ] && break; sleep 1; done
|
||||
ck "the list is written to the plugin's own per-site file" "grep -q '^zebra crossing xyzzy' '$NR_FILE'"
|
||||
|
||||
echo "== backups: a full backup keeps no-results.tsv, a transfer copy leaves it out =="
|
||||
sc default -o "$SCRATCH/full.zip" "$BASE/__admin/backups/download"
|
||||
sc default -o "$SCRATCH/transfer.zip" "$BASE/__admin/backups/download-transfer"
|
||||
zipq() { # zip mode -> prints what was asked
|
||||
python3 -I - "$@" <<'PY'
|
||||
import sys, zipfile
|
||||
z = zipfile.ZipFile(sys.argv[1]); mode = sys.argv[2]
|
||||
names = z.namelist()
|
||||
if mode == "has":
|
||||
sys.exit(0 if any(n.endswith(sys.argv[3]) for n in names) else 1)
|
||||
if mode == "read":
|
||||
n = next(n for n in names if n.endswith(sys.argv[3])); sys.stdout.write(z.read(n).decode("utf-8"))
|
||||
PY
|
||||
}
|
||||
zipq "$SCRATCH/full.zip" read manifest.yml > "$SCRATCH/full-manifest.yml" 2>/dev/null
|
||||
zipq "$SCRATCH/transfer.zip" read manifest.yml > "$SCRATCH/transfer-manifest.yml" 2>/dev/null
|
||||
ck "the full backup carries plugins/search/no-results.tsv with the terms" \
|
||||
"zipq '$SCRATCH/full.zip' read plugins/search/no-results.tsv | grep -q 'zebra crossing xyzzy'"
|
||||
ck "the transfer copy has NO plugins/search/no-results.tsv" "! zipq '$SCRATCH/transfer.zip' has plugins/search/no-results.tsv"
|
||||
ck "…and its manifest lists the omission" "grep -q 'plugins/search/no-results.tsv' '$SCRATCH/transfer-manifest.yml'"
|
||||
ck "…while the settings file travels" "zipq '$SCRATCH/transfer.zip' has plugins/search.yml"
|
||||
ck "the full backup's manifest omits nothing of search" "! grep -q 'plugins/search/no-results.tsv' '$SCRATCH/full-manifest.yml'"
|
||||
|
||||
echo "== clearing the no-result list (CSRF-checked POST) =="
|
||||
ck "clear without the CSRF token is refused (403)" \
|
||||
"[ \"\$(sc default -o /dev/null -w '%{http_code}' -X POST '$BASE/search/no-results/clear')\" = 403 ]"
|
||||
ck "a GET does not clear (404)" "[ \"\$(sc default -o /dev/null -w '%{http_code}' '$BASE/search/no-results/clear')\" = 404 ]"
|
||||
ck "clear with the page's token redirects back to the settings (303)" \
|
||||
"[ \"\$(sc default -o /dev/null -w '%{http_code}' -X POST '$BASE/search/no-results/clear' --data-urlencode \"_csrf=\$(token < '$SCRATCH/settings-2.html')\")\" = 303 ]"
|
||||
ck "the list and the file are gone" "! sc default '$SETTINGS' | grep -q 'zebra crossing xyzzy' && [ ! -e '$NR_FILE' ]"
|
||||
|
||||
echo "== a Messages save reaches the index at once (kernel 1.0.0-rc6+: no reindex) =="
|
||||
login default
|
||||
MSG_TOKEN="$(sc default "$BASE/__admin/messages" | token)"
|
||||
ck "the Messages save is accepted" \
|
||||
"sc default -X POST '$BASE/__admin/messages/apply' -H 'Content-Type: application/json' -H \"X-CSRF-TOKEN: \$MSG_TOKEN\" \
|
||||
--data '{\"cells\":[{\"key\":\"verify.faculty\",\"locale\":\"en\",\"value\":\"Our students learn from astronomers.\"}]}' \
|
||||
| grep -q '\"saved\":1'"
|
||||
ck "the new English string is found by the next query" \
|
||||
"curl -s '$BASE/search/api?q=astronomers&lang=en' | grep -q '\"url\":\"/faculty\"'"
|
||||
ck "…and the old one is gone" "! curl -s '$BASE/search/api?q=researchers&lang=en' | grep -q '/faculty'"
|
||||
|
||||
echo "== the API's rate limit keys on the kernel-gated client IP =="
|
||||
# Every request below comes from ::1 (an untrusted peer here) and carries a different made-up X-Forwarded-For. The
|
||||
# kernel's trusted-proxy gate ignores the header, so all of them share the ::1 key and the ceiling applies; a request
|
||||
# from 127.0.0.1 is another client with its own budget.
|
||||
V6="http://[::1]:$PORT"; V4="http://127.0.0.1:$PORT"
|
||||
LIMITED=0
|
||||
for i in $(seq 1 $((PER_MINUTE + 5))); do
|
||||
c="$(curl -s -o /dev/null -w '%{http_code}' -H "Host: localhost:$PORT" \
|
||||
-H "X-Forwarded-For: 10.9.$((i / 250)).$((i % 250))" "$V6/search/api?q=rate$i")"
|
||||
[ "$c" = 429 ] && LIMITED=$((LIMITED + 1))
|
||||
done
|
||||
ck "made-up X-Forwarded-For headers do not evade the per-minute ceiling of $PER_MINUTE ($LIMITED of $((PER_MINUTE + 5)) answered 429)" \
|
||||
"[ $LIMITED -ge 5 ]"
|
||||
ck "…the 429 is the API's JSON answer" \
|
||||
"curl -s -H 'Host: localhost:$PORT' '$V6/search/api?q=again' | grep -qx '{\"error\":\"rate_limited\"}'"
|
||||
ck "another client address has its own budget (200)" \
|
||||
"[ \"\$(curl -s -o /dev/null -w '%{http_code}' -H 'Host: localhost:$PORT' '$V4/search/api?q=other')\" = 200 ]"
|
||||
ck "a blank query is not counted (still 200 at the ceiling)" \
|
||||
"[ \"\$(curl -s -o /dev/null -w '%{http_code}' -H 'Host: localhost:$PORT' '$V6/search/api?q=')\" = 200 ]"
|
||||
|
||||
ck "still no WARN/ERROR names the plugin after the run" "! grep -E ' (WARN|ERROR) ' '$LOG' | grep -qiE \"plugin 'search'|mx\\.quest\\.search\""
|
||||
|
||||
echo; echo "RESULT: $PASS passed, $FAIL failed"
|
||||
if [ "$KEEP" = "yes" ]; then echo "[verify] kept at $BASE (scratch $SCRATCH; kill $PID to stop)"; wait "$PID"; fi
|
||||
exit "$FAIL"
|
||||
@@ -0,0 +1,32 @@
|
||||
package mx.quest.search;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import mx.quest.search.spi.SearchHit;
|
||||
|
||||
/**
|
||||
* The link from a search result to the page it found, carrying the words to highlight there: the hit's URL plus the
|
||||
* fragment {@code #rw-hl=<words>}, the words separated by spaces and percent-encoded as one component. The fragment
|
||||
* never reaches the server, so the page is served and cached exactly as without it; {@code static/highlight.js} on
|
||||
* the target page reads it, highlights the words and removes it from the address bar (see {@link SearchHighlightHead}).
|
||||
*
|
||||
* <p>A hit with no matched words, or whose URL already has a fragment, links plainly.
|
||||
*/
|
||||
final class HighlightMarker {
|
||||
|
||||
/** The fragment key the page script reads. Changing it breaks links already shared, so it is fixed. */
|
||||
static final String KEY = "rw-hl";
|
||||
|
||||
private HighlightMarker() {
|
||||
}
|
||||
|
||||
/** The hit's link: its URL, with the marker when it has matched words and no fragment of its own. */
|
||||
static String link(SearchHit hit) {
|
||||
if (hit.terms().isEmpty() || hit.url().indexOf('#') >= 0) {
|
||||
return hit.url();
|
||||
}
|
||||
// URLEncoder writes a space as '+', which decodeURIComponent leaves alone; %20 decodes the same everywhere.
|
||||
String words = URLEncoder.encode(String.join(" ", hit.terms()), StandardCharsets.UTF_8).replace("+", "%20");
|
||||
return hit.url() + "#" + KEY + "=" + words;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package mx.quest.search;
|
||||
|
||||
/**
|
||||
* Minimal HTML escaping for the plugin's own generated markup (the search box widget and the results page).
|
||||
* The plugin owns escaping of every value it interpolates — page titles, snippets, the user's query — so a
|
||||
* crafted query or page title can never inject markup into the results page.
|
||||
*/
|
||||
final class Html {
|
||||
|
||||
private Html() {
|
||||
}
|
||||
|
||||
/** Escapes text for an element body or a double-quoted attribute value. */
|
||||
static String escape(String value) {
|
||||
if (value == null || value.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
return value.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
.replace("\"", """).replace("'", "'");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package mx.quest.search;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Reduces a page's raw HTML source to searchable plain text so the built-in engine can index a page's
|
||||
* <b>body</b>, not just its metadata. It removes {@code <script>}/{@code <style>} blocks and HTML comments
|
||||
* (whose contents are not visible prose), strips the remaining tags, decodes the handful of entities a page body
|
||||
* commonly carries, and collapses runs of whitespace to single spaces.
|
||||
*
|
||||
* <p>This is deliberately a best-effort extractor, not a conforming HTML parser: a malformed or exotic page must
|
||||
* still yield <em>some</em> reasonable text rather than throw, because indexing must never fail on a single bad
|
||||
* page. The output is plain text with no markup — the snippet builder is what later re-introduces the safe
|
||||
* {@code <mark>} highlight over an escaped slice of it.
|
||||
*/
|
||||
final class HtmlText {
|
||||
|
||||
/** {@code <script>…</script>} / {@code <style>…</style>} — content is code/CSS, never indexable prose. */
|
||||
private static final Pattern SCRIPT_STYLE = Pattern.compile("(?is)<(script|style)\\b[^>]*>.*?</\\1>");
|
||||
private static final Pattern COMMENT = Pattern.compile("(?s)<!--.*?-->");
|
||||
private static final Pattern TAG = Pattern.compile("<[^>]+>");
|
||||
private static final Pattern WHITESPACE = Pattern.compile("\\s+");
|
||||
|
||||
private HtmlText() {
|
||||
}
|
||||
|
||||
/** The visible text of {@code html} (never {@code null}; empty for {@code null}/blank input). */
|
||||
static String toText(String html) {
|
||||
if (html == null || html.isBlank()) {
|
||||
return "";
|
||||
}
|
||||
String text = SCRIPT_STYLE.matcher(html).replaceAll(" ");
|
||||
text = COMMENT.matcher(text).replaceAll(" ");
|
||||
text = TAG.matcher(text).replaceAll(" ");
|
||||
// Decode the common named/numeric entities a body carries; & is decoded LAST so a literal
|
||||
// "&lt;" round-trips to "<" rather than being over-decoded to "<".
|
||||
text = text.replace(" ", " ")
|
||||
.replace("<", "<").replace(">", ">")
|
||||
.replace(""", "\"").replace("'", "'").replace("'", "'")
|
||||
.replace("&", "&");
|
||||
return WHITESPACE.matcher(text).replaceAll(" ").strip();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package mx.quest.search;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import mx.quest.search.spi.SearchHit;
|
||||
|
||||
/**
|
||||
* The words the built-in engine matched in one document, for {@link SearchHit#terms()}. The built-in engine matches
|
||||
* a query term anywhere inside a word ({@code maestr} finds {@code maestrías}), so the word to highlight on the
|
||||
* target page is the whole word around each occurrence, not the term. Reads the lowercased fields of a
|
||||
* {@link SearchDocument}, title first, so the words a visitor sees first are the ones kept when the cap is reached.
|
||||
*/
|
||||
final class MatchedWords {
|
||||
|
||||
/** Occurrences of one term examined per field; enough to collect the distinct forms of a real page. */
|
||||
private static final int MAX_OCCURRENCES_PER_TERM = 200;
|
||||
|
||||
private MatchedWords() {
|
||||
}
|
||||
|
||||
/** The distinct whole words containing any of {@code terms}, in field order, at most {@link SearchHit#MAX_TERMS}. */
|
||||
static List<String> in(SearchDocument doc, List<String> terms) {
|
||||
Set<String> words = new LinkedHashSet<>();
|
||||
for (String field : List.of(doc.normTitle(), doc.normDescription(), doc.normBody())) {
|
||||
for (String term : terms) {
|
||||
collect(field, term, words);
|
||||
if (words.size() >= SearchHit.MAX_TERMS) {
|
||||
return List.copyOf(words);
|
||||
}
|
||||
}
|
||||
}
|
||||
return List.copyOf(words);
|
||||
}
|
||||
|
||||
private static void collect(String text, String term, Set<String> words) {
|
||||
if (term.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
int seen = 0;
|
||||
for (int i = text.indexOf(term); i >= 0 && seen < MAX_OCCURRENCES_PER_TERM;
|
||||
i = text.indexOf(term, i + term.length())) {
|
||||
seen++;
|
||||
int start = i;
|
||||
while (start > 0 && isWordChar(text.charAt(start - 1))) {
|
||||
start--;
|
||||
}
|
||||
int end = i + term.length();
|
||||
while (end < text.length() && isWordChar(text.charAt(end))) {
|
||||
end++;
|
||||
}
|
||||
if (end - start <= SearchHit.MAX_TERM_LENGTH) {
|
||||
words.add(text.substring(start, end));
|
||||
if (words.size() >= SearchHit.MAX_TERMS) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A letter, digit or combining mark: the characters the page highlighter also treats as part of a word. */
|
||||
private static boolean isWordChar(char c) {
|
||||
return Character.isLetterOrDigit(c) || Character.getType(c) == Character.NON_SPACING_MARK;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1372 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user