Runway 1.0.0
This commit is contained in:
commit
dcf819146b
1372 files changed
+188168
No files matched your search
@@ -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"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user